a couple of minor things accidentally left out of the last commit
[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 article path, for "current version" links
37 var $oldArticlePath = 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 global $wgMakeDumpLinks;
100
101 print "Making index.html ";
102
103 // Set up globals with no ../../.. in the link URLs
104 $this->setupGlobals( 0 );
105
106 // But still use that directory style
107 $wgMakeDumpLinks = 3;
108
109 $title = Title::newMainPage();
110 $text = $this->getArticleHTML( $title );
111 $file = fopen( "{$this->dest}/index.html", "w" );
112 if ( !$file ) {
113 print "\nCan't open index.html for writing\n";
114 return false;
115 }
116 fwrite( $file, $text );
117 fclose( $file );
118 print "\n";
119 }
120
121 function doImageDescriptions() {
122 global $wgSharedUploadDirectory;
123
124 $fname = 'DumpHTML::doImageDescriptions';
125
126 $this->setupGlobals( 3 );
127
128 /**
129 * Dump image description pages that don't have an associated article, but do
130 * have a local image
131 */
132 $dbr =& wfGetDB( DB_SLAVE );
133 extract( $dbr->tableNames( 'image', 'page' ) );
134 $res = $dbr->select( 'image', array( 'img_name' ), false, $fname );
135
136 $i = 0;
137 print "Writing image description pages for local images\n";
138 $num = $dbr->numRows( $res );
139 while ( $row = $dbr->fetchObject( $res ) ) {
140 wfWaitForSlaves( 10 );
141 if ( !( ++$i % REPORTING_INTERVAL ) ) {
142 print "Done $i of $num\r";
143 }
144 $title = Title::makeTitle( NS_IMAGE, $row->img_name );
145 if ( $title->getArticleID() ) {
146 // Already done by dumpHTML
147 continue;
148 }
149 $this->doArticle( $title );
150 }
151 print "\n";
152
153 /**
154 * Dump images which only have a real description page on commons
155 */
156 print "Writing description pages for commons images\n";
157 $i = 0;
158 for ( $hash = 0; $hash < 256; $hash++ ) {
159 $dir = sprintf( "%01x/%02x", intval( $hash / 16 ), $hash );
160 $paths = array_merge( glob( "{$this->sharedStaticPath}/$dir/*" ),
161 glob( "{$this->sharedStaticPath}/thumb/$dir/*" ) );
162
163 foreach ( $paths as $path ) {
164 $file = basename( $path );
165 if ( !(++$i % REPORTING_INTERVAL ) ) {
166 print "$i\r";
167 }
168
169 $title = Title::makeTitle( NS_IMAGE, $file );
170 $this->doArticle( $title );
171 }
172 }
173 print "\n";
174 }
175
176 function doCategories() {
177 $fname = 'DumpHTML::doCategories';
178 $this->setupGlobals();
179
180 $dbr =& wfGetDB( DB_SLAVE );
181 $categorylinks = $dbr->tableName( 'categorylinks' );
182 print "Selecting categories...";
183 $sql = 'SELECT DISTINCT cl_to FROM categorylinks';
184 $res = $dbr->query( $sql, $fname );
185
186 print "\nWriting " . $dbr->numRows( $res ). " category pages\n";
187 $i = 0;
188 while ( $row = $dbr->fetchObject( $res ) ) {
189 wfWaitForSlaves( 10 );
190 if ( !(++$i % REPORTING_INTERVAL ) ) {
191 print "$i\r";
192 }
193 $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
194 $this->doArticle( $title );
195 }
196 print "\n";
197 }
198
199 function doRedirects() {
200 global $wgLinkCache;
201
202 print "Doing redirects...\n";
203 $fname = 'DumpHTML::doRedirects';
204 $this->setupGlobals();
205 $dbr =& wfGetDB( DB_SLAVE );
206
207 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
208 array( 'page_is_redirect' => 1 ), $fname );
209 $num = $dbr->numRows( $res );
210 print "$num redirects to do...\n";
211 $i = 0;
212 while ( $row = $dbr->fetchObject( $res ) ) {
213 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
214 if ( !(++$i % (REPORTING_INTERVAL*10) ) ) {
215 print "Done $i of $num\n";
216 }
217 $this->doArticle( $title );
218 }
219 }
220
221 /** Write an article specified by title */
222 function doArticle( $title ) {
223 global $wgTitle, $wgSharedUploadPath, $wgSharedUploadDirectory;
224 global $wgUploadDirectory;
225
226 $this->rawPages = array();
227 $text = $this->getArticleHTML( $title );
228
229 if ( $text === false ) {
230 return;
231 }
232
233 # Parse the XHTML to find the images
234 $images = $this->findImages( $text );
235 $this->copyImages( $images );
236
237 # Write to file
238 $this->writeArticle( $title, $text );
239
240 # Do raw pages
241 wfMkdirParents( "{$this->dest}/raw", 0755 );
242 foreach( $this->rawPages as $record ) {
243 list( $file, $title, $params ) = $record;
244
245 $path = "{$this->dest}/raw/$file";
246 if ( !file_exists( $path ) ) {
247 $article = new Article( $title );
248 $request = new FauxRequest( $params );
249 $rp = new RawPage( $article, $request );
250 $text = $rp->getRawText();
251
252 print "Writing $file\n";
253 $file = fopen( $path, 'w' );
254 if ( !$file ) {
255 print("Can't open file $fullName for writing\n");
256 continue;
257 }
258 fwrite( $file, $text );
259 fclose( $file );
260 }
261 }
262 }
263
264 /** Write the given text to the file identified by the given title object */
265 function writeArticle( &$title, $text ) {
266 $filename = $this->getHashedFilename( $title );
267 $fullName = "{$this->dest}/$filename";
268 $fullDir = dirname( $fullName );
269
270 wfMkdirParents( $fullDir, 0755 );
271
272 $file = fopen( $fullName, 'w' );
273 if ( !$file ) {
274 print("Can't open file $fullName for writing\n");
275 return;
276 }
277
278 fwrite( $file, $text );
279 fclose( $file );
280 }
281
282 /** Set up globals required for parsing */
283 function setupGlobals( $depth = NULL ) {
284 global $wgUser, $wgTitle, $wgMakeDumpLinks, $wgStylePath, $wgArticlePath;
285 global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
286 global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
287 global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
288 global $wgRightsUrl, $wgRightsText;
289
290 static $oldLogo = NULL;
291
292 if ( !$this->setupDone ) {
293 $wgHooks['GetLocalURL'][] =& $this;
294 $wgHooks['GetFullURL'][] =& $this;
295 $this->oldArticlePath = $wgServer . $wgArticlePath;
296 }
297
298 if ( is_null( $depth ) ) {
299 $wgMakeDumpLinks = $this->depth;
300 } else {
301 $wgMakeDumpLinks = $depth;
302 }
303
304 if ( $this->alternateScriptPath ) {
305 if ( $wgMakeDumpLinks == 0 ) {
306 $wgScriptPath = '.';
307 } else {
308 $wgScriptPath = '..' . str_repeat( '/..', $wgMakeDumpLinks - 1 );
309 }
310 } else {
311 $wgScriptPath = '..' . str_repeat( '/..', $wgMakeDumpLinks );
312 }
313
314 $wgArticlePath = str_repeat( '../', $wgMakeDumpLinks ) . '$1';
315
316 # Logo image
317 # Allow for repeated setup
318 if ( !is_null( $oldLogo ) ) {
319 $wgLogo = $oldLogo;
320 } else {
321 $oldLogo = $wgLogo;
322 }
323
324 if ( strpos( $wgLogo, $wgUploadPath ) === 0 ) {
325 # If it's in the upload directory, rewrite it to the new upload directory
326 $wgLogo = "$wgScriptPath/{$this->imageRel}/" . substr( $wgLogo, strlen( $wgUploadPath ) + 1 );
327 } elseif ( $wgLogo{0} == '/' ) {
328 # This is basically heuristic
329 # Rewrite an absolute logo path to one relative to the the script path
330 $wgLogo = $wgScriptPath . $wgLogo;
331 }
332
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 }
345
346 $wgUser = new User;
347 $wgUser->setOption( 'skin', 'htmldump' );
348 $wgUser->setOption( 'editsection', 0 );
349
350 $this->sharedStaticPath = "$wgUploadDirectory/shared";
351
352 $this->setupDone = true;
353 }
354
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 SpecialPage::executePath( $wgTitle );
367 } else {
368 if ( $ns == NS_IMAGE ) {
369 $wgArticle = new ImagePage( $wgTitle );
370 } elseif ( $wgUseCategoryMagic && $ns == NS_CATEGORY ) {
371 $wgArticle = new CategoryPage( $wgTitle );
372 } else {
373 $wgArticle = new Article( $wgTitle );
374 }
375 $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
376 if ( $rt != NULL ) {
377 return $this->getRedirect( $rt );
378 } else {
379 $wgOut = new OutputPage;
380 $wgOut->setParserOptions( new ParserOptions );
381 $wgLinkCache = new LinkCache;
382
383 $wgArticle->view();
384 }
385 }
386
387 $sk =& $wgUser->getSkin();
388 ob_start();
389 $sk->outputPage( $wgOut );
390 $text = ob_get_contents();
391 ob_end_clean();
392
393 return $text;
394 }
395
396 function getRedirect( $rt ) {
397 $url = $rt->escapeLocalURL();
398 $text = $rt->getPrefixedText();
399 return <<<ENDTEXT
400 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
401 <html xmlns="http://www.w3.org/1999/xhtml">
402 <head>
403 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
404 <meta http-equiv="Refresh" content="0;url=$url" />
405 </head>
406 <body>
407 <p>Redirecting to <a href="$url">$text</a></p>
408 </body>
409 </html>
410 ENDTEXT;
411 }
412
413 /** Returns image paths used in an XHTML document */
414 function findImages( $text ) {
415 global $wgOutputEncoding, $wgDumpImages;
416 $parser = xml_parser_create( $wgOutputEncoding );
417 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
418
419 $wgDumpImages = array();
420 xml_parse( $parser, $text );
421 xml_parser_free( $parser );
422
423 return $wgDumpImages;
424 }
425
426 /**
427 * Copy images (or create symlinks) from commons to a static directory.
428 * This is necessary even if you intend to distribute all of commons, because
429 * the directory contents is used to work out which image description pages
430 * are needed.
431 *
432 * Also copies math images
433 *
434 */
435 function copyImages( $images ) {
436 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
437 # Find shared uploads and copy them into the static directory
438 $sharedPathLength = strlen( $wgSharedUploadPath );
439 $mathPathLength = strlen( $wgMathPath );
440 foreach ( $images as $escapedImage => $dummy ) {
441 $image = urldecode( $escapedImage );
442
443 # Is it shared?
444 if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
445 # Reconstruct full filename
446 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
447 $sourceLoc = "$wgSharedUploadDirectory/$rel";
448 $staticLoc = "{$this->sharedStaticPath}/$rel";
449 #print "Copying $sourceLoc to $staticLoc\n";
450 # Copy to static directory
451 if ( !file_exists( $staticLoc ) ) {
452 wfMkdirParents( dirname( $staticLoc ), 0755 );
453 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
454 symlink( $sourceLoc, $staticLoc );
455 } else {
456 copy( $sourceLoc, $staticLoc );
457 }
458 }
459
460 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
461 # That was a thumbnail
462 # We will also copy the real image
463 $parts = explode( '/', $rel );
464 $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
465 $sourceLoc = "$wgSharedUploadDirectory/$rel";
466 $staticLoc = "{$this->sharedStaticPath}/$rel";
467 #print "Copying $sourceLoc to $staticLoc\n";
468 if ( !file_exists( $staticLoc ) ) {
469 wfMkdirParents( dirname( $staticLoc ), 0755 );
470 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
471 symlink( $sourceLoc, $staticLoc );
472 } else {
473 copy( $sourceLoc, $staticLoc );
474 }
475 }
476 }
477 } else
478 # Is it math?
479 if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
480 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
481 $source = "$wgMathDirectory/$rel";
482 $dest = "{$this->dest}/math/$rel";
483 @mkdir( "{$this->dest}/math", 0755 );
484 if ( !file_exists( $dest ) ) {
485 copy( $source, $dest );
486 }
487 }
488 }
489 }
490
491 function onGetFullURL( &$title, &$url, $query ) {
492 global $wgContLang, $wgArticlePath;
493
494 $iw = $title->getInterwiki();
495 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
496 if ( $title->getDBkey() == '' ) {
497 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
498 } else {
499 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
500 $wgArticlePath );
501 }
502 return false;
503 } else {
504 return true;
505 }
506 }
507
508 function onGetLocalURL( &$title, &$url, $query ) {
509 global $wgArticlePath;
510
511 if ( $title->isExternal() ) {
512 # Default is fine for interwiki
513 return true;
514 }
515
516 $url = false;
517 if ( $query != '' ) {
518 parse_str( $query, $params );
519 if ( isset($params['action']) && $params['action'] == 'raw' ) {
520 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
521 $file = 'gen.' . $params['gen'];
522 } else {
523 $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
524 // Clean up Monobook.css etc.
525 if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
526 $file = $matches[1] . '.' . $matches[2];
527 }
528 }
529 $this->rawPages[$file] = array( $file, $title, $params );
530 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
531 }
532 }
533 if ( $url === false ) {
534 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
535 }
536 return false;
537 }
538
539 function getHashedFilename( &$title ) {
540 if ( '' != $title->mInterwiki ) {
541 $dbkey = $title->getDBkey();
542 } else {
543 $dbkey = $title->getPrefixedDBkey();
544 }
545
546 $mainPage = Title::newMainPage();
547 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
548 return 'index.html';
549 }
550
551 return $this->getHashedDirectory( $title ) . '/' .
552 $this->getFriendlyName( $dbkey ) . '.html';
553 }
554
555 function getFriendlyName( $name ) {
556 # Replace illegal characters for Windows paths with underscores
557 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
558
559 # Work out lower case form. We assume we're on a system with case-insensitive
560 # filenames, so unless the case is of a special form, we have to disambiguate
561 $lowerCase = ucfirst( strtolower( $name ) );
562
563 # Make it mostly unique
564 if ( $lowerCase != $friendlyName ) {
565 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
566 }
567 # Handle colon specially by replacing it with tilde
568 # Thus we reduce the number of paths with hashes appended
569 $friendlyName = str_replace( ':', '~', $friendlyName );
570
571 return $friendlyName;
572 }
573
574 /**
575 * Get a relative directory for putting a title into
576 */
577 function getHashedDirectory( &$title ) {
578 if ( '' != $title->getInterwiki() ) {
579 $pdbk = $title->getDBkey();
580 } else {
581 $pdbk = $title->getPrefixedDBkey();
582 }
583
584 # Find the first colon if there is one, use characters after it
585 $p = strpos( $pdbk, ':' );
586 if ( $p !== false ) {
587 $dbk = substr( $pdbk, $p + 1 );
588 $dbk = substr( $dbk, strspn( $dbk, '_' ) );
589 } else {
590 $dbk = $pdbk;
591 }
592
593 # Split into characters
594 preg_match_all( '/./us', $dbk, $m );
595
596 $chars = $m[0];
597 $length = count( $chars );
598 $dir = '';
599
600 for ( $i = 0; $i < $this->depth; $i++ ) {
601 if ( $i ) {
602 $dir .= '/';
603 }
604 if ( $i >= $length ) {
605 $dir .= '_';
606 } else {
607 $c = $chars[$i];
608 if ( ord( $c ) >= 128 || ctype_alnum( $c ) ) {
609 if ( function_exists( 'mb_strtolower' ) ) {
610 $dir .= mb_strtolower( $c );
611 } else {
612 $dir .= strtolower( $c );
613 }
614 } else {
615 $dir .= sprintf( "%02X", ord( $c ) );
616 }
617 }
618 }
619 return $dir;
620 }
621
622 }
623
624 /** XML parser callback */
625 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
626 global $wgDumpImages;
627
628 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
629 $wgDumpImages[$attribs['SRC']] = true;
630 }
631 }
632
633 /** XML parser callback */
634 function wfDumpEndTagHandler( $parser, $name ) {}
635
636 # vim: syn=php
637 ?>