Add missing @throws in Importers
[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 Exception
550 * @throws MWException
551 * @return bool
552 */
553 public function doImport() {
554 // Calls to reader->read need to be wrapped in calls to
555 // libxml_disable_entity_loader() to avoid local file
556 // inclusion attacks (T48932).
557 $oldDisable = libxml_disable_entity_loader( true );
558 $this->reader->read();
559
560 if ( $this->reader->localName != 'mediawiki' ) {
561 libxml_disable_entity_loader( $oldDisable );
562 throw new MWException( "Expected <mediawiki> tag, got " .
563 $this->reader->localName );
564 }
565 $this->debug( "<mediawiki> tag is correct." );
566
567 $this->debug( "Starting primary dump processing loop." );
568
569 $keepReading = $this->reader->read();
570 $skip = false;
571 $rethrow = null;
572 $pageCount = 0;
573 try {
574 while ( $keepReading ) {
575 $tag = $this->reader->localName;
576 if ( $this->pageOffset ) {
577 if ( $tag === 'page' ) {
578 $pageCount++;
579 }
580 if ( $pageCount < $this->pageOffset ) {
581 $keepReading = $this->reader->next();
582 continue;
583 }
584 }
585 $type = $this->reader->nodeType;
586
587 if ( !Hooks::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
588 // Do nothing
589 } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
590 break;
591 } elseif ( $tag == 'siteinfo' ) {
592 $this->handleSiteInfo();
593 } elseif ( $tag == 'page' ) {
594 $this->handlePage();
595 } elseif ( $tag == 'logitem' ) {
596 $this->handleLogItem();
597 } elseif ( $tag != '#text' ) {
598 $this->warn( "Unhandled top-level XML tag $tag" );
599
600 $skip = true;
601 }
602
603 if ( $skip ) {
604 $keepReading = $this->reader->next();
605 $skip = false;
606 $this->debug( "Skip" );
607 } else {
608 $keepReading = $this->reader->read();
609 }
610 }
611 } catch ( Exception $ex ) {
612 $rethrow = $ex;
613 }
614
615 // finally
616 libxml_disable_entity_loader( $oldDisable );
617 $this->reader->close();
618
619 if ( $rethrow ) {
620 throw $rethrow;
621 }
622
623 return true;
624 }
625
626 private function handleSiteInfo() {
627 $this->debug( "Enter site info handler." );
628 $siteInfo = [];
629
630 // Fields that can just be stuffed in the siteInfo object
631 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
632
633 while ( $this->reader->read() ) {
634 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
635 $this->reader->localName == 'siteinfo' ) {
636 break;
637 }
638
639 $tag = $this->reader->localName;
640
641 if ( $tag == 'namespace' ) {
642 $this->foreignNamespaces[$this->nodeAttribute( 'key' )] =
643 $this->nodeContents();
644 } elseif ( in_array( $tag, $normalFields ) ) {
645 $siteInfo[$tag] = $this->nodeContents();
646 }
647 }
648
649 $siteInfo['_namespaces'] = $this->foreignNamespaces;
650 $this->siteInfoCallback( $siteInfo );
651 }
652
653 private function handleLogItem() {
654 $this->debug( "Enter log item handler." );
655 $logInfo = [];
656
657 // Fields that can just be stuffed in the pageInfo object
658 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
659 'logtitle', 'params' ];
660
661 while ( $this->reader->read() ) {
662 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
663 $this->reader->localName == 'logitem' ) {
664 break;
665 }
666
667 $tag = $this->reader->localName;
668
669 if ( !Hooks::run( 'ImportHandleLogItemXMLTag', [
670 $this, $logInfo
671 ] ) ) {
672 // Do nothing
673 } elseif ( in_array( $tag, $normalFields ) ) {
674 $logInfo[$tag] = $this->nodeContents();
675 } elseif ( $tag == 'contributor' ) {
676 $logInfo['contributor'] = $this->handleContributor();
677 } elseif ( $tag != '#text' ) {
678 $this->warn( "Unhandled log-item XML tag $tag" );
679 }
680 }
681
682 $this->processLogItem( $logInfo );
683 }
684
685 /**
686 * @param array $logInfo
687 * @return bool|mixed
688 */
689 private function processLogItem( $logInfo ) {
690 $revision = new WikiRevision( $this->config );
691
692 if ( isset( $logInfo['id'] ) ) {
693 $revision->setID( $logInfo['id'] );
694 }
695 $revision->setType( $logInfo['type'] );
696 $revision->setAction( $logInfo['action'] );
697 if ( isset( $logInfo['timestamp'] ) ) {
698 $revision->setTimestamp( $logInfo['timestamp'] );
699 }
700 if ( isset( $logInfo['params'] ) ) {
701 $revision->setParams( $logInfo['params'] );
702 }
703 if ( isset( $logInfo['logtitle'] ) ) {
704 // @todo Using Title for non-local titles is a recipe for disaster.
705 // We should use ForeignTitle here instead.
706 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
707 }
708
709 $revision->setNoUpdates( $this->mNoUpdates );
710
711 if ( isset( $logInfo['comment'] ) ) {
712 $revision->setComment( $logInfo['comment'] );
713 }
714
715 if ( isset( $logInfo['contributor']['ip'] ) ) {
716 $revision->setUserIP( $logInfo['contributor']['ip'] );
717 }
718
719 if ( !isset( $logInfo['contributor']['username'] ) ) {
720 $revision->setUsername( 'Unknown user' );
721 } else {
722 $revision->setUsername( $logInfo['contributor']['username'] );
723 }
724
725 return $this->logItemCallback( $revision );
726 }
727
728 private function handlePage() {
729 // Handle page data.
730 $this->debug( "Enter page handler." );
731 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
732
733 // Fields that can just be stuffed in the pageInfo object
734 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
735
736 $skip = false;
737 $badTitle = false;
738
739 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
740 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
741 $this->reader->localName == 'page' ) {
742 break;
743 }
744
745 $skip = false;
746
747 $tag = $this->reader->localName;
748
749 if ( $badTitle ) {
750 // The title is invalid, bail out of this page
751 $skip = true;
752 } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', [ $this,
753 &$pageInfo ] ) ) {
754 // Do nothing
755 } elseif ( in_array( $tag, $normalFields ) ) {
756 // An XML snippet:
757 // <page>
758 // <id>123</id>
759 // <title>Page</title>
760 // <redirect title="NewTitle"/>
761 // ...
762 // Because the redirect tag is built differently, we need special handling for that case.
763 if ( $tag == 'redirect' ) {
764 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
765 } else {
766 $pageInfo[$tag] = $this->nodeContents();
767 }
768 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
769 if ( !isset( $title ) ) {
770 $title = $this->processTitle( $pageInfo['title'],
771 isset( $pageInfo['ns'] ) ? $pageInfo['ns'] : null );
772
773 // $title is either an array of two titles or false.
774 if ( is_array( $title ) ) {
775 $this->pageCallback( $title );
776 list( $pageInfo['_title'], $foreignTitle ) = $title;
777 } else {
778 $badTitle = true;
779 $skip = true;
780 }
781 }
782
783 if ( $title ) {
784 if ( $tag == 'revision' ) {
785 $this->handleRevision( $pageInfo );
786 } else {
787 $this->handleUpload( $pageInfo );
788 }
789 }
790 } elseif ( $tag != '#text' ) {
791 $this->warn( "Unhandled page XML tag $tag" );
792 $skip = true;
793 }
794 }
795
796 // @note $pageInfo is only set if a valid $title is processed above with
797 // no error. If we have a valid $title, then pageCallback is called
798 // above, $pageInfo['title'] is set and we do pageOutCallback here.
799 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
800 // set since they both come from $title above.
801 if ( array_key_exists( '_title', $pageInfo ) ) {
802 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
803 $pageInfo['revisionCount'],
804 $pageInfo['successfulRevisionCount'],
805 $pageInfo );
806 }
807 }
808
809 /**
810 * @param array $pageInfo
811 */
812 private function handleRevision( &$pageInfo ) {
813 $this->debug( "Enter revision handler" );
814 $revisionInfo = [];
815
816 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text', 'sha1' ];
817
818 $skip = false;
819
820 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
821 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
822 $this->reader->localName == 'revision' ) {
823 break;
824 }
825
826 $tag = $this->reader->localName;
827
828 if ( !Hooks::run( 'ImportHandleRevisionXMLTag', [
829 $this, $pageInfo, $revisionInfo
830 ] ) ) {
831 // Do nothing
832 } elseif ( in_array( $tag, $normalFields ) ) {
833 $revisionInfo[$tag] = $this->nodeContents();
834 } elseif ( $tag == 'contributor' ) {
835 $revisionInfo['contributor'] = $this->handleContributor();
836 } elseif ( $tag != '#text' ) {
837 $this->warn( "Unhandled revision XML tag $tag" );
838 $skip = true;
839 }
840 }
841
842 $pageInfo['revisionCount']++;
843 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
844 $pageInfo['successfulRevisionCount']++;
845 }
846 }
847
848 /**
849 * @param array $pageInfo
850 * @param array $revisionInfo
851 * @throws MWException
852 * @return bool|mixed
853 */
854 private function processRevision( $pageInfo, $revisionInfo ) {
855 global $wgMaxArticleSize;
856
857 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
858 // database errors and instability. Testing for revisions with only listed
859 // content models, as other content models might use serialization formats
860 // which aren't checked against $wgMaxArticleSize.
861 if ( ( !isset( $revisionInfo['model'] ) ||
862 in_array( $revisionInfo['model'], [
863 'wikitext',
864 'css',
865 'json',
866 'javascript',
867 'text',
868 ''
869 ] ) ) &&
870 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
871 ) {
872 throw new MWException( 'The text of ' .
873 ( isset( $revisionInfo['id'] ) ?
874 "the revision with ID $revisionInfo[id]" :
875 'a revision'
876 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
877 }
878
879 $revision = new WikiRevision( $this->config );
880
881 if ( isset( $revisionInfo['id'] ) ) {
882 $revision->setID( $revisionInfo['id'] );
883 }
884 if ( isset( $revisionInfo['model'] ) ) {
885 $revision->setModel( $revisionInfo['model'] );
886 }
887 if ( isset( $revisionInfo['format'] ) ) {
888 $revision->setFormat( $revisionInfo['format'] );
889 }
890 $revision->setTitle( $pageInfo['_title'] );
891
892 if ( isset( $revisionInfo['text'] ) ) {
893 $handler = $revision->getContentHandler();
894 $text = $handler->importTransform(
895 $revisionInfo['text'],
896 $revision->getFormat() );
897
898 $revision->setText( $text );
899 }
900 if ( isset( $revisionInfo['timestamp'] ) ) {
901 $revision->setTimestamp( $revisionInfo['timestamp'] );
902 } else {
903 $revision->setTimestamp( wfTimestampNow() );
904 }
905
906 if ( isset( $revisionInfo['comment'] ) ) {
907 $revision->setComment( $revisionInfo['comment'] );
908 }
909
910 if ( isset( $revisionInfo['minor'] ) ) {
911 $revision->setMinor( true );
912 }
913 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
914 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
915 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
916 $revision->setUsername( $revisionInfo['contributor']['username'] );
917 } else {
918 $revision->setUsername( 'Unknown user' );
919 }
920 if ( isset( $revisionInfo['sha1'] ) ) {
921 $revision->setSha1Base36( $revisionInfo['sha1'] );
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 }