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