Make Sanitizer::removeHTMLtags() and ::removeHTMLComments public
[mediawiki.git] / maintenance / backupTextPass.inc
blob85ebd51bfecf75fb3070eb3a9c9207ecd81b2f48
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  * https://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         public $prefetch = null;
35         // when we spend more than maxTimeAllowed seconds on this run, we continue
36         // processing until we write out the next complete page, then save output file(s),
37         // rename it/them and open new one(s)
38         public $maxTimeAllowed = 0; // 0 = no limit
40         protected $input = "php://stdin";
41         protected $history = WikiExporter::FULL;
42         protected $fetchCount = 0;
43         protected $prefetchCount = 0;
44         protected $prefetchCountLast = 0;
45         protected $fetchCountLast = 0;
47         protected $maxFailures = 5;
48         protected $maxConsecutiveFailedTextRetrievals = 200;
49         protected $failureTimeout = 5; // Seconds to sleep after db failure
51         protected $php = "php";
52         protected $spawn = false;
54         /**
55          * @var bool|resource
56          */
57         protected $spawnProc = false;
59         /**
60          * @var bool|resource
61          */
62         protected $spawnWrite = false;
64         /**
65          * @var bool|resource
66          */
67         protected $spawnRead = false;
69         /**
70          * @var bool|resource
71          */
72         protected $spawnErr = false;
74         protected $xmlwriterobj = false;
76         protected $timeExceeded = false;
77         protected $firstPageWritten = false;
78         protected $lastPageWritten = false;
79         protected $checkpointJustWritten = false;
80         protected $checkpointFiles = array();
82         /**
83          * @var DatabaseBase
84          */
85         protected $db;
87         /**
88          * Drop the database connection $this->db and try to get a new one.
89          *
90          * This function tries to get a /different/ connection if this is
91          * possible. Hence, (if this is possible) it switches to a different
92          * failover upon each call.
93          *
94          * This function resets $this->lb and closes all connections on it.
95          *
96          * @throws MWException
97          */
98         function rotateDb() {
99                 // Cleaning up old connections
100                 if ( isset( $this->lb ) ) {
101                         $this->lb->closeAll();
102                         unset( $this->lb );
103                 }
105                 if ( $this->forcedDb !== null ) {
106                         $this->db = $this->forcedDb;
108                         return;
109                 }
111                 if ( isset( $this->db ) && $this->db->isOpen() ) {
112                         throw new MWException( 'DB is set and has not been closed by the Load Balancer' );
113                 }
115                 unset( $this->db );
117                 // Trying to set up new connection.
118                 // We do /not/ retry upon failure, but delegate to encapsulating logic, to avoid
119                 // individually retrying at different layers of code.
121                 // 1. The LoadBalancer.
122                 try {
123                         $this->lb = wfGetLBFactory()->newMainLB();
124                 } catch ( Exception $e ) {
125                         throw new MWException( __METHOD__
126                                 . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
127                 }
129                 // 2. The Connection, through the load balancer.
130                 try {
131                         $this->db = $this->lb->getConnection( DB_SLAVE, 'dump' );
132                 } catch ( Exception $e ) {
133                         throw new MWException( __METHOD__
134                                 . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
135                 }
136         }
138         function initProgress( $history = WikiExporter::FULL ) {
139                 parent::initProgress();
140                 $this->timeOfCheckpoint = $this->startTime;
141         }
143         function dump( $history, $text = WikiExporter::TEXT ) {
144                 // Notice messages will foul up your XML output even if they're
145                 // relatively harmless.
146                 if ( ini_get( 'display_errors' ) ) {
147                         ini_set( 'display_errors', 'stderr' );
148                 }
150                 $this->initProgress( $this->history );
152                 // We are trying to get an initial database connection to avoid that the
153                 // first try of this request's first call to getText fails. However, if
154                 // obtaining a good DB connection fails it's not a serious issue, as
155                 // getText does retry upon failure and can start without having a working
156                 // DB connection.
157                 try {
158                         $this->rotateDb();
159                 } catch ( Exception $e ) {
160                         // We do not even count this as failure. Just let eventual
161                         // watchdogs know.
162                         $this->progress( "Getting initial DB connection failed (" .
163                                 $e->getMessage() . ")" );
164                 }
166                 $this->egress = new ExportProgressFilter( $this->sink, $this );
168                 // it would be nice to do it in the constructor, oh well. need egress set
169                 $this->finalOptionCheck();
171                 // we only want this so we know how to close a stream :-P
172                 $this->xmlwriterobj = new XmlDumpWriter();
174                 $input = fopen( $this->input, "rt" );
175                 $this->readDump( $input );
177                 if ( $this->spawnProc ) {
178                         $this->closeSpawn();
179                 }
181                 $this->report( true );
182         }
184         function processOption( $opt, $val, $param ) {
185                 global $IP;
186                 $url = $this->processFileOpt( $val, $param );
188                 switch ( $opt ) {
189                         case 'prefetch':
190                                 require_once "$IP/maintenance/backupPrefetch.inc";
191                                 $this->prefetch = new BaseDump( $url );
192                                 break;
193                         case 'stub':
194                                 $this->input = $url;
195                                 break;
196                         case 'maxtime':
197                                 $this->maxTimeAllowed = intval( $val ) * 60;
198                                 break;
199                         case 'checkpointfile':
200                                 $this->checkpointFiles[] = $val;
201                                 break;
202                         case 'current':
203                                 $this->history = WikiExporter::CURRENT;
204                                 break;
205                         case 'full':
206                                 $this->history = WikiExporter::FULL;
207                                 break;
208                         case 'spawn':
209                                 $this->spawn = true;
210                                 if ( $val ) {
211                                         $this->php = $val;
212                                 }
213                                 break;
214                 }
215         }
217         function processFileOpt( $val, $param ) {
218                 $fileURIs = explode( ';', $param );
219                 foreach ( $fileURIs as $URI ) {
220                         switch ( $val ) {
221                                 case "file":
222                                         $newURI = $URI;
223                                         break;
224                                 case "gzip":
225                                         $newURI = "compress.zlib://$URI";
226                                         break;
227                                 case "bzip2":
228                                         $newURI = "compress.bzip2://$URI";
229                                         break;
230                                 case "7zip":
231                                         $newURI = "mediawiki.compress.7z://$URI";
232                                         break;
233                                 default:
234                                         $newURI = $URI;
235                         }
236                         $newFileURIs[] = $newURI;
237                 }
238                 $val = implode( ';', $newFileURIs );
240                 return $val;
241         }
243         /**
244          * Overridden to include prefetch ratio if enabled.
245          */
246         function showReport() {
247                 if ( !$this->prefetch ) {
248                         parent::showReport();
250                         return;
251                 }
253                 if ( $this->reporting ) {
254                         $now = wfTimestamp( TS_DB );
255                         $nowts = microtime( true );
256                         $deltaAll = $nowts - $this->startTime;
257                         $deltaPart = $nowts - $this->lastTime;
258                         $this->pageCountPart = $this->pageCount - $this->pageCountLast;
259                         $this->revCountPart = $this->revCount - $this->revCountLast;
261                         if ( $deltaAll ) {
262                                 $portion = $this->revCount / $this->maxCount;
263                                 $eta = $this->startTime + $deltaAll / $portion;
264                                 $etats = wfTimestamp( TS_DB, intval( $eta ) );
265                                 if ( $this->fetchCount ) {
266                                         $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
267                                 } else {
268                                         $fetchRate = '-';
269                                 }
270                                 $pageRate = $this->pageCount / $deltaAll;
271                                 $revRate = $this->revCount / $deltaAll;
272                         } else {
273                                 $pageRate = '-';
274                                 $revRate = '-';
275                                 $etats = '-';
276                                 $fetchRate = '-';
277                         }
278                         if ( $deltaPart ) {
279                                 if ( $this->fetchCountLast ) {
280                                         $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
281                                 } else {
282                                         $fetchRatePart = '-';
283                                 }
284                                 $pageRatePart = $this->pageCountPart / $deltaPart;
285                                 $revRatePart = $this->revCountPart / $deltaPart;
286                         } else {
287                                 $fetchRatePart = '-';
288                                 $pageRatePart = '-';
289                                 $revRatePart = '-';
290                         }
291                         $this->progress( sprintf(
292                                 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
293                                         . "%d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% "
294                                         . "prefetched (all|curr), ETA %s [max %d]",
295                                 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate,
296                                 $pageRatePart, $this->revCount, $revRate, $revRatePart,
297                                 $fetchRate, $fetchRatePart, $etats, $this->maxCount
298                         ) );
299                         $this->lastTime = $nowts;
300                         $this->revCountLast = $this->revCount;
301                         $this->prefetchCountLast = $this->prefetchCount;
302                         $this->fetchCountLast = $this->fetchCount;
303                 }
304         }
306         function setTimeExceeded() {
307                 $this->timeExceeded = true;
308         }
310         function checkIfTimeExceeded() {
311                 if ( $this->maxTimeAllowed
312                         && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed )
313                 ) {
314                         return true;
315                 }
317                 return false;
318         }
320         function finalOptionCheck() {
321                 if ( ( $this->checkpointFiles && !$this->maxTimeAllowed )
322                         || ( $this->maxTimeAllowed && !$this->checkpointFiles )
323                 ) {
324                         throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
325                 }
326                 foreach ( $this->checkpointFiles as $checkpointFile ) {
327                         $count = substr_count( $checkpointFile, "%s" );
328                         if ( $count != 2 ) {
329                                 throw new MWException( "Option checkpointfile must contain two '%s' "
330                                         . "for substitution of first and last pageids, count is $count instead, "
331                                         . "file is $checkpointFile.\n" );
332                         }
333                 }
335                 if ( $this->checkpointFiles ) {
336                         $filenameList = (array)$this->egress->getFilenames();
337                         if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
338                                 throw new MWException( "One checkpointfile must be specified "
339                                         . "for each output option, if maxtime is used.\n" );
340                         }
341                 }
342         }
344         /**
345          * @throws MWException Failure to parse XML input
346          * @param string $input
347          * @return bool
348          */
349         function readDump( $input ) {
350                 $this->buffer = "";
351                 $this->openElement = false;
352                 $this->atStart = true;
353                 $this->state = "";
354                 $this->lastName = "";
355                 $this->thisPage = 0;
356                 $this->thisRev = 0;
357                 $this->thisRevModel = null;
358                 $this->thisRevFormat = null;
360                 $parser = xml_parser_create( "UTF-8" );
361                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
363                 xml_set_element_handler(
364                         $parser,
365                         array( &$this, 'startElement' ),
366                         array( &$this, 'endElement' )
367                 );
368                 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
370                 $offset = 0; // for context extraction on error reporting
371                 $bufferSize = 512 * 1024;
372                 do {
373                         if ( $this->checkIfTimeExceeded() ) {
374                                 $this->setTimeExceeded();
375                         }
376                         $chunk = fread( $input, $bufferSize );
377                         if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
378                                 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
380                                 $byte = xml_get_current_byte_index( $parser );
381                                 $msg = wfMessage( 'xml-error-string',
382                                         'XML import parse failure',
383                                         xml_get_current_line_number( $parser ),
384                                         xml_get_current_column_number( $parser ),
385                                         $byte . ( is_null( $chunk ) ? null : ( '; "' . substr( $chunk, $byte - $offset, 16 ) . '"' ) ),
386                                         xml_error_string( xml_get_error_code( $parser ) ) )->escaped();
388                                 xml_parser_free( $parser );
390                                 throw new MWException( $msg );
391                         }
392                         $offset += strlen( $chunk );
393                 } while ( $chunk !== false && !feof( $input ) );
394                 if ( $this->maxTimeAllowed ) {
395                         $filenameList = (array)$this->egress->getFilenames();
396                         // we wrote some stuff after last checkpoint that needs renamed
397                         if ( file_exists( $filenameList[0] ) ) {
398                                 $newFilenames = array();
399                                 # we might have just written the header and footer and had no
400                                 # pages or revisions written... perhaps they were all deleted
401                                 # there's no pageID 0 so we use that. the caller is responsible
402                                 # for deciding what to do with a file containing only the
403                                 # siteinfo information and the mw tags.
404                                 if ( !$this->firstPageWritten ) {
405                                         $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
406                                         $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
407                                 } else {
408                                         $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
409                                         $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
410                                 }
412                                 $filenameCount = count( $filenameList );
413                                 for ( $i = 0; $i < $filenameCount; $i++ ) {
414                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
415                                         $fileinfo = pathinfo( $filenameList[$i] );
416                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
417                                 }
418                                 $this->egress->closeAndRename( $newFilenames );
419                         }
420                 }
421                 xml_parser_free( $parser );
423                 return true;
424         }
426         /**
427          * Applies applicable export transformations to $text.
428          *
429          * @param string $text
430          * @param string $model
431          * @param string|null $format
432          *
433          * @return string
434          */
435         private function exportTransform( $text, $model, $format = null ) {
436                 try {
437                         $handler = ContentHandler::getForModelID( $model );
438                         $text = $handler->exportTransform( $text, $format );
439                 }
440                 catch ( MWException $ex ) {
441                         $this->progress(
442                                 "Unable to apply export transformation for content model '$model': " .
443                                 $ex->getMessage()
444                         );
445                 }
447                 return $text;
448         }
450         /**
451          * Tries to get the revision text for a revision id.
452          * Export transformations are applied if the content model can is given or can be
453          * determined from the database.
454          *
455          * Upon errors, retries (Up to $this->maxFailures tries each call).
456          * If still no good revision get could be found even after this retrying, "" is returned.
457          * If no good revision text could be returned for
458          * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
459          * is thrown.
460          *
461          * @param string $id The revision id to get the text for
462          * @param string|bool|null $model The content model used to determine applicable export transformations.
463          *      If $model is null, it will be determined from the database.
464          * @param string|null $format The content format used when applying export transformations.
465          *
466          * @throws MWException
467          * @return string The revision text for $id, or ""
468          */
469         function getText( $id, $model = null, $format = null ) {
470                 global $wgContentHandlerUseDB;
472                 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
473                 $text = false; // The candidate for a good text. false if no proper value.
474                 $failures = 0; // The number of times, this invocation of getText already failed.
476                 // The number of times getText failed without yielding a good text in between.
477                 static $consecutiveFailedTextRetrievals = 0;
479                 $this->fetchCount++;
481                 // To allow to simply return on success and do not have to worry about book keeping,
482                 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
483                 // the old value, so we can restore it, if problems occur (See after the while loop).
484                 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
485                 $consecutiveFailedTextRetrievals = 0;
487                 if ( $model === null && $wgContentHandlerUseDB ) {
488                         $row = $this->db->selectRow(
489                                 'revision',
490                                 array( 'rev_content_model', 'rev_content_format' ),
491                                 array( 'rev_id' => $this->thisRev ),
492                                 __METHOD__
493                         );
495                         if ( $row ) {
496                                 $model = $row->rev_content_model;
497                                 $format = $row->rev_content_format;
498                         }
499                 }
501                 if ( $model === null || $model === '' ) {
502                         $model = false;
503                 }
505                 while ( $failures < $this->maxFailures ) {
507                         // As soon as we found a good text for the $id, we will return immediately.
508                         // Hence, if we make it past the try catch block, we know that we did not
509                         // find a good text.
511                         try {
512                                 // Step 1: Get some text (or reuse from previous iteratuon if checking
513                                 //         for plausibility failed)
515                                 // Trying to get prefetch, if it has not been tried before
516                                 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
517                                         $prefetchNotTried = false;
518                                         $tryIsPrefetch = true;
519                                         $text = $this->prefetch->prefetch( intval( $this->thisPage ),
520                                                 intval( $this->thisRev ) );
522                                         if ( $text === null ) {
523                                                 $text = false;
524                                         }
526                                         if ( is_string( $text ) && $model !== false ) {
527                                                 // Apply export transformation to text coming from an old dump.
528                                                 // The purpose of this transformation is to convert up from legacy
529                                                 // formats, which may still be used in the older dump that is used
530                                                 // for pre-fetching. Applying the transformation again should not
531                                                 // interfere with content that is already in the correct form.
532                                                 $text = $this->exportTransform( $text, $model, $format );
533                                         }
534                                 }
536                                 if ( $text === false ) {
537                                         // Fallback to asking the database
538                                         $tryIsPrefetch = false;
539                                         if ( $this->spawn ) {
540                                                 $text = $this->getTextSpawned( $id );
541                                         } else {
542                                                 $text = $this->getTextDb( $id );
543                                         }
545                                         if ( $text !== false && $model !== false ) {
546                                                 // Apply export transformation to text coming from the database.
547                                                 // Prefetched text should already have transformations applied.
548                                                 $text = $this->exportTransform( $text, $model, $format );
549                                         }
551                                         // No more checks for texts from DB for now.
552                                         // If we received something that is not false,
553                                         // We treat it as good text, regardless of whether it actually is or is not
554                                         if ( $text !== false ) {
555                                                 return $text;
556                                         }
557                                 }
559                                 if ( $text === false ) {
560                                         throw new MWException( "Generic error while obtaining text for id " . $id );
561                                 }
563                                 // We received a good candidate for the text of $id via some method
565                                 // Step 2: Checking for plausibility and return the text if it is
566                                 //         plausible
567                                 $revID = intval( $this->thisRev );
568                                 if ( !isset( $this->db ) ) {
569                                         throw new MWException( "No database available" );
570                                 }
572                                 if ( $model !== CONTENT_MODEL_WIKITEXT ) {
573                                         $revLength = strlen( $text );
574                                 } else {
575                                         $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
576                                 }
578                                 if ( strlen( $text ) == $revLength ) {
579                                         if ( $tryIsPrefetch ) {
580                                                 $this->prefetchCount++;
581                                         }
583                                         return $text;
584                                 }
586                                 $text = false;
587                                 throw new MWException( "Received text is unplausible for id " . $id );
588                         } catch ( Exception $e ) {
589                                 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
590                                 if ( $failures + 1 < $this->maxFailures ) {
591                                         $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
592                                 }
593                                 $this->progress( $msg );
594                         }
596                         // Something went wrong; we did not a text that was plausible :(
597                         $failures++;
599                         // A failure in a prefetch hit does not warrant resetting db connection etc.
600                         if ( !$tryIsPrefetch ) {
601                                 // After backing off for some time, we try to reboot the whole process as
602                                 // much as possible to not carry over failures from one part to the other
603                                 // parts
604                                 sleep( $this->failureTimeout );
605                                 try {
606                                         $this->rotateDb();
607                                         if ( $this->spawn ) {
608                                                 $this->closeSpawn();
609                                                 $this->openSpawn();
610                                         }
611                                 } catch ( Exception $e ) {
612                                         $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
613                                                 " Trying to continue anyways" );
614                                 }
615                         }
616                 }
618                 // Retirieving a good text for $id failed (at least) maxFailures times.
619                 // We abort for this $id.
621                 // Restoring the consecutive failures, and maybe aborting, if the dump
622                 // is too broken.
623                 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
624                 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
625                         throw new MWException( "Graceful storage failure" );
626                 }
628                 return "";
629         }
631         /**
632          * May throw a database error if, say, the server dies during query.
633          * @param int $id
634          * @return bool|string
635          * @throws MWException
636          */
637         private function getTextDb( $id ) {
638                 global $wgContLang;
639                 if ( !isset( $this->db ) ) {
640                         throw new MWException( __METHOD__ . "No database available" );
641                 }
642                 $row = $this->db->selectRow( 'text',
643                         array( 'old_text', 'old_flags' ),
644                         array( 'old_id' => $id ),
645                         __METHOD__ );
646                 $text = Revision::getRevisionText( $row );
647                 if ( $text === false ) {
648                         return false;
649                 }
650                 $stripped = str_replace( "\r", "", $text );
651                 $normalized = $wgContLang->normalize( $stripped );
653                 return $normalized;
654         }
656         private function getTextSpawned( $id ) {
657                 wfSuppressWarnings();
658                 if ( !$this->spawnProc ) {
659                         // First time?
660                         $this->openSpawn();
661                 }
662                 $text = $this->getTextSpawnedOnce( $id );
663                 wfRestoreWarnings();
665                 return $text;
666         }
668         function openSpawn() {
669                 global $IP;
671                 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
672                         $cmd = implode( " ",
673                                 array_map( 'wfEscapeShellArg',
674                                         array(
675                                                 $this->php,
676                                                 "$IP/../multiversion/MWScript.php",
677                                                 "fetchText.php",
678                                                 '--wiki', wfWikiID() ) ) );
679                 } else {
680                         $cmd = implode( " ",
681                                 array_map( 'wfEscapeShellArg',
682                                         array(
683                                                 $this->php,
684                                                 "$IP/maintenance/fetchText.php",
685                                                 '--wiki', wfWikiID() ) ) );
686                 }
687                 $spec = array(
688                         0 => array( "pipe", "r" ),
689                         1 => array( "pipe", "w" ),
690                         2 => array( "file", "/dev/null", "a" ) );
691                 $pipes = array();
693                 $this->progress( "Spawning database subprocess: $cmd" );
694                 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
695                 if ( !$this->spawnProc ) {
696                         // shit
697                         $this->progress( "Subprocess spawn failed." );
699                         return false;
700                 }
701                 list(
702                         $this->spawnWrite, // -> stdin
703                         $this->spawnRead, // <- stdout
704                 ) = $pipes;
706                 return true;
707         }
709         private function closeSpawn() {
710                 wfSuppressWarnings();
711                 if ( $this->spawnRead ) {
712                         fclose( $this->spawnRead );
713                 }
714                 $this->spawnRead = false;
715                 if ( $this->spawnWrite ) {
716                         fclose( $this->spawnWrite );
717                 }
718                 $this->spawnWrite = false;
719                 if ( $this->spawnErr ) {
720                         fclose( $this->spawnErr );
721                 }
722                 $this->spawnErr = false;
723                 if ( $this->spawnProc ) {
724                         pclose( $this->spawnProc );
725                 }
726                 $this->spawnProc = false;
727                 wfRestoreWarnings();
728         }
730         private function getTextSpawnedOnce( $id ) {
731                 global $wgContLang;
733                 $ok = fwrite( $this->spawnWrite, "$id\n" );
734                 // $this->progress( ">> $id" );
735                 if ( !$ok ) {
736                         return false;
737                 }
739                 $ok = fflush( $this->spawnWrite );
740                 // $this->progress( ">> [flush]" );
741                 if ( !$ok ) {
742                         return false;
743                 }
745                 // check that the text id they are sending is the one we asked for
746                 // this avoids out of sync revision text errors we have encountered in the past
747                 $newId = fgets( $this->spawnRead );
748                 if ( $newId === false ) {
749                         return false;
750                 }
751                 if ( $id != intval( $newId ) ) {
752                         return false;
753                 }
755                 $len = fgets( $this->spawnRead );
756                 // $this->progress( "<< " . trim( $len ) );
757                 if ( $len === false ) {
758                         return false;
759                 }
761                 $nbytes = intval( $len );
762                 // actual error, not zero-length text
763                 if ( $nbytes < 0 ) {
764                         return false;
765                 }
767                 $text = "";
769                 // Subprocess may not send everything at once, we have to loop.
770                 while ( $nbytes > strlen( $text ) ) {
771                         $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
772                         if ( $buffer === false ) {
773                                 break;
774                         }
775                         $text .= $buffer;
776                 }
778                 $gotbytes = strlen( $text );
779                 if ( $gotbytes != $nbytes ) {
780                         $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
782                         return false;
783                 }
785                 // Do normalization in the dump thread...
786                 $stripped = str_replace( "\r", "", $text );
787                 $normalized = $wgContLang->normalize( $stripped );
789                 return $normalized;
790         }
792         function startElement( $parser, $name, $attribs ) {
793                 $this->checkpointJustWritten = false;
795                 $this->clearOpenElement( null );
796                 $this->lastName = $name;
798                 if ( $name == 'revision' ) {
799                         $this->state = $name;
800                         $this->egress->writeOpenPage( null, $this->buffer );
801                         $this->buffer = "";
802                 } elseif ( $name == 'page' ) {
803                         $this->state = $name;
804                         if ( $this->atStart ) {
805                                 $this->egress->writeOpenStream( $this->buffer );
806                                 $this->buffer = "";
807                                 $this->atStart = false;
808                         }
809                 }
811                 if ( $name == "text" && isset( $attribs['id'] ) ) {
812                         $id = $attribs['id'];
813                         $model = trim( $this->thisRevModel );
814                         $format = trim( $this->thisRevFormat );
816                         $model = $model === '' ? null : $model;
817                         $format = $format === '' ? null : $format;
819                         $text = $this->getText( $id, $model, $format );
820                         $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
821                         if ( strlen( $text ) > 0 ) {
822                                 $this->characterData( $parser, $text );
823                         }
824                 } else {
825                         $this->openElement = array( $name, $attribs );
826                 }
827         }
829         function endElement( $parser, $name ) {
830                 $this->checkpointJustWritten = false;
832                 if ( $this->openElement ) {
833                         $this->clearOpenElement( "" );
834                 } else {
835                         $this->buffer .= "</$name>";
836                 }
838                 if ( $name == 'revision' ) {
839                         $this->egress->writeRevision( null, $this->buffer );
840                         $this->buffer = "";
841                         $this->thisRev = "";
842                         $this->thisRevModel = null;
843                         $this->thisRevFormat = null;
844                 } elseif ( $name == 'page' ) {
845                         if ( !$this->firstPageWritten ) {
846                                 $this->firstPageWritten = trim( $this->thisPage );
847                         }
848                         $this->lastPageWritten = trim( $this->thisPage );
849                         if ( $this->timeExceeded ) {
850                                 $this->egress->writeClosePage( $this->buffer );
851                                 // nasty hack, we can't just write the chardata after the
852                                 // page tag, it will include leading blanks from the next line
853                                 $this->egress->sink->write( "\n" );
855                                 $this->buffer = $this->xmlwriterobj->closeStream();
856                                 $this->egress->writeCloseStream( $this->buffer );
858                                 $this->buffer = "";
859                                 $this->thisPage = "";
860                                 // this could be more than one file if we had more than one output arg
862                                 $filenameList = (array)$this->egress->getFilenames();
863                                 $newFilenames = array();
864                                 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
865                                 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
866                                 $filenamesCount = count( $filenameList );
867                                 for ( $i = 0; $i < $filenamesCount; $i++ ) {
868                                         $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
869                                         $fileinfo = pathinfo( $filenameList[$i] );
870                                         $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
871                                 }
872                                 $this->egress->closeRenameAndReopen( $newFilenames );
873                                 $this->buffer = $this->xmlwriterobj->openStream();
874                                 $this->timeExceeded = false;
875                                 $this->timeOfCheckpoint = $this->lastTime;
876                                 $this->firstPageWritten = false;
877                                 $this->checkpointJustWritten = true;
878                         } else {
879                                 $this->egress->writeClosePage( $this->buffer );
880                                 $this->buffer = "";
881                                 $this->thisPage = "";
882                         }
883                 } elseif ( $name == 'mediawiki' ) {
884                         $this->egress->writeCloseStream( $this->buffer );
885                         $this->buffer = "";
886                 }
887         }
889         function characterData( $parser, $data ) {
890                 $this->clearOpenElement( null );
891                 if ( $this->lastName == "id" ) {
892                         if ( $this->state == "revision" ) {
893                                 $this->thisRev .= $data;
894                         } elseif ( $this->state == "page" ) {
895                                 $this->thisPage .= $data;
896                         }
897                 }
898                 elseif ( $this->lastName == "model" ) {
899                         $this->thisRevModel .= $data;
900                 }
901                 elseif ( $this->lastName == "format" ) {
902                         $this->thisRevFormat .= $data;
903                 }
905                 // have to skip the newline left over from closepagetag line of
906                 // end of checkpoint files. nasty hack!!
907                 if ( $this->checkpointJustWritten ) {
908                         if ( $data[0] == "\n" ) {
909                                 $data = substr( $data, 1 );
910                         }
911                         $this->checkpointJustWritten = false;
912                 }
913                 $this->buffer .= htmlspecialchars( $data );
914         }
916         function clearOpenElement( $style ) {
917                 if ( $this->openElement ) {
918                         $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
919                         $this->openElement = false;
920                 }
921         }