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