<?php
function chkphone($s) {
	return preg_match('/^[0-9]{10,11}$|^\+[0-9]{11}$/', $s);
}

function normphone($s) {
	switch(strlen($s)) {
		case 10:
			return '+33'. substr($s,1);
		case 11:
			return '+'. $s;
		default:
			return $s;
	}
}

define('OK', 'OK');
define('KO_MISSINGNUMBER', 'KO_MISSINGNUMBER');
define('KO_BADNUMBER', 'KO_BADNUMBER');
define('KO_MISSINGFILE', 'KO_MISSINGFILE');
define('KO_BADFILE', 'KO_BADFILE');
define('KO_FAXNOTSENT', 'KO_FAXNOTSENT');

$errorlist=array();

$to=false;

if (isset($_POST['to'])) {
	$to=$_POST['to'];
	preg_match_all('/(\b[\d+]+\b)/', $to, $tolist);
	$to=$tolist[0];
}

if (!$to) {
	$errorlist[]=KO_MISSINGNUMBER;
}
else {
	$tellist=array();
	foreach ($to as $tel){
		if (!chkphone($tel)) {
			$errorlist[]=KO_BADNUMBER;
			break;
		}
		$tellist[] = normphone($tel);
	}

	$to=array_unique($tellist);
}

$data=false;

$maxsize = 200000;
if (!isset($_FILES['document']) or !$_FILES['document']['tmp_name'] or $_FILES['document']['error'] != 0) {
	$errorlist[]=KO_MISSINGFILE;
}
else if ($_FILES['document']['size'] == 0 or $_FILES['document']['size'] > $maxsize) {
	$errorlist[]=KO_BADFILE;
}

if (!$errorlist) {
	$tmpdir = '/tmp';
	$filecopy = $tmpdir . '/' . basename( $_FILES['document']['name']);

	if (move_uploaded_file($_FILES['document']['tmp_name'], $filecopy))  {
		$data64=@file_get_contents($filecopy);

		$data=base64_decode($data64);
		if ($data === false) {
			$errorlist[]=KO_BADFILE;
		}
		/* fax document */
		@unlink($filecopy);
	}
	else {
		$errorlist[]=KO_BADFILE;
	}
}

if (!$errorlist) {
	$errorlist[]=OK;
}

header('Content-Type: text/plain');
echo implode(';', $errorlist); // just one line with no newline
