Remove superfluous inclusion of SiteConfiguration in doMaintenance. It's in the AutoL...
[lhc/web/wiklou.git] / includes / Import.php
1 <?php
2 /**
3 * MediaWiki page data importer
4 *
5 * Copyright © 2003,2005 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 * @ingroup SpecialPage
25 */
26
27 /**
28 * XML file reader for the page data importer
29 *
30 * implements Special:Import
31 * @ingroup SpecialPage
32 */
33 class WikiImporter {
34 private $reader = null;
35 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
36 private $mSiteInfoCallback, $mTargetNamespace, $mPageOutCallback;
37 private $mDebug;
38 private $mImportUploads, $mImageBasePath;
39
40 /**
41 * Creates an ImportXMLReader drawing from the source provided
42 */
43 function __construct( $source ) {
44 $this->reader = new XMLReader();
45
46 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
47 $id = UploadSourceAdapter::registerSource( $source );
48 $this->reader->open( "uploadsource://$id" );
49
50 // Default callbacks
51 $this->setRevisionCallback( array( $this, "importRevision" ) );
52 $this->setUploadCallback( array( $this, 'importUpload' ) );
53 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
54 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
55 }
56
57 private function throwXmlError( $err ) {
58 $this->debug( "FAILURE: $err" );
59 wfDebug( "WikiImporter XML error: $err\n" );
60 }
61
62 private function debug( $data ) {
63 if( $this->mDebug ) {
64 wfDebug( "IMPORT: $data\n" );
65 }
66 }
67
68 private function warn( $data ) {
69 wfDebug( "IMPORT: $data\n" );
70 }
71
72 private function notice( $data ) {
73 global $wgCommandLineMode;
74 if( $wgCommandLineMode ) {
75 print "$data\n";
76 } else {
77 global $wgOut;
78 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
79 }
80 }
81
82 /**
83 * Set debug mode...
84 */
85 function setDebug( $debug ) {
86 $this->mDebug = $debug;
87 }
88
89 /**
90 * Sets the action to perform as each new page in the stream is reached.
91 * @param $callback callback
92 * @return callback
93 */
94 public function setPageCallback( $callback ) {
95 $previous = $this->mPageCallback;
96 $this->mPageCallback = $callback;
97 return $previous;
98 }
99
100 /**
101 * Sets the action to perform as each page in the stream is completed.
102 * Callback accepts the page title (as a Title object), a second object
103 * with the original title form (in case it's been overridden into a
104 * local namespace), and a count of revisions.
105 *
106 * @param $callback callback
107 * @return callback
108 */
109 public function setPageOutCallback( $callback ) {
110 $previous = $this->mPageOutCallback;
111 $this->mPageOutCallback = $callback;
112 return $previous;
113 }
114
115 /**
116 * Sets the action to perform as each page revision is reached.
117 * @param $callback callback
118 * @return callback
119 */
120 public function setRevisionCallback( $callback ) {
121 $previous = $this->mRevisionCallback;
122 $this->mRevisionCallback = $callback;
123 return $previous;
124 }
125
126 /**
127 * Sets the action to perform as each file upload version is reached.
128 * @param $callback callback
129 * @return callback
130 */
131 public function setUploadCallback( $callback ) {
132 $previous = $this->mUploadCallback;
133 $this->mUploadCallback = $callback;
134 return $previous;
135 }
136
137 /**
138 * Sets the action to perform as each log item reached.
139 * @param $callback callback
140 * @return callback
141 */
142 public function setLogItemCallback( $callback ) {
143 $previous = $this->mLogItemCallback;
144 $this->mLogItemCallback = $callback;
145 return $previous;
146 }
147
148 /**
149 * Sets the action to perform when site info is encountered
150 * @param $callback callback
151 * @return callback
152 */
153 public function setSiteInfoCallback( $callback ) {
154 $previous = $this->mSiteInfoCallback;
155 $this->mSiteInfoCallback = $callback;
156 return $previous;
157 }
158
159 /**
160 * Set a target namespace to override the defaults
161 */
162 public function setTargetNamespace( $namespace ) {
163 if( is_null( $namespace ) ) {
164 // Don't override namespaces
165 $this->mTargetNamespace = null;
166 } elseif( $namespace >= 0 ) {
167 // @todo FIXME: Check for validity
168 $this->mTargetNamespace = intval( $namespace );
169 } else {
170 return false;
171 }
172 }
173
174 /**
175 *
176 */
177 public function setImageBasePath( $dir ) {
178 $this->mImageBasePath = $dir;
179 }
180 public function setImportUploads( $import ) {
181 $this->mImportUploads = $import;
182 }
183
184 /**
185 * Default per-revision callback, performs the import.
186 * @param $revision WikiRevision
187 */
188 public function importRevision( $revision ) {
189 $dbw = wfGetDB( DB_MASTER );
190 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
191 }
192
193 /**
194 * Default per-revision callback, performs the import.
195 * @param $rev WikiRevision
196 */
197 public function importLogItem( $rev ) {
198 $dbw = wfGetDB( DB_MASTER );
199 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
200 }
201
202 /**
203 * Dummy for now...
204 */
205 public function importUpload( $revision ) {
206 $dbw = wfGetDB( DB_MASTER );
207 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
208 }
209
210 /**
211 * Mostly for hook use
212 */
213 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
214 $args = func_get_args();
215 return wfRunHooks( 'AfterImportPage', $args );
216 }
217
218 /**
219 * Alternate per-revision callback, for debugging.
220 * @param $revision WikiRevision
221 */
222 public function debugRevisionHandler( &$revision ) {
223 $this->debug( "Got revision:" );
224 if( is_object( $revision->title ) ) {
225 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
226 } else {
227 $this->debug( "-- Title: <invalid>" );
228 }
229 $this->debug( "-- User: " . $revision->user_text );
230 $this->debug( "-- Timestamp: " . $revision->timestamp );
231 $this->debug( "-- Comment: " . $revision->comment );
232 $this->debug( "-- Text: " . $revision->text );
233 }
234
235 /**
236 * Notify the callback function when a new <page> is reached.
237 * @param $title Title
238 */
239 function pageCallback( $title ) {
240 if( isset( $this->mPageCallback ) ) {
241 call_user_func( $this->mPageCallback, $title );
242 }
243 }
244
245 /**
246 * Notify the callback function when a </page> is closed.
247 * @param $title Title
248 * @param $origTitle Title
249 * @param $revCount Integer
250 * @param $sucCount Int: number of revisions for which callback returned true
251 * @param $pageInfo Array: associative array of page information
252 */
253 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
254 if( isset( $this->mPageOutCallback ) ) {
255 $args = func_get_args();
256 call_user_func_array( $this->mPageOutCallback, $args );
257 }
258 }
259
260 /**
261 * Notify the callback function of a revision
262 * @param $revision A WikiRevision object
263 */
264 private function revisionCallback( $revision ) {
265 if ( isset( $this->mRevisionCallback ) ) {
266 return call_user_func_array( $this->mRevisionCallback,
267 array( $revision, $this ) );
268 } else {
269 return false;
270 }
271 }
272
273 /**
274 * Notify the callback function of a new log item
275 * @param $revision A WikiRevision object
276 */
277 private function logItemCallback( $revision ) {
278 if ( isset( $this->mLogItemCallback ) ) {
279 return call_user_func_array( $this->mLogItemCallback,
280 array( $revision, $this ) );
281 } else {
282 return false;
283 }
284 }
285
286 /**
287 * Shouldn't something like this be built-in to XMLReader?
288 * Fetches text contents of the current element, assuming
289 * no sub-elements or such scary things.
290 * @return string
291 * @access private
292 */
293 private function nodeContents() {
294 if( $this->reader->isEmptyElement ) {
295 return "";
296 }
297 $buffer = "";
298 while( $this->reader->read() ) {
299 switch( $this->reader->nodeType ) {
300 case XmlReader::TEXT:
301 case XmlReader::SIGNIFICANT_WHITESPACE:
302 $buffer .= $this->reader->value;
303 break;
304 case XmlReader::END_ELEMENT:
305 return $buffer;
306 }
307 }
308
309 $this->reader->close();
310 return '';
311 }
312
313 # --------------
314
315 /** Left in for debugging */
316 private function dumpElement() {
317 static $lookup = null;
318 if (!$lookup) {
319 $xmlReaderConstants = array(
320 "NONE",
321 "ELEMENT",
322 "ATTRIBUTE",
323 "TEXT",
324 "CDATA",
325 "ENTITY_REF",
326 "ENTITY",
327 "PI",
328 "COMMENT",
329 "DOC",
330 "DOC_TYPE",
331 "DOC_FRAGMENT",
332 "NOTATION",
333 "WHITESPACE",
334 "SIGNIFICANT_WHITESPACE",
335 "END_ELEMENT",
336 "END_ENTITY",
337 "XML_DECLARATION",
338 );
339 $lookup = array();
340
341 foreach( $xmlReaderConstants as $name ) {
342 $lookup[constant("XmlReader::$name")] = $name;
343 }
344 }
345
346 print( var_dump(
347 $lookup[$this->reader->nodeType],
348 $this->reader->name,
349 $this->reader->value
350 )."\n\n" );
351 }
352
353 /**
354 * Primary entry point
355 */
356 public function doImport() {
357 $this->reader->read();
358
359 if ( $this->reader->name != 'mediawiki' ) {
360 throw new MWException( "Expected <mediawiki> tag, got ".
361 $this->reader->name );
362 }
363 $this->debug( "<mediawiki> tag is correct." );
364
365 $this->debug( "Starting primary dump processing loop." );
366
367 $keepReading = $this->reader->read();
368 $skip = false;
369 while ( $keepReading ) {
370 $tag = $this->reader->name;
371 $type = $this->reader->nodeType;
372
373 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
374 // Do nothing
375 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
376 break;
377 } elseif ( $tag == 'siteinfo' ) {
378 $this->handleSiteInfo();
379 } elseif ( $tag == 'page' ) {
380 $this->handlePage();
381 } elseif ( $tag == 'logitem' ) {
382 $this->handleLogItem();
383 } elseif ( $tag != '#text' ) {
384 $this->warn( "Unhandled top-level XML tag $tag" );
385
386 $skip = true;
387 }
388
389 if ($skip) {
390 $keepReading = $this->reader->next();
391 $skip = false;
392 $this->debug( "Skip" );
393 } else {
394 $keepReading = $this->reader->read();
395 }
396 }
397
398 return true;
399 }
400
401 private function handleSiteInfo() {
402 // Site info is useful, but not actually used for dump imports.
403 // Includes a quick short-circuit to save performance.
404 if ( ! $this->mSiteInfoCallback ) {
405 $this->reader->next();
406 return true;
407 }
408 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
409 }
410
411 private function handleLogItem() {
412 $this->debug( "Enter log item handler." );
413 $logInfo = array();
414
415 // Fields that can just be stuffed in the pageInfo object
416 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
417 'logtitle', 'params' );
418
419 while ( $this->reader->read() ) {
420 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
421 $this->reader->name == 'logitem') {
422 break;
423 }
424
425 $tag = $this->reader->name;
426
427 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
428 $this, $logInfo ) ) {
429 // Do nothing
430 } elseif ( in_array( $tag, $normalFields ) ) {
431 $logInfo[$tag] = $this->nodeContents();
432 } elseif ( $tag == 'contributor' ) {
433 $logInfo['contributor'] = $this->handleContributor();
434 } elseif ( $tag != '#text' ) {
435 $this->warn( "Unhandled log-item XML tag $tag" );
436 }
437 }
438
439 $this->processLogItem( $logInfo );
440 }
441
442 private function processLogItem( $logInfo ) {
443 $revision = new WikiRevision;
444
445 $revision->setID( $logInfo['id'] );
446 $revision->setType( $logInfo['type'] );
447 $revision->setAction( $logInfo['action'] );
448 $revision->setTimestamp( $logInfo['timestamp'] );
449 $revision->setParams( $logInfo['params'] );
450 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
451
452 if ( isset( $logInfo['comment'] ) ) {
453 $revision->setComment( $logInfo['comment'] );
454 }
455
456 if ( isset( $logInfo['contributor']['ip'] ) ) {
457 $revision->setUserIP( $logInfo['contributor']['ip'] );
458 }
459 if ( isset( $logInfo['contributor']['username'] ) ) {
460 $revision->setUserName( $logInfo['contributor']['username'] );
461 }
462
463 return $this->logItemCallback( $revision );
464 }
465
466 private function handlePage() {
467 // Handle page data.
468 $this->debug( "Enter page handler." );
469 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
470
471 // Fields that can just be stuffed in the pageInfo object
472 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
473
474 $skip = false;
475 $badTitle = false;
476
477 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
478 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
479 $this->reader->name == 'page') {
480 break;
481 }
482
483 $tag = $this->reader->name;
484
485 if ( $badTitle ) {
486 // The title is invalid, bail out of this page
487 $skip = true;
488 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
489 &$pageInfo ) ) ) {
490 // Do nothing
491 } elseif ( in_array( $tag, $normalFields ) ) {
492 $pageInfo[$tag] = $this->nodeContents();
493 if ( $tag == 'title' ) {
494 $title = $this->processTitle( $pageInfo['title'] );
495
496 if ( !$title ) {
497 $badTitle = true;
498 $skip = true;
499 }
500
501 $this->pageCallback( $title );
502 list( $pageInfo['_title'], $origTitle ) = $title;
503 }
504 } elseif ( $tag == 'revision' ) {
505 $this->handleRevision( $pageInfo );
506 } elseif ( $tag == 'upload' ) {
507 $this->handleUpload( $pageInfo );
508 } elseif ( $tag != '#text' ) {
509 $this->warn( "Unhandled page XML tag $tag" );
510 $skip = true;
511 }
512 }
513
514 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
515 $pageInfo['revisionCount'],
516 $pageInfo['successfulRevisionCount'],
517 $pageInfo );
518 }
519
520 private function handleRevision( &$pageInfo ) {
521 $this->debug( "Enter revision handler" );
522 $revisionInfo = array();
523
524 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
525
526 $skip = false;
527
528 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
529 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
530 $this->reader->name == 'revision') {
531 break;
532 }
533
534 $tag = $this->reader->name;
535
536 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
537 $pageInfo, $revisionInfo ) ) {
538 // Do nothing
539 } elseif ( in_array( $tag, $normalFields ) ) {
540 $revisionInfo[$tag] = $this->nodeContents();
541 } elseif ( $tag == 'contributor' ) {
542 $revisionInfo['contributor'] = $this->handleContributor();
543 } elseif ( $tag != '#text' ) {
544 $this->warn( "Unhandled revision XML tag $tag" );
545 $skip = true;
546 }
547 }
548
549 $pageInfo['revisionCount']++;
550 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
551 $pageInfo['successfulRevisionCount']++;
552 }
553 }
554
555 private function processRevision( $pageInfo, $revisionInfo ) {
556 $revision = new WikiRevision;
557
558 if( isset( $revisionInfo['id'] ) ) {
559 $revision->setID( $revisionInfo['id'] );
560 }
561 if ( isset( $revisionInfo['text'] ) ) {
562 $revision->setText( $revisionInfo['text'] );
563 }
564 $revision->setTitle( $pageInfo['_title'] );
565
566 if ( isset( $revisionInfo['timestamp'] ) ) {
567 $revision->setTimestamp( $revisionInfo['timestamp'] );
568 } else {
569 $revision->setTimestamp( wfTimestampNow() );
570 }
571
572 if ( isset( $revisionInfo['comment'] ) ) {
573 $revision->setComment( $revisionInfo['comment'] );
574 }
575
576 if ( isset( $revisionInfo['minor'] ) ) {
577 $revision->setMinor( true );
578 }
579 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
580 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
581 }
582 if ( isset( $revisionInfo['contributor']['username'] ) ) {
583 $revision->setUserName( $revisionInfo['contributor']['username'] );
584 }
585
586 return $this->revisionCallback( $revision );
587 }
588
589 private function handleUpload( &$pageInfo ) {
590 $this->debug( "Enter upload handler" );
591 $uploadInfo = array();
592
593 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
594 'src', 'size', 'sha1base36', 'archivename', 'rel' );
595
596 $skip = false;
597
598 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
599 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
600 $this->reader->name == 'upload') {
601 break;
602 }
603
604 $tag = $this->reader->name;
605
606 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
607 $pageInfo ) ) {
608 // Do nothing
609 } elseif ( in_array( $tag, $normalFields ) ) {
610 $uploadInfo[$tag] = $this->nodeContents();
611 } elseif ( $tag == 'contributor' ) {
612 $uploadInfo['contributor'] = $this->handleContributor();
613 } elseif ( $tag == 'contents' ) {
614 $contents = $this->nodeContents();
615 $encoding = $this->reader->getAttribute( 'encoding' );
616 if ( $encoding === 'base64' ) {
617 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
618 $uploadInfo['isTempSrc'] = true;
619 }
620 } elseif ( $tag != '#text' ) {
621 $this->warn( "Unhandled upload XML tag $tag" );
622 $skip = true;
623 }
624 }
625
626 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
627 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
628 if ( file_exists( $path ) ) {
629 $uploadInfo['fileSrc'] = $path;
630 $uploadInfo['isTempSrc'] = false;
631 }
632 }
633
634 if ( $this->mImportUploads ) {
635 return $this->processUpload( $pageInfo, $uploadInfo );
636 }
637 }
638
639 private function dumpTemp( $contents ) {
640 $filename = tempnam( wfTempDir(), 'importupload' );
641 file_put_contents( $filename, $contents );
642 return $filename;
643 }
644
645
646 private function processUpload( $pageInfo, $uploadInfo ) {
647 $revision = new WikiRevision;
648 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
649
650 $revision->setTitle( $pageInfo['_title'] );
651 $revision->setID( $pageInfo['id'] );
652 $revision->setTimestamp( $uploadInfo['timestamp'] );
653 $revision->setText( $text );
654 $revision->setFilename( $uploadInfo['filename'] );
655 if ( isset( $uploadInfo['archivename'] ) ) {
656 $revision->setArchiveName( $uploadInfo['archivename'] );
657 }
658 $revision->setSrc( $uploadInfo['src'] );
659 if ( isset( $uploadInfo['fileSrc'] ) ) {
660 $revision->setFileSrc( $uploadInfo['fileSrc'],
661 !empty( $uploadInfo['isTempSrc'] ) );
662 }
663 if ( isset( $uploadInfo['sha1base36'] ) ) {
664 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
665 }
666 $revision->setSize( intval( $uploadInfo['size'] ) );
667 $revision->setComment( $uploadInfo['comment'] );
668
669 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
670 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
671 }
672 if ( isset( $uploadInfo['contributor']['username'] ) ) {
673 $revision->setUserName( $uploadInfo['contributor']['username'] );
674 }
675
676 return call_user_func( $this->mUploadCallback, $revision );
677 }
678
679 private function handleContributor() {
680 $fields = array( 'id', 'ip', 'username' );
681 $info = array();
682
683 while ( $this->reader->read() ) {
684 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
685 $this->reader->name == 'contributor') {
686 break;
687 }
688
689 $tag = $this->reader->name;
690
691 if ( in_array( $tag, $fields ) ) {
692 $info[$tag] = $this->nodeContents();
693 }
694 }
695
696 return $info;
697 }
698
699 private function processTitle( $text ) {
700 $workTitle = $text;
701 $origTitle = Title::newFromText( $workTitle );
702
703 if( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
704 $title = Title::makeTitle( $this->mTargetNamespace,
705 $origTitle->getDBkey() );
706 } else {
707 $title = Title::newFromText( $workTitle );
708 }
709
710 if( is_null( $title ) ) {
711 // Invalid page title? Ignore the page
712 $this->notice( "Skipping invalid page title '$workTitle'" );
713 return false;
714 } elseif( $title->getInterwiki() != '' ) {
715 $this->notice( "Skipping interwiki page title '$workTitle'" );
716 return false;
717 }
718
719 return array( $title, $origTitle );
720 }
721 }
722
723 /** This is a horrible hack used to keep source compatibility */
724 class UploadSourceAdapter {
725 static $sourceRegistrations = array();
726
727 private $mSource;
728 private $mBuffer;
729 private $mPosition;
730
731 static function registerSource( $source ) {
732 $id = wfGenerateToken();
733
734 self::$sourceRegistrations[$id] = $source;
735
736 return $id;
737 }
738
739 function stream_open( $path, $mode, $options, &$opened_path ) {
740 $url = parse_url($path);
741 $id = $url['host'];
742
743 if ( !isset( self::$sourceRegistrations[$id] ) ) {
744 return false;
745 }
746
747 $this->mSource = self::$sourceRegistrations[$id];
748
749 return true;
750 }
751
752 function stream_read( $count ) {
753 $return = '';
754 $leave = false;
755
756 while ( !$leave && !$this->mSource->atEnd() &&
757 strlen($this->mBuffer) < $count ) {
758 $read = $this->mSource->readChunk();
759
760 if ( !strlen($read) ) {
761 $leave = true;
762 }
763
764 $this->mBuffer .= $read;
765 }
766
767 if ( strlen($this->mBuffer) ) {
768 $return = substr( $this->mBuffer, 0, $count );
769 $this->mBuffer = substr( $this->mBuffer, $count );
770 }
771
772 $this->mPosition += strlen($return);
773
774 return $return;
775 }
776
777 function stream_write( $data ) {
778 return false;
779 }
780
781 function stream_tell() {
782 return $this->mPosition;
783 }
784
785 function stream_eof() {
786 return $this->mSource->atEnd();
787 }
788
789 function url_stat() {
790 $result = array();
791
792 $result['dev'] = $result[0] = 0;
793 $result['ino'] = $result[1] = 0;
794 $result['mode'] = $result[2] = 0;
795 $result['nlink'] = $result[3] = 0;
796 $result['uid'] = $result[4] = 0;
797 $result['gid'] = $result[5] = 0;
798 $result['rdev'] = $result[6] = 0;
799 $result['size'] = $result[7] = 0;
800 $result['atime'] = $result[8] = 0;
801 $result['mtime'] = $result[9] = 0;
802 $result['ctime'] = $result[10] = 0;
803 $result['blksize'] = $result[11] = 0;
804 $result['blocks'] = $result[12] = 0;
805
806 return $result;
807 }
808 }
809
810 class XMLReader2 extends XMLReader {
811 function nodeContents() {
812 if( $this->isEmptyElement ) {
813 return "";
814 }
815 $buffer = "";
816 while( $this->read() ) {
817 switch( $this->nodeType ) {
818 case XmlReader::TEXT:
819 case XmlReader::SIGNIFICANT_WHITESPACE:
820 $buffer .= $this->value;
821 break;
822 case XmlReader::END_ELEMENT:
823 return $buffer;
824 }
825 }
826 return $this->close();
827 }
828 }
829
830 /**
831 * @todo document (e.g. one-sentence class description).
832 * @ingroup SpecialPage
833 */
834 class WikiRevision {
835 var $importer = null;
836 var $title = null;
837 var $id = 0;
838 var $timestamp = "20010115000000";
839 var $user = 0;
840 var $user_text = "";
841 var $text = "";
842 var $comment = "";
843 var $minor = false;
844 var $type = "";
845 var $action = "";
846 var $params = "";
847 var $fileSrc = '';
848 var $sha1base36 = false;
849 var $isTemp = false;
850 var $archiveName = '';
851
852 function setTitle( $title ) {
853 if( is_object( $title ) ) {
854 $this->title = $title;
855 } elseif( is_null( $title ) ) {
856 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
857 } else {
858 throw new MWException( "WikiRevision given non-object title in import." );
859 }
860 }
861
862 function setID( $id ) {
863 $this->id = $id;
864 }
865
866 function setTimestamp( $ts ) {
867 # 2003-08-05T18:30:02Z
868 $this->timestamp = wfTimestamp( TS_MW, $ts );
869 }
870
871 function setUsername( $user ) {
872 $this->user_text = $user;
873 }
874
875 function setUserIP( $ip ) {
876 $this->user_text = $ip;
877 }
878
879 function setText( $text ) {
880 $this->text = $text;
881 }
882
883 function setComment( $text ) {
884 $this->comment = $text;
885 }
886
887 function setMinor( $minor ) {
888 $this->minor = (bool)$minor;
889 }
890
891 function setSrc( $src ) {
892 $this->src = $src;
893 }
894 function setFileSrc( $src, $isTemp ) {
895 $this->fileSrc = $src;
896 $this->fileIsTemp = $isTemp;
897 }
898 function setSha1Base36( $sha1base36 ) {
899 $this->sha1base36 = $sha1base36;
900 }
901
902 function setFilename( $filename ) {
903 $this->filename = $filename;
904 }
905 function setArchiveName( $archiveName ) {
906 $this->archiveName = $archiveName;
907 }
908
909 function setSize( $size ) {
910 $this->size = intval( $size );
911 }
912
913 function setType( $type ) {
914 $this->type = $type;
915 }
916
917 function setAction( $action ) {
918 $this->action = $action;
919 }
920
921 function setParams( $params ) {
922 $this->params = $params;
923 }
924
925 /**
926 * @return Title
927 */
928 function getTitle() {
929 return $this->title;
930 }
931
932 function getID() {
933 return $this->id;
934 }
935
936 function getTimestamp() {
937 return $this->timestamp;
938 }
939
940 function getUser() {
941 return $this->user_text;
942 }
943
944 function getText() {
945 return $this->text;
946 }
947
948 function getComment() {
949 return $this->comment;
950 }
951
952 function getMinor() {
953 return $this->minor;
954 }
955
956 function getSrc() {
957 return $this->src;
958 }
959 function getSha1() {
960 if ( $this->sha1base36 ) {
961 return wfBaseConvert( $this->sha1base36, 36, 16 );
962 }
963 return false;
964 }
965 function getFileSrc() {
966 return $this->fileSrc;
967 }
968 function isTempSrc() {
969 return $this->isTemp;
970 }
971
972 function getFilename() {
973 return $this->filename;
974 }
975 function getArchiveName() {
976 return $this->archiveName;
977 }
978
979 function getSize() {
980 return $this->size;
981 }
982
983 function getType() {
984 return $this->type;
985 }
986
987 function getAction() {
988 return $this->action;
989 }
990
991 function getParams() {
992 return $this->params;
993 }
994
995 function importOldRevision() {
996 $dbw = wfGetDB( DB_MASTER );
997
998 # Sneak a single revision into place
999 $user = User::newFromName( $this->getUser() );
1000 if( $user ) {
1001 $userId = intval( $user->getId() );
1002 $userText = $user->getName();
1003 $userObj = $user;
1004 } else {
1005 $userId = 0;
1006 $userText = $this->getUser();
1007 $userObj = new User;
1008 }
1009
1010 // avoid memory leak...?
1011 $linkCache = LinkCache::singleton();
1012 $linkCache->clear();
1013
1014 $article = new Article( $this->title );
1015 $pageId = $article->getId();
1016 if( $pageId == 0 ) {
1017 # must create the page...
1018 $pageId = $article->insertOn( $dbw );
1019 $created = true;
1020 $oldcountable = null;
1021 } else {
1022 $created = false;
1023
1024 $prior = $dbw->selectField( 'revision', '1',
1025 array( 'rev_page' => $pageId,
1026 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1027 'rev_user_text' => $userText,
1028 'rev_comment' => $this->getComment() ),
1029 __METHOD__
1030 );
1031 if( $prior ) {
1032 // @todo FIXME: This could fail slightly for multiple matches :P
1033 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1034 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1035 return false;
1036 }
1037 $oldcountable = $article->isCountable();
1038 }
1039
1040 # @todo FIXME: Use original rev_id optionally (better for backups)
1041 # Insert the row
1042 $revision = new Revision( array(
1043 'page' => $pageId,
1044 'text' => $this->getText(),
1045 'comment' => $this->getComment(),
1046 'user' => $userId,
1047 'user_text' => $userText,
1048 'timestamp' => $this->timestamp,
1049 'minor_edit' => $this->minor,
1050 ) );
1051 $revision->insertOn( $dbw );
1052 $changed = $article->updateIfNewerOn( $dbw, $revision );
1053
1054 if ( $changed !== false ) {
1055 wfDebug( __METHOD__ . ": running updates\n" );
1056 $article->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1057 }
1058
1059 return true;
1060 }
1061
1062 function importLogItem() {
1063 $dbw = wfGetDB( DB_MASTER );
1064 # @todo FIXME: This will not record autoblocks
1065 if( !$this->getTitle() ) {
1066 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1067 $this->timestamp . "\n" );
1068 return;
1069 }
1070 # Check if it exists already
1071 // @todo FIXME: Use original log ID (better for backups)
1072 $prior = $dbw->selectField( 'logging', '1',
1073 array( 'log_type' => $this->getType(),
1074 'log_action' => $this->getAction(),
1075 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1076 'log_namespace' => $this->getTitle()->getNamespace(),
1077 'log_title' => $this->getTitle()->getDBkey(),
1078 'log_comment' => $this->getComment(),
1079 #'log_user_text' => $this->user_text,
1080 'log_params' => $this->params ),
1081 __METHOD__
1082 );
1083 // @todo FIXME: This could fail slightly for multiple matches :P
1084 if( $prior ) {
1085 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1086 $this->timestamp . "\n" );
1087 return false;
1088 }
1089 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1090 $data = array(
1091 'log_id' => $log_id,
1092 'log_type' => $this->type,
1093 'log_action' => $this->action,
1094 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1095 'log_user' => User::idFromName( $this->user_text ),
1096 #'log_user_text' => $this->user_text,
1097 'log_namespace' => $this->getTitle()->getNamespace(),
1098 'log_title' => $this->getTitle()->getDBkey(),
1099 'log_comment' => $this->getComment(),
1100 'log_params' => $this->params
1101 );
1102 $dbw->insert( 'logging', $data, __METHOD__ );
1103 }
1104
1105 function importUpload() {
1106 # Construct a file
1107 $archiveName = $this->getArchiveName();
1108 if ( $archiveName ) {
1109 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1110 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1111 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1112 } else {
1113 $file = wfLocalFile( $this->getTitle() );
1114 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1115 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1116 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1117 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1118 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1119 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1120 }
1121 }
1122 if( !$file ) {
1123 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1124 return false;
1125 }
1126
1127 # Get the file source or download if necessary
1128 $source = $this->getFileSrc();
1129 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1130 if ( !$source ) {
1131 $source = $this->downloadSource();
1132 $flags |= File::DELETE_SOURCE;
1133 }
1134 if( !$source ) {
1135 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1136 return false;
1137 }
1138 $sha1 = $this->getSha1();
1139 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1140 if ( $flags & File::DELETE_SOURCE ) {
1141 # Broken file; delete it if it is a temporary file
1142 unlink( $source );
1143 }
1144 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1145 return false;
1146 }
1147
1148 $user = User::newFromName( $this->user_text );
1149
1150 # Do the actual upload
1151 if ( $archiveName ) {
1152 $status = $file->uploadOld( $source, $archiveName,
1153 $this->getTimestamp(), $this->getComment(), $user, $flags );
1154 } else {
1155 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1156 $flags, false, $this->getTimestamp(), $user );
1157 }
1158
1159 if ( $status->isGood() ) {
1160 wfDebug( __METHOD__ . ": Succesful\n" );
1161 return true;
1162 } else {
1163 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1164 return false;
1165 }
1166 }
1167
1168 function downloadSource() {
1169 global $wgEnableUploads;
1170 if( !$wgEnableUploads ) {
1171 return false;
1172 }
1173
1174 $tempo = tempnam( wfTempDir(), 'download' );
1175 $f = fopen( $tempo, 'wb' );
1176 if( !$f ) {
1177 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1178 return false;
1179 }
1180
1181 // @todo FIXME!
1182 $src = $this->getSrc();
1183 $data = Http::get( $src );
1184 if( !$data ) {
1185 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1186 fclose( $f );
1187 unlink( $tempo );
1188 return false;
1189 }
1190
1191 fwrite( $f, $data );
1192 fclose( $f );
1193
1194 return $tempo;
1195 }
1196
1197 }
1198
1199 /**
1200 * @todo document (e.g. one-sentence class description).
1201 * @ingroup SpecialPage
1202 */
1203 class ImportStringSource {
1204 function __construct( $string ) {
1205 $this->mString = $string;
1206 $this->mRead = false;
1207 }
1208
1209 function atEnd() {
1210 return $this->mRead;
1211 }
1212
1213 function readChunk() {
1214 if( $this->atEnd() ) {
1215 return false;
1216 } else {
1217 $this->mRead = true;
1218 return $this->mString;
1219 }
1220 }
1221 }
1222
1223 /**
1224 * @todo document (e.g. one-sentence class description).
1225 * @ingroup SpecialPage
1226 */
1227 class ImportStreamSource {
1228 function __construct( $handle ) {
1229 $this->mHandle = $handle;
1230 }
1231
1232 function atEnd() {
1233 return feof( $this->mHandle );
1234 }
1235
1236 function readChunk() {
1237 return fread( $this->mHandle, 32768 );
1238 }
1239
1240 static function newFromFile( $filename ) {
1241 wfSuppressWarnings();
1242 $file = fopen( $filename, 'rt' );
1243 wfRestoreWarnings();
1244 if( !$file ) {
1245 return Status::newFatal( "importcantopen" );
1246 }
1247 return Status::newGood( new ImportStreamSource( $file ) );
1248 }
1249
1250 static function newFromUpload( $fieldname = "xmlimport" ) {
1251 $upload =& $_FILES[$fieldname];
1252
1253 if( !isset( $upload ) || !$upload['name'] ) {
1254 return Status::newFatal( 'importnofile' );
1255 }
1256 if( !empty( $upload['error'] ) ) {
1257 switch($upload['error']){
1258 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1259 return Status::newFatal( 'importuploaderrorsize' );
1260 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1261 return Status::newFatal( 'importuploaderrorsize' );
1262 case 3: # The uploaded file was only partially uploaded
1263 return Status::newFatal( 'importuploaderrorpartial' );
1264 case 6: #Missing a temporary folder.
1265 return Status::newFatal( 'importuploaderrortemp' );
1266 # case else: # Currently impossible
1267 }
1268
1269 }
1270 $fname = $upload['tmp_name'];
1271 if( is_uploaded_file( $fname ) ) {
1272 return ImportStreamSource::newFromFile( $fname );
1273 } else {
1274 return Status::newFatal( 'importnofile' );
1275 }
1276 }
1277
1278 static function newFromURL( $url, $method = 'GET' ) {
1279 wfDebug( __METHOD__ . ": opening $url\n" );
1280 # Use the standard HTTP fetch function; it times out
1281 # quicker and sorts out user-agent problems which might
1282 # otherwise prevent importing from large sites, such
1283 # as the Wikimedia cluster, etc.
1284 $data = Http::request( $method, $url );
1285 if( $data !== false ) {
1286 $file = tmpfile();
1287 fwrite( $file, $data );
1288 fflush( $file );
1289 fseek( $file, 0 );
1290 return Status::newGood( new ImportStreamSource( $file ) );
1291 } else {
1292 return Status::newFatal( 'importcantopen' );
1293 }
1294 }
1295
1296 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1297 if( $page == '' ) {
1298 return Status::newFatal( 'import-noarticle' );
1299 }
1300 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1301 if( is_null( $link ) || $link->getInterwiki() == '' ) {
1302 return Status::newFatal( 'importbadinterwiki' );
1303 } else {
1304 $params = array();
1305 if ( $history ) $params['history'] = 1;
1306 if ( $templates ) $params['templates'] = 1;
1307 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1308 $url = $link->getFullUrl( $params );
1309 # For interwikis, use POST to avoid redirects.
1310 return ImportStreamSource::newFromURL( $url, "POST" );
1311 }
1312 }
1313 }