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