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