8f583442ce6f55b923eeccfd303ab6dc718331b4
[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 Title $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 private function handlePage() {
742 // Handle page data.
743 $this->debug( "Enter page handler." );
744 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
745
746 // Fields that can just be stuffed in the pageInfo object
747 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
748
749 $skip = false;
750 $badTitle = false;
751
752 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
753 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
754 $this->reader->localName == 'page' ) {
755 break;
756 }
757
758 $skip = false;
759
760 $tag = $this->reader->localName;
761
762 if ( $badTitle ) {
763 // The title is invalid, bail out of this page
764 $skip = true;
765 } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', [ $this,
766 &$pageInfo ] ) ) {
767 // Do nothing
768 } elseif ( in_array( $tag, $normalFields ) ) {
769 // An XML snippet:
770 // <page>
771 // <id>123</id>
772 // <title>Page</title>
773 // <redirect title="NewTitle"/>
774 // ...
775 // Because the redirect tag is built differently, we need special handling for that case.
776 if ( $tag == 'redirect' ) {
777 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
778 } else {
779 $pageInfo[$tag] = $this->nodeContents();
780 }
781 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
782 if ( !isset( $title ) ) {
783 $title = $this->processTitle( $pageInfo['title'],
784 $pageInfo['ns'] ?? null );
785
786 // $title is either an array of two titles or false.
787 if ( is_array( $title ) ) {
788 $this->pageCallback( $title );
789 list( $pageInfo['_title'], $foreignTitle ) = $title;
790 } else {
791 $badTitle = true;
792 $skip = true;
793 }
794 }
795
796 if ( $title ) {
797 if ( $tag == 'revision' ) {
798 $this->handleRevision( $pageInfo );
799 } else {
800 $this->handleUpload( $pageInfo );
801 }
802 }
803 } elseif ( $tag != '#text' ) {
804 $this->warn( "Unhandled page XML tag $tag" );
805 $skip = true;
806 }
807 }
808
809 // @note $pageInfo is only set if a valid $title is processed above with
810 // no error. If we have a valid $title, then pageCallback is called
811 // above, $pageInfo['title'] is set and we do pageOutCallback here.
812 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
813 // set since they both come from $title above.
814 if ( array_key_exists( '_title', $pageInfo ) ) {
815 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
816 $pageInfo['revisionCount'],
817 $pageInfo['successfulRevisionCount'],
818 $pageInfo );
819 }
820 }
821
822 /**
823 * @param array $pageInfo
824 */
825 private function handleRevision( &$pageInfo ) {
826 $this->debug( "Enter revision handler" );
827 $revisionInfo = [];
828
829 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text', 'sha1' ];
830
831 $skip = false;
832
833 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
834 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
835 $this->reader->localName == 'revision' ) {
836 break;
837 }
838
839 $tag = $this->reader->localName;
840
841 if ( !Hooks::run( 'ImportHandleRevisionXMLTag', [
842 $this, $pageInfo, $revisionInfo
843 ] ) ) {
844 // Do nothing
845 } elseif ( in_array( $tag, $normalFields ) ) {
846 $revisionInfo[$tag] = $this->nodeContents();
847 } elseif ( $tag == 'contributor' ) {
848 $revisionInfo['contributor'] = $this->handleContributor();
849 } elseif ( $tag != '#text' ) {
850 $this->warn( "Unhandled revision XML tag $tag" );
851 $skip = true;
852 }
853 }
854
855 $pageInfo['revisionCount']++;
856 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
857 $pageInfo['successfulRevisionCount']++;
858 }
859 }
860
861 /**
862 * @param array $pageInfo
863 * @param array $revisionInfo
864 * @throws MWException
865 * @return bool|mixed
866 */
867 private function processRevision( $pageInfo, $revisionInfo ) {
868 global $wgMaxArticleSize;
869
870 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
871 // database errors and instability. Testing for revisions with only listed
872 // content models, as other content models might use serialization formats
873 // which aren't checked against $wgMaxArticleSize.
874 if ( ( !isset( $revisionInfo['model'] ) ||
875 in_array( $revisionInfo['model'], [
876 'wikitext',
877 'css',
878 'json',
879 'javascript',
880 'text',
881 ''
882 ] ) ) &&
883 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
884 ) {
885 throw new MWException( 'The text of ' .
886 ( isset( $revisionInfo['id'] ) ?
887 "the revision with ID $revisionInfo[id]" :
888 'a revision'
889 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
890 }
891
892 // FIXME: process schema version 11!
893 $revision = new WikiRevision( $this->config );
894
895 if ( isset( $revisionInfo['id'] ) ) {
896 $revision->setID( $revisionInfo['id'] );
897 }
898 if ( isset( $revisionInfo['model'] ) ) {
899 $revision->setModel( $revisionInfo['model'] );
900 }
901 if ( isset( $revisionInfo['format'] ) ) {
902 $revision->setFormat( $revisionInfo['format'] );
903 }
904 $revision->setTitle( $pageInfo['_title'] );
905
906 if ( isset( $revisionInfo['text'] ) ) {
907 $handler = $revision->getContentHandler();
908 $text = $handler->importTransform(
909 $revisionInfo['text'],
910 $revision->getFormat() );
911
912 $revision->setText( $text );
913 }
914 $revision->setTimestamp( $revisionInfo['timestamp'] ?? wfTimestampNow() );
915
916 if ( isset( $revisionInfo['comment'] ) ) {
917 $revision->setComment( $revisionInfo['comment'] );
918 }
919
920 if ( isset( $revisionInfo['minor'] ) ) {
921 $revision->setMinor( true );
922 }
923 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
924 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
925 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
926 $revision->setUsername(
927 $this->externalUserNames->applyPrefix( $revisionInfo['contributor']['username'] )
928 );
929 } else {
930 $revision->setUsername( $this->externalUserNames->addPrefix( 'Unknown user' ) );
931 }
932 if ( isset( $revisionInfo['sha1'] ) ) {
933 $revision->setSha1Base36( $revisionInfo['sha1'] );
934 }
935 $revision->setNoUpdates( $this->mNoUpdates );
936
937 return $this->revisionCallback( $revision );
938 }
939
940 /**
941 * @param array $pageInfo
942 * @return mixed
943 */
944 private function handleUpload( &$pageInfo ) {
945 $this->debug( "Enter upload handler" );
946 $uploadInfo = [];
947
948 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
949 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
950
951 $skip = false;
952
953 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
954 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
955 $this->reader->localName == 'upload' ) {
956 break;
957 }
958
959 $tag = $this->reader->localName;
960
961 if ( !Hooks::run( 'ImportHandleUploadXMLTag', [
962 $this, $pageInfo
963 ] ) ) {
964 // Do nothing
965 } elseif ( in_array( $tag, $normalFields ) ) {
966 $uploadInfo[$tag] = $this->nodeContents();
967 } elseif ( $tag == 'contributor' ) {
968 $uploadInfo['contributor'] = $this->handleContributor();
969 } elseif ( $tag == 'contents' ) {
970 $contents = $this->nodeContents();
971 $encoding = $this->reader->getAttribute( 'encoding' );
972 if ( $encoding === 'base64' ) {
973 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
974 $uploadInfo['isTempSrc'] = true;
975 }
976 } elseif ( $tag != '#text' ) {
977 $this->warn( "Unhandled upload XML tag $tag" );
978 $skip = true;
979 }
980 }
981
982 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
983 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
984 if ( file_exists( $path ) ) {
985 $uploadInfo['fileSrc'] = $path;
986 $uploadInfo['isTempSrc'] = false;
987 }
988 }
989
990 if ( $this->mImportUploads ) {
991 return $this->processUpload( $pageInfo, $uploadInfo );
992 }
993 }
994
995 /**
996 * @param string $contents
997 * @return string
998 */
999 private function dumpTemp( $contents ) {
1000 $filename = tempnam( wfTempDir(), 'importupload' );
1001 file_put_contents( $filename, $contents );
1002 return $filename;
1003 }
1004
1005 /**
1006 * @param array $pageInfo
1007 * @param array $uploadInfo
1008 * @return mixed
1009 */
1010 private function processUpload( $pageInfo, $uploadInfo ) {
1011 $revision = new WikiRevision( $this->config );
1012 $text = $uploadInfo['text'] ?? '';
1013
1014 $revision->setTitle( $pageInfo['_title'] );
1015 $revision->setID( $pageInfo['id'] );
1016 $revision->setTimestamp( $uploadInfo['timestamp'] );
1017 $revision->setText( $text );
1018 $revision->setFilename( $uploadInfo['filename'] );
1019 if ( isset( $uploadInfo['archivename'] ) ) {
1020 $revision->setArchiveName( $uploadInfo['archivename'] );
1021 }
1022 $revision->setSrc( $uploadInfo['src'] );
1023 if ( isset( $uploadInfo['fileSrc'] ) ) {
1024 $revision->setFileSrc( $uploadInfo['fileSrc'],
1025 !empty( $uploadInfo['isTempSrc'] ) );
1026 }
1027 if ( isset( $uploadInfo['sha1base36'] ) ) {
1028 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1029 }
1030 $revision->setSize( intval( $uploadInfo['size'] ) );
1031 $revision->setComment( $uploadInfo['comment'] );
1032
1033 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1034 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1035 }
1036 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1037 $revision->setUsername(
1038 $this->externalUserNames->applyPrefix( $uploadInfo['contributor']['username'] )
1039 );
1040 }
1041 $revision->setNoUpdates( $this->mNoUpdates );
1042
1043 return call_user_func( $this->mUploadCallback, $revision );
1044 }
1045
1046 /**
1047 * @return array
1048 */
1049 private function handleContributor() {
1050 $fields = [ 'id', 'ip', 'username' ];
1051 $info = [];
1052
1053 if ( $this->reader->isEmptyElement ) {
1054 return $info;
1055 }
1056 while ( $this->reader->read() ) {
1057 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
1058 $this->reader->localName == 'contributor' ) {
1059 break;
1060 }
1061
1062 $tag = $this->reader->localName;
1063
1064 if ( in_array( $tag, $fields ) ) {
1065 $info[$tag] = $this->nodeContents();
1066 }
1067 }
1068
1069 return $info;
1070 }
1071
1072 /**
1073 * @param string $text
1074 * @param string|null $ns
1075 * @return array|bool
1076 */
1077 private function processTitle( $text, $ns = null ) {
1078 if ( is_null( $this->foreignNamespaces ) ) {
1079 $foreignTitleFactory = new NaiveForeignTitleFactory();
1080 } else {
1081 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1082 $this->foreignNamespaces );
1083 }
1084
1085 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1086 intval( $ns ) );
1087
1088 $title = $this->importTitleFactory->createTitleFromForeignTitle(
1089 $foreignTitle );
1090
1091 $commandLineMode = $this->config->get( 'CommandLineMode' );
1092 if ( is_null( $title ) ) {
1093 # Invalid page title? Ignore the page
1094 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1095 return false;
1096 } elseif ( $title->isExternal() ) {
1097 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1098 return false;
1099 } elseif ( !$title->canExist() ) {
1100 $this->notice( 'import-error-special', $title->getPrefixedText() );
1101 return false;
1102 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1103 # Do not import if the importing wiki user cannot edit this page
1104 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1105 return false;
1106 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1107 # Do not import if the importing wiki user cannot create this page
1108 $this->notice( 'import-error-create', $title->getPrefixedText() );
1109 return false;
1110 }
1111
1112 return [ $title, $foreignTitle ];
1113 }
1114 }