Killing double quotes
[mediawiki.git] / maintenance / dumpHTML.inc
blob6c2ced57588be4fd00a0f64302e5bba233adfe73
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 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         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                 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                 $wgHideInterlangageLinks = !$this->interwiki;
341                 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
342                 $wgEnableParserCache = false;
343                 $wgMathPath = "$wgScriptPath/math";
344                 
345                 if ( !empty( $wgRightsText ) ) {
346                         $wgRightsUrl = "$wgScriptPath/COPYING.html";
347                 }
349                 $wgUser = new User;
350                 $wgUser->setOption( 'skin', 'htmldump' );
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, $wgUseCategoryMagic, $wgLinkCache;
361                 
362                 $wgTitle = $title;
363                 if ( is_null( $wgTitle ) ) {
364                         return false;
365                 }
366                 
367                 $ns = $wgTitle->getNamespace();
368                 if ( $ns == NS_SPECIAL ) {
369                         $wgOut = new OutputPage;
370                         $wgOut->setParserOptions( new ParserOptions );
371                         $wgLinkCache = new LinkCache;
372                         SpecialPage::executePath( $wgTitle );
373                 } else {
374                         if ( $ns == NS_IMAGE ) {
375                                 $wgArticle = new ImagePage( $wgTitle );
376                         } elseif ( $wgUseCategoryMagic && $ns == NS_CATEGORY ) {
377                                 $wgArticle = new CategoryPage( $wgTitle );
378                         } else {
379                                 $wgArticle = new Article( $wgTitle );
380                         }
381                         $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
382                         if ( $rt != NULL ) {
383                                 return $this->getRedirect( $rt );
384                         } else {
385                                 $wgOut = new OutputPage;
386                                 $wgOut->setParserOptions( new ParserOptions );
387                                 $wgLinkCache = new LinkCache;
388                 
389                                 $wgArticle->view();
390                         }
391                 }
393                 $sk =& $wgUser->getSkin();
394                 ob_start();
395                 $sk->outputPage( $wgOut );
396                 $text = ob_get_contents();
397                 ob_end_clean();
399                 return $text;
400         }
402         function getRedirect( $rt ) {
403                 $url = $rt->escapeLocalURL();
404                 $text = $rt->getPrefixedText();
405                 return <<<ENDTEXT
406 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
407 <html xmlns="http://www.w3.org/1999/xhtml">
408 <head>
409   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
410   <meta http-equiv="Refresh" content="0;url=$url" />
411 </head>
412 <body>
413   <p>Redirecting to <a href="$url">$text</a></p>
414 </body>
415 </html>
416 ENDTEXT;
417         }
419         /** Returns image paths used in an XHTML document */
420         function findImages( $text ) {
421                 global $wgOutputEncoding, $wgDumpImages;
422                 $parser = xml_parser_create( $wgOutputEncoding );
423                 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
424                 
425                 $wgDumpImages = array();
426                 xml_parse( $parser, $text );
427                 xml_parser_free( $parser );
429                 return $wgDumpImages;
430         }
432         /**
433          * Copy images (or create symlinks) from commons to a static directory.
434          * This is necessary even if you intend to distribute all of commons, because
435          * the directory contents is used to work out which image description pages
436          * are needed.
437          * 
438          * Also copies math images
439          *
440          */
441         function copyImages( $images ) {
442                 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
443                 # Find shared uploads and copy them into the static directory
444                 $sharedPathLength = strlen( $wgSharedUploadPath ); 
445                 $mathPathLength = strlen( $wgMathPath );
446                 foreach ( $images as $escapedImage => $dummy ) {
447                         $image = urldecode( $escapedImage );
449                         # Is it shared?
450                         if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
451                                 # Reconstruct full filename
452                                 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
453                                 $sourceLoc = "$wgSharedUploadDirectory/$rel";
454                                 $staticLoc = "{$this->sharedStaticPath}/$rel";
455                                 #print "Copying $sourceLoc to $staticLoc\n";
456                                 # Copy to static directory
457                                 if ( !file_exists( $staticLoc ) ) {
458                                         wfMkdirParents( dirname( $staticLoc ), 0755 );
459                                         if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
460                                                 symlink( $sourceLoc, $staticLoc );
461                                         } else {
462                                                 copy( $sourceLoc, $staticLoc );
463                                         }
464                                 }
466                                 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
467                                         # That was a thumbnail
468                                         # We will also copy the real image
469                                         $parts = explode( '/', $rel );
470                                         $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
471                                         $sourceLoc = "$wgSharedUploadDirectory/$rel";
472                                         $staticLoc = "{$this->sharedStaticPath}/$rel";
473                                         #print "Copying $sourceLoc to $staticLoc\n";
474                                         if ( !file_exists( $staticLoc ) ) {
475                                                 wfMkdirParents( dirname( $staticLoc ), 0755 );
476                                                 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
477                                                         symlink( $sourceLoc, $staticLoc );
478                                                 } else {
479                                                         copy( $sourceLoc, $staticLoc );
480                                                 }
481                                         }
482                                 }
483                         } else
484                         # Is it math?
485                         if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
486                                 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
487                                 $source = "$wgMathDirectory/$rel";
488                                 $dest = "{$this->dest}/math/$rel";
489                                 @mkdir( "{$this->dest}/math", 0755 );
490                                 if ( !file_exists( $dest ) ) {
491                                         copy( $source, $dest );
492                                 }
493                         }
494                 }
495         }
497         function onGetFullURL( &$title, &$url, $query ) {
498                 global $wgContLang, $wgArticlePath;
500                 $iw = $title->getInterwiki();
501                 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
502                         if ( $title->getDBkey() == '' ) {
503                                 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
504                         } else {
505                                 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ), 
506                                         $wgArticlePath );
507                         }
508                         return false;
509                 } else {
510                         return true;
511                 }
512         }
513         
514         function onGetLocalURL( &$title, &$url, $query ) {
515                 global $wgArticlePath;
517                 if ( $title->isExternal() ) {
518                         # Default is fine for interwiki
519                         return true;
520                 }
522                 $url = false;
523                 if ( $query != '' ) {
524                         parse_str( $query, $params );
525                         if ( isset($params['action']) && $params['action'] == 'raw' ) {
526                                 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
527                                         $file = 'gen.' . $params['gen'];
528                                 } else {
529                                         $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
530                                         // Clean up Monobook.css etc.
531                                         if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
532                                                 $file = $matches[1] . '.' . $matches[2];
533                                         }
534                                 }
535                                 $this->rawPages[$file] = array( $file, $title, $params );
536                                 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
537                         }
538                 }
539                 if ( $url === false ) {
540                         $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
541                 }
542                 
543                 return false;
544         }
546         function getHashedFilename( &$title ) {
547                 if ( '' != $title->mInterwiki ) {
548                         $dbkey = $title->getDBkey();
549                 } else {
550                         $dbkey = $title->getPrefixedDBkey();
551                 }
553                 $mainPage = Title::newMainPage();
554                 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
555                         return 'index.html';
556                 }
558                 return $this->getHashedDirectory( $title ) . '/' . 
559                         $this->getFriendlyName( $dbkey ) . '.html';
560         }
562         function getFriendlyName( $name ) {
563                 global $wgLang;
564                 # Replace illegal characters for Windows paths with underscores
565                 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
567                 # Work out lower case form. We assume we're on a system with case-insensitive
568                 # filenames, so unless the case is of a special form, we have to disambiguate
569                 if ( function_exists( 'mb_strtolower' ) ) {
570                         $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
571                 } else {
572                         $lowerCase = ucfirst( strtolower( $name ) );
573                 }
575                 # Make it mostly unique
576                 if ( $lowerCase != $friendlyName  ) {
577                         $friendlyName .= '_' . substr(md5( $name ), 0, 4);
578                 }
579                 # Handle colon specially by replacing it with tilde
580                 # Thus we reduce the number of paths with hashes appended
581                 $friendlyName = str_replace( ':', '~', $friendlyName );
583                 return $friendlyName;
584         }
585         
586         /**
587          * Get a relative directory for putting a title into
588          */
589         function getHashedDirectory( &$title ) {
590                 if ( '' != $title->getInterwiki() ) {
591                         $pdbk = $title->getDBkey();
592                 } else {
593                         $pdbk = $title->getPrefixedDBkey();
594                 }
596                 # Find the first colon if there is one, use characters after it
597                 $p = strpos( $pdbk, ':' );
598                 if ( $p !== false ) {
599                         $dbk = substr( $pdbk, $p + 1 );
600                         $dbk = substr( $dbk, strspn( $dbk, '_' ) );
601                 } else {
602                         $dbk = $pdbk;
603                 }
605                 # Split into characters
606                 preg_match_all( '/./us', $dbk, $m );
608                 $chars = $m[0];
609                 $length = count( $chars );
610                 $dir = '';
612                 for ( $i = 0; $i < $this->depth; $i++ ) {
613                         if ( $i ) {
614                                 $dir .= '/';
615                         }
616                         if ( $i >= $length ) {
617                                 $dir .= '_';
618                         } else {
619                                 $c = $chars[$i];
620                                 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
621                                         if ( function_exists( 'mb_strtolower' ) ) {
622                                                 $dir .= mb_strtolower( $c );
623                                         } else {
624                                                 $dir .= strtolower( $c );
625                                         }
626                                 } else {
627                                         $dir .= sprintf( "%02X", ord( $c ) );
628                                 }
629                         }
630                 }
631                 return $dir;
632         }
636 /** XML parser callback */
637 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
638         global $wgDumpImages;
640         if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
641                 $wgDumpImages[$attribs['SRC']] = true;
642         }
645 /** XML parser callback */
646 function wfDumpEndTagHandler( $parser, $name ) {}
648 # vim: syn=php