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