Deprecate WebRequest::escapeAppendQuery()
[mediawiki.git] / maintenance / backupTextPass.inc
blob675216682cdaf7a1215b9ba307d619c8d16908c5
1 <?php
2 /**
3  * BackupDumper that postprocesses XML dumps from dumpBackup.php to add page text
4  *
5  * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
6  * http://www.mediawiki.org/
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  * http://www.gnu.org/copyleft/gpl.html
22  *
23  * @file
24  * @ingroup Maintenance
25  */
28 /**
29  * @ingroup Maintenance
30  */
31 class TextPassDumper extends BackupDumper {
32         var $prefetch = null;
33         var $input = "php://stdin";
34         var $history = WikiExporter::FULL;
35         var $fetchCount = 0;
36         var $prefetchCount = 0;
37         var $prefetchCountLast = 0;
38         var $fetchCountLast = 0;
40         var $maxFailures = 5;
41         var $maxConsecutiveFailedTextRetrievals = 200;
42         var $failureTimeout = 5; // Seconds to sleep after db failure
44         var $php = "php";
45         var $spawn = false;
47         /**
48          * @var bool|resource
49          */
50         var $spawnProc = false;
52         /**
53          * @var bool|resource
54          */
55         var $spawnWrite = false;
57         /**
58          * @var bool|resource
59          */
60         var $spawnRead = false;
62         /**
63          * @var bool|resource
64          */
65         var $spawnErr = false;
67         var $xmlwriterobj = false;
69         // when we spend more than maxTimeAllowed seconds on this run, we continue
70         // processing until we write out the next complete page, then save output file(s),
71         // rename it/them and open new one(s)
72         var $maxTimeAllowed = 0;  // 0 = no limit
73         var $timeExceeded = false;
74         var $firstPageWritten = false;
75         var $lastPageWritten = false;
76         var $checkpointJustWritten = false;
77         var $checkpointFiles = array();
79         /**
80          * @var DatabaseBase
81          */
82         protected $db;
85         /**
86          * Drop the database connection $this->db and try to get a new one.
87          *
88          * This function tries to get a /different/ connection if this is
89          * possible. Hence, (if this is possible) it switches to a different
90          * failover upon each call.
91          *
92          * This function resets $this->lb and closes all connections on it.
93          *
94          * @throws MWException
95          */
96         function rotateDb() {
97                 // Cleaning up old connections
98                 if ( isset( $this->lb ) ) {
99                         $this->lb->closeAll();
100                         unset( $this->lb );
101                 }
103                 if ( $this->forcedDb !== null ) {
104                         $this->db = $this->forcedDb;
105                         return;
106                 }
108                 if ( isset( $this->db ) && $this->db->isOpen() ) {
109                         throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
110                 }
112                 unset( $this->db );
114                 // Trying to set up new connection.
115                 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
116                 // individually retrying at different layers of code.
118                 // 1. The LoadBalancer.
119                 try {
120                         $this->lb = wfGetLBFactory()->newMainLB();
121                 } catch ( Exception $e ) {
122                         throw new MWException( __METHOD__ . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
123                 }
126                 // 2. The Connection, through the load balancer.
127                 try {
128                         $this->db = $this->lb->getConnection( DB_SLAVE, 'backup' );
129                 } catch ( Exception $e ) {
130                         throw new MWException( __METHOD__ . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
131                 }
132         }
135         function initProgress( $history = WikiExporter::FULL ) {
136                 parent::initProgress();
137                 $this->timeOfCheckpoint = $this->startTime;
138         }
140         function dump( $history, $text = WikiExporter::TEXT ) {
141                 // Notice messages will foul up your XML output even if they're
142                 // relatively harmless.
143                 if ( ini_get( 'display_errors' ) )
144                         ini_set( 'display_errors', 'stderr' );
146                 $this->initProgress( $this->history );
148                 // We are trying to get an initial database connection to avoid that the
149                 // first try of this request's first call to getText fails. However, if
150                 // obtaining a good DB connection fails it's not a serious issue, as
151                 // getText does retry upon failure and can start without having a working
152                 // DB connection.
153                 try {
154                         $this->rotateDb();
155                 } catch ( Exception $e ) {
156                         // We do not even count this as failure. Just let eventual
157                         // watchdogs know.
158                         $this->progress( "Getting initial DB connection failed (" .
159                                 $e->getMessage() . ")" );
160                 }
162                 $this->egress = new ExportProgressFilter( $this->sink, $this );
164                 // it would be nice to do it in the constructor, oh well. need egress set
165                 $this->finalOptionCheck();
167                 // we only want this so we know how to close a stream :-P
168                 $this->xmlwriterobj = new XmlDumpWriter();
170                 $input = fopen( $this->input, "rt" );
171                 $result = $this->readDump( $input );
173                 if ( WikiError::isError( $result ) ) {
174                         throw new MWException( $result->getMessage() );
175                 }
177                 if ( $this->spawnProc ) {
178                         $this->closeSpawn();
179                 }
181                 $this->report( true );
182         }
184         function processOption( $opt, $val, $param ) {
185                 global $IP;
186                 $url = $this->processFileOpt( $val, $param );
188                 switch( $opt ) {
189                 case 'prefetch':
190                         require_once "$IP/maintenance/backupPrefetch.inc";
191                         $this->prefetch = new BaseDump( $url );
192                         break;
193                 case 'stub':
194                         $this->input = $url;
195                         break;
196                 case 'maxtime':
197                         $this->maxTimeAllowed = intval( $val ) * 60;
198                         break;
199                 case 'checkpointfile':
200                         $this->checkpointFiles[] = $val;
201                         break;
202                 case 'current':
203                         $this->history = WikiExporter::CURRENT;
204                         break;
205                 case 'full':
206                         $this->history = WikiExporter::FULL;
207                         break;
208                 case 'spawn':
209                         $this->spawn = true;
210                         if ( $val ) {
211                                 $this->php = $val;
212                         }
213                         break;
214                 }
215         }
217         function processFileOpt( $val, $param ) {
218                 $fileURIs = explode( ';', $param );
219                 foreach ( $fileURIs as $URI ) {
220                         switch( $val ) {
221                                 case "file":
222                                         $newURI = $URI;
223                                         break;
224                                 case "gzip":
225                                         $newURI = "compress.zlib://$URI";
226                                         break;
227                                 case "bzip2":
228                                         $newURI = "compress.bzip2://$URI";
229                                         break;
230                                 case "7zip":
231                                         $newURI = "mediawiki.compress.7z://$URI";
232                                         break;
233                                 default:
234                                         $newURI = $URI;
235                         }
236                         $newFileURIs[] = $newURI;
237                 }
238                 $val = implode( ';', $newFileURIs );
239                 return $val;
240         }
242         /**
243          * Overridden to include prefetch ratio if enabled.
244          */
245         function showReport() {
246                 if ( !$this->prefetch ) {
247                         parent::showReport();
248                         return;
249                 }
251                 if ( $this->reporting ) {
252                         $now = wfTimestamp( TS_DB );
253                         $nowts = wfTime();
254                         $deltaAll = wfTime() - $this->startTime;
255                         $deltaPart = wfTime() - $this->lastTime;
256                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
257                         $this->revCountPart = $this->revCount - $this->revCountLast;
259                         if ( $deltaAll ) {
260                                 $portion = $this->revCount / $this->maxCount;
261                                 $eta = $this->startTime + $deltaAll / $portion;
262                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
263                                 if ( $this->fetchCount ) {
264                                         $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
265                                 } else {
266                                         $fetchRate = '-';
267                                 }
268                                 $pageRate = $this->pageCount / $deltaAll;
269                                 $revRate = $this->revCount / $deltaAll;
270                         } else {
271                                 $pageRate = '-';
272                                 $revRate = '-';
273                                 $etats = '-';
274                                 $fetchRate = '-';
275                         }
276                         if ( $deltaPart ) {
277                                 if ( $this->fetchCountLast ) {
278                                         $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
279                                 } else {
280                                         $fetchRatePart = '-';
281                                 }
282                                 $pageRatePart = $this->pageCountPart / $deltaPart;
283                                 $revRatePart = $this->revCountPart / $deltaPart;
285                         } else {
286                                 $fetchRatePart = '-';
287                                 $pageRatePart = '-';
288                                 $revRatePart = '-';
289                         }
290                         $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]",
291                                         $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $fetchRate, $fetchRatePart, $etats, $this->maxCount ) );
292                         $this->lastTime = $nowts;
293                         $this->revCountLast = $this->revCount;
294                         $this->prefetchCountLast = $this->prefetchCount;
295                         $this->fetchCountLast = $this->fetchCount;
296                 }
297         }
299         function setTimeExceeded() {
300                 $this->timeExceeded = True;
301         }
303         function checkIfTimeExceeded() {
304                 if ( $this->maxTimeAllowed &&  ( $this->lastTime - $this->timeOfCheckpoint  > $this->maxTimeAllowed ) ) {
305                         return true;
306                 }
307                 return false;
308         }
310         function finalOptionCheck() {
311                 if ( ( $this->checkpointFiles && ! $this->maxTimeAllowed ) ||
312                         ( $this->maxTimeAllowed && !$this->checkpointFiles ) ) {
313                         throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
314                 }
315                 foreach ( $this->checkpointFiles as $checkpointFile ) {
316                         $count = substr_count ( $checkpointFile, "%s" );
317                         if ( $count != 2 ) {
318                                 throw new MWException( "Option checkpointfile must contain two '%s' for substitution of first and last pageids, count is $count instead, file is $checkpointFile.\n" );
319                         }
320                 }
322                 if ( $this->checkpointFiles ) {
323                         $filenameList = (array)$this->egress->getFilenames();
324                         if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
325                                 throw new MWException( "One checkpointfile must be specified for each output option, if maxtime is used.\n" );
326                         }
327                 }
328         }
330         function readDump( $input ) {
331                 $this->buffer = "";
332                 $this->openElement = false;
333                 $this->atStart = true;
334                 $this->state = "";
335                 $this->lastName = "";
336                 $this->thisPage = 0;
337                 $this->thisRev = 0;
339                 $parser = xml_parser_create( "UTF-8" );
340                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
342                 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
343                 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
345                 $offset = 0; // for context extraction on error reporting
346                 $bufferSize = 512 * 1024;
347                 do {
348                         if ( $this->checkIfTimeExceeded() ) {
349                                 $this->setTimeExceeded();
350                         }
351                         $chunk = fread( $input, $bufferSize );
352                         if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
353                                 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
354                                 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
355                         }
356                         $offset += strlen( $chunk );
357                 } while ( $chunk !== false && !feof( $input ) );
358                 if ( $this->maxTimeAllowed ) {
359                         $filenameList = (array)$this->egress->getFilenames();
360                         // we wrote some stuff after last checkpoint that needs renamed
361                         if ( file_exists( $filenameList[0] ) ) {
362                                 $newFilenames = array();
363                                 # we might have just written the header and footer and had no
364                                 # pages or revisions written... perhaps they were all deleted
365                                 # there's no pageID 0 so we use that. the caller is responsible
366                                 # for deciding what to do with a file containing only the
367                                 # siteinfo information and the mw tags.
368                                 if ( ! $this->firstPageWritten ) {
369                                         $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
370                                         $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
371                                 }
372                                 else {
373                                         $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
374                                         $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
375                                 }
376                                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
377                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
378                                         $fileinfo = pathinfo( $filenameList[$i] );
379                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
380                                 }
381                                 $this->egress->closeAndRename( $newFilenames );
382                         }
383                 }
384                 xml_parser_free( $parser );
386                 return true;
387         }
389         /**
390          * Tries to get the revision text for a revision id.
391          *
392          * Upon errors, retries (Up to $this->maxFailures tries each call).
393          * If still no good revision get could be found even after this retrying, "" is returned.
394          * If no good revision text could be returned for
395          * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
396          * is thrown.
397          *
398          * @param $id string The revision id to get the text for
399          *
400          * @return string The revision text for $id, or ""
401          * @throws MWException
402          */
403         function getText( $id ) {
404                 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
405                 $text = false; // The candidate for a good text. false if no proper value.
406                 $failures = 0; // The number of times, this invocation of getText already failed.
408                 static $consecutiveFailedTextRetrievals = 0; // The number of times getText failed without
409                                                              // yielding a good text in between.
411                 $this->fetchCount++;
413                 // To allow to simply return on success and do not have to worry about book keeping,
414                 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
415                 // the old value, so we can restore it, if problems occur (See after the while loop).
416                 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
417                 $consecutiveFailedTextRetrievals = 0;
419                 while ( $failures < $this->maxFailures ) {
421                         // As soon as we found a good text for the $id, we will return immediately.
422                         // Hence, if we make it past the try catch block, we know that we did not
423                         // find a good text.
425                         try {
426                                 // Step 1: Get some text (or reuse from previous iteratuon if checking
427                                 //         for plausibility failed)
429                                 // Trying to get prefetch, if it has not been tried before
430                                 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
431                                         $prefetchNotTried = false;
432                                         $tryIsPrefetch = true;
433                                         $text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
434                                         if ( $text === null ) {
435                                                 $text = false;
436                                         }
437                                 }
439                                 if ( $text === false ) {
440                                         // Fallback to asking the database
441                                         $tryIsPrefetch = false;
442                                         if ( $this->spawn ) {
443                                                 $text = $this->getTextSpawned( $id );
444                                         } else {
445                                                 $text = $this->getTextDb( $id );
446                                         }
447                                 }
449                                 if ( $text === false ) {
450                                         throw new MWException( "Generic error while obtaining text for id " . $id );
451                                 }
453                                 // We received a good candidate for the text of $id via some method
455                                 // Step 2: Checking for plausibility and return the text if it is
456                                 //         plausible
457                                 $revID = intval( $this->thisRev );
458                                 if ( ! isset( $this->db ) ) {
459                                         throw new MWException( "No database available" );
460                                 }
461                                 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
462                                 if ( strlen( $text ) == $revLength ) {
463                                         if ( $tryIsPrefetch ) {
464                                                 $this->prefetchCount++;
465                                         }
466                                         return $text;
467                                 }
469                                 $text = false;
470                                 throw new MWException( "Received text is unplausible for id " . $id );
472                         } catch ( Exception $e ) {
473                                 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
474                                 if ( $failures + 1 < $this->maxFailures ) {
475                                         $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
476                                 }
477                                 $this->progress( $msg );
478                         }
480                         // Something went wrong; we did not a text that was plausible :(
481                         $failures++;
484                         // After backing off for some time, we try to reboot the whole process as
485                         // much as possible to not carry over failures from one part to the other
486                         // parts
487                         sleep( $this->failureTimeout );
488                         try {
489                                 $this->rotateDb();
490                                 if ( $this->spawn ) {
491                                         $this->closeSpawn();
492                                         $this->openSpawn();
493                                 }
494                         } catch ( Exception $e ) {
495                                 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
496                                         " Trying to continue anyways" );
497                         }
498                 }
500                 // Retirieving a good text for $id failed (at least) maxFailures times.
501                 // We abort for this $id.
503                 // Restoring the consecutive failures, and maybe aborting, if the dump
504                 // is too broken.
505                 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
506                 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
507                         throw new MWException( "Graceful storage failure" );
508                 }
510                 return "";
511         }
514         /**
515          * May throw a database error if, say, the server dies during query.
516          * @param $id
517          * @return bool|string
518          * @throws MWException
519          */
520         private function getTextDb( $id ) {
521                 global $wgContLang;
522                 if ( ! isset( $this->db ) ) {
523                         throw new MWException( __METHOD__ . "No database available" );
524                 }
525                 $row = $this->db->selectRow( 'text',
526                         array( 'old_text', 'old_flags' ),
527                         array( 'old_id' => $id ),
528                         __METHOD__ );
529                 $text = Revision::getRevisionText( $row );
530                 if ( $text === false ) {
531                         return false;
532                 }
533                 $stripped = str_replace( "\r", "", $text );
534                 $normalized = $wgContLang->normalize( $stripped );
535                 return $normalized;
536         }
538         private function getTextSpawned( $id ) {
539                 wfSuppressWarnings();
540                 if ( !$this->spawnProc ) {
541                         // First time?
542                         $this->openSpawn();
543                 }
544                 $text = $this->getTextSpawnedOnce( $id );
545                 wfRestoreWarnings();
546                 return $text;
547         }
549         function openSpawn() {
550                 global $IP;
552                 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
553                         $cmd = implode( " ",
554                                 array_map( 'wfEscapeShellArg',
555                                         array(
556                                                 $this->php,
557                                                 "$IP/../multiversion/MWScript.php",
558                                                 "fetchText.php",
559                                                 '--wiki', wfWikiID() ) ) );
560                 }
561                 else {
562                         $cmd = implode( " ",
563                                 array_map( 'wfEscapeShellArg',
564                                         array(
565                                                 $this->php,
566                                                 "$IP/maintenance/fetchText.php",
567                                                 '--wiki', wfWikiID() ) ) );
568                 }
569                 $spec = array(
570                         0 => array( "pipe", "r" ),
571                         1 => array( "pipe", "w" ),
572                         2 => array( "file", "/dev/null", "a" ) );
573                 $pipes = array();
575                 $this->progress( "Spawning database subprocess: $cmd" );
576                 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
577                 if ( !$this->spawnProc ) {
578                         // shit
579                         $this->progress( "Subprocess spawn failed." );
580                         return false;
581                 }
582                 list(
583                         $this->spawnWrite, // -> stdin
584                         $this->spawnRead,  // <- stdout
585                 ) = $pipes;
587                 return true;
588         }
590         private function closeSpawn() {
591                 wfSuppressWarnings();
592                 if ( $this->spawnRead )
593                         fclose( $this->spawnRead );
594                 $this->spawnRead = false;
595                 if ( $this->spawnWrite )
596                         fclose( $this->spawnWrite );
597                 $this->spawnWrite = false;
598                 if ( $this->spawnErr )
599                         fclose( $this->spawnErr );
600                 $this->spawnErr = false;
601                 if ( $this->spawnProc )
602                         pclose( $this->spawnProc );
603                 $this->spawnProc = false;
604                 wfRestoreWarnings();
605         }
607         private function getTextSpawnedOnce( $id ) {
608                 global $wgContLang;
610                 $ok = fwrite( $this->spawnWrite, "$id\n" );
611                 // $this->progress( ">> $id" );
612                 if ( !$ok ) return false;
614                 $ok = fflush( $this->spawnWrite );
615                 // $this->progress( ">> [flush]" );
616                 if ( !$ok ) return false;
618                 // check that the text id they are sending is the one we asked for
619                 // this avoids out of sync revision text errors we have encountered in the past
620                 $newId = fgets( $this->spawnRead );
621                 if ( $newId === false ) {
622                         return false;
623                 }
624                 if ( $id != intval( $newId ) ) {
625                         return false;
626                 }
628                 $len = fgets( $this->spawnRead );
629                 // $this->progress( "<< " . trim( $len ) );
630                 if ( $len === false ) return false;
632                 $nbytes = intval( $len );
633                 // actual error, not zero-length text
634                 if ( $nbytes < 0 ) return false;
636                 $text = "";
638                 // Subprocess may not send everything at once, we have to loop.
639                 while ( $nbytes > strlen( $text ) ) {
640                         $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
641                         if ( $buffer === false ) break;
642                         $text .= $buffer;
643                 }
645                 $gotbytes = strlen( $text );
646                 if ( $gotbytes != $nbytes ) {
647                         $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
648                         return false;
649                 }
651                 // Do normalization in the dump thread...
652                 $stripped = str_replace( "\r", "", $text );
653                 $normalized = $wgContLang->normalize( $stripped );
654                 return $normalized;
655         }
657         function startElement( $parser, $name, $attribs ) {
658                 $this->checkpointJustWritten = false;
660                 $this->clearOpenElement( null );
661                 $this->lastName = $name;
663                 if ( $name == 'revision' ) {
664                         $this->state = $name;
665                         $this->egress->writeOpenPage( null, $this->buffer );
666                         $this->buffer = "";
667                 } elseif ( $name == 'page' ) {
668                         $this->state = $name;
669                         if ( $this->atStart ) {
670                                 $this->egress->writeOpenStream( $this->buffer );
671                                 $this->buffer = "";
672                                 $this->atStart = false;
673                         }
674                 }
676                 if ( $name == "text" && isset( $attribs['id'] ) ) {
677                         $text = $this->getText( $attribs['id'] );
678                         $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
679                         if ( strlen( $text ) > 0 ) {
680                                 $this->characterData( $parser, $text );
681                         }
682                 } else {
683                         $this->openElement = array( $name, $attribs );
684                 }
685         }
687         function endElement( $parser, $name ) {
688                 $this->checkpointJustWritten = false;
690                 if ( $this->openElement ) {
691                         $this->clearOpenElement( "" );
692                 } else {
693                         $this->buffer .= "</$name>";
694                 }
696                 if ( $name == 'revision' ) {
697                         $this->egress->writeRevision( null, $this->buffer );
698                         $this->buffer = "";
699                         $this->thisRev = "";
700                 } elseif ( $name == 'page' ) {
701                         if ( ! $this->firstPageWritten ) {
702                                 $this->firstPageWritten = trim( $this->thisPage );
703                         }
704                         $this->lastPageWritten = trim( $this->thisPage );
705                         if ( $this->timeExceeded ) {
706                                 $this->egress->writeClosePage( $this->buffer );
707                                 // nasty hack, we can't just write the chardata after the
708                                 // page tag, it will include leading blanks from the next line
709                                 $this->egress->sink->write( "\n" );
711                                 $this->buffer = $this->xmlwriterobj->closeStream();
712                                 $this->egress->writeCloseStream( $this->buffer );
714                                 $this->buffer = "";
715                                 $this->thisPage = "";
716                                 // this could be more than one file if we had more than one output arg
718                                 $filenameList = (array)$this->egress->getFilenames();
719                                 $newFilenames = array();
720                                 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
721                                 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
722                                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
723                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
724                                         $fileinfo = pathinfo( $filenameList[$i] );
725                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
726                                 }
727                                 $this->egress->closeRenameAndReopen( $newFilenames );
728                                 $this->buffer = $this->xmlwriterobj->openStream();
729                                 $this->timeExceeded = false;
730                                 $this->timeOfCheckpoint = $this->lastTime;
731                                 $this->firstPageWritten = false;
732                                 $this->checkpointJustWritten = true;
733                         }
734                         else {
735                                 $this->egress->writeClosePage( $this->buffer );
736                                 $this->buffer = "";
737                                 $this->thisPage = "";
738                         }
740                 } elseif ( $name == 'mediawiki' ) {
741                         $this->egress->writeCloseStream( $this->buffer );
742                         $this->buffer = "";
743                 }
744         }
746         function characterData( $parser, $data ) {
747                 $this->clearOpenElement( null );
748                 if ( $this->lastName == "id" ) {
749                         if ( $this->state == "revision" ) {
750                                 $this->thisRev .= $data;
751                         } elseif ( $this->state == "page" ) {
752                                 $this->thisPage .= $data;
753                         }
754                 }
755                 // have to skip the newline left over from closepagetag line of
756                 // end of checkpoint files. nasty hack!!
757                 if ( $this->checkpointJustWritten ) {
758                         if ( $data[0] == "\n" ) {
759                                 $data = substr( $data, 1 );
760                         }
761                         $this->checkpointJustWritten = false;
762                 }
763                 $this->buffer .= htmlspecialchars( $data );
764         }
766         function clearOpenElement( $style ) {
767                 if ( $this->openElement ) {
768                         $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
769                         $this->openElement = false;
770                 }
771         }