<?php

/**
 * ZWIdoku Plugin: Submit the article.
 *
 * @license  LGPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author   S.Chekanov 
 * @based_on "pageindex" plugin by Kite <Kite@puzzlers.org>
 * @based_on "externallink" plugin by Otto Vainio <plugins@valjakko.net>
 * @based_on "pagelist" plugin by Esther Brunner <wikidesign@gmail.com>
 *
 */


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");


$CURRENT_URL="https://enhub.org/dokuwiki";



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

$target_dir = DOKU_INC. "/data/tmp/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

// start page
echo file_get_contents(DOKU_INC.'/lib/plugins/zwidoku/html_start');

$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {


   // Check file size
  if ($_FILES["fileToUpload"]["size"] > 10000000) {
    echo "<h3>Sorry, your file is too large (more than 10MB)</h3>";
    $uploadOk = 0;
    die();
  }


   // Check if file already exists
  if (file_exists($target_file)) {
    echo "<h3>Sorry, file already exists.</h3>";
    $uploadOk = 0;
    die();
  }

// Allow certain file formats
 if($imageFileType != "zwi" && $imageFileType != "ZWI" ) {
    echo "<h3>Sorry, only ZWI  files are allowed.</h3>";
    echo "<h3>Please return and select correct ZWI file.</h3>";
    $uploadOk = 0;
    die();
 }


// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";


     $zip = new ZipArchive;
     $zip->open( $target_file);
     $json=$zip->getFromName('metadata.json');

     $infowik=json_decode($json, TRUE); 
     $ZWIversion = $infowik['ZWIversion'];
     $Title = $infowik['Title'];
     $Namespace = $infowik['Namespace'];


     # check plugins
     $json1=$zip->getFromName('plugins.json');
     $infoplugins=json_decode( $json1, TRUE);
     // list used plugins for consistency
     foreach(glob(DOKU_INC."lib/plugins/*", GLOB_ONLYDIR) as $dir) {
        $usedplugins[] = basename($dir);
     }



     $json2=$zip->getFromName('metadata.json');
     $infopage=json_decode( $json2, TRUE);
     $Xmeta=$infopage["meta"];
     $Xtitle= $Xmeta["title"];
     $Xcreator= $Xmeta["creator"];
     echo "<center><h1>" . $Xtitle . "</h1>";
     echo "original author: " . $Xcreator . "</center></br>";
     // get article
     $article=$zip->getFromName('article.dokuwiki'); 
     //echo "Title=". $Title ."<br>";
     echo "Namespace:". $Namespace ."<br>";

     $newtitle = str_replace(":", "/", $Title) . ".txt";
     $out_file= DOKU_INC."data/pages/".$newtitle;

     $articleExist=False;
     if (file_exists($out_file)) {

           $ss="<a href='/doukuwiki/doku.php?id=".$Title."&do=revisions'> Old Revisions </a>"; 
           echo "<p style=\"color:#cc7a00;  font-weight: bold;\">"; 
           echo "Status: replacement for the existing article with the same name.</br>";
           echo "Article $Title was replaced. If this is not your intension, revert it using $ss</br>";
            echo "</p>"; 
           $articleExist=true;
     } else {
            echo "<p style=\"color:#009900;  font-weight: bold;\">";
            echo "Status: New article";
            echo "</p>";
           //echo "Fill name of the new article: ". $Title ."<br>";
     }

     echo "ZWI format version=". $ZWIversion ."<br>";
     echo "Checking compartibility of used plugins<br>";
     $compat=true;
     foreach ($usedplugins as &$value) {
              $ex=false;
              foreach ($infoplugins as &$val)
                     if ($val == $value) $ex=true;
              if ($ex == false) {
                 echo "Warning: plugin \"$value\" used for this ZWI file is missing<br>";
                 $compat=false;
              };
         }
    if ($compat) echo "All plugins used for this file are available in the system<br>";


     file_put_contents($out_file, $article);
     $xpath=str_replace(":", "/", $Title);

     $out_dir= DOKU_INC."data/tmp/".$xpath; 
     $zip->extractTo($out_dir);


     // we always copy (add) media from ZWI 
     $xm="/data/media/".$Namespace."/";
     $out_media = DOKU_INC.$xm;
     $input_media = $out_dir . $xm;

     $cmd="cp -rf $input_media $out_media";
     shell_exec("mkdir -p " . $out_meta);
     shell_exec($cmd);

     // new article. Then copy meta and history 
   if  ($articleExist==false) {     
     // if this is new article, we also copy previous revisions and meta
     $xm="/data/attic/".$Namespace."/";
     $input_attic = $out_dir . $xm;
     $out_attic = DOKU_INC.$xm; 
     $cmd="cp -rf $input_attic $out_attic";
     #echo  $cmd;
     shell_exec("mkdir -p " . $out_attic); 
     shell_exec($cmd);

    // if this is new article, we also copy metadata
     $xm="/data/meta/".$Namespace."/";
     $input_meta = $out_dir . $xm;
     $out_meta = DOKU_INC.$xm;
     $cmd="cp -rf $input_meta $out_meta";
     shell_exec("mkdir -p " . $out_meta); 
     shell_exec($cmd);

     echo "Old revisions were imported from the ZWI file.<br>";

   } //




     echo "All media files for this article were imported<br>";
     echo "<b>Done! Your article in the <a href='/dokuwiki/doku.php?id=articles'> Staged article area </a> </b>"; 







     $zip->close();


    // cleaning
    //$cmd="rm -rf $out_dir";
    //shell_exec($cmd);
 
    unlink( $target_file  );
   // reading zip file end
    } else {
        die("Sorry, there was an error uploading your file.");

    }
 }

}


echo file_get_contents(DOKU_INC.'/lib/plugins/zwidoku/html_end');

?>
