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