xref: /plugin/siteexport/action/ajax.php (revision 46ccacef82c2ab5e90691bbdc83c281d0dd24ab2)
1<?php
2/**
3 * Site Export Plugin
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     i-net software <tools@inetsoftware.de>
7 * @author     Gerry Weissbach <gweissbach@inetsoftware.de>
8 */
9
10// must be run within Dokuwiki
11if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../../../').'/');
12if(!defined('DOKU_PLUGIN')) {
13    // Just for sanity
14    require_once(DOKU_INC.'inc/plugin.php');
15    define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
16}
17
18require_once(DOKU_PLUGIN.'action.php');
19require_once(DOKU_INC.'/inc/search.php');
20
21require_once(DOKU_PLUGIN.'siteexport/inc/functions.php');
22require_once(DOKU_PLUGIN.'siteexport/inc/httpproxy.php');
23require_once(DOKU_PLUGIN.'siteexport/inc/filewriter.php');
24require_once(DOKU_PLUGIN.'siteexport/inc/toc.php');
25require_once(DOKU_PLUGIN.'siteexport/inc/javahelp.php');
26
27class action_plugin_siteexport_ajax extends DokuWiki_Action_Plugin
28{
29    /**
30     * New internal variables for better structure
31     */
32    private $filewriter = null;
33    public $functions = null;
34
35    // List of files that have already been checked
36    private $fileChecked = array();
37
38    // Namespace of the page to export
39    private $namespace = '';
40
41    /**
42     * Register Plugin in DW
43     **/
44    function register(&$controller) {
45        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajax_siteexport_provider');
46        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'siteexport_action');
47    }
48
49    /**
50     * AJAX Provider - check what is going to be done
51     * @param $event
52     * @param $args
53     */
54    function ajax_siteexport_provider(&$event, $args) {
55
56        // If this is not a siteexport call, ignore it.
57        if ( !strstr($event->data, '__siteexport' ) )
58        {
59            return;
60        }
61
62        $this->__init_functions(true);
63
64        switch( $event->data ) {
65            case '__siteexport_getsitelist': $this->ajax_siteexport_getsitelist( $event ); break;
66            case '__siteexport_addsite': $this->ajax_siteexport_addsite( $event ); break;
67            case '__siteexport_generateurl': $this->ajax_siteexport_generateurl( $event ); break;
68            case '__siteexport_aggregate': $this->ajax_siteexport_aggregate( $event ); break;
69        }
70    }
71
72    /**
73     * Export from a URL - action
74     * @param $event
75     */
76    function siteexport_action( &$event ) {
77        global $ID;
78
79        // Check if the 'do' was siteexport
80	    $command = is_array($event->data) ? array_shift(array_keys($event->data)) : $event->data;
81        if ( $command != 'siteexport' ) { return false; }
82		$event->data = act_clean($event->data);
83
84        if ( headers_sent() ) {
85            msg("The siteexport function has to be called prior to any header output.", -1);
86        }
87
88        $this->__init_functions();
89
90        $this->functions->debug->message("========================================", null, 1);
91        $this->functions->debug->message("Starting export from URL call", null, 1);
92        $this->functions->debug->message("----------------------------------------", null, 1);
93
94        $event->preventDefault();
95        $event->stopPropagation();
96
97        // Fake security Token if none given
98        if ( empty( $_REQUEST['sectok'] ) ) {
99            $_REQUEST['sectok'] = getSecurityToken();
100        }
101
102        // The timer will be used to do redirects if needed to prevent timeouts
103        $starttimer = time();
104        $timerdiff = $this->getConf('max_execution_time');
105
106        $data = $this->__get_siteexport_list_and_init_tocs($ID, !empty($_REQUEST['startcounter']));
107
108        if ( $data === false ) {
109            header("HTTP/1.0 401 Unauthorized");
110            print 'Unauthorized';
111            exit;
112        }
113
114        $counter = 0;
115
116        if ( count($data) == 0 && !$this->functions->settings->hasValidCacheFile ) {
117            exit();
118        }
119
120        foreach ( $data as $site ) {
121
122			if ( intval($site['exists']) == 1 || !isset($site['exists']) ) {
123
124	            // Skip over the amount of urls that have been exported already
125	            if ( empty($_REQUEST['startcounter']) || $counter >= intval($_REQUEST['startcounter']) ) {
126	                $status = $this->__siteexport_add_site($site['id']);
127
128			        if ( $status === false ) {
129				        $this->functions->debug->message("----------------------------------------", null, 1);
130				        $this->functions->debug->message("Errors during export from URL call", null, 1);
131				        $this->functions->debug->message("========================================", null, 1);
132						print $this->functions->debug->runtimeErrors;
133        			    exit(0); // We need to stop
134			        }
135	            }
136			}
137
138            $counter ++;
139            if ( time() - $starttimer >= $timerdiff ) {
140                $this->functions->debug->message("Will Redirect", null, 1);
141                $this->handleRuntimeErrorOutput();
142                $this->functions->startRedirctProcess($counter);
143            }
144        }
145
146        $this->functions->debug->message("----------------------------------------", null, 1);
147        $this->functions->debug->message("Finishing export from URL call", null, 1);
148        $this->functions->debug->message("========================================", null, 1);
149
150        $this->cleanCacheFiles();
151
152        $URL = ml($this->functions->settings->origZipFile, array('cache' => 'nocache', 'siteexport' => $this->functions->settings->pattern, 'sectok' => getSecurityToken()), true, '&');
153        $this->functions->debug->message("Redirecting to final file", $URL, 2);
154
155        $this->handleRuntimeErrorOutput();
156        send_redirect($URL);
157        exit(0); // Should not be reached, but anyways
158    }
159
160    private function handleRuntimeErrorOutput()
161    {
162        if ( !empty($this->functions->debug->runtimeErrors) )
163        {
164            $this->filewriter->__moveDataToZip($this->functions->debug->runtimeErrors, '_runtime_error/' . time() . '.html');
165        }
166    }
167
168    public function __init_functions($isAJAX=false)
169    {
170        $this->functions = new siteexport_functions(true, $isAJAX);
171        $this->filewriter = new siteexport_zipfilewriter($this->functions);
172
173        // Check for PDF Capabilities
174        if ( $this->filewriter->canDoPDF() ) {
175            $this->functions->settings->fileType = 'pdf';
176        }
177    }
178
179    /**
180     * Prepares the generated URL for direct download access
181     * Also gives back the parameters for this URL
182     * @param $event init event of the ajax request
183     */
184    function ajax_siteexport_prepareURL_and_POSTData( &$event ) {
185
186        $event->preventDefault();
187        $event->stopPropagation();
188
189        // Retrieve Information for download URL
190        $this->functions->debug->message("Prepared URL and POST from Request:", $_REQUEST, 2);
191        $url = $this->functions->prepare_POSTData($_REQUEST);
192        $combined = $this->functions->urlToPathAndParams($url);
193        list($path, $query) = explode('?', $combined, 2);
194        $return = array($url, $combined, $path, $query);
195
196        $this->functions->debug->message("Prepared URL and POST data:", $return, 2);
197        return $return;
198    }
199
200    /**
201     * Executes a Cron Job Action
202     * @param $event
203     */
204    function ajax_siteexport_cronaction( &$event )
205    {
206        $cronOverwriteExisting = intval($_REQUEST['cronOverwriteExisting']) == 1;
207        list($url, $combined) = $this->ajax_siteexport_prepareURL_and_POSTData($event);
208
209        if ( !$function =& plugin_load('cron', 'siteexport' ) )
210        {
211            $this->functions->debug->message("Tried to do an action with siteexport/cron, but the cron plugin is missing.", null, 4);
212        }
213
214        $status = null;
215        switch( $event->data ) {
216            case '__siteexport_savecron': $status = $function->saveCronDataWithParameters($combined, $cronOverwriteExisting); break;
217            case '__siteexport_deletecron': $status = $function->deleteCronDataWithParameters($combined); break;
218        }
219
220        if ( !empty($status) )
221        {
222            $this->functions->debug->message("Tried to do an action with siteexport/cron, but failed.", $status, 4);
223        }
224    }
225
226    /**
227     * generate direct access URL
228     **/
229    function ajax_siteexport_generateurl( &$event ) {
230
231        list($url, $combined, $path, $POSTData) = $this->ajax_siteexport_prepareURL_and_POSTData($event);
232
233        // WGET Redirects - this is an option for wget only.
234        // Calculate the maximum redirects that we want to allow. A Problem is that we don't know how long it will take to fetch one page
235        // Therefore we assume it takes about 5s for each page - that gives the freedom to have anough time for redirect.
236        $maxRedirectNumber = ceil( ( count($this->__get_siteexport_list($NS, true)) * 5) / $this->getConf('max_execution_time') );
237        $maxRedirect = $maxRedirectNumber > 0 ? '--max-redirect=' . ($maxRedirectNumber+3) . ' ' : '';
238        $maxRedirs = $maxRedirectNumber > 0 ? '--max-redirs ' . ($maxRedirectNumber+3) . ' ' : '';
239
240        $this->functions->debug->message("Generating Direct Download URL", $url, 2);
241
242        // If there was a Runtime Exception
243        if ( !$this->functions->debug->firstRE() ) {
244            $this->functions->debug->message("There have been errors while generating the download URLs.", null, 4);
245            return;
246        }
247
248        echo $url;
249        echo "\n";
250        echo 'wget ' . $maxRedirect . '--output-document=' . array_pop(explode(":", ($this->getConf('zipfilename')))) . ' --post-data="' . $POSTData . '" ' . wl(cleanID($path), null, true) . ' --http-user=USER --http-passwd=PASSWD';
251        echo "\n";
252        echo 'curl -L ' . $maxRedirs . '-o ' . array_pop(explode(":", ($this->getConf('zipfilename')))) . ' -d "' . $POSTData . '" ' . wl(cleanID($path), null, true) . ' --anyauth --user USER:PASSWD';
253        echo "\n";
254
255        $this->functions->debug->message("Checking for Cron parameters: ", $combined, 1);
256        if ( !$functions =& plugin_load('cron', 'siteexport' ) ||
257        !$functions->hasCronJobForParameters($combined) ) {
258            echo "false";
259        } else
260        {
261            echo "true";
262        }
263
264        return;
265    }
266
267    /**
268     * Get List of sites to be exported for AJAX (wrapper)
269     **/
270    function ajax_siteexport_getsitelist( &$event ) {
271
272        $event->preventDefault();
273        $event->stopPropagation();
274
275        $data = $this->__get_siteexport_list_and_init_tocs($_REQUEST['ns']);
276
277        // Important for reconaisance of the session
278
279        if ( $data === false )
280        {
281            $this->functions->debug->runtimeException("No data generated. List of Files is 'false'.");
282            return;
283        }
284
285        if ( empty($data) && !$this->functions->settings->hasValidCacheFile )
286        {
287            $this->functions->debug->runtimeException("Generated list is empty.");
288            return;
289        }
290
291        // If there was a Runtime Exception
292        if ( !$this->functions->debug->firstRE() )
293        {
294            $this->functions->debug->message("There have been errors while generating site list.", null, 4);
295            return;
296        }
297
298        echo "{$this->functions->settings->pattern}\n";
299        echo $this->functions->downloadURL() . "\n";
300        foreach($data as $line ){
301            echo $line['id'] . "\n";
302        }
303
304        return;
305    }
306
307    function ajax_siteexport_aggregate( &$event ) {
308
309        // Quick preparations for one page only
310        if ( $this->filewriter->hasValidCacheFile($_REQUEST, $data) ) {
311            $this->functions->debug->message("Had a valid cache file and will use it.", null, 2);
312            print $this->functions->downloadURL();
313
314            $event->preventDefault();
315            $event->stopPropagation();
316        } else {
317            // Then go for it!
318            $this->functions->debug->message("Will create a new cache thing.", null, 2);
319            $this->ajax_siteexport_addsite( $event );
320        }
321
322    }
323
324    /**
325     * Add a page to the package (for AJAX calls - Wrapper)
326     **/
327    function ajax_siteexport_addsite( &$event ) {
328
329        $event->preventDefault();
330        $event->stopPropagation();
331
332        $this->functions->debug->message("========================================", null, 1);
333        $this->functions->debug->message("Starting export from AJAX call", null, 1);
334        $this->functions->debug->message("----------------------------------------", null, 1);
335
336        $status = $this->__siteexport_add_site($_REQUEST['site']);
337        if ( $status === false ) {
338	        $this->functions->debug->message("----------------------------------------", null, 1);
339	        $this->functions->debug->message("Errors during export from AJAX call", null, 1);
340	        $this->functions->debug->message("========================================", null, 1);
341        	return;
342        }
343
344        $this->functions->debug->message("----------------------------------------", null, 1);
345        $this->functions->debug->message("Finishing export from AJAX call", null, 1);
346        $this->functions->debug->message("========================================", null, 1);
347
348        // Print the download zip-File
349        $this->cleanCacheFiles();
350
351        // If there was a Runtime Exception
352        if ( !$this->functions->debug->firstRE() ) {
353            $this->functions->debug->message("There have been errors during the export.", null, 4);
354            return;
355        }
356
357        print $this->functions->downloadURL();
358        return;
359    }
360
361    /**
362     * Fetch the list of pages to be exported
363     **/
364    function __get_siteexport_list($NS, $overrideCache=false) {
365        global $conf;
366
367        $NS = $this->namespace = $this->functions->getNamespaceFromID($NS, $PAGE);
368
369        $depth = $this->getConf('depth');
370        $query = '';
371        $doSearch = 'search_allpages';
372
373        switch( intval($_REQUEST['depthType']) ) {
374            case 0:
375                $query = $this->functions->cleanID(str_replace(":", "/", $NS.':'.$PAGE));
376                resolve_pageid($NS, $PAGE, $exists);
377
378                if ( $exists ) {
379                    $data = array( array( 'id' => $PAGE) );
380
381                    $this->functions->debug->message("Checking for Cache", null, 2);
382                    if ( !$overrideCache && $this->filewriter->hasValidCacheFile($_REQUEST, $data) )
383                    {
384                        return array();
385                    }
386
387                    return $data;
388                }
389            case 1:	$depth = 0;
390            break;
391            case 2:	$depth = intval($_REQUEST['depth']);
392            break;
393        }
394
395        $opts = array( 'depth' => $depth, 'skipacl' => $this->getConf('skipacl'), 'query' => $query);
396        $this->functions->debug->message("Options", $opts, 2);
397
398        $data = array();
399        require_once (DOKU_INC.'inc/search.php');
400
401        // Check, which TOC to take
402        if ( !$this->functions->settings->useTOCFile ) {
403            search($data, $conf['datadir'], $doSearch, $opts, $this->namespace);
404        } else {
405            $this->functions->debug->message("Using TOC for data", null, 2);
406
407            $doSearch = 'search_pagename';
408
409            // Create Data of the TOC File should be used instead
410            $opts['query'] = 'toc.txt';
411
412            $RAWdata = array();
413            search($RAWdata, $conf['datadir'], $doSearch, $opts, $this->namespace);
414
415            // There may be more than one toc and all of them have to be merged.
416            $data = array();
417            foreach( $RAWdata as $entry )
418            {
419                $tmpData = p_get_metadata($entry['id'], 'sitetoc siteexportTOC', true);
420
421                if ( is_array($tmpData) )
422                {
423                    $data = array_merge($data, $tmpData);
424                }
425            }
426        }
427
428        $this->functions->debug->message("Checking for Cache", null, 2);
429        if ( !$overrideCache && $this->filewriter->hasValidCacheFile($_REQUEST, $data) )
430        {
431            return array();
432        }
433
434        $this->functions->debug->message("Exporting the following sites: ", $data, 2);
435        return $data;
436    }
437
438    function __get_siteexport_list_and_init_tocs($NS, $isRedirected=false ) {
439
440        // Clean up if not redirected
441        if ( !$isRedirected && !$this->__removeOldZip() ) {
442            $this->functions->debug->runtimeException("Can't remove old files.");
443            return false;
444        }
445
446        $data = $this->__get_siteexport_list($NS, $isRedirected);
447        if ( $isRedirected || empty($data) )
448        {
449            // if we have been redirected, simply return the data
450            return $data;
451        }
452
453        // Create Eclipse Documentation Pages - TOC.xml, Context.xml
454        if ( !empty($_REQUEST['absolutePath']) ) $this->namespace = "";
455//        $this->__removeOldZip( $this->functions->settings->eclipseZipFile );
456
457        if ( !empty($_REQUEST['eclipseDocZip']) )
458        {
459            $toc = new siteexport_toc($this->functions);
460            $this->functions->debug->message("Generating eclipseDocZip", null, 2);
461            $this->filewriter->__moveDataToZip($toc->__getTOCXML($data), 'toc.xml');
462            $this->filewriter->__moveDataToZip($toc->__getContextXML($data), 'context.xml');
463        } else  if ( !empty($_REQUEST['JavaHelpDocZip']) )
464        {
465            $toc = new siteexport_javahelp($this->functions, $this->filewriter);
466            $toc->createTOCFiles($data);
467
468/*            $toc = new siteexport_toc($this->functions);
469            list($tocData, $mapData) = $toc->__getJavaHelpTOCXML($data);
470            $this->functions->debug->message("Generating JavaHelpDocZip", null, 2);
471            $this->filewriter->__moveDataToZip($tocData, 'toc.xml');
472            $this->filewriter->__moveDataToZip($mapData, 'map.xml');
473*/        }
474
475        return $data;
476    }
477
478    /**
479     * Add page with ID to the package
480     **/
481    function __siteexport_add_site( $ID ) {
482        global $conf, $currentID;
483
484        // Which is the current ID?
485        $currentID = $ID;
486
487        $this->functions->debug->message("========================================", null, 2);
488        $this->functions->debug->message("Adding Site: '$ID'", null, 2);
489        $this->functions->debug->message("----------------------------------------", $_REQUEST, 2);
490
491        $request = $this->functions->settings->additionalParameters;
492        unset($request['diPlu']); // This will not be needed for the first request.
493        unset($request['diInv']); // This will not be needed for the first request.
494
495        // say, what to export and Build URL
496        // http://documentation:81/helpdesk/de/hds/getting-started?depthType=0&do=siteexport&ens=helpdesk%3Ade%3Ahds%3Agetting-started&pdfExport=1&renderer=siteexport_siteexportpdf&template=helpdesk
497
498        $do = (intval($_REQUEST['exportbody']) == 1 ? (empty($_REQUEST['renderer']) ? $conf['renderer_xhtml'] : $_REQUEST['renderer'] ) : '' );
499
500        if ($do == 'pdf' && $this->filewriter->canDoPDF() )
501        {
502            $do = 'export_siteexport_pdf';
503            $_REQUEST['origRenderer'] = (empty($_REQUEST['renderer']) ? $conf['renderer_xhtml'] : $_REQUEST['renderer'] );
504        }
505
506        $do = ($do == $conf['renderer_xhtml'] && intval($_REQUEST['exportbody']) != 1) ? '' : 'export_' . $do;
507
508        if ( $do != 'export_' && !empty($do) )
509        {
510            $request['do'] = $do;
511        }
512
513        // set Template
514        if ( !empty( $_REQUEST['template'] ) ) {
515            $request['template'] = $_REQUEST['template'];
516        }
517
518        $this->functions->debug->message("REQUEST for add_site:", $request, 2);
519
520        $ID = $this->functions->cleanID($ID);
521        $url = $this->functions->wl($ID, $request, true, '&');
522
523        // Parse URI PATH and add "html"
524        $fileName = $this->functions->getSiteName($ID, true);
525        $this->functions->debug->message("Filename could be:", $fileName, 2);
526
527        $this->fileChecked[$url] = $fileName; // 2010-09-03 - One URL to one FileName
528        $this->functions->settings->depth = str_repeat('../', count(explode('/', $fileName))-1);
529
530        // fetch URL and save it in temp file
531        $tmpFile = $this->__getHTTPFile($url);
532        if ( $tmpFile === false ) {
533        	// return $this->functions->debug->message("Creating temporary download file failed for '$url'. See log for more information.");
534        	$this->functions->debug->runtimeException("Creating temporary download file failed for '$url'. See log for more information.");
535        	return false;
536        }
537
538        $dirname = dirname($fileName);
539        // If a Filename was given that does not comply to the original name, use this one!
540		if ( $this->filewriter->canDoPDF() ) {
541
542			$this->functions->debug->message("Will replace old filename '{$fileName}' with {$tmpFile[2]}", null, 1);
543        	$extension = array_pop(explode('.', $fileName));
544
545        	// 2014-04-29 added cleanID to ensure that links are generated consistently when using [[this>...]] or another local, relativ linking
546			$fileName = $dirname . '/' . $this->functions->cleanID($this->functions->getSiteTitle($ID)) . '.' . $extension;
547        } else if ( !empty($tmpFile[1]) && !strstr($DATA[2], $tmpFile[1]) ) {
548
549			$this->functions->debug->message("Will replace old filename '{$fileName}' with {$dirname}/{$tmpFile[1]}", null, 1);
550			$fileName = $dirname . '/' . $tmpFile[1];
551        }
552
553        // Add to zip
554		$this->fileChecked[$url] = $fileName;
555        $status = $this->filewriter->__addFileToZip($tmpFile[0], $fileName);
556        @unlink($tmpFile[0]);
557
558        return $status;
559    }
560
561    function __preg_quote($input) {
562	    return preg_quote($input, '/');
563    }
564
565    /**
566     * Download the file via HTTP URL + recurse if this is not an image
567     * The file will be saved as temporary file. The filename is the result.
568     **/
569    function __getHTTPFile($URL, $RECURSE=false, $newAdditionalParameters=null) {
570        global $conf;
571
572        $EXCLUDE = $this->getConf('exclude');
573        if ( !empty($EXCLUDE) ) {
574	        $PATTERN = "/(" . implode('|', explode(' ', preg_quote($EXCLUDE, '/'))) . ")/i";
575
576	        $this->functions->debug->message("Checking for exclude: ", array(
577	        	"pattern" => $PATTERN,
578	        	"file" => $URL,
579	        	"matches" => preg_match($PATTERN, $URL) ? 'match' : 'no match'
580	        ), 2);
581
582			if ( preg_match($PATTERN, $URL) ) { return false; }
583        }
584
585        require_once( DOKU_INC . 'inc/HTTPClient.php');
586
587        $http = new HTTPProxy($this->functions->debug, $this->functions->settings);
588        $http->max_bodysize = $conf['fetchsize'];
589        // $http->user = $_SERVER['PHP_AUTH_USER']; // Must not be set, or the files will be authenticated and have the edit thingies
590        // $http->pass = $_SERVER['PHP_AUTH_PW']; // Must not be set, or the files will be authenticated and have the edit thingies
591
592        // Add additional Params
593        $this->functions->addAdditionalParametersToURL($URL, $newAdditionalParameters);
594
595        $this->functions->debug->message("Fetching URL: '$URL'", null, 2);
596        $getData = $http->get($URL);
597
598        if( $getData === false ) {
599
600        	if ( $this->functions->settings->ignoreNon200 ) {
601	        	return null;
602        	}
603
604            $this->functions->debug->message("Sending request failed with error, HTTP status was '{$http->status}'.", $URL, 4);
605            return false;
606        }
607
608        if( empty($getData) ) {
609            $this->functions->debug->message("No data fetched.", null , 4);
610            return false;
611        }
612
613        $tmpFile = tempnam($this->functions->settings->tmpDir , 'siteexport__');
614        $this->functions->debug->message("Temporary filename", $tmpFile, 1);
615
616        $fp = fopen( $tmpFile, "w");
617        if(!$fp) {
618            $this->functions->debug->message("Can't open temporary File '$tmpFile'.", null , 4);
619            return false;
620        }
621
622        $this->functions->debug->message("Headers received", $http->resp_headers, 2);
623
624        if ( !$RECURSE ) {
625            // Parse URI PATH and add "html"
626            $this->functions->debug->message("========================================", null, 1);
627            $this->functions->debug->message("Starting to recurse file '$URL'", null , 1);
628			$this->functions->debug->message("----------------------------------------", null, 1);
629            $this->__getInternalLinks($getData);
630			$this->functions->debug->message("----------------------------------------", null, 1);
631            $this->functions->debug->message("Finished to recurse file '$URL'", null , 1);
632            $this->functions->debug->message("========================================", null, 1);
633        }
634
635        fwrite($fp,$getData);
636        fclose($fp);
637
638        return array($tmpFile, preg_replace("/.*?filename=\"?(.*?)\"?;?$/", "$1", $http->resp_headers['content-disposition']));
639    }
640
641    /**
642     * Find internal links in the currently downloaded file. This also matches inside CSS files
643     **/
644    function __getInternalLinks(&$DATA) {
645
646        $PATTERN = '(href|src|action)="([^"]*)"';
647        $CALLBACK = array($this, '__fetchAndReplaceLink');
648        $DATA = preg_replace_callback("/$PATTERN/i", $CALLBACK, $DATA);
649
650        $PATTERNCSS = '(url\s*?)\(([^\)]*)\)';
651        $DATA = preg_replace_callback("/$PATTERNCSS/i", $CALLBACK, $DATA);
652    }
653
654    /**
655     * Deep Fetch and replace of links inside the texts matched by __getInternalLinks
656     **/
657    function __fetchAndReplaceLink($DATA) {
658        global $conf, $currentID;
659
660        $noDeepReplace = true;
661        $newAdditionalParameters = $this->functions->settings->additionalParameters;
662        $newDepth = $this->functions->settings->depth;
663        $hadBase = false;
664
665		// Clean data[2], remote ' and "
666		$DATA[2] = preg_replace("/^\s*?['\"]?(.*?)['\"]?\s*?$/", '\1', trim($DATA[2]));
667
668        $this->functions->debug->message("Starting Link Replacement", $DATA, 2);
669
670        // $DATA[2] = urldecode($DATA[2]); // Leads to problems because it does not re-encode the url
671        // External and mailto links
672        if ( preg_match("%^(https?://|mailto:|javascript:|data:)%", $DATA[2]) ) {
673            $this->functions->debug->message("Don't like http, mailto, data or javascript links here", null, 1);
674            return $this->__rebuildLink($DATA, "");
675        }
676        //if ( preg_match("%^(https?://|mailto:|" . DOKU_BASE . "/_export/)%", $DATA[2]) ) { return $this->__rebuildLink($DATA, ""); }
677        // External media - this is deep down in the link, so we have to grep it out
678        if ( preg_match("%media=(https?://.*?$)%", $DATA[2], $matches) ) {
679            $DATA[2] = $matches[1];
680            $this->functions->debug->message("This is an HTTP like somewhere else", $DATA, 1);
681            return $this->__rebuildLink($DATA, "");
682        }
683        // reference only links won't have to be rewritten
684        if ( preg_match("%^#.*?$%", $DATA[2]) ) {
685            $this->functions->debug->message("This is a refercence only", null, 1);
686            return $this->__rebuildLink($DATA, "");
687        }
688
689        // strip all things out
690        // changed Data
691        $PARAMS = @parse_url($DATA[2], PHP_URL_QUERY);
692        $ANCHOR = @parse_url($DATA[2], PHP_URL_FRAGMENT);
693        $DATA[2] = @parse_url($DATA[2], PHP_URL_PATH);
694
695        // 2010-08-25 - fix problem with relative movement in links ( "test/../test2" )
696        $tmpData2 = '';
697        while( $tmpData2 != $DATA[2] ) {
698            $tmpData2 = $DATA[2];
699            $DATA[2] = preg_replace("#/(?!\.\.)[^\/]*?/\.\./#", '/', $DATA[2]);
700        }
701
702        $temp = preg_replace("%^" . DOKU_BASE . "%", "", $DATA[2]);
703        if ( $temp != $DATA[2] ) {
704            $DATA[2] = $temp;
705            $hadBase = true; // 2010-08-23 Check if there has been a rewrite here that will have to be considered later on
706        }
707
708        $this->functions->debug->message("URL before rewriting option for others than 1", array($DATA, $PARAMS, $hadBase), 1);
709
710        // Handle rewrites other than 1 - just for non-lib-files
711        // if ( !preg_match('$^/?lib/$', $DATA[2]) ) {
712        if ( !preg_match('$^(' . DOKU_BASE . ')?lib/$', $DATA[2]) ) {
713		    $this->functions->debug->message("Did not match '$^(" . DOKU_BASE . ")?lib/$' userewrite == ", $conf['userewrite'], 2);
714            if ( $conf['userewrite'] == 2 ) {
715                $DATA[2] = $this->__getInternalRewriteURL($DATA[2]);
716            } elseif ( $conf['userewrite'] == 0 ) {
717                $this->__getParamsAndDataRewritten($DATA, $PARAMS);
718            }
719        } else {
720	    	$this->functions->debug->message("This file must be inside lib ...", null, 2);
721        }
722
723        $this->functions->debug->message("URL before rewriting option", array($DATA, $PARAMS), 2);
724
725        $ORIGDATA2 = $DATA;
726        //        $ORIGDATA2 = $DATA[2]; // 08/10/2010 - this line required a $this->functions->wl which may mess up with the base URL
727        $this->functions->debug->message("OrigDATA is:", $ORIGDATA2, 1);
728
729        // Generate ID
730        $DATA[2] = str_replace('/', ':', $DATA[2]);
731
732        // If Data was empty this must be the same file!;
733        if ( empty( $DATA[2] ) ) {
734            $DATA[2] = $currentID;
735        }
736
737        $ID = $DATA[2];
738        $MEDIAMATCHER = "#(_media(/|:)|media=|_detail(/|:)|_export(/|:)|do=export_)#i"; // 2010-10-23 added "(/|:)" for the ID may not contain slashes anymore
739        $ID = $this->functions->cleanID($DATA[2], null, preg_match($MEDIAMATCHER, $DATA[2]) );
740        //        $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media') ); // Export anpassung nun weiter unten
741
742        //        $IDexists = page_exists($ID); // 08/10/2010 - Not needed. This will be done in the next block.
743        //        $this->functions->debug->message("Current ID: '$ID' exists: '" . ($IDexists ? 'true' : 'false') . "' (will be set to 'false' anyway)", null, 1);
744
745        $IDifIDnotExists = $ID; // 08/10/2010 - Save ID - with possible upper cases to preserve them
746        $IDexists = false;
747
748        $this->functions->debug->message("Resolving ID: '$ID'", null, 2);
749        if ( preg_match($MEDIAMATCHER, $DATA[2]) ) {
750            resolve_mediaid(null, $ID, $IDexists);
751
752            $this->functions->debug->message("Current mediaID to filename: '" . mediaFN($ID) . "'", null, 2);
753        } else {
754            resolve_pageid(null, $ID, $IDexists);
755            $this->functions->debug->message("Current ID to filename: '" . wikiFN($ID) . "'", null, 2);
756        }
757
758        $this->functions->debug->message("Current ID after resolvement: '$ID' the ID does exist: '" . ($IDexists ? 'true' : 'false') . "'", null, 2);
759        //        $ORIGDATA2 = @parse_url($this->functions->wl($ORIGDATA2, null, true)); // What was the next 2 line for? It did mess up with links from {{jdoc>}}
760        //        $this->functions->debug->message("OrigData ID after parse:", $ORIGDATA2, 1); // 08/10/2010 - The lines are obsolete when the $ORIGDATA2 = $DATA. $ORIGDATA is only for fallback
761
762        // 08/10/2010 - If the ID does not exist, we may have a problem here with upper cases - they will all be lower by now!
763        if ( !$IDexists ) {
764            $ID = $IDifIDnotExists; // there may have been presevered Upper cases. We will need them!
765        }
766
767        // $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media') || strstr($DATA[2], 'export') );
768        if ( substr($ID, -1) == ':' || empty($ID) ) $ID .= $conf['start'];
769
770        // Generate Download URL
771        // $PARAMS = trim(str_replace('&amp;', '&', $PARAMS));
772        $PARAMS = trim($PARAMS);
773        $this->functions->removeWikiVariables($PARAMS, false, true);
774
775        $url = $this->functions->wl($ID, null, true, null, null, true, $hadBase) . ( !empty( $ANCHOR) ? '#' . $ANCHOR : '' ) . ( !empty( $PARAMS) ? '?' . $PARAMS : '' );
776        $this->functions->debug->message("URL from ID: '$url'", null, 2);
777
778        // Parse URI PATH and add "html"
779        $uri = @parse_url($url);
780        $DATA[2] = $uri['path'];
781        $DATA['ANCHOR'] = $ANCHOR;
782        $DATA['PARAMS'] = $PARAMS;
783
784        $this->functions->debug->message("DATA after parsing.", $DATA, 2);
785
786        // Second Rewrite for UseRewrite = 2
787        if ( $conf['userewrite'] == 2 ) {
788            $DATA[2] = preg_replace( '$/lib/.*?fetch\.php$', '', $DATA[2]);
789            $DATA[2] = preg_replace( '%(/lib/.*?detail\.php.*$)%', '\1' . '.' . $this->functions->settings->fileType, $DATA[2]);
790
791            if ( preg_match( '%/(lib/.*?detail|doku)\.php%', $DATA[2])) {
792                $noDeepReplace = false;
793                $fileName = $this->functions->getSiteName($ID);
794                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
795            }
796
797            $this->functions->debug->message("DATA after second rewrite with UseRewrite = 2", array($DATA, $noDeepReplace, $fileName, $newDepth), 1);
798        }
799
800        switch ( array_pop(explode('/', $DATA[2])) ) {
801            // CSS Extra Handling with extra rewrites
802            case 'css.php'	:	// $DATA[2] .=  ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS))) . '.css';
803                $DATA[2] .=  '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS)) . '.css'; // allways put parameters behind
804                // No paramters needed since they are rewritten.
805                $DATA['PARAMS'] = "";
806                $noDeepReplace = false;
807                $fileName = $this->functions->getSiteName($ID);
808                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
809                $newAdditionalParameters['do'] = 'siteexport';
810
811                $this->functions->debug->message("This is CSS file", array($DATA, $noDeepReplace, $fileName, $newDepth, $newAdditionalParameters), 2);
812
813                break;
814            case 'js.php'	:	// $DATA[2] .= ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS))) . '.js';
815                $DATA[2] .=  '.t.' . $this->functions->cleanID($_REQUEST['template']) . '.js'; // allways put parameters behind
816                // set Template
817                if ( !empty( $_REQUEST['template'] ) ) {
818                    $url .= ( strstr($url, '?') ? '&' : '?' ) . 'template=' . $_REQUEST['template'];
819                }
820                // No paramters needed since they are rewritten.
821                $DATA['PARAMS'] = "";
822                $newAdditionalParameters['do'] = 'siteexport';
823
824                $this->functions->debug->message("This is JS file", array($DATA, $url, $fileName, $newAdditionalParameters), 2);
825
826                break;
827                // Detail Handling with extra Rewrites if Paramaters are available - otherwise this is just the fetch
828            case 'indexer.php' :
829                $this->functions->debug->message("Skipping indexer", null, 2);
830                return "";
831                break;
832            case 'detail.php' :
833                $fileName = $this->functions->getSiteName($ID, true); // 2010-09-03 - rewrite with override enabled
834            case 'doku.php' :
835                if ( $this->functions->settings->addParams ) {
836                    $noDeepReplace = false;
837
838                    if ( empty($fileName) ) {
839                        $fileName = $this->functions->getSiteName($ID); // 2010-09-03 - rewrite with override enabled
840                    }
841
842                    $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
843                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
844
845                    $this->functions->debug->message("This is doku.php or detail.php file with addParams", array($DATA, $fileName, $newDepth, $newAdditionalParameters), 2);
846                    break;
847                }
848
849                $url = str_replace('detail.php', 'fetch.php', $url);
850                $this->functions->debug->message("This is doku.php or detail.php file '$url'", null, 2);
851                // Fetch Handling for media - rewriting everything
852            case 'fetch.php':
853                $this->__getParamsAndDataRewritten($DATA, $PARAMS, 'media');
854
855                $DATA[2] = str_replace('/', ':', $DATA[2]);
856                $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media'));
857
858                $urlM = ml($ID, null, true);
859                $uriM = @parse_url($urlM);
860                $DATA[2] = $uriM['path'] . ( !empty( $ANCHOR) ? '#' . $ANCHOR : '' ) . ( !empty( $PARAMS) ? '?' . $PARAMS : '' );
861
862                $DATA['PARAMS'] = "";
863                $newAdditionalParameters = array();
864
865                $this->functions->debug->message("This is fetch.php file", array($DATA, $ID, $PARAMS), 2);
866                break;
867
868                // default Handling for Pages
869            default			:
870                if ( preg_match("%" . DOKU_BASE . "_detail/%", $DATA[2]) ) {
871
872                    // GET ID Param from origdata2
873                    preg_match("#id=(.*?)(&|\")#i", $DATA[0], $backlinkID);
874                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
875
876                    $fileIDPart = isset($backlinkID[1]) && !empty($backlinkID[1]) ? $this->functions->cleanID(urldecode($backlinkID[1])) : 'detail';
877
878                    $DATA[2] .= '/' . $fileIDPart . '.' . $this->functions->settings->fileType; // add namespace and subpage for back button and add filetype
879
880                    $noDeepReplace = false;
881                    $fileName = $this->functions->shortenName($DATA[2]);
882                    $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
883                    $url .= ( strstr($url, '?') ? '&' : '?' ) . 'id=' . $fileIDPart; // add id-part to URL for backlinks
884
885                    $DATA['PARAMS'] = "";
886
887                    $this->functions->debug->message("This is something with '_detail' file", array($DATA, $backlinkID, $newDepth, $url), 2);
888                } else if ( preg_match("%" . DOKU_BASE . "_export/(.*?)/%", $DATA[2], $fileType) ) {
889
890                    // Fixes multiple codeblocks in one file
891                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
892
893                    // add the Params no matter what they are. This is export. We don't mess with other files
894                    // adding the "/" fixes the usage of multiple codeblocks in the same namespace
895                    $DATA[2] .= (empty( $PARAMS ) ? '' : '/' . $PARAMS) . '.'. $fileType[1];
896
897                    $DATA['PARAMS'] = "";
898                    $this->functions->debug->message("This is something with '_export' file", $DATA, 2);
899
900                } else if ( $IDexists ) { // 08/10/2010 - was page_exists($ID) - but this should do as well.
901                    // If this is a page ... skip it!
902                    $DATA[2] .= ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS)))  . '.' . $this->functions->settings->fileType;
903
904                    // 2012-06-15 originally has an absolute path ... we might need a relative one if not in our namespace
905                    $this->functions->debug->message("OK, this is to be absolute: " . (empty($_REQUEST['absolutePath'])?'false':'true'), null, 1);
906                    if ( empty($_REQUEST['absolutePath']) )
907                    {
908                        $DATA[2] = $this->functions->getRelativeURL($DATA[2], $currentID);
909                    }
910
911                    $DATA[2] = $this->functions->shortenName($DATA[2]);
912
913                    // If Parameters are to be included in the filename - they must not be added twice
914                    if ( $this->functions->settings->addParams ) $DATA['PARAMS'] = "";
915
916                    $this->functions->debug->message("This page really exists", $DATA, 1);
917
918                    return $this->__rebuildLink($DATA);
919                } else {
920                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
921                }
922
923                unset($newAdditionalParameters['diPlu']);
924        }
925
926
927        $this->functions->debug->message("DATA after SWITCH CASE decision", array($DATA, $noDeepReplace, $fileName, $newDepth), 1);
928
929        if ( $this->filewriter->canDoPDF() ) {
930            $this->functions->addAdditionalParametersToURL($url, $newAdditionalParameters);
931            $DATA[2] = $url;
932            unset($DATA['PARAMS']);
933            $url = $this->__rebuildLink($DATA, '');
934
935            $this->functions->debug->message("Creating PDF with URL '$url'", null, 2);
936
937            return $url;
938        }
939
940        // Create Name to save the file at
941        $DATA[2] = str_replace(':', '_', $DATA[2]);
942        $DATA[2] = $this->functions->shortenName($DATA[2]);
943
944
945        // File already loaded?
946        // 2010-10-23 - changes in_array from DATA[2] to $url - to check real URLs, the DATA[2] file will be checked with fileExistsInZip
947        if ( in_array($url, array_keys($this->fileChecked)) ) {
948            $DATA[2] = $this->fileChecked[$url];
949            $this->functions->debug->message("File has been checked before.", array($DATA, $url), 2);
950            return $this->__rebuildLink($DATA);
951        }
952
953        // 2010-09-03 - second check if the file is in the ZIP already.
954        if ( $this->filewriter->fileExistsInZip($DATA[2]) ) {
955            $this->functions->debug->message("File with DATA exists in ZIP.", $DATA, 3);
956            return $this->__rebuildLink($DATA);
957        }
958
959        // 2010-10-23 - What if this is a fetch.php? than we produced an error.
960        //        $this->fileChecked[] = $DATA[2];
961
962        // get tempFile and save it
963        $origDepth = $this->functions->settings->depth;
964        $this->functions->settings->depth = $newDepth;
965
966        $tmpID = $currentID;
967        $tmpFile === false;
968
969        $this->functions->debug->message("Going to get the file", array($url, $noDeepReplace, $newAdditionalParameters), 2);
970        $tmpFile = $this->__getHTTPFile($url, $noDeepReplace, $newAdditionalParameters);
971        $this->functions->debug->message("This is the getHTTPFile result", $tmpFile, 2);
972
973        $currentID = $tmpID;
974        $this->functions->settings->depth = $origDepth; // 2010-09-03 - Reset depth at the very end
975
976        if ( $tmpFile === false ) {
977            // Keep an potentially extra link intact
978
979            $this->functions->debug->message("The fetched file '$url' is 'false'", null, 3);
980            if ( $IDexists === false ) {
981                $this->functions->debug->message("The file does not exist, fallback to ORIGDATA", $ORIGDATA2, 2);
982                $DATA[2] = $this->functions->shortenName($ORIGDATA2[2]); // get Origdata Path
983            }
984
985            $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
986            $link = $this->__rebuildLink($DATA);
987            $this->functions->debug->message("Final Link after empty file from '$url'", null, 2);
988
989            return $link;
990        }
991
992        $this->functions->debug->message("The fetched file looks good.", $tmpFile, 1);
993        $dirname = dirname($DATA[2]);
994
995        // If a Filename was given that does not comply to the original name, us this one!
996        // 2014-02-28 But only if we are on PDF Mode. Does this produce any other Problems?
997        if ( $this->filewriter->canDoPDF() && !empty($tmpFile[1]) && !strstr($DATA[2], $tmpFile[1]) ) {
998			$DATA[2] = $dirname . '/' . $tmpFile[1];
999        }
1000
1001        // Add to zip
1002        $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
1003
1004        $status = $this->filewriter->__addFileToZip($tmpFile[0], $DATA[2]);
1005        @unlink($tmpFile[0]);
1006
1007        $newURL = $this->__rebuildLink($DATA);
1008        $this->functions->debug->message("Returning final Link to document: '$newURL'", null, 2);
1009
1010        return $newURL;
1011    }
1012
1013    /**
1014     * build the new link to be put in place for the donwloaded site
1015     **/
1016    function __rebuildLink($DATA, $DEPTH = null) {
1017
1018        // depth is set, skip this one
1019        if ( is_null( $DEPTH ) ) $DEPTH = $this->functions->settings->depth;
1020        $DATA[2] .= ( !empty( $DATA['PARAMS']) && $this->functions->settings->addParams? '?' . $DATA['PARAMS'] : '' ) . ( !empty( $DATA['ANCHOR'] ) ? '#' . $DATA['ANCHOR'] : '' );
1021
1022        $newURL = $DATA[1] == 'url' ? $DATA[1] . '(' . $DEPTH . $DATA[2] . ')' : $DATA[1] . '="' . $DEPTH . $DATA[2] . '"';
1023        $this->functions->debug->message("Re-created URL: '$newURL'", null, 2);
1024
1025        return $newURL;
1026    }
1027
1028
1029    /**
1030     * remove an old zip file
1031     **/
1032    function __removeOldZip( $FILENAMEID=null, $checkForMore=true ) {
1033        global $INFO;
1034        global $conf;
1035
1036        $returnValue = true;
1037
1038        if ( empty($FILENAMEID) ) {
1039            $FILENAMEID = $this->functions->settings->origZipFile;
1040        }
1041
1042        if ( !file_exists(mediaFN($FILENAMEID)) ) {
1043            $returnValue = true;
1044        } else {
1045
1046            require_once( DOKU_INC . 'inc/media.php');
1047            if ( !media_delete($FILENAMEID, $INFO['perm']) ) {
1048                $returnValue = false;
1049            }
1050        }
1051
1052        if ( $checkForMore ) {
1053            // Try to remove more files.
1054            $ns = getNS($FILENAMEID);
1055            $fn = $this->functions->getSpecialExportFileName(noNS($FILENAMEID), '.+');
1056
1057            $data = array();
1058            search($data, $conf['mediadir'], 'search_media', array('pattern' => "/$fn$/i"), $ns);
1059
1060            if ( count($data > 0) ) {
1061
1062                // 30 Minuten Cache Zeit
1063                $cache = $this->functions->settings->cachetime;
1064                foreach ( $data as $media ) {
1065
1066                    //decide if has to be deleted needed:
1067                    if( $media['mtime'] < time()-$cache) {
1068                        $this->__removeOldZip($media['id'], false);
1069                    }
1070                }
1071            }
1072
1073        }
1074
1075        return $returnValue;
1076    }
1077
1078    /**
1079     * if confrewrite is set to internal rewrite, use this function - taken from a DW renderer
1080     **/
1081    function __getInternalRewriteURL($url) {
1082        global $conf;
1083
1084        //construct page id from request URI
1085        if( $conf['userewrite'] != 2) { return $url; }
1086
1087        //get the script URL
1088        if($conf['basedir']) {
1089            $relpath = '';
1090            $script = $conf['basedir'].$relpath.basename($_SERVER['SCRIPT_FILENAME']);
1091        } elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
1092            $script = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
1093            $_SERVER['SCRIPT_FILENAME']);
1094            $script = '/'.$script;
1095        }else{
1096            $script = $_SERVER['SCRIPT_NAME'];
1097        }
1098
1099        //clean script and request (fixes a windows problem)
1100        $script  = preg_replace('/\/\/+/','/',$script);
1101        $request = preg_replace('/\/\/+/','/',$url);
1102
1103        //remove script URL and Querystring to gain the id
1104        if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){
1105            $id = preg_replace ('/\?.*/','',$match[1]);
1106        }
1107        $id = urldecode($id);
1108        //strip leading slashes
1109        $id = preg_replace('!^/+!','',$id);
1110
1111        return $id;
1112    }
1113
1114    /**
1115     * rewrite parameter calls
1116     **/
1117    function __getParamsAndDataRewritten(&$DATA, &$PARAMS, $IDKEY='id') {
1118
1119        $PARRAY = explode('&', str_replace('&amp;', '&', $PARAMS) );
1120        $PARAMS = "";
1121
1122        foreach ( $PARRAY as $item ) {
1123            list($key, $value) = explode('=', $item, 2);
1124            if ( empty($key) || empty($value) )
1125            continue;
1126
1127            if ( strtolower(trim($key)) == $IDKEY ) {
1128                $DATA[2] = preg_replace("%^" . DOKU_BASE . "%", "", $value);
1129                continue;
1130            }
1131
1132            if ( !empty( $PARAMS) ) {
1133                $PARAMS .= '&';
1134            }
1135
1136            $PARAMS .= "$key=$value";
1137        }
1138    }
1139
1140    /**
1141     * rewrite detail.php calls
1142     **/
1143    function __rebuildDataForNormalFiles(&$DATA, &$PARAMS) {
1144        $PARTS = explode('.', $DATA[2]);
1145        if ( count($PARTS) > 1 ) {
1146            $EXT = '.' . array_pop($PARTS);
1147        }
1148
1149        $PARAMS = preg_replace("/(=|\?|&amp;)/", ".", $PARAMS);
1150        $DATA[2] = implode('.', $PARTS) . ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID($PARAMS)) . ( $EXT == '.php' ? '.' . $this->functions->settings->fileType : $EXT );
1151        $DATA[2] = preg_replace("/\.+/", ".", $DATA[2]);
1152    }
1153
1154
1155
1156
1157    /*
1158     * Clean JS and CSS cache files
1159     */
1160    function cleanCacheFiles() {
1161
1162        $_SERVER['HTTP_HOST'] = preg_replace("/:?\d+$/", '', $_SERVER['HTTP_HOST']);
1163        $cache = getCacheName('scripts'.$_SERVER['HTTP_HOST'].'-siteexport-js-'.$_SERVER['SERVER_PORT'],'.js');
1164        $this->unlinkIfExists($cache);
1165
1166        $tpl = trim(preg_replace('/[^\w-]+/','',$_REQUEST['template']));
1167        if($tpl)
1168        {
1169            $tplinc = DOKU_INC.'lib/tpl/'.$tpl.'/';
1170            $tpldir = DOKU_BASE.'lib/tpl/'.$tpl.'/';
1171        } else {
1172            $tplinc = DOKU_TPLINC;
1173            $tpldir = DOKU_TPL;
1174        }
1175
1176        // The generated script depends on some dynamic options
1177        $cache = getCacheName('styles'.$_SERVER['HTTP_HOST'].'-siteexport-js-'.$_SERVER['SERVER_PORT'].DOKU_BASE.$tplinc.$style,'.css');
1178        $this->unlinkIfExists($cache);
1179    }
1180
1181    function unlinkIfExists($cache) {
1182        if ( file_exists($cache) ) {
1183            @unlink($cache);
1184            if(function_exists('gzopen')) @unlink("$cache.gz");
1185        }
1186    }
1187
1188    // Private unset function
1189    private function clear(&$variable)
1190    {
1191        if ( isset($variable) )
1192        {
1193            unset($variable);
1194        }
1195    }
1196}