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