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