fixed relative path bug
[mediawiki.git] / maintenance / dumpHTML.inc
blobec29fb02ddc78702864709fbe2538d531a3d2565
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;
19         
20         # Depth of HTML directory tree
21         var $depth = 3;
23         # Directory that commons images are copied into
24         var $sharedStaticPath;
25         
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 article path, for "current version" links
37         var $oldArticlePath = 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         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';
57                 
58                 $this->setupGlobals();
59                 
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();
68                 
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;
119                 
120                 $fname = 'DumpHTML::doImageDescriptions';
121                 
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                 $categorylinks = $dbr->tableName( 'categorylinks' );
178                 print "Selecting categories...";
179                 $sql = 'SELECT DISTINCT cl_to FROM categorylinks';
180                 $res = $dbr->query( $sql, $fname );
182                 print "\nWriting " . $dbr->numRows( $res ).  " category pages\n";
183                 $i = 0;
184                 while ( $row = $dbr->fetchObject( $res ) ) {
185                         wfWaitForSlaves( 10 );
186                         if ( !(++$i % REPORTING_INTERVAL ) ) {
187                                 print "$i\r";
188                         }
189                         $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
190                         $this->doArticle( $title );
191                 }
192                 print "\n";
193         }
195         function doRedirects() {
196                 global $wgLinkCache;
197                 
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                 }
273                 
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;
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;
287                 
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                 }
297                 
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                 $wgCopyrightIcon = str_replace( 'src="/images', 
329                         'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $wgCopyrightIcon );
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";
341                 
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, $wgUseCategoryMagic, $wgLinkCache;
358                 
359                 $wgTitle = $title;
360                 if ( is_null( $wgTitle ) ) {
361                         return false;
362                 }
363                 
364                 $ns = $wgTitle->getNamespace();
365                 if ( $ns == NS_SPECIAL ) {
366                         $wgOut = new OutputPage;
367                         $wgOut->setParserOptions( new ParserOptions );
368                         $wgLinkCache = new LinkCache;
369                         SpecialPage::executePath( $wgTitle );
370                 } else {
371                         if ( $ns == NS_IMAGE ) {
372                                 $wgArticle = new ImagePage( $wgTitle );
373                         } elseif ( $wgUseCategoryMagic && $ns == NS_CATEGORY ) {
374                                 $wgArticle = new CategoryPage( $wgTitle );
375                         } else {
376                                 $wgArticle = new Article( $wgTitle );
377                         }
378                         $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
379                         if ( $rt != NULL ) {
380                                 return $this->getRedirect( $rt );
381                         } else {
382                                 $wgOut = new OutputPage;
383                                 $wgOut->setParserOptions( new ParserOptions );
384                                 $wgLinkCache = new LinkCache;
385                 
386                                 $wgArticle->view();
387                         }
388                 }
390                 $sk =& $wgUser->getSkin();
391                 ob_start();
392                 $sk->outputPage( $wgOut );
393                 $text = ob_get_contents();
394                 ob_end_clean();
396                 return $text;
397         }
399         function getRedirect( $rt ) {
400                 $url = $rt->escapeLocalURL();
401                 $text = $rt->getPrefixedText();
402                 return <<<ENDTEXT
403 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
404 <html xmlns="http://www.w3.org/1999/xhtml">
405 <head>
406   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
407   <meta http-equiv="Refresh" content="0;url=$url" />
408 </head>
409 <body>
410   <p>Redirecting to <a href="$url">$text</a></p>
411 </body>
412 </html>
413 ENDTEXT;
414         }
416         /** Returns image paths used in an XHTML document */
417         function findImages( $text ) {
418                 global $wgOutputEncoding, $wgDumpImages;
419                 $parser = xml_parser_create( $wgOutputEncoding );
420                 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
421                 
422                 $wgDumpImages = array();
423                 xml_parse( $parser, $text );
424                 xml_parser_free( $parser );
426                 return $wgDumpImages;
427         }
429         /**
430          * Copy images (or create symlinks) from commons to a static directory.
431          * This is necessary even if you intend to distribute all of commons, because
432          * the directory contents is used to work out which image description pages
433          * are needed.
434          * 
435          * Also copies math images
436          *
437          */
438         function copyImages( $images ) {
439                 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
440                 # Find shared uploads and copy them into the static directory
441                 $sharedPathLength = strlen( $wgSharedUploadPath ); 
442                 $mathPathLength = strlen( $wgMathPath );
443                 foreach ( $images as $escapedImage => $dummy ) {
444                         $image = urldecode( $escapedImage );
446                         # Is it shared?
447                         if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
448                                 # Reconstruct full filename
449                                 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
450                                 $sourceLoc = "$wgSharedUploadDirectory/$rel";
451                                 $staticLoc = "{$this->sharedStaticPath}/$rel";
452                                 #print "Copying $sourceLoc to $staticLoc\n";
453                                 # Copy to static directory
454                                 if ( !file_exists( $staticLoc ) ) {
455                                         wfMkdirParents( dirname( $staticLoc ), 0755 );
456                                         if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
457                                                 symlink( $sourceLoc, $staticLoc );
458                                         } else {
459                                                 copy( $sourceLoc, $staticLoc );
460                                         }
461                                 }
463                                 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
464                                         # That was a thumbnail
465                                         # We will also copy the real image
466                                         $parts = explode( '/', $rel );
467                                         $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
468                                         $sourceLoc = "$wgSharedUploadDirectory/$rel";
469                                         $staticLoc = "{$this->sharedStaticPath}/$rel";
470                                         #print "Copying $sourceLoc to $staticLoc\n";
471                                         if ( !file_exists( $staticLoc ) ) {
472                                                 wfMkdirParents( dirname( $staticLoc ), 0755 );
473                                                 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
474                                                         symlink( $sourceLoc, $staticLoc );
475                                                 } else {
476                                                         copy( $sourceLoc, $staticLoc );
477                                                 }
478                                         }
479                                 }
480                         } else
481                         # Is it math?
482                         if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
483                                 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
484                                 $source = "$wgMathDirectory/$rel";
485                                 $dest = "{$this->dest}/math/$rel";
486                                 @mkdir( "{$this->dest}/math", 0755 );
487                                 if ( !file_exists( $dest ) ) {
488                                         copy( $source, $dest );
489                                 }
490                         }
491                 }
492         }
494         function onGetFullURL( &$title, &$url, $query ) {
495                 global $wgContLang, $wgArticlePath;
497                 $iw = $title->getInterwiki();
498                 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
499                         if ( $title->getDBkey() == '' ) {
500                                 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
501                         } else {
502                                 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ), 
503                                         $wgArticlePath );
504                         }
505                         return false;
506                 } else {
507                         return true;
508                 }
509         }
510         
511         function onGetLocalURL( &$title, &$url, $query ) {
512                 global $wgArticlePath;
514                 if ( $title->isExternal() ) {
515                         # Default is fine for interwiki
516                         return true;
517                 }
519                 $url = false;
520                 if ( $query != '' ) {
521                         parse_str( $query, $params );
522                         if ( isset($params['action']) && $params['action'] == 'raw' ) {
523                                 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
524                                         $file = 'gen.' . $params['gen'];
525                                 } else {
526                                         $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
527                                         // Clean up Monobook.css etc.
528                                         if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
529                                                 $file = $matches[1] . '.' . $matches[2];
530                                         }
531                                 }
532                                 $this->rawPages[$file] = array( $file, $title, $params );
533                                 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
534                         }
535                 }
536                 if ( $url === false ) {
537                         $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
538                 }
539                 
540                 return false;
541         }
543         function getHashedFilename( &$title ) {
544                 if ( '' != $title->mInterwiki ) {
545                         $dbkey = $title->getDBkey();
546                 } else {
547                         $dbkey = $title->getPrefixedDBkey();
548                 }
550                 $mainPage = Title::newMainPage();
551                 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
552                         return 'index.html';
553                 }
555                 return $this->getHashedDirectory( $title ) . '/' . 
556                         $this->getFriendlyName( $dbkey ) . '.html';
557         }
559         function getFriendlyName( $name ) {
560                 global $wgLang;
561                 # Replace illegal characters for Windows paths with underscores
562                 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
564                 # Work out lower case form. We assume we're on a system with case-insensitive
565                 # filenames, so unless the case is of a special form, we have to disambiguate
566                 if ( function_exists( 'mb_strtolower' ) ) {
567                         $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
568                 } else {
569                         $lowerCase = ucfirst( strtolower( $name ) );
570                 }
572                 # Make it mostly unique
573                 if ( $lowerCase != $friendlyName  ) {
574                         $friendlyName .= '_' . substr(md5( $name ), 0, 4);
575                 }
576                 # Handle colon specially by replacing it with tilde
577                 # Thus we reduce the number of paths with hashes appended
578                 $friendlyName = str_replace( ':', '~', $friendlyName );
580                 return $friendlyName;
581         }
582         
583         /**
584          * Get a relative directory for putting a title into
585          */
586         function getHashedDirectory( &$title ) {
587                 if ( '' != $title->getInterwiki() ) {
588                         $pdbk = $title->getDBkey();
589                 } else {
590                         $pdbk = $title->getPrefixedDBkey();
591                 }
593                 # Find the first colon if there is one, use characters after it
594                 $p = strpos( $pdbk, ':' );
595                 if ( $p !== false ) {
596                         $dbk = substr( $pdbk, $p + 1 );
597                         $dbk = substr( $dbk, strspn( $dbk, '_' ) );
598                 } else {
599                         $dbk = $pdbk;
600                 }
602                 # Split into characters
603                 preg_match_all( '/./us', $dbk, $m );
605                 $chars = $m[0];
606                 $length = count( $chars );
607                 $dir = '';
609                 for ( $i = 0; $i < $this->depth; $i++ ) {
610                         if ( $i ) {
611                                 $dir .= '/';
612                         }
613                         if ( $i >= $length ) {
614                                 $dir .= '_';
615                         } else {
616                                 $c = $chars[$i];
617                                 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
618                                         if ( function_exists( 'mb_strtolower' ) ) {
619                                                 $dir .= mb_strtolower( $c );
620                                         } else {
621                                                 $dir .= strtolower( $c );
622                                         }
623                                 } else {
624                                         $dir .= sprintf( "%02X", ord( $c ) );
625                                 }
626                         }
627                 }
628                 return $dir;
629         }
633 /** XML parser callback */
634 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
635         global $wgDumpImages;
637         if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
638                 $wgDumpImages[$attribs['SRC']] = true;
639         }
642 /** XML parser callback */
643 function wfDumpEndTagHandler( $parser, $name ) {}
645 # vim: syn=php