xref: /plugin/zwidoku/getEncyc.php (revision f82bbc904bd835fc66a3f52ffaef251433904ec2)
1<?php
2/**
3 * ZWIdoku Plugin: Get the article.
4 *
5 * @license  LGPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author   S.Chekanov
7 * @based_on "pageindex" plugin by Kite <Kite@puzzlers.org>
8 * @based_on "externallink" plugin by Otto Vainio <plugins@valjakko.net>
9 * @based_on "pagelist" plugin by Esther Brunner <wikidesign@gmail.com>
10 *
11 */
12
13
14if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../../').'/');
15if(!defined('DOKU_LIB')) define('DOKU_LIB',realpath(dirname(__FILE__).'/../../').'/');
16if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_LIB.'plugins/');
17//define('DOKU_MAIN',realpath(dirname(__FILE__).'/../../../').'/');
18
19// must be run within Dokuwiki
20if(!defined('DOKU_INC')) die("Cannot find installed DokuWiki");
21
22
23$wgMzwiName="enhub";
24# action tab to make "Export to ZWI"
25$wgMzwiTab=true;
26# Submission webpage to Encyclosphere
27# Set to 0 to trigger download and nothing more
28# Set to 1 to create ZWI in extension/ZWIMaker/tmp and do not do anything
29# Set to 2 to create ZWI in extension/ZWIMaker/tmp and submit to the Encyclosphre
30$wgMzwiSubmit=1;
31#
32# if false, then anybody after login can send ZWI file to Encyclosphere
33# if true, then only authors or contributors can send the article to Encyclosphere
34$wgMzwiAuthorApprove=false;
35#
36# Password for the submission
37$wgMzwiPassword='wfA7NKt1W2';
38#
39# Encyclosphere submission URL if select 1
40$wgMzwiSubmitUrl="https://encycloreader.org/upload/";
41
42# what about the license?
43$wgMzwiLicense='CC BY-SA 3.0';
44
45//echo DOKU_INC;
46//die();
47
48//require_once(DOKU_INC.'/inc/pageutils.php');
49require_once(DOKU_INC.'/inc/init.php');
50require_once(DOKU_INC.'/inc/template.php');
51
52$CURRENT_URL="https://enhub.org/dokuwiki/";
53
54$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
55$newlink = str_replace("lib/plugins/zwidoku/getEncyc.php?id=", "doku.php?id=", "$actual_link");
56
57$tmp=explode("getEncyc.php", $actual_link);
58$ext_path = trim( $tmp[0] );
59
60
61require("Html2Text.php");
62require("ShortDescription.php");
63
64
65       function texifyReference($reference) {
66                $patterns[ 0] = '/[áâ�| åä]/ui';
67                $patterns[ 1] = '/[ðéêèë]/ui';
68                $patterns[ 2] = '/[íîìï]/ui';
69                $patterns[ 3] = '/[óôòøõö]/ui';
70                $patterns[ 4] = '/[úûùü]/ui';
71                $patterns[ 5] = '/æ/ui';
72                $patterns[ 6] = '/ç/ui';
73                $patterns[ 7] = '/�~_/ui';
74                $patterns[ 8] = '/\\s/';
75                $patterns[ 9] = '/#/';
76                $patterns[10] = '/[^A-Za-z0-9\\-:]/';
77                $replacements[ 0] = 'a';
78                $replacements[ 1] = 'e';
79                $replacements[ 2] = 'i';
80                $replacements[ 3] = 'o';
81                $replacements[ 4] = 'u';
82                $replacements[ 5] = 'ae';
83                $replacements[ 6] = 'c';
84                $replacements[ 7] = 'ss';
85                $replacements[ 8] = '-';
86                $replacements[ 9] = ':';
87                $replacements[10] = '_';
88
89                return preg_replace($patterns, $replacements, $reference);
90        }
91
92
93
94$ID = cleanID(getID());
95//die("ID=".$ID);
96$onlyCode = $INPUT->str('onlyCode');
97$insideTag = $INPUT->str('insideTag');
98$title=tpl_pagetitle(null,true);
99$titletext=tpl_pagetitle(null,true);
100
101
102    if (empty($conf['useacl']) || auth_quickaclcheck($ID) >= AUTH_READ) {
103    	$file = rawWiki($ID);
104        $articleWiki = $file;
105
106	$fileLastMod = wikiFN($ID);
107        $lastMod     = @filemtime($fileLastMod); // from page
108        $NS=getNS($ID);
109
110        // get revisions
111        $filepath = str_replace(":", "/", $ID);
112        // list all revisions
113        $path=DOKU_INC."data/attic/". $filepath."*";
114        $files = glob($path);
115
116        //print_r($files);
117
118        $changes="data/meta/".$filepath .".changes";
119        $indexed="data/meta/".$filepath .".indexed";
120        $meta="data/meta/".$filepath .".meta";
121
122        $dir_changes=DOKU_INC."data/meta/".$filepath .".changes";
123        $dir_indexed=DOKU_INC."data/meta/".$filepath .".indexed";
124        $dir_meta=DOKU_INC."data/meta/".$filepath .".meta";
125
126        //echo $dir_changes;
127
128    	//if ($onlyCode)
129    	//	$file = preg_replace('/[\s\S]*<code>/m', '', preg_replace('/<\/code>[\s\S]*/m', '', $file));
130    	//if ($insideTag)
131        //		$file = preg_replace('/[\s\S]*<' . $insideTag . '[^>]*>/m', '', preg_replace('/<\/' . $insideTag . '>[\s\S]*/m', '', $file));
132
133    	//print $file;
134       // file_put_contents("tmp/article.txt", $file);
135
136
137$pieces = explode(":", $ID);
138
139$filename="article";
140if (count($pieces)>1)
141   $filename=texifyReference($pieces[1]);  // no spaces etc..
142
143$filename=DOKU_INC."data/cache/".$filename . ".zwi";
144$zipfilename=$filename;
145// clear
146unlink( $filename );
147
148//$filename="/tmp/".$filename . ".wik";
149//echo $filename;
150//die("OK");
151
152$zip = new ZipArchive;
153$isZipOpen=$zip->open($filename, ZipArchive::CREATE);
154
155if ($isZipOpen === TRUE)
156{
157    // Add files to the zip file
158    //$zip->addFile('test.txt');
159    //$zip->addFile('test.pdf');
160    // Add random.txt file to zip and rename it to newfile.txt
161    //$zip->addFile('random.txt', 'newfile.txt');
162    // Add a file new.txt file to zip using the text specified
163    $zip->addFromString('article.dokuwiki', $articleWiki);
164
165   // XHTML for embedding
166   $xx=$CURRENT_URL."/doku.php?id=".$ID."&do=export_xhtmlbody";
167   $body_content = file_get_contents($xx);
168
169
170   # push all revisions too
171    $xr=0;
172    foreach ($files as $xfile) {
173             $destination = str_replace(DOKU_INC, "", $xfile);
174             //print($destination);
175             $zip->addFile($xfile, $destination);
176             $xr=$xr+1;
177             };
178
179    // metadata
180    $zip->addFile($dir_changes, $changes);
181    $zip->addFile($dir_indexed, $indexed);
182    $zip->addFile($dir_meta,   $meta);
183
184
185    // css
186    $css_file=DOKU_INC."/lib/plugins/zwidoku/files/common.css";
187    $zip->addFile($css_file, "data/css/common.css");
188    $css_file=DOKU_INC."/lib/plugins/zwidoku/files/fonts.css";
189    $zip->addFile($css_file, "data/css/fonts.css");
190    $css_file=DOKU_INC."/lib/plugins/zwidoku/files/doku.css";
191    $zip->addFile($css_file, "data/css/doku.css");
192
193
194    $page_title=tpl_pagetitle(null,true);
195    //$page_info=tpl_pageinfo(true);
196
197    //die("OK");
198
199    // list used plugins for consistency
200     foreach(glob(DOKU_INC."lib/plugins/*", GLOB_ONLYDIR) as $dir) {
201        $usedplugins[] = basename($dir);
202     }
203
204
205    $zip->addFromString('plugins.json', json_encode($usedplugins));
206
207
208    $DESC = new ShortDescription($articleWiki,$articleTXT);
209    $description=$DESC->getDescription();
210
211    $Lang="en";
212
213    // remove styles
214    $html_tmp=preg_replace('/(<(script|style)\b[^>]*>).*?(<\/\2>)/is', "$1$3", $body_content);
215    $html_tmp=strip_tags($html_tmp, '<b>');    // remove bold, so it will not move to upper case;
216    $html_tmp=strip_tags($html_tmp, '<i>'); // remove italic
217    $html2TextConverter = new \Html2Text\Html2Text($html_tmp);
218    $articleTXT = $html2TextConverter->getText();
219
220
221    $content_array= array();
222    $content_array["article.dokuwiki"]=sha1($file); //$revision->getSha1();
223    $content_array["article.html"]=sha1($body_content);
224    $content_array["article.txt"]=sha1($articleTXT);
225
226    $generator="DokuWiki";
227
228    // ZWI -specific metadata for the current revision
229    $tt['ZWIversion'] = "1.3";
230    $tt['Primary'] = "article.dokuwiki";
231    $tt['Title'] = $title;
232    $tt['Namespace'] = $NS;
233    $tt['LastModified'] = dformat($INFO['lastmod']);
234    $tt['TimeCreated'] = dformat($INFO['lastmod']);
235    $tt['Location'] =  $fileLastMod;
236    $tt['Revisions'] =  $xr;
237    $tt['Publisher']=$wgMzwiName;
238    $tt['Content'] = $content_array;
239    $tt['GeneratorName'] = $generator;
240
241   // short description
242   // article information
243   $pagemeta=pageinfo();
244
245   // do not expose pass
246   $pagemeta["userinfo"]["pass"]="";
247   $tt['PageInfo'] =  $pagemeta;
248   //$tt['Creator']=$pagemeta['meta'][;
249   //$tt['Contributors']=$pagemeta['contributor'];
250   // $mresult = array_merge($tt, $pagemeta);
251   //$mresult=$tt;
252
253    $tt['Lang'] = $Lang;
254    //$tt['Comment'] = $title->getEditNotices ();
255    $tt['Rating'] = "";
256    $tt['License'] = $wgMzwiLicense;
257    $tt['Description']=$description;
258    $tt['Author']=$author;
259
260   // write
261   $zip->addFromString('metadata.json', json_encode($tt, JSON_PRETTY_PRINT));
262
263
264$toReplace = array();
265$replacement = array();
266
267$nn=0;
268$doc = new DOMDocument();
269@$doc->loadHTML($body_content);
270$tags = $doc->getElementsByTagName('img');
271foreach ($tags as $tag) {
272       $URL=$tag->getAttribute('src');
273       //die($URL);
274
275       $pieces = explode($NS.":", $URL);
276       $img="none";
277       if (count($pieces))
278                     $img=$pieces[1];
279
280       $output="data/media/".$NS."/".$img;
281       //echo $output ."\n";
282       $imgfile_tmp=$output;
283       //die($imgfile_tmp);
284
285       $imgfile=DOKU_INC.$output;
286       //die($imgfile);
287
288       $info = pathinfo($imgfile);
289       $ext   = $info["extension"];
290       if (strlen($ext)<1) continue;
291
292       if (!file_exists($imgfile)) continue;
293
294       //die($imgfile);
295
296       //echo $imgfile ."\n";
297       $URL = str_replace("&", "&amp;", $URL);
298       //echo $URL . " -> " . $imgfile;
299       //die($imgfile);
300
301       //print($URL);
302
303       $zip->addFile($imgfile, $output);
304       array_push($toReplace,$URL);
305       array_push($replacement,$imgfile_tmp);
306
307       //$newbody_content  = str_replace($URL, $imgfile_tmp, $body_content);
308       //$newhtml_content  = str_replace($URL, $imgfile_tmp, $html_content);
309       //print($URL. "\n");
310
311       $nn=$nn+1;
312}
313
314
315//print_r($toReplace);
316//print_r($replacement);
317//die();
318
319//$newhtml_content = str_replace($toReplace, $replacement, $html_content);
320$newbody_content = str_replace($toReplace, $replacement, $body_content);
321
322//print($newhtml_content);
323//die();
324
325/*
326$lines = explode("\n", $newbody_content);
327$exclude = array();
328$n=0;
329foreach ($lines as $line) {
330    if (strpos($line, 'stylesheet') !== FALSE) {
331            $exclude[] = "<link rel=\"stylesheet\" href=\"data/css/styles.css\">";
332            continue;
333    }
334    $exclude[] = $line;
335}
336$newhtml_content=implode("\n", $exclude);
337*/
338
339
340$start_content = file_get_contents( DOKU_INC."/lib/plugins/zwidoku/html_start" );
341$end_content = file_get_contents( DOKU_INC."/lib/plugins/zwidoku/html_end" );
342
343$html_content = $start_content . $newbody_content  . $end_content;
344
345
346$zip->addFromString('article.html', $html_content);
347// $zip->addFromString('article.xhtml', $newbody_content);
348$zip->addFromString("article.txt", $articleTXT);
349
350
351}
352
353// All files are added, so close the zip file.
354$zip->close();
355
356/*
357if (file_exists($filename)) {
358     print($filename);
359};
360*/
361
362/*
363  if (file_exists($filename)) {
364     header('Content-Type: application/zip');
365     header('Content-Disposition: attachment; filename="'.basename($filename).'"');
366     header('Content-Length: ' . filesize($filename));
367     flush();
368     readfile($filename);
369     // delete file
370     unlink($filename);
371   }
372 */
373
374
375//die($ext_path);
376
377$permissionErr = 0;
378$xsub="";
379if ($permissionErr ==0)
380        $xsub="<input type=\"submit\" name=\"submit\" value=\"Submit to the Encyclosphere Network\" />";
381else if ($permissionErr == 1)
382        $xsub="<input type=\"submit\" name=\"submit\" value=\"Submission to the Encyclosphere is disabled\"  readonly=\"readonly\"  onfocus=\"this.blur();\"  disabled/> <br> (not registered user)";
383else if ($permissionErr == 2)
384        $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)";
385
386
387$submit_script=$ext_path . "/" . "zwipush.php";
388
389
390$str = <<<EOD
391<!DOCTYPE html>
392<html class="client-nojs" lang="en" dir="ltr">
393<head>
394<meta charset="UTF-8"/>
395<title>ZWI submit</title>
396<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes, minimum-scale=0.25, maximum-scale=5.0"/>
397<link rel="stylesheet" type="text/css" href="$ext_path/css/zwimaker.css" />
398</head>
399<body>
400<p>
401</p>
402<center>
403<h3>Export the article '$title' ?</h3>
404<p>
405</p>
406<form action="$submit_script" method="post">
407$xsub
408<br>Submit this article to the Encyclosphere Network
409that 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>
410<p></p>
411<input type="submit" name="download" value="Download to your computer" />
412<br>Save this article to your computer
413<p></p>
414<input type="button" name="cancel" value="Cancel" onClick="window.location='$newlink';" />
415<input type="hidden" id="zwititle" name="zwititle" value='$titletext'  >
416<input type="hidden" id="zwifile" name="zwifile" value='$zipfilename' >
417<input type="hidden" id="posturl" name="posturl" value='$wgMzwiSubmitUrl' >
418<input type="hidden" id="postkey" name="postkey" value='$wgMzwiPassword'  >
419<input type="hidden" id="backlink" name="backlink" value='$newlink'  >
420<input type="hidden" id="extpath" name="extpath" value='$ext_path'  >
421<input type="hidden" id="permission" name="permission" value='$permissionErr'  >
422</form>
423<center>
424</body>
425</html>
426EOD;
427
428    print($str);
429
430    }
431    else
432    	print "Unauthorized";
433
434?>
435
436