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