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