Merge "merging latest master" into Wikidata
[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 $comment = "";
1021 var $minor = false;
1022 var $type = "";
1023 var $action = "";
1024 var $params = "";
1025 var $fileSrc = '';
1026 var $sha1base36 = false;
1027 var $isTemp = false;
1028 var $archiveName = '';
1029 var $fileIsTemp;
1030 private $mNoUpdates = false;
1031
1032 /**
1033 * @param $title
1034 * @throws MWException
1035 */
1036 function setTitle( $title ) {
1037 if( is_object( $title ) ) {
1038 $this->title = $title;
1039 } elseif( is_null( $title ) ) {
1040 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
1041 } else {
1042 throw new MWException( "WikiRevision given non-object title in import." );
1043 }
1044 }
1045
1046 /**
1047 * @param $id
1048 */
1049 function setID( $id ) {
1050 $this->id = $id;
1051 }
1052
1053 /**
1054 * @param $ts
1055 */
1056 function setTimestamp( $ts ) {
1057 # 2003-08-05T18:30:02Z
1058 $this->timestamp = wfTimestamp( TS_MW, $ts );
1059 }
1060
1061 /**
1062 * @param $user
1063 */
1064 function setUsername( $user ) {
1065 $this->user_text = $user;
1066 }
1067
1068 /**
1069 * @param $ip
1070 */
1071 function setUserIP( $ip ) {
1072 $this->user_text = $ip;
1073 }
1074
1075 /**
1076 * @param $model
1077 */
1078 function setModel( $model ) {
1079 $this->model = $model;
1080 }
1081
1082 /**
1083 * @param $format
1084 */
1085 function setFormat( $format ) {
1086 $this->format = $format;
1087 }
1088
1089 /**
1090 * @param $text
1091 */
1092 function setText( $text ) {
1093 $this->text = $text;
1094 }
1095
1096 /**
1097 * @param $text
1098 */
1099 function setComment( $text ) {
1100 $this->comment = $text;
1101 }
1102
1103 /**
1104 * @param $minor
1105 */
1106 function setMinor( $minor ) {
1107 $this->minor = (bool)$minor;
1108 }
1109
1110 /**
1111 * @param $src
1112 */
1113 function setSrc( $src ) {
1114 $this->src = $src;
1115 }
1116
1117 /**
1118 * @param $src
1119 * @param $isTemp
1120 */
1121 function setFileSrc( $src, $isTemp ) {
1122 $this->fileSrc = $src;
1123 $this->fileIsTemp = $isTemp;
1124 }
1125
1126 /**
1127 * @param $sha1base36
1128 */
1129 function setSha1Base36( $sha1base36 ) {
1130 $this->sha1base36 = $sha1base36;
1131 }
1132
1133 /**
1134 * @param $filename
1135 */
1136 function setFilename( $filename ) {
1137 $this->filename = $filename;
1138 }
1139
1140 /**
1141 * @param $archiveName
1142 */
1143 function setArchiveName( $archiveName ) {
1144 $this->archiveName = $archiveName;
1145 }
1146
1147 /**
1148 * @param $size
1149 */
1150 function setSize( $size ) {
1151 $this->size = intval( $size );
1152 }
1153
1154 /**
1155 * @param $type
1156 */
1157 function setType( $type ) {
1158 $this->type = $type;
1159 }
1160
1161 /**
1162 * @param $action
1163 */
1164 function setAction( $action ) {
1165 $this->action = $action;
1166 }
1167
1168 /**
1169 * @param $params
1170 */
1171 function setParams( $params ) {
1172 $this->params = $params;
1173 }
1174
1175 /**
1176 * @param $noupdates
1177 */
1178 public function setNoUpdates( $noupdates ) {
1179 $this->mNoUpdates = $noupdates;
1180 }
1181
1182 /**
1183 * @return Title
1184 */
1185 function getTitle() {
1186 return $this->title;
1187 }
1188
1189 /**
1190 * @return int
1191 */
1192 function getID() {
1193 return $this->id;
1194 }
1195
1196 /**
1197 * @return string
1198 */
1199 function getTimestamp() {
1200 return $this->timestamp;
1201 }
1202
1203 /**
1204 * @return string
1205 */
1206 function getUser() {
1207 return $this->user_text;
1208 }
1209
1210 /**
1211 * @return string
1212 */
1213 function getText() {
1214 return $this->text;
1215 }
1216
1217 /**
1218 * @return String
1219 */
1220 function getModel() {
1221 if ( is_null( $this->model ) ) {
1222 $this->model = $this->getTitle()->getContentModel();
1223 }
1224
1225 return $this->model;
1226 }
1227
1228 /**
1229 * @return String
1230 */
1231 function getFormat() {
1232 if ( is_null( $this->model ) ) {
1233 $this->format = ContentHandler::getForTitle( $this->getTitle() )->getDefaultFormat();
1234 }
1235
1236 return $this->format;
1237 }
1238
1239 /**
1240 * @return string
1241 */
1242 function getComment() {
1243 return $this->comment;
1244 }
1245
1246 /**
1247 * @return bool
1248 */
1249 function getMinor() {
1250 return $this->minor;
1251 }
1252
1253 /**
1254 * @return mixed
1255 */
1256 function getSrc() {
1257 return $this->src;
1258 }
1259
1260 /**
1261 * @return bool|String
1262 */
1263 function getSha1() {
1264 if ( $this->sha1base36 ) {
1265 return wfBaseConvert( $this->sha1base36, 36, 16 );
1266 }
1267 return false;
1268 }
1269
1270 /**
1271 * @return string
1272 */
1273 function getFileSrc() {
1274 return $this->fileSrc;
1275 }
1276
1277 /**
1278 * @return bool
1279 */
1280 function isTempSrc() {
1281 return $this->isTemp;
1282 }
1283
1284 /**
1285 * @return mixed
1286 */
1287 function getFilename() {
1288 return $this->filename;
1289 }
1290
1291 /**
1292 * @return string
1293 */
1294 function getArchiveName() {
1295 return $this->archiveName;
1296 }
1297
1298 /**
1299 * @return mixed
1300 */
1301 function getSize() {
1302 return $this->size;
1303 }
1304
1305 /**
1306 * @return string
1307 */
1308 function getType() {
1309 return $this->type;
1310 }
1311
1312 /**
1313 * @return string
1314 */
1315 function getAction() {
1316 return $this->action;
1317 }
1318
1319 /**
1320 * @return string
1321 */
1322 function getParams() {
1323 return $this->params;
1324 }
1325
1326 /**
1327 * @return bool
1328 */
1329 function importOldRevision() {
1330 $dbw = wfGetDB( DB_MASTER );
1331
1332 # Sneak a single revision into place
1333 $user = User::newFromName( $this->getUser() );
1334 if( $user ) {
1335 $userId = intval( $user->getId() );
1336 $userText = $user->getName();
1337 $userObj = $user;
1338 } else {
1339 $userId = 0;
1340 $userText = $this->getUser();
1341 $userObj = new User;
1342 }
1343
1344 // avoid memory leak...?
1345 $linkCache = LinkCache::singleton();
1346 $linkCache->clear();
1347
1348 $page = WikiPage::factory( $this->title );
1349 if( !$page->exists() ) {
1350 # must create the page...
1351 $pageId = $page->insertOn( $dbw );
1352 $created = true;
1353 $oldcountable = null;
1354 } else {
1355 $pageId = $page->getId();
1356 $created = false;
1357
1358 $prior = $dbw->selectField( 'revision', '1',
1359 array( 'rev_page' => $pageId,
1360 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1361 'rev_user_text' => $userText,
1362 'rev_comment' => $this->getComment() ),
1363 __METHOD__
1364 );
1365 if( $prior ) {
1366 // @todo FIXME: This could fail slightly for multiple matches :P
1367 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1368 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1369 return false;
1370 }
1371 $oldcountable = $page->isCountable();
1372 }
1373
1374 # @todo FIXME: Use original rev_id optionally (better for backups)
1375 # Insert the row
1376 $revision = new Revision( array(
1377 'page' => $pageId,
1378 'content_model' => $this->getModel(),
1379 'content_format' => $this->getFormat(),
1380 'text' => $this->getText(),
1381 'comment' => $this->getComment(),
1382 'user' => $userId,
1383 'user_text' => $userText,
1384 'timestamp' => $this->timestamp,
1385 'minor_edit' => $this->minor,
1386 ) );
1387 $revision->insertOn( $dbw );
1388 $changed = $page->updateIfNewerOn( $dbw, $revision );
1389
1390 if ( $changed !== false && !$this->mNoUpdates ) {
1391 wfDebug( __METHOD__ . ": running updates\n" );
1392 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1393 }
1394
1395 return true;
1396 }
1397
1398 /**
1399 * @return mixed
1400 */
1401 function importLogItem() {
1402 $dbw = wfGetDB( DB_MASTER );
1403 # @todo FIXME: This will not record autoblocks
1404 if( !$this->getTitle() ) {
1405 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1406 $this->timestamp . "\n" );
1407 return;
1408 }
1409 # Check if it exists already
1410 // @todo FIXME: Use original log ID (better for backups)
1411 $prior = $dbw->selectField( 'logging', '1',
1412 array( 'log_type' => $this->getType(),
1413 'log_action' => $this->getAction(),
1414 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1415 'log_namespace' => $this->getTitle()->getNamespace(),
1416 'log_title' => $this->getTitle()->getDBkey(),
1417 'log_comment' => $this->getComment(),
1418 #'log_user_text' => $this->user_text,
1419 'log_params' => $this->params ),
1420 __METHOD__
1421 );
1422 // @todo FIXME: This could fail slightly for multiple matches :P
1423 if( $prior ) {
1424 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1425 $this->timestamp . "\n" );
1426 return;
1427 }
1428 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1429 $data = array(
1430 'log_id' => $log_id,
1431 'log_type' => $this->type,
1432 'log_action' => $this->action,
1433 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1434 'log_user' => User::idFromName( $this->user_text ),
1435 #'log_user_text' => $this->user_text,
1436 'log_namespace' => $this->getTitle()->getNamespace(),
1437 'log_title' => $this->getTitle()->getDBkey(),
1438 'log_comment' => $this->getComment(),
1439 'log_params' => $this->params
1440 );
1441 $dbw->insert( 'logging', $data, __METHOD__ );
1442 }
1443
1444 /**
1445 * @return bool
1446 */
1447 function importUpload() {
1448 # Construct a file
1449 $archiveName = $this->getArchiveName();
1450 if ( $archiveName ) {
1451 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1452 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1453 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1454 } else {
1455 $file = wfLocalFile( $this->getTitle() );
1456 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1457 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1458 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1459 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1460 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1461 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1462 }
1463 }
1464 if( !$file ) {
1465 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1466 return false;
1467 }
1468
1469 # Get the file source or download if necessary
1470 $source = $this->getFileSrc();
1471 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1472 if ( !$source ) {
1473 $source = $this->downloadSource();
1474 $flags |= File::DELETE_SOURCE;
1475 }
1476 if( !$source ) {
1477 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1478 return false;
1479 }
1480 $sha1 = $this->getSha1();
1481 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1482 if ( $flags & File::DELETE_SOURCE ) {
1483 # Broken file; delete it if it is a temporary file
1484 unlink( $source );
1485 }
1486 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1487 return false;
1488 }
1489
1490 $user = User::newFromName( $this->user_text );
1491
1492 # Do the actual upload
1493 if ( $archiveName ) {
1494 $status = $file->uploadOld( $source, $archiveName,
1495 $this->getTimestamp(), $this->getComment(), $user, $flags );
1496 } else {
1497 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1498 $flags, false, $this->getTimestamp(), $user );
1499 }
1500
1501 if ( $status->isGood() ) {
1502 wfDebug( __METHOD__ . ": Succesful\n" );
1503 return true;
1504 } else {
1505 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1506 return false;
1507 }
1508 }
1509
1510 /**
1511 * @return bool|string
1512 */
1513 function downloadSource() {
1514 global $wgEnableUploads;
1515 if( !$wgEnableUploads ) {
1516 return false;
1517 }
1518
1519 $tempo = tempnam( wfTempDir(), 'download' );
1520 $f = fopen( $tempo, 'wb' );
1521 if( !$f ) {
1522 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1523 return false;
1524 }
1525
1526 // @todo FIXME!
1527 $src = $this->getSrc();
1528 $data = Http::get( $src );
1529 if( !$data ) {
1530 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1531 fclose( $f );
1532 unlink( $tempo );
1533 return false;
1534 }
1535
1536 fwrite( $f, $data );
1537 fclose( $f );
1538
1539 return $tempo;
1540 }
1541
1542 }
1543
1544 /**
1545 * @todo document (e.g. one-sentence class description).
1546 * @ingroup SpecialPage
1547 */
1548 class ImportStringSource {
1549 function __construct( $string ) {
1550 $this->mString = $string;
1551 $this->mRead = false;
1552 }
1553
1554 /**
1555 * @return bool
1556 */
1557 function atEnd() {
1558 return $this->mRead;
1559 }
1560
1561 /**
1562 * @return bool|string
1563 */
1564 function readChunk() {
1565 if( $this->atEnd() ) {
1566 return false;
1567 }
1568 $this->mRead = true;
1569 return $this->mString;
1570 }
1571 }
1572
1573 /**
1574 * @todo document (e.g. one-sentence class description).
1575 * @ingroup SpecialPage
1576 */
1577 class ImportStreamSource {
1578 function __construct( $handle ) {
1579 $this->mHandle = $handle;
1580 }
1581
1582 /**
1583 * @return bool
1584 */
1585 function atEnd() {
1586 return feof( $this->mHandle );
1587 }
1588
1589 /**
1590 * @return string
1591 */
1592 function readChunk() {
1593 return fread( $this->mHandle, 32768 );
1594 }
1595
1596 /**
1597 * @param $filename string
1598 * @return Status
1599 */
1600 static function newFromFile( $filename ) {
1601 wfSuppressWarnings();
1602 $file = fopen( $filename, 'rt' );
1603 wfRestoreWarnings();
1604 if( !$file ) {
1605 return Status::newFatal( "importcantopen" );
1606 }
1607 return Status::newGood( new ImportStreamSource( $file ) );
1608 }
1609
1610 /**
1611 * @param $fieldname string
1612 * @return Status
1613 */
1614 static function newFromUpload( $fieldname = "xmlimport" ) {
1615 $upload =& $_FILES[$fieldname];
1616
1617 if( !isset( $upload ) || !$upload['name'] ) {
1618 return Status::newFatal( 'importnofile' );
1619 }
1620 if( !empty( $upload['error'] ) ) {
1621 switch($upload['error']){
1622 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1623 return Status::newFatal( 'importuploaderrorsize' );
1624 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1625 return Status::newFatal( 'importuploaderrorsize' );
1626 case 3: # The uploaded file was only partially uploaded
1627 return Status::newFatal( 'importuploaderrorpartial' );
1628 case 6: #Missing a temporary folder.
1629 return Status::newFatal( 'importuploaderrortemp' );
1630 # case else: # Currently impossible
1631 }
1632
1633 }
1634 $fname = $upload['tmp_name'];
1635 if( is_uploaded_file( $fname ) ) {
1636 return ImportStreamSource::newFromFile( $fname );
1637 } else {
1638 return Status::newFatal( 'importnofile' );
1639 }
1640 }
1641
1642 /**
1643 * @param $url
1644 * @param $method string
1645 * @return Status
1646 */
1647 static function newFromURL( $url, $method = 'GET' ) {
1648 wfDebug( __METHOD__ . ": opening $url\n" );
1649 # Use the standard HTTP fetch function; it times out
1650 # quicker and sorts out user-agent problems which might
1651 # otherwise prevent importing from large sites, such
1652 # as the Wikimedia cluster, etc.
1653 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1654 if( $data !== false ) {
1655 $file = tmpfile();
1656 fwrite( $file, $data );
1657 fflush( $file );
1658 fseek( $file, 0 );
1659 return Status::newGood( new ImportStreamSource( $file ) );
1660 } else {
1661 return Status::newFatal( 'importcantopen' );
1662 }
1663 }
1664
1665 /**
1666 * @param $interwiki
1667 * @param $page
1668 * @param $history bool
1669 * @param $templates bool
1670 * @param $pageLinkDepth int
1671 * @return Status
1672 */
1673 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1674 if( $page == '' ) {
1675 return Status::newFatal( 'import-noarticle' );
1676 }
1677 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1678 if( is_null( $link ) || $link->getInterwiki() == '' ) {
1679 return Status::newFatal( 'importbadinterwiki' );
1680 } else {
1681 $params = array();
1682 if ( $history ) $params['history'] = 1;
1683 if ( $templates ) $params['templates'] = 1;
1684 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1685 $url = $link->getFullUrl( $params );
1686 # For interwikis, use POST to avoid redirects.
1687 return ImportStreamSource::newFromURL( $url, "POST" );
1688 }
1689 }
1690 }