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 ) {
223 global $wgTitle, $wgSharedUploadPath, $wgSharedUploadDirectory;
224 global $wgUploadDirectory;
226 $this->rawPages = array();
227 $text = $this->getArticleHTML( $title );
229 if ( $text === false ) {
233 # Parse the XHTML to find the images
234 $images = $this->findImages( $text );
235 $this->copyImages( $images );
238 $this->writeArticle( $title, $text );
241 wfMkdirParents( "{$this->dest}/raw", 0755 );
242 foreach( $this->rawPages as $record ) {
243 list( $file, $title, $params ) = $record;
245 $path = "{$this->dest}/raw/$file";
246 if ( !file_exists( $path ) ) {
247 $article = new Article( $title );
248 $request = new FauxRequest( $params );
249 $rp = new RawPage( $article, $request );
250 $text = $rp->getRawText();
252 print "Writing $file\n";
253 $file = fopen( $path, 'w' );
255 print("Can't open file $fullName for writing\n");
258 fwrite( $file, $text );
264 /** Write the given text to the file identified by the given title object */
265 function writeArticle( &$title, $text ) {
266 $filename = $this->getHashedFilename( $title );
267 $fullName = "{$this->dest}/$filename";
268 $fullDir = dirname( $fullName );
270 wfMkdirParents( $fullDir, 0755 );
272 $file = fopen( $fullName, 'w' );
274 print("Can't open file $fullName for writing\n");
278 fwrite( $file, $text );
282 /** Set up globals required for parsing */
283 function setupGlobals( $depth = NULL ) {
284 global $wgUser, $wgTitle, $wgMakeDumpLinks, $wgStylePath, $wgArticlePath;
285 global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
286 global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
287 global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
288 global $wgRightsUrl, $wgRightsText, $wgCopyrightIcon;
290 static $oldLogo = NULL;
292 if ( !$this->setupDone ) {
293 $wgHooks['GetLocalURL'][] =& $this;
294 $wgHooks['GetFullURL'][] =& $this;
295 $this->oldArticlePath = $wgServer . $wgArticlePath;
298 if ( is_null( $depth ) ) {
299 $wgMakeDumpLinks = $this->depth;
301 $wgMakeDumpLinks = $depth;
304 if ( $this->alternateScriptPath ) {
305 if ( $wgMakeDumpLinks == 0 ) {
308 $wgScriptPath = '..' . str_repeat( '/..', $wgMakeDumpLinks - 1 );
311 $wgScriptPath = '..' . str_repeat( '/..', $wgMakeDumpLinks );
314 $wgArticlePath = str_repeat( '../', $wgMakeDumpLinks ) . '$1';
317 # Allow for repeated setup
318 if ( !is_null( $oldLogo ) ) {
324 if ( strpos( $wgLogo, $wgUploadPath ) === 0 ) {
325 # If it's in the upload directory, rewrite it to the new upload directory
326 $wgLogo = "$wgScriptPath/{$this->imageRel}/" . substr( $wgLogo, strlen( $wgUploadPath ) + 1 );
327 } elseif ( $wgLogo{0} == '/' ) {
328 # This is basically heuristic
329 # Rewrite an absolute logo path to one relative to the the script path
330 $wgLogo = $wgScriptPath . $wgLogo;
334 $wgCopyrightIcon = str_replace( 'src="/images',
335 'src="' . htmlspecialchars( $wgScriptPath ) . '/images', $wgCopyrightIcon );
339 $wgStylePath = "$wgScriptPath/skins";
340 $wgUploadPath = "$wgScriptPath/{$this->imageRel}";
341 $wgSharedUploadPath = "$wgUploadPath/shared";
343 $wgHideInterlangageLinks = !$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', 'htmldump' );
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, $wgUseCategoryMagic, $wgLinkCache;
366 if ( is_null( $wgTitle ) ) {
370 $ns = $wgTitle->getNamespace();
371 if ( $ns == NS_SPECIAL ) {
372 SpecialPage::executePath( $wgTitle );
374 if ( $ns == NS_IMAGE ) {
375 $wgArticle = new ImagePage( $wgTitle );
376 } elseif ( $wgUseCategoryMagic && $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 );
545 function getHashedFilename( &$title ) {
546 if ( '' != $title->mInterwiki ) {
547 $dbkey = $title->getDBkey();
549 $dbkey = $title->getPrefixedDBkey();
552 $mainPage = Title::newMainPage();
553 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
557 return $this->getHashedDirectory( $title ) . '/' .
558 $this->getFriendlyName( $dbkey ) . '.html';
561 function getFriendlyName( $name ) {
563 # Replace illegal characters for Windows paths with underscores
564 $friendlyName = strtr( $name, '/\\*?"<>|~', '_________' );
566 # Work out lower case form. We assume we're on a system with case-insensitive
567 # filenames, so unless the case is of a special form, we have to disambiguate
568 if ( function_exists( 'mb_strtolower' ) ) {
569 $lowerCase = $wgLang->ucfirst( mb_strtolower( $name ) );
571 $lowerCase = ucfirst( strtolower( $name ) );
574 # Make it mostly unique
575 if ( $lowerCase != $friendlyName ) {
576 $friendlyName .= '_' . substr(md5( $name ), 0, 4);
578 # Handle colon specially by replacing it with tilde
579 # Thus we reduce the number of paths with hashes appended
580 $friendlyName = str_replace( ':', '~', $friendlyName );
582 return $friendlyName;
586 * Get a relative directory for putting a title into
588 function getHashedDirectory( &$title ) {
589 if ( '' != $title->getInterwiki() ) {
590 $pdbk = $title->getDBkey();
592 $pdbk = $title->getPrefixedDBkey();
595 # Find the first colon if there is one, use characters after it
596 $p = strpos( $pdbk, ':' );
597 if ( $p !== false ) {
598 $dbk = substr( $pdbk, $p + 1 );
599 $dbk = substr( $dbk, strspn( $dbk, '_' ) );
604 # Split into characters
605 preg_match_all( '/./us', $dbk, $m );
608 $length = count( $chars );
611 for ( $i = 0; $i < $this->depth; $i++ ) {
615 if ( $i >= $length ) {
619 if ( ord( $c ) >= 128 || preg_match( '/[a-zA-Z0-9!#$%&()+,[\]^_`{}-]/', $c ) ) {
620 if ( function_exists( 'mb_strtolower' ) ) {
621 $dir .= mb_strtolower( $c );
623 $dir .= strtolower( $c );
626 $dir .= sprintf( "%02X", ord( $c ) );
635 /** XML parser callback */
636 function wfDumpStartTagHandler( $parser, $name, $attribs ) {
637 global $wgDumpImages;
639 if ( $name == 'IMG' && isset( $attribs['SRC'] ) ) {
640 $wgDumpImages[$attribs['SRC']] = true;
644 /** XML parser callback */
645 function wfDumpEndTagHandler( $parser, $name ) {}