<?php
require_once ('../../../../wp-load.php');
require_once ('../includes/utils.inc.php');

if ( !current_user_can('edit_pages') ) {
	wp_die( __('You are not allowed to edit this item.') );
}

mb_regex_encoding('UTF-8');
mb_internal_encoding("UTF-8");

$book_id = (int)$_POST['book_id'];
$bind = $_POST['bind'];
$css = $_POST['css'];
$epubmeta = $_POST['epubmeta'];
$etemplate = $_POST['etemplate'];
$title = get_cat_name($book_id);

if ($bind == 'right') {
	$bind = 'rtl';
}
else {
	$bind = 'ltr';
}

/**
 * UUIDを生成
 * 
 * @author     Anis uddin Ahmad <admin@ajaxray.com>
 * @param      string  an optional prefix
 * @return     string  the formatted uuid
 */
function uuid($prefix = '') {
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr($chars, 0, 8) . '-';
    $uuid .= substr($chars, 8, 4) . '-';
    $uuid .= substr($chars, 12, 4) . '-';
    $uuid .= substr($chars, 16, 4) . '-';
    $uuid .= substr($chars, 20, 12);
    return $prefix . $uuid;
}

global $wpdb;
$sql = "SELECT p.id,p.post_title,p.post_content
        FROM {$wpdb->prefix}term_relationships AS t
        INNER JOIN {$wpdb->prefix}posts AS p ON p.id=t.object_id
        WHERE t.term_taxonomy_id=$book_id";
$entries = $wpdb->get_results($sql, ARRAY_A);
$rows = $wpdb->get_results($sql, ARRAY_A);
pripre_sort_bookposts($book_id, $rows);

$tmpdir = pripre_get_tmp_dir();
$dir = tempnam($tmpdir, "dir");
unlink($dir);
mkdir($dir);

file_put_contents("$dir/mimetype", "application/epub+zip");

$data = <<< EOD
<?xml version="1.0" encoding="utf-8"?>
<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
   <rootfiles>
      <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
   </rootfiles>
</container>
EOD;
mkdir("$dir/META-INF");
file_put_contents("$dir/META-INF/container.xml", $data);

$uuid = uuid();
$modified = date('Y-m-d\Th:i:s\Z');

global $more;
$more = 1;

$rsrcs = array();

mkdir("$dir/OEBPS");
$fp = fopen("$dir/OEBPS/content.opf", "w");
if (empty($epubmeta)) {
    $epubmeta = <<< EOD
   <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
      <dc:language>ja</dc:language>
      <dc:identifier id="BookID">$uuid</dc:identifier>
      <dc:title>$title</dc:title>
      <meta property="dcterms:modified">$modified</meta>
   </metadata>

EOD;
}
else {
	$epubmeta = str_replace('@TITLE@', $title, $epubmeta);
	$epubmeta = str_replace('@UUID@', $uuid, $epubmeta);
	$epubmeta = str_replace('@MODIFIED@', $modified, $epubmeta);
}
$data = <<< EOD
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="BookID">
   $epubmeta
   <manifest>
      <item id="nav" href="nav.html" properties="nav" media-type="application/xhtml+xml"/>
      <item id="common-css" href="common.css" media-type="text/css"/>
      
EOD;
fwrite($fp, $data);

if (!empty($etemplate)) {
	$data = <<< EOD
      <item id="style-css" href="style.css" media-type="text/css"/>

EOD;
	fwrite($fp, $data);
}

if (!empty($css)) {
$data = <<< EOD
      <item id="ext-css" href="ext.css" media-type="text/css"/>

EOD;
fwrite($fp, $data);
}

function _endsWith($haystack, $needle) {
    $start = - strlen($needle);
    return (substr($haystack, $start) === $needle);
}

foreach ($rows as $row) {
    $id = $row['id'];
$data = <<< EOD
      <item id="t$id" href="$id.html" media-type="application/xhtml+xml"/>
    
EOD;
fwrite($fp, $data);

    $content = $row['post_content'];
    $regs = array();
    preg_match_all ('/src=\\"([^\\"]*)\\"/', $content, $regs, PREG_PATTERN_ORDER);
    foreach ($regs[1] as $src) {
        $slash = mb_strrpos($src, '/');
        if ($slash !== FALSE) {
            $name = mb_substr($src, $slash + 1);
        }
        else {
            $name = $src;
        }
        $rsrcs[$src] = $name;
        $mime = "image/jpeg";
        if (_endsWith($name, ".svg")) {
            $mime = "image/svg+xml";
        }
        else if (_endsWith($name, ".png")) {
            $mime = "image/png";
        }
$data = <<< EOD
      <item id="r-$name" href="$name" media-type="$mime"/>
    
EOD;
fwrite($fp, $data);
    }
    
}

$data = <<< EOD
   </manifest>
   <spine page-progression-direction="$bind">

EOD;
fwrite($fp, $data);

foreach ($rows as $row) {
    $id = $row['id'];
$data = <<< EOD
      <itemref idref="t$id"/>
    
EOD;
fwrite($fp, $data);
}

$data = <<< EOD
   </spine>
</package>
EOD;
fwrite($fp, $data);
fclose($fp);

$fp = fopen("$dir/OEBPS/nav.html", "w");
$data = <<< EOD
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html lang="ja"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:epub="http://www.idpf.org/2007/ops">
  <head>
    <meta charset="UTF-8" />
    <meta name="generator" content="PriPre" />
    <title>$title</title>
  </head>
  <body>
    <nav epub:type="toc" id="toc">
      <ol>

EOD;
fwrite($fp, $data);

$i = 0;
foreach ($rows as $row) {
    $id = $row['id'];
    $post_title = $row['post_title'];
    ++$i;
$data = <<< EOD
        <li><a href="$id.html">$post_title</a></li>

EOD;
fwrite($fp, $data);
}

$data = <<< EOD
      </ol>
    </nav>
  </body>
</html>
EOD;
fwrite($fp, $data);
fclose($fp);

$basedir = pripre_get_base_dir();
copy("$basedir/templates/common.css", "$dir/OEBPS/common.css");
if (!empty($etemplate)) {
	copy("$basedir/templates/ebook/$etemplate/style.css", "$dir/OEBPS/style.css");
}
if (!empty($css)) {
	file_put_contents("$dir/OEBPS/ext.css", $css);
}

foreach ($rsrcs as $src => $name) {
	$file = "$dir/OEBPS/$name";
	@mkdir(dirname($file), 0777, true);
    copy($src, $file);
}

$html_head = <<< EOD
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="generator" content="PriPre" />
    <link rel="stylesheet" href="common.css" type="text/css" />

EOD;

if (!empty($etemplate)) {
	$html_head .= <<< EOD
    <link rel="stylesheet" href="style.css" type="text/css" />

EOD;
}

if (!empty($css)) {
	$html_head .= <<< EOD
    <link rel="stylesheet" href="ext.css" type="text/css" />

EOD;
}

foreach ($rows as $row) {
    $id = $row['id'];
    $title = $row['post_title'];
    $content = $row['post_content'];
    foreach ($rsrcs as $src => $name) {
    	$content = str_replace(" src=\"$src\"", " src=\"$name\"", $content);
    }
    
    if (empty($etemplate)) {
	    $template = get_post_custom_values('pripre_entry_style', $id);
	    if (empty($template)) {
	    	$template = "book/plain";
	    }
	    else {
	    	$template = "book/".$template[0];
	    }
	    ob_start();
	    include ("$basedir/templates/$template/style.css");
	    $css = ob_get_contents();
	    ob_end_clean();
    }
    else {
    	$css = '';
    	$template = "ebook/$etemplate";
    }
    
    
    ob_start();
    include ("$basedir/templates/$template/entry.php");
    $entry = ob_get_contents();
    ob_end_clean();
    
$data = $html_head;
if (!empty($css)) {
	$data .= <<< EOD
    <style type="text/css">
$css
    </style>

EOD;
}

$data .= <<< EOD
    <title>$title</title>
  </head>
  <body>
$entry
  </body>
</html>
EOD;
	file_put_contents("$dir/OEBPS/$id.html", $data);
}

header("Content-Type: application/epub+zip");
header("Content-Disposition: attachment");
passthru("perl ".dirname(__FILE__)."/publish-epub.pl $dir");
pripre_rmr($dir);
?>
