Merge "Move ApiQueryRecentChanges::parseRCType to static method on RecentChange"
[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 * https://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, $mTargetRootPage, $mPageOutCallback;
37 private $mNoticeCallback, $mDebug;
38 private $mImportUploads, $mImageBasePath;
39 private $mNoUpdates = false;
40
41 /**
42 * Creates an ImportXMLReader drawing from the source provided
43 * @param string $source
44 */
45 function __construct( $source ) {
46 $this->reader = new XMLReader();
47
48 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
49 $id = UploadSourceAdapter::registerSource( $source );
50 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
51 $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
52 } else {
53 $this->reader->open( "uploadsource://$id" );
54 }
55
56 // Default callbacks
57 $this->setRevisionCallback( array( $this, "importRevision" ) );
58 $this->setUploadCallback( array( $this, 'importUpload' ) );
59 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
60 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
61 }
62
63 /**
64 * @return null|XMLReader
65 */
66 public function getReader() {
67 return $this->reader;
68 }
69
70 public function throwXmlError( $err ) {
71 $this->debug( "FAILURE: $err" );
72 wfDebug( "WikiImporter XML error: $err\n" );
73 }
74
75 public function debug( $data ) {
76 if ( $this->mDebug ) {
77 wfDebug( "IMPORT: $data\n" );
78 }
79 }
80
81 public function warn( $data ) {
82 wfDebug( "IMPORT: $data\n" );
83 }
84
85 public function notice( $msg /*, $param, ...*/ ) {
86 $params = func_get_args();
87 array_shift( $params );
88
89 if ( is_callable( $this->mNoticeCallback ) ) {
90 call_user_func( $this->mNoticeCallback, $msg, $params );
91 } else { # No ImportReporter -> CLI
92 echo wfMessage( $msg, $params )->text() . "\n";
93 }
94 }
95
96 /**
97 * Set debug mode...
98 * @param bool $debug
99 */
100 function setDebug( $debug ) {
101 $this->mDebug = $debug;
102 }
103
104 /**
105 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
106 * @param bool $noupdates
107 */
108 function setNoUpdates( $noupdates ) {
109 $this->mNoUpdates = $noupdates;
110 }
111
112 /**
113 * Set a callback that displays notice messages
114 *
115 * @param callable $callback
116 * @return callable
117 */
118 public function setNoticeCallback( $callback ) {
119 return wfSetVar( $this->mNoticeCallback, $callback );
120 }
121
122 /**
123 * Sets the action to perform as each new page in the stream is reached.
124 * @param callable $callback
125 * @return callable
126 */
127 public function setPageCallback( $callback ) {
128 $previous = $this->mPageCallback;
129 $this->mPageCallback = $callback;
130 return $previous;
131 }
132
133 /**
134 * Sets the action to perform as each page in the stream is completed.
135 * Callback accepts the page title (as a Title object), a second object
136 * with the original title form (in case it's been overridden into a
137 * local namespace), and a count of revisions.
138 *
139 * @param callable $callback
140 * @return callable
141 */
142 public function setPageOutCallback( $callback ) {
143 $previous = $this->mPageOutCallback;
144 $this->mPageOutCallback = $callback;
145 return $previous;
146 }
147
148 /**
149 * Sets the action to perform as each page revision is reached.
150 * @param callable $callback
151 * @return callable
152 */
153 public function setRevisionCallback( $callback ) {
154 $previous = $this->mRevisionCallback;
155 $this->mRevisionCallback = $callback;
156 return $previous;
157 }
158
159 /**
160 * Sets the action to perform as each file upload version is reached.
161 * @param callable $callback
162 * @return callable
163 */
164 public function setUploadCallback( $callback ) {
165 $previous = $this->mUploadCallback;
166 $this->mUploadCallback = $callback;
167 return $previous;
168 }
169
170 /**
171 * Sets the action to perform as each log item reached.
172 * @param callable $callback
173 * @return callable
174 */
175 public function setLogItemCallback( $callback ) {
176 $previous = $this->mLogItemCallback;
177 $this->mLogItemCallback = $callback;
178 return $previous;
179 }
180
181 /**
182 * Sets the action to perform when site info is encountered
183 * @param callable $callback
184 * @return callable
185 */
186 public function setSiteInfoCallback( $callback ) {
187 $previous = $this->mSiteInfoCallback;
188 $this->mSiteInfoCallback = $callback;
189 return $previous;
190 }
191
192 /**
193 * Set a target namespace to override the defaults
194 * @param null|int $namespace
195 * @return bool
196 */
197 public function setTargetNamespace( $namespace ) {
198 if ( is_null( $namespace ) ) {
199 // Don't override namespaces
200 $this->mTargetNamespace = null;
201 } elseif ( $namespace >= 0 ) {
202 // @todo FIXME: Check for validity
203 $this->mTargetNamespace = intval( $namespace );
204 } else {
205 return false;
206 }
207 }
208
209 /**
210 * Set a target root page under which all pages are imported
211 * @param null|string $rootpage
212 * @return Status
213 */
214 public function setTargetRootPage( $rootpage ) {
215 $status = Status::newGood();
216 if ( is_null( $rootpage ) ) {
217 // No rootpage
218 $this->mTargetRootPage = null;
219 } elseif ( $rootpage !== '' ) {
220 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
221 $title = Title::newFromText( $rootpage, !is_null( $this->mTargetNamespace ) ? $this->mTargetNamespace : NS_MAIN );
222 if ( !$title || $title->isExternal() ) {
223 $status->fatal( 'import-rootpage-invalid' );
224 } else {
225 if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
226 global $wgContLang;
227
228 $displayNSText = $title->getNamespace() == NS_MAIN
229 ? wfMessage( 'blanknamespace' )->text()
230 : $wgContLang->getNsText( $title->getNamespace() );
231 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
232 } else {
233 // set namespace to 'all', so the namespace check in processTitle() can passed
234 $this->setTargetNamespace( null );
235 $this->mTargetRootPage = $title->getPrefixedDBkey();
236 }
237 }
238 }
239 return $status;
240 }
241
242 /**
243 * @param string $dir
244 */
245 public function setImageBasePath( $dir ) {
246 $this->mImageBasePath = $dir;
247 }
248
249 /**
250 * @param bool $import
251 */
252 public function setImportUploads( $import ) {
253 $this->mImportUploads = $import;
254 }
255
256 /**
257 * Default per-revision callback, performs the import.
258 * @param WikiRevision $revision
259 * @return bool
260 */
261 public function importRevision( $revision ) {
262 if ( !$revision->getContent()->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
263 $this->notice( 'import-error-bad-location',
264 $revision->getTitle()->getPrefixedText(),
265 $revision->getID(),
266 $revision->getModel(),
267 $revision->getFormat() );
268
269 return false;
270 }
271
272 try {
273 $dbw = wfGetDB( DB_MASTER );
274 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
275 } catch ( MWContentSerializationException $ex ) {
276 $this->notice( 'import-error-unserialize',
277 $revision->getTitle()->getPrefixedText(),
278 $revision->getID(),
279 $revision->getModel(),
280 $revision->getFormat() );
281 }
282
283 return false;
284 }
285
286 /**
287 * Default per-revision callback, performs the import.
288 * @param WikiRevision $rev
289 * @return bool
290 */
291 public function importLogItem( $rev ) {
292 $dbw = wfGetDB( DB_MASTER );
293 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
294 }
295
296 /**
297 * Dummy for now...
298 * @param WikiRevision $revision
299 * @return bool
300 */
301 public function importUpload( $revision ) {
302 $dbw = wfGetDB( DB_MASTER );
303 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
304 }
305
306 /**
307 * Mostly for hook use
308 * @param Title $title
309 * @param string $origTitle
310 * @param int $revCount
311 * @param int $sRevCount
312 * @param array $pageInfo
313 * @return
314 */
315 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
316 $args = func_get_args();
317 return wfRunHooks( 'AfterImportPage', $args );
318 }
319
320 /**
321 * Alternate per-revision callback, for debugging.
322 * @param WikiRevision $revision
323 */
324 public function debugRevisionHandler( &$revision ) {
325 $this->debug( "Got revision:" );
326 if ( is_object( $revision->title ) ) {
327 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
328 } else {
329 $this->debug( "-- Title: <invalid>" );
330 }
331 $this->debug( "-- User: " . $revision->user_text );
332 $this->debug( "-- Timestamp: " . $revision->timestamp );
333 $this->debug( "-- Comment: " . $revision->comment );
334 $this->debug( "-- Text: " . $revision->text );
335 }
336
337 /**
338 * Notify the callback function when a new "<page>" is reached.
339 * @param Title $title
340 */
341 function pageCallback( $title ) {
342 if ( isset( $this->mPageCallback ) ) {
343 call_user_func( $this->mPageCallback, $title );
344 }
345 }
346
347 /**
348 * Notify the callback function when a "</page>" is closed.
349 * @param Title $title
350 * @param Title $origTitle
351 * @param int $revCount
352 * @param int $sucCount Number of revisions for which callback returned true
353 * @param array $pageInfo Associative array of page information
354 */
355 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
356 if ( isset( $this->mPageOutCallback ) ) {
357 $args = func_get_args();
358 call_user_func_array( $this->mPageOutCallback, $args );
359 }
360 }
361
362 /**
363 * Notify the callback function of a revision
364 * @param WikiRevision $revision
365 * @return bool|mixed
366 */
367 private function revisionCallback( $revision ) {
368 if ( isset( $this->mRevisionCallback ) ) {
369 return call_user_func_array( $this->mRevisionCallback,
370 array( $revision, $this ) );
371 } else {
372 return false;
373 }
374 }
375
376 /**
377 * Notify the callback function of a new log item
378 * @param WikiRevision $revision
379 * @return bool|mixed
380 */
381 private function logItemCallback( $revision ) {
382 if ( isset( $this->mLogItemCallback ) ) {
383 return call_user_func_array( $this->mLogItemCallback,
384 array( $revision, $this ) );
385 } else {
386 return false;
387 }
388 }
389
390 /**
391 * Shouldn't something like this be built-in to XMLReader?
392 * Fetches text contents of the current element, assuming
393 * no sub-elements or such scary things.
394 * @return string
395 * @access private
396 */
397 public function nodeContents() {
398 if ( $this->reader->isEmptyElement ) {
399 return "";
400 }
401 $buffer = "";
402 while ( $this->reader->read() ) {
403 switch ( $this->reader->nodeType ) {
404 case XmlReader::TEXT:
405 case XmlReader::SIGNIFICANT_WHITESPACE:
406 $buffer .= $this->reader->value;
407 break;
408 case XmlReader::END_ELEMENT:
409 return $buffer;
410 }
411 }
412
413 $this->reader->close();
414 return '';
415 }
416
417 # --------------
418
419 /** Left in for debugging */
420 private function dumpElement() {
421 static $lookup = null;
422 if ( !$lookup ) {
423 $xmlReaderConstants = array(
424 "NONE",
425 "ELEMENT",
426 "ATTRIBUTE",
427 "TEXT",
428 "CDATA",
429 "ENTITY_REF",
430 "ENTITY",
431 "PI",
432 "COMMENT",
433 "DOC",
434 "DOC_TYPE",
435 "DOC_FRAGMENT",
436 "NOTATION",
437 "WHITESPACE",
438 "SIGNIFICANT_WHITESPACE",
439 "END_ELEMENT",
440 "END_ENTITY",
441 "XML_DECLARATION",
442 );
443 $lookup = array();
444
445 foreach ( $xmlReaderConstants as $name ) {
446 $lookup[constant( "XmlReader::$name" )] = $name;
447 }
448 }
449
450 print var_dump(
451 $lookup[$this->reader->nodeType],
452 $this->reader->name,
453 $this->reader->value
454 ) . "\n\n";
455 }
456
457 /**
458 * Primary entry point
459 * @throws MWException
460 * @return bool
461 */
462 public function doImport() {
463
464 // Calls to reader->read need to be wrapped in calls to
465 // libxml_disable_entity_loader() to avoid local file
466 // inclusion attacks (bug 46932).
467 $oldDisable = libxml_disable_entity_loader( true );
468 $this->reader->read();
469
470 if ( $this->reader->name != 'mediawiki' ) {
471 libxml_disable_entity_loader( $oldDisable );
472 throw new MWException( "Expected <mediawiki> tag, got " .
473 $this->reader->name );
474 }
475 $this->debug( "<mediawiki> tag is correct." );
476
477 $this->debug( "Starting primary dump processing loop." );
478
479 $keepReading = $this->reader->read();
480 $skip = false;
481 while ( $keepReading ) {
482 $tag = $this->reader->name;
483 $type = $this->reader->nodeType;
484
485 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
486 // Do nothing
487 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
488 break;
489 } elseif ( $tag == 'siteinfo' ) {
490 $this->handleSiteInfo();
491 } elseif ( $tag == 'page' ) {
492 $this->handlePage();
493 } elseif ( $tag == 'logitem' ) {
494 $this->handleLogItem();
495 } elseif ( $tag != '#text' ) {
496 $this->warn( "Unhandled top-level XML tag $tag" );
497
498 $skip = true;
499 }
500
501 if ( $skip ) {
502 $keepReading = $this->reader->next();
503 $skip = false;
504 $this->debug( "Skip" );
505 } else {
506 $keepReading = $this->reader->read();
507 }
508 }
509
510 libxml_disable_entity_loader( $oldDisable );
511 return true;
512 }
513
514 /**
515 * @return bool
516 * @throws MWException
517 */
518 private function handleSiteInfo() {
519 // Site info is useful, but not actually used for dump imports.
520 // Includes a quick short-circuit to save performance.
521 if ( ! $this->mSiteInfoCallback ) {
522 $this->reader->next();
523 return true;
524 }
525 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
526 }
527
528 private function handleLogItem() {
529 $this->debug( "Enter log item handler." );
530 $logInfo = array();
531
532 // Fields that can just be stuffed in the pageInfo object
533 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
534 'logtitle', 'params' );
535
536 while ( $this->reader->read() ) {
537 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
538 $this->reader->name == 'logitem' ) {
539 break;
540 }
541
542 $tag = $this->reader->name;
543
544 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
545 $this, $logInfo
546 ) ) ) {
547 // Do nothing
548 } elseif ( in_array( $tag, $normalFields ) ) {
549 $logInfo[$tag] = $this->nodeContents();
550 } elseif ( $tag == 'contributor' ) {
551 $logInfo['contributor'] = $this->handleContributor();
552 } elseif ( $tag != '#text' ) {
553 $this->warn( "Unhandled log-item XML tag $tag" );
554 }
555 }
556
557 $this->processLogItem( $logInfo );
558 }
559
560 /**
561 * @param array $logInfo
562 * @return bool|mixed
563 */
564 private function processLogItem( $logInfo ) {
565 $revision = new WikiRevision;
566
567 $revision->setID( $logInfo['id'] );
568 $revision->setType( $logInfo['type'] );
569 $revision->setAction( $logInfo['action'] );
570 $revision->setTimestamp( $logInfo['timestamp'] );
571 $revision->setParams( $logInfo['params'] );
572 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
573 $revision->setNoUpdates( $this->mNoUpdates );
574
575 if ( isset( $logInfo['comment'] ) ) {
576 $revision->setComment( $logInfo['comment'] );
577 }
578
579 if ( isset( $logInfo['contributor']['ip'] ) ) {
580 $revision->setUserIP( $logInfo['contributor']['ip'] );
581 }
582 if ( isset( $logInfo['contributor']['username'] ) ) {
583 $revision->setUserName( $logInfo['contributor']['username'] );
584 }
585
586 return $this->logItemCallback( $revision );
587 }
588
589 private function handlePage() {
590 // Handle page data.
591 $this->debug( "Enter page handler." );
592 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
593
594 // Fields that can just be stuffed in the pageInfo object
595 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
596
597 $skip = false;
598 $badTitle = false;
599
600 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
601 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
602 $this->reader->name == 'page' ) {
603 break;
604 }
605
606 $tag = $this->reader->name;
607
608 if ( $badTitle ) {
609 // The title is invalid, bail out of this page
610 $skip = true;
611 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
612 &$pageInfo ) ) ) {
613 // Do nothing
614 } elseif ( in_array( $tag, $normalFields ) ) {
615 $pageInfo[$tag] = $this->nodeContents();
616 if ( $tag == 'title' ) {
617 $title = $this->processTitle( $pageInfo['title'] );
618
619 if ( !$title ) {
620 $badTitle = true;
621 $skip = true;
622 }
623
624 $this->pageCallback( $title );
625 list( $pageInfo['_title'], $origTitle ) = $title;
626 }
627 } elseif ( $tag == 'revision' ) {
628 $this->handleRevision( $pageInfo );
629 } elseif ( $tag == 'upload' ) {
630 $this->handleUpload( $pageInfo );
631 } elseif ( $tag != '#text' ) {
632 $this->warn( "Unhandled page XML tag $tag" );
633 $skip = true;
634 }
635 }
636
637 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
638 $pageInfo['revisionCount'],
639 $pageInfo['successfulRevisionCount'],
640 $pageInfo );
641 }
642
643 /**
644 * @param array $pageInfo
645 */
646 private function handleRevision( &$pageInfo ) {
647 $this->debug( "Enter revision handler" );
648 $revisionInfo = array();
649
650 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
651
652 $skip = false;
653
654 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
655 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
656 $this->reader->name == 'revision' ) {
657 break;
658 }
659
660 $tag = $this->reader->name;
661
662 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', array(
663 $this, $pageInfo, $revisionInfo
664 ) ) ) {
665 // Do nothing
666 } elseif ( in_array( $tag, $normalFields ) ) {
667 $revisionInfo[$tag] = $this->nodeContents();
668 } elseif ( $tag == 'contributor' ) {
669 $revisionInfo['contributor'] = $this->handleContributor();
670 } elseif ( $tag != '#text' ) {
671 $this->warn( "Unhandled revision XML tag $tag" );
672 $skip = true;
673 }
674 }
675
676 $pageInfo['revisionCount']++;
677 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
678 $pageInfo['successfulRevisionCount']++;
679 }
680 }
681
682 /**
683 * @param array $pageInfo
684 * @param array $revisionInfo
685 * @return bool|mixed
686 */
687 private function processRevision( $pageInfo, $revisionInfo ) {
688 $revision = new WikiRevision;
689
690 if ( isset( $revisionInfo['id'] ) ) {
691 $revision->setID( $revisionInfo['id'] );
692 }
693 if ( isset( $revisionInfo['text'] ) ) {
694 $revision->setText( $revisionInfo['text'] );
695 }
696 if ( isset( $revisionInfo['model'] ) ) {
697 $revision->setModel( $revisionInfo['model'] );
698 }
699 if ( isset( $revisionInfo['format'] ) ) {
700 $revision->setFormat( $revisionInfo['format'] );
701 }
702 $revision->setTitle( $pageInfo['_title'] );
703
704 if ( isset( $revisionInfo['timestamp'] ) ) {
705 $revision->setTimestamp( $revisionInfo['timestamp'] );
706 } else {
707 $revision->setTimestamp( wfTimestampNow() );
708 }
709
710 if ( isset( $revisionInfo['comment'] ) ) {
711 $revision->setComment( $revisionInfo['comment'] );
712 }
713
714 if ( isset( $revisionInfo['minor'] ) ) {
715 $revision->setMinor( true );
716 }
717 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
718 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
719 }
720 if ( isset( $revisionInfo['contributor']['username'] ) ) {
721 $revision->setUserName( $revisionInfo['contributor']['username'] );
722 }
723 $revision->setNoUpdates( $this->mNoUpdates );
724
725 return $this->revisionCallback( $revision );
726 }
727
728 /**
729 * @param array $pageInfo
730 * @return mixed
731 */
732 private function handleUpload( &$pageInfo ) {
733 $this->debug( "Enter upload handler" );
734 $uploadInfo = array();
735
736 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
737 'src', 'size', 'sha1base36', 'archivename', 'rel' );
738
739 $skip = false;
740
741 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
742 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
743 $this->reader->name == 'upload' ) {
744 break;
745 }
746
747 $tag = $this->reader->name;
748
749 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
750 $this, $pageInfo
751 ) ) ) {
752 // Do nothing
753 } elseif ( in_array( $tag, $normalFields ) ) {
754 $uploadInfo[$tag] = $this->nodeContents();
755 } elseif ( $tag == 'contributor' ) {
756 $uploadInfo['contributor'] = $this->handleContributor();
757 } elseif ( $tag == 'contents' ) {
758 $contents = $this->nodeContents();
759 $encoding = $this->reader->getAttribute( 'encoding' );
760 if ( $encoding === 'base64' ) {
761 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
762 $uploadInfo['isTempSrc'] = true;
763 }
764 } elseif ( $tag != '#text' ) {
765 $this->warn( "Unhandled upload XML tag $tag" );
766 $skip = true;
767 }
768 }
769
770 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
771 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
772 if ( file_exists( $path ) ) {
773 $uploadInfo['fileSrc'] = $path;
774 $uploadInfo['isTempSrc'] = false;
775 }
776 }
777
778 if ( $this->mImportUploads ) {
779 return $this->processUpload( $pageInfo, $uploadInfo );
780 }
781 }
782
783 /**
784 * @param string $contents
785 * @return string
786 */
787 private function dumpTemp( $contents ) {
788 $filename = tempnam( wfTempDir(), 'importupload' );
789 file_put_contents( $filename, $contents );
790 return $filename;
791 }
792
793 /**
794 * @param array $pageInfo
795 * @param array $uploadInfo
796 * @return mixed
797 */
798 private function processUpload( $pageInfo, $uploadInfo ) {
799 $revision = new WikiRevision;
800 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
801
802 $revision->setTitle( $pageInfo['_title'] );
803 $revision->setID( $pageInfo['id'] );
804 $revision->setTimestamp( $uploadInfo['timestamp'] );
805 $revision->setText( $text );
806 $revision->setFilename( $uploadInfo['filename'] );
807 if ( isset( $uploadInfo['archivename'] ) ) {
808 $revision->setArchiveName( $uploadInfo['archivename'] );
809 }
810 $revision->setSrc( $uploadInfo['src'] );
811 if ( isset( $uploadInfo['fileSrc'] ) ) {
812 $revision->setFileSrc( $uploadInfo['fileSrc'],
813 !empty( $uploadInfo['isTempSrc'] ) );
814 }
815 if ( isset( $uploadInfo['sha1base36'] ) ) {
816 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
817 }
818 $revision->setSize( intval( $uploadInfo['size'] ) );
819 $revision->setComment( $uploadInfo['comment'] );
820
821 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
822 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
823 }
824 if ( isset( $uploadInfo['contributor']['username'] ) ) {
825 $revision->setUserName( $uploadInfo['contributor']['username'] );
826 }
827 $revision->setNoUpdates( $this->mNoUpdates );
828
829 return call_user_func( $this->mUploadCallback, $revision );
830 }
831
832 /**
833 * @return array
834 */
835 private function handleContributor() {
836 $fields = array( 'id', 'ip', 'username' );
837 $info = array();
838
839 while ( $this->reader->read() ) {
840 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
841 $this->reader->name == 'contributor' ) {
842 break;
843 }
844
845 $tag = $this->reader->name;
846
847 if ( in_array( $tag, $fields ) ) {
848 $info[$tag] = $this->nodeContents();
849 }
850 }
851
852 return $info;
853 }
854
855 /**
856 * @param string $text
857 * @return array|bool
858 */
859 private function processTitle( $text ) {
860 global $wgCommandLineMode;
861
862 $workTitle = $text;
863 $origTitle = Title::newFromText( $workTitle );
864
865 if ( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
866 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
867 # and than dbKey can begin with a lowercase char
868 $title = Title::makeTitleSafe( $this->mTargetNamespace,
869 $origTitle->getDBkey() );
870 } else {
871 if ( !is_null( $this->mTargetRootPage ) ) {
872 $workTitle = $this->mTargetRootPage . '/' . $workTitle;
873 }
874 $title = Title::newFromText( $workTitle );
875 }
876
877 if ( is_null( $title ) ) {
878 # Invalid page title? Ignore the page
879 $this->notice( 'import-error-invalid', $workTitle );
880 return false;
881 } elseif ( $title->isExternal() ) {
882 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
883 return false;
884 } elseif ( !$title->canExist() ) {
885 $this->notice( 'import-error-special', $title->getPrefixedText() );
886 return false;
887 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
888 # Do not import if the importing wiki user cannot edit this page
889 $this->notice( 'import-error-edit', $title->getPrefixedText() );
890 return false;
891 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
892 # Do not import if the importing wiki user cannot create this page
893 $this->notice( 'import-error-create', $title->getPrefixedText() );
894 return false;
895 }
896
897 return array( $title, $origTitle );
898 }
899 }
900
901 /** This is a horrible hack used to keep source compatibility */
902 class UploadSourceAdapter {
903 static $sourceRegistrations = array();
904
905 private $mSource;
906 private $mBuffer;
907 private $mPosition;
908
909 /**
910 * @param string $source
911 * @return string
912 */
913 static function registerSource( $source ) {
914 $id = wfRandomString();
915
916 self::$sourceRegistrations[$id] = $source;
917
918 return $id;
919 }
920
921 /**
922 * @param string $path
923 * @param string $mode
924 * @param array $options
925 * @param string $opened_path
926 * @return bool
927 */
928 function stream_open( $path, $mode, $options, &$opened_path ) {
929 $url = parse_url( $path );
930 $id = $url['host'];
931
932 if ( !isset( self::$sourceRegistrations[$id] ) ) {
933 return false;
934 }
935
936 $this->mSource = self::$sourceRegistrations[$id];
937
938 return true;
939 }
940
941 /**
942 * @param int $count
943 * @return string
944 */
945 function stream_read( $count ) {
946 $return = '';
947 $leave = false;
948
949 while ( !$leave && !$this->mSource->atEnd() &&
950 strlen( $this->mBuffer ) < $count ) {
951 $read = $this->mSource->readChunk();
952
953 if ( !strlen( $read ) ) {
954 $leave = true;
955 }
956
957 $this->mBuffer .= $read;
958 }
959
960 if ( strlen( $this->mBuffer ) ) {
961 $return = substr( $this->mBuffer, 0, $count );
962 $this->mBuffer = substr( $this->mBuffer, $count );
963 }
964
965 $this->mPosition += strlen( $return );
966
967 return $return;
968 }
969
970 /**
971 * @param string $data
972 * @return bool
973 */
974 function stream_write( $data ) {
975 return false;
976 }
977
978 /**
979 * @return mixed
980 */
981 function stream_tell() {
982 return $this->mPosition;
983 }
984
985 /**
986 * @return bool
987 */
988 function stream_eof() {
989 return $this->mSource->atEnd();
990 }
991
992 /**
993 * @return array
994 */
995 function url_stat() {
996 $result = array();
997
998 $result['dev'] = $result[0] = 0;
999 $result['ino'] = $result[1] = 0;
1000 $result['mode'] = $result[2] = 0;
1001 $result['nlink'] = $result[3] = 0;
1002 $result['uid'] = $result[4] = 0;
1003 $result['gid'] = $result[5] = 0;
1004 $result['rdev'] = $result[6] = 0;
1005 $result['size'] = $result[7] = 0;
1006 $result['atime'] = $result[8] = 0;
1007 $result['mtime'] = $result[9] = 0;
1008 $result['ctime'] = $result[10] = 0;
1009 $result['blksize'] = $result[11] = 0;
1010 $result['blocks'] = $result[12] = 0;
1011
1012 return $result;
1013 }
1014 }
1015
1016 class XMLReader2 extends XMLReader {
1017
1018 /**
1019 * @return bool|string
1020 */
1021 function nodeContents() {
1022 if ( $this->isEmptyElement ) {
1023 return "";
1024 }
1025 $buffer = "";
1026 while ( $this->read() ) {
1027 switch ( $this->nodeType ) {
1028 case XmlReader::TEXT:
1029 case XmlReader::SIGNIFICANT_WHITESPACE:
1030 $buffer .= $this->value;
1031 break;
1032 case XmlReader::END_ELEMENT:
1033 return $buffer;
1034 }
1035 }
1036 return $this->close();
1037 }
1038 }
1039
1040 /**
1041 * @todo document (e.g. one-sentence class description).
1042 * @ingroup SpecialPage
1043 */
1044 class WikiRevision {
1045 var $importer = null;
1046
1047 /**
1048 * @var Title
1049 */
1050 var $title = null;
1051 var $id = 0;
1052 var $timestamp = "20010115000000";
1053 var $user = 0;
1054 var $user_text = "";
1055 var $model = null;
1056 var $format = null;
1057 var $text = "";
1058 var $content = null;
1059 var $comment = "";
1060 var $minor = false;
1061 var $type = "";
1062 var $action = "";
1063 var $params = "";
1064 var $fileSrc = '';
1065 var $sha1base36 = false;
1066 var $isTemp = false;
1067 var $archiveName = '';
1068 var $fileIsTemp;
1069 private $mNoUpdates = false;
1070
1071 /**
1072 * @param Title $title
1073 * @throws MWException
1074 */
1075 function setTitle( $title ) {
1076 if ( is_object( $title ) ) {
1077 $this->title = $title;
1078 } elseif ( is_null( $title ) ) {
1079 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
1080 } else {
1081 throw new MWException( "WikiRevision given non-object title in import." );
1082 }
1083 }
1084
1085 /**
1086 * @param int $id
1087 */
1088 function setID( $id ) {
1089 $this->id = $id;
1090 }
1091
1092 /**
1093 * @param string $ts
1094 */
1095 function setTimestamp( $ts ) {
1096 # 2003-08-05T18:30:02Z
1097 $this->timestamp = wfTimestamp( TS_MW, $ts );
1098 }
1099
1100 /**
1101 * @param string $user
1102 */
1103 function setUsername( $user ) {
1104 $this->user_text = $user;
1105 }
1106
1107 /**
1108 * @param string $ip
1109 */
1110 function setUserIP( $ip ) {
1111 $this->user_text = $ip;
1112 }
1113
1114 /**
1115 * @param string $model
1116 */
1117 function setModel( $model ) {
1118 $this->model = $model;
1119 }
1120
1121 /**
1122 * @param string $format
1123 */
1124 function setFormat( $format ) {
1125 $this->format = $format;
1126 }
1127
1128 /**
1129 * @param string $text
1130 */
1131 function setText( $text ) {
1132 $this->text = $text;
1133 }
1134
1135 /**
1136 * @param string $text
1137 */
1138 function setComment( $text ) {
1139 $this->comment = $text;
1140 }
1141
1142 /**
1143 * @param bool $minor
1144 */
1145 function setMinor( $minor ) {
1146 $this->minor = (bool)$minor;
1147 }
1148
1149 /**
1150 * @param mixed $src
1151 */
1152 function setSrc( $src ) {
1153 $this->src = $src;
1154 }
1155
1156 /**
1157 * @param string $src
1158 * @param bool $isTemp
1159 */
1160 function setFileSrc( $src, $isTemp ) {
1161 $this->fileSrc = $src;
1162 $this->fileIsTemp = $isTemp;
1163 }
1164
1165 /**
1166 * @param string $sha1base36
1167 */
1168 function setSha1Base36( $sha1base36 ) {
1169 $this->sha1base36 = $sha1base36;
1170 }
1171
1172 /**
1173 * @param string $filename
1174 */
1175 function setFilename( $filename ) {
1176 $this->filename = $filename;
1177 }
1178
1179 /**
1180 * @param string $archiveName
1181 */
1182 function setArchiveName( $archiveName ) {
1183 $this->archiveName = $archiveName;
1184 }
1185
1186 /**
1187 * @param int $size
1188 */
1189 function setSize( $size ) {
1190 $this->size = intval( $size );
1191 }
1192
1193 /**
1194 * @param string $type
1195 */
1196 function setType( $type ) {
1197 $this->type = $type;
1198 }
1199
1200 /**
1201 * @param string $action
1202 */
1203 function setAction( $action ) {
1204 $this->action = $action;
1205 }
1206
1207 /**
1208 * @param array $params
1209 */
1210 function setParams( $params ) {
1211 $this->params = $params;
1212 }
1213
1214 /**
1215 * @param bool $noupdates
1216 */
1217 public function setNoUpdates( $noupdates ) {
1218 $this->mNoUpdates = $noupdates;
1219 }
1220
1221 /**
1222 * @return Title
1223 */
1224 function getTitle() {
1225 return $this->title;
1226 }
1227
1228 /**
1229 * @return int
1230 */
1231 function getID() {
1232 return $this->id;
1233 }
1234
1235 /**
1236 * @return string
1237 */
1238 function getTimestamp() {
1239 return $this->timestamp;
1240 }
1241
1242 /**
1243 * @return string
1244 */
1245 function getUser() {
1246 return $this->user_text;
1247 }
1248
1249 /**
1250 * @return string
1251 *
1252 * @deprecated Since 1.21, use getContent() instead.
1253 */
1254 function getText() {
1255 ContentHandler::deprecated( __METHOD__, '1.21' );
1256
1257 return $this->text;
1258 }
1259
1260 /**
1261 * @return Content
1262 */
1263 function getContent() {
1264 if ( is_null( $this->content ) ) {
1265 $this->content =
1266 ContentHandler::makeContent(
1267 $this->text,
1268 $this->getTitle(),
1269 $this->getModel(),
1270 $this->getFormat()
1271 );
1272 }
1273
1274 return $this->content;
1275 }
1276
1277 /**
1278 * @return string
1279 */
1280 function getModel() {
1281 if ( is_null( $this->model ) ) {
1282 $this->model = $this->getTitle()->getContentModel();
1283 }
1284
1285 return $this->model;
1286 }
1287
1288 /**
1289 * @return string
1290 */
1291 function getFormat() {
1292 if ( is_null( $this->model ) ) {
1293 $this->format = ContentHandler::getForTitle( $this->getTitle() )->getDefaultFormat();
1294 }
1295
1296 return $this->format;
1297 }
1298
1299 /**
1300 * @return string
1301 */
1302 function getComment() {
1303 return $this->comment;
1304 }
1305
1306 /**
1307 * @return bool
1308 */
1309 function getMinor() {
1310 return $this->minor;
1311 }
1312
1313 /**
1314 * @return mixed
1315 */
1316 function getSrc() {
1317 return $this->src;
1318 }
1319
1320 /**
1321 * @return bool|string
1322 */
1323 function getSha1() {
1324 if ( $this->sha1base36 ) {
1325 return wfBaseConvert( $this->sha1base36, 36, 16 );
1326 }
1327 return false;
1328 }
1329
1330 /**
1331 * @return string
1332 */
1333 function getFileSrc() {
1334 return $this->fileSrc;
1335 }
1336
1337 /**
1338 * @return bool
1339 */
1340 function isTempSrc() {
1341 return $this->isTemp;
1342 }
1343
1344 /**
1345 * @return mixed
1346 */
1347 function getFilename() {
1348 return $this->filename;
1349 }
1350
1351 /**
1352 * @return string
1353 */
1354 function getArchiveName() {
1355 return $this->archiveName;
1356 }
1357
1358 /**
1359 * @return mixed
1360 */
1361 function getSize() {
1362 return $this->size;
1363 }
1364
1365 /**
1366 * @return string
1367 */
1368 function getType() {
1369 return $this->type;
1370 }
1371
1372 /**
1373 * @return string
1374 */
1375 function getAction() {
1376 return $this->action;
1377 }
1378
1379 /**
1380 * @return string
1381 */
1382 function getParams() {
1383 return $this->params;
1384 }
1385
1386 /**
1387 * @return bool
1388 */
1389 function importOldRevision() {
1390 $dbw = wfGetDB( DB_MASTER );
1391
1392 # Sneak a single revision into place
1393 $user = User::newFromName( $this->getUser() );
1394 if ( $user ) {
1395 $userId = intval( $user->getId() );
1396 $userText = $user->getName();
1397 $userObj = $user;
1398 } else {
1399 $userId = 0;
1400 $userText = $this->getUser();
1401 $userObj = new User;
1402 }
1403
1404 // avoid memory leak...?
1405 $linkCache = LinkCache::singleton();
1406 $linkCache->clear();
1407
1408 $page = WikiPage::factory( $this->title );
1409 if ( !$page->exists() ) {
1410 # must create the page...
1411 $pageId = $page->insertOn( $dbw );
1412 $created = true;
1413 $oldcountable = null;
1414 } else {
1415 $pageId = $page->getId();
1416 $created = false;
1417
1418 $prior = $dbw->selectField( 'revision', '1',
1419 array( 'rev_page' => $pageId,
1420 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1421 'rev_user_text' => $userText,
1422 'rev_comment' => $this->getComment() ),
1423 __METHOD__
1424 );
1425 if ( $prior ) {
1426 // @todo FIXME: This could fail slightly for multiple matches :P
1427 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1428 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1429 return false;
1430 }
1431 $oldcountable = $page->isCountable();
1432 }
1433
1434 # @todo FIXME: Use original rev_id optionally (better for backups)
1435 # Insert the row
1436 $revision = new Revision( array(
1437 'title' => $this->title,
1438 'page' => $pageId,
1439 'content_model' => $this->getModel(),
1440 'content_format' => $this->getFormat(),
1441 'text' => $this->getContent()->serialize( $this->getFormat() ), //XXX: just set 'content' => $this->getContent()?
1442 'comment' => $this->getComment(),
1443 'user' => $userId,
1444 'user_text' => $userText,
1445 'timestamp' => $this->timestamp,
1446 'minor_edit' => $this->minor,
1447 ) );
1448 $revision->insertOn( $dbw );
1449 $changed = $page->updateIfNewerOn( $dbw, $revision );
1450
1451 if ( $changed !== false && !$this->mNoUpdates ) {
1452 wfDebug( __METHOD__ . ": running updates\n" );
1453 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1454 }
1455
1456 return true;
1457 }
1458
1459 /**
1460 * @return mixed
1461 */
1462 function importLogItem() {
1463 $dbw = wfGetDB( DB_MASTER );
1464 # @todo FIXME: This will not record autoblocks
1465 if ( !$this->getTitle() ) {
1466 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1467 $this->timestamp . "\n" );
1468 return;
1469 }
1470 # Check if it exists already
1471 // @todo FIXME: Use original log ID (better for backups)
1472 $prior = $dbw->selectField( 'logging', '1',
1473 array( 'log_type' => $this->getType(),
1474 'log_action' => $this->getAction(),
1475 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1476 'log_namespace' => $this->getTitle()->getNamespace(),
1477 'log_title' => $this->getTitle()->getDBkey(),
1478 'log_comment' => $this->getComment(),
1479 #'log_user_text' => $this->user_text,
1480 'log_params' => $this->params ),
1481 __METHOD__
1482 );
1483 // @todo FIXME: This could fail slightly for multiple matches :P
1484 if ( $prior ) {
1485 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1486 $this->timestamp . "\n" );
1487 return;
1488 }
1489 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1490 $data = array(
1491 'log_id' => $log_id,
1492 'log_type' => $this->type,
1493 'log_action' => $this->action,
1494 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1495 'log_user' => User::idFromName( $this->user_text ),
1496 #'log_user_text' => $this->user_text,
1497 'log_namespace' => $this->getTitle()->getNamespace(),
1498 'log_title' => $this->getTitle()->getDBkey(),
1499 'log_comment' => $this->getComment(),
1500 'log_params' => $this->params
1501 );
1502 $dbw->insert( 'logging', $data, __METHOD__ );
1503 }
1504
1505 /**
1506 * @return bool
1507 */
1508 function importUpload() {
1509 # Construct a file
1510 $archiveName = $this->getArchiveName();
1511 if ( $archiveName ) {
1512 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1513 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1514 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1515 } else {
1516 $file = wfLocalFile( $this->getTitle() );
1517 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1518 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1519 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1520 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1521 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1522 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1523 }
1524 }
1525 if ( !$file ) {
1526 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1527 return false;
1528 }
1529
1530 # Get the file source or download if necessary
1531 $source = $this->getFileSrc();
1532 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1533 if ( !$source ) {
1534 $source = $this->downloadSource();
1535 $flags |= File::DELETE_SOURCE;
1536 }
1537 if ( !$source ) {
1538 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1539 return false;
1540 }
1541 $sha1 = $this->getSha1();
1542 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1543 if ( $flags & File::DELETE_SOURCE ) {
1544 # Broken file; delete it if it is a temporary file
1545 unlink( $source );
1546 }
1547 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1548 return false;
1549 }
1550
1551 $user = User::newFromName( $this->user_text );
1552
1553 # Do the actual upload
1554 if ( $archiveName ) {
1555 $status = $file->uploadOld( $source, $archiveName,
1556 $this->getTimestamp(), $this->getComment(), $user, $flags );
1557 } else {
1558 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1559 $flags, false, $this->getTimestamp(), $user );
1560 }
1561
1562 if ( $status->isGood() ) {
1563 wfDebug( __METHOD__ . ": Successful\n" );
1564 return true;
1565 } else {
1566 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1567 return false;
1568 }
1569 }
1570
1571 /**
1572 * @return bool|string
1573 */
1574 function downloadSource() {
1575 global $wgEnableUploads;
1576 if ( !$wgEnableUploads ) {
1577 return false;
1578 }
1579
1580 $tempo = tempnam( wfTempDir(), 'download' );
1581 $f = fopen( $tempo, 'wb' );
1582 if ( !$f ) {
1583 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1584 return false;
1585 }
1586
1587 // @todo FIXME!
1588 $src = $this->getSrc();
1589 $data = Http::get( $src );
1590 if ( !$data ) {
1591 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1592 fclose( $f );
1593 unlink( $tempo );
1594 return false;
1595 }
1596
1597 fwrite( $f, $data );
1598 fclose( $f );
1599
1600 return $tempo;
1601 }
1602
1603 }
1604
1605 /**
1606 * @todo document (e.g. one-sentence class description).
1607 * @ingroup SpecialPage
1608 */
1609 class ImportStringSource {
1610 function __construct( $string ) {
1611 $this->mString = $string;
1612 $this->mRead = false;
1613 }
1614
1615 /**
1616 * @return bool
1617 */
1618 function atEnd() {
1619 return $this->mRead;
1620 }
1621
1622 /**
1623 * @return bool|string
1624 */
1625 function readChunk() {
1626 if ( $this->atEnd() ) {
1627 return false;
1628 }
1629 $this->mRead = true;
1630 return $this->mString;
1631 }
1632 }
1633
1634 /**
1635 * @todo document (e.g. one-sentence class description).
1636 * @ingroup SpecialPage
1637 */
1638 class ImportStreamSource {
1639 function __construct( $handle ) {
1640 $this->mHandle = $handle;
1641 }
1642
1643 /**
1644 * @return bool
1645 */
1646 function atEnd() {
1647 return feof( $this->mHandle );
1648 }
1649
1650 /**
1651 * @return string
1652 */
1653 function readChunk() {
1654 return fread( $this->mHandle, 32768 );
1655 }
1656
1657 /**
1658 * @param string $filename
1659 * @return Status
1660 */
1661 static function newFromFile( $filename ) {
1662 wfSuppressWarnings();
1663 $file = fopen( $filename, 'rt' );
1664 wfRestoreWarnings();
1665 if ( !$file ) {
1666 return Status::newFatal( "importcantopen" );
1667 }
1668 return Status::newGood( new ImportStreamSource( $file ) );
1669 }
1670
1671 /**
1672 * @param string $fieldname
1673 * @return Status
1674 */
1675 static function newFromUpload( $fieldname = "xmlimport" ) {
1676 $upload =& $_FILES[$fieldname];
1677
1678 if ( $upload === null || !$upload['name'] ) {
1679 return Status::newFatal( 'importnofile' );
1680 }
1681 if ( !empty( $upload['error'] ) ) {
1682 switch ( $upload['error'] ) {
1683 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1684 return Status::newFatal( 'importuploaderrorsize' );
1685 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1686 return Status::newFatal( 'importuploaderrorsize' );
1687 case 3: # The uploaded file was only partially uploaded
1688 return Status::newFatal( 'importuploaderrorpartial' );
1689 case 6: #Missing a temporary folder.
1690 return Status::newFatal( 'importuploaderrortemp' );
1691 # case else: # Currently impossible
1692 }
1693
1694 }
1695 $fname = $upload['tmp_name'];
1696 if ( is_uploaded_file( $fname ) ) {
1697 return ImportStreamSource::newFromFile( $fname );
1698 } else {
1699 return Status::newFatal( 'importnofile' );
1700 }
1701 }
1702
1703 /**
1704 * @param string $url
1705 * @param string $method
1706 * @return Status
1707 */
1708 static function newFromURL( $url, $method = 'GET' ) {
1709 wfDebug( __METHOD__ . ": opening $url\n" );
1710 # Use the standard HTTP fetch function; it times out
1711 # quicker and sorts out user-agent problems which might
1712 # otherwise prevent importing from large sites, such
1713 # as the Wikimedia cluster, etc.
1714 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1715 if ( $data !== false ) {
1716 $file = tmpfile();
1717 fwrite( $file, $data );
1718 fflush( $file );
1719 fseek( $file, 0 );
1720 return Status::newGood( new ImportStreamSource( $file ) );
1721 } else {
1722 return Status::newFatal( 'importcantopen' );
1723 }
1724 }
1725
1726 /**
1727 * @param string $interwiki
1728 * @param string $page
1729 * @param bool $history
1730 * @param bool $templates
1731 * @param int $pageLinkDepth
1732 * @return Status
1733 */
1734 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1735 if ( $page == '' ) {
1736 return Status::newFatal( 'import-noarticle' );
1737 }
1738 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1739 if ( is_null( $link ) || !$link->isExternal() ) {
1740 return Status::newFatal( 'importbadinterwiki' );
1741 } else {
1742 $params = array();
1743 if ( $history ) {
1744 $params['history'] = 1;
1745 }
1746 if ( $templates ) {
1747 $params['templates'] = 1;
1748 }
1749 if ( $pageLinkDepth ) {
1750 $params['pagelink-depth'] = $pageLinkDepth;
1751 }
1752 $url = $link->getFullURL( $params );
1753 # For interwikis, use POST to avoid redirects.
1754 return ImportStreamSource::newFromURL( $url, "POST" );
1755 }
1756 }
1757 }