Log job execution time
[mediawiki.git] / maintenance / dumpHTML.inc
blob2ed1e4a2c83fb8c633433fe91f7a17883a1a435d
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         # Show interlanguage links?
18         var $interwiki = true;
20         # Depth of HTML directory tree
21         var $depth = 3;
23         # Directory that commons images are copied into
24         var $sharedStaticPath;
26         # Relative path to image directory
27         var $imageRel = 'upload';
29         # Copy commons images instead of symlinking
30         var $forceCopy = false;
32         # Make links assuming the script path is in the same directory as
33         # the destination
34         var $alternateScriptPath = false;
36         # Original values of various globals
37         var $oldArticlePath = false, $oldCopyrightIcon = false;
39         # Has setupGlobals been called?
40         var $setupDone = false;
42         # List of raw pages used in the current article
43         var $rawPages;
44         
45         # Skin to use
46         var $skin = 'dumphtml';
48         function DumpHTML( $settings ) {
49                 foreach ( $settings as $var => $value ) {
50                         $this->$var = $value;
51                 }
52         }
54         /**
55          * Write a set of articles specified by start and end page_id
56          * Skip categories and images, they will be done separately
57          */
58         function doArticles( $start, $end = false ) {
59                 $fname = 'DumpHTML::doArticles';
61                 $this->setupGlobals();
63                 if ( $end === false ) {
64                         $dbr =& wfGetDB( DB_SLAVE );
65                         $end = $dbr->selectField( 'page', 'max(page_id)', false, $fname );
66                 }
68                 $mainPageObj = Title::newMainPage();
69                 $mainPage = $mainPageObj->getPrefixedDBkey();
72                 for ($id = $start; $id <= $end; $id++) {
73                         wfWaitForSlaves( 20 );
74                         if ( !($id % REPORTING_INTERVAL) ) {
75                                 print "Processing ID: $id\r";
76                         }
77                         if ( !($id % (REPORTING_INTERVAL*10) ) ) {
78                                 print "\n";
79                         }
80                         $title = Title::newFromID( $id );
81                         if ( $title ) {
82                                 $ns = $title->getNamespace() ;
83                                 if ( $ns != NS_CATEGORY && $title->getPrefixedDBkey() != $mainPage ) {
84                                         $this->doArticle( $title );
85                                 }
86                         }
87                 }
88                 print "\n";
89         }
91         function doSpecials() {
92                 $this->doMainPage();
94                 $this->setupGlobals();
95                 print "Special:Categories...";
96                 $this->doArticle( Title::makeTitle( NS_SPECIAL, 'Categories' ) );
97                 print "\n";
98         }
100         /** Write the main page as index.html */
101         function doMainPage() {
103                 print "Making index.html  ";
105                 // Set up globals with no ../../.. in the link URLs
106                 $this->setupGlobals( 0 );
108                 $title = Title::newMainPage();
109                 $text = $this->getArticleHTML( $title );
110                 $file = fopen( "{$this->dest}/index.html", "w" );
111                 if ( !$file ) {
112                         print "\nCan't open index.html for writing\n";
113                         return false;
114                 }
115                 fwrite( $file, $text );
116                 fclose( $file );
117                 print "\n";
118         }
120         function doImageDescriptions() {
121                 global $wgSharedUploadDirectory;
123                 $fname = 'DumpHTML::doImageDescriptions';
125                 $this->setupGlobals();
127                 /**
128                  * Dump image description pages that don't have an associated article, but do
129                  * have a local image
130                  */
131                 $dbr =& wfGetDB( DB_SLAVE );
132                 extract( $dbr->tableNames( 'image', 'page' ) );
133                 $res = $dbr->select( 'image', array( 'img_name' ), false, $fname );
135                 $i = 0;
136                 print "Writing image description pages for local images\n";
137                 $num = $dbr->numRows( $res );
138                 while ( $row = $dbr->fetchObject( $res ) ) {
139                         wfWaitForSlaves( 10 );
140                         if ( !( ++$i % REPORTING_INTERVAL ) ) {
141                                 print "Done $i of $num\r";
142                         }
143                         $title = Title::makeTitle( NS_IMAGE, $row->img_name );
144                         if ( $title->getArticleID() ) {
145                                 // Already done by dumpHTML
146                                 continue;
147                         }
148                         $this->doArticle( $title );
149                 }
150                 print "\n";
152                 /**
153                  * Dump images which only have a real description page on commons
154                  */
155                 print "Writing description pages for commons images\n";
156                 $i = 0;
157                 for ( $hash = 0; $hash < 256; $hash++ ) {
158                         $dir = sprintf( "%01x/%02x", intval( $hash / 16 ), $hash );
159                         $paths = array_merge( glob( "{$this->sharedStaticPath}/$dir/*" ),
160                                 glob( "{$this->sharedStaticPath}/thumb/$dir/*" ) );
162                         foreach ( $paths as $path ) {
163                                 $file = basename( $path );
164                                 if ( !(++$i % REPORTING_INTERVAL ) ) {
165                                         print "$i\r";
166                                 }
168                                 $title = Title::makeTitle( NS_IMAGE, $file );
169                                 $this->doArticle( $title );
170                         }
171                 }
172                 print "\n";
173         }
175         function doCategories() {
176                 $fname = 'DumpHTML::doCategories';
177                 $this->setupGlobals();
179                 $dbr =& wfGetDB( DB_SLAVE );
180                 print "Selecting categories...";
181                 $sql = 'SELECT DISTINCT cl_to FROM ' . $dbr->tableName( 'categorylinks' );
182                 $res = $dbr->query( $sql, $fname );
184                 print "\nWriting " . $dbr->numRows( $res ).  " category pages\n";
185                 $i = 0;
186                 while ( $row = $dbr->fetchObject( $res ) ) {
187                         wfWaitForSlaves( 10 );
188                         if ( !(++$i % REPORTING_INTERVAL ) ) {
189                                 print "$i\r";
190                         }
191                         $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
192                         $this->doArticle( $title );
193                 }
194                 print "\n";
195         }
197         function doRedirects() {
198                 print "Doing redirects...\n";
199                 $fname = 'DumpHTML::doRedirects';
200                 $this->setupGlobals();
201                 $dbr =& wfGetDB( DB_SLAVE );
203                 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
204                         array( 'page_is_redirect' => 1 ), $fname );
205                 $num = $dbr->numRows( $res );
206                 print "$num redirects to do...\n";
207                 $i = 0;
208                 while ( $row = $dbr->fetchObject( $res ) ) {
209                         $title = Title::makeTitle( $row->page_namespace, $row->page_title );
210                         if ( !(++$i % (REPORTING_INTERVAL*10) ) ) {
211                                 print "Done $i of $num\n";
212                         }
213                         $this->doArticle( $title );
214                 }
215         }
217         /** Write an article specified by title */
218         function doArticle( $title ) {
219                 global $wgTitle, $wgSharedUploadPath, $wgSharedUploadDirectory;
220                 global $wgUploadDirectory;
222                 $this->rawPages = array();
223                 $text = $this->getArticleHTML( $title );
225                 if ( $text === false ) {
226                         return;
227                 }
229                 # Parse the XHTML to find the images
230                 $images = $this->findImages( $text );
231                 $this->copyImages( $images );
233                 # Write to file
234                 $this->writeArticle( $title, $text );
236                 # Do raw pages
237                 wfMkdirParents( "{$this->dest}/raw", 0755 );
238                 foreach( $this->rawPages as $record ) {
239                         list( $file, $title, $params ) = $record;
241                         $path = "{$this->dest}/raw/$file";
242                         if ( !file_exists( $path ) ) {
243                                 $article = new Article( $title );
244                                 $request = new FauxRequest( $params );
245                                 $rp = new RawPage( $article, $request );
246                                 $text = $rp->getRawText();
248                                 print "Writing $file\n";
249                                 $file = fopen( $path, 'w' );
250                                 if ( !$file ) {
251                                         print("Can't open file $fullName for writing\n");
252                                         continue;
253                                 }
254                                 fwrite( $file, $text );
255                                 fclose( $file );
256                         }
257                 }
258         }
260         /** Write the given text to the file identified by the given title object */
261         function writeArticle( &$title, $text ) {
262                 $filename = $this->getHashedFilename( $title );
263                 $fullName = "{$this->dest}/$filename";
264                 $fullDir = dirname( $fullName );
266                 wfMkdirParents( $fullDir, 0755 );
268                 $file = fopen( $fullName, 'w' );
269                 if ( !$file ) {
270                         print("Can't open file $fullName for writing\n");
271                         return;
272                 }
274                 fwrite( $file, $text );
275                 fclose( $file );
276         }
278         /** Set up globals required for parsing */
279         function setupGlobals( $currentDepth = NULL ) {
280                 global $wgUser, $wgTitle, $wgStylePath, $wgArticlePath, $wgMathPath;
281                 global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
282                 global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
283                 global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
284                 global $wgRightsUrl, $wgRightsText, $wgCopyrightIcon;
286                 static $oldLogo = NULL;
288                 if ( !$this->setupDone ) {
289                         $wgHooks['GetLocalURL'][] =& $this;
290                         $wgHooks['GetFullURL'][] =& $this;
291                         $this->oldArticlePath = $wgServer . $wgArticlePath;
292                 }
294                 if ( is_null( $currentDepth ) ) {
295                         $currentDepth = $this->depth;
296                 }
298                 if ( $this->alternateScriptPath ) {
299                         if ( $currentDepth == 0 ) {
300                                 $wgScriptPath = '.';
301                         } else {
302                                 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth - 1 );
303                         }
304                 } else {
305                         $wgScriptPath = '..' . str_repeat( '/..', $currentDepth );
306                 }
308                 $wgArticlePath = str_repeat( '../', $currentDepth ) . '$1';
310                 # Logo image
311                 # Allow for repeated setup
312                 if ( !is_null( $oldLogo ) ) {
313                         $wgLogo = $oldLogo;
314                 } else {
315                         $oldLogo = $wgLogo;
316                 }
318                 if ( strpos( $wgLogo, $wgUploadPath ) === 0 ) {
319                         # If it's in the upload directory, rewrite it to the new upload directory
320                         $wgLogo = "$wgScriptPath/{$this->imageRel}/" . substr( $wgLogo, strlen( $wgUploadPath ) + 1 );
321                 } elseif ( $wgLogo{0} == '/' ) {
322                         # This is basically heuristic
323                         # Rewrite an absolute logo path to one relative to the the script path
324                         $wgLogo = $wgScriptPath . $wgLogo;
325                 }
327                 # Another ugly hack
328                 if ( !$this->setupDone ) {
329                         $this->oldCopyrightIcon = $wgCopyrightIcon;
330                 }
331                 $wgCopyrightIcon = str_replace( 'src="/images',
332                         'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $this->oldCopyrightIcon );
336                 $wgStylePath = "$wgScriptPath/skins";
337                 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
338                 $wgSharedUploadPath = "$wgUploadPath/shared";
339                 $wgMaxCredits = -1;
340                 $wgHideInterlanguageLinks = !$this->interwiki;
341                 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
342                 $wgEnableParserCache = false;
343                 $wgMathPath = "$wgScriptPath/math";
345                 if ( !empty( $wgRightsText ) ) {
346                         $wgRightsUrl = "$wgScriptPath/COPYING.html";
347                 }
349                 $wgUser = new User;
350                 $wgUser->setOption( 'skin', $this->skin );
351                 $wgUser->setOption( 'editsection', 0 );
353                 $this->sharedStaticPath = "$wgUploadDirectory/shared";
355                 $this->setupDone = true;
356         }
358         /** Reads the content of a title object, executes the skin and captures the result */
359         function getArticleHTML( &$title ) {
360                 global $wgOut, $wgTitle, $wgArticle, $wgUser;
362                 $linkCache =& LinkCache::singleton();
363                 $linkCache->clear();
364                 $wgTitle = $title;
365                 if ( is_null( $wgTitle ) ) {
366                         return false;
367                 }
369                 $ns = $wgTitle->getNamespace();
370                 if ( $ns == NS_SPECIAL ) {
371                         $wgOut = new OutputPage;
372                         $wgOut->setParserOptions( new ParserOptions );
373                         SpecialPage::executePath( $wgTitle );
374                 } else {
375                         /** @todo merge with Wiki.php code */
376                         if ( $ns == NS_IMAGE ) {
377                                 $wgArticle = new ImagePage( $wgTitle );
378                         } elseif ( $ns == NS_CATEGORY ) {
379                                 $wgArticle = new CategoryPage( $wgTitle );
380                         } else {
381                                 $wgArticle = new Article( $wgTitle );
382                         }
383                         $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
384                         if ( $rt != NULL ) {
385                                 return $this->getRedirect( $rt );
386                         } else {
387                                 $wgOut = new OutputPage;
388                                 $wgOut->setParserOptions( new ParserOptions );
390                                 $wgArticle->view();
391                         }
392                 }
394                 $sk =& $wgUser->getSkin();
395                 ob_start();
396                 $sk->outputPage( $wgOut );
397                 $text = ob_get_contents();
398                 ob_end_clean();
400                 return $text;
401         }
403         function getRedirect( $rt ) {
404                 $url = $rt->escapeLocalURL();
405                 $text = $rt->getPrefixedText();
406                 return <<<ENDTEXT
407 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
408 <html xmlns="http://www.w3.org/1999/xhtml">
409 <head>
410   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
411   <meta http-equiv="Refresh" content="0;url=$url" />
412 </head>
413 <body>
414   <p>Redirecting to <a href="$url">$text</a></p>
415 </body>
416 </html>
417 ENDTEXT;
418         }
420         /** Returns image paths used in an XHTML document */
421         function findImages( $text ) {
422                 global $wgOutputEncoding, $wgDumpImages;
423                 $parser = xml_parser_create( $wgOutputEncoding );
424                 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
426                 $wgDumpImages = array();
427                 xml_parse( $parser, $text );
428                 xml_parser_free( $parser );
430                 return $wgDumpImages;
431         }
433         /**
434          * Copy images (or create symlinks) from commons to a static directory.
435          * This is necessary even if you intend to distribute all of commons, because
436          * the directory contents is used to work out which image description pages
437          * are needed.
438          *
439          * Also copies math images
440          *
441          */
442         function copyImages( $images ) {
443                 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
444                 # Find shared uploads and copy them into the static directory
445                 $sharedPathLength = strlen( $wgSharedUploadPath );
446                 $mathPathLength = strlen( $wgMathPath );
447                 foreach ( $images as $escapedImage => $dummy ) {
448                         $image = urldecode( $escapedImage );
450                         # Is it shared?
451                         if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
452                                 # Reconstruct full filename
453                                 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
454                                 $sourceLoc = "$wgSharedUploadDirectory/$rel";
455                                 $staticLoc = "{$this->sharedStaticPath}/$rel";
456                                 #print "Copying $sourceLoc to $staticLoc\n";
457                                 # Copy to static directory
458                                 if ( !file_exists( $staticLoc ) ) {
459                                         wfMkdirParents( dirname( $staticLoc ), 0755 );
460                                         if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
461                                                 symlink( $sourceLoc, $staticLoc );
462                                         } else {
463                                                 copy( $sourceLoc, $staticLoc );
464                                         }
465                                 }
467                                 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
468                                         # That was a thumbnail
469                                         # We will also copy the real image
470                                         $parts = explode( '/', $rel );
471                                         $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
472                                         $sourceLoc = "$wgSharedUploadDirectory/$rel";
473                                         $staticLoc = "{$this->sharedStaticPath}/$rel";
474                                         #print "Copying $sourceLoc to $staticLoc\n";
475                                         if ( !file_exists( $staticLoc ) ) {
476                                                 wfMkdirParents( dirname( $staticLoc ), 0755 );
477                                                 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
478                                                         symlink( $sourceLoc, $staticLoc );
479                                                 } else {
480                                                         copy( $sourceLoc, $staticLoc );
481                                                 }
482                                         }
483                                 }
484                         } else
485                         # Is it math?
486                         if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
487                                 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
488                                 $source = "$wgMathDirectory/$rel";
489                                 $dest = "{$this->dest}/math/$rel";
490                                 @mkdir( "{$this->dest}/math", 0755 );
491                                 if ( !file_exists( $dest ) ) {
492                                         copy( $source, $dest );
493                                 }
494                         }
495                 }
496         }
498         function onGetFullURL( &$title, &$url, $query ) {
499                 global $wgContLang, $wgArticlePath;
501                 $iw = $title->getInterwiki();
502                 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
503                         if ( $title->getDBkey() == '' ) {
504                                 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
505                         } else {
506                                 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
507                                         $wgArticlePath );
508                         }
509                         return false;
510                 } else {
511                         return true;
512                 }
513         }
515         function onGetLocalURL( &$title, &$url, $query ) {
516                 global $wgArticlePath;
518                 if ( $title->isExternal() ) {
519                         # Default is fine for interwiki
520                         return true;
521                 }
523                 $url = false;
524                 if ( $query != '' ) {
525                         parse_str( $query, $params );
526                         if ( isset($params['action']) && $params['action'] == 'raw' ) {
527                                 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
528                                         $file = 'gen.' . $params['gen'];
529                                 } else {
530                                         $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
531                                         // Clean up Monobook.css etc.
532                                         if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
533                                                 $file = $matches[1] . '.' . $matches[2];
534                                         }
535                                 }
536                                 $this->rawPages[$file] = array( $file, $title, $params );
537                                 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
538                         }
539                 }
540                 if ( $url === false ) {
541                         $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
542                 }
544                 return false;
545         }
547         function getHashedFilename( &$title ) {
548                 if ( '' != $title->mInterwiki ) {
549                         $dbkey = $title->getDBkey();
550                 } else {
551                         $dbkey = $title->getPrefixedDBkey();
552                 }
554                 $mainPage = Title::newMainPage();
555                 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
556                         return 'index.html';
557                 }
559                 return $this->getHashedDirectory( $title ) . '/' .
560                         $this->getFriendlyName( $dbkey ) . '.html';
561         }
563         function getFriendlyName( $name ) {
564                 global $wgLang;
565                 # Replace illegal characters for Windows paths with underscores
566                 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
568                 # Work out lower case form. We assume we're on a system with case-insensitive
569                 # filenames, so unless the case is of a special form, we have to disambiguate
570                 if ( function_exists( 'mb_strtolower' ) ) {
571                         $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
572                 } else {
573                         $lowerCase = ucfirst( strtolower( $name ) );
574                 }
576                 # Make it mostly unique
577                 if ( $lowerCase != $friendlyName  ) {
578                         $friendlyName .= '_' . substr(md5( $name ), 0, 4);
579                 }
580                 # Handle colon specially by replacing it with tilde
581                 # Thus we reduce the number of paths with hashes appended
582                 $friendlyName = str_replace( ':', '~', $friendlyName );
584                 return $friendlyName;
585         }
587         /**
588          * Get a relative directory for putting a title into
589          */
590         function getHashedDirectory( &$title ) {
591                 if ( '' != $title->getInterwiki() ) {
592                         $pdbk = $title->getDBkey();
593                 } else {
594                         $pdbk = $title->getPrefixedDBkey();
595                 }
597                 # Find the first colon if there is one, use characters after it
598                 $p = strpos( $pdbk, ':' );
599                 if ( $p !== false ) {
600                         $dbk = substr( $pdbk, $p + 1 );
601                         $dbk = substr( $dbk, strspn( $dbk, '_' ) );
602                 } else {
603                         $dbk = $pdbk;
604                 }
606                 # Split into characters
607                 preg_match_all( '/./us', $dbk, $m );
609                 $chars = $m[0];
610                 $length = count( $chars );
611                 $dir = '';
613                 for ( $i = 0; $i < $this->depth; $i++ ) {
614                         if ( $i ) {
615                                 $dir .= '/';
616                         }
617                         if ( $i >= $length ) {
618                                 $dir .= '_';
619                         } else {
620                                 $c = $chars[$i];
621                                 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
622                                         if ( function_exists( 'mb_strtolower' ) ) {
623                                                 $dir .= mb_strtolower( $c );
624                                         } else {
625                                                 $dir .= strtolower( $c );
626                                         }
627                                 } else {
628                                         $dir .= sprintf( "%02X", ord( $c ) );
629                                 }
630                         }
631                 }
632                 return $dir;
633         }
637 /** XML parser callback */
638 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
639         global $wgDumpImages;
641         if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
642                 $wgDumpImages[$attribs['SRC']] = true;
643         }
646 /** XML parser callback */
647 function wfDumpEndTagHandler( $parser, $name ) {}
649 # vim: syn=php