Laravel – development environment

laravel with sail

basics

  • install docker compose with specific commands of the system it is used on
  • install composer locally: wget https://getcomposer.org/installer
  • install sail (docker environment for laravel): curl -s “https://laravel.build/project-name?with=mysql,selenium,mailhog,redis” | bash
  • check for local and forward ports for docker in file .env and add available ports
    • (APP_PORT=38080
      FORWARD_DB_PORT=33306
      FORWARD_REDIS_PORT=36379
      FORWARD_MEILISEARCH_PORT=37700
      FORWARD_MAILHOG_PORT=31025
      FORWARD_MAILHOG_DASHBOARD_PORT=38025)
  • start docker environment in background: ./vendor/bin/sail up -d
  • new app may be accessed via http://localhost:port
  • stop the server again: sail down

command alias: alias sail='[ -f sail ] && sh sail || sh vendor/bin/sail'

Proxy

in App\Http\Middleware\TrustProxies the protected variable $proxies must be changed to:

protected $proxies = [‘127.0.0.1’];

git

  • initialize git repo in current folder: git init
  • git remote add laravel ssh://git@olkn.myvnc.com/home/git/repo-laravel-dev.git
  • .gitignore to list all files that should not be included in git repo (sail automatically generates the file)
  • add files to staging: git add -A
  • commit changes to repo: git commit -m “comment“
  • push changes to remote repo: git push laravel

Laravel Breeze

  • install the breeze packages to start of with: sail composer require laravel/breeze –dev
  • install blade frontend with breeze: sail php artisan breeze:install blade (complete template including user authentication)
  • compile CSS and refresh browser: sail npm run dev
  • migrate data base: sail php artisan migrate

Models/Migrations/Controllers

sail php artisan make:model -mrc

Models

interface to the tables in the data base; eloquent model

app/Models/.php

Migrations

create and modify tables in data base

database/migrations/_create__tables.php

Controllers

processing requests towards application and returning responses

app/Http/Controller/Controller.php

deployment

steps on server

  • git clone serverAddressAndFolder
  • point web server root to folder public
  • modify/update .env file
  • php artisan key:generate – generates APP_KEY in .env file
  • php artisan migrate – migrate the data base schema
  • php artisan db:seed – if you want to seed your data base
  • php artisan down – shut website down for maintenance
  • git pull – pull latest git files to server
  • composer install – to check for any necessary updates from composer.lock file
  • php artisan migrate – migrate the data base schema
  • systemctl restart apache2 – to kill any php session
  • php artisan queue:restart – to enable and restart any queues
  • php artisan cache:clear – clear cache
  • php artisan up – start laravel website again

.env

php artisan config:cache enable caching of env in production environment


APP_DEBUG = true for development only
APP_EMV=staging for development server
APP_URL=http://localhost - may be different for dev server
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

maintenance mode

php artisan down #enable maintenance

php artisan up #disable maintenance

folder structure

  • app – core code
    • Broadcasting – broadcast channel classes
    • Console – custom artisan commands
    • Events – event classes
    • Exceptions – app exceptions handlers
    • Http – controllers and middleware
    • Jobs – queueable jobs
    • Listeners – classes that handle events
    • Mail – email classes
    • Models – eloquent model classes
    • Notifications – transactional notifications
    • Policies – authorization policy classes
    • Providers – service provider classes
    • Rules – custom validation rules
  • bootstrap – app.php to bootstrap the framework
  • config
  • database – database migrations, model factories and seeds
  • lang – language files
  • public – index.php as entry point
  • resources – all views and raw assets (CSS, JavaScript)
  • routes – all route definitions
  • storage – logs, compiled Blade templates, session files, file caches
  • tests – automated tests
  • vendor – composer dependencies

Request Lifecycle

some useful commands

  • sail shell (access a shel within the docker container)
  • sail root-shell
  • ./vendor/bin/sail php –version
  • ./vendor/bin/sail artisan –version
  • ./vendor/bin/sail composer –version
  • ./vendor/bin/sail npm –version

speed up

  • php artisan config:cache
  • php artisan route:cache
  • php artisan optimize –force

clean up

  • php artisan config:clear
  • php artisan route:clear
  • php artisan view:clear

Laravel Sail Docker Environment

vendor/laravel/sail/runtimes/8.2/Dockerfile

FROM ubuntu:22.04

LABEL maintainer="Taylor Otwell"

ARG WWWGROUP
ARG NODE_VERSION=16
ARG POSTGRES_VERSION=14

WORKDIR /var/www/html

ENV DEBIAN_FRONTEND noninteractive
ENV TZ=UTC

RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

RUN apt-get update \
&& apt-get install -y gnupg gosu curl ca-certificates zip unzip git supervisor sqlite3 libcap2-bin libpng-dev python2 \
&& mkdir -p ~/.gnupg \
&& chmod 600 ~/.gnupg \
&& echo "disable-ipv6" >> ~/.gnupg/dirmngr.conf \
&& echo "keyserver hkp://keyserver.ubuntu.com:80" >> ~/.gnupg/dirmngr.conf \
&& gpg --recv-key 0x14aa40ec0831756756d7f66c4f4ea0aae5267a6c \
&& gpg --export 0x14aa40ec0831756756d7f66c4f4ea0aae5267a6c > /usr/share/keyrings/ppa_ondrej_php.gpg \
&& echo "deb [signed-by=/usr/share/keyrings/ppa_ondrej_php.gpg] https://ppa.launchpadcontent.net/ondrej/php/ubuntu jammy main" > /etc/apt/sources.list.d/ppa_ondrej_php.list \
&& apt-get update \
&& apt-get install -y php8.2-cli php8.2-dev \
php8.2-pgsql php8.2-sqlite3 php8.2-gd \
php8.2-curl \
php8.2-imap php8.2-mysql php8.2-mbstring \
php8.2-xml php8.2-zip php8.2-bcmath php8.2-soap \
php8.2-intl php8.2-readline \
php8.2-ldap \
# php8.2-msgpack php8.2-igbinary php8.2-redis php8.2-swoole \
# php8.2-memcached php8.2-pcov php8.2-xdebug \
&& php -r "readfile('https://getcomposer.org/installer');" | php -- --install-dir=/usr/bin/ --filename=composer \
&& curl -sLS https://deb.nodesource.com/setup_$NODE_VERSION.x | bash - \
&& apt-get install -y nodejs \
&& npm install -g npm \
&& curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | gpg --dearmor | tee /usr/share/keyrings/yarn.gpg >/dev/null \
&& echo "deb [signed-by=/usr/share/keyrings/yarn.gpg] https://dl.yarnpkg.com/debian/ stable main" > /etc/apt/sources.list.d/yarn.list \
&& curl -sS https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor | tee /usr/share/keyrings/pgdg.gpg >/dev/null \
&& echo "deb [signed-by=/usr/share/keyrings/pgdg.gpg] http://apt.postgresql.org/pub/repos/apt jammy-pgdg main" > /etc/apt/sources.list.d/pgdg.list \
&& apt-get update \
&& apt-get install -y yarn \
&& apt-get install -y mysql-client \
&& apt-get install -y postgresql-client-$POSTGRES_VERSION \
&& apt-get -y autoremove \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN setcap "cap_net_bind_service=+ep" /usr/bin/php8.2

RUN groupadd --force -g $WWWGROUP sail
RUN useradd -ms /bin/bash --no-user-group -g $WWWGROUP -u 1337 sail

COPY start-container /usr/local/bin/start-container
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY php.ini /etc/php/8.2/cli/conf.d/99-sail.ini
RUN chmod +x /usr/local/bin/start-container

EXPOSE 8000

ENTRYPOINT ["start-container"]

./docker-compose.yml

# For more information: https://laravel.com/docs/sail
version: '3'
services:
laravel.test:
build:
context: ./vendor/laravel/sail/runtimes/8.1
dockerfile: Dockerfile
args:
WWWGROUP: '${WWWGROUP}'
image: sail-8.1/app
extra_hosts:
- 'host.docker.internal:host-gateway'
ports:
- '${APP_PORT:-80}:80'
- '${VITE_PORT:-5173}:${VITE_PORT:-5173}'
environment:
WWWUSER: '${WWWUSER}'
LARAVEL_SAIL: 1
XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
volumes:
- '.:/var/www/html'
networks:
- sail
depends_on:
- mysql
- mailhog
- selenium
mysql:
image: 'mysql/mysql-server:8.0'
ports:
- '${FORWARD_DB_PORT:-3306}:3306'
environment:
MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
MYSQL_ROOT_HOST: "%"
MYSQL_DATABASE: '${DB_DATABASE}'
MYSQL_USER: '${DB_USERNAME}'
MYSQL_PASSWORD: '${DB_PASSWORD}'
MYSQL_ALLOW_EMPTY_PASSWORD: 1
volumes:
- 'sail-mysql:/var/lib/mysql'
- './vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh'
networks:
- sail
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
retries: 3
timeout: 5s
mailhog:
image: 'mailhog/mailhog:latest'
ports:
- '${FORWARD_MAILHOG_PORT:-1025}:1025'
- '${FORWARD_MAILHOG_DASHBOARD_PORT:-8025}:8025'
networks:
- sail
selenium:
image: 'selenium/standalone-chrome'
extra_hosts:
- 'host.docker.internal:host-gateway'
volumes:
- '/dev/shm:/dev/shm'
networks:
- sail
networks:
sail:
driver: bridge
volumes:
sail-mysql:
driver: local

VSCode

Export extensions via local shell command (STRG+SHIFT+P terminal local):

code --list-extensions | sed -e 's/^/code --install-extension /' > my_vscode_extensions.sh

Import extensions via:

bash my_vscode_extensions.sh

web scraper

contents

  • logging
  • data base access
  • solr indexing
  • filesystem access
  • web scraping

logging

Data base access

– mysql in python


import mysql.connector
# from mysql.connector import Error

# pip3 install mysql-connector
# https://dev.mysql.com/doc/connector-python/en/connector-python-reference.html

class DB():
    def __init__(self, config):
        self.connection = None
        self.connection = mysql.connector.connect(**config)
        
    def query(self, sql, args):
        cursor = self.connection.cursor()
        cursor.execute(sql, args)
        return cursor

    def insert(self,sql,args):
        cursor = self.query(sql, args)
        id = cursor.lastrowid
        self.connection.commit()
        cursor.close()
        return id

    # https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html
    def insertmany(self,sql,args):
        cursor = self.connection.cursor()
        cursor.executemany(sql, args)
        rowcount = cursor.rowcount
        self.connection.commit()
        cursor.close()
        return rowcount

    def update(self,sql,args):
        cursor = self.query(sql, args)
        rowcount = cursor.rowcount
        self.connection.commit()
        cursor.close()
        return rowcount

    def fetch(self, sql, args):
        rows = []
        cursor = self.query(sql, args)
        if cursor.with_rows:
            rows = cursor.fetchall()
        cursor.close()
        return rows

    def fetchone(self, sql, args):
        row = None
        cursor = self.query(sql, args)
        if cursor.with_rows:
            row = cursor.fetchone()
        cursor.close()
        return row

    def __del__(self):
        if self.connection != None:
            self.connection.close()

  # write your function here for CRUD operations

solr indexing

filesystem access

web scraping

docker web dev

To simplify the development I tried docker for building the runtime environment. Here are the major steps to get it running.

Prerequisites

The docker installation is straight forward as described on the docker home page:

un-install old version

aptitude remove docker docker-engine docker.io

add reporitory

aptitude update

aptitude install apt-transport-https ca-certificates curl gnupg2 software-properties-common

add docker official key

curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -

check fingerprint

apt-key fingerprint 0EBFCD88

add repository

add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"

aptitude update

install docker from repo

aptitude install docker-ce

check if everything works

docker run hello-world

install docker compose

curl -L https://github.com/docker/compose/releases/download/1.21.2/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose

chmod +x /usr/local/bin/docker-compose

and check everything works

docker-compose --version

Docker Cheat Sheet

## List Docker CLI commands
docker
docker container –help

## Display Docker version and info
docker –version
docker version
docker info

## Execute Docker image
docker run hello-world

## List Docker images
docker image ls

## List Docker containers (running, all, all in quiet mode)
docker container ls
docker container ls –all
docker container ls -aq

Development Environment

create folder for docker environment

mkdir dockerproject

create yaml file for docker compose

vi docker-compose.yaml

At least the following sections should be available:

  • app
  • main application configuration

  • web
  • Webserver configuration is required

  • database
  • database configuration is required

and here comes an exmaple


version: '3'
services:
app:
build:
context: ./
dockerfile: app.dockerfile
working_dir: /var/www
volumes:
- ./../laravel:/var/www
environment:
- "DB_PORT=3306"
- "DB_HOST=database"
web:
build:
context: ./
dockerfile: web.dockerfile
working_dir: /var/www
volumes:
- ./../laravel:/var/www
ports:
- 8080:80
database:
image: mysql:5.6
volumes:
- dbdata:/var/lib/mysql
environment:
- "MYSQL_DATABASE=homestead"
- "MYSQL_USER=homestead"
- "MYSQL_PASSWORD=secret"
- "MYSQL_ROOT_PASSWORD=secret"
ports:
- "33061:3306"
volumes:
dbdata:

and now the app configuration


FROM php:7.1.3-fpm

RUN apt-get update
RUN apt-get install -y libmcrypt-dev
RUN apt-get install -y mysql-client
RUN apt-get install -y libmagickwand-dev --no-install-recommends
RUN pecl install imagick
RUN docker-php-ext-enable imagick
RUN docker-php-ext-install mcrypt pdo_mysql
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
RUN php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
RUN php composer-setup.php
RUN php -r "unlink('composer-setup.php');"
RUN mv composer.phar /usr/local/bin/composer
RUN apt-get install -y git
RUN apt-get update && apt-get install -y zlib1g-dev
RUN docker-php-ext-install zip

the web configuration


FROM nginx:1.10

ADD vhost.conf /etc/nginx/conf.d/default.conf

wake on lan and terminal management page

This code was written to get a management interface for my own servers. But as I switched to another option the code was never in productive state.

<?php ############# HEAD  ############################
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n";
echo "<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n";
############# docu ################################
/* create user account on target machine for shutdown (shutdownuser)
 * enable shutdown command for user on target machine (sudoers)
 * copy public key file for HTTP Server account to target machines .ssh/authorized_keys
 */
############# style sheets ########################
echo "<title>Terminal Server</title>\n<link rel='stylesheet' type='text/css' href='terminal.css'></head>\n<body>\n\n";
############# Configuration ##########################
/*
 * start server via relais
 * link zu shell in box fuer direkten connect
 */
$mac_adress_file = "terminal-list";# path where mac adresses are listed, must be accessible on webserver machine with webserver user rights
$server_port_to_check=22;# port to check for availability
$domain = ".steppenwolf.de";# domain all server reside in
$table_headers = array("Check", "Server (Terminal)", "Start", "Stop", "Comment");
$redirect_header = "/bananas";# if we were redirected we append level to URI
$shutdown_command = "ls ";
$shutdown_user = "shutdownuser";# user for shutdown command
$shutdown_public_keyfile = "id_rsa.pub"; # public_keyfile, must be accessible on webserver machine with webserver user rights
$Shutdown_private_keyfile = "id_rsa"; # private_keyfile, must be accessible on webserver machine with webserver user rights
###### links to shell in a box #################################
/*
 * shellinaboxd -t -s /:LOGIN -s /who:nobody:nogroup:/:w
 * In addition to the login shell at http://localhost:4200, show a list of currently logged in users when accessing http://localhost:4200/who. This command must be run as root in order to be able to change to nobody:nogroup as requested by the service description
 * shellinaboxd -t -s '/:root:root:/:wy60 -c /bin/login'
 * Instead of the standard ANSI/VT100 terminal, publish a Wyse 60 terminal. Again, this command should be run as root.
 * shellinaboxd -s /:SSH:example.org

    The terminal connects to a ssh session on example.org. 

shellinaboxd -t -s /:AUTH:HOME:/bin/bash

    Interactively request the user's name and password prior to launching a Bourne shell. This command can be run by unprivileged users. But if doing so, it only allows this particular user to log in. 
    
    oder spezieller Nutzer mit PRG als shell
*/		
###### parse contents of configfile and store everything in two arrays
function parse_file_contents($filename){
	global $inputvalues;
	$return = true;
	if ($data = file_get_contents($filename)){
		$contents = explode("\n", $data);
		foreach ($contents as $line) { # parse each line of the input file seperately
			$line = trim($line); $value = ""; # and override default values with config file values
			if (strlen($line) && substr($line, 0, 1) != '#') { # no comment lines and only lines with contents are parsed
				$key = trim(strtok($line, " \t")); # name of the specific option is first parameter
				$inputvalues["values"][$key] = trim(strtok(" \t")); # second entry is value for option
				while ($inputpart = strtok(" \t")) $value = $value.trim($inputpart)."\t"; # rest of the line is combined as comment
					$inputvalues["comment"][$key] = trim($value);
			} # comment lines and empty lines are ignored
		}# parsing of all lines done
	}# could not get file contents via function so die
	else {
		$return = false;
	}
	return $return;
}
###### check availability of server
function check_vitality($server, $timeout = 2){# ICMP ping packet with a pre-calculated checksum
return "1 OK toki";
	global $server_port_to_check;
	$contents = "";
	$fp = fsockopen($server, $server_port_to_check, $errno, $errstr, $timeout);
	if (!$fp) {
		$return = "0"."$errstr ($errno)";
	} else {
		stream_set_timeout($fp, $timeout);
	    $contents = $contents.fgets($fp, 128);
	    fclose($fp);
	    $return = "1".$contents;
	}
	return $return;
}
###### start server via GPIO
function start_server($server){
	$return = "Alles gut";
	return $return;
}
###### shutdown server
function shutdown_server($server){
	global $shutdown_command, $shutdown_user, $shutdown_public_keyfile, $Shutdown_private_keyfile;
	$connection = ssh2_connect($server, 22, array('hostkey', 'ssh-rsa'));
	if (ssh2_auth_pubkey_file($connection, $shutdown_user,$shutdown_public_keyfile, $Shutdown_private_keyfile)) {
		$return = "Public Key Authentication Successful\n<br>Shutting down server<br>\n";
		$stream = ssh2_exec($connection, $shutdown_command);
		$return = $return."<br>done ...<br>\n";
		fclose($stream);
	} else {
		$return = "Public Key Authentication Failed";
	}
	return $return;
}
###### edit terminal list
function edit_conf_file() {
	global $inputvalues;
	echo "<table border=1 width=700>\n"; # main table with all server names listed
	echo "<tr>\n<td colspan=3 class=header-style><br> Edit terminal list <br>&nbsp</td></tr>\n";
	echo "<tr>\n<td class=subheader-style> Server </td><td class=subheader-style> Terminal </td><td class=subheader-style> Comment </td></tr>\n";
	$counter = 0;
	foreach ($inputvalues["values"] as $key => $value){
		$counter ++;
		echo "<tr><td><input type='input' value='".$key."' name='server".$counter."'></td>";
		echo "<td><input type='input' value='".$value."' name='tty".$counter."'></td>";
		echo "<td  class=Comment-style><input class=Comment-style type='input' size=50 value='".$inputvalues['comment'][$key]."' name='comment".$counter."'></td></tr> ";
	}
	echo "<tr>\n<td colspan=2 align=center><input type='submit' name='CANCEL' value='CANCEL'></td><td align=center><input class=attention-style type='submit' name='SAVE' value='SAVE'></td></tr>\n";
	echo "<input type='hidden' name='counter' value='".$counter."'>\n";
	return;
}
###### save values to file
function save_conf_file($filename){
	$ergebnis = false;
	$output = "";
	for ($i=1;$i <= $_GET['counter']; $i++){# number of entries is stored in variable
		$output = $output.$_GET['server'.$i]."\t".$_GET['tty'.$i]."\t".$_GET['comment'.$i]."\n";
	}
	if ($handle = fopen($filename, "w")){ # open configfile for write
		fwrite($handle, $output);
		fclose($handle);
		$ergebnis = true;
	}
	else { # can not open output file
		$ergebnis = false;
	}
	return $ergebnis;
}
###### debug output of POST
function debug_output(){
	echo "<pre><br><h1>Hier kommt der schamass!</h1>";
	print_r($_GET);
	echo "</pre>"; return ;
}
############################## MAIN ##################################
if (isset($_SERVER['HTTP_X_FORWARDED_SERVER'])){ # if redirected, we use a different URI
	$action_script = $redirect_header.htmlspecialchars($_SERVER['PHP_SELF']);
}else {
	$action_script = htmlspecialchars($_SERVER['PHP_SELF']);
}
echo "<form method='get' action='".$action_script."'>\n";# page header with headline and table headers
if ( !parse_file_contents($mac_adress_file)) { # get contents of external file
	echo "<h1>Error reading config file!!</h1>";
} else {
	echo "<table border=1 width=700>\n"; # main table with all server names listed
	echo "<tr><td colspan=4 class=header-style><br> mini Server Admin Page <br>&nbsp</td><td align='center'><input class=attention-style type='submit' name='EDIT' value='EDIT'></td></tr>\n";
	echo "<tr>";
	foreach ($table_headers as $header)
		echo "<th class='".$header."-style' > ".$header."</th>";
	echo "</tr>\n";
	foreach ($inputvalues["values"] as $key => $value){# iterate over complete list of items 
		$title_text = check_vitality($key); # text to display on mouseover for button
		if (substr($title_text, 0, 1) == "1") 
			$text_color = "green";
		else 	
			$text_color = "red";
		echo "<tr><td align='center'><input type='submit' title='".substr($title_text, 1)."' name='CHECK' value='".$key."'></td>";
		echo "<td align='left' bgcolor='".$text_color."'> <a href='".$inputvalues['values'][$key]."' > ".$key.$domain." </td>";# link to terminal
		echo "<td class=Start-style><input type='submit' name='START' value='".$key."'></td>";# start server
		echo "<td align='center' class=Stop-style><input type='submit' name='STOP' value='".$key."'></td>";# stop server
		echo "<td class=Comment-style> ".$inputvalues['comment'][$key]." </td></tr>\n";# add comments field
	}
	echo "<tr><td colspan=5></td></tr>\n";
	echo "<tr><td colspan=5 align='center'><input type='submit' value='REFRESH' name='REFRESH'></td></tr>\n</table>\n";# just refresh the screen
	if (isset($_GET['STOP']) && array_key_exists($_GET['STOP'], $inputvalues['values'])){############ shutdown system ########################
		$server = $_GET['STOP'];
		echo "<h2>Stop Server: ".$server." </h2>\n<br><br>\n";
		echo shutdown_server($server);
	}
	elseif (isset($_GET['START']) && array_key_exists($_GET['START'], $inputvalues['values'])){############ wake up system ###################
		$server = $_GET['START'];
		echo "<h2>Wake Up System: ".$server."</h2>\n<br><br>\n";
		echo start_server($server);
	}
	elseif (isset($_GET['CHECK']) && array_key_exists($_GET['CHECK'], $inputvalues['values'])){############ get response on connectiontrial ###################
		$server = $_GET['CHECK'];
		echo "<h2>System returns: </h2>\n<br><br>".substr(check_vitality($server), 1)."\n<br><br>\n";
	}
	elseif (isset($_GET['EDIT'])) { ########### edit list of terminals #######################
		echo "<h2>Edit Terminallist</h2>\n";
		edit_conf_file();
	}
	elseif (isset($_GET['SAVE'])) { ########### save new entries to conf file ################
		echo "<h2>Save values to conf</h2>";
		if (save_conf_file($mac_adress_file)) echo "Updating Conf File successful (Choose REFRESH to see changes)!";
		else echo "Error during updating!";
	}
	elseif (!isset($_GET['REFRESH']) && !empty($_GET) && !isset($_GET['CANCEL'])) echo "<h1>Wrong Server choosen</h1>";############ user tries to cheat ################
	}
#print_r($inputvalues);
#debug_output();
echo "</form>\n</Body></HTML>\n";
########### END ###################################?>
@CHARSET "ISO-8859-1";
barbox_a {
  position: absolute;
  top: 330px;
  left: 250px;
  margin: 0px 0px 0px -160px;
  width: 304px;
  height: 24px;
  background-color: black;
}
.per {
  position: absolute;
  top: 330px;
  font-size: 18px;
  left: 250px;
  margin: 1px 0px 0px 150px;
  background-color: #FFFFFF;
}

.bar {
  position: absolute;
  top: 332px;
  left: 250px;
  margin: 0px 0px 0px -158px;
  width: 0px;
  height: 20px;
  background-color: #777777;
  border-style: solid;
  border-width: 1px;
}

.blank {
  background-color: white;
  width: 300px;
  border-style: solid;
  border-width: 1px;
}
.Stop-style {
	color: lightgray;
	background-color: firebrick;
	
}
.header-style {
	font-size: 20px;
}
.Start-style {
	text-align: center;
	background-color: blue;
	color: white;
}
.Comment-style {
	color: gray;
	background-color: lightgray;
}
a {
	color: lightgray;
}
.attention-style {
	background-color: red;
	color: white;
}
.subheader-style {
	color: white;
	background-color: dimgray;
}

Here is an example of the external file which lists the servers and its interfaces.


backup ttyUSB0 Backup Server
bananas ttyUSB1 Nas Server on Banana Pi
toradex ttyUSB2 Certification Authority on Toradex
raspberrypi ttyUSB3 Raspberry Pi for trials
cubietruck ttyUSB4 Cubie Main Server

picture viewer

This is my own version of a picture archive and view web interface. On the corresponding server the pictures are stored in folders for year, month and day. There is also the possibility to create specific albums with pictures as well as storing pictures in a folder to reprint/copy.

<?php ############# HEAD  ############################
echo "<!DOCTYPE html>\n";
echo "<html>\n<head>\n <meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'>\n";
############# style sheets ########################
echo "<link rel='stylesheet' type='text/css' href='stylesheet.css'>";
echo "<title>PictureViewer</title>\n</head>\n<body>\n\n";
echo "<header><h1>My Thoughts</h1><h4>sniplets worth to be remebered</h4></header>\n";
############# Configuration ##########################
$PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']); # use one file only which will be reload with new parameters all the time
$pathes = array("pictures" => "BackupFromMobile",
				"reprint" => "BackupFromMobile/reprint",
				"albums" => "BackupFromMobile/albums");
$thumb_params = array("width" => 300, "height" => 300, "row" => 5, "big" => 500);# thumbnail parameters
$folder_to_hide = array("pictures", "icons", "thumbnails", "bin");# some folders should not be showed normally
$file_extensions = array( "image" => array(".jpg", ".jpeg", ".png", ".gif"),
						  "audio" => array(".mp3", ".ogg", ".wav"),
						  "ebook" => array(".epub", ".pdf", ".rtx"),
						  "video" => array(".avi", ".3gp", ".flv"));# allowed extensions for files
$rotation_select_box="<option selected value='none'>none</option>
		<option value='0'>0&deg;</option>
		<option value='90'>+90&deg;</option>
		<option value='180'>+180&deg;</option>
		<option value='270'>-90&deg;</option>";# select box for image rotation in 90 degree grade
####### clear html variables from malicious code
function clean_html($variable){
	return trim(htmlspecialchars($variable));
}
###### debug output of POSTå
function debug_output(){
	echo "<pre><br><h1>Hier kommt der schamass!</h1>";
	print_r($_POST);
	echo "</pre>"; return ;
}
############# create thumbnails in subfolder ######
function check_thumbnail($path, $filename){
	global $thumb_params;
	if (!file_exists($path."thumbnails")){#create thumbnail folder
		if (!mkdir($path."thumbnails")) die ("Unable to create folder (".$path."thumbnails)!");
	}
	$thumb = new Imagick(realpath($path."/".$filename));# Imagick needs absolute path for reference
	$orientation = $thumb -> getimageorientation();# check for image orientation
	# check if rotation was selected
	if (!empty($orientation)){
		switch ($orientation){# rotate image to get it upright
			case imagick::ORIENTATION_BOTTOMRIGHT:
				$thumb->rotateimage("#000000", 180);
				break;
			case imagick::ORIENTATION_RIGHTTOP:
				$thumb->rotateimage("#000000", 90);
				break;
			case imagick::ORIENTATION_LEFTBOTTOM:
				$thumb->rotateimage("#000000", -90);
				break;
			case imagick::ORIENTATION_UNDEFINED:
				$thumb->rotateimage("#000000", 90);
				break;
		}
		$thumb->setImageOrientation(imagick::ORIENTATION_TOPLEFT);# set exif data
	}# resize image but keep ratio
	$thumb->setResourceLimit( Imagick::RESOURCETYPE_MEMORY, 2 );
	$thumb->thumbnailImage($thumb_params["width"], $thumb_params["height"], true);
	$thumb->writeImage(realpath($path)."/thumbnails/".$filename);
	return ; }
############# show side navigation #######################
function explore_directories($current_path, $target_path, $expert_mode){
	global $file_extensions, $folder_to_hide;
	echo "<ul class='navigation'>\n";
	foreach (scandir($current_path, 0) as $element){
		if (substr($element, 0, 1) != "." && !in_array($element, $folder_to_hide)){
			if (is_file($current_path."/".$element)){
				echo "<input type='hidden' name='elements[]' value='".$current_path."/".$element."'>";
				foreach ($file_extensions as $key => $value){# extensions are grouped in multidimensional array
					if (in_array(strtolower(strrchr($element, ".")), $file_extensions[$key])){# only some file extensions will be shown
						echo "<li class='actual_entry'><label><img src='icons/file.png'>";
						echo "<input class='hidden' type='submit' name='folder[".$key."]' value='".$current_path."/".$element."'>".$element."</label></li>\n";
					}
				}
			}
			else { #subfolder
				echo "<li class='navigation'><label><img src='icons/dir.png'>";
				echo "<input class='hidden' type='submit' name='folder[folder]' value='".$current_path."/".$element."/test'>".$element."</label></li>\n";
			}
			if (strncmp($current_path."/".$element, $target_path, strlen($current_path."/".$element)) == 0){
				explore_directories($current_path."/".$element, $target_path, $expert_mode);
			}
		} elseif ($element == "reprint" && $expert_mode == "normal"){# show reprint folder contents if in expert mode
			echo "<li class='navigation'><label><img src='icons/dir.png'>";
			echo "<input class='hidden' type='submit' name='folder[folder]' value='".$current_path."/".$element."/test'>".$element."</label></li>\n";
		}
	}
	echo "</ul>\n";
	return ; }
############ show thumbnails #############################
function show_thumbnails($path, $number_of_rows, $expert_mode){
	global $file_extensions,$rotation_select_box, $pathes;
	$i=0;
	foreach (scandir($path) as $file){# iterate over complete directory contents
		if (substr($file,0,1) != "." && in_array(strtolower(strrchr($file, ".")), $file_extensions["image"])){# only allowed extension will be shown
			$file = htmlspecialchars($file); $i++;# clean filename
			if (!file_exists($path."/thumbnails/".$file)){
				check_thumbnail($path."/", $file);
			}
			echo "<div class='gallery'><label><input class='hidden' type='submit' name='folder[image]' value='".$path."/".$file."'>";
			echo "<img src='".$path."/thumbnails/".$file."' alt='".$file."'></label>\n";
			if ($expert_mode == "normal"){# show checkbox for reprint
				if (strncmp($path, $pathes['reprint'], strlen($pathes['reprint'])) == 0 ) {
					echo "<p class='delete'><input type='checkbox' name='delete".$i."' value='".$path."/".$file."'> delete from reprint list </p>\n";
				}
				else {
					echo "<p class='reprint'><input type='checkbox' name='reprint".$i."' value='".$path."/".$file."'> reprint <span> rotate <select name='rotate".$i."'>";
					echo $rotation_select_box."</select></span><input type='hidden' name='rotation".$i."' value='".$path."/".$file."'></p>\n";# we need the filename beside the rotation value
					if (strncmp($path, $pathes['albums'], strlen($pathes['albums'])) == 0)
						echo "<p class='delete'><input type='checkbox' name='delete".$i."' value='".$path."/".$file."'> delete from album </p>\n";
					else
						echo "<p class='album'><input type='checkbox' name='album".$i."' value='".$path."/".$file."'> add to album choosen above</p>\n";
				}
			}
			echo "</div>\n";
		}
	}
	return ;}
############# rotate pictures from list in given direction ##############
function rotatepictures($rotation, $files){
	global $thumb_params; $i=0;
	$path = dirname($files[0]);
	foreach ($files as $value) {
		$thumb = new Imagick(realpath($value));# Imagick needs absolute path for reference
		switch ($rotation[$i]){# rotate image to get it upright
			case "0";
				$thumb->rotateimage("#000000", 0);
				break;
			case "90";
				$thumb->rotateimage("#000000", 90);
				break;
			case "180":
				$thumb->rotateimage("#000000", 180);
				break;
			case "270":
				$thumb->rotateimage("#000000", -90);
				break;
		}
		$thumb->setImageOrientation(imagick::ORIENTATION_TOPLEFT);# set exif data
		$thumb->setResourceLimit( Imagick::RESOURCETYPE_MEMORY, 2 );# resize image but keep ratio
		$thumb->thumbnailImage($thumb_params["width"], $thumb_params["height"], true);
		$thumb->writeImage(realpath($path)."/thumbnails/".basename($value));
		$i++; # take a counter with us to get desired orientation
	}
	return "done";}
############# copy pics for reprint ###################
function copypictures($files, $folder){
	if (!file_exists($folder)){
		if (!mkdir($folder)) die("Could not create folder:".$folder);
	}
	foreach ($files as $value) {
		if (!copy($value, $folder."/".basename($value) ))
				die("Could not copy file".$value." to ".$folder."/".basename($value));
		}
	return "done";}
############# delete pictures from album ##############
function delpictures($files){
	foreach ($files as $value) {
		if (!unlink($value))
			die("Could not delete file".$value);
	}
	return "done";}
######################################################################
############################## MAIN ##################################
######################################################################
echo "<body><form method='POST' action='$PHP_SELF'>\n";# page header with headline and table headers
$filelist=array(); $albumlist=array();$dellist=array();$rotatelist=array();$rotationnamelist=array();# list of files for reprint
foreach (array_diff_key($_POST, array("change" => "", "action" => "", "folder" => "", "album" => "")) as $key => $value){
	if (substr($key, 0, 7) == "reprint")# files for reprint are numbered as reprint1..9
		array_push($filelist, $value);# generate array list of files to reprint
	elseif (substr($key, 0, 5) == "album")# files for album are numbered as album1..9
		array_push($albumlist, $value);# generate array list of files for actual album
	elseif (substr($key, 0, 6) == "delete")# files to delete from album
		array_push($dellist, $value);
	elseif (substr($key, 0, 6) == "rotate" && $_POST[$key] != "none"){# files to rotate
		array_push($rotatelist, $value);# store value for rotation
		$index_for_rotation="rotation".substr($key, 6);
		array_push($rotationnamelist, $_POST[$index_for_rotation]);# get image name to rotate
	}
}
# get default values for action, target folder and expert view mode
# $key = last action choosen, e.g. play video, show pictures
# $target_folder = the last folder that was opened
# $expert_mode = status of expert view
if (isset($_POST['actual_action']) && $_POST['actual_action'] != "")
	$key = clean_html($_POST['actual_action']);
else 
	$key = "folder";# default action is showing pictures in folder
if (isset($_POST['folder']) && $_POST['folder'] != ""){
	foreach ($_POST[folder] as $key => $value)# generate target folder variable from POST
		$target_path = clean_html(dirname($value));# if a new folder icon was clicked update target folder
	$key = clean_html(array_keys($_POST['folder'])[0]);$value = clean_html($_POST['folder'][$key]);
}elseif (isset($_POST['actual_folder']) && $_POST['actual_folder'] != ""){
	$target_path = clean_html($_POST['actual_folder']);$value = clean_html($_POST['actual_contents']);
} else 
	$target_path = $pathes['pictures'];
# check the actual status of expert view and toggle if requested by user button press
if (isset($_POST['change']) && $_POST['change'] == "expert")# button is pressed, so we need to toggle
	$expert_mode = "normal";# change value as user triggered the button to change
elseif (isset($_POST['change']) && $_POST['change'] == "normal")
	$expert_mode = "expert";# keep the old stage if set
elseif (isset($_POST['expert_mode']) && $_POST['expert_mode'] == "normal")
	$expert_mode = "normal";
else 
	$expert_mode = "expert";
echo "<input type='hidden' name='expert_mode' value='".$expert_mode."'><input type='hidden' name='actual_folder' value='".$target_path."'>";
echo "<input type='hidden' name='actual_action' value='".$key."'><input type='hidden' name='actual_contents' value='".$value."'>";
############## show navigation on top ###########################################
echo "<div class='navi'><input type='submit' name='change' value='".$expert_mode."'>";
# manage access to albums in special folder
if ($expert_mode == "normal"){# select album from list if in expert mode
	echo "<select name='album'>\n<option value='new'>create new entry</option>\n";
	foreach ( glob($pathes['albums']."/*", GLOB_ONLYDIR) as $directory){
		echo "<option ";
		if (isset($_POST['album']) && $_POST['album'] == $directory)
			echo " selected ";
			echo "value='".$directory."'>".basename($directory)."</option>\n";
	}
	echo "</select>\n<input type='submit' name='action' value='action'>\n";
}
if (isset($_POST['action'])){# action button pressed
	echo "<span class='response'>";
	if (isset($_POST['new_album']) && !empty($_POST['new_album'])){
		if (!file_exists($pathes['albums']."/".$_POST['new_album']))
			if (!mkdir($pathes['albums']."/".$_POST['new_album'])) die("Could not create folder:".$_POST['new_album']);
	}
	else {
		if (isset($_POST['album']) && $_POST['album'] == "new"){
			echo "Create new album: <input type='text' size='20' name='new_album'>\n";
		}
		elseif (!empty($albumlist))# copy pictures to album
			echo copypictures($albumlist, $_POST['album']);
		if (!empty($filelist)) # copy pictures for reprint
			echo copypictures($filelist, $pathes['reprint']);
		if (!empty($dellist)) # delete entries from album
			echo delpictures($dellist);
		if (!empty($rotatelist))# rotate pictures in given direction
			echo rotatepictures($rotatelist, $rotationnamelist);
}
	echo "</span>\n";
}
explore_directories($pathes['pictures'], $target_path, $expert_mode);# show the navigation menue
echo "</div>\n";
############### page content to the right ##################################
echo "<section class='contents'>";
switch ($key){
	case "audio":
		echo "<".$key." controls height='240' width='320'>\n<source src='".$value."' type='".$key."/".strtolower(substr(strrchr($value, "."),1))."'>\n";
		echo "No support for file: ".$value." in your Browser!</".$key.">\n";
		break;
	case "video":
		echo "<".$key." controls height='240' width='320'>\n<source src='".$value."' type='".$key."/".strtolower(substr(strrchr($value, "."),1))."'>\n";
		echo "No support for file: ".$value." in your Browser!</".$key.">\n";
		break;
	case "ebook":
		echo "<br>Read ebook: ".$value."<br>";
		break;
	case "image":
		echo "<div class='gallery'>\n";
		if (isset($_POST['elements']) && $_POST['elements'] != "") {
			$number_of_pictures = count($_POST['elements'])-1;# index is running from 0 up
			for ($i=0; $i<=$number_of_pictures; $i++){# iterate over complete image list
				if ($_POST['elements'][$i] == $value){ # find the number of the current image in list
					if ($i == 0) $last = $_POST['elements'][$number_of_pictures];# we are at position 0 already
					else $last = $_POST['elements'][$i-1];
					if ($i == $number_of_pictures) $next = $_POST['elements'][0];# we are at the end already
					else $next = $_POST['elements'][$i+1];
					echo "<div class='arrow-left'><button type='submit' name='folder[image]' value='".$last."'>";
					echo "<img src='icons/transparent.png' style='border:none;'></button></div>";
					echo "<a href='".$value."'> <img src='".$value."' width='".$thumb_params["big"]."' alt='".$value."'></a>";
					echo "<div class='arrow-right'><button type='submit' name='folder[image]' value='".$next."'>";
					echo "<img src='icons/transparent.png' style='border:none;'></button></div>";
					break;
				}
			}
		}
		if ($expert_mode == "normal"){# show checkbox for reprint
			if (explode("/", $value)[0] == $pathes['reprint']) {
				echo "<p class='delete'><input type='checkbox' name='delete".$i."' value='".$value."'> delete from reprint list </p>\n";
			}
			else {
				echo "<p class='reprint'><input type='checkbox' name='reprint".$i."' value='".$value."'> reprint <span> rotate <select name='rotate".$i."'>";
				echo $rotation_select_box."</select></span><input type='hidden' name='rotation".$i."' value='".$value."'></p>\n";# we need the filename beside the rotation value
				if (explode("/", $value)[0] == $pathes['albums'])
					echo "<p class='delete'><input type='checkbox' name='delete".$i."' value='".$value."'> delete from album </p>\n";
				else
					echo "<p class='album'><input type='checkbox' name='album".$i."' value='".$value."'> add to album choosen above</p>\n";
			}
		}
		echo "</div>";
		break;
	case "folder":
		show_thumbnails($target_path, $thumb_params['row'], $expert_mode);# show thumbs
		break;
	default:
		echo "<br>File type not supported!<br>";
		break;
}
echo "</section>\n";
############# cleanup and end ########################################		
debug_output();
echo "</form>\n<footer id='footer'>My personal page hosted on my own server &copy; olkn</footer></body></HTML>\n";
########### END ###################################?>
@CHARSET "ISO-8859-1";
body {
    background-color: #2C2C29;
   	font-family:"Times New Roman", Times, serif;
    font-size: 13px;
    color: white;
}
.arrow-right {
    position: absolute;
	width: 20%;
    height: 100%;
    right: -50px;
    top: 0;
}
.arrow-left {
    position: absolute;
	width: 20%;
    height: 100%;
    left: -50px;
    top: 0;
}
.arrow-left:hover {
	background: transparent url(icons/arrow-left.png) no-repeat left center;
}
.arrow-right:hover {
	background: transparent url(icons/arrow-right.png) no-repeat right center;
}
.hidden {
	display: none;
}
.response {
	padding: 0 0 0 50px;
}
.navigation {/* navigation divs are nested on the left */
	padding: 0px 0px 0px 12px;
	text-shadow: 4px 3px 0 #444444;
}
ul {
    list-style-type: none;
    padding: 0px 20px 0px 0px;
}
li {
	padding: 0px 0px 0px 12px;
}
.navi { /* show text shadow */
	float: left;
	text-shadow: 4px 3px 0 #444444;
}
a { /* some stylings for links */
	text-decoration:none;
}
a:link {
    color: dimgray;
}
a:visited {
    color: darkgray;
}
a:hover {
    color: royalblue;
}
a:active {
    color: silver;
}
p.reprint { /* caption for reprint */
	background: teal;
	margin: 5px;
	text-align: left;
}
p.reprint span { 
	float:right;
	padding: 0 5px 0 0;
}
p.album { /* caption for add to album */
	background: royalblue;
	margin: 5px;
	text-align: left;
}
p.delete { /* caption for pic delete */
	background: darkred;
	margin: 5px;
	text-align: left;
}
.gallery { /* show nice white border for pics */
	position: relative;
	display: inline-block;
	padding: 5px 5px 20px 5px;
	margin: 20px;
	background: white;
}
.gallery img {
	margin:2px;
	border:1px solid #000000;
  	height:auto;
}
.gallery img:hover { /* blurr image when mouse is over */
	opacity:0.7;
	filter:alpha(opacity=70); 
}
img.arrow {
	border: none;
	margin: 100% 0;
}
button {
	height: 100%;
	width: 130px;
	background: transparent;
	border: none;
}
footer { /* footer in new line */
	clear: left;
}

print documents via web interface

This simple php code will allow to choose one or more documents and prints them using the local cups printer. There is also a possibility to select one of the locally installed printers.

There are some prerequesites as follows:

  • install unoconv and openoffice/libreoffice (import filters are required)
  • install calc, writer, impress, draw as required (import formats)
  • local lpr printing programm and lpstat for list of installed printers are required
  • upload is putting any non-pdf document in a local folder on the webserver for conversion this folder must be writable by PHP/apache
  • copy this file to location accessible by apache
<?php ############# HEAD  ############################
echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n";
echo "<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n";
/* Short Introduction
 * 
 * - install unoconv and openoffice/libreoffice (import filters are required)
 * - install calc, writer, impress, draw as required (import formats)
 * - local lpr printing programm and lpstat for list of installed printers are required
 * - upload is putting any non-pdf document in a local folder on the webserver for conversion
 *   this folder must be writable by PHP/apache
 * - copy this file to location accessible by apache
 */
############# Configuration ##########################
$print_command = "/usr/bin/lpr -P ";# local print command
$conv_command = "unoconv -f pdf ";# conversion command
$upload_directory ="/var/www/PDF/";# dir where all the magic takes place
$filesize = 100000;# file size limit in kB
$printer_default = "PDF";# default printer for first start
### no changes should be necessary beneathe this line
$reg_printer = "/^device for (.*): .*$/im";# examination of lpstat to get list of installed printers
$PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']); 
$uploadcounter = 1;#default value for number of upload buttons
echo "<title>Print File</title>\n</head>\n<body>\n\n";
###### debug output of POST
# debugging function to show HTML variables
#
function debug_output(){
	echo "<pre><br><h1>Show internal variables</h1>";
	print_r($_POST);echo "<br>";
	print_r($_FILES);
	echo "</pre>"; return ;
}
###### get local printerrs #############
# function will examine lpstat to get list of
# locally installed printers
#
function get_local_printer($printer_default){
	global $reg_printer;
	$output = shell_exec("/usr/bin/lpstat -s");
	if (preg_match_all($reg_printer, $output, $printer)) {
		echo "<SELECT name='printer' size='1'>\n";
		foreach ($printer[1] as $key => $value){
		echo "<OPTION";if ($printer_default == $value) echo " selected";echo "> ".$value." </OPTION>\n";
		}
		echo "</SELECT>";
	}
	return;
}
###### file upload box with comment text
# show file upload box with in-/decrease button
#
function fileupload_box($text, $count=1){
	global $filesize;
	if ($text != "") echo "<h2>".$text."</h2>\n";# show status information on top
	echo '<input type="hidden" name="MAX_FILE_SIZE" value="'.$filesize.'" >';
	echo "<table border='0'>";# Table for formatting
	for ($i=0; $i < $count; $i++){
		echo "<tr><td><input type='submit' name='addcounter' value='+'></td>";
		echo "<td><input type='submit' name='delcounter' value='-'></td>";
		echo "<td>File to print Nr. ".$i." :</td><td><INPUT TYPE='file' NAME='print_file[]' size='50'></td></tr>\n";
	}
	echo "<tr><td colspan='4'>&nbsp; </td></tr>";
	echo "<tr><td colspan='4' align='center'><INPUT TYPE='SUBMIT' NAME='UPLOAD' value=' PRINT '></td></tr>\n</table>\n";
}
############################## MAIN ##################################
echo "<form method='post' action='$PHP_SELF' enctype='multipart/form-data'>\n";# form for file upload
if (isset($_POST['uploadcounter'])) $uploadcounter = $_POST['uploadcounter'];
if (isset($_POST['addcounter'])) $uploadcounter = $uploadcounter+1;# additional upload button please
if (isset($_POST['delcounter'])) $uploadcounter = $uploadcounter-1;# delete one upload button please
if (isset($_POST['printer'])) $printer_default = $_POST['printer'];# keep choosen printer
if ($uploadcounter < 1) $uploadcounter=1;# at least one entry must remain
echo "<table width='100%'><tr><td><h1>Print selected Files</h1></td>\n";$text = "";
echo "<td>Choose Printer:</td><td>";get_local_printer($printer_default);
echo "</td></tr></table>\n";
if (isset($_POST['UPLOAD'])) {# upload button pressed;the magic begins
	for ($i=0; $i < $uploadcounter; $i++){# iterate over list of files
		$file = $_FILES['print_file']['tmp_name'][$i];# temporary file name
		$filename = $upload_directory.basename($file);# final doc name incl folder
		if ($file == "" || $_FILES['print_file']['size'][$i] == 0 || !is_file($file)) { # no file selected 
			$text = "Please choose files to print!";
		}
		else {
			if (is_uploaded_file($file)) { # check for upload errors
				if(!move_uploaded_file($file, $filename))# copy files to dir
					echo "<h2>Moving file".$file." to destination ".$upload_directory." failed!</h2>";
				else{
					if (strripos(mime_content_type($filename), "pdf") === false){# check if file mime type is pdf
						shell_exec( $conv_command." ".$filename." -o ".$filename.".pdf > /dev/null");# unoconv -f pdf file
						shell_exec( $print_command.$printer_default." ".$filename.".pdf > /dev/null");# execute print command
						echo "<p style='color:#aaaaaa, font-size:50%'> (".$print_command.$printer_default." ".$filename.".pdf) </p>";
					}
					else # file is pdf, so print directly
						shell_exec( $print_command.$printer_default." ".$file." > /dev/null");# execute print command
					echo "<br>Printouts may be found in your local printer\n";# be polite ;-)
				}
			}
			else { # file upload went wrong
				$text = "File Upload error";
			}
		}
	}
	$uploadcounter=1;# reset counter
}
echo "<input type='hidden' name='uploadcounter' value='".$uploadcounter."'>";# take hidden counter for number of upload buttons
fileupload_box($text, $uploadcounter);# generate upload boxes
#debug_output();# show debug information
echo "</form>\n</Body></HTML>\n";# The End!
########### END ###################################?>