4 * @subpackage Maintenance
7 define( 'REPORTING_INTERVAL', 10 );
9 require_once( 'includes/ImagePage.php' );
10 require_once( 'includes/CategoryPage.php' );
11 require_once( 'includes/RawPage.php' );
14 # Destination directory
17 # Show interlanguage links?
18 var $interwiki = true;
20 # Depth of HTML directory tree
23 # Directory that commons images are copied into
24 var $sharedStaticDirectory;
26 # Directory that the images are in, after copying
27 var $destUploadDirectory;
29 # Relative path to image directory
30 var $imageRel = 'upload';
32 # Copy commons images instead of symlinking
33 var $forceCopy = false;
35 # Make a copy of all images encountered
36 var $makeSnapshot = false;
38 # Make links assuming the script path is in the same directory as
40 var $alternateScriptPath = false;
42 # Original values of various globals
43 var $oldArticlePath = false, $oldCopyrightIcon = false;
45 # Has setupGlobals been called?
46 var $setupDone = false;
48 # List of raw pages used in the current article
52 var $skin = 'htmldump';
54 function DumpHTML( $settings ) {
55 foreach ( $settings as $var => $value ) {
61 * Write a set of articles specified by start and end page_id
62 * Skip categories and images, they will be done separately
64 function doArticles( $start, $end = false ) {
65 $fname = 'DumpHTML::doArticles';
67 $this->setupGlobals();
69 if ( $end === false ) {
70 $dbr =& wfGetDB( DB_SLAVE );
71 $end = $dbr->selectField( 'page', 'max(page_id)', false, $fname );
74 $mainPageObj = Title::newMainPage();
75 $mainPage = $mainPageObj->getPrefixedDBkey();
78 for ($id = $start; $id <= $end; $id++) {
79 wfWaitForSlaves( 20 );
80 if ( !($id % REPORTING_INTERVAL) ) {
81 print "Processing ID: $id\r";
83 if ( !($id % (REPORTING_INTERVAL*10) ) ) {
86 $title = Title::newFromID( $id );
88 $ns = $title->getNamespace() ;
89 if ( $ns != NS_CATEGORY && $title->getPrefixedDBkey() != $mainPage ) {
90 $this->doArticle( $title );
97 function doSpecials() {
100 $this->setupGlobals();
101 print "Special:Categories...";
102 $this->doArticle( Title::makeTitle( NS_SPECIAL, 'Categories' ) );
106 /** Write the main page as index.html */
107 function doMainPage() {
109 print "Making index.html ";
111 // Set up globals with no ../../.. in the link URLs
112 $this->setupGlobals( 0 );
114 $title = Title::newMainPage();
115 $text = $this->getArticleHTML( $title );
117 # Parse the XHTML to find the images
118 $images = $this->findImages( $text );
119 $this->copyImages( $images );
121 $file = fopen( "{$this->dest}/index.html", "w" );
123 print "\nCan't open index.html for writing\n";
126 fwrite( $file, $text );
131 function doImageDescriptions() {
132 global $wgSharedUploadDirectory;
134 $fname = 'DumpHTML::doImageDescriptions';
136 $this->setupGlobals();
139 * Dump image description pages that don't have an associated article, but do
142 $dbr =& wfGetDB( DB_SLAVE );
143 extract( $dbr->tableNames( 'image', 'page' ) );
144 $res = $dbr->select( 'image', array( 'img_name' ), false, $fname );
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";
154 $title = Title::makeTitle( NS_IMAGE, $row->img_name );
155 if ( $title->getArticleID() ) {
156 // Already done by dumpHTML
159 $this->doArticle( $title );
164 * Dump images which only have a real description page on commons
166 print "Writing description pages for commons images\n";
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/*" ) );
173 foreach ( $paths as $path ) {
174 $file = basename( $path );
175 if ( !(++$i % REPORTING_INTERVAL ) ) {
179 $title = Title::makeTitle( NS_IMAGE, $file );
180 $this->doArticle( $title );
186 function doCategories() {
187 $fname = 'DumpHTML::doCategories';
188 $this->setupGlobals();
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 );
195 print "\nWriting " . $dbr->numRows( $res ). " category pages\n";
197 while ( $row = $dbr->fetchObject( $res ) ) {
198 wfWaitForSlaves( 10 );
199 if ( !(++$i % REPORTING_INTERVAL ) ) {
202 $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
203 $this->doArticle( $title );
208 function doRedirects() {
209 print "Doing redirects...\n";
210 $fname = 'DumpHTML::doRedirects';
211 $this->setupGlobals();
212 $dbr =& wfGetDB( DB_SLAVE );
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";
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";
224 $this->doArticle( $title );
228 /** Write an article specified by title */
229 function doArticle( $title ) {
230 global $wgTitle, $wgSharedUploadPath, $wgSharedUploadDirectory;
231 global $wgUploadDirectory;
233 $this->rawPages = array();
234 $text = $this->getArticleHTML( $title );
236 if ( $text === false ) {
240 # Parse the XHTML to find the images
241 $images = $this->findImages( $text );
242 $this->copyImages( $images );
245 $this->writeArticle( $title, $text );
248 wfMkdirParents( "{$this->dest}/raw", 0755 );
249 foreach( $this->rawPages as $record ) {
250 list( $file, $title, $params ) = $record;
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();
259 print "Writing $file\n";
260 $file = fopen( $path, 'w' );
262 print("Can't open file $fullName for writing\n");
265 fwrite( $file, $text );
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 );
277 wfMkdirParents( $fullDir, 0755 );
279 wfSuppressWarnings();
280 $file = fopen( $fullName, 'w' );
284 die("Can't open file '$fullName' for writing.\nCheck permissions or use another destination (-d).\n");
288 fwrite( $file, $text );
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;
300 static $oldLogo = NULL;
302 if ( !$this->setupDone ) {
303 $wgHooks['GetLocalURL'][] =& $this;
304 $wgHooks['GetFullURL'][] =& $this;
305 $this->oldArticlePath = $wgServer . $wgArticlePath;
308 if ( is_null( $currentDepth ) ) {
309 $currentDepth = $this->depth;
312 if ( $this->alternateScriptPath ) {
313 if ( $currentDepth == 0 ) {
316 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth - 1 );
319 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth );
322 $wgArticlePath = str_repeat( '../', $currentDepth ) . '$1';
325 # Allow for repeated setup
326 if ( !is_null( $oldLogo ) ) {
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;
342 if ( !$this->setupDone ) {
343 $this->oldCopyrightIcon = $wgCopyrightIcon;
345 $wgCopyrightIcon = str_replace( 'src="/images',
346 'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $this->oldCopyrightIcon );
348 $wgStylePath = "$wgScriptPath/skins";
349 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
350 $wgSharedUploadPath = "$wgUploadPath/shared";
352 $wgHideInterlanguageLinks = !$this->interwiki;
353 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
354 $wgEnableParserCache = false;
355 $wgMathPath = "$wgScriptPath/math";
356 $wgEnableSidebarCache = false;
358 if ( !empty( $wgRightsText ) ) {
359 $wgRightsUrl = "$wgScriptPath/COPYING.html";
363 $wgUser->setOption( 'skin', $this->skin );
364 $wgUser->setOption( 'editsection', 0 );
366 if ( $this->makeSnapshot ) {
367 $this->destUploadDirectory = "{$this->dest}/{$this->imageRel}";
368 if ( realpath( $this->destUploadDirectory == $wgUploadDirectory ) ) {
369 $this->makeSnapshot = false;
373 $this->sharedStaticDirectory = "{$this->destUploadDirectory}/shared";
375 $this->setupDone = true;
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;
382 $linkCache =& LinkCache::singleton();
385 if ( is_null( $wgTitle ) ) {
389 $ns = $wgTitle->getNamespace();
390 if ( $ns == NS_SPECIAL ) {
391 $wgOut = new OutputPage;
392 $wgOut->setParserOptions( new ParserOptions );
393 SpecialPage::executePath( $wgTitle );
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 );
401 $wgArticle = new Article( $wgTitle );
403 $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
405 return $this->getRedirect( $rt );
407 $wgOut = new OutputPage;
408 $wgOut->setParserOptions( new ParserOptions );
414 $sk =& $wgUser->getSkin();
416 $sk->outputPage( $wgOut );
417 $text = ob_get_contents();
423 function getRedirect( $rt ) {
424 $url = $rt->escapeLocalURL();
425 $text = $rt->getPrefixedText();
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">
430 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
431 <meta http-equiv="Refresh" content="0;url=$url" />
434 <p>Redirecting to <a href="$url">$text</a></p>
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' );
446 $wgDumpImages = array();
447 xml_parse( $parser, $text );
448 xml_parser_free( $parser );
450 return $wgDumpImages;
454 * Copy a file specified by a URL to a given directory
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
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 );
471 copy( $sourceLoc, $destLoc );
477 * Copy an image, and if it is a thumbnail, copy its parent image too
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 );
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
499 * Also copies math images, and full-sized images if the makeSnapshot option
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 );
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 );
523 function onGetFullURL( &$title, &$url, $query ) {
524 global $wgContLang, $wgArticlePath;
526 $iw = $title->getInterwiki();
527 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
528 if ( $title->getDBkey() == '' ) {
529 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
531 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
540 function onGetLocalURL( &$title, &$url, $query ) {
541 global $wgArticlePath;
543 if ( $title->isExternal() ) {
544 # Default is fine for interwiki
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'];
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];
561 $this->rawPages[$file] = array( $file, $title, $params );
562 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
565 if ( $url === false ) {
566 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
572 function getHashedFilename( &$title ) {
573 if ( '' != $title->mInterwiki ) {
574 $dbkey = $title->getDBkey();
576 $dbkey = $title->getPrefixedDBkey();
579 $mainPage = Title::newMainPage();
580 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
584 return $this->getHashedDirectory( $title ) . '/' .
585 $this->getFriendlyName( $dbkey ) . '.html';
588 function getFriendlyName( $name ) {
590 # Replace illegal characters for Windows paths with underscores
591 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
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 ) );
598 $lowerCase = ucfirst( strtolower( $name ) );
601 # Make it mostly unique
602 if ( $lowerCase != $friendlyName ) {
603 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
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 );
609 return $friendlyName;
613 * Get a relative directory for putting a title into
615 function getHashedDirectory( &$title ) {
616 if ( '' != $title->getInterwiki() ) {
617 $pdbk = $title->getDBkey();
619 $pdbk = $title->getPrefixedDBkey();
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, '_' ) );
631 # Split into characters
632 preg_match_all( '/./us', $dbk, $m );
635 $length = count( $chars );
638 for ( $i = 0; $i < $this->depth; $i++ ) {
642 if ( $i >= $length ) {
646 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
647 if ( function_exists( 'mb_strtolower' ) ) {
648 $dir .= mb_strtolower( $c );
650 $dir .= strtolower( $c );
653 $dir .= sprintf( "%02X", ord( $c ) );
662 /** XML parser callback */
663 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
664 global $wgDumpImages;
666 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
667 $wgDumpImages[$attribs['SRC']] = true;
671 /** XML parser callback */
672 function wfDumpEndTagHandler( $parser, $name ) {}