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