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