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