<?php
include("./config.php");
include_once(
"/mnt/server/data/test/utility/DataAccessObject.php");
DataAccessObject::setDBName($config["db_name"]);
ini_set("display_errors",true);

function 
getdir(){
    
$explode explode("/",$_SERVER["SCRIPT_NAME"]);
    
$script_filename $explode[count($explode)-1];
    return 
str_replace($script_filename,"",$_SERVER["SCRIPT_NAME"]);
}

function 
bytes_unit($filesize){
    
$count 0;

    while(
$filesize >= 1024){
        
$filesize /= 1024;
        
$count++;
    }

    
$units[0] = "B";
    
$units[1] = "KB";
    
$units[2] = "MB";
    
$units[3] = "GB";

    if(
preg_match("/\./",$filesize)){
        
$tmp explode(".",$filesize);
        
$tmp[1] = substr($tmp[1],0,2);
        return 
"{$tmp[0]}.{$tmp[1]} {$units[$count]}";
    } else {
        return 
"{$filesize} {$units[$count]}";
    }
}

foreach(
$_GET as $key => $value){
    
$_GET[$key] = preg_replace("/'|`/","",$_GET[$key]);
}

foreach(
$_POST as $key => $value){
    
$_POST[$key] = preg_replace("/'|`/","",$_POST[$key]);
}


if(!
stristr($_SERVER["REQUEST_URI"],"{$_SERVER["SCRIPT_NAME"]}/") && ($_SERVER["QUERY_STRING"] == "" && !isSet($_POST["mode"])) || (is_numeric($_GET["gallery"]) && !isSet($_POST["mode"])) || (is_numeric($_GET["page"]) && !isSet($_POST["mode"])) || ($_GET["search_text"] != "" && isSet($_POST)) || ($_GET["mode"] == "ranking" && isSet($_POST))){
    if(isset(
$_GET["c"]) && $_GET["c"] < || $_GET["c"] > 32){    
        
$notfound true;
    }

    if(!isset(
$_GET["page"]) && !is_numeric($_GET["page"])){
        
$_GET["page"] = 1;
    }
    
$pp intval($_GET["page"]);
    
$gallery = isset($_GET["gallery"]) ? intval($_GET["gallery"]) : "";

    
$rand rand(0,31);
    
$search_text = isset($_GET["search_text"]) ? htmlspecialchars($_GET["search_text"]) : "";
    
$query_id "id";
    if(
$search_text != ""){
        
$search_query " WHERE (`id` LIKE '%{$search_text}%' or `comment` LIKE '%{$search_text}%' or `extension` LIKE '%{$search_text}%' or `original_filename` REGEXP '%{$search_text}%') and `status`='found'";
        
$search_query_2 " WHERE (`id` LIKE '%{$search_text}%' or `comment` LIKE '%{$search_text}%' or `extension` LIKE '%{$search_text}%' or `original_filename` REGEXP '%{$search_text}%') and `status`='found'";
        
$search_page "&search_text={$search_text}";
    } elseif(
$_GET["mode"] == "ranking"){
        
$search_query "  WHERE `status`='found' ORDER BY `dl` DESC";
        
$search_query_2 " WHERE `status`='found'";
        
$query_id "dl";
    } else {
        
$search_query_2 " WHERE `status`='found'";    
    }
    
$query "SELECT COUNT(*) FROM `list`{$search_query}";
    if(!
$_GET["search_text"] && $_GET["mode"] != "ranking"){
        
$query .= " WHERE `status`='found'";
    }
    
$count DataAccessObject::selectOne($query,array());

    if(
ceil($count["COUNT(*)"] + 30) < $_GET["page"] || $_GET["page"] < 1){
        
$notfound true;    
    }
    
$limit_min = ($_GET["page"] - 1) * 30;
    
$limit_max = ($_GET["page"]) * 30;
    
$page_link .= ("    <div id=\"page\">\r\n        ");

    
$min_page 0;
    
$max_page ceil($count["COUNT(*)"] / 30);
    
$page 0;
    if(
$_GET["gallery"] == 1){
        
$gallery_mode "&gallery=1";
    }
    if(
$_GET["mode"] == "ranking") {
        
$gallery_mode .= "&mode=ranking";
    }
    if(
$_GET["page"] > 1){
        
$pp $_GET["page"] - 1;
        
$prev_page "[<a href=\"./?page={$pp}{$gallery_mode}{$search_page}\">{$pp}</a>]";
    }
    if(
$_GET["page"] < $max_page){
        
$np $_GET["page"] + 1;
        
$next_page "[<a href=\"./?page={$np}{$gallery_mode}{$search_page}\">{$np}</a>]";
    }
    
$page_link .= "&lt;&lt;&nbsp;{$prev_page}&nbsp;\r\n        <form action=\"./\" method=\"GET\" id=\"page_select\">\r\n            <select name=\"page\" onChange=\"page_change(this);\">\r\n";
    while(
$min_page $max_page){
        
$page $min_page 1;
        if(
$_GET["page"] == $page){
            
$page_link .= ("                <option value=\"{$page}\" selected>{$page}</option>\r\n");
        } else {

            
$page_link .= ("                <option value=\"{$page}\">{$page}</option>\r\n");
        }
        
$min_page++;    
    }

    if(
$_GET["gallery"] == 1){
        
$gallery intval($_GET["gallery"]);
        
$gal "\r\n\t\t<input type=\"hidden\" name=\"gallery\" value=\"{$gallery}\">";
    }
    if(
$_GET["mode"] == "ranking"){
        
$rnk "\r\n\t\t<input type=\"hidden\" name=\"mode\" value=\"ranking\">";
    }
    if(
$_GET["search_text"] != ""){
        
$search_t "<input type=\"hidden\" name=\"search_text\" value=\"{$search_text}\">";
    }
    
$page_link .= ("            </select>{$gal}{$rnk}{$search_t}\r\n        <input type=\"submit\" value=\"移動\">\r\n        </form>\r\n        &nbsp;{$next_page}&nbsp;&gt;&gt;");
    
$page_link .= ("</div>\r\n");
    
$num_query DataAccessObject::select("SELECT * FROM `list`{$search_query_2} ORDER BY `{$query_id}` DESC LIMIT {$limit_min},30",array());
    
$waru_5 0;
    
$dir getdir();

    while(
$row $num_query->fetch()){
        
$time date("Y/m/d(D) H:i",$row["date"]);
        
$size $row["filesize"];


        
$size bytes_unit($size);

        
//$number = str_pad($row["id"],5,0,STR_PAD_LEFT);
        
$sa date("U") - $row["date"];
        if(
$sa 103200){
            
$new "New!";
        }
        
$edit "<a href=\"./?mode=edit&id={$row["id"]}\">編集/詳細</a>";
        if(
$row["dl_password"] != ""){
            
$pass "<font color=\"red\">[🔒]</font>";
        }
        
$short "";
        if(!empty(
$row["short"])){
            
$short "[<a href=" $row["short"] . ">短縮</a>]";
        }
        if(
$_GET["gallery"] == || $config["image_mode"] == 1){
            if(
preg_match("/0|5|10|15|20|25/",$waru_5)){
                
//$mae = "<tr>";
            
}
            if(
preg_match("/4|9|14|19|24|29/",$waru_5)){
                
//$usiro = "</tr>";
            
}
            switch(
strtolower($row["extension"])){
                case 
"zip":
                case 
"7z":
                case 
"lzh":
                case 
"rar":
                
$thumbnail "./archive.png";
                break;
                case 
"mp3":
                case 
"wma":
                case 
"m4a":
                case 
"wav":
                case 
"mid":
                
$thumbnail "./music.png";
                break;
                case 
"mp4":
                
//case "mpg":
                //case "mpeg":
                    
if($row["dl_password"] == ""){
                        
$player "<a href=\"./view.php?id={$row["id"]}\">[再生]</a>";
                    }
                default:
                    if(
$row["dl_password"] == ""){
                        
$thumbnail "./t.php?file={$row["id"]}.{$row["extension"]}";
                    } else {
                        
$thumbnail "./image.png";
                    }
                break;
            }

            
$data = <<<DATA
        {$mae}<div class="thumbnail"><span class="list_image"><a href="./?mode=dl&id={$row["id"]}" target="_blank"><img src="{$thumbnail}" /></a></span><br /><span class="list_text"><font color="red">{$new}</font> [<a href="./?mode=dl&id={$row["id"]}" target="_blank">{$row["id"]}.{$row["extension"]}</a>]{$pass}{$short}{$player}<br />DL:{$row["dl"]}<br />{$edit}<input type="button" value="追加" name="http://{$_SERVER["HTTP_HOST"]}{$dir}?mode=dl&id={$row["id"]}" onClick="add_str(this);" /></span></div>{$usiro}
DATA;
            
$waru_5++;
        } else {
            switch(
strtolower($row["extension"])){
                case 
"mp4":
                case 
"mpg":
                case 
"mpeg":
                    if(
$row["dl_password"] == ""){
                        
$player "<a href=\"./view.php?id={$row["id"]}\">[再生]</a>";
                    }
                default:
            }
            
$data = <<<DATA

        <tr><td class="new">
{$new}</td><td class="dl">{$row["dl"]}</td><td class="time">{$time}</td><td class="filename" width="200px"><input type="button" value="追加" name="http://{$_SERVER["HTTP_HOST"]}{$dir}?mode=dl&id={$row["id"]}" onClick="add_str(this);" />[<a href="./?mode=dl&id={$row["id"]}" target="_blank">{$row["id"]}.{$row["extension"]}</a>]{$pass}{$short}{$player}</td><td class="edit">{$edit}</td></tr>

DATA;
        }
        
$file_list .= $data;
        
$sa "";
        
$new "";
        
$mae "";
        
$usiro "";
        
$pass "";
        
$player "";
    }

    if(
$_GET["gallery"] != && $config["image_mode"] != 1){
        
$table_th "<tr><th width=\"50px\">新着</th><th width=\"20px\">DL</th><th width=\"120px\">日付</th><th width=\"200px\">ファイル名</th><th></th></tr>";
        
$table_start "<table id=\"file_list\" border style='width: 540px;'>";
        
$table_end "</table>";
    }
    
$body = <<<BODY
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="js/form.js"></script>
<title>
{$config["page_title"]}</title>
<script type="text/javascript">
function page_change(select_page){
    if(location.href.match(/page=/)){
        location.href = location.href.replace(/page=[0-9]+/,"page=" + select_page.value);
    } else {
        if(location.href.match(/\/$/)){
            location.href = location.href + "?page=" + select_page.value;
        } else {
            location.href = location.href + "&page=" + select_page.value;
        }
    }
}
</script>
</head>
<body>
<div id="wrapper">
    <div id="header">
    <h1>
{$config["page_title"]}</h1>

    </div>
{$config["menu"]}
    <div id="message">
        <p>
{$config["message"]}
        </p>    
    </div>
    <div id="upload_form">
        <form action="./" enctype="multipart/form-data" method="POST" id="form">
            <table>
                <tr><td class="ubg">
                <label for="file">ファイル</label>
                </td><td>
                <input type="file" name="file[]" id="file" multiple />
                </td><td class="ubg">
                <label for="edit_password">編集パス</label></td>
                <td><input type="password" name="edit_password" id="edit_password" /></td>
                <td class="ubg">
                <label for="dl_password">DLパス(任意)</label></td>
                <td><input type="password" name="dl_password" id="dl_password" /></td>
                </tr>
                <tr><td class="ubg">
                <label for="comment">コメント</label>
                </td><td>
                <input type="text" name="comment" value="" id="comment" />
                </td><td colspan="4">
                <input type="reset" value="リセット" />
                <input type="hidden" name="mode" value="upload" />
                <input type="button" value="アップロード" onClick="upload();" />
                </td></tr>
            </table>
            <p>
                <ul>
{$config["upload_form"]}
                </ul>
            </p>
        </form>
        <div id="upload_progress_div" style="width:610px;height:15px;margin:10px 0;border: 1px solid #555555;display: none;"><div id="upload_progress_bar" style="background-color: #819FF7;height: 15px;width: 0px;"></div></div>
        <div id="progress_bytes"></div><div id="progress_percent"></div>
        <script>
        function bytes_unit(e){
            var count = 0;
            while(e >= 1024){
                e = e / 1024;
                count++;
            }
            var unit = "";
            switch(count){
                case 0:
                    unit = "B";
                break;
                case 1:
                    unit = "KB";
                break;
                case 2:
                    unit = "MB";
                break;
                case 3:
                    unit = "GB";
                break;
            }
            e_split = e.toString().split(".");
            return e_split[0] + "." + e_split[1].substr(0,3) + unit;
        }
        function upload(){
        if(document.getElementById("edit_password").value == ""){
            alert("編集パスワードが設定されていません。");
            return false;
        }
            var form = document.getElementById("form");
            form.style.display = "none";
            
            if(!window.FormData){
                form.submit();
            }
            
            var form_data = new FormData(form);
            var req = new XMLHttpRequest();
            document.getElementById("upload_progress_div").style.display = "block";
            
            req.onreadystatechange = function(){
                if(req.readyState == 4 && req.status == 200){
                    location.reload();
                }
            }
            req.upload.onprogress = function(e){
                if(e.total > 
{$config["max_filesize"]}){
                    req.abort();
                    location.reload();
                    return false;
                }
                document.getElementById("progress_percent").textContent = Math.floor(e.loaded / e.total * 100) + "%";
                document.getElementById("progress_bytes").textContent = bytes_unit(e.loaded) + "/" + bytes_unit(e.total);
                document.getElementById("upload_progress_bar").style.width = Math.floor(e.loaded / e.total * 610) + "px";
            };
            req.open(form.method,form.action);
            req.send(form_data);
        }
        </script>
    </div>
    <div id="search_form">
        <form action="./" method="GET">
            <input type="hidden" name="gallery" value="
{$gallery}" />
            <input type="text" name="search_text" />
            <input type="submit" value="検索" />
        </form>
    </div>
    <div class="page_link">
    
{$page_link}
    </div>
    <div id="list">
    
{$table_start}
        
{$table_th}
{$file_list}
    
{$table_end}
    </div>
    <div class="page_link">
    
{$page_link}
    </div>
    <div id="copy_form">
        <form name="form1">
        <textarea name="copy_area" id="copy_area" rows="10" cols="60"></textarea>
        <br />
        <input type="button" value="選択" onclick="document.form1.copy_area.focus();document.form1.copy_area.select();" style="width:60;height:40;font-size:16px" />
        <input type="button" value="リセット" onclick="del_str();" style="height:40px;font-size:16px" />
        </form>
    </div>
    <div id="copyright">
        <p>
{$_SERVER["HTTP_HOST"]}</p>
    </div>
</div>
</body>
</html>
BODY;
    print(
$body);
    
$access true;
}

if(
$_GET["mode"] == "edit" && $_GET["id"]){

    
$id intval($_GET["id"]);
    
$id_0 str_pad($id,5,0,STR_PAD_LEFT);

    
$row DataAccessObject::selectOne("SELECT * FROM `list` WHERE `id`={$id}",array());
    
$date date("Y/m/d(D) H:i",$row["date"]);
    if(
$row["dl_password"] != ""){
        
$pass "<font color=\"red\">[🔒]</font>";
    }
    
$size $row["filesize"];
    
$size bytes_unit($size);
$body = <<<BODY
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="js/form.js"></script>
<title>
{$config["page_title"]}</title>
</head>
<body>
<div id="wrapper">
    <div id="header">
    <h1>
{$config["page_title"]}</h1>

    </div>
{$div["menu"]}
    <div id="message">
        <p>
{$div["message"]}
        </p>    
    </div>
    <div id="info">
        <table style="border-collapse: collapse;" border>
            <tr><th width="120px">日付</th><th width="160px">ファイル名</th><th width="160px">オリジナル名</th></tr>
            <tr><td class="time">
{$date}</td><td class="filename"><a href="./?mode=dl&id={$row["id"]}" target="_blank">{$row["id"]}.{$row["extension"]}</a></td><td class="original"><a href="./?mode=dl&id={$row["id"]}&original=1" target="_blank">{$row["original_filename"]}</a></td></tr>
            <tr><th>ダウンロード数</th><th width="60px">サイズ</th><th width="200px">コメント</th></tr>
            <tr><td class="dl">
{$row["dl"]}</td><td class="size">{$size}</td><td>{$pass}{$row["comment"]}</td></tr>
        </table>
    </div>
    <div id="edit_form">
        <form action="./" method="POST">
            <label for="comment">コメントを編集</label><br />
            <input type="text" name="comment" id="comment" value="
{$row["comment"]}" class="text" />
            <br />
            <label for="edit_password">編集パス</label><br />
            <input type="password" name="edit_password" id="edit_password" />
            <input type="hidden" name="mode" value="edit_or_delete" />
            <input type="hidden" name="id" value="
{$id}" />
            <input type="submit" name="edit" value="コメント修正" />
            <input type="submit" name="edit" value="ファイル削除" />
        </form>
    </div>
    <div id="copyright">
        <p>
{$_SERVER["HTTP_HOST"]}</p>
    </div>
</div>
</body>
</html>
BODY;
    if(
$row["status"] != "found"){
        
header("Location: ./");
    } else {    
        print(
$body);
    }
    
$access true;
}

function 
outputFile($path){
    
$fp fopen($path,"r");
    while((
$buf fread($fp,4096)) != false){
        echo 
$buf;
        
flush();
    }
    
fclose($fp);
}
list(,,,
$id,$filename) = explode("/",$_SERVER["REQUEST_URI"]);
if((
$_GET["id"] != "" && $_GET["mode"] == "dl" || is_numeric($id) && $filename != "") && !$access){
    
//    if(file_exists("./{$config["upfolder"]}/{$row["id"]}.{$row["extension"]}")){
        
if(is_numeric($id) && $id){
            
$_GET["id"] = $id;
        }

            
$row DataAccessObject::selectOne("SELECT * FROM `list` WHERE `id`={$_GET["id"]}",array());
            if(
$_GET["original"] == "1" && $row["dl_password"] == ""){
                
header("Location: {$_SERVER["SCRIPT_NAME"]}/{$_GET["id"]}/{$row["original_filename"]}");
                exit;
            }
            
$size $row["filesize"];
            
$size bytes_unit($size);
            
//$id = str_pad($row["id"],5,0,STR_PAD_LEFT);
        
if($row["status"] != "found"){
            
header("Location: ./");
            exit;
        }
        if(
$row["id"] > 0){
            
$dl $row["dl"] + 1;
            if(!
$row["dl_password"]){
                
header("Content-Length: {$row["filesize"]}");
                if(
$filename != ""){
                    
$encoded_filename rawurlencode($row["original_filename"]);
                    if(!
preg_match("/Trident/",$_SERVER["HTTP_USER_AGENT"])){
                        
//if(rawurlencode($row["original_filename"]) == rawurlencode($filename)){
                            
header("Content-Disposition: attachment;filename=\"{$row["original_filename"]}\"");
                            
header("Content-Type: application/octet-stream");
                            
outputFile("./{$config["upfolder"]}/{$row["id"]}.{$row["extension"]}");
                        
/*} else {
                            header("Location: /uploade./{$config["upfolder"]}/{$row["id"]}.{$row["extension"]}");
                        }*/
                    
} else {
                        
//if(rawurlencode($row["original_filename"]) == rawurlencode($filename)){
                            
header("Content-Type: application/octet-stream");
                            
header("Content-Disposition: attachment;filename=\"{$encoded_filename}\"");
                            
header("X-Content-Type-Options: nosniff");
                            
outputFile("./{$config["upfolder"]}/{$row["id"]}.{$row["extension"]}");
                        
/*} else {
                            header("Location: /uploade./{$config["upfolder"]}/{$row["id"]}.{$row["extension"]}");
                        }*/
                    
}
                    
DataAccessObject::update("UPDATE `list` SET `id`={$row["id"]},`dl`={$dl} WHERE `id`={$row["id"]}",array());
                } else {
                    
// 悪意のあるコードの実行を防ぐため、readfile経由でファイルを読み込むように変更。 2018/01/27
                    //header("Location: ./{$config["upfolder"]}/{$row["id"]}.{$row["extension"]}");
                    
header("Content-Type: application/octet-stream");
                    
header("Content-Disposition: filename={$row["id"]}.{$row["extension"]}");
                    
$path "./{$config["upfolder"]}/{$row["id"]}.{$row["extension"]}";
                    
$filesize filesize($path);
                    
outputFile($path);
                    
                    
DataAccessObject::update("UPDATE `list` SET `id`={$row["id"]},`dl`={$dl} WHERE `id`={$row["id"]}",array());
                }
            } else {
                if(
$_POST["mode"] == "dl" && $_POST["id"] == $_GET["id"] && $row["dl_password"] == substr(md5($_POST["dl_password"]),2,7)){
                    
$dl_hash $row["id"]."_".$row["dl_password"];
                    
header("Content-Length: {$row["filesize"]}");
                    if(
$_GET["original"] == "1"){
                        
$encoded_filename rawurlencode($row["original_filename"]);
                        if(!
preg_match("/Trident/",$_SERVER["HTTP_USER_AGENT"])){
                            
header("Content-Disposition: attachment;filename=\"{$row["original_filename"]}\"");
                        } else {
                            
header("Content-Disposition: attachment;filename=\"{$encoded_filename}\"");
                        }
                        
header("Content-Type: application/octet-stream");
                        
outputFile("./{$config["upfolder_pass"]}/{$dl_hash}/{$row["id"]}.{$row["extension"]}");
                    } else {
                        
header("Content-Disposition: attachment;filename=\"{$row["id"]}.{$row["extension"]}\"");
                        
header("Content-Type: application/octet-stream");
                        
outputFile("./{$config["upfolder_pass"]}/{$dl_hash}/{$row["id"]}.{$row["extension"]}");
                    }
                    
DataAccessObject::update("UPDATE `list` SET `id`={$row["id"]},`dl`={$dl} WHERE `id`={$row["id"]}",array());
                } else {
                    if(
$row["dl_password"] != ""){
                        
$pass "<font color=\"red\">[🔒]</font>";
                    }
                    if(
$sa 103200){
                        
$new "New!";
                    }
                    if(
$_GET["original"] == "1"){
                        
$original "&original=1";
                    }
        
$original_filename htmlspecialchars($row["original_filename"]);
        
$date date("Y/m/d H:i:s",$row["date"]);
        
$dl_password = empty($_GET["pass"]) ? "" $_GET["pass"];
        
$body = <<<BODY
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="./js/form.js"></script>
<title>
{$original_filename} - 小物アップローダー</title>
<style type="text/css">
th,td {
    padding: 5px;
}
th {
    background-color: #EEEEEE;
}
#dl_form {
    margin-top: 10px;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <h1>
{$config["page_title"]}</h1>
    </div>
    <center>
        <!-- admax -->
        <script type="text/javascript" src="https://adm.shinobi.jp/s/d7fa22fb4103e7a7c81bcb62a0190bb7"></script>
        <!-- admax -->
    </center>
    <div id="list">
    <table style="border-collapse: collapse;" border>
        <tr><th width="120px">日付</th><th width="160px">ファイル名</th><th width="160px">オリジナル名</th></tr>
        <tr><td class="time">
{$date}</td><td class="filename">{$row["id"]}.{$row["extension"]}</td><td class="original">{$row["original_filename"]}</td></tr>
        <tr><th>ダウンロード数</th><th width="60px">サイズ</th><th width="200px">コメント</th></tr>
        
        <tr><td class="dl">
{$row["dl"]}</td><td class="size">{$size}</td><td>{$pass}{$row["comment"]}</td></tr>

    </table>
    </div>
    <div id="dl_form">
        <form action="./?mode=dl&id=
{$row["id"]}{$original}" method="POST">
            <label for="dl_password">DLパス</label><br />
            <input type="text" name="dl_password" id="dl_password" class="text" value="
{$dl_password}"/>
            <br />
            <input type="hidden" name="mode" value="dl" />
            <input type="hidden" name="id" value="
{$row["id"]}" />
            <input type="submit" value="ダウンロード" />
        </form>
    </div>
    <div id="copyright">
        <p>
{$_SERVER["HTTP_HOST"]}</p>
    </div>
</div>
</body>
</html>
BODY;
                    print(
$body);
                }
            }
        } else {
            
header("HTTP/1.1 404 Not Found.");
            print(
"404 Not Found");
        }
    
$access true;
}

function 
post($i,$config){
    if(!
$config["upload"]){
        exit;
    }
    
$deny_ext_pattern_pattern implode("|",$config["deny_ext"]);
    
$allow_ext_pattern_pattern implode("|",$config["allow_ext"]);

    if((
preg_match("/({$deny_ext_pattern})/i",$_FILES["file"]["name"][$i]) && count($config["deny_ext"]) > && $config["order_deny_allow"] == "deny") || (!preg_match("/({$allow_ext_pattern_pattern})/i",$_FILES["file"]["name"][$i]) && count($config["allow_ext"]) > && $config["order_deny_allow"] == "allow") || $_POST["comment"] = "" || $_FILES["file"]["tmp_name"][$i] == "" || $_FILES["file"]["size"][$i] > $config["max_filesize"]){
        
header("Location: ./");
        exit;
    }

    if(
$_POST["comment"] == ""){
        
$_POST["comment"] = "up";
    }

    
$editpass_hash substr(md5($_POST["edit_password"]),2,7);
    
$dlpass_hash substr(md5($_POST["dl_password"]),2,7);

    
$num DataAccessObject::selectOne("select * from `list` order by `id` desc limit 1",array());

    
$id $num["id"] + 1;

    
$u date("U");
    if(
preg_match("/jpg|jpeg|jpe|png|gif/i",$_FILES["file"]["tmp_name"][$i])){
        
$info getimagesize($_FILES["file"]["tmp_name"][$i]);
        switch(
$info[2]){
            case 
1:
            
$ext "gif";
            break;
            case 
2:
            
$ext "jpg";
            break;
            case 
3:
            
$ext "png";
            break;
            default:
            
$not_image true;
            break;
        }
    }

    if(
$_POST["edit_password"] == ""){
        
$editpass_hash "";
    }

    if(
$_POST["dl_password"] != ""){
        
$dl_hash $id."_".substr(md5($_POST["dl_password"]),2,7);
        @
mkdir("./{$config["upfolder_pass"]}/{$dl_hash}");
        
chmod("./{$config["upfolder_pass"]}/{$dl_hash}",0777);
        
$path $config["upfolder_pass"]."/".$dl_hash;
    } else {
        
$path $config["upfolder"];
        
$dlpass_hash "";
    }
    
    
$ext strtolower($ext);
    
$filename_dot explode(".",$_FILES["file"]["name"][$i]);
    
$dot_count count($filename_dot);
    if(!
$ext){
    
$ext strtolower($filename_dot[$dot_count 1]);
        if(!
stristr($_FILES["file"]["name"][$i],".")){
            
$ext "bin";
        }
    }

    if(
move_uploaded_file($_FILES["file"]["tmp_name"][$i],"./{$path}/{$id}.{$ext}")){
        
chmod("./{$path}/{$id}.{$ext}",0777);
        
$short "";
        
DataAccessObject::insert("INSERT INTO `list`(`id`,`remote_addr`, `original_filename`, `extension`, `filesize`, `date`, `comment`, `dl`, `edit_password`, `dl_password`,`short`, `status`) VALUES ({$id},'{$_SERVER["REMOTE_ADDR"]}','{$_FILES["file"]["name"][$i]}','{$ext}',{$_FILES["file"]["size"][$i]},'{$u}','{$comment}',0,'{$editpass_hash}','{$dlpass_hash}','{$short}','found')",array());
        
$file_list "";

    } else {
        @
unlink($_FILES["file"]["tmp_name"][$i]);
        
$error true;
    }
}
        
if(
$_POST["mode"] == "upload" && !$access){
    
    
$comment htmlspecialchars(preg_replace("/\t|\r|\n/","",$_POST["comment"]));

    
$max count($_FILES["file"]["tmp_name"]);

    for(
$i 0;$i $max;$i++){
        
post($i,$config);
    }

    
header("Location: ./");
    
$access true;
}

if(
$_POST["mode"] == "edit_or_delete" && !$access){

    
$id intval($_POST["id"]);
    
$comment htmlspecialchars(preg_replace("/\t|\r|\n/","",$_POST["comment"]));
    
$editpass_hash substr(md5($_POST["edit_password"]),2,7);
    
$ip "xxx.xxx.xxx.xxx";

    
$data DataAccessObject::selectOne("select `id`,`extension`,`edit_password`,`dl_password`,`status` from `list` where `id`={$id}",array());
    if((
$data["edit_password"] == $editpass_hash || preg_match("/192\.168\.3\./",$_SERVER["REMOTE_ADDR"]) || $_SERVER["REMOTE_ADDR"] == $ip) && $_POST["edit"] == "ファイル削除"){
        if(
$data["id"] == $id && is_numeric($_POST["id"])){
            
DataAccessObject::update("UPDATE `list` SET `status`='notfound' WHERE `id`={$id}",array());
            
$dl_hash $data["dl_password"];
            @
rename("./{$config["upfolder_pass"]}/{$data["id"]}_{$dl_hash}/{$data["id"]}.{$data["extension"]}","./{$config["deletefolder"]}/{$data["id"]}.{$data["extension"]}");
            @
rename("./{$config["upfolder"]}/{$data["id"]}.{$data["extension"]}","./{$config["deletefolder"]}/{$data["id"]}.{$data["extension"]}");
            @
unlink("./thumb/{$data["id"]}.jpg");
            
header("Location: ./");
        } else {
            
header("Location: ./?mode=edit&id={$id}");
        }
    } else {
        if((
$data["edit_password"] == $editpass_hash || preg_match("/192\.168\.3\./",$_SERVER["REMOTE_ADDR"])) && $_POST["edit"] == "コメント修正"){
            if(
$data["id"] == $id && $data["status"] == "found" && isSet($_POST["edit"])){

            
DataAccessObject::update("UPDATE `list` SET `comment`='{$comment}' WHERE `id`={$id}",array());
            
header("Location: ./?mode=edit&id={$id}");
            } else {
            
header("Location: ./?mode=edit&id={$id}");
            }
        } else {
            
header("Location: ./?mode=edit&id={$id}");
        }
    }

    
$access true;
}

?>