Chunked queries. Use modulo slicing instead of range slicing to avoid gaps when the...
[lhc/web/wiklou.git] / maintenance / dumpHTML.inc
1 <?php
2 /**
3 * @package MediaWiki
4 * @subpackage Maintenance
5 */
6
7 define( 'REPORTING_INTERVAL', 10 );
8
9 require_once( 'includes/ImagePage.php' );
10 require_once( 'includes/CategoryPage.php' );
11 require_once( 'includes/RawPage.php' );
12
13 class DumpHTML {
14 # Destination directory
15 var $dest;
16
17 # Skip existing files
18 var $noOverwrite = false;
19
20 # Show interlanguage links?
21 var $interwiki = true;
22
23 # Depth of HTML directory tree
24 var $depth = 3;
25
26 # Directory that commons images are copied into
27 var $sharedStaticDirectory;
28
29 # Directory that the images are in, after copying
30 var $destUploadDirectory;
31
32 # Relative path to image directory
33 var $imageRel = 'upload';
34
35 # Copy commons images instead of symlinking
36 var $forceCopy = false;
37
38 # Make a copy of all images encountered
39 var $makeSnapshot = false;
40
41 # Make links assuming the script path is in the same directory as
42 # the destination
43 var $alternateScriptPath = false;
44
45 # Original values of various globals
46 var $oldArticlePath = false, $oldCopyrightIcon = false;
47
48 # Has setupGlobals been called?
49 var $setupDone = false;
50
51 # List of raw pages used in the current article
52 var $rawPages;
53
54 # Skin to use
55 var $skin = 'htmldump';
56
57 # Checkpoint stuff
58 var $checkpointFile = false, $checkpoints = false;
59
60 var $startID = 1, $endID = false;
61
62 var $sliceNumerator = 1, $sliceDenominator = 1;
63
64 # Max page ID, lazy initialised
65 var $maxPageID = false;
66
67 function DumpHTML( $settings = array() ) {
68 foreach ( $settings as $var => $value ) {
69 $this->$var = $value;
70 }
71 }
72
73 function loadCheckpoints() {
74 if ( $this->checkpoints !== false ) {
75 return true;
76 } elseif ( !$this->checkpointFile ) {
77 return false;
78 } else {
79 $lines = @file( $this->checkpointFile );
80 if ( $lines === false ) {
81 print "Starting new checkpoint file \"{$this->checkpointFile}\"\n";
82 $this->checkpoints = array();
83 } else {
84 $lines = array_map( 'trim', $lines );
85 $this->checkpoints = array();
86 foreach ( $lines as $line ) {
87 list( $name, $value ) = explode( '=', $line, 2 );
88 $this->checkpoints[$name] = $value;
89 }
90 }
91 return true;
92 }
93 }
94
95 function getCheckpoint( $type, $defValue = false ) {
96 if ( !$this->loadCheckpoints() ) {
97 return false;
98 }
99 if ( !isset( $this->checkpoints[$type] ) ) {
100 return false;
101 } else {
102 return $this->checkpoints[$type];
103 }
104 }
105
106 function setCheckpoint( $type, $value ) {
107 if ( !$this->checkpointFile ) {
108 return;
109 }
110 $this->checkpoints[$type] = $value;
111 $blob = '';
112 foreach ( $this->checkpoints as $type => $value ) {
113 $blob .= "$type=$value\n";
114 }
115 file_put_contents( $this->checkpointFile, $blob );
116 }
117
118 function doEverything() {
119 if ( $this->getCheckpoint( 'everything' ) == 'done' ) {
120 print "Checkpoint says everything is already done\n";
121 return;
122 }
123 $this->doArticles();
124 $this->doLocalImageDescriptions();
125 $this->doSharedImageDescriptions();
126 $this->doCategories();
127 $this->doRedirects();
128 if ( $this->sliceNumerator == 1 ) {
129 $this->doSpecials();
130 }
131
132 $this->setCheckpoint( 'everything', 'done' );
133 }
134
135 /**
136 * Write a set of articles specified by start and end page_id
137 * Skip categories and images, they will be done separately
138 */
139 function doArticles() {
140 if ( $this->endID === false ) {
141 $this->endID = $this->getMaxPageID();
142 }
143
144 # Start from the checkpoint
145 $cp = $this->getCheckpoint( 'article' );
146 if ( $cp == 'done' ) {
147 print "Articles already done\n";
148 return;
149 } elseif ( $cp !== false ) {
150 $start = $cp;
151 print "Resuming article dump from checkpoint at page_id $start of $end\n";
152 } else {
153 print "Starting from page_id $start of $end\n";
154 }
155
156 # Move the start point to the correct slice if it isn't there already
157 $start = $this->modSliceStart( $start );
158
159 $this->setupGlobals();
160
161 $mainPageObj = Title::newMainPage();
162 $mainPage = $mainPageObj->getPrefixedDBkey();
163
164 for ( $id = $start, $i = 0; $id <= $end; $id += $this->sliceDenominator, $i++ ) {
165 wfWaitForSlaves( 20 );
166 if ( !( $i % REPORTING_INTERVAL) ) {
167 print "Processing ID: $id\r";
168 $this->setCheckpoint( 'article', $id );
169 }
170 if ( !($i % (REPORTING_INTERVAL*10) ) ) {
171 print "\n";
172 }
173 $title = Title::newFromID( $id );
174 if ( $title ) {
175 $ns = $title->getNamespace() ;
176 if ( $ns != NS_CATEGORY && $title->getPrefixedDBkey() != $mainPage ) {
177 $this->doArticle( $title );
178 }
179 }
180 }
181 $this->setCheckpoint( 'article', 'done' );
182 print "\n";
183 }
184
185 function doSpecials() {
186 $this->doMainPage();
187
188 $this->setupGlobals();
189 print "Special:Categories...";
190 $this->doArticle( Title::makeTitle( NS_SPECIAL, 'Categories' ) );
191 print "\n";
192 }
193
194 /** Write the main page as index.html */
195 function doMainPage() {
196
197 print "Making index.html ";
198
199 // Set up globals with no ../../.. in the link URLs
200 $this->setupGlobals( 0 );
201
202 $title = Title::newMainPage();
203 $text = $this->getArticleHTML( $title );
204
205 # Parse the XHTML to find the images
206 $images = $this->findImages( $text );
207 $this->copyImages( $images );
208
209 $file = fopen( "{$this->dest}/index.html", "w" );
210 if ( !$file ) {
211 print "\nCan't open index.html for writing\n";
212 return false;
213 }
214 fwrite( $file, $text );
215 fclose( $file );
216 print "\n";
217 }
218
219 function doImageDescriptions() {
220 $this->doLocalImageDescriptions();
221 $this->doSharedImageDescriptions();
222 }
223
224 /**
225 * Dump image description pages that don't have an associated article, but do
226 * have a local image
227 */
228 function doLocalImageDescriptions() {
229 global $wgSharedUploadDirectory;
230 $chunkSize = 1000;
231
232 $dbr =& wfGetDB( DB_SLAVE );
233
234 $cp = $this->getCheckpoint( 'local image' );
235 if ( $cp == 'done' ) {
236 print "Local image descriptions already done\n";
237 return;
238 } elseif ( $cp !== false ) {
239 print "Writing image description pages starting from $cp\n";
240 $conds = array( 'img_name >= ' . $dbr->addQuotes( $cp ) );
241 } else {
242 print "Writing image description pages for local images\n";
243 $conds = false;
244 }
245
246 $this->setupGlobals();
247 $i = 0;
248
249 do {
250 $res = $dbr->select( 'image', array( 'img_name' ), $conds, __METHOD__,
251 array( 'ORDER BY' => 'img_name', 'LIMIT' => $chunkSize ) );
252 $numRows = $dbr->numRows( $res );
253
254 while ( $row = $dbr->fetchObject( $res ) ) {
255 # Update conds for the next chunk query
256 $conds = array( 'img_name > ' . $dbr->addQuotes( $row->img_name ) );
257
258 // Slice the result set with a filter
259 if ( !$this->sliceFilter( $row->img_name ) ) {
260 continue;
261 }
262
263 wfWaitForSlaves( 10 );
264 if ( !( ++$i % REPORTING_INTERVAL ) ) {
265 print "{$row->img_name}\n";
266 if ( $row->img_name !== 'done' ) {
267 $this->setCheckpoint( 'local image', $row->img_name );
268 }
269 }
270 $title = Title::makeTitle( NS_IMAGE, $row->img_name );
271 if ( $title->getArticleID() ) {
272 // Already done by dumpHTML
273 continue;
274 }
275 $this->doArticle( $title );
276 }
277 $dbr->freeResult( $res );
278 } while ( $numRows );
279
280 $this->setCheckpoint( 'local image', 'done' );
281 print "\n";
282 }
283
284 /**
285 * Dump images which only have a real description page on commons
286 */
287 function doSharedImageDescriptions() {
288 list( $start, $end ) = $this->sliceRange( 0, 255 );
289
290 $cp = $this->getCheckpoint( 'shared image' );
291 if ( $cp == 'done' ) {
292 print "Shared description pages already done\n";
293 return;
294 } elseif ( $cp !== false ) {
295 print "Writing description pages for commons images starting from directory $cp/255\n";
296 $start = $cp;
297 } else {
298 print "Writing description pages for commons images\n";
299 }
300
301 $this->setupGlobals();
302 $i = 0;
303 for ( $hash = $start; $hash <= $end; $hash++ ) {
304 $this->setCheckpoint( 'shared image', $hash );
305
306 $dir = sprintf( "%01x/%02x", intval( $hash / 16 ), $hash );
307 $paths = array_merge( glob( "{$this->sharedStaticDirectory}/$dir/*" ),
308 glob( "{$this->sharedStaticDirectory}/thumb/$dir/*" ) );
309
310 foreach ( $paths as $path ) {
311 $file = wfBaseName( $path );
312 if ( !(++$i % REPORTING_INTERVAL ) ) {
313 print "$i\r";
314 }
315
316 $title = Title::makeTitle( NS_IMAGE, $file );
317 $this->doArticle( $title );
318 }
319 }
320 $this->setCheckpoint( 'shared image', 'done' );
321 print "\n";
322 }
323
324 function doCategories() {
325 $chunkSize = 1000;
326
327 $this->setupGlobals();
328 $dbr =& wfGetDB( DB_SLAVE );
329
330 $cp = $this->getCheckpoint( 'category' );
331 if ( $cp == 'done' ) {
332 print "Category pages already done\n";
333 return;
334 } elseif ( $cp !== false ) {
335 print "Resuming category page dump from $cp\n";
336 $conds = array( 'cl_to >= ' $dbr->addQuotes( $cp ) );
337 } else {
338 print "Starting category pages\n";
339 $conds = false;
340 }
341
342 $i = 0;
343 do {
344 $res = $dbr->select( 'categorylinks', 'DISTINCT cl_to', $conds, __METHOD__
345 array( 'ORDER BY' => 'cl_to', 'LIMIT' => $chunkSize ) );
346 $numRows = $dbr->numRows( $res );
347
348 while ( $row = $dbr->fetchObject( $res ) ) {
349 // Set conditions for next chunk
350 $conds = array( 'cl_to > ' $dbr->addQuotes( $row->cl_to ) );
351
352 // Filter pages from other slices
353 if ( !$this->sliceFilter( $row->cl_to ) ) {
354 continue;
355 }
356
357 wfWaitForSlaves( 10 );
358 if ( !(++$i % REPORTING_INTERVAL ) ) {
359 print "{$row->cl_to}\n";
360 if ( $row->cl_to != 'done' ) {
361 $this->setCheckpoint( 'category', $row->cl_to );
362 }
363 }
364 $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
365 $this->doArticle( $title );
366 }
367 $dbr->freeResult( $res );
368 } while ( $numRows );
369
370 $this->setCheckpoint( 'category', 'done' );
371 print "\n";
372 }
373
374 function doRedirects() {
375 print "Doing redirects...\n";
376
377 $chunkSize = 10000;
378 $end = $this->getMaxPageID();
379 $cp = $this->getCheckpoint( 'redirect' );
380 if ( $cp == 'done' ) {
381 print "Redirects already done\n";
382 return;
383 } elseif ( $cp !== false ) {
384 print "Resuming redirect generation from page_id $cp\n";
385 $start = intval( $cp );
386 }
387
388 $this->setupGlobals();
389 $dbr =& wfGetDB( DB_SLAVE );
390 $i = 0;
391
392 for ( $chunkStart = $start; $chunkStart <= $end; $chunkStart += $chunkSize ) {
393 $chunkEnd = min( $end, $chunkStart + $chunkSize - 1 );
394 $conds = array(
395 'page_is_redirect' => 1,
396 "page_id BETWEEN $chunkStart AND $chunkEnd"
397 );
398 # Modulo slicing in SQL
399 if ( $this->sliceDenominator != 1 ) {
400 $n = intval( $this->sliceNumerator );
401 $m = intval( $this->sliceDenominator );
402 $conds[] = "page_id % $m = $n";
403 }
404 $res = $dbr->select( 'page', array( 'page_id', 'page_namespace', 'page_title' ),
405 $conds, __METHOD__ );
406
407 while ( $row = $dbr->fetchObject( $res ) ) {
408 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
409 if ( !(++$i % (REPORTING_INTERVAL*10) ) ) {
410 printf( "Done %d redirects (%2.3f%%)\n", $i, $row->page_id / $end * 100 );
411 $this->setCheckpoint( 'redirect', $row->page_id );
412 }
413 $this->doArticle( $title );
414 }
415 $dbr->freeResult( $res );
416 }
417 $this->setCheckpoint( 'redirect', 'done' );
418 }
419
420 /** Write an article specified by title */
421 function doArticle( $title ) {
422 global $wgTitle, $wgSharedUploadPath, $wgSharedUploadDirectory;
423 global $wgUploadDirectory;
424
425 if ( $this->noOverwrite ) {
426 $fileName = $this->dest.'/'.$this->getHashedFilename( $title );
427 if ( file_exists( $fileName ) ) {
428 return;
429 }
430 }
431
432 $this->rawPages = array();
433 $text = $this->getArticleHTML( $title );
434
435 if ( $text === false ) {
436 return;
437 }
438
439 # Parse the XHTML to find the images
440 $images = $this->findImages( $text );
441 $this->copyImages( $images );
442
443 # Write to file
444 $this->writeArticle( $title, $text );
445
446 # Do raw pages
447 wfMkdirParents( "{$this->dest}/raw", 0755 );
448 foreach( $this->rawPages as $record ) {
449 list( $file, $title, $params ) = $record;
450
451 $path = "{$this->dest}/raw/$file";
452 if ( !file_exists( $path ) ) {
453 $article = new Article( $title );
454 $request = new FauxRequest( $params );
455 $rp = new RawPage( $article, $request );
456 $text = $rp->getRawText();
457
458 print "Writing $file\n";
459 $file = fopen( $path, 'w' );
460 if ( !$file ) {
461 print("Can't open file $fullName for writing\n");
462 continue;
463 }
464 fwrite( $file, $text );
465 fclose( $file );
466 }
467 }
468 }
469
470 /** Write the given text to the file identified by the given title object */
471 function writeArticle( &$title, $text ) {
472 $filename = $this->getHashedFilename( $title );
473 $fullName = "{$this->dest}/$filename";
474 $fullDir = dirname( $fullName );
475
476 wfMkdirParents( $fullDir, 0755 );
477
478 wfSuppressWarnings();
479 $file = fopen( $fullName, 'w' );
480 wfRestoreWarnings();
481
482 if ( !$file ) {
483 die("Can't open file '$fullName' for writing.\nCheck permissions or use another destination (-d).\n");
484 return;
485 }
486
487 fwrite( $file, $text );
488 fclose( $file );
489 }
490
491 /** Set up globals required for parsing */
492 function setupGlobals( $currentDepth = NULL ) {
493 global $wgUser, $wgTitle, $wgStylePath, $wgArticlePath, $wgMathPath;
494 global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
495 global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
496 global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
497 global $wgRightsUrl, $wgRightsText, $wgCopyrightIcon, $wgEnableSidebarCache;
498 global $wgGenerateThumbnailOnParse;
499
500 static $oldLogo = NULL;
501
502 if ( !$this->setupDone ) {
503 $wgHooks['GetLocalURL'][] =& $this;
504 $wgHooks['GetFullURL'][] =& $this;
505 $wgHooks['SiteNoticeBefore'][] =& $this;
506 $wgHooks['SiteNoticeAfter'][] =& $this;
507 $this->oldArticlePath = $wgServer . $wgArticlePath;
508 }
509
510 if ( is_null( $currentDepth ) ) {
511 $currentDepth = $this->depth;
512 }
513
514 if ( $this->alternateScriptPath ) {
515 if ( $currentDepth == 0 ) {
516 $wgScriptPath = '.';
517 } else {
518 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth - 1 );
519 }
520 } else {
521 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth );
522 }
523
524 $wgArticlePath = str_repeat( '../', $currentDepth ) . '$1';
525
526 # Logo image
527 # Allow for repeated setup
528 if ( !is_null( $oldLogo ) ) {
529 $wgLogo = $oldLogo;
530 } else {
531 $oldLogo = $wgLogo;
532 }
533
534 if ( strpos( $wgLogo, $wgUploadPath ) === 0 ) {
535 # If it's in the upload directory, rewrite it to the new upload directory
536 $wgLogo = "$wgScriptPath/{$this->imageRel}/" . substr( $wgLogo, strlen( $wgUploadPath ) + 1 );
537 } elseif ( $wgLogo{0} == '/' ) {
538 # This is basically heuristic
539 # Rewrite an absolute logo path to one relative to the the script path
540 $wgLogo = $wgScriptPath . $wgLogo;
541 }
542
543 # Another ugly hack
544 if ( !$this->setupDone ) {
545 $this->oldCopyrightIcon = $wgCopyrightIcon;
546 }
547 $wgCopyrightIcon = str_replace( 'src="/images',
548 'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $this->oldCopyrightIcon );
549
550 $wgStylePath = "$wgScriptPath/skins";
551 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
552 $wgSharedUploadPath = "$wgUploadPath/shared";
553 $wgMaxCredits = -1;
554 $wgHideInterlanguageLinks = !$this->interwiki;
555 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
556 $wgEnableParserCache = false;
557 $wgMathPath = "$wgScriptPath/math";
558 $wgEnableSidebarCache = false;
559 $wgGenerateThumbnailOnParse = true;
560
561 if ( !empty( $wgRightsText ) ) {
562 $wgRightsUrl = "$wgScriptPath/COPYING.html";
563 }
564
565 $wgUser = new User;
566 $wgUser->setOption( 'skin', $this->skin );
567 $wgUser->setOption( 'editsection', 0 );
568
569 if ( $this->makeSnapshot ) {
570 $this->destUploadDirectory = "{$this->dest}/{$this->imageRel}";
571 if ( realpath( $this->destUploadDirectory == $wgUploadDirectory ) ) {
572 $this->makeSnapshot = false;
573 }
574 }
575
576 $this->sharedStaticDirectory = "{$this->destUploadDirectory}/shared";
577
578 $this->setupDone = true;
579 }
580
581 /** Reads the content of a title object, executes the skin and captures the result */
582 function getArticleHTML( &$title ) {
583 global $wgOut, $wgTitle, $wgArticle, $wgUser;
584
585 $linkCache =& LinkCache::singleton();
586 $linkCache->clear();
587 $wgTitle = $title;
588 if ( is_null( $wgTitle ) ) {
589 return false;
590 }
591
592 $ns = $wgTitle->getNamespace();
593 if ( $ns == NS_SPECIAL ) {
594 $wgOut = new OutputPage;
595 $wgOut->setParserOptions( new ParserOptions );
596 SpecialPage::executePath( $wgTitle );
597 } else {
598 /** @todo merge with Wiki.php code */
599 if ( $ns == NS_IMAGE ) {
600 $wgArticle = new ImagePage( $wgTitle );
601 } elseif ( $ns == NS_CATEGORY ) {
602 $wgArticle = new CategoryPage( $wgTitle );
603 } else {
604 $wgArticle = new Article( $wgTitle );
605 }
606 $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
607 if ( $rt != NULL ) {
608 return $this->getRedirect( $rt );
609 } else {
610 $wgOut = new OutputPage;
611 $wgOut->setParserOptions( new ParserOptions );
612
613 $wgArticle->view();
614 }
615 }
616
617 $sk =& $wgUser->getSkin();
618 ob_start();
619 $sk->outputPage( $wgOut );
620 $text = ob_get_contents();
621 ob_end_clean();
622
623 return $text;
624 }
625
626 function getRedirect( $rt ) {
627 $url = $rt->escapeLocalURL();
628 $text = $rt->getPrefixedText();
629 return <<<ENDTEXT
630 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
631 <html xmlns="http://www.w3.org/1999/xhtml">
632 <head>
633 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
634 <meta http-equiv="Refresh" content="0;url=$url" />
635 </head>
636 <body>
637 <p>Redirecting to <a href="$url">$text</a></p>
638 </body>
639 </html>
640 ENDTEXT;
641 }
642
643 /** Returns image paths used in an XHTML document */
644 function findImages( $text ) {
645 global $wgOutputEncoding, $wgDumpImages;
646 $parser = xml_parser_create( $wgOutputEncoding );
647 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
648
649 $wgDumpImages = array();
650 xml_parse( $parser, $text );
651 xml_parser_free( $parser );
652
653 return $wgDumpImages;
654 }
655
656 /**
657 * Copy a file specified by a URL to a given directory
658 *
659 * @param string $srcPath The source URL
660 * @param string $srcPathBase The base directory of the source URL
661 * @param string $srcDirBase The base filesystem directory of the source URL
662 * @param string $destDirBase The base filesystem directory of the destination URL
663 */
664 function relativeCopy( $srcPath, $srcPathBase, $srcDirBase, $destDirBase ) {
665 $rel = substr( $srcPath, strlen( $srcPathBase ) + 1 ); // +1 for slash
666 $sourceLoc = "$srcDirBase/$rel";
667 $destLoc = "$destDirBase/$rel";
668 #print "Copying $sourceLoc to $destLoc\n";
669 if ( !file_exists( $destLoc ) ) {
670 wfMkdirParents( dirname( $destLoc ), 0755 );
671 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
672 symlink( $sourceLoc, $destLoc );
673 } else {
674 copy( $sourceLoc, $destLoc );
675 }
676 }
677 }
678
679 /**
680 * Copy an image, and if it is a thumbnail, copy its parent image too
681 */
682 function copyImage( $srcPath, $srcPathBase, $srcDirBase, $destDirBase ) {
683 global $wgUploadPath, $wgUploadDirectory, $wgSharedUploadPath;
684 $this->relativeCopy( $srcPath, $srcPathBase, $srcDirBase, $destDirBase );
685 if ( substr( $srcPath, strlen( $srcPathBase ) + 1, 6 ) == 'thumb/' ) {
686 # The image was a thumbnail
687 # Copy the source image as well
688 $rel = substr( $srcPath, strlen( $srcPathBase ) + 1 );
689 $parts = explode( '/', $rel );
690 $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
691 $newSrc = "$srcPathBase/$rel";
692 $this->relativeCopy( $newSrc, $srcPathBase, $srcDirBase, $destDirBase );
693 }
694 }
695
696 /**
697 * Copy images (or create symlinks) from commons to a static directory.
698 * This is necessary even if you intend to distribute all of commons, because
699 * the directory contents is used to work out which image description pages
700 * are needed.
701 *
702 * Also copies math images, and full-sized images if the makeSnapshot option
703 * is specified.
704 *
705 */
706 function copyImages( $images ) {
707 global $wgUploadPath, $wgUploadDirectory, $wgSharedUploadPath, $wgSharedUploadDirectory,
708 $wgMathPath, $wgMathDirectory;
709 # Find shared uploads and copy them into the static directory
710 $sharedPathLength = strlen( $wgSharedUploadPath );
711 $mathPathLength = strlen( $wgMathPath );
712 $uploadPathLength = strlen( $wgUploadPath );
713 foreach ( $images as $escapedImage => $dummy ) {
714 $image = urldecode( $escapedImage );
715
716 if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
717 $this->copyImage( $image, $wgSharedUploadPath, $wgSharedUploadDirectory, $this->sharedStaticDirectory );
718 } elseif ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
719 $this->relativeCopy( $image, $wgMathPath, $wgMathDirectory, "{$this->dest}/math" );
720 } elseif ( $this->makeSnapshot && substr( $image, 0, $uploadPathLength ) == $wgUploadPath ) {
721 $this->copyImage( $image, $wgUploadPath, $wgUploadDirectory, $this->destUploadDirectory );
722 }
723 }
724 }
725
726 function onGetFullURL( &$title, &$url, $query ) {
727 global $wgContLang, $wgArticlePath;
728
729 $iw = $title->getInterwiki();
730 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
731 if ( $title->getDBkey() == '' ) {
732 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
733 } else {
734 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
735 $wgArticlePath );
736 }
737 return false;
738 } else {
739 return true;
740 }
741 }
742
743 function onGetLocalURL( &$title, &$url, $query ) {
744 global $wgArticlePath;
745
746 if ( $title->isExternal() ) {
747 # Default is fine for interwiki
748 return true;
749 }
750
751 $url = false;
752 if ( $query != '' ) {
753 parse_str( $query, $params );
754 if ( isset($params['action']) && $params['action'] == 'raw' ) {
755 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
756 $file = 'gen.' . $params['gen'];
757 } else {
758 $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
759 // Clean up Monobook.css etc.
760 if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
761 $file = $matches[1] . '.' . $matches[2];
762 }
763 }
764 $this->rawPages[$file] = array( $file, $title, $params );
765 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
766 }
767 }
768 if ( $url === false ) {
769 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
770 }
771
772 return false;
773 }
774
775 function getHashedFilename( &$title ) {
776 if ( '' != $title->mInterwiki ) {
777 $dbkey = $title->getDBkey();
778 } else {
779 $dbkey = $title->getPrefixedDBkey();
780 }
781
782 $mainPage = Title::newMainPage();
783 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
784 return 'index.html';
785 }
786
787 return $this->getHashedDirectory( $title ) . '/' .
788 $this->getFriendlyName( $dbkey ) . '.html';
789 }
790
791 function getFriendlyName( $name ) {
792 global $wgLang;
793 # Replace illegal characters for Windows paths with underscores
794 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
795
796 # Work out lower case form. We assume we're on a system with case-insensitive
797 # filenames, so unless the case is of a special form, we have to disambiguate
798 if ( function_exists( 'mb_strtolower' ) ) {
799 $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
800 } else {
801 $lowerCase = ucfirst( strtolower( $name ) );
802 }
803
804 # Make it mostly unique
805 if ( $lowerCase != $friendlyName ) {
806 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
807 }
808 # Handle colon specially by replacing it with tilde
809 # Thus we reduce the number of paths with hashes appended
810 $friendlyName = str_replace( ':', '~', $friendlyName );
811
812 return $friendlyName;
813 }
814
815 /**
816 * Get a relative directory for putting a title into
817 */
818 function getHashedDirectory( &$title ) {
819 if ( '' != $title->getInterwiki() ) {
820 $pdbk = $title->getDBkey();
821 } else {
822 $pdbk = $title->getPrefixedDBkey();
823 }
824
825 # Find the first colon if there is one, use characters after it
826 $p = strpos( $pdbk, ':' );
827 if ( $p !== false ) {
828 $dbk = substr( $pdbk, $p + 1 );
829 $dbk = substr( $dbk, strspn( $dbk, '_' ) );
830 } else {
831 $dbk = $pdbk;
832 }
833
834 # Split into characters
835 preg_match_all( '/./us', $dbk, $m );
836
837 $chars = $m[0];
838 $length = count( $chars );
839 $dir = '';
840
841 for ( $i = 0; $i < $this->depth; $i++ ) {
842 if ( $i ) {
843 $dir .= '/';
844 }
845 if ( $i >= $length ) {
846 $dir .= '_';
847 } else {
848 $c = $chars[$i];
849 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
850 if ( function_exists( 'mb_strtolower' ) ) {
851 $dir .= mb_strtolower( $c );
852 } else {
853 $dir .= strtolower( $c );
854 }
855 } else {
856 $dir .= sprintf( "%02X", ord( $c ) );
857 }
858 }
859 }
860 return $dir;
861 }
862
863 /**
864 * Calculate the start end end of a job based on the current slice
865 * @param integer $start
866 * @param integer $end
867 * @return array of integers
868 */
869 function sliceRange( $start, $end ) {
870 $count = $end - $start + 1;
871 $each = $count / $this->sliceDenominator;
872 $sliceStart = $start + intval( $each * ( $this->sliceNumerator - 1 ) );
873 if ( $this->sliceNumerator == $this->sliceDenominator ) {
874 $sliceEnd = $end;
875 } else {
876 $sliceEnd = $start + intval( $each * $this->sliceNumerator ) - 1;
877 }
878 return array( $sliceStart, $sliceEnd );
879 }
880
881 /**
882 * Adjust a start point so that it belongs to the current slice, where slices are defined by integer modulo
883 * @param integer $start
884 * @param integer $base The true start of the range; the minimum start
885 */
886 function modSliceStart( $start, $base = 1 ) {
887 return $start - ( $start % $this->sliceDenominator ) + $this->sliceNumerator - 1 + $base;
888 }
889
890 /**
891 * Determine whether a string belongs to the current slice, based on hash
892 */
893 function sliceFilter( $s ) {
894 return crc32( $s ) % $this->sliceDenominator == $this->sliceNumerator - 1;
895 }
896
897 /**
898 * No site notice
899 */
900 function onSiteNoticeBefore( &$text ) {
901 $text = '';
902 return false;
903 }
904 function onSiteNoticeAfter( &$text ) {
905 $text = '';
906 return false;
907 }
908
909 function getMaxPageID() {
910 if ( $this->maxPageID === false ) {
911 $dbr =& wfGetDB( DB_SLAVE );
912 $this->maxPageID = $dbr->selectField( 'page', 'max(page_id)', false, __METHOD__ );
913 }
914 return $this->maxPageID;
915 }
916
917 }
918
919 /** XML parser callback */
920 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
921 global $wgDumpImages;
922
923 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
924 $wgDumpImages[$attribs['SRC']] = true;
925 }
926 }
927
928 /** XML parser callback */
929 function wfDumpEndTagHandler( $parser, $name ) {}
930
931 # vim: syn=php
932 ?>