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