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