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