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