Merge "Make feedlink icon visible by setting a size"
[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 applicable export transformations.
468 * If $model is null, it will be determined from the database.
469 * @param string|null $format The content format used when applying export transformations.
470 *
471 * @throws MWException
472 * @return string The revision text for $id, or ""
473 */
474 function getText( $id, $model = null, $format = null ) {
475 global $wgContentHandlerUseDB;
476
477 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
478 $text = false; // The candidate for a good text. false if no proper value.
479 $failures = 0; // The number of times, this invocation of getText already failed.
480
481 // The number of times getText failed without yielding a good text in between.
482 static $consecutiveFailedTextRetrievals = 0;
483
484 $this->fetchCount++;
485
486 // To allow to simply return on success and do not have to worry about book keeping,
487 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
488 // the old value, so we can restore it, if problems occur (See after the while loop).
489 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
490 $consecutiveFailedTextRetrievals = 0;
491
492 if ( $model === null && $wgContentHandlerUseDB ) {
493 $row = $this->db->selectRow(
494 'revision',
495 array( 'rev_content_model', 'rev_content_format' ),
496 array( 'rev_id' => $this->thisRev ),
497 __METHOD__
498 );
499
500 if ( $row ) {
501 $model = $row->rev_content_model;
502 $format = $row->rev_content_format;
503 }
504 }
505
506 if ( $model === null || $model === '' ) {
507 $model = false;
508 }
509
510 while ( $failures < $this->maxFailures ) {
511
512 // As soon as we found a good text for the $id, we will return immediately.
513 // Hence, if we make it past the try catch block, we know that we did not
514 // find a good text.
515
516 try {
517 // Step 1: Get some text (or reuse from previous iteratuon if checking
518 // for plausibility failed)
519
520 // Trying to get prefetch, if it has not been tried before
521 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
522 $prefetchNotTried = false;
523 $tryIsPrefetch = true;
524 $text = $this->prefetch->prefetch( intval( $this->thisPage ),
525 intval( $this->thisRev ) );
526
527 if ( $text === null ) {
528 $text = false;
529 }
530
531 if ( is_string( $text ) && $model !== false ) {
532 // Apply export transformation to text coming from an old dump.
533 // The purpose of this transformation is to convert up from legacy
534 // formats, which may still be used in the older dump that is used
535 // for pre-fetching. Applying the transformation again should not
536 // interfere with content that is already in the correct form.
537 $text = $this->exportTransform( $text, $model, $format );
538 }
539 }
540
541 if ( $text === false ) {
542 // Fallback to asking the database
543 $tryIsPrefetch = false;
544 if ( $this->spawn ) {
545 $text = $this->getTextSpawned( $id );
546 } else {
547 $text = $this->getTextDb( $id );
548 }
549
550 if ( $text !== false && $model !== false ) {
551 // Apply export transformation to text coming from the database.
552 // Prefetched text should already have transformations applied.
553 $text = $this->exportTransform( $text, $model, $format );
554 }
555
556 // No more checks for texts from DB for now.
557 // If we received something that is not false,
558 // We treat it as good text, regardless of whether it actually is or is not
559 if ( $text !== false ) {
560 return $text;
561 }
562 }
563
564 if ( $text === false ) {
565 throw new MWException( "Generic error while obtaining text for id " . $id );
566 }
567
568 // We received a good candidate for the text of $id via some method
569
570 // Step 2: Checking for plausibility and return the text if it is
571 // plausible
572 $revID = intval( $this->thisRev );
573 if ( !isset( $this->db ) ) {
574 throw new MWException( "No database available" );
575 }
576
577 if ( $model !== CONTENT_MODEL_WIKITEXT ) {
578 $revLength = strlen( $text );
579 } else {
580 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
581 }
582
583 if ( strlen( $text ) == $revLength ) {
584 if ( $tryIsPrefetch ) {
585 $this->prefetchCount++;
586 }
587
588 return $text;
589 }
590
591 $text = false;
592 throw new MWException( "Received text is unplausible for id " . $id );
593 } catch ( Exception $e ) {
594 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
595 if ( $failures + 1 < $this->maxFailures ) {
596 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
597 }
598 $this->progress( $msg );
599 }
600
601 // Something went wrong; we did not a text that was plausible :(
602 $failures++;
603
604 // A failure in a prefetch hit does not warrant resetting db connection etc.
605 if ( !$tryIsPrefetch ) {
606 // After backing off for some time, we try to reboot the whole process as
607 // much as possible to not carry over failures from one part to the other
608 // parts
609 sleep( $this->failureTimeout );
610 try {
611 $this->rotateDb();
612 if ( $this->spawn ) {
613 $this->closeSpawn();
614 $this->openSpawn();
615 }
616 } catch ( Exception $e ) {
617 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
618 " Trying to continue anyways" );
619 }
620 }
621 }
622
623 // Retirieving a good text for $id failed (at least) maxFailures times.
624 // We abort for this $id.
625
626 // Restoring the consecutive failures, and maybe aborting, if the dump
627 // is too broken.
628 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
629 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
630 throw new MWException( "Graceful storage failure" );
631 }
632
633 return "";
634 }
635
636 /**
637 * May throw a database error if, say, the server dies during query.
638 * @param int $id
639 * @return bool|string
640 * @throws MWException
641 */
642 private function getTextDb( $id ) {
643 global $wgContLang;
644 if ( !isset( $this->db ) ) {
645 throw new MWException( __METHOD__ . "No database available" );
646 }
647 $row = $this->db->selectRow( 'text',
648 array( 'old_text', 'old_flags' ),
649 array( 'old_id' => $id ),
650 __METHOD__ );
651 $text = Revision::getRevisionText( $row );
652 if ( $text === false ) {
653 return false;
654 }
655 $stripped = str_replace( "\r", "", $text );
656 $normalized = $wgContLang->normalize( $stripped );
657
658 return $normalized;
659 }
660
661 private function getTextSpawned( $id ) {
662 MediaWiki\suppressWarnings();
663 if ( !$this->spawnProc ) {
664 // First time?
665 $this->openSpawn();
666 }
667 $text = $this->getTextSpawnedOnce( $id );
668 MediaWiki\restoreWarnings();
669
670 return $text;
671 }
672
673 function openSpawn() {
674 global $IP;
675
676 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
677 $cmd = implode( " ",
678 array_map( 'wfEscapeShellArg',
679 array(
680 $this->php,
681 "$IP/../multiversion/MWScript.php",
682 "fetchText.php",
683 '--wiki', wfWikiID() ) ) );
684 } else {
685 $cmd = implode( " ",
686 array_map( 'wfEscapeShellArg',
687 array(
688 $this->php,
689 "$IP/maintenance/fetchText.php",
690 '--wiki', wfWikiID() ) ) );
691 }
692 $spec = array(
693 0 => array( "pipe", "r" ),
694 1 => array( "pipe", "w" ),
695 2 => array( "file", "/dev/null", "a" ) );
696 $pipes = array();
697
698 $this->progress( "Spawning database subprocess: $cmd" );
699 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
700 if ( !$this->spawnProc ) {
701 // shit
702 $this->progress( "Subprocess spawn failed." );
703
704 return false;
705 }
706 list(
707 $this->spawnWrite, // -> stdin
708 $this->spawnRead, // <- stdout
709 ) = $pipes;
710
711 return true;
712 }
713
714 private function closeSpawn() {
715 MediaWiki\suppressWarnings();
716 if ( $this->spawnRead ) {
717 fclose( $this->spawnRead );
718 }
719 $this->spawnRead = false;
720 if ( $this->spawnWrite ) {
721 fclose( $this->spawnWrite );
722 }
723 $this->spawnWrite = false;
724 if ( $this->spawnErr ) {
725 fclose( $this->spawnErr );
726 }
727 $this->spawnErr = false;
728 if ( $this->spawnProc ) {
729 pclose( $this->spawnProc );
730 }
731 $this->spawnProc = false;
732 MediaWiki\restoreWarnings();
733 }
734
735 private function getTextSpawnedOnce( $id ) {
736 global $wgContLang;
737
738 $ok = fwrite( $this->spawnWrite, "$id\n" );
739 // $this->progress( ">> $id" );
740 if ( !$ok ) {
741 return false;
742 }
743
744 $ok = fflush( $this->spawnWrite );
745 // $this->progress( ">> [flush]" );
746 if ( !$ok ) {
747 return false;
748 }
749
750 // check that the text id they are sending is the one we asked for
751 // this avoids out of sync revision text errors we have encountered in the past
752 $newId = fgets( $this->spawnRead );
753 if ( $newId === false ) {
754 return false;
755 }
756 if ( $id != intval( $newId ) ) {
757 return false;
758 }
759
760 $len = fgets( $this->spawnRead );
761 // $this->progress( "<< " . trim( $len ) );
762 if ( $len === false ) {
763 return false;
764 }
765
766 $nbytes = intval( $len );
767 // actual error, not zero-length text
768 if ( $nbytes < 0 ) {
769 return false;
770 }
771
772 $text = "";
773
774 // Subprocess may not send everything at once, we have to loop.
775 while ( $nbytes > strlen( $text ) ) {
776 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
777 if ( $buffer === false ) {
778 break;
779 }
780 $text .= $buffer;
781 }
782
783 $gotbytes = strlen( $text );
784 if ( $gotbytes != $nbytes ) {
785 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
786
787 return false;
788 }
789
790 // Do normalization in the dump thread...
791 $stripped = str_replace( "\r", "", $text );
792 $normalized = $wgContLang->normalize( $stripped );
793
794 return $normalized;
795 }
796
797 function startElement( $parser, $name, $attribs ) {
798 $this->checkpointJustWritten = false;
799
800 $this->clearOpenElement( null );
801 $this->lastName = $name;
802
803 if ( $name == 'revision' ) {
804 $this->state = $name;
805 $this->egress->writeOpenPage( null, $this->buffer );
806 $this->buffer = "";
807 } elseif ( $name == 'page' ) {
808 $this->state = $name;
809 if ( $this->atStart ) {
810 $this->egress->writeOpenStream( $this->buffer );
811 $this->buffer = "";
812 $this->atStart = false;
813 }
814 }
815
816 if ( $name == "text" && isset( $attribs['id'] ) ) {
817 $id = $attribs['id'];
818 $model = trim( $this->thisRevModel );
819 $format = trim( $this->thisRevFormat );
820
821 $model = $model === '' ? null : $model;
822 $format = $format === '' ? null : $format;
823
824 $text = $this->getText( $id, $model, $format );
825 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
826 if ( strlen( $text ) > 0 ) {
827 $this->characterData( $parser, $text );
828 }
829 } else {
830 $this->openElement = array( $name, $attribs );
831 }
832 }
833
834 function endElement( $parser, $name ) {
835 $this->checkpointJustWritten = false;
836
837 if ( $this->openElement ) {
838 $this->clearOpenElement( "" );
839 } else {
840 $this->buffer .= "</$name>";
841 }
842
843 if ( $name == 'revision' ) {
844 $this->egress->writeRevision( null, $this->buffer );
845 $this->buffer = "";
846 $this->thisRev = "";
847 $this->thisRevModel = null;
848 $this->thisRevFormat = null;
849 } elseif ( $name == 'page' ) {
850 if ( !$this->firstPageWritten ) {
851 $this->firstPageWritten = trim( $this->thisPage );
852 }
853 $this->lastPageWritten = trim( $this->thisPage );
854 if ( $this->timeExceeded ) {
855 $this->egress->writeClosePage( $this->buffer );
856 // nasty hack, we can't just write the chardata after the
857 // page tag, it will include leading blanks from the next line
858 $this->egress->sink->write( "\n" );
859
860 $this->buffer = $this->xmlwriterobj->closeStream();
861 $this->egress->writeCloseStream( $this->buffer );
862
863 $this->buffer = "";
864 $this->thisPage = "";
865 // this could be more than one file if we had more than one output arg
866
867 $filenameList = (array)$this->egress->getFilenames();
868 $newFilenames = array();
869 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
870 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
871 $filenamesCount = count( $filenameList );
872 for ( $i = 0; $i < $filenamesCount; $i++ ) {
873 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
874 $fileinfo = pathinfo( $filenameList[$i] );
875 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
876 }
877 $this->egress->closeRenameAndReopen( $newFilenames );
878 $this->buffer = $this->xmlwriterobj->openStream();
879 $this->timeExceeded = false;
880 $this->timeOfCheckpoint = $this->lastTime;
881 $this->firstPageWritten = false;
882 $this->checkpointJustWritten = true;
883 } else {
884 $this->egress->writeClosePage( $this->buffer );
885 $this->buffer = "";
886 $this->thisPage = "";
887 }
888 } elseif ( $name == 'mediawiki' ) {
889 $this->egress->writeCloseStream( $this->buffer );
890 $this->buffer = "";
891 }
892 }
893
894 function characterData( $parser, $data ) {
895 $this->clearOpenElement( null );
896 if ( $this->lastName == "id" ) {
897 if ( $this->state == "revision" ) {
898 $this->thisRev .= $data;
899 } elseif ( $this->state == "page" ) {
900 $this->thisPage .= $data;
901 }
902 }
903 elseif ( $this->lastName == "model" ) {
904 $this->thisRevModel .= $data;
905 }
906 elseif ( $this->lastName == "format" ) {
907 $this->thisRevFormat .= $data;
908 }
909
910 // have to skip the newline left over from closepagetag line of
911 // end of checkpoint files. nasty hack!!
912 if ( $this->checkpointJustWritten ) {
913 if ( $data[0] == "\n" ) {
914 $data = substr( $data, 1 );
915 }
916 $this->checkpointJustWritten = false;
917 }
918 $this->buffer .= htmlspecialchars( $data );
919 }
920
921 function clearOpenElement( $style ) {
922 if ( $this->openElement ) {
923 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
924 $this->openElement = false;
925 }
926 }
927 }