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