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