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