Change position of <model> and <format> tags in XML dumps.
[lhc/web/wiklou.git] / includes / Export.php
1 <?php
2 /**
3 * Base classes for dumps and export
4 *
5 * Copyright © 2003, 2005, 2006 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 */
25
26 /**
27 * @defgroup Dump Dump
28 */
29
30 /**
31 * @ingroup SpecialPage Dump
32 */
33 class WikiExporter {
34 /** @var bool Return distinct author list (when not returning full history) */
35 public $list_authors = false;
36
37 /** @var bool */
38 public $dumpUploads = false;
39
40 /** @var bool */
41 public $dumpUploadFileContents = false;
42
43 /** @var string */
44 public $author_list = "";
45
46 const FULL = 1;
47 const CURRENT = 2;
48 const STABLE = 4; // extension defined
49 const LOGS = 8;
50 const RANGE = 16;
51
52 const BUFFER = 0;
53 const STREAM = 1;
54
55 const TEXT = 0;
56 const STUB = 1;
57
58 /** @var int */
59 public $buffer;
60
61 /** @var int */
62 public $text;
63
64 /** @var DumpOutput */
65 public $sink;
66
67 /**
68 * Returns the export schema version.
69 * @return string
70 */
71 public static function schemaVersion() {
72 return "0.10";
73 }
74
75 /**
76 * If using WikiExporter::STREAM to stream a large amount of data,
77 * provide a database connection which is not managed by
78 * LoadBalancer to read from: some history blob types will
79 * make additional queries to pull source data while the
80 * main query is still running.
81 *
82 * @param DatabaseBase $db
83 * @param int|array $history One of WikiExporter::FULL, WikiExporter::CURRENT,
84 * WikiExporter::RANGE or WikiExporter::STABLE, or an associative array:
85 * - offset: non-inclusive offset at which to start the query
86 * - limit: maximum number of rows to return
87 * - dir: "asc" or "desc" timestamp order
88 * @param int $buffer One of WikiExporter::BUFFER or WikiExporter::STREAM
89 * @param int $text One of WikiExporter::TEXT or WikiExporter::STUB
90 */
91 function __construct( $db, $history = WikiExporter::CURRENT,
92 $buffer = WikiExporter::BUFFER, $text = WikiExporter::TEXT ) {
93 $this->db = $db;
94 $this->history = $history;
95 $this->buffer = $buffer;
96 $this->writer = new XmlDumpWriter();
97 $this->sink = new DumpOutput();
98 $this->text = $text;
99 }
100
101 /**
102 * Set the DumpOutput or DumpFilter object which will receive
103 * various row objects and XML output for filtering. Filters
104 * can be chained or used as callbacks.
105 *
106 * @param DumpOutput $sink
107 */
108 public function setOutputSink( &$sink ) {
109 $this->sink =& $sink;
110 }
111
112 public function openStream() {
113 $output = $this->writer->openStream();
114 $this->sink->writeOpenStream( $output );
115 }
116
117 public function closeStream() {
118 $output = $this->writer->closeStream();
119 $this->sink->writeCloseStream( $output );
120 }
121
122 /**
123 * Dumps a series of page and revision records for all pages
124 * in the database, either including complete history or only
125 * the most recent version.
126 */
127 public function allPages() {
128 $this->dumpFrom( '' );
129 }
130
131 /**
132 * Dumps a series of page and revision records for those pages
133 * in the database falling within the page_id range given.
134 * @param int $start Inclusive lower limit (this id is included)
135 * @param int $end Exclusive upper limit (this id is not included)
136 * If 0, no upper limit.
137 */
138 public function pagesByRange( $start, $end ) {
139 $condition = 'page_id >= ' . intval( $start );
140 if ( $end ) {
141 $condition .= ' AND page_id < ' . intval( $end );
142 }
143 $this->dumpFrom( $condition );
144 }
145
146 /**
147 * Dumps a series of page and revision records for those pages
148 * in the database with revisions falling within the rev_id range given.
149 * @param int $start Inclusive lower limit (this id is included)
150 * @param int $end Exclusive upper limit (this id is not included)
151 * If 0, no upper limit.
152 */
153 public function revsByRange( $start, $end ) {
154 $condition = 'rev_id >= ' . intval( $start );
155 if ( $end ) {
156 $condition .= ' AND rev_id < ' . intval( $end );
157 }
158 $this->dumpFrom( $condition );
159 }
160
161 /**
162 * @param Title $title
163 */
164 public function pageByTitle( $title ) {
165 $this->dumpFrom(
166 'page_namespace=' . $title->getNamespace() .
167 ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
168 }
169
170 /**
171 * @param string $name
172 * @throws MWException
173 */
174 public function pageByName( $name ) {
175 $title = Title::newFromText( $name );
176 if ( is_null( $title ) ) {
177 throw new MWException( "Can't export invalid title" );
178 } else {
179 $this->pageByTitle( $title );
180 }
181 }
182
183 /**
184 * @param array $names
185 */
186 public function pagesByName( $names ) {
187 foreach ( $names as $name ) {
188 $this->pageByName( $name );
189 }
190 }
191
192 public function allLogs() {
193 $this->dumpFrom( '' );
194 }
195
196 /**
197 * @param int $start
198 * @param int $end
199 */
200 public function logsByRange( $start, $end ) {
201 $condition = 'log_id >= ' . intval( $start );
202 if ( $end ) {
203 $condition .= ' AND log_id < ' . intval( $end );
204 }
205 $this->dumpFrom( $condition );
206 }
207
208 /**
209 * Generates the distinct list of authors of an article
210 * Not called by default (depends on $this->list_authors)
211 * Can be set by Special:Export when not exporting whole history
212 *
213 * @param array $cond
214 */
215 protected function do_list_authors( $cond ) {
216 wfProfileIn( __METHOD__ );
217 $this->author_list = "<contributors>";
218 // rev_deleted
219
220 $res = $this->db->select(
221 array( 'page', 'revision' ),
222 array( 'DISTINCT rev_user_text', 'rev_user' ),
223 array(
224 $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
225 $cond,
226 'page_id = rev_id',
227 ),
228 __METHOD__
229 );
230
231 foreach ( $res as $row ) {
232 $this->author_list .= "<contributor>" .
233 "<username>" .
234 htmlentities( $row->rev_user_text ) .
235 "</username>" .
236 "<id>" .
237 $row->rev_user .
238 "</id>" .
239 "</contributor>";
240 }
241 $this->author_list .= "</contributors>";
242 wfProfileOut( __METHOD__ );
243 }
244
245 /**
246 * @param string $cond
247 * @throws MWException
248 * @throws Exception
249 */
250 protected function dumpFrom( $cond = '' ) {
251 wfProfileIn( __METHOD__ );
252 # For logging dumps...
253 if ( $this->history & self::LOGS ) {
254 $where = array( 'user_id = log_user' );
255 # Hide private logs
256 $hideLogs = LogEventsList::getExcludeClause( $this->db );
257 if ( $hideLogs ) {
258 $where[] = $hideLogs;
259 }
260 # Add on any caller specified conditions
261 if ( $cond ) {
262 $where[] = $cond;
263 }
264 # Get logging table name for logging.* clause
265 $logging = $this->db->tableName( 'logging' );
266
267 if ( $this->buffer == WikiExporter::STREAM ) {
268 $prev = $this->db->bufferResults( false );
269 }
270 $result = null; // Assuring $result is not undefined, if exception occurs early
271 try {
272 $result = $this->db->select( array( 'logging', 'user' ),
273 array( "{$logging}.*", 'user_name' ), // grab the user name
274 $where,
275 __METHOD__,
276 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
277 );
278 $this->outputLogStream( $result );
279 if ( $this->buffer == WikiExporter::STREAM ) {
280 $this->db->bufferResults( $prev );
281 }
282 } catch ( Exception $e ) {
283 // Throwing the exception does not reliably free the resultset, and
284 // would also leave the connection in unbuffered mode.
285
286 // Freeing result
287 try {
288 if ( $result ) {
289 $result->free();
290 }
291 } catch ( Exception $e2 ) {
292 // Already in panic mode -> ignoring $e2 as $e has
293 // higher priority
294 }
295
296 // Putting database back in previous buffer mode
297 try {
298 if ( $this->buffer == WikiExporter::STREAM ) {
299 $this->db->bufferResults( $prev );
300 }
301 } catch ( Exception $e2 ) {
302 // Already in panic mode -> ignoring $e2 as $e has
303 // higher priority
304 }
305
306 // Inform caller about problem
307 wfProfileOut( __METHOD__ );
308 throw $e;
309 }
310 # For page dumps...
311 } else {
312 $tables = array( 'page', 'revision' );
313 $opts = array( 'ORDER BY' => 'page_id ASC' );
314 $opts['USE INDEX'] = array();
315 $join = array();
316 if ( is_array( $this->history ) ) {
317 # Time offset/limit for all pages/history...
318 $revJoin = 'page_id=rev_page';
319 # Set time order
320 if ( $this->history['dir'] == 'asc' ) {
321 $op = '>';
322 $opts['ORDER BY'] = 'rev_timestamp ASC';
323 } else {
324 $op = '<';
325 $opts['ORDER BY'] = 'rev_timestamp DESC';
326 }
327 # Set offset
328 if ( !empty( $this->history['offset'] ) ) {
329 $revJoin .= " AND rev_timestamp $op " .
330 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
331 }
332 $join['revision'] = array( 'INNER JOIN', $revJoin );
333 # Set query limit
334 if ( !empty( $this->history['limit'] ) ) {
335 $opts['LIMIT'] = intval( $this->history['limit'] );
336 }
337 } elseif ( $this->history & WikiExporter::FULL ) {
338 # Full history dumps...
339 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
340 } elseif ( $this->history & WikiExporter::CURRENT ) {
341 # Latest revision dumps...
342 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
343 $this->do_list_authors( $cond );
344 }
345 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
346 } elseif ( $this->history & WikiExporter::STABLE ) {
347 # "Stable" revision dumps...
348 # Default JOIN, to be overridden...
349 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
350 # One, and only one hook should set this, and return false
351 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
352 wfProfileOut( __METHOD__ );
353 throw new MWException( __METHOD__ . " given invalid history dump type." );
354 }
355 } elseif ( $this->history & WikiExporter::RANGE ) {
356 # Dump of revisions within a specified range
357 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
358 $opts['ORDER BY'] = array( 'rev_page ASC', 'rev_id ASC' );
359 } else {
360 # Unknown history specification parameter?
361 wfProfileOut( __METHOD__ );
362 throw new MWException( __METHOD__ . " given invalid history dump type." );
363 }
364 # Query optimization hacks
365 if ( $cond == '' ) {
366 $opts[] = 'STRAIGHT_JOIN';
367 $opts['USE INDEX']['page'] = 'PRIMARY';
368 }
369 # Build text join options
370 if ( $this->text != WikiExporter::STUB ) { // 1-pass
371 $tables[] = 'text';
372 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
373 }
374
375 if ( $this->buffer == WikiExporter::STREAM ) {
376 $prev = $this->db->bufferResults( false );
377 }
378
379 $result = null; // Assuring $result is not undefined, if exception occurs early
380 try {
381 wfRunHooks( 'ModifyExportQuery',
382 array( $this->db, &$tables, &$cond, &$opts, &$join ) );
383
384 # Do the query!
385 $result = $this->db->select( $tables, '*', $cond, __METHOD__, $opts, $join );
386 # Output dump results
387 $this->outputPageStream( $result );
388
389 if ( $this->buffer == WikiExporter::STREAM ) {
390 $this->db->bufferResults( $prev );
391 }
392 } catch ( Exception $e ) {
393 // Throwing the exception does not reliably free the resultset, and
394 // would also leave the connection in unbuffered mode.
395
396 // Freeing result
397 try {
398 if ( $result ) {
399 $result->free();
400 }
401 } catch ( Exception $e2 ) {
402 // Already in panic mode -> ignoring $e2 as $e has
403 // higher priority
404 }
405
406 // Putting database back in previous buffer mode
407 try {
408 if ( $this->buffer == WikiExporter::STREAM ) {
409 $this->db->bufferResults( $prev );
410 }
411 } catch ( Exception $e2 ) {
412 // Already in panic mode -> ignoring $e2 as $e has
413 // higher priority
414 }
415
416 // Inform caller about problem
417 throw $e;
418 }
419 }
420 wfProfileOut( __METHOD__ );
421 }
422
423 /**
424 * Runs through a query result set dumping page and revision records.
425 * The result set should be sorted/grouped by page to avoid duplicate
426 * page records in the output.
427 *
428 * Should be safe for
429 * streaming (non-buffered) queries, as long as it was made on a
430 * separate database connection not managed by LoadBalancer; some
431 * blob storage types will make queries to pull source data.
432 *
433 * @param ResultWrapper $resultset
434 */
435 protected function outputPageStream( $resultset ) {
436 $last = null;
437 foreach ( $resultset as $row ) {
438 if ( $last === null ||
439 $last->page_namespace != $row->page_namespace ||
440 $last->page_title != $row->page_title ) {
441 if ( $last !== null ) {
442 $output = '';
443 if ( $this->dumpUploads ) {
444 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
445 }
446 $output .= $this->writer->closePage();
447 $this->sink->writeClosePage( $output );
448 }
449 $output = $this->writer->openPage( $row );
450 $this->sink->writeOpenPage( $row, $output );
451 $last = $row;
452 }
453 $output = $this->writer->writeRevision( $row );
454 $this->sink->writeRevision( $row, $output );
455 }
456 if ( $last !== null ) {
457 $output = '';
458 if ( $this->dumpUploads ) {
459 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
460 }
461 $output .= $this->author_list;
462 $output .= $this->writer->closePage();
463 $this->sink->writeClosePage( $output );
464 }
465 }
466
467 /**
468 * @param ResultWrapper $resultset
469 */
470 protected function outputLogStream( $resultset ) {
471 foreach ( $resultset as $row ) {
472 $output = $this->writer->writeLogItem( $row );
473 $this->sink->writeLogItem( $row, $output );
474 }
475 }
476 }
477
478 /**
479 * @ingroup Dump
480 */
481 class XmlDumpWriter {
482 /**
483 * Opens the XML output stream's root "<mediawiki>" element.
484 * This does not include an xml directive, so is safe to include
485 * as a subelement in a larger XML stream. Namespace and XML Schema
486 * references are included.
487 *
488 * Output will be encoded in UTF-8.
489 *
490 * @return string
491 */
492 function openStream() {
493 global $wgLanguageCode;
494 $ver = WikiExporter::schemaVersion();
495 return Xml::element( 'mediawiki', array(
496 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
497 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
498 /*
499 * When a new version of the schema is created, it needs staging on mediawiki.org.
500 * This requires a change in the operations/mediawiki-config git repo.
501 *
502 * Create a changeset like https://gerrit.wikimedia.org/r/#/c/149643/ in which
503 * you copy in the new xsd file.
504 *
505 * After it is reviewed, merged and deployed (sync-docroot), the index.html needs purging.
506 * echo "http://www.mediawiki.org/xml/index.html" | mwscript purgeList.php --wiki=aawiki
507 */
508 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
509 "http://www.mediawiki.org/xml/export-$ver.xsd",
510 'version' => $ver,
511 'xml:lang' => $wgLanguageCode ),
512 null ) .
513 "\n" .
514 $this->siteInfo();
515 }
516
517 /**
518 * @return string
519 */
520 function siteInfo() {
521 $info = array(
522 $this->sitename(),
523 $this->dbname(),
524 $this->homelink(),
525 $this->generator(),
526 $this->caseSetting(),
527 $this->namespaces() );
528 return " <siteinfo>\n " .
529 implode( "\n ", $info ) .
530 "\n </siteinfo>\n";
531 }
532
533 /**
534 * @return string
535 */
536 function sitename() {
537 global $wgSitename;
538 return Xml::element( 'sitename', array(), $wgSitename );
539 }
540
541 /**
542 * @return string
543 */
544 function dbname() {
545 global $wgDBname;
546 return Xml::element( 'dbname', array(), $wgDBname );
547 }
548
549 /**
550 * @return string
551 */
552 function generator() {
553 global $wgVersion;
554 return Xml::element( 'generator', array(), "MediaWiki $wgVersion" );
555 }
556
557 /**
558 * @return string
559 */
560 function homelink() {
561 return Xml::element( 'base', array(), Title::newMainPage()->getCanonicalURL() );
562 }
563
564 /**
565 * @return string
566 */
567 function caseSetting() {
568 global $wgCapitalLinks;
569 // "case-insensitive" option is reserved for future
570 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
571 return Xml::element( 'case', array(), $sensitivity );
572 }
573
574 /**
575 * @return string
576 */
577 function namespaces() {
578 global $wgContLang;
579 $spaces = "<namespaces>\n";
580 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
581 $spaces .= ' ' .
582 Xml::element( 'namespace',
583 array(
584 'key' => $ns,
585 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
586 ), $title ) . "\n";
587 }
588 $spaces .= " </namespaces>";
589 return $spaces;
590 }
591
592 /**
593 * Closes the output stream with the closing root element.
594 * Call when finished dumping things.
595 *
596 * @return string
597 */
598 function closeStream() {
599 return "</mediawiki>\n";
600 }
601
602 /**
603 * Opens a "<page>" section on the output stream, with data
604 * from the given database row.
605 *
606 * @param object $row
607 * @return string
608 */
609 public function openPage( $row ) {
610 $out = " <page>\n";
611 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
612 $out .= ' ' . Xml::elementClean( 'title', array(), self::canonicalTitle( $title ) ) . "\n";
613 $out .= ' ' . Xml::element( 'ns', array(), strval( $row->page_namespace ) ) . "\n";
614 $out .= ' ' . Xml::element( 'id', array(), strval( $row->page_id ) ) . "\n";
615 if ( $row->page_is_redirect ) {
616 $page = WikiPage::factory( $title );
617 $redirect = $page->getRedirectTarget();
618 if ( $redirect instanceof Title && $redirect->isValidRedirectTarget() ) {
619 $out .= ' ';
620 $out .= Xml::element( 'redirect', array( 'title' => self::canonicalTitle( $redirect ) ) );
621 $out .= "\n";
622 }
623 }
624
625 if ( $row->page_restrictions != '' ) {
626 $out .= ' ' . Xml::element( 'restrictions', array(),
627 strval( $row->page_restrictions ) ) . "\n";
628 }
629
630 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
631
632 return $out;
633 }
634
635 /**
636 * Closes a "<page>" section on the output stream.
637 *
638 * @access private
639 * @return string
640 */
641 function closePage() {
642 return " </page>\n";
643 }
644
645 /**
646 * Dumps a "<revision>" section on the output stream, with
647 * data filled in from the given database row.
648 *
649 * @param object $row
650 * @return string
651 * @access private
652 */
653 function writeRevision( $row ) {
654 wfProfileIn( __METHOD__ );
655
656 $out = " <revision>\n";
657 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
658 if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
659 $out .= " " . Xml::element( 'parentid', null, strval( $row->rev_parent_id ) ) . "\n";
660 }
661
662 $out .= $this->writeTimestamp( $row->rev_timestamp );
663
664 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_USER ) ) {
665 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
666 } else {
667 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
668 }
669
670 if ( isset( $row->rev_minor_edit ) && $row->rev_minor_edit ) {
671 $out .= " <minor/>\n";
672 }
673 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_COMMENT ) ) {
674 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
675 } elseif ( $row->rev_comment != '' ) {
676 $out .= " " . Xml::elementClean( 'comment', array(), strval( $row->rev_comment ) ) . "\n";
677 }
678
679 if ( isset( $row->rev_content_model ) && !is_null( $row->rev_content_model ) ) {
680 $content_model = strval( $row->rev_content_model );
681 } else {
682 // probably using $wgContentHandlerUseDB = false;
683 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
684 $content_model = ContentHandler::getDefaultModelFor( $title );
685 }
686
687 $content_handler = ContentHandler::getForModelID( $content_model );
688
689 if ( isset( $row->rev_content_format ) && !is_null( $row->rev_content_format ) ) {
690 $content_format = strval( $row->rev_content_format );
691 } else {
692 // probably using $wgContentHandlerUseDB = false;
693 $content_format = $content_handler->getDefaultFormat();
694 }
695
696 $out .= " " . Xml::element( 'model', null, strval( $content_model ) ) . "\n";
697 $out .= " " . Xml::element( 'format', null, strval( $content_format ) ) . "\n";
698
699 $text = '';
700 if ( isset( $row->rev_deleted ) && ( $row->rev_deleted & Revision::DELETED_TEXT ) ) {
701 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
702 } elseif ( isset( $row->old_text ) ) {
703 // Raw text from the database may have invalid chars
704 $text = strval( Revision::getRevisionText( $row ) );
705 $text = $content_handler->exportTransform( $text, $content_format );
706 $out .= " " . Xml::elementClean( 'text',
707 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len ) ),
708 strval( $text ) ) . "\n";
709 } else {
710 // Stub output
711 $out .= " " . Xml::element( 'text',
712 array( 'id' => $row->rev_text_id, 'bytes' => intval( $row->rev_len ) ),
713 "" ) . "\n";
714 }
715
716 if ( isset( $row->rev_sha1 )
717 && $row->rev_sha1
718 && !( $row->rev_deleted & Revision::DELETED_TEXT )
719 ) {
720 $out .= " " . Xml::element( 'sha1', null, strval( $row->rev_sha1 ) ) . "\n";
721 } else {
722 $out .= " <sha1/>\n";
723 }
724
725 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
726
727 $out .= " </revision>\n";
728
729 wfProfileOut( __METHOD__ );
730 return $out;
731 }
732
733 /**
734 * Dumps a "<logitem>" section on the output stream, with
735 * data filled in from the given database row.
736 *
737 * @param object $row
738 * @return string
739 * @access private
740 */
741 function writeLogItem( $row ) {
742 wfProfileIn( __METHOD__ );
743
744 $out = " <logitem>\n";
745 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
746
747 $out .= $this->writeTimestamp( $row->log_timestamp, " " );
748
749 if ( $row->log_deleted & LogPage::DELETED_USER ) {
750 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
751 } else {
752 $out .= $this->writeContributor( $row->log_user, $row->user_name, " " );
753 }
754
755 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
756 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
757 } elseif ( $row->log_comment != '' ) {
758 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
759 }
760
761 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
762 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
763
764 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
765 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
766 } else {
767 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
768 $out .= " " . Xml::elementClean( 'logtitle', null, self::canonicalTitle( $title ) ) . "\n";
769 $out .= " " . Xml::elementClean( 'params',
770 array( 'xml:space' => 'preserve' ),
771 strval( $row->log_params ) ) . "\n";
772 }
773
774 $out .= " </logitem>\n";
775
776 wfProfileOut( __METHOD__ );
777 return $out;
778 }
779
780 /**
781 * @param string $timestamp
782 * @param string $indent Default to six spaces
783 * @return string
784 */
785 function writeTimestamp( $timestamp, $indent = " " ) {
786 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
787 return $indent . Xml::element( 'timestamp', null, $ts ) . "\n";
788 }
789
790 /**
791 * @param int $id
792 * @param string $text
793 * @param string $indent Default to six spaces
794 * @return string
795 */
796 function writeContributor( $id, $text, $indent = " " ) {
797 $out = $indent . "<contributor>\n";
798 if ( $id || !IP::isValid( $text ) ) {
799 $out .= $indent . " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
800 $out .= $indent . " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
801 } else {
802 $out .= $indent . " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
803 }
804 $out .= $indent . "</contributor>\n";
805 return $out;
806 }
807
808 /**
809 * Warning! This data is potentially inconsistent. :(
810 * @param object $row
811 * @param bool $dumpContents
812 * @return string
813 */
814 function writeUploads( $row, $dumpContents = false ) {
815 if ( $row->page_namespace == NS_FILE ) {
816 $img = wfLocalFile( $row->page_title );
817 if ( $img && $img->exists() ) {
818 $out = '';
819 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
820 $out .= $this->writeUpload( $ver, $dumpContents );
821 }
822 $out .= $this->writeUpload( $img, $dumpContents );
823 return $out;
824 }
825 }
826 return '';
827 }
828
829 /**
830 * @param File $file
831 * @param bool $dumpContents
832 * @return string
833 */
834 function writeUpload( $file, $dumpContents = false ) {
835 if ( $file->isOld() ) {
836 $archiveName = " " .
837 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
838 } else {
839 $archiveName = '';
840 }
841 if ( $dumpContents ) {
842 $be = $file->getRepo()->getBackend();
843 # Dump file as base64
844 # Uses only XML-safe characters, so does not need escaping
845 # @todo Too bad this loads the contents into memory (script might swap)
846 $contents = ' <contents encoding="base64">' .
847 chunk_split( base64_encode(
848 $be->getFileContents( array( 'src' => $file->getPath() ) ) ) ) .
849 " </contents>\n";
850 } else {
851 $contents = '';
852 }
853 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
854 $comment = Xml::element( 'comment', array( 'deleted' => 'deleted' ) );
855 } else {
856 $comment = Xml::elementClean( 'comment', null, $file->getDescription() );
857 }
858 return " <upload>\n" .
859 $this->writeTimestamp( $file->getTimestamp() ) .
860 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
861 " " . $comment . "\n" .
862 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
863 $archiveName .
864 " " . Xml::element( 'src', null, $file->getCanonicalURL() ) . "\n" .
865 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
866 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
867 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
868 $contents .
869 " </upload>\n";
870 }
871
872 /**
873 * Return prefixed text form of title, but using the content language's
874 * canonical namespace. This skips any special-casing such as gendered
875 * user namespaces -- which while useful, are not yet listed in the
876 * XML "<siteinfo>" data so are unsafe in export.
877 *
878 * @param Title $title
879 * @return string
880 * @since 1.18
881 */
882 public static function canonicalTitle( Title $title ) {
883 if ( $title->isExternal() ) {
884 return $title->getPrefixedText();
885 }
886
887 global $wgContLang;
888 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
889
890 if ( $prefix !== '' ) {
891 $prefix .= ':';
892 }
893
894 return $prefix . $title->getText();
895 }
896 }
897
898 /**
899 * Base class for output stream; prints to stdout or buffer or wherever.
900 * @ingroup Dump
901 */
902 class DumpOutput {
903
904 /**
905 * @param string $string
906 */
907 function writeOpenStream( $string ) {
908 $this->write( $string );
909 }
910
911 /**
912 * @param string $string
913 */
914 function writeCloseStream( $string ) {
915 $this->write( $string );
916 }
917
918 /**
919 * @param object $page
920 * @param string $string
921 */
922 function writeOpenPage( $page, $string ) {
923 $this->write( $string );
924 }
925
926 /**
927 * @param string $string
928 */
929 function writeClosePage( $string ) {
930 $this->write( $string );
931 }
932
933 /**
934 * @param object $rev
935 * @param string $string
936 */
937 function writeRevision( $rev, $string ) {
938 $this->write( $string );
939 }
940
941 /**
942 * @param object $rev
943 * @param string $string
944 */
945 function writeLogItem( $rev, $string ) {
946 $this->write( $string );
947 }
948
949 /**
950 * Override to write to a different stream type.
951 * @param string $string
952 * @return bool
953 */
954 function write( $string ) {
955 print $string;
956 }
957
958 /**
959 * Close the old file, move it to a specified name,
960 * and reopen new file with the old name. Use this
961 * for writing out a file in multiple pieces
962 * at specified checkpoints (e.g. every n hours).
963 * @param string|array $newname File name. May be a string or an array with one element
964 */
965 function closeRenameAndReopen( $newname ) {
966 }
967
968 /**
969 * Close the old file, and move it to a specified name.
970 * Use this for the last piece of a file written out
971 * at specified checkpoints (e.g. every n hours).
972 * @param string|array $newname File name. May be a string or an array with one element
973 * @param bool $open If true, a new file with the old filename will be opened
974 * again for writing (default: false)
975 */
976 function closeAndRename( $newname, $open = false ) {
977 }
978
979 /**
980 * Returns the name of the file or files which are
981 * being written to, if there are any.
982 * @return null
983 */
984 function getFilenames() {
985 return null;
986 }
987 }
988
989 /**
990 * Stream outputter to send data to a file.
991 * @ingroup Dump
992 */
993 class DumpFileOutput extends DumpOutput {
994 protected $handle = false, $filename;
995
996 /**
997 * @param string $file
998 */
999 function __construct( $file ) {
1000 $this->handle = fopen( $file, "wt" );
1001 $this->filename = $file;
1002 }
1003
1004 /**
1005 * @param string $string
1006 */
1007 function writeCloseStream( $string ) {
1008 parent::writeCloseStream( $string );
1009 if ( $this->handle ) {
1010 fclose( $this->handle );
1011 $this->handle = false;
1012 }
1013 }
1014
1015 /**
1016 * @param string $string
1017 */
1018 function write( $string ) {
1019 fputs( $this->handle, $string );
1020 }
1021
1022 /**
1023 * @param string $newname
1024 */
1025 function closeRenameAndReopen( $newname ) {
1026 $this->closeAndRename( $newname, true );
1027 }
1028
1029 /**
1030 * @param string $newname
1031 * @throws MWException
1032 */
1033 function renameOrException( $newname ) {
1034 if ( !rename( $this->filename, $newname ) ) {
1035 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
1036 }
1037 }
1038
1039 /**
1040 * @param array $newname
1041 * @return string
1042 * @throws MWException
1043 */
1044 function checkRenameArgCount( $newname ) {
1045 if ( is_array( $newname ) ) {
1046 if ( count( $newname ) > 1 ) {
1047 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
1048 } else {
1049 $newname = $newname[0];
1050 }
1051 }
1052 return $newname;
1053 }
1054
1055 /**
1056 * @param string $newname
1057 * @param bool $open
1058 */
1059 function closeAndRename( $newname, $open = false ) {
1060 $newname = $this->checkRenameArgCount( $newname );
1061 if ( $newname ) {
1062 if ( $this->handle ) {
1063 fclose( $this->handle );
1064 $this->handle = false;
1065 }
1066 $this->renameOrException( $newname );
1067 if ( $open ) {
1068 $this->handle = fopen( $this->filename, "wt" );
1069 }
1070 }
1071 }
1072
1073 /**
1074 * @return string|null
1075 */
1076 function getFilenames() {
1077 return $this->filename;
1078 }
1079 }
1080
1081 /**
1082 * Stream outputter to send data to a file via some filter program.
1083 * Even if compression is available in a library, using a separate
1084 * program can allow us to make use of a multi-processor system.
1085 * @ingroup Dump
1086 */
1087 class DumpPipeOutput extends DumpFileOutput {
1088 protected $command, $filename;
1089 protected $procOpenResource = false;
1090
1091 /**
1092 * @param string $command
1093 * @param string $file
1094 */
1095 function __construct( $command, $file = null ) {
1096 if ( !is_null( $file ) ) {
1097 $command .= " > " . wfEscapeShellArg( $file );
1098 }
1099
1100 $this->startCommand( $command );
1101 $this->command = $command;
1102 $this->filename = $file;
1103 }
1104
1105 /**
1106 * @param string $string
1107 */
1108 function writeCloseStream( $string ) {
1109 parent::writeCloseStream( $string );
1110 if ( $this->procOpenResource ) {
1111 proc_close( $this->procOpenResource );
1112 $this->procOpenResource = false;
1113 }
1114 }
1115
1116 /**
1117 * @param string $command
1118 */
1119 function startCommand( $command ) {
1120 $spec = array(
1121 0 => array( "pipe", "r" ),
1122 );
1123 $pipes = array();
1124 $this->procOpenResource = proc_open( $command, $spec, $pipes );
1125 $this->handle = $pipes[0];
1126 }
1127
1128 /**
1129 * @param string $newname
1130 */
1131 function closeRenameAndReopen( $newname ) {
1132 $this->closeAndRename( $newname, true );
1133 }
1134
1135 /**
1136 * @param string $newname
1137 * @param bool $open
1138 */
1139 function closeAndRename( $newname, $open = false ) {
1140 $newname = $this->checkRenameArgCount( $newname );
1141 if ( $newname ) {
1142 if ( $this->handle ) {
1143 fclose( $this->handle );
1144 $this->handle = false;
1145 }
1146 if ( $this->procOpenResource ) {
1147 proc_close( $this->procOpenResource );
1148 $this->procOpenResource = false;
1149 }
1150 $this->renameOrException( $newname );
1151 if ( $open ) {
1152 $command = $this->command;
1153 $command .= " > " . wfEscapeShellArg( $this->filename );
1154 $this->startCommand( $command );
1155 }
1156 }
1157 }
1158 }
1159
1160 /**
1161 * Sends dump output via the gzip compressor.
1162 * @ingroup Dump
1163 */
1164 class DumpGZipOutput extends DumpPipeOutput {
1165 /**
1166 * @param string $file
1167 */
1168 function __construct( $file ) {
1169 parent::__construct( "gzip", $file );
1170 }
1171 }
1172
1173 /**
1174 * Sends dump output via the bgzip2 compressor.
1175 * @ingroup Dump
1176 */
1177 class DumpBZip2Output extends DumpPipeOutput {
1178 /**
1179 * @param string $file
1180 */
1181 function __construct( $file ) {
1182 parent::__construct( "bzip2", $file );
1183 }
1184 }
1185
1186 /**
1187 * Sends dump output via the p7zip compressor.
1188 * @ingroup Dump
1189 */
1190 class Dump7ZipOutput extends DumpPipeOutput {
1191 /**
1192 * @param string $file
1193 */
1194 function __construct( $file ) {
1195 $command = $this->setup7zCommand( $file );
1196 parent::__construct( $command );
1197 $this->filename = $file;
1198 }
1199
1200 /**
1201 * @param string $file
1202 * @return string
1203 */
1204 function setup7zCommand( $file ) {
1205 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1206 // Suppress annoying useless crap from p7zip
1207 // Unfortunately this could suppress real error messages too
1208 $command .= ' >' . wfGetNull() . ' 2>&1';
1209 return $command;
1210 }
1211
1212 /**
1213 * @param string $newname
1214 * @param bool $open
1215 */
1216 function closeAndRename( $newname, $open = false ) {
1217 $newname = $this->checkRenameArgCount( $newname );
1218 if ( $newname ) {
1219 fclose( $this->handle );
1220 proc_close( $this->procOpenResource );
1221 $this->renameOrException( $newname );
1222 if ( $open ) {
1223 $command = $this->setup7zCommand( $this->filename );
1224 $this->startCommand( $command );
1225 }
1226 }
1227 }
1228 }
1229
1230 /**
1231 * Dump output filter class.
1232 * This just does output filtering and streaming; XML formatting is done
1233 * higher up, so be careful in what you do.
1234 * @ingroup Dump
1235 */
1236 class DumpFilter {
1237 /**
1238 * @var DumpOutput
1239 * FIXME will need to be made protected whenever legacy code
1240 * is updated.
1241 */
1242 public $sink;
1243
1244 /**
1245 * @var bool
1246 */
1247 protected $sendingThisPage;
1248
1249 /**
1250 * @param DumpOutput $sink
1251 */
1252 function __construct( &$sink ) {
1253 $this->sink =& $sink;
1254 }
1255
1256 /**
1257 * @param string $string
1258 */
1259 function writeOpenStream( $string ) {
1260 $this->sink->writeOpenStream( $string );
1261 }
1262
1263 /**
1264 * @param string $string
1265 */
1266 function writeCloseStream( $string ) {
1267 $this->sink->writeCloseStream( $string );
1268 }
1269
1270 /**
1271 * @param object $page
1272 * @param string $string
1273 */
1274 function writeOpenPage( $page, $string ) {
1275 $this->sendingThisPage = $this->pass( $page, $string );
1276 if ( $this->sendingThisPage ) {
1277 $this->sink->writeOpenPage( $page, $string );
1278 }
1279 }
1280
1281 /**
1282 * @param string $string
1283 */
1284 function writeClosePage( $string ) {
1285 if ( $this->sendingThisPage ) {
1286 $this->sink->writeClosePage( $string );
1287 $this->sendingThisPage = false;
1288 }
1289 }
1290
1291 /**
1292 * @param object $rev
1293 * @param string $string
1294 */
1295 function writeRevision( $rev, $string ) {
1296 if ( $this->sendingThisPage ) {
1297 $this->sink->writeRevision( $rev, $string );
1298 }
1299 }
1300
1301 /**
1302 * @param object $rev
1303 * @param string $string
1304 */
1305 function writeLogItem( $rev, $string ) {
1306 $this->sink->writeRevision( $rev, $string );
1307 }
1308
1309 /**
1310 * @param string $newname
1311 */
1312 function closeRenameAndReopen( $newname ) {
1313 $this->sink->closeRenameAndReopen( $newname );
1314 }
1315
1316 /**
1317 * @param string $newname
1318 * @param bool $open
1319 */
1320 function closeAndRename( $newname, $open = false ) {
1321 $this->sink->closeAndRename( $newname, $open );
1322 }
1323
1324 /**
1325 * @return array
1326 */
1327 function getFilenames() {
1328 return $this->sink->getFilenames();
1329 }
1330
1331 /**
1332 * Override for page-based filter types.
1333 * @param object $page
1334 * @return bool
1335 */
1336 function pass( $page ) {
1337 return true;
1338 }
1339 }
1340
1341 /**
1342 * Simple dump output filter to exclude all talk pages.
1343 * @ingroup Dump
1344 */
1345 class DumpNotalkFilter extends DumpFilter {
1346 /**
1347 * @param object $page
1348 * @return bool
1349 */
1350 function pass( $page ) {
1351 return !MWNamespace::isTalk( $page->page_namespace );
1352 }
1353 }
1354
1355 /**
1356 * Dump output filter to include or exclude pages in a given set of namespaces.
1357 * @ingroup Dump
1358 */
1359 class DumpNamespaceFilter extends DumpFilter {
1360 /** @var bool */
1361 public $invert = false;
1362
1363 /** @var array */
1364 public $namespaces = array();
1365
1366 /**
1367 * @param DumpOutput $sink
1368 * @param array $param
1369 * @throws MWException
1370 */
1371 function __construct( &$sink, $param ) {
1372 parent::__construct( $sink );
1373
1374 $constants = array(
1375 "NS_MAIN" => NS_MAIN,
1376 "NS_TALK" => NS_TALK,
1377 "NS_USER" => NS_USER,
1378 "NS_USER_TALK" => NS_USER_TALK,
1379 "NS_PROJECT" => NS_PROJECT,
1380 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
1381 "NS_FILE" => NS_FILE,
1382 "NS_FILE_TALK" => NS_FILE_TALK,
1383 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
1384 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
1385 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
1386 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
1387 "NS_TEMPLATE" => NS_TEMPLATE,
1388 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
1389 "NS_HELP" => NS_HELP,
1390 "NS_HELP_TALK" => NS_HELP_TALK,
1391 "NS_CATEGORY" => NS_CATEGORY,
1392 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
1393
1394 if ( $param { 0 } == '!' ) {
1395 $this->invert = true;
1396 $param = substr( $param, 1 );
1397 }
1398
1399 foreach ( explode( ',', $param ) as $key ) {
1400 $key = trim( $key );
1401 if ( isset( $constants[$key] ) ) {
1402 $ns = $constants[$key];
1403 $this->namespaces[$ns] = true;
1404 } elseif ( is_numeric( $key ) ) {
1405 $ns = intval( $key );
1406 $this->namespaces[$ns] = true;
1407 } else {
1408 throw new MWException( "Unrecognized namespace key '$key'\n" );
1409 }
1410 }
1411 }
1412
1413 /**
1414 * @param object $page
1415 * @return bool
1416 */
1417 function pass( $page ) {
1418 $match = isset( $this->namespaces[$page->page_namespace] );
1419 return $this->invert xor $match;
1420 }
1421 }
1422
1423 /**
1424 * Dump output filter to include only the last revision in each page sequence.
1425 * @ingroup Dump
1426 */
1427 class DumpLatestFilter extends DumpFilter {
1428 public $page;
1429
1430 public $pageString;
1431
1432 public $rev;
1433
1434 public $revString;
1435
1436 /**
1437 * @param object $page
1438 * @param string $string
1439 */
1440 function writeOpenPage( $page, $string ) {
1441 $this->page = $page;
1442 $this->pageString = $string;
1443 }
1444
1445 /**
1446 * @param string $string
1447 */
1448 function writeClosePage( $string ) {
1449 if ( $this->rev ) {
1450 $this->sink->writeOpenPage( $this->page, $this->pageString );
1451 $this->sink->writeRevision( $this->rev, $this->revString );
1452 $this->sink->writeClosePage( $string );
1453 }
1454 $this->rev = null;
1455 $this->revString = null;
1456 $this->page = null;
1457 $this->pageString = null;
1458 }
1459
1460 /**
1461 * @param object $rev
1462 * @param string $string
1463 */
1464 function writeRevision( $rev, $string ) {
1465 if ( $rev->rev_id == $this->page->page_latest ) {
1466 $this->rev = $rev;
1467 $this->revString = $string;
1468 }
1469 }
1470 }
1471
1472 /**
1473 * Base class for output stream; prints to stdout or buffer or wherever.
1474 * @ingroup Dump
1475 */
1476 class DumpMultiWriter {
1477
1478 /**
1479 * @param array $sinks
1480 */
1481 function __construct( $sinks ) {
1482 $this->sinks = $sinks;
1483 $this->count = count( $sinks );
1484 }
1485
1486 /**
1487 * @param string $string
1488 */
1489 function writeOpenStream( $string ) {
1490 for ( $i = 0; $i < $this->count; $i++ ) {
1491 $this->sinks[$i]->writeOpenStream( $string );
1492 }
1493 }
1494
1495 /**
1496 * @param string $string
1497 */
1498 function writeCloseStream( $string ) {
1499 for ( $i = 0; $i < $this->count; $i++ ) {
1500 $this->sinks[$i]->writeCloseStream( $string );
1501 }
1502 }
1503
1504 /**
1505 * @param object $page
1506 * @param string $string
1507 */
1508 function writeOpenPage( $page, $string ) {
1509 for ( $i = 0; $i < $this->count; $i++ ) {
1510 $this->sinks[$i]->writeOpenPage( $page, $string );
1511 }
1512 }
1513
1514 /**
1515 * @param string $string
1516 */
1517 function writeClosePage( $string ) {
1518 for ( $i = 0; $i < $this->count; $i++ ) {
1519 $this->sinks[$i]->writeClosePage( $string );
1520 }
1521 }
1522
1523 /**
1524 * @param object $rev
1525 * @param string $string
1526 */
1527 function writeRevision( $rev, $string ) {
1528 for ( $i = 0; $i < $this->count; $i++ ) {
1529 $this->sinks[$i]->writeRevision( $rev, $string );
1530 }
1531 }
1532
1533 /**
1534 * @param array $newnames
1535 */
1536 function closeRenameAndReopen( $newnames ) {
1537 $this->closeAndRename( $newnames, true );
1538 }
1539
1540 /**
1541 * @param array $newnames
1542 * @param bool $open
1543 */
1544 function closeAndRename( $newnames, $open = false ) {
1545 for ( $i = 0; $i < $this->count; $i++ ) {
1546 $this->sinks[$i]->closeAndRename( $newnames[$i], $open );
1547 }
1548 }
1549
1550 /**
1551 * @return array
1552 */
1553 function getFilenames() {
1554 $filenames = array();
1555 for ( $i = 0; $i < $this->count; $i++ ) {
1556 $filenames[] = $this->sinks[$i]->getFilenames();
1557 }
1558 return $filenames;
1559 }
1560 }