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