Merge "Use new xsd schema 0.7 in Export.php"
[mediawiki.git] / maintenance / backupTextPass.inc
blob3846ef50b8ee201d2f4d15548ae24dc078b2e21e
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( dirname( __FILE__ ) . '/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                 $result = $this->readDump( $input );
174                 if ( WikiError::isError( $result ) ) {
175                         throw new MWException( $result->getMessage() );
176                 }
178                 if ( $this->spawnProc ) {
179                         $this->closeSpawn();
180                 }
182                 $this->report( true );
183         }
185         function processOption( $opt, $val, $param ) {
186                 global $IP;
187                 $url = $this->processFileOpt( $val, $param );
189                 switch( $opt ) {
190                 case 'prefetch':
191                         require_once "$IP/maintenance/backupPrefetch.inc";
192                         $this->prefetch = new BaseDump( $url );
193                         break;
194                 case 'stub':
195                         $this->input = $url;
196                         break;
197                 case 'maxtime':
198                         $this->maxTimeAllowed = intval( $val ) * 60;
199                         break;
200                 case 'checkpointfile':
201                         $this->checkpointFiles[] = $val;
202                         break;
203                 case 'current':
204                         $this->history = WikiExporter::CURRENT;
205                         break;
206                 case 'full':
207                         $this->history = WikiExporter::FULL;
208                         break;
209                 case 'spawn':
210                         $this->spawn = true;
211                         if ( $val ) {
212                                 $this->php = $val;
213                         }
214                         break;
215                 }
216         }
218         function processFileOpt( $val, $param ) {
219                 $fileURIs = explode( ';', $param );
220                 foreach ( $fileURIs as $URI ) {
221                         switch( $val ) {
222                                 case "file":
223                                         $newURI = $URI;
224                                         break;
225                                 case "gzip":
226                                         $newURI = "compress.zlib://$URI";
227                                         break;
228                                 case "bzip2":
229                                         $newURI = "compress.bzip2://$URI";
230                                         break;
231                                 case "7zip":
232                                         $newURI = "mediawiki.compress.7z://$URI";
233                                         break;
234                                 default:
235                                         $newURI = $URI;
236                         }
237                         $newFileURIs[] = $newURI;
238                 }
239                 $val = implode( ';', $newFileURIs );
240                 return $val;
241         }
243         /**
244          * Overridden to include prefetch ratio if enabled.
245          */
246         function showReport() {
247                 if ( !$this->prefetch ) {
248                         parent::showReport();
249                         return;
250                 }
252                 if ( $this->reporting ) {
253                         $now = wfTimestamp( TS_DB );
254                         $nowts = wfTime();
255                         $deltaAll = wfTime() - $this->startTime;
256                         $deltaPart = wfTime() - $this->lastTime;
257                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
258                         $this->revCountPart = $this->revCount - $this->revCountLast;
260                         if ( $deltaAll ) {
261                                 $portion = $this->revCount / $this->maxCount;
262                                 $eta = $this->startTime + $deltaAll / $portion;
263                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
264                                 if ( $this->fetchCount ) {
265                                         $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
266                                 } else {
267                                         $fetchRate = '-';
268                                 }
269                                 $pageRate = $this->pageCount / $deltaAll;
270                                 $revRate = $this->revCount / $deltaAll;
271                         } else {
272                                 $pageRate = '-';
273                                 $revRate = '-';
274                                 $etats = '-';
275                                 $fetchRate = '-';
276                         }
277                         if ( $deltaPart ) {
278                                 if ( $this->fetchCountLast ) {
279                                         $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
280                                 } else {
281                                         $fetchRatePart = '-';
282                                 }
283                                 $pageRatePart = $this->pageCountPart / $deltaPart;
284                                 $revRatePart = $this->revCountPart / $deltaPart;
286                         } else {
287                                 $fetchRatePart = '-';
288                                 $pageRatePart = '-';
289                                 $revRatePart = '-';
290                         }
291                         $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]",
292                                         $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $fetchRate, $fetchRatePart, $etats, $this->maxCount ) );
293                         $this->lastTime = $nowts;
294                         $this->revCountLast = $this->revCount;
295                         $this->prefetchCountLast = $this->prefetchCount;
296                         $this->fetchCountLast = $this->fetchCount;
297                 }
298         }
300         function setTimeExceeded() {
301                 $this->timeExceeded = True;
302         }
304         function checkIfTimeExceeded() {
305                 if ( $this->maxTimeAllowed &&  ( $this->lastTime - $this->timeOfCheckpoint  > $this->maxTimeAllowed ) ) {
306                         return true;
307                 }
308                 return false;
309         }
311         function finalOptionCheck() {
312                 if ( ( $this->checkpointFiles && ! $this->maxTimeAllowed ) ||
313                         ( $this->maxTimeAllowed && !$this->checkpointFiles ) ) {
314                         throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
315                 }
316                 foreach ( $this->checkpointFiles as $checkpointFile ) {
317                         $count = substr_count ( $checkpointFile, "%s" );
318                         if ( $count != 2 ) {
319                                 throw new MWException( "Option checkpointfile must contain two '%s' for substitution of first and last pageids, count is $count instead, file is $checkpointFile.\n" );
320                         }
321                 }
323                 if ( $this->checkpointFiles ) {
324                         $filenameList = (array)$this->egress->getFilenames();
325                         if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
326                                 throw new MWException( "One checkpointfile must be specified for each output option, if maxtime is used.\n" );
327                         }
328                 }
329         }
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" );
355                                 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
356                         }
357                         $offset += strlen( $chunk );
358                 } while ( $chunk !== false && !feof( $input ) );
359                 if ( $this->maxTimeAllowed ) {
360                         $filenameList = (array)$this->egress->getFilenames();
361                         // we wrote some stuff after last checkpoint that needs renamed
362                         if ( file_exists( $filenameList[0] ) ) {
363                                 $newFilenames = array();
364                                 # we might have just written the header and footer and had no
365                                 # pages or revisions written... perhaps they were all deleted
366                                 # there's no pageID 0 so we use that. the caller is responsible
367                                 # for deciding what to do with a file containing only the
368                                 # siteinfo information and the mw tags.
369                                 if ( ! $this->firstPageWritten ) {
370                                         $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
371                                         $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
372                                 }
373                                 else {
374                                         $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
375                                         $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
376                                 }
377                                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
378                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
379                                         $fileinfo = pathinfo( $filenameList[$i] );
380                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
381                                 }
382                                 $this->egress->closeAndRename( $newFilenames );
383                         }
384                 }
385                 xml_parser_free( $parser );
387                 return true;
388         }
390         /**
391          * Tries to get the revision text for a revision id.
392          *
393          * Upon errors, retries (Up to $this->maxFailures tries each call).
394          * If still no good revision get could be found even after this retrying, "" is returned.
395          * If no good revision text could be returned for
396          * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
397          * is thrown.
398          *
399          * @param $id string The revision id to get the text for
400          *
401          * @return string The revision text for $id, or ""
402          * @throws MWException
403          */
404         function getText( $id ) {
405                 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
406                 $text = false; // The candidate for a good text. false if no proper value.
407                 $failures = 0; // The number of times, this invocation of getText already failed.
409                 static $consecutiveFailedTextRetrievals = 0; // The number of times getText failed without
410                                                              // yielding a good text in between.
412                 $this->fetchCount++;
414                 // To allow to simply return on success and do not have to worry about book keeping,
415                 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
416                 // the old value, so we can restore it, if problems occur (See after the while loop).
417                 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
418                 $consecutiveFailedTextRetrievals = 0;
420                 while ( $failures < $this->maxFailures ) {
422                         // As soon as we found a good text for the $id, we will return immediately.
423                         // Hence, if we make it past the try catch block, we know that we did not
424                         // find a good text.
426                         try {
427                                 // Step 1: Get some text (or reuse from previous iteratuon if checking
428                                 //         for plausibility failed)
430                                 // Trying to get prefetch, if it has not been tried before
431                                 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
432                                         $prefetchNotTried = false;
433                                         $tryIsPrefetch = true;
434                                         $text = $this->prefetch->prefetch( intval( $this->thisPage ),
435                                                 intval( $this->thisRev ) );
436                                         if ( $text === null ) {
437                                                 $text = false;
438                                         }
439                                 }
441                                 if ( $text === false ) {
442                                         // Fallback to asking the database
443                                         $tryIsPrefetch = false;
444                                         if ( $this->spawn ) {
445                                                 $text = $this->getTextSpawned( $id );
446                                         } else {
447                                                 $text = $this->getTextDb( $id );
448                                         }
450                                         // No more checks for texts from DB for now.
451                                         // If we received something that is not false,
452                                         // We treat it as good text, regardless of whether it actually is or is not
453                                         if ( $text !== false ) {
454                                                 return $text;
455                                         }
456                                 }
458                                 if ( $text === false ) {
459                                         throw new MWException( "Generic error while obtaining text for id " . $id );
460                                 }
462                                 // We received a good candidate for the text of $id via some method
464                                 // Step 2: Checking for plausibility and return the text if it is
465                                 //         plausible
466                                 $revID = intval( $this->thisRev );
467                                 if ( ! isset( $this->db ) ) {
468                                         throw new MWException( "No database available" );
469                                 }
470                                 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
471                                 if ( strlen( $text ) == $revLength ) {
472                                         if ( $tryIsPrefetch ) {
473                                                 $this->prefetchCount++;
474                                         }
475                                         return $text;
476                                 }
478                                 $text = false;
479                                 throw new MWException( "Received text is unplausible for id " . $id );
481                         } catch ( Exception $e ) {
482                                 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
483                                 if ( $failures + 1 < $this->maxFailures ) {
484                                         $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
485                                 }
486                                 $this->progress( $msg );
487                         }
489                         // Something went wrong; we did not a text that was plausible :(
490                         $failures++;
492                         // A failure in a prefetch hit does not warrant resetting db connection etc.
493                         if ( ! $tryIsPrefetch ) {
494                                 // After backing off for some time, we try to reboot the whole process as
495                                 // much as possible to not carry over failures from one part to the other
496                                 // parts
497                                 sleep( $this->failureTimeout );
498                                 try {
499                                         $this->rotateDb();
500                                         if ( $this->spawn ) {
501                                                 $this->closeSpawn();
502                                                 $this->openSpawn();
503                                         }
504                                 } catch ( Exception $e ) {
505                                         $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
506                                                 " Trying to continue anyways" );
507                                 }
508                         }
509                 }
511                 // Retirieving a good text for $id failed (at least) maxFailures times.
512                 // We abort for this $id.
514                 // Restoring the consecutive failures, and maybe aborting, if the dump
515                 // is too broken.
516                 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
517                 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
518                         throw new MWException( "Graceful storage failure" );
519                 }
521                 return "";
522         }
525         /**
526          * May throw a database error if, say, the server dies during query.
527          * @param $id
528          * @return bool|string
529          * @throws MWException
530          */
531         private function getTextDb( $id ) {
532                 global $wgContLang;
533                 if ( ! isset( $this->db ) ) {
534                         throw new MWException( __METHOD__ . "No database available" );
535                 }
536                 $row = $this->db->selectRow( 'text',
537                         array( 'old_text', 'old_flags' ),
538                         array( 'old_id' => $id ),
539                         __METHOD__ );
540                 $text = Revision::getRevisionText( $row );
541                 if ( $text === false ) {
542                         return false;
543                 }
544                 $stripped = str_replace( "\r", "", $text );
545                 $normalized = $wgContLang->normalize( $stripped );
546                 return $normalized;
547         }
549         private function getTextSpawned( $id ) {
550                 wfSuppressWarnings();
551                 if ( !$this->spawnProc ) {
552                         // First time?
553                         $this->openSpawn();
554                 }
555                 $text = $this->getTextSpawnedOnce( $id );
556                 wfRestoreWarnings();
557                 return $text;
558         }
560         function openSpawn() {
561                 global $IP;
563                 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
564                         $cmd = implode( " ",
565                                 array_map( 'wfEscapeShellArg',
566                                         array(
567                                                 $this->php,
568                                                 "$IP/../multiversion/MWScript.php",
569                                                 "fetchText.php",
570                                                 '--wiki', wfWikiID() ) ) );
571                 }
572                 else {
573                         $cmd = implode( " ",
574                                 array_map( 'wfEscapeShellArg',
575                                         array(
576                                                 $this->php,
577                                                 "$IP/maintenance/fetchText.php",
578                                                 '--wiki', wfWikiID() ) ) );
579                 }
580                 $spec = array(
581                         0 => array( "pipe", "r" ),
582                         1 => array( "pipe", "w" ),
583                         2 => array( "file", "/dev/null", "a" ) );
584                 $pipes = array();
586                 $this->progress( "Spawning database subprocess: $cmd" );
587                 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
588                 if ( !$this->spawnProc ) {
589                         // shit
590                         $this->progress( "Subprocess spawn failed." );
591                         return false;
592                 }
593                 list(
594                         $this->spawnWrite, // -> stdin
595                         $this->spawnRead,  // <- stdout
596                 ) = $pipes;
598                 return true;
599         }
601         private function closeSpawn() {
602                 wfSuppressWarnings();
603                 if ( $this->spawnRead )
604                         fclose( $this->spawnRead );
605                 $this->spawnRead = false;
606                 if ( $this->spawnWrite )
607                         fclose( $this->spawnWrite );
608                 $this->spawnWrite = false;
609                 if ( $this->spawnErr )
610                         fclose( $this->spawnErr );
611                 $this->spawnErr = false;
612                 if ( $this->spawnProc )
613                         pclose( $this->spawnProc );
614                 $this->spawnProc = false;
615                 wfRestoreWarnings();
616         }
618         private function getTextSpawnedOnce( $id ) {
619                 global $wgContLang;
621                 $ok = fwrite( $this->spawnWrite, "$id\n" );
622                 // $this->progress( ">> $id" );
623                 if ( !$ok ) return false;
625                 $ok = fflush( $this->spawnWrite );
626                 // $this->progress( ">> [flush]" );
627                 if ( !$ok ) return false;
629                 // check that the text id they are sending is the one we asked for
630                 // this avoids out of sync revision text errors we have encountered in the past
631                 $newId = fgets( $this->spawnRead );
632                 if ( $newId === false ) {
633                         return false;
634                 }
635                 if ( $id != intval( $newId ) ) {
636                         return false;
637                 }
639                 $len = fgets( $this->spawnRead );
640                 // $this->progress( "<< " . trim( $len ) );
641                 if ( $len === false ) return false;
643                 $nbytes = intval( $len );
644                 // actual error, not zero-length text
645                 if ( $nbytes < 0 ) return false;
647                 $text = "";
649                 // Subprocess may not send everything at once, we have to loop.
650                 while ( $nbytes > strlen( $text ) ) {
651                         $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
652                         if ( $buffer === false ) break;
653                         $text .= $buffer;
654                 }
656                 $gotbytes = strlen( $text );
657                 if ( $gotbytes != $nbytes ) {
658                         $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
659                         return false;
660                 }
662                 // Do normalization in the dump thread...
663                 $stripped = str_replace( "\r", "", $text );
664                 $normalized = $wgContLang->normalize( $stripped );
665                 return $normalized;
666         }
668         function startElement( $parser, $name, $attribs ) {
669                 $this->checkpointJustWritten = false;
671                 $this->clearOpenElement( null );
672                 $this->lastName = $name;
674                 if ( $name == 'revision' ) {
675                         $this->state = $name;
676                         $this->egress->writeOpenPage( null, $this->buffer );
677                         $this->buffer = "";
678                 } elseif ( $name == 'page' ) {
679                         $this->state = $name;
680                         if ( $this->atStart ) {
681                                 $this->egress->writeOpenStream( $this->buffer );
682                                 $this->buffer = "";
683                                 $this->atStart = false;
684                         }
685                 }
687                 if ( $name == "text" && isset( $attribs['id'] ) ) {
688                         $text = $this->getText( $attribs['id'] );
689                         $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
690                         if ( strlen( $text ) > 0 ) {
691                                 $this->characterData( $parser, $text );
692                         }
693                 } else {
694                         $this->openElement = array( $name, $attribs );
695                 }
696         }
698         function endElement( $parser, $name ) {
699                 $this->checkpointJustWritten = false;
701                 if ( $this->openElement ) {
702                         $this->clearOpenElement( "" );
703                 } else {
704                         $this->buffer .= "</$name>";
705                 }
707                 if ( $name == 'revision' ) {
708                         $this->egress->writeRevision( null, $this->buffer );
709                         $this->buffer = "";
710                         $this->thisRev = "";
711                 } elseif ( $name == 'page' ) {
712                         if ( ! $this->firstPageWritten ) {
713                                 $this->firstPageWritten = trim( $this->thisPage );
714                         }
715                         $this->lastPageWritten = trim( $this->thisPage );
716                         if ( $this->timeExceeded ) {
717                                 $this->egress->writeClosePage( $this->buffer );
718                                 // nasty hack, we can't just write the chardata after the
719                                 // page tag, it will include leading blanks from the next line
720                                 $this->egress->sink->write( "\n" );
722                                 $this->buffer = $this->xmlwriterobj->closeStream();
723                                 $this->egress->writeCloseStream( $this->buffer );
725                                 $this->buffer = "";
726                                 $this->thisPage = "";
727                                 // this could be more than one file if we had more than one output arg
729                                 $filenameList = (array)$this->egress->getFilenames();
730                                 $newFilenames = array();
731                                 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
732                                 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
733                                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
734                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
735                                         $fileinfo = pathinfo( $filenameList[$i] );
736                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
737                                 }
738                                 $this->egress->closeRenameAndReopen( $newFilenames );
739                                 $this->buffer = $this->xmlwriterobj->openStream();
740                                 $this->timeExceeded = false;
741                                 $this->timeOfCheckpoint = $this->lastTime;
742                                 $this->firstPageWritten = false;
743                                 $this->checkpointJustWritten = true;
744                         }
745                         else {
746                                 $this->egress->writeClosePage( $this->buffer );
747                                 $this->buffer = "";
748                                 $this->thisPage = "";
749                         }
751                 } elseif ( $name == 'mediawiki' ) {
752                         $this->egress->writeCloseStream( $this->buffer );
753                         $this->buffer = "";
754                 }
755         }
757         function characterData( $parser, $data ) {
758                 $this->clearOpenElement( null );
759                 if ( $this->lastName == "id" ) {
760                         if ( $this->state == "revision" ) {
761                                 $this->thisRev .= $data;
762                         } elseif ( $this->state == "page" ) {
763                                 $this->thisPage .= $data;
764                         }
765                 }
766                 // have to skip the newline left over from closepagetag line of
767                 // end of checkpoint files. nasty hack!!
768                 if ( $this->checkpointJustWritten ) {
769                         if ( $data[0] == "\n" ) {
770                                 $data = substr( $data, 1 );
771                         }
772                         $this->checkpointJustWritten = false;
773                 }
774                 $this->buffer .= htmlspecialchars( $data );
775         }
777         function clearOpenElement( $style ) {
778                 if ( $this->openElement ) {
779                         $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
780                         $this->openElement = false;
781                 }
782         }