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