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