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