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