#!/bin/bash

# Variables pour php, à personnaliser si besoin

upload_max_filesize="2G"
max_input_time="10800"
max_execution_time="10800"
post_max_size="2G"

# Pour avoir un retour du choix de l'utilisateur
asksomething()
{
    read -r -p "${1} [y/N] " response

    case "$response" in
        [yY][eE][sS]|[yY])
            true
            ;;
        *)
            false
            ;;
    esac
}

showlicence() {

	echo ""
	cecho "-----------------------------------------------------------------------------" $light_gray
	echo ""
	cecho "            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE" $light_gray
	cecho "                   Version 2, December 2004" $light_gray
	echo ""
	cecho "           Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>" $light_gray
	echo ""
	cecho "Everyone is permitted to copy and distribute verbatim or modified" $light_gray
	cecho "copies of this license document, and changing it is allowed as long" $light_gray
	cecho "as the name is changed." $light_gray
	echo ""
	cecho "           DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE" $light_gray
	cecho "  TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION" $light_gray
	echo ""
	cecho " 0. You just DO WHAT THE FUCK YOU WANT TO." $light_gray
	echo ""
	cecho "-----------------------------------------------------------------------------" $light_gray
	echo ""
	cecho "                        Fermeture du script dans 5 secondes" $light_green
	sleep 5s
	return
}


# Pour mettre de la couleur
red="\033[0;31m"
blue="\033[0;34m"
light_blue="\033[1;34m"
light_red="\033[1;31m"
cyan="\033[0;36m"
light_green="\033[1;32m"
light_gray="\033[0;37m"
green="\033[0;32m"
yellow="\033[1;33m"
light_purple="\033[1;35m"
purple="\033[0;35m"
reset_color="\033[0;00m"

cecho () {
	local msg_par_defaut=""

	local message=${1:-$msg_par_defaut} # Message par défaut.
	local couleur=${2:-$reset_color}    # Couleur par défaut si non spécifié.

	echo -e "$couleur $message"
	# Restaure le paramètre d'origine
	tput sgr0                     # Retour à la normale.

	return
}


runserver() {

	# Recherche de l'adresse ipv4 du poste.
	local poste=`hostname -I | tr -s ' ' | cut -d' ' -f1`
	local serverport=8512 # default port
	local keepportallowedbyfirewall=false
	local openserver=false


	# Lancer un serveur monothread sur le port voulu (defaut : 8512)
	cecho "   		 #############################################" $light_blue
	cecho "   		 #                                           #" $light_blue
	cecho "   		 #                                           #" $light_blue
	cecho "   		 #    Ouverture d'un serveur monothread      #" $light_blue
	cecho "   		 #                                           #" $light_blue
	cecho "   		 #          author : Jerry Wham              #" $light_blue
	cecho "   		 #          contact()ecyseo.net              #" $light_blue
	cecho "   		 #          version 2021-11-16               #" $light_blue
	cecho "   		 #                                           #" $light_blue
	cecho "   		 #                                           #" $light_blue
	cecho "   		 #############################################" $light_blue
	echo ""
	echo -n "Entrez le numéro du port que vous souhaiter utiliser, entre 8000 et 8999 :"
	# local userinput=$1
	read userinput


	if [[ $userinput -lt 8000 || $userinput -gt 8999 ]];   # checks that the input is within the desired range
		then
			echo ""
			cecho "Votre saisie est en dehors de la plage autorisée." $light_red
			cecho "Le port sera celui par défaut : 8512." $light_red
		else
			serverport=$userinput
	fi

	# Commandes pour lancer le serveur
		local cmdphp="php -d upload_max_filesize="$upload_max_filesize" -d max_input_time="$max_input_time" -d max_execution_time="$max_execution_time" -d post_max_size="$post_max_size" -S"
		local cmdpython="python3 -m http.server $serverport"
	if [[ $poste == "" ]] ; then
		cmdphp="$cmdphp localhost"
	else
		# cmdpython="$cmdpython --bind $poste"
		cmdphp="$cmdphp $poste"
	fi
	cmdphp="$cmdphp:$serverport monothread-server.php"

	# Vérifie si le port est autorisé par le parefeu
	echo ""
	echo "Vérification de l'autorisation d'ouverture du port $serverport par le parefeu dans 2 secondes..."
	sleep 2s
	pkexec ufw status verbose | tr -d "[:space:]" | grep -q "$serverport""ALLOW"
	# Récupère le status de la commande précédente
	local status=$?
	echo ""
	# "0" : le port est ouvert. "1" : il est fermé
	if [[ $status == 1 ]]; then
		cecho "Le port est actuellement fermé." $light_red
		if asksomething "Autoriser l'ouverture du port $serverport ?"; then
			pkexec ufw allow $serverport
			if asksomething "Souhaitez-vous conserver cette règle lorsque le serveur sera fermé ?"; then
				keepportallowedbyfirewall=true
			fi
			openserver=true
		else
			echo ""
			cecho "Vous avez refusé l'ouverture du port." $light_red
			echo "Le serveur ne sera pas lancé. Le script va se terminer."
			showlicence
			notify-send -i info -t 20000 "Serveur fermé"
			exit
		fi
	else
		cecho "Le port $serverport est actuellement ouvert." $light_green
		if asksomething "Souhaitez-vous conserver cette règle lorsque le serveur sera fermé ?"; then
			keepportallowedbyfirewall=true
		fi
		openserver=true
	fi
	if [[ $openserver == true ]]; then
		# Choix du type de serveur
		# Et lancement de celui-ci
		echo ""
		echo "   		 		---- *** ----"
		echo ""
		echo "			   Initialisation du serveur."
		cecho "		Appuyer sur les touches ctrl+c pour le fermer..." $light_green
		echo ""
		echo "   		 		---- *** ----"
		echo ""
		echo "Vous avez le choix entre un serveur python et un serveur php."
		echo "Le serveur php ajoute un routeur temporaire au dossier dans lequel le script est lancé."
		echo "Il permet d'envoyer des fichiers sur le poste."
		echo "Ce routeur est supprimé à l'arrêt du script."
		echo ""
		echo "Voulez-vous lancer un serveur python ?"
		if asksomething "Dans le cas contraire, un serveur php sera lancé"; then
			echo ""
			printf '		 		   \U1F409\n'
			cecho "			 Lancement du serveur python." $light_green
			echo ""
			printf '		 		   \U1F409\n'
			echo ""
			($cmdpython)
		else
			touch monothread-server.php
			echo "<?php
\$allowedExtensions = [
        'aac' => 'audio/aac',
        'avi' => 'video/x-msvideo',
        'bz' => 'application/x-bzip',
        'bmp' => 'image/bmp',
        'csv' => 'text/csv',
        'doc' => 'application/msword',
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'dot' => 'application/msword',
        'gif' => 'image/gif',
        'ico' => 'image/x-icon',
        'ics' => 'text/calendar',
        'png' => 'image/png',
        'jpeg' => 'image/jpeg',
        'jpg' => 'image/jpeg',
        'key' => 'application/octet-stream',
        'md' => 'text/plain',
        'mkv' => 'video/x-matroska',
        'mp3' => 'audio/mpeg3',
        'mpeg' => 'video/mpeg',
        'numbers' => 'application/octet-stream',
        'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        'odt' => 'application/vnd.oasis.opendocument.text',
        'odp' => 'application/vnd.oasis.opendocument.presentation',
        'otp' => 'application/vnd.oasis.opendocument.presentation-template',
        'ott' => 'application/vnd.oasis.opendocument.text-template',
        'ogg' => 'application/ogg',
        'pages' => 'application/octet-stream',
        'pdf' => 'application/pdf',
        'pot' => 'application/vnd.ms-powerpoint',
        'pps' => 'application/vnd.ms-powerpoint',
        'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
        'ppt' => 'application/vnd.ms-powerpoint',
        'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
	    'png' => 'image/png',
	    'sig' => 'application/octet-stream',
        'sql' => 'application/octet-stream',
        'tar' => 'application/x-tar',
        'txt' => 'text/plain',
        'wav' => 'audio/x-wav',
        'xls' => 'application/vnd.ms-excel',
        'xla' => 'application/vnd.ms-excel',
        'xlb' => 'application/vnd.ms-excel',
        'xlb' => 'application/x-excel',
        'xlc' => 'application/vnd.ms-excel',
        'xld' => 'application/vnd.ms-excel',
        'xlk' => 'application/vnd.ms-excel',
        'xll' => 'application/vnd.ms-excel',
        'xlm' => 'application/vnd.ms-excel',
        'xl' => 'application/vnd.ms-excel',
        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'xlt' => 'application/vnd.ms-excel',
        'xlv' => 'application/vnd.ms-excel',
        'xlw' => 'application/x-excel',
        'zip' => 'application/zip',
    ];
/**
* Check \$_FILES[][name]
*
* @param (string) \$filename - Uploaded file name.
* @author Yousef Ismaeil Cliprz
*/
function check_file_uploaded_name(\$filename)
{
    return (bool) ((!ctype_alnum(str_replace(array('.','-','_'), '', \$filename)) || !preg_match('/^(?:[a-z0-9._-]|\.(?!\.))+\$/iD',\$filename)) ? false : true);
}
/**
* Check \$_FILES[][name] length.
*
* @param (string) \$filename - Uploaded file name.
* @author Yousef Ismaeil Cliprz.
*/
function check_file_uploaded_length(\$filename)
{
    return (bool) ((mb_strlen(\$filename,'UTF-8') > 225) ? false : true);
}
function getExtension(\$file) {
    \$e = explode('.',\$file);
    \$e = trim(end(\$e));
    if (\$e == \$file) {return '';}
    return \$e;
}

# convert to octet (Merci Bronco @ warriordudimanche.net ^_^)
function toOctet(\$size=null,\$default_unit=null){
    if (!\$size){return;}
    \$size=strtolower(\$size);
    \$nb=intval(\$size);
    if (
           stripos(\$size, 'k')===false
        && stripos(\$size, 'm')===false
        && stripos(\$size, 'g')===false
    ){
        if (\$default_unit){\$size.=\$default_unit;}
        else{return \$nb;}
    }
    if (empty(\$nb)){return 0;}
    if (stripos(\$size, 'k')!==false){return \$nb*(1024);}
    if (stripos(\$size, 'm')!==false){return \$nb*(1024*1024);}
    if (stripos(\$size, 'g')!==false){return \$nb*(1024*1024*1024);}
}


function scanFileNameRecursivly(\$path = '', &\$name = array() ) {
	\$path = \$path == ''? dirname(__FILE__) : \$path;
	\$lists = @scandir(\$path);
	if(!empty(\$lists)){
		foreach(\$lists as \$f){
			if(is_dir(\$path.DIRECTORY_SEPARATOR.\$f) && '..' != \$f && '.' != \$f){
				scanFileNameRecursivly(\$path.DIRECTORY_SEPARATOR.\$f, \$name);
			} else if ('..' != \$f && '.' != \$f && 'monothread-server.php' != \$f){
				\$name[] = \$path.DIRECTORY_SEPARATOR.\$f;
			}
		}
	}
	return \$name;
}


function token()
{
	return array_reduce(scanFileNameRecursivly(__DIR__),function(\$a) {return md5(\$a);});
}

function clean(\$a) {
	return str_replace(__DIR__.'/','',\$a);
}


\$requestedAbsoluteFile = dirname(__FILE__) . \$_SERVER['REQUEST_URI'];
if (!preg_match('/\.php\$/', \$requestedAbsoluteFile) && \$_SERVER['REQUEST_URI'] != '/') {
	header('Content-Type: '.mime_content_type(\$requestedAbsoluteFile));

	\$fh = fopen(\$requestedAbsoluteFile, 'r');

	fpassthru(\$fh);
	fclose(\$fh);
	return true;
}


\$files = scanFileNameRecursivly(__DIR__);
\$newfile = '';

echo '<!DOCTYPE html><html lang=\"fr\"><head><link rel=\"icon\" href=\"data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🐘</text></svg>\"><style>/* MVP.css v1.8 - https://github.com/andybrewer/mvp */

:root {--active-brightness: 0.85;--border-radius: 5px;--box-shadow: 2px 2px 10px;--color: #118bee;--color-accent: #118bee15;--color-bg: #fff;--color-bg-secondary: #e9e9e9;--color-link: #118bee;--color-secondary: #920de9;--color-secondary-accent: #920de90b;--color-shadow: #f4f4f4;--color-table: #118bee;--color-text: #000;--color-text-secondary: #999;--font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen-Sans, Ubuntu, Cantarell, \"Helvetica Neue\", sans-serif;--hover-brightness: 1.2;--justify-important: center;--justify-normal: left;--line-height: 1.5;--width-card: 285px;--width-card-medium: 460px;--width-card-wide: 800px;--width-content: 1080px;
}@media (prefers-color-scheme: dark) {:root {    --color: #0097fc;    --color-accent: #0097fc4f;    --color-bg: #333;    --color-bg-secondary: #555;    --color-link: #0097fc;    --color-secondary: #e20de9;    --color-secondary-accent: #e20de94f;    --color-shadow: #bbbbbb20;    --color-table: #0097fc;    --color-text: #f7f7f7;    --color-text-secondary: #aaa;}
}/* Layout */
article aside {background: var(--color-secondary-accent);border-left: 4px solid var(--color-secondary);padding: 0.01rem 0.8rem;
}
body {background: var(--color-bg);color: var(--color-text);font-family: var(--font-family);line-height: var(--line-height);margin: 0;overflow-x: hidden;padding: 0;
}
/*footer,
header,
main {margin: 0 auto;max-width: var(--width-content);padding: 3rem 1rem;
}*/
footer {text-align:center;}
hr {background-color: var(--color-bg-secondary);border: none;height: 1px;margin: 4rem 0;width: 100%;
}
section {display: flex;flex-wrap: wrap;justify-content: var(--justify-important);
}
section img,
article img {max-width: 100%;
}
section pre {overflow: auto;
}
section aside {border: 1px solid var(--color-bg-secondary);border-radius: var(--border-radius);box-shadow: var(--box-shadow) var(--color-shadow);margin: 1rem;padding: 1.25rem;width: var(--width-card);
}
section aside:hover {box-shadow: var(--box-shadow) var(--color-bg-secondary);
}
[hidden] {display: none;
}
/* Headers */
article header,
div header,
main header {padding-top: 0;
}
header {text-align: var(--justify-important);
}
header a b,
header a em,
header a i,
header a strong {margin-left: 0.5rem;margin-right: 0.5rem;
}
header nav img {margin: 1rem 0;
}
section header {padding-top: 0;width: 100%;
}
/* Nav */
nav {align-items: center;display: flex;font-weight: bold;justify-content: space-between;margin-bottom: 7rem;
}
nav ul {list-style: none;padding: 0;
}
nav ul li {display: inline-block;margin: 0 0.5rem;position: relative;text-align: left;
}
/* Nav Dropdown */
nav ul li:hover ul {display: block;
}
nav ul li ul {background: var(--color-bg);border: 1px solid var(--color-bg-secondary);border-radius: var(--border-radius);box-shadow: var(--box-shadow) var(--color-shadow);display: none;height: auto;left: -2px;padding: .5rem 1rem;position: absolute;top: 1.7rem;white-space: nowrap;width: auto;z-index: 1;
}
nav ul li ul::before {/* fill gap above to make mousing over them easier */content: \"\";position: absolute;left: 0;right: 0;top: -0.5rem;height: 0.5rem;
}
nav ul li ul li,
nav ul li ul li a {display: block;
}
/* Typography */
code,
samp {background-color: var(--color-accent);border-radius: var(--border-radius);color: var(--color-text);display: inline-block;margin: 0 0.1rem;padding: 0 0.5rem;
}
details {margin: 1.3rem 0;
}
details summary {font-weight: bold;cursor: pointer;
}
h1,
h2,
h3,
h4,
h5,
h6 {line-height: var(--line-height);
}
mark {padding: 0.1rem;
}
ol li,
ul li {padding: 0.2rem 0;
}
p {margin: 0.75rem 0;padding: 0;width: 100%;
}
pre {margin: 1rem 0;max-width: var(--width-card-wide);padding: 1rem 0;
}
pre code,
pre samp {display: block;max-width: var(--width-card-wide);padding: 0.5rem 2rem;white-space: pre-wrap;
}
small {color: var(--color-text-secondary);
}
sup {background-color: var(--color-secondary);border-radius: var(--border-radius);color: var(--color-bg);font-size: xx-small;font-weight: bold;margin: 0.2rem;padding: 0.2rem 0.3rem;position: relative;top: -2px;
}
/* Links */
a {color: var(--color-link);display: inline-block;font-weight: bold;text-decoration: none;
}
a:active {filter: brightness(var(--active-brightness));text-decoration: underline;
}
a:hover {filter: brightness(var(--hover-brightness));text-decoration: underline;
}
a b,
a em,
a i,
a strong,
button {border-radius: var(--border-radius);display: inline-block;font-size: medium;font-weight: bold;line-height: var(--line-height);margin: 0.5rem 0;padding: 1rem 2rem;
}
button {font-family: var(--font-family);
}
button:active {filter: brightness(var(--active-brightness));
}
button:hover {cursor: pointer;filter: brightness(var(--hover-brightness));
}
a b,
a strong,
button {background-color: var(--color-link);border: 2px solid var(--color-link);color: var(--color-bg);
}
a em,
a i {border: 2px solid var(--color-link);border-radius: var(--border-radius);color: var(--color-link);display: inline-block;padding: 1rem 2rem;
}
article aside a {color: var(--color-secondary);
}
/* Images */
figure {margin: 0;padding: 0;
}
figure img {max-width: 100%;
}
figure figcaption {color: var(--color-text-secondary);
}
/* Forms */

button:disabled,
input:disabled {background: var(--color-bg-secondary);border-color: var(--color-bg-secondary);color: var(--color-text-secondary);cursor: not-allowed;
}
button[disabled]:hover {filter: none;
}
form {border: 1px solid var(--color-bg-secondary);border-radius: var(--border-radius);box-shadow: var(--box-shadow) var(--color-shadow);display: block;max-width: var(--width-card-wide);min-width: var(--width-card);padding: 1.5rem;text-align: var(--justify-normal);
}
form header {margin: 1.5rem 0;padding: 1.5rem 0;
}
input,
label,
select,
textarea {display: block;font-size: inherit;max-width: var(--width-card-wide);
}
input[type=\"checkbox\"],
input[type=\"radio\"] {display: inline-block;
}
input[type=\"checkbox\"]+label,
input[type=\"radio\"]+label {display: inline-block;font-weight: normal;position: relative;top: 1px;
}
input,
select,
textarea {border: 1px solid var(--color-bg-secondary);border-radius: var(--border-radius);margin-bottom: 1rem;padding: 0.4rem 0.8rem;
}
input[readonly],
textarea[readonly] {background-color: var(--color-bg-secondary);
}
label {font-weight: bold;margin-bottom: 0.2rem;
}
/* Tables */
table {border: 1px solid var(--color-bg-secondary);border-radius: var(--border-radius);border-spacing: 0;display: inline-block;max-width: 100%;overflow-x: auto;padding: 0;white-space: nowrap;
}
table td,
table th,
table tr {padding: 0.4rem 0.8rem;text-align: var(--justify-important);
}
table thead {background-color: var(--color-table);border-collapse: collapse;border-radius: var(--border-radius);color: var(--color-bg);margin: 0;padding: 0;
}
table thead th:first-child {border-top-left-radius: var(--border-radius);
}
table thead th:last-child {border-top-right-radius: var(--border-radius);
}
table thead th:first-child,
table tr td:first-child {text-align: var(--justify-normal);
}
table tr:nth-child(even) {background-color: var(--color-accent);
}
/* Quotes */
blockquote {display: block;font-size: x-large;line-height: var(--line-height);margin: 1rem auto;max-width: var(--width-card-medium);padding: 1.5rem 1rem;text-align: var(--justify-important);
}
blockquote footer {color: var(--color-text-secondary);display: block;font-size: small;line-height: var(--line-height);padding: 1.5rem 0;
}
* {
  box-sizing: border-box;
}

@media (prefers-reduced-motion: no-preference) {
  html {
    scroll-behavior: smooth;
  }
}
main {
  padding: 0 3rem;
  position: relative;
  max-width: 50rem;
  margin: 2rem auto;
}
main *:last-child {
  margin-bottom: 0;
}

.back-to-top-wrapper {
  position: absolute;
  top: 100vh;
  right: 0.25rem;
  bottom: -5em;
  width: 3em;
  pointer-events: none;
}

.back-to-top-link {
  position: fixed;
  position: sticky;
  pointer-events: all;
  top: calc(100vh - 5rem);
  display: inline-block;
  text-decoration: none;
  font-size: 2rem;
  line-height: 3rem;
  text-align: center;
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  padding: 0.25rem;
  border: 1px solid #254568;
  background-color: #d6e3f0;
  transition: transform 80ms ease-in;
}
.back-to-top-link:hover, .back-to-top-link:focus {
  transform: scale(1.1);
}
.back-to-top-link:focus {
  outline: none;
  box-shadow: 0 0 0 3px #4e85c0;
}

body {
  min-height: 100vh;
  height: 100%;
  display: grid;
  grid-template-rows: auto 1fr auto auto;
  margin: 0;
}

header,
footer {
  display: grid;
  place-items: center;
  background-color: #254568;
  color: #fff;
}
h1 {
  font-size: 4rem;
  text-align: center;
}

p {
  font-size: 1.125rem;
  line-height: 1.5;
}

</style></head><body><header id=\"top\"><h1>Dossier /</h1></header><main><article><section>
';

if (isset(\$_FILES['upfile']['tmp_name'])) {

	if (!isset(\$_POST['token'])) {
    	throw new RuntimeException('Invalid parameters.');
    }
	if (\$_POST['token'] != token()) {
        throw new RuntimeException('Invalid parameters.');
    }

	try {
	    // Undefined | Multiple Files | \$_FILES Corruption Attack
	    // If this request falls under any of them, treat it invalid.
	    if (
	        !isset(\$_FILES['upfile']['error']) ||
	        is_array(\$_FILES['upfile']['error'])
	    ) {
	        throw new RuntimeException('Invalid parameters.');
	    }

	    // Check \$_FILES['upfile']['error'] value.
	    switch (\$_FILES['upfile']['error']) {
	        case UPLOAD_ERR_OK:
	            break;
	        case UPLOAD_ERR_NO_FILE:
	            throw new RuntimeException('No file sent.');
	        case UPLOAD_ERR_INI_SIZE:
	        case UPLOAD_ERR_FORM_SIZE:
	            throw new RuntimeException('Exceeded filesize limit.');
	        default:
	            throw new RuntimeException('Unknown errors.');
	    }

	    // You should also check filesize here.
	    if (\$_FILES['upfile']['size'] > 1000000) {
	        throw new RuntimeException('Exceeded filesize limit.');
	    }

	    // DO NOT TRUST \$_FILES['upfile']['mime'] VALUE !!
	    // Check MIME Type by yourself.
	    \$finfo = new finfo(FILEINFO_MIME_TYPE);
	    \$mimetype = \$finfo->file(\$_FILES['upfile']['tmp_name']);
	    if (false === \$ext = array_search(
	        \$mimetype,
	        \$allowedExtensions,
	        true
	    )) {
	        throw new RuntimeException('Invalid file format '.\$mimetype.'. You could had this type of file in allowedExtensions.');
	    }

	    \$extension = getExtension(trim(\$_FILES['upfile']['name']));
	    if (!isset(\$allowedExtensions[\$extension]) || \$allowedExtensions[\$extension] != \$allowedExtensions[\$ext]) {
	    	throw new RuntimeException('Invalid file format.');
	    } else {
	    	\$ext = \$extension;
	    }

	    if (check_file_uploaded_name(\$_FILES['upfile']['name']) === false || check_file_uploaded_length(\$_FILES['upfile']['name']) === false) {
	    	throw new RuntimeException('Invalid file name.');
	    }

	    \$newfile = sprintf('%s.%s',
	        str_replace('.'.\$ext,'',trim(\$_FILES['upfile']['name'])).'-'.md5(sha1_file(\$_FILES['upfile']['tmp_name']).date('Ymdhis')),
	        \$ext
	    );

	    // You should name it uniquely.
	    // DO NOT USE \$_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
	    // Obtain safe unique name from its binary data.
	    if (!move_uploaded_file(
	        \$_FILES['upfile']['tmp_name'],
	        './'.\$newfile
	    )) {
	        throw new RuntimeException('Failed to move uploaded file.');
	    }

	    \$reply = 'File is uploaded successfully.';

	} catch (RuntimeException \$e) {

	    \$reply = \$e->getMessage();

	}
	echo '<dialog open><p>'.\$reply.'</p></dialog>';
}

?>
<form method=\"post\" action=\"\" enctype=\"multipart/form-data\" id=\"send\">

        <div class=\"grid-6-small-3 has-gutter\">
            <p class=\"col-all\">
                <input type=\"hidden\" name=\"dir\" value=\"\">
                <input type=\"file\" name=\"upfile\" id=\"browse\" multiple/>
            </p>
        </div>
        <div id=\"files_list\"></div>
        <p>
            <input type=\"submit\" value=\"UPLOAD\" id=\"submitButton\">
            <input type=\"hidden\" name=\"token\" value=\"<?=token();?>\">
        </p>
        <p>
            <small>upload_max_filesize = <?=trim(ini_get('upload_max_filesize'));?></small><br/>
            <small>max_input_time = <?=trim(ini_get('max_input_time'));?></small><br/>
            <small>max_execution_time = <?=trim(ini_get('max_execution_time'));?></small><br/>
            <small>post_max_size = <?=trim(ini_get('post_max_size'));?></small>
        </p>

</form>
<?php
echo '<ul>';

foreach (\$files as \$i => \$file) {
	if ('.' !== \$file && '..' !== \$file && 'monothread-server.php' !== \$file) {
		\$f = str_replace(__DIR__.'/','',\$file);
		echo '<li><a href=\"'.\$f.'\">'.(isset(\$_POST['new']) && \$_POST['new'] == \$f ? '<mark>'.\$f.'</mark>' : \$f).'</a></li>';
	}
}
?>
</ul>
<?php
if (isset(\$reply)) {
	echo '<form action=\"\" method=\"post\" name=\"answer\" style=\"display:none;\">';
			echo '<input type=\"hidden\" name=\"new\" value=\"'.\$newfile.'\"/>';
	echo '</form>
		<script>
			function envoyer(){
				document.answer.submit();
			}
			setInterval(function(){envoyer()}, 800);
		</script>';
}
?>

		</section>
		</article>
		<div class=\"back-to-top-wrapper\">
		   <a href=\"#top\" class=\"back-to-top-link\" aria-label=\"Scroll to Top\">🔝</a>
		 </div>
		</main>
		<footer>
		  <p>Serveur de fichiers PHP autonome</p>
		</footer>
 	</body>
</html>
" >> monothread-server.php
			echo ""
			printf '		 		   \U1F418\n'
			cecho "			 Lancement du serveur php." $light_blue
			echo ""
			printf '		 		   \U1F418\n'
			echo ""
			($cmdphp)
			rm monothread-server.php
		fi
		if [[ $keepportallowedbyfirewall == false ]]; then
			echo ""
			if asksomething "Autoriser la fermeture du port $serverport ?"; then
				pkexec ufw deny $serverport
			else
				cecho "Le port restera ouvert lorsque ce script sera terminé" $light_blue
				sleep 3s
			fi
		fi
		showlicence
		notify-send -i info -t 20000 "Serveur fermé"
		exit
	fi
}

runserver