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