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