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 $file = fopen( $fullName, 'w' );
270 print("Can't open file $fullName for writing\n");
274 fwrite( $file, $text );
278 /** Set up globals required for parsing */
279 function setupGlobals( $currentDepth = NULL ) {
280 global $wgUser, $wgTitle, $wgStylePath, $wgArticlePath, $wgMathPath;
281 global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
282 global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
283 global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
284 global $wgRightsUrl, $wgRightsText, $wgCopyrightIcon;
286 static $oldLogo = NULL;
288 if ( !$this->setupDone ) {
289 $wgHooks['GetLocalURL'][] =& $this;
290 $wgHooks['GetFullURL'][] =& $this;
291 $this->oldArticlePath = $wgServer . $wgArticlePath;
294 if ( is_null( $currentDepth ) ) {
295 $currentDepth = $this->depth;
298 if ( $this->alternateScriptPath ) {
299 if ( $currentDepth == 0 ) {
302 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth - 1 );
305 $wgScriptPath = '..' . str_repeat( '/..', $currentDepth );
308 $wgArticlePath = str_repeat( '../', $currentDepth ) . '$1';
311 # Allow for repeated setup
312 if ( !is_null( $oldLogo ) ) {
318 if ( strpos( $wgLogo, $wgUploadPath ) === 0 ) {
319 # If it's in the upload directory, rewrite it to the new upload directory
320 $wgLogo = "$wgScriptPath/{$this->imageRel}/" . substr( $wgLogo, strlen( $wgUploadPath ) + 1 );
321 } elseif ( $wgLogo{0} == '/' ) {
322 # This is basically heuristic
323 # Rewrite an absolute logo path to one relative to the the script path
324 $wgLogo = $wgScriptPath . $wgLogo;
328 if ( !$this->setupDone ) {
329 $this->oldCopyrightIcon = $wgCopyrightIcon;
331 $wgCopyrightIcon = str_replace( 'src="/images',
332 'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $this->oldCopyrightIcon );
336 $wgStylePath = "$wgScriptPath/skins";
337 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
338 $wgSharedUploadPath = "$wgUploadPath/shared";
340 $wgHideInterlanguageLinks = !$this->interwiki;
341 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
342 $wgEnableParserCache = false;
343 $wgMathPath = "$wgScriptPath/math";
345 if ( !empty( $wgRightsText ) ) {
346 $wgRightsUrl = "$wgScriptPath/COPYING.html";
350 $wgUser->setOption( 'skin', $this->skin );
351 $wgUser->setOption( 'editsection', 0 );
353 $this->sharedStaticPath = "$wgUploadDirectory/shared";
355 $this->setupDone = true;
358 /** Reads the content of a title object, executes the skin and captures the result */
359 function getArticleHTML( &$title ) {
360 global $wgOut, $wgTitle, $wgArticle, $wgUser;
362 $linkCache =& LinkCache::singleton();
365 if ( is_null( $wgTitle ) ) {
369 $ns = $wgTitle->getNamespace();
370 if ( $ns == NS_SPECIAL ) {
371 $wgOut = new OutputPage;
372 $wgOut->setParserOptions( new ParserOptions );
373 SpecialPage::executePath( $wgTitle );
375 /** @todo merge with Wiki.php code */
376 if ( $ns == NS_IMAGE ) {
377 $wgArticle = new ImagePage( $wgTitle );
378 } elseif ( $ns == NS_CATEGORY ) {
379 $wgArticle = new CategoryPage( $wgTitle );
381 $wgArticle = new Article( $wgTitle );
383 $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
385 return $this->getRedirect( $rt );
387 $wgOut = new OutputPage;
388 $wgOut->setParserOptions( new ParserOptions );
394 $sk =& $wgUser->getSkin();
396 $sk->outputPage( $wgOut );
397 $text = ob_get_contents();
403 function getRedirect( $rt ) {
404 $url = $rt->escapeLocalURL();
405 $text = $rt->getPrefixedText();
407 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
408 <html xmlns="http://www.w3.org/1999/xhtml">
410 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
411 <meta http-equiv="Refresh" content="0;url=$url" />
414 <p>Redirecting to <a href="$url">$text</a></p>
420 /** Returns image paths used in an XHTML document */
421 function findImages( $text ) {
422 global $wgOutputEncoding, $wgDumpImages;
423 $parser = xml_parser_create( $wgOutputEncoding );
424 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
426 $wgDumpImages = array();
427 xml_parse( $parser, $text );
428 xml_parser_free( $parser );
430 return $wgDumpImages;
434 * Copy images (or create symlinks) from commons to a static directory.
435 * This is necessary even if you intend to distribute all of commons, because
436 * the directory contents is used to work out which image description pages
439 * Also copies math images
442 function copyImages( $images ) {
443 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
444 # Find shared uploads and copy them into the static directory
445 $sharedPathLength = strlen( $wgSharedUploadPath );
446 $mathPathLength = strlen( $wgMathPath );
447 foreach ( $images as $escapedImage => $dummy ) {
448 $image = urldecode( $escapedImage );
451 if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
452 # Reconstruct full filename
453 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
454 $sourceLoc = "$wgSharedUploadDirectory/$rel";
455 $staticLoc = "{$this->sharedStaticPath}/$rel";
456 #print "Copying $sourceLoc to $staticLoc\n";
457 # Copy to static directory
458 if ( !file_exists( $staticLoc ) ) {
459 wfMkdirParents( dirname( $staticLoc ), 0755 );
460 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
461 symlink( $sourceLoc, $staticLoc );
463 copy( $sourceLoc, $staticLoc );
467 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
468 # That was a thumbnail
469 # We will also copy the real image
470 $parts = explode( '/', $rel );
471 $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
472 $sourceLoc = "$wgSharedUploadDirectory/$rel";
473 $staticLoc = "{$this->sharedStaticPath}/$rel";
474 #print "Copying $sourceLoc to $staticLoc\n";
475 if ( !file_exists( $staticLoc ) ) {
476 wfMkdirParents( dirname( $staticLoc ), 0755 );
477 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
478 symlink( $sourceLoc, $staticLoc );
480 copy( $sourceLoc, $staticLoc );
486 if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
487 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
488 $source = "$wgMathDirectory/$rel";
489 $dest = "{$this->dest}/math/$rel";
490 @mkdir( "{$this->dest}/math", 0755 );
491 if ( !file_exists( $dest ) ) {
492 copy( $source, $dest );
498 function onGetFullURL( &$title, &$url, $query ) {
499 global $wgContLang, $wgArticlePath;
501 $iw = $title->getInterwiki();
502 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
503 if ( $title->getDBkey() == '' ) {
504 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
506 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
515 function onGetLocalURL( &$title, &$url, $query ) {
516 global $wgArticlePath;
518 if ( $title->isExternal() ) {
519 # Default is fine for interwiki
524 if ( $query != '' ) {
525 parse_str( $query, $params );
526 if ( isset($params['action']) && $params['action'] == 'raw' ) {
527 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
528 $file = 'gen.' . $params['gen'];
530 $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
531 // Clean up Monobook.css etc.
532 if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
533 $file = $matches[1] . '.' . $matches[2];
536 $this->rawPages[$file] = array( $file, $title, $params );
537 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
540 if ( $url === false ) {
541 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
547 function getHashedFilename( &$title ) {
548 if ( '' != $title->mInterwiki ) {
549 $dbkey = $title->getDBkey();
551 $dbkey = $title->getPrefixedDBkey();
554 $mainPage = Title::newMainPage();
555 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
559 return $this->getHashedDirectory( $title ) . '/' .
560 $this->getFriendlyName( $dbkey ) . '.html';
563 function getFriendlyName( $name ) {
565 # Replace illegal characters for Windows paths with underscores
566 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
568 # Work out lower case form. We assume we're on a system with case-insensitive
569 # filenames, so unless the case is of a special form, we have to disambiguate
570 if ( function_exists( 'mb_strtolower' ) ) {
571 $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
573 $lowerCase = ucfirst( strtolower( $name ) );
576 # Make it mostly unique
577 if ( $lowerCase != $friendlyName ) {
578 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
580 # Handle colon specially by replacing it with tilde
581 # Thus we reduce the number of paths with hashes appended
582 $friendlyName = str_replace( ':', '~', $friendlyName );
584 return $friendlyName;
588 * Get a relative directory for putting a title into
590 function getHashedDirectory( &$title ) {
591 if ( '' != $title->getInterwiki() ) {
592 $pdbk = $title->getDBkey();
594 $pdbk = $title->getPrefixedDBkey();
597 # Find the first colon if there is one, use characters after it
598 $p = strpos( $pdbk, ':' );
599 if ( $p !== false ) {
600 $dbk = substr( $pdbk, $p + 1 );
601 $dbk = substr( $dbk, strspn( $dbk, '_' ) );
606 # Split into characters
607 preg_match_all( '/./us', $dbk, $m );
610 $length = count( $chars );
613 for ( $i = 0; $i < $this->depth; $i++ ) {
617 if ( $i >= $length ) {
621 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
622 if ( function_exists( 'mb_strtolower' ) ) {
623 $dir .= mb_strtolower( $c );
625 $dir .= strtolower( $c );
628 $dir .= sprintf( "%02X", ord( $c ) );
637 /** XML parser callback */
638 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
639 global $wgDumpImages;
641 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
642 $wgDumpImages[$attribs['SRC']] = true;
646 /** XML parser callback */
647 function wfDumpEndTagHandler( $parser, $name ) {}