* (bug 7061) Format title on "from (page)" links on Special:Allpages
[mediawiki.git] / maintenance / dumpHTML.inc
blob6adcb8da08469c1a761055d190f2455016fdb0ba
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         # 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                 wfSuppressWarnings();
269                 $file = fopen( $fullName, 'w' );
270                 wfRestoreWarnings();
272                 if ( !$file ) {
273                         die("Can't open file '$fullName' for writing.\nCheck permissions or use another destination (-d).\n");
274                         return;
275                 }
277                 fwrite( $file, $text );
278                 fclose( $file );
279         }
281         /** Set up globals required for parsing */
282         function setupGlobals( $currentDepth = NULL ) {
283                 global $wgUser, $wgTitle, $wgStylePath, $wgArticlePath, $wgMathPath;
284                 global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
285                 global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
286                 global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
287                 global $wgRightsUrl, $wgRightsText, $wgCopyrightIcon;
289                 static $oldLogo = NULL;
291                 if ( !$this->setupDone ) {
292                         $wgHooks['GetLocalURL'][] =& $this;
293                         $wgHooks['GetFullURL'][] =& $this;
294                         $this->oldArticlePath = $wgServer . $wgArticlePath;
295                 }
297                 if ( is_null( $currentDepth ) ) {
298                         $currentDepth = $this->depth;
299                 }
301                 if ( $this->alternateScriptPath ) {
302                         if ( $currentDepth == 0 ) {
303                                 $wgScriptPath = '.';
304                         } else {
305                                 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth - 1 );
306                         }
307                 } else {
308                         $wgScriptPath = '..' . str_repeat( '/..', $currentDepth );
309                 }
311                 $wgArticlePath = str_repeat( '../', $currentDepth ) . '$1';
313                 # Logo image
314                 # Allow for repeated setup
315                 if ( !is_null( $oldLogo ) ) {
316                         $wgLogo = $oldLogo;
317                 } else {
318                         $oldLogo = $wgLogo;
319                 }
321                 if ( strpos( $wgLogo, $wgUploadPath ) === 0 ) {
322                         # If it's in the upload directory, rewrite it to the new upload directory
323                         $wgLogo = "$wgScriptPath/{$this->imageRel}/" . substr( $wgLogo, strlen( $wgUploadPath ) + 1 );
324                 } elseif ( $wgLogo{0} == '/' ) {
325                         # This is basically heuristic
326                         # Rewrite an absolute logo path to one relative to the the script path
327                         $wgLogo = $wgScriptPath . $wgLogo;
328                 }
330                 # Another ugly hack
331                 if ( !$this->setupDone ) {
332                         $this->oldCopyrightIcon = $wgCopyrightIcon;
333                 }
334                 $wgCopyrightIcon = str_replace( 'src="/images',
335                         'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $this->oldCopyrightIcon );
339                 $wgStylePath = "$wgScriptPath/skins";
340                 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
341                 $wgSharedUploadPath = "$wgUploadPath/shared";
342                 $wgMaxCredits = -1;
343                 $wgHideInterlanguageLinks = !$this->interwiki;
344                 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
345                 $wgEnableParserCache = false;
346                 $wgMathPath = "$wgScriptPath/math";
348                 if ( !empty( $wgRightsText ) ) {
349                         $wgRightsUrl = "$wgScriptPath/COPYING.html";
350                 }
352                 $wgUser = new User;
353                 $wgUser->setOption( 'skin', $this->skin );
354                 $wgUser->setOption( 'editsection', 0 );
356                 $this->sharedStaticPath = "$wgUploadDirectory/shared";
358                 $this->setupDone = true;
359         }
361         /** Reads the content of a title object, executes the skin and captures the result */
362         function getArticleHTML( &$title ) {
363                 global $wgOut, $wgTitle, $wgArticle, $wgUser;
365                 $linkCache =& LinkCache::singleton();
366                 $linkCache->clear();
367                 $wgTitle = $title;
368                 if ( is_null( $wgTitle ) ) {
369                         return false;
370                 }
372                 $ns = $wgTitle->getNamespace();
373                 if ( $ns == NS_SPECIAL ) {
374                         $wgOut = new OutputPage;
375                         $wgOut->setParserOptions( new ParserOptions );
376                         SpecialPage::executePath( $wgTitle );
377                 } else {
378                         /** @todo merge with Wiki.php code */
379                         if ( $ns == NS_IMAGE ) {
380                                 $wgArticle = new ImagePage( $wgTitle );
381                         } elseif ( $ns == NS_CATEGORY ) {
382                                 $wgArticle = new CategoryPage( $wgTitle );
383                         } else {
384                                 $wgArticle = new Article( $wgTitle );
385                         }
386                         $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
387                         if ( $rt != NULL ) {
388                                 return $this->getRedirect( $rt );
389                         } else {
390                                 $wgOut = new OutputPage;
391                                 $wgOut->setParserOptions( new ParserOptions );
393                                 $wgArticle->view();
394                         }
395                 }
397                 $sk =& $wgUser->getSkin();
398                 ob_start();
399                 $sk->outputPage( $wgOut );
400                 $text = ob_get_contents();
401                 ob_end_clean();
403                 return $text;
404         }
406         function getRedirect( $rt ) {
407                 $url = $rt->escapeLocalURL();
408                 $text = $rt->getPrefixedText();
409                 return <<<ENDTEXT
410 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
411 <html xmlns="http://www.w3.org/1999/xhtml">
412 <head>
413   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
414   <meta http-equiv="Refresh" content="0;url=$url" />
415 </head>
416 <body>
417   <p>Redirecting to <a href="$url">$text</a></p>
418 </body>
419 </html>
420 ENDTEXT;
421         }
423         /** Returns image paths used in an XHTML document */
424         function findImages( $text ) {
425                 global $wgOutputEncoding, $wgDumpImages;
426                 $parser = xml_parser_create( $wgOutputEncoding );
427                 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
429                 $wgDumpImages = array();
430                 xml_parse( $parser, $text );
431                 xml_parser_free( $parser );
433                 return $wgDumpImages;
434         }
436         /**
437          * Copy images (or create symlinks) from commons to a static directory.
438          * This is necessary even if you intend to distribute all of commons, because
439          * the directory contents is used to work out which image description pages
440          * are needed.
441          *
442          * Also copies math images
443          *
444          */
445         function copyImages( $images ) {
446                 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
447                 # Find shared uploads and copy them into the static directory
448                 $sharedPathLength = strlen( $wgSharedUploadPath );
449                 $mathPathLength = strlen( $wgMathPath );
450                 foreach ( $images as $escapedImage => $dummy ) {
451                         $image = urldecode( $escapedImage );
453                         # Is it shared?
454                         if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
455                                 # Reconstruct full filename
456                                 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
457                                 $sourceLoc = "$wgSharedUploadDirectory/$rel";
458                                 $staticLoc = "{$this->sharedStaticPath}/$rel";
459                                 #print "Copying $sourceLoc to $staticLoc\n";
460                                 # Copy to static directory
461                                 if ( !file_exists( $staticLoc ) ) {
462                                         wfMkdirParents( dirname( $staticLoc ), 0755 );
463                                         if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
464                                                 symlink( $sourceLoc, $staticLoc );
465                                         } else {
466                                                 copy( $sourceLoc, $staticLoc );
467                                         }
468                                 }
470                                 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
471                                         # That was a thumbnail
472                                         # We will also copy the real image
473                                         $parts = explode( '/', $rel );
474                                         $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
475                                         $sourceLoc = "$wgSharedUploadDirectory/$rel";
476                                         $staticLoc = "{$this->sharedStaticPath}/$rel";
477                                         #print "Copying $sourceLoc to $staticLoc\n";
478                                         if ( !file_exists( $staticLoc ) ) {
479                                                 wfMkdirParents( dirname( $staticLoc ), 0755 );
480                                                 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
481                                                         symlink( $sourceLoc, $staticLoc );
482                                                 } else {
483                                                         copy( $sourceLoc, $staticLoc );
484                                                 }
485                                         }
486                                 }
487                         } else
488                         # Is it math?
489                         if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
490                                 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
491                                 $source = "$wgMathDirectory/$rel";
492                                 $dest = "{$this->dest}/math/$rel";
493                                 @mkdir( "{$this->dest}/math", 0755 );
494                                 if ( !file_exists( $dest ) ) {
495                                         copy( $source, $dest );
496                                 }
497                         }
498                 }
499         }
501         function onGetFullURL( &$title, &$url, $query ) {
502                 global $wgContLang, $wgArticlePath;
504                 $iw = $title->getInterwiki();
505                 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
506                         if ( $title->getDBkey() == '' ) {
507                                 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
508                         } else {
509                                 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
510                                         $wgArticlePath );
511                         }
512                         return false;
513                 } else {
514                         return true;
515                 }
516         }
518         function onGetLocalURL( &$title, &$url, $query ) {
519                 global $wgArticlePath;
521                 if ( $title->isExternal() ) {
522                         # Default is fine for interwiki
523                         return true;
524                 }
526                 $url = false;
527                 if ( $query != '' ) {
528                         parse_str( $query, $params );
529                         if ( isset($params['action']) && $params['action'] == 'raw' ) {
530                                 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
531                                         $file = 'gen.' . $params['gen'];
532                                 } else {
533                                         $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
534                                         // Clean up Monobook.css etc.
535                                         if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
536                                                 $file = $matches[1] . '.' . $matches[2];
537                                         }
538                                 }
539                                 $this->rawPages[$file] = array( $file, $title, $params );
540                                 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
541                         }
542                 }
543                 if ( $url === false ) {
544                         $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
545                 }
547                 return false;
548         }
550         function getHashedFilename( &$title ) {
551                 if ( '' != $title->mInterwiki ) {
552                         $dbkey = $title->getDBkey();
553                 } else {
554                         $dbkey = $title->getPrefixedDBkey();
555                 }
557                 $mainPage = Title::newMainPage();
558                 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
559                         return 'index.html';
560                 }
562                 return $this->getHashedDirectory( $title ) . '/' .
563                         $this->getFriendlyName( $dbkey ) . '.html';
564         }
566         function getFriendlyName( $name ) {
567                 global $wgLang;
568                 # Replace illegal characters for Windows paths with underscores
569                 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
571                 # Work out lower case form. We assume we're on a system with case-insensitive
572                 # filenames, so unless the case is of a special form, we have to disambiguate
573                 if ( function_exists( 'mb_strtolower' ) ) {
574                         $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
575                 } else {
576                         $lowerCase = ucfirst( strtolower( $name ) );
577                 }
579                 # Make it mostly unique
580                 if ( $lowerCase != $friendlyName  ) {
581                         $friendlyName .= '_' . substr(md5( $name ), 0, 4);
582                 }
583                 # Handle colon specially by replacing it with tilde
584                 # Thus we reduce the number of paths with hashes appended
585                 $friendlyName = str_replace( ':', '~', $friendlyName );
587                 return $friendlyName;
588         }
590         /**
591          * Get a relative directory for putting a title into
592          */
593         function getHashedDirectory( &$title ) {
594                 if ( '' != $title->getInterwiki() ) {
595                         $pdbk = $title->getDBkey();
596                 } else {
597                         $pdbk = $title->getPrefixedDBkey();
598                 }
600                 # Find the first colon if there is one, use characters after it
601                 $p = strpos( $pdbk, ':' );
602                 if ( $p !== false ) {
603                         $dbk = substr( $pdbk, $p + 1 );
604                         $dbk = substr( $dbk, strspn( $dbk, '_' ) );
605                 } else {
606                         $dbk = $pdbk;
607                 }
609                 # Split into characters
610                 preg_match_all( '/./us', $dbk, $m );
612                 $chars = $m[0];
613                 $length = count( $chars );
614                 $dir = '';
616                 for ( $i = 0; $i < $this->depth; $i++ ) {
617                         if ( $i ) {
618                                 $dir .= '/';
619                         }
620                         if ( $i >= $length ) {
621                                 $dir .= '_';
622                         } else {
623                                 $c = $chars[$i];
624                                 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
625                                         if ( function_exists( 'mb_strtolower' ) ) {
626                                                 $dir .= mb_strtolower( $c );
627                                         } else {
628                                                 $dir .= strtolower( $c );
629                                         }
630                                 } else {
631                                         $dir .= sprintf( "%02X", ord( $c ) );
632                                 }
633                         }
634                 }
635                 return $dir;
636         }
640 /** XML parser callback */
641 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
642         global $wgDumpImages;
644         if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
645                 $wgDumpImages[$attribs['SRC']] = true;
646         }
649 /** XML parser callback */
650 function wfDumpEndTagHandler( $parser, $name ) {}
652 # vim: syn=php