<?php
/**
 * ZWIdoku Plugin: Export DokuWiki acrticle to the ZWI format. 
 *
 * @license  LGPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author   S.Chekanov (KSF)  
 *
 */
########################## start configuration ###############################

# add name of your encyclopedia (or sandbox)
$wgMzwiName="sandbox";
#
# action tab to make "Export to ZWI"
$wgMzwiTab=true;
# Submission webpage to Encyclosphere
# Set to 0 to trigger download and nothing more
# Set to 1 to create ZWI in extension/ZWIMaker/tmp and do not do anything
# Set to 2 to create ZWI in extension/ZWIMaker/tmp and submit to the Encyclosphre
$wgMzwiSubmit=1;
#
# if false, then anybody after login can send ZWI file to Encyclosphere
# if true, then only authors or contributors can send the article to Encyclosphere
$wgMzwiAuthorApprove=false;
#
# Password for the submission
$wgMzwiPassword='0123456789';
#
# Encyclosphere submission URL if select 1
$wgMzwiSubmitUrl="https://encycloreader.org/upload/";
#
# what about the license? 
$wgMzwiLicense='CC BY-SA 3.0';
#
# Current URL of your wiki
$CURRENT_URL="https://enhub.org/dokuwiki/";
#
############################ end configuration #############################


if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../../').'/');
if(!defined('DOKU_LIB')) define('DOKU_LIB',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_LIB.'plugins/');
//define('DOKU_MAIN',realpath(dirname(__FILE__).'/../../../').'/');

// must be run within Dokuwiki
if(!defined('DOKU_INC')) die("Cannot find installed DokuWiki");

require_once(DOKU_INC.'/inc/init.php');
require_once(DOKU_INC.'/inc/template.php');


$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$newlink = str_replace("lib/plugins/zwidoku/getEncyc.php?id=", "doku.php?id=", "$actual_link");

$tmp=explode("getEncyc.php", $actual_link);
$ext_path = trim( $tmp[0] );


require("Html2Text.php");
require("ShortDescription.php");


       function texifyReference($reference) {
                $patterns[ 0] = '/[áâ�| åä]/ui';
                $patterns[ 1] = '/[ðéêèë]/ui';
                $patterns[ 2] = '/[íîìï]/ui';
                $patterns[ 3] = '/[óôòøõö]/ui';
                $patterns[ 4] = '/[úûùü]/ui';
                $patterns[ 5] = '/æ/ui';
                $patterns[ 6] = '/ç/ui';
                $patterns[ 7] = '/�~_/ui';
                $patterns[ 8] = '/\\s/';
                $patterns[ 9] = '/#/';
                $patterns[10] = '/[^A-Za-z0-9\\-:]/';
                $replacements[ 0] = 'a';
                $replacements[ 1] = 'e';
                $replacements[ 2] = 'i';
                $replacements[ 3] = 'o';
                $replacements[ 4] = 'u';
                $replacements[ 5] = 'ae';
                $replacements[ 6] = 'c';
                $replacements[ 7] = 'ss';
                $replacements[ 8] = '-';
                $replacements[ 9] = ':';
                $replacements[10] = '_';

                return preg_replace($patterns, $replacements, $reference);
        }



$ID = cleanID(getID());
//die("ID=".$ID);
$onlyCode = $INPUT->str('onlyCode');
$insideTag = $INPUT->str('insideTag');
$title=tpl_pagetitle(null,true);
$titletext=tpl_pagetitle(null,true);


    if (empty($conf['useacl']) || auth_quickaclcheck($ID) >= AUTH_READ) {
    	$file = rawWiki($ID);
        $articleWiki = $file;

	$fileLastMod = wikiFN($ID);
        $lastMod     = @filemtime($fileLastMod); // from page
        $NS=getNS($ID); 

        // get revisions
        $filepath = str_replace(":", "/", $ID);
        // list all revisions 
        $path=DOKU_INC."data/attic/". $filepath."*";
        $files = glob($path);
      
        //print_r($files);

        $changes="data/meta/".$filepath .".changes";
        $indexed="data/meta/".$filepath .".indexed";
        $meta="data/meta/".$filepath .".meta";

        $dir_changes=DOKU_INC."data/meta/".$filepath .".changes";
        $dir_indexed=DOKU_INC."data/meta/".$filepath .".indexed";
        $dir_meta=DOKU_INC."data/meta/".$filepath .".meta";

        //echo $dir_changes;

    	//if ($onlyCode)
    	//	$file = preg_replace('/[\s\S]*<code>/m', '', preg_replace('/<\/code>[\s\S]*/m', '', $file));
    	//if ($insideTag)
        //		$file = preg_replace('/[\s\S]*<' . $insideTag . '[^>]*>/m', '', preg_replace('/<\/' . $insideTag . '>[\s\S]*/m', '', $file));

    	//print $file;
       // file_put_contents("tmp/article.txt", $file);
        

$pieces = explode(":", $ID);

$filename="article";
if (count($pieces)>1)
   $filename=texifyReference($pieces[1]);  // no spaces etc..

$filename=DOKU_INC."data/cache/".$filename . ".zwi";
$zipfilename=$filename;
// clear
unlink( $filename );

//$filename="/tmp/".$filename . ".wik";
//echo $filename;
//die("OK");

$zip = new ZipArchive;
$isZipOpen=$zip->open($filename, ZipArchive::CREATE);

if ($isZipOpen === TRUE)
{
    // Add files to the zip file
    //$zip->addFile('test.txt');
    //$zip->addFile('test.pdf');
    // Add random.txt file to zip and rename it to newfile.txt
    //$zip->addFile('random.txt', 'newfile.txt');
    // Add a file new.txt file to zip using the text specified
    $zip->addFromString('article.dokuwiki', $articleWiki);

   // XHTML for embedding
   $xx=$CURRENT_URL."/doku.php?id=".$ID."&do=export_xhtmlbody";
   $body_content = file_get_contents($xx);


   # push all revisions too
    $xr=0;
    foreach ($files as $xfile) { 
             $destination = str_replace(DOKU_INC, "", $xfile);
             //print($destination);
             $zip->addFile($xfile, $destination);
             $xr=$xr+1;
             };

    // metadata
    $zip->addFile($dir_changes, $changes);
    $zip->addFile($dir_indexed, $indexed);
    $zip->addFile($dir_meta,   $meta);


    // css 
    $css_file=DOKU_INC."/lib/plugins/zwidoku/files/common.css";
    $zip->addFile($css_file, "data/css/common.css");
    $css_file=DOKU_INC."/lib/plugins/zwidoku/files/fonts.css";
    $zip->addFile($css_file, "data/css/fonts.css");
    $css_file=DOKU_INC."/lib/plugins/zwidoku/files/doku.css";
    $zip->addFile($css_file, "data/css/doku.css");
 

    $page_title=tpl_pagetitle(null,true);
    //$page_info=tpl_pageinfo(true);

    //die("OK");

    // list used plugins for consistency
     foreach(glob(DOKU_INC."lib/plugins/*", GLOB_ONLYDIR) as $dir) {
        $usedplugins[] = basename($dir);
     }


    $zip->addFromString('plugins.json', json_encode($usedplugins));


    $DESC = new ShortDescription($articleWiki,$articleTXT);
    $description=$DESC->getDescription();

    $Lang="en";

    // remove styles
    $html_tmp=preg_replace('/(<(script|style)\b[^>]*>).*?(<\/\2>)/is', "$1$3", $body_content);
    $html_tmp=strip_tags($html_tmp, '<b>');    // remove bold, so it will not move to upper case;
    $html_tmp=strip_tags($html_tmp, '<i>'); // remove italic
    $html2TextConverter = new \Html2Text\Html2Text($html_tmp);
    $articleTXT = $html2TextConverter->getText();


    $content_array= array();
    $content_array["article.dokuwiki"]=sha1($file); //$revision->getSha1();
    $content_array["article.html"]=sha1($body_content);
    $content_array["article.txt"]=sha1($articleTXT);

    $generator="DokuWiki"; 

    // ZWI -specific metadata for the current revision
    $tt['ZWIversion'] = "1.3";
    $tt['Primary'] = "article.dokuwiki";
    $tt['Title'] = $title;
    $tt['Namespace'] = $NS;
    $tt['LastModified'] = dformat($INFO['lastmod']);
    $tt['TimeCreated'] = dformat($INFO['lastmod']);
    $tt['Location'] =  $fileLastMod;
    $tt['Revisions'] =  $xr; 
    $tt['Publisher']=$wgMzwiName;
    $tt['Content'] = $content_array; 
    $tt['GeneratorName'] = $generator;

   // short description
   // article information
   $pagemeta=pageinfo();

   // do not expose pass
   $pagemeta["userinfo"]["pass"]="";
   $tt['PageInfo'] =  $pagemeta;
   //$tt['Creator']=$pagemeta['meta'][;
   //$tt['Contributors']=$pagemeta['contributor'];
   // $mresult = array_merge($tt, $pagemeta); 
   //$mresult=$tt;

    $tt['Lang'] = $Lang;
    //$tt['Comment'] = $title->getEditNotices ();
    $tt['Rating'] = "";
    $tt['License'] = $wgMzwiLicense;
    $tt['Description']=$description;
    $tt['Author']=$author;

   // write
   $zip->addFromString('metadata.json', json_encode($tt, JSON_PRETTY_PRINT));


$toReplace = array();
$replacement = array();

$nn=0;
$doc = new DOMDocument();
@$doc->loadHTML($body_content);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
       $URL=$tag->getAttribute('src');
       //die($URL);

       $pieces = explode($NS.":", $URL);
       $img="none";
       if (count($pieces))
                     $img=$pieces[1];

       $output="data/media/".$NS."/".$img;
       //echo $output ."\n";
       $imgfile_tmp=$output;
       //die($imgfile_tmp);

       $imgfile=DOKU_INC.$output;
       //die($imgfile);

       $info = pathinfo($imgfile);
       $ext   = $info["extension"];
       if (strlen($ext)<1) continue;

       if (!file_exists($imgfile)) continue;

       //die($imgfile);

       //echo $imgfile ."\n";
       $URL = str_replace("&", "&amp;", $URL);
       //echo $URL . " -> " . $imgfile;
       //die($imgfile);

       //print($URL);

       $zip->addFile($imgfile, $output);
       array_push($toReplace,$URL);
       array_push($replacement,$imgfile_tmp);

       //$newbody_content  = str_replace($URL, $imgfile_tmp, $body_content);
       //$newhtml_content  = str_replace($URL, $imgfile_tmp, $html_content);
       //print($URL. "\n");

       $nn=$nn+1;
}


//print_r($toReplace); 
//print_r($replacement);
//die();

//$newhtml_content = str_replace($toReplace, $replacement, $html_content);
$newbody_content = str_replace($toReplace, $replacement, $body_content);

//print($newhtml_content);
//die();

/*
$lines = explode("\n", $newbody_content);
$exclude = array();
$n=0;
foreach ($lines as $line) {
    if (strpos($line, 'stylesheet') !== FALSE) {
            $exclude[] = "<link rel=\"stylesheet\" href=\"data/css/styles.css\">";
            continue; 
    }
    $exclude[] = $line;
}
$newhtml_content=implode("\n", $exclude);
*/


$start_content = file_get_contents( DOKU_INC."/lib/plugins/zwidoku/html_start" );
$end_content = file_get_contents( DOKU_INC."/lib/plugins/zwidoku/html_end" );

$html_content = $start_content . $newbody_content  . $end_content;


$zip->addFromString('article.html', $html_content);
// $zip->addFromString('article.xhtml', $newbody_content);
$zip->addFromString("article.txt", $articleTXT);


}

// All files are added, so close the zip file.
$zip->close();

/*
if (file_exists($filename)) {
     print($filename);
};
*/

/*
  if (file_exists($filename)) {
     header('Content-Type: application/zip');
     header('Content-Disposition: attachment; filename="'.basename($filename).'"');
     header('Content-Length: ' . filesize($filename));
     flush();
     readfile($filename);
     // delete file
     unlink($filename);
   }
 */


//die($ext_path);

$permissionErr = 0;
$xsub="";
if ($permissionErr ==0)
        $xsub="<input type=\"submit\" name=\"submit\" value=\"Submit to the Encyclosphere Network\" />";
else if ($permissionErr == 1)
        $xsub="<input type=\"submit\" name=\"submit\" value=\"Submission to the Encyclosphere is disabled\"  readonly=\"readonly\"  onfocus=\"this.blur();\"  disabled/> <br> (not registered user)";
else if ($permissionErr == 2)
        $xsub="<input type=\"submit\" name=\"submit\" value=\"Submission to the Encyclosphere is disabled\"   readonly=\"readonly\"   onfocus=\"this.blur();\"  disabled/> <br> (did not contribute to this article)";


$submit_script=$ext_path . "/" . "zwipush.php";


$str = <<<EOD
<!DOCTYPE html>
<html class="client-nojs" lang="en" dir="ltr">
<head>
<meta charset="UTF-8"/>
<title>ZWI submit</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes, minimum-scale=0.25, maximum-scale=5.0"/>
<link rel="stylesheet" type="text/css" href="$ext_path/css/zwimaker.css" />
</head>
<body>
<p>
</p>
<center>
<h3>Export the article '$title' ?</h3>
<p>
</p>
<form action="$submit_script" method="post">
$xsub
<br>Submit this article to the Encyclosphere Network
that can be viewed in <a href="https://encycloreader.org/">EncycloReader</a> supported by <a href='https://encyclosphere.org/about/'><img src='$ext_path/img/Encyclosphere_logo24px.png' alt="Encyclosphere" style='vertical-align:middle;margin:0;'/>KSF</a>
<p></p>
<input type="submit" name="download" value="Download to your computer" />
<br>Save this article to your computer
<p></p>
<input type="button" name="cancel" value="Cancel" onClick="window.location='$newlink';" />
<input type="hidden" id="zwititle" name="zwititle" value='$titletext'  >
<input type="hidden" id="zwifile" name="zwifile" value='$zipfilename' >
<input type="hidden" id="posturl" name="posturl" value='$wgMzwiSubmitUrl' >
<input type="hidden" id="postkey" name="postkey" value='$wgMzwiPassword'  >
<input type="hidden" id="backlink" name="backlink" value='$newlink'  >
<input type="hidden" id="extpath" name="extpath" value='$ext_path'  >
<input type="hidden" id="permission" name="permission" value='$permissionErr'  >
</form>
<center>
</body>
</html>
EOD;

    print($str);

    }
    else
    	print "Unauthorized";

?>

