Unsuppress phan issues part 6
[lhc/web/wiklou.git] / includes / import / WikiImporter.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 use MediaWiki\MediaWikiServices;
28
29 /**
30 * XML file reader for the page data importer.
31 *
32 * implements Special:Import
33 * @ingroup SpecialPage
34 */
35 class WikiImporter {
36 private $reader = null;
37 private $foreignNamespaces = null;
38 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
39 private $mSiteInfoCallback, $mPageOutCallback;
40 private $mNoticeCallback, $mDebug;
41 private $mImportUploads, $mImageBasePath;
42 private $mNoUpdates = false;
43 private $pageOffset = 0;
44 /** @var Config */
45 private $config;
46 /** @var ImportTitleFactory */
47 private $importTitleFactory;
48 /** @var array */
49 private $countableCache = [];
50 /** @var bool */
51 private $disableStatisticsUpdate = false;
52 /** @var ExternalUserNames */
53 private $externalUserNames;
54
55 /**
56 * Creates an ImportXMLReader drawing from the source provided
57 * @param ImportSource $source
58 * @param Config $config
59 * @throws Exception
60 */
61 function __construct( ImportSource $source, Config $config ) {
62 if ( !class_exists( 'XMLReader' ) ) {
63 throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
64 }
65
66 $this->reader = new XMLReader();
67 $this->config = $config;
68
69 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
70 stream_wrapper_register( 'uploadsource', UploadSourceAdapter::class );
71 }
72 $id = UploadSourceAdapter::registerSource( $source );
73
74 // Enable the entity loader, as it is needed for loading external URLs via
75 // XMLReader::open (T86036)
76 $oldDisable = libxml_disable_entity_loader( false );
77 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
78 $status = $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
79 } else {
80 $status = $this->reader->open( "uploadsource://$id" );
81 }
82 if ( !$status ) {
83 $error = libxml_get_last_error();
84 libxml_disable_entity_loader( $oldDisable );
85 throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
86 $error->message );
87 }
88 libxml_disable_entity_loader( $oldDisable );
89
90 // Default callbacks
91 $this->setPageCallback( [ $this, 'beforeImportPage' ] );
92 $this->setRevisionCallback( [ $this, "importRevision" ] );
93 $this->setUploadCallback( [ $this, 'importUpload' ] );
94 $this->setLogItemCallback( [ $this, 'importLogItem' ] );
95 $this->setPageOutCallback( [ $this, 'finishImportPage' ] );
96
97 $this->importTitleFactory = new NaiveImportTitleFactory();
98 $this->externalUserNames = new ExternalUserNames( 'imported', false );
99 }
100
101 /**
102 * @return null|XMLReader
103 */
104 public function getReader() {
105 return $this->reader;
106 }
107
108 public function throwXmlError( $err ) {
109 $this->debug( "FAILURE: $err" );
110 wfDebug( "WikiImporter XML error: $err\n" );
111 }
112
113 public function debug( $data ) {
114 if ( $this->mDebug ) {
115 wfDebug( "IMPORT: $data\n" );
116 }
117 }
118
119 public function warn( $data ) {
120 wfDebug( "IMPORT: $data\n" );
121 }
122
123 public function notice( $msg, ...$params ) {
124 if ( is_callable( $this->mNoticeCallback ) ) {
125 call_user_func( $this->mNoticeCallback, $msg, $params );
126 } else { # No ImportReporter -> CLI
127 // T177997: the command line importers should call setNoticeCallback()
128 // for their own custom callback to echo the notice
129 wfDebug( wfMessage( $msg, $params )->text() . "\n" );
130 }
131 }
132
133 /**
134 * Set debug mode...
135 * @param bool $debug
136 */
137 function setDebug( $debug ) {
138 $this->mDebug = $debug;
139 }
140
141 /**
142 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
143 * @param bool $noupdates
144 */
145 function setNoUpdates( $noupdates ) {
146 $this->mNoUpdates = $noupdates;
147 }
148
149 /**
150 * Sets 'pageOffset' value. So it will skip the first n-1 pages
151 * and start from the nth page. It's 1-based indexing.
152 * @param int $nthPage
153 * @since 1.29
154 */
155 function setPageOffset( $nthPage ) {
156 $this->pageOffset = $nthPage;
157 }
158
159 /**
160 * Set a callback that displays notice messages
161 *
162 * @param callable $callback
163 * @return callable
164 */
165 public function setNoticeCallback( $callback ) {
166 return wfSetVar( $this->mNoticeCallback, $callback );
167 }
168
169 /**
170 * Sets the action to perform as each new page in the stream is reached.
171 * @param callable $callback
172 * @return callable
173 */
174 public function setPageCallback( $callback ) {
175 $previous = $this->mPageCallback;
176 $this->mPageCallback = $callback;
177 return $previous;
178 }
179
180 /**
181 * Sets the action to perform as each page in the stream is completed.
182 * Callback accepts the page title (as a Title object), a second object
183 * with the original title form (in case it's been overridden into a
184 * local namespace), and a count of revisions.
185 *
186 * @param callable $callback
187 * @return callable
188 */
189 public function setPageOutCallback( $callback ) {
190 $previous = $this->mPageOutCallback;
191 $this->mPageOutCallback = $callback;
192 return $previous;
193 }
194
195 /**
196 * Sets the action to perform as each page revision is reached.
197 * @param callable $callback
198 * @return callable
199 */
200 public function setRevisionCallback( $callback ) {
201 $previous = $this->mRevisionCallback;
202 $this->mRevisionCallback = $callback;
203 return $previous;
204 }
205
206 /**
207 * Sets the action to perform as each file upload version is reached.
208 * @param callable $callback
209 * @return callable
210 */
211 public function setUploadCallback( $callback ) {
212 $previous = $this->mUploadCallback;
213 $this->mUploadCallback = $callback;
214 return $previous;
215 }
216
217 /**
218 * Sets the action to perform as each log item reached.
219 * @param callable $callback
220 * @return callable
221 */
222 public function setLogItemCallback( $callback ) {
223 $previous = $this->mLogItemCallback;
224 $this->mLogItemCallback = $callback;
225 return $previous;
226 }
227
228 /**
229 * Sets the action to perform when site info is encountered
230 * @param callable $callback
231 * @return callable
232 */
233 public function setSiteInfoCallback( $callback ) {
234 $previous = $this->mSiteInfoCallback;
235 $this->mSiteInfoCallback = $callback;
236 return $previous;
237 }
238
239 /**
240 * Sets the factory object to use to convert ForeignTitle objects into local
241 * Title objects
242 * @param ImportTitleFactory $factory
243 */
244 public function setImportTitleFactory( $factory ) {
245 $this->importTitleFactory = $factory;
246 }
247
248 /**
249 * Set a target namespace to override the defaults
250 * @param null|int $namespace
251 * @return bool
252 */
253 public function setTargetNamespace( $namespace ) {
254 if ( is_null( $namespace ) ) {
255 // Don't override namespaces
256 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
257 return true;
258 } elseif (
259 $namespace >= 0 &&
260 MediaWikiServices::getInstance()->getNamespaceInfo()->exists( intval( $namespace ) )
261 ) {
262 $namespace = intval( $namespace );
263 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
264 return true;
265 } else {
266 return false;
267 }
268 }
269
270 /**
271 * Set a target root page under which all pages are imported
272 * @param null|string $rootpage
273 * @return Status
274 */
275 public function setTargetRootPage( $rootpage ) {
276 $status = Status::newGood();
277 if ( is_null( $rootpage ) ) {
278 // No rootpage
279 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
280 } elseif ( $rootpage !== '' ) {
281 $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
282 $title = Title::newFromText( $rootpage );
283
284 if ( !$title || $title->isExternal() ) {
285 $status->fatal( 'import-rootpage-invalid' );
286 } elseif (
287 !MediaWikiServices::getInstance()->getNamespaceInfo()->
288 hasSubpages( $title->getNamespace() )
289 ) {
290 $displayNSText = $title->getNamespace() == NS_MAIN
291 ? wfMessage( 'blanknamespace' )->text()
292 : MediaWikiServices::getInstance()->getContentLanguage()->
293 getNsText( $title->getNamespace() );
294 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
295 } else {
296 // set namespace to 'all', so the namespace check in processTitle() can pass
297 $this->setTargetNamespace( null );
298 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
299 }
300 }
301 return $status;
302 }
303
304 /**
305 * @param string $dir
306 */
307 public function setImageBasePath( $dir ) {
308 $this->mImageBasePath = $dir;
309 }
310
311 /**
312 * @param bool $import
313 */
314 public function setImportUploads( $import ) {
315 $this->mImportUploads = $import;
316 }
317
318 /**
319 * @since 1.31
320 * @param string $usernamePrefix Prefix to apply to unknown (and possibly also known) usernames
321 * @param bool $assignKnownUsers Whether to apply the prefix to usernames that exist locally
322 */
323 public function setUsernamePrefix( $usernamePrefix, $assignKnownUsers ) {
324 $this->externalUserNames = new ExternalUserNames( $usernamePrefix, $assignKnownUsers );
325 }
326
327 /**
328 * Statistics update can cause a lot of time
329 * @since 1.29
330 */
331 public function disableStatisticsUpdate() {
332 $this->disableStatisticsUpdate = true;
333 }
334
335 /**
336 * Default per-page callback. Sets up some things related to site statistics
337 * @param array $titleAndForeignTitle Two-element array, with Title object at
338 * index 0 and ForeignTitle object at index 1
339 * @return bool
340 */
341 public function beforeImportPage( $titleAndForeignTitle ) {
342 $title = $titleAndForeignTitle[0];
343 $page = WikiPage::factory( $title );
344 $this->countableCache['title_' . $title->getPrefixedText()] = $page->isCountable();
345 return true;
346 }
347
348 /**
349 * Default per-revision callback, performs the import.
350 * @param WikiRevision $revision
351 * @return bool
352 */
353 public function importRevision( $revision ) {
354 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
355 $this->notice( 'import-error-bad-location',
356 $revision->getTitle()->getPrefixedText(),
357 $revision->getID(),
358 $revision->getModel(),
359 $revision->getFormat() );
360
361 return false;
362 }
363
364 try {
365 return $revision->importOldRevision();
366 } catch ( MWContentSerializationException $ex ) {
367 $this->notice( 'import-error-unserialize',
368 $revision->getTitle()->getPrefixedText(),
369 $revision->getID(),
370 $revision->getModel(),
371 $revision->getFormat() );
372 }
373
374 return false;
375 }
376
377 /**
378 * Default per-revision callback, performs the import.
379 * @param WikiRevision $revision
380 * @return bool
381 */
382 public function importLogItem( $revision ) {
383 return $revision->importLogItem();
384 }
385
386 /**
387 * Dummy for now...
388 * @param WikiRevision $revision
389 * @return bool
390 */
391 public function importUpload( $revision ) {
392 return $revision->importUpload();
393 }
394
395 /**
396 * Mostly for hook use
397 * @param Title $title
398 * @param ForeignTitle $foreignTitle
399 * @param int $revCount
400 * @param int $sRevCount
401 * @param array $pageInfo
402 * @return bool
403 */
404 public function finishImportPage( $title, $foreignTitle, $revCount,
405 $sRevCount, $pageInfo
406 ) {
407 // Update article count statistics (T42009)
408 // The normal counting logic in WikiPage->doEditUpdates() is designed for
409 // one-revision-at-a-time editing, not bulk imports. In this situation it
410 // suffers from issues of replica DB lag. We let WikiPage handle the total page
411 // and revision count, and we implement our own custom logic for the
412 // article (content page) count.
413 if ( !$this->disableStatisticsUpdate ) {
414 $page = WikiPage::factory( $title );
415 $page->loadPageData( 'fromdbmaster' );
416 $content = $page->getContent();
417 if ( $content === null ) {
418 wfDebug( __METHOD__ . ': Skipping article count adjustment for ' . $title .
419 ' because WikiPage::getContent() returned null' );
420 } else {
421 $editInfo = $page->prepareContentForEdit( $content );
422 $countKey = 'title_' . $title->getPrefixedText();
423 $countable = $page->isCountable( $editInfo );
424 if ( array_key_exists( $countKey, $this->countableCache ) &&
425 $countable != $this->countableCache[$countKey] ) {
426 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [
427 'articles' => ( (int)$countable - (int)$this->countableCache[$countKey] )
428 ] ) );
429 }
430 }
431 }
432
433 return Hooks::run( 'AfterImportPage', func_get_args() );
434 }
435
436 /**
437 * Alternate per-revision callback, for debugging.
438 * @param WikiRevision &$revision
439 */
440 public function debugRevisionHandler( &$revision ) {
441 $this->debug( "Got revision:" );
442 if ( is_object( $revision->title ) ) {
443 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
444 } else {
445 $this->debug( "-- Title: <invalid>" );
446 }
447 $this->debug( "-- User: " . $revision->user_text );
448 $this->debug( "-- Timestamp: " . $revision->timestamp );
449 $this->debug( "-- Comment: " . $revision->comment );
450 $this->debug( "-- Text: " . $revision->text );
451 }
452
453 /**
454 * Notify the callback function of site info
455 * @param array $siteInfo
456 * @return bool|mixed
457 */
458 private function siteInfoCallback( $siteInfo ) {
459 if ( isset( $this->mSiteInfoCallback ) ) {
460 return call_user_func_array( $this->mSiteInfoCallback,
461 [ $siteInfo, $this ] );
462 } else {
463 return false;
464 }
465 }
466
467 /**
468 * Notify the callback function when a new "<page>" is reached.
469 * @param array $title
470 */
471 function pageCallback( $title ) {
472 if ( isset( $this->mPageCallback ) ) {
473 call_user_func( $this->mPageCallback, $title );
474 }
475 }
476
477 /**
478 * Notify the callback function when a "</page>" is closed.
479 * @param Title $title
480 * @param ForeignTitle $foreignTitle
481 * @param int $revCount
482 * @param int $sucCount Number of revisions for which callback returned true
483 * @param array $pageInfo Associative array of page information
484 */
485 private function pageOutCallback( $title, $foreignTitle, $revCount,
486 $sucCount, $pageInfo ) {
487 if ( isset( $this->mPageOutCallback ) ) {
488 call_user_func_array( $this->mPageOutCallback, func_get_args() );
489 }
490 }
491
492 /**
493 * Notify the callback function of a revision
494 * @param WikiRevision $revision
495 * @return bool|mixed
496 */
497 private function revisionCallback( $revision ) {
498 if ( isset( $this->mRevisionCallback ) ) {
499 return call_user_func_array( $this->mRevisionCallback,
500 [ $revision, $this ] );
501 } else {
502 return false;
503 }
504 }
505
506 /**
507 * Notify the callback function of a new log item
508 * @param WikiRevision $revision
509 * @return bool|mixed
510 */
511 private function logItemCallback( $revision ) {
512 if ( isset( $this->mLogItemCallback ) ) {
513 return call_user_func_array( $this->mLogItemCallback,
514 [ $revision, $this ] );
515 } else {
516 return false;
517 }
518 }
519
520 /**
521 * Retrieves the contents of the named attribute of the current element.
522 * @param string $attr The name of the attribute
523 * @return string The value of the attribute or an empty string if it is not set in the current
524 * element.
525 */
526 public function nodeAttribute( $attr ) {
527 return $this->reader->getAttribute( $attr );
528 }
529
530 /**
531 * Shouldn't something like this be built-in to XMLReader?
532 * Fetches text contents of the current element, assuming
533 * no sub-elements or such scary things.
534 * @return string
535 * @private
536 */
537 public function nodeContents() {
538 if ( $this->reader->isEmptyElement ) {
539 return "";
540 }
541 $buffer = "";
542 while ( $this->reader->read() ) {
543 switch ( $this->reader->nodeType ) {
544 case XMLReader::TEXT:
545 case XMLReader::CDATA:
546 case XMLReader::SIGNIFICANT_WHITESPACE:
547 $buffer .= $this->reader->value;
548 break;
549 case XMLReader::END_ELEMENT:
550 return $buffer;
551 }
552 }
553
554 $this->reader->close();
555 return '';
556 }
557
558 /**
559 * Primary entry point
560 * @throws Exception
561 * @throws MWException
562 * @return bool
563 */
564 public function doImport() {
565 // Calls to reader->read need to be wrapped in calls to
566 // libxml_disable_entity_loader() to avoid local file
567 // inclusion attacks (T48932).
568 $oldDisable = libxml_disable_entity_loader( true );
569 $this->reader->read();
570
571 if ( $this->reader->localName != 'mediawiki' ) {
572 libxml_disable_entity_loader( $oldDisable );
573 throw new MWException( "Expected <mediawiki> tag, got " .
574 $this->reader->localName );
575 }
576 $this->debug( "<mediawiki> tag is correct." );
577
578 $this->debug( "Starting primary dump processing loop." );
579
580 $keepReading = $this->reader->read();
581 $skip = false;
582 $rethrow = null;
583 $pageCount = 0;
584 try {
585 while ( $keepReading ) {
586 $tag = $this->reader->localName;
587 if ( $this->pageOffset ) {
588 if ( $tag === 'page' ) {
589 $pageCount++;
590 }
591 if ( $pageCount < $this->pageOffset ) {
592 $keepReading = $this->reader->next();
593 continue;
594 }
595 }
596 $type = $this->reader->nodeType;
597
598 if ( !Hooks::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
599 // Do nothing
600 } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
601 break;
602 } elseif ( $tag == 'siteinfo' ) {
603 $this->handleSiteInfo();
604 } elseif ( $tag == 'page' ) {
605 $this->handlePage();
606 } elseif ( $tag == 'logitem' ) {
607 $this->handleLogItem();
608 } elseif ( $tag != '#text' ) {
609 $this->warn( "Unhandled top-level XML tag $tag" );
610
611 $skip = true;
612 }
613
614 if ( $skip ) {
615 $keepReading = $this->reader->next();
616 $skip = false;
617 $this->debug( "Skip" );
618 } else {
619 $keepReading = $this->reader->read();
620 }
621 }
622 } catch ( Exception $ex ) {
623 $rethrow = $ex;
624 }
625
626 // finally
627 libxml_disable_entity_loader( $oldDisable );
628 $this->reader->close();
629
630 if ( $rethrow ) {
631 throw $rethrow;
632 }
633
634 return true;
635 }
636
637 private function handleSiteInfo() {
638 $this->debug( "Enter site info handler." );
639 $siteInfo = [];
640
641 // Fields that can just be stuffed in the siteInfo object
642 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
643
644 while ( $this->reader->read() ) {
645 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
646 $this->reader->localName == 'siteinfo' ) {
647 break;
648 }
649
650 $tag = $this->reader->localName;
651
652 if ( $tag == 'namespace' ) {
653 $this->foreignNamespaces[$this->nodeAttribute( 'key' )] =
654 $this->nodeContents();
655 } elseif ( in_array( $tag, $normalFields ) ) {
656 $siteInfo[$tag] = $this->nodeContents();
657 }
658 }
659
660 $siteInfo['_namespaces'] = $this->foreignNamespaces;
661 $this->siteInfoCallback( $siteInfo );
662 }
663
664 private function handleLogItem() {
665 $this->debug( "Enter log item handler." );
666 $logInfo = [];
667
668 // Fields that can just be stuffed in the pageInfo object
669 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
670 'logtitle', 'params' ];
671
672 while ( $this->reader->read() ) {
673 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
674 $this->reader->localName == 'logitem' ) {
675 break;
676 }
677
678 $tag = $this->reader->localName;
679
680 if ( !Hooks::run( 'ImportHandleLogItemXMLTag', [
681 $this, $logInfo
682 ] ) ) {
683 // Do nothing
684 } elseif ( in_array( $tag, $normalFields ) ) {
685 $logInfo[$tag] = $this->nodeContents();
686 } elseif ( $tag == 'contributor' ) {
687 $logInfo['contributor'] = $this->handleContributor();
688 } elseif ( $tag != '#text' ) {
689 $this->warn( "Unhandled log-item XML tag $tag" );
690 }
691 }
692
693 $this->processLogItem( $logInfo );
694 }
695
696 /**
697 * @param array $logInfo
698 * @return bool|mixed
699 */
700 private function processLogItem( $logInfo ) {
701 $revision = new WikiRevision( $this->config );
702
703 if ( isset( $logInfo['id'] ) ) {
704 $revision->setID( $logInfo['id'] );
705 }
706 $revision->setType( $logInfo['type'] );
707 $revision->setAction( $logInfo['action'] );
708 if ( isset( $logInfo['timestamp'] ) ) {
709 $revision->setTimestamp( $logInfo['timestamp'] );
710 }
711 if ( isset( $logInfo['params'] ) ) {
712 $revision->setParams( $logInfo['params'] );
713 }
714 if ( isset( $logInfo['logtitle'] ) ) {
715 // @todo Using Title for non-local titles is a recipe for disaster.
716 // We should use ForeignTitle here instead.
717 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
718 }
719
720 $revision->setNoUpdates( $this->mNoUpdates );
721
722 if ( isset( $logInfo['comment'] ) ) {
723 $revision->setComment( $logInfo['comment'] );
724 }
725
726 if ( isset( $logInfo['contributor']['ip'] ) ) {
727 $revision->setUserIP( $logInfo['contributor']['ip'] );
728 }
729
730 if ( !isset( $logInfo['contributor']['username'] ) ) {
731 $revision->setUsername( $this->externalUserNames->addPrefix( 'Unknown user' ) );
732 } else {
733 $revision->setUsername(
734 $this->externalUserNames->applyPrefix( $logInfo['contributor']['username'] )
735 );
736 }
737
738 return $this->logItemCallback( $revision );
739 }
740
741 /**
742 * @suppress PhanTypeInvalidDimOffset Phan not reading the reference inside the hook
743 */
744 private function handlePage() {
745 // Handle page data.
746 $this->debug( "Enter page handler." );
747 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
748
749 // Fields that can just be stuffed in the pageInfo object
750 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
751
752 $skip = false;
753 $badTitle = false;
754
755 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
756 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
757 $this->reader->localName == 'page' ) {
758 break;
759 }
760
761 $skip = false;
762
763 $tag = $this->reader->localName;
764
765 if ( $badTitle ) {
766 // The title is invalid, bail out of this page
767 $skip = true;
768 } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', [ $this,
769 &$pageInfo ] ) ) {
770 // Do nothing
771 } elseif ( in_array( $tag, $normalFields ) ) {
772 // An XML snippet:
773 // <page>
774 // <id>123</id>
775 // <title>Page</title>
776 // <redirect title="NewTitle"/>
777 // ...
778 // Because the redirect tag is built differently, we need special handling for that case.
779 if ( $tag == 'redirect' ) {
780 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
781 } else {
782 $pageInfo[$tag] = $this->nodeContents();
783 }
784 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
785 if ( !isset( $title ) ) {
786 $title = $this->processTitle( $pageInfo['title'],
787 $pageInfo['ns'] ?? null );
788
789 // $title is either an array of two titles or false.
790 if ( is_array( $title ) ) {
791 $this->pageCallback( $title );
792 list( $pageInfo['_title'], $foreignTitle ) = $title;
793 } else {
794 $badTitle = true;
795 $skip = true;
796 }
797 }
798
799 if ( $title ) {
800 if ( $tag == 'revision' ) {
801 $this->handleRevision( $pageInfo );
802 } else {
803 $this->handleUpload( $pageInfo );
804 }
805 }
806 } elseif ( $tag != '#text' ) {
807 $this->warn( "Unhandled page XML tag $tag" );
808 $skip = true;
809 }
810 }
811
812 // @note $pageInfo is only set if a valid $title is processed above with
813 // no error. If we have a valid $title, then pageCallback is called
814 // above, $pageInfo['title'] is set and we do pageOutCallback here.
815 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
816 // set since they both come from $title above.
817 if ( array_key_exists( '_title', $pageInfo ) ) {
818 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
819 $pageInfo['revisionCount'],
820 $pageInfo['successfulRevisionCount'],
821 $pageInfo );
822 }
823 }
824
825 /**
826 * @param array $pageInfo
827 */
828 private function handleRevision( &$pageInfo ) {
829 $this->debug( "Enter revision handler" );
830 $revisionInfo = [];
831
832 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text', 'sha1' ];
833
834 $skip = false;
835
836 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
837 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
838 $this->reader->localName == 'revision' ) {
839 break;
840 }
841
842 $tag = $this->reader->localName;
843
844 if ( !Hooks::run( 'ImportHandleRevisionXMLTag', [
845 $this, $pageInfo, $revisionInfo
846 ] ) ) {
847 // Do nothing
848 } elseif ( in_array( $tag, $normalFields ) ) {
849 $revisionInfo[$tag] = $this->nodeContents();
850 } elseif ( $tag == 'contributor' ) {
851 $revisionInfo['contributor'] = $this->handleContributor();
852 } elseif ( $tag != '#text' ) {
853 $this->warn( "Unhandled revision XML tag $tag" );
854 $skip = true;
855 }
856 }
857
858 $pageInfo['revisionCount']++;
859 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
860 $pageInfo['successfulRevisionCount']++;
861 }
862 }
863
864 /**
865 * @param array $pageInfo
866 * @param array $revisionInfo
867 * @throws MWException
868 * @return bool|mixed
869 */
870 private function processRevision( $pageInfo, $revisionInfo ) {
871 global $wgMaxArticleSize;
872
873 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
874 // database errors and instability. Testing for revisions with only listed
875 // content models, as other content models might use serialization formats
876 // which aren't checked against $wgMaxArticleSize.
877 if ( ( !isset( $revisionInfo['model'] ) ||
878 in_array( $revisionInfo['model'], [
879 'wikitext',
880 'css',
881 'json',
882 'javascript',
883 'text',
884 ''
885 ] ) ) &&
886 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
887 ) {
888 throw new MWException( 'The text of ' .
889 ( isset( $revisionInfo['id'] ) ?
890 "the revision with ID $revisionInfo[id]" :
891 'a revision'
892 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
893 }
894
895 // FIXME: process schema version 11!
896 $revision = new WikiRevision( $this->config );
897
898 if ( isset( $revisionInfo['id'] ) ) {
899 $revision->setID( $revisionInfo['id'] );
900 }
901 if ( isset( $revisionInfo['model'] ) ) {
902 $revision->setModel( $revisionInfo['model'] );
903 }
904 if ( isset( $revisionInfo['format'] ) ) {
905 $revision->setFormat( $revisionInfo['format'] );
906 }
907 $revision->setTitle( $pageInfo['_title'] );
908
909 if ( isset( $revisionInfo['text'] ) ) {
910 $handler = $revision->getContentHandler();
911 $text = $handler->importTransform(
912 $revisionInfo['text'],
913 $revision->getFormat() );
914
915 $revision->setText( $text );
916 }
917 $revision->setTimestamp( $revisionInfo['timestamp'] ?? wfTimestampNow() );
918
919 if ( isset( $revisionInfo['comment'] ) ) {
920 $revision->setComment( $revisionInfo['comment'] );
921 }
922
923 if ( isset( $revisionInfo['minor'] ) ) {
924 $revision->setMinor( true );
925 }
926 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
927 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
928 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
929 $revision->setUsername(
930 $this->externalUserNames->applyPrefix( $revisionInfo['contributor']['username'] )
931 );
932 } else {
933 $revision->setUsername( $this->externalUserNames->addPrefix( 'Unknown user' ) );
934 }
935 if ( isset( $revisionInfo['sha1'] ) ) {
936 $revision->setSha1Base36( $revisionInfo['sha1'] );
937 }
938 $revision->setNoUpdates( $this->mNoUpdates );
939
940 return $this->revisionCallback( $revision );
941 }
942
943 /**
944 * @param array $pageInfo
945 * @return mixed
946 */
947 private function handleUpload( &$pageInfo ) {
948 $this->debug( "Enter upload handler" );
949 $uploadInfo = [];
950
951 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
952 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
953
954 $skip = false;
955
956 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
957 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
958 $this->reader->localName == 'upload' ) {
959 break;
960 }
961
962 $tag = $this->reader->localName;
963
964 if ( !Hooks::run( 'ImportHandleUploadXMLTag', [
965 $this, $pageInfo
966 ] ) ) {
967 // Do nothing
968 } elseif ( in_array( $tag, $normalFields ) ) {
969 $uploadInfo[$tag] = $this->nodeContents();
970 } elseif ( $tag == 'contributor' ) {
971 $uploadInfo['contributor'] = $this->handleContributor();
972 } elseif ( $tag == 'contents' ) {
973 $contents = $this->nodeContents();
974 $encoding = $this->reader->getAttribute( 'encoding' );
975 if ( $encoding === 'base64' ) {
976 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
977 $uploadInfo['isTempSrc'] = true;
978 }
979 } elseif ( $tag != '#text' ) {
980 $this->warn( "Unhandled upload XML tag $tag" );
981 $skip = true;
982 }
983 }
984
985 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
986 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
987 if ( file_exists( $path ) ) {
988 $uploadInfo['fileSrc'] = $path;
989 $uploadInfo['isTempSrc'] = false;
990 }
991 }
992
993 if ( $this->mImportUploads ) {
994 return $this->processUpload( $pageInfo, $uploadInfo );
995 }
996 }
997
998 /**
999 * @param string $contents
1000 * @return string
1001 */
1002 private function dumpTemp( $contents ) {
1003 $filename = tempnam( wfTempDir(), 'importupload' );
1004 file_put_contents( $filename, $contents );
1005 return $filename;
1006 }
1007
1008 /**
1009 * @param array $pageInfo
1010 * @param array $uploadInfo
1011 * @return mixed
1012 */
1013 private function processUpload( $pageInfo, $uploadInfo ) {
1014 $revision = new WikiRevision( $this->config );
1015 $text = $uploadInfo['text'] ?? '';
1016
1017 $revision->setTitle( $pageInfo['_title'] );
1018 $revision->setID( $pageInfo['id'] );
1019 $revision->setTimestamp( $uploadInfo['timestamp'] );
1020 $revision->setText( $text );
1021 $revision->setFilename( $uploadInfo['filename'] );
1022 if ( isset( $uploadInfo['archivename'] ) ) {
1023 $revision->setArchiveName( $uploadInfo['archivename'] );
1024 }
1025 $revision->setSrc( $uploadInfo['src'] );
1026 if ( isset( $uploadInfo['fileSrc'] ) ) {
1027 $revision->setFileSrc( $uploadInfo['fileSrc'],
1028 !empty( $uploadInfo['isTempSrc'] ) );
1029 }
1030 if ( isset( $uploadInfo['sha1base36'] ) ) {
1031 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1032 }
1033 $revision->setSize( intval( $uploadInfo['size'] ) );
1034 $revision->setComment( $uploadInfo['comment'] );
1035
1036 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1037 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1038 }
1039 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1040 $revision->setUsername(
1041 $this->externalUserNames->applyPrefix( $uploadInfo['contributor']['username'] )
1042 );
1043 }
1044 $revision->setNoUpdates( $this->mNoUpdates );
1045
1046 return call_user_func( $this->mUploadCallback, $revision );
1047 }
1048
1049 /**
1050 * @return array
1051 */
1052 private function handleContributor() {
1053 $fields = [ 'id', 'ip', 'username' ];
1054 $info = [];
1055
1056 if ( $this->reader->isEmptyElement ) {
1057 return $info;
1058 }
1059 while ( $this->reader->read() ) {
1060 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
1061 $this->reader->localName == 'contributor' ) {
1062 break;
1063 }
1064
1065 $tag = $this->reader->localName;
1066
1067 if ( in_array( $tag, $fields ) ) {
1068 $info[$tag] = $this->nodeContents();
1069 }
1070 }
1071
1072 return $info;
1073 }
1074
1075 /**
1076 * @param string $text
1077 * @param string|null $ns
1078 * @return array|bool
1079 */
1080 private function processTitle( $text, $ns = null ) {
1081 if ( is_null( $this->foreignNamespaces ) ) {
1082 $foreignTitleFactory = new NaiveForeignTitleFactory();
1083 } else {
1084 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1085 $this->foreignNamespaces );
1086 }
1087
1088 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1089 intval( $ns ) );
1090
1091 $title = $this->importTitleFactory->createTitleFromForeignTitle(
1092 $foreignTitle );
1093
1094 $commandLineMode = $this->config->get( 'CommandLineMode' );
1095 if ( is_null( $title ) ) {
1096 # Invalid page title? Ignore the page
1097 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1098 return false;
1099 } elseif ( $title->isExternal() ) {
1100 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1101 return false;
1102 } elseif ( !$title->canExist() ) {
1103 $this->notice( 'import-error-special', $title->getPrefixedText() );
1104 return false;
1105 } elseif ( !$commandLineMode ) {
1106 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
1107 $user = RequestContext::getMain()->getUser();
1108
1109 if ( !$permissionManager->userCan( 'edit', $user, $title ) ) {
1110 # Do not import if the importing wiki user cannot edit this page
1111 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1112
1113 return false;
1114 }
1115
1116 if ( !$title->exists() && !$permissionManager->userCan( 'create', $user, $title ) ) {
1117 # Do not import if the importing wiki user cannot create this page
1118 $this->notice( 'import-error-create', $title->getPrefixedText() );
1119
1120 return false;
1121 }
1122 }
1123
1124 return [ $title, $foreignTitle ];
1125 }
1126 }