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