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() {
99 global $wgMakeDumpLinks;
101 print "Making index.html ";
103 // Set up globals with no ../../.. in the link URLs
104 $this->setupGlobals( 0 );
106 // But still use that directory style
107 $wgMakeDumpLinks = 3;
109 $title = Title::newMainPage();
110 $text = $this->getArticleHTML( $title );
111 $file = fopen( "{$this->dest}/index.html", "w" );
113 print "\nCan't open index.html for writing\n";
116 fwrite( $file, $text );
121 function doImageDescriptions() {
122 global $wgSharedUploadDirectory;
124 $fname = 'DumpHTML::doImageDescriptions';
126 $this->setupGlobals( 3 );
129 * Dump image description pages that don't have an associated article, but do
132 $dbr =& wfGetDB( DB_SLAVE );
133 extract( $dbr->tableNames( 'image', 'page' ) );
134 $res = $dbr->select( 'image', array( 'img_name' ), false, $fname );
137 print "Writing image description pages for local images\n";
138 $num = $dbr->numRows( $res );
139 while ( $row = $dbr->fetchObject( $res ) ) {
140 wfWaitForSlaves( 10 );
141 if ( !( ++$i % REPORTING_INTERVAL ) ) {
142 print "Done $i of $num\r";
144 $title = Title::makeTitle( NS_IMAGE, $row->img_name );
145 if ( $title->getArticleID() ) {
146 // Already done by dumpHTML
149 $this->doArticle( $title );
154 * Dump images which only have a real description page on commons
156 print "Writing description pages for commons images\n";
158 for ( $hash = 0; $hash < 256; $hash++ ) {
159 $dir = sprintf( "%01x/%02x", intval( $hash / 16 ), $hash );
160 $paths = array_merge( glob( "{$this->sharedStaticPath}/$dir/*" ),
161 glob( "{$this->sharedStaticPath}/thumb/$dir/*" ) );
163 foreach ( $paths as $path ) {
164 $file = basename( $path );
165 if ( !(++$i % REPORTING_INTERVAL ) ) {
169 $title = Title::makeTitle( NS_IMAGE, $file );
170 $this->doArticle( $title );
176 function doCategories() {
177 $fname = 'DumpHTML::doCategories';
178 $this->setupGlobals();
180 $dbr =& wfGetDB( DB_SLAVE );
181 $categorylinks = $dbr->tableName( 'categorylinks' );
182 print "Selecting categories...";
183 $sql = 'SELECT DISTINCT cl_to FROM categorylinks';
184 $res = $dbr->query( $sql, $fname );
186 print "\nWriting " . $dbr->numRows( $res ). " category pages\n";
188 while ( $row = $dbr->fetchObject( $res ) ) {
189 wfWaitForSlaves( 10 );
190 if ( !(++$i % REPORTING_INTERVAL ) ) {
193 $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
194 $this->doArticle( $title );
199 function doRedirects() {
202 print "Doing redirects...\n";
203 $fname = 'DumpHTML::doRedirects';
204 $this->setupGlobals();
205 $dbr =& wfGetDB( DB_SLAVE );
207 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
208 array( 'page_is_redirect' => 1 ), $fname );
209 $num = $dbr->numRows( $res );
210 print "$num redirects to do...\n";
212 while ( $row = $dbr->fetchObject( $res ) ) {
213 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
214 if ( !(++$i % (REPORTING_INTERVAL*10) ) ) {
215 print "Done $i of $num\n";
217 $this->doArticle( $title );
221 /** Write an article specified by title */
222 function doArticle( $title ) {
224 if ( $title->getNamespace() == 8 ) {
228 global $wgTitle, $wgSharedUploadPath, $wgSharedUploadDirectory;
229 global $wgUploadDirectory;
231 $this->rawPages = array();
232 $text = $this->getArticleHTML( $title );
234 if ( $text === false ) {
238 # Parse the XHTML to find the images
239 $images = $this->findImages( $text );
240 $this->copyImages( $images );
243 $this->writeArticle( $title, $text );
246 wfMkdirParents( "{$this->dest}/raw", 0755 );
247 foreach( $this->rawPages as $record ) {
248 list( $file, $title, $params ) = $record;
250 $path = "{$this->dest}/raw/$file";
251 if ( !file_exists( $path ) ) {
252 $article = new Article( $title );
253 $request = new FauxRequest( $params );
254 $rp = new RawPage( $article, $request );
255 $text = $rp->getRawText();
257 print "Writing $file\n";
258 $file = fopen( $path, 'w' );
260 print("Can't open file $fullName for writing\n");
263 fwrite( $file, $text );
269 /** Write the given text to the file identified by the given title object */
270 function writeArticle( &$title, $text ) {
271 $filename = $this->getHashedFilename( $title );
272 $fullName = "{$this->dest}/$filename";
273 $fullDir = dirname( $fullName );
275 wfMkdirParents( $fullDir, 0755 );
277 $file = fopen( $fullName, 'w' );
279 print("Can't open file $fullName for writing\n");
283 fwrite( $file, $text );
287 /** Set up globals required for parsing */
288 function setupGlobals( $depth = NULL ) {
289 global $wgUser, $wgTitle, $wgMakeDumpLinks, $wgStylePath, $wgArticlePath;
290 global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
291 global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
292 global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
293 global $wgRightsUrl, $wgRightsText;
295 static $oldLogo = NULL;
297 if ( !$this->setupDone ) {
298 $wgHooks['GetLocalURL'][] =& $this;
299 $wgHooks['GetFullURL'][] =& $this;
300 $this->oldArticlePath = $wgServer . $wgArticlePath;
303 if ( is_null( $depth ) ) {
304 $wgMakeDumpLinks = $this->depth;
306 $wgMakeDumpLinks = $depth;
309 if ( $this->alternateScriptPath ) {
310 if ( $wgMakeDumpLinks == 0 ) {
313 $wgScriptPath = '..' . str_repeat( '/..', $wgMakeDumpLinks - 1 );
316 $wgScriptPath = '..' . str_repeat( '/..', $wgMakeDumpLinks );
319 $wgArticlePath = str_repeat( '../', $wgMakeDumpLinks ) . '$1';
322 # Allow for repeated setup
323 if ( !is_null( $oldLogo ) ) {
329 if ( strpos( $wgLogo, $wgUploadPath ) === 0 ) {
330 # If it's in the upload directory, rewrite it to the new upload directory
331 $wgLogo = "$wgScriptPath/{$this->imageRel}/" . substr( $wgLogo, strlen( $wgUploadPath ) + 1 );
332 } elseif ( $wgLogo{0} == '/' ) {
333 # This is basically heuristic
334 # Rewrite an absolute logo path to one relative to the the script path
335 $wgLogo = $wgScriptPath . $wgLogo;
338 $wgStylePath = "$wgScriptPath/skins";
339 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
340 $wgSharedUploadPath = "$wgUploadPath/shared";
342 $wgHideInterlangageLinks = !$this->interwiki;
343 $wgThumbnailScriptPath = $wgSharedThumbnailScriptPath = false;
344 $wgEnableParserCache = false;
345 $wgMathPath = "$wgScriptPath/math";
347 if ( !empty( $wgRightsText ) ) {
348 $wgRightsUrl = "$wgScriptPath/COPYING.html";
352 $wgUser->setOption( 'skin', 'htmldump' );
353 $wgUser->setOption( 'editsection', 0 );
355 $this->sharedStaticPath = "$wgUploadDirectory/shared";
357 $this->setupDone = true;
360 /** Reads the content of a title object, executes the skin and captures the result */
361 function getArticleHTML( &$title ) {
362 global $wgOut, $wgTitle, $wgArticle, $wgUser, $wgUseCategoryMagic, $wgLinkCache;
365 if ( is_null( $wgTitle ) ) {
369 $ns = $wgTitle->getNamespace();
370 if ( $ns == NS_SPECIAL ) {
371 SpecialPage::executePath( $wgTitle );
373 if ( $ns == NS_IMAGE ) {
374 $wgArticle = new ImagePage( $wgTitle );
375 } elseif ( $wgUseCategoryMagic && $ns == NS_CATEGORY ) {
376 $wgArticle = new CategoryPage( $wgTitle );
378 $wgArticle = new Article( $wgTitle );
380 $rt = Title::newFromRedirect( $wgArticle->fetchContent() );
382 return $this->getRedirect( $rt );
384 $wgOut = new OutputPage;
385 $wgOut->setParserOptions( new ParserOptions );
386 $wgLinkCache = new LinkCache;
392 $sk =& $wgUser->getSkin();
394 $sk->outputPage( $wgOut );
395 $text = ob_get_contents();
401 function getRedirect( $rt ) {
402 $url = $rt->escapeLocalURL();
403 $text = $rt->getPrefixedText();
405 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
406 <html xmlns="http://www.w3.org/1999/xhtml">
408 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
409 <meta http-equiv="Refresh" content="0;url=$url" />
412 <p>Redirecting to <a href="$url">$text</a></p>
418 /** Returns image paths used in an XHTML document */
419 function findImages( $text ) {
420 global $wgOutputEncoding, $wgDumpImages;
421 $parser = xml_parser_create( $wgOutputEncoding );
422 xml_set_element_handler( $parser, 'wfDumpStartTagHandler', 'wfDumpEndTagHandler' );
424 $wgDumpImages = array();
425 xml_parse( $parser, $text );
426 xml_parser_free( $parser );
428 return $wgDumpImages;
432 * Copy images (or create symlinks) from commons to a static directory.
433 * This is necessary even if you intend to distribute all of commons, because
434 * the directory contents is used to work out which image description pages
437 * Also copies math images
440 function copyImages( $images ) {
441 global $wgSharedUploadPath, $wgSharedUploadDirectory, $wgMathPath, $wgMathDirectory;
442 # Find shared uploads and copy them into the static directory
443 $sharedPathLength = strlen( $wgSharedUploadPath );
444 $mathPathLength = strlen( $wgMathPath );
445 foreach ( $images as $escapedImage => $dummy ) {
446 $image = urldecode( $escapedImage );
449 if ( substr( $image, 0, $sharedPathLength ) == $wgSharedUploadPath ) {
450 # Reconstruct full filename
451 $rel = substr( $image, $sharedPathLength + 1 ); // +1 for slash
452 $sourceLoc = "$wgSharedUploadDirectory/$rel";
453 $staticLoc = "{$this->sharedStaticPath}/$rel";
454 #print "Copying $sourceLoc to $staticLoc\n";
455 # Copy to static directory
456 if ( !file_exists( $staticLoc ) ) {
457 wfMkdirParents( dirname( $staticLoc ), 0755 );
458 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
459 symlink( $sourceLoc, $staticLoc );
461 copy( $sourceLoc, $staticLoc );
465 if ( substr( $rel, 0, 6 ) == 'thumb/' ) {
466 # That was a thumbnail
467 # We will also copy the real image
468 $parts = explode( '/', $rel );
469 $rel = "{$parts[1]}/{$parts[2]}/{$parts[3]}";
470 $sourceLoc = "$wgSharedUploadDirectory/$rel";
471 $staticLoc = "{$this->sharedStaticPath}/$rel";
472 #print "Copying $sourceLoc to $staticLoc\n";
473 if ( !file_exists( $staticLoc ) ) {
474 wfMkdirParents( dirname( $staticLoc ), 0755 );
475 if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
476 symlink( $sourceLoc, $staticLoc );
478 copy( $sourceLoc, $staticLoc );
484 if ( substr( $image, 0, $mathPathLength ) == $wgMathPath ) {
485 $rel = substr( $image, $mathPathLength + 1 ); // +1 for slash
486 $source = "$wgMathDirectory/$rel";
487 $dest = "{$this->dest}/math/$rel";
488 @mkdir( "{$this->dest}/math", 0755 );
489 if ( !file_exists( $dest ) ) {
490 copy( $source, $dest );
496 function onGetFullURL( &$title, &$url, $query ) {
497 global $wgContLang, $wgArticlePath;
499 $iw = $title->getInterwiki();
500 if ( $title->isExternal() && $wgContLang->getLanguageName( $iw ) ) {
501 if ( $title->getDBkey() == '' ) {
502 $url = str_replace( '$1', "../$iw/index.html", $wgArticlePath );
504 $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
513 function onGetLocalURL( &$title, &$url, $query ) {
514 global $wgArticlePath;
516 if ( $title->isExternal() ) {
517 # Default is fine for interwiki
522 if ( $query != '' ) {
523 parse_str( $query, $params );
524 if ( isset($params['action']) && $params['action'] == 'raw' ) {
525 if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
526 $file = 'gen.' . $params['gen'];
528 $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
529 // Clean up Monobook.css etc.
530 if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
531 $file = $matches[1] . '.' . $matches[2];
534 $this->rawPages[$file] = array( $file, $title, $params );
535 $url = str_replace( '$1', "raw/" . wfUrlencode( $file ), $wgArticlePath );
538 if ( $url === false ) {
539 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
544 function getHashedFilename( &$title ) {
545 if ( '' != $title->mInterwiki ) {
546 $dbkey = $title->getDBkey();
548 $dbkey = $title->getPrefixedDBkey();
551 $mainPage = Title::newMainPage();
552 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
556 return $this->getHashedDirectory( $title ) . '/' .
557 $this->getFriendlyName( $dbkey ) . '.html';
560 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 $lowerCase = ucfirst( strtolower( $name ) );
568 # Make it mostly unique
569 if ( $lowerCase != $friendlyName ) {
570 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
572 # Handle colon specially by replacing it with tilde
573 # Thus we reduce the number of paths with hashes appended
574 $friendlyName = str_replace( ':', '~', $friendlyName );
576 return $friendlyName;
580 * Get a relative directory for putting a title into
582 function getHashedDirectory( &$title ) {
583 if ( '' != $title->getInterwiki() ) {
584 $pdbk = $title->getDBkey();
586 $pdbk = $title->getPrefixedDBkey();
589 # Find the first colon if there is one, use characters after it
590 $p = strpos( $pdbk, ':' );
591 if ( $p !== false ) {
592 $dbk = substr( $pdbk, $p + 1 );
593 $dbk = substr( $dbk, strspn( $dbk, '_' ) );
598 # Split into characters
599 preg_match_all( '/./us', $dbk, $m );
602 $length = count( $chars );
605 for ( $i = 0; $i < $this->depth; $i++ ) {
609 if ( $i >= $length ) {
613 if ( ord( $c ) >= 128 || ctype_alnum( $c ) ) {
614 if ( function_exists( 'mb_strtolower' ) ) {
615 $dir .= mb_strtolower( $c );
617 $dir .= strtolower( $c );
620 $dir .= sprintf( "%02X", ord( $c ) );
629 /** XML parser callback */
630 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
631 global $wgDumpImages;
633 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
634 $wgDumpImages[$attribs['SRC']] = true;
638 /** XML parser callback */
639 function wfDumpEndTagHandler( $parser, $name ) {}