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