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