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