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