Add a way for packagers to override some installation details
[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 ( $row->rev_sha1 && !( $row->rev_deleted & Revision::DELETED_TEXT ) ) {
648 $out .= " " . Xml::element('sha1', null, strval( $row->rev_sha1 ) ) . "\n";
649 } else {
650 $out .= " <sha1/>\n";
651 }
652
653 $text = '';
654 if ( $row->rev_deleted & Revision::DELETED_TEXT ) {
655 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
656 } elseif ( isset( $row->old_text ) ) {
657 // Raw text from the database may have invalid chars
658 $text = strval( Revision::getRevisionText( $row ) );
659 $out .= " " . Xml::elementClean( 'text',
660 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len ) ),
661 strval( $text ) ) . "\n";
662 } else {
663 // Stub output
664 $out .= " " . Xml::element( 'text',
665 array( 'id' => $row->rev_text_id, 'bytes' => intval( $row->rev_len ) ),
666 "" ) . "\n";
667 }
668
669 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
670
671 $out .= " </revision>\n";
672
673 wfProfileOut( __METHOD__ );
674 return $out;
675 }
676
677 /**
678 * Dumps a <logitem> section on the output stream, with
679 * data filled in from the given database row.
680 *
681 * @param $row object
682 * @return string
683 * @access private
684 */
685 function writeLogItem( $row ) {
686 wfProfileIn( __METHOD__ );
687
688 $out = " <logitem>\n";
689 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
690
691 $out .= $this->writeTimestamp( $row->log_timestamp, " " );
692
693 if ( $row->log_deleted & LogPage::DELETED_USER ) {
694 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
695 } else {
696 $out .= $this->writeContributor( $row->log_user, $row->user_name, " " );
697 }
698
699 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
700 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
701 } elseif ( $row->log_comment != '' ) {
702 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
703 }
704
705 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
706 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
707
708 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
709 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
710 } else {
711 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
712 $out .= " " . Xml::elementClean( 'logtitle', null, self::canonicalTitle( $title ) ) . "\n";
713 $out .= " " . Xml::elementClean( 'params',
714 array( 'xml:space' => 'preserve' ),
715 strval( $row->log_params ) ) . "\n";
716 }
717
718 $out .= " </logitem>\n";
719
720 wfProfileOut( __METHOD__ );
721 return $out;
722 }
723
724 /**
725 * @param $timestamp string
726 * @return string
727 */
728 function writeTimestamp( $timestamp, $indent = " " ) {
729 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
730 return $indent . Xml::element( 'timestamp', null, $ts ) . "\n";
731 }
732
733 /**
734 * @param $id
735 * @param $text string
736 * @return string
737 */
738 function writeContributor( $id, $text, $indent = " " ) {
739 $out = $indent . "<contributor>\n";
740 if ( $id || !IP::isValid( $text ) ) {
741 $out .= $indent . " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
742 $out .= $indent . " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
743 } else {
744 $out .= $indent . " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
745 }
746 $out .= $indent . "</contributor>\n";
747 return $out;
748 }
749
750 /**
751 * Warning! This data is potentially inconsistent. :(
752 * @param $row
753 * @param $dumpContents bool
754 * @return string
755 */
756 function writeUploads( $row, $dumpContents = false ) {
757 if ( $row->page_namespace == NS_IMAGE ) {
758 $img = wfLocalFile( $row->page_title );
759 if ( $img && $img->exists() ) {
760 $out = '';
761 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
762 $out .= $this->writeUpload( $ver, $dumpContents );
763 }
764 $out .= $this->writeUpload( $img, $dumpContents );
765 return $out;
766 }
767 }
768 return '';
769 }
770
771 /**
772 * @param $file File
773 * @param $dumpContents bool
774 * @return string
775 */
776 function writeUpload( $file, $dumpContents = false ) {
777 if ( $file->isOld() ) {
778 $archiveName = " " .
779 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
780 } else {
781 $archiveName = '';
782 }
783 if ( $dumpContents ) {
784 # Dump file as base64
785 # Uses only XML-safe characters, so does not need escaping
786 $contents = ' <contents encoding="base64">' .
787 chunk_split( base64_encode( file_get_contents( $file->getPath() ) ) ) .
788 " </contents>\n";
789 } else {
790 $contents = '';
791 }
792 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
793 $comment = Xml::element( 'comment', array( 'deleted' => 'deleted' ) );
794 } else {
795 $comment = Xml::elementClean( 'comment', null, $file->getDescription() );
796 }
797 return " <upload>\n" .
798 $this->writeTimestamp( $file->getTimestamp() ) .
799 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
800 " " . $comment . "\n" .
801 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
802 $archiveName .
803 " " . Xml::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
804 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
805 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
806 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
807 $contents .
808 " </upload>\n";
809 }
810
811 /**
812 * Return prefixed text form of title, but using the content language's
813 * canonical namespace. This skips any special-casing such as gendered
814 * user namespaces -- which while useful, are not yet listed in the
815 * XML <siteinfo> data so are unsafe in export.
816 *
817 * @param Title $title
818 * @return string
819 * @since 1.18
820 */
821 public static function canonicalTitle( Title $title ) {
822 if ( $title->getInterwiki() ) {
823 return $title->getPrefixedText();
824 }
825
826 global $wgContLang;
827 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
828
829 if ( $prefix !== '' ) {
830 $prefix .= ':';
831 }
832
833 return $prefix . $title->getText();
834 }
835 }
836
837
838 /**
839 * Base class for output stream; prints to stdout or buffer or whereever.
840 * @ingroup Dump
841 */
842 class DumpOutput {
843
844 /**
845 * @param $string string
846 */
847 function writeOpenStream( $string ) {
848 $this->write( $string );
849 }
850
851 /**
852 * @param $string string
853 */
854 function writeCloseStream( $string ) {
855 $this->write( $string );
856 }
857
858 /**
859 * @param $page
860 * @param $string string
861 */
862 function writeOpenPage( $page, $string ) {
863 $this->write( $string );
864 }
865
866 /**
867 * @param $string string
868 */
869 function writeClosePage( $string ) {
870 $this->write( $string );
871 }
872
873 /**
874 * @param $rev
875 * @param $string string
876 */
877 function writeRevision( $rev, $string ) {
878 $this->write( $string );
879 }
880
881 /**
882 * @param $rev
883 * @param $string string
884 */
885 function writeLogItem( $rev, $string ) {
886 $this->write( $string );
887 }
888
889 /**
890 * Override to write to a different stream type.
891 * @param $string string
892 * @return bool
893 */
894 function write( $string ) {
895 print $string;
896 }
897
898 /**
899 * Close the old file, move it to a specified name,
900 * and reopen new file with the old name. Use this
901 * for writing out a file in multiple pieces
902 * at specified checkpoints (e.g. every n hours).
903 * @param $newname mixed File name. May be a string or an array with one element
904 */
905 function closeRenameAndReopen( $newname ) {
906 return;
907 }
908
909 /**
910 * Close the old file, and move it to a specified name.
911 * Use this for the last piece of a file written out
912 * at specified checkpoints (e.g. every n hours).
913 * @param $newname mixed File name. May be a string or an array with one element
914 * @param $open bool If true, a new file with the old filename will be opened again for writing (default: false)
915 */
916 function closeAndRename( $newname, $open = false ) {
917 return;
918 }
919
920 /**
921 * Returns the name of the file or files which are
922 * being written to, if there are any.
923 * @return null
924 */
925 function getFilenames() {
926 return NULL;
927 }
928 }
929
930 /**
931 * Stream outputter to send data to a file.
932 * @ingroup Dump
933 */
934 class DumpFileOutput extends DumpOutput {
935 protected $handle = false, $filename;
936
937 /**
938 * @param $file
939 */
940 function __construct( $file ) {
941 $this->handle = fopen( $file, "wt" );
942 $this->filename = $file;
943 }
944
945 /**
946 * @param $string string
947 */
948 function writeCloseStream( $string ) {
949 parent::writeCloseStream( $string );
950 if ( $this->handle ) {
951 fclose( $this->handle );
952 $this->handle = false;
953 }
954 }
955
956 /**
957 * @param $string string
958 */
959 function write( $string ) {
960 fputs( $this->handle, $string );
961 }
962
963 /**
964 * @param $newname
965 */
966 function closeRenameAndReopen( $newname ) {
967 $this->closeAndRename( $newname, true );
968 }
969
970 /**
971 * @param $newname
972 * @throws MWException
973 */
974 function renameOrException( $newname ) {
975 if (! rename( $this->filename, $newname ) ) {
976 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
977 }
978 }
979
980 /**
981 * @param $newname array
982 * @return mixed
983 * @throws MWException
984 */
985 function checkRenameArgCount( $newname ) {
986 if ( is_array( $newname ) ) {
987 if ( count( $newname ) > 1 ) {
988 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
989 } else {
990 $newname = $newname[0];
991 }
992 }
993 return $newname;
994 }
995
996 /**
997 * @param $newname mixed
998 * @param $open bool
999 */
1000 function closeAndRename( $newname, $open = false ) {
1001 $newname = $this->checkRenameArgCount( $newname );
1002 if ( $newname ) {
1003 if ( $this->handle ) {
1004 fclose( $this->handle );
1005 $this->handle = false;
1006 }
1007 $this->renameOrException( $newname );
1008 if ( $open ) {
1009 $this->handle = fopen( $this->filename, "wt" );
1010 }
1011 }
1012 }
1013
1014 /**
1015 * @return string|null
1016 */
1017 function getFilenames() {
1018 return $this->filename;
1019 }
1020 }
1021
1022 /**
1023 * Stream outputter to send data to a file via some filter program.
1024 * Even if compression is available in a library, using a separate
1025 * program can allow us to make use of a multi-processor system.
1026 * @ingroup Dump
1027 */
1028 class DumpPipeOutput extends DumpFileOutput {
1029 protected $command, $filename;
1030 protected $procOpenResource = false;
1031
1032 /**
1033 * @param $command
1034 * @param $file null
1035 */
1036 function __construct( $command, $file = null ) {
1037 if ( !is_null( $file ) ) {
1038 $command .= " > " . wfEscapeShellArg( $file );
1039 }
1040
1041 $this->startCommand( $command );
1042 $this->command = $command;
1043 $this->filename = $file;
1044 }
1045
1046 /**
1047 * @param $string string
1048 */
1049 function writeCloseStream( $string ) {
1050 parent::writeCloseStream( $string );
1051 if ( $this->procOpenResource ) {
1052 proc_close( $this->procOpenResource );
1053 $this->procOpenResource = false;
1054 }
1055 }
1056
1057 /**
1058 * @param $command
1059 */
1060 function startCommand( $command ) {
1061 $spec = array(
1062 0 => array( "pipe", "r" ),
1063 );
1064 $pipes = array();
1065 $this->procOpenResource = proc_open( $command, $spec, $pipes );
1066 $this->handle = $pipes[0];
1067 }
1068
1069 /**
1070 * @param mixed $newname
1071 */
1072 function closeRenameAndReopen( $newname ) {
1073 $this->closeAndRename( $newname, true );
1074 }
1075
1076 /**
1077 * @param $newname mixed
1078 * @param $open bool
1079 */
1080 function closeAndRename( $newname, $open = false ) {
1081 $newname = $this->checkRenameArgCount( $newname );
1082 if ( $newname ) {
1083 if ( $this->handle ) {
1084 fclose( $this->handle );
1085 $this->handle = false;
1086 }
1087 if ( $this->procOpenResource ) {
1088 proc_close( $this->procOpenResource );
1089 $this->procOpenResource = false;
1090 }
1091 $this->renameOrException( $newname );
1092 if ( $open ) {
1093 $command = $this->command;
1094 $command .= " > " . wfEscapeShellArg( $this->filename );
1095 $this->startCommand( $command );
1096 }
1097 }
1098 }
1099
1100 }
1101
1102 /**
1103 * Sends dump output via the gzip compressor.
1104 * @ingroup Dump
1105 */
1106 class DumpGZipOutput extends DumpPipeOutput {
1107
1108 /**
1109 * @param $file string
1110 */
1111 function __construct( $file ) {
1112 parent::__construct( "gzip", $file );
1113 }
1114 }
1115
1116 /**
1117 * Sends dump output via the bgzip2 compressor.
1118 * @ingroup Dump
1119 */
1120 class DumpBZip2Output extends DumpPipeOutput {
1121
1122 /**
1123 * @param $file string
1124 */
1125 function __construct( $file ) {
1126 parent::__construct( "bzip2", $file );
1127 }
1128 }
1129
1130 /**
1131 * Sends dump output via the p7zip compressor.
1132 * @ingroup Dump
1133 */
1134 class Dump7ZipOutput extends DumpPipeOutput {
1135
1136 /**
1137 * @param $file string
1138 */
1139 function __construct( $file ) {
1140 $command = $this->setup7zCommand( $file );
1141 parent::__construct( $command );
1142 $this->filename = $file;
1143 }
1144
1145 /**
1146 * @param $file string
1147 * @return string
1148 */
1149 function setup7zCommand( $file ) {
1150 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1151 // Suppress annoying useless crap from p7zip
1152 // Unfortunately this could suppress real error messages too
1153 $command .= ' >' . wfGetNull() . ' 2>&1';
1154 return( $command );
1155 }
1156
1157 /**
1158 * @param $newname string
1159 * @param $open bool
1160 */
1161 function closeAndRename( $newname, $open = false ) {
1162 $newname = $this->checkRenameArgCount( $newname );
1163 if ( $newname ) {
1164 fclose( $this->handle );
1165 proc_close( $this->procOpenResource );
1166 $this->renameOrException( $newname );
1167 if ( $open ) {
1168 $command = $this->setup7zCommand( $this->filename );
1169 $this->startCommand( $command );
1170 }
1171 }
1172 }
1173 }
1174
1175 /**
1176 * Dump output filter class.
1177 * This just does output filtering and streaming; XML formatting is done
1178 * higher up, so be careful in what you do.
1179 * @ingroup Dump
1180 */
1181 class DumpFilter {
1182
1183 /**
1184 * @var DumpOutput
1185 * FIXME will need to be made protected whenever legacy code
1186 * is updated.
1187 */
1188 public $sink;
1189
1190 /**
1191 * @var bool
1192 */
1193 protected $sendingThisPage;
1194
1195 /**
1196 * @param $sink DumpOutput
1197 */
1198 function __construct( &$sink ) {
1199 $this->sink =& $sink;
1200 }
1201
1202 /**
1203 * @param $string string
1204 */
1205 function writeOpenStream( $string ) {
1206 $this->sink->writeOpenStream( $string );
1207 }
1208
1209 /**
1210 * @param $string string
1211 */
1212 function writeCloseStream( $string ) {
1213 $this->sink->writeCloseStream( $string );
1214 }
1215
1216 /**
1217 * @param $page
1218 * @param $string string
1219 */
1220 function writeOpenPage( $page, $string ) {
1221 $this->sendingThisPage = $this->pass( $page, $string );
1222 if ( $this->sendingThisPage ) {
1223 $this->sink->writeOpenPage( $page, $string );
1224 }
1225 }
1226
1227 /**
1228 * @param $string string
1229 */
1230 function writeClosePage( $string ) {
1231 if ( $this->sendingThisPage ) {
1232 $this->sink->writeClosePage( $string );
1233 $this->sendingThisPage = false;
1234 }
1235 }
1236
1237 /**
1238 * @param $rev
1239 * @param $string string
1240 */
1241 function writeRevision( $rev, $string ) {
1242 if ( $this->sendingThisPage ) {
1243 $this->sink->writeRevision( $rev, $string );
1244 }
1245 }
1246
1247 /**
1248 * @param $rev
1249 * @param $string string
1250 */
1251 function writeLogItem( $rev, $string ) {
1252 $this->sink->writeRevision( $rev, $string );
1253 }
1254
1255 /**
1256 * @param $newname string
1257 */
1258 function closeRenameAndReopen( $newname ) {
1259 $this->sink->closeRenameAndReopen( $newname );
1260 }
1261
1262 /**
1263 * @param $newname string
1264 * @param $open bool
1265 */
1266 function closeAndRename( $newname, $open = false ) {
1267 $this->sink->closeAndRename( $newname, $open );
1268 }
1269
1270 /**
1271 * @return array
1272 */
1273 function getFilenames() {
1274 return $this->sink->getFilenames();
1275 }
1276
1277 /**
1278 * Override for page-based filter types.
1279 * @param $page
1280 * @return bool
1281 */
1282 function pass( $page ) {
1283 return true;
1284 }
1285 }
1286
1287 /**
1288 * Simple dump output filter to exclude all talk pages.
1289 * @ingroup Dump
1290 */
1291 class DumpNotalkFilter extends DumpFilter {
1292
1293 /**
1294 * @param $page
1295 * @return bool
1296 */
1297 function pass( $page ) {
1298 return !MWNamespace::isTalk( $page->page_namespace );
1299 }
1300 }
1301
1302 /**
1303 * Dump output filter to include or exclude pages in a given set of namespaces.
1304 * @ingroup Dump
1305 */
1306 class DumpNamespaceFilter extends DumpFilter {
1307 var $invert = false;
1308 var $namespaces = array();
1309
1310 /**
1311 * @param $sink DumpOutput
1312 * @param $param
1313 */
1314 function __construct( &$sink, $param ) {
1315 parent::__construct( $sink );
1316
1317 $constants = array(
1318 "NS_MAIN" => NS_MAIN,
1319 "NS_TALK" => NS_TALK,
1320 "NS_USER" => NS_USER,
1321 "NS_USER_TALK" => NS_USER_TALK,
1322 "NS_PROJECT" => NS_PROJECT,
1323 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
1324 "NS_FILE" => NS_FILE,
1325 "NS_FILE_TALK" => NS_FILE_TALK,
1326 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
1327 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
1328 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
1329 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
1330 "NS_TEMPLATE" => NS_TEMPLATE,
1331 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
1332 "NS_HELP" => NS_HELP,
1333 "NS_HELP_TALK" => NS_HELP_TALK,
1334 "NS_CATEGORY" => NS_CATEGORY,
1335 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
1336
1337 if ( $param { 0 } == '!' ) {
1338 $this->invert = true;
1339 $param = substr( $param, 1 );
1340 }
1341
1342 foreach ( explode( ',', $param ) as $key ) {
1343 $key = trim( $key );
1344 if ( isset( $constants[$key] ) ) {
1345 $ns = $constants[$key];
1346 $this->namespaces[$ns] = true;
1347 } elseif ( is_numeric( $key ) ) {
1348 $ns = intval( $key );
1349 $this->namespaces[$ns] = true;
1350 } else {
1351 throw new MWException( "Unrecognized namespace key '$key'\n" );
1352 }
1353 }
1354 }
1355
1356 /**
1357 * @param $page
1358 * @return bool
1359 */
1360 function pass( $page ) {
1361 $match = isset( $this->namespaces[$page->page_namespace] );
1362 return $this->invert xor $match;
1363 }
1364 }
1365
1366
1367 /**
1368 * Dump output filter to include only the last revision in each page sequence.
1369 * @ingroup Dump
1370 */
1371 class DumpLatestFilter extends DumpFilter {
1372 var $page, $pageString, $rev, $revString;
1373
1374 /**
1375 * @param $page
1376 * @param $string string
1377 */
1378 function writeOpenPage( $page, $string ) {
1379 $this->page = $page;
1380 $this->pageString = $string;
1381 }
1382
1383 /**
1384 * @param $string string
1385 */
1386 function writeClosePage( $string ) {
1387 if ( $this->rev ) {
1388 $this->sink->writeOpenPage( $this->page, $this->pageString );
1389 $this->sink->writeRevision( $this->rev, $this->revString );
1390 $this->sink->writeClosePage( $string );
1391 }
1392 $this->rev = null;
1393 $this->revString = null;
1394 $this->page = null;
1395 $this->pageString = null;
1396 }
1397
1398 /**
1399 * @param $rev
1400 * @param $string string
1401 */
1402 function writeRevision( $rev, $string ) {
1403 if ( $rev->rev_id == $this->page->page_latest ) {
1404 $this->rev = $rev;
1405 $this->revString = $string;
1406 }
1407 }
1408 }
1409
1410 /**
1411 * Base class for output stream; prints to stdout or buffer or whereever.
1412 * @ingroup Dump
1413 */
1414 class DumpMultiWriter {
1415
1416 /**
1417 * @param $sinks
1418 */
1419 function __construct( $sinks ) {
1420 $this->sinks = $sinks;
1421 $this->count = count( $sinks );
1422 }
1423
1424 /**
1425 * @param $string string
1426 */
1427 function writeOpenStream( $string ) {
1428 for ( $i = 0; $i < $this->count; $i++ ) {
1429 $this->sinks[$i]->writeOpenStream( $string );
1430 }
1431 }
1432
1433 /**
1434 * @param $string string
1435 */
1436 function writeCloseStream( $string ) {
1437 for ( $i = 0; $i < $this->count; $i++ ) {
1438 $this->sinks[$i]->writeCloseStream( $string );
1439 }
1440 }
1441
1442 /**
1443 * @param $page
1444 * @param $string string
1445 */
1446 function writeOpenPage( $page, $string ) {
1447 for ( $i = 0; $i < $this->count; $i++ ) {
1448 $this->sinks[$i]->writeOpenPage( $page, $string );
1449 }
1450 }
1451
1452 /**
1453 * @param $string
1454 */
1455 function writeClosePage( $string ) {
1456 for ( $i = 0; $i < $this->count; $i++ ) {
1457 $this->sinks[$i]->writeClosePage( $string );
1458 }
1459 }
1460
1461 /**
1462 * @param $rev
1463 * @param $string
1464 */
1465 function writeRevision( $rev, $string ) {
1466 for ( $i = 0; $i < $this->count; $i++ ) {
1467 $this->sinks[$i]->writeRevision( $rev, $string );
1468 }
1469 }
1470
1471 /**
1472 * @param $newnames
1473 */
1474 function closeRenameAndReopen( $newnames ) {
1475 $this->closeAndRename( $newnames, true );
1476 }
1477
1478 /**
1479 * @param $newnames array
1480 * @param bool $open
1481 */
1482 function closeAndRename( $newnames, $open = false ) {
1483 for ( $i = 0; $i < $this->count; $i++ ) {
1484 $this->sinks[$i]->closeAndRename( $newnames[$i], $open );
1485 }
1486 }
1487
1488 /**
1489 * @return array
1490 */
1491 function getFilenames() {
1492 $filenames = array();
1493 for ( $i = 0; $i < $this->count; $i++ ) {
1494 $filenames[] = $this->sinks[$i]->getFilenames();
1495 }
1496 return $filenames;
1497 }
1498
1499 }
1500
1501 /**
1502 * @param $string string
1503 * @return string
1504 */
1505 function xmlsafe( $string ) {
1506 wfProfileIn( __FUNCTION__ );
1507
1508 /**
1509 * The page may contain old data which has not been properly normalized.
1510 * Invalid UTF-8 sequences or forbidden control characters will make our
1511 * XML output invalid, so be sure to strip them out.
1512 */
1513 $string = UtfNormal::cleanUp( $string );
1514
1515 $string = htmlspecialchars( $string );
1516 wfProfileOut( __FUNCTION__ );
1517 return $string;
1518 }