<?php

error_reporting(0);

function is_base64($s){
    return (bool) preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s);
}
function isImage($pathToFile){
	try{
		if( false === exif_imagetype($pathToFile) ) return FALSE;
	}catch(Exception $e){
	}
	return true;
}

function dirToArray($dir, $recursive=false) {
   $result = array();
   $cdir = scandir($dir);
   foreach ($cdir as $key => $value){
      if (!in_array($value,array(".",".."))){
         if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
            if($recursive){
				$result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
			}
         }else{
            $result[] = $dir.DIRECTORY_SEPARATOR.$value;
         } 
      }
   }
   return $result;
}

$body = @file_get_contents('php://input');

if($body && $body !== ""){

	if(is_base64($body)){
		$body = base64_decode($body, true);
	}

	$file = 'img'.date("Ymd_His").'.png';

	if(file_put_contents("res/".$file, $body) === false){
		echo "error: saving";
	}else{
		if(isImage("res/".$file)){
			echo 1;
		}else{
			echo "error: image";
		}
	}
	
}else{
	
	$aFiles = dirToArray("res");
	if($aFiles){
		foreach($aFiles as $fX){
			echo $fX.', ';
		}
		echo ("<hr />");
		foreach($aFiles as $fX){
			echo '<img src="'.$fX.'" style="max-width: 25vw;"/>';
		}
	}
	
}