xref: /plugin/siteexport/inc/functions.php (revision 3aa0ad132b323f1afef9d443f43b22322b57a827)
1<?php
2
3if(!defined('DOKU_PLUGIN')) die('meh');
4require_once(DOKU_PLUGIN.'siteexport/inc/settings.php');
5require_once(DOKU_PLUGIN.'siteexport/inc/debug.php');
6
7class siteexport_functions extends DokuWiki_Plugin
8{
9    public $debug = null;
10    public $settings = null;
11
12    public function siteexport_functions($init=true, $isAJAX=false)
13    {
14        if ( $init )
15        {
16            $this->debug = new siteexport_debug();
17            $this->debug->isAJAX = $isAJAX;
18
19            $this->settings = new settings_plugin_siteexport_settings($this);
20            $this->debug->message("Settings completed: zipFile", $this->settings->zipFile, 1);
21        }
22    }
23
24    public function getPluginName()
25    {
26        return 'siteexport';
27    }
28
29    public function downloadURL()
30    {
31        $params = array('cache' => 'nocache', 'siteexport' => $this->settings->pattern);
32
33        if ( $this->debug->debugLevel() < 5 ) {
34            // If debug, then debug!
35            $params['debug'] = $this->debug->debugLevel();
36        }
37
38        return ml($this->settings->origZipFile, $params, true, '&');
39    }
40
41    public function checkIfCacheFileExistsForFileWithPattern($file, $pattern)
42    {
43        if ( !@file_exists($file) )
44        {
45            // If the cache File does not exist, move the newly created one over ...
46            $this->debug->message("'{$file}' does not exist. Checking original ZipFile", null, 3 );
47            $newCacheFile = mediaFN($this->getSpecialExportFileName($this->settings->origZipFile, $pattern));
48
49            if ( !@file_exists($newCacheFile) )
50            {
51                $this->debug->message("The export must have gone wrong. The cached file does not exist.", array("pattern" => $pattern, "original File" => $this->settings->origZipFile, "expected cached file" => $newCacheFile), 3);
52            }
53
54            $status = io_rename($newCacheFile, $file);
55            $this->debug->message("had to move another original file over. Did it work? " . ($status ? 'Yes, it did.' : 'No, it did not.'), null, 2 );
56        } else {
57            $this->debug->message("The file does exist!", $file, 2 );
58        }
59    }
60
61
62    /**
63     * Returns an utf8 encoded Namespace for a Page and input Namespace
64     * @param $NS
65     * @param $PAGE
66     */
67    function getNamespaceFromID($NS, &$PAGE) {
68        global $conf;
69        // Check current page - if its an NS add the startpage
70        $clean = true;
71        resolve_pageid(getNS($NS), $NS, $clean);
72        $NSa = explode(':', $NS);
73        if ( ! page_exists($NS) && array_pop($NSa) != strtolower($conf['start'] )) { // Compare to lowercase since clean lowers it.
74            $NS .= ':' . $conf['start'];
75            resolve_pageid(getNS($NS), $NS, $clean);
76        }
77
78        $PAGE = noNS($NS);
79        $NS = getNS($NS);
80
81        return utf8_encodeFN(str_replace(':', '/', $NS));
82    }
83
84    /**
85     * create a file name for the page
86     **/
87    public function getSiteName($ID, $overrideRewrite=false) {
88        global $conf;
89
90        if ( empty($ID) ) return false;
91
92        // Remove extensions
93        if ( $overrideRewrite ) {
94            $ID = preg_replace("#\.[^\.]+$#", '', $ID);
95        }
96
97        $url = $this->wl($this->cleanID($ID), null, true, null, null, $overrideRewrite); // this must be done with rewriting set to override
98        //$url = $this->wl($this->cleanID($ID), null, true); // this must be done with rewriting set to override
99        $uri = @parse_url($url);
100        if ( $uri['path'][0] == '/' ) {
101            $uri['path'] = substr($uri['path'], 1);
102        }
103
104        return $this->shortenName($uri['path'] . '.' . $this->settings->fileType);
105    }
106
107    /**
108     * get the Title for the page
109     **/
110    public function getSiteTitle($ID) {
111        if (useHeading('content') && $ID) {
112            $heading = p_get_first_heading($ID,true);
113            if ($heading) {
114                return $this->xmlEntities($heading);
115            }
116        }
117        return ucwords($this->xmlEntities(array_pop(explode(':', $ID))));
118    }
119
120    /**
121     * Encoding ()taken from DW - but without needing the renderer
122     **/
123    public function xmlEntities($string) {
124        return htmlspecialchars($string,ENT_QUOTES,'UTF-8');
125    }
126
127    /**
128     * Create name for the file inside the zip and the replacements
129     **/
130    function shortenName($NAME)
131    {
132        $NS = $this->settings->exportNamespace;
133        $NAME = preg_replace("%^" . DOKU_BASE . "%", "", $NAME);
134        $NAME = preg_replace("%^(_media/)?(" . $NS . "/)?%", "", $NAME);
135
136        $this->debug->message("Shortening file to '$NAME'", null, 1);
137        return $NAME;
138    }
139
140    /**
141     * Remove unwanted chars from ID
142     *
143     * Cleans a given ID to only use allowed characters. Accented characters are
144     * converted to unaccented ones
145     *
146     * @author Andreas Gohr <andi@splitbrain.org>
147     * @param  string  $raw_id    The pageid to clean
148     * @param  boolean $ascii     Force ASCII
149     * @param  boolean $media     Allow leading or trailing _ for media files
150     */
151    function cleanID($raw_id,$ascii=false,$media=false){
152        global $conf;
153        global $lang;
154        static $sepcharpat = null;
155
156        global $cache_cleanid;
157        $cache = & $cache_cleanid;
158
159        // check if it's already in the memory cache
160        if (isset($cache[(string)$raw_id])) {
161            return $cache[(string)$raw_id];
162        }
163
164        $sepchar = $conf['sepchar'];
165        if($sepcharpat == null) // build string only once to save clock cycles
166        $sepcharpat = '#\\'.$sepchar.'+#';
167
168        $id = trim((string)$raw_id);
169        //        $id = utf8_strtolower($id); // NO LowerCase for us!
170
171        //alternative namespace seperator
172        $id = strtr($id,';',':');
173        if($conf['useslash']){
174            $id = strtr($id,'/',':');
175        }else{
176            $id = strtr($id,'/',$sepchar);
177        }
178
179        if($conf['deaccent'] == 2 || $ascii) $id = utf8_romanize($id);
180        if($conf['deaccent'] || $ascii) $id = utf8_deaccent($id,-1);
181
182        // We want spaces to be preserved when they are in the link.
183        global $UTF8_SPECIAL_CHARS2;
184        $UTF8_SPECIAL_CHARS2_SAVE = (string)$UTF8_SPECIAL_CHARS2;
185        $UTF8_SPECIAL_CHARS2 = str_replace(' ', '', $UTF8_SPECIAL_CHARS2);
186
187        //remove specials
188        $id = utf8_stripspecials($id,$sepchar,'\*');
189        $UTF8_SPECIAL_CHARS2 = $UTF8_SPECIAL_CHARS2_SAVE;
190
191        if($ascii) $id = utf8_strip($id);
192
193        //clean up
194        $id = preg_replace($sepcharpat,$sepchar,$id);
195        $id = preg_replace('#:+#',':',$id);
196        $id = ($media ? trim($id,':.-') : trim($id,':._-'));
197        $id = preg_replace('#:[:\._\-]+#',':',$id);
198
199        $cache[(string)$raw_id] = $id;
200        return($id);
201    }
202
203
204    /**
205     * This builds a link to a wikipage - changed for internal use here
206     *
207     * It handles URL rewriting and adds additional parameter if
208     * given in $more
209     *
210     * @author Andreas Gohr <andi@splitbrain.org>
211     */
212
213    function wl($id='',$more='',$abs=false,$sep='&amp;', $IDexists=true, $overrideRewrite=false, $hadBase=false){
214        global $conf;
215
216        $this->debug->message("Starting to build WL-URL for '$id'", $more, 1);
217
218        if(is_array($more)){
219
220        	$intermediateMore = '';
221        	foreach( $more as $key => $value) {
222
223        		if ( strlen($intermediateMore) > 0 ) {
224	        		$intermediateMore .= $sep;
225        		}
226
227	        	if ( !is_array($value) ) {
228		        	$intermediateMore .= rawurlencode($key) . '=';
229		        	$intermediateMore .= rawurlencode($value);
230		        	continue;
231	        	}
232
233	        	foreach( $value as $val ) {
234	        		if ( strlen($intermediateMore) > 0 ) {
235		        		$intermediateMore .= $sep;
236	        		}
237
238		        	$intermediateMore .= rawurlencode($key) . '[]=';
239		        	$intermediateMore .= rawurlencode($val);
240	        	}
241        	}
242
243            $more = $intermediateMore;
244        }else{
245            $more = str_replace(',',$sep,$more);
246        }
247
248        $id = idfilter($id);
249
250        if($abs){
251            $xlink = DOKU_URL;
252            if ( !$IDexists && !$hadBase ) { // If the file does not exist, we have to remove the base. This link my be one to an parallel BASE.
253                $xlink = preg_replace('#' . DOKU_BASE . '$#', '', $xlink);
254            }
255        }else if ($IDexists || $hadBase) { // if the ID does exist, we may add the base.
256            $xlink = DOKU_BASE;
257        } else{
258            $xlink = "";
259        }
260
261        // $this->debug->message("internal WL function Before Replacing: '$xlink'", array(DOKU_REL, DOKU_URL, DOKU_BASE, $xlink), 2);
262        $xlink = preg_replace('#(?<!http:|https:)//+#','/', ($abs ? '' : '/') . "$xlink/"); // ensure slashes at beginning and ending, but strip doubles
263        $this->debug->message("'$xlink'", array(DOKU_REL, DOKU_URL, DOKU_BASE, $xlink), 2);
264
265        if ( $overrideRewrite ) {
266            $this->debug->message("Override enabled.", null, 1);
267            $id = strtr($id,':','/');
268
269            $xlink .= $id;
270            if($more) $xlink .= '?'.$more;
271        } else {
272            if($conf['userewrite'] == 2 ){
273                $xlink .= DOKU_SCRIPT.'/'.$id;
274                if($more) $xlink .= '?'.$more;
275            }elseif($conf['userewrite'] ){
276                $xlink .= $id;
277                if($more) $xlink .= '?'.$more;
278            }elseif($id){
279                $xlink .= DOKU_SCRIPT.'?id='.$id;
280                if($more) $xlink .= $sep.$more;
281            }else{
282                $xlink .= DOKU_SCRIPT;
283                if($more) $xlink .= '?'.$more;
284            }
285        }
286
287        $this->debug->message("internal WL function result: '$xlink'", null, 2);
288
289        return $xlink;
290    }
291
292    /**
293     * Create the export file name - this is the file where everything is being stored
294     * @param $FILE
295     * @param $PATTERN - additional pattern for re-using old files
296     */
297    public function getSpecialExportFileName($FILE, $PATTERN=null) {
298
299        if ( empty($FILE) )
300        {
301            $FILE = $this->settings->origZipFile;
302        }
303
304        if ( empty($PATTERN) && empty($this->settings->pattern) ){
305            $this->debug->message("Generating an internal md5 pattern. This will go wrong - and won't cache properly.", null, 3);
306            $PATTERN = md5(microtime(false));
307        }
308
309        // Set Pattern Global for other stuff
310        if ( empty($this->settings->pattern) ) {
311            $this->settings['pattern'] = $PATTERN;
312        } else {
313            $PATTERN = $this->settings->pattern;
314        }
315
316        $FA = explode('.', $FILE);
317        $EXT = array_pop($FA);
318        array_push($FA, 'auto');
319        array_push($FA, $PATTERN);
320        array_push($FA, $EXT);
321
322        $fileName = implode('.', $FA);
323        $this->debug->message("Export Filename for '$FILE' will be: '$fileName'", null, 2);
324        return $fileName;
325    }
326
327    public function getCacheFileNameForPattern($PATTERN = null)
328    {
329        if ( $PATTERN == null ) {
330            $PATTERN = $this->settings->pattern;
331        }
332
333        return getCacheName($this->getSpecialExportFileName($this->settings->origZipFile, $PATTERN), '.' . basename(mediaFN($this->settings->origZipFile)) );
334    }
335
336    function startRedirctProcess($counter) {
337        global $ID;
338
339        $URL = wl($ID);
340
341        $additionalParameters = $_REQUEST;
342        $additionalParameters['startcounter'] = $counter;
343        $additionalParameters['pattern'] = $this->settings->pattern;
344
345        unset($additionalParameters['id']);
346        unset($additionalParameters['u']);
347        unset($additionalParameters['p']);
348        unset($additionalParameters['r']);
349        unset($additionalParameters['http_credentials']);
350
351        $this->addAdditionalParametersToURL($URL, $additionalParameters);
352        $this->debug->message("Redirecting to '$URL'", null, 2);
353
354        send_redirect($URL);
355        exit(0); // Should not be reached, but anyways
356    }
357
358    /**
359     * Builds additional Parameters into the URL given
360     * @param $URL
361     * @param $newAdditionalParameters
362     */
363    function addAdditionalParametersToURL(&$URL, $newAdditionalParameters) {
364
365        // Add additionalParameters
366        if ( !empty($newAdditionalParameters) ) {
367            foreach($newAdditionalParameters as $key => $value ) {
368                if ( empty($key) || empty($value) ) { continue; }
369
370                $append = '';
371
372                if ( is_array($value) ) {
373                    foreach( array_values($value) as $aValue ) { // Array Handling
374                        $URL .= (strstr($URL, '?') ? '&' : '?') . $key . "[]=$aValue";
375                    }
376                } else {
377                    $append = "$key=$value";
378                    $URL .= empty($append) || strstr($URL, $append)  ? '' : (strstr($URL, '?') ? '&' : '?') . $append;
379                }
380
381            }
382        }
383    }
384
385    /**
386     * Cleans the wiki variables and returns a rebuild URL that has the new variables at hand
387     * @param $data
388     */
389    function prepare_POSTData($data)
390    {
391        $NS = !empty($data['ns']) ? $data['ns'] : $data['id'];
392
393        $this->removeWikiVariables($data);
394        $data['do'] = 'siteexport';
395        $additionalKeys = '';
396
397        ksort($data);
398
399        $this->debug->message("Prepared POST data:", $data, 1);
400
401        foreach( $data as $key => $value ) {
402
403            if ( !is_array($value) ) { continue; }
404            $this->debug->message("Found inner Array:", $value, 1);
405
406            asort($value);
407            foreach ( $value as $innerKey => $aValue )
408            {
409                if ( is_numeric($innerKey))
410                {
411                    $innerKey = '';
412                }
413
414                $additionalKeys .= "&$key" . "[$innerKey]=$aValue";
415            }
416
417            unset($data[$key]);
418        }
419
420        return wl($NS, $data, true, '&') . $additionalKeys;
421    }
422
423    /**
424     * Parses a String into a $_REQUEST Like variant. You have to tell if a decode of the values is needed
425     * @param $inputArray
426     * @param $decode
427     */
428    public function parseStringToRequestArray($inputArray, $decode=false)
429    {
430        global $plugin_controller;
431
432        $outputArray = $inputArray;
433        if ( !is_array($inputArray) )
434        {
435            $intermediate = str_replace("&amp;", "&", $inputArray);
436
437            $outputArray = array();
438            foreach( explode("&", $intermediate) as $param ) {
439                list($key, $value) = explode("=", $param, 2);
440
441                // This is needed if we do want to calculate $_REQUEST for a non HTTP-Request
442                if ( $decode)
443                {
444                    $value = urldecode($value);
445                }
446
447                if ( empty($key) ) { continue; } // Don't check on Value, because there may be only the key that should be preserved
448
449                if ( substr($key, -2) == '[]' ) {
450	                $key = substr($key, 0, -2);
451	                if ( !is_array($outputArray[$key]) ) {
452		                $outputArray[$key] = array();
453	                }
454
455                    array_push($outputArray[$key], $value); // Array Handling
456                } else {
457                    $outputArray[$key] = $value;
458                }
459            }
460        }
461
462        if ( !empty($outputArray['diPlu']) ) {
463
464            $allPlugins = array();
465            foreach($plugin_controller->getList(null,true) as $plugin ) {
466                // check for CSS or JS
467                if ( !file_exists(DOKU_PLUGIN."$plugin/script.js") && !file_exists(DOKU_PLUGIN."$p/style.css") ) { continue; }
468                $allPlugins[] = $plugin;
469            }
470
471            if ( count($outputArray['diPlu']) > (count($allPlugins) / 2) ) {
472                $outputArray['diInv'] = 1;
473                $outputArray['diPlu'] = array_diff($allPlugins, $outputArray['diPlu']);
474            }
475        }
476
477        return $outputArray;
478    }
479
480    /**
481     * Remove certain fields from the list.
482     * @param $removeArray
483     * @param $advanced
484     * @param $isString
485     */
486    function removeWikiVariables(&$removeArray, $advanced=false, $isString=false) {
487
488        $removeArray = $this->parseStringToRequestArray($removeArray);
489
490        // 2010-08-23 - If there is still the media set, retain the id for e.g. detail.php
491        if ( !isset($removeArray['media']) ) {
492            unset($removeArray['id']);
493        }
494
495        unset($removeArray['do']);
496        unset($removeArray['ns']);
497        unset($removeArray['call']);
498        unset($removeArray['sectok']);
499        unset($removeArray['rndval']);
500        unset($removeArray['tseed']);
501        unset($removeArray['http_credentials']);
502        unset($removeArray['u']);
503        unset($removeArray['p']);
504        unset($removeArray['r']);
505        unset($removeArray['base']);
506        unset($removeArray['siteexport']);
507        unset($removeArray['DokuWiki']);
508        unset($removeArray['cronOverwriteExisting']);
509
510        if ( $removeArray['renderer'] == 'xhtml' ) {
511            $removeArray['do'] = 'export_' . $removeArray['renderer'];
512            unset($removeArray['renderer']);
513        }
514
515        // Keep custom options
516        if ( is_array($removeArray['customoptionname']) && is_array($removeArray['customoptionvalue']) && count($removeArray['customoptionname']) == count($removeArray['customoptionvalue']) )
517        {
518            for( $index=0; $index<count($removeArray['customoptionname']); $index++)
519            {
520                $removeArray[$removeArray['customoptionname'][$index]] = $removeArray['customoptionvalue'][$index];
521            }
522	        unset($removeArray['customoptionname']);
523	        unset($removeArray['customoptionvalue']);
524        }
525
526        if ( $advanced ) {
527            if ( $removeArray['renderer'] != 'xhtml' && !empty($removeArray['renderer']) ) {
528                $removeArray['do'] = 'export_' . $removeArray['renderer'];
529            }
530
531            // 2010-08-25 - Need fakeMedia for some _detail cases with rewrite = 2
532            if ( isset($removeArray['fakeMedia'])  ) {
533                unset($removeArray['media']);
534                unset($removeArray['fakeMedia']);
535            }
536
537            /* remove internal params */
538            unset($removeArray['ens']);
539            unset($removeArray['renderer']);
540            unset($removeArray['site']);
541            unset($removeArray['namespace']);
542            unset($removeArray['exportbody']);
543            unset($removeArray['addParams']);
544            unset($removeArray['template']);
545            unset($removeArray['eclipseDocZip']);
546            unset($removeArray['useTocFile']);
547            unset($removeArray['JavaHelpDocZip']);
548            unset($removeArray['depth']);
549            unset($removeArray['depthType']);
550            unset($removeArray['startcounter']);
551            unset($removeArray['pattern']);
552            unset($removeArray['TOCMapWithoutTranslation']);
553			// unset($removeArray['disableCache']);
554			unset($removeArray['debug']);
555        }
556
557        if ( $isString && is_array($removeArray) ) {
558            $intermediate = $removeArray;
559            $removeArray = array();
560
561            foreach ( $intermediate as $key => $value ) {
562                if ( is_array($value) ) {
563                    foreach( array_values($value) as $aValue ) { // Array Handling
564                        $removeArray[] = $key . "[]=$aValue";
565                    }
566                } else {
567                    $value = trim($value);
568
569                    $removeArray[] = "$key" . ( ((empty($value) && intval($value) !== 0)) || $value == '' ? '' : "=$value" ); // If the Value is empty, the Key must be preserved
570                }
571            }
572
573            //$removeArray = implode( ($this->settings->fileType == 'pdf' ? "&" : "&amp;"), $removeArray);
574            $removeArray = implode( "&", $removeArray); // The &amp; made problems with the HTTPClient / Apache. It should not be a problem to have &
575        }
576    }
577
578    /**
579     * returns a hashed name for the parameters
580     * @param $parameters
581     */
582    public function cronJobNameForParameters($parameters)
583    {
584        return md5($parameters);
585    }
586
587    /**
588     * Takes an URL and transforms it into the path+query part
589     * Used several times, e.g. for genering the hash for the cache file
590     * @param $url
591     */
592    public function urlToPathAndParams($url)
593    {
594        $query = parse_url($url, PHP_URL_QUERY);
595        $path = preg_replace(":^".DOKU_REL.":", "", parse_url($url, PHP_URL_PATH));
596        return "{$path}?{$query}";
597    }
598
599    /**
600     * Transforms an $_REQUEST into a Hash that can be used for cron and cache file
601     * @param $request
602     */
603    public function requestParametersToCacheHash($request)
604    {
605        $params = $this->urlToPathAndParams($this->prepare_POSTData($request));
606        $this->debug->message("Calculated the following Cache Hash URL: ", $params, 2);
607        return $this->cronJobNameForParameters($params);
608    }
609
610    /**
611     * Check a replaceURL against a baseURL - and make the replaceURL relative against it
612     * @param replaceURL - URL which will be made relative if needed
613     * @param baseURL - URL which is the reference to be made relative against
614     */
615    public function getRelativeURL($replaceURL, $baseURL)
616    {
617        // Base is always absolute without anything at the beginning
618        if ( preg_match("#^(\.\./)+#", $baseURL) ) {
619            $this->debug->message("The baseURL was not absolute.", $baseURL, 1);
620            return $replaceURL;
621        }
622
623        $origReplaceURL = $replaceURL;
624        $replaceURL = preg_replace("#^(\.\./)+#", '', $replaceURL);
625
626        // Remove ../ at beginning to get the absolute path
627        if ( $replaceURL == $origReplaceURL ) {
628            $this->debug->message("The replaceURL was already absolute.", $replaceURL, 1);
629            return $replaceURL;
630        }
631
632        $replaceParts = explode('/', $replaceURL);
633        $fileName = array_pop($replaceParts); // Get file
634
635        $baseParts = explode('/', $baseURL);
636        array_pop($baseParts); // Remove file. We only need the path to this location.
637
638        $this->debug->message("State before kicking.", array($replaceParts, $baseParts), 1);
639
640        // Kick all ../
641        while( count($replaceParts) > 0 && count($baseParts) > 0 ) {
642
643            if ( $baseParts[0] == $replaceParts[0] ) {
644                // Beginning is OK, so remove it.
645                array_shift($replaceParts);
646                array_shift($baseParts);
647            } else {
648                break;
649            }
650
651        }
652
653        $this->debug->message("Found URL '{$replaceURL}' that is relative to current page '{$baseURL}'.", array($replaceParts, $baseParts), 1);
654
655        // Remove everything that is identical
656        $replaceParts[] = $fileName;
657
658        return str_repeat('../', count($baseParts)) . implode('/', $replaceParts);
659    }
660}
661
662?>