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