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