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