xref: /plugin/siteexport/action/ajax.php (revision 7793901e160da6f92c016cb88713575a75e2af66)
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_shift(array_keys($event->data)) : $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        $dirname = dirname($fileName);
528        // If a Filename was given that does not comply to the original name, use this one!
529		if ( $this->filewriter->canDoPDF() ) {
530
531			$this->functions->debug->message("Will replace old filename '{$fileName}' with {$tmpFile[2]}", null, 1);
532        	$extension = array_pop(explode('.', $fileName));
533			$fileName = $dirname . '/' .  $this->functions->getSiteTitle($ID) . '.' . $extension;
534			$this->fileChecked[$url] = $fileName;
535        } else if ( !empty($tmpFile[1]) && !strstr($DATA[2], $tmpFile[1]) ) {
536
537			$this->functions->debug->message("Will replace old filename '{$fileName}' with {$tmpFile[1]}", null, 1);
538			$fileName = $dirname . '/' . $tmpFile[1];
539			$this->fileChecked[$url] = $fileName;
540        }
541
542        // Add to zip
543        $status = $this->filewriter->__addFileToZip($tmpFile[0], $fileName);
544        @unlink($tmpFile[0]);
545
546        return $status;
547    }
548
549    function __preg_quote($input) {
550	    return preg_quote($input, '/');
551    }
552
553    /**
554     * Download the file via HTTP URL + recurse if this is not an image
555     * The file will be saved as temporary file. The filename is the result.
556     **/
557    function __getHTTPFile($URL, $RECURSE=false, $newAdditionalParameters=null) {
558        global $conf;
559
560        $EXCLUDE = $this->getConf('exclude');
561        if ( !empty($EXCLUDE) ) {
562	        $PATTERN = "/(" . implode('|', explode(' ', preg_quote($EXCLUDE, '/'))) . ")/i";
563
564	        $this->functions->debug->message("Checking for exclude: ", array(
565	        	"pattern" => $PATTERN,
566	        	"file" => $URL,
567	        	"matches" => preg_match($PATTERN, $URL) ? 'match' : 'no match'
568	        ), 2);
569
570			if ( preg_match($PATTERN, $URL) ) { return false; }
571        }
572
573        require_once( DOKU_INC . 'inc/HTTPClient.php');
574
575        $http = new HTTPProxy($this->functions->debug, $this->functions->settings);
576        $http->max_bodysize = $conf['fetchsize'];
577        // $http->user = $_SERVER['PHP_AUTH_USER']; // Must not be set, or the files will be authenticated and have the edit thingies
578        // $http->pass = $_SERVER['PHP_AUTH_PW']; // Must not be set, or the files will be authenticated and have the edit thingies
579
580        // Add additional Params
581        $this->functions->addAdditionalParametersToURL($URL, $newAdditionalParameters);
582
583        $this->functions->debug->message("Fetching URL: '$URL'", null, 2);
584        $getData = $http->get($URL);
585
586        if( $getData === false ) {
587
588        	if ( $this->functions->settings->ignoreNon200 ) {
589	        	return null;
590        	}
591
592            $this->functions->debug->message("Sending request failed with error, HTTP status was '{$http->status}'.", $URL, 4);
593            return false;
594        }
595
596        if( empty($getData) ) {
597            $this->functions->debug->message("No data fetched.", null , 4);
598            return false;
599        }
600
601        $tmpFile = tempnam($this->functions->settings->tmpDir , 'siteexport__');
602        $this->functions->debug->message("Temporary filename", $tmpFile, 1);
603
604        $fp = fopen( $tmpFile, "w");
605        if(!$fp) {
606            $this->functions->debug->message("Can't open temporary File '$tmpFile'.", null , 4);
607            return false;
608        }
609
610        $this->functions->debug->message("Headers received", $http->resp_headers, 2);
611
612        if ( !$RECURSE ) {
613            // Parse URI PATH and add "html"
614            $this->functions->debug->message("========================================", null, 1);
615            $this->functions->debug->message("Starting to recurse file '$URL'", null , 1);
616			$this->functions->debug->message("----------------------------------------", null, 1);
617            $this->__getInternalLinks($getData);
618			$this->functions->debug->message("----------------------------------------", null, 1);
619            $this->functions->debug->message("Finished to recurse file '$URL'", null , 1);
620            $this->functions->debug->message("========================================", null, 1);
621        }
622
623        fwrite($fp,$getData);
624        fclose($fp);
625
626        return array($tmpFile, preg_replace("/.*?filename=\"?(.*?)\"?;?$/", "$1", $http->resp_headers['content-disposition']));
627    }
628
629    /**
630     * Find internal links in the currently downloaded file. This also matches inside CSS files
631     **/
632    function __getInternalLinks(&$DATA) {
633
634        $PATTERN = '(href|src|action)="([^"]*)"';
635        $CALLBACK = array($this, '__fetchAndReplaceLink');
636        $DATA = preg_replace_callback("/$PATTERN/i", $CALLBACK, $DATA);
637
638        $PATTERNCSS = '(url\s*?)\(([^\)]*)\)';
639        $DATA = preg_replace_callback("/$PATTERNCSS/i", $CALLBACK, $DATA);
640    }
641
642    /**
643     * Deep Fetch and replace of links inside the texts matched by __getInternalLinks
644     **/
645    function __fetchAndReplaceLink($DATA) {
646        global $conf, $currentID;
647
648        $noDeepReplace = true;
649        $newAdditionalParameters = $this->functions->settings->additionalParameters;
650        $newDepth = $this->functions->settings->depth;
651        $hadBase = false;
652
653		// Clean data[2], remote ' and "
654		$DATA[2] = preg_replace("/^\s*?['\"]?(.*?)['\"]?\s*?$/", '\1', trim($DATA[2]));
655
656        $this->functions->debug->message("Starting Link Replacement", $DATA, 2);
657
658        // $DATA[2] = urldecode($DATA[2]); // Leads to problems because it does not re-encode the url
659        // External and mailto links
660        if ( preg_match("%^(https?://|mailto:|javascript:|data:)%", $DATA[2]) ) {
661            $this->functions->debug->message("Don't like http, mailto, data or javascript links here", null, 1);
662            return $this->__rebuildLink($DATA, "");
663        }
664        //if ( preg_match("%^(https?://|mailto:|" . DOKU_BASE . "/_export/)%", $DATA[2]) ) { return $this->__rebuildLink($DATA, ""); }
665        // External media - this is deep down in the link, so we have to grep it out
666        if ( preg_match("%media=(https?://.*?$)%", $DATA[2], $matches) ) {
667            $DATA[2] = $matches[1];
668            $this->functions->debug->message("This is an HTTP like somewhere else", $DATA, 1);
669            return $this->__rebuildLink($DATA, "");
670        }
671        // reference only links won't have to be rewritten
672        if ( preg_match("%^#.*?$%", $DATA[2]) ) {
673            $this->functions->debug->message("This is a refercence only", null, 1);
674            return $this->__rebuildLink($DATA, "");
675        }
676
677        // strip all things out
678        // changed Data
679        $PARAMS = @parse_url($DATA[2], PHP_URL_QUERY);
680        $ANCHOR = @parse_url($DATA[2], PHP_URL_FRAGMENT);
681        $DATA[2] = @parse_url($DATA[2], PHP_URL_PATH);
682
683        // 2010-08-25 - fix problem with relative movement in links ( "test/../test2" )
684        $tmpData2 = '';
685        while( $tmpData2 != $DATA[2] ) {
686            $tmpData2 = $DATA[2];
687            $DATA[2] = preg_replace("#/(?!\.\.)[^\/]*?/\.\./#", '/', $DATA[2]);
688        }
689
690        $temp = preg_replace("%^" . DOKU_BASE . "%", "", $DATA[2]);
691        if ( $temp != $DATA[2] ) {
692            $DATA[2] = $temp;
693            $hadBase = true; // 2010-08-23 Check if there has been a rewrite here that will have to be considered later on
694        }
695
696        $this->functions->debug->message("URL before rewriting option for others than 1", array($DATA, $PARAMS, $hadBase), 1);
697
698        // Handle rewrites other than 1 - just for non-lib-files
699        // if ( !preg_match('$^/?lib/$', $DATA[2]) ) {
700        if ( !preg_match('$^(' . DOKU_BASE . ')?lib/$', $DATA[2]) ) {
701		    $this->functions->debug->message("Did not match '$^(" . DOKU_BASE . ")?lib/$' userewrite == ", $conf['userewrite'], 2);
702            if ( $conf['userewrite'] == 2 ) {
703                $DATA[2] = $this->__getInternalRewriteURL($DATA[2]);
704            } elseif ( $conf['userewrite'] == 0 ) {
705                $this->__getParamsAndDataRewritten($DATA, $PARAMS);
706            }
707        } else {
708	    	$this->functions->debug->message("This file must be inside lib ...", null, 2);
709        }
710
711        $this->functions->debug->message("URL before rewriting option", array($DATA, $PARAMS), 2);
712
713        $ORIGDATA2 = $DATA;
714        //        $ORIGDATA2 = $DATA[2]; // 08/10/2010 - this line required a $this->functions->wl which may mess up with the base URL
715        $this->functions->debug->message("OrigDATA is:", $ORIGDATA2, 1);
716
717        // Generate ID
718        $DATA[2] = str_replace('/', ':', $DATA[2]);
719
720        // If Data was empty this must be the same file!;
721        if ( empty( $DATA[2] ) ) {
722            $DATA[2] = $currentID;
723        }
724
725        $ID = $DATA[2];
726        $MEDIAMATCHER = "#(_media(/|:)|media=|_detail(/|:)|_export(/|:)|do=export_)#i"; // 2010-10-23 added "(/|:)" for the ID may not contain slashes anymore
727        $ID = $this->functions->cleanID($DATA[2], null, preg_match($MEDIAMATCHER, $DATA[2]) );
728        //        $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media') ); // Export anpassung nun weiter unten
729
730        //        $IDexists = page_exists($ID); // 08/10/2010 - Not needed. This will be done in the next block.
731        //        $this->functions->debug->message("Current ID: '$ID' exists: '" . ($IDexists ? 'true' : 'false') . "' (will be set to 'false' anyway)", null, 1);
732
733        $IDifIDnotExists = $ID; // 08/10/2010 - Save ID - with possible upper cases to preserve them
734        $IDexists = false;
735
736        $this->functions->debug->message("Resolving ID: '$ID'", null, 2);
737        if ( preg_match($MEDIAMATCHER, $DATA[2]) ) {
738            resolve_mediaid(null, $ID, $IDexists);
739
740            $this->functions->debug->message("Current mediaID to filename: '" . mediaFN($ID) . "'", null, 2);
741        } else {
742            resolve_pageid(null, $ID, $IDexists);
743            $this->functions->debug->message("Current ID to filename: '" . wikiFN($ID) . "'", null, 2);
744        }
745
746        $this->functions->debug->message("Current ID after resolvement: '$ID' the ID does exist: '" . ($IDexists ? 'true' : 'false') . "'", null, 2);
747        //        $ORIGDATA2 = @parse_url($this->functions->wl($ORIGDATA2, null, true)); // What was the next 2 line for? It did mess up with links from {{jdoc>}}
748        //        $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
749
750        // 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!
751        if ( !$IDexists ) {
752            $ID = $IDifIDnotExists; // there may have been presevered Upper cases. We will need them!
753        }
754
755        // $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media') || strstr($DATA[2], 'export') );
756        if ( substr($ID, -1) == ':' || empty($ID) ) $ID .= $conf['start'];
757
758        // Generate Download URL
759        // $PARAMS = trim(str_replace('&amp;', '&', $PARAMS));
760        $PARAMS = trim($PARAMS);
761        $this->functions->removeWikiVariables($PARAMS, false, true);
762
763        $url = $this->functions->wl($ID, null, true, null, null, true, $hadBase) . ( !empty( $ANCHOR) ? '#' . $ANCHOR : '' ) . ( !empty( $PARAMS) ? '?' . $PARAMS : '' );
764        $this->functions->debug->message("URL from ID: '$url'", null, 2);
765
766        // Parse URI PATH and add "html"
767        $uri = @parse_url($url);
768        $DATA[2] = $uri['path'];
769        $DATA['ANCHOR'] = $ANCHOR;
770        $DATA['PARAMS'] = $PARAMS;
771
772        $this->functions->debug->message("DATA after parsing.", $DATA, 2);
773
774        // Second Rewrite for UseRewrite = 2
775        if ( $conf['userewrite'] == 2 ) {
776            $DATA[2] = preg_replace( '$/lib/.*?fetch\.php$', '', $DATA[2]);
777            $DATA[2] = preg_replace( '%(/lib/.*?detail\.php.*$)%', '\1' . '.' . $this->functions->settings->fileType, $DATA[2]);
778
779            if ( preg_match( '%/(lib/.*?detail|doku)\.php%', $DATA[2])) {
780                $noDeepReplace = false;
781                $fileName = $this->functions->getSiteName($ID);
782                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
783            }
784
785            $this->functions->debug->message("DATA after second rewrite with UseRewrite = 2", array($DATA, $noDeepReplace, $fileName, $newDepth), 1);
786        }
787
788        switch ( array_pop(explode('/', $DATA[2])) ) {
789            // CSS Extra Handling with extra rewrites
790            case 'css.php'	:	// $DATA[2] .=  ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS))) . '.css';
791                $DATA[2] .=  '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS)) . '.css'; // allways put parameters behind
792                // No paramters needed since they are rewritten.
793                $DATA['PARAMS'] = "";
794                $noDeepReplace = false;
795                $fileName = $this->functions->getSiteName($ID);
796                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
797                $newAdditionalParameters['do'] = 'siteexport';
798
799                $this->functions->debug->message("This is CSS file", array($DATA, $noDeepReplace, $fileName, $newDepth, $newAdditionalParameters), 2);
800
801                break;
802            case 'js.php'	:	// $DATA[2] .= ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS))) . '.js';
803                $DATA[2] .=  '.t.' . $this->functions->cleanID($_REQUEST['template']) . '.js'; // allways put parameters behind
804                // set Template
805                if ( !empty( $_REQUEST['template'] ) ) {
806                    $url .= ( strstr($url, '?') ? '&' : '?' ) . 'template=' . $_REQUEST['template'];
807                }
808                // No paramters needed since they are rewritten.
809                $DATA['PARAMS'] = "";
810                $newAdditionalParameters['do'] = 'siteexport';
811
812                $this->functions->debug->message("This is JS file", array($DATA, $url, $fileName, $newAdditionalParameters), 2);
813
814                break;
815                // Detail Handling with extra Rewrites if Paramaters are available - otherwise this is just the fetch
816            case 'indexer.php' :
817                $this->functions->debug->message("Skipping indexer", null, 2);
818                return "";
819                break;
820            case 'detail.php' :
821                $fileName = $this->functions->getSiteName($ID, true); // 2010-09-03 - rewrite with override enabled
822            case 'doku.php' :
823                if ( $this->functions->settings->addParams ) {
824                    $noDeepReplace = false;
825
826                    if ( empty($fileName) ) {
827                        $fileName = $this->functions->getSiteName($ID); // 2010-09-03 - rewrite with override enabled
828                    }
829
830                    $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
831                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
832
833                    $this->functions->debug->message("This is doku.php or detail.php file with addParams", array($DATA, $fileName, $newDepth, $newAdditionalParameters), 2);
834                    break;
835                }
836
837                $url = str_replace('detail.php', 'fetch.php', $url);
838                $this->functions->debug->message("This is doku.php or detail.php file '$url'", null, 2);
839                // Fetch Handling for media - rewriting everything
840            case 'fetch.php':
841                $this->__getParamsAndDataRewritten($DATA, $PARAMS, 'media');
842
843                $DATA[2] = str_replace('/', ':', $DATA[2]);
844                $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media'));
845
846                $urlM = ml($ID, null, true);
847                $uriM = @parse_url($urlM);
848                $DATA[2] = $uriM['path'] . ( !empty( $ANCHOR) ? '#' . $ANCHOR : '' ) . ( !empty( $PARAMS) ? '?' . $PARAMS : '' );
849
850                $DATA['PARAMS'] = "";
851                $newAdditionalParameters = array();
852
853                $this->functions->debug->message("This is fetch.php file", array($DATA, $ID, $PARAMS), 2);
854                break;
855
856                // default Handling for Pages
857            default			:
858                if ( preg_match("%" . DOKU_BASE . "_detail/%", $DATA[2]) ) {
859
860                    // GET ID Param from origdata2
861                    preg_match("#id=(.*?)(&|\")#i", $DATA[0], $backlinkID);
862                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
863
864                    $fileIDPart = isset($backlinkID[1]) && !empty($backlinkID[1]) ? $this->functions->cleanID(urldecode($backlinkID[1])) : 'detail';
865
866                    $DATA[2] .= '/' . $fileIDPart . '.' . $this->functions->settings->fileType; // add namespace and subpage for back button and add filetype
867
868                    $noDeepReplace = false;
869                    $fileName = $this->functions->shortenName($DATA[2]);
870                    $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
871                    $url .= ( strstr($url, '?') ? '&' : '?' ) . 'id=' . $fileIDPart; // add id-part to URL for backlinks
872
873                    $DATA['PARAMS'] = "";
874
875                    $this->functions->debug->message("This is something with '_detail' file", array($DATA, $backlinkID, $newDepth, $url), 2);
876                } else if ( preg_match("%" . DOKU_BASE . "_export/(.*?)/%", $DATA[2], $fileType) ) {
877
878                    // Fixes multiple codeblocks in one file
879                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
880
881                    // add the Params no matter what they are. This is export. We don't mess with other files
882                    // adding the "/" fixes the usage of multiple codeblocks in the same namespace
883                    $DATA[2] .= (empty( $PARAMS ) ? '' : '/' . $PARAMS) . '.'. $fileType[1];
884
885                    $DATA['PARAMS'] = "";
886                    $this->functions->debug->message("This is something with '_export' file", $DATA, 2);
887
888                } else if ( $IDexists ) { // 08/10/2010 - was page_exists($ID) - but this should do as well.
889                    // If this is a page ... skip it!
890                    $DATA[2] .= ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS)))  . '.' . $this->functions->settings->fileType;
891
892                    // 2012-06-15 originally has an absolute path ... we might need a relative one if not in our namespace
893                    $this->functions->debug->message("OK, this is to be absolute: " . (empty($_REQUEST['absolutePath'])?'false':'true'), null, 1);
894                    if ( empty($_REQUEST['absolutePath']) )
895                    {
896                        $DATA[2] = $this->functions->getRelativeURL($DATA[2], $currentID);
897                    }
898
899                    $DATA[2] = $this->functions->shortenName($DATA[2]);
900
901                    // If Parameters are to be included in the filename - they must not be added twice
902                    if ( $this->functions->settings->addParams ) $DATA['PARAMS'] = "";
903
904                    $this->functions->debug->message("This page really exists", $DATA, 1);
905
906                    return $this->__rebuildLink($DATA);
907                } else {
908                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
909                }
910
911                unset($newAdditionalParameters['diPlu']);
912        }
913
914
915        $this->functions->debug->message("DATA after SWITCH CASE decision", array($DATA, $noDeepReplace, $fileName, $newDepth), 1);
916
917        if ( $this->filewriter->canDoPDF() ) {
918            $this->functions->addAdditionalParametersToURL($url, $newAdditionalParameters);
919            $DATA[2] = $url;
920            unset($DATA['PARAMS']);
921            $url = $this->__rebuildLink($DATA, '');
922
923            $this->functions->debug->message("Creating PDF with URL '$url'", null, 2);
924
925            return $url;
926        }
927
928        // Create Name to save the file at
929        $DATA[2] = str_replace(':', '_', $DATA[2]);
930        $DATA[2] = $this->functions->shortenName($DATA[2]);
931
932
933        // File already loaded?
934        // 2010-10-23 - changes in_array from DATA[2] to $url - to check real URLs, the DATA[2] file will be checked with fileExistsInZip
935        if ( in_array($url, array_keys($this->fileChecked)) ) {
936            $DATA[2] = $this->fileChecked[$url];
937            $this->functions->debug->message("File has been checked before.", array($DATA, $url), 2);
938            return $this->__rebuildLink($DATA);
939        }
940
941        // 2010-09-03 - second check if the file is in the ZIP already.
942        if ( $this->filewriter->fileExistsInZip($DATA[2]) ) {
943            $this->functions->debug->message("File with DATA exists in ZIP.", $DATA, 3);
944            return $this->__rebuildLink($DATA);
945        }
946
947        // 2010-10-23 - What if this is a fetch.php? than we produced an error.
948        //        $this->fileChecked[] = $DATA[2];
949        $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
950
951        // get tempFile and save it
952        $origDepth = $this->functions->settings->depth;
953        $this->functions->settings->depth = $newDepth;
954
955        $tmpID = $currentID;
956        $tmpFile === false;
957
958        $this->functions->debug->message("Going to get the file", array($url, $noDeepReplace, $newAdditionalParameters), 2);
959        $tmpFile = $this->__getHTTPFile($url, $noDeepReplace, $newAdditionalParameters);
960        $this->functions->debug->message("This is the getHTTPFile result", $tmpFile, 2);
961
962        $currentID = $tmpID;
963        $this->functions->settings->depth = $origDepth; // 2010-09-03 - Reset depth at the very end
964
965        if ( $tmpFile === false ) {
966            // Keep an potentially extra link intact
967
968            $this->functions->debug->message("The fetched file '$url' is 'false'", null, 3);
969            if ( $IDexists === false ) {
970                $this->functions->debug->message("The file does not exist, fallback to ORIGDATA", $ORIGDATA2, 2);
971                $DATA[2] = $this->functions->shortenName($ORIGDATA2[2]); // get Origdata Path
972            }
973
974            $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
975            $link = $this->__rebuildLink($DATA);
976            $this->functions->debug->message("Final Link after empty file from '$url'", null, 2);
977
978            return $link;
979        }
980
981        $this->functions->debug->message("The fetched file looks good.", $tmpFile, 1);
982        $dirname = dirname($DATA[2]);
983
984        // If a Filename was given that does not comply to the original name, us this one!
985        if ( !empty($tmpFile[1]) && !strstr($DATA[2], $tmpFile[1]) ) {
986			$DATA[2] = $dirname . '/' . $tmpFile[1];
987        }
988
989        // Add to zip
990        $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
991
992        $status = $this->filewriter->__addFileToZip($tmpFile[0], $DATA[2]);
993        @unlink($tmpFile[0]);
994
995        $newURL = $this->__rebuildLink($DATA);
996        $this->functions->debug->message("Returning final Link to document: '$newURL'", null, 2);
997
998        return $newURL;
999    }
1000
1001    /**
1002     * build the new link to be put in place for the donwloaded site
1003     **/
1004    function __rebuildLink($DATA, $DEPTH = null) {
1005
1006        // depth is set, skip this one
1007        if ( is_null( $DEPTH ) ) $DEPTH = $this->functions->settings->depth;
1008        $DATA[2] .= ( !empty( $DATA['PARAMS']) ? '?' . $DATA['PARAMS'] : '' ) . ( !empty( $DATA['ANCHOR'] ) ? '#' . $DATA['ANCHOR'] : '' );
1009
1010        $newURL = $DATA[1] == 'url' ? $DATA[1] . '(' . $DEPTH . $DATA[2] . ')' : $DATA[1] . '="' . $DEPTH . $DATA[2] . '"';
1011        $this->functions->debug->message("Re-created URL: '$newURL'", null, 2);
1012
1013        return $newURL;
1014    }
1015
1016
1017    /**
1018     * remove an old zip file
1019     **/
1020    function __removeOldZip( $FILENAMEID=null, $checkForMore=true ) {
1021        global $INFO;
1022        global $conf;
1023
1024        $returnValue = true;
1025
1026        if ( empty($FILENAMEID) ) {
1027            $FILENAMEID = $this->functions->settings->origZipFile;
1028        }
1029
1030        if ( !file_exists(mediaFN($FILENAMEID)) ) {
1031            $returnValue = true;
1032        } else {
1033
1034            require_once( DOKU_INC . 'inc/media.php');
1035            if ( !media_delete($FILENAMEID, $INFO['perm']) ) {
1036                $returnValue = false;
1037            }
1038        }
1039
1040        if ( $checkForMore ) {
1041            // Try to remove more files.
1042            $ns = getNS($FILENAMEID);
1043            $fn = $this->functions->getSpecialExportFileName(noNS($FILENAMEID), '.+');
1044
1045            $data = array();
1046            search($data, $conf['mediadir'], 'search_media', array('pattern' => "/$fn$/i"), $ns);
1047
1048            if ( count($data > 0) ) {
1049
1050                // 30 Minuten Cache Zeit
1051                $cache = $this->functions->settings->cachetime;
1052                foreach ( $data as $media ) {
1053
1054                    //decide if has to be deleted needed:
1055                    if( $media['mtime'] < time()-$cache) {
1056                        $this->__removeOldZip($media['id'], false);
1057                    }
1058                }
1059            }
1060
1061        }
1062
1063        return $returnValue;
1064    }
1065
1066    /**
1067     * if confrewrite is set to internal rewrite, use this function - taken from a DW renderer
1068     **/
1069    function __getInternalRewriteURL($url) {
1070        global $conf;
1071
1072        //construct page id from request URI
1073        if( $conf['userewrite'] != 2) { return $url; }
1074
1075        //get the script URL
1076        if($conf['basedir']) {
1077            $relpath = '';
1078            $script = $conf['basedir'].$relpath.basename($_SERVER['SCRIPT_FILENAME']);
1079        } elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
1080            $script = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
1081            $_SERVER['SCRIPT_FILENAME']);
1082            $script = '/'.$script;
1083        }else{
1084            $script = $_SERVER['SCRIPT_NAME'];
1085        }
1086
1087        //clean script and request (fixes a windows problem)
1088        $script  = preg_replace('/\/\/+/','/',$script);
1089        $request = preg_replace('/\/\/+/','/',$url);
1090
1091        //remove script URL and Querystring to gain the id
1092        if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){
1093            $id = preg_replace ('/\?.*/','',$match[1]);
1094        }
1095        $id = urldecode($id);
1096        //strip leading slashes
1097        $id = preg_replace('!^/+!','',$id);
1098
1099        return $id;
1100    }
1101
1102    /**
1103     * rewrite parameter calls
1104     **/
1105    function __getParamsAndDataRewritten(&$DATA, &$PARAMS, $IDKEY='id') {
1106
1107        $PARRAY = explode('&', str_replace('&amp;', '&', $PARAMS) );
1108        $PARAMS = "";
1109
1110        foreach ( $PARRAY as $item ) {
1111            list($key, $value) = explode('=', $item, 2);
1112            if ( empty($key) || empty($value) )
1113            continue;
1114
1115            if ( strtolower(trim($key)) == $IDKEY ) {
1116                $DATA[2] = preg_replace("%^" . DOKU_BASE . "%", "", $value);
1117                continue;
1118            }
1119
1120            if ( !empty( $PARAMS) ) {
1121                $PARAMS .= '&';
1122            }
1123
1124            $PARAMS .= "$key=$value";
1125        }
1126    }
1127
1128    /**
1129     * rewrite detail.php calls
1130     **/
1131    function __rebuildDataForNormalFiles(&$DATA, &$PARAMS) {
1132        $PARTS = explode('.', $DATA[2]);
1133        if ( count($PARTS) > 1 ) {
1134            $EXT = '.' . array_pop($PARTS);
1135        }
1136
1137        $PARAMS = preg_replace("/(=|\?|&amp;)/", ".", $PARAMS);
1138        $DATA[2] = implode('.', $PARTS) . ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID($PARAMS)) . ( $EXT == '.php' ? '.' . $this->functions->settings->fileType : $EXT );
1139        $DATA[2] = preg_replace("/\.+/", ".", $DATA[2]);
1140    }
1141
1142
1143
1144
1145    /*
1146     * Clean JS and CSS cache files
1147     */
1148    function cleanCacheFiles() {
1149
1150        $_SERVER['HTTP_HOST'] = preg_replace("/:?\d+$/", '', $_SERVER['HTTP_HOST']);
1151        $cache = getCacheName('scripts'.$_SERVER['HTTP_HOST'].'-siteexport-js-'.$_SERVER['SERVER_PORT'],'.js');
1152        $this->unlinkIfExists($cache);
1153
1154        $tpl = trim(preg_replace('/[^\w-]+/','',$_REQUEST['template']));
1155        if($tpl)
1156        {
1157            $tplinc = DOKU_INC.'lib/tpl/'.$tpl.'/';
1158            $tpldir = DOKU_BASE.'lib/tpl/'.$tpl.'/';
1159        } else {
1160            $tplinc = DOKU_TPLINC;
1161            $tpldir = DOKU_TPL;
1162        }
1163
1164        // The generated script depends on some dynamic options
1165        $cache = getCacheName('styles'.$_SERVER['HTTP_HOST'].'-siteexport-js-'.$_SERVER['SERVER_PORT'].DOKU_BASE.$tplinc.$style,'.css');
1166        $this->unlinkIfExists($cache);
1167    }
1168
1169    function unlinkIfExists($cache) {
1170        if ( file_exists($cache) ) {
1171            @unlink($cache);
1172            if(function_exists('gzopen')) @unlink("$cache.gz");
1173        }
1174    }
1175
1176    // Private unset function
1177    private function clear(&$variable)
1178    {
1179        if ( isset($variable) )
1180        {
1181            unset($variable);
1182        }
1183    }
1184}