Merge "Fix variable collision"
[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 return $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 return $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 return $this->dumpFrom( $condition );
137 }
138
139 /**
140 * @param $title Title
141 */
142 public function pageByTitle( $title ) {
143 return $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 return $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 return $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 return $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 $text = '';
598 if ( $row->rev_deleted & Revision::DELETED_TEXT ) {
599 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
600 } elseif ( isset( $row->old_text ) ) {
601 // Raw text from the database may have invalid chars
602 $text = strval( Revision::getRevisionText( $row ) );
603 $out .= " " . Xml::elementClean( 'text',
604 array( 'xml:space' => 'preserve', 'bytes' => intval( $row->rev_len ) ),
605 strval( $text ) ) . "\n";
606 } else {
607 // Stub output
608 $out .= " " . Xml::element( 'text',
609 array( 'id' => $row->rev_text_id, 'bytes' => intval( $row->rev_len ) ),
610 "" ) . "\n";
611 }
612
613 if ( $row->rev_sha1 && !( $row->rev_deleted & Revision::DELETED_TEXT ) ) {
614 $out .= " " . Xml::element('sha1', null, strval( $row->rev_sha1 ) ) . "\n";
615 } else {
616 $out .= " <sha1/>\n";
617 }
618
619 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
620
621 $out .= " </revision>\n";
622
623 wfProfileOut( __METHOD__ );
624 return $out;
625 }
626
627 /**
628 * Dumps a <logitem> 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 writeLogItem( $row ) {
636 wfProfileIn( __METHOD__ );
637
638 $out = " <logitem>\n";
639 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
640
641 $out .= $this->writeTimestamp( $row->log_timestamp );
642
643 if ( $row->log_deleted & LogPage::DELETED_USER ) {
644 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
645 } else {
646 $out .= $this->writeContributor( $row->log_user, $row->user_name );
647 }
648
649 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
650 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
651 } elseif ( $row->log_comment != '' ) {
652 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
653 }
654
655 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
656 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
657
658 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
659 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
660 } else {
661 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
662 $out .= " " . Xml::elementClean( 'logtitle', null, self::canonicalTitle( $title ) ) . "\n";
663 $out .= " " . Xml::elementClean( 'params',
664 array( 'xml:space' => 'preserve' ),
665 strval( $row->log_params ) ) . "\n";
666 }
667
668 $out .= " </logitem>\n";
669
670 wfProfileOut( __METHOD__ );
671 return $out;
672 }
673
674 function writeTimestamp( $timestamp ) {
675 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
676 return " " . Xml::element( 'timestamp', null, $ts ) . "\n";
677 }
678
679 function writeContributor( $id, $text ) {
680 $out = " <contributor>\n";
681 if ( $id || !IP::isValid( $text ) ) {
682 $out .= " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
683 $out .= " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
684 } else {
685 $out .= " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
686 }
687 $out .= " </contributor>\n";
688 return $out;
689 }
690
691 /**
692 * Warning! This data is potentially inconsistent. :(
693 * @return string
694 */
695 function writeUploads( $row, $dumpContents = false ) {
696 if ( $row->page_namespace == NS_IMAGE ) {
697 $img = wfLocalFile( $row->page_title );
698 if ( $img && $img->exists() ) {
699 $out = '';
700 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
701 $out .= $this->writeUpload( $ver, $dumpContents );
702 }
703 $out .= $this->writeUpload( $img, $dumpContents );
704 return $out;
705 }
706 }
707 return '';
708 }
709
710 /**
711 * @param $file File
712 * @param $dumpContents bool
713 * @return string
714 */
715 function writeUpload( $file, $dumpContents = false ) {
716 if ( $file->isOld() ) {
717 $archiveName = " " .
718 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
719 } else {
720 $archiveName = '';
721 }
722 if ( $dumpContents ) {
723 # Dump file as base64
724 # Uses only XML-safe characters, so does not need escaping
725 $contents = ' <contents encoding="base64">' .
726 chunk_split( base64_encode( file_get_contents( $file->getPath() ) ) ) .
727 " </contents>\n";
728 } else {
729 $contents = '';
730 }
731 return " <upload>\n" .
732 $this->writeTimestamp( $file->getTimestamp() ) .
733 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
734 " " . Xml::elementClean( 'comment', null, $file->getDescription() ) . "\n" .
735 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
736 $archiveName .
737 " " . Xml::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
738 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
739 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
740 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
741 $contents .
742 " </upload>\n";
743 }
744
745 /**
746 * Return prefixed text form of title, but using the content language's
747 * canonical namespace. This skips any special-casing such as gendered
748 * user namespaces -- which while useful, are not yet listed in the
749 * XML <siteinfo> data so are unsafe in export.
750 *
751 * @param Title $title
752 * @return string
753 * @since 1.18
754 */
755 public static function canonicalTitle( Title $title ) {
756 if ( $title->getInterwiki() ) {
757 return $title->getPrefixedText();
758 }
759
760 global $wgContLang;
761 $prefix = str_replace( '_', ' ', $wgContLang->getNsText( $title->getNamespace() ) );
762
763 if ( $prefix !== '' ) {
764 $prefix .= ':';
765 }
766
767 return $prefix . $title->getText();
768 }
769 }
770
771
772 /**
773 * Base class for output stream; prints to stdout or buffer or whereever.
774 * @ingroup Dump
775 */
776 class DumpOutput {
777 function writeOpenStream( $string ) {
778 $this->write( $string );
779 }
780
781 function writeCloseStream( $string ) {
782 $this->write( $string );
783 }
784
785 function writeOpenPage( $page, $string ) {
786 $this->write( $string );
787 }
788
789 function writeClosePage( $string ) {
790 $this->write( $string );
791 }
792
793 function writeRevision( $rev, $string ) {
794 $this->write( $string );
795 }
796
797 function writeLogItem( $rev, $string ) {
798 $this->write( $string );
799 }
800
801 /**
802 * Override to write to a different stream type.
803 * @return bool
804 */
805 function write( $string ) {
806 print $string;
807 }
808
809 /**
810 * Close the old file, move it to a specified name,
811 * and reopen new file with the old name. Use this
812 * for writing out a file in multiple pieces
813 * at specified checkpoints (e.g. every n hours).
814 * @param $newname mixed File name. May be a string or an array with one element
815 */
816 function closeRenameAndReopen( $newname ) {
817 return;
818 }
819
820 /**
821 * Close the old file, and move it to a specified name.
822 * Use this for the last piece of a file written out
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 * @param $open bool If true, a new file with the old filename will be opened again for writing (default: false)
826 */
827 function closeAndRename( $newname, $open = false ) {
828 return;
829 }
830
831 /**
832 * Returns the name of the file or files which are
833 * being written to, if there are any.
834 * @return null
835 */
836 function getFilenames() {
837 return NULL;
838 }
839 }
840
841 /**
842 * Stream outputter to send data to a file.
843 * @ingroup Dump
844 */
845 class DumpFileOutput extends DumpOutput {
846 protected $handle = false, $filename;
847
848 function __construct( $file ) {
849 $this->handle = fopen( $file, "wt" );
850 $this->filename = $file;
851 }
852
853 function writeCloseStream( $string ) {
854 parent::writeCloseStream( $string );
855 if ( $this->handle ) {
856 fclose( $this->handle );
857 $this->handle = false;
858 }
859 }
860
861 function write( $string ) {
862 fputs( $this->handle, $string );
863 }
864
865 function closeRenameAndReopen( $newname ) {
866 $this->closeAndRename( $newname, true );
867 }
868
869 function renameOrException( $newname ) {
870 if (! rename( $this->filename, $newname ) ) {
871 throw new MWException( __METHOD__ . ": rename of file {$this->filename} to $newname failed\n" );
872 }
873 }
874
875 function checkRenameArgCount( $newname ) {
876 if ( is_array( $newname ) ) {
877 if ( count( $newname ) > 1 ) {
878 throw new MWException( __METHOD__ . ": passed multiple arguments for rename of single file\n" );
879 } else {
880 $newname = $newname[0];
881 }
882 }
883 return $newname;
884 }
885
886 function closeAndRename( $newname, $open = false ) {
887 $newname = $this->checkRenameArgCount( $newname );
888 if ( $newname ) {
889 if ( $this->handle ) {
890 fclose( $this->handle );
891 $this->handle = false;
892 }
893 $this->renameOrException( $newname );
894 if ( $open ) {
895 $this->handle = fopen( $this->filename, "wt" );
896 }
897 }
898 }
899
900 function getFilenames() {
901 return $this->filename;
902 }
903 }
904
905 /**
906 * Stream outputter to send data to a file via some filter program.
907 * Even if compression is available in a library, using a separate
908 * program can allow us to make use of a multi-processor system.
909 * @ingroup Dump
910 */
911 class DumpPipeOutput extends DumpFileOutput {
912 protected $command, $filename;
913 protected $procOpenResource = false;
914
915 function __construct( $command, $file = null ) {
916 if ( !is_null( $file ) ) {
917 $command .= " > " . wfEscapeShellArg( $file );
918 }
919
920 $this->startCommand( $command );
921 $this->command = $command;
922 $this->filename = $file;
923 }
924
925 function writeCloseStream( $string ) {
926 parent::writeCloseStream( $string );
927 if ( $this->procOpenResource ) {
928 proc_close( $this->procOpenResource );
929 $this->procOpenResource = false;
930 }
931 }
932
933 function startCommand( $command ) {
934 $spec = array(
935 0 => array( "pipe", "r" ),
936 );
937 $pipes = array();
938 $this->procOpenResource = proc_open( $command, $spec, $pipes );
939 $this->handle = $pipes[0];
940 }
941
942 function closeRenameAndReopen( $newname ) {
943 $this->closeAndRename( $newname, true );
944 }
945
946 function closeAndRename( $newname, $open = false ) {
947 $newname = $this->checkRenameArgCount( $newname );
948 if ( $newname ) {
949 if ( $this->handle ) {
950 fclose( $this->handle );
951 $this->handle = false;
952 }
953 if ( $this->procOpenResource ) {
954 proc_close( $this->procOpenResource );
955 $this->procOpenResource = false;
956 }
957 $this->renameOrException( $newname );
958 if ( $open ) {
959 $command = $this->command;
960 $command .= " > " . wfEscapeShellArg( $this->filename );
961 $this->startCommand( $command );
962 }
963 }
964 }
965
966 }
967
968 /**
969 * Sends dump output via the gzip compressor.
970 * @ingroup Dump
971 */
972 class DumpGZipOutput extends DumpPipeOutput {
973 function __construct( $file ) {
974 parent::__construct( "gzip", $file );
975 }
976 }
977
978 /**
979 * Sends dump output via the bgzip2 compressor.
980 * @ingroup Dump
981 */
982 class DumpBZip2Output extends DumpPipeOutput {
983 function __construct( $file ) {
984 parent::__construct( "bzip2", $file );
985 }
986 }
987
988 /**
989 * Sends dump output via the p7zip compressor.
990 * @ingroup Dump
991 */
992 class Dump7ZipOutput extends DumpPipeOutput {
993 function __construct( $file ) {
994 $command = $this->setup7zCommand( $file );
995 parent::__construct( $command );
996 $this->filename = $file;
997 }
998
999 function setup7zCommand( $file ) {
1000 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
1001 // Suppress annoying useless crap from p7zip
1002 // Unfortunately this could suppress real error messages too
1003 $command .= ' >' . wfGetNull() . ' 2>&1';
1004 return( $command );
1005 }
1006
1007 function closeAndRename( $newname, $open = false ) {
1008 $newname = $this->checkRenameArgCount( $newname );
1009 if ( $newname ) {
1010 fclose( $this->handle );
1011 proc_close( $this->procOpenResource );
1012 $this->renameOrException( $newname );
1013 if ( $open ) {
1014 $command = $this->setup7zCommand( $this->filename );
1015 $this->startCommand( $command );
1016 }
1017 }
1018 }
1019 }
1020
1021
1022
1023 /**
1024 * Dump output filter class.
1025 * This just does output filtering and streaming; XML formatting is done
1026 * higher up, so be careful in what you do.
1027 * @ingroup Dump
1028 */
1029 class DumpFilter {
1030 function __construct( &$sink ) {
1031 $this->sink =& $sink;
1032 }
1033
1034 function writeOpenStream( $string ) {
1035 $this->sink->writeOpenStream( $string );
1036 }
1037
1038 function writeCloseStream( $string ) {
1039 $this->sink->writeCloseStream( $string );
1040 }
1041
1042 function writeOpenPage( $page, $string ) {
1043 $this->sendingThisPage = $this->pass( $page, $string );
1044 if ( $this->sendingThisPage ) {
1045 $this->sink->writeOpenPage( $page, $string );
1046 }
1047 }
1048
1049 function writeClosePage( $string ) {
1050 if ( $this->sendingThisPage ) {
1051 $this->sink->writeClosePage( $string );
1052 $this->sendingThisPage = false;
1053 }
1054 }
1055
1056 function writeRevision( $rev, $string ) {
1057 if ( $this->sendingThisPage ) {
1058 $this->sink->writeRevision( $rev, $string );
1059 }
1060 }
1061
1062 function writeLogItem( $rev, $string ) {
1063 $this->sink->writeRevision( $rev, $string );
1064 }
1065
1066 function closeRenameAndReopen( $newname ) {
1067 $this->sink->closeRenameAndReopen( $newname );
1068 }
1069
1070 function closeAndRename( $newname, $open = false ) {
1071 $this->sink->closeAndRename( $newname, $open );
1072 }
1073
1074 function getFilenames() {
1075 return $this->sink->getFilenames();
1076 }
1077
1078 /**
1079 * Override for page-based filter types.
1080 * @return bool
1081 */
1082 function pass( $page ) {
1083 return true;
1084 }
1085 }
1086
1087 /**
1088 * Simple dump output filter to exclude all talk pages.
1089 * @ingroup Dump
1090 */
1091 class DumpNotalkFilter extends DumpFilter {
1092 function pass( $page ) {
1093 return !MWNamespace::isTalk( $page->page_namespace );
1094 }
1095 }
1096
1097 /**
1098 * Dump output filter to include or exclude pages in a given set of namespaces.
1099 * @ingroup Dump
1100 */
1101 class DumpNamespaceFilter extends DumpFilter {
1102 var $invert = false;
1103 var $namespaces = array();
1104
1105 function __construct( &$sink, $param ) {
1106 parent::__construct( $sink );
1107
1108 $constants = array(
1109 "NS_MAIN" => NS_MAIN,
1110 "NS_TALK" => NS_TALK,
1111 "NS_USER" => NS_USER,
1112 "NS_USER_TALK" => NS_USER_TALK,
1113 "NS_PROJECT" => NS_PROJECT,
1114 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
1115 "NS_FILE" => NS_FILE,
1116 "NS_FILE_TALK" => NS_FILE_TALK,
1117 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
1118 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
1119 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
1120 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
1121 "NS_TEMPLATE" => NS_TEMPLATE,
1122 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
1123 "NS_HELP" => NS_HELP,
1124 "NS_HELP_TALK" => NS_HELP_TALK,
1125 "NS_CATEGORY" => NS_CATEGORY,
1126 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
1127
1128 if ( $param { 0 } == '!' ) {
1129 $this->invert = true;
1130 $param = substr( $param, 1 );
1131 }
1132
1133 foreach ( explode( ',', $param ) as $key ) {
1134 $key = trim( $key );
1135 if ( isset( $constants[$key] ) ) {
1136 $ns = $constants[$key];
1137 $this->namespaces[$ns] = true;
1138 } elseif ( is_numeric( $key ) ) {
1139 $ns = intval( $key );
1140 $this->namespaces[$ns] = true;
1141 } else {
1142 throw new MWException( "Unrecognized namespace key '$key'\n" );
1143 }
1144 }
1145 }
1146
1147 function pass( $page ) {
1148 $match = isset( $this->namespaces[$page->page_namespace] );
1149 return $this->invert xor $match;
1150 }
1151 }
1152
1153
1154 /**
1155 * Dump output filter to include only the last revision in each page sequence.
1156 * @ingroup Dump
1157 */
1158 class DumpLatestFilter extends DumpFilter {
1159 var $page, $pageString, $rev, $revString;
1160
1161 function writeOpenPage( $page, $string ) {
1162 $this->page = $page;
1163 $this->pageString = $string;
1164 }
1165
1166 function writeClosePage( $string ) {
1167 if ( $this->rev ) {
1168 $this->sink->writeOpenPage( $this->page, $this->pageString );
1169 $this->sink->writeRevision( $this->rev, $this->revString );
1170 $this->sink->writeClosePage( $string );
1171 }
1172 $this->rev = null;
1173 $this->revString = null;
1174 $this->page = null;
1175 $this->pageString = null;
1176 }
1177
1178 function writeRevision( $rev, $string ) {
1179 if ( $rev->rev_id == $this->page->page_latest ) {
1180 $this->rev = $rev;
1181 $this->revString = $string;
1182 }
1183 }
1184 }
1185
1186 /**
1187 * Base class for output stream; prints to stdout or buffer or whereever.
1188 * @ingroup Dump
1189 */
1190 class DumpMultiWriter {
1191 function __construct( $sinks ) {
1192 $this->sinks = $sinks;
1193 $this->count = count( $sinks );
1194 }
1195
1196 function writeOpenStream( $string ) {
1197 for ( $i = 0; $i < $this->count; $i++ ) {
1198 $this->sinks[$i]->writeOpenStream( $string );
1199 }
1200 }
1201
1202 function writeCloseStream( $string ) {
1203 for ( $i = 0; $i < $this->count; $i++ ) {
1204 $this->sinks[$i]->writeCloseStream( $string );
1205 }
1206 }
1207
1208 function writeOpenPage( $page, $string ) {
1209 for ( $i = 0; $i < $this->count; $i++ ) {
1210 $this->sinks[$i]->writeOpenPage( $page, $string );
1211 }
1212 }
1213
1214 function writeClosePage( $string ) {
1215 for ( $i = 0; $i < $this->count; $i++ ) {
1216 $this->sinks[$i]->writeClosePage( $string );
1217 }
1218 }
1219
1220 function writeRevision( $rev, $string ) {
1221 for ( $i = 0; $i < $this->count; $i++ ) {
1222 $this->sinks[$i]->writeRevision( $rev, $string );
1223 }
1224 }
1225
1226 function closeRenameAndReopen( $newnames ) {
1227 $this->closeAndRename( $newnames, true );
1228 }
1229
1230 function closeAndRename( $newnames, $open = false ) {
1231 for ( $i = 0; $i < $this->count; $i++ ) {
1232 $this->sinks[$i]->closeAndRename( $newnames[$i], $open );
1233 }
1234 }
1235
1236 function getFilenames() {
1237 $filenames = array();
1238 for ( $i = 0; $i < $this->count; $i++ ) {
1239 $filenames[] = $this->sinks[$i]->getFilenames();
1240 }
1241 return $filenames;
1242 }
1243
1244 }
1245
1246 function xmlsafe( $string ) {
1247 wfProfileIn( __FUNCTION__ );
1248
1249 /**
1250 * The page may contain old data which has not been properly normalized.
1251 * Invalid UTF-8 sequences or forbidden control characters will make our
1252 * XML output invalid, so be sure to strip them out.
1253 */
1254 $string = UtfNormal::cleanUp( $string );
1255
1256 $string = htmlspecialchars( $string );
1257 wfProfileOut( __FUNCTION__ );
1258 return $string;
1259 }