<?php

require '../header.php';

require_login();

if ( isset($_REQUEST['comic']) ) {
   $comicfull = realpath(COMICSDIR . base64_decode(urldecode($_REQUEST['comic'])));
   if ( $comicfull === false ) exit();
   if ( substr($comicfull, 0, strlen(COMICSDIR)) != COMICSDIR ) exit();
   $comic = substr($comicfull, strlen(COMICSDIR));
   $comicoutputurl = "comics" . str_replace("#", "", $comic) . "/";
   $comicoutputfull = "../" . EXTRACTSDIR . str_replace("#", "", $comic) . "/";
} else {
   exit();
}

$ext = strtolower(substr($comicfull, -3));
$_SESSION['comfile'] = basename($comicfull);

$data = array();

// Get the current page for this comic or 0 (zero) if never opened
$query = "SELECT currentpage FROM pagetracker WHERE username=:username AND issue=:issue";
$fields = array();
$fields[':username'] = $_SESSION['username'];
$fields[':issue'] = $_SESSION['comfile'];
$sth = $globaldbh->prepare($query);
$sth->execute($fields);
if ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
   $currentpage = intval($row['currentpage']);
} else {
   $currentpage = 0;
}
$data["startindex"] = $currentpage;

if ( !is_dir($comicoutputfull) ) {
   mkdir($comicoutputfull, 0755, true);
}

$files = array();
if ( $ext == "cbz" ) {
   $zip = new ZipArchive();
   $opened = $zip->open($comicfull);
   for ( $i=0; $i<$zip->numFiles; $i++ ) {
      $imgname = basename($zip->getNameIndex($i));
      $myext = substr($imgname, -3);
      if ( ($myext == "jpg") || ($myext == "png") ) {
         $imgname = str_replace("#", "", $imgname);
         $imgcontents = $zip->getFromIndex($i);
         $written = file_put_contents($comicoutputfull . $imgname, $imgcontents);
         if ( $written ) $files[] = $imgname;
      }
   }
} elseif ( $ext == "cbr" ) {
   $junk = `/usr/local/bin/rar e -ep -o+ "$comicfull" "$comicoutputfull"`;
   $fh = opendir($comicoutputfull);
   while ( false !== ($file = readdir($fh)) ) {
      $myfile = $comicoutputfull . $file;
      $mynewfile = $comicoutputfull . str_replace("#", "", $file);
      $myext = strtolower(substr($file, -3));
      if ( ($myext == "jpg") || ($myext == "png") ) {
         rename($myfile, $mynewfile);
         $files[] = basename($mynewfile);
      }
   }
   closedir($fh);
} else {
   exit();
}

natsort($files);

$images = array();
$captions = array();

$last = count($files);
$count = 0;
foreach ( $files as $file ) {
   $count++;
   $images[] = $comicoutputurl . $file;
   $captions[] = substr(basename($comicoutputurl), 0, -4) . ": {$count} of {$last}";
}
$debug = (DEBUG_SHOWCOMICAJAX || DEBUG_ALL);

$data["debug"] = $debug;
$data["images"] = $images;
$data["captions"] = $captions;
header('Content-Type: application/json');
echo json_encode($data);
exit();

// vim: set ts=3 sw=3 et: