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