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