Introduce ContentHandler::importTransform.
[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->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['model'] ) ) {
698 $revision->setModel( $revisionInfo['model'] );
699 }
700 if ( isset( $revisionInfo['format'] ) ) {
701 $revision->setFormat( $revisionInfo['format'] );
702 }
703 $revision->setTitle( $pageInfo['_title'] );
704
705 if ( isset( $revisionInfo['text'] ) ) {
706 $handler = $revision->getContentHandler();
707 $text = $handler->importTransform(
708 $revisionInfo['text'],
709 $revision->getFormat() );
710
711 $revision->setText( $text );
712 }
713 if ( isset( $revisionInfo['timestamp'] ) ) {
714 $revision->setTimestamp( $revisionInfo['timestamp'] );
715 } else {
716 $revision->setTimestamp( wfTimestampNow() );
717 }
718
719 if ( isset( $revisionInfo['comment'] ) ) {
720 $revision->setComment( $revisionInfo['comment'] );
721 }
722
723 if ( isset( $revisionInfo['minor'] ) ) {
724 $revision->setMinor( true );
725 }
726 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
727 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
728 }
729 if ( isset( $revisionInfo['contributor']['username'] ) ) {
730 $revision->setUserName( $revisionInfo['contributor']['username'] );
731 }
732 $revision->setNoUpdates( $this->mNoUpdates );
733
734 return $this->revisionCallback( $revision );
735 }
736
737 /**
738 * @param array $pageInfo
739 * @return mixed
740 */
741 private function handleUpload( &$pageInfo ) {
742 $this->debug( "Enter upload handler" );
743 $uploadInfo = array();
744
745 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
746 'src', 'size', 'sha1base36', 'archivename', 'rel' );
747
748 $skip = false;
749
750 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
751 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
752 $this->reader->name == 'upload' ) {
753 break;
754 }
755
756 $tag = $this->reader->name;
757
758 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
759 $this, $pageInfo
760 ) ) ) {
761 // Do nothing
762 } elseif ( in_array( $tag, $normalFields ) ) {
763 $uploadInfo[$tag] = $this->nodeContents();
764 } elseif ( $tag == 'contributor' ) {
765 $uploadInfo['contributor'] = $this->handleContributor();
766 } elseif ( $tag == 'contents' ) {
767 $contents = $this->nodeContents();
768 $encoding = $this->reader->getAttribute( 'encoding' );
769 if ( $encoding === 'base64' ) {
770 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
771 $uploadInfo['isTempSrc'] = true;
772 }
773 } elseif ( $tag != '#text' ) {
774 $this->warn( "Unhandled upload XML tag $tag" );
775 $skip = true;
776 }
777 }
778
779 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
780 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
781 if ( file_exists( $path ) ) {
782 $uploadInfo['fileSrc'] = $path;
783 $uploadInfo['isTempSrc'] = false;
784 }
785 }
786
787 if ( $this->mImportUploads ) {
788 return $this->processUpload( $pageInfo, $uploadInfo );
789 }
790 }
791
792 /**
793 * @param string $contents
794 * @return string
795 */
796 private function dumpTemp( $contents ) {
797 $filename = tempnam( wfTempDir(), 'importupload' );
798 file_put_contents( $filename, $contents );
799 return $filename;
800 }
801
802 /**
803 * @param array $pageInfo
804 * @param array $uploadInfo
805 * @return mixed
806 */
807 private function processUpload( $pageInfo, $uploadInfo ) {
808 $revision = new WikiRevision;
809 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
810
811 $revision->setTitle( $pageInfo['_title'] );
812 $revision->setID( $pageInfo['id'] );
813 $revision->setTimestamp( $uploadInfo['timestamp'] );
814 $revision->setText( $text );
815 $revision->setFilename( $uploadInfo['filename'] );
816 if ( isset( $uploadInfo['archivename'] ) ) {
817 $revision->setArchiveName( $uploadInfo['archivename'] );
818 }
819 $revision->setSrc( $uploadInfo['src'] );
820 if ( isset( $uploadInfo['fileSrc'] ) ) {
821 $revision->setFileSrc( $uploadInfo['fileSrc'],
822 !empty( $uploadInfo['isTempSrc'] ) );
823 }
824 if ( isset( $uploadInfo['sha1base36'] ) ) {
825 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
826 }
827 $revision->setSize( intval( $uploadInfo['size'] ) );
828 $revision->setComment( $uploadInfo['comment'] );
829
830 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
831 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
832 }
833 if ( isset( $uploadInfo['contributor']['username'] ) ) {
834 $revision->setUserName( $uploadInfo['contributor']['username'] );
835 }
836 $revision->setNoUpdates( $this->mNoUpdates );
837
838 return call_user_func( $this->mUploadCallback, $revision );
839 }
840
841 /**
842 * @return array
843 */
844 private function handleContributor() {
845 $fields = array( 'id', 'ip', 'username' );
846 $info = array();
847
848 while ( $this->reader->read() ) {
849 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
850 $this->reader->name == 'contributor' ) {
851 break;
852 }
853
854 $tag = $this->reader->name;
855
856 if ( in_array( $tag, $fields ) ) {
857 $info[$tag] = $this->nodeContents();
858 }
859 }
860
861 return $info;
862 }
863
864 /**
865 * @param string $text
866 * @return array|bool
867 */
868 private function processTitle( $text ) {
869 global $wgCommandLineMode;
870
871 $workTitle = $text;
872 $origTitle = Title::newFromText( $workTitle );
873
874 if ( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
875 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
876 # and than dbKey can begin with a lowercase char
877 $title = Title::makeTitleSafe( $this->mTargetNamespace,
878 $origTitle->getDBkey() );
879 } else {
880 if ( !is_null( $this->mTargetRootPage ) ) {
881 $workTitle = $this->mTargetRootPage . '/' . $workTitle;
882 }
883 $title = Title::newFromText( $workTitle );
884 }
885
886 if ( is_null( $title ) ) {
887 # Invalid page title? Ignore the page
888 $this->notice( 'import-error-invalid', $workTitle );
889 return false;
890 } elseif ( $title->isExternal() ) {
891 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
892 return false;
893 } elseif ( !$title->canExist() ) {
894 $this->notice( 'import-error-special', $title->getPrefixedText() );
895 return false;
896 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
897 # Do not import if the importing wiki user cannot edit this page
898 $this->notice( 'import-error-edit', $title->getPrefixedText() );
899 return false;
900 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
901 # Do not import if the importing wiki user cannot create this page
902 $this->notice( 'import-error-create', $title->getPrefixedText() );
903 return false;
904 }
905
906 return array( $title, $origTitle );
907 }
908 }
909
910 /** This is a horrible hack used to keep source compatibility */
911 class UploadSourceAdapter {
912 /** @var array */
913 private static $sourceRegistrations = array();
914
915 /** @var string */
916 private $mSource;
917
918 /** @var string */
919 private $mBuffer;
920
921 /** @var int */
922 private $mPosition;
923
924 /**
925 * @param string $source
926 * @return string
927 */
928 static function registerSource( $source ) {
929 $id = wfRandomString();
930
931 self::$sourceRegistrations[$id] = $source;
932
933 return $id;
934 }
935
936 /**
937 * @param string $path
938 * @param string $mode
939 * @param array $options
940 * @param string $opened_path
941 * @return bool
942 */
943 function stream_open( $path, $mode, $options, &$opened_path ) {
944 $url = parse_url( $path );
945 $id = $url['host'];
946
947 if ( !isset( self::$sourceRegistrations[$id] ) ) {
948 return false;
949 }
950
951 $this->mSource = self::$sourceRegistrations[$id];
952
953 return true;
954 }
955
956 /**
957 * @param int $count
958 * @return string
959 */
960 function stream_read( $count ) {
961 $return = '';
962 $leave = false;
963
964 while ( !$leave && !$this->mSource->atEnd() &&
965 strlen( $this->mBuffer ) < $count ) {
966 $read = $this->mSource->readChunk();
967
968 if ( !strlen( $read ) ) {
969 $leave = true;
970 }
971
972 $this->mBuffer .= $read;
973 }
974
975 if ( strlen( $this->mBuffer ) ) {
976 $return = substr( $this->mBuffer, 0, $count );
977 $this->mBuffer = substr( $this->mBuffer, $count );
978 }
979
980 $this->mPosition += strlen( $return );
981
982 return $return;
983 }
984
985 /**
986 * @param string $data
987 * @return bool
988 */
989 function stream_write( $data ) {
990 return false;
991 }
992
993 /**
994 * @return mixed
995 */
996 function stream_tell() {
997 return $this->mPosition;
998 }
999
1000 /**
1001 * @return bool
1002 */
1003 function stream_eof() {
1004 return $this->mSource->atEnd();
1005 }
1006
1007 /**
1008 * @return array
1009 */
1010 function url_stat() {
1011 $result = array();
1012
1013 $result['dev'] = $result[0] = 0;
1014 $result['ino'] = $result[1] = 0;
1015 $result['mode'] = $result[2] = 0;
1016 $result['nlink'] = $result[3] = 0;
1017 $result['uid'] = $result[4] = 0;
1018 $result['gid'] = $result[5] = 0;
1019 $result['rdev'] = $result[6] = 0;
1020 $result['size'] = $result[7] = 0;
1021 $result['atime'] = $result[8] = 0;
1022 $result['mtime'] = $result[9] = 0;
1023 $result['ctime'] = $result[10] = 0;
1024 $result['blksize'] = $result[11] = 0;
1025 $result['blocks'] = $result[12] = 0;
1026
1027 return $result;
1028 }
1029 }
1030
1031 class XMLReader2 extends XMLReader {
1032
1033 /**
1034 * @return bool|string
1035 */
1036 function nodeContents() {
1037 if ( $this->isEmptyElement ) {
1038 return "";
1039 }
1040 $buffer = "";
1041 while ( $this->read() ) {
1042 switch ( $this->nodeType ) {
1043 case XmlReader::TEXT:
1044 case XmlReader::SIGNIFICANT_WHITESPACE:
1045 $buffer .= $this->value;
1046 break;
1047 case XmlReader::END_ELEMENT:
1048 return $buffer;
1049 }
1050 }
1051 return $this->close();
1052 }
1053 }
1054
1055 /**
1056 * @todo document (e.g. one-sentence class description).
1057 * @ingroup SpecialPage
1058 */
1059 class WikiRevision {
1060 /** @todo Unused? */
1061 private $importer = null;
1062
1063 /** @var Title */
1064 public $title = null;
1065
1066 /** @var int */
1067 private $id = 0;
1068
1069 /** @var string */
1070 public $timestamp = "20010115000000";
1071
1072 /**
1073 * @var int
1074 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1075 public $user = 0;
1076
1077 /** @var string */
1078 public $user_text = "";
1079
1080 /** @var string */
1081 protected $model = null;
1082
1083 /** @var string */
1084 protected $format = null;
1085
1086 /** @var string */
1087 public $text = "";
1088
1089 /** @var int */
1090 protected $size;
1091
1092 /** @var Content */
1093 protected $content = null;
1094
1095 /** @var ContentHandler */
1096 protected $contentHandler = null;
1097
1098 /** @var string */
1099 public $comment = "";
1100
1101 /** @var bool */
1102 protected $minor = false;
1103
1104 /** @var string */
1105 protected $type = "";
1106
1107 /** @var string */
1108 protected $action = "";
1109
1110 /** @var string */
1111 protected $params = "";
1112
1113 /** @var string */
1114 protected $fileSrc = '';
1115
1116 /** @var bool|string */
1117 protected $sha1base36 = false;
1118
1119 /**
1120 * @var bool
1121 * @todo Unused?
1122 */
1123 private $isTemp = false;
1124
1125 /** @var string */
1126 protected $archiveName = '';
1127
1128 protected $filename;
1129
1130 /** @var mixed */
1131 protected $src;
1132
1133 /** @todo Unused? */
1134 private $fileIsTemp;
1135
1136 /** @var bool */
1137 private $mNoUpdates = false;
1138
1139 /**
1140 * @param Title $title
1141 * @throws MWException
1142 */
1143 function setTitle( $title ) {
1144 if ( is_object( $title ) ) {
1145 $this->title = $title;
1146 } elseif ( is_null( $title ) ) {
1147 throw new MWException( "WikiRevision given a null title in import. "
1148 . "You may need to adjust \$wgLegalTitleChars." );
1149 } else {
1150 throw new MWException( "WikiRevision given non-object title in import." );
1151 }
1152 }
1153
1154 /**
1155 * @param int $id
1156 */
1157 function setID( $id ) {
1158 $this->id = $id;
1159 }
1160
1161 /**
1162 * @param string $ts
1163 */
1164 function setTimestamp( $ts ) {
1165 # 2003-08-05T18:30:02Z
1166 $this->timestamp = wfTimestamp( TS_MW, $ts );
1167 }
1168
1169 /**
1170 * @param string $user
1171 */
1172 function setUsername( $user ) {
1173 $this->user_text = $user;
1174 }
1175
1176 /**
1177 * @param string $ip
1178 */
1179 function setUserIP( $ip ) {
1180 $this->user_text = $ip;
1181 }
1182
1183 /**
1184 * @param string $model
1185 */
1186 function setModel( $model ) {
1187 $this->model = $model;
1188 }
1189
1190 /**
1191 * @param string $format
1192 */
1193 function setFormat( $format ) {
1194 $this->format = $format;
1195 }
1196
1197 /**
1198 * @param string $text
1199 */
1200 function setText( $text ) {
1201 $this->text = $text;
1202 }
1203
1204 /**
1205 * @param string $text
1206 */
1207 function setComment( $text ) {
1208 $this->comment = $text;
1209 }
1210
1211 /**
1212 * @param bool $minor
1213 */
1214 function setMinor( $minor ) {
1215 $this->minor = (bool)$minor;
1216 }
1217
1218 /**
1219 * @param mixed $src
1220 */
1221 function setSrc( $src ) {
1222 $this->src = $src;
1223 }
1224
1225 /**
1226 * @param string $src
1227 * @param bool $isTemp
1228 */
1229 function setFileSrc( $src, $isTemp ) {
1230 $this->fileSrc = $src;
1231 $this->fileIsTemp = $isTemp;
1232 }
1233
1234 /**
1235 * @param string $sha1base36
1236 */
1237 function setSha1Base36( $sha1base36 ) {
1238 $this->sha1base36 = $sha1base36;
1239 }
1240
1241 /**
1242 * @param string $filename
1243 */
1244 function setFilename( $filename ) {
1245 $this->filename = $filename;
1246 }
1247
1248 /**
1249 * @param string $archiveName
1250 */
1251 function setArchiveName( $archiveName ) {
1252 $this->archiveName = $archiveName;
1253 }
1254
1255 /**
1256 * @param int $size
1257 */
1258 function setSize( $size ) {
1259 $this->size = intval( $size );
1260 }
1261
1262 /**
1263 * @param string $type
1264 */
1265 function setType( $type ) {
1266 $this->type = $type;
1267 }
1268
1269 /**
1270 * @param string $action
1271 */
1272 function setAction( $action ) {
1273 $this->action = $action;
1274 }
1275
1276 /**
1277 * @param array $params
1278 */
1279 function setParams( $params ) {
1280 $this->params = $params;
1281 }
1282
1283 /**
1284 * @param bool $noupdates
1285 */
1286 public function setNoUpdates( $noupdates ) {
1287 $this->mNoUpdates = $noupdates;
1288 }
1289
1290 /**
1291 * @return Title
1292 */
1293 function getTitle() {
1294 return $this->title;
1295 }
1296
1297 /**
1298 * @return int
1299 */
1300 function getID() {
1301 return $this->id;
1302 }
1303
1304 /**
1305 * @return string
1306 */
1307 function getTimestamp() {
1308 return $this->timestamp;
1309 }
1310
1311 /**
1312 * @return string
1313 */
1314 function getUser() {
1315 return $this->user_text;
1316 }
1317
1318 /**
1319 * @return string
1320 *
1321 * @deprecated Since 1.21, use getContent() instead.
1322 */
1323 function getText() {
1324 ContentHandler::deprecated( __METHOD__, '1.21' );
1325
1326 return $this->text;
1327 }
1328
1329 /**
1330 * @return ContentHandler
1331 */
1332 function getContentHandler() {
1333 if ( is_null( $this->contentHandler ) ) {
1334 $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
1335 }
1336
1337 return $this->contentHandler;
1338 }
1339
1340 /**
1341 * @return Content
1342 */
1343 function getContent() {
1344 if ( is_null( $this->content ) ) {
1345 $handler = $this->getContentHandler();
1346 $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
1347 }
1348
1349 return $this->content;
1350 }
1351
1352 /**
1353 * @return string
1354 */
1355 function getModel() {
1356 if ( is_null( $this->model ) ) {
1357 $this->model = $this->getTitle()->getContentModel();
1358 }
1359
1360 return $this->model;
1361 }
1362
1363 /**
1364 * @return string
1365 */
1366 function getFormat() {
1367 if ( is_null( $this->format ) ) {
1368 $this->format = $this->getContentHandler()->getDefaultFormat();
1369 }
1370
1371 return $this->format;
1372 }
1373
1374 /**
1375 * @return string
1376 */
1377 function getComment() {
1378 return $this->comment;
1379 }
1380
1381 /**
1382 * @return bool
1383 */
1384 function getMinor() {
1385 return $this->minor;
1386 }
1387
1388 /**
1389 * @return mixed
1390 */
1391 function getSrc() {
1392 return $this->src;
1393 }
1394
1395 /**
1396 * @return bool|string
1397 */
1398 function getSha1() {
1399 if ( $this->sha1base36 ) {
1400 return wfBaseConvert( $this->sha1base36, 36, 16 );
1401 }
1402 return false;
1403 }
1404
1405 /**
1406 * @return string
1407 */
1408 function getFileSrc() {
1409 return $this->fileSrc;
1410 }
1411
1412 /**
1413 * @return bool
1414 */
1415 function isTempSrc() {
1416 return $this->isTemp;
1417 }
1418
1419 /**
1420 * @return mixed
1421 */
1422 function getFilename() {
1423 return $this->filename;
1424 }
1425
1426 /**
1427 * @return string
1428 */
1429 function getArchiveName() {
1430 return $this->archiveName;
1431 }
1432
1433 /**
1434 * @return mixed
1435 */
1436 function getSize() {
1437 return $this->size;
1438 }
1439
1440 /**
1441 * @return string
1442 */
1443 function getType() {
1444 return $this->type;
1445 }
1446
1447 /**
1448 * @return string
1449 */
1450 function getAction() {
1451 return $this->action;
1452 }
1453
1454 /**
1455 * @return string
1456 */
1457 function getParams() {
1458 return $this->params;
1459 }
1460
1461 /**
1462 * @return bool
1463 */
1464 function importOldRevision() {
1465 $dbw = wfGetDB( DB_MASTER );
1466
1467 # Sneak a single revision into place
1468 $user = User::newFromName( $this->getUser() );
1469 if ( $user ) {
1470 $userId = intval( $user->getId() );
1471 $userText = $user->getName();
1472 $userObj = $user;
1473 } else {
1474 $userId = 0;
1475 $userText = $this->getUser();
1476 $userObj = new User;
1477 }
1478
1479 // avoid memory leak...?
1480 $linkCache = LinkCache::singleton();
1481 $linkCache->clear();
1482
1483 $page = WikiPage::factory( $this->title );
1484 if ( !$page->exists() ) {
1485 # must create the page...
1486 $pageId = $page->insertOn( $dbw );
1487 $created = true;
1488 $oldcountable = null;
1489 } else {
1490 $pageId = $page->getId();
1491 $created = false;
1492
1493 $prior = $dbw->selectField( 'revision', '1',
1494 array( 'rev_page' => $pageId,
1495 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1496 'rev_user_text' => $userText,
1497 'rev_comment' => $this->getComment() ),
1498 __METHOD__
1499 );
1500 if ( $prior ) {
1501 // @todo FIXME: This could fail slightly for multiple matches :P
1502 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1503 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1504 return false;
1505 }
1506 $oldcountable = $page->isCountable();
1507 }
1508
1509 # @todo FIXME: Use original rev_id optionally (better for backups)
1510 # Insert the row
1511 $revision = new Revision( array(
1512 'title' => $this->title,
1513 'page' => $pageId,
1514 'content_model' => $this->getModel(),
1515 'content_format' => $this->getFormat(),
1516 //XXX: just set 'content' => $this->getContent()?
1517 'text' => $this->getContent()->serialize( $this->getFormat() ),
1518 'comment' => $this->getComment(),
1519 'user' => $userId,
1520 'user_text' => $userText,
1521 'timestamp' => $this->timestamp,
1522 'minor_edit' => $this->minor,
1523 ) );
1524 $revision->insertOn( $dbw );
1525 $changed = $page->updateIfNewerOn( $dbw, $revision );
1526
1527 if ( $changed !== false && !$this->mNoUpdates ) {
1528 wfDebug( __METHOD__ . ": running updates\n" );
1529 $page->doEditUpdates(
1530 $revision,
1531 $userObj,
1532 array( 'created' => $created, 'oldcountable' => $oldcountable )
1533 );
1534 }
1535
1536 return true;
1537 }
1538
1539 /**
1540 * @return mixed
1541 */
1542 function importLogItem() {
1543 $dbw = wfGetDB( DB_MASTER );
1544 # @todo FIXME: This will not record autoblocks
1545 if ( !$this->getTitle() ) {
1546 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1547 $this->timestamp . "\n" );
1548 return;
1549 }
1550 # Check if it exists already
1551 // @todo FIXME: Use original log ID (better for backups)
1552 $prior = $dbw->selectField( 'logging', '1',
1553 array( 'log_type' => $this->getType(),
1554 'log_action' => $this->getAction(),
1555 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1556 'log_namespace' => $this->getTitle()->getNamespace(),
1557 'log_title' => $this->getTitle()->getDBkey(),
1558 'log_comment' => $this->getComment(),
1559 #'log_user_text' => $this->user_text,
1560 'log_params' => $this->params ),
1561 __METHOD__
1562 );
1563 // @todo FIXME: This could fail slightly for multiple matches :P
1564 if ( $prior ) {
1565 wfDebug( __METHOD__
1566 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1567 . $this->timestamp . "\n" );
1568 return;
1569 }
1570 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1571 $data = array(
1572 'log_id' => $log_id,
1573 'log_type' => $this->type,
1574 'log_action' => $this->action,
1575 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1576 'log_user' => User::idFromName( $this->user_text ),
1577 #'log_user_text' => $this->user_text,
1578 'log_namespace' => $this->getTitle()->getNamespace(),
1579 'log_title' => $this->getTitle()->getDBkey(),
1580 'log_comment' => $this->getComment(),
1581 'log_params' => $this->params
1582 );
1583 $dbw->insert( 'logging', $data, __METHOD__ );
1584 }
1585
1586 /**
1587 * @return bool
1588 */
1589 function importUpload() {
1590 # Construct a file
1591 $archiveName = $this->getArchiveName();
1592 if ( $archiveName ) {
1593 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1594 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1595 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1596 } else {
1597 $file = wfLocalFile( $this->getTitle() );
1598 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1599 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1600 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1601 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1602 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1603 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1604 }
1605 }
1606 if ( !$file ) {
1607 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1608 return false;
1609 }
1610
1611 # Get the file source or download if necessary
1612 $source = $this->getFileSrc();
1613 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1614 if ( !$source ) {
1615 $source = $this->downloadSource();
1616 $flags |= File::DELETE_SOURCE;
1617 }
1618 if ( !$source ) {
1619 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1620 return false;
1621 }
1622 $sha1 = $this->getSha1();
1623 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1624 if ( $flags & File::DELETE_SOURCE ) {
1625 # Broken file; delete it if it is a temporary file
1626 unlink( $source );
1627 }
1628 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1629 return false;
1630 }
1631
1632 $user = User::newFromName( $this->user_text );
1633
1634 # Do the actual upload
1635 if ( $archiveName ) {
1636 $status = $file->uploadOld( $source, $archiveName,
1637 $this->getTimestamp(), $this->getComment(), $user, $flags );
1638 } else {
1639 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1640 $flags, false, $this->getTimestamp(), $user );
1641 }
1642
1643 if ( $status->isGood() ) {
1644 wfDebug( __METHOD__ . ": Successful\n" );
1645 return true;
1646 } else {
1647 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1648 return false;
1649 }
1650 }
1651
1652 /**
1653 * @return bool|string
1654 */
1655 function downloadSource() {
1656 global $wgEnableUploads;
1657 if ( !$wgEnableUploads ) {
1658 return false;
1659 }
1660
1661 $tempo = tempnam( wfTempDir(), 'download' );
1662 $f = fopen( $tempo, 'wb' );
1663 if ( !$f ) {
1664 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1665 return false;
1666 }
1667
1668 // @todo FIXME!
1669 $src = $this->getSrc();
1670 $data = Http::get( $src );
1671 if ( !$data ) {
1672 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1673 fclose( $f );
1674 unlink( $tempo );
1675 return false;
1676 }
1677
1678 fwrite( $f, $data );
1679 fclose( $f );
1680
1681 return $tempo;
1682 }
1683
1684 }
1685
1686 /**
1687 * @todo document (e.g. one-sentence class description).
1688 * @ingroup SpecialPage
1689 */
1690 class ImportStringSource {
1691 function __construct( $string ) {
1692 $this->mString = $string;
1693 $this->mRead = false;
1694 }
1695
1696 /**
1697 * @return bool
1698 */
1699 function atEnd() {
1700 return $this->mRead;
1701 }
1702
1703 /**
1704 * @return bool|string
1705 */
1706 function readChunk() {
1707 if ( $this->atEnd() ) {
1708 return false;
1709 }
1710 $this->mRead = true;
1711 return $this->mString;
1712 }
1713 }
1714
1715 /**
1716 * @todo document (e.g. one-sentence class description).
1717 * @ingroup SpecialPage
1718 */
1719 class ImportStreamSource {
1720 function __construct( $handle ) {
1721 $this->mHandle = $handle;
1722 }
1723
1724 /**
1725 * @return bool
1726 */
1727 function atEnd() {
1728 return feof( $this->mHandle );
1729 }
1730
1731 /**
1732 * @return string
1733 */
1734 function readChunk() {
1735 return fread( $this->mHandle, 32768 );
1736 }
1737
1738 /**
1739 * @param string $filename
1740 * @return Status
1741 */
1742 static function newFromFile( $filename ) {
1743 wfSuppressWarnings();
1744 $file = fopen( $filename, 'rt' );
1745 wfRestoreWarnings();
1746 if ( !$file ) {
1747 return Status::newFatal( "importcantopen" );
1748 }
1749 return Status::newGood( new ImportStreamSource( $file ) );
1750 }
1751
1752 /**
1753 * @param string $fieldname
1754 * @return Status
1755 */
1756 static function newFromUpload( $fieldname = "xmlimport" ) {
1757 $upload =& $_FILES[$fieldname];
1758
1759 if ( $upload === null || !$upload['name'] ) {
1760 return Status::newFatal( 'importnofile' );
1761 }
1762 if ( !empty( $upload['error'] ) ) {
1763 switch ( $upload['error'] ) {
1764 case 1:
1765 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1766 return Status::newFatal( 'importuploaderrorsize' );
1767 case 2:
1768 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1769 # was specified in the HTML form.
1770 return Status::newFatal( 'importuploaderrorsize' );
1771 case 3:
1772 # The uploaded file was only partially uploaded
1773 return Status::newFatal( 'importuploaderrorpartial' );
1774 case 6:
1775 # Missing a temporary folder.
1776 return Status::newFatal( 'importuploaderrortemp' );
1777 # case else: # Currently impossible
1778 }
1779
1780 }
1781 $fname = $upload['tmp_name'];
1782 if ( is_uploaded_file( $fname ) ) {
1783 return ImportStreamSource::newFromFile( $fname );
1784 } else {
1785 return Status::newFatal( 'importnofile' );
1786 }
1787 }
1788
1789 /**
1790 * @param string $url
1791 * @param string $method
1792 * @return Status
1793 */
1794 static function newFromURL( $url, $method = 'GET' ) {
1795 wfDebug( __METHOD__ . ": opening $url\n" );
1796 # Use the standard HTTP fetch function; it times out
1797 # quicker and sorts out user-agent problems which might
1798 # otherwise prevent importing from large sites, such
1799 # as the Wikimedia cluster, etc.
1800 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1801 if ( $data !== false ) {
1802 $file = tmpfile();
1803 fwrite( $file, $data );
1804 fflush( $file );
1805 fseek( $file, 0 );
1806 return Status::newGood( new ImportStreamSource( $file ) );
1807 } else {
1808 return Status::newFatal( 'importcantopen' );
1809 }
1810 }
1811
1812 /**
1813 * @param string $interwiki
1814 * @param string $page
1815 * @param bool $history
1816 * @param bool $templates
1817 * @param int $pageLinkDepth
1818 * @return Status
1819 */
1820 public static function newFromInterwiki( $interwiki, $page, $history = false,
1821 $templates = false, $pageLinkDepth = 0
1822 ) {
1823 if ( $page == '' ) {
1824 return Status::newFatal( 'import-noarticle' );
1825 }
1826 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1827 if ( is_null( $link ) || !$link->isExternal() ) {
1828 return Status::newFatal( 'importbadinterwiki' );
1829 } else {
1830 $params = array();
1831 if ( $history ) {
1832 $params['history'] = 1;
1833 }
1834 if ( $templates ) {
1835 $params['templates'] = 1;
1836 }
1837 if ( $pageLinkDepth ) {
1838 $params['pagelink-depth'] = $pageLinkDepth;
1839 }
1840 $url = $link->getFullURL( $params );
1841 # For interwikis, use POST to avoid redirects.
1842 return ImportStreamSource::newFromURL( $url, "POST" );
1843 }
1844 }
1845 }