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