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 $sharedStaticPath;
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
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
46 var $skin = 'dumphtml';
48 function DumpHTML( $settings ) {
49 foreach ( $settings as $var => $value ) {
55 * Write a set of articles specified by start and end page_id
56 * Skip categories and images, they will be done separately
58 function doArticles( $start, $end = false ) {
59 $fname = 'DumpHTML::doArticles';
61 $this->setupGlobals();
63 if ( $end === false ) {
64 $dbr =& wfGetDB( DB_SLAVE );
65 $end = $dbr->selectField( 'page', 'max(page_id)', false, $fname );
68 $mainPageObj = Title::newMainPage();
69 $mainPage = $mainPageObj->getPrefixedDBkey();
72 for ($id = $start; $id <= $end; $id++) {
73 wfWaitForSlaves( 20 );
74 if ( !($id % REPORTING_INTERVAL) ) {
75 print "Processing ID: $id\r";
77 if ( !($id % (REPORTING_INTERVAL*10) ) ) {
80 $title = Title::newFromID( $id );
82 $ns = $title->getNamespace() ;
83 if ( $ns != NS_CATEGORY && $title->getPrefixedDBkey() != $mainPage ) {
84 $this->doArticle( $title );
91 function doSpecials() {
94 $this->setupGlobals();
95 print "Special:Categories...";
96 $this->doArticle( Title::makeTitle( NS_SPECIAL, 'Categories' ) );
100 /** Write the main page as index.html */
101 function doMainPage() {
103 print "Making index.html ";
105 // Set up globals with no ../../.. in the link URLs
106 $this->setupGlobals( 0 );
108 $title = Title::newMainPage();
109 $text = $this->getArticleHTML( $title );
110 $file = fopen( "{$this->dest}/index.html", "w" );
112 print "\nCan't open index.html for writing\n";
115 fwrite( $file, $text );
120 function doImageDescriptions() {
121 global $wgSharedUploadDirectory;
123 $fname = 'DumpHTML::doImageDescriptions';
125 $this->setupGlobals();
128 * Dump image description pages that don't have an associated article, but do
131 $dbr =& wfGetDB( DB_SLAVE );
132 extract( $dbr->tableNames( 'image', 'page' ) );
133 $res = $dbr->select( 'image', array( 'img_name' ), false, $fname );
136 print "Writing image description pages for local images\n";
137 $num = $dbr->numRows( $res );
138 while ( $row = $dbr->fetchObject( $res ) ) {
139 wfWaitForSlaves( 10 );
140 if ( !( ++$i % REPORTING_INTERVAL ) ) {
141 print "Done $i of $num\r";
143 $title = Title::makeTitle( NS_IMAGE, $row->img_name );
144 if ( $title->getArticleID() ) {
145 // Already done by dumpHTML
148 $this->doArticle( $title );
153 * Dump images which only have a real description page on commons
155 print "Writing description pages for commons images\n";
157 for ( $hash = 0; $hash < 256; $hash++ ) {
158 $dir = sprintf( "%01x/%02x", intval( $hash / 16 ), $hash );
159 $paths = array_merge( glob( "{$this->sharedStaticPath}/$dir/*" ),
160 glob( "{$this->sharedStaticPath}/thumb/$dir/*" ) );
162 foreach ( $paths as $path ) {
163 $file = basename( $path );
164 if ( !(++$i % REPORTING_INTERVAL ) ) {
168 $title = Title::makeTitle( NS_IMAGE, $file );
169 $this->doArticle( $title );
175 function doCategories() {
176 $fname = 'DumpHTML::doCategories';
177 $this->setupGlobals();
179 $dbr =& wfGetDB( DB_SLAVE );
180 print "Selecting categories...";
181 $sql = 'SELECT DISTINCT cl_to FROM ' . $dbr->tableName( 'categorylinks' );
182 $res = $dbr->query( $sql, $fname );
184 print "\nWriting " . $dbr->numRows( $res ). " category pages\n";
186 while ( $row = $dbr->fetchObject( $res ) ) {
187 wfWaitForSlaves( 10 );
188 if ( !(++$i % REPORTING_INTERVAL ) ) {
191 $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
192 $this->doArticle( $title );
197 function doRedirects() {
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";
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";
213 $this->doArticle( $title );
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 ) {
229 # Parse the XHTML to find the images
230 $images = $this->findImages( $text );
231 $this->copyImages( $images );
234 $this->writeArticle( $title, $text );
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' );
251 print("Can't open file $fullName for writing\n");
254 fwrite( $file, $text );
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 wfSuppressWarnings();
269 $file = fopen( $fullName, 'w' );
273 die("Can't open file '$fullName' for writing.\nCheck permissions or use another destination (-d).\n");
277 fwrite( $file, $text );
281 /** Set up globals required for parsing */
282 function setupGlobals( $currentDepth = NULL ) {
283 global $wgUser, $wgTitle, $wgStylePath, $wgArticlePath, $wgMathPath;
284 global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
285 global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
286 global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
287 global $wgRightsUrl, $wgRightsText, $wgCopyrightIcon;
289 static $oldLogo = NULL;
291 if ( !$this->setupDone ) {
292 $wgHooks['GetLocalURL'][] =& $this;
293 $wgHooks['GetFullURL'][] =& $this;
294 $this->oldArticlePath = $wgServer . $wgArticlePath;
297 if ( is_null( $currentDepth ) ) {
298 $currentDepth = $this->depth;
301 if ( $this->alternateScriptPath ) {
302 if ( $currentDepth == 0 ) {
305 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth - 1 );
308 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth );
311 $wgArticlePath = str_repeat( '../', $currentDepth ) . '$1';
314 # Allow for repeated setup
315 if ( !is_null( $oldLogo ) ) {
321 if ( strpos( $wgLogo, $wgUploadPath ) === 0 ) {
322 # If it's in the upload directory, rewrite it to the new upload directory
323 $wgLogo = "$wgScriptPath/{$this->imageRel}/" . substr( $wgLogo, strlen( $wgUploadPath ) + 1 );
324 } elseif ( $wgLogo{0} == '/' ) {
325 # This is basically heuristic
326 # Rewrite an absolute logo path to one relative to the the script path
327 $wgLogo = $wgScriptPath . $wgLogo;
331 if ( !$this->setupDone ) {
332 $this->oldCopyrightIcon = $wgCopyrightIcon;
334 $wgCopyrightIcon = str_replace( 'src="/images',
335 'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $this->oldCopyrightIcon );
339 $wgStylePath = "$wgScriptPath/skins";
340 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
341 $wgSharedUploadPath = "$wgUploadPath/shared";
343 $wgHideInterlanguageLinks = !$this->interwiki;
344 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
345 $wgEnableParserCache = false;
346 $wgMathPath = "$wgScriptPath/math";
348 if ( !empty( $wgRightsText ) ) {
349 $wgRightsUrl = "$wgScriptPath/COPYING.html";
353 $wgUser->setOption( 'skin', $this->skin );
354 $wgUser->setOption( 'editsection', 0 );
356 $this->sharedStaticPath = "$wgUploadDirectory/shared";
358 $this->setupDone = true;
361 /** Reads the content of a title object, executes the skin and captures the result */
362 function getArticleHTML( &$title ) {
363 global $wgOut, $wgTitle, $wgArticle, $wgUser;
365 $linkCache =& LinkCache::singleton();
368 if ( is_null( $wgTitle ) ) {
372 $ns = $wgTitle->getNamespace();
373 if ( $ns == NS_SPECIAL ) {
374 $wgOut = new OutputPage;
375 $wgOut->setParserOptions( new ParserOptions );
376 SpecialPage::executePath( $wgTitle );
378 /** @todo merge with Wiki.php code */
379 if ( $ns == NS_IMAGE ) {
380 $wgArticle = new ImagePage( $wgTitle );
381 } elseif ( $ns == NS_CATEGORY ) {
382 $wgArticle = new CategoryPage( $wgTitle );
384 $wgArticle = new Article( $wgTitle );
386 $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
388 return $this->getRedirect( $rt );
390 $wgOut = new OutputPage;
391 $wgOut->setParserOptions( new ParserOptions );
397 $sk =& $wgUser->getSkin();
399 $sk->outputPage( $wgOut );
400 $text = ob_get_contents();
406 function getRedirect( $rt ) {
407 $url = $rt->escapeLocalURL();
408 $text = $rt->getPrefixedText();
410 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
411 <html xmlns="http://www.w3.org/1999/xhtml">
413 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
414 <meta http-equiv="Refresh" content="0;url=$url" />
417 <p>Redirecting to <a href="$url">$text</a></p>
423 /** Returns image paths used in an XHTML document */
424 function findImages( $text ) {
425 global $wgOutputEncoding, $wgDumpImages;
426 $parser = xml_parser_create( $wgOutputEncoding );
427 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
429 $wgDumpImages = array();
430 xml_parse( $parser, $text );
431 xml_parser_free( $parser );
433 return $wgDumpImages;
437 * Copy images (or create symlinks) from commons to a static directory.
438 * This is necessary even if you intend to distribute all of commons, because
439 * the directory contents is used to work out which image description pages
442 * Also copies math images
445 function copyImages( $images ) {
446 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
447 # Find shared uploads and copy them into the static directory
448 $sharedPathLength = strlen( $wgSharedUploadPath );
449 $mathPathLength = strlen( $wgMathPath );
450 foreach ( $images as $escapedImage => $dummy ) {
451 $image = urldecode( $escapedImage );
454 if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
455 # Reconstruct full filename
456 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
457 $sourceLoc = "$wgSharedUploadDirectory/$rel";
458 $staticLoc = "{$this->sharedStaticPath}/$rel";
459 #print "Copying $sourceLoc to $staticLoc\n";
460 # Copy to static directory
461 if ( !file_exists( $staticLoc ) ) {
462 wfMkdirParents( dirname( $staticLoc ), 0755 );
463 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
464 symlink( $sourceLoc, $staticLoc );
466 copy( $sourceLoc, $staticLoc );
470 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
471 # That was a thumbnail
472 # We will also copy the real image
473 $parts = explode( '/', $rel );
474 $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
475 $sourceLoc = "$wgSharedUploadDirectory/$rel";
476 $staticLoc = "{$this->sharedStaticPath}/$rel";
477 #print "Copying $sourceLoc to $staticLoc\n";
478 if ( !file_exists( $staticLoc ) ) {
479 wfMkdirParents( dirname( $staticLoc ), 0755 );
480 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
481 symlink( $sourceLoc, $staticLoc );
483 copy( $sourceLoc, $staticLoc );
489 if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
490 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
491 $source = "$wgMathDirectory/$rel";
492 $dest = "{$this->dest}/math/$rel";
493 @mkdir( "{$this->dest}/math", 0755 );
494 if ( !file_exists( $dest ) ) {
495 copy( $source, $dest );
501 function onGetFullURL( &$title, &$url, $query ) {
502 global $wgContLang, $wgArticlePath;
504 $iw = $title->getInterwiki();
505 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
506 if ( $title->getDBkey() == '' ) {
507 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
509 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
518 function onGetLocalURL( &$title, &$url, $query ) {
519 global $wgArticlePath;
521 if ( $title->isExternal() ) {
522 # Default is fine for interwiki
527 if ( $query != '' ) {
528 parse_str( $query, $params );
529 if ( isset($params['action']) && $params['action'] == 'raw' ) {
530 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
531 $file = 'gen.' . $params['gen'];
533 $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
534 // Clean up Monobook.css etc.
535 if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
536 $file = $matches[1] . '.' . $matches[2];
539 $this->rawPages[$file] = array( $file, $title, $params );
540 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
543 if ( $url === false ) {
544 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
550 function getHashedFilename( &$title ) {
551 if ( '' != $title->mInterwiki ) {
552 $dbkey = $title->getDBkey();
554 $dbkey = $title->getPrefixedDBkey();
557 $mainPage = Title::newMainPage();
558 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
562 return $this->getHashedDirectory( $title ) . '/' .
563 $this->getFriendlyName( $dbkey ) . '.html';
566 function getFriendlyName( $name ) {
568 # Replace illegal characters for Windows paths with underscores
569 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
571 # Work out lower case form. We assume we're on a system with case-insensitive
572 # filenames, so unless the case is of a special form, we have to disambiguate
573 if ( function_exists( 'mb_strtolower' ) ) {
574 $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
576 $lowerCase = ucfirst( strtolower( $name ) );
579 # Make it mostly unique
580 if ( $lowerCase != $friendlyName ) {
581 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
583 # Handle colon specially by replacing it with tilde
584 # Thus we reduce the number of paths with hashes appended
585 $friendlyName = str_replace( ':', '~', $friendlyName );
587 return $friendlyName;
591 * Get a relative directory for putting a title into
593 function getHashedDirectory( &$title ) {
594 if ( '' != $title->getInterwiki() ) {
595 $pdbk = $title->getDBkey();
597 $pdbk = $title->getPrefixedDBkey();
600 # Find the first colon if there is one, use characters after it
601 $p = strpos( $pdbk, ':' );
602 if ( $p !== false ) {
603 $dbk = substr( $pdbk, $p + 1 );
604 $dbk = substr( $dbk, strspn( $dbk, '_' ) );
609 # Split into characters
610 preg_match_all( '/./us', $dbk, $m );
613 $length = count( $chars );
616 for ( $i = 0; $i < $this->depth; $i++ ) {
620 if ( $i >= $length ) {
624 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
625 if ( function_exists( 'mb_strtolower' ) ) {
626 $dir .= mb_strtolower( $c );
628 $dir .= strtolower( $c );
631 $dir .= sprintf( "%02X", ord( $c ) );
640 /** XML parser callback */
641 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
642 global $wgDumpImages;
644 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
645 $wgDumpImages[$attribs['SRC']] = true;
649 /** XML parser callback */
650 function wfDumpEndTagHandler( $parser, $name ) {}