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