MediaWiki  REL1_23
backupTextPass.inc
Go to the documentation of this file.
00001 <?php
00027 require_once __DIR__ . '/backup.inc';
00028 
00032 class TextPassDumper extends BackupDumper {
00033     var $prefetch = null;
00034     var $input = "php://stdin";
00035     var $history = WikiExporter::FULL;
00036     var $fetchCount = 0;
00037     var $prefetchCount = 0;
00038     var $prefetchCountLast = 0;
00039     var $fetchCountLast = 0;
00040 
00041     var $maxFailures = 5;
00042     var $maxConsecutiveFailedTextRetrievals = 200;
00043     var $failureTimeout = 5; // Seconds to sleep after db failure
00044 
00045     var $php = "php";
00046     var $spawn = false;
00047 
00051     var $spawnProc = false;
00052 
00056     var $spawnWrite = false;
00057 
00061     var $spawnRead = false;
00062 
00066     var $spawnErr = false;
00067 
00068     var $xmlwriterobj = false;
00069 
00070     // when we spend more than maxTimeAllowed seconds on this run, we continue
00071     // processing until we write out the next complete page, then save output file(s),
00072     // rename it/them and open new one(s)
00073     var $maxTimeAllowed = 0;  // 0 = no limit
00074     var $timeExceeded = false;
00075     var $firstPageWritten = false;
00076     var $lastPageWritten = false;
00077     var $checkpointJustWritten = false;
00078     var $checkpointFiles = array();
00079 
00083     protected $db;
00084 
00096     function rotateDb() {
00097         // Cleaning up old connections
00098         if ( isset( $this->lb ) ) {
00099             $this->lb->closeAll();
00100             unset( $this->lb );
00101         }
00102 
00103         if ( $this->forcedDb !== null ) {
00104             $this->db = $this->forcedDb;
00105             return;
00106         }
00107 
00108         if ( isset( $this->db ) && $this->db->isOpen() ) {
00109             throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
00110         }
00111 
00112         unset( $this->db );
00113 
00114         // Trying to set up new connection.
00115         // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
00116         // individually retrying at different layers of code.
00117 
00118         // 1. The LoadBalancer.
00119         try {
00120             $this->lb = wfGetLBFactory()->newMainLB();
00121         } catch ( Exception $e ) {
00122             throw new MWException( __METHOD__ . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
00123         }
00124 
00125         // 2. The Connection, through the load balancer.
00126         try {
00127             $this->db = $this->lb->getConnection( DB_SLAVE, 'dump' );
00128         } catch ( Exception $e ) {
00129             throw new MWException( __METHOD__ . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
00130         }
00131     }
00132 
00133     function initProgress( $history = WikiExporter::FULL ) {
00134         parent::initProgress();
00135         $this->timeOfCheckpoint = $this->startTime;
00136     }
00137 
00138     function dump( $history, $text = WikiExporter::TEXT ) {
00139         // Notice messages will foul up your XML output even if they're
00140         // relatively harmless.
00141         if ( ini_get( 'display_errors' ) ) {
00142             ini_set( 'display_errors', 'stderr' );
00143         }
00144 
00145         $this->initProgress( $this->history );
00146 
00147         // We are trying to get an initial database connection to avoid that the
00148         // first try of this request's first call to getText fails. However, if
00149         // obtaining a good DB connection fails it's not a serious issue, as
00150         // getText does retry upon failure and can start without having a working
00151         // DB connection.
00152         try {
00153             $this->rotateDb();
00154         } catch ( Exception $e ) {
00155             // We do not even count this as failure. Just let eventual
00156             // watchdogs know.
00157             $this->progress( "Getting initial DB connection failed (" .
00158                 $e->getMessage() . ")" );
00159         }
00160 
00161         $this->egress = new ExportProgressFilter( $this->sink, $this );
00162 
00163         // it would be nice to do it in the constructor, oh well. need egress set
00164         $this->finalOptionCheck();
00165 
00166         // we only want this so we know how to close a stream :-P
00167         $this->xmlwriterobj = new XmlDumpWriter();
00168 
00169         $input = fopen( $this->input, "rt" );
00170         $this->readDump( $input );
00171 
00172         if ( $this->spawnProc ) {
00173             $this->closeSpawn();
00174         }
00175 
00176         $this->report( true );
00177     }
00178 
00179     function processOption( $opt, $val, $param ) {
00180         global $IP;
00181         $url = $this->processFileOpt( $val, $param );
00182 
00183         switch ( $opt ) {
00184         case 'prefetch':
00185             require_once "$IP/maintenance/backupPrefetch.inc";
00186             $this->prefetch = new BaseDump( $url );
00187             break;
00188         case 'stub':
00189             $this->input = $url;
00190             break;
00191         case 'maxtime':
00192             $this->maxTimeAllowed = intval( $val ) * 60;
00193             break;
00194         case 'checkpointfile':
00195             $this->checkpointFiles[] = $val;
00196             break;
00197         case 'current':
00198             $this->history = WikiExporter::CURRENT;
00199             break;
00200         case 'full':
00201             $this->history = WikiExporter::FULL;
00202             break;
00203         case 'spawn':
00204             $this->spawn = true;
00205             if ( $val ) {
00206                 $this->php = $val;
00207             }
00208             break;
00209         }
00210     }
00211 
00212     function processFileOpt( $val, $param ) {
00213         $fileURIs = explode( ';', $param );
00214         foreach ( $fileURIs as $URI ) {
00215             switch ( $val ) {
00216                 case "file":
00217                     $newURI = $URI;
00218                     break;
00219                 case "gzip":
00220                     $newURI = "compress.zlib://$URI";
00221                     break;
00222                 case "bzip2":
00223                     $newURI = "compress.bzip2://$URI";
00224                     break;
00225                 case "7zip":
00226                     $newURI = "mediawiki.compress.7z://$URI";
00227                     break;
00228                 default:
00229                     $newURI = $URI;
00230             }
00231             $newFileURIs[] = $newURI;
00232         }
00233         $val = implode( ';', $newFileURIs );
00234         return $val;
00235     }
00236 
00240     function showReport() {
00241         if ( !$this->prefetch ) {
00242             parent::showReport();
00243             return;
00244         }
00245 
00246         if ( $this->reporting ) {
00247             $now = wfTimestamp( TS_DB );
00248             $nowts = microtime( true );
00249             $deltaAll = $nowts - $this->startTime;
00250             $deltaPart = $nowts - $this->lastTime;
00251             $this->pageCountPart = $this->pageCount - $this->pageCountLast;
00252             $this->revCountPart = $this->revCount - $this->revCountLast;
00253 
00254             if ( $deltaAll ) {
00255                 $portion = $this->revCount / $this->maxCount;
00256                 $eta = $this->startTime + $deltaAll / $portion;
00257                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
00258                 if ( $this->fetchCount ) {
00259                     $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
00260                 } else {
00261                     $fetchRate = '-';
00262                 }
00263                 $pageRate = $this->pageCount / $deltaAll;
00264                 $revRate = $this->revCount / $deltaAll;
00265             } else {
00266                 $pageRate = '-';
00267                 $revRate = '-';
00268                 $etats = '-';
00269                 $fetchRate = '-';
00270             }
00271             if ( $deltaPart ) {
00272                 if ( $this->fetchCountLast ) {
00273                     $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
00274                 } else {
00275                     $fetchRatePart = '-';
00276                 }
00277                 $pageRatePart = $this->pageCountPart / $deltaPart;
00278                 $revRatePart = $this->revCountPart / $deltaPart;
00279 
00280             } else {
00281                 $fetchRatePart = '-';
00282                 $pageRatePart = '-';
00283                 $revRatePart = '-';
00284             }
00285             $this->progress( sprintf( "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), %d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% prefetched (all|curr), ETA %s [max %d]",
00286                     $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $fetchRate, $fetchRatePart, $etats, $this->maxCount ) );
00287             $this->lastTime = $nowts;
00288             $this->revCountLast = $this->revCount;
00289             $this->prefetchCountLast = $this->prefetchCount;
00290             $this->fetchCountLast = $this->fetchCount;
00291         }
00292     }
00293 
00294     function setTimeExceeded() {
00295         $this->timeExceeded = true;
00296     }
00297 
00298     function checkIfTimeExceeded() {
00299         if ( $this->maxTimeAllowed && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed ) ) {
00300             return true;
00301         }
00302         return false;
00303     }
00304 
00305     function finalOptionCheck() {
00306         if ( ( $this->checkpointFiles && ! $this->maxTimeAllowed ) ||
00307             ( $this->maxTimeAllowed && !$this->checkpointFiles ) ) {
00308             throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
00309         }
00310         foreach ( $this->checkpointFiles as $checkpointFile ) {
00311             $count = substr_count ( $checkpointFile, "%s" );
00312             if ( $count != 2 ) {
00313                 throw new MWException( "Option checkpointfile must contain two '%s' for substitution of first and last pageids, count is $count instead, file is $checkpointFile.\n" );
00314             }
00315         }
00316 
00317         if ( $this->checkpointFiles ) {
00318             $filenameList = (array)$this->egress->getFilenames();
00319             if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
00320                 throw new MWException( "One checkpointfile must be specified for each output option, if maxtime is used.\n" );
00321             }
00322         }
00323     }
00324 
00329     function readDump( $input ) {
00330         $this->buffer = "";
00331         $this->openElement = false;
00332         $this->atStart = true;
00333         $this->state = "";
00334         $this->lastName = "";
00335         $this->thisPage = 0;
00336         $this->thisRev = 0;
00337 
00338         $parser = xml_parser_create( "UTF-8" );
00339         xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
00340 
00341         xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
00342         xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
00343 
00344         $offset = 0; // for context extraction on error reporting
00345         $bufferSize = 512 * 1024;
00346         do {
00347             if ( $this->checkIfTimeExceeded() ) {
00348                 $this->setTimeExceeded();
00349             }
00350             $chunk = fread( $input, $bufferSize );
00351             if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
00352                 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
00353 
00354                 $byte = xml_get_current_byte_index( $parser );
00355                 $msg = wfMessage( 'xml-error-string',
00356                     'XML import parse failure',
00357                     xml_get_current_line_number( $parser ),
00358                     xml_get_current_column_number( $parser ),
00359                     $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte -$offset, 16 ) . '"' ) ),
00360                     xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
00361 
00362                 xml_parser_free( $parser );
00363 
00364                 throw new MWException( $msg );
00365             }
00366             $offset += strlen( $chunk );
00367         } while ( $chunk !== false && !feof( $input ) );
00368         if ( $this->maxTimeAllowed ) {
00369             $filenameList = (array)$this->egress->getFilenames();
00370             // we wrote some stuff after last checkpoint that needs renamed
00371             if ( file_exists( $filenameList[0] ) ) {
00372                 $newFilenames = array();
00373                 # we might have just written the header and footer and had no
00374                 # pages or revisions written... perhaps they were all deleted
00375                 # there's no pageID 0 so we use that. the caller is responsible
00376                 # for deciding what to do with a file containing only the
00377                 # siteinfo information and the mw tags.
00378                 if ( ! $this->firstPageWritten ) {
00379                     $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
00380                     $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
00381                 }
00382                 else {
00383                     $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
00384                     $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
00385                 }
00386                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
00387                     $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
00388                     $fileinfo = pathinfo( $filenameList[$i] );
00389                     $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
00390                 }
00391                 $this->egress->closeAndRename( $newFilenames );
00392             }
00393         }
00394         xml_parser_free( $parser );
00395 
00396         return true;
00397     }
00398 
00413     function getText( $id ) {
00414         global $wgContentHandlerUseDB;
00415 
00416         $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
00417         $text = false; // The candidate for a good text. false if no proper value.
00418         $failures = 0; // The number of times, this invocation of getText already failed.
00419 
00420         // The number of times getText failed without yielding a good text in between.
00421         static $consecutiveFailedTextRetrievals = 0;
00422 
00423         $this->fetchCount++;
00424 
00425         // To allow to simply return on success and do not have to worry about book keeping,
00426         // we assume, this fetch works (possible after some retries). Nevertheless, we koop
00427         // the old value, so we can restore it, if problems occur (See after the while loop).
00428         $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
00429         $consecutiveFailedTextRetrievals = 0;
00430 
00431         while ( $failures < $this->maxFailures ) {
00432 
00433             // As soon as we found a good text for the $id, we will return immediately.
00434             // Hence, if we make it past the try catch block, we know that we did not
00435             // find a good text.
00436 
00437             try {
00438                 // Step 1: Get some text (or reuse from previous iteratuon if checking
00439                 //         for plausibility failed)
00440 
00441                 // Trying to get prefetch, if it has not been tried before
00442                 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
00443                     $prefetchNotTried = false;
00444                     $tryIsPrefetch = true;
00445                     $text = $this->prefetch->prefetch( intval( $this->thisPage ),
00446                         intval( $this->thisRev ) );
00447                     if ( $text === null ) {
00448                         $text = false;
00449                     }
00450                 }
00451 
00452                 if ( $text === false ) {
00453                     // Fallback to asking the database
00454                     $tryIsPrefetch = false;
00455                     if ( $this->spawn ) {
00456                         $text = $this->getTextSpawned( $id );
00457                     } else {
00458                         $text = $this->getTextDb( $id );
00459                     }
00460 
00461                     // No more checks for texts from DB for now.
00462                     // If we received something that is not false,
00463                     // We treat it as good text, regardless of whether it actually is or is not
00464                     if ( $text !== false ) {
00465                         return $text;
00466                     }
00467                 }
00468 
00469                 if ( $text === false ) {
00470                     throw new MWException( "Generic error while obtaining text for id " . $id );
00471                 }
00472 
00473                 // We received a good candidate for the text of $id via some method
00474 
00475                 // Step 2: Checking for plausibility and return the text if it is
00476                 //         plausible
00477                 $revID = intval( $this->thisRev );
00478                 if ( ! isset( $this->db ) ) {
00479                     throw new MWException( "No database available" );
00480                 }
00481 
00482                 $revLength = strlen( $text );
00483                 if ( $wgContentHandlerUseDB ) {
00484                     $row = $this->db->selectRow(
00485                         'revision',
00486                         array( 'rev_len', 'rev_content_model' ),
00487                         array( 'rev_id' => $revID ),
00488                         __METHOD__
00489                     );
00490                     if ( $row ) {
00491                         // only check the length for the wikitext content handler,
00492                         // it's a wasted (and failed) check otherwise
00493                         if ( $row->rev_content_model == CONTENT_MODEL_WIKITEXT ) {
00494                             $revLength = $row->rev_len;
00495                         }
00496                     }
00497 
00498                 }
00499                 else {
00500                     $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
00501                 }
00502 
00503                 if ( strlen( $text ) == $revLength ) {
00504                     if ( $tryIsPrefetch ) {
00505                         $this->prefetchCount++;
00506                     }
00507                     return $text;
00508                 }
00509 
00510                 $text = false;
00511                 throw new MWException( "Received text is unplausible for id " . $id );
00512 
00513             } catch ( Exception $e ) {
00514                 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
00515                 if ( $failures + 1 < $this->maxFailures ) {
00516                     $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
00517                 }
00518                 $this->progress( $msg );
00519             }
00520 
00521             // Something went wrong; we did not a text that was plausible :(
00522             $failures++;
00523 
00524             // A failure in a prefetch hit does not warrant resetting db connection etc.
00525             if ( ! $tryIsPrefetch ) {
00526                 // After backing off for some time, we try to reboot the whole process as
00527                 // much as possible to not carry over failures from one part to the other
00528                 // parts
00529                 sleep( $this->failureTimeout );
00530                 try {
00531                     $this->rotateDb();
00532                     if ( $this->spawn ) {
00533                         $this->closeSpawn();
00534                         $this->openSpawn();
00535                     }
00536                 } catch ( Exception $e ) {
00537                     $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
00538                         " Trying to continue anyways" );
00539                 }
00540             }
00541         }
00542 
00543         // Retirieving a good text for $id failed (at least) maxFailures times.
00544         // We abort for this $id.
00545 
00546         // Restoring the consecutive failures, and maybe aborting, if the dump
00547         // is too broken.
00548         $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
00549         if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
00550             throw new MWException( "Graceful storage failure" );
00551         }
00552 
00553         return "";
00554     }
00555 
00562     private function getTextDb( $id ) {
00563         global $wgContLang;
00564         if ( ! isset( $this->db ) ) {
00565             throw new MWException( __METHOD__ . "No database available" );
00566         }
00567         $row = $this->db->selectRow( 'text',
00568             array( 'old_text', 'old_flags' ),
00569             array( 'old_id' => $id ),
00570             __METHOD__ );
00571         $text = Revision::getRevisionText( $row );
00572         if ( $text === false ) {
00573             return false;
00574         }
00575         $stripped = str_replace( "\r", "", $text );
00576         $normalized = $wgContLang->normalize( $stripped );
00577         return $normalized;
00578     }
00579 
00580     private function getTextSpawned( $id ) {
00581         wfSuppressWarnings();
00582         if ( !$this->spawnProc ) {
00583             // First time?
00584             $this->openSpawn();
00585         }
00586         $text = $this->getTextSpawnedOnce( $id );
00587         wfRestoreWarnings();
00588         return $text;
00589     }
00590 
00591     function openSpawn() {
00592         global $IP;
00593 
00594         if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
00595             $cmd = implode( " ",
00596                 array_map( 'wfEscapeShellArg',
00597                     array(
00598                         $this->php,
00599                         "$IP/../multiversion/MWScript.php",
00600                         "fetchText.php",
00601                         '--wiki', wfWikiID() ) ) );
00602         }
00603         else {
00604             $cmd = implode( " ",
00605                 array_map( 'wfEscapeShellArg',
00606                     array(
00607                         $this->php,
00608                         "$IP/maintenance/fetchText.php",
00609                         '--wiki', wfWikiID() ) ) );
00610         }
00611         $spec = array(
00612             0 => array( "pipe", "r" ),
00613             1 => array( "pipe", "w" ),
00614             2 => array( "file", "/dev/null", "a" ) );
00615         $pipes = array();
00616 
00617         $this->progress( "Spawning database subprocess: $cmd" );
00618         $this->spawnProc = proc_open( $cmd, $spec, $pipes );
00619         if ( !$this->spawnProc ) {
00620             // shit
00621             $this->progress( "Subprocess spawn failed." );
00622             return false;
00623         }
00624         list(
00625             $this->spawnWrite, // -> stdin
00626             $this->spawnRead,  // <- stdout
00627         ) = $pipes;
00628 
00629         return true;
00630     }
00631 
00632     private function closeSpawn() {
00633         wfSuppressWarnings();
00634         if ( $this->spawnRead ) {
00635             fclose( $this->spawnRead );
00636         }
00637         $this->spawnRead = false;
00638         if ( $this->spawnWrite ) {
00639             fclose( $this->spawnWrite );
00640         }
00641         $this->spawnWrite = false;
00642         if ( $this->spawnErr ) {
00643             fclose( $this->spawnErr );
00644         }
00645         $this->spawnErr = false;
00646         if ( $this->spawnProc ) {
00647             pclose( $this->spawnProc );
00648         }
00649         $this->spawnProc = false;
00650         wfRestoreWarnings();
00651     }
00652 
00653     private function getTextSpawnedOnce( $id ) {
00654         global $wgContLang;
00655 
00656         $ok = fwrite( $this->spawnWrite, "$id\n" );
00657         // $this->progress( ">> $id" );
00658         if ( !$ok ) {
00659             return false;
00660         }
00661 
00662         $ok = fflush( $this->spawnWrite );
00663         // $this->progress( ">> [flush]" );
00664         if ( !$ok ) {
00665             return false;
00666         }
00667 
00668         // check that the text id they are sending is the one we asked for
00669         // this avoids out of sync revision text errors we have encountered in the past
00670         $newId = fgets( $this->spawnRead );
00671         if ( $newId === false ) {
00672             return false;
00673         }
00674         if ( $id != intval( $newId ) ) {
00675             return false;
00676         }
00677 
00678         $len = fgets( $this->spawnRead );
00679         // $this->progress( "<< " . trim( $len ) );
00680         if ( $len === false ) {
00681             return false;
00682         }
00683 
00684         $nbytes = intval( $len );
00685         // actual error, not zero-length text
00686         if ( $nbytes < 0 ) {
00687             return false;
00688         }
00689 
00690         $text = "";
00691 
00692         // Subprocess may not send everything at once, we have to loop.
00693         while ( $nbytes > strlen( $text ) ) {
00694             $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
00695             if ( $buffer === false ) {
00696                 break;
00697             }
00698             $text .= $buffer;
00699         }
00700 
00701         $gotbytes = strlen( $text );
00702         if ( $gotbytes != $nbytes ) {
00703             $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
00704             return false;
00705         }
00706 
00707         // Do normalization in the dump thread...
00708         $stripped = str_replace( "\r", "", $text );
00709         $normalized = $wgContLang->normalize( $stripped );
00710         return $normalized;
00711     }
00712 
00713     function startElement( $parser, $name, $attribs ) {
00714         $this->checkpointJustWritten = false;
00715 
00716         $this->clearOpenElement( null );
00717         $this->lastName = $name;
00718 
00719         if ( $name == 'revision' ) {
00720             $this->state = $name;
00721             $this->egress->writeOpenPage( null, $this->buffer );
00722             $this->buffer = "";
00723         } elseif ( $name == 'page' ) {
00724             $this->state = $name;
00725             if ( $this->atStart ) {
00726                 $this->egress->writeOpenStream( $this->buffer );
00727                 $this->buffer = "";
00728                 $this->atStart = false;
00729             }
00730         }
00731 
00732         if ( $name == "text" && isset( $attribs['id'] ) ) {
00733             $text = $this->getText( $attribs['id'] );
00734             $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
00735             if ( strlen( $text ) > 0 ) {
00736                 $this->characterData( $parser, $text );
00737             }
00738         } else {
00739             $this->openElement = array( $name, $attribs );
00740         }
00741     }
00742 
00743     function endElement( $parser, $name ) {
00744         $this->checkpointJustWritten = false;
00745 
00746         if ( $this->openElement ) {
00747             $this->clearOpenElement( "" );
00748         } else {
00749             $this->buffer .= "</$name>";
00750         }
00751 
00752         if ( $name == 'revision' ) {
00753             $this->egress->writeRevision( null, $this->buffer );
00754             $this->buffer = "";
00755             $this->thisRev = "";
00756         } elseif ( $name == 'page' ) {
00757             if ( ! $this->firstPageWritten ) {
00758                 $this->firstPageWritten = trim( $this->thisPage );
00759             }
00760             $this->lastPageWritten = trim( $this->thisPage );
00761             if ( $this->timeExceeded ) {
00762                 $this->egress->writeClosePage( $this->buffer );
00763                 // nasty hack, we can't just write the chardata after the
00764                 // page tag, it will include leading blanks from the next line
00765                 $this->egress->sink->write( "\n" );
00766 
00767                 $this->buffer = $this->xmlwriterobj->closeStream();
00768                 $this->egress->writeCloseStream( $this->buffer );
00769 
00770                 $this->buffer = "";
00771                 $this->thisPage = "";
00772                 // this could be more than one file if we had more than one output arg
00773 
00774                 $filenameList = (array)$this->egress->getFilenames();
00775                 $newFilenames = array();
00776                 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
00777                 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
00778                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
00779                     $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
00780                     $fileinfo = pathinfo( $filenameList[$i] );
00781                     $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
00782                 }
00783                 $this->egress->closeRenameAndReopen( $newFilenames );
00784                 $this->buffer = $this->xmlwriterobj->openStream();
00785                 $this->timeExceeded = false;
00786                 $this->timeOfCheckpoint = $this->lastTime;
00787                 $this->firstPageWritten = false;
00788                 $this->checkpointJustWritten = true;
00789             }
00790             else {
00791                 $this->egress->writeClosePage( $this->buffer );
00792                 $this->buffer = "";
00793                 $this->thisPage = "";
00794             }
00795 
00796         } elseif ( $name == 'mediawiki' ) {
00797             $this->egress->writeCloseStream( $this->buffer );
00798             $this->buffer = "";
00799         }
00800     }
00801 
00802     function characterData( $parser, $data ) {
00803         $this->clearOpenElement( null );
00804         if ( $this->lastName == "id" ) {
00805             if ( $this->state == "revision" ) {
00806                 $this->thisRev .= $data;
00807             } elseif ( $this->state == "page" ) {
00808                 $this->thisPage .= $data;
00809             }
00810         }
00811         // have to skip the newline left over from closepagetag line of
00812         // end of checkpoint files. nasty hack!!
00813         if ( $this->checkpointJustWritten ) {
00814             if ( $data[0] == "\n" ) {
00815                 $data = substr( $data, 1 );
00816             }
00817             $this->checkpointJustWritten = false;
00818         }
00819         $this->buffer .= htmlspecialchars( $data );
00820     }
00821 
00822     function clearOpenElement( $style ) {
00823         if ( $this->openElement ) {
00824             $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
00825             $this->openElement = false;
00826         }
00827     }
00828 }