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