<?php
    
    function decodeSTRING($val){
        // #, &, +  < > などが URI 送信で化けるため encode して送られたものを decode
        $array = explode("%x0;", $val);
        $val = implode("#", $array);
        $array = explode("%x1;", $val);
        $val = implode("&", $array);
        $array = explode("%x2;", $val);
        $val = implode("+", $array);
        $array = explode("%x3;", $val);
        $val = implode("<", $array);
        $array = explode("%x4;", $val);
        $val = implode(">", $array);
        $array = explode("%x5;", $val);
        $val = implode(" ", $array);
        $array = explode("%x6;", $val);
        $val = implode("\n", $array);
        $array = explode("%x7;", $val);
        $val = implode("\"", $array);
        $array = explode("%x8;", $val);
        $val = implode("$", $array);
        $array = explode("%x9;", $val);
        $val = implode("\'", $array);
        return $val;
    }
    
    function fwrite_stream($fp, $string) {
        for ($written = 0; $written < strlen($string); $written += $fwrite) {
            $fwrite = fwrite($fp, substr($string, $written));
            if ($fwrite === false) {
                return $written;
            }
        }
        return $written;
    }
    
	function suffix($filename){
		// ファイル名末尾の拡張子を返す
		$array = explode(".", $filename);
		
		if (count($array) > 1)
			return '.'.$array[count($array) - 1];
		else
			return "";
	}
    
    function getDir($dir){
        // $dir 内のファイルをリストアップ
        $results = array();
        $array = array();
        $files = scandir($dir);
        for ($i=0,$count=count($files); $i < $count; $i++){
            $filename = $files[$i];
            if ($filename == ".") continue;
            if ($filename == "..") continue;
            
            // folder は除外する
            $path = "$dir/$filename";
            if (scandir($path)) continue;
            
            $array[] = $filename;
        }
        rsort($array); // 逆順にソート
        $results['path'] = $dir;
		$results['files'] = $array;
        
        return $results;
    }
	
    
    /* ########################################
     ### 以下でも $_POST['key'] と同じに機能する ###
     if (isset($_REQUEST['key'])) {
     $key = $_REQUEST['key'];
     }
     ########################################## */
    
    $key = $_POST['key'];
    $value = $_POST['value'];
    $value = decodeSTRING($value); // lib.php
    $container = $_POST['container'];
    $filename = $_POST['filename'];
    
    // 以下は Web サーバ経由でなく Draw から dir を辿るので絶対パスでなく相対パス
    $homeDir = "../NOA_ARCHIVE";
    
    if (! file_exists($homeDir)) mkdir($homeDir);
    $dir = "$homeDir/$container";
    if (! file_exists($dir)) mkdir($dir);
    $path = "$dir/$filename";
    
    if ($key == "PUT_IMAGE"){
        if ($value){
            $value = base64_decode($value, FALSE);
            $path = "$path.png";
            $fp = fopen($path, 'w');
            $size = fwrite_stream($fp, $value);
            fclose($fp);
            echo "<img src=$path><br>";
            echo "<SEPARATOR>Saved size( $size )\n path( $path )";
        } else {
            echo "<SEPARATOR>Has no base64 \nvalue($value)";
        }
    } else if ($key == "SAVE_IMAGE"){
        //$imageSrc = $_POST['imageSrc'];
        $imageId = $_POST['imageId'];
        $files = $_FILES['files']['name'];
        $tmpFiles = $_FILES['files']['tmp_name'];
        
        $count = count($files);
        for ($i=0; $i < $count; $i++){
            $filename = $files[$i];
            $tmp = $tmpFiles[$i];
            if (strlen($filename) > 0){
                if (!is_uploaded_file($tmp)){
                    echo "<p>$filename を保存できませんでした</p>";
                    break;
                } else {
                    $sfx = suffix($filename);
                    $path = "$dir/$imageId"."_$i$sfx";
                    copy($tmp, $path);
                    echo "<img src=$path><br>";
                    echo "SAVED: $path <br>";
                }
            }
        }
        
        $uri = $_SERVER['HTTP_REFERER'];
        echo "<p><A HREF=$uri>元の画面へ戻る</A></p>";
        //header("Location: ".$uri); // ### 前後で何かを表示すると機能しない ###
        exit;
    } else if ($key == "REMOVE_IMAGE"){
        unlink($value); // $value は full path
        $results = getDir($dir);
		echo "<SEPARATOR>";
		echo json_encode($results);
    } else if ($key == "GET_DIRECTORY"){
        $results = getDir($dir);
        //rsort($results); // 逆順にソート
		echo "<SEPARATOR>";
		echo json_encode($results);
    } else if ($key == "TEST_IMAGE"){
        $type = $_POST['type'];
        $filename = $_POST['name']; // [object FileList]
		echo "file($type) name($filename)";
    } else {
        echo "<p>key( $key ) is wrong *****</p>";
    }
    
?>