466e3d873c67284f2d8e364290cd87535d978bc0
[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 MWNamespace::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 ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
287 $displayNSText = $title->getNamespace() == NS_MAIN
288 ? wfMessage( 'blanknamespace' )->text()
289 : MediaWikiServices::getInstance()->getContentLanguage()->
290 getNsText( $title->getNamespace() );
291 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
292 } else {
293 // set namespace to 'all', so the namespace check in processTitle() can pass
294 $this->setTargetNamespace( null );
295 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
296 }
297 }
298 return $status;
299 }
300
301 /**
302 * @param string $dir
303 */
304 public function setImageBasePath( $dir ) {
305 $this->mImageBasePath = $dir;
306 }
307
308 /**
309 * @param bool $import
310 */
311 public function setImportUploads( $import ) {
312 $this->mImportUploads = $import;
313 }
314
315 /**
316 * @since 1.31
317 * @param string $usernamePrefix Prefix to apply to unknown (and possibly also known) usernames
318 * @param bool $assignKnownUsers Whether to apply the prefix to usernames that exist locally
319 */
320 public function setUsernamePrefix( $usernamePrefix, $assignKnownUsers ) {
321 $this->externalUserNames = new ExternalUserNames( $usernamePrefix, $assignKnownUsers );
322 }
323
324 /**
325 * Statistics update can cause a lot of time
326 * @since 1.29
327 */
328 public function disableStatisticsUpdate() {
329 $this->disableStatisticsUpdate = true;
330 }
331
332 /**
333 * Default per-page callback. Sets up some things related to site statistics
334 * @param array $titleAndForeignTitle Two-element array, with Title object at
335 * index 0 and ForeignTitle object at index 1
336 * @return bool
337 */
338 public function beforeImportPage( $titleAndForeignTitle ) {
339 $title = $titleAndForeignTitle[0];
340 $page = WikiPage::factory( $title );
341 $this->countableCache['title_' . $title->getPrefixedText()] = $page->isCountable();
342 return true;
343 }
344
345 /**
346 * Default per-revision callback, performs the import.
347 * @param WikiRevision $revision
348 * @return bool
349 */
350 public function importRevision( $revision ) {
351 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
352 $this->notice( 'import-error-bad-location',
353 $revision->getTitle()->getPrefixedText(),
354 $revision->getID(),
355 $revision->getModel(),
356 $revision->getFormat() );
357
358 return false;
359 }
360
361 try {
362 return $revision->importOldRevision();
363 } catch ( MWContentSerializationException $ex ) {
364 $this->notice( 'import-error-unserialize',
365 $revision->getTitle()->getPrefixedText(),
366 $revision->getID(),
367 $revision->getModel(),
368 $revision->getFormat() );
369 }
370
371 return false;
372 }
373
374 /**
375 * Default per-revision callback, performs the import.
376 * @param WikiRevision $revision
377 * @return bool
378 */
379 public function importLogItem( $revision ) {
380 return $revision->importLogItem();
381 }
382
383 /**
384 * Dummy for now...
385 * @param WikiRevision $revision
386 * @return bool
387 */
388 public function importUpload( $revision ) {
389 return $revision->importUpload();
390 }
391
392 /**
393 * Mostly for hook use
394 * @param Title $title
395 * @param ForeignTitle $foreignTitle
396 * @param int $revCount
397 * @param int $sRevCount
398 * @param array $pageInfo
399 * @return bool
400 */
401 public function finishImportPage( $title, $foreignTitle, $revCount,
402 $sRevCount, $pageInfo
403 ) {
404 // Update article count statistics (T42009)
405 // The normal counting logic in WikiPage->doEditUpdates() is designed for
406 // one-revision-at-a-time editing, not bulk imports. In this situation it
407 // suffers from issues of replica DB lag. We let WikiPage handle the total page
408 // and revision count, and we implement our own custom logic for the
409 // article (content page) count.
410 if ( !$this->disableStatisticsUpdate ) {
411 $page = WikiPage::factory( $title );
412 $page->loadPageData( 'fromdbmaster' );
413 $content = $page->getContent();
414 if ( $content === null ) {
415 wfDebug( __METHOD__ . ': Skipping article count adjustment for ' . $title .
416 ' because WikiPage::getContent() returned null' );
417 } else {
418 $editInfo = $page->prepareContentForEdit( $content );
419 $countKey = 'title_' . $title->getPrefixedText();
420 $countable = $page->isCountable( $editInfo );
421 if ( array_key_exists( $countKey, $this->countableCache ) &&
422 $countable != $this->countableCache[$countKey] ) {
423 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [
424 'articles' => ( (int)$countable - (int)$this->countableCache[$countKey] )
425 ] ) );
426 }
427 }
428 }
429
430 return Hooks::run( 'AfterImportPage', func_get_args() );
431 }
432
433 /**
434 * Alternate per-revision callback, for debugging.
435 * @param WikiRevision &$revision
436 */
437 public function debugRevisionHandler( &$revision ) {
438 $this->debug( "Got revision:" );
439 if ( is_object( $revision->title ) ) {
440 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
441 } else {
442 $this->debug( "-- Title: <invalid>" );
443 }
444 $this->debug( "-- User: " . $revision->user_text );
445 $this->debug( "-- Timestamp: " . $revision->timestamp );
446 $this->debug( "-- Comment: " . $revision->comment );
447 $this->debug( "-- Text: " . $revision->text );
448 }
449
450 /**
451 * Notify the callback function of site info
452 * @param array $siteInfo
453 * @return bool|mixed
454 */
455 private function siteInfoCallback( $siteInfo ) {
456 if ( isset( $this->mSiteInfoCallback ) ) {
457 return call_user_func_array( $this->mSiteInfoCallback,
458 [ $siteInfo, $this ] );
459 } else {
460 return false;
461 }
462 }
463
464 /**
465 * Notify the callback function when a new "<page>" is reached.
466 * @param Title $title
467 */
468 function pageCallback( $title ) {
469 if ( isset( $this->mPageCallback ) ) {
470 call_user_func( $this->mPageCallback, $title );
471 }
472 }
473
474 /**
475 * Notify the callback function when a "</page>" is closed.
476 * @param Title $title
477 * @param ForeignTitle $foreignTitle
478 * @param int $revCount
479 * @param int $sucCount Number of revisions for which callback returned true
480 * @param array $pageInfo Associative array of page information
481 */
482 private function pageOutCallback( $title, $foreignTitle, $revCount,
483 $sucCount, $pageInfo ) {
484 if ( isset( $this->mPageOutCallback ) ) {
485 call_user_func_array( $this->mPageOutCallback, func_get_args() );
486 }
487 }
488
489 /**
490 * Notify the callback function of a revision
491 * @param WikiRevision $revision
492 * @return bool|mixed
493 */
494 private function revisionCallback( $revision ) {
495 if ( isset( $this->mRevisionCallback ) ) {
496 return call_user_func_array( $this->mRevisionCallback,
497 [ $revision, $this ] );
498 } else {
499 return false;
500 }
501 }
502
503 /**
504 * Notify the callback function of a new log item
505 * @param WikiRevision $revision
506 * @return bool|mixed
507 */
508 private function logItemCallback( $revision ) {
509 if ( isset( $this->mLogItemCallback ) ) {
510 return call_user_func_array( $this->mLogItemCallback,
511 [ $revision, $this ] );
512 } else {
513 return false;
514 }
515 }
516
517 /**
518 * Retrieves the contents of the named attribute of the current element.
519 * @param string $attr The name of the attribute
520 * @return string The value of the attribute or an empty string if it is not set in the current
521 * element.
522 */
523 public function nodeAttribute( $attr ) {
524 return $this->reader->getAttribute( $attr );
525 }
526
527 /**
528 * Shouldn't something like this be built-in to XMLReader?
529 * Fetches text contents of the current element, assuming
530 * no sub-elements or such scary things.
531 * @return string
532 * @private
533 */
534 public function nodeContents() {
535 if ( $this->reader->isEmptyElement ) {
536 return "";
537 }
538 $buffer = "";
539 while ( $this->reader->read() ) {
540 switch ( $this->reader->nodeType ) {
541 case XMLReader::TEXT:
542 case XMLReader::CDATA:
543 case XMLReader::SIGNIFICANT_WHITESPACE:
544 $buffer .= $this->reader->value;
545 break;
546 case XMLReader::END_ELEMENT:
547 return $buffer;
548 }
549 }
550
551 $this->reader->close();
552 return '';
553 }
554
555 /**
556 * Primary entry point
557 * @throws Exception
558 * @throws MWException
559 * @return bool
560 */
561 public function doImport() {
562 // Calls to reader->read need to be wrapped in calls to
563 // libxml_disable_entity_loader() to avoid local file
564 // inclusion attacks (T48932).
565 $oldDisable = libxml_disable_entity_loader( true );
566 $this->reader->read();
567
568 if ( $this->reader->localName != 'mediawiki' ) {
569 libxml_disable_entity_loader( $oldDisable );
570 throw new MWException( "Expected <mediawiki> tag, got " .
571 $this->reader->localName );
572 }
573 $this->debug( "<mediawiki> tag is correct." );
574
575 $this->debug( "Starting primary dump processing loop." );
576
577 $keepReading = $this->reader->read();
578 $skip = false;
579 $rethrow = null;
580 $pageCount = 0;
581 try {
582 while ( $keepReading ) {
583 $tag = $this->reader->localName;
584 if ( $this->pageOffset ) {
585 if ( $tag === 'page' ) {
586 $pageCount++;
587 }
588 if ( $pageCount < $this->pageOffset ) {
589 $keepReading = $this->reader->next();
590 continue;
591 }
592 }
593 $type = $this->reader->nodeType;
594
595 if ( !Hooks::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
596 // Do nothing
597 } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
598 break;
599 } elseif ( $tag == 'siteinfo' ) {
600 $this->handleSiteInfo();
601 } elseif ( $tag == 'page' ) {
602 $this->handlePage();
603 } elseif ( $tag == 'logitem' ) {
604 $this->handleLogItem();
605 } elseif ( $tag != '#text' ) {
606 $this->warn( "Unhandled top-level XML tag $tag" );
607
608 $skip = true;
609 }
610
611 if ( $skip ) {
612 $keepReading = $this->reader->next();
613 $skip = false;
614 $this->debug( "Skip" );
615 } else {
616 $keepReading = $this->reader->read();
617 }
618 }
619 } catch ( Exception $ex ) {
620 $rethrow = $ex;
621 }
622
623 // finally
624 libxml_disable_entity_loader( $oldDisable );
625 $this->reader->close();
626
627 if ( $rethrow ) {
628 throw $rethrow;
629 }
630
631 return true;
632 }
633
634 private function handleSiteInfo() {
635 $this->debug( "Enter site info handler." );
636 $siteInfo = [];
637
638 // Fields that can just be stuffed in the siteInfo object
639 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
640
641 while ( $this->reader->read() ) {
642 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
643 $this->reader->localName == 'siteinfo' ) {
644 break;
645 }
646
647 $tag = $this->reader->localName;
648
649 if ( $tag == 'namespace' ) {
650 $this->foreignNamespaces[$this->nodeAttribute( 'key' )] =
651 $this->nodeContents();
652 } elseif ( in_array( $tag, $normalFields ) ) {
653 $siteInfo[$tag] = $this->nodeContents();
654 }
655 }
656
657 $siteInfo['_namespaces'] = $this->foreignNamespaces;
658 $this->siteInfoCallback( $siteInfo );
659 }
660
661 private function handleLogItem() {
662 $this->debug( "Enter log item handler." );
663 $logInfo = [];
664
665 // Fields that can just be stuffed in the pageInfo object
666 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
667 'logtitle', 'params' ];
668
669 while ( $this->reader->read() ) {
670 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
671 $this->reader->localName == 'logitem' ) {
672 break;
673 }
674
675 $tag = $this->reader->localName;
676
677 if ( !Hooks::run( 'ImportHandleLogItemXMLTag', [
678 $this, $logInfo
679 ] ) ) {
680 // Do nothing
681 } elseif ( in_array( $tag, $normalFields ) ) {
682 $logInfo[$tag] = $this->nodeContents();
683 } elseif ( $tag == 'contributor' ) {
684 $logInfo['contributor'] = $this->handleContributor();
685 } elseif ( $tag != '#text' ) {
686 $this->warn( "Unhandled log-item XML tag $tag" );
687 }
688 }
689
690 $this->processLogItem( $logInfo );
691 }
692
693 /**
694 * @param array $logInfo
695 * @return bool|mixed
696 */
697 private function processLogItem( $logInfo ) {
698 $revision = new WikiRevision( $this->config );
699
700 if ( isset( $logInfo['id'] ) ) {
701 $revision->setID( $logInfo['id'] );
702 }
703 $revision->setType( $logInfo['type'] );
704 $revision->setAction( $logInfo['action'] );
705 if ( isset( $logInfo['timestamp'] ) ) {
706 $revision->setTimestamp( $logInfo['timestamp'] );
707 }
708 if ( isset( $logInfo['params'] ) ) {
709 $revision->setParams( $logInfo['params'] );
710 }
711 if ( isset( $logInfo['logtitle'] ) ) {
712 // @todo Using Title for non-local titles is a recipe for disaster.
713 // We should use ForeignTitle here instead.
714 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
715 }
716
717 $revision->setNoUpdates( $this->mNoUpdates );
718
719 if ( isset( $logInfo['comment'] ) ) {
720 $revision->setComment( $logInfo['comment'] );
721 }
722
723 if ( isset( $logInfo['contributor']['ip'] ) ) {
724 $revision->setUserIP( $logInfo['contributor']['ip'] );
725 }
726
727 if ( !isset( $logInfo['contributor']['username'] ) ) {
728 $revision->setUsername( $this->externalUserNames->addPrefix( 'Unknown user' ) );
729 } else {
730 $revision->setUsername(
731 $this->externalUserNames->applyPrefix( $logInfo['contributor']['username'] )
732 );
733 }
734
735 return $this->logItemCallback( $revision );
736 }
737
738 private function handlePage() {
739 // Handle page data.
740 $this->debug( "Enter page handler." );
741 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
742
743 // Fields that can just be stuffed in the pageInfo object
744 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
745
746 $skip = false;
747 $badTitle = false;
748
749 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
750 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
751 $this->reader->localName == 'page' ) {
752 break;
753 }
754
755 $skip = false;
756
757 $tag = $this->reader->localName;
758
759 if ( $badTitle ) {
760 // The title is invalid, bail out of this page
761 $skip = true;
762 } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', [ $this,
763 &$pageInfo ] ) ) {
764 // Do nothing
765 } elseif ( in_array( $tag, $normalFields ) ) {
766 // An XML snippet:
767 // <page>
768 // <id>123</id>
769 // <title>Page</title>
770 // <redirect title="NewTitle"/>
771 // ...
772 // Because the redirect tag is built differently, we need special handling for that case.
773 if ( $tag == 'redirect' ) {
774 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
775 } else {
776 $pageInfo[$tag] = $this->nodeContents();
777 }
778 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
779 if ( !isset( $title ) ) {
780 $title = $this->processTitle( $pageInfo['title'],
781 $pageInfo['ns'] ?? null );
782
783 // $title is either an array of two titles or false.
784 if ( is_array( $title ) ) {
785 $this->pageCallback( $title );
786 list( $pageInfo['_title'], $foreignTitle ) = $title;
787 } else {
788 $badTitle = true;
789 $skip = true;
790 }
791 }
792
793 if ( $title ) {
794 if ( $tag == 'revision' ) {
795 $this->handleRevision( $pageInfo );
796 } else {
797 $this->handleUpload( $pageInfo );
798 }
799 }
800 } elseif ( $tag != '#text' ) {
801 $this->warn( "Unhandled page XML tag $tag" );
802 $skip = true;
803 }
804 }
805
806 // @note $pageInfo is only set if a valid $title is processed above with
807 // no error. If we have a valid $title, then pageCallback is called
808 // above, $pageInfo['title'] is set and we do pageOutCallback here.
809 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
810 // set since they both come from $title above.
811 if ( array_key_exists( '_title', $pageInfo ) ) {
812 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
813 $pageInfo['revisionCount'],
814 $pageInfo['successfulRevisionCount'],
815 $pageInfo );
816 }
817 }
818
819 /**
820 * @param array $pageInfo
821 */
822 private function handleRevision( &$pageInfo ) {
823 $this->debug( "Enter revision handler" );
824 $revisionInfo = [];
825
826 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text', 'sha1' ];
827
828 $skip = false;
829
830 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
831 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
832 $this->reader->localName == 'revision' ) {
833 break;
834 }
835
836 $tag = $this->reader->localName;
837
838 if ( !Hooks::run( 'ImportHandleRevisionXMLTag', [
839 $this, $pageInfo, $revisionInfo
840 ] ) ) {
841 // Do nothing
842 } elseif ( in_array( $tag, $normalFields ) ) {
843 $revisionInfo[$tag] = $this->nodeContents();
844 } elseif ( $tag == 'contributor' ) {
845 $revisionInfo['contributor'] = $this->handleContributor();
846 } elseif ( $tag != '#text' ) {
847 $this->warn( "Unhandled revision XML tag $tag" );
848 $skip = true;
849 }
850 }
851
852 $pageInfo['revisionCount']++;
853 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
854 $pageInfo['successfulRevisionCount']++;
855 }
856 }
857
858 /**
859 * @param array $pageInfo
860 * @param array $revisionInfo
861 * @throws MWException
862 * @return bool|mixed
863 */
864 private function processRevision( $pageInfo, $revisionInfo ) {
865 global $wgMaxArticleSize;
866
867 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
868 // database errors and instability. Testing for revisions with only listed
869 // content models, as other content models might use serialization formats
870 // which aren't checked against $wgMaxArticleSize.
871 if ( ( !isset( $revisionInfo['model'] ) ||
872 in_array( $revisionInfo['model'], [
873 'wikitext',
874 'css',
875 'json',
876 'javascript',
877 'text',
878 ''
879 ] ) ) &&
880 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
881 ) {
882 throw new MWException( 'The text of ' .
883 ( isset( $revisionInfo['id'] ) ?
884 "the revision with ID $revisionInfo[id]" :
885 'a revision'
886 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
887 }
888
889 // FIXME: process schema version 11!
890 $revision = new WikiRevision( $this->config );
891
892 if ( isset( $revisionInfo['id'] ) ) {
893 $revision->setID( $revisionInfo['id'] );
894 }
895 if ( isset( $revisionInfo['model'] ) ) {
896 $revision->setModel( $revisionInfo['model'] );
897 }
898 if ( isset( $revisionInfo['format'] ) ) {
899 $revision->setFormat( $revisionInfo['format'] );
900 }
901 $revision->setTitle( $pageInfo['_title'] );
902
903 if ( isset( $revisionInfo['text'] ) ) {
904 $handler = $revision->getContentHandler();
905 $text = $handler->importTransform(
906 $revisionInfo['text'],
907 $revision->getFormat() );
908
909 $revision->setText( $text );
910 }
911 $revision->setTimestamp( $revisionInfo['timestamp'] ?? wfTimestampNow() );
912
913 if ( isset( $revisionInfo['comment'] ) ) {
914 $revision->setComment( $revisionInfo['comment'] );
915 }
916
917 if ( isset( $revisionInfo['minor'] ) ) {
918 $revision->setMinor( true );
919 }
920 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
921 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
922 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
923 $revision->setUsername(
924 $this->externalUserNames->applyPrefix( $revisionInfo['contributor']['username'] )
925 );
926 } else {
927 $revision->setUsername( $this->externalUserNames->addPrefix( 'Unknown user' ) );
928 }
929 if ( isset( $revisionInfo['sha1'] ) ) {
930 $revision->setSha1Base36( $revisionInfo['sha1'] );
931 }
932 $revision->setNoUpdates( $this->mNoUpdates );
933
934 return $this->revisionCallback( $revision );
935 }
936
937 /**
938 * @param array $pageInfo
939 * @return mixed
940 */
941 private function handleUpload( &$pageInfo ) {
942 $this->debug( "Enter upload handler" );
943 $uploadInfo = [];
944
945 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
946 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
947
948 $skip = false;
949
950 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
951 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
952 $this->reader->localName == 'upload' ) {
953 break;
954 }
955
956 $tag = $this->reader->localName;
957
958 if ( !Hooks::run( 'ImportHandleUploadXMLTag', [
959 $this, $pageInfo
960 ] ) ) {
961 // Do nothing
962 } elseif ( in_array( $tag, $normalFields ) ) {
963 $uploadInfo[$tag] = $this->nodeContents();
964 } elseif ( $tag == 'contributor' ) {
965 $uploadInfo['contributor'] = $this->handleContributor();
966 } elseif ( $tag == 'contents' ) {
967 $contents = $this->nodeContents();
968 $encoding = $this->reader->getAttribute( 'encoding' );
969 if ( $encoding === 'base64' ) {
970 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
971 $uploadInfo['isTempSrc'] = true;
972 }
973 } elseif ( $tag != '#text' ) {
974 $this->warn( "Unhandled upload XML tag $tag" );
975 $skip = true;
976 }
977 }
978
979 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
980 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
981 if ( file_exists( $path ) ) {
982 $uploadInfo['fileSrc'] = $path;
983 $uploadInfo['isTempSrc'] = false;
984 }
985 }
986
987 if ( $this->mImportUploads ) {
988 return $this->processUpload( $pageInfo, $uploadInfo );
989 }
990 }
991
992 /**
993 * @param string $contents
994 * @return string
995 */
996 private function dumpTemp( $contents ) {
997 $filename = tempnam( wfTempDir(), 'importupload' );
998 file_put_contents( $filename, $contents );
999 return $filename;
1000 }
1001
1002 /**
1003 * @param array $pageInfo
1004 * @param array $uploadInfo
1005 * @return mixed
1006 */
1007 private function processUpload( $pageInfo, $uploadInfo ) {
1008 $revision = new WikiRevision( $this->config );
1009 $text = $uploadInfo['text'] ?? '';
1010
1011 $revision->setTitle( $pageInfo['_title'] );
1012 $revision->setID( $pageInfo['id'] );
1013 $revision->setTimestamp( $uploadInfo['timestamp'] );
1014 $revision->setText( $text );
1015 $revision->setFilename( $uploadInfo['filename'] );
1016 if ( isset( $uploadInfo['archivename'] ) ) {
1017 $revision->setArchiveName( $uploadInfo['archivename'] );
1018 }
1019 $revision->setSrc( $uploadInfo['src'] );
1020 if ( isset( $uploadInfo['fileSrc'] ) ) {
1021 $revision->setFileSrc( $uploadInfo['fileSrc'],
1022 !empty( $uploadInfo['isTempSrc'] ) );
1023 }
1024 if ( isset( $uploadInfo['sha1base36'] ) ) {
1025 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1026 }
1027 $revision->setSize( intval( $uploadInfo['size'] ) );
1028 $revision->setComment( $uploadInfo['comment'] );
1029
1030 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1031 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1032 }
1033 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1034 $revision->setUsername(
1035 $this->externalUserNames->applyPrefix( $uploadInfo['contributor']['username'] )
1036 );
1037 }
1038 $revision->setNoUpdates( $this->mNoUpdates );
1039
1040 return call_user_func( $this->mUploadCallback, $revision );
1041 }
1042
1043 /**
1044 * @return array
1045 */
1046 private function handleContributor() {
1047 $fields = [ 'id', 'ip', 'username' ];
1048 $info = [];
1049
1050 if ( $this->reader->isEmptyElement ) {
1051 return $info;
1052 }
1053 while ( $this->reader->read() ) {
1054 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
1055 $this->reader->localName == 'contributor' ) {
1056 break;
1057 }
1058
1059 $tag = $this->reader->localName;
1060
1061 if ( in_array( $tag, $fields ) ) {
1062 $info[$tag] = $this->nodeContents();
1063 }
1064 }
1065
1066 return $info;
1067 }
1068
1069 /**
1070 * @param string $text
1071 * @param string|null $ns
1072 * @return array|bool
1073 */
1074 private function processTitle( $text, $ns = null ) {
1075 if ( is_null( $this->foreignNamespaces ) ) {
1076 $foreignTitleFactory = new NaiveForeignTitleFactory();
1077 } else {
1078 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1079 $this->foreignNamespaces );
1080 }
1081
1082 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1083 intval( $ns ) );
1084
1085 $title = $this->importTitleFactory->createTitleFromForeignTitle(
1086 $foreignTitle );
1087
1088 $commandLineMode = $this->config->get( 'CommandLineMode' );
1089 if ( is_null( $title ) ) {
1090 # Invalid page title? Ignore the page
1091 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1092 return false;
1093 } elseif ( $title->isExternal() ) {
1094 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1095 return false;
1096 } elseif ( !$title->canExist() ) {
1097 $this->notice( 'import-error-special', $title->getPrefixedText() );
1098 return false;
1099 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1100 # Do not import if the importing wiki user cannot edit this page
1101 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1102 return false;
1103 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1104 # Do not import if the importing wiki user cannot create this page
1105 $this->notice( 'import-error-create', $title->getPrefixedText() );
1106 return false;
1107 }
1108
1109 return [ $title, $foreignTitle ];
1110 }
1111 }