define and use closeAndRename() after last write of xml dump file; convert from popen...
[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
45 const BUFFER = 0;
46 const STREAM = 1;
47
48 const TEXT = 0;
49 const STUB = 1;
50
51 /**
52 * If using WikiExporter::STREAM to stream a large amount of data,
53 * provide a database connection which is not managed by
54 * LoadBalancer to read from: some history blob types will
55 * make additional queries to pull source data while the
56 * main query is still running.
57 *
58 * @param $db Database
59 * @param $history Mixed: one of WikiExporter::FULL or WikiExporter::CURRENT,
60 * or an associative array:
61 * offset: non-inclusive offset at which to start the query
62 * limit: maximum number of rows to return
63 * dir: "asc" or "desc" timestamp order
64 * @param $buffer Int: one of WikiExporter::BUFFER or WikiExporter::STREAM
65 * @param $text Int: one of WikiExporter::TEXT or WikiExporter::STUB
66 */
67 function __construct( &$db, $history = WikiExporter::CURRENT,
68 $buffer = WikiExporter::BUFFER, $text = WikiExporter::TEXT ) {
69 $this->db =& $db;
70 $this->history = $history;
71 $this->buffer = $buffer;
72 $this->writer = new XmlDumpWriter();
73 $this->sink = new DumpOutput();
74 $this->text = $text;
75 }
76
77 /**
78 * Set the DumpOutput or DumpFilter object which will receive
79 * various row objects and XML output for filtering. Filters
80 * can be chained or used as callbacks.
81 *
82 * @param $sink mixed
83 */
84 public function setOutputSink( &$sink ) {
85 $this->sink =& $sink;
86 }
87
88 public function openStream() {
89 $output = $this->writer->openStream();
90 $this->sink->writeOpenStream( $output );
91 }
92
93 public function closeStream() {
94 $output = $this->writer->closeStream();
95 $this->sink->writeCloseStream( $output );
96 }
97
98 /**
99 * Dumps a series of page and revision records for all pages
100 * in the database, either including complete history or only
101 * the most recent version.
102 */
103 public function allPages() {
104 return $this->dumpFrom( '' );
105 }
106
107 /**
108 * Dumps a series of page and revision records for those pages
109 * in the database falling within the page_id range given.
110 * @param $start Int: inclusive lower limit (this id is included)
111 * @param $end Int: Exclusive upper limit (this id is not included)
112 * If 0, no upper limit.
113 */
114 public function pagesByRange( $start, $end ) {
115 $condition = 'page_id >= ' . intval( $start );
116 if ( $end ) {
117 $condition .= ' AND page_id < ' . intval( $end );
118 }
119 return $this->dumpFrom( $condition );
120 }
121
122 /**
123 * @param $title Title
124 */
125 public function pageByTitle( $title ) {
126 return $this->dumpFrom(
127 'page_namespace=' . $title->getNamespace() .
128 ' AND page_title=' . $this->db->addQuotes( $title->getDBkey() ) );
129 }
130
131 public function pageByName( $name ) {
132 $title = Title::newFromText( $name );
133 if ( is_null( $title ) ) {
134 throw new MWException( "Can't export invalid title" );
135 } else {
136 return $this->pageByTitle( $title );
137 }
138 }
139
140 public function pagesByName( $names ) {
141 foreach ( $names as $name ) {
142 $this->pageByName( $name );
143 }
144 }
145
146 public function allLogs() {
147 return $this->dumpFrom( '' );
148 }
149
150 public function logsByRange( $start, $end ) {
151 $condition = 'log_id >= ' . intval( $start );
152 if ( $end ) {
153 $condition .= ' AND log_id < ' . intval( $end );
154 }
155 return $this->dumpFrom( $condition );
156 }
157
158 # Generates the distinct list of authors of an article
159 # Not called by default (depends on $this->list_authors)
160 # Can be set by Special:Export when not exporting whole history
161 protected function do_list_authors( $cond ) {
162 wfProfileIn( __METHOD__ );
163 $this->author_list = "<contributors>";
164 // rev_deleted
165
166 $res = $this->db->select(
167 array( 'page', 'revision' ),
168 array( 'DISTINCT rev_user_text', 'rev_user' ),
169 array(
170 $this->db->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0',
171 $cond,
172 'page_id = rev_id',
173 ),
174 __METHOD__
175 );
176
177 foreach ( $res as $row ) {
178 $this->author_list .= "<contributor>" .
179 "<username>" .
180 htmlentities( $row->rev_user_text ) .
181 "</username>" .
182 "<id>" .
183 $row->rev_user .
184 "</id>" .
185 "</contributor>";
186 }
187 $this->author_list .= "</contributors>";
188 wfProfileOut( __METHOD__ );
189 }
190
191 protected function dumpFrom( $cond = '' ) {
192 wfProfileIn( __METHOD__ );
193 # For logging dumps...
194 if ( $this->history & self::LOGS ) {
195 if ( $this->buffer == WikiExporter::STREAM ) {
196 $prev = $this->db->bufferResults( false );
197 }
198 $where = array( 'user_id = log_user' );
199 # Hide private logs
200 $hideLogs = LogEventsList::getExcludeClause( $this->db );
201 if ( $hideLogs ) $where[] = $hideLogs;
202 # Add on any caller specified conditions
203 if ( $cond ) $where[] = $cond;
204 # Get logging table name for logging.* clause
205 $logging = $this->db->tableName( 'logging' );
206 $result = $this->db->select( array( 'logging', 'user' ),
207 array( "{$logging}.*", 'user_name' ), // grab the user name
208 $where,
209 __METHOD__,
210 array( 'ORDER BY' => 'log_id', 'USE INDEX' => array( 'logging' => 'PRIMARY' ) )
211 );
212 $wrapper = $this->db->resultObject( $result );
213 $this->outputLogStream( $wrapper );
214 if ( $this->buffer == WikiExporter::STREAM ) {
215 $this->db->bufferResults( $prev );
216 }
217 # For page dumps...
218 } else {
219 $tables = array( 'page', 'revision' );
220 $opts = array( 'ORDER BY' => 'page_id ASC' );
221 $opts['USE INDEX'] = array();
222 $join = array();
223 if ( is_array( $this->history ) ) {
224 # Time offset/limit for all pages/history...
225 $revJoin = 'page_id=rev_page';
226 # Set time order
227 if ( $this->history['dir'] == 'asc' ) {
228 $op = '>';
229 $opts['ORDER BY'] = 'rev_timestamp ASC';
230 } else {
231 $op = '<';
232 $opts['ORDER BY'] = 'rev_timestamp DESC';
233 }
234 # Set offset
235 if ( !empty( $this->history['offset'] ) ) {
236 $revJoin .= " AND rev_timestamp $op " .
237 $this->db->addQuotes( $this->db->timestamp( $this->history['offset'] ) );
238 }
239 $join['revision'] = array( 'INNER JOIN', $revJoin );
240 # Set query limit
241 if ( !empty( $this->history['limit'] ) ) {
242 $opts['LIMIT'] = intval( $this->history['limit'] );
243 }
244 } elseif ( $this->history & WikiExporter::FULL ) {
245 # Full history dumps...
246 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page' );
247 } elseif ( $this->history & WikiExporter::CURRENT ) {
248 # Latest revision dumps...
249 if ( $this->list_authors && $cond != '' ) { // List authors, if so desired
250 $this->do_list_authors( $cond );
251 }
252 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
253 } elseif ( $this->history & WikiExporter::STABLE ) {
254 # "Stable" revision dumps...
255 # Default JOIN, to be overridden...
256 $join['revision'] = array( 'INNER JOIN', 'page_id=rev_page AND page_latest=rev_id' );
257 # One, and only one hook should set this, and return false
258 if ( wfRunHooks( 'WikiExporter::dumpStableQuery', array( &$tables, &$opts, &$join ) ) ) {
259 wfProfileOut( __METHOD__ );
260 throw new MWException( __METHOD__ . " given invalid history dump type." );
261 }
262 } else {
263 # Uknown history specification parameter?
264 wfProfileOut( __METHOD__ );
265 throw new MWException( __METHOD__ . " given invalid history dump type." );
266 }
267 # Query optimization hacks
268 if ( $cond == '' ) {
269 $opts[] = 'STRAIGHT_JOIN';
270 $opts['USE INDEX']['page'] = 'PRIMARY';
271 }
272 # Build text join options
273 if ( $this->text != WikiExporter::STUB ) { // 1-pass
274 $tables[] = 'text';
275 $join['text'] = array( 'INNER JOIN', 'rev_text_id=old_id' );
276 }
277
278 if ( $this->buffer == WikiExporter::STREAM ) {
279 $prev = $this->db->bufferResults( false );
280 }
281
282 wfRunHooks( 'ModifyExportQuery',
283 array( $this->db, &$tables, &$cond, &$opts, &$join ) );
284
285 # Do the query!
286 $result = $this->db->select( $tables, '*', $cond, __METHOD__, $opts, $join );
287 $wrapper = $this->db->resultObject( $result );
288 # Output dump results
289 $this->outputPageStream( $wrapper );
290 if ( $this->list_authors ) {
291 $this->outputPageStream( $wrapper );
292 }
293
294 if ( $this->buffer == WikiExporter::STREAM ) {
295 $this->db->bufferResults( $prev );
296 }
297 }
298 wfProfileOut( __METHOD__ );
299 }
300
301 /**
302 * Runs through a query result set dumping page and revision records.
303 * The result set should be sorted/grouped by page to avoid duplicate
304 * page records in the output.
305 *
306 * The result set will be freed once complete. Should be safe for
307 * streaming (non-buffered) queries, as long as it was made on a
308 * separate database connection not managed by LoadBalancer; some
309 * blob storage types will make queries to pull source data.
310 *
311 * @param $resultset ResultWrapper
312 */
313 protected function outputPageStream( $resultset ) {
314 $last = null;
315 foreach ( $resultset as $row ) {
316 if ( is_null( $last ) ||
317 $last->page_namespace != $row->page_namespace ||
318 $last->page_title != $row->page_title ) {
319 if ( isset( $last ) ) {
320 $output = '';
321 if ( $this->dumpUploads ) {
322 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
323 }
324 $output .= $this->writer->closePage();
325 $this->sink->writeClosePage( $output );
326 }
327 $output = $this->writer->openPage( $row );
328 $this->sink->writeOpenPage( $row, $output );
329 $last = $row;
330 }
331 $output = $this->writer->writeRevision( $row );
332 $this->sink->writeRevision( $row, $output );
333 }
334 if ( isset( $last ) ) {
335 $output = '';
336 if ( $this->dumpUploads ) {
337 $output .= $this->writer->writeUploads( $last, $this->dumpUploadFileContents );
338 }
339 $output .= $this->author_list;
340 $output .= $this->writer->closePage();
341 $this->sink->writeClosePage( $output );
342 }
343 }
344
345 protected function outputLogStream( $resultset ) {
346 foreach ( $resultset as $row ) {
347 $output = $this->writer->writeLogItem( $row );
348 $this->sink->writeLogItem( $row, $output );
349 }
350 }
351 }
352
353 /**
354 * @ingroup Dump
355 */
356 class XmlDumpWriter {
357 var $firstPageWritten = 0;
358 var $lastPageWritten = 0;
359 var $pageInProgress = 0;
360
361 /**
362 * Returns the export schema version.
363 * @return string
364 */
365 function schemaVersion() {
366 return "0.5";
367 }
368
369 /**
370 * Opens the XML output stream's root <mediawiki> element.
371 * This does not include an xml directive, so is safe to include
372 * as a subelement in a larger XML stream. Namespace and XML Schema
373 * references are included.
374 *
375 * Output will be encoded in UTF-8.
376 *
377 * @return string
378 */
379 function openStream() {
380 global $wgLanguageCode;
381 $ver = $this->schemaVersion();
382 return Xml::element( 'mediawiki', array(
383 'xmlns' => "http://www.mediawiki.org/xml/export-$ver/",
384 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
385 'xsi:schemaLocation' => "http://www.mediawiki.org/xml/export-$ver/ " .
386 "http://www.mediawiki.org/xml/export-$ver.xsd",
387 'version' => $ver,
388 'xml:lang' => $wgLanguageCode ),
389 null ) .
390 "\n" .
391 $this->siteInfo();
392 }
393
394 function siteInfo() {
395 $info = array(
396 $this->sitename(),
397 $this->homelink(),
398 $this->generator(),
399 $this->caseSetting(),
400 $this->namespaces() );
401 return " <siteinfo>\n " .
402 implode( "\n ", $info ) .
403 "\n </siteinfo>\n";
404 }
405
406 function sitename() {
407 global $wgSitename;
408 return Xml::element( 'sitename', array(), $wgSitename );
409 }
410
411 function generator() {
412 global $wgVersion;
413 return Xml::element( 'generator', array(), "MediaWiki $wgVersion" );
414 }
415
416 function homelink() {
417 return Xml::element( 'base', array(), Title::newMainPage()->getCanonicalUrl() );
418 }
419
420 function caseSetting() {
421 global $wgCapitalLinks;
422 // "case-insensitive" option is reserved for future
423 $sensitivity = $wgCapitalLinks ? 'first-letter' : 'case-sensitive';
424 return Xml::element( 'case', array(), $sensitivity );
425 }
426
427 function namespaces() {
428 global $wgContLang;
429 $spaces = "<namespaces>\n";
430 foreach ( $wgContLang->getFormattedNamespaces() as $ns => $title ) {
431 $spaces .= ' ' .
432 Xml::element( 'namespace',
433 array( 'key' => $ns,
434 'case' => MWNamespace::isCapitalized( $ns ) ? 'first-letter' : 'case-sensitive',
435 ), $title ) . "\n";
436 }
437 $spaces .= " </namespaces>";
438 return $spaces;
439 }
440
441 /**
442 * Closes the output stream with the closing root element.
443 * Call when finished dumping things.
444 *
445 * @return string
446 */
447 function closeStream() {
448 return "</mediawiki>\n";
449 }
450
451 /**
452 * Opens a <page> section on the output stream, with data
453 * from the given database row.
454 *
455 * @param $row object
456 * @return string
457 * @access private
458 */
459 function openPage( $row ) {
460 $out = " <page>\n";
461 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
462 $out .= ' ' . Xml::elementClean( 'title', array(), $title->getPrefixedText() ) . "\n";
463 $out .= ' ' . Xml::element( 'id', array(), strval( $row->page_id ) ) . "\n";
464 $this->pageInProgress = $row->page_id;
465 if ( $row->page_is_redirect ) {
466 $out .= ' ' . Xml::element( 'redirect', array() ) . "\n";
467 }
468 if ( $row->page_restrictions != '' ) {
469 $out .= ' ' . Xml::element( 'restrictions', array(),
470 strval( $row->page_restrictions ) ) . "\n";
471 }
472
473 wfRunHooks( 'XmlDumpWriterOpenPage', array( $this, &$out, $row, $title ) );
474
475 return $out;
476 }
477
478 /**
479 * Closes a <page> section on the output stream.
480 *
481 * @access private
482 */
483 function closePage() {
484 return " </page>\n";
485 if (! $this->firstPageWritten) {
486 $this->firstPageWritten = $this->pageInProgress;
487 }
488 $this->lastPageWritten = $this->pageInProgress;
489 }
490
491 /**
492 * Dumps a <revision> section on the output stream, with
493 * data filled in from the given database row.
494 *
495 * @param $row object
496 * @return string
497 * @access private
498 */
499 function writeRevision( $row ) {
500 wfProfileIn( __METHOD__ );
501
502 $out = " <revision>\n";
503 $out .= " " . Xml::element( 'id', null, strval( $row->rev_id ) ) . "\n";
504
505 $out .= $this->writeTimestamp( $row->rev_timestamp );
506
507 if ( $row->rev_deleted & Revision::DELETED_USER ) {
508 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
509 } else {
510 $out .= $this->writeContributor( $row->rev_user, $row->rev_user_text );
511 }
512
513 if ( $row->rev_minor_edit ) {
514 $out .= " <minor/>\n";
515 }
516 if ( $row->rev_deleted & Revision::DELETED_COMMENT ) {
517 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
518 } elseif ( $row->rev_comment != '' ) {
519 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->rev_comment ) ) . "\n";
520 }
521
522 $text = '';
523 if ( $row->rev_deleted & Revision::DELETED_TEXT ) {
524 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
525 } elseif ( isset( $row->old_text ) ) {
526 // Raw text from the database may have invalid chars
527 $text = strval( Revision::getRevisionText( $row ) );
528 $out .= " " . Xml::elementClean( 'text',
529 array( 'xml:space' => 'preserve', 'bytes' => $row->rev_len ),
530 strval( $text ) ) . "\n";
531 } else {
532 // Stub output
533 $out .= " " . Xml::element( 'text',
534 array( 'id' => $row->rev_text_id, 'bytes' => $row->rev_len ),
535 "" ) . "\n";
536 }
537
538 wfRunHooks( 'XmlDumpWriterWriteRevision', array( &$this, &$out, $row, $text ) );
539
540 $out .= " </revision>\n";
541
542 wfProfileOut( __METHOD__ );
543 return $out;
544 }
545
546 /**
547 * Dumps a <logitem> section on the output stream, with
548 * data filled in from the given database row.
549 *
550 * @param $row object
551 * @return string
552 * @access private
553 */
554 function writeLogItem( $row ) {
555 wfProfileIn( __METHOD__ );
556
557 $out = " <logitem>\n";
558 $out .= " " . Xml::element( 'id', null, strval( $row->log_id ) ) . "\n";
559
560 $out .= $this->writeTimestamp( $row->log_timestamp );
561
562 if ( $row->log_deleted & LogPage::DELETED_USER ) {
563 $out .= " " . Xml::element( 'contributor', array( 'deleted' => 'deleted' ) ) . "\n";
564 } else {
565 $out .= $this->writeContributor( $row->log_user, $row->user_name );
566 }
567
568 if ( $row->log_deleted & LogPage::DELETED_COMMENT ) {
569 $out .= " " . Xml::element( 'comment', array( 'deleted' => 'deleted' ) ) . "\n";
570 } elseif ( $row->log_comment != '' ) {
571 $out .= " " . Xml::elementClean( 'comment', null, strval( $row->log_comment ) ) . "\n";
572 }
573
574 $out .= " " . Xml::element( 'type', null, strval( $row->log_type ) ) . "\n";
575 $out .= " " . Xml::element( 'action', null, strval( $row->log_action ) ) . "\n";
576
577 if ( $row->log_deleted & LogPage::DELETED_ACTION ) {
578 $out .= " " . Xml::element( 'text', array( 'deleted' => 'deleted' ) ) . "\n";
579 } else {
580 $title = Title::makeTitle( $row->log_namespace, $row->log_title );
581 $out .= " " . Xml::elementClean( 'logtitle', null, $title->getPrefixedText() ) . "\n";
582 $out .= " " . Xml::elementClean( 'params',
583 array( 'xml:space' => 'preserve' ),
584 strval( $row->log_params ) ) . "\n";
585 }
586
587 $out .= " </logitem>\n";
588
589 wfProfileOut( __METHOD__ );
590 return $out;
591 }
592
593 function writeTimestamp( $timestamp ) {
594 $ts = wfTimestamp( TS_ISO_8601, $timestamp );
595 return " " . Xml::element( 'timestamp', null, $ts ) . "\n";
596 }
597
598 function writeContributor( $id, $text ) {
599 $out = " <contributor>\n";
600 if ( $id ) {
601 $out .= " " . Xml::elementClean( 'username', null, strval( $text ) ) . "\n";
602 $out .= " " . Xml::element( 'id', null, strval( $id ) ) . "\n";
603 } else {
604 $out .= " " . Xml::elementClean( 'ip', null, strval( $text ) ) . "\n";
605 }
606 $out .= " </contributor>\n";
607 return $out;
608 }
609
610 /**
611 * Warning! This data is potentially inconsistent. :(
612 */
613 function writeUploads( $row, $dumpContents = false ) {
614 if ( $row->page_namespace == NS_IMAGE ) {
615 $img = wfLocalFile( $row->page_title );
616 if ( $img && $img->exists() ) {
617 $out = '';
618 foreach ( array_reverse( $img->getHistory() ) as $ver ) {
619 $out .= $this->writeUpload( $ver, $dumpContents );
620 }
621 $out .= $this->writeUpload( $img, $dumpContents );
622 return $out;
623 }
624 }
625 return '';
626 }
627
628 /**
629 * @param $file File
630 * @param $dumpContents bool
631 * @return string
632 */
633 function writeUpload( $file, $dumpContents = false ) {
634 if ( $file->isOld() ) {
635 $archiveName = " " .
636 Xml::element( 'archivename', null, $file->getArchiveName() ) . "\n";
637 } else {
638 $archiveName = '';
639 }
640 if ( $dumpContents ) {
641 # Dump file as base64
642 # Uses only XML-safe characters, so does not need escaping
643 $contents = ' <contents encoding="base64">' .
644 chunk_split( base64_encode( file_get_contents( $file->getPath() ) ) ) .
645 " </contents>\n";
646 } else {
647 $contents = '';
648 }
649 return " <upload>\n" .
650 $this->writeTimestamp( $file->getTimestamp() ) .
651 $this->writeContributor( $file->getUser( 'id' ), $file->getUser( 'text' ) ) .
652 " " . Xml::elementClean( 'comment', null, $file->getDescription() ) . "\n" .
653 " " . Xml::element( 'filename', null, $file->getName() ) . "\n" .
654 $archiveName .
655 " " . Xml::element( 'src', null, $file->getCanonicalUrl() ) . "\n" .
656 " " . Xml::element( 'size', null, $file->getSize() ) . "\n" .
657 " " . Xml::element( 'sha1base36', null, $file->getSha1() ) . "\n" .
658 " " . Xml::element( 'rel', null, $file->getRel() ) . "\n" .
659 $contents .
660 " </upload>\n";
661 }
662
663 }
664
665
666 /**
667 * Base class for output stream; prints to stdout or buffer or whereever.
668 * @ingroup Dump
669 */
670 class DumpOutput {
671 function writeOpenStream( $string ) {
672 $this->write( $string );
673 }
674
675 function writeCloseStream( $string ) {
676 $this->write( $string );
677 }
678
679 function writeOpenPage( $page, $string ) {
680 $this->write( $string );
681 }
682
683 function writeClosePage( $string ) {
684 $this->write( $string );
685 }
686
687 function writeRevision( $rev, $string ) {
688 $this->write( $string );
689 }
690
691 function writeLogItem( $rev, $string ) {
692 $this->write( $string );
693 }
694
695 /**
696 * Override to write to a different stream type.
697 * @return bool
698 */
699 function write( $string ) {
700 print $string;
701 }
702
703 function closeRenameAndReopen( $newname ) {
704 return;
705 }
706
707 function closeAndRename( $newname ) {
708 return;
709 }
710
711 function rename( $newname ) {
712 return;
713 }
714
715 function getFilename() {
716 return NULL;
717 }
718 }
719
720 /**
721 * Stream outputter to send data to a file.
722 * @ingroup Dump
723 */
724 class DumpFileOutput extends DumpOutput {
725 var $handle;
726 var $filename;
727
728 function __construct( $file ) {
729 $this->handle = fopen( $file, "wt" );
730 $this->filename = $file;
731 }
732
733 function write( $string ) {
734 fputs( $this->handle, $string );
735 }
736
737 /**
738 * Close the old file, move it to a specified name,
739 * and reopen new file with the old name. Use this
740 * for writing out a file in multiple pieces
741 * at specified checkpoints (e.g. every n hours).
742 */
743 function closeRenameAndReopen( $newname ) {
744 if ( is_array($newname) ) {
745 if (count($newname) > 1) {
746 throw new MWException("Export closeRenameAndReopen: passed multiple argumnts for rename of single file\n");
747 }
748 else {
749 $newname = $newname[0];
750 }
751 }
752 if ( $newname ) {
753 fclose( $this->handle );
754 rename( $this->filename, $newname );
755 $this->handle = fopen( $this->filename, "wt" );
756 }
757 }
758
759 function closeAndRename( $newname ) {
760 if ( is_array($newname) ) {
761 if (count($newname) > 1) {
762 throw new MWException("Export closeRenameAndReopen: passed multiple argumnts for rename of single file\n");
763 }
764 else {
765 $newname = $newname[0];
766 }
767 }
768 if ( $newname ) {
769 fclose( $this->handle );
770 rename( $this->filename, $newname );
771 }
772 }
773
774 function rename( $newname ) {
775 if ( is_array($newname) ) {
776 if (count($newname) > 1) {
777 throw new MWException("Export closeRenameAndReopen: passed multiple argumnts for rename of single file\n");
778 }
779 else {
780 $newname = $newname[0];
781 }
782 }
783 if ( $newname ) {
784 rename( $this->filename, $newname );
785 }
786 }
787
788 function getFilename() {
789 return $this->filename;
790 }
791 }
792
793 /**
794 * Stream outputter to send data to a file via some filter program.
795 * Even if compression is available in a library, using a separate
796 * program can allow us to make use of a multi-processor system.
797 * @ingroup Dump
798 */
799 class DumpPipeOutput extends DumpFileOutput {
800 var $command;
801
802 function __construct( $command, $file = null ) {
803 if ( !is_null( $file ) ) {
804 $command .= " > " . wfEscapeShellArg( $file );
805 }
806
807 $this->startCommand($command);
808 $this->command = $command;
809 $this->filename = $file;
810 }
811
812 function startCommand($command) {
813 $spec = array(
814 0 => array( "pipe", "r" ),
815 );
816 $pipes = array();
817 $this->procOpenResource = proc_open( $command, $spec, $pipes );
818 $this->handle = $pipes[0];
819 }
820
821 /**
822 * Close the old file, move it to a specified name,
823 * and reopen new file with the old name.
824 */
825 function closeRenameAndReopen( $newname ) {
826 if ( is_array($newname) ) {
827 if (count($newname) > 1) {
828 throw new MWException("Export closeRenameAndReopen: passed multiple argumnts for rename of single file\n");
829 }
830 else {
831 $newname = $newname[0];
832 }
833 }
834 if ( $newname ) {
835 fclose( $this->handle );
836 proc_close($this->procOpenResource);
837 rename( $this->filename, $newname );
838 $command = $this->command;
839 $command .= " > " . wfEscapeShellArg( $this->filename );
840 $this->startCommand($command);
841 }
842 }
843
844 function closeAndRename( $newname ) {
845 if ( is_array($newname) ) {
846 if (count($newname) > 1) {
847 throw new MWException("Export closeRenameAndReopen: passed multiple argumnts for rename of single file\n");
848 }
849 else {
850 $newname = $newname[0];
851 }
852 }
853 if ( $newname ) {
854 # pclose( $this->handle );
855 fclose( $this->handle );
856 proc_close($this->procOpenResource);
857 rename( $this->filename, $newname );
858 }
859 }
860
861 function rename( $newname ) {
862 if ( is_array($newname) ) {
863 if (count($newname) > 1) {
864 throw new MWException("Export closeRenameAndReopen: passed multiple argumnts for rename of single file\n");
865 }
866 else {
867 $newname = $newname[0];
868 }
869 }
870 if ( $newname ) {
871 rename( $this->filename, $newname );
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 var $filename;
902
903 function __construct( $file ) {
904 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
905 // Suppress annoying useless crap from p7zip
906 // Unfortunately this could suppress real error messages too
907 $command .= ' >' . wfGetNull() . ' 2>&1';
908 parent::__construct( $command );
909 $this->filename = $file;
910 }
911
912 function closeRenameAndReopen( $newname ) {
913 if ( is_array($newname) ) {
914 if (count($newname) > 1) {
915 throw new MWException("Export closeRenameAndReopen: passed multiple argumnts for rename of single file\n");
916 }
917 else {
918 $newname = $newname[0];
919 }
920 }
921 if ( $newname ) {
922 fclose( $this->handle );
923 proc_close($this->procOpenResource);
924 rename( $this->filename, $newname );
925 $command = "7za a -bd -si " . wfEscapeShellArg( $file );
926 $command .= ' >' . wfGetNull() . ' 2>&1';
927 $this->startCommand($command);
928 }
929 }
930
931 function closeAndRename( $newname ) {
932 if ( is_array($newname) ) {
933 if (count($newname) > 1) {
934 throw new MWException("Export closeRenameAndReopen: passed multiple argumnts for rename of single file\n");
935 }
936 else {
937 $newname = $newname[0];
938 }
939 }
940 if ( $newname ) {
941 fclose( $this->handle );
942 proc_close($this->procOpenResource);
943 rename( $this->filename, $newname );
944 }
945 }
946
947 function rename( $newname ) {
948 if ( is_array($newname) ) {
949 if (count($newname) > 1) {
950 throw new MWException("Export closeRenameAndReopen: passed multiple argumnts for rename of single file\n");
951 }
952 else {
953 $newname = $newname[0];
954 }
955 }
956 if ( $newname ) {
957 rename( $this->filename, $newname );
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 ) {
1012 $this->sink->closeAndRename( $newname );
1013 }
1014
1015 function rename( $newname ) {
1016 $this->sink->rename( $newname );
1017 }
1018
1019 function getFilename() {
1020 return $this->sink->getFilename();
1021 }
1022
1023 /**
1024 * Override for page-based filter types.
1025 * @return bool
1026 */
1027 function pass( $page ) {
1028 return true;
1029 }
1030 }
1031
1032 /**
1033 * Simple dump output filter to exclude all talk pages.
1034 * @ingroup Dump
1035 */
1036 class DumpNotalkFilter extends DumpFilter {
1037 function pass( $page ) {
1038 return !MWNamespace::isTalk( $page->page_namespace );
1039 }
1040 }
1041
1042 /**
1043 * Dump output filter to include or exclude pages in a given set of namespaces.
1044 * @ingroup Dump
1045 */
1046 class DumpNamespaceFilter extends DumpFilter {
1047 var $invert = false;
1048 var $namespaces = array();
1049
1050 function __construct( &$sink, $param ) {
1051 parent::__construct( $sink );
1052
1053 $constants = array(
1054 "NS_MAIN" => NS_MAIN,
1055 "NS_TALK" => NS_TALK,
1056 "NS_USER" => NS_USER,
1057 "NS_USER_TALK" => NS_USER_TALK,
1058 "NS_PROJECT" => NS_PROJECT,
1059 "NS_PROJECT_TALK" => NS_PROJECT_TALK,
1060 "NS_FILE" => NS_FILE,
1061 "NS_FILE_TALK" => NS_FILE_TALK,
1062 "NS_IMAGE" => NS_IMAGE, // NS_IMAGE is an alias for NS_FILE
1063 "NS_IMAGE_TALK" => NS_IMAGE_TALK,
1064 "NS_MEDIAWIKI" => NS_MEDIAWIKI,
1065 "NS_MEDIAWIKI_TALK" => NS_MEDIAWIKI_TALK,
1066 "NS_TEMPLATE" => NS_TEMPLATE,
1067 "NS_TEMPLATE_TALK" => NS_TEMPLATE_TALK,
1068 "NS_HELP" => NS_HELP,
1069 "NS_HELP_TALK" => NS_HELP_TALK,
1070 "NS_CATEGORY" => NS_CATEGORY,
1071 "NS_CATEGORY_TALK" => NS_CATEGORY_TALK );
1072
1073 if ( $param { 0 } == '!' ) {
1074 $this->invert = true;
1075 $param = substr( $param, 1 );
1076 }
1077
1078 foreach ( explode( ',', $param ) as $key ) {
1079 $key = trim( $key );
1080 if ( isset( $constants[$key] ) ) {
1081 $ns = $constants[$key];
1082 $this->namespaces[$ns] = true;
1083 } elseif ( is_numeric( $key ) ) {
1084 $ns = intval( $key );
1085 $this->namespaces[$ns] = true;
1086 } else {
1087 throw new MWException( "Unrecognized namespace key '$key'\n" );
1088 }
1089 }
1090 }
1091
1092 function pass( $page ) {
1093 $match = isset( $this->namespaces[$page->page_namespace] );
1094 return $this->invert xor $match;
1095 }
1096 }
1097
1098
1099 /**
1100 * Dump output filter to include only the last revision in each page sequence.
1101 * @ingroup Dump
1102 */
1103 class DumpLatestFilter extends DumpFilter {
1104 var $page, $pageString, $rev, $revString;
1105
1106 function writeOpenPage( $page, $string ) {
1107 $this->page = $page;
1108 $this->pageString = $string;
1109 }
1110
1111 function writeClosePage( $string ) {
1112 if ( $this->rev ) {
1113 $this->sink->writeOpenPage( $this->page, $this->pageString );
1114 $this->sink->writeRevision( $this->rev, $this->revString );
1115 $this->sink->writeClosePage( $string );
1116 }
1117 $this->rev = null;
1118 $this->revString = null;
1119 $this->page = null;
1120 $this->pageString = null;
1121 }
1122
1123 function writeRevision( $rev, $string ) {
1124 if ( $rev->rev_id == $this->page->page_latest ) {
1125 $this->rev = $rev;
1126 $this->revString = $string;
1127 }
1128 }
1129 }
1130
1131 /**
1132 * Base class for output stream; prints to stdout or buffer or whereever.
1133 * @ingroup Dump
1134 */
1135 class DumpMultiWriter {
1136 function __construct( $sinks ) {
1137 $this->sinks = $sinks;
1138 $this->count = count( $sinks );
1139 }
1140
1141 function writeOpenStream( $string ) {
1142 for ( $i = 0; $i < $this->count; $i++ ) {
1143 $this->sinks[$i]->writeOpenStream( $string );
1144 }
1145 }
1146
1147 function writeCloseStream( $string ) {
1148 for ( $i = 0; $i < $this->count; $i++ ) {
1149 $this->sinks[$i]->writeCloseStream( $string );
1150 }
1151 }
1152
1153 function writeOpenPage( $page, $string ) {
1154 for ( $i = 0; $i < $this->count; $i++ ) {
1155 $this->sinks[$i]->writeOpenPage( $page, $string );
1156 }
1157 }
1158
1159 function writeClosePage( $string ) {
1160 for ( $i = 0; $i < $this->count; $i++ ) {
1161 $this->sinks[$i]->writeClosePage( $string );
1162 }
1163 }
1164
1165 function writeRevision( $rev, $string ) {
1166 for ( $i = 0; $i < $this->count; $i++ ) {
1167 $this->sinks[$i]->writeRevision( $rev, $string );
1168 }
1169 }
1170
1171 function closeRenameAndReopen( $newnames ) {
1172 for( $i = 0; $i < $this->count; $i++ ) {
1173 $this->sinks[$i]->closeRenameAndReopen( $newnames[$i] );
1174 }
1175 }
1176
1177 function closeAndRename( $newname ) {
1178 for( $i = 0; $i < $this->count; $i++ ) {
1179 $this->sinks[$i]->closeAndRename( $newnames[$i] );
1180 }
1181 }
1182 function rename( $newnames ) {
1183 for( $i = 0; $i < $this->count; $i++ ) {
1184 $this->sinks[$i]->rename( $newnames[$i] );
1185 }
1186 }
1187
1188 function getFilename() {
1189 $filenames = array();
1190 for( $i = 0; $i < $this->count; $i++ ) {
1191 $filenames[] = $this->sinks[$i]->getFilename();
1192 }
1193 return $filenames;
1194 }
1195
1196 }
1197
1198 function xmlsafe( $string ) {
1199 wfProfileIn( __FUNCTION__ );
1200
1201 /**
1202 * The page may contain old data which has not been properly normalized.
1203 * Invalid UTF-8 sequences or forbidden control characters will make our
1204 * XML output invalid, so be sure to strip them out.
1205 */
1206 $string = UtfNormal::cleanUp( $string );
1207
1208 $string = htmlspecialchars( $string );
1209 wfProfileOut( __FUNCTION__ );
1210 return $string;
1211 }