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
45 function DumpHTML( $settings ) {
46 foreach ( $settings as $var => $value ) {
52 * Write a set of articles specified by start and end page_id
53 * Skip categories and images, they will be done separately
55 function doArticles( $start, $end = false ) {
56 $fname = 'DumpHTML::doArticles';
58 $this->setupGlobals();
60 if ( $end === false ) {
61 $dbr =& wfGetDB( DB_SLAVE );
62 $end = $dbr->selectField( 'page', 'max(page_id)', false, $fname );
65 $mainPageObj = Title::newMainPage();
66 $mainPage = $mainPageObj->getPrefixedDBkey();
69 for ($id = $start; $id <= $end; $id++) {
70 wfWaitForSlaves( 20 );
71 if ( !($id % REPORTING_INTERVAL) ) {
72 print "Processing ID: $id\r";
74 if ( !($id % (REPORTING_INTERVAL*10) ) ) {
77 $title = Title::newFromID( $id );
79 $ns = $title->getNamespace() ;
80 if ( $ns != NS_CATEGORY && $title->getPrefixedDBkey() != $mainPage ) {
81 $this->doArticle( $title );
88 function doSpecials() {
91 $this->setupGlobals();
92 print "Special:Categories...";
93 $this->doArticle( Title::makeTitle( NS_SPECIAL, 'Categories' ) );
97 /** Write the main page as index.html */
98 function doMainPage() {
100 print "Making index.html ";
102 // Set up globals with no ../../.. in the link URLs
103 $this->setupGlobals( 0 );
105 $title = Title::newMainPage();
106 $text = $this->getArticleHTML( $title );
107 $file = fopen( "{$this->dest}/index.html", "w" );
109 print "\nCan't open index.html for writing\n";
112 fwrite( $file, $text );
117 function doImageDescriptions() {
118 global $wgSharedUploadDirectory;
120 $fname = 'DumpHTML::doImageDescriptions';
122 $this->setupGlobals();
125 * Dump image description pages that don't have an associated article, but do
128 $dbr =& wfGetDB( DB_SLAVE );
129 extract( $dbr->tableNames( 'image', 'page' ) );
130 $res = $dbr->select( 'image', array( 'img_name' ), false, $fname );
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";
140 $title = Title::makeTitle( NS_IMAGE, $row->img_name );
141 if ( $title->getArticleID() ) {
142 // Already done by dumpHTML
145 $this->doArticle( $title );
150 * Dump images which only have a real description page on commons
152 print "Writing description pages for commons images\n";
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/*" ) );
159 foreach ( $paths as $path ) {
160 $file = basename( $path );
161 if ( !(++$i % REPORTING_INTERVAL ) ) {
165 $title = Title::makeTitle( NS_IMAGE, $file );
166 $this->doArticle( $title );
172 function doCategories() {
173 $fname = 'DumpHTML::doCategories';
174 $this->setupGlobals();
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 );
182 print "\nWriting " . $dbr->numRows( $res ). " category pages\n";
184 while ( $row = $dbr->fetchObject( $res ) ) {
185 wfWaitForSlaves( 10 );
186 if ( !(++$i % REPORTING_INTERVAL ) ) {
189 $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
190 $this->doArticle( $title );
195 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;
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 $wgHideInterlangageLinks = !$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', 'htmldump' );
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, $wgLinkCache;
363 if ( is_null( $wgTitle ) ) {
367 $ns = $wgTitle->getNamespace();
368 if ( $ns == NS_SPECIAL ) {
369 $wgOut = new OutputPage;
370 $wgOut->setParserOptions( new ParserOptions );
371 $wgLinkCache = new LinkCache;
372 SpecialPage::executePath( $wgTitle );
374 if ( $ns == NS_IMAGE ) {
375 $wgArticle = new ImagePage( $wgTitle );
376 } elseif ( $ns == NS_CATEGORY ) {
377 $wgArticle = new CategoryPage( $wgTitle );
379 $wgArticle = new Article( $wgTitle );
381 $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
383 return $this->getRedirect( $rt );
385 $wgOut = new OutputPage;
386 $wgOut->setParserOptions( new ParserOptions );
387 $wgLinkCache = new LinkCache;
393 $sk =& $wgUser->getSkin();
395 $sk->outputPage( $wgOut );
396 $text = ob_get_contents();
402 function getRedirect( $rt ) {
403 $url = $rt->escapeLocalURL();
404 $text = $rt->getPrefixedText();
406 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
407 <html xmlns="http://www.w3.org/1999/xhtml">
409 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
410 <meta http-equiv="Refresh" content="0;url=$url" />
413 <p>Redirecting to <a href="$url">$text</a></p>
419 /** Returns image paths used in an XHTML document */
420 function findImages( $text ) {
421 global $wgOutputEncoding, $wgDumpImages;
422 $parser = xml_parser_create( $wgOutputEncoding );
423 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
425 $wgDumpImages = array();
426 xml_parse( $parser, $text );
427 xml_parser_free( $parser );
429 return $wgDumpImages;
433 * Copy images (or create symlinks) from commons to a static directory.
434 * This is necessary even if you intend to distribute all of commons, because
435 * the directory contents is used to work out which image description pages
438 * Also copies math images
441 function copyImages( $images ) {
442 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
443 # Find shared uploads and copy them into the static directory
444 $sharedPathLength = strlen( $wgSharedUploadPath );
445 $mathPathLength = strlen( $wgMathPath );
446 foreach ( $images as $escapedImage => $dummy ) {
447 $image = urldecode( $escapedImage );
450 if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
451 # Reconstruct full filename
452 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
453 $sourceLoc = "$wgSharedUploadDirectory/$rel";
454 $staticLoc = "{$this->sharedStaticPath}/$rel";
455 #print "Copying $sourceLoc to $staticLoc\n";
456 # Copy to static directory
457 if ( !file_exists( $staticLoc ) ) {
458 wfMkdirParents( dirname( $staticLoc ), 0755 );
459 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
460 symlink( $sourceLoc, $staticLoc );
462 copy( $sourceLoc, $staticLoc );
466 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
467 # That was a thumbnail
468 # We will also copy the real image
469 $parts = explode( '/', $rel );
470 $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
471 $sourceLoc = "$wgSharedUploadDirectory/$rel";
472 $staticLoc = "{$this->sharedStaticPath}/$rel";
473 #print "Copying $sourceLoc to $staticLoc\n";
474 if ( !file_exists( $staticLoc ) ) {
475 wfMkdirParents( dirname( $staticLoc ), 0755 );
476 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
477 symlink( $sourceLoc, $staticLoc );
479 copy( $sourceLoc, $staticLoc );
485 if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
486 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
487 $source = "$wgMathDirectory/$rel";
488 $dest = "{$this->dest}/math/$rel";
489 @mkdir( "{$this->dest}/math", 0755 );
490 if ( !file_exists( $dest ) ) {
491 copy( $source, $dest );
497 function onGetFullURL( &$title, &$url, $query ) {
498 global $wgContLang, $wgArticlePath;
500 $iw = $title->getInterwiki();
501 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
502 if ( $title->getDBkey() == '' ) {
503 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
505 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
514 function onGetLocalURL( &$title, &$url, $query ) {
515 global $wgArticlePath;
517 if ( $title->isExternal() ) {
518 # Default is fine for interwiki
523 if ( $query != '' ) {
524 parse_str( $query, $params );
525 if ( isset($params['action']) && $params['action'] == 'raw' ) {
526 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
527 $file = 'gen.' . $params['gen'];
529 $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
530 // Clean up Monobook.css etc.
531 if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
532 $file = $matches[1] . '.' . $matches[2];
535 $this->rawPages[$file] = array( $file, $title, $params );
536 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
539 if ( $url === false ) {
540 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
546 function getHashedFilename( &$title ) {
547 if ( '' != $title->mInterwiki ) {
548 $dbkey = $title->getDBkey();
550 $dbkey = $title->getPrefixedDBkey();
553 $mainPage = Title::newMainPage();
554 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
558 return $this->getHashedDirectory( $title ) . '/' .
559 $this->getFriendlyName( $dbkey ) . '.html';
562 function getFriendlyName( $name ) {
564 # Replace illegal characters for Windows paths with underscores
565 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
567 # Work out lower case form. We assume we're on a system with case-insensitive
568 # filenames, so unless the case is of a special form, we have to disambiguate
569 if ( function_exists( 'mb_strtolower' ) ) {
570 $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
572 $lowerCase = ucfirst( strtolower( $name ) );
575 # Make it mostly unique
576 if ( $lowerCase != $friendlyName ) {
577 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
579 # Handle colon specially by replacing it with tilde
580 # Thus we reduce the number of paths with hashes appended
581 $friendlyName = str_replace( ':', '~', $friendlyName );
583 return $friendlyName;
587 * Get a relative directory for putting a title into
589 function getHashedDirectory( &$title ) {
590 if ( '' != $title->getInterwiki() ) {
591 $pdbk = $title->getDBkey();
593 $pdbk = $title->getPrefixedDBkey();
596 # Find the first colon if there is one, use characters after it
597 $p = strpos( $pdbk, ':' );
598 if ( $p !== false ) {
599 $dbk = substr( $pdbk, $p + 1 );
600 $dbk = substr( $dbk, strspn( $dbk, '_' ) );
605 # Split into characters
606 preg_match_all( '/./us', $dbk, $m );
609 $length = count( $chars );
612 for ( $i = 0; $i < $this->depth; $i++ ) {
616 if ( $i >= $length ) {
620 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
621 if ( function_exists( 'mb_strtolower' ) ) {
622 $dir .= mb_strtolower( $c );
624 $dir .= strtolower( $c );
627 $dir .= sprintf( "%02X", ord( $c ) );
636 /** XML parser callback */
637 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
638 global $wgDumpImages;
640 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
641 $wgDumpImages[$attribs['SRC']] = true;
645 /** XML parser callback */
646 function wfDumpEndTagHandler( $parser, $name ) {}