xref: /plugin/siteexport/action/ajax.php (revision 4b7d84d77ace6e94701379a80214814665f499a4)
17d101cc1SGerry Weißbach<?php
27d101cc1SGerry Weißbach/**
37d101cc1SGerry Weißbach * Site Export Plugin
47d101cc1SGerry Weißbach *
57d101cc1SGerry Weißbach * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
67d101cc1SGerry Weißbach * @author     i-net software <tools@inetsoftware.de>
77d101cc1SGerry Weißbach * @author     Gerry Weissbach <gweissbach@inetsoftware.de>
87d101cc1SGerry Weißbach */
97d101cc1SGerry Weißbach
107d101cc1SGerry Weißbach// must be run within Dokuwiki
117d101cc1SGerry Weißbachif(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../../../').'/');
127d101cc1SGerry Weißbachif(!defined('DOKU_PLUGIN')) {
137d101cc1SGerry Weißbach    // Just for sanity
147d101cc1SGerry Weißbach    require_once(DOKU_INC.'inc/plugin.php');
157d101cc1SGerry Weißbach    define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
167d101cc1SGerry Weißbach}
177d101cc1SGerry Weißbach
187d101cc1SGerry Weißbachrequire_once(DOKU_PLUGIN.'action.php');
197d101cc1SGerry Weißbachrequire_once(DOKU_INC.'/inc/search.php');
207d101cc1SGerry Weißbach
217d101cc1SGerry Weißbachrequire_once(DOKU_PLUGIN.'siteexport/inc/functions.php');
227d101cc1SGerry Weißbachrequire_once(DOKU_PLUGIN.'siteexport/inc/httpproxy.php');
237d101cc1SGerry Weißbachrequire_once(DOKU_PLUGIN.'siteexport/inc/filewriter.php');
247d101cc1SGerry Weißbachrequire_once(DOKU_PLUGIN.'siteexport/inc/toc.php');
257d101cc1SGerry Weißbachrequire_once(DOKU_PLUGIN.'siteexport/inc/javahelp.php');
267d101cc1SGerry Weißbach
277d101cc1SGerry Weißbachclass action_plugin_siteexport_ajax extends DokuWiki_Action_Plugin
287d101cc1SGerry Weißbach{
297d101cc1SGerry Weißbach    /**
307d101cc1SGerry Weißbach     * New internal variables for better structure
317d101cc1SGerry Weißbach     */
327d101cc1SGerry Weißbach    private $filewriter = null;
337d101cc1SGerry Weißbach    public $functions = null;
347d101cc1SGerry Weißbach
357d101cc1SGerry Weißbach    // List of files that have already been checked
367d101cc1SGerry Weißbach    private $fileChecked = array();
377d101cc1SGerry Weißbach
387d101cc1SGerry Weißbach    // Namespace of the page to export
397d101cc1SGerry Weißbach    private $namespace = '';
407d101cc1SGerry Weißbach
417d101cc1SGerry Weißbach    /**
427d101cc1SGerry Weißbach     * Register Plugin in DW
437d101cc1SGerry Weißbach     **/
447d101cc1SGerry Weißbach    function register(&$controller) {
457d101cc1SGerry Weißbach        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajax_siteexport_provider');
467d101cc1SGerry Weißbach        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'siteexport_action');
477d101cc1SGerry Weißbach    }
487d101cc1SGerry Weißbach
497d101cc1SGerry Weißbach    /**
507d101cc1SGerry Weißbach     * AJAX Provider - check what is going to be done
517d101cc1SGerry Weißbach     * @param $event
527d101cc1SGerry Weißbach     * @param $args
537d101cc1SGerry Weißbach     */
547d101cc1SGerry Weißbach    function ajax_siteexport_provider(&$event, $args) {
557d101cc1SGerry Weißbach
567d101cc1SGerry Weißbach        // If this is not a siteexport call, ignore it.
577d101cc1SGerry Weißbach        if ( !strstr($event->data, '__siteexport' ) )
587d101cc1SGerry Weißbach        {
597d101cc1SGerry Weißbach            return;
607d101cc1SGerry Weißbach        }
617d101cc1SGerry Weißbach
622270cdc5SGerry Weißbach        $this->__init_functions(true);
637d101cc1SGerry Weißbach
647d101cc1SGerry Weißbach        switch( $event->data ) {
657d101cc1SGerry Weißbach            case '__siteexport_getsitelist': $this->ajax_siteexport_getsitelist( $event ); break;
667d101cc1SGerry Weißbach            case '__siteexport_addsite': $this->ajax_siteexport_addsite( $event ); break;
677d101cc1SGerry Weißbach            case '__siteexport_generateurl': $this->ajax_siteexport_generateurl( $event ); break;
687d101cc1SGerry Weißbach        }
697d101cc1SGerry Weißbach    }
707d101cc1SGerry Weißbach
717d101cc1SGerry Weißbach    /**
727d101cc1SGerry Weißbach     * Export from a URL - action
737d101cc1SGerry Weißbach     * @param $event
747d101cc1SGerry Weißbach     */
757d101cc1SGerry Weißbach    function siteexport_action( &$event ) {
767d101cc1SGerry Weißbach        global $ID;
777d101cc1SGerry Weißbach
787d101cc1SGerry Weißbach        // Check if the 'do' was siteexport
797793901eSGerry Weißbach	    $command = is_array($event->data) ? array_shift(array_keys($event->data)) : $event->data;
80fd385364SGerry Weißbach        if ( $command != 'siteexport' ) { return false; }
81fd385364SGerry Weißbach		$event->data = act_clean($event->data);
82fd385364SGerry Weißbach
837d101cc1SGerry Weißbach        if ( headers_sent() ) {
847d101cc1SGerry Weißbach            msg("The siteexport function has to be called prior to any header output.", -1);
857d101cc1SGerry Weißbach        }
867d101cc1SGerry Weißbach
877d101cc1SGerry Weißbach        $this->__init_functions();
887d101cc1SGerry Weißbach
897d101cc1SGerry Weißbach        $this->functions->debug->message("========================================", null, 1);
907d101cc1SGerry Weißbach        $this->functions->debug->message("Starting export from URL call", null, 1);
918da901a0SGerry Weißbach        $this->functions->debug->message("----------------------------------------", null, 1);
927d101cc1SGerry Weißbach
937d101cc1SGerry Weißbach        $event->preventDefault();
947d101cc1SGerry Weißbach        $event->stopPropagation();
957d101cc1SGerry Weißbach
967d101cc1SGerry Weißbach        // Fake security Token if none given
977d101cc1SGerry Weißbach        if ( empty( $_REQUEST['sectok'] ) ) {
987d101cc1SGerry Weißbach            $_REQUEST['sectok'] = getSecurityToken();
997d101cc1SGerry Weißbach        }
1007d101cc1SGerry Weißbach
1017d101cc1SGerry Weißbach        // The timer will be used to do redirects if needed to prevent timeouts
1027d101cc1SGerry Weißbach        $starttimer = time();
1037d101cc1SGerry Weißbach        $timerdiff = $this->getConf('max_execution_time');
1047d101cc1SGerry Weißbach
1057d101cc1SGerry Weißbach        $data = $this->__get_siteexport_list_and_init_tocs($ID, !empty($_REQUEST['startcounter']));
1067d101cc1SGerry Weißbach
1077d101cc1SGerry Weißbach        if ( $data === false ) {
1087d101cc1SGerry Weißbach            header("HTTP/1.0 401 Unauthorized");
1097d101cc1SGerry Weißbach            print 'Unauthorized';
1107d101cc1SGerry Weißbach            exit;
1117d101cc1SGerry Weißbach        }
1127d101cc1SGerry Weißbach
1137d101cc1SGerry Weißbach        $counter = 0;
1147d101cc1SGerry Weißbach
1157d101cc1SGerry Weißbach        if ( count($data) == 0 && !$this->functions->settings->hasValidCacheFile ) {
1167d101cc1SGerry Weißbach            exit();
1177d101cc1SGerry Weißbach        }
1187d101cc1SGerry Weißbach
1197d101cc1SGerry Weißbach        foreach ( $data as $site ) {
1207d101cc1SGerry Weißbach
1217d101cc1SGerry Weißbach			if ( intval($site['exists']) == 1 || !isset($site['exists']) ) {
1227d101cc1SGerry Weißbach
1237d101cc1SGerry Weißbach	            // Skip over the amount of urls that have been exported already
1247d101cc1SGerry Weißbach	            if ( empty($_REQUEST['startcounter']) || $counter >= intval($_REQUEST['startcounter']) ) {
1257d101cc1SGerry Weißbach	                $status = $this->__siteexport_add_site($site['id']);
1268da901a0SGerry Weißbach
1278da901a0SGerry Weißbach			        if ( $status === false ) {
1288da901a0SGerry Weißbach				        $this->functions->debug->message("----------------------------------------", null, 1);
1298da901a0SGerry Weißbach				        $this->functions->debug->message("Errors during export from URL call", null, 1);
1308da901a0SGerry Weißbach				        $this->functions->debug->message("========================================", null, 1);
1318da901a0SGerry Weißbach						print $this->functions->debug->runtimeErrors;
1328da901a0SGerry Weißbach        			    exit(0); // We need to stop
1338da901a0SGerry Weißbach			        }
1347d101cc1SGerry Weißbach	            }
1357d101cc1SGerry Weißbach			}
1367d101cc1SGerry Weißbach
1377d101cc1SGerry Weißbach            $counter ++;
1387d101cc1SGerry Weißbach            if ( time() - $starttimer >= $timerdiff ) {
1397d101cc1SGerry Weißbach                $this->functions->debug->message("Will Redirect", null, 1);
1407d101cc1SGerry Weißbach                $this->handleRuntimeErrorOutput();
1417d101cc1SGerry Weißbach                $this->functions->startRedirctProcess($counter);
1427d101cc1SGerry Weißbach            }
1437d101cc1SGerry Weißbach        }
1447d101cc1SGerry Weißbach
1458da901a0SGerry Weißbach        $this->functions->debug->message("----------------------------------------", null, 1);
1467d101cc1SGerry Weißbach        $this->functions->debug->message("Finishing export from URL call", null, 1);
1477d101cc1SGerry Weißbach        $this->functions->debug->message("========================================", null, 1);
1487d101cc1SGerry Weißbach
1497d101cc1SGerry Weißbach        $this->cleanCacheFiles();
1507d101cc1SGerry Weißbach
1517d101cc1SGerry Weißbach        $URL = ml($this->functions->settings->origZipFile, array('cache' => 'nocache', 'siteexport' => $this->functions->settings->pattern, 'sectok' => getSecurityToken()), true, '&');
1527d101cc1SGerry Weißbach        $this->functions->debug->message("Redirecting to final file", $URL, 2);
1537d101cc1SGerry Weißbach
1547d101cc1SGerry Weißbach        $this->handleRuntimeErrorOutput();
1557d101cc1SGerry Weißbach        send_redirect($URL);
1567d101cc1SGerry Weißbach        exit(0); // Should not be reached, but anyways
1577d101cc1SGerry Weißbach    }
1587d101cc1SGerry Weißbach
1597d101cc1SGerry Weißbach    private function handleRuntimeErrorOutput()
1607d101cc1SGerry Weißbach    {
1617d101cc1SGerry Weißbach        if ( !empty($this->functions->debug->runtimeErrors) )
1627d101cc1SGerry Weißbach        {
1637d101cc1SGerry Weißbach            $this->filewriter->__moveDataToZip($this->functions->debug->runtimeErrors, '_runtime_error/' . time() . '.html');
1647d101cc1SGerry Weißbach        }
1657d101cc1SGerry Weißbach    }
1667d101cc1SGerry Weißbach
1672270cdc5SGerry Weißbach    public function __init_functions($isAJAX=false)
1687d101cc1SGerry Weißbach    {
1692270cdc5SGerry Weißbach        $this->functions = new siteexport_functions(true, $isAJAX);
1707d101cc1SGerry Weißbach        $this->filewriter = new siteexport_zipfilewriter($this->functions);
1717d101cc1SGerry Weißbach
1727d101cc1SGerry Weißbach        // Check for PDF Capabilities
1737d101cc1SGerry Weißbach        if ( $this->filewriter->canDoPDF() ) {
1747d101cc1SGerry Weißbach            $this->functions->settings->fileType = 'pdf';
1757d101cc1SGerry Weißbach        }
1767d101cc1SGerry Weißbach    }
1777d101cc1SGerry Weißbach
1787d101cc1SGerry Weißbach    /**
1797d101cc1SGerry Weißbach     * Prepares the generated URL for direct download access
1807d101cc1SGerry Weißbach     * Also gives back the parameters for this URL
1817d101cc1SGerry Weißbach     * @param $event init event of the ajax request
1827d101cc1SGerry Weißbach     */
1837d101cc1SGerry Weißbach    function ajax_siteexport_prepareURL_and_POSTData( &$event ) {
1847d101cc1SGerry Weißbach
1857d101cc1SGerry Weißbach        $event->preventDefault();
1867d101cc1SGerry Weißbach        $event->stopPropagation();
1877d101cc1SGerry Weißbach
1887d101cc1SGerry Weißbach        // Retrieve Information for download URL
189a609ae53SGerry Weißbach        $this->functions->debug->message("Prepared URL and POST from Request:", $_REQUEST, 2);
1907d101cc1SGerry Weißbach        $url = $this->functions->prepare_POSTData($_REQUEST);
1917d101cc1SGerry Weißbach        $combined = $this->functions->urlToPathAndParams($url);
1927d101cc1SGerry Weißbach        list($path, $query) = explode('?', $combined, 2);
1937d101cc1SGerry Weißbach        $return = array($url, $combined, $path, $query);
1947d101cc1SGerry Weißbach
1957d101cc1SGerry Weißbach        $this->functions->debug->message("Prepared URL and POST data:", $return, 2);
1967d101cc1SGerry Weißbach        return $return;
1977d101cc1SGerry Weißbach    }
1987d101cc1SGerry Weißbach
1997d101cc1SGerry Weißbach    /**
2007d101cc1SGerry Weißbach     * Executes a Cron Job Action
2017d101cc1SGerry Weißbach     * @param $event
2027d101cc1SGerry Weißbach     */
2037d101cc1SGerry Weißbach    function ajax_siteexport_cronaction( &$event )
2047d101cc1SGerry Weißbach    {
2057d101cc1SGerry Weißbach        $cronOverwriteExisting = intval($_REQUEST['cronOverwriteExisting']) == 1;
2067d101cc1SGerry Weißbach        list($url, $combined) = $this->ajax_siteexport_prepareURL_and_POSTData($event);
2077d101cc1SGerry Weißbach
2087d101cc1SGerry Weißbach        if ( !$function =& plugin_load('cron', 'siteexport' ) )
2097d101cc1SGerry Weißbach        {
2107d101cc1SGerry Weißbach            $this->functions->debug->message("Tried to do an action with siteexport/cron, but the cron plugin is missing.", null, 4);
2117d101cc1SGerry Weißbach        }
2127d101cc1SGerry Weißbach
2137d101cc1SGerry Weißbach        $status = null;
2147d101cc1SGerry Weißbach        switch( $event->data ) {
2157d101cc1SGerry Weißbach            case '__siteexport_savecron': $status = $function->saveCronDataWithParameters($combined, $cronOverwriteExisting); break;
2167d101cc1SGerry Weißbach            case '__siteexport_deletecron': $status = $function->deleteCronDataWithParameters($combined); break;
2177d101cc1SGerry Weißbach        }
2187d101cc1SGerry Weißbach
2197d101cc1SGerry Weißbach        if ( !empty($status) )
2207d101cc1SGerry Weißbach        {
2217d101cc1SGerry Weißbach            $this->functions->debug->message("Tried to do an action with siteexport/cron, but failed.", $status, 4);
2227d101cc1SGerry Weißbach        }
2237d101cc1SGerry Weißbach    }
2247d101cc1SGerry Weißbach
2257d101cc1SGerry Weißbach    /**
2267d101cc1SGerry Weißbach     * generate direct access URL
2277d101cc1SGerry Weißbach     **/
2287d101cc1SGerry Weißbach    function ajax_siteexport_generateurl( &$event ) {
2297d101cc1SGerry Weißbach
2307d101cc1SGerry Weißbach        list($url, $combined, $path, $POSTData) = $this->ajax_siteexport_prepareURL_and_POSTData($event);
2317d101cc1SGerry Weißbach
2327d101cc1SGerry Weißbach        // WGET Redirects - this is an option for wget only.
2337d101cc1SGerry Weißbach        // 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
2347d101cc1SGerry Weißbach        // Therefore we assume it takes about 5s for each page - that gives the freedom to have anough time for redirect.
2357d101cc1SGerry Weißbach        $maxRedirectNumber = ceil( ( count($this->__get_siteexport_list($NS, true)) * 5) / $this->getConf('max_execution_time') );
2367d101cc1SGerry Weißbach        $maxRedirect = $maxRedirectNumber > 0 ? '--max-redirect=' . ($maxRedirectNumber+3) . ' ' : '';
2377d101cc1SGerry Weißbach        $maxRedirs = $maxRedirectNumber > 0 ? '--max-redirs ' . ($maxRedirectNumber+3) . ' ' : '';
2387d101cc1SGerry Weißbach
2397d101cc1SGerry Weißbach        $this->functions->debug->message("Generating Direct Download URL", $url, 2);
2407d101cc1SGerry Weißbach
2417d101cc1SGerry Weißbach        // If there was a Runtime Exception
2427d101cc1SGerry Weißbach        if ( !$this->functions->debug->firstRE() ) {
2437d101cc1SGerry Weißbach            $this->functions->debug->message("There have been errors while generating the download URLs.", null, 4);
2447d101cc1SGerry Weißbach            return;
2457d101cc1SGerry Weißbach        }
2467d101cc1SGerry Weißbach
2477d101cc1SGerry Weißbach        echo $url;
2487d101cc1SGerry Weißbach        echo "\n";
2497d101cc1SGerry Weißbach        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';
2507d101cc1SGerry Weißbach        echo "\n";
2517d101cc1SGerry Weißbach        echo 'curl -L ' . $maxRedirs . '-o ' . array_pop(explode(":", ($this->getConf('zipfilename')))) . ' -d "' . $POSTData . '" ' . wl(cleanID($path), null, true) . ' --anyauth --user USER:PASSWD';
2527d101cc1SGerry Weißbach        echo "\n";
2537d101cc1SGerry Weißbach
2547d101cc1SGerry Weißbach        $this->functions->debug->message("Checking for Cron parameters: ", $combined, 1);
2557d101cc1SGerry Weißbach        if ( !$functions =& plugin_load('cron', 'siteexport' ) ||
2567d101cc1SGerry Weißbach        !$functions->hasCronJobForParameters($combined) ) {
2577d101cc1SGerry Weißbach            echo "false";
2587d101cc1SGerry Weißbach        } else
2597d101cc1SGerry Weißbach        {
2607d101cc1SGerry Weißbach            echo "true";
2617d101cc1SGerry Weißbach        }
2627d101cc1SGerry Weißbach
2637d101cc1SGerry Weißbach        return;
2647d101cc1SGerry Weißbach    }
2657d101cc1SGerry Weißbach
2667d101cc1SGerry Weißbach    /**
2677d101cc1SGerry Weißbach     * Get List of sites to be exported for AJAX (wrapper)
2687d101cc1SGerry Weißbach     **/
2697d101cc1SGerry Weißbach    function ajax_siteexport_getsitelist( &$event ) {
2707d101cc1SGerry Weißbach
2717d101cc1SGerry Weißbach        $event->preventDefault();
2727d101cc1SGerry Weißbach        $event->stopPropagation();
2737d101cc1SGerry Weißbach
2747d101cc1SGerry Weißbach        $data = $this->__get_siteexport_list_and_init_tocs($_REQUEST['ns']);
2757d101cc1SGerry Weißbach
2767d101cc1SGerry Weißbach        // Important for reconaisance of the session
2777d101cc1SGerry Weißbach
2787d101cc1SGerry Weißbach        if ( $data === false )
2797d101cc1SGerry Weißbach        {
2807d101cc1SGerry Weißbach            $this->functions->debug->runtimeException("No data generated. List of Files is 'false'.");
2817d101cc1SGerry Weißbach            return;
2827d101cc1SGerry Weißbach        }
2837d101cc1SGerry Weißbach
2847d101cc1SGerry Weißbach        if ( empty($data) && !$this->functions->settings->hasValidCacheFile )
2857d101cc1SGerry Weißbach        {
2867d101cc1SGerry Weißbach            $this->functions->debug->runtimeException("Generated list is empty.");
2877d101cc1SGerry Weißbach            return;
2887d101cc1SGerry Weißbach        }
2897d101cc1SGerry Weißbach
2907d101cc1SGerry Weißbach        // If there was a Runtime Exception
2917d101cc1SGerry Weißbach        if ( !$this->functions->debug->firstRE() )
2927d101cc1SGerry Weißbach        {
2937d101cc1SGerry Weißbach            $this->functions->debug->message("There have been errors while generating site list.", null, 4);
2947d101cc1SGerry Weißbach            return;
2957d101cc1SGerry Weißbach        }
2967d101cc1SGerry Weißbach
2977d101cc1SGerry Weißbach        echo "{$this->functions->settings->pattern}\n";
2987d101cc1SGerry Weißbach        echo $this->functions->downloadURL() . "\n";
2997d101cc1SGerry Weißbach        foreach($data as $line ){
3007d101cc1SGerry Weißbach            echo $line['id'] . "\n";
3017d101cc1SGerry Weißbach        }
3027d101cc1SGerry Weißbach
3037d101cc1SGerry Weißbach        return;
3047d101cc1SGerry Weißbach    }
3057d101cc1SGerry Weißbach
3067d101cc1SGerry Weißbach    /**
3077d101cc1SGerry Weißbach     * Add a page to the package (for AJAX calls - Wrapper)
3087d101cc1SGerry Weißbach     **/
3097d101cc1SGerry Weißbach    function ajax_siteexport_addsite( &$event ) {
3107d101cc1SGerry Weißbach
3117d101cc1SGerry Weißbach        $event->preventDefault();
3127d101cc1SGerry Weißbach        $event->stopPropagation();
3137d101cc1SGerry Weißbach
3147d101cc1SGerry Weißbach        $this->functions->debug->message("========================================", null, 1);
3157d101cc1SGerry Weißbach        $this->functions->debug->message("Starting export from AJAX call", null, 1);
3168da901a0SGerry Weißbach        $this->functions->debug->message("----------------------------------------", null, 1);
3177d101cc1SGerry Weißbach
3187d101cc1SGerry Weißbach        $status = $this->__siteexport_add_site($_REQUEST['site']);
3198da901a0SGerry Weißbach        if ( $status === false ) {
3208da901a0SGerry Weißbach	        $this->functions->debug->message("----------------------------------------", null, 1);
3218da901a0SGerry Weißbach	        $this->functions->debug->message("Errors during export from AJAX call", null, 1);
3228da901a0SGerry Weißbach	        $this->functions->debug->message("========================================", null, 1);
3238da901a0SGerry Weißbach        	return;
3248da901a0SGerry Weißbach        }
3257d101cc1SGerry Weißbach
3268da901a0SGerry Weißbach        $this->functions->debug->message("----------------------------------------", null, 1);
3277d101cc1SGerry Weißbach        $this->functions->debug->message("Finishing export from AJAX call", null, 1);
3287d101cc1SGerry Weißbach        $this->functions->debug->message("========================================", null, 1);
3297d101cc1SGerry Weißbach
3307d101cc1SGerry Weißbach        // Print the download zip-File
3317d101cc1SGerry Weißbach        $this->cleanCacheFiles();
3327d101cc1SGerry Weißbach
3337d101cc1SGerry Weißbach        // If there was a Runtime Exception
3347d101cc1SGerry Weißbach        if ( !$this->functions->debug->firstRE() ) {
3357d101cc1SGerry Weißbach            $this->functions->debug->message("There have been errors during the export.", null, 4);
3367d101cc1SGerry Weißbach            return;
3377d101cc1SGerry Weißbach        }
3387d101cc1SGerry Weißbach
3397d101cc1SGerry Weißbach        print $this->functions->downloadURL();
3407d101cc1SGerry Weißbach        return;
3417d101cc1SGerry Weißbach    }
3427d101cc1SGerry Weißbach
3437d101cc1SGerry Weißbach    /**
3447d101cc1SGerry Weißbach     * Fetch the list of pages to be exported
3457d101cc1SGerry Weißbach     **/
3467d101cc1SGerry Weißbach    function __get_siteexport_list($NS, $overrideCache=false) {
3477d101cc1SGerry Weißbach        global $conf;
3487d101cc1SGerry Weißbach
3497d101cc1SGerry Weißbach        $NS = $this->namespace = $this->functions->getNamespaceFromID($NS, $PAGE);
3507d101cc1SGerry Weißbach
3517d101cc1SGerry Weißbach        $depth = $this->getConf('depth');
3527d101cc1SGerry Weißbach        $query = '';
3537d101cc1SGerry Weißbach        $doSearch = 'search_allpages';
3547d101cc1SGerry Weißbach
3557d101cc1SGerry Weißbach        switch( intval($_REQUEST['depthType']) ) {
3567d101cc1SGerry Weißbach            case 0:
3577d101cc1SGerry Weißbach                $query = $this->functions->cleanID(str_replace(":", "/", $NS.':'.$PAGE));
3587d101cc1SGerry Weißbach                resolve_pageid($NS, $PAGE, $exists);
3597d101cc1SGerry Weißbach
3607d101cc1SGerry Weißbach                if ( $exists ) {
3617d101cc1SGerry Weißbach                    $data = array( array( 'id' => $PAGE) );
3627d101cc1SGerry Weißbach
3637d101cc1SGerry Weißbach                    $this->functions->debug->message("Checking for Cache", null, 2);
3647d101cc1SGerry Weißbach                    if ( !$overrideCache && $this->filewriter->hasValidCacheFile($_REQUEST, $data) )
3657d101cc1SGerry Weißbach                    {
3667d101cc1SGerry Weißbach                        return array();
3677d101cc1SGerry Weißbach                    }
3687d101cc1SGerry Weißbach
3697d101cc1SGerry Weißbach                    return $data;
3707d101cc1SGerry Weißbach                }
3717d101cc1SGerry Weißbach            case 1:	$depth = 0;
3727d101cc1SGerry Weißbach            break;
3737d101cc1SGerry Weißbach            case 2:	$depth = intval($_REQUEST['depth']);
3747d101cc1SGerry Weißbach            break;
3757d101cc1SGerry Weißbach        }
3767d101cc1SGerry Weißbach
3777d101cc1SGerry Weißbach        $opts = array( 'depth' => $depth, 'skipacl' => $this->getConf('skipacl'), 'query' => $query);
378a609ae53SGerry Weißbach        $this->functions->debug->message("Options", $opts, 2);
379a609ae53SGerry Weißbach
3807d101cc1SGerry Weißbach        $data = array();
3817d101cc1SGerry Weißbach        require_once (DOKU_INC.'inc/search.php');
3827d101cc1SGerry Weißbach
3837d101cc1SGerry Weißbach        // Check, which TOC to take
3847d101cc1SGerry Weißbach        if ( !$this->functions->settings->useTOCFile ) {
3857d101cc1SGerry Weißbach            search($data, $conf['datadir'], $doSearch, $opts, $this->namespace);
3867d101cc1SGerry Weißbach        } else {
3877d101cc1SGerry Weißbach            $this->functions->debug->message("Using TOC for data", null, 2);
3887d101cc1SGerry Weißbach
3897d101cc1SGerry Weißbach            $doSearch = 'search_pagename';
3907d101cc1SGerry Weißbach
3917d101cc1SGerry Weißbach            // Create Data of the TOC File should be used instead
3927d101cc1SGerry Weißbach            $opts['query'] = 'toc.txt';
3937d101cc1SGerry Weißbach
3947d101cc1SGerry Weißbach            $RAWdata = array();
3957d101cc1SGerry Weißbach            search($RAWdata, $conf['datadir'], $doSearch, $opts, $this->namespace);
3967d101cc1SGerry Weißbach
3977d101cc1SGerry Weißbach            // There may be more than one toc and all of them have to be merged.
3987d101cc1SGerry Weißbach            $data = array();
3997d101cc1SGerry Weißbach            foreach( $RAWdata as $entry )
4007d101cc1SGerry Weißbach            {
4017d101cc1SGerry Weißbach                $tmpData = p_get_metadata($entry['id'], 'sitetoc siteexportTOC', true);
4027d101cc1SGerry Weißbach
4037d101cc1SGerry Weißbach                if ( is_array($tmpData) )
4047d101cc1SGerry Weißbach                {
4057d101cc1SGerry Weißbach                    $data = array_merge($data, $tmpData);
4067d101cc1SGerry Weißbach                }
4077d101cc1SGerry Weißbach            }
4087d101cc1SGerry Weißbach        }
4097d101cc1SGerry Weißbach
4107d101cc1SGerry Weißbach        $this->functions->debug->message("Checking for Cache", null, 2);
4117d101cc1SGerry Weißbach        if ( !$overrideCache && $this->filewriter->hasValidCacheFile($_REQUEST, $data) )
4127d101cc1SGerry Weißbach        {
4137d101cc1SGerry Weißbach            return array();
4147d101cc1SGerry Weißbach        }
4157d101cc1SGerry Weißbach
4167d101cc1SGerry Weißbach        $this->functions->debug->message("Exporting the following sites: ", $data, 2);
4177d101cc1SGerry Weißbach        return $data;
4187d101cc1SGerry Weißbach    }
4197d101cc1SGerry Weißbach
4207d101cc1SGerry Weißbach    function __get_siteexport_list_and_init_tocs($NS, $isRedirected=false ) {
4217d101cc1SGerry Weißbach
4227d101cc1SGerry Weißbach        // Clean up if not redirected
4237d101cc1SGerry Weißbach        if ( !$isRedirected && !$this->__removeOldZip() ) {
4247d101cc1SGerry Weißbach            $this->functions->debug->runtimeException("Can't remove old files.");
4257d101cc1SGerry Weißbach            return false;
4267d101cc1SGerry Weißbach        }
4277d101cc1SGerry Weißbach
4287d101cc1SGerry Weißbach        $data = $this->__get_siteexport_list($NS, $isRedirected);
4297d101cc1SGerry Weißbach        if ( $isRedirected || empty($data) )
4307d101cc1SGerry Weißbach        {
4317d101cc1SGerry Weißbach            // if we have been redirected, simply return the data
4327d101cc1SGerry Weißbach            return $data;
4337d101cc1SGerry Weißbach        }
4347d101cc1SGerry Weißbach
4357d101cc1SGerry Weißbach        // Create Eclipse Documentation Pages - TOC.xml, Context.xml
4367d101cc1SGerry Weißbach        if ( !empty($_REQUEST['absolutePath']) ) $this->namespace = "";
4377d101cc1SGerry Weißbach//        $this->__removeOldZip( $this->functions->settings->eclipseZipFile );
4387d101cc1SGerry Weißbach
4397d101cc1SGerry Weißbach        if ( !empty($_REQUEST['eclipseDocZip']) )
4407d101cc1SGerry Weißbach        {
4417d101cc1SGerry Weißbach            $toc = new siteexport_toc($this->functions);
4427d101cc1SGerry Weißbach            $this->functions->debug->message("Generating eclipseDocZip", null, 2);
4437d101cc1SGerry Weißbach            $this->filewriter->__moveDataToZip($toc->__getTOCXML($data), 'toc.xml');
4447d101cc1SGerry Weißbach            $this->filewriter->__moveDataToZip($toc->__getContextXML($data), 'context.xml');
4457d101cc1SGerry Weißbach        } else  if ( !empty($_REQUEST['JavaHelpDocZip']) )
4467d101cc1SGerry Weißbach        {
4477d101cc1SGerry Weißbach            $toc = new siteexport_javahelp($this->functions, $this->filewriter);
4487d101cc1SGerry Weißbach            $toc->createTOCFiles($data);
4497d101cc1SGerry Weißbach
4507d101cc1SGerry Weißbach/*            $toc = new siteexport_toc($this->functions);
4517d101cc1SGerry Weißbach            list($tocData, $mapData) = $toc->__getJavaHelpTOCXML($data);
4527d101cc1SGerry Weißbach            $this->functions->debug->message("Generating JavaHelpDocZip", null, 2);
4537d101cc1SGerry Weißbach            $this->filewriter->__moveDataToZip($tocData, 'toc.xml');
4547d101cc1SGerry Weißbach            $this->filewriter->__moveDataToZip($mapData, 'map.xml');
4557d101cc1SGerry Weißbach*/        }
4567d101cc1SGerry Weißbach
4577d101cc1SGerry Weißbach        return $data;
4587d101cc1SGerry Weißbach    }
4597d101cc1SGerry Weißbach
4607d101cc1SGerry Weißbach    /**
4617d101cc1SGerry Weißbach     * Add page with ID to the package
4627d101cc1SGerry Weißbach     **/
4637d101cc1SGerry Weißbach    function __siteexport_add_site( $ID ) {
4647d101cc1SGerry Weißbach        global $conf, $currentID;
4657d101cc1SGerry Weißbach
4667d101cc1SGerry Weißbach        // Which is the current ID?
4677d101cc1SGerry Weißbach        $currentID = $ID;
4687d101cc1SGerry Weißbach
4697d101cc1SGerry Weißbach        $this->functions->debug->message("========================================", null, 2);
4707d101cc1SGerry Weißbach        $this->functions->debug->message("Adding Site: '$ID'", null, 2);
471*4b7d84d7SGerry Weißbach        $this->functions->debug->message("----------------------------------------", $_REQUEST, 2);
4727d101cc1SGerry Weißbach
4737d101cc1SGerry Weißbach        $request = $this->functions->settings->additionalParameters;
4747d101cc1SGerry Weißbach        unset($request['diPlu']); // This will not be needed for the first request.
4757d101cc1SGerry Weißbach        unset($request['diInv']); // This will not be needed for the first request.
4767d101cc1SGerry Weißbach
4777d101cc1SGerry Weißbach        // say, what to export and Build URL
4787d101cc1SGerry Weißbach        // 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
4797d101cc1SGerry Weißbach
4807d101cc1SGerry Weißbach        $do = (intval($_REQUEST['exportbody']) == 1 ? (empty($_REQUEST['renderer']) ? $conf['renderer_xhtml'] : $_REQUEST['renderer'] ) : '' );
4817d101cc1SGerry Weißbach
4827d101cc1SGerry Weißbach        if ($do == 'pdf' && $this->filewriter->canDoPDF() )
4837d101cc1SGerry Weißbach        {
4847d101cc1SGerry Weißbach            $do = 'export_siteexport_pdf';
4857d101cc1SGerry Weißbach            $_REQUEST['origRenderer'] = (empty($_REQUEST['renderer']) ? $conf['renderer_xhtml'] : $_REQUEST['renderer'] );
4867d101cc1SGerry Weißbach        }
4877d101cc1SGerry Weißbach
4887d101cc1SGerry Weißbach        $do = ($do == $conf['renderer_xhtml'] && intval($_REQUEST['exportbody']) != 1) ? '' : 'export_' . $do;
4897d101cc1SGerry Weißbach
4907d101cc1SGerry Weißbach        if ( $do != 'export_' && !empty($do) )
4917d101cc1SGerry Weißbach        {
4927d101cc1SGerry Weißbach            $request['do'] = $do;
4937d101cc1SGerry Weißbach        }
4947d101cc1SGerry Weißbach
4957d101cc1SGerry Weißbach        // set Template
4967d101cc1SGerry Weißbach        if ( !empty( $_REQUEST['template'] ) ) {
4977d101cc1SGerry Weißbach            $request['template'] = $_REQUEST['template'];
4987d101cc1SGerry Weißbach        }
4997d101cc1SGerry Weißbach
5007d101cc1SGerry Weißbach        $this->functions->debug->message("REQUEST for add_site:", $request, 2);
5017d101cc1SGerry Weißbach
5027d101cc1SGerry Weißbach        $ID = $this->functions->cleanID($ID);
5037d101cc1SGerry Weißbach        $url = $this->functions->wl($ID, $request, true, '&');
5047d101cc1SGerry Weißbach
5057d101cc1SGerry Weißbach        // Parse URI PATH and add "html"
5067d101cc1SGerry Weißbach        $fileName = $this->functions->getSiteName($ID, true);
5077d101cc1SGerry Weißbach
5087d101cc1SGerry Weißbach        $this->fileChecked[$url] = $fileName; // 2010-09-03 - One URL to one FileName
5097d101cc1SGerry Weißbach        $this->functions->settings->depth = str_repeat('../', count(explode('/', $fileName))-1);
5107d101cc1SGerry Weißbach
5117d101cc1SGerry Weißbach        // fetch URL and save it in temp file
5127d101cc1SGerry Weißbach        $tmpFile = $this->__getHTTPFile($url);
5137d101cc1SGerry Weißbach        if ( $tmpFile === false ) {
5148da901a0SGerry Weißbach        	// return $this->functions->debug->message("Creating temporary download file failed for '$url'. See log for more information.");
5158da901a0SGerry Weißbach        	$this->functions->debug->runtimeException("Creating temporary download file failed for '$url'. See log for more information.");
5168da901a0SGerry Weißbach        	return false;
5177d101cc1SGerry Weißbach        }
5187d101cc1SGerry Weißbach
519281ed919SGerry Weißbach        $dirname = dirname($fileName);
5207d101cc1SGerry Weißbach        // If a Filename was given that does not comply to the original name, use this one!
521281ed919SGerry Weißbach		if ( $this->filewriter->canDoPDF() ) {
5227d101cc1SGerry Weißbach
523281ed919SGerry Weißbach			$this->functions->debug->message("Will replace old filename '{$fileName}' with {$tmpFile[2]}", null, 1);
524281ed919SGerry Weißbach        	$extension = array_pop(explode('.', $fileName));
525281ed919SGerry Weißbach			$fileName = $dirname . '/' .  $this->functions->getSiteTitle($ID) . '.' . $extension;
526281ed919SGerry Weißbach			$this->fileChecked[$url] = $fileName;
527281ed919SGerry Weißbach        } else if ( !empty($tmpFile[1]) && !strstr($DATA[2], $tmpFile[1]) ) {
5287d101cc1SGerry Weißbach
529281ed919SGerry Weißbach			$this->functions->debug->message("Will replace old filename '{$fileName}' with {$tmpFile[1]}", null, 1);
530281ed919SGerry Weißbach			$fileName = $dirname . '/' . $tmpFile[1];
5317d101cc1SGerry Weißbach			$this->fileChecked[$url] = $fileName;
5327d101cc1SGerry Weißbach        }
5337d101cc1SGerry Weißbach
5347d101cc1SGerry Weißbach        // Add to zip
5357d101cc1SGerry Weißbach        $status = $this->filewriter->__addFileToZip($tmpFile[0], $fileName);
5367d101cc1SGerry Weißbach        @unlink($tmpFile[0]);
5377d101cc1SGerry Weißbach
5387d101cc1SGerry Weißbach        return $status;
5397d101cc1SGerry Weißbach    }
5407d101cc1SGerry Weißbach
541d3cbbad8SGerry Weißbach    function __preg_quote($input) {
542d3cbbad8SGerry Weißbach	    return preg_quote($input, '/');
543d3cbbad8SGerry Weißbach    }
544d3cbbad8SGerry Weißbach
5457d101cc1SGerry Weißbach    /**
5467d101cc1SGerry Weißbach     * Download the file via HTTP URL + recurse if this is not an image
5477d101cc1SGerry Weißbach     * The file will be saved as temporary file. The filename is the result.
5487d101cc1SGerry Weißbach     **/
5497d101cc1SGerry Weißbach    function __getHTTPFile($URL, $RECURSE=false, $newAdditionalParameters=null) {
5507d101cc1SGerry Weißbach        global $conf;
5517d101cc1SGerry Weißbach
552d3cbbad8SGerry Weißbach        $EXCLUDE = $this->getConf('exclude');
553d3cbbad8SGerry Weißbach        if ( !empty($EXCLUDE) ) {
554d3cbbad8SGerry Weißbach	        $PATTERN = "/(" . implode('|', explode(' ', preg_quote($EXCLUDE, '/'))) . ")/i";
5557d101cc1SGerry Weißbach
556d3cbbad8SGerry Weißbach	        $this->functions->debug->message("Checking for exclude: ", array(
557d3cbbad8SGerry Weißbach	        	"pattern" => $PATTERN,
558d3cbbad8SGerry Weißbach	        	"file" => $URL,
559d3cbbad8SGerry Weißbach	        	"matches" => preg_match($PATTERN, $URL) ? 'match' : 'no match'
560d3cbbad8SGerry Weißbach	        ), 2);
561d3cbbad8SGerry Weißbach
562d3cbbad8SGerry Weißbach			if ( preg_match($PATTERN, $URL) ) { return false; }
563d3cbbad8SGerry Weißbach        }
5647d101cc1SGerry Weißbach
5657d101cc1SGerry Weißbach        require_once( DOKU_INC . 'inc/HTTPClient.php');
5667d101cc1SGerry Weißbach
5678da901a0SGerry Weißbach        $http = new HTTPProxy($this->functions->debug, $this->functions->settings);
5687d101cc1SGerry Weißbach        $http->max_bodysize = $conf['fetchsize'];
5697d101cc1SGerry Weißbach        // $http->user = $_SERVER['PHP_AUTH_USER']; // Must not be set, or the files will be authenticated and have the edit thingies
5707d101cc1SGerry Weißbach        // $http->pass = $_SERVER['PHP_AUTH_PW']; // Must not be set, or the files will be authenticated and have the edit thingies
5717d101cc1SGerry Weißbach
5727d101cc1SGerry Weißbach        // Add additional Params
5737d101cc1SGerry Weißbach        $this->functions->addAdditionalParametersToURL($URL, $newAdditionalParameters);
5747d101cc1SGerry Weißbach
5757d101cc1SGerry Weißbach        $this->functions->debug->message("Fetching URL: '$URL'", null, 2);
5767d101cc1SGerry Weißbach        $getData = $http->get($URL);
5777d101cc1SGerry Weißbach
5787d101cc1SGerry Weißbach        if( $getData === false ) {
579cb168401SGerry Weißbach
580cb168401SGerry Weißbach        	if ( $this->functions->settings->ignoreNon200 ) {
581cb168401SGerry Weißbach	        	return null;
582cb168401SGerry Weißbach        	}
583cb168401SGerry Weißbach
5847d101cc1SGerry Weißbach            $this->functions->debug->message("Sending request failed with error, HTTP status was '{$http->status}'.", $URL, 4);
5857d101cc1SGerry Weißbach            return false;
5867d101cc1SGerry Weißbach        }
5877d101cc1SGerry Weißbach
5887d101cc1SGerry Weißbach        if( empty($getData) ) {
5897d101cc1SGerry Weißbach            $this->functions->debug->message("No data fetched.", null , 4);
5907d101cc1SGerry Weißbach            return false;
5917d101cc1SGerry Weißbach        }
5927d101cc1SGerry Weißbach
5937d101cc1SGerry Weißbach        $tmpFile = tempnam($this->functions->settings->tmpDir , 'siteexport__');
5947d101cc1SGerry Weißbach        $this->functions->debug->message("Temporary filename", $tmpFile, 1);
5957d101cc1SGerry Weißbach
5967d101cc1SGerry Weißbach        $fp = fopen( $tmpFile, "w");
5977d101cc1SGerry Weißbach        if(!$fp) {
5987d101cc1SGerry Weißbach            $this->functions->debug->message("Can't open temporary File '$tmpFile'.", null , 4);
5997d101cc1SGerry Weißbach            return false;
6007d101cc1SGerry Weißbach        }
6017d101cc1SGerry Weißbach
602281ed919SGerry Weißbach        $this->functions->debug->message("Headers received", $http->resp_headers, 2);
603281ed919SGerry Weißbach
6047d101cc1SGerry Weißbach        if ( !$RECURSE ) {
6057d101cc1SGerry Weißbach            // Parse URI PATH and add "html"
6067d101cc1SGerry Weißbach            $this->functions->debug->message("========================================", null, 1);
6077d101cc1SGerry Weißbach            $this->functions->debug->message("Starting to recurse file '$URL'", null , 1);
6088da901a0SGerry Weißbach			$this->functions->debug->message("----------------------------------------", null, 1);
6097d101cc1SGerry Weißbach            $this->__getInternalLinks($getData);
6108da901a0SGerry Weißbach			$this->functions->debug->message("----------------------------------------", null, 1);
6117d101cc1SGerry Weißbach            $this->functions->debug->message("Finished to recurse file '$URL'", null , 1);
6127d101cc1SGerry Weißbach            $this->functions->debug->message("========================================", null, 1);
6137d101cc1SGerry Weißbach        }
6147d101cc1SGerry Weißbach
6157d101cc1SGerry Weißbach        fwrite($fp,$getData);
6167d101cc1SGerry Weißbach        fclose($fp);
6177d101cc1SGerry Weißbach
6187d101cc1SGerry Weißbach        return array($tmpFile, preg_replace("/.*?filename=\"?(.*?)\"?;?$/", "$1", $http->resp_headers['content-disposition']));
6197d101cc1SGerry Weißbach    }
6207d101cc1SGerry Weißbach
6217d101cc1SGerry Weißbach    /**
6227d101cc1SGerry Weißbach     * Find internal links in the currently downloaded file. This also matches inside CSS files
6237d101cc1SGerry Weißbach     **/
6247d101cc1SGerry Weißbach    function __getInternalLinks(&$DATA) {
6257d101cc1SGerry Weißbach
6267d101cc1SGerry Weißbach        $PATTERN = '(href|src|action)="([^"]*)"';
6277d101cc1SGerry Weißbach        $CALLBACK = array($this, '__fetchAndReplaceLink');
6287d101cc1SGerry Weißbach        $DATA = preg_replace_callback("/$PATTERN/i", $CALLBACK, $DATA);
6297d101cc1SGerry Weißbach
6300fc5c0e0SGerry Weißbach        $PATTERNCSS = '(url\s*?)\(([^\)]*)\)';
6317d101cc1SGerry Weißbach        $DATA = preg_replace_callback("/$PATTERNCSS/i", $CALLBACK, $DATA);
6327d101cc1SGerry Weißbach    }
6337d101cc1SGerry Weißbach
6347d101cc1SGerry Weißbach    /**
6357d101cc1SGerry Weißbach     * Deep Fetch and replace of links inside the texts matched by __getInternalLinks
6367d101cc1SGerry Weißbach     **/
6377d101cc1SGerry Weißbach    function __fetchAndReplaceLink($DATA) {
6387d101cc1SGerry Weißbach        global $conf, $currentID;
6397d101cc1SGerry Weißbach
6407d101cc1SGerry Weißbach        $noDeepReplace = true;
6417d101cc1SGerry Weißbach        $newAdditionalParameters = $this->functions->settings->additionalParameters;
6427d101cc1SGerry Weißbach        $newDepth = $this->functions->settings->depth;
6437d101cc1SGerry Weißbach        $hadBase = false;
6447d101cc1SGerry Weißbach
645d3cbbad8SGerry Weißbach		// Clean data[2], remote ' and "
646d3cbbad8SGerry Weißbach		$DATA[2] = preg_replace("/^\s*?['\"]?(.*?)['\"]?\s*?$/", '\1', trim($DATA[2]));
647d3cbbad8SGerry Weißbach
6487d101cc1SGerry Weißbach        $this->functions->debug->message("Starting Link Replacement", $DATA, 2);
6497d101cc1SGerry Weißbach
6507d101cc1SGerry Weißbach        // $DATA[2] = urldecode($DATA[2]); // Leads to problems because it does not re-encode the url
6517d101cc1SGerry Weißbach        // External and mailto links
6527d101cc1SGerry Weißbach        if ( preg_match("%^(https?://|mailto:|javascript:|data:)%", $DATA[2]) ) {
6537d101cc1SGerry Weißbach            $this->functions->debug->message("Don't like http, mailto, data or javascript links here", null, 1);
6547d101cc1SGerry Weißbach            return $this->__rebuildLink($DATA, "");
6557d101cc1SGerry Weißbach        }
6567d101cc1SGerry Weißbach        //if ( preg_match("%^(https?://|mailto:|" . DOKU_BASE . "/_export/)%", $DATA[2]) ) { return $this->__rebuildLink($DATA, ""); }
6577d101cc1SGerry Weißbach        // External media - this is deep down in the link, so we have to grep it out
6587d101cc1SGerry Weißbach        if ( preg_match("%media=(https?://.*?$)%", $DATA[2], $matches) ) {
6597d101cc1SGerry Weißbach            $DATA[2] = $matches[1];
6607d101cc1SGerry Weißbach            $this->functions->debug->message("This is an HTTP like somewhere else", $DATA, 1);
6617d101cc1SGerry Weißbach            return $this->__rebuildLink($DATA, "");
6627d101cc1SGerry Weißbach        }
6637d101cc1SGerry Weißbach        // reference only links won't have to be rewritten
6647d101cc1SGerry Weißbach        if ( preg_match("%^#.*?$%", $DATA[2]) ) {
6657d101cc1SGerry Weißbach            $this->functions->debug->message("This is a refercence only", null, 1);
6667d101cc1SGerry Weißbach            return $this->__rebuildLink($DATA, "");
6677d101cc1SGerry Weißbach        }
6687d101cc1SGerry Weißbach
6697d101cc1SGerry Weißbach        // strip all things out
6707d101cc1SGerry Weißbach        // changed Data
6717d101cc1SGerry Weißbach        $PARAMS = @parse_url($DATA[2], PHP_URL_QUERY);
6727d101cc1SGerry Weißbach        $ANCHOR = @parse_url($DATA[2], PHP_URL_FRAGMENT);
6737d101cc1SGerry Weißbach        $DATA[2] = @parse_url($DATA[2], PHP_URL_PATH);
6747d101cc1SGerry Weißbach
6757d101cc1SGerry Weißbach        // 2010-08-25 - fix problem with relative movement in links ( "test/../test2" )
6767d101cc1SGerry Weißbach        $tmpData2 = '';
6777d101cc1SGerry Weißbach        while( $tmpData2 != $DATA[2] ) {
6787d101cc1SGerry Weißbach            $tmpData2 = $DATA[2];
6797d101cc1SGerry Weißbach            $DATA[2] = preg_replace("#/(?!\.\.)[^\/]*?/\.\./#", '/', $DATA[2]);
6807d101cc1SGerry Weißbach        }
6817d101cc1SGerry Weißbach
6827d101cc1SGerry Weißbach        $temp = preg_replace("%^" . DOKU_BASE . "%", "", $DATA[2]);
6837d101cc1SGerry Weißbach        if ( $temp != $DATA[2] ) {
6847d101cc1SGerry Weißbach            $DATA[2] = $temp;
6857d101cc1SGerry Weißbach            $hadBase = true; // 2010-08-23 Check if there has been a rewrite here that will have to be considered later on
6867d101cc1SGerry Weißbach        }
6877d101cc1SGerry Weißbach
6887d101cc1SGerry Weißbach        $this->functions->debug->message("URL before rewriting option for others than 1", array($DATA, $PARAMS, $hadBase), 1);
6897d101cc1SGerry Weißbach
690d3cbbad8SGerry Weißbach        // Handle rewrites other than 1 - just for non-lib-files
691d3cbbad8SGerry Weißbach        // if ( !preg_match('$^/?lib/$', $DATA[2]) ) {
692d3cbbad8SGerry Weißbach        if ( !preg_match('$^(' . DOKU_BASE . ')?lib/$', $DATA[2]) ) {
693d3cbbad8SGerry Weißbach		    $this->functions->debug->message("Did not match '$^(" . DOKU_BASE . ")?lib/$' userewrite == ", $conf['userewrite'], 2);
6947d101cc1SGerry Weißbach            if ( $conf['userewrite'] == 2 ) {
6957d101cc1SGerry Weißbach                $DATA[2] = $this->__getInternalRewriteURL($DATA[2]);
6967d101cc1SGerry Weißbach            } elseif ( $conf['userewrite'] == 0 ) {
6977d101cc1SGerry Weißbach                $this->__getParamsAndDataRewritten($DATA, $PARAMS);
6987d101cc1SGerry Weißbach            }
6990fc5c0e0SGerry Weißbach        } else {
7000fc5c0e0SGerry Weißbach	    	$this->functions->debug->message("This file must be inside lib ...", null, 2);
7017d101cc1SGerry Weißbach        }
7027d101cc1SGerry Weißbach
7037d101cc1SGerry Weißbach        $this->functions->debug->message("URL before rewriting option", array($DATA, $PARAMS), 2);
7047d101cc1SGerry Weißbach
7057d101cc1SGerry Weißbach        $ORIGDATA2 = $DATA;
7067d101cc1SGerry Weißbach        //        $ORIGDATA2 = $DATA[2]; // 08/10/2010 - this line required a $this->functions->wl which may mess up with the base URL
7077d101cc1SGerry Weißbach        $this->functions->debug->message("OrigDATA is:", $ORIGDATA2, 1);
7087d101cc1SGerry Weißbach
7097d101cc1SGerry Weißbach        // Generate ID
7107d101cc1SGerry Weißbach        $DATA[2] = str_replace('/', ':', $DATA[2]);
7117d101cc1SGerry Weißbach
7127d101cc1SGerry Weißbach        // If Data was empty this must be the same file!;
7137d101cc1SGerry Weißbach        if ( empty( $DATA[2] ) ) {
7147d101cc1SGerry Weißbach            $DATA[2] = $currentID;
7157d101cc1SGerry Weißbach        }
7167d101cc1SGerry Weißbach
7177d101cc1SGerry Weißbach        $ID = $DATA[2];
7187d101cc1SGerry Weißbach        $MEDIAMATCHER = "#(_media(/|:)|media=|_detail(/|:)|_export(/|:)|do=export_)#i"; // 2010-10-23 added "(/|:)" for the ID may not contain slashes anymore
7197d101cc1SGerry Weißbach        $ID = $this->functions->cleanID($DATA[2], null, preg_match($MEDIAMATCHER, $DATA[2]) );
7207d101cc1SGerry Weißbach        //        $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media') ); // Export anpassung nun weiter unten
7217d101cc1SGerry Weißbach
7227d101cc1SGerry Weißbach        //        $IDexists = page_exists($ID); // 08/10/2010 - Not needed. This will be done in the next block.
7237d101cc1SGerry Weißbach        //        $this->functions->debug->message("Current ID: '$ID' exists: '" . ($IDexists ? 'true' : 'false') . "' (will be set to 'false' anyway)", null, 1);
7247d101cc1SGerry Weißbach
7257d101cc1SGerry Weißbach        $IDifIDnotExists = $ID; // 08/10/2010 - Save ID - with possible upper cases to preserve them
7267d101cc1SGerry Weißbach        $IDexists = false;
7277d101cc1SGerry Weißbach
7287d101cc1SGerry Weißbach        $this->functions->debug->message("Resolving ID: '$ID'", null, 2);
7297d101cc1SGerry Weißbach        if ( preg_match($MEDIAMATCHER, $DATA[2]) ) {
7307d101cc1SGerry Weißbach            resolve_mediaid(null, $ID, $IDexists);
7317d101cc1SGerry Weißbach
7327d101cc1SGerry Weißbach            $this->functions->debug->message("Current mediaID to filename: '" . mediaFN($ID) . "'", null, 2);
7337d101cc1SGerry Weißbach        } else {
7347d101cc1SGerry Weißbach            resolve_pageid(null, $ID, $IDexists);
7357d101cc1SGerry Weißbach            $this->functions->debug->message("Current ID to filename: '" . wikiFN($ID) . "'", null, 2);
7367d101cc1SGerry Weißbach        }
7377d101cc1SGerry Weißbach
7387d101cc1SGerry Weißbach        $this->functions->debug->message("Current ID after resolvement: '$ID' the ID does exist: '" . ($IDexists ? 'true' : 'false') . "'", null, 2);
7397d101cc1SGerry Weißbach        //        $ORIGDATA2 = @parse_url($this->functions->wl($ORIGDATA2, null, true)); // What was the next 2 line for? It did mess up with links from {{jdoc>}}
7407d101cc1SGerry Weißbach        //        $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
7417d101cc1SGerry Weißbach
7427d101cc1SGerry Weißbach        // 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!
7437d101cc1SGerry Weißbach        if ( !$IDexists ) {
7447d101cc1SGerry Weißbach            $ID = $IDifIDnotExists; // there may have been presevered Upper cases. We will need them!
7457d101cc1SGerry Weißbach        }
7467d101cc1SGerry Weißbach
7477d101cc1SGerry Weißbach        // $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media') || strstr($DATA[2], 'export') );
7487d101cc1SGerry Weißbach        if ( substr($ID, -1) == ':' || empty($ID) ) $ID .= $conf['start'];
7497d101cc1SGerry Weißbach
7507d101cc1SGerry Weißbach        // Generate Download URL
7517d101cc1SGerry Weißbach        // $PARAMS = trim(str_replace('&amp;', '&', $PARAMS));
7527d101cc1SGerry Weißbach        $PARAMS = trim($PARAMS);
7537d101cc1SGerry Weißbach        $this->functions->removeWikiVariables($PARAMS, false, true);
7547d101cc1SGerry Weißbach
7557d101cc1SGerry Weißbach        $url = $this->functions->wl($ID, null, true, null, null, true, $hadBase) . ( !empty( $ANCHOR) ? '#' . $ANCHOR : '' ) . ( !empty( $PARAMS) ? '?' . $PARAMS : '' );
7567d101cc1SGerry Weißbach        $this->functions->debug->message("URL from ID: '$url'", null, 2);
7577d101cc1SGerry Weißbach
7587d101cc1SGerry Weißbach        // Parse URI PATH and add "html"
7597d101cc1SGerry Weißbach        $uri = @parse_url($url);
7607d101cc1SGerry Weißbach        $DATA[2] = $uri['path'];
7617d101cc1SGerry Weißbach        $DATA['ANCHOR'] = $ANCHOR;
7627d101cc1SGerry Weißbach        $DATA['PARAMS'] = $PARAMS;
7637d101cc1SGerry Weißbach
7647d101cc1SGerry Weißbach        $this->functions->debug->message("DATA after parsing.", $DATA, 2);
7657d101cc1SGerry Weißbach
7667d101cc1SGerry Weißbach        // Second Rewrite for UseRewrite = 2
7677d101cc1SGerry Weißbach        if ( $conf['userewrite'] == 2 ) {
7687d101cc1SGerry Weißbach            $DATA[2] = preg_replace( '$/lib/.*?fetch\.php$', '', $DATA[2]);
7697d101cc1SGerry Weißbach            $DATA[2] = preg_replace( '%(/lib/.*?detail\.php.*$)%', '\1' . '.' . $this->functions->settings->fileType, $DATA[2]);
7707d101cc1SGerry Weißbach
7717d101cc1SGerry Weißbach            if ( preg_match( '%/(lib/.*?detail|doku)\.php%', $DATA[2])) {
7727d101cc1SGerry Weißbach                $noDeepReplace = false;
7737d101cc1SGerry Weißbach                $fileName = $this->functions->getSiteName($ID);
7747d101cc1SGerry Weißbach                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
7757d101cc1SGerry Weißbach            }
7767d101cc1SGerry Weißbach
7777d101cc1SGerry Weißbach            $this->functions->debug->message("DATA after second rewrite with UseRewrite = 2", array($DATA, $noDeepReplace, $fileName, $newDepth), 1);
7787d101cc1SGerry Weißbach        }
7797d101cc1SGerry Weißbach
7807d101cc1SGerry Weißbach        switch ( array_pop(explode('/', $DATA[2])) ) {
7817d101cc1SGerry Weißbach            // CSS Extra Handling with extra rewrites
7827d101cc1SGerry Weißbach            case 'css.php'	:	// $DATA[2] .=  ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS))) . '.css';
7837d101cc1SGerry Weißbach                $DATA[2] .=  '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS)) . '.css'; // allways put parameters behind
7847d101cc1SGerry Weißbach                // No paramters needed since they are rewritten.
7857d101cc1SGerry Weißbach                $DATA['PARAMS'] = "";
7867d101cc1SGerry Weißbach                $noDeepReplace = false;
7877d101cc1SGerry Weißbach                $fileName = $this->functions->getSiteName($ID);
7887d101cc1SGerry Weißbach                $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
7897d101cc1SGerry Weißbach                $newAdditionalParameters['do'] = 'siteexport';
7907d101cc1SGerry Weißbach
7917d101cc1SGerry Weißbach                $this->functions->debug->message("This is CSS file", array($DATA, $noDeepReplace, $fileName, $newDepth, $newAdditionalParameters), 2);
7927d101cc1SGerry Weißbach
7937d101cc1SGerry Weißbach                break;
7947d101cc1SGerry Weißbach            case 'js.php'	:	// $DATA[2] .= ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS))) . '.js';
7957d101cc1SGerry Weißbach                $DATA[2] .=  '.t.' . $this->functions->cleanID($_REQUEST['template']) . '.js'; // allways put parameters behind
7967d101cc1SGerry Weißbach                // set Template
7977d101cc1SGerry Weißbach                if ( !empty( $_REQUEST['template'] ) ) {
7987d101cc1SGerry Weißbach                    $url .= ( strstr($url, '?') ? '&' : '?' ) . 'template=' . $_REQUEST['template'];
7997d101cc1SGerry Weißbach                }
8007d101cc1SGerry Weißbach                // No paramters needed since they are rewritten.
8017d101cc1SGerry Weißbach                $DATA['PARAMS'] = "";
8027d101cc1SGerry Weißbach                $newAdditionalParameters['do'] = 'siteexport';
8037d101cc1SGerry Weißbach
8047d101cc1SGerry Weißbach                $this->functions->debug->message("This is JS file", array($DATA, $url, $fileName, $newAdditionalParameters), 2);
8057d101cc1SGerry Weißbach
8067d101cc1SGerry Weißbach                break;
8077d101cc1SGerry Weißbach                // Detail Handling with extra Rewrites if Paramaters are available - otherwise this is just the fetch
8087d101cc1SGerry Weißbach            case 'indexer.php' :
8097d101cc1SGerry Weißbach                $this->functions->debug->message("Skipping indexer", null, 2);
8107d101cc1SGerry Weißbach                return "";
8117d101cc1SGerry Weißbach                break;
8127d101cc1SGerry Weißbach            case 'detail.php' :
8137d101cc1SGerry Weißbach                $fileName = $this->functions->getSiteName($ID, true); // 2010-09-03 - rewrite with override enabled
8147d101cc1SGerry Weißbach            case 'doku.php' :
8157d101cc1SGerry Weißbach                if ( $this->functions->settings->addParams ) {
8167d101cc1SGerry Weißbach                    $noDeepReplace = false;
8177d101cc1SGerry Weißbach
8187d101cc1SGerry Weißbach                    if ( empty($fileName) ) {
8197d101cc1SGerry Weißbach                        $fileName = $this->functions->getSiteName($ID); // 2010-09-03 - rewrite with override enabled
8207d101cc1SGerry Weißbach                    }
8217d101cc1SGerry Weißbach
8227d101cc1SGerry Weißbach                    $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
8237d101cc1SGerry Weißbach                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
8247d101cc1SGerry Weißbach
8257d101cc1SGerry Weißbach                    $this->functions->debug->message("This is doku.php or detail.php file with addParams", array($DATA, $fileName, $newDepth, $newAdditionalParameters), 2);
8267d101cc1SGerry Weißbach                    break;
8277d101cc1SGerry Weißbach                }
8287d101cc1SGerry Weißbach
8297d101cc1SGerry Weißbach                $url = str_replace('detail.php', 'fetch.php', $url);
8307d101cc1SGerry Weißbach                $this->functions->debug->message("This is doku.php or detail.php file '$url'", null, 2);
8317d101cc1SGerry Weißbach                // Fetch Handling for media - rewriting everything
8327d101cc1SGerry Weißbach            case 'fetch.php':
8337d101cc1SGerry Weißbach                $this->__getParamsAndDataRewritten($DATA, $PARAMS, 'media');
8347d101cc1SGerry Weißbach
8357d101cc1SGerry Weißbach                $DATA[2] = str_replace('/', ':', $DATA[2]);
8367d101cc1SGerry Weißbach                $ID = $this->functions->cleanID($DATA[2], null, strstr($DATA[2], 'media'));
8377d101cc1SGerry Weißbach
8387d101cc1SGerry Weißbach                $urlM = ml($ID, null, true);
8397d101cc1SGerry Weißbach                $uriM = @parse_url($urlM);
8407d101cc1SGerry Weißbach                $DATA[2] = $uriM['path'] . ( !empty( $ANCHOR) ? '#' . $ANCHOR : '' ) . ( !empty( $PARAMS) ? '?' . $PARAMS : '' );
8417d101cc1SGerry Weißbach
8427d101cc1SGerry Weißbach                $DATA['PARAMS'] = "";
8437d101cc1SGerry Weißbach                $newAdditionalParameters = array();
8447d101cc1SGerry Weißbach
8450b4abc9fSGerry Weißbach                $this->functions->debug->message("This is fetch.php file", array($DATA, $ID, $PARAMS), 2);
8467d101cc1SGerry Weißbach                break;
8477d101cc1SGerry Weißbach
8487d101cc1SGerry Weißbach                // default Handling for Pages
8497d101cc1SGerry Weißbach            default			:
8507d101cc1SGerry Weißbach                if ( preg_match("%" . DOKU_BASE . "_detail/%", $DATA[2]) ) {
8517d101cc1SGerry Weißbach
8527d101cc1SGerry Weißbach                    // GET ID Param from origdata2
8537d101cc1SGerry Weißbach                    preg_match("#id=(.*?)(&|\")#i", $DATA[0], $backlinkID);
8547d101cc1SGerry Weißbach                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
8557d101cc1SGerry Weißbach
8567d101cc1SGerry Weißbach                    $fileIDPart = isset($backlinkID[1]) && !empty($backlinkID[1]) ? $this->functions->cleanID(urldecode($backlinkID[1])) : 'detail';
8577d101cc1SGerry Weißbach
8587d101cc1SGerry Weißbach                    $DATA[2] .= '/' . $fileIDPart . '.' . $this->functions->settings->fileType; // add namespace and subpage for back button and add filetype
8597d101cc1SGerry Weißbach
8607d101cc1SGerry Weißbach                    $noDeepReplace = false;
8617d101cc1SGerry Weißbach                    $fileName = $this->functions->shortenName($DATA[2]);
8627d101cc1SGerry Weißbach                    $newDepth = str_repeat('../', count(explode('/', $fileName))-1);
8637d101cc1SGerry Weißbach                    $url .= ( strstr($url, '?') ? '&' : '?' ) . 'id=' . $fileIDPart; // add id-part to URL for backlinks
8647d101cc1SGerry Weißbach
8657d101cc1SGerry Weißbach                    $DATA['PARAMS'] = "";
8667d101cc1SGerry Weißbach
8677d101cc1SGerry Weißbach                    $this->functions->debug->message("This is something with '_detail' file", array($DATA, $backlinkID, $newDepth, $url), 2);
8687d101cc1SGerry Weißbach                } else if ( preg_match("%" . DOKU_BASE . "_export/(.*?)/%", $DATA[2], $fileType) ) {
8697d101cc1SGerry Weißbach
8707d101cc1SGerry Weißbach                    // Fixes multiple codeblocks in one file
8717d101cc1SGerry Weißbach                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
8727d101cc1SGerry Weißbach
8737d101cc1SGerry Weißbach                    // add the Params no matter what they are. This is export. We don't mess with other files
8747d101cc1SGerry Weißbach                    // adding the "/" fixes the usage of multiple codeblocks in the same namespace
8757d101cc1SGerry Weißbach                    $DATA[2] .= (empty( $PARAMS ) ? '' : '/' . $PARAMS) . '.'. $fileType[1];
8767d101cc1SGerry Weißbach
8777d101cc1SGerry Weißbach                    $DATA['PARAMS'] = "";
8787d101cc1SGerry Weißbach                    $this->functions->debug->message("This is something with '_export' file", $DATA, 2);
8797d101cc1SGerry Weißbach
8807d101cc1SGerry Weißbach                } else if ( $IDexists ) { // 08/10/2010 - was page_exists($ID) - but this should do as well.
8817d101cc1SGerry Weißbach                    // If this is a page ... skip it!
8827d101cc1SGerry Weißbach                    $DATA[2] .= ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID(preg_replace("/(=|\?|&amp;)/", ".", $PARAMS)))  . '.' . $this->functions->settings->fileType;
8837d101cc1SGerry Weißbach
8847d101cc1SGerry Weißbach                    // 2012-06-15 originally has an absolute path ... we might need a relative one if not in our namespace
8857d101cc1SGerry Weißbach                    $this->functions->debug->message("OK, this is to be absolute: " . (empty($_REQUEST['absolutePath'])?'false':'true'), null, 1);
8867d101cc1SGerry Weißbach                    if ( empty($_REQUEST['absolutePath']) )
8877d101cc1SGerry Weißbach                    {
8887d101cc1SGerry Weißbach                        $DATA[2] = $this->functions->getRelativeURL($DATA[2], $currentID);
8897d101cc1SGerry Weißbach                    }
8907d101cc1SGerry Weißbach
8917d101cc1SGerry Weißbach                    $DATA[2] = $this->functions->shortenName($DATA[2]);
8927d101cc1SGerry Weißbach
8937d101cc1SGerry Weißbach                    // If Parameters are to be included in the filename - they must not be added twice
8947d101cc1SGerry Weißbach                    if ( $this->functions->settings->addParams ) $DATA['PARAMS'] = "";
8957d101cc1SGerry Weißbach
8967d101cc1SGerry Weißbach                    $this->functions->debug->message("This page really exists", $DATA, 1);
8977d101cc1SGerry Weißbach
8987d101cc1SGerry Weißbach                    return $this->__rebuildLink($DATA);
8997d101cc1SGerry Weißbach                } else {
9007d101cc1SGerry Weißbach                    $this->__rebuildDataForNormalFiles($DATA, $PARAMS);
9017d101cc1SGerry Weißbach                }
9027d101cc1SGerry Weißbach
9037d101cc1SGerry Weißbach                unset($newAdditionalParameters['diPlu']);
9047d101cc1SGerry Weißbach        }
9057d101cc1SGerry Weißbach
9067d101cc1SGerry Weißbach
9077d101cc1SGerry Weißbach        $this->functions->debug->message("DATA after SWITCH CASE decision", array($DATA, $noDeepReplace, $fileName, $newDepth), 1);
9087d101cc1SGerry Weißbach
9097d101cc1SGerry Weißbach        if ( $this->filewriter->canDoPDF() ) {
9107d101cc1SGerry Weißbach            $this->functions->addAdditionalParametersToURL($url, $newAdditionalParameters);
9117d101cc1SGerry Weißbach            $DATA[2] = $url;
9127d101cc1SGerry Weißbach            unset($DATA['PARAMS']);
9137d101cc1SGerry Weißbach            $url = $this->__rebuildLink($DATA, '');
9147d101cc1SGerry Weißbach
9157d101cc1SGerry Weißbach            $this->functions->debug->message("Creating PDF with URL '$url'", null, 2);
9167d101cc1SGerry Weißbach
9177d101cc1SGerry Weißbach            return $url;
9187d101cc1SGerry Weißbach        }
9197d101cc1SGerry Weißbach
9207d101cc1SGerry Weißbach        // Create Name to save the file at
9217d101cc1SGerry Weißbach        $DATA[2] = str_replace(':', '_', $DATA[2]);
9227d101cc1SGerry Weißbach        $DATA[2] = $this->functions->shortenName($DATA[2]);
9237d101cc1SGerry Weißbach
9247d101cc1SGerry Weißbach
9257d101cc1SGerry Weißbach        // File already loaded?
9267d101cc1SGerry Weißbach        // 2010-10-23 - changes in_array from DATA[2] to $url - to check real URLs, the DATA[2] file will be checked with fileExistsInZip
9277d101cc1SGerry Weißbach        if ( in_array($url, array_keys($this->fileChecked)) ) {
9287d101cc1SGerry Weißbach            $DATA[2] = $this->fileChecked[$url];
9297d101cc1SGerry Weißbach            $this->functions->debug->message("File has been checked before.", array($DATA, $url), 2);
9307d101cc1SGerry Weißbach            return $this->__rebuildLink($DATA);
9317d101cc1SGerry Weißbach        }
9327d101cc1SGerry Weißbach
9337d101cc1SGerry Weißbach        // 2010-09-03 - second check if the file is in the ZIP already.
9347d101cc1SGerry Weißbach        if ( $this->filewriter->fileExistsInZip($DATA[2]) ) {
9357d101cc1SGerry Weißbach            $this->functions->debug->message("File with DATA exists in ZIP.", $DATA, 3);
9367d101cc1SGerry Weißbach            return $this->__rebuildLink($DATA);
9377d101cc1SGerry Weißbach        }
9387d101cc1SGerry Weißbach
9397d101cc1SGerry Weißbach        // 2010-10-23 - What if this is a fetch.php? than we produced an error.
9407d101cc1SGerry Weißbach        //        $this->fileChecked[] = $DATA[2];
9417d101cc1SGerry Weißbach        $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
9427d101cc1SGerry Weißbach
9437d101cc1SGerry Weißbach        // get tempFile and save it
9447d101cc1SGerry Weißbach        $origDepth = $this->functions->settings->depth;
9457d101cc1SGerry Weißbach        $this->functions->settings->depth = $newDepth;
9467d101cc1SGerry Weißbach
9477d101cc1SGerry Weißbach        $tmpID = $currentID;
9487d101cc1SGerry Weißbach        $tmpFile === false;
9497d101cc1SGerry Weißbach
9507d101cc1SGerry Weißbach        $this->functions->debug->message("Going to get the file", array($url, $noDeepReplace, $newAdditionalParameters), 2);
9517d101cc1SGerry Weißbach        $tmpFile = $this->__getHTTPFile($url, $noDeepReplace, $newAdditionalParameters);
9527d101cc1SGerry Weißbach        $this->functions->debug->message("This is the getHTTPFile result", $tmpFile, 2);
9537d101cc1SGerry Weißbach
9547d101cc1SGerry Weißbach        $currentID = $tmpID;
9557d101cc1SGerry Weißbach        $this->functions->settings->depth = $origDepth; // 2010-09-03 - Reset depth at the very end
9567d101cc1SGerry Weißbach
9577d101cc1SGerry Weißbach        if ( $tmpFile === false ) {
9587d101cc1SGerry Weißbach            // Keep an potentially extra link intact
9597d101cc1SGerry Weißbach
9607d101cc1SGerry Weißbach            $this->functions->debug->message("The fetched file '$url' is 'false'", null, 3);
9617d101cc1SGerry Weißbach            if ( $IDexists === false ) {
9627d101cc1SGerry Weißbach                $this->functions->debug->message("The file does not exist, fallback to ORIGDATA", $ORIGDATA2, 2);
9637d101cc1SGerry Weißbach                $DATA[2] = $this->functions->shortenName($ORIGDATA2[2]); // get Origdata Path
9647d101cc1SGerry Weißbach            }
9657d101cc1SGerry Weißbach
9667d101cc1SGerry Weißbach            $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
9677d101cc1SGerry Weißbach            $link = $this->__rebuildLink($DATA);
9687d101cc1SGerry Weißbach            $this->functions->debug->message("Final Link after empty file from '$url'", null, 2);
9697d101cc1SGerry Weißbach
9707d101cc1SGerry Weißbach            return $link;
9717d101cc1SGerry Weißbach        }
9727d101cc1SGerry Weißbach
9737d101cc1SGerry Weißbach        $this->functions->debug->message("The fetched file looks good.", $tmpFile, 1);
974281ed919SGerry Weißbach        $dirname = dirname($DATA[2]);
9757d101cc1SGerry Weißbach
9767d101cc1SGerry Weißbach        // If a Filename was given that does not comply to the original name, us this one!
9777d101cc1SGerry Weißbach        if ( !empty($tmpFile[1]) && !strstr($DATA[2], $tmpFile[1]) ) {
978281ed919SGerry Weißbach			$DATA[2] = $dirname . '/' . $tmpFile[1];
9797d101cc1SGerry Weißbach        }
9807d101cc1SGerry Weißbach
9817d101cc1SGerry Weißbach        // Add to zip
9827d101cc1SGerry Weißbach        $this->fileChecked[$url] = $DATA[2]; // 2010-09-03 - One URL to one FileName
9837d101cc1SGerry Weißbach
9847d101cc1SGerry Weißbach        $status = $this->filewriter->__addFileToZip($tmpFile[0], $DATA[2]);
9857d101cc1SGerry Weißbach        @unlink($tmpFile[0]);
9867d101cc1SGerry Weißbach
9877d101cc1SGerry Weißbach        $newURL = $this->__rebuildLink($DATA);
9887d101cc1SGerry Weißbach        $this->functions->debug->message("Returning final Link to document: '$newURL'", null, 2);
9897d101cc1SGerry Weißbach
9907d101cc1SGerry Weißbach        return $newURL;
9917d101cc1SGerry Weißbach    }
9927d101cc1SGerry Weißbach
9937d101cc1SGerry Weißbach    /**
9947d101cc1SGerry Weißbach     * build the new link to be put in place for the donwloaded site
9957d101cc1SGerry Weißbach     **/
9967d101cc1SGerry Weißbach    function __rebuildLink($DATA, $DEPTH = null) {
9977d101cc1SGerry Weißbach
9987d101cc1SGerry Weißbach        // depth is set, skip this one
9997d101cc1SGerry Weißbach        if ( is_null( $DEPTH ) ) $DEPTH = $this->functions->settings->depth;
10007d101cc1SGerry Weißbach        $DATA[2] .= ( !empty( $DATA['PARAMS']) ? '?' . $DATA['PARAMS'] : '' ) . ( !empty( $DATA['ANCHOR'] ) ? '#' . $DATA['ANCHOR'] : '' );
10017d101cc1SGerry Weißbach
10027d101cc1SGerry Weißbach        $newURL = $DATA[1] == 'url' ? $DATA[1] . '(' . $DEPTH . $DATA[2] . ')' : $DATA[1] . '="' . $DEPTH . $DATA[2] . '"';
10037d101cc1SGerry Weißbach        $this->functions->debug->message("Re-created URL: '$newURL'", null, 2);
10047d101cc1SGerry Weißbach
10057d101cc1SGerry Weißbach        return $newURL;
10067d101cc1SGerry Weißbach    }
10077d101cc1SGerry Weißbach
10087d101cc1SGerry Weißbach
10097d101cc1SGerry Weißbach    /**
10107d101cc1SGerry Weißbach     * remove an old zip file
10117d101cc1SGerry Weißbach     **/
10127d101cc1SGerry Weißbach    function __removeOldZip( $FILENAMEID=null, $checkForMore=true ) {
10137d101cc1SGerry Weißbach        global $INFO;
10147d101cc1SGerry Weißbach        global $conf;
10157d101cc1SGerry Weißbach
10167d101cc1SGerry Weißbach        $returnValue = true;
10177d101cc1SGerry Weißbach
10187d101cc1SGerry Weißbach        if ( empty($FILENAMEID) ) {
10197d101cc1SGerry Weißbach            $FILENAMEID = $this->functions->settings->origZipFile;
10207d101cc1SGerry Weißbach        }
10217d101cc1SGerry Weißbach
10228da901a0SGerry Weißbach        if ( !file_exists(mediaFN($FILENAMEID)) ) {
10238da901a0SGerry Weißbach            $returnValue = true;
10248da901a0SGerry Weißbach        } else {
10258da901a0SGerry Weißbach
10267d101cc1SGerry Weißbach            require_once( DOKU_INC . 'inc/media.php');
10277d101cc1SGerry Weißbach            if ( !media_delete($FILENAMEID, $INFO['perm']) ) {
10287d101cc1SGerry Weißbach                $returnValue = false;
10297d101cc1SGerry Weißbach            }
10307d101cc1SGerry Weißbach        }
10317d101cc1SGerry Weißbach
10327d101cc1SGerry Weißbach        if ( $checkForMore ) {
10337d101cc1SGerry Weißbach            // Try to remove more files.
10347d101cc1SGerry Weißbach            $ns = getNS($FILENAMEID);
10357d101cc1SGerry Weißbach            $fn = $this->functions->getSpecialExportFileName(noNS($FILENAMEID), '.+');
10367d101cc1SGerry Weißbach
10377d101cc1SGerry Weißbach            $data = array();
10387d101cc1SGerry Weißbach            search($data, $conf['mediadir'], 'search_media', array('pattern' => "/$fn$/i"), $ns);
10397d101cc1SGerry Weißbach
10407d101cc1SGerry Weißbach            if ( count($data > 0) ) {
10417d101cc1SGerry Weißbach
10427d101cc1SGerry Weißbach                // 30 Minuten Cache Zeit
1043f8fd18e7SGerry Weißbach                $cache = $this->functions->settings->cachetime;
10447d101cc1SGerry Weißbach                foreach ( $data as $media ) {
10457d101cc1SGerry Weißbach
10467d101cc1SGerry Weißbach                    //decide if has to be deleted needed:
10477d101cc1SGerry Weißbach                    if( $media['mtime'] < time()-$cache) {
10487d101cc1SGerry Weißbach                        $this->__removeOldZip($media['id'], false);
10497d101cc1SGerry Weißbach                    }
10507d101cc1SGerry Weißbach                }
10517d101cc1SGerry Weißbach            }
10527d101cc1SGerry Weißbach
10537d101cc1SGerry Weißbach        }
10547d101cc1SGerry Weißbach
10557d101cc1SGerry Weißbach        return $returnValue;
10567d101cc1SGerry Weißbach    }
10577d101cc1SGerry Weißbach
10587d101cc1SGerry Weißbach    /**
10597d101cc1SGerry Weißbach     * if confrewrite is set to internal rewrite, use this function - taken from a DW renderer
10607d101cc1SGerry Weißbach     **/
10617d101cc1SGerry Weißbach    function __getInternalRewriteURL($url) {
10627d101cc1SGerry Weißbach        global $conf;
10637d101cc1SGerry Weißbach
10647d101cc1SGerry Weißbach        //construct page id from request URI
10657d101cc1SGerry Weißbach        if( $conf['userewrite'] != 2) { return $url; }
10667d101cc1SGerry Weißbach
10677d101cc1SGerry Weißbach        //get the script URL
10687d101cc1SGerry Weißbach        if($conf['basedir']) {
10697d101cc1SGerry Weißbach            $relpath = '';
10707d101cc1SGerry Weißbach            $script = $conf['basedir'].$relpath.basename($_SERVER['SCRIPT_FILENAME']);
10717d101cc1SGerry Weißbach        } elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
10727d101cc1SGerry Weißbach            $script = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
10737d101cc1SGerry Weißbach            $_SERVER['SCRIPT_FILENAME']);
10747d101cc1SGerry Weißbach            $script = '/'.$script;
10757d101cc1SGerry Weißbach        }else{
10767d101cc1SGerry Weißbach            $script = $_SERVER['SCRIPT_NAME'];
10777d101cc1SGerry Weißbach        }
10787d101cc1SGerry Weißbach
10797d101cc1SGerry Weißbach        //clean script and request (fixes a windows problem)
10807d101cc1SGerry Weißbach        $script  = preg_replace('/\/\/+/','/',$script);
10817d101cc1SGerry Weißbach        $request = preg_replace('/\/\/+/','/',$url);
10827d101cc1SGerry Weißbach
10837d101cc1SGerry Weißbach        //remove script URL and Querystring to gain the id
10847d101cc1SGerry Weißbach        if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){
10857d101cc1SGerry Weißbach            $id = preg_replace ('/\?.*/','',$match[1]);
10867d101cc1SGerry Weißbach        }
10877d101cc1SGerry Weißbach        $id = urldecode($id);
10887d101cc1SGerry Weißbach        //strip leading slashes
10897d101cc1SGerry Weißbach        $id = preg_replace('!^/+!','',$id);
10907d101cc1SGerry Weißbach
10917d101cc1SGerry Weißbach        return $id;
10927d101cc1SGerry Weißbach    }
10937d101cc1SGerry Weißbach
10947d101cc1SGerry Weißbach    /**
10957d101cc1SGerry Weißbach     * rewrite parameter calls
10967d101cc1SGerry Weißbach     **/
10977d101cc1SGerry Weißbach    function __getParamsAndDataRewritten(&$DATA, &$PARAMS, $IDKEY='id') {
10987d101cc1SGerry Weißbach
10997d101cc1SGerry Weißbach        $PARRAY = explode('&', str_replace('&amp;', '&', $PARAMS) );
11007d101cc1SGerry Weißbach        $PARAMS = "";
11017d101cc1SGerry Weißbach
11027d101cc1SGerry Weißbach        foreach ( $PARRAY as $item ) {
11037d101cc1SGerry Weißbach            list($key, $value) = explode('=', $item, 2);
11047d101cc1SGerry Weißbach            if ( empty($key) || empty($value) )
11057d101cc1SGerry Weißbach            continue;
11067d101cc1SGerry Weißbach
11077d101cc1SGerry Weißbach            if ( strtolower(trim($key)) == $IDKEY ) {
11087d101cc1SGerry Weißbach                $DATA[2] = preg_replace("%^" . DOKU_BASE . "%", "", $value);
11097d101cc1SGerry Weißbach                continue;
11107d101cc1SGerry Weißbach            }
11117d101cc1SGerry Weißbach
11127d101cc1SGerry Weißbach            if ( !empty( $PARAMS) ) {
11130b4abc9fSGerry Weißbach                $PARAMS .= '&';
11147d101cc1SGerry Weißbach            }
11157d101cc1SGerry Weißbach
11167d101cc1SGerry Weißbach            $PARAMS .= "$key=$value";
11177d101cc1SGerry Weißbach        }
11187d101cc1SGerry Weißbach    }
11197d101cc1SGerry Weißbach
11207d101cc1SGerry Weißbach    /**
11217d101cc1SGerry Weißbach     * rewrite detail.php calls
11227d101cc1SGerry Weißbach     **/
11237d101cc1SGerry Weißbach    function __rebuildDataForNormalFiles(&$DATA, &$PARAMS) {
11247d101cc1SGerry Weißbach        $PARTS = explode('.', $DATA[2]);
11257d101cc1SGerry Weißbach        if ( count($PARTS) > 1 ) {
11267d101cc1SGerry Weißbach            $EXT = '.' . array_pop($PARTS);
11277d101cc1SGerry Weißbach        }
11287d101cc1SGerry Weißbach
11297d101cc1SGerry Weißbach        $PARAMS = preg_replace("/(=|\?|&amp;)/", ".", $PARAMS);
11307d101cc1SGerry Weißbach        $DATA[2] = implode('.', $PARTS) . ( !$this->functions->settings->addParams || empty($PARAMS) ? '' : '.' . $this->functions->cleanID($PARAMS)) . ( $EXT == '.php' ? '.' . $this->functions->settings->fileType : $EXT );
11317d101cc1SGerry Weißbach        $DATA[2] = preg_replace("/\.+/", ".", $DATA[2]);
11327d101cc1SGerry Weißbach    }
11337d101cc1SGerry Weißbach
11347d101cc1SGerry Weißbach
11357d101cc1SGerry Weißbach
11367d101cc1SGerry Weißbach
11377d101cc1SGerry Weißbach    /*
11387d101cc1SGerry Weißbach     * Clean JS and CSS cache files
11397d101cc1SGerry Weißbach     */
11407d101cc1SGerry Weißbach    function cleanCacheFiles() {
11417d101cc1SGerry Weißbach
11427d101cc1SGerry Weißbach        $_SERVER['HTTP_HOST'] = preg_replace("/:?\d+$/", '', $_SERVER['HTTP_HOST']);
11437d101cc1SGerry Weißbach        $cache = getCacheName('scripts'.$_SERVER['HTTP_HOST'].'-siteexport-js-'.$_SERVER['SERVER_PORT'],'.js');
11447d101cc1SGerry Weißbach        $this->unlinkIfExists($cache);
11457d101cc1SGerry Weißbach
11467d101cc1SGerry Weißbach        $tpl = trim(preg_replace('/[^\w-]+/','',$_REQUEST['template']));
11477d101cc1SGerry Weißbach        if($tpl)
11487d101cc1SGerry Weißbach        {
11497d101cc1SGerry Weißbach            $tplinc = DOKU_INC.'lib/tpl/'.$tpl.'/';
11507d101cc1SGerry Weißbach            $tpldir = DOKU_BASE.'lib/tpl/'.$tpl.'/';
11517d101cc1SGerry Weißbach        } else {
11527d101cc1SGerry Weißbach            $tplinc = DOKU_TPLINC;
11537d101cc1SGerry Weißbach            $tpldir = DOKU_TPL;
11547d101cc1SGerry Weißbach        }
11557d101cc1SGerry Weißbach
11567d101cc1SGerry Weißbach        // The generated script depends on some dynamic options
11577d101cc1SGerry Weißbach        $cache = getCacheName('styles'.$_SERVER['HTTP_HOST'].'-siteexport-js-'.$_SERVER['SERVER_PORT'].DOKU_BASE.$tplinc.$style,'.css');
11587d101cc1SGerry Weißbach        $this->unlinkIfExists($cache);
11597d101cc1SGerry Weißbach    }
11607d101cc1SGerry Weißbach
11617d101cc1SGerry Weißbach    function unlinkIfExists($cache) {
11627d101cc1SGerry Weißbach        if ( file_exists($cache) ) {
11637d101cc1SGerry Weißbach            @unlink($cache);
11647d101cc1SGerry Weißbach            if(function_exists('gzopen')) @unlink("$cache.gz");
11657d101cc1SGerry Weißbach        }
11667d101cc1SGerry Weißbach    }
11677d101cc1SGerry Weißbach
11687d101cc1SGerry Weißbach    // Private unset function
11697d101cc1SGerry Weißbach    private function clear(&$variable)
11707d101cc1SGerry Weißbach    {
11717d101cc1SGerry Weißbach        if ( isset($variable) )
11727d101cc1SGerry Weißbach        {
11737d101cc1SGerry Weißbach            unset($variable);
11747d101cc1SGerry Weißbach        }
11757d101cc1SGerry Weißbach    }
11767d101cc1SGerry Weißbach}