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