* (bug 1103) Fix up redirect handling for images, categories
[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 $sharedStaticPath;
25
26 # Relative path to image directory
27 var $imageRel = 'upload';
28
29 # Copy commons images instead of symlinking
30 var $forceCopy = false;
31
32 # Make links assuming the script path is in the same directory as
33 # the destination
34 var $alternateScriptPath = false;
35
36 # Original values of various globals
37 var $oldArticlePath = false, $oldCopyrightIcon = false;
38
39 # Has setupGlobals been called?
40 var $setupDone = false;
41
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 }
50
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 }
64
65 $mainPageObj = Title::newMainPage();
66 $mainPage = $mainPageObj->getPrefixedDBkey();
67
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 }
87
88 function doSpecials() {
89 $this->doMainPage();
90
91 $this->setupGlobals();
92 print "Special:Categories...";
93 $this->doArticle( Title::makeTitle( NS_SPECIAL, 'Categories' ) );
94 print "\n";
95 }
96
97 /** Write the main page as index.html */
98 function doMainPage() {
99
100 print "Making index.html ";
101
102 // Set up globals with no ../../.. in the link URLs
103 $this->setupGlobals( 0 );
104
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 }
116
117 function doImageDescriptions() {
118 global $wgSharedUploadDirectory;
119
120 $fname = 'DumpHTML::doImageDescriptions';
121
122 $this->setupGlobals();
123
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 );
131
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";
148
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/*" ) );
158
159 foreach ( $paths as $path ) {
160 $file = basename( $path );
161 if ( !(++$i % REPORTING_INTERVAL ) ) {
162 print "$i\r";
163 }
164
165 $title = Title::makeTitle( NS_IMAGE, $file );
166 $this->doArticle( $title );
167 }
168 }
169 print "\n";
170 }
171
172 function doCategories() {
173 $fname = 'DumpHTML::doCategories';
174 $this->setupGlobals();
175
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 );
181
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 }
194
195 function doRedirects() {
196 print "Doing redirects...\n";
197 $fname = 'DumpHTML::doRedirects';
198 $this->setupGlobals();
199 $dbr =& wfGetDB( DB_SLAVE );
200
201 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
202 array( 'page_is_redirect' => 1 ), $fname );
203 $num = $dbr->numRows( $res );
204 print "$num redirects to do...\n";
205 $i = 0;
206 while ( $row = $dbr->fetchObject( $res ) ) {
207 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
208 if ( !(++$i % (REPORTING_INTERVAL*10) ) ) {
209 print "Done $i of $num\n";
210 }
211 $this->doArticle( $title );
212 }
213 }
214
215 /** Write an article specified by title */
216 function doArticle( $title ) {
217 global $wgTitle, $wgSharedUploadPath, $wgSharedUploadDirectory;
218 global $wgUploadDirectory;
219
220 $this->rawPages = array();
221 $text = $this->getArticleHTML( $title );
222
223 if ( $text === false ) {
224 return;
225 }
226
227 # Parse the XHTML to find the images
228 $images = $this->findImages( $text );
229 $this->copyImages( $images );
230
231 # Write to file
232 $this->writeArticle( $title, $text );
233
234 # Do raw pages
235 wfMkdirParents( "{$this->dest}/raw", 0755 );
236 foreach( $this->rawPages as $record ) {
237 list( $file, $title, $params ) = $record;
238
239 $path = "{$this->dest}/raw/$file";
240 if ( !file_exists( $path ) ) {
241 $article = new Article( $title );
242 $request = new FauxRequest( $params );
243 $rp = new RawPage( $article, $request );
244 $text = $rp->getRawText();
245
246 print "Writing $file\n";
247 $file = fopen( $path, 'w' );
248 if ( !$file ) {
249 print("Can't open file $fullName for writing\n");
250 continue;
251 }
252 fwrite( $file, $text );
253 fclose( $file );
254 }
255 }
256 }
257
258 /** Write the given text to the file identified by the given title object */
259 function writeArticle( &$title, $text ) {
260 $filename = $this->getHashedFilename( $title );
261 $fullName = "{$this->dest}/$filename";
262 $fullDir = dirname( $fullName );
263
264 wfMkdirParents( $fullDir, 0755 );
265
266 $file = fopen( $fullName, 'w' );
267 if ( !$file ) {
268 print("Can't open file $fullName for writing\n");
269 return;
270 }
271
272 fwrite( $file, $text );
273 fclose( $file );
274 }
275
276 /** Set up globals required for parsing */
277 function setupGlobals( $currentDepth = NULL ) {
278 global $wgUser, $wgTitle, $wgStylePath, $wgArticlePath;
279 global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
280 global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
281 global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
282 global $wgRightsUrl, $wgRightsText, $wgCopyrightIcon;
283
284 static $oldLogo = NULL;
285
286 if ( !$this->setupDone ) {
287 $wgHooks['GetLocalURL'][] =& $this;
288 $wgHooks['GetFullURL'][] =& $this;
289 $this->oldArticlePath = $wgServer . $wgArticlePath;
290 }
291
292 if ( is_null( $currentDepth ) ) {
293 $currentDepth = $this->depth;
294 }
295
296 if ( $this->alternateScriptPath ) {
297 if ( $currentDepth == 0 ) {
298 $wgScriptPath = '.';
299 } else {
300 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth - 1 );
301 }
302 } else {
303 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth );
304 }
305
306 $wgArticlePath = str_repeat( '../', $currentDepth ) . '$1';
307
308 # Logo image
309 # Allow for repeated setup
310 if ( !is_null( $oldLogo ) ) {
311 $wgLogo = $oldLogo;
312 } else {
313 $oldLogo = $wgLogo;
314 }
315
316 if ( strpos( $wgLogo, $wgUploadPath ) === 0 ) {
317 # If it's in the upload directory, rewrite it to the new upload directory
318 $wgLogo = "$wgScriptPath/{$this->imageRel}/" . substr( $wgLogo, strlen( $wgUploadPath ) + 1 );
319 } elseif ( $wgLogo{0} == '/' ) {
320 # This is basically heuristic
321 # Rewrite an absolute logo path to one relative to the the script path
322 $wgLogo = $wgScriptPath . $wgLogo;
323 }
324
325 # Another ugly hack
326 if ( !$this->setupDone ) {
327 $this->oldCopyrightIcon = $wgCopyrightIcon;
328 }
329 $wgCopyrightIcon = str_replace( 'src="/images',
330 'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $this->oldCopyrightIcon );
331
332
333
334 $wgStylePath = "$wgScriptPath/skins";
335 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
336 $wgSharedUploadPath = "$wgUploadPath/shared";
337 $wgMaxCredits = -1;
338 $wgHideInterlangageLinks = !$this->interwiki;
339 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
340 $wgEnableParserCache = false;
341 $wgMathPath = "$wgScriptPath/math";
342
343 if ( !empty( $wgRightsText ) ) {
344 $wgRightsUrl = "$wgScriptPath/COPYING.html";
345 }
346
347 $wgUser = new User;
348 $wgUser->setOption( 'skin', 'htmldump' );
349 $wgUser->setOption( 'editsection', 0 );
350
351 $this->sharedStaticPath = "$wgUploadDirectory/shared";
352
353 $this->setupDone = true;
354 }
355
356 /** Reads the content of a title object, executes the skin and captures the result */
357 function getArticleHTML( &$title ) {
358 global $wgOut, $wgTitle, $wgArticle, $wgUser;
359
360 $linkCache =& LinkCache::singleton();
361 $linkCache->clear();
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 SpecialPage::executePath( $wgTitle );
372 } else {
373 /** @todo merge with Wiki.php code */
374 if ( $ns == NS_IMAGE ) {
375 $wgArticle = new ImagePage( $wgTitle );
376 } elseif ( $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
388 $wgArticle->view();
389 }
390 }
391
392 $sk =& $wgUser->getSkin();
393 ob_start();
394 $sk->outputPage( $wgOut );
395 $text = ob_get_contents();
396 ob_end_clean();
397
398 return $text;
399 }
400
401 function getRedirect( $rt ) {
402 $url = $rt->escapeLocalURL();
403 $text = $rt->getPrefixedText();
404 return <<<ENDTEXT
405 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
406 <html xmlns="http://www.w3.org/1999/xhtml">
407 <head>
408 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
409 <meta http-equiv="Refresh" content="0;url=$url" />
410 </head>
411 <body>
412 <p>Redirecting to <a href="$url">$text</a></p>
413 </body>
414 </html>
415 ENDTEXT;
416 }
417
418 /** Returns image paths used in an XHTML document */
419 function findImages( $text ) {
420 global $wgOutputEncoding, $wgDumpImages;
421 $parser = xml_parser_create( $wgOutputEncoding );
422 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
423
424 $wgDumpImages = array();
425 xml_parse( $parser, $text );
426 xml_parser_free( $parser );
427
428 return $wgDumpImages;
429 }
430
431 /**
432 * Copy images (or create symlinks) from commons to a static directory.
433 * This is necessary even if you intend to distribute all of commons, because
434 * the directory contents is used to work out which image description pages
435 * are needed.
436 *
437 * Also copies math images
438 *
439 */
440 function copyImages( $images ) {
441 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
442 # Find shared uploads and copy them into the static directory
443 $sharedPathLength = strlen( $wgSharedUploadPath );
444 $mathPathLength = strlen( $wgMathPath );
445 foreach ( $images as $escapedImage => $dummy ) {
446 $image = urldecode( $escapedImage );
447
448 # Is it shared?
449 if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
450 # Reconstruct full filename
451 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
452 $sourceLoc = "$wgSharedUploadDirectory/$rel";
453 $staticLoc = "{$this->sharedStaticPath}/$rel";
454 #print "Copying $sourceLoc to $staticLoc\n";
455 # Copy to static directory
456 if ( !file_exists( $staticLoc ) ) {
457 wfMkdirParents( dirname( $staticLoc ), 0755 );
458 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
459 symlink( $sourceLoc, $staticLoc );
460 } else {
461 copy( $sourceLoc, $staticLoc );
462 }
463 }
464
465 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
466 # That was a thumbnail
467 # We will also copy the real image
468 $parts = explode( '/', $rel );
469 $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
470 $sourceLoc = "$wgSharedUploadDirectory/$rel";
471 $staticLoc = "{$this->sharedStaticPath}/$rel";
472 #print "Copying $sourceLoc to $staticLoc\n";
473 if ( !file_exists( $staticLoc ) ) {
474 wfMkdirParents( dirname( $staticLoc ), 0755 );
475 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
476 symlink( $sourceLoc, $staticLoc );
477 } else {
478 copy( $sourceLoc, $staticLoc );
479 }
480 }
481 }
482 } else
483 # Is it math?
484 if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
485 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
486 $source = "$wgMathDirectory/$rel";
487 $dest = "{$this->dest}/math/$rel";
488 @mkdir( "{$this->dest}/math", 0755 );
489 if ( !file_exists( $dest ) ) {
490 copy( $source, $dest );
491 }
492 }
493 }
494 }
495
496 function onGetFullURL( &$title, &$url, $query ) {
497 global $wgContLang, $wgArticlePath;
498
499 $iw = $title->getInterwiki();
500 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
501 if ( $title->getDBkey() == '' ) {
502 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
503 } else {
504 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
505 $wgArticlePath );
506 }
507 return false;
508 } else {
509 return true;
510 }
511 }
512
513 function onGetLocalURL( &$title, &$url, $query ) {
514 global $wgArticlePath;
515
516 if ( $title->isExternal() ) {
517 # Default is fine for interwiki
518 return true;
519 }
520
521 $url = false;
522 if ( $query != '' ) {
523 parse_str( $query, $params );
524 if ( isset($params['action']) && $params['action'] == 'raw' ) {
525 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
526 $file = 'gen.' . $params['gen'];
527 } else {
528 $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
529 // Clean up Monobook.css etc.
530 if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
531 $file = $matches[1] . '.' . $matches[2];
532 }
533 }
534 $this->rawPages[$file] = array( $file, $title, $params );
535 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
536 }
537 }
538 if ( $url === false ) {
539 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
540 }
541
542 return false;
543 }
544
545 function getHashedFilename( &$title ) {
546 if ( '' != $title->mInterwiki ) {
547 $dbkey = $title->getDBkey();
548 } else {
549 $dbkey = $title->getPrefixedDBkey();
550 }
551
552 $mainPage = Title::newMainPage();
553 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
554 return 'index.html';
555 }
556
557 return $this->getHashedDirectory( $title ) . '/' .
558 $this->getFriendlyName( $dbkey ) . '.html';
559 }
560
561 function getFriendlyName( $name ) {
562 global $wgLang;
563 # Replace illegal characters for Windows paths with underscores
564 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
565
566 # Work out lower case form. We assume we're on a system with case-insensitive
567 # filenames, so unless the case is of a special form, we have to disambiguate
568 if ( function_exists( 'mb_strtolower' ) ) {
569 $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
570 } else {
571 $lowerCase = ucfirst( strtolower( $name ) );
572 }
573
574 # Make it mostly unique
575 if ( $lowerCase != $friendlyName ) {
576 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
577 }
578 # Handle colon specially by replacing it with tilde
579 # Thus we reduce the number of paths with hashes appended
580 $friendlyName = str_replace( ':', '~', $friendlyName );
581
582 return $friendlyName;
583 }
584
585 /**
586 * Get a relative directory for putting a title into
587 */
588 function getHashedDirectory( &$title ) {
589 if ( '' != $title->getInterwiki() ) {
590 $pdbk = $title->getDBkey();
591 } else {
592 $pdbk = $title->getPrefixedDBkey();
593 }
594
595 # Find the first colon if there is one, use characters after it
596 $p = strpos( $pdbk, ':' );
597 if ( $p !== false ) {
598 $dbk = substr( $pdbk, $p + 1 );
599 $dbk = substr( $dbk, strspn( $dbk, '_' ) );
600 } else {
601 $dbk = $pdbk;
602 }
603
604 # Split into characters
605 preg_match_all( '/./us', $dbk, $m );
606
607 $chars = $m[0];
608 $length = count( $chars );
609 $dir = '';
610
611 for ( $i = 0; $i < $this->depth; $i++ ) {
612 if ( $i ) {
613 $dir .= '/';
614 }
615 if ( $i >= $length ) {
616 $dir .= '_';
617 } else {
618 $c = $chars[$i];
619 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
620 if ( function_exists( 'mb_strtolower' ) ) {
621 $dir .= mb_strtolower( $c );
622 } else {
623 $dir .= strtolower( $c );
624 }
625 } else {
626 $dir .= sprintf( "%02X", ord( $c ) );
627 }
628 }
629 }
630 return $dir;
631 }
632
633 }
634
635 /** XML parser callback */
636 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
637 global $wgDumpImages;
638
639 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
640 $wgDumpImages[$attribs['SRC']] = true;
641 }
642 }
643
644 /** XML parser callback */
645 function wfDumpEndTagHandler( $parser, $name ) {}
646
647 # vim: syn=php
648 ?>