Merge "Minor CSS cleanup for Vector and Monobook skins"
[mediawiki.git] / maintenance / backupTextPass.inc
blobc99f00480c61ad3f27f7465e8f3c22081e2322ad
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' );
146                 }
148                 $this->initProgress( $this->history );
150                 // We are trying to get an initial database connection to avoid that the
151                 // first try of this request's first call to getText fails. However, if
152                 // obtaining a good DB connection fails it's not a serious issue, as
153                 // getText does retry upon failure and can start without having a working
154                 // DB connection.
155                 try {
156                         $this->rotateDb();
157                 } catch ( Exception $e ) {
158                         // We do not even count this as failure. Just let eventual
159                         // watchdogs know.
160                         $this->progress( "Getting initial DB connection failed (" .
161                                 $e->getMessage() . ")" );
162                 }
164                 $this->egress = new ExportProgressFilter( $this->sink, $this );
166                 // it would be nice to do it in the constructor, oh well. need egress set
167                 $this->finalOptionCheck();
169                 // we only want this so we know how to close a stream :-P
170                 $this->xmlwriterobj = new XmlDumpWriter();
172                 $input = fopen( $this->input, "rt" );
173                 $this->readDump( $input );
175                 if ( $this->spawnProc ) {
176                         $this->closeSpawn();
177                 }
179                 $this->report( true );
180         }
182         function processOption( $opt, $val, $param ) {
183                 global $IP;
184                 $url = $this->processFileOpt( $val, $param );
186                 switch( $opt ) {
187                 case 'prefetch':
188                         require_once "$IP/maintenance/backupPrefetch.inc";
189                         $this->prefetch = new BaseDump( $url );
190                         break;
191                 case 'stub':
192                         $this->input = $url;
193                         break;
194                 case 'maxtime':
195                         $this->maxTimeAllowed = intval( $val ) * 60;
196                         break;
197                 case 'checkpointfile':
198                         $this->checkpointFiles[] = $val;
199                         break;
200                 case 'current':
201                         $this->history = WikiExporter::CURRENT;
202                         break;
203                 case 'full':
204                         $this->history = WikiExporter::FULL;
205                         break;
206                 case 'spawn':
207                         $this->spawn = true;
208                         if ( $val ) {
209                                 $this->php = $val;
210                         }
211                         break;
212                 }
213         }
215         function processFileOpt( $val, $param ) {
216                 $fileURIs = explode( ';', $param );
217                 foreach ( $fileURIs as $URI ) {
218                         switch( $val ) {
219                                 case "file":
220                                         $newURI = $URI;
221                                         break;
222                                 case "gzip":
223                                         $newURI = "compress.zlib://$URI";
224                                         break;
225                                 case "bzip2":
226                                         $newURI = "compress.bzip2://$URI";
227                                         break;
228                                 case "7zip":
229                                         $newURI = "mediawiki.compress.7z://$URI";
230                                         break;
231                                 default:
232                                         $newURI = $URI;
233                         }
234                         $newFileURIs[] = $newURI;
235                 }
236                 $val = implode( ';', $newFileURIs );
237                 return $val;
238         }
240         /**
241          * Overridden to include prefetch ratio if enabled.
242          */
243         function showReport() {
244                 if ( !$this->prefetch ) {
245                         parent::showReport();
246                         return;
247                 }
249                 if ( $this->reporting ) {
250                         $now = wfTimestamp( TS_DB );
251                         $nowts = microtime( true );
252                         $deltaAll = $nowts - $this->startTime;
253                         $deltaPart = $nowts - $this->lastTime;
254                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
255                         $this->revCountPart = $this->revCount - $this->revCountLast;
257                         if ( $deltaAll ) {
258                                 $portion = $this->revCount / $this->maxCount;
259                                 $eta = $this->startTime + $deltaAll / $portion;
260                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
261                                 if ( $this->fetchCount ) {
262                                         $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
263                                 } else {
264                                         $fetchRate = '-';
265                                 }
266                                 $pageRate = $this->pageCount / $deltaAll;
267                                 $revRate = $this->revCount / $deltaAll;
268                         } else {
269                                 $pageRate = '-';
270                                 $revRate = '-';
271                                 $etats = '-';
272                                 $fetchRate = '-';
273                         }
274                         if ( $deltaPart ) {
275                                 if ( $this->fetchCountLast ) {
276                                         $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
277                                 } else {
278                                         $fetchRatePart = '-';
279                                 }
280                                 $pageRatePart = $this->pageCountPart / $deltaPart;
281                                 $revRatePart = $this->revCountPart / $deltaPart;
283                         } else {
284                                 $fetchRatePart = '-';
285                                 $pageRatePart = '-';
286                                 $revRatePart = '-';
287                         }
288                         $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]",
289                                         $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $fetchRate, $fetchRatePart, $etats, $this->maxCount ) );
290                         $this->lastTime = $nowts;
291                         $this->revCountLast = $this->revCount;
292                         $this->prefetchCountLast = $this->prefetchCount;
293                         $this->fetchCountLast = $this->fetchCount;
294                 }
295         }
297         function setTimeExceeded() {
298                 $this->timeExceeded = true;
299         }
301         function checkIfTimeExceeded() {
302                 if ( $this->maxTimeAllowed && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed ) ) {
303                         return true;
304                 }
305                 return false;
306         }
308         function finalOptionCheck() {
309                 if ( ( $this->checkpointFiles && ! $this->maxTimeAllowed ) ||
310                         ( $this->maxTimeAllowed && !$this->checkpointFiles ) ) {
311                         throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
312                 }
313                 foreach ( $this->checkpointFiles as $checkpointFile ) {
314                         $count = substr_count ( $checkpointFile, "%s" );
315                         if ( $count != 2 ) {
316                                 throw new MWException( "Option checkpointfile must contain two '%s' for substitution of first and last pageids, count is $count instead, file is $checkpointFile.\n" );
317                         }
318                 }
320                 if ( $this->checkpointFiles ) {
321                         $filenameList = (array)$this->egress->getFilenames();
322                         if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
323                                 throw new MWException( "One checkpointfile must be specified for each output option, if maxtime is used.\n" );
324                         }
325                 }
326         }
328         /**
329          * @throws MWException Failure to parse XML input
330          * @return true
331          */
332         function readDump( $input ) {
333                 $this->buffer = "";
334                 $this->openElement = false;
335                 $this->atStart = true;
336                 $this->state = "";
337                 $this->lastName = "";
338                 $this->thisPage = 0;
339                 $this->thisRev = 0;
341                 $parser = xml_parser_create( "UTF-8" );
342                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
344                 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
345                 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
347                 $offset = 0; // for context extraction on error reporting
348                 $bufferSize = 512 * 1024;
349                 do {
350                         if ( $this->checkIfTimeExceeded() ) {
351                                 $this->setTimeExceeded();
352                         }
353                         $chunk = fread( $input, $bufferSize );
354                         if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
355                                 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
357                                 $byte = xml_get_current_byte_index( $parser );
358                                 $msg = wfMessage( 'xml-error-string',
359                                         'XML import parse failure',
360                                         xml_get_current_line_number( $parser ),
361                                         xml_get_current_column_number( $parser ),
362                                         $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte -$offset, 16 ) . '"' ) ),
363                                         xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
365                                 xml_parser_free( $parser );
367                                 throw new MWException( $msg );
368                         }
369                         $offset += strlen( $chunk );
370                 } while ( $chunk !== false && !feof( $input ) );
371                 if ( $this->maxTimeAllowed ) {
372                         $filenameList = (array)$this->egress->getFilenames();
373                         // we wrote some stuff after last checkpoint that needs renamed
374                         if ( file_exists( $filenameList[0] ) ) {
375                                 $newFilenames = array();
376                                 # we might have just written the header and footer and had no
377                                 # pages or revisions written... perhaps they were all deleted
378                                 # there's no pageID 0 so we use that. the caller is responsible
379                                 # for deciding what to do with a file containing only the
380                                 # siteinfo information and the mw tags.
381                                 if ( ! $this->firstPageWritten ) {
382                                         $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
383                                         $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
384                                 }
385                                 else {
386                                         $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
387                                         $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
388                                 }
389                                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
390                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
391                                         $fileinfo = pathinfo( $filenameList[$i] );
392                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
393                                 }
394                                 $this->egress->closeAndRename( $newFilenames );
395                         }
396                 }
397                 xml_parser_free( $parser );
399                 return true;
400         }
402         /**
403          * Tries to get the revision text for a revision id.
404          *
405          * Upon errors, retries (Up to $this->maxFailures tries each call).
406          * If still no good revision get could be found even after this retrying, "" is returned.
407          * If no good revision text could be returned for
408          * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
409          * is thrown.
410          *
411          * @param $id string The revision id to get the text for
412          *
413          * @return string The revision text for $id, or ""
414          * @throws MWException
415          */
416         function getText( $id ) {
417                 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
418                 $text = false; // The candidate for a good text. false if no proper value.
419                 $failures = 0; // The number of times, this invocation of getText already failed.
421                 static $consecutiveFailedTextRetrievals = 0; // The number of times getText failed without
422                                                              // yielding a good text in between.
424                 $this->fetchCount++;
426                 // To allow to simply return on success and do not have to worry about book keeping,
427                 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
428                 // the old value, so we can restore it, if problems occur (See after the while loop).
429                 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
430                 $consecutiveFailedTextRetrievals = 0;
432                 while ( $failures < $this->maxFailures ) {
434                         // As soon as we found a good text for the $id, we will return immediately.
435                         // Hence, if we make it past the try catch block, we know that we did not
436                         // find a good text.
438                         try {
439                                 // Step 1: Get some text (or reuse from previous iteratuon if checking
440                                 //         for plausibility failed)
442                                 // Trying to get prefetch, if it has not been tried before
443                                 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
444                                         $prefetchNotTried = false;
445                                         $tryIsPrefetch = true;
446                                         $text = $this->prefetch->prefetch( intval( $this->thisPage ),
447                                                 intval( $this->thisRev ) );
448                                         if ( $text === null ) {
449                                                 $text = false;
450                                         }
451                                 }
453                                 if ( $text === false ) {
454                                         // Fallback to asking the database
455                                         $tryIsPrefetch = false;
456                                         if ( $this->spawn ) {
457                                                 $text = $this->getTextSpawned( $id );
458                                         } else {
459                                                 $text = $this->getTextDb( $id );
460                                         }
462                                         // No more checks for texts from DB for now.
463                                         // If we received something that is not false,
464                                         // We treat it as good text, regardless of whether it actually is or is not
465                                         if ( $text !== false ) {
466                                                 return $text;
467                                         }
468                                 }
470                                 if ( $text === false ) {
471                                         throw new MWException( "Generic error while obtaining text for id " . $id );
472                                 }
474                                 // We received a good candidate for the text of $id via some method
476                                 // Step 2: Checking for plausibility and return the text if it is
477                                 //         plausible
478                                 $revID = intval( $this->thisRev );
479                                 if ( ! isset( $this->db ) ) {
480                                         throw new MWException( "No database available" );
481                                 }
482                                 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
483                                 if ( strlen( $text ) == $revLength ) {
484                                         if ( $tryIsPrefetch ) {
485                                                 $this->prefetchCount++;
486                                         }
487                                         return $text;
488                                 }
490                                 $text = false;
491                                 throw new MWException( "Received text is unplausible for id " . $id );
493                         } catch ( Exception $e ) {
494                                 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
495                                 if ( $failures + 1 < $this->maxFailures ) {
496                                         $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
497                                 }
498                                 $this->progress( $msg );
499                         }
501                         // Something went wrong; we did not a text that was plausible :(
502                         $failures++;
504                         // A failure in a prefetch hit does not warrant resetting db connection etc.
505                         if ( ! $tryIsPrefetch ) {
506                                 // After backing off for some time, we try to reboot the whole process as
507                                 // much as possible to not carry over failures from one part to the other
508                                 // parts
509                                 sleep( $this->failureTimeout );
510                                 try {
511                                         $this->rotateDb();
512                                         if ( $this->spawn ) {
513                                                 $this->closeSpawn();
514                                                 $this->openSpawn();
515                                         }
516                                 } catch ( Exception $e ) {
517                                         $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
518                                                 " Trying to continue anyways" );
519                                 }
520                         }
521                 }
523                 // Retirieving a good text for $id failed (at least) maxFailures times.
524                 // We abort for this $id.
526                 // Restoring the consecutive failures, and maybe aborting, if the dump
527                 // is too broken.
528                 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
529                 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
530                         throw new MWException( "Graceful storage failure" );
531                 }
533                 return "";
534         }
537         /**
538          * May throw a database error if, say, the server dies during query.
539          * @param $id
540          * @return bool|string
541          * @throws MWException
542          */
543         private function getTextDb( $id ) {
544                 global $wgContLang;
545                 if ( ! isset( $this->db ) ) {
546                         throw new MWException( __METHOD__ . "No database available" );
547                 }
548                 $row = $this->db->selectRow( 'text',
549                         array( 'old_text', 'old_flags' ),
550                         array( 'old_id' => $id ),
551                         __METHOD__ );
552                 $text = Revision::getRevisionText( $row );
553                 if ( $text === false ) {
554                         return false;
555                 }
556                 $stripped = str_replace( "\r", "", $text );
557                 $normalized = $wgContLang->normalize( $stripped );
558                 return $normalized;
559         }
561         private function getTextSpawned( $id ) {
562                 wfSuppressWarnings();
563                 if ( !$this->spawnProc ) {
564                         // First time?
565                         $this->openSpawn();
566                 }
567                 $text = $this->getTextSpawnedOnce( $id );
568                 wfRestoreWarnings();
569                 return $text;
570         }
572         function openSpawn() {
573                 global $IP;
575                 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
576                         $cmd = implode( " ",
577                                 array_map( 'wfEscapeShellArg',
578                                         array(
579                                                 $this->php,
580                                                 "$IP/../multiversion/MWScript.php",
581                                                 "fetchText.php",
582                                                 '--wiki', wfWikiID() ) ) );
583                 }
584                 else {
585                         $cmd = implode( " ",
586                                 array_map( 'wfEscapeShellArg',
587                                         array(
588                                                 $this->php,
589                                                 "$IP/maintenance/fetchText.php",
590                                                 '--wiki', wfWikiID() ) ) );
591                 }
592                 $spec = array(
593                         0 => array( "pipe", "r" ),
594                         1 => array( "pipe", "w" ),
595                         2 => array( "file", "/dev/null", "a" ) );
596                 $pipes = array();
598                 $this->progress( "Spawning database subprocess: $cmd" );
599                 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
600                 if ( !$this->spawnProc ) {
601                         // shit
602                         $this->progress( "Subprocess spawn failed." );
603                         return false;
604                 }
605                 list(
606                         $this->spawnWrite, // -> stdin
607                         $this->spawnRead,  // <- stdout
608                 ) = $pipes;
610                 return true;
611         }
613         private function closeSpawn() {
614                 wfSuppressWarnings();
615                 if ( $this->spawnRead ) {
616                         fclose( $this->spawnRead );
617                 }
618                 $this->spawnRead = false;
619                 if ( $this->spawnWrite ) {
620                         fclose( $this->spawnWrite );
621                 }
622                 $this->spawnWrite = false;
623                 if ( $this->spawnErr ) {
624                         fclose( $this->spawnErr );
625                 }
626                 $this->spawnErr = false;
627                 if ( $this->spawnProc ) {
628                         pclose( $this->spawnProc );
629                 }
630                 $this->spawnProc = false;
631                 wfRestoreWarnings();
632         }
634         private function getTextSpawnedOnce( $id ) {
635                 global $wgContLang;
637                 $ok = fwrite( $this->spawnWrite, "$id\n" );
638                 // $this->progress( ">> $id" );
639                 if ( !$ok ) {
640                         return false;
641                 }
643                 $ok = fflush( $this->spawnWrite );
644                 // $this->progress( ">> [flush]" );
645                 if ( !$ok ) {
646                         return false;
647                 }
649                 // check that the text id they are sending is the one we asked for
650                 // this avoids out of sync revision text errors we have encountered in the past
651                 $newId = fgets( $this->spawnRead );
652                 if ( $newId === false ) {
653                         return false;
654                 }
655                 if ( $id != intval( $newId ) ) {
656                         return false;
657                 }
659                 $len = fgets( $this->spawnRead );
660                 // $this->progress( "<< " . trim( $len ) );
661                 if ( $len === false ) {
662                         return false;
663                 }
665                 $nbytes = intval( $len );
666                 // actual error, not zero-length text
667                 if ( $nbytes < 0 ) {
668                         return false;
669                 }
671                 $text = "";
673                 // Subprocess may not send everything at once, we have to loop.
674                 while ( $nbytes > strlen( $text ) ) {
675                         $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
676                         if ( $buffer === false ) {
677                                 break;
678                         }
679                         $text .= $buffer;
680                 }
682                 $gotbytes = strlen( $text );
683                 if ( $gotbytes != $nbytes ) {
684                         $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
685                         return false;
686                 }
688                 // Do normalization in the dump thread...
689                 $stripped = str_replace( "\r", "", $text );
690                 $normalized = $wgContLang->normalize( $stripped );
691                 return $normalized;
692         }
694         function startElement( $parser, $name, $attribs ) {
695                 $this->checkpointJustWritten = false;
697                 $this->clearOpenElement( null );
698                 $this->lastName = $name;
700                 if ( $name == 'revision' ) {
701                         $this->state = $name;
702                         $this->egress->writeOpenPage( null, $this->buffer );
703                         $this->buffer = "";
704                 } elseif ( $name == 'page' ) {
705                         $this->state = $name;
706                         if ( $this->atStart ) {
707                                 $this->egress->writeOpenStream( $this->buffer );
708                                 $this->buffer = "";
709                                 $this->atStart = false;
710                         }
711                 }
713                 if ( $name == "text" && isset( $attribs['id'] ) ) {
714                         $text = $this->getText( $attribs['id'] );
715                         $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
716                         if ( strlen( $text ) > 0 ) {
717                                 $this->characterData( $parser, $text );
718                         }
719                 } else {
720                         $this->openElement = array( $name, $attribs );
721                 }
722         }
724         function endElement( $parser, $name ) {
725                 $this->checkpointJustWritten = false;
727                 if ( $this->openElement ) {
728                         $this->clearOpenElement( "" );
729                 } else {
730                         $this->buffer .= "</$name>";
731                 }
733                 if ( $name == 'revision' ) {
734                         $this->egress->writeRevision( null, $this->buffer );
735                         $this->buffer = "";
736                         $this->thisRev = "";
737                 } elseif ( $name == 'page' ) {
738                         if ( ! $this->firstPageWritten ) {
739                                 $this->firstPageWritten = trim( $this->thisPage );
740                         }
741                         $this->lastPageWritten = trim( $this->thisPage );
742                         if ( $this->timeExceeded ) {
743                                 $this->egress->writeClosePage( $this->buffer );
744                                 // nasty hack, we can't just write the chardata after the
745                                 // page tag, it will include leading blanks from the next line
746                                 $this->egress->sink->write( "\n" );
748                                 $this->buffer = $this->xmlwriterobj->closeStream();
749                                 $this->egress->writeCloseStream( $this->buffer );
751                                 $this->buffer = "";
752                                 $this->thisPage = "";
753                                 // this could be more than one file if we had more than one output arg
755                                 $filenameList = (array)$this->egress->getFilenames();
756                                 $newFilenames = array();
757                                 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
758                                 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
759                                 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
760                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
761                                         $fileinfo = pathinfo( $filenameList[$i] );
762                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
763                                 }
764                                 $this->egress->closeRenameAndReopen( $newFilenames );
765                                 $this->buffer = $this->xmlwriterobj->openStream();
766                                 $this->timeExceeded = false;
767                                 $this->timeOfCheckpoint = $this->lastTime;
768                                 $this->firstPageWritten = false;
769                                 $this->checkpointJustWritten = true;
770                         }
771                         else {
772                                 $this->egress->writeClosePage( $this->buffer );
773                                 $this->buffer = "";
774                                 $this->thisPage = "";
775                         }
777                 } elseif ( $name == 'mediawiki' ) {
778                         $this->egress->writeCloseStream( $this->buffer );
779                         $this->buffer = "";
780                 }
781         }
783         function characterData( $parser, $data ) {
784                 $this->clearOpenElement( null );
785                 if ( $this->lastName == "id" ) {
786                         if ( $this->state == "revision" ) {
787                                 $this->thisRev .= $data;
788                         } elseif ( $this->state == "page" ) {
789                                 $this->thisPage .= $data;
790                         }
791                 }
792                 // have to skip the newline left over from closepagetag line of
793                 // end of checkpoint files. nasty hack!!
794                 if ( $this->checkpointJustWritten ) {
795                         if ( $data[0] == "\n" ) {
796                                 $data = substr( $data, 1 );
797                         }
798                         $this->checkpointJustWritten = false;
799                 }
800                 $this->buffer .= htmlspecialchars( $data );
801         }
803         function clearOpenElement( $style ) {
804                 if ( $this->openElement ) {
805                         $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
806                         $this->openElement = false;
807                 }
808         }