Debian Codegraph @

includes/import/WikiImporter.php

raw symbols SCIP
1 <?php
2 /**
3 * MediaWiki page data importer.
4 *
5 * Copyright © 2003,2005 Brooke Vibber <[email protected]>
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\Cache\CacheKeyHelper;
28 use MediaWiki\Config\Config;
29 use MediaWiki\Content\Content;
30 use MediaWiki\Content\IContentHandlerFactory;
31 use MediaWiki\Deferred\DeferredUpdates;
32 use MediaWiki\Deferred\SiteStatsUpdate;
33 use MediaWiki\HookContainer\HookContainer;
34 use MediaWiki\HookContainer\HookRunner;
35 use MediaWiki\Language\Language;
36 use MediaWiki\MainConfigNames;
37 use MediaWiki\Page\PageIdentity;
38 use MediaWiki\Page\WikiPageFactory;
39 use MediaWiki\Permissions\Authority;
40 use MediaWiki\Revision\SlotRecord;
41 use MediaWiki\Revision\SlotRoleRegistry;
42 use MediaWiki\Status\Status;
43 use MediaWiki\Title\ForeignTitle;
44 use MediaWiki\Title\ImportTitleFactory;
45 use MediaWiki\Title\NaiveForeignTitleFactory;
46 use MediaWiki\Title\NaiveImportTitleFactory;
47 use MediaWiki\Title\NamespaceAwareForeignTitleFactory;
48 use MediaWiki\Title\NamespaceImportTitleFactory;
49 use MediaWiki\Title\NamespaceInfo;
50 use MediaWiki\Title\SubpageImportTitleFactory;
51 use MediaWiki\Title\Title;
52 use MediaWiki\Title\TitleFactory;
53 use MediaWiki\User\ExternalUserNames;
54 use Wikimedia\AtEase\AtEase;
55 use Wikimedia\Message\MessageValue;
56 use Wikimedia\NormalizedException\NormalizedException;
57 use Wikimedia\Rdbms\IDBAccessObject;
58
59 /**
60 * XML file reader for the page data importer.
61 *
62 * implements Special:Import
63 * @ingroup SpecialPage
64 */
65 class WikiImporter {
66 /** @var XMLReader|null */
67 private $reader;
68
69 /** @var string */
70 private $sourceAdapterId;
71
72 /** @var array|null */
73 private $foreignNamespaces = null;
74
75 /** @var callable */
76 private $mLogItemCallback;
77
78 /** @var callable */
79 private $mUploadCallback;
80
81 /** @var callable|null */
82 private $mRevisionCallback;
83
84 /** @var callable|null */
85 private $mPageCallback;
86
87 /** @var callable|null */
88 private $mSiteInfoCallback;
89
90 /** @var callable|null */
91 private $mPageOutCallback;
92
93 /** @var callable|null */
94 private $mNoticeCallback;
95
96 /** @var bool|null */
97 private $mDebug;
98
99 /** @var bool|null */
100 private $mImportUploads;
101
102 /** @var string|null */
103 private $mImageBasePath;
104
105 /** @var bool */
106 private $mNoUpdates = false;
107
108 /** @var int */
109 private $pageOffset = 0;
110
111 private ImportTitleFactory $importTitleFactory;
112 private ExternalUserNames $externalUserNames;
113
114 /** @var array */
115 private $countableCache = [];
116
117 /** @var bool */
118 private $disableStatisticsUpdate = false;
119
120 /**
121 * Authority used for permission checks only (to ensure that the user performing the import is
122 * allowed to edit the pages they're importing). To skip the checks, use UltimateAuthority.
123 *
124 * If you want to also log the import actions, see ImportReporter.
125 */
126 private Authority $performer;
127
128 private Config $config;
129 private HookRunner $hookRunner;
130 private Language $contentLanguage;
131 private NamespaceInfo $namespaceInfo;
132 private TitleFactory $titleFactory;
133 private WikiPageFactory $wikiPageFactory;
134 private UploadRevisionImporter $uploadRevisionImporter;
135 private IContentHandlerFactory $contentHandlerFactory;
136 private SlotRoleRegistry $slotRoleRegistry;
137
138 /**
139 * Creates an ImportXMLReader drawing from the source provided
140 */
141 public function __construct(
142 ImportSource $source,
143 Authority $performer,
144 Config $config,
145 HookContainer $hookContainer,
146 Language $contentLanguage,
147 NamespaceInfo $namespaceInfo,
148 TitleFactory $titleFactory,
149 WikiPageFactory $wikiPageFactory,
150 UploadRevisionImporter $uploadRevisionImporter,
151 IContentHandlerFactory $contentHandlerFactory,
152 SlotRoleRegistry $slotRoleRegistry
153 ) {
154 $this->performer = $performer;
155 $this->config = $config;
156 $this->hookRunner = new HookRunner( $hookContainer );
157 $this->contentLanguage = $contentLanguage;
158 $this->namespaceInfo = $namespaceInfo;
159 $this->titleFactory = $titleFactory;
160 $this->wikiPageFactory = $wikiPageFactory;
161 $this->uploadRevisionImporter = $uploadRevisionImporter;
162 $this->contentHandlerFactory = $contentHandlerFactory;
163 $this->slotRoleRegistry = $slotRoleRegistry;
164
165 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
166 stream_wrapper_register( 'uploadsource', UploadSourceAdapter::class );
167 }
168 $this->sourceAdapterId = UploadSourceAdapter::registerSource( $source );
169
170 $this->openReader();
171
172 // Default callbacks
173 $this->setPageCallback( [ $this, 'beforeImportPage' ] );
174 $this->setRevisionCallback( [ $this, "importRevision" ] );
175 $this->setUploadCallback( [ $this, 'importUpload' ] );
176 $this->setLogItemCallback( [ $this, 'importLogItem' ] );
177 $this->setPageOutCallback( [ $this, 'finishImportPage' ] );
178
179 $this->importTitleFactory = new NaiveImportTitleFactory(
180 $this->contentLanguage,
181 $this->namespaceInfo,
182 $this->titleFactory
183 );
184 $this->externalUserNames = new ExternalUserNames( 'imported', false );
185 }
186
187 /**
188 * @return null|XMLReader
189 */
190 public function getReader() {
191 return $this->reader;
192 }
193
194 /**
195 * @param string $err
196 */
197 public function throwXmlError( $err ) {
198 $this->debug( "FAILURE: $err" );
199 wfDebug( "WikiImporter XML error: $err" );
200 }
201
202 /**
203 * @param string $data
204 */
205 public function debug( $data ) {
206 if ( $this->mDebug ) {
207 wfDebug( "IMPORT: $data" );
208 }
209 }
210
211 /**
212 * @param string $data
213 */
214 public function warn( $data ) {
215 wfDebug( "IMPORT: $data" );
216 }
217
218 /**
219 * @param string $msg
220 * @param mixed ...$params
221 */
222 public function notice( $msg, ...$params ) {
223 if ( is_callable( $this->mNoticeCallback ) ) {
224 call_user_func( $this->mNoticeCallback, $msg, $params );
225 } else { # No ImportReporter -> CLI
226 // T177997: the command line importers should call setNoticeCallback()
227 // for their own custom callback to echo the notice
228 wfDebug( wfMessage( $msg, $params )->text() );
229 }
230 }
231
232 /**
233 * Set debug mode...
234 * @param bool $debug
235 */
236 public function setDebug( $debug ) {
237 $this->mDebug = $debug;
238 }
239
240 /**
241 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
242 * @param bool $noupdates
243 */
244 public function setNoUpdates( $noupdates ) {
245 $this->mNoUpdates = $noupdates;
246 }
247
248 /**
249 * Sets 'pageOffset' value. So it will skip the first n-1 pages
250 * and start from the nth page. It's 1-based indexing.
251 * @param int $nthPage
252 * @since 1.29
253 */
254 public function setPageOffset( $nthPage ) {
255 $this->pageOffset = $nthPage;
256 }
257
258 /**
259 * Set a callback that displays notice messages
260 *
261 * @param callable $callback
262 * @return callable
263 */
264 public function setNoticeCallback( $callback ) {
265 return wfSetVar( $this->mNoticeCallback, $callback );
266 }
267
268 /**
269 * Sets the action to perform as each new page in the stream is reached.
270 * @param callable|null $callback
271 * @return callable|null
272 */
273 public function setPageCallback( $callback ) {
274 $previous = $this->mPageCallback;
275 $this->mPageCallback = $callback;
276 return $previous;
277 }
278
279 /**
280 * Sets the action to perform as each page in the stream is completed.
281 * Callback accepts the page title (as a Title object), a second object
282 * with the original title form (in case it's been overridden into a
283 * local namespace), and a count of revisions.
284 *
285 * @param callable|null $callback
286 * @return callable|null
287 */
288 public function setPageOutCallback( $callback ) {
289 $previous = $this->mPageOutCallback;
290 $this->mPageOutCallback = $callback;
291 return $previous;
292 }
293
294 /**
295 * Sets the action to perform as each page revision is reached.
296 * @param callable|null $callback
297 * @return callable|null
298 */
299 public function setRevisionCallback( $callback ) {
300 $previous = $this->mRevisionCallback;
301 $this->mRevisionCallback = $callback;
302 return $previous;
303 }
304
305 /**
306 * Sets the action to perform as each file upload version is reached.
307 * @param callable $callback
308 * @return callable
309 */
310 public function setUploadCallback( $callback ) {
311 $previous = $this->mUploadCallback;
312 $this->mUploadCallback = $callback;
313 return $previous;
314 }
315
316 /**
317 * Sets the action to perform as each log item reached.
318 * @param callable $callback
319 * @return callable
320 */
321 public function setLogItemCallback( $callback ) {
322 $previous = $this->mLogItemCallback;
323 $this->mLogItemCallback = $callback;
324 return $previous;
325 }
326
327 /**
328 * Sets the action to perform when site info is encountered
329 * @param callable $callback
330 * @return callable
331 */
332 public function setSiteInfoCallback( $callback ) {
333 $previous = $this->mSiteInfoCallback;
334 $this->mSiteInfoCallback = $callback;
335 return $previous;
336 }
337
338 /**
339 * Sets the factory object to use to convert ForeignTitle objects into local
340 * Title objects
341 * @param ImportTitleFactory $factory
342 */
343 public function setImportTitleFactory( $factory ) {
344 $this->importTitleFactory = $factory;
345 }
346
347 /**
348 * Set a target namespace to override the defaults
349 * @param null|int $namespace
350 * @return bool
351 */
352 public function setTargetNamespace( $namespace ) {
353 if ( $namespace === null ) {
354 // Don't override namespaces
355 $this->setImportTitleFactory(
356 new NaiveImportTitleFactory(
357 $this->contentLanguage,
358 $this->namespaceInfo,
359 $this->titleFactory
360 )
361 );
362 return true;
363 } elseif (
364 $namespace >= 0 &&
365 $this->namespaceInfo->exists( intval( $namespace ) )
366 ) {
367 $namespace = intval( $namespace );
368 $this->setImportTitleFactory(
369 new NamespaceImportTitleFactory(
370 $this->namespaceInfo,
371 $this->titleFactory,
372 $namespace
373 )
374 );
375 return true;
376 } else {
377 return false;
378 }
379 }
380
381 /**
382 * Set a target root page under which all pages are imported
383 * @param null|string $rootpage
384 * @return Status
385 */
386 public function setTargetRootPage( $rootpage ) {
387 $status = Status::newGood();
388 $nsInfo = $this->namespaceInfo;
389 if ( $rootpage === null ) {
390 // No rootpage
391 $this->setImportTitleFactory(
392 new NaiveImportTitleFactory(
393 $this->contentLanguage,
394 $nsInfo,
395 $this->titleFactory
396 )
397 );
398 } elseif ( $rootpage !== '' ) {
399 $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
400 $title = Title::newFromText( $rootpage );
401
402 if ( !$title || $title->isExternal() ) {
403 $status->fatal( 'import-rootpage-invalid' );
404 } elseif ( !$nsInfo->hasSubpages( $title->getNamespace() ) ) {
405 $displayNSText = $title->getNamespace() === NS_MAIN
406 ? wfMessage( 'blanknamespace' )->text()
407 : $this->contentLanguage->getNsText( $title->getNamespace() );
408 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
409 } else {
410 // set namespace to 'all', so the namespace check in processTitle() can pass
411 $this->setTargetNamespace( null );
412 $this->setImportTitleFactory(
413 new SubpageImportTitleFactory(
414 $nsInfo,
415 $this->titleFactory,
416 $title
417 )
418 );
419 }
420 }
421 return $status;
422 }
423
424 /**
425 * @param string $dir
426 */
427 public function setImageBasePath( $dir ) {
428 $this->mImageBasePath = $dir;
429 }
430
431 /**
432 * @param bool $import
433 */
434 public function setImportUploads( $import ) {
435 $this->mImportUploads = $import;
436 }
437
438 /**
439 * @since 1.31
440 * @param string $usernamePrefix Prefix to apply to unknown (and possibly also known) usernames
441 * @param bool $assignKnownUsers Whether to apply the prefix to usernames that exist locally
442 */
443 public function setUsernamePrefix( $usernamePrefix, $assignKnownUsers ) {
444 $this->externalUserNames = new ExternalUserNames( $usernamePrefix, $assignKnownUsers );
445 }
446
447 /**
448 * Statistics update can cause a lot of time
449 * @since 1.29
450 */
451 public function disableStatisticsUpdate() {
452 $this->disableStatisticsUpdate = true;
453 }
454
455 /**
456 * Default per-page callback. Sets up some things related to site statistics
457 * @param array $titleAndForeignTitle Two-element array, with Title object at
458 * index 0 and ForeignTitle object at index 1
459 * @return bool
460 */
461 public function beforeImportPage( $titleAndForeignTitle ) {
462 $title = $titleAndForeignTitle[0];
463 $page = $this->wikiPageFactory->newFromTitle( $title );
464 $this->countableCache['title_' . $title->getPrefixedText()] = $page->isCountable();
465 return true;
466 }
467
468 /**
469 * Default per-revision callback, performs the import.
470 * @param WikiRevision $revision
471 * @return bool
472 */
473 public function importRevision( $revision ) {
474 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
475 $this->notice( 'import-error-bad-location',
476 $revision->getTitle()->getPrefixedText(),
477 $revision->getID(),
478 $revision->getModel(),
479 $revision->getFormat()
480 );
481
482 return false;
483 }
484
485 try {
486 return $revision->importOldRevision();
487 } catch ( MWContentSerializationException $ex ) {
488 $this->notice( 'import-error-unserialize',
489 $revision->getTitle()->getPrefixedText(),
490 $revision->getID(),
491 $revision->getModel(),
492 $revision->getFormat()
493 );
494 }
495
496 return false;
497 }
498
499 /**
500 * Default per-revision callback, performs the import.
501 * @param WikiRevision $revision
502 * @return bool
503 */
504 public function importLogItem( $revision ) {
505 return $revision->importLogItem();
506 }
507
508 /**
509 * Dummy for now...
510 * @param WikiRevision $revision
511 * @return bool
512 */
513 public function importUpload( $revision ) {
514 $status = $this->uploadRevisionImporter->import( $revision );
515 return $status->isGood();
516 }
517
518 /**
519 * Mostly for hook use
520 * @param PageIdentity $pageIdentity
521 * @param ForeignTitle $foreignTitle
522 * @param int $revCount
523 * @param int $sRevCount
524 * @param array $pageInfo
525 * @return bool
526 */
527 public function finishImportPage( PageIdentity $pageIdentity, $foreignTitle, $revCount,
528 $sRevCount, $pageInfo
529 ) {
530 // Update article count statistics (T42009)
531 // The normal counting logic in WikiPage->doEditUpdates() is designed for
532 // one-revision-at-a-time editing, not bulk imports. In this situation it
533 // suffers from issues of replica DB lag. We let WikiPage handle the total page
534 // and revision count, and we implement our own custom logic for the
535 // article (content page) count.
536 if ( !$this->disableStatisticsUpdate ) {
537 $page = $this->wikiPageFactory->newFromTitle( $pageIdentity );
538
539 $page->loadPageData( IDBAccessObject::READ_LATEST );
540 $rev = $page->getRevisionRecord();
541 if ( $rev === null ) {
542
543 wfDebug( __METHOD__ . ': Skipping article count adjustment for ' . $pageIdentity .
544 ' because WikiPage::getRevisionRecord() returned null' );
545 } else {
546 $update = $page->newPageUpdater( $this->performer )->prepareUpdate();
547 $countKey = 'title_' . CacheKeyHelper::getKeyForPage( $pageIdentity );
548 $countable = $update->isCountable();
549 if ( array_key_exists( $countKey, $this->countableCache ) &&
550 $countable != $this->countableCache[$countKey] ) {
551 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [
552 'articles' => ( (int)$countable - (int)$this->countableCache[$countKey] )
553 ] ) );
554 }
555 }
556 }
557
558 $title = Title::newFromPageIdentity( $pageIdentity );
559 return $this->hookRunner->onAfterImportPage( $title, $foreignTitle,
560 $revCount, $sRevCount, $pageInfo );
561 }
562
563 /**
564 * Notify the callback function of site info
565 * @param array $siteInfo
566 * @return mixed|false
567 */
568 private function siteInfoCallback( $siteInfo ) {
569 if ( isset( $this->mSiteInfoCallback ) ) {
570 return call_user_func_array(
571 $this->mSiteInfoCallback,
572 [ $siteInfo, $this ]
573 );
574 } else {
575 return false;
576 }
577 }
578
579 /**
580 * Notify the callback function when a new "<page>" is reached.
581 * @param array $title
582 */
583 public function pageCallback( $title ) {
584 if ( isset( $this->mPageCallback ) ) {
585 call_user_func( $this->mPageCallback, $title );
586 }
587 }
588
589 /**
590 * Notify the callback function when a "</page>" is closed.
591 * @param PageIdentity $pageIdentity
592 * @param ForeignTitle $foreignTitle
593 * @param int $revCount
594 * @param int $sucCount Number of revisions for which callback returned true
595 * @param array $pageInfo Associative array of page information
596 */
597 private function pageOutCallback( PageIdentity $pageIdentity, $foreignTitle, $revCount,
598 $sucCount, $pageInfo ) {
599 if ( isset( $this->mPageOutCallback ) ) {
600 call_user_func_array( $this->mPageOutCallback, func_get_args() );
601 }
602 }
603
604 /**
605 * Notify the callback function of a revision
606 * @param WikiRevision $revision
607 * @return bool|mixed
608 */
609 private function revisionCallback( $revision ) {
610 if ( isset( $this->mRevisionCallback ) ) {
611 return call_user_func_array(
612 $this->mRevisionCallback,
613 [ $revision, $this ]
614 );
615 } else {
616 return false;
617 }
618 }
619
620 /**
621 * Notify the callback function of a new log item
622 * @param WikiRevision $revision
623 * @return mixed|false
624 */
625 private function logItemCallback( $revision ) {
626 if ( isset( $this->mLogItemCallback ) ) {
627 return call_user_func_array(
628 $this->mLogItemCallback,
629 [ $revision, $this ]
630 );
631 } else {
632 return false;
633 }
634 }
635
636 /**
637 * Retrieves the contents of the named attribute of the current element.
638 * @param string $attr The name of the attribute
639 * @return string The value of the attribute or an empty string if it is not set in the current
640 * element.
641 */
642 public function nodeAttribute( $attr ) {
643 return $this->reader->getAttribute( $attr ) ?? '';
644 }
645
646 /**
647 * Shouldn't something like this be built-in to XMLReader?
648 * Fetches text contents of the current element, assuming
649 * no sub-elements or such scary things.
650 * @return string
651 * @internal
652 */
653 public function nodeContents() {
654 if ( $this->reader->isEmptyElement ) {
655 return "";
656 }
657 $buffer = "";
658 while ( $this->reader->read() ) {
659 switch ( $this->reader->nodeType ) {
660 case XMLReader::TEXT:
661 case XMLReader::CDATA:
662 case XMLReader::SIGNIFICANT_WHITESPACE:
663 $buffer .= $this->reader->value;
664 break;
665 case XMLReader::END_ELEMENT:
666 return $buffer;
667 }
668 }
669
670 $this->reader->close();
671 return '';
672 }
673
674 /**
675 * Primary entry point
676 * @throws Exception
677 * @return bool
678 */
679 public function doImport() {
680 $this->syntaxCheckXML();
681
682 // Calls to reader->read need to be wrapped in calls to
683 // libxml_disable_entity_loader() to avoid local file
684 // inclusion attacks (T48932).
685 // phpcs:ignore Generic.PHP.NoSilencedErrors -- suppress deprecation per T268847
686 $oldDisable = @libxml_disable_entity_loader( true );
687 try {
688 $this->reader->read();
689
690 if ( $this->reader->localName != 'mediawiki' ) {
691 // phpcs:ignore Generic.PHP.NoSilencedErrors
692 @libxml_disable_entity_loader( $oldDisable );
693 $error = libxml_get_last_error();
694 if ( $error ) {
695 throw new NormalizedException( "XML error at line {line}: {message}", [
696 'line' => $error->line,
697 'message' => $error->message,
698 ] );
699 } else {
700 throw new UnexpectedValueException(
701 "Expected '<mediawiki>' tag, got '<{$this->reader->localName}>' tag."
702 );
703 }
704 }
705 $this->debug( "<mediawiki> tag is correct." );
706
707 $this->debug( "Starting primary dump processing loop." );
708
709 $keepReading = $this->reader->read();
710 $skip = false;
711 $pageCount = 0;
712 while ( $keepReading ) {
713 $tag = $this->reader->localName;
714 if ( $this->pageOffset ) {
715 if ( $tag === 'page' ) {
716 $pageCount++;
717 }
718 if ( $pageCount < $this->pageOffset ) {
719 $keepReading = $this->reader->next();
720 continue;
721 }
722 }
723 $type = $this->reader->nodeType;
724
725 if ( !$this->hookRunner->onImportHandleToplevelXMLTag( $this ) ) {
726 // Do nothing
727 } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
728 break;
729 } elseif ( $tag == 'siteinfo' ) {
730 $this->handleSiteInfo();
731 } elseif ( $tag == 'page' ) {
732 $this->handlePage();
733 } elseif ( $tag == 'logitem' ) {
734 $this->handleLogItem();
735 } elseif ( $tag != '#text' ) {
736 $this->warn( "Unhandled top-level XML tag $tag" );
737
738 $skip = true;
739 }
740
741 if ( $skip ) {
742 $keepReading = $this->reader->next();
743 $skip = false;
744 $this->debug( "Skip" );
745 } else {
746 $keepReading = $this->reader->read();
747 }
748 }
749 } finally {
750 // phpcs:ignore Generic.PHP.NoSilencedErrors
751 @libxml_disable_entity_loader( $oldDisable );
752 $this->reader->close();
753 }
754
755 return true;
756 }
757
758 private function handleSiteInfo() {
759 $this->debug( "Enter site info handler." );
760 $siteInfo = [];
761
762 // Fields that can just be stuffed in the siteInfo object
763 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
764
765 while ( $this->reader->read() ) {
766 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
767 $this->reader->localName == 'siteinfo' ) {
768 break;
769 }
770
771 $tag = $this->reader->localName;
772
773 if ( $tag == 'namespace' ) {
774 $this->foreignNamespaces[$this->nodeAttribute( 'key' )] =
775 $this->nodeContents();
776 } elseif ( in_array( $tag, $normalFields ) ) {
777 $siteInfo[$tag] = $this->nodeContents();
778 }
779 }
780
781 $siteInfo['_namespaces'] = $this->foreignNamespaces;
782 $this->siteInfoCallback( $siteInfo );
783 }
784
785 private function handleLogItem() {
786 $this->debug( "Enter log item handler." );
787 $logInfo = [];
788
789 // Fields that can just be stuffed in the pageInfo object
790 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
791 'logtitle', 'params' ];
792
793 while ( $this->reader->read() ) {
794 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
795 $this->reader->localName == 'logitem' ) {
796 break;
797 }
798
799 $tag = $this->reader->localName;
800
801 if ( !$this->hookRunner->onImportHandleLogItemXMLTag( $this, $logInfo ) ) {
802 // Do nothing
803 } elseif ( in_array( $tag, $normalFields ) ) {
804 $logInfo[$tag] = $this->nodeContents();
805 } elseif ( $tag == 'contributor' ) {
806 $logInfo['contributor'] = $this->handleContributor();
807 } elseif ( $tag != '#text' ) {
808 $this->warn( "Unhandled log-item XML tag $tag" );
809 }
810 }
811
812 $this->processLogItem( $logInfo );
813 }
814
815 /**
816 * @param array $logInfo
817 * @return mixed|false
818 */
819 private function processLogItem( $logInfo ) {
820 if ( !$this->performer->authorizeAction( 'logentryimport' ) ) {
821 $this->notice( 'permissionserrorstext-withaction-noreason', MessageValue::new( 'action-logentryimport' ) );
822 return false;
823 }
824
825 $revision = new WikiRevision();
826
827 if ( isset( $logInfo['id'] ) ) {
828 $revision->setID( $logInfo['id'] );
829 }
830 $revision->setType( $logInfo['type'] );
831 $revision->setAction( $logInfo['action'] );
832 if ( isset( $logInfo['timestamp'] ) ) {
833 $revision->setTimestamp( $logInfo['timestamp'] );
834 }
835 if ( isset( $logInfo['params'] ) ) {
836 $revision->setParams( $logInfo['params'] );
837 }
838 if ( isset( $logInfo['logtitle'] ) ) {
839 // @todo Using Title for non-local titles is a recipe for disaster.
840 // We should use ForeignTitle here instead.
841 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
842 }
843
844 $revision->setNoUpdates( $this->mNoUpdates );
845
846 if ( isset( $logInfo['comment'] ) ) {
847 $revision->setComment( $logInfo['comment'] );
848 }
849
850 if ( isset( $logInfo['contributor']['username'] ) ) {
851 $revision->setUsername(
852 $this->externalUserNames->applyPrefix( $logInfo['contributor']['username'] )
853 );
854 } elseif ( isset( $logInfo['contributor']['ip'] ) ) {
855 $revision->setUserIP( $logInfo['contributor']['ip'] );
856 } else {
857 $revision->setUsername( $this->externalUserNames->addPrefix( 'Unknown user' ) );
858 }
859
860 return $this->logItemCallback( $revision );
861 }
862
863 private function handlePage() {
864 // Handle page data.
865 $this->debug( "Enter page handler." );
866 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
867
868 // Fields that can just be stuffed in the pageInfo object
869 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
870
871 $skip = false;
872 $badTitle = false;
873
874 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
875 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
876 $this->reader->localName == 'page' ) {
877 break;
878 }
879
880 $skip = false;
881
882 $tag = $this->reader->localName;
883
884 if ( $badTitle ) {
885 // The title is invalid, bail out of this page
886 $skip = true;
887 } elseif ( !$this->hookRunner->onImportHandlePageXMLTag( $this, $pageInfo ) ) {
888 // Do nothing
889 } elseif ( in_array( $tag, $normalFields ) ) {
890 // An XML snippet:
891 // <page>
892 // <id>123</id>
893 // <title>Page</title>
894 // <redirect title="NewTitle"/>
895 // ...
896 // Because the redirect tag is built differently, we need special handling for that case.
897 if ( $tag == 'redirect' ) {
898 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
899 } else {
900 $pageInfo[$tag] = $this->nodeContents();
901 }
902 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
903 if ( !isset( $title ) ) {
904 $title = $this->processTitle( $pageInfo['title'],
905 $pageInfo['ns'] ?? null );
906
907 // $title is either an array of two titles or false.
908 if ( is_array( $title ) ) {
909 $this->pageCallback( $title );
910 [ $pageInfo['_title'], $foreignTitle ] = $title;
911 } else {
912 $badTitle = true;
913 $skip = true;
914 }
915 }
916
917 if ( $title ) {
918 if ( $tag == 'revision' ) {
919 $this->handleRevision( $pageInfo );
920 } else {
921 $this->handleUpload( $pageInfo );
922 }
923 }
924 } elseif ( $tag != '#text' ) {
925 $this->warn( "Unhandled page XML tag $tag" );
926 $skip = true;
927 }
928 }
929
930 // @note $pageInfo is only set if a valid $title is processed above with
931 // no error. If we have a valid $title, then pageCallback is called
932 // above, $pageInfo['title'] is set and we do pageOutCallback here.
933 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
934 // set since they both come from $title above.
935 if ( array_key_exists( '_title', $pageInfo ) ) {
936 /** @var Title $title */
937 $title = $pageInfo['_title'];
938 $this->pageOutCallback(
939 $title,
940 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable Set together with _title key
941 $foreignTitle,
942 $pageInfo['revisionCount'],
943 $pageInfo['successfulRevisionCount'],
944 $pageInfo
945 );
946 }
947 }
948
949 /**
950 * @param array &$pageInfo
951 */
952 private function handleRevision( &$pageInfo ) {
953 $this->debug( "Enter revision handler" );
954 $revisionInfo = [];
955
956 $normalFields = [ 'id', 'parentid', 'timestamp', 'comment', 'minor', 'origin',
957 'model', 'format', 'text', 'sha1' ];
958
959 $skip = false;
960
961 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
962 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
963 $this->reader->localName == 'revision' ) {
964 break;
965 }
966
967 $tag = $this->reader->localName;
968
969 if ( !$this->hookRunner->onImportHandleRevisionXMLTag(
970 $this, $pageInfo, $revisionInfo )
971 ) {
972 // Do nothing
973 } elseif ( in_array( $tag, $normalFields ) ) {
974 $revisionInfo[$tag] = $this->nodeContents();
975 } elseif ( $tag == 'content' ) {
976 // We can have multiple content tags, so make this an array.
977 $revisionInfo[$tag][] = $this->handleContent();
978 } elseif ( $tag == 'contributor' ) {
979 $revisionInfo['contributor'] = $this->handleContributor();
980 } elseif ( $tag != '#text' ) {
981 $this->warn( "Unhandled revision XML tag $tag" );
982 $skip = true;
983 }
984 }
985
986 $pageInfo['revisionCount']++;
987 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
988 $pageInfo['successfulRevisionCount']++;
989 }
990 }
991
992 private function handleContent() {
993 $this->debug( "Enter content handler" );
994 $contentInfo = [];
995
996 $normalFields = [ 'role', 'origin', 'model', 'format', 'text' ];
997
998 $skip = false;
999
1000 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
1001 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
1002 $this->reader->localName == 'content' ) {
1003 break;
1004 }
1005
1006 $tag = $this->reader->localName;
1007
1008 if ( !$this->hookRunner->onImportHandleContentXMLTag(
1009 $this, $contentInfo )
1010 ) {
1011 // Do nothing
1012 } elseif ( in_array( $tag, $normalFields ) ) {
1013 $contentInfo[$tag] = $this->nodeContents();
1014 } elseif ( $tag != '#text' ) {
1015 $this->warn( "Unhandled content XML tag $tag" );
1016 $skip = true;
1017 }
1018 }
1019
1020 return $contentInfo;
1021 }
1022
1023 /**
1024 * @param PageIdentity $page
1025 * @param int $revisionId
1026 * @param array $contentInfo
1027 *
1028 * @return Content
1029 */
1030 private function makeContent( PageIdentity $page, $revisionId, $contentInfo ) {
1031 $maxArticleSize = $this->config->get( MainConfigNames::MaxArticleSize );
1032
1033 if ( !isset( $contentInfo['text'] ) ) {
1034 throw new InvalidArgumentException( 'Missing text field in import.' );
1035 }
1036
1037 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
1038 // database errors and instability. Testing for revisions with only listed
1039 // content models, as other content models might use serialization formats
1040 // which aren't checked against $wgMaxArticleSize.
1041 if ( ( !isset( $contentInfo['model'] ) ||
1042 in_array( $contentInfo['model'], [
1043 'wikitext',
1044 'css',
1045 'json',
1046 'javascript',
1047 'text',
1048 ''
1049 ] ) ) &&
1050 strlen( $contentInfo['text'] ) > $maxArticleSize * 1024
1051 ) {
1052 throw new RuntimeException( 'The text of ' .
1053 ( $revisionId ?
1054 "the revision with ID $revisionId" :
1055 'a revision'
1056 ) . " exceeds the maximum allowable size ({$maxArticleSize} KiB)" );
1057 }
1058
1059 $role = $contentInfo['role'] ?? SlotRecord::MAIN;
1060 $model = $contentInfo['model'] ?? $this->slotRoleRegistry
1061 ->getRoleHandler( $role )
1062 ->getDefaultModel( $page );
1063 $handler = $this->contentHandlerFactory->getContentHandler( $model );
1064
1065 $text = $handler->importTransform( $contentInfo['text'] );
1066
1067 return $handler->unserializeContent( $text );
1068 }
1069
1070 /**
1071 * @param array $pageInfo
1072 * @param array $revisionInfo
1073 * @return mixed|false
1074 */
1075 private function processRevision( $pageInfo, $revisionInfo ) {
1076 $revision = new WikiRevision();
1077
1078 $revId = $revisionInfo['id'] ?? 0;
1079 if ( $revId ) {
1080 $revision->setID( $revisionInfo['id'] );
1081 }
1082
1083 $title = $pageInfo['_title'];
1084 $revision->setTitle( $title );
1085
1086 $content = $this->makeContent( $title, $revId, $revisionInfo );
1087 $revision->setContent( SlotRecord::MAIN, $content );
1088
1089 foreach ( $revisionInfo['content'] ?? [] as $slotInfo ) {
1090 if ( !isset( $slotInfo['role'] ) ) {
1091 throw new RuntimeException( "Missing role for imported slot." );
1092 }
1093
1094 $content = $this->makeContent( $title, $revId, $slotInfo );
1095 $revision->setContent( $slotInfo['role'], $content );
1096 }
1097 $revision->setTimestamp( $revisionInfo['timestamp'] ?? wfTimestampNow() );
1098
1099 if ( isset( $revisionInfo['comment'] ) ) {
1100 $revision->setComment( $revisionInfo['comment'] );
1101 }
1102
1103 if ( isset( $revisionInfo['minor'] ) ) {
1104 $revision->setMinor( true );
1105 }
1106 if ( isset( $revisionInfo['contributor']['username'] ) ) {
1107 $revision->setUsername(
1108 $this->externalUserNames->applyPrefix( $revisionInfo['contributor']['username'] )
1109 );
1110 } elseif ( isset( $revisionInfo['contributor']['ip'] ) ) {
1111 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
1112 } else {
1113 $revision->setUsername( $this->externalUserNames->addPrefix( 'Unknown user' ) );
1114 }
1115 if ( isset( $revisionInfo['sha1'] ) ) {
1116 $revision->setSha1Base36( $revisionInfo['sha1'] );
1117 }
1118 $revision->setNoUpdates( $this->mNoUpdates );
1119
1120 return $this->revisionCallback( $revision );
1121 }
1122
1123 /**
1124 * @param array &$pageInfo
1125 * @return mixed
1126 */
1127 private function handleUpload( &$pageInfo ) {
1128 $this->debug( "Enter upload handler" );
1129 $uploadInfo = [];
1130
1131 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
1132 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
1133
1134 $skip = false;
1135
1136 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
1137 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
1138 $this->reader->localName == 'upload' ) {
1139 break;
1140 }
1141
1142 $tag = $this->reader->localName;
1143
1144 if ( !$this->hookRunner->onImportHandleUploadXMLTag( $this, $pageInfo ) ) {
1145 // Do nothing
1146 } elseif ( in_array( $tag, $normalFields ) ) {
1147 $uploadInfo[$tag] = $this->nodeContents();
1148 } elseif ( $tag == 'contributor' ) {
1149 $uploadInfo['contributor'] = $this->handleContributor();
1150 } elseif ( $tag == 'contents' ) {
1151 $contents = $this->nodeContents();
1152 $encoding = $this->reader->getAttribute( 'encoding' );
1153 if ( $encoding === 'base64' ) {
1154 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
1155 $uploadInfo['isTempSrc'] = true;
1156 }
1157 } elseif ( $tag != '#text' ) {
1158 $this->warn( "Unhandled upload XML tag $tag" );
1159 $skip = true;
1160 }
1161 }
1162
1163 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
1164 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
1165 if ( file_exists( $path ) ) {
1166 $uploadInfo['fileSrc'] = $path;
1167 $uploadInfo['isTempSrc'] = false;
1168 }
1169 }
1170
1171 if ( $this->mImportUploads ) {
1172 return $this->processUpload( $pageInfo, $uploadInfo );
1173 }
1174 }
1175
1176 /**
1177 * @param string $contents
1178 * @return string
1179 */
1180 private function dumpTemp( $contents ) {
1181 $filename = tempnam( wfTempDir(), 'importupload' );
1182 file_put_contents( $filename, $contents );
1183 return $filename;
1184 }
1185
1186 /**
1187 * @param array $pageInfo
1188 * @param array $uploadInfo
1189 * @return mixed
1190 */
1191 private function processUpload( $pageInfo, $uploadInfo ) {
1192 $revision = new WikiRevision();
1193 $revId = $pageInfo['id'];
1194 $title = $pageInfo['_title'];
1195 // T292348: text key may be absent, force addition if null
1196 $uploadInfo['text'] ??= '';
1197 $content = $this->makeContent( $title, $revId, $uploadInfo );
1198
1199 $revision->setTitle( $title );
1200 $revision->setID( $revId );
1201 $revision->setTimestamp( $uploadInfo['timestamp'] );
1202 $revision->setContent( SlotRecord::MAIN, $content );
1203 $revision->setFilename( $uploadInfo['filename'] );
1204 if ( isset( $uploadInfo['archivename'] ) ) {
1205 $revision->setArchiveName( $uploadInfo['archivename'] );
1206 }
1207 $revision->setSrc( $uploadInfo['src'] );
1208 if ( isset( $uploadInfo['fileSrc'] ) ) {
1209 $revision->setFileSrc( $uploadInfo['fileSrc'],
1210 !empty( $uploadInfo['isTempSrc'] )
1211 );
1212 }
1213 if ( isset( $uploadInfo['sha1base36'] ) ) {
1214 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1215 }
1216 $revision->setSize( intval( $uploadInfo['size'] ) );
1217 $revision->setComment( $uploadInfo['comment'] );
1218
1219 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1220 $revision->setUsername(
1221 $this->externalUserNames->applyPrefix( $uploadInfo['contributor']['username'] )
1222 );
1223 } elseif ( isset( $uploadInfo['contributor']['ip'] ) ) {
1224 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1225 }
1226 $revision->setNoUpdates( $this->mNoUpdates );
1227
1228 return call_user_func( $this->mUploadCallback, $revision );
1229 }
1230
1231 /**
1232 * @return array
1233 */
1234 private function handleContributor() {
1235 $this->debug( "Enter contributor handler." );
1236
1237 if ( $this->reader->isEmptyElement ) {
1238 return [];
1239 }
1240
1241 $fields = [ 'id', 'ip', 'username' ];
1242 $info = [];
1243
1244 while ( $this->reader->read() ) {
1245 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
1246 $this->reader->localName == 'contributor' ) {
1247 break;
1248 }
1249
1250 $tag = $this->reader->localName;
1251
1252 if ( in_array( $tag, $fields ) ) {
1253 $info[$tag] = $this->nodeContents();
1254 }
1255 }
1256
1257 return $info;
1258 }
1259
1260 /**
1261 * @param string $text
1262 * @param string|null $ns
1263 * @return array|false
1264 */
1265 private function processTitle( $text, $ns = null ) {
1266 if ( $this->foreignNamespaces === null ) {
1267 $foreignTitleFactory = new NaiveForeignTitleFactory(
1268 $this->contentLanguage
1269 );
1270 } else {
1271 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1272 $this->foreignNamespaces );
1273 }
1274
1275 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1276 intval( $ns ) );
1277
1278 $title = $this->importTitleFactory->createTitleFromForeignTitle(
1279 $foreignTitle );
1280
1281 if ( $title === null ) {
1282 # Invalid page title? Ignore the page
1283 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1284 return false;
1285 } elseif ( $title->isExternal() ) {
1286 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1287 return false;
1288 } elseif ( !$title->canExist() ) {
1289 $this->notice( 'import-error-special', $title->getPrefixedText() );
1290 return false;
1291 } elseif ( !$this->performer->definitelyCan( 'edit', $title ) ) {
1292 # Do not import if the importing wiki user cannot edit this page
1293 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1294 return false;
1295 }
1296
1297 return [ $title, $foreignTitle ];
1298 }
1299
1300 /**
1301 * Open the XMLReader connected to the source adapter id
1302 */
1303 private function openReader() {
1304 // Enable the entity loader, as it is needed for loading external URLs via
1305 // XMLReader::open (T86036)
1306 // phpcs:ignore Generic.PHP.NoSilencedErrors -- suppress deprecation per T268847
1307 $oldDisable = @libxml_disable_entity_loader( false );
1308
1309 // A static call, to avoid https://github.com/php/php-src/issues/11548
1310 $reader = XMLReader::open(
1311 'uploadsource://' . $this->sourceAdapterId, null, LIBXML_PARSEHUGE );
1312 if ( $reader instanceof XMLReader ) {
1313 $this->reader = $reader;
1314 $status = true;
1315 } else {
1316 $status = false;
1317 }
1318 if ( !$status ) {
1319 $error = libxml_get_last_error();
1320 // phpcs:ignore Generic.PHP.NoSilencedErrors
1321 @libxml_disable_entity_loader( $oldDisable );
1322 throw new RuntimeException(
1323 'Encountered an internal error while initializing WikiImporter object: ' . $error->message
1324 );
1325 }
1326 // phpcs:ignore Generic.PHP.NoSilencedErrors
1327 @libxml_disable_entity_loader( $oldDisable );
1328 }
1329
1330 /**
1331 * Check the syntax of the given xml
1332 */
1333 private function syntaxCheckXML() {
1334 if ( !UploadSourceAdapter::isSeekableSource( $this->sourceAdapterId ) ) {
1335 return;
1336 }
1337 AtEase::suppressWarnings();
1338 $oldDisable = libxml_disable_entity_loader( false );
1339 try {
1340 while ( $this->reader->read() );
1341 $error = libxml_get_last_error();
1342 if ( $error ) {
1343 $errorMessage = 'XML error at line ' . $error->line . ': ' . $error->message;
1344 wfDebug( __METHOD__ . ': Invalid xml found - ' . $errorMessage );
1345 throw new RuntimeException( $errorMessage );
1346 }
1347 } finally {
1348 libxml_disable_entity_loader( $oldDisable );
1349 AtEase::restoreWarnings();
1350 $this->reader->close();
1351 }
1352
1353 // Reopen for the real import
1354 UploadSourceAdapter::seekSource( $this->sourceAdapterId, 0 );
1355 $this->openReader();
1356 }
1357 }