* Made special page names case-insensitive and localisable. Care has been taken to...
[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->doLocalImageDescriptions();
128 $this->doSharedImageDescriptions();
129 $this->doCategories();
130 $this->doRedirects();
131 if ( $this->sliceNumerator == 1 ) {
132 $this->doSpecials();
133 }
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( "%01x/%02x", intval( $hash / 16 ), $hash );
313 $paths = array_merge( glob( "{$this->sharedStaticDirectory}/$dir/*" ),
314 glob( "{$this->sharedStaticDirectory}/thumb/$dir/*" ) );
315
316 foreach ( $paths as $path ) {
317 $file = wfBaseName( $path );
318 if ( !(++$i % REPORTING_INTERVAL ) ) {
319 print "$i\r";
320 }
321
322 $title = Title::makeTitle( NS_IMAGE, $file );
323 $this->doArticle( $title );
324 }
325 }
326 $this->setCheckpoint( 'shared image', 'done' );
327 print "\n";
328 }
329
330 function doCategories() {
331 $chunkSize = 1000;
332
333 $this->setupGlobals();
334 $dbr =& wfGetDB( DB_SLAVE );
335
336 $cp = $this->getCheckpoint( 'category' );
337 if ( $cp == 'done' ) {
338 print "Category pages already done\n";
339 return;
340 } elseif ( $cp !== false ) {
341 print "Resuming category page dump from $cp\n";
342 $conds = array( 'cl_to >= ' . $dbr->addQuotes( $cp ) );
343 } else {
344 print "Starting category pages\n";
345 $conds = false;
346 }
347
348 $i = 0;
349 do {
350 $res = $dbr->select( 'categorylinks', 'DISTINCT cl_to', $conds, __METHOD__,
351 array( 'ORDER BY' => 'cl_to', 'LIMIT' => $chunkSize ) );
352 $numRows = $dbr->numRows( $res );
353
354 while ( $row = $dbr->fetchObject( $res ) ) {
355 // Set conditions for next chunk
356 $conds = array( 'cl_to > ' . $dbr->addQuotes( $row->cl_to ) );
357
358 // Filter pages from other slices
359 if ( !$this->sliceFilter( $row->cl_to ) ) {
360 continue;
361 }
362
363 wfWaitForSlaves( 10 );
364 if ( !(++$i % REPORTING_INTERVAL ) ) {
365 print "{$row->cl_to}\n";
366 if ( $row->cl_to != 'done' ) {
367 $this->setCheckpoint( 'category', $row->cl_to );
368 }
369 }
370 $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
371 $this->doArticle( $title );
372 }
373 $dbr->freeResult( $res );
374 } while ( $numRows );
375
376 $this->setCheckpoint( 'category', 'done' );
377 print "\n";
378 }
379
380 function doRedirects() {
381 print "Doing redirects...\n";
382
383 $chunkSize = 10000;
384 $end = $this->getMaxPageID();
385 $cp = $this->getCheckpoint( 'redirect' );
386 if ( $cp == 'done' ) {
387 print "Redirects already done\n";
388 return;
389 } elseif ( $cp !== false ) {
390 print "Resuming redirect generation from page_id $cp\n";
391 $start = intval( $cp );
392 } else {
393 $start = 1;
394 }
395
396 $this->setupGlobals();
397 $dbr =& wfGetDB( DB_SLAVE );
398 $i = 0;
399
400 for ( $chunkStart = $start; $chunkStart <= $end; $chunkStart += $chunkSize ) {
401 $chunkEnd = min( $end, $chunkStart + $chunkSize - 1 );
402 $conds = array(
403 'page_is_redirect' => 1,
404 "page_id BETWEEN $chunkStart AND $chunkEnd"
405 );
406 # Modulo slicing in SQL
407 if ( $this->sliceDenominator != 1 ) {
408 $n = intval( $this->sliceNumerator );
409 $m = intval( $this->sliceDenominator );
410 $conds[] = "page_id % $m = $n";
411 }
412 $res = $dbr->select( 'page', array( 'page_id', 'page_namespace', 'page_title' ),
413 $conds, __METHOD__ );
414
415 while ( $row = $dbr->fetchObject( $res ) ) {
416 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
417 if ( !(++$i % (REPORTING_INTERVAL*10) ) ) {
418 printf( "Done %d redirects (%2.3f%%)\n", $i, $row->page_id / $end * 100 );
419 $this->setCheckpoint( 'redirect', $row->page_id );
420 }
421 $this->doArticle( $title );
422 }
423 $dbr->freeResult( $res );
424 }
425 $this->setCheckpoint( 'redirect', 'done' );
426 }
427
428 /** Write an article specified by title */
429 function doArticle( $title ) {
430 global $wgTitle, $wgSharedUploadPath, $wgSharedUploadDirectory;
431 global $wgUploadDirectory;
432
433 if ( $this->noOverwrite ) {
434 $fileName = $this->dest.'/'.$this->getHashedFilename( $title );
435 if ( file_exists( $fileName ) ) {
436 return;
437 }
438 }
439
440 $this->rawPages = array();
441 $text = $this->getArticleHTML( $title );
442
443 if ( $text === false ) {
444 return;
445 }
446
447 # Parse the XHTML to find the images
448 $images = $this->findImages( $text );
449 $this->copyImages( $images );
450
451 # Write to file
452 $this->writeArticle( $title, $text );
453
454 # Do raw pages
455 wfMkdirParents( "{$this->dest}/raw", 0755 );
456 foreach( $this->rawPages as $record ) {
457 list( $file, $title, $params ) = $record;
458
459 $path = "{$this->dest}/raw/$file";
460 if ( !file_exists( $path ) ) {
461 $article = new Article( $title );
462 $request = new FauxRequest( $params );
463 $rp = new RawPage( $article, $request );
464 $text = $rp->getRawText();
465
466 print "Writing $file\n";
467 $file = fopen( $path, 'w' );
468 if ( !$file ) {
469 print("Can't open file $fullName for writing\n");
470 continue;
471 }
472 fwrite( $file, $text );
473 fclose( $file );
474 }
475 }
476 }
477
478 /** Write the given text to the file identified by the given title object */
479 function writeArticle( &$title, $text ) {
480 $filename = $this->getHashedFilename( $title );
481 $fullName = "{$this->dest}/$filename";
482 $fullDir = dirname( $fullName );
483
484 if ( $this->compress ) {
485 $fullName .= ".gz";
486 $text = gzencode( $text, 9 );
487 }
488
489 wfMkdirParents( $fullDir, 0755 );
490
491 wfSuppressWarnings();
492 $file = fopen( $fullName, 'w' );
493 wfRestoreWarnings();
494
495 if ( !$file ) {
496 die("Can't open file '$fullName' for writing.\nCheck permissions or use another destination (-d).\n");
497 return;
498 }
499
500 fwrite( $file, $text );
501 fclose( $file );
502 }
503
504 /** Set up globals required for parsing */
505 function setupGlobals( $currentDepth = NULL ) {
506 global $wgUser, $wgTitle, $wgStylePath, $wgArticlePath, $wgMathPath;
507 global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
508 global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
509 global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
510 global $wgRightsUrl, $wgRightsText, $wgCopyrightIcon, $wgEnableSidebarCache;
511 global $wgGenerateThumbnailOnParse;
512
513 static $oldLogo = NULL;
514
515 if ( !$this->setupDone ) {
516 $wgHooks['GetLocalURL'][] =& $this;
517 $wgHooks['GetFullURL'][] =& $this;
518 $wgHooks['SiteNoticeBefore'][] =& $this;
519 $wgHooks['SiteNoticeAfter'][] =& $this;
520 $this->oldArticlePath = $wgServer . $wgArticlePath;
521 }
522
523 if ( is_null( $currentDepth ) ) {
524 $currentDepth = $this->depth;
525 }
526
527 if ( $this->alternateScriptPath ) {
528 if ( $currentDepth == 0 ) {
529 $wgScriptPath = '.';
530 } else {
531 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth - 1 );
532 }
533 } else {
534 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth );
535 }
536
537 $wgArticlePath = str_repeat( '../', $currentDepth ) . '$1';
538
539 # Logo image
540 # Allow for repeated setup
541 if ( !is_null( $oldLogo ) ) {
542 $wgLogo = $oldLogo;
543 } else {
544 $oldLogo = $wgLogo;
545 }
546
547 if ( strpos( $wgLogo, $wgUploadPath ) === 0 ) {
548 # If it's in the upload directory, rewrite it to the new upload directory
549 $wgLogo = "$wgScriptPath/{$this->imageRel}/" . substr( $wgLogo, strlen( $wgUploadPath ) + 1 );
550 } elseif ( $wgLogo{0} == '/' ) {
551 # This is basically heuristic
552 # Rewrite an absolute logo path to one relative to the the script path
553 $wgLogo = $wgScriptPath . $wgLogo;
554 }
555
556 # Another ugly hack
557 if ( !$this->setupDone ) {
558 $this->oldCopyrightIcon = $wgCopyrightIcon;
559 }
560 $wgCopyrightIcon = str_replace( 'src="/images',
561 'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $this->oldCopyrightIcon );
562
563 $wgStylePath = "$wgScriptPath/skins";
564 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
565 $wgSharedUploadPath = "$wgUploadPath/shared";
566 $wgMaxCredits = -1;
567 $wgHideInterlanguageLinks = !$this->interwiki;
568 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
569 $wgEnableParserCache = false;
570 $wgMathPath = "$wgScriptPath/math";
571 $wgEnableSidebarCache = false;
572 $wgGenerateThumbnailOnParse = true;
573
574 if ( !empty( $wgRightsText ) ) {
575 $wgRightsUrl = "$wgScriptPath/COPYING.html";
576 }
577
578 $wgUser = new User;
579 $wgUser->setOption( 'skin', $this->skin );
580 $wgUser->setOption( 'editsection', 0 );
581
582 if ( $this->makeSnapshot ) {
583 $this->destUploadDirectory = "{$this->dest}/{$this->imageRel}";
584 if ( realpath( $this->destUploadDirectory == $wgUploadDirectory ) ) {
585 $this->makeSnapshot = false;
586 }
587 }
588
589 $this->sharedStaticDirectory = "{$this->destUploadDirectory}/shared";
590
591 $this->setupDone = true;
592 }
593
594 /** Reads the content of a title object, executes the skin and captures the result */
595 function getArticleHTML( &$title ) {
596 global $wgOut, $wgTitle, $wgArticle, $wgUser;
597
598 $linkCache =& LinkCache::singleton();
599 $linkCache->clear();
600 $wgTitle = $title;
601 if ( is_null( $wgTitle ) ) {
602 return false;
603 }
604
605 $ns = $wgTitle->getNamespace();
606 if ( $ns == NS_SPECIAL ) {
607 $wgOut = new OutputPage;
608 $wgOut->setParserOptions( new ParserOptions );
609 SpecialPage::executePath( $wgTitle );
610 } else {
611 /** @todo merge with Wiki.php code */
612 if ( $ns == NS_IMAGE ) {
613 $wgArticle = new ImagePage( $wgTitle );
614 } elseif ( $ns == NS_CATEGORY ) {
615 $wgArticle = new CategoryPage( $wgTitle );
616 } else {
617 $wgArticle = new Article( $wgTitle );
618 }
619 $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
620 if ( $rt != NULL ) {
621 return $this->getRedirect( $rt );
622 } else {
623 $wgOut = new OutputPage;
624 $wgOut->setParserOptions( new ParserOptions );
625
626 $wgArticle->view();
627 }
628 }
629
630
631 $sk =& $wgUser->getSkin();
632 ob_start();
633 $sk->outputPage( $wgOut );
634 $text = ob_get_contents();
635 ob_end_clean();
636
637 return $text;
638 }
639
640 function getRedirect( $rt ) {
641 $url = $rt->escapeLocalURL();
642 $text = $rt->getPrefixedText();
643 return <<<ENDTEXT
644 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
645 <html xmlns="http://www.w3.org/1999/xhtml">
646 <head>
647 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
648 <meta http-equiv="Refresh" content="0;url=$url" />
649 </head>
650 <body>
651 <p>Redirecting to <a href="$url">$text</a></p>
652 </body>
653 </html>
654 ENDTEXT;
655 }
656
657 /** Returns image paths used in an XHTML document */
658 function findImages( $text ) {
659 global $wgOutputEncoding, $wgDumpImages;
660 $parser = xml_parser_create( $wgOutputEncoding );
661 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
662
663 $wgDumpImages = array();
664 xml_parse( $parser, $text );
665 xml_parser_free( $parser );
666
667 return $wgDumpImages;
668 }
669
670 /**
671 * Copy a file specified by a URL to a given directory
672 *
673 * @param string $srcPath The source URL
674 * @param string $srcPathBase The base directory of the source URL
675 * @param string $srcDirBase The base filesystem directory of the source URL
676 * @param string $destDirBase The base filesystem directory of the destination URL
677 */
678 function relativeCopy( $srcPath, $srcPathBase, $srcDirBase, $destDirBase ) {
679 $rel = substr( $srcPath, strlen( $srcPathBase ) + 1 ); // +1 for slash
680 $sourceLoc = "$srcDirBase/$rel";
681 $destLoc = "$destDirBase/$rel";
682 #print "Copying $sourceLoc to $destLoc\n";
683 if ( !file_exists( $destLoc ) ) {
684 wfMkdirParents( dirname( $destLoc ), 0755 );
685 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
686 symlink( $sourceLoc, $destLoc );
687 } else {
688 copy( $sourceLoc, $destLoc );
689 }
690 }
691 }
692
693 /**
694 * Copy an image, and if it is a thumbnail, copy its parent image too
695 */
696 function copyImage( $srcPath, $srcPathBase, $srcDirBase, $destDirBase ) {
697 global $wgUploadPath, $wgUploadDirectory, $wgSharedUploadPath;
698 $this->relativeCopy( $srcPath, $srcPathBase, $srcDirBase, $destDirBase );
699 if ( substr( $srcPath, strlen( $srcPathBase ) + 1, 6 ) == 'thumb/' ) {
700 # The image was a thumbnail
701 # Copy the source image as well
702 $rel = substr( $srcPath, strlen( $srcPathBase ) + 1 );
703 $parts = explode( '/', $rel );
704 $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
705 $newSrc = "$srcPathBase/$rel";
706 $this->relativeCopy( $newSrc, $srcPathBase, $srcDirBase, $destDirBase );
707 }
708 }
709
710 /**
711 * Copy images (or create symlinks) from commons to a static directory.
712 * This is necessary even if you intend to distribute all of commons, because
713 * the directory contents is used to work out which image description pages
714 * are needed.
715 *
716 * Also copies math images, and full-sized images if the makeSnapshot option
717 * is specified.
718 *
719 */
720 function copyImages( $images ) {
721 global $wgUploadPath, $wgUploadDirectory, $wgSharedUploadPath, $wgSharedUploadDirectory,
722 $wgMathPath, $wgMathDirectory;
723 # Find shared uploads and copy them into the static directory
724 $sharedPathLength = strlen( $wgSharedUploadPath );
725 $mathPathLength = strlen( $wgMathPath );
726 $uploadPathLength = strlen( $wgUploadPath );
727 foreach ( $images as $escapedImage => $dummy ) {
728 $image = urldecode( $escapedImage );
729
730 if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
731 $this->copyImage( $image, $wgSharedUploadPath, $wgSharedUploadDirectory, $this->sharedStaticDirectory );
732 } elseif ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
733 $this->relativeCopy( $image, $wgMathPath, $wgMathDirectory, "{$this->dest}/math" );
734 } elseif ( $this->makeSnapshot && substr( $image, 0, $uploadPathLength ) == $wgUploadPath ) {
735 $this->copyImage( $image, $wgUploadPath, $wgUploadDirectory, $this->destUploadDirectory );
736 }
737 }
738 }
739
740 function onGetFullURL( &$title, &$url, $query ) {
741 global $wgContLang, $wgArticlePath;
742
743 $iw = $title->getInterwiki();
744 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
745 if ( $title->getDBkey() == '' ) {
746 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
747 } else {
748 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
749 $wgArticlePath );
750 }
751 $url .= $this->compress ? ".gz" : "";
752 return false;
753 } else {
754 return true;
755 }
756 }
757
758 function onGetLocalURL( &$title, &$url, $query ) {
759 global $wgArticlePath;
760
761 if ( $title->isExternal() ) {
762 # Default is fine for interwiki
763 return true;
764 }
765
766 $url = false;
767 if ( $query != '' ) {
768 parse_str( $query, $params );
769 if ( isset($params['action']) && $params['action'] == 'raw' ) {
770 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
771 $file = 'gen.' . $params['gen'];
772 } else {
773 $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
774 // Clean up Monobook.css etc.
775 if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
776 $file = $matches[1] . '.' . $matches[2];
777 }
778 }
779 $this->rawPages[$file] = array( $file, $title, $params );
780 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
781 }
782 }
783 if ( $url === false ) {
784 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
785 }
786 $url .= $this->compress ? ".gz" : "";
787 return false;
788 }
789
790 function getHashedFilename( &$title ) {
791 if ( '' != $title->mInterwiki ) {
792 $dbkey = $title->getDBkey();
793 } else {
794 $dbkey = $title->getPrefixedDBkey();
795 }
796
797 $mainPage = Title::newMainPage();
798 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
799 return 'index.html';
800 }
801
802 return $this->getHashedDirectory( $title ) . '/' .
803 $this->getFriendlyName( $dbkey ) . '.html';
804 }
805
806 function getFriendlyName( $name ) {
807 global $wgLang;
808 # Replace illegal characters for Windows paths with underscores
809 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
810
811 # Work out lower case form. We assume we're on a system with case-insensitive
812 # filenames, so unless the case is of a special form, we have to disambiguate
813 if ( function_exists( 'mb_strtolower' ) ) {
814 $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
815 } else {
816 $lowerCase = ucfirst( strtolower( $name ) );
817 }
818
819 # Make it mostly unique
820 if ( $lowerCase != $friendlyName ) {
821 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
822 }
823 # Handle colon specially by replacing it with tilde
824 # Thus we reduce the number of paths with hashes appended
825 $friendlyName = str_replace( ':', '~', $friendlyName );
826
827 return $friendlyName;
828 }
829
830 /**
831 * Get a relative directory for putting a title into
832 */
833 function getHashedDirectory( &$title ) {
834 if ( '' != $title->getInterwiki() ) {
835 $pdbk = $title->getDBkey();
836 } else {
837 $pdbk = $title->getPrefixedDBkey();
838 }
839
840 # Find the first colon if there is one, use characters after it
841 $p = strpos( $pdbk, ':' );
842 if ( $p !== false ) {
843 $dbk = substr( $pdbk, $p + 1 );
844 $dbk = substr( $dbk, strspn( $dbk, '_' ) );
845 } else {
846 $dbk = $pdbk;
847 }
848
849 # Split into characters
850 preg_match_all( '/./us', $dbk, $m );
851
852 $chars = $m[0];
853 $length = count( $chars );
854 $dir = '';
855
856 for ( $i = 0; $i < $this->depth; $i++ ) {
857 if ( $i ) {
858 $dir .= '/';
859 }
860 if ( $i >= $length ) {
861 $dir .= '_';
862 } else {
863 $c = $chars[$i];
864 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
865 if ( function_exists( 'mb_strtolower' ) ) {
866 $dir .= mb_strtolower( $c );
867 } else {
868 $dir .= strtolower( $c );
869 }
870 } else {
871 $dir .= sprintf( "%02X", ord( $c ) );
872 }
873 }
874 }
875 return $dir;
876 }
877
878 /**
879 * Calculate the start end end of a job based on the current slice
880 * @param integer $start
881 * @param integer $end
882 * @return array of integers
883 */
884 function sliceRange( $start, $end ) {
885 $count = $end - $start + 1;
886 $each = $count / $this->sliceDenominator;
887 $sliceStart = $start + intval( $each * ( $this->sliceNumerator - 1 ) );
888 if ( $this->sliceNumerator == $this->sliceDenominator ) {
889 $sliceEnd = $end;
890 } else {
891 $sliceEnd = $start + intval( $each * $this->sliceNumerator ) - 1;
892 }
893 return array( $sliceStart, $sliceEnd );
894 }
895
896 /**
897 * Adjust a start point so that it belongs to the current slice, where slices are defined by integer modulo
898 * @param integer $start
899 * @param integer $base The true start of the range; the minimum start
900 */
901 function modSliceStart( $start, $base = 1 ) {
902 return $start - ( $start % $this->sliceDenominator ) + $this->sliceNumerator - 1 + $base;
903 }
904
905 /**
906 * Determine whether a string belongs to the current slice, based on hash
907 */
908 function sliceFilter( $s ) {
909 return crc32( $s ) % $this->sliceDenominator == $this->sliceNumerator - 1;
910 }
911
912 /**
913 * No site notice
914 */
915 function onSiteNoticeBefore( &$text ) {
916 $text = '';
917 return false;
918 }
919 function onSiteNoticeAfter( &$text ) {
920 $text = '';
921 return false;
922 }
923
924 function getMaxPageID() {
925 if ( $this->maxPageID === false ) {
926 $dbr =& wfGetDB( DB_SLAVE );
927 $this->maxPageID = $dbr->selectField( 'page', 'max(page_id)', false, __METHOD__ );
928 }
929 return $this->maxPageID;
930 }
931
932 }
933
934 /** XML parser callback */
935 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
936 global $wgDumpImages;
937
938 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
939 $wgDumpImages[$attribs['SRC']] = true;
940 }
941 }
942
943 /** XML parser callback */
944 function wfDumpEndTagHandler( $parser, $name ) {}
945
946 # vim: syn=php
947 ?>