<?php
if(isset($_POST["mode"]) && $_POST["mode"] == "upload_image"){
    if(
preg_match("/image/",$_FILES["file"]["type"])){
        print(
"data:{$_FILES["file"]["type"]};base64,".base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
    }
    exit;
}

function 
html_header(){
    
$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>HTML5 お絵かき掲示板</title>
    <style>
        body {
            width: 1180px;
            margin: 0 auto;
        }
        #canvasarea {
            overflow: auto;
            display: none;
        }
        #left {
            float: left;
        }
        #colorarea {
        }
        #canvas {
            float: left;
        }
        #pen {
            font-size: 12px;
        }
        table {
            clear: both;
            border: 1px solid #AAAAAA;
            padding: 10px;
            margin-top: 20px;
            margin-left: 65px;
            width: 528px;
        }
        textarea {
            width: 522px;
            height: 135px;
        }
        #name,#email {
            width: 360px;
        }
        .res {
            border: 1px solid #AAAAAA;
            padding: 10px;
            margin-bottom: 20px;
        }
        .res_num {
            font-size: 18px;
        }
        img {
            border: 1px dotted #000000;
        }
        img.thumbnail {
            border: 1px solid #000000;
        }
        #file {
            display: none;
        }
        #select_button {
            width: 70px;
        }
        #image_list {
            clear: both;
            margin: 20px;
        }
        #image_list_table {
            border-collapse: collapse;
            width: 800px;
        }
        #image_list_table td {
            
        }
    </style>
</head>

HTML;
    return 
$html;
}

function 
replaceXSS($array){
    foreach(
$array as $key => $value){
        switch(
$key){
            case 
"name":
                if(
preg_replace("/\r|\n|\t|\s/","",$value)){
                    
$array[$key] = htmlspecialchars($value);
                    
$array[$key] = preg_replace("/\r|\n|\t/","<br />",$array[$key]);
                } else {
                
//    $array["error"] = "name";
                
}
            break;
            case 
"email":
                if(
$value){
                    if(
filter_var($value,FILTER_VALIDATE_EMAIL)){
                    } else {
                    
//    $array["error"] = "email";
                    
}
                }
            break;
            case 
"text":
                if(
preg_replace("/\r|\n|\t|\s/","",$value)){
                    
$array[$key] = htmlspecialchars($value);
                    
$array[$key] = str_replace("\r\n","<br />",$array[$key]);
                    
$array[$key] = str_replace("\n","<br />",$array[$key]);
                    
$array[$key] = str_replace("\r","<br />",$array[$key]);
                } else {
                    
$array["error"] = "text";
                }
            break;
        }
    }
    return 
$array;
}

if(!isset(
$_POST["mode"]) && !isset($_GET["mode"])){
    
$file = @file("./res.dat");
    
$res "";
    
$img "";
    if(
is_array($file)){
        foreach(
$file as $key => $value){
            list(
$date,$remote_addr,$name,$email,$text,$id,$image) = explode("<>",$value);
            
            list(
$u,$mili) = explode(".",$date);
            
$mili substr($mili,0,2);

            
$image preg_replace("/\n/","",$image);
            if(
$image$img "<br /><a href=\"./image/{$image}\"><img src=\"./thumbnail/{$image}\"></a>";
            if(!
$name$name "名無しさん";

            
$num $key 1;
            
            
$week = array("日","月","火","水","木","金","土");
            
            
$w date("w",$u);
            
$YmdHis date("Y年m月d日({$week[$w]}) H時i分s.{$mili}秒",$u);
            
            
$res .= <<<RES
<div class="res">
    <span id="
{$num}" class="res_num">{$num}. </span> <span>名前:{$name}</span>[{$email}] <span class="date">{$YmdHis}</span> <span>ID:{$id}</span>
    <p>
    
{$text}{$img}
    </p>
</div>

RES;
            unset(
$img);
        }
    }
    print(
html_header());
    
$html = <<<HTML
<body>
<h1>HTML5 お絵かき掲示板</h1>
<h3><a href="https://portfolio24.dip.jp/source.php?site=paint_bbs&file=index.php">ソースコードを表示</a></h3>
{$res}
<div id="canvasarea">
    <div id="left">
        <div id="colorarea">
        </div>
        <div id="pen">
            ペンの大きさ<br />
            <select onchange="context.lineWidth = this.value;" id="select">
                <script>
                    var penSize = 10;
                    var select = document.getElementById("select");
                    for(var i = 100;i > 0;i--){
                        var tmp = document.createElement("option");
                        tmp.value = i;
                        tmp.textContent = i;
                        if(i == penSize){
                            tmp.selected = true;
                        }
                        select.appendChild(tmp);
                    }
                </script>
            </select>
        </div>
        <form action="./" method="POST" enctype="multipart/form-data" id="form">
            <input type="file" name="file" id="file" />
            <input type="hidden" name="mode" value="upload_image" />
        </form>
        <button id="select_button" onClick="select_file();">画像読込</button>
        <script>
            var file = document.getElementById("file");
            function select_file(){
                file.click();
            };
            file.onchange = function(){
                upload_image();
            };
            function upload_image(){
                var req = new XMLHttpRequest();
                var form = document.getElementById("form");
                var formData = new FormData(form);

                req.onreadystatechange = function(){
                    if(req.readyState == 4 && req.status == "200"){
                        load_image(req.responseText);
                        movable(imgArray[imgArray.length-1]);
                        click_menu(imgArray[imgArray.length-1]);
                        display_image(imgArray[imgArray.length-1]);
                        createThumbnail(imgArray[imgArray.length-1]);
                        display_image_list();
                    }
                };
                req.open(form.method,form.action);
                req.send(formData);
            }
        </script>
    </div>
    <div id="canvas_wrapper">
        <canvas id="canvas" width="960px" height="540px" style="border:1px solid #000000">
        </canvas>
    </div>
    <button onClick="canvasClear();">消す</button><br />
    <script>
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");
        
        var color_list = new Array(
            "#000000","#7f7f7f","#880015","#ed1c24","#ff7f27",
            "#fff200","#22b14c","#00a2e8","#3f48cc","#a349a4",
            "#ffffff","#c3c3c3","#b97a57","#ffaec9","#ffc90e",
            "#efe4b0","#b5e61d","#99d9ea","#7092be","#c8bfe7"
        );
        
        var tmp = new Array();
        var colorarea = document.getElementById("colorarea");
        
        for(var i=0;i < color_list.length;i++){
            tmp[i] = document.createElement("div");
            tmp[i].class = "color";
            tmp[i].addEventListener("click",function(){
                context.strokeStyle = this.value;
            });
            tmp[i].style.backgroundColor = color_list[i];
            tmp[i].style.border = "1px solid #555555";
            tmp[i].style.width = "20px";
            tmp[i].style.height = "20px";
            tmp[i].style.marginBottom = "1px";
            tmp[i].style.marginRight = "8px";
            tmp[i].value = color_list[i];
            colorarea.appendChild(tmp[i]);
        }
        
        var color = "rgb(200,0,0)";
        var scrollTop = 0;

        context.lineWidth = penSize;
        context.strokeStyle = color;
        context.lineCap = "round";
        
        function canvas_move(e){
            if(flag){
                scrollTop = getScrollTop();
                if(e.type == "touchmove"){
                    var touch_list = e.changedTouches;
                    context.fillRect(touch_list[0].clientX-canvas.offsetLeft-5,touch_list[0].clientY-canvas.offsetTop-5+scrollTop,penSize,penSize);
                } else {
                    context.lineTo(e.clientX-canvas.offsetLeft-5,e.clientY-canvas.offsetTop-5+scrollTop);
                    context.stroke();
                }
            }
        }

        function setImage(){

            if(canvas_mode == 1){
                document.getElementById("image").value = canvas.toDataURL("image/png");
            } else {
                document.getElementById("image").value = "";
            }
        }
        
        var flag;

        if(navigator.userAgent.match(/Android|Tablet/) && window.TouchEvent){
            canvas.addEventListener("touchstart",function(){
                flag = true;
                context.beginPath();
            },true);
            canvas.addEventListener("touchend",function(){
                flag = false;
                context.closePath();
            },true);
            canvas.addEventListener("touchcancel",function(){
                flag = false;
                context.closePath();
            },true);
            canvas.addEventListener("touchmove",canvas_move);
        } else {
            canvas.addEventListener("mousedown",function(){
                flag = true;
                context.beginPath();
            },true);

            canvas.addEventListener("mouseup",function(){
                flag = false;
                context.closePath();
            },true);

            canvas.addEventListener("mousemove",canvas_move);
        }
        
        function canvasClear(){
            context.clearRect(0,0,canvas.width,canvas.height);
        }
        
        var imgArray = new Array();
        var maxId = 0;
        
        function load_image(url){
            var img = document.createElement("img");
            img.src = url;
            img.id = maxId;
            img.style.zIndex = maxId;
            imgArray.push(img);
            maxId++;
        }

        function display_image(){
            for(var i in imgArray){
                document.getElementsByTagName("form")[0].appendChild(imgArray[i]);
            }
        }
        
        function display_image_list(){
            var image_list = document.getElementById("image_list_table");
            var thumb;
            image_list.innerHTML = "";
            for(var i in imgArray){
                createThumbnail(imgArray[i]);
                thumb = thumbArray[imgArray[i].id].toDataURL();
                image_list.innerHTML += '<tr><th><img src="' + thumb + '" width="50px" class="thumbnail"></th><td>width:<input type="text" name="width" value="' + imgArray[i].width + '"></td><td>height:<input type="text" name="height" value="' + imgArray[i].height + '"></td><!-- <td>1%<input type="range" name="percent" min="1" max="100" value="100" onChange="resizeByPercent(' + i + ',' + imgArray[i].width + ',' + imgArray[i].height + ')">100%</td> --><td><button onClick="change_image_size(' + i + ')">変更</button></td></tr>';
            }
        }

        var mouseX = 0;
        var mouseY = 0;
        
        function drawCanvas(element){
            draw_x = element.offsetLeft - canvas.offsetLeft;
            draw_y = element.offsetTop - canvas.offsetTop;

            context.drawImage(element,draw_x,draw_y,element.width,element.height);
        }
        
        document.addEventListener("mousemove",function(e){
            mouseX = e.clientX;
            mouseY = e.clientY;
        });

        var menu = document.createElement("div");
        menu.style.position = "absolute";
        menu.style.display = "none";
        menu.style.backgroundColor = "#EEEEEE";
        menu.style.listStyleType = "none";
        menu.style.border = "1px solid #AAAAAA";

        function getScrollTop(){
            var scroll;
            if(navigator.userAgent.match(/Chrome|OPR/)){
                scrollTop = document.documentElement.scrollTop || document.body.scrollTop
                scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
            } else if(navigator.userAgent.match(/Firefox|Trident/)){
                scrollTop = document.getElementsByTagName("html")[0].scrollTop;
                scrollLeft = document.getElementsByTagName("html")[0].scrollLeft;
            }
            return scrollTop;
        }

        document.body.appendChild(menu);

        function click_menu(element){
            element.oncontextmenu = function(e){
                e.preventDefault();
                menu.style.display = "block";
                menu.style.zIndex = maxId+1;
                menu.style.top = getScrollTop() + mouseY + "px";
                menu.style.left = mouseX + "px";
                menu.innerHTML = '<a style="cursor: pointer;list-style-type: none;border-bottom:1px solid #AAAAAA;display: block;padding: 10px 0 10px 20px;width:150px;font-size: 14px;" onMouseOver="this.style.background=\'#AAAAAA\';this.style.color=\'#FFFFFF\'" onMouseOut="this.style.background=\'#EEEEEE\';this.style.color=\'#000000\'" onClick="drawCanvas(imgArray[' + getRankById(this.id) + ']);">貼付</a>';
                menu.innerHTML += '<a style="cursor: pointer;list-style-type: none;border-bottom:1px solid #AAAAAA;display: block;padding: 10px 0 10px 20px;width:150px;font-size: 14px;" onMouseOver="this.style.background=\'#AAAAAA\';this.style.color=\'#FFFFFF\'" onMouseOut="this.style.background=\'#EEEEEE\';this.style.color=\'#000000\'" onClick="deleteImage(' + this.id + ');">削除</a>';
            };
            document.onmouseup = function(){
                menu.style.display = "none";
            }
        }

        function getRankById(id){
            for(var i in imgArray){
                if(id == imgArray[i].id){
                    return i;
                }
            }
            return false;
        }

        function deleteImage(element_id){
            rank = getRankById(element_id);
            if(rank != maxId){
                for(var i in imgArray){
                    if(imgArray[rank].style.zIndex < imgArray[i].style.zIndex){
                        imgArray[i].style.zIndex--;
                    }
                }
            }

            document.getElementsByTagName("form")[0].removeChild(imgArray[rank]);
            imgArray.splice(rank,1);

            display_image_list();
        }
        
        function maxImageId(){
            var tmp = 0;
            for(var i in imgArray){
                if(imgArray[i].id > tmp){
                    tmp = imgArray[i].id;
                }
            }
            return tmp;
        }
        
        function movable(element){
            var img_flag = false;

            element.style.position = "absolute";
            element.draggable = "true";

            document.body.appendChild(element);

            element.addEventListener("dragover",imgmove);

            element.addEventListener("dragend",function(){
                img_flag = false;
            },true);

            element.addEventListener("dragstart",function(){
                img_flag = true;
                sx = mouseX - element.offsetLeft;
                sy = mouseY - element.offsetTop;

                if(element.style.zIndex != maxId){
                    for(var i in imgArray){
                        if(element.style.zIndex < imgArray[i].style.zIndex){
                            imgArray[i].style.zIndex--;
                        }
                    }
                    element.style.zIndex = maxId;
                }
            },true);

            var bx = 0;
            var by = 0;
            var sx = 0;
            var sy = 0;

            function imgmove(e){

                if(img_flag && (bx != e.clientX || by != e.clientY)){
                    if(e.clientX != 0){
                        element.style.left =  e.clientX - sx +  "px";
                    }
                    if(e.clientY != 0){
                        element.style.top = e.clientY - sy +  "px";
                    }

                    bx = e.clientX;
                    by = e.clientY;
                }
            }

        }

    </script>
</div>
<div id="image_list">
    <table id="image_list_table">
    </table>
</div>
<script>
    var width_array = document.getElementsByName("width");
    var height_array = document.getElementsByName("height");

    function change_image_size(id){
        var percent_array = document.getElementsByName("percent");
        imgArray[id].width = width_array[id].value;
        imgArray[id].height = height_array[id].value;
    }
    
    var tmp_img = document.createElement("canvas");
    
    function resizeByPercent(id,width,height){
        var percent_array = document.getElementsByName("percent");
        width_array[id].value = width * (percent_array[id].value / 100);
        height_array[id].value = height * (percent_array[id].value / 100);

        tmp_img.width = width_array[id].value;
        tmp_img.height = height_array[id].value;
        tmp_img.style.border = "1px solid green";
        tmp_ctx = tmp_img.getContext("2d");
        tmp_ctx.drawImage(imgArray[id],0,0,width_array[id].value,height_array[id].value);

        imgArray[id].src = tmp_img.toDataURL();
        tmp_img = null;
    }

    var thumbArray = new Array();

    function createThumbnail(element){
        var tmp_img = document.createElement("canvas");
        tmp_img.width = "50";
        tmp_img.height = 50 / element.width * element.height;
        
        tmp_img.style.border = "1px solid yellow";
        tmp_ctx = tmp_img.getContext("2d");
        tmp_ctx.drawImage(element,0,0,tmp_img.width,tmp_img.height);
        
        thumbArray[element.id] = tmp_img;
        tmp_img = null;
    }
    
    
    //load_image("./1.jpg");
    //movable(imgArray[0]);
    //click_menu(imgArray[0]);
    display_image();

</script>
<form action="./" method="POST" enctype="multipart/form-data">
    <input type="hidden" id="image" name="image" />
    <table>
        <tbody>
            <tr><td>[名前]</td><td><input type="text" name="name" id="name" /></td></tr>
            <tr><td>[メールアドレス]</td><td><input type="text" name="email" id="email" /></td></tr>
            <tr><td colspan="2">[本文]<br /><textarea name="text"></textarea></td></tr>
            <tr><td colspan="2"><input type="submit" value="投稿" onMouseOver="setImage();" /><input type="checkbox" onChange="canvas_toggle(this);" />絵を描く</td></tr>
        </tbody>
    </table>
</form>
<script>
    function max_index(array){
        var tmp = 0;
        for(var i = 0;array.length > i;i++){
            if(tmp < array[i].style.zIndex){
                tmp = array[i].style.zIndex;
            }
        }
        return tmp;
    }

    var canvas_mode = 0;

    function canvas_toggle(e){
        var canvasarea = document.getElementById("canvasarea");

        if(e.checked){
            canvasarea.style.display = "block";
            canvas_mode = 1;
            display_image_list();
            } else {
            canvasarea.style.display = "none";
            canvas_mode = 0;
        }
    }
    var postMode = document.createElement("input");
    postMode.type = "hidden";
    postMode.name = "mode";
    postMode.value = "post";
    document.getElementsByTagName("form")[1].appendChild(postMode);
</script>
</body>
</html>
HTML;
    print(
$html);
} else {
    if(isset(
$_POST["mode"]) && $_POST["mode"] == "post"){
        
$replacedXSSArray replaceXSS($_POST);
        
$name $replacedXSSArray["name"];
        
$email $replacedXSSArray["email"];
        
$text $replacedXSSArray["text"];
        
$error $replacedXSSArray["error"];
        
$hash md5($_SERVER["REMOTE_ADDR"].date("YmdHis").$_SERVER["HTTP_USER_AGENT"].$name.$email.$text);
        
$image_upload false;

        if(
$_POST["image"] != ""){
            
$fp fopen("./tmp/canvas_{$hash}.png","w");
            
$base64 explode(",",$_POST["image"]);
            
fwrite($fp,base64_decode($base64[1]));
            
fclose($fp);
            
$size getimagesize("./tmp/canvas_{$hash}.png");
            if(
$size[2] == 3){
                
$image_upload true;
                
$image_filename date("YmdHis").hash("crc32b",date("YmdHis")).".png";
                
rename("./tmp/canvas_{$hash}.png","./image/{$image_filename}");
                
                if(
$size[0] > $size[1]){
                    
$width 300;
                    
$height 300 $size[0] * $size[1];
                } else {
                    
$width 300 $size[1] * $size[0];
                    
$height 300;
                }

                
$width ceil($width);
                
$height ceil($height);

                
$img imageCreateFromPng("./image/{$image_filename}");
                
$canvas imageCreateTrueColor($width,$height);
                
                
imageAlphaBlending($canvas,false);
                
imageSaveAlpha($canvas,true);
                
$transparent imageColorAllocateAlpha($canvas,0xFF,0x00,0xFF,127);
                
imageFill($canvas,0,0,$transparent);
                
                
imageCopyResampled($canvas,$img,0,0,0,0,$width,$height,$size[0],$size[1]);
                
                
imagePng($canvas,"./thumbnail/{$image_filename}");
                
imageDestroy($canvas);

            } else {
                
unlink();
                
$image_upload false;
                
$image_filename "";
            }
        }

        if((
$_POST["image"] != "" && $image_upload || $_POST["image"] == "" && !$image_upload) && !$error){
            
$fp_t fopen("./res.dat","a");
            
            
$date date("U") + microtime();
            
$id hash("crc32b",$date.$_SERVER["REMOTE_ADDR"]);
            
fwrite($fp_t,"{$date}<>{$_SERVER["REMOTE_ADDR"]}<>{$name}<>{$email}<>{$text}<>{$id}<>{$image_filename}\n");
            
fclose($fp_t);
            print(
html_header());
            print(
"<meta http-equiv=\"Refresh\" content=\"3;./\" />\r\n");
            print(
"<body>\r\n");
            
$html = <<<HTML
            <p>投稿しました。</p>
HTML;
            print(
$html);
            print(
"</body>\r\n</html>");
        } else {
            @
unlink("./tmp/canvas_{$hash}.png");
            print(
html_header());
            print(
"<body>\r\n");
            switch(
$error){
                
/*case "name":
                    $error_message = "名前がありません。";
                break;*/
                /*case "email":
                    $error_message = "メールアドレスがありません。";
                break;*/
                
case "text":
                    
$error_message "本文がありません。";
                break;
            }
            print(
$error_message);
            print(
"</body>\r\n</html>");
        }
    }
}
?>