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 article path, for "current version" links
37 var $oldArticlePath = 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 $wgCopyrightIcon = str_replace( 'src="/images',
329 'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $wgCopyrightIcon );
333 $wgStylePath = "$wgScriptPath/skins";
334 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
335 $wgSharedUploadPath = "$wgUploadPath/shared";
337 $wgHideInterlangageLinks = !$this->interwiki;
338 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
339 $wgEnableParserCache = false;
340 $wgMathPath = "$wgScriptPath/math";
342 if ( !empty( $wgRightsText ) ) {
343 $wgRightsUrl = "$wgScriptPath/COPYING.html";
347 $wgUser->setOption( 'skin', 'htmldump' );
348 $wgUser->setOption( 'editsection', 0 );
350 $this->sharedStaticPath = "$wgUploadDirectory/shared";
352 $this->setupDone = true;
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;
360 if ( is_null( $wgTitle ) ) {
364 $ns = $wgTitle->getNamespace();
365 if ( $ns == NS_SPECIAL ) {
366 $wgOut = new OutputPage;
367 $wgOut->setParserOptions( new ParserOptions );
368 $wgLinkCache = new LinkCache;
369 SpecialPage::executePath( $wgTitle );
371 if ( $ns == NS_IMAGE ) {
372 $wgArticle = new ImagePage( $wgTitle );
373 } elseif ( $wgUseCategoryMagic && $ns == NS_CATEGORY ) {
374 $wgArticle = new CategoryPage( $wgTitle );
376 $wgArticle = new Article( $wgTitle );
378 $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
380 return $this->getRedirect( $rt );
382 $wgOut = new OutputPage;
383 $wgOut->setParserOptions( new ParserOptions );
384 $wgLinkCache = new LinkCache;
390 $sk =& $wgUser->getSkin();
392 $sk->outputPage( $wgOut );
393 $text = ob_get_contents();
399 function getRedirect( $rt ) {
400 $url = $rt->escapeLocalURL();
401 $text = $rt->getPrefixedText();
403 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
404 <html xmlns="http://www.w3.org/1999/xhtml">
406 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
407 <meta http-equiv="Refresh" content="0;url=$url" />
410 <p>Redirecting to <a href="$url">$text</a></p>
416 /** Returns image paths used in an XHTML document */
417 function findImages( $text ) {
418 global $wgOutputEncoding, $wgDumpImages;
419 $parser = xml_parser_create( $wgOutputEncoding );
420 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
422 $wgDumpImages = array();
423 xml_parse( $parser, $text );
424 xml_parser_free( $parser );
426 return $wgDumpImages;
430 * Copy images (or create symlinks) from commons to a static directory.
431 * This is necessary even if you intend to distribute all of commons, because
432 * the directory contents is used to work out which image description pages
435 * Also copies math images
438 function copyImages( $images ) {
439 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
440 # Find shared uploads and copy them into the static directory
441 $sharedPathLength = strlen( $wgSharedUploadPath );
442 $mathPathLength = strlen( $wgMathPath );
443 foreach ( $images as $escapedImage => $dummy ) {
444 $image = urldecode( $escapedImage );
447 if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
448 # Reconstruct full filename
449 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
450 $sourceLoc = "$wgSharedUploadDirectory/$rel";
451 $staticLoc = "{$this->sharedStaticPath}/$rel";
452 #print "Copying $sourceLoc to $staticLoc\n";
453 # Copy to static directory
454 if ( !file_exists( $staticLoc ) ) {
455 wfMkdirParents( dirname( $staticLoc ), 0755 );
456 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
457 symlink( $sourceLoc, $staticLoc );
459 copy( $sourceLoc, $staticLoc );
463 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
464 # That was a thumbnail
465 # We will also copy the real image
466 $parts = explode( '/', $rel );
467 $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
468 $sourceLoc = "$wgSharedUploadDirectory/$rel";
469 $staticLoc = "{$this->sharedStaticPath}/$rel";
470 #print "Copying $sourceLoc to $staticLoc\n";
471 if ( !file_exists( $staticLoc ) ) {
472 wfMkdirParents( dirname( $staticLoc ), 0755 );
473 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
474 symlink( $sourceLoc, $staticLoc );
476 copy( $sourceLoc, $staticLoc );
482 if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
483 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
484 $source = "$wgMathDirectory/$rel";
485 $dest = "{$this->dest}/math/$rel";
486 @mkdir( "{$this->dest}/math", 0755 );
487 if ( !file_exists( $dest ) ) {
488 copy( $source, $dest );
494 function onGetFullURL( &$title, &$url, $query ) {
495 global $wgContLang, $wgArticlePath;
497 $iw = $title->getInterwiki();
498 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
499 if ( $title->getDBkey() == '' ) {
500 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
502 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
511 function onGetLocalURL( &$title, &$url, $query ) {
512 global $wgArticlePath;
514 if ( $title->isExternal() ) {
515 # Default is fine for interwiki
520 if ( $query != '' ) {
521 parse_str( $query, $params );
522 if ( isset($params['action']) && $params['action'] == 'raw' ) {
523 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
524 $file = 'gen.' . $params['gen'];
526 $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
527 // Clean up Monobook.css etc.
528 if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
529 $file = $matches[1] . '.' . $matches[2];
532 $this->rawPages[$file] = array( $file, $title, $params );
533 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
536 if ( $url === false ) {
537 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
543 function getHashedFilename( &$title ) {
544 if ( '' != $title->mInterwiki ) {
545 $dbkey = $title->getDBkey();
547 $dbkey = $title->getPrefixedDBkey();
550 $mainPage = Title::newMainPage();
551 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
555 return $this->getHashedDirectory( $title ) . '/' .
556 $this->getFriendlyName( $dbkey ) . '.html';
559 function getFriendlyName( $name ) {
561 # Replace illegal characters for Windows paths with underscores
562 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
564 # Work out lower case form. We assume we're on a system with case-insensitive
565 # filenames, so unless the case is of a special form, we have to disambiguate
566 if ( function_exists( 'mb_strtolower' ) ) {
567 $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
569 $lowerCase = ucfirst( strtolower( $name ) );
572 # Make it mostly unique
573 if ( $lowerCase != $friendlyName ) {
574 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
576 # Handle colon specially by replacing it with tilde
577 # Thus we reduce the number of paths with hashes appended
578 $friendlyName = str_replace( ':', '~', $friendlyName );
580 return $friendlyName;
584 * Get a relative directory for putting a title into
586 function getHashedDirectory( &$title ) {
587 if ( '' != $title->getInterwiki() ) {
588 $pdbk = $title->getDBkey();
590 $pdbk = $title->getPrefixedDBkey();
593 # Find the first colon if there is one, use characters after it
594 $p = strpos( $pdbk, ':' );
595 if ( $p !== false ) {
596 $dbk = substr( $pdbk, $p + 1 );
597 $dbk = substr( $dbk, strspn( $dbk, '_' ) );
602 # Split into characters
603 preg_match_all( '/./us', $dbk, $m );
606 $length = count( $chars );
609 for ( $i = 0; $i < $this->depth; $i++ ) {
613 if ( $i >= $length ) {
617 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
618 if ( function_exists( 'mb_strtolower' ) ) {
619 $dir .= mb_strtolower( $c );
621 $dir .= strtolower( $c );
624 $dir .= sprintf( "%02X", ord( $c ) );
633 /** XML parser callback */
634 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
635 global $wgDumpImages;
637 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
638 $wgDumpImages[$attribs['SRC']] = true;
642 /** XML parser callback */
643 function wfDumpEndTagHandler( $parser, $name ) {}