xref: /plugin/siteexport/action/ajax.php (revision 9d84786f537810ed15bcc0654f796d186209da1c)
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
314            $event->preventDefault();
315            $event->stopPropagation();
316        } else {
317            // Then go for it!
318            $this->functions->debug->message("Will create a new cache thing.", null, 2);
319            $this->ajax_siteexport_addsite( $event );
320        }
321
322    }
323
324    /**
325     * Add a page to the package (for AJAX calls - Wrapper)
326     **/
327    function ajax_siteexport_addsite( &$event ) {
328
329        $event->preventDefault();
330        $event->stopPropagation();
331
332        $this->functions->debug->message("========================================", null, 1);
333        $this->functions->debug->message("Starting export from AJAX call", null, 1);
334        $this->functions->debug->message("----------------------------------------", null, 1);
335
336        $status = $this->__siteexport_add_site($_REQUEST['site']);
337        if ( $status === false ) {
338	        $this->functions->debug->message("----------------------------------------", null, 1);
339	        $this->functions->debug->message("Errors during export from AJAX call", null, 1);
340	        $this->functions->debug->message("========================================", null, 1);
341        	return;
342        }
343
344        $this->functions->debug->message("----------------------------------------", null, 1);
345        $this->functions->debug->message("Finishing export from AJAX call", null, 1);
346        $this->functions->debug->message("========================================", null, 1);
347
348        // Print the download zip-File
349        $this->cleanCacheFiles();
350
351        // If there was a Runtime Exception
352        if ( !$this->functions->debug->firstRE() ) {
353            $this->functions->debug->message("There have been errors during the export.", null, 4);
354            return;
355        }
356
357        print $this->functions->downloadURL();
358        return;
359    }
360
361    /**
362     * Fetch the list of pages to be exported
363     **/
364    function __get_siteexport_list($NS, $overrideCache=false) {
365        global $conf;
366
367        $NS = $this->namespace = $this->functions->getNamespaceFromID($NS, $PAGE);
368
369        $depth = $this->getConf('depth');
370        $query = '';
371        $doSearch = 'search_allpages';
372
373        switch( intval($_REQUEST['depthType']) ) {
374            case 0:
375                $query = $this->functions->cleanID(str_replace(":", "/", $NS.':'.$PAGE));
376                resolve_pageid($NS, $PAGE, $exists);
377
378                if ( $exists ) {
379                    $data = array( array( 'id' => $PAGE) );
380
381                    $this->functions->debug->message("Checking for Cache", null, 2);
382                    if ( !$overrideCache && $this->filewriter->hasValidCacheFile($_REQUEST, $data) )
383                    {
384                        return array();
385                    }
386
387                    return $data;
388                }
389            case 1:	$depth = 0;
390            break;
391            case 2:	$depth = intval($_REQUEST['depth']);
392            break;
393        }
394
395        $opts = array( 'depth' => $depth, 'skipacl' => $this->getConf('skipacl'), 'query' => $query);
396        $this->functions->debug->message("Options", $opts, 2);
397
398        $data = array();
399        require_once (DOKU_INC.'inc/search.php');
400
401        // Check, which TOC to take
402        if ( !$this->functions->settings->useTOCFile ) {
403            search($data, $conf['datadir'], $doSearch, $opts, $this->namespace);
404        } else {
405            $this->functions->debug->message("Using TOC for data", null, 2);
406
407            $doSearch = 'search_pagename';
408
409            // Create Data of the TOC File should be used instead
410            $opts['query'] = 'toc.txt';
411
412            $RAWdata = array();
413            search($RAWdata, $conf['datadir'], $doSearch, $opts, $this->namespace);
414
415            // There may be more than one toc and all of them have to be merged.
416            $data = array();
417            foreach( $RAWdata as $entry )
418            {
419                $tmpData = p_get_metadata($entry['id'], 'sitetoc siteexportTOC', true);
420
421                if ( is_array($tmpData) )
422                {
423                    $data = array_merge($data, $tmpData);
424                }
425            }
426        }
427
428        $this->functions->debug->message("Checking for Cache", null, 2);
429        if ( !$overrideCache && $this->filewriter->hasValidCacheFile($_REQUEST, $data) )
430        {
431            return array();
432        }
433
434        $this->functions->debug->message("Exporting the following sites: ", $data, 2);
435        return $data;
436    }
437
438    function __get_siteexport_list_and_init_tocs($NS, $isRedirected=false ) {
439
440        // Clean up if not redirected
441        if ( !$isRedirected && !$this->__removeOldZip() ) {
442            $this->functions->debug->runtimeException("Can't remove old files.");
443            return false;
444        }
445
446        $data = $this->__get_siteexport_list($NS, $isRedirected);
447        if ( $isRedirected || empty($data) )
448        {
449            // if we have been redirected, simply return the data
450            return $data;
451        }
452
453        // Create Eclipse Documentation Pages - TOC.xml, Context.xml
454        if ( !empty($_REQUEST['absolutePath']) ) $this->namespace = "";
455//        $this->__removeOldZip( $this->functions->settings->eclipseZipFile );
456
457        if ( !empty($_REQUEST['eclipseDocZip']) )
458        {
459            $toc = new siteexport_toc($this->functions);
460            $this->functions->debug->message("Generating eclipseDocZip", null, 2);
461            $this->filewriter->__moveDataToZip($toc->__getTOCXML($data), 'toc.xml');
462            $this->filewriter->__moveDataToZip($toc->__getContextXML($data), 'context.xml');
463        } else  if ( !empty($_REQUEST['JavaHelpDocZip']) )
464        {
465            $toc = new siteexport_javahelp($this->functions, $this->filewriter);
466            $toc->createTOCFiles($data);
467
468/*            $toc = new siteexport_toc($this->functions);
469            list($tocData, $mapData) = $toc->__getJavaHelpTOCXML($data);
470            $this->functions->debug->message("Generating JavaHelpDocZip", null, 2);
471            $this->filewriter->__moveDataToZip($tocData, 'toc.xml');
472            $this->filewriter->__moveDataToZip($mapData, 'map.xml');
473*/        }
474
475        return $data;
476    }
477
478    /**
479     * Add page with ID to the package
480     **/
481    function __siteexport_add_site( $ID ) {
482        global $conf, $currentID;
483
484        // Which is the current ID?
485        $currentID = $ID;
486
487        $this->functions->debug->message("========================================", null, 2);
488        $this->functions->debug->message("Adding Site: '$ID'", null, 2);
489        $this->functions->debug->message("----------------------------------------", $_REQUEST, 2);
490
491        $request = $this->functions->settings->additionalParameters;
492        unset($request['diPlu']); // This will not be needed for the first request.
493        unset($request['diInv']); // This will not be needed for the first request.
494
495        // say, what to export and Build URL
496        // 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
497
498        $do = (intval($_REQUEST['exportbody']) == 1 ? (empty($_REQUEST['renderer']) ? $conf['renderer_xhtml'] : $_REQUEST['renderer'] ) : '' );
499
500        if ($do == 'pdf' && $this->filewriter->canDoPDF() )
501        {
502            $do = 'export_siteexport_pdf';
503            $_REQUEST['origRenderer'] = (empty($_REQUEST['renderer']) ? $conf['renderer_xhtml'] : $_REQUEST['renderer'] );
504        }
505
506        $do = ($do == $conf['renderer_xhtml'] && intval($_REQUEST['exportbody']) != 1) ? '' : 'export_' . $do;
507
508        if ( $do != 'export_' && !empty($do) )
509        {
510            $request['do'] = $do;
511        }
512
513        // set Template
514        if ( !empty( $_REQUEST['template'] ) ) {
515            $request['template'] = $_REQUEST['template'];
516        }
517
518        $this->functions->debug->message("REQUEST for add_site:", $request, 2);
519
520        $ID = $this->functions->cleanID($ID);
521        $url = $this->functions->wl($ID, $request, true, '&');
522
523        // Parse URI PATH and add "html"
524        $fileName = $this->functions->getSiteName($ID, true);
525        $this->functions->debug->message("Filename could be:", $fileName, 2);
526
527        $this->fileChecked[$url] = $fileName; // 2010-09-03 - One URL to one FileName
528        $this->functions->settings->depth = str_repeat('../', count(explode('/', $fileName))-1);
529
530        // fetch URL and save it in temp file
531        $tmpFile = $this->__getHTTPFile($url);
532        if ( $tmpFile === false ) {
533        	// return $this->functions->debug->message("Creating temporary download file failed for '$url'. See log for more information.");
534        	$this->functions->debug->runtimeException("Creating temporary download file failed for '$url'. See log for more information.");
535        	return false;
536        }
537
538        $dirname = dirname($fileName);
539        // If a Filename was given that does not comply to the original name, use this one!
540		if ( $this->filewriter->canDoPDF() ) {
541
542			$this->functions->debug->message("Will replace old filename '{$fileName}' with {$tmpFile[2]}", null, 1);
543        	$extension = array_pop(explode('.', $fileName));
544
545        	// 2014-04-29 added cleanID to ensure that links are generated consistently when using [[this>...]] or another local, relativ linking
546			$fileName = $dirname . '/' . $this->functions->cleanID($this->functions->getSiteTitle($ID)) . '.' . $extension;
547        } else if ( !empty($tmpFile[1]) && !strstr($DATA[2], $tmpFile[1]) ) {
548
549			$this->functions->debug->message("Will replace old filename '{$fileName}' with {$dirname}/{$tmpFile[1]}", null, 1);
550			$fileName = $dirname . '/' . $tmpFile[1];
551        }
552
553        // Add to zip
554		$this->fileChecked[$url] = $fileName;
555        $status = $this->filewriter->__addFileToZip($tmpFile[0], $fileName);
556        @unlink($tmpFile[0]);
557
558        return $status;
559    }
560
561    function __preg_quote($input) {
562	    return preg_quote($input, '/');
563    }
564
565    /**
566     * Download the file via HTTP URL + recurse if this is not an image
567     * The file will be saved as temporary file. The filename is the result.
568     **/
569    function __getHTTPFile($URL, $RECURSE=false, $newAdditionalParameters=null) {
570        global $conf;
571
572        $EXCLUDE = $this->getConf('exclude');
573        if ( !empty($EXCLUDE) ) {
574	        $PATTERN = "/(" . implode('|', explode(' ', preg_quote($EXCLUDE, '/'))) . ")/i";
575
576	        $this->functions->debug->message("Checking for exclude: ", array(
577	        	"pattern" => $PATTERN,
578	        	"file" => $URL,
579	        	"matches" => preg_match($PATTERN, $URL) ? 'match' : 'no match'
580	        ), 2);
581
582			if ( preg_match($PATTERN, $URL) ) { return false; }
583        }
584
585        require_once( DOKU_INC . 'inc/HTTPClient.php');
586
587        $http = new HTTPProxy($this->functions->debug, $this->functions->settings);
588        $http->max_bodysize = $conf['fetchsize'];
589        // $http->user = $_SERVER['PHP_AUTH_USER']; // Must not be set, or the files will be authenticated and have the edit thingies
590        // $http->pass = $_SERVER['PHP_AUTH_PW']; // Must not be set, or the files will be authenticated and have the edit thingies
591
592        // Add additional Params
593        $this->functions->addAdditionalParametersToURL($URL, $newAdditionalParameters);
594
595        $this->functions->debug->message("Fetching URL: '$URL'", null, 2);
596        $getData = $http->get($URL, true); // true == sloopy, get 304 body as well.
597
598        if( $getData === false ) {
599
600        	if ( $this->functions->settings->ignoreNon200 ) {
601	        	return null;
602        	}
603
604            $this->functions->debug->message("Sending request failed with error, HTTP status was '{$http->status}'.", $URL, 4);
605            return false;
606        }
607
608        if( empty($getData) ) {
609            $this->functions->debug->message("No data fetched.", null , 4);
610            return false;
611        }
612
613        $this->functions->debug->message("Headers received", $http->resp_headers, 2);
614
615        if ( !$RECURSE ) {
616            // Parse URI PATH and add "html"
617            $this->functions->debug->message("========================================", null, 1);
618            $this->functions->debug->message("Starting to recurse file '$URL'", null , 1);
619			$this->functions->debug->message("----------------------------------------", null, 1);
620            $this->__getInternalLinks($getData);
621			$this->functions->debug->message("----------------------------------------", null, 1);
622            $this->functions->debug->message("Finished to recurse file '$URL'", null , 1);
623            $this->functions->debug->message("========================================", null, 1);
624        }
625
626        $tmpFile = tempnam($this->functions->settings->tmpDir , 'siteexport__');
627        $this->functions->debug->message("Temporary filename", $tmpFile, 1);
628
629        $fp = fopen( $tmpFile, "w");
630        if(!$fp) {
631            $this->functions->debug->message("Can't open temporary File '$tmpFile'.", null , 4);
632            return false;
633        }
634
635        fwrite($fp,$getData);
636        fclose($fp);
637
638        return array($tmpFile, preg_replace("/.*?filename=\"?(.*?)\"?;?$/", "$1", $http->resp_headers['content-disposition'], strrev(array_shift(explode('/', strrev($http->resp_headers['content-type']), 2)))));
639    }
640
641    /**
642     * Find internal links in the currently downloaded file. This also matches inside CSS files
643     **/
644    function __getInternalLinks(&$DATA) {
645
646        $PATTERN = '(href|src|action)="([^"]*)"';
647        $CALLBACK = array($this, '__fetchAndReplaceLink');
648        $DATA = preg_replace_callback("/$PATTERN/i", $CALLBACK, $DATA);
649
650        $PATTERNCSS = '(url\s*?)\(([^\)]*)\)';
651        $DATA = preg_replace_callback("/$PATTERNCSS/i", $CALLBACK, $DATA);
652    }
653
654    /**
655     * Deep Fetch and replace of links inside the texts matched by __getInternalLinks
656     **/
657    function __fetchAndReplaceLink($DATA) {
658        global $conf, $currentID;
659
660        $noDeepReplace = true;
661        $newAdditionalParameters = $this->functions->settings->additionalParameters;
662        $newDepth = $this->functions->settings->depth;
663        $hadBase = false;
664
665		// Clean data[2], remote ' and "
666		$DATA[2] = preg_replace("/^\s*?['\"]?(.*?)['\"]?\s*?$/", '\1', trim($DATA[2]));
667
668        $this->functions->debug->message("Starting Link Replacement", array( 'data' => $DATA, 'additional Params' => $newAdditionalParameters, 'newDepth' => $newDepth, 'currentID' => $currentID), 2);
669
670        // $DATA[2] = urldecode($DATA[2]); // Leads to problems because it does not re-encode the url
671        // External and mailto links
672        if ( preg_match("%^(https?://|mailto:|javascript:|data:)%", $DATA[2]) ) {
673            $this->functions->debug->message("Don't like http, mailto, data or javascript links here", null, 1);
674            return $this->__rebuildLink($DATA, "");
675        }
676        //if ( preg_match("%^(https?://|mailto:|" . DOKU_BASE . "/_export/)%", $DATA[2]) ) { return $this->__rebuildLink($DATA, ""); }
677        // External media - this is deep down in the link, so we have to grep it out
678        if ( preg_match("%media=(https?://.*?$)%", $DATA[2], $matches) ) {
679            $DATA[2] = $matches[1];
680            $this->functions->debug->message("This is an HTTP like somewhere else", $DATA, 1);
681            return $this->__rebuildLink($DATA, "");
682        }
683        // reference only links won't have to be rewritten
684        if ( preg_match("%^#.*?$%", $DATA[2]) ) {
685            $this->functions->debug->message("This is a refercence only", null, 1);
686            return $this->__rebuildLink($DATA, "");
687        }
688
689        // strip all things out
690        // changed Data
691        $PARAMS = @parse_url($DATA[2], PHP_URL_QUERY);
692        $ANCHOR = @parse_url($DATA[2], PHP_URL_FRAGMENT);
693        $DATA[2] = @parse_url($DATA[2], PHP_URL_PATH);
694
695        // 2014-05-12 - fix problem with URLs starting with a ./ or ../ ... they seem to need the current IDs root
696        if ( preg_match("#^..?/#", $DATA[2])) {
697            $DATA[2] = getNS($currentID) . ':' . $DATA[2];
698        }
699
700        // 2010-08-25 - fix problem with relative movement in links ( "test/../test2" )
701        $tmpData2 = '';
702        while( $tmpData2 != $DATA[2] ) {
703            $tmpData2 = $DATA[2];
704            $DATA[2] = preg_replace("#/(?!\.\.)[^\/]*?/\.\./#", '/', $DATA[2]);
705        }
706
707        $temp = preg_replace("%^" . DOKU_BASE . "%", "", $DATA[2]);
708        if ( $temp != $DATA[2] ) {
709            $DATA[2] = $temp;
710            $hadBase = true; // 2010-08-23 Check if there has been a rewrite here that will have to be considered later on
711        }
712
713        $this->functions->debug->message("URL before rewriting option for others than 1", array($DATA, $PARAMS, $hadBase), 1);
714
715        // Handle rewrites other than 1 - just for non-lib-files
716        // if ( !preg_match('$^/?lib/$', $DATA[2]) ) {
717        if ( !preg_match('$^(' . DOKU_BASE . ')?lib/$', $DATA[2]) ) {
718		    $this->functions->debug->message("Did not match '$^(" . DOKU_BASE . ")?lib/$' userewrite == {$conf['userewrite']}", null, 2);
719            if ( $conf['userewrite'] == 2 ) {
720                $DATA[2] = $this->__getInternalRewriteURL($DATA[2]);
721            } elseif ( $conf['userewrite'] == 0 ) {
722                $this->__getParamsAndDataRewritten($DATA, $PARAMS);
723            }
724        } else {
725	    	$this->functions->debug->message("This file must be inside lib ...", null, 2);
726        }
727
728        $this->functions->debug->message("URL before rewriting option", array($DATA, $PARAMS), 2);
729
730        $ORIGDATA2 = $DATA;
731        //        $ORIGDATA2 = $DATA[2]; // 08/10/2010 - this line required a $this->functions->wl which may mess up with the base URL
732        $this->functions->debug->message("OrigDATA is:", $ORIGDATA2, 1);
733
734        // Generate ID
735        $DATA[2] = str_replace('/', ':', $DATA[2]);
736
737        // If Data was empty this must be the same file!;
738        if ( empty( $DATA[2] ) ) {
739            $DATA[2] = $currentID;
740        }
741
742        $ID = $DATA[2];
743        $MEDIAMATCHER = "#(_media(/|:)|media=|_detail(/|:)|_export(/|:)|do=export_)#i"; // 2010-10-23 added "(/|:)" for the ID may not contain slashes anymore
744        $ID = $this->functions->cleanID($DATA[2], null, preg_match($MEDIAMATCHER, $DATA[2]) );
745        //        $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media') ); // Export anpassung nun weiter unten
746
747        //        $IDexists = page_exists($ID); // 08/10/2010 - Not needed. This will be done in the next block.
748        //        $this->functions->debug->message("Current ID: '$ID' exists: '" . ($IDexists ? 'true' : 'false') . "' (will be set to 'false' anyway)", null, 1);
749
750        $IDifIDnotExists = $ID; // 08/10/2010 - Save ID - with possible upper cases to preserve them
751        $IDexists = false;
752
753        $this->functions->debug->message("Resolving ID: '$ID'", null, 2);
754        if ( preg_match($MEDIAMATCHER, $DATA[2]) ) {
755            resolve_mediaid(null, $ID, $IDexists);
756
757            $this->functions->debug->message("Current mediaID to filename: '" . mediaFN($ID) . "'", null, 2);
758        } else {
759            resolve_pageid(null, $ID, $IDexists);
760            $this->functions->debug->message("Current ID to filename: '" . wikiFN($ID) . "'", null, 2);
761        }
762
763        $this->functions->debug->message("Current ID after resolvement: '$ID' the ID does exist: '" . ($IDexists ? 'true' : 'false') . "'", null, 2);
764        //        $ORIGDATA2 = @parse_url($this->functions->wl($ORIGDATA2, null, true)); // What was the next 2 line for? It did mess up with links from {{jdoc>}}
765        //        $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
766
767        // 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!
768        if ( !$IDexists ) {
769            $ID = $IDifIDnotExists; // there may have been presevered Upper cases. We will need them!
770        }
771
772        // $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media') || strstr($DATA[2], 'export') );
773        if ( substr($ID, -1) == ':' || empty($ID) ) $ID .= $conf['start'];
774
775        // Generate Download URL
776        // $PARAMS = trim(str_replace('&amp;', '&', $PARAMS));
777        $PARAMS = trim($PARAMS);
778        $this->functions->removeWikiVariables($PARAMS, false, true);
779
780        $url = $this->functions->wl($ID, null, true, null, null, true, $hadBase) . ( !empty( $ANCHOR) ? '#' . $ANCHOR : '' ) . ( !empty( $PARAMS) ? '?' . $PARAMS : '' );
781        $this->functions->debug->message("URL from ID: '$url'", null, 2);
782
783        // Parse URI PATH and add "html"
784        $uri = @parse_url($url);
785        $DATA[2] = $uri['path'];
786        $DATA['ANCHOR'] = $ANCHOR;
787        $DATA['PARAMS'] = $PARAMS;
788
789        $this->functions->debug->message("DATA after parsing.", $DATA, 2);
790
791        // Second Rewrite for UseRewrite = 2
792        if ( $conf['userewrite'] == 2 ) {
793            $DATA[2] = preg_replace( '$/lib/.*?fetch\.php$', '', $DATA[2]);
794            $DATA[2] = preg_replace( '%(/lib/.*?detail\.php.*$)%', '\1' . '.' . $this->functions->settings->fileType, $DATA[2]);
795
796            if ( preg_match( '%/(lib/.*?detail|doku)\.php%', $DATA[2])) {
797                $noDeepReplace = false;
798                $fileName = $this->functions->getSiteName($ID);
799                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
800            }
801
802            $this->functions->debug->message("DATA after second rewrite with UseRewrite = 2", array($DATA, $noDeepReplace, $fileName, $newDepth), 1);
803        }
804
805        switch ( array_pop(explode('/', $DATA[2])) ) {
806            // CSS Extra Handling with extra rewrites
807            case 'css.php'	:	// $DATA[2] .=  ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS))) . '.css';
808                $DATA[2] .=  '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS)) . '.css'; // allways put parameters behind
809                // No paramters needed since they are rewritten.
810                $DATA['PARAMS'] = "";
811                $noDeepReplace = false;
812                $fileName = $this->functions->getSiteName($ID);
813                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
814                $newAdditionalParameters['do'] = 'siteexport';
815
816                $this->functions->debug->message("This is CSS file", array($DATA, $noDeepReplace, $fileName, $newDepth, $newAdditionalParameters), 2);
817
818                break;
819            case 'js.php'	:	// $DATA[2] .= ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS))) . '.js';
820                $DATA[2] .=  '.t.' . $this->functions->cleanID($_REQUEST['template']) . '.js'; // allways put parameters behind
821                // set Template
822                if ( !empty( $_REQUEST['template'] ) ) {
823                    $url .= ( strstr($url, '?') ? '&' : '?' ) . 'template=' . $_REQUEST['template'];
824                }
825                // No paramters needed since they are rewritten.
826                $DATA['PARAMS'] = "";
827                $newAdditionalParameters['do'] = 'siteexport';
828
829                $this->functions->debug->message("This is JS file", array($DATA, $url, $fileName, $newAdditionalParameters), 2);
830
831                break;
832                // Detail Handling with extra Rewrites if Paramaters are available - otherwise this is just the fetch
833            case 'indexer.php' :
834                $this->functions->debug->message("Skipping indexer", null, 2);
835                return "";
836                break;
837            case 'detail.php' :
838                $fileName = $this->functions->getSiteName($ID, true); // 2010-09-03 - rewrite with override enabled
839                $noDeepReplace = true;
840
841                $this->__getParamsAndDataRewritten($DATA, $PARAMS, 'id');
842                $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'id'));
843
844                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
845                $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
846                $DATA[2] .= '.' . array_pop(explode('/', $fileName));
847
848                $this->functions->debug->message("This is detail.php file with addParams", array($DATA, $ID, $fileName, $newDepth, $newAdditionalParameters), 2);
849                break;
850            case 'doku.php' :
851
852                $noDeepReplace = false;
853                $this->__getParamsAndDataRewritten($DATA, $PARAMS, 'id');
854                $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'id'));
855
856                $this->functions->debug->message("Current ID to filename (doku.php): '" . wikiFN($ID) . "'", null, 2);
857
858                $fileName = $this->functions->getSiteName($ID); // 2010-09-03 - rewrite with override enabled
859
860                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
861                $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
862                $DATA[2] .= '.' . array_pop(explode('/', $fileName));
863
864                $this->functions->debug->message("This is doku.php file with addParams", array($DATA, $ID, $fileName, $newDepth, $newAdditionalParameters), 2);
865                return $this->__rebuildLink($DATA);
866                break;
867
868                // Fetch Handling for media - rewriting everything
869            case 'fetch.php':
870                $this->__getParamsAndDataRewritten($DATA, $PARAMS, 'media');
871
872                $DATA[2] = str_replace('/', ':', $DATA[2]);
873                $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media'));
874                resolve_mediaid(null, $ID, $IDexists);
875
876                $DATA[2] = $this->functions->wl($ID, null, null, null, $IDexists, true);
877                $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
878
879                $DATA['PARAMS'] = "";
880                $newAdditionalParameters = array();
881
882                $this->functions->debug->message("This is fetch.php file", array($DATA, $ID, $PARAMS), 2);
883                break;
884
885                // default Handling for Pages
886            case 'feed.php':
887                return ""; // Ignore. Has no sense to export.
888                break;
889            default:
890                if ( preg_match("%" . DOKU_BASE . "_detail/%", $DATA[2]) ) {
891
892                    // GET ID Param from origdata2
893                    preg_match("#id=(.*?)(&|\")#i", $DATA[0], $backlinkID);
894                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
895
896                    $fileIDPart = isset($backlinkID[1]) && !empty($backlinkID[1]) ? $this->functions->cleanID(urldecode($backlinkID[1])) : 'detail';
897
898                    $DATA[2] .= '/' . $fileIDPart . '.' . $this->functions->settings->fileType; // add namespace and subpage for back button and add filetype
899
900                    $noDeepReplace = false;
901                    $fileName = $this->functions->shortenName($DATA[2]);
902                    $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
903                    $url .= ( strstr($url, '?') ? '&' : '?' ) . 'id=' . $fileIDPart; // add id-part to URL for backlinks
904
905                    $DATA['PARAMS'] = "";
906
907                    $this->functions->debug->message("This is something with '_detail' file", array($DATA, $backlinkID, $newDepth, $url), 2);
908                } else if ( preg_match("%" . DOKU_BASE . "_export/(.*?)/%", $DATA[2], $fileType) ) {
909
910                    // Fixes multiple codeblocks in one file
911                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
912
913                    // add the Params no matter what they are. This is export. We don't mess with other files
914                    // adding the "/" fixes the usage of multiple codeblocks in the same namespace
915                    $DATA[2] .= (empty( $PARAMS ) ? '' : '/' . $PARAMS) . '.'. $fileType[1];
916
917                    $DATA['PARAMS'] = "";
918                    $this->functions->debug->message("This is something with '_export' file", $DATA, 2);
919
920                } else if ( $IDexists ) { // 08/10/2010 - was page_exists($ID) - but this should do as well.
921                    // If this is a page ... skip it!
922                    $DATA[2] .= ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS)))  . '.' . $this->functions->settings->fileType;
923
924                    // 2012-06-15 originally has an absolute path ... we might need a relative one if not in our namespace
925                    $this->functions->debug->message("OK, this is to be absolute: " . (empty($_REQUEST['absolutePath'])?'false':'true'), null, 1);
926                    if ( empty($_REQUEST['absolutePath']) )
927                    {
928                        $DATA[2] = $this->functions->getRelativeURL($DATA[2], $currentID);
929                    }
930
931                    $DATA[2] = $this->functions->shortenName($DATA[2]);
932
933                    // If Parameters are to be included in the filename - they must not be added twice
934                    if ( $this->functions->settings->addParams ) $DATA['PARAMS'] = "";
935
936                    $this->functions->debug->message("This page really exists", $DATA, 1);
937
938                    return $this->__rebuildLink($DATA);
939                } else {
940                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS, true);
941                    $newAdditionalParameters = null; // 2014-06-27 - when using the "normal" files way we will not need any additional stuff.
942                    // This would make problems with e.g. ditaa plugin
943                }
944
945                unset($newAdditionalParameters['diPlu']);
946        }
947
948
949        $this->functions->debug->message("DATA after SWITCH CASE decision", array($DATA, $noDeepReplace, $fileName, $newDepth), 1);
950
951        if ( $this->filewriter->canDoPDF() ) {
952            $this->functions->addAdditionalParametersToURL($url, $newAdditionalParameters);
953            $DATA[2] = $url;
954            unset($DATA['PARAMS']);
955            $url = $this->__rebuildLink($DATA, '');
956
957            $this->functions->debug->message("Creating PDF with URL '$url'", null, 2);
958
959            return $url;
960        }
961
962        // Create Name to save the file at
963        $DATA[2] = str_replace(':', '_', $DATA[2]);
964        $DATA[2] = $this->functions->shortenName($DATA[2]);
965
966
967        // File already loaded?
968        // 2010-10-23 - changes in_array from DATA[2] to $url - to check real URLs, the DATA[2] file will be checked with fileExistsInZip
969        if ( in_array($url, array_keys($this->fileChecked)) ) {
970            $DATA[2] = $this->fileChecked[$url];
971            $this->functions->debug->message("File has been checked before.", array($DATA, $url), 2);
972            return $this->__rebuildLink($DATA);
973        }
974
975        // 2010-09-03 - second check if the file is in the ZIP already.
976        if ( $this->filewriter->fileExistsInZip($DATA[2]) ) {
977            $this->functions->debug->message("File with DATA exists in ZIP.", $DATA, 3);
978            return $this->__rebuildLink($DATA);
979        }
980
981        // 2010-10-23 - What if this is a fetch.php? than we produced an error.
982        //        $this->fileChecked[] = $DATA[2];
983
984        // get tempFile and save it
985        $origDepth = $this->functions->settings->depth;
986        $this->functions->settings->depth = $newDepth;
987
988        $tmpID = $currentID;
989        $tmpFile = false;
990
991        $this->functions->debug->message("Going to get the file", array($url, $noDeepReplace, $newAdditionalParameters), 2);
992        $tmpFile = $this->__getHTTPFile($url, $noDeepReplace, $newAdditionalParameters);
993        $this->functions->debug->message("The getHTTPFile result is still empty", $tmpFile === false ? 'YES' : 'NO', 2);
994
995        $currentID = $tmpID;
996        $this->functions->settings->depth = $origDepth; // 2010-09-03 - Reset depth at the very end
997
998        if ( $tmpFile === false ) {
999            // Keep an potentially extra link intact
1000
1001            $this->functions->debug->message("The fetched file '$url' is 'false'", null, 3);
1002            if ( $IDexists === false ) {
1003                $this->functions->debug->message("The file does not exist, fallback to ORIGDATA", $ORIGDATA2, 2);
1004                $DATA[2] = $this->functions->shortenName($ORIGDATA2[2]); // get Origdata Path
1005            }
1006
1007            $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
1008            $link = $this->__rebuildLink($DATA);
1009            $this->functions->debug->message("Final Link after empty file from '$url'", null, 2);
1010
1011            return $link;
1012        }
1013
1014        $this->functions->debug->message("The fetched file looks good.", $tmpFile, 1);
1015        $dirname = dirname($DATA[2]);
1016
1017        // If a Filename was given that does not comply to the original name, us this one!
1018        // 2014-02-28 But only if we are on PDF Mode. Does this produce any other Problems?
1019        if ( $this->filewriter->canDoPDF() && !empty($tmpFile[1]) && !strstr($DATA[2], $tmpFile[1]) ) {
1020			$DATA[2] = $dirname . '/' . $tmpFile[1];
1021        }
1022
1023        // Add to zip
1024        $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
1025
1026        $status = $this->filewriter->__addFileToZip($tmpFile[0], $DATA[2]);
1027        @unlink($tmpFile[0]);
1028
1029        $newURL = $this->__rebuildLink($DATA);
1030        $this->functions->debug->message("Returning final Link to document: '$newURL'", null, 2);
1031
1032        return $newURL;
1033    }
1034
1035    /**
1036     * build the new link to be put in place for the donwloaded site
1037     **/
1038    function __rebuildLink($DATA, $DEPTH = null) {
1039        global $currentID;
1040
1041        // depth is set, skip this one
1042        if ( is_null( $DEPTH ) ) $DEPTH = $this->functions->settings->depth;
1043        $DATA[2] .= ( !empty( $DATA['PARAMS']) && $this->functions->settings->addParams? '?' . $DATA['PARAMS'] : '' ) . ( !empty( $DATA['ANCHOR'] ) ? '#' . $DATA['ANCHOR'] : '' );
1044
1045        $intermediateURL = $DEPTH . $DATA[2];
1046
1047        // Check if the URL has a ../../something/somethingelse
1048        // and basically goes back to our current page or something in parallel
1049        // 1) remove all ../ at begining
1050        $checkURL = preg_replace("#^(\.\./)+#", '', $intermediateURL);
1051        if ( $checkURL != $intermediateURL ) {
1052
1053            // 2) check if the URLs next parts match the current ENS to all NS parts of the current ID
1054            // $this->functions->debug->message("Found ENS: '{$this->functions->settings->exportNamespace}', currentID: {$currentID}'", null, 2);
1055            $currentIDPart = preg_replace("#^{$this->functions->settings->exportNamespace}/#", "", str_replace(':', '/', getNS($currentID) . '/'));
1056
1057            $this->functions->debug->message("Found ../: '$checkURL' / currentIDPart: '{$currentIDPart}'", null, 2);
1058            if ( ($newURL = preg_replace("#^{$currentIDPart}#", "./", $checkURL)) != $checkURL ) {
1059            // 3) if so, remove these parts
1060                $intermediateURL = $newURL;
1061                $this->functions->debug->message("Found ./ URL: '$newURL'", null, 2);
1062            }
1063        }
1064
1065        $newURL = $DATA[1] == 'url' ? $DATA[1] . '(' . $intermediateURL . ')' : $DATA[1] . '="' . $intermediateURL . '"';
1066        $this->functions->debug->message("Re-created URL: '$newURL'", null, 2);
1067
1068        return $newURL;
1069    }
1070
1071
1072    /**
1073     * remove an old zip file
1074     **/
1075    function __removeOldZip( $FILENAMEID=null, $checkForMore=true ) {
1076        global $INFO;
1077        global $conf;
1078
1079        $returnValue = true;
1080
1081        if ( empty($FILENAMEID) ) {
1082            $FILENAMEID = $this->functions->settings->origZipFile;
1083        }
1084
1085        if ( !file_exists(mediaFN($FILENAMEID)) ) {
1086            $returnValue = true;
1087        } else {
1088
1089            require_once( DOKU_INC . 'inc/media.php');
1090            if ( !media_delete($FILENAMEID, $INFO['perm']) ) {
1091                $returnValue = false;
1092            }
1093        }
1094
1095        if ( $checkForMore ) {
1096            // Try to remove more files.
1097            $ns = getNS($FILENAMEID);
1098            $fn = $this->functions->getSpecialExportFileName(noNS($FILENAMEID), '.+');
1099
1100            $data = array();
1101            search($data, $conf['mediadir'], 'search_media', array('pattern' => "/$fn$/i"), $ns);
1102
1103            if ( count($data > 0) ) {
1104
1105                // 30 Minuten Cache Zeit
1106                $cache = $this->functions->settings->cachetime;
1107                foreach ( $data as $media ) {
1108
1109                    //decide if has to be deleted needed:
1110                    if( $media['mtime'] < time()-$cache) {
1111                        $this->__removeOldZip($media['id'], false);
1112                    }
1113                }
1114            }
1115
1116        }
1117
1118        return $returnValue;
1119    }
1120
1121    /**
1122     * if confrewrite is set to internal rewrite, use this function - taken from a DW renderer
1123     **/
1124    function __getInternalRewriteURL($url) {
1125        global $conf;
1126
1127        //construct page id from request URI
1128        if( $conf['userewrite'] != 2) { return $url; }
1129
1130        //get the script URL
1131        if($conf['basedir']) {
1132            $relpath = '';
1133            $script = $conf['basedir'].$relpath.basename($_SERVER['SCRIPT_FILENAME']);
1134        } elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
1135            $script = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
1136            $_SERVER['SCRIPT_FILENAME']);
1137            $script = '/'.$script;
1138        }else{
1139            $script = $_SERVER['SCRIPT_NAME'];
1140        }
1141
1142        //clean script and request (fixes a windows problem)
1143        $script  = preg_replace('/\/\/+/','/',$script);
1144        $request = preg_replace('/\/\/+/','/',$url);
1145
1146        //remove script URL and Querystring to gain the id
1147        if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){
1148            $id = preg_replace ('/\?.*/','',$match[1]);
1149        }
1150        $id = urldecode($id);
1151        //strip leading slashes
1152        $id = preg_replace('!^/+!','',$id);
1153
1154        return $id;
1155    }
1156
1157    /**
1158     * rewrite parameter calls
1159     **/
1160    function __getParamsAndDataRewritten(&$DATA, &$PARAMS, $IDKEY='id') {
1161
1162        $PARRAY = explode('&', str_replace('&amp;', '&', $PARAMS) );
1163        $PARAMS = array();
1164
1165        foreach ( $PARRAY as $item ) {
1166            list($key, $value) = explode('=', $item, 2);
1167            if ( empty($key) || empty($value) )
1168            continue;
1169
1170            if ( strtolower(trim($key)) == $IDKEY ) {
1171                $DATA[2] = preg_replace("%^" . DOKU_BASE . "%", "", $value);
1172                continue;
1173            }
1174
1175            $PARAMS[] = "$key=$value";
1176        }
1177
1178        $PARAMS = implode('&', $PARAMS);
1179    }
1180
1181    /**
1182     * rewrite detail.php calls
1183     **/
1184    function __rebuildDataForNormalFiles(&$DATA, &$PARAMS, $addHash=false) {
1185        $PARTS = explode('.', $DATA[2]);
1186        if ( count($PARTS) > 1 ) {
1187            $EXT = '.' . array_pop($PARTS);
1188        }
1189
1190        $internalParams = $PARAMS = preg_replace("/(=|\?|&amp;)/", ".", $PARAMS);
1191
1192        // add anyways - if on overridde
1193        if ( !$this->functions->settings->addParams && !empty($PARAMS) && $addHash ) {
1194            $internalParams = md5($PARAMS);
1195        } else if ( !$this->functions->settings->addParams ){
1196            $internalParams = null;
1197        }
1198
1199        $DATA[2] = implode('.', $PARTS) . ( empty($internalParams) ? '' : '.' . $this->functions->cleanID($internalParams)) . ( $EXT == '.php' ? '.' . $this->functions->settings->fileType : $EXT );
1200        $DATA[2] = preg_replace("/\.+/", ".", $DATA[2]);
1201        $this->functions->debug->message("Rebuilding Data for normal file.", $DATA[2], 1);
1202    }
1203
1204
1205
1206
1207    /*
1208     * Clean JS and CSS cache files
1209     */
1210    function cleanCacheFiles() {
1211
1212        $_SERVER['HTTP_HOST'] = preg_replace("/:?\d+$/", '', $_SERVER['HTTP_HOST']);
1213        $cache = getCacheName('scripts'.$_SERVER['HTTP_HOST'].'-siteexport-js-'.$_SERVER['SERVER_PORT'],'.js');
1214        $this->unlinkIfExists($cache);
1215
1216        $tpl = trim(preg_replace('/[^\w-]+/','',$_REQUEST['template']));
1217        if($tpl)
1218        {
1219            $tplinc = DOKU_INC.'lib/tpl/'.$tpl.'/';
1220            $tpldir = DOKU_BASE.'lib/tpl/'.$tpl.'/';
1221        } else {
1222            $tplinc = DOKU_TPLINC;
1223            $tpldir = DOKU_TPL;
1224        }
1225
1226        // The generated script depends on some dynamic options
1227        $cache = getCacheName('styles'.$_SERVER['HTTP_HOST'].'-siteexport-js-'.$_SERVER['SERVER_PORT'].DOKU_BASE.$tplinc.$style,'.css');
1228        $this->unlinkIfExists($cache);
1229    }
1230
1231    function unlinkIfExists($cache) {
1232        if ( file_exists($cache) ) {
1233            @unlink($cache);
1234            if(function_exists('gzopen')) @unlink("$cache.gz");
1235        }
1236    }
1237
1238    // Private unset function
1239    private function clear(&$variable)
1240    {
1241        if ( isset($variable) )
1242        {
1243            unset($variable);
1244        }
1245    }
1246}