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