xref: /plugin/siteexport/action/ajax.php (revision ccdae5380c7d613a043b75f581bf3a4adbb326c3)
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", $URL, 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        // plain/text; ...
639        $extension = array_shift(explode(';', $http->resp_headers['content-type'], 2));
640        $extension = explode('/', $extension, 2);
641        if ( $extension[0] == 'image' || $extension[1] == 'html' ) {
642            $extension = $extension[1];
643        } else {
644            unset($extension);
645        }
646
647        return array($tmpFile, preg_replace("/.*?filename=\"?(.*?)\"?;?$/", "$1", $http->resp_headers['content-disposition']), $extension);
648    }
649
650    /**
651     * Find internal links in the currently downloaded file. This also matches inside CSS files
652     **/
653    function __getInternalLinks(&$DATA) {
654
655        $PATTERN = '(href|src|action)="([^"]*)"';
656        $CALLBACK = array($this, '__fetchAndReplaceLink');
657        $DATA = preg_replace_callback("/$PATTERN/i", $CALLBACK, $DATA);
658
659        $PATTERNCSS = '(url\s*?)\(([^\)]*)\)';
660        $DATA = preg_replace_callback("/$PATTERNCSS/i", $CALLBACK, $DATA);
661    }
662
663    /**
664     * Deep Fetch and replace of links inside the texts matched by __getInternalLinks
665     **/
666    function __fetchAndReplaceLink($DATA) {
667        global $conf, $currentID, $currentParent;
668
669        $noDeepReplace = true;
670        $newAdditionalParameters = $this->functions->settings->additionalParameters;
671        $newDepth = $this->functions->settings->depth;
672        $hadBase = false;
673
674		// Clean data[2], remote ' and "
675		$DATA[2] = preg_replace("/^\s*?['\"]?(.*?)['\"]?\s*?$/", '\1', trim($DATA[2]));
676
677        $this->functions->debug->message("Starting Link Replacement", array( 'data' => $DATA, 'additional Params' => $newAdditionalParameters, 'newDepth' => $newDepth, 'currentID' => $currentID), 2);
678
679        // $DATA[2] = urldecode($DATA[2]); // Leads to problems because it does not re-encode the url
680        // External and mailto links
681        if ( preg_match("%^(https?://|mailto:|javascript:|data:)%", $DATA[2]) ) {
682            $this->functions->debug->message("Don't like http, mailto, data or javascript links here", null, 1);
683            return $this->__rebuildLink($DATA, "");
684        }
685        //if ( preg_match("%^(https?://|mailto:|" . DOKU_BASE . "/_export/)%", $DATA[2]) ) { return $this->__rebuildLink($DATA, ""); }
686        // External media - this is deep down in the link, so we have to grep it out
687        if ( preg_match("%media=(https?://.*?$)%", $DATA[2], $matches) ) {
688            $DATA[2] = $matches[1];
689            $this->functions->debug->message("This is an HTTP like somewhere else", $DATA, 1);
690            return $this->__rebuildLink($DATA, "");
691        }
692        // reference only links won't have to be rewritten
693        if ( preg_match("%^#.*?$%", $DATA[2]) ) {
694            $this->functions->debug->message("This is a refercence only", null, 1);
695            return $this->__rebuildLink($DATA, "");
696        }
697
698        // strip all things out
699        // changed Data
700        $PARAMS = @parse_url($DATA[2], PHP_URL_QUERY);
701        $ANCHOR = @parse_url($DATA[2], PHP_URL_FRAGMENT);
702        $DATA[2] = @parse_url($DATA[2], PHP_URL_PATH);
703
704        // 2014-05-12 - fix problem with URLs starting with a ./ or ../ ... they seem to need the current IDs root
705        if ( preg_match("#^\.\.?/#", $DATA[2])) {
706            $DATA[2] = getNS($currentID) . ':' . $DATA[2];
707        }
708
709        // 2010-08-25 - fix problem with relative movement in links ( "test/../test2" )
710        // 2014-06-30 - what? to what will this end relatively?
711        $tmpData2 = '';
712        while( $tmpData2 != $DATA[2] ) {
713            $tmpData2 = $DATA[2];
714            $DATA[2] = preg_replace("#/(?!\.\.)[^\/]*?/\.\./#", '/', $DATA[2]);
715        }
716
717        $temp = preg_replace("%^" . DOKU_BASE . "%", "", $DATA[2]);
718        if ( $temp != $DATA[2] ) {
719            $DATA[2] = $temp;
720            $hadBase = true; // 2010-08-23 Check if there has been a rewrite here that will have to be considered later on
721        }
722
723        $this->functions->debug->message("URL before rewriting option for others than 1", array($DATA, $PARAMS, $hadBase), 1);
724
725        // Handle rewrites other than 1 - just for non-lib-files
726        // if ( !preg_match('$^/?lib/$', $DATA[2]) ) {
727        if ( !preg_match('$^(' . DOKU_BASE . ')?lib/$', $DATA[2]) ) {
728		    $this->functions->debug->message("Did not match '$^(" . DOKU_BASE . ")?lib/$' userewrite == {$conf['userewrite']}", null, 2);
729            if ( $conf['userewrite'] == 2 ) {
730                $DATA[2] = $this->__getInternalRewriteURL($DATA[2]);
731            } elseif ( $conf['userewrite'] == 0 ) {
732                $this->__getParamsAndDataRewritten($DATA, $PARAMS);
733            }
734        } else {
735	    	$this->functions->debug->message("This file must be inside lib ...", null, 2);
736        }
737
738        $this->functions->debug->message("URL before rewriting option", array($DATA, $PARAMS), 2);
739
740        $ORIGDATA2 = $DATA;
741        //        $ORIGDATA2 = $DATA[2]; // 08/10/2010 - this line required a $this->functions->wl which may mess up with the base URL
742        $this->functions->debug->message("OrigDATA is:", $ORIGDATA2, 1);
743
744        // Generate ID
745        $DATA[2] = str_replace('/', ':', $DATA[2]);
746
747        // If Data was empty this must be the same file!;
748        if ( empty( $DATA[2] ) ) {
749            $DATA[2] = $currentID;
750        }
751
752        $ID = $DATA[2];
753        $MEDIAMATCHER = "#(_media(/|:)|media=|_detail(/|:)|_export(/|:)|do=export_)#i"; // 2010-10-23 added "(/|:)" for the ID may not contain slashes anymore
754        $ID = $this->functions->cleanID($DATA[2], null, preg_match($MEDIAMATCHER, $DATA[2]) );
755        //        $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media') ); // Export anpassung nun weiter unten
756
757        //        $IDexists = page_exists($ID); // 08/10/2010 - Not needed. This will be done in the next block.
758        //        $this->functions->debug->message("Current ID: '$ID' exists: '" . ($IDexists ? 'true' : 'false') . "' (will be set to 'false' anyway)", null, 1);
759
760        $IDifIDnotExists = $ID; // 08/10/2010 - Save ID - with possible upper cases to preserve them
761        $IDexists = false;
762
763        $this->functions->debug->message("Resolving ID: '$ID'", null, 2);
764        if ( preg_match($MEDIAMATCHER, $DATA[2]) ) {
765            resolve_mediaid(null, $ID, $IDexists);
766
767            $this->functions->debug->message("Current mediaID to filename: '" . mediaFN($ID) . "'", null, 2);
768        } else {
769            resolve_pageid(null, $ID, $IDexists);
770            $this->functions->debug->message("Current ID to filename: '" . wikiFN($ID) . "'", null, 2);
771        }
772
773        $this->functions->debug->message("Current ID after resolvement: '$ID' the ID does exist: '" . ($IDexists ? 'true' : 'false') . "'", null, 2);
774        //        $ORIGDATA2 = @parse_url($this->functions->wl($ORIGDATA2, null, true)); // What was the next 2 line for? It did mess up with links from {{jdoc>}}
775        //        $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
776
777        // 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!
778        if ( !$IDexists ) {
779            $ID = $IDifIDnotExists; // there may have been presevered Upper cases. We will need them!
780        }
781
782        // $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media') || strstr($DATA[2], 'export') );
783        if ( substr($ID, -1) == ':' || empty($ID) ) $ID .= $conf['start'];
784
785        // Generate Download URL
786        // $PARAMS = trim(str_replace('&amp;', '&', $PARAMS));
787        $PARAMS = trim($PARAMS);
788        $this->functions->removeWikiVariables($PARAMS, false, true);
789
790        $url = $this->functions->wl($ID, null, true, null, null, true, $hadBase) . ( !empty( $ANCHOR) ? '#' . $ANCHOR : '' ) . ( !empty( $PARAMS) ? '?' . $PARAMS : '' );
791        $this->functions->debug->message("URL from ID: '$url'", null, 2);
792
793        // Parse URI PATH and add "html"
794        $uri = @parse_url($url);
795        $DATA[2] = $uri['path'];
796        $DATA['ANCHOR'] = $ANCHOR;
797        $DATA['PARAMS'] = $PARAMS;
798
799        $this->functions->debug->message("DATA after parsing.", $DATA, 2);
800
801        // Second Rewrite for UseRewrite = 2
802        if ( $conf['userewrite'] == 2 ) {
803            $DATA[2] = preg_replace( '$/lib/.*?fetch\.php$', '', $DATA[2]);
804            $DATA[2] = preg_replace( '%(/lib/.*?detail\.php.*$)%', '\1' . '.' . $this->functions->settings->fileType, $DATA[2]);
805
806            if ( preg_match( '%/(lib/.*?detail|doku)\.php%', $DATA[2])) {
807                $noDeepReplace = false;
808                $fileName = $this->functions->getSiteName($ID);
809                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
810            }
811
812            $this->functions->debug->message("DATA after second rewrite with UseRewrite = 2", array($DATA, $noDeepReplace, $fileName, $newDepth), 1);
813        }
814
815        switch ( array_pop(explode('/', $DATA[2])) ) {
816            // CSS Extra Handling with extra rewrites
817            case 'css.php'	:	// $DATA[2] .=  ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS))) . '.css';
818                $DATA[2] .=  '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS)) . '.css'; // allways put parameters behind
819                // No paramters needed since they are rewritten.
820                $DATA['PARAMS'] = "";
821                $noDeepReplace = false;
822                $fileName = $this->functions->getSiteName($ID);
823
824                // NewDepth has to be relative to the css file itself ...
825                $newDepth = './' . str_repeat('../', count(explode(':', $fileName))-1); // it is an ID at this point.
826                $newAdditionalParameters['do'] = 'siteexport';
827
828                $this->functions->debug->message("This is CSS file", array($DATA, $noDeepReplace, $fileName, $newDepth, $newAdditionalParameters), 2);
829
830                break;
831            case 'js.php'	:	// $DATA[2] .= ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS))) . '.js';
832                $DATA[2] .=  '.t.' . $this->functions->cleanID($_REQUEST['template']) . '.js'; // allways put parameters behind
833                // set Template
834                if ( !empty( $_REQUEST['template'] ) ) {
835                    $url .= ( strstr($url, '?') ? '&' : '?' ) . 'template=' . $_REQUEST['template'];
836                }
837                // No paramters needed since they are rewritten.
838                $DATA['PARAMS'] = "";
839                $newAdditionalParameters['do'] = 'siteexport';
840
841                $this->functions->debug->message("This is JS file", array($DATA, $url, $fileName, $newAdditionalParameters), 2);
842
843                break;
844                // Detail Handling with extra Rewrites if Paramaters are available - otherwise this is just the fetch
845            case 'indexer.php' :
846                $this->functions->debug->message("Skipping indexer", null, 2);
847                return "";
848                break;
849            case 'detail.php' :
850                $fileName = $this->functions->getSiteName($ID, true); // 2010-09-03 - rewrite with override enabled
851                $noDeepReplace = true;
852
853                $this->__getParamsAndDataRewritten($DATA, $PARAMS, 'id');
854                $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'id'));
855
856                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
857                $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
858                $DATA[2] .= '.' . array_pop(explode('/', $fileName));
859
860                $this->functions->debug->message("This is detail.php file with addParams", array($DATA, $ID, $fileName, $newDepth, $newAdditionalParameters), 2);
861                break;
862            case 'doku.php' :
863
864                $noDeepReplace = false;
865                $this->__getParamsAndDataRewritten($DATA, $PARAMS, 'id');
866                $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'id'));
867
868                $this->functions->debug->message("Current ID to filename (doku.php): '" . wikiFN($ID) . "'", null, 2);
869
870                $fileName = $this->functions->getSiteName($ID); // 2010-09-03 - rewrite with override enabled
871
872                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
873                $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
874                $DATA[2] .= '.' . array_pop(explode('/', $fileName));
875
876                $this->functions->debug->message("This is doku.php file with addParams", array($DATA, $ID, $fileName, $newDepth, $newAdditionalParameters), 2);
877                return $this->__rebuildLink($DATA);
878                break;
879
880                // Fetch Handling for media - rewriting everything
881            case 'fetch.php':
882                $this->__getParamsAndDataRewritten($DATA, $PARAMS, 'media');
883
884                $DATA[2] = str_replace('/', ':', $DATA[2]);
885                $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media'));
886                resolve_mediaid(null, $ID, $IDexists);
887
888                $DATA[2] = $this->functions->wl($ID, null, null, null, $IDexists, true);
889                $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
890
891                $DATA['PARAMS'] = "";
892                $newAdditionalParameters = array();
893
894                $this->functions->debug->message("This is fetch.php file", array($DATA, $ID, $PARAMS), 2);
895                break;
896
897                // default Handling for Pages
898            case 'feed.php':
899                return ""; // Ignore. Has no sense to export.
900                break;
901            default:
902                if ( preg_match("%" . DOKU_BASE . "_detail/%", $DATA[2]) ) {
903
904                    // GET ID Param from origdata2
905                    preg_match("#id=(.*?)(&|\")#i", $DATA[0], $backlinkID);
906                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
907
908                    $fileIDPart = isset($backlinkID[1]) && !empty($backlinkID[1]) ? $this->functions->cleanID(urldecode($backlinkID[1])) : 'detail';
909
910                    $DATA[2] .= '/' . $fileIDPart . '.' . $this->functions->settings->fileType; // add namespace and subpage for back button and add filetype
911
912                    $noDeepReplace = false;
913                    $fileName = $this->functions->shortenName($DATA[2]);
914                    $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
915                    $url .= ( strstr($url, '?') ? '&' : '?' ) . 'id=' . $fileIDPart; // add id-part to URL for backlinks
916
917                    $DATA['PARAMS'] = "";
918
919                    $this->functions->debug->message("This is something with '_detail' file", array($DATA, $backlinkID, $newDepth, $url), 2);
920                } else if ( preg_match("%" . DOKU_BASE . "_export/(.*?)/%", $DATA[2], $fileType) ) {
921
922                    // Fixes multiple codeblocks in one file
923                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
924
925                    // add the Params no matter what they are. This is export. We don't mess with other files
926                    // adding the "/" fixes the usage of multiple codeblocks in the same namespace
927                    $DATA[2] .= (empty( $PARAMS ) ? '' : '/' . $PARAMS) . '.'. $fileType[1];
928
929                    $DATA['PARAMS'] = "";
930                    $this->functions->debug->message("This is something with '_export' file", $DATA, 2);
931
932                } else if ( $IDexists ) { // 08/10/2010 - was page_exists($ID) - but this should do as well.
933                    // If this is a page ... skip it!
934                    $DATA[2] .= ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS)))  . '.' . $this->functions->settings->fileType;
935
936                    // 2012-06-15 originally has an absolute path ... we might need a relative one if not in our namespace
937                    $this->functions->debug->message("OK, this is to be absolute: " . (empty($_REQUEST['absolutePath'])?'false':'true'), null, 1);
938                    if ( empty($_REQUEST['absolutePath']) )
939                    {
940                        $DATA[2] = $this->functions->getRelativeURL($DATA[2], $currentID);
941                    }
942
943                    $DATA[2] = $this->functions->shortenName($DATA[2]);
944
945                    // If Parameters are to be included in the filename - they must not be added twice
946                    if ( $this->functions->settings->addParams ) $DATA['PARAMS'] = "";
947
948                    $this->functions->debug->message("This page really exists", $DATA, 1);
949
950                    return $this->__rebuildLink($DATA);
951                } else {
952                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS, true);
953                    $newAdditionalParameters = null; // 2014-06-27 - when using the "normal" files way we will not need any additional stuff.
954                    // This would make problems with e.g. ditaa plugin
955                }
956
957                unset($newAdditionalParameters['diPlu']);
958        }
959
960
961        $this->functions->debug->message("DATA after SWITCH CASE decision", array($DATA, $noDeepReplace, $fileName, $newDepth), 1);
962
963        if ( $this->filewriter->canDoPDF() ) {
964            $this->functions->addAdditionalParametersToURL($url, $newAdditionalParameters);
965            $DATA[2] = $url;
966            unset($DATA['PARAMS']);
967            $url = $this->__rebuildLink($DATA, '');
968
969            $this->functions->debug->message("Creating PDF with URL '$url'", null, 2);
970
971            return $url;
972        }
973
974        // Create Name to save the file at
975        $DATA[2] = str_replace(':', '_', $DATA[2]);
976        $DATA[2] = $this->functions->shortenName($DATA[2]);
977
978
979        // File already loaded?
980        // 2010-10-23 - changes in_array from DATA[2] to $url - to check real URLs, the DATA[2] file will be checked with fileExistsInZip
981        if ( in_array($url, array_keys($this->fileChecked)) ) {
982            $DATA[2] = $this->fileChecked[$url];
983            $this->functions->debug->message("File has been checked before.", array($DATA, $url), 2);
984            return $this->__rebuildLink($DATA);
985        }
986
987        // 2010-09-03 - second check if the file is in the ZIP already.
988        if ( $this->filewriter->fileExistsInZip($DATA[2]) ) {
989            $this->functions->debug->message("File with DATA exists in ZIP.", $DATA, 3);
990            return $this->__rebuildLink($DATA);
991        }
992
993        // 2010-10-23 - What if this is a fetch.php? than we produced an error.
994        //        $this->fileChecked[] = $DATA[2];
995
996        // get tempFile and save it
997        $origDepth = $this->functions->settings->depth;
998        $this->functions->settings->depth = $newDepth;
999
1000        $tmpID = $currentID;
1001        $tmpParent = $currentParent;
1002        $tmpFile = false;
1003
1004        $currentParent = dirname($DATA[2]);
1005        $this->functions->debug->message("Going to get the file", array($url, $noDeepReplace, $newAdditionalParameters), 2);
1006        $tmpFile = $this->__getHTTPFile($url, $noDeepReplace, $newAdditionalParameters);
1007        $this->functions->debug->message("The getHTTPFile result is still empty", $tmpFile === false ? 'YES' : 'NO', 2);
1008
1009        $currentParent = $tmpParent;
1010        $currentID = $tmpID;
1011        $this->functions->settings->depth = $origDepth; // 2010-09-03 - Reset depth at the very end
1012
1013        if ( $tmpFile === false ) {
1014            // Keep an potentially extra link intact
1015
1016            $this->functions->debug->message("The fetched file '$url' is 'false'", null, 3);
1017            if ( $IDexists === false ) {
1018                $this->functions->debug->message("The file does not exist, fallback to ORIGDATA", $ORIGDATA2, 2);
1019                $DATA[2] = $this->functions->shortenName($ORIGDATA2[2]); // get Origdata Path
1020            }
1021
1022            $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
1023            $link = $this->__rebuildLink($DATA);
1024            $this->functions->debug->message("Final Link after empty file from '$url'", null, 2);
1025
1026            return $link;
1027        }
1028
1029        $this->functions->debug->message("The fetched file looks good.", $tmpFile, 1);
1030        $dirname = dirname($DATA[2]);
1031
1032        // If a Filename was given that does not comply to the original name, us this one!
1033        // 2014-02-28 But only if we are on PDF Mode. Does this produce any other Problems?
1034        if ( $this->filewriter->canDoPDF() && !empty($tmpFile[1]) && !strstr($DATA[2], $tmpFile[1]) ) {
1035			$DATA[2] = $dirname . '/' . $tmpFile[1];
1036        }
1037
1038        // Custom extension
1039        if ( !empty($tmpFile[2]) ) {
1040            $DATA[2] .= '.' . $tmpFile[2];
1041        }
1042
1043        // Add to zip
1044        $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
1045
1046        $status = $this->filewriter->__addFileToZip($tmpFile[0], $DATA[2]);
1047        @unlink($tmpFile[0]);
1048
1049        $newURL = $this->__rebuildLink($DATA);
1050        $this->functions->debug->message("Returning final Link to document: '$newURL'", null, 2);
1051
1052        return $newURL;
1053    }
1054
1055    /**
1056     * build the new link to be put in place for the donwloaded site
1057     **/
1058    function __rebuildLink($DATA, $DEPTH = null) {
1059        global $currentID, $currentParent;
1060
1061        // depth is set, skip this one
1062        if ( is_null( $DEPTH ) ) $DEPTH = $this->functions->settings->depth;
1063        $DATA[2] .= ( !empty( $DATA['PARAMS']) && $this->functions->settings->addParams? '?' . $DATA['PARAMS'] : '' ) . ( !empty( $DATA['ANCHOR'] ) ? '#' . $DATA['ANCHOR'] : '' );
1064
1065        $intermediateURL = $DEPTH . $DATA[2];
1066
1067        $this->functions->debug->message("currentID: '{$currentID}'; currentParent: '{$currentParent}'", null, 1);
1068
1069        if ( preg_match("#^(\.\./)+#", $intermediateURL) ) {
1070            // Experimental
1071            $intermediateURL = $this->functions->getRelativeURL($intermediateURL, $currentParent);
1072            $this->functions->debug->message("relative URL is: '{$relativeURL}'", null, 1);
1073        }
1074
1075/*
1076        // Check if the URL has a ../../something/somethingelse
1077        // and basically goes back to our current page or something in parallel
1078        // 1) remove all ../ at begining
1079
1080        $this->functions->debug->message("currentID: '{$currentID}'", null, 1);
1081        $checkURL = preg_replace("#^(\.\./)+#", '', $intermediateURL);
1082        if ( $checkURL != $intermediateURL ) {
1083            $this->functions->debug->message("Found ../: '$checkURL' / currentIDPart: '{$currentIDPart}'", null, 2);
1084
1085            // 2) check if the URLs next parts match the current ENS to all NS parts of the current ID
1086            // $this->functions->debug->message("Found ENS: '{$this->functions->settings->exportNamespace}', currentID: {$currentID}'", null, 2);
1087            $currentIDPart = preg_replace("#^{$this->functions->settings->exportNamespace}/#", "", str_replace(':', '/', getNS($currentID) . '/'));
1088
1089            if ( ($newURL = preg_replace("#^{$currentIDPart}#", "./", $checkURL)) != $checkURL ) {
1090                // 3) if so, remove these parts
1091                $intermediateURL = $newURL;
1092                $this->functions->debug->message("Found ./ URL: '$newURL'", null, 2);
1093            }
1094        }
1095*/
1096        $newURL = $DATA[1] == 'url' ? $DATA[1] . '(' . $intermediateURL . ')' : $DATA[1] . '="' . $intermediateURL . '"';
1097        $this->functions->debug->message("Re-created URL: '$newURL'", $DEPTH, 2);
1098
1099        return $newURL;
1100    }
1101
1102
1103    /**
1104     * remove an old zip file
1105     **/
1106    function __removeOldZip( $FILENAMEID=null, $checkForMore=true ) {
1107        global $INFO;
1108        global $conf;
1109
1110        $returnValue = true;
1111
1112        if ( empty($FILENAMEID) ) {
1113            $FILENAMEID = $this->functions->settings->origZipFile;
1114        }
1115
1116        if ( !file_exists(mediaFN($FILENAMEID)) ) {
1117            $returnValue = true;
1118        } else {
1119
1120            require_once( DOKU_INC . 'inc/media.php');
1121            if ( !media_delete($FILENAMEID, $INFO['perm']) ) {
1122                $returnValue = false;
1123            }
1124        }
1125
1126        if ( $checkForMore ) {
1127            // Try to remove more files.
1128            $ns = getNS($FILENAMEID);
1129            $fn = $this->functions->getSpecialExportFileName(noNS($FILENAMEID), '.+');
1130
1131            $data = array();
1132            search($data, $conf['mediadir'], 'search_media', array('pattern' => "/$fn$/i"), $ns);
1133
1134            if ( count($data > 0) ) {
1135
1136                // 30 Minuten Cache Zeit
1137                $cache = $this->functions->settings->cachetime;
1138                foreach ( $data as $media ) {
1139
1140                    //decide if has to be deleted needed:
1141                    if( $media['mtime'] < time()-$cache) {
1142                        $this->__removeOldZip($media['id'], false);
1143                    }
1144                }
1145            }
1146
1147        }
1148
1149        return $returnValue;
1150    }
1151
1152    /**
1153     * if confrewrite is set to internal rewrite, use this function - taken from a DW renderer
1154     **/
1155    function __getInternalRewriteURL($url) {
1156        global $conf;
1157
1158        //construct page id from request URI
1159        if( $conf['userewrite'] != 2) { return $url; }
1160
1161        //get the script URL
1162        if($conf['basedir']) {
1163            $relpath = '';
1164            $script = $conf['basedir'].$relpath.basename($_SERVER['SCRIPT_FILENAME']);
1165        } elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
1166            $script = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
1167            $_SERVER['SCRIPT_FILENAME']);
1168            $script = '/'.$script;
1169        }else{
1170            $script = $_SERVER['SCRIPT_NAME'];
1171        }
1172
1173        //clean script and request (fixes a windows problem)
1174        $script  = preg_replace('/\/\/+/','/',$script);
1175        $request = preg_replace('/\/\/+/','/',$url);
1176
1177        //remove script URL and Querystring to gain the id
1178        if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){
1179            $id = preg_replace ('/\?.*/','',$match[1]);
1180        }
1181        $id = urldecode($id);
1182        //strip leading slashes
1183        $id = preg_replace('!^/+!','',$id);
1184
1185        return $id;
1186    }
1187
1188    /**
1189     * rewrite parameter calls
1190     **/
1191    function __getParamsAndDataRewritten(&$DATA, &$PARAMS, $IDKEY='id') {
1192
1193        $PARRAY = explode('&', str_replace('&amp;', '&', $PARAMS) );
1194        $PARAMS = array();
1195
1196        foreach ( $PARRAY as $item ) {
1197            list($key, $value) = explode('=', $item, 2);
1198            if ( empty($key) || empty($value) )
1199            continue;
1200
1201            if ( strtolower(trim($key)) == $IDKEY ) {
1202                $DATA[2] = preg_replace("%^" . DOKU_BASE . "%", "", $value);
1203                continue;
1204            }
1205
1206            $PARAMS[] = "$key=$value";
1207        }
1208
1209        $PARAMS = implode('&', $PARAMS);
1210    }
1211
1212    /**
1213     * rewrite detail.php calls
1214     **/
1215    function __rebuildDataForNormalFiles(&$DATA, &$PARAMS, $addHash=false) {
1216        $PARTS = explode('.', $DATA[2]);
1217        if ( count($PARTS) > 1 ) {
1218            $EXT = '.' . array_pop($PARTS);
1219        }
1220
1221        $internalParams = $PARAMS = preg_replace("/(=|\?|&amp;)/", ".", $PARAMS);
1222
1223        // add anyways - if on overridde
1224        if ( !$this->functions->settings->addParams && !empty($PARAMS) && $addHash ) {
1225            $internalParams = md5($PARAMS);
1226        } else if ( !$this->functions->settings->addParams ){
1227            $internalParams = null;
1228        }
1229
1230        $DATA[2] = implode('.', $PARTS) . ( empty($internalParams) ? '' : '.' . $this->functions->cleanID($internalParams)) . ( $EXT == '.php' ? '.' . $this->functions->settings->fileType : $EXT );
1231        $DATA[2] = preg_replace("/\.+/", ".", $DATA[2]);
1232        $this->functions->debug->message("Rebuilding Data for normal file.", $DATA[2], 1);
1233    }
1234
1235
1236
1237
1238    /*
1239     * Clean JS and CSS cache files
1240     */
1241    function cleanCacheFiles() {
1242
1243        $_SERVER['HTTP_HOST'] = preg_replace("/:?\d+$/", '', $_SERVER['HTTP_HOST']);
1244        $cache = getCacheName('scripts'.$_SERVER['HTTP_HOST'].'-siteexport-js-'.$_SERVER['SERVER_PORT'],'.js');
1245        $this->unlinkIfExists($cache);
1246
1247        $tpl = trim(preg_replace('/[^\w-]+/','',$_REQUEST['template']));
1248        if($tpl)
1249        {
1250            $tplinc = DOKU_INC.'lib/tpl/'.$tpl.'/';
1251            $tpldir = DOKU_BASE.'lib/tpl/'.$tpl.'/';
1252        } else {
1253            $tplinc = DOKU_TPLINC;
1254            $tpldir = DOKU_TPL;
1255        }
1256
1257        // The generated script depends on some dynamic options
1258        $cache = getCacheName('styles'.$_SERVER['HTTP_HOST'].'-siteexport-js-'.$_SERVER['SERVER_PORT'].DOKU_BASE.$tplinc.$style,'.css');
1259        $this->unlinkIfExists($cache);
1260    }
1261
1262    function unlinkIfExists($cache) {
1263        if ( file_exists($cache) ) {
1264            @unlink($cache);
1265            if(function_exists('gzopen')) @unlink("$cache.gz");
1266        }
1267    }
1268
1269    // Private unset function
1270    private function clear(&$variable)
1271    {
1272        if ( isset($variable) )
1273        {
1274            unset($variable);
1275        }
1276    }
1277}