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