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