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