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