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