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