Remove annoying `s from the definition of the protected_titles table.
[lhc/web/wiklou.git] / maintenance / dumpHTML.inc
index e0ef494..18f5a9d 100644 (file)
@@ -1,7 +1,6 @@
 <?php
 /**
- * @package MediaWiki
- * @subpackage Maintenance
+ * @addtogroup Maintenance
  */
 
 define( 'REPORTING_INTERVAL', 10 );
@@ -10,10 +9,17 @@ require_once( 'includes/ImagePage.php' );
 require_once( 'includes/CategoryPage.php' );
 require_once( 'includes/RawPage.php' );
 
+# Explicitly disable article view counter (bug 6823)
+global $wgDisableCounters;
+$wgDisableCounters = true;
+
 class DumpHTML {
        # Destination directory
        var $dest;
 
+       # Skip existing files
+       var $noOverwrite = false;
+
        # Show interlanguage links?
        var $interwiki = true;
 
@@ -35,6 +41,9 @@ class DumpHTML {
        # Make a copy of all images encountered
        var $makeSnapshot = false;
 
+       # Don't image description pages in doEverything()
+       var $noSharedDesc = false;
+
        # Make links assuming the script path is in the same directory as
        # the destination
        var $alternateScriptPath = false;
@@ -45,6 +54,9 @@ class DumpHTML {
        # Has setupGlobals been called?
        var $setupDone = false;
 
+       # Has to compress html pages
+       var $compress = false;
+
        # List of raw pages used in the current article
        var $rawPages;
 
@@ -58,6 +70,12 @@ class DumpHTML {
 
        var $sliceNumerator = 1, $sliceDenominator = 1;
 
+       # Max page ID, lazy initialised
+       var $maxPageID = false;
+
+       # UDP profiling
+       var $udpProfile, $udpProfileCounter = 0, $udpProfileInit = false;
+
        function DumpHTML( $settings = array() ) {
                foreach ( $settings as $var => $value ) {
                        $this->$var = $value;
@@ -115,13 +133,16 @@ class DumpHTML {
                        return;
                }
                $this->doArticles();
-               $this->doLocalImageDescriptions();
-               $this->doSharedImageDescriptions();
                $this->doCategories();
                $this->doRedirects();
                if ( $this->sliceNumerator == 1 ) {
                        $this->doSpecials();
                }
+               $this->doLocalImageDescriptions();
+
+               if ( !$this->noSharedDesc ) {
+                       $this->doSharedImageDescriptions();
+               }
 
                $this->setCheckpoint( 'everything', 'done' );
        }
@@ -131,16 +152,13 @@ class DumpHTML {
         * Skip categories and images, they will be done separately
         */
        function doArticles() {
-               $fname = 'DumpHTML::doArticles';
-
                if ( $this->endID === false ) {
-                       $dbr =& wfGetDB( DB_SLAVE );
-                       $this->endID = $dbr->selectField( 'page', 'max(page_id)', false, $fname );
+                       $end = $this->getMaxPageID();
+               } else {
+                       $end = $this->endID;
                }
+               $start = $this->startID;
                
-               # Slice the range
-               list( $start, $end ) = $this->sliceRange( $this->startID, $this->endID );
-
                # Start from the checkpoint
                $cp = $this->getCheckpoint( 'article' );
                if ( $cp == 'done' ) {
@@ -153,24 +171,28 @@ class DumpHTML {
                        print "Starting from page_id $start of $end\n";
                }
 
+               # Move the start point to the correct slice if it isn't there already
+               $start = $this->modSliceStart( $start );
+
                $this->setupGlobals();
 
                $mainPageObj = Title::newMainPage();
                $mainPage = $mainPageObj->getPrefixedDBkey();
 
-               for ($id = $start; $id <= $end; $id++) {
+               for ( $id = $start, $i = 0; $id <= $end; $id += $this->sliceDenominator, $i++ ) {
                        wfWaitForSlaves( 20 );
-                       if ( !($id % REPORTING_INTERVAL) ) {
+                       if ( !( $i % REPORTING_INTERVAL) ) {
                                print "Processing ID: $id\r";
                                $this->setCheckpoint( 'article', $id );
                        }
-                       if ( !($id % (REPORTING_INTERVAL*10) ) ) {
+                       if ( !($i % (REPORTING_INTERVAL*10) ) ) {
                                print "\n";
                        }
                        $title = Title::newFromID( $id );
                        if ( $title ) {
                                $ns = $title->getNamespace() ;
-                               if ( $ns != NS_CATEGORY && $title->getPrefixedDBkey() != $mainPage ) {
+                               if ( $ns != NS_CATEGORY && $ns != NS_MEDIAWIKI && 
+                                 $title->getPrefixedDBkey() != $mainPage ) {
                                        $this->doArticle( $title );
                                }
                        }
@@ -184,7 +206,7 @@ class DumpHTML {
 
                $this->setupGlobals();
                print "Special:Categories...";
-               $this->doArticle( Title::makeTitle( NS_SPECIAL, 'Categories' ) );
+               $this->doArticle( SpecialPage::getTitleFor( 'Categories' ) );
                print "\n";
        }
 
@@ -215,7 +237,9 @@ class DumpHTML {
 
        function doImageDescriptions() {
                $this->doLocalImageDescriptions();
-               $this->doSharedImageDescriptions();
+               if ( !$this->noSharedDesc ) {
+                       $this->doSharedImageDescriptions();
+               }
        }
 
        /**
@@ -223,9 +247,9 @@ class DumpHTML {
         * have a local image
         */
        function doLocalImageDescriptions() {
-               global $wgSharedUploadDirectory;
+               $chunkSize = 1000;
 
-               $dbr =& wfGetDB( DB_SLAVE );
+               $dbr = wfGetDB( DB_SLAVE );
                
                $cp = $this->getCheckpoint( 'local image' );
                if ( $cp == 'done' ) {
@@ -240,32 +264,39 @@ class DumpHTML {
                }
 
                $this->setupGlobals();
-
-               $res = $dbr->select( 'image', array( 'img_name' ), $conds, __METHOD__, 
-                       array( 'ORDER BY' => 'img_name' ) );
-
                $i = 0;
-               $num = $dbr->numRows( $res );
-               while ( $row = $dbr->fetchObject( $res ) ) {
-                       // Slice the result set with a filter
-                       if ( !$this->sliceFilter( $row->img_name ) ) {
-                               continue;
-                       }
 
-                       wfWaitForSlaves( 10 );
-                       if ( !( ++$i % REPORTING_INTERVAL ) ) {
-                               print "Done $i of $num\r";
-                               if ( $row->img_name !== 'done' ) {
-                                       $this->setCheckpoint( 'local image', $row->img_name );
+               do {
+                       $res = $dbr->select( 'image', array( 'img_name' ), $conds, __METHOD__, 
+                               array( 'ORDER BY' => 'img_name', 'LIMIT' => $chunkSize ) );
+                       $numRows = $dbr->numRows( $res );
+
+                       while ( $row = $dbr->fetchObject( $res ) ) {
+                               # Update conds for the next chunk query
+                               $conds = array( 'img_name > ' . $dbr->addQuotes( $row->img_name ) );
+                               
+                               // Slice the result set with a filter
+                               if ( !$this->sliceFilter( $row->img_name ) ) {
+                                       continue;
                                }
+
+                               wfWaitForSlaves( 10 );
+                               if ( !( ++$i % REPORTING_INTERVAL ) ) {
+                                       print "{$row->img_name}\n";
+                                       if ( $row->img_name !== 'done' ) {
+                                               $this->setCheckpoint( 'local image', $row->img_name );
+                                       }
+                               }
+                               $title = Title::makeTitle( NS_IMAGE, $row->img_name );
+                               if ( $title->getArticleID() ) {
+                                       // Already done by dumpHTML
+                                       continue;
+                               }
+                               $this->doArticle( $title );
                        }
-                       $title = Title::makeTitle( NS_IMAGE, $row->img_name );
-                       if ( $title->getArticleID() ) {
-                               // Already done by dumpHTML
-                               continue;
-                       }
-                       $this->doArticle( $title );
-               }
+                       $dbr->freeResult( $res );
+               } while ( $numRows );
+               
                $this->setCheckpoint( 'local image', 'done' );
                print "\n";
        }
@@ -287,80 +318,88 @@ class DumpHTML {
                        print "Writing description pages for commons images\n";
                }
 
-
                $this->setupGlobals();
                $i = 0;
                for ( $hash = $start; $hash <= $end; $hash++ ) {
                        $this->setCheckpoint( 'shared image', $hash );
 
-                       $dir = sprintf( "%01x/%02x", intval( $hash / 16 ), $hash );
-                       $paths = array_merge( glob( "{$this->sharedStaticDirectory}/$dir/*" ),
-                               glob( "{$this->sharedStaticDirectory}/thumb/$dir/*" ) );
-
-                       foreach ( $paths as $path ) {
-                               $file = basename( $path );
+                       $dir = sprintf( "%s/%01x/%02x", $this->sharedStaticDirectory,
+                               intval( $hash / 16 ), $hash );
+                       $handle = @opendir( $dir );
+                       while ( $handle && $file = readdir( $handle ) ) {
+                               if ( $file[0] == '.' ) {
+                                       continue;
+                               }
                                if ( !(++$i % REPORTING_INTERVAL ) ) {
                                        print "$i\r";
                                }
 
-                               $title = Title::makeTitle( NS_IMAGE, $file );
+                               $title = Title::makeTitleSafe( NS_IMAGE, $file );
                                $this->doArticle( $title );
                        }
+                       if ( $handle ) {
+                               closedir( $handle );
+                       }
                }
                $this->setCheckpoint( 'shared image', 'done' );
                print "\n";
        }
 
        function doCategories() {
-               $fname = 'DumpHTML::doCategories';
+               $chunkSize = 1000;
+               
                $this->setupGlobals();
-               $dbr =& wfGetDB( DB_SLAVE );
-               $sql = 'SELECT DISTINCT cl_to FROM ' . $dbr->tableName( 'categorylinks' );
-
+               $dbr = wfGetDB( DB_SLAVE );
+               
                $cp = $this->getCheckpoint( 'category' );
                if ( $cp == 'done' ) {
                        print "Category pages already done\n";
                        return;
                } elseif ( $cp !== false ) {
                        print "Resuming category page dump from $cp\n";
-                       $sql .= ' WHERE cl_to >= ' . $dbr->addQuotes( $cp );
+                       $conds = array( 'cl_to >= ' . $dbr->addQuotes( $cp ) );
+               } else {
+                       print "Starting category pages\n";
+                       $conds = false;
                }
 
-               $sql .= ' ORDER BY cl_to';
-               print "Selecting categories...";
-               $res = $dbr->query( $sql, $fname );
-
-               print "\nWriting " . $dbr->numRows( $res ).  " category pages\n";
                $i = 0;
-               while ( $row = $dbr->fetchObject( $res ) ) {
-                       // Filter pages from other slices
-                       if ( !$this->sliceFilter( $row->cl_to ) ) {
-                               continue;
-                       }
+               do {
+                       $res = $dbr->select( 'categorylinks', 'DISTINCT cl_to', $conds, __METHOD__, 
+                               array( 'ORDER BY' => 'cl_to', 'LIMIT' => $chunkSize ) );
+                       $numRows = $dbr->numRows( $res );
+                       
+                       while ( $row = $dbr->fetchObject( $res ) ) {
+                               // Set conditions for next chunk
+                               $conds = array( 'cl_to > ' . $dbr->addQuotes( $row->cl_to ) );
+                               
+                               // Filter pages from other slices
+                               if ( !$this->sliceFilter( $row->cl_to ) ) {
+                                       continue;
+                               }
 
-                       wfWaitForSlaves( 10 );
-                       if ( !(++$i % REPORTING_INTERVAL ) ) {
-                               print "{$row->cl_to}\n";
-                               if ( $row->cl_to != 'done' ) {
-                                       $this->setCheckpoint( 'category', $row->cl_to );
+                               wfWaitForSlaves( 10 );
+                               if ( !(++$i % REPORTING_INTERVAL ) ) {
+                                       print "{$row->cl_to}\n";
+                                       if ( $row->cl_to != 'done' ) {
+                                               $this->setCheckpoint( 'category', $row->cl_to );
+                                       }
                                }
+                               $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
+                               $this->doArticle( $title );
                        }
-                       $title = Title::makeTitle( NS_CATEGORY, $row->cl_to );
-                       $this->doArticle( $title );
-               }
+                       $dbr->freeResult( $res );
+               } while ( $numRows );
+               
                $this->setCheckpoint( 'category', 'done' );
                print "\n";
        }
 
        function doRedirects() {
                print "Doing redirects...\n";
-               $fname = 'DumpHTML::doRedirects';
-
-               
-               $dbr =& wfGetDB( DB_SLAVE );
-               $end = $dbr->selectField( 'page', 'max(page_id)', false, $fname );
-               list( $start, $end ) = $this->sliceRange( 1, $end );
 
+               $chunkSize = 10000;
+               $end = $this->getMaxPageID();
                $cp = $this->getCheckpoint( 'redirect' );
                if ( $cp == 'done' )  {
                        print "Redirects already done\n";
@@ -368,34 +407,52 @@ class DumpHTML {
                } elseif ( $cp !== false ) {
                        print "Resuming redirect generation from page_id $cp\n";
                        $start = intval( $cp );
+               } else {
+                       $start = 1;
                }
-               
-               $conds = array( 
-                       'page_is_redirect' => 1,
-                       "page_id BETWEEN $start AND $end"
-               );
 
                $this->setupGlobals();
-               $res = $dbr->select( 'page', array( 'page_id', 'page_namespace', 'page_title' ),
-                       $conds, $fname );
-               $num = $dbr->numRows( $res );
-               print "$num redirects to do...\n";
+               $dbr = wfGetDB( DB_SLAVE );
                $i = 0;
-               while ( $row = $dbr->fetchObject( $res ) ) {
-                       $title = Title::makeTitle( $row->page_namespace, $row->page_title );
-                       if ( !(++$i % (REPORTING_INTERVAL*10) ) ) {
-                               print "Done $i of $num (ID {$row->page_id})\n";
-                               $this->setCheckpoint( 'redirect', $row->page_id );
+
+               for ( $chunkStart = $start; $chunkStart <= $end; $chunkStart += $chunkSize ) {
+                       $chunkEnd = min( $end, $chunkStart + $chunkSize - 1 );
+                       $conds = array( 
+                               'page_is_redirect' => 1,
+                               "page_id BETWEEN $chunkStart AND $chunkEnd"
+                       );
+                       # Modulo slicing in SQL
+                       if ( $this->sliceDenominator != 1 ) {
+                               $n = intval( $this->sliceNumerator );
+                               $m = intval( $this->sliceDenominator );
+                               $conds[] = "page_id % $m = $n";
+                       }
+                       $res = $dbr->select( 'page', array( 'page_id', 'page_namespace', 'page_title' ),
+                               $conds, __METHOD__ );
+                       
+                       while ( $row = $dbr->fetchObject( $res ) ) {
+                               $title = Title::makeTitle( $row->page_namespace, $row->page_title );
+                               if ( !(++$i % (REPORTING_INTERVAL*10) ) ) {
+                                       printf( "Done %d redirects (%2.3f%%)\n", $i, $row->page_id / $end * 100 );
+                                       $this->setCheckpoint( 'redirect', $row->page_id );
+                               }
+                               $this->doArticle( $title );
                        }
-                       $this->doArticle( $title );
+                       $dbr->freeResult( $res );
                }
                $this->setCheckpoint( 'redirect', 'done' );
        }
 
        /** Write an article specified by title */
        function doArticle( $title ) {
-               global $wgTitle, $wgSharedUploadPath, $wgSharedUploadDirectory;
-               global $wgUploadDirectory;
+               if ( $this->noOverwrite ) {
+                       $fileName = $this->dest.'/'.$this->getHashedFilename( $title );
+                       if ( file_exists( $fileName ) ) {
+                               return;
+                       }
+               }
+
+               $this->profile();
 
                $this->rawPages = array();
                $text = $this->getArticleHTML( $title );
@@ -426,21 +483,41 @@ class DumpHTML {
                                print "Writing $file\n";
                                $file = fopen( $path, 'w' );
                                if ( !$file ) {
-                                       print("Can't open file $fullName for writing\n");
+                                       print("Can't open file $path for writing\n");
                                        continue;
                                }
                                fwrite( $file, $text );
                                fclose( $file );
                        }
                }
+
+               wfIncrStats( 'dumphtml_article' );
        }
 
        /** Write the given text to the file identified by the given title object */
-       function writeArticle( &$title, $text ) {
+       function writeArticle( $title, $text ) {
                $filename = $this->getHashedFilename( $title );
+
+               # Temporary hack for current dump, this should be moved to 
+               # getFriendlyName() at the earliest opportunity.
+               #
+               # Limit filename length to 255 characters, so it works on ext3.
+               # Titles are in fact limited to 255 characters, but dumpHTML 
+               # adds a suffix which may put them over the limit.
+               $length = strlen( $filename );
+               if ( $length > 255 ) {
+                       print "Warning: Filename too long ($length bytes). Skipping.\n";
+                       return;
+               }
+                       
                $fullName = "{$this->dest}/$filename";
                $fullDir = dirname( $fullName );
 
+               if ( $this->compress ) {
+                       $fullName .= ".gz";
+                       $text = gzencode( $text, 9 );                           
+               }
+
                wfMkdirParents( $fullDir, 0755 );
 
                wfSuppressWarnings();
@@ -458,7 +535,7 @@ class DumpHTML {
 
        /** Set up globals required for parsing */
        function setupGlobals( $currentDepth = NULL ) {
-               global $wgUser, $wgTitle, $wgStylePath, $wgArticlePath, $wgMathPath;
+               global $wgUser, $wgStylePath, $wgArticlePath, $wgMathPath;
                global $wgUploadPath, $wgLogo, $wgMaxCredits, $wgSharedUploadPath;
                global $wgHideInterlanguageLinks, $wgUploadDirectory, $wgThumbnailScriptPath;
                global $wgSharedThumbnailScriptPath, $wgEnableParserCache, $wgHooks, $wgServer;
@@ -534,20 +611,18 @@ class DumpHTML {
                $wgUser->setOption( 'skin', $this->skin );
                $wgUser->setOption( 'editsection', 0 );
 
-               if ( $this->makeSnapshot ) {
-                       $this->destUploadDirectory = "{$this->dest}/{$this->imageRel}";
-                       if ( realpath( $this->destUploadDirectory == $wgUploadDirectory ) ) {
-                               $this->makeSnapshot = false;
-                       }
+               $this->destUploadDirectory = "{$this->dest}/{$this->imageRel}";
+               if ( realpath( $this->destUploadDirectory ) == realpath( $wgUploadDirectory ) ) {
+                       print "Disabling image snapshot because the destination is the same as the source\n";
+                       $this->makeSnapshot = false;
                }
-
                $this->sharedStaticDirectory = "{$this->destUploadDirectory}/shared";
 
                $this->setupDone = true;
        }
 
        /** Reads the content of a title object, executes the skin and captures the result */
-       function getArticleHTML( &$title ) {
+       function getArticleHTML( $title ) {
                global $wgOut, $wgTitle, $wgArticle, $wgUser;
 
                $linkCache =& LinkCache::singleton();
@@ -582,6 +657,7 @@ class DumpHTML {
                        }
                }
 
+       
                $sk =& $wgUser->getSkin();
                ob_start();
                $sk->outputPage( $wgOut );
@@ -637,9 +713,13 @@ ENDTEXT;
                if ( !file_exists( $destLoc ) ) {
                        wfMkdirParents( dirname( $destLoc ), 0755 );
                        if ( function_exists( 'symlink' ) && !$this->forceCopy ) {
-                               symlink( $sourceLoc, $destLoc );
+                               if ( !symlink( $sourceLoc, $destLoc ) ) {
+                                       print "Warning: unable to create symlink at $destLoc\n";
+                               }
                        } else {
-                               copy( $sourceLoc, $destLoc );
+                               if ( !copy( $sourceLoc, $destLoc ) ) {
+                                       print "Warning: unable to copy $sourceLoc to $destLoc\n";
+                               }
                        }
                }
        }
@@ -702,6 +782,7 @@ ENDTEXT;
                                $url = str_replace( '$1', "../$iw/" . wfUrlencode( $this->getHashedFilename( $title ) ),
                                        $wgArticlePath );
                        }
+                       $url .= $this->compress ? ".gz" : "";
                        return false;
                } else {
                        return true;
@@ -718,6 +799,7 @@ ENDTEXT;
 
                $url = false;
                if ( $query != '' ) {
+                       $params = array();
                        parse_str( $query, $params );
                        if ( isset($params['action']) && $params['action'] == 'raw' ) {
                                if ( $params['gen'] == 'css' || $params['gen'] == 'js' ) {
@@ -725,6 +807,7 @@ ENDTEXT;
                                } else {
                                        $file = $this->getFriendlyName( $title->getPrefixedDBkey() );
                                        // Clean up Monobook.css etc.
+                                       $matches = array();
                                        if ( preg_match( '/^(.*)\.(css|js)_[0-9a-f]{4}$/', $file, $matches ) ) {
                                                $file = $matches[1] . '.' . $matches[2];
                                        }
@@ -736,7 +819,7 @@ ENDTEXT;
                if ( $url === false ) {
                        $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename( $title ) ), $wgArticlePath );
                }
-
+               $url .= $this->compress ? ".gz" : "";
                return false;
        }
 
@@ -800,6 +883,7 @@ ENDTEXT;
                }
 
                # Split into characters
+               $m = array();
                preg_match_all( '/./us', $dbk, $m );
 
                $chars = $m[0];
@@ -846,6 +930,15 @@ ENDTEXT;
                return array( $sliceStart, $sliceEnd );
        }
 
+       /**
+        * Adjust a start point so that it belongs to the current slice, where slices are defined by integer modulo
+        * @param integer $start
+        * @param integer $base The true start of the range; the minimum start
+        */
+       function modSliceStart( $start, $base = 1 ) {
+               return $start - ( $start % $this->sliceDenominator ) + $this->sliceNumerator - 1 + $base;
+       }
+
        /**
         * Determine whether a string belongs to the current slice, based on hash
         */
@@ -864,6 +957,41 @@ ENDTEXT;
                $text = '';
                return false;
        }
+
+       function getMaxPageID() {
+               if ( $this->maxPageID === false ) {
+                       $dbr = wfGetDB( DB_SLAVE );
+                       $this->maxPageID = $dbr->selectField( 'page', 'max(page_id)', false, __METHOD__ );
+               }
+               return $this->maxPageID;
+       }
+
+       function profile() {
+               global $wgProfiler;
+
+               if ( !$this->udpProfile ) {
+                       return;
+               }
+               if ( !$this->udpProfileInit ) {
+                       $this->udpProfileInit = true;
+               } elseif ( $this->udpProfileCounter == 1 % $this->udpProfile ) {
+                       $wgProfiler->getFunctionReport();
+                       $wgProfiler = new DumpHTML_ProfilerStub;
+               }
+               if ( $this->udpProfileCounter == 0 ) {
+                       $wgProfiler = new ProfilerSimpleUDP;
+                       $wgProfiler->setProfileID( 'dumpHTML' );
+               }
+               $this->udpProfileCounter = ( $this->udpProfileCounter + 1 ) % $this->udpProfile;
+       }
+}
+
+class DumpHTML_ProfilerStub {
+       function profileIn() {}
+       function profileOut() {}
+       function getOutput() {}
+       function close() {}
+       function getFunctionReport() {}
 }
 
 /** XML parser callback */