717f21b0e1e48e2eaf4fdb2cbe2ac2c4f7f9f870
[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 * http://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Maintenance
25 */
26
27
28 /**
29 * @ingroup Maintenance
30 */
31 class TextPassDumper extends BackupDumper {
32 var $prefetch = null;
33 var $input = "php://stdin";
34 var $history = WikiExporter::FULL;
35 var $fetchCount = 0;
36 var $prefetchCount = 0;
37 var $prefetchCountLast = 0;
38 var $fetchCountLast = 0;
39
40 var $maxFailures = 5;
41 var $maxConsecutiveFailedTextRetrievals = 200;
42 var $failureTimeout = 5; // Seconds to sleep after db failure
43
44 var $php = "php";
45 var $spawn = false;
46
47 /**
48 * @var bool|resource
49 */
50 var $spawnProc = false;
51
52 /**
53 * @var bool|resource
54 */
55 var $spawnWrite = false;
56
57 /**
58 * @var bool|resource
59 */
60 var $spawnRead = false;
61
62 /**
63 * @var bool|resource
64 */
65 var $spawnErr = false;
66
67 var $xmlwriterobj = false;
68
69 // when we spend more than maxTimeAllowed seconds on this run, we continue
70 // processing until we write out the next complete page, then save output file(s),
71 // rename it/them and open new one(s)
72 var $maxTimeAllowed = 0; // 0 = no limit
73 var $timeExceeded = false;
74 var $firstPageWritten = false;
75 var $lastPageWritten = false;
76 var $checkpointJustWritten = false;
77 var $checkpointFiles = array();
78
79 /**
80 * @var DatabaseBase
81 */
82 protected $db;
83
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__ . " rotating DB failed to obtain new load balancer (" . $e->getMessage() . ")" );
123 }
124
125
126 // 2. The Connection, through the load balancer.
127 try {
128 $this->db = $this->lb->getConnection( DB_SLAVE, 'backup' );
129 } catch ( Exception $e ) {
130 throw new MWException( __METHOD__ . " rotating DB failed to obtain new database (" . $e->getMessage() . ")" );
131 }
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 $this->initProgress( $this->history );
147
148 // We are trying to get an initial database connection to avoid that the
149 // first try of this request's first call to getText fails. However, if
150 // obtaining a good DB connection fails it's not a serious issue, as
151 // getText does retry upon failure and can start without having a working
152 // DB connection.
153 try {
154 $this->rotateDb();
155 } catch ( Exception $e ) {
156 // We do not even count this as failure. Just let eventual
157 // watchdogs know.
158 $this->progress( "Getting initial DB connection failed (" .
159 $e->getMessage() . ")" );
160 }
161
162 $this->egress = new ExportProgressFilter( $this->sink, $this );
163
164 // it would be nice to do it in the constructor, oh well. need egress set
165 $this->finalOptionCheck();
166
167 // we only want this so we know how to close a stream :-P
168 $this->xmlwriterobj = new XmlDumpWriter();
169
170 $input = fopen( $this->input, "rt" );
171 $result = $this->readDump( $input );
172
173 if ( WikiError::isError( $result ) ) {
174 throw new MWException( $result->getMessage() );
175 }
176
177 if ( $this->spawnProc ) {
178 $this->closeSpawn();
179 }
180
181 $this->report( true );
182 }
183
184 function processOption( $opt, $val, $param ) {
185 global $IP;
186 $url = $this->processFileOpt( $val, $param );
187
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 }
216
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 );
239 return $val;
240 }
241
242 /**
243 * Overridden to include prefetch ratio if enabled.
244 */
245 function showReport() {
246 if ( !$this->prefetch ) {
247 parent::showReport();
248 return;
249 }
250
251 if ( $this->reporting ) {
252 $now = wfTimestamp( TS_DB );
253 $nowts = wfTime();
254 $deltaAll = wfTime() - $this->startTime;
255 $deltaPart = wfTime() - $this->lastTime;
256 $this->pageCountPart = $this->pageCount - $this->pageCountLast;
257 $this->revCountPart = $this->revCount - $this->revCountLast;
258
259 if ( $deltaAll ) {
260 $portion = $this->revCount / $this->maxCount;
261 $eta = $this->startTime + $deltaAll / $portion;
262 $etats = wfTimestamp( TS_DB, intval( $eta ) );
263 if ( $this->fetchCount ) {
264 $fetchRate = 100.0 * $this->prefetchCount / $this->fetchCount;
265 } else {
266 $fetchRate = '-';
267 }
268 $pageRate = $this->pageCount / $deltaAll;
269 $revRate = $this->revCount / $deltaAll;
270 } else {
271 $pageRate = '-';
272 $revRate = '-';
273 $etats = '-';
274 $fetchRate = '-';
275 }
276 if ( $deltaPart ) {
277 if ( $this->fetchCountLast ) {
278 $fetchRatePart = 100.0 * $this->prefetchCountLast / $this->fetchCountLast;
279 } else {
280 $fetchRatePart = '-';
281 }
282 $pageRatePart = $this->pageCountPart / $deltaPart;
283 $revRatePart = $this->revCountPart / $deltaPart;
284
285 } else {
286 $fetchRatePart = '-';
287 $pageRatePart = '-';
288 $revRatePart = '-';
289 }
290 $this->progress( sprintf( "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), %d revs (%0.1f|%0.1f/sec all|curr), %0.1f%%|%0.1f%% prefetched (all|curr), ETA %s [max %d]",
291 $now, wfWikiID(), $this->ID, $this->pageCount, $pageRate, $pageRatePart, $this->revCount, $revRate, $revRatePart, $fetchRate, $fetchRatePart, $etats, $this->maxCount ) );
292 $this->lastTime = $nowts;
293 $this->revCountLast = $this->revCount;
294 $this->prefetchCountLast = $this->prefetchCount;
295 $this->fetchCountLast = $this->fetchCount;
296 }
297 }
298
299 function setTimeExceeded() {
300 $this->timeExceeded = True;
301 }
302
303 function checkIfTimeExceeded() {
304 if ( $this->maxTimeAllowed && ( $this->lastTime - $this->timeOfCheckpoint > $this->maxTimeAllowed ) ) {
305 return true;
306 }
307 return false;
308 }
309
310 function finalOptionCheck() {
311 if ( ( $this->checkpointFiles && ! $this->maxTimeAllowed ) ||
312 ( $this->maxTimeAllowed && !$this->checkpointFiles ) ) {
313 throw new MWException( "Options checkpointfile and maxtime must be specified together.\n" );
314 }
315 foreach ( $this->checkpointFiles as $checkpointFile ) {
316 $count = substr_count ( $checkpointFile, "%s" );
317 if ( $count != 2 ) {
318 throw new MWException( "Option checkpointfile must contain two '%s' for substitution of first and last pageids, count is $count instead, file is $checkpointFile.\n" );
319 }
320 }
321
322 if ( $this->checkpointFiles ) {
323 $filenameList = (array)$this->egress->getFilenames();
324 if ( count( $filenameList ) != count( $this->checkpointFiles ) ) {
325 throw new MWException( "One checkpointfile must be specified for each output option, if maxtime is used.\n" );
326 }
327 }
328 }
329
330 function readDump( $input ) {
331 $this->buffer = "";
332 $this->openElement = false;
333 $this->atStart = true;
334 $this->state = "";
335 $this->lastName = "";
336 $this->thisPage = 0;
337 $this->thisRev = 0;
338
339 $parser = xml_parser_create( "UTF-8" );
340 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
341
342 xml_set_element_handler( $parser, array( &$this, 'startElement' ), array( &$this, 'endElement' ) );
343 xml_set_character_data_handler( $parser, array( &$this, 'characterData' ) );
344
345 $offset = 0; // for context extraction on error reporting
346 $bufferSize = 512 * 1024;
347 do {
348 if ( $this->checkIfTimeExceeded() ) {
349 $this->setTimeExceeded();
350 }
351 $chunk = fread( $input, $bufferSize );
352 if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
353 wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
354 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
355 }
356 $offset += strlen( $chunk );
357 } while ( $chunk !== false && !feof( $input ) );
358 if ( $this->maxTimeAllowed ) {
359 $filenameList = (array)$this->egress->getFilenames();
360 // we wrote some stuff after last checkpoint that needs renamed
361 if ( file_exists( $filenameList[0] ) ) {
362 $newFilenames = array();
363 # we might have just written the header and footer and had no
364 # pages or revisions written... perhaps they were all deleted
365 # there's no pageID 0 so we use that. the caller is responsible
366 # for deciding what to do with a file containing only the
367 # siteinfo information and the mw tags.
368 if ( ! $this->firstPageWritten ) {
369 $firstPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
370 $lastPageID = str_pad( 0, 9, "0", STR_PAD_LEFT );
371 }
372 else {
373 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
374 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
375 }
376 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
377 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
378 $fileinfo = pathinfo( $filenameList[$i] );
379 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
380 }
381 $this->egress->closeAndRename( $newFilenames );
382 }
383 }
384 xml_parser_free( $parser );
385
386 return true;
387 }
388
389 /**
390 * Tries to get the revision text for a revision id.
391 *
392 * Upon errors, retries (Up to $this->maxFailures tries each call).
393 * If still no good revision get could be found even after this retrying, "" is returned.
394 * If no good revision text could be returned for
395 * $this->maxConsecutiveFailedTextRetrievals consecutive calls to getText, MWException
396 * is thrown.
397 *
398 * @param $id string The revision id to get the text for
399 *
400 * @return string The revision text for $id, or ""
401 * @throws MWException
402 */
403 function getText( $id ) {
404 $prefetchNotTried = true; // Whether or not we already tried to get the text via prefetch.
405 $text = false; // The candidate for a good text. false if no proper value.
406 $failures = 0; // The number of times, this invocation of getText already failed.
407
408 static $consecutiveFailedTextRetrievals = 0; // The number of times getText failed without
409 // yielding a good text in between.
410
411 $this->fetchCount++;
412
413 // To allow to simply return on success and do not have to worry about book keeping,
414 // we assume, this fetch works (possible after some retries). Nevertheless, we koop
415 // the old value, so we can restore it, if problems occur (See after the while loop).
416 $oldConsecutiveFailedTextRetrievals = $consecutiveFailedTextRetrievals;
417 $consecutiveFailedTextRetrievals = 0;
418
419 while ( $failures < $this->maxFailures ) {
420
421 // As soon as we found a good text for the $id, we will return immediately.
422 // Hence, if we make it past the try catch block, we know that we did not
423 // find a good text.
424
425 try {
426 // Step 1: Get some text (or reuse from previous iteratuon if checking
427 // for plausibility failed)
428
429 // Trying to get prefetch, if it has not been tried before
430 if ( $text === false && isset( $this->prefetch ) && $prefetchNotTried ) {
431 $prefetchNotTried = false;
432 $tryIsPrefetch = true;
433 $text = $this->prefetch->prefetch( intval( $this->thisPage ),
434 intval( $this->thisRev ) );
435 if ( $text === null ) {
436 $text = false;
437 }
438 }
439
440 if ( $text === false ) {
441 // Fallback to asking the database
442 $tryIsPrefetch = false;
443 if ( $this->spawn ) {
444 $text = $this->getTextSpawned( $id );
445 } else {
446 $text = $this->getTextDb( $id );
447 }
448
449 // No more checks for texts from DB for now.
450 // If we received something that is not false,
451 // We treat it as good text, regardless of whether it actually is or is not
452 if ( $text !== false ) {
453 return $text;
454 }
455 }
456
457 if ( $text === false ) {
458 throw new MWException( "Generic error while obtaining text for id " . $id );
459 }
460
461 // We received a good candidate for the text of $id via some method
462
463 // Step 2: Checking for plausibility and return the text if it is
464 // plausible
465 $revID = intval( $this->thisRev );
466 if ( ! isset( $this->db ) ) {
467 throw new MWException( "No database available" );
468 }
469 $revLength = $this->db->selectField( 'revision', 'rev_len', array( 'rev_id' => $revID ) );
470 if ( strlen( $text ) == $revLength ) {
471 if ( $tryIsPrefetch ) {
472 $this->prefetchCount++;
473 }
474 return $text;
475 }
476
477 $text = false;
478 throw new MWException( "Received text is unplausible for id " . $id );
479
480 } catch ( Exception $e ) {
481 $msg = "getting/checking text " . $id . " failed (" . $e->getMessage() . ")";
482 if ( $failures + 1 < $this->maxFailures ) {
483 $msg .= " (Will retry " . ( $this->maxFailures - $failures - 1 ) . " more times)";
484 }
485 $this->progress( $msg );
486 }
487
488 // Something went wrong; we did not a text that was plausible :(
489 $failures++;
490
491 // A failure in a prefetch hit does not warrant resetting db connection etc.
492 if ( ! $tryIsPrefetch ) {
493 // After backing off for some time, we try to reboot the whole process as
494 // much as possible to not carry over failures from one part to the other
495 // parts
496 sleep( $this->failureTimeout );
497 try {
498 $this->rotateDb();
499 if ( $this->spawn ) {
500 $this->closeSpawn();
501 $this->openSpawn();
502 }
503 } catch ( Exception $e ) {
504 $this->progress( "Rebooting getText infrastructure failed (" . $e->getMessage() . ")" .
505 " Trying to continue anyways" );
506 }
507 }
508 }
509
510 // Retirieving a good text for $id failed (at least) maxFailures times.
511 // We abort for this $id.
512
513 // Restoring the consecutive failures, and maybe aborting, if the dump
514 // is too broken.
515 $consecutiveFailedTextRetrievals = $oldConsecutiveFailedTextRetrievals + 1;
516 if ( $consecutiveFailedTextRetrievals > $this->maxConsecutiveFailedTextRetrievals ) {
517 throw new MWException( "Graceful storage failure" );
518 }
519
520 return "";
521 }
522
523
524 /**
525 * May throw a database error if, say, the server dies during query.
526 * @param $id
527 * @return bool|string
528 * @throws MWException
529 */
530 private function getTextDb( $id ) {
531 global $wgContLang;
532 if ( ! isset( $this->db ) ) {
533 throw new MWException( __METHOD__ . "No database available" );
534 }
535 $row = $this->db->selectRow( 'text',
536 array( 'old_text', 'old_flags' ),
537 array( 'old_id' => $id ),
538 __METHOD__ );
539 $text = Revision::getRevisionText( $row );
540 if ( $text === false ) {
541 return false;
542 }
543 $stripped = str_replace( "\r", "", $text );
544 $normalized = $wgContLang->normalize( $stripped );
545 return $normalized;
546 }
547
548 private function getTextSpawned( $id ) {
549 wfSuppressWarnings();
550 if ( !$this->spawnProc ) {
551 // First time?
552 $this->openSpawn();
553 }
554 $text = $this->getTextSpawnedOnce( $id );
555 wfRestoreWarnings();
556 return $text;
557 }
558
559 function openSpawn() {
560 global $IP;
561
562 if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
563 $cmd = implode( " ",
564 array_map( 'wfEscapeShellArg',
565 array(
566 $this->php,
567 "$IP/../multiversion/MWScript.php",
568 "fetchText.php",
569 '--wiki', wfWikiID() ) ) );
570 }
571 else {
572 $cmd = implode( " ",
573 array_map( 'wfEscapeShellArg',
574 array(
575 $this->php,
576 "$IP/maintenance/fetchText.php",
577 '--wiki', wfWikiID() ) ) );
578 }
579 $spec = array(
580 0 => array( "pipe", "r" ),
581 1 => array( "pipe", "w" ),
582 2 => array( "file", "/dev/null", "a" ) );
583 $pipes = array();
584
585 $this->progress( "Spawning database subprocess: $cmd" );
586 $this->spawnProc = proc_open( $cmd, $spec, $pipes );
587 if ( !$this->spawnProc ) {
588 // shit
589 $this->progress( "Subprocess spawn failed." );
590 return false;
591 }
592 list(
593 $this->spawnWrite, // -> stdin
594 $this->spawnRead, // <- stdout
595 ) = $pipes;
596
597 return true;
598 }
599
600 private function closeSpawn() {
601 wfSuppressWarnings();
602 if ( $this->spawnRead )
603 fclose( $this->spawnRead );
604 $this->spawnRead = false;
605 if ( $this->spawnWrite )
606 fclose( $this->spawnWrite );
607 $this->spawnWrite = false;
608 if ( $this->spawnErr )
609 fclose( $this->spawnErr );
610 $this->spawnErr = false;
611 if ( $this->spawnProc )
612 pclose( $this->spawnProc );
613 $this->spawnProc = false;
614 wfRestoreWarnings();
615 }
616
617 private function getTextSpawnedOnce( $id ) {
618 global $wgContLang;
619
620 $ok = fwrite( $this->spawnWrite, "$id\n" );
621 // $this->progress( ">> $id" );
622 if ( !$ok ) return false;
623
624 $ok = fflush( $this->spawnWrite );
625 // $this->progress( ">> [flush]" );
626 if ( !$ok ) return false;
627
628 // check that the text id they are sending is the one we asked for
629 // this avoids out of sync revision text errors we have encountered in the past
630 $newId = fgets( $this->spawnRead );
631 if ( $newId === false ) {
632 return false;
633 }
634 if ( $id != intval( $newId ) ) {
635 return false;
636 }
637
638 $len = fgets( $this->spawnRead );
639 // $this->progress( "<< " . trim( $len ) );
640 if ( $len === false ) return false;
641
642 $nbytes = intval( $len );
643 // actual error, not zero-length text
644 if ( $nbytes < 0 ) return false;
645
646 $text = "";
647
648 // Subprocess may not send everything at once, we have to loop.
649 while ( $nbytes > strlen( $text ) ) {
650 $buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
651 if ( $buffer === false ) break;
652 $text .= $buffer;
653 }
654
655 $gotbytes = strlen( $text );
656 if ( $gotbytes != $nbytes ) {
657 $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
658 return false;
659 }
660
661 // Do normalization in the dump thread...
662 $stripped = str_replace( "\r", "", $text );
663 $normalized = $wgContLang->normalize( $stripped );
664 return $normalized;
665 }
666
667 function startElement( $parser, $name, $attribs ) {
668 $this->checkpointJustWritten = false;
669
670 $this->clearOpenElement( null );
671 $this->lastName = $name;
672
673 if ( $name == 'revision' ) {
674 $this->state = $name;
675 $this->egress->writeOpenPage( null, $this->buffer );
676 $this->buffer = "";
677 } elseif ( $name == 'page' ) {
678 $this->state = $name;
679 if ( $this->atStart ) {
680 $this->egress->writeOpenStream( $this->buffer );
681 $this->buffer = "";
682 $this->atStart = false;
683 }
684 }
685
686 if ( $name == "text" && isset( $attribs['id'] ) ) {
687 $text = $this->getText( $attribs['id'] );
688 $this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
689 if ( strlen( $text ) > 0 ) {
690 $this->characterData( $parser, $text );
691 }
692 } else {
693 $this->openElement = array( $name, $attribs );
694 }
695 }
696
697 function endElement( $parser, $name ) {
698 $this->checkpointJustWritten = false;
699
700 if ( $this->openElement ) {
701 $this->clearOpenElement( "" );
702 } else {
703 $this->buffer .= "</$name>";
704 }
705
706 if ( $name == 'revision' ) {
707 $this->egress->writeRevision( null, $this->buffer );
708 $this->buffer = "";
709 $this->thisRev = "";
710 } elseif ( $name == 'page' ) {
711 if ( ! $this->firstPageWritten ) {
712 $this->firstPageWritten = trim( $this->thisPage );
713 }
714 $this->lastPageWritten = trim( $this->thisPage );
715 if ( $this->timeExceeded ) {
716 $this->egress->writeClosePage( $this->buffer );
717 // nasty hack, we can't just write the chardata after the
718 // page tag, it will include leading blanks from the next line
719 $this->egress->sink->write( "\n" );
720
721 $this->buffer = $this->xmlwriterobj->closeStream();
722 $this->egress->writeCloseStream( $this->buffer );
723
724 $this->buffer = "";
725 $this->thisPage = "";
726 // this could be more than one file if we had more than one output arg
727
728 $filenameList = (array)$this->egress->getFilenames();
729 $newFilenames = array();
730 $firstPageID = str_pad( $this->firstPageWritten, 9, "0", STR_PAD_LEFT );
731 $lastPageID = str_pad( $this->lastPageWritten, 9, "0", STR_PAD_LEFT );
732 for ( $i = 0; $i < count( $filenameList ); $i++ ) {
733 $checkpointNameFilledIn = sprintf( $this->checkpointFiles[$i], $firstPageID, $lastPageID );
734 $fileinfo = pathinfo( $filenameList[$i] );
735 $newFilenames[] = $fileinfo['dirname'] . '/' . $checkpointNameFilledIn;
736 }
737 $this->egress->closeRenameAndReopen( $newFilenames );
738 $this->buffer = $this->xmlwriterobj->openStream();
739 $this->timeExceeded = false;
740 $this->timeOfCheckpoint = $this->lastTime;
741 $this->firstPageWritten = false;
742 $this->checkpointJustWritten = true;
743 }
744 else {
745 $this->egress->writeClosePage( $this->buffer );
746 $this->buffer = "";
747 $this->thisPage = "";
748 }
749
750 } elseif ( $name == 'mediawiki' ) {
751 $this->egress->writeCloseStream( $this->buffer );
752 $this->buffer = "";
753 }
754 }
755
756 function characterData( $parser, $data ) {
757 $this->clearOpenElement( null );
758 if ( $this->lastName == "id" ) {
759 if ( $this->state == "revision" ) {
760 $this->thisRev .= $data;
761 } elseif ( $this->state == "page" ) {
762 $this->thisPage .= $data;
763 }
764 }
765 // have to skip the newline left over from closepagetag line of
766 // end of checkpoint files. nasty hack!!
767 if ( $this->checkpointJustWritten ) {
768 if ( $data[0] == "\n" ) {
769 $data = substr( $data, 1 );
770 }
771 $this->checkpointJustWritten = false;
772 }
773 $this->buffer .= htmlspecialchars( $data );
774 }
775
776 function clearOpenElement( $style ) {
777 if ( $this->openElement ) {
778 $this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
779 $this->openElement = false;
780 }
781 }
782 }