Merge "Disable transaction warnings for automatic trx."
[mediawiki.git] / maintenance / backupTextPass.inc
blob81e61b7bd515ea0565831b1de4325a038ed16f9f
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  */
27 require_once( __DIR__ . '/backup.inc' );
29 /**
30  * @ingroup Maintenance
31  */
32 class TextPassDumper extends BackupDumper {
33         var $prefetch = null;
34         var $input = "php://stdin";
35         var $history = WikiExporter::FULL;
36         var $fetchCount = 0;
37         var $prefetchCount = 0;
38         var $prefetchCountLast = 0;
39         var $fetchCountLast = 0;
41         var $maxFailures = 5;
42         var $maxConsecutiveFailedTextRetrievals = 200;
43         var $failureTimeout = 5; // Seconds to sleep after db failure
45         var $php = "php";
46         var $spawn = false;
48         /**
49          * @var bool|resource
50          */
51         var $spawnProc = false;
53         /**
54          * @var bool|resource
55          */
56         var $spawnWrite = false;
58         /**
59          * @var bool|resource
60          */
61         var $spawnRead = false;
63         /**
64          * @var bool|resource
65          */
66         var $spawnErr = false;
68         var $xmlwriterobj = false;
70         // when we spend more than maxTimeAllowed seconds on this run, we continue
71         // processing until we write out the next complete page, then save output file(s),
72         // rename it/them and open new one(s)
73         var $maxTimeAllowed = 0;  // 0 = no limit
74         var $timeExceeded = false;
75         var $firstPageWritten = false;
76         var $lastPageWritten = false;
77         var $checkpointJustWritten = false;
78         var $checkpointFiles = array();
80         /**
81          * @var DatabaseBase
82          */
83         protected $db;
86         /**
87          * Drop the database connection $this->db and try to get a new one.
88          *
89          * This function tries to get a /different/ connection if this is
90          * possible. Hence, (if this is possible) it switches to a different
91          * failover upon each call.
92          *
93          * This function resets $this->lb and closes all connections on it.
94          *
95          * @throws MWException
96          */
97         function rotateDb() {
98                 // Cleaning up old connections
99                 if ( isset( $this->lb ) ) {
100                         $this->lb->closeAll();
101                         unset( $this->lb );
102                 }
104                 if ( $this->forcedDb !== null ) {
105                         $this->db = $this->forcedDb;
106                         return;
107                 }
109                 if ( isset( $this->db ) && $this->db->isOpen() ) {
110                         throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
111                 }
113                 unset( $this->db );
115                 // Trying to set up new connection.
116                 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
117                 // individually retrying at different layers of code.
119                 // 1. The LoadBalancer.
120                 try {
121                         $this->lb = wfGetLBFactory()->newMainLB();
122                 } catch ( Exception $e ) {
123                         throw new MWException( __METHOD__ . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
124                 }
127                 // 2. The Connection, through the load balancer.
128                 try {
129                         $this->db = $this->lb->getConnection( DB_SLAVE, 'backup' );
130                 } catch ( Exception $e ) {
131                         throw new MWException( __METHOD__ . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
132                 }
133         }
136         function initProgress( $history = WikiExporter::FULL ) {
137                 parent::initProgress();
138                 $this->timeOfCheckpoint = $this->startTime;
139         }
141         function dump( $history, $text = WikiExporter::TEXT ) {
142                 // Notice messages will foul up your XML output even if they're
143                 // relatively harmless.
144                 if ( ini_get( 'display_errors' ) )
145                         ini_set( 'display_errors', 'stderr' );
147                 $this->initProgress( $this->history );
149                 // We are trying to get an initial database connection to avoid that the
150                 // first try of this request's first call to getText fails. However, if
151                 // obtaining a good DB connection fails it's not a serious issue, as
152                 // getText does retry upon failure and can start without having a working
153                 // DB connection.
154                 try {
155                         $this->rotateDb();
156                 } catch ( Exception $e ) {
157                         // We do not even count this as failure. Just let eventual
158                         // watchdogs know.
159                         $this->progress( "Getting initial DB connection failed (" .
160                                 $e->getMessage() . ")" );
161                 }
163                 $this->egress = new ExportProgressFilter( $this->sink, $this );
165                 // it would be nice to do it in the constructor, oh well. need egress set
166                 $this->finalOptionCheck();
168                 // we only want this so we know how to close a stream :-P
169                 $this->xmlwriterobj = new XmlDumpWriter();
171                 $input = fopen( $this->input, "rt" );
172                 $this->readDump( $input );
174                 if ( $this->spawnProc ) {
175                         $this->closeSpawn();
176                 }
178                 $this->report( true );
179         }
181         function processOption( $opt, $val, $param ) {
182                 global $IP;
183                 $url = $this->processFileOpt( $val, $param );
185                 switch( $opt ) {
186                 case 'prefetch':
187                         require_once "$IP/maintenance/backupPrefetch.inc";
188                         $this->prefetch = new BaseDump( $url );
189                         break;
190                 case 'stub':
191                         $this->input = $url;
192                         break;
193                 case 'maxtime':
194                         $this->maxTimeAllowed = intval( $val ) * 60;
195                         break;
196                 case 'checkpointfile':
197                         $this->checkpointFiles[] = $val;
198                         break;
199                 case 'current':
200                         $this->history = WikiExporter::CURRENT;
201                         break;
202                 case 'full':
203                         $this->history = WikiExporter::FULL;
204                         break;
205                 case 'spawn':
206                         $this->spawn = true;
207                         if ( $val ) {
208                                 $this->php = $val;
209                         }
210                         break;
211                 }
212         }
214         function processFileOpt( $val, $param ) {
215                 $fileURIs = explode( ';', $param );
216                 foreach ( $fileURIs as $URI ) {
217                         switch( $val ) {
218                                 case "file":
219                                         $newURI = $URI;
220                                         break;
221                                 case "gzip":
222                                         $newURI = "compress.zlib://$URI";
223                                         break;
224                                 case "bzip2":
225                                         $newURI = "compress.bzip2://$URI";
226                                         break;
227                                 case "7zip":
228                                         $newURI = "mediawiki.compress.7z://$URI";
229                                         break;
230                                 default:
231                                         $newURI = $URI;
232                         }
233                         $newFileURIs[] = $newURI;
234                 }
235                 $val = implode( ';', $newFileURIs );
236                 return $val;
237         }
239         /**
240          * Overridden to include prefetch ratio if enabled.
241          */
242         function showReport() {
243                 if ( !$this->prefetch ) {
244                         parent::showReport();
245                         return;
246                 }
248                 if ( $this->reporting ) {
249                         $now = wfTimestamp( TS_DB );
250                         $nowts = microtime( true );
251                         $deltaAll = $nowts - $this->startTime;
252                         $deltaPart = $nowts - $this->lastTime;
253                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
254                         $this->revCountPart = $this->revCount - $this->revCountLast;
256                         if ( $deltaAll ) {
257                                 $portion = $this->revCount / $this->maxCount;
258                                 $eta = $this->startTime + $deltaAll / $portion;
259                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
260                                 if ( $this->fetchCount ) {
261                                         $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
262                                 } else {
263                                         $fetchRate = '-';
264                                 }
265                                 $pageRate = $this->pageCount / $deltaAll;
266                                 $revRate = $this->revCount / $deltaAll;
267                         } else {
268                                 $pageRate = '-';
269                                 $revRate = '-';
270                                 $etats = '-';
271                                 $fetchRate = '-';
272                         }
273                         if ( $deltaPart ) {
274                                 if ( $this->fetchCountLast ) {
275                                         $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
276                                 } else {
277                                         $fetchRatePart = '-';
278                                 }
279                                 $pageRatePart = $this->pageCountPart / $deltaPart;
280                                 $revRatePart = $this->revCountPart / $deltaPart;
282                         } else {
283                                 $fetchRatePart = '-';
284                                 $pageRatePart = '-';
285                                 $revRatePart = '-';
286                         }
287                         $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]",
288                                         $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $fetchRate, $fetchRatePart, $etats, $this->maxCount ) );
289                         $this->lastTime = $nowts;
290                         $this->revCountLast = $this->revCount;
291                         $this->prefetchCountLast = $this->prefetchCount;
292                         $this->fetchCountLast = $this->fetchCount;
293                 }
294         }
296         function setTimeExceeded() {
297                 $this->timeExceeded = True;
298         }
300         function checkIfTimeExceeded() {
301                 if ( $this->maxTimeAllowed &&  ( $this->lastTime - $this->timeOfCheckpoint  > $this->maxTimeAllowed ) ) {
302                         return true;
303                 }
304                 return false;
305         }
307         function finalOptionCheck() {
308                 if ( ( $this->checkpointFiles && ! $this->maxTimeAllowed ) ||
309                         ( $this->maxTimeAllowed && !$this->checkpointFiles ) ) {
310                         throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
311                 }
312                 foreach ( $this->checkpointFiles as $checkpointFile ) {
313                         $count = substr_count ( $checkpointFile, "%s" );
314                         if ( $count != 2 ) {
315                                 throw new MWException( "Option checkpointfile must contain two '%s' for substitution of first and last pageids, count is $count instead, file is $checkpointFile.\n" );
316                         }
317                 }
319                 if ( $this->checkpointFiles ) {
320                         $filenameList = (array)$this->egress->getFilenames();
321                         if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
322                                 throw new MWException( "One checkpointfile must be specified for each output option, if maxtime is used.\n" );
323                         }
324                 }
325         }
327         /**
328          * @throws MWException Failure to parse XML input
329          * @return true
330          */
331         function readDump( $input ) {
332                 $this->buffer = "";
333                 $this->openElement = false;
334                 $this->atStart = true;
335                 $this->state = "";
336                 $this->lastName = "";
337                 $this->thisPage = 0;
338                 $this->thisRev = 0;
340                 $parser = xml_parser_create( "UTF-8" );
341                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
343                 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
344                 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
346                 $offset = 0; // for context extraction on error reporting
347                 $bufferSize = 512 * 1024;
348                 do {
349                         if ( $this->checkIfTimeExceeded() ) {
350                                 $this->setTimeExceeded();
351                         }
352                         $chunk = fread( $input, $bufferSize );
353                         if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
354                                 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
356                                 $byte = xml_get_current_byte_index( $parser );
357                                 $msg = wfMessage( 'xml-error-string',
358                                         'XML import parse failure',
359                                         xml_get_current_line_number( $parser ),
360                                         xml_get_current_column_number( $parser ),
361                                         $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte -$offset, 16 ) . '"' ) ),
362                                         xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
364                                 xml_parser_free( $parser );
366                                 throw new MWException( $msg );
367                         }
368                         $offset += strlen( $chunk );
369                 } while ( $chunk !== false && !feof( $input ) );
370                 if ( $this->maxTimeAllowed ) {
371                         $filenameList = (array)$this->egress->getFilenames();
372                         // we wrote some stuff after last checkpoint that needs renamed
373                         if ( file_exists( $filenameList[0] ) ) {
374                                 $newFilenames = array();
375                                 # we might have just written the header and footer and had no
376                                 # pages or revisions written... perhaps they were all deleted
377                                 # there's no pageID 0 so we use that. the caller is responsible
378                                 # for deciding what to do with a file containing only the
379                                 # siteinfo information and the mw tags.
380                                 if ( ! $this->firstPageWritten ) {
381                                         $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
382                                         $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
383                                 }
384                                 else {
385                                         $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
386                                         $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
387                                 }
388                                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
389                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
390                                         $fileinfo = pathinfo( $filenameList[$i] );
391                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
392                                 }
393                                 $this->egress->closeAndRename( $newFilenames );
394                         }
395                 }
396                 xml_parser_free( $parser );
398                 return true;
399         }
401         /**
402          * Tries to get the revision text for a revision id.
403          *
404          * Upon errors, retries (Up to $this->maxFailures tries each call).
405          * If still no good revision get could be found even after this retrying, "" is returned.
406          * If no good revision text could be returned for
407          * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
408          * is thrown.
409          *
410          * @param $id string The revision id to get the text for
411          *
412          * @return string The revision text for $id, or ""
413          * @throws MWException
414          */
415         function getText( $id ) {
416                 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
417                 $text = false; // The candidate for a good text. false if no proper value.
418                 $failures = 0; // The number of times, this invocation of getText already failed.
420                 static $consecutiveFailedTextRetrievals = 0; // The number of times getText failed without
421                                                              // yielding a good text in between.
423                 $this->fetchCount++;
425                 // To allow to simply return on success and do not have to worry about book keeping,
426                 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
427                 // the old value, so we can restore it, if problems occur (See after the while loop).
428                 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
429                 $consecutiveFailedTextRetrievals = 0;
431                 while ( $failures < $this->maxFailures ) {
433                         // As soon as we found a good text for the $id, we will return immediately.
434                         // Hence, if we make it past the try catch block, we know that we did not
435                         // find a good text.
437                         try {
438                                 // Step 1: Get some text (or reuse from previous iteratuon if checking
439                                 //         for plausibility failed)
441                                 // Trying to get prefetch, if it has not been tried before
442                                 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
443                                         $prefetchNotTried = false;
444                                         $tryIsPrefetch = true;
445                                         $text = $this->prefetch->prefetch( intval( $this->thisPage ),
446                                                 intval( $this->thisRev ) );
447                                         if ( $text === null ) {
448                                                 $text = false;
449                                         }
450                                 }
452                                 if ( $text === false ) {
453                                         // Fallback to asking the database
454                                         $tryIsPrefetch = false;
455                                         if ( $this->spawn ) {
456                                                 $text = $this->getTextSpawned( $id );
457                                         } else {
458                                                 $text = $this->getTextDb( $id );
459                                         }
461                                         // No more checks for texts from DB for now.
462                                         // If we received something that is not false,
463                                         // We treat it as good text, regardless of whether it actually is or is not
464                                         if ( $text !== false ) {
465                                                 return $text;
466                                         }
467                                 }
469                                 if ( $text === false ) {
470                                         throw new MWException( "Generic error while obtaining text for id " . $id );
471                                 }
473                                 // We received a good candidate for the text of $id via some method
475                                 // Step 2: Checking for plausibility and return the text if it is
476                                 //         plausible
477                                 $revID = intval( $this->thisRev );
478                                 if ( ! isset( $this->db ) ) {
479                                         throw new MWException( "No database available" );
480                                 }
481                                 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
482                                 if ( strlen( $text ) == $revLength ) {
483                                         if ( $tryIsPrefetch ) {
484                                                 $this->prefetchCount++;
485                                         }
486                                         return $text;
487                                 }
489                                 $text = false;
490                                 throw new MWException( "Received text is unplausible for id " . $id );
492                         } catch ( Exception $e ) {
493                                 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
494                                 if ( $failures + 1 < $this->maxFailures ) {
495                                         $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
496                                 }
497                                 $this->progress( $msg );
498                         }
500                         // Something went wrong; we did not a text that was plausible :(
501                         $failures++;
503                         // A failure in a prefetch hit does not warrant resetting db connection etc.
504                         if ( ! $tryIsPrefetch ) {
505                                 // After backing off for some time, we try to reboot the whole process as
506                                 // much as possible to not carry over failures from one part to the other
507                                 // parts
508                                 sleep( $this->failureTimeout );
509                                 try {
510                                         $this->rotateDb();
511                                         if ( $this->spawn ) {
512                                                 $this->closeSpawn();
513                                                 $this->openSpawn();
514                                         }
515                                 } catch ( Exception $e ) {
516                                         $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
517                                                 " Trying to continue anyways" );
518                                 }
519                         }
520                 }
522                 // Retirieving a good text for $id failed (at least) maxFailures times.
523                 // We abort for this $id.
525                 // Restoring the consecutive failures, and maybe aborting, if the dump
526                 // is too broken.
527                 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
528                 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
529                         throw new MWException( "Graceful storage failure" );
530                 }
532                 return "";
533         }
536         /**
537          * May throw a database error if, say, the server dies during query.
538          * @param $id
539          * @return bool|string
540          * @throws MWException
541          */
542         private function getTextDb( $id ) {
543                 global $wgContLang;
544                 if ( ! isset( $this->db ) ) {
545                         throw new MWException( __METHOD__ . "No database available" );
546                 }
547                 $row = $this->db->selectRow( 'text',
548                         array( 'old_text', 'old_flags' ),
549                         array( 'old_id' => $id ),
550                         __METHOD__ );
551                 $text = Revision::getRevisionText( $row );
552                 if ( $text === false ) {
553                         return false;
554                 }
555                 $stripped = str_replace( "\r", "", $text );
556                 $normalized = $wgContLang->normalize( $stripped );
557                 return $normalized;
558         }
560         private function getTextSpawned( $id ) {
561                 wfSuppressWarnings();
562                 if ( !$this->spawnProc ) {
563                         // First time?
564                         $this->openSpawn();
565                 }
566                 $text = $this->getTextSpawnedOnce( $id );
567                 wfRestoreWarnings();
568                 return $text;
569         }
571         function openSpawn() {
572                 global $IP;
574                 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
575                         $cmd = implode( " ",
576                                 array_map( 'wfEscapeShellArg',
577                                         array(
578                                                 $this->php,
579                                                 "$IP/../multiversion/MWScript.php",
580                                                 "fetchText.php",
581                                                 '--wiki', wfWikiID() ) ) );
582                 }
583                 else {
584                         $cmd = implode( " ",
585                                 array_map( 'wfEscapeShellArg',
586                                         array(
587                                                 $this->php,
588                                                 "$IP/maintenance/fetchText.php",
589                                                 '--wiki', wfWikiID() ) ) );
590                 }
591                 $spec = array(
592                         0 => array( "pipe", "r" ),
593                         1 => array( "pipe", "w" ),
594                         2 => array( "file", "/dev/null", "a" ) );
595                 $pipes = array();
597                 $this->progress( "Spawning database subprocess: $cmd" );
598                 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
599                 if ( !$this->spawnProc ) {
600                         // shit
601                         $this->progress( "Subprocess spawn failed." );
602                         return false;
603                 }
604                 list(
605                         $this->spawnWrite, // -> stdin
606                         $this->spawnRead,  // <- stdout
607                 ) = $pipes;
609                 return true;
610         }
612         private function closeSpawn() {
613                 wfSuppressWarnings();
614                 if ( $this->spawnRead )
615                         fclose( $this->spawnRead );
616                 $this->spawnRead = false;
617                 if ( $this->spawnWrite )
618                         fclose( $this->spawnWrite );
619                 $this->spawnWrite = false;
620                 if ( $this->spawnErr )
621                         fclose( $this->spawnErr );
622                 $this->spawnErr = false;
623                 if ( $this->spawnProc )
624                         pclose( $this->spawnProc );
625                 $this->spawnProc = false;
626                 wfRestoreWarnings();
627         }
629         private function getTextSpawnedOnce( $id ) {
630                 global $wgContLang;
632                 $ok = fwrite( $this->spawnWrite, "$id\n" );
633                 // $this->progress( ">> $id" );
634                 if ( !$ok ) return false;
636                 $ok = fflush( $this->spawnWrite );
637                 // $this->progress( ">> [flush]" );
638                 if ( !$ok ) return false;
640                 // check that the text id they are sending is the one we asked for
641                 // this avoids out of sync revision text errors we have encountered in the past
642                 $newId = fgets( $this->spawnRead );
643                 if ( $newId === false ) {
644                         return false;
645                 }
646                 if ( $id != intval( $newId ) ) {
647                         return false;
648                 }
650                 $len = fgets( $this->spawnRead );
651                 // $this->progress( "<< " . trim( $len ) );
652                 if ( $len === false ) return false;
654                 $nbytes = intval( $len );
655                 // actual error, not zero-length text
656                 if ( $nbytes < 0 ) return false;
658                 $text = "";
660                 // Subprocess may not send everything at once, we have to loop.
661                 while ( $nbytes > strlen( $text ) ) {
662                         $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
663                         if ( $buffer === false ) break;
664                         $text .= $buffer;
665                 }
667                 $gotbytes = strlen( $text );
668                 if ( $gotbytes != $nbytes ) {
669                         $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
670                         return false;
671                 }
673                 // Do normalization in the dump thread...
674                 $stripped = str_replace( "\r", "", $text );
675                 $normalized = $wgContLang->normalize( $stripped );
676                 return $normalized;
677         }
679         function startElement( $parser, $name, $attribs ) {
680                 $this->checkpointJustWritten = false;
682                 $this->clearOpenElement( null );
683                 $this->lastName = $name;
685                 if ( $name == 'revision' ) {
686                         $this->state = $name;
687                         $this->egress->writeOpenPage( null, $this->buffer );
688                         $this->buffer = "";
689                 } elseif ( $name == 'page' ) {
690                         $this->state = $name;
691                         if ( $this->atStart ) {
692                                 $this->egress->writeOpenStream( $this->buffer );
693                                 $this->buffer = "";
694                                 $this->atStart = false;
695                         }
696                 }
698                 if ( $name == "text" && isset( $attribs['id'] ) ) {
699                         $text = $this->getText( $attribs['id'] );
700                         $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
701                         if ( strlen( $text ) > 0 ) {
702                                 $this->characterData( $parser, $text );
703                         }
704                 } else {
705                         $this->openElement = array( $name, $attribs );
706                 }
707         }
709         function endElement( $parser, $name ) {
710                 $this->checkpointJustWritten = false;
712                 if ( $this->openElement ) {
713                         $this->clearOpenElement( "" );
714                 } else {
715                         $this->buffer .= "</$name>";
716                 }
718                 if ( $name == 'revision' ) {
719                         $this->egress->writeRevision( null, $this->buffer );
720                         $this->buffer = "";
721                         $this->thisRev = "";
722                 } elseif ( $name == 'page' ) {
723                         if ( ! $this->firstPageWritten ) {
724                                 $this->firstPageWritten = trim( $this->thisPage );
725                         }
726                         $this->lastPageWritten = trim( $this->thisPage );
727                         if ( $this->timeExceeded ) {
728                                 $this->egress->writeClosePage( $this->buffer );
729                                 // nasty hack, we can't just write the chardata after the
730                                 // page tag, it will include leading blanks from the next line
731                                 $this->egress->sink->write( "\n" );
733                                 $this->buffer = $this->xmlwriterobj->closeStream();
734                                 $this->egress->writeCloseStream( $this->buffer );
736                                 $this->buffer = "";
737                                 $this->thisPage = "";
738                                 // this could be more than one file if we had more than one output arg
740                                 $filenameList = (array)$this->egress->getFilenames();
741                                 $newFilenames = array();
742                                 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
743                                 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
744                                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
745                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
746                                         $fileinfo = pathinfo( $filenameList[$i] );
747                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
748                                 }
749                                 $this->egress->closeRenameAndReopen( $newFilenames );
750                                 $this->buffer = $this->xmlwriterobj->openStream();
751                                 $this->timeExceeded = false;
752                                 $this->timeOfCheckpoint = $this->lastTime;
753                                 $this->firstPageWritten = false;
754                                 $this->checkpointJustWritten = true;
755                         }
756                         else {
757                                 $this->egress->writeClosePage( $this->buffer );
758                                 $this->buffer = "";
759                                 $this->thisPage = "";
760                         }
762                 } elseif ( $name == 'mediawiki' ) {
763                         $this->egress->writeCloseStream( $this->buffer );
764                         $this->buffer = "";
765                 }
766         }
768         function characterData( $parser, $data ) {
769                 $this->clearOpenElement( null );
770                 if ( $this->lastName == "id" ) {
771                         if ( $this->state == "revision" ) {
772                                 $this->thisRev .= $data;
773                         } elseif ( $this->state == "page" ) {
774                                 $this->thisPage .= $data;
775                         }
776                 }
777                 // have to skip the newline left over from closepagetag line of
778                 // end of checkpoint files. nasty hack!!
779                 if ( $this->checkpointJustWritten ) {
780                         if ( $data[0] == "\n" ) {
781                                 $data = substr( $data, 1 );
782                         }
783                         $this->checkpointJustWritten = false;
784                 }
785                 $this->buffer .= htmlspecialchars( $data );
786         }
788         function clearOpenElement( $style ) {
789                 if ( $this->openElement ) {
790                         $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
791                         $this->openElement = false;
792                 }
793         }