<?php
define('VERSION', '1.2.0');

umask(002);

mb_language('ja');
mb_internal_encoding('UTF-8');
date_default_timezone_set('Asia/Tokyo');

session_start();

require_once('lib/smarty/Smarty.class.php');

require_once('../init.php');

function remove_directory($dir) {
    $files = array_diff(scandir($dir), array('.', '..'));
    foreach ($files as $file) {
        if (is_dir("$dir/$file")) {
            remove_directory("$dir/$file");
        } else {
            unlink("$dir/$file");
        }
    }
    return rmdir($dir);
}

function delete_cache($dir)
{
    $expire = strtotime("24 hours ago");
    $files = array_diff(scandir($dir), array('.', '..'));
    foreach ($files as $value) {
        $file = $dir . $value;
        $mtime = filemtime($file);
        if ($mtime < $expire) {
            if (is_dir($file))
                remove_directory($file);
            else
                unlink($file);
        }
    }
}

function dir_tree($dir) {
    $path = array();
    $stack[] = $dir;
    while ($stack) {
        $thisdir = array_pop($stack);
        if ($dircont = scandir($thisdir)) {
            $i=0;
            while (isset($dircont[$i])) {
                if ($dircont[$i] !== '.' && $dircont[$i] !== '..') {
                    $current_file = "{$thisdir}/{$dircont[$i]}";
                    if (is_file($current_file)) {
                        $path[] = $thisdir.'/'.rawurlencode($dircont[$i]);
                    } elseif (is_dir($current_file)) {
                        $stack[] = $current_file;
                    }
                }
                $i++;
            }
        }
    }
    return $path;
}

$bookpath = isset($_REQUEST['bookpath']) ? $_REQUEST['bookpath'] : "";
$dataurl = "";
$baseurl = "";
$home = isset($_REQUEST['home']) ? $_REQUEST['home'] : "";
$title = isset($_REQUEST['title']) ? $_REQUEST['title'] : "";
$charset = "auto";
$filetype = "txt";
$fragment = "";
$mobile = "0";
$yoko = isset($_REQUEST['yoko']) ? $_REQUEST['yoko'] : "";
$license = "";
$time = "";
$site = "";
$base = "";

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
    $proto = "https://";
else
    $proto = "http://";
$selfurl = $proto.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$rooturl = substr($selfurl, 0, strrpos($selfurl, '/') + 1);

if (isset($_SERVER['HTTP_USER_AGENT'])) {
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    if (preg_match('!Android!', $userAgent)
        || preg_match('!Mobile!', $userAgent)) {
        $mobile = "1";
    }
}

$licensefile = "../easoshiplus_license.csv";
if (file_exists($licensefile)) {
    $license = trim(file_get_contents($licensefile));
} else {
    $option = array();
    $option['ssl'] = array();
    $option['ssl']['verify_peer'] = false;
    $option['ssl']['verify_peer_name'] = false;
    $license = file_get_contents('https://www.satokazzz.com/license/easoshiplus.php?host='
        .urlencode($_SERVER['HTTP_HOST']), false, stream_context_create($option));
}

delete_cache('../cache/');

if ($yoko === "")
    $yoko = YOKOGUMI;

$time = time();

if (empty($bookpath)) {
    $bookpath = "README.txt";
    $title = "えあ草紙＋";
    $home = "https://www.satokazzz.com/airzoshi";
}

@list($base, $dummy) = explode('#', $bookpath, 2);
$site = parse_url($bookpath);
@$fragment = $site['fragment'];

$yoko = ($yoko ? 1 : 0);

$temp = md5(time().rand());
while (file_exists("../cache/".$temp.".tmp"))
    $temp = md5(time().rand());

if (!@copy($bookpath, "../cache/".$temp.".tmp"))
    exit("本の読み取りに失敗しました。");

$zip = new ZipArchive;
if ($zip->open("../cache/".$temp.".tmp") === true) {
    mkdir("../cache/".$temp);
    $zip->extractTo("../cache/".$temp);
    $zip->close();

    $images = array();
    $first_text = "";
    $files = dir_tree("../cache/".$temp);
    foreach ($files as $file) {
        $extention = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (array_search($extention, array('jpg', 'jpeg', 'jfif', 'png', 'gif')) !== false) {
            array_push($images, $file);
        } else if ($extention == 'txt' && $first_text == '') {
            $first_text = $file;
        }
    }

    if ($first_text != '') {
        $s = file_get_contents($first_text);
        $cs = strtolower(mb_detect_encoding($s, "auto"));
        if ($cs == "sjis")
            $cs .= "-win";
        else if ($cs == "euc-jp") {
            $s = mb_convert_encoding($s, "sjis-win",
                "eucJP-win");
            $cs = "sjis-win";
        }
        $s = mb_convert_encoding($s, "UTF-8", $cs);
        file_put_contents($first_text, $s);
        $charset = "utf-8";
        $dataurl = $rooturl.$file;
        $baseurl = dirname($rooturl)."/cache/".$temp."/";
        $filetype = "txt";
    } else if (!empty($images)) {
        $s = "";
        $n = count($images);
        for ($i = 0; $i < $n; $i++) {
            if ($i < $n - 1) {
                $s .= "［＃（".substr($images[$i], 42)."）入る］\n［＃改ページ］\n";
            } else {
                $s .= "［＃（".substr($images[$i], 42)."）入る］\n";
            }
        }
        file_put_contents("../cache/".$temp."/book.txt", $s);
        $charset = "utf-8";
        $dataurl = dirname($rooturl)."/cache/".$temp."/book.txt";
        $baseurl = dirname($rooturl)."/cache/".$temp."/";
        $filetype = "image";
    } else {
        exit("ZIP ファイルの中に TXT ファイルが見つかりませんでした。");
    }
} else {
    $s = file_get_contents("../cache/".$temp.".tmp");
    $cs = strtolower(mb_detect_encoding($s, "auto"));
    if ($cs == "sjis")
        $cs .= "-win";
    else if ($cs == "euc-jp") {
        $s = mb_convert_encoding($s, "sjis-win", "eucJP-win");
        $cs = "sjis-win";
    }
    $s = mb_convert_encoding($s, "UTF-8", $cs);

    $convmap = array(0, 0x10FFFF, 0, 0x10FFFF);
    $s = mb_decode_numericentity($s, $convmap, 'UTF-8');

    if (substr($cs, 0, 4) == "sjis")
        $s = str_replace("\\", "¥", $s);

    $s = str_replace(array('､', '｡'), array('、', '。'), $s);

    $s = str_replace('−−', '――', $s);
    $s = str_replace('／゛＼', '／″＼', $s);

    $r1 = array('｢', '｣');
    $r2 = array('「', '」');
    $s = str_replace($r1, $r2, $s);

    if (strpos($s, '［＃') === FALSE) {
        $r1 = array('《', '》', '［', '］', '〔', '〕', '｜', '＃', '※');
        $r2 = array(
            "\x01始め二重山括弧、1-1-52\x02",
            "\x01終わり二重山括弧、1-1-53\x02",
            "\x01始め角括弧、1-1-46\x02",
            "\x01終わり角括弧、1-1-47\x02",
            "\x01始めきっこう（亀甲）括弧、1-1-44\x02",
            "\x01終わりきっこう（亀甲）括弧、1-1-45\x02",
            "\x01縦線、1-1-35\x02",
            "\x01井げた、1-1-84\x02",
            "\x01米印、1-2-8\x02");
        $s = str_replace($r1, $r2, $s);
        $r1 = array("\x01", "\x02");
        $r2 = array('※［＃', '］');
        $s = str_replace($r1, $r2, $s);
    }

    $r1 = array('≪', '≫');
    $r2 = array('※［＃始め二重山括弧、1-1-52］',
        '※［＃終わり二重山括弧、1-1-53］');
    $s = str_replace($r1, $r2, $s);

    $path = "../cache/".$temp.".txt";
    // text
    file_put_contents($path, $s);
    $filetype = "txt";
    $charset = "utf-8";
    $dataurl = $rooturl.$path;
    $baseurl = dirname($site['path'])."/";
}

if ($charset == "auto") {
    $s = file_get_contents($dataurl, false, NULL, 0, 1000);
    $charset = strtolower(mb_detect_encoding($s, "auto"));
    if (substr($charset, 0, 4) == "sjis")
        $charset = "shift_jis";
}

$smarty = new Smarty();
$smarty->template_dir = 'lib/tmpl/';
$smarty->compile_dir = '../tmplc/';
$smarty->left_delimiter = '{{';
$smarty->right_delimiter = '}}';

$include_head = file_get_contents('../include_head.tpl');
$include_body = file_get_contents('../include_body.tpl');
$include_end = file_get_contents('../include_end.tpl');
$smarty->assign('include_head', $include_head);
$smarty->assign('include_body', $include_body);
$smarty->assign('include_end', $include_end);

$smarty->assign('time', $time);
$smarty->assign('bookpath', $bookpath);
$smarty->assign('dataurl', $dataurl);
$smarty->assign('baseurl', $baseurl);
$smarty->assign('home', $home);
$smarty->assign('title', $title);
$smarty->assign('charset', $charset);
$smarty->assign('filetype', $filetype);
$smarty->assign('fragment', $fragment);
$smarty->assign('mobile', $mobile);
$smarty->assign('yoko', $yoko);
$smarty->assign('license', $license);
$smarty->assign('version', VERSION);
$smarty->assign('copyrightyear', date("Y"));

$smarty->display('easoshiplus.html');
?>
