Merge "mediawiki.page.patrol.ajax: Rename file to match module name"
[lhc/web/wiklou.git] / includes / Import.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 /** @var Config */
42 private $config;
43 /** @var ImportTitleFactory */
44 private $importTitleFactory;
45 /** @var array */
46 private $countableCache = array();
47
48 /**
49 * Creates an ImportXMLReader drawing from the source provided
50 * @param ImportSource $source
51 * @param Config $config
52 * @throws Exception
53 */
54 function __construct( ImportSource $source, Config $config = null ) {
55 if ( !class_exists( 'XMLReader' ) ) {
56 throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
57 }
58
59 $this->reader = new XMLReader();
60 if ( !$config ) {
61 wfDeprecated( __METHOD__ . ' without a Config instance', '1.25' );
62 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
63 }
64 $this->config = $config;
65
66 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
67 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
68 }
69 $id = UploadSourceAdapter::registerSource( $source );
70
71 // Enable the entity loader, as it is needed for loading external URLs via
72 // XMLReader::open (T86036)
73 $oldDisable = libxml_disable_entity_loader( false );
74 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
75 $status = $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
76 } else {
77 $status = $this->reader->open( "uploadsource://$id" );
78 }
79 if ( !$status ) {
80 $error = libxml_get_last_error();
81 libxml_disable_entity_loader( $oldDisable );
82 throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
83 $error->message );
84 }
85 libxml_disable_entity_loader( $oldDisable );
86
87 // Default callbacks
88 $this->setPageCallback( array( $this, 'beforeImportPage' ) );
89 $this->setRevisionCallback( array( $this, "importRevision" ) );
90 $this->setUploadCallback( array( $this, 'importUpload' ) );
91 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
92 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
93
94 $this->importTitleFactory = new NaiveImportTitleFactory();
95 }
96
97 /**
98 * @return null|XMLReader
99 */
100 public function getReader() {
101 return $this->reader;
102 }
103
104 public function throwXmlError( $err ) {
105 $this->debug( "FAILURE: $err" );
106 wfDebug( "WikiImporter XML error: $err\n" );
107 }
108
109 public function debug( $data ) {
110 if ( $this->mDebug ) {
111 wfDebug( "IMPORT: $data\n" );
112 }
113 }
114
115 public function warn( $data ) {
116 wfDebug( "IMPORT: $data\n" );
117 }
118
119 public function notice( $msg /*, $param, ...*/ ) {
120 $params = func_get_args();
121 array_shift( $params );
122
123 if ( is_callable( $this->mNoticeCallback ) ) {
124 call_user_func( $this->mNoticeCallback, $msg, $params );
125 } else { # No ImportReporter -> CLI
126 echo wfMessage( $msg, $params )->text() . "\n";
127 }
128 }
129
130 /**
131 * Set debug mode...
132 * @param bool $debug
133 */
134 function setDebug( $debug ) {
135 $this->mDebug = $debug;
136 }
137
138 /**
139 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
140 * @param bool $noupdates
141 */
142 function setNoUpdates( $noupdates ) {
143 $this->mNoUpdates = $noupdates;
144 }
145
146 /**
147 * Set a callback that displays notice messages
148 *
149 * @param callable $callback
150 * @return callable
151 */
152 public function setNoticeCallback( $callback ) {
153 return wfSetVar( $this->mNoticeCallback, $callback );
154 }
155
156 /**
157 * Sets the action to perform as each new page in the stream is reached.
158 * @param callable $callback
159 * @return callable
160 */
161 public function setPageCallback( $callback ) {
162 $previous = $this->mPageCallback;
163 $this->mPageCallback = $callback;
164 return $previous;
165 }
166
167 /**
168 * Sets the action to perform as each page in the stream is completed.
169 * Callback accepts the page title (as a Title object), a second object
170 * with the original title form (in case it's been overridden into a
171 * local namespace), and a count of revisions.
172 *
173 * @param callable $callback
174 * @return callable
175 */
176 public function setPageOutCallback( $callback ) {
177 $previous = $this->mPageOutCallback;
178 $this->mPageOutCallback = $callback;
179 return $previous;
180 }
181
182 /**
183 * Sets the action to perform as each page revision is reached.
184 * @param callable $callback
185 * @return callable
186 */
187 public function setRevisionCallback( $callback ) {
188 $previous = $this->mRevisionCallback;
189 $this->mRevisionCallback = $callback;
190 return $previous;
191 }
192
193 /**
194 * Sets the action to perform as each file upload version is reached.
195 * @param callable $callback
196 * @return callable
197 */
198 public function setUploadCallback( $callback ) {
199 $previous = $this->mUploadCallback;
200 $this->mUploadCallback = $callback;
201 return $previous;
202 }
203
204 /**
205 * Sets the action to perform as each log item reached.
206 * @param callable $callback
207 * @return callable
208 */
209 public function setLogItemCallback( $callback ) {
210 $previous = $this->mLogItemCallback;
211 $this->mLogItemCallback = $callback;
212 return $previous;
213 }
214
215 /**
216 * Sets the action to perform when site info is encountered
217 * @param callable $callback
218 * @return callable
219 */
220 public function setSiteInfoCallback( $callback ) {
221 $previous = $this->mSiteInfoCallback;
222 $this->mSiteInfoCallback = $callback;
223 return $previous;
224 }
225
226 /**
227 * Sets the factory object to use to convert ForeignTitle objects into local
228 * Title objects
229 * @param ImportTitleFactory $factory
230 */
231 public function setImportTitleFactory( $factory ) {
232 $this->importTitleFactory = $factory;
233 }
234
235 /**
236 * Set a target namespace to override the defaults
237 * @param null|int $namespace
238 * @return bool
239 */
240 public function setTargetNamespace( $namespace ) {
241 if ( is_null( $namespace ) ) {
242 // Don't override namespaces
243 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
244 return true;
245 } elseif (
246 $namespace >= 0 &&
247 MWNamespace::exists( intval( $namespace ) )
248 ) {
249 $namespace = intval( $namespace );
250 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
251 return true;
252 } else {
253 return false;
254 }
255 }
256
257 /**
258 * Set a target root page under which all pages are imported
259 * @param null|string $rootpage
260 * @return Status
261 */
262 public function setTargetRootPage( $rootpage ) {
263 $status = Status::newGood();
264 if ( is_null( $rootpage ) ) {
265 // No rootpage
266 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
267 } elseif ( $rootpage !== '' ) {
268 $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
269 $title = Title::newFromText( $rootpage );
270
271 if ( !$title || $title->isExternal() ) {
272 $status->fatal( 'import-rootpage-invalid' );
273 } else {
274 if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
275 global $wgContLang;
276
277 $displayNSText = $title->getNamespace() == NS_MAIN
278 ? wfMessage( 'blanknamespace' )->text()
279 : $wgContLang->getNsText( $title->getNamespace() );
280 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
281 } else {
282 // set namespace to 'all', so the namespace check in processTitle() can pass
283 $this->setTargetNamespace( null );
284 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
285 }
286 }
287 }
288 return $status;
289 }
290
291 /**
292 * @param string $dir
293 */
294 public function setImageBasePath( $dir ) {
295 $this->mImageBasePath = $dir;
296 }
297
298 /**
299 * @param bool $import
300 */
301 public function setImportUploads( $import ) {
302 $this->mImportUploads = $import;
303 }
304
305 /**
306 * Default per-page callback. Sets up some things related to site statistics
307 * @param array $titleAndForeignTitle Two-element array, with Title object at
308 * index 0 and ForeignTitle object at index 1
309 * @return bool
310 */
311 public function beforeImportPage( $titleAndForeignTitle ) {
312 $title = $titleAndForeignTitle[0];
313 $page = WikiPage::factory( $title );
314 $this->countableCache['title_' . $title->getPrefixedText()] = $page->isCountable();
315 return true;
316 }
317
318 /**
319 * Default per-revision callback, performs the import.
320 * @param WikiRevision $revision
321 * @return bool
322 */
323 public function importRevision( $revision ) {
324 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
325 $this->notice( 'import-error-bad-location',
326 $revision->getTitle()->getPrefixedText(),
327 $revision->getID(),
328 $revision->getModel(),
329 $revision->getFormat() );
330
331 return false;
332 }
333
334 try {
335 $dbw = wfGetDB( DB_MASTER );
336 return $dbw->deadlockLoop( array( $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 $dbw = wfGetDB( DB_MASTER );
355 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
356 }
357
358 /**
359 * Dummy for now...
360 * @param WikiRevision $revision
361 * @return bool
362 */
363 public function importUpload( $revision ) {
364 $dbw = wfGetDB( DB_MASTER );
365 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
366 }
367
368 /**
369 * Mostly for hook use
370 * @param Title $title
371 * @param ForeignTitle $foreignTitle
372 * @param int $revCount
373 * @param int $sRevCount
374 * @param array $pageInfo
375 * @return bool
376 */
377 public function finishImportPage( $title, $foreignTitle, $revCount,
378 $sRevCount, $pageInfo ) {
379
380 // Update article count statistics (T42009)
381 // The normal counting logic in WikiPage->doEditUpdates() is designed for
382 // one-revision-at-a-time editing, not bulk imports. In this situation it
383 // suffers from issues of slave lag. We let WikiPage handle the total page
384 // and revision count, and we implement our own custom logic for the
385 // article (content page) count.
386 $page = WikiPage::factory( $title );
387 $page->loadPageData( 'fromdbmaster' );
388 $content = $page->getContent();
389 if ( $content === null ) {
390 wfDebug( __METHOD__ . ': Skipping article count adjustment for ' . $title .
391 ' because WikiPage::getContent() returned null' );
392 } else {
393 $editInfo = $page->prepareContentForEdit( $content );
394 $countKey = 'title_' . $title->getPrefixedText();
395 $countable = $page->isCountable( $editInfo );
396 if ( array_key_exists( $countKey, $this->countableCache ) &&
397 $countable != $this->countableCache[$countKey] ) {
398 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array(
399 'articles' => ( (int)$countable - (int)$this->countableCache[$countKey] )
400 ) ) );
401 }
402 }
403
404 $args = func_get_args();
405 return Hooks::run( 'AfterImportPage', $args );
406 }
407
408 /**
409 * Alternate per-revision callback, for debugging.
410 * @param WikiRevision $revision
411 */
412 public function debugRevisionHandler( &$revision ) {
413 $this->debug( "Got revision:" );
414 if ( is_object( $revision->title ) ) {
415 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
416 } else {
417 $this->debug( "-- Title: <invalid>" );
418 }
419 $this->debug( "-- User: " . $revision->user_text );
420 $this->debug( "-- Timestamp: " . $revision->timestamp );
421 $this->debug( "-- Comment: " . $revision->comment );
422 $this->debug( "-- Text: " . $revision->text );
423 }
424
425 /**
426 * Notify the callback function of site info
427 * @param array $siteInfo
428 * @return bool|mixed
429 */
430 private function siteInfoCallback( $siteInfo ) {
431 if ( isset( $this->mSiteInfoCallback ) ) {
432 return call_user_func_array( $this->mSiteInfoCallback,
433 array( $siteInfo, $this ) );
434 } else {
435 return false;
436 }
437 }
438
439 /**
440 * Notify the callback function when a new "<page>" is reached.
441 * @param Title $title
442 */
443 function pageCallback( $title ) {
444 if ( isset( $this->mPageCallback ) ) {
445 call_user_func( $this->mPageCallback, $title );
446 }
447 }
448
449 /**
450 * Notify the callback function when a "</page>" is closed.
451 * @param Title $title
452 * @param ForeignTitle $foreignTitle
453 * @param int $revCount
454 * @param int $sucCount Number of revisions for which callback returned true
455 * @param array $pageInfo Associative array of page information
456 */
457 private function pageOutCallback( $title, $foreignTitle, $revCount,
458 $sucCount, $pageInfo ) {
459 if ( isset( $this->mPageOutCallback ) ) {
460 $args = func_get_args();
461 call_user_func_array( $this->mPageOutCallback, $args );
462 }
463 }
464
465 /**
466 * Notify the callback function of a revision
467 * @param WikiRevision $revision
468 * @return bool|mixed
469 */
470 private function revisionCallback( $revision ) {
471 if ( isset( $this->mRevisionCallback ) ) {
472 return call_user_func_array( $this->mRevisionCallback,
473 array( $revision, $this ) );
474 } else {
475 return false;
476 }
477 }
478
479 /**
480 * Notify the callback function of a new log item
481 * @param WikiRevision $revision
482 * @return bool|mixed
483 */
484 private function logItemCallback( $revision ) {
485 if ( isset( $this->mLogItemCallback ) ) {
486 return call_user_func_array( $this->mLogItemCallback,
487 array( $revision, $this ) );
488 } else {
489 return false;
490 }
491 }
492
493 /**
494 * Retrieves the contents of the named attribute of the current element.
495 * @param string $attr The name of the attribute
496 * @return string The value of the attribute or an empty string if it is not set in the current
497 * element.
498 */
499 public function nodeAttribute( $attr ) {
500 return $this->reader->getAttribute( $attr );
501 }
502
503 /**
504 * Shouldn't something like this be built-in to XMLReader?
505 * Fetches text contents of the current element, assuming
506 * no sub-elements or such scary things.
507 * @return string
508 * @access private
509 */
510 public function nodeContents() {
511 if ( $this->reader->isEmptyElement ) {
512 return "";
513 }
514 $buffer = "";
515 while ( $this->reader->read() ) {
516 switch ( $this->reader->nodeType ) {
517 case XMLReader::TEXT:
518 case XMLReader::CDATA:
519 case XMLReader::SIGNIFICANT_WHITESPACE:
520 $buffer .= $this->reader->value;
521 break;
522 case XMLReader::END_ELEMENT:
523 return $buffer;
524 }
525 }
526
527 $this->reader->close();
528 return '';
529 }
530
531 /**
532 * Primary entry point
533 * @throws MWException
534 * @return bool
535 */
536 public function doImport() {
537 // Calls to reader->read need to be wrapped in calls to
538 // libxml_disable_entity_loader() to avoid local file
539 // inclusion attacks (bug 46932).
540 $oldDisable = libxml_disable_entity_loader( true );
541 $this->reader->read();
542
543 if ( $this->reader->localName != 'mediawiki' ) {
544 libxml_disable_entity_loader( $oldDisable );
545 throw new MWException( "Expected <mediawiki> tag, got " .
546 $this->reader->localName );
547 }
548 $this->debug( "<mediawiki> tag is correct." );
549
550 $this->debug( "Starting primary dump processing loop." );
551
552 $keepReading = $this->reader->read();
553 $skip = false;
554 $rethrow = null;
555 try {
556 while ( $keepReading ) {
557 $tag = $this->reader->localName;
558 $type = $this->reader->nodeType;
559
560 if ( !Hooks::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
561 // Do nothing
562 } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
563 break;
564 } elseif ( $tag == 'siteinfo' ) {
565 $this->handleSiteInfo();
566 } elseif ( $tag == 'page' ) {
567 $this->handlePage();
568 } elseif ( $tag == 'logitem' ) {
569 $this->handleLogItem();
570 } elseif ( $tag != '#text' ) {
571 $this->warn( "Unhandled top-level XML tag $tag" );
572
573 $skip = true;
574 }
575
576 if ( $skip ) {
577 $keepReading = $this->reader->next();
578 $skip = false;
579 $this->debug( "Skip" );
580 } else {
581 $keepReading = $this->reader->read();
582 }
583 }
584 } catch ( Exception $ex ) {
585 $rethrow = $ex;
586 }
587
588 // finally
589 libxml_disable_entity_loader( $oldDisable );
590 $this->reader->close();
591
592 if ( $rethrow ) {
593 throw $rethrow;
594 }
595
596 return true;
597 }
598
599 private function handleSiteInfo() {
600 $this->debug( "Enter site info handler." );
601 $siteInfo = array();
602
603 // Fields that can just be stuffed in the siteInfo object
604 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
605
606 while ( $this->reader->read() ) {
607 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
608 $this->reader->localName == 'siteinfo' ) {
609 break;
610 }
611
612 $tag = $this->reader->localName;
613
614 if ( $tag == 'namespace' ) {
615 $this->foreignNamespaces[$this->nodeAttribute( 'key' )] =
616 $this->nodeContents();
617 } elseif ( in_array( $tag, $normalFields ) ) {
618 $siteInfo[$tag] = $this->nodeContents();
619 }
620 }
621
622 $siteInfo['_namespaces'] = $this->foreignNamespaces;
623 $this->siteInfoCallback( $siteInfo );
624 }
625
626 private function handleLogItem() {
627 $this->debug( "Enter log item handler." );
628 $logInfo = array();
629
630 // Fields that can just be stuffed in the pageInfo object
631 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
632 'logtitle', 'params' );
633
634 while ( $this->reader->read() ) {
635 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
636 $this->reader->localName == 'logitem' ) {
637 break;
638 }
639
640 $tag = $this->reader->localName;
641
642 if ( !Hooks::run( 'ImportHandleLogItemXMLTag', array(
643 $this, $logInfo
644 ) ) ) {
645 // Do nothing
646 } elseif ( in_array( $tag, $normalFields ) ) {
647 $logInfo[$tag] = $this->nodeContents();
648 } elseif ( $tag == 'contributor' ) {
649 $logInfo['contributor'] = $this->handleContributor();
650 } elseif ( $tag != '#text' ) {
651 $this->warn( "Unhandled log-item XML tag $tag" );
652 }
653 }
654
655 $this->processLogItem( $logInfo );
656 }
657
658 /**
659 * @param array $logInfo
660 * @return bool|mixed
661 */
662 private function processLogItem( $logInfo ) {
663
664 $revision = new WikiRevision( $this->config );
665
666 if ( isset( $logInfo['id'] ) ) {
667 $revision->setID( $logInfo['id'] );
668 }
669 $revision->setType( $logInfo['type'] );
670 $revision->setAction( $logInfo['action'] );
671 if ( isset( $logInfo['timestamp'] ) ) {
672 $revision->setTimestamp( $logInfo['timestamp'] );
673 }
674 if ( isset( $logInfo['params'] ) ) {
675 $revision->setParams( $logInfo['params'] );
676 }
677 if ( isset( $logInfo['logtitle'] ) ) {
678 // @todo Using Title for non-local titles is a recipe for disaster.
679 // We should use ForeignTitle here instead.
680 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
681 }
682
683 $revision->setNoUpdates( $this->mNoUpdates );
684
685 if ( isset( $logInfo['comment'] ) ) {
686 $revision->setComment( $logInfo['comment'] );
687 }
688
689 if ( isset( $logInfo['contributor']['ip'] ) ) {
690 $revision->setUserIP( $logInfo['contributor']['ip'] );
691 }
692
693 if ( !isset( $logInfo['contributor']['username'] ) ) {
694 $revision->setUsername( 'Unknown user' );
695 } else {
696 $revision->setUserName( $logInfo['contributor']['username'] );
697 }
698
699 return $this->logItemCallback( $revision );
700 }
701
702 private function handlePage() {
703 // Handle page data.
704 $this->debug( "Enter page handler." );
705 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
706
707 // Fields that can just be stuffed in the pageInfo object
708 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
709
710 $skip = false;
711 $badTitle = false;
712
713 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
714 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
715 $this->reader->localName == 'page' ) {
716 break;
717 }
718
719 $skip = false;
720
721 $tag = $this->reader->localName;
722
723 if ( $badTitle ) {
724 // The title is invalid, bail out of this page
725 $skip = true;
726 } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', array( $this,
727 &$pageInfo ) ) ) {
728 // Do nothing
729 } elseif ( in_array( $tag, $normalFields ) ) {
730 // An XML snippet:
731 // <page>
732 // <id>123</id>
733 // <title>Page</title>
734 // <redirect title="NewTitle"/>
735 // ...
736 // Because the redirect tag is built differently, we need special handling for that case.
737 if ( $tag == 'redirect' ) {
738 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
739 } else {
740 $pageInfo[$tag] = $this->nodeContents();
741 }
742 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
743 if ( !isset( $title ) ) {
744 $title = $this->processTitle( $pageInfo['title'],
745 isset( $pageInfo['ns'] ) ? $pageInfo['ns'] : null );
746
747 // $title is either an array of two titles or false.
748 if ( is_array( $title ) ) {
749 $this->pageCallback( $title );
750 list( $pageInfo['_title'], $foreignTitle ) = $title;
751 } else {
752 $badTitle = true;
753 $skip = true;
754 }
755 }
756
757 if ( $title ) {
758 if ( $tag == 'revision' ) {
759 $this->handleRevision( $pageInfo );
760 } else {
761 $this->handleUpload( $pageInfo );
762 }
763 }
764 } elseif ( $tag != '#text' ) {
765 $this->warn( "Unhandled page XML tag $tag" );
766 $skip = true;
767 }
768 }
769
770 // @note $pageInfo is only set if a valid $title is processed above with
771 // no error. If we have a valid $title, then pageCallback is called
772 // above, $pageInfo['title'] is set and we do pageOutCallback here.
773 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
774 // set since they both come from $title above.
775 if ( array_key_exists( '_title', $pageInfo ) ) {
776 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
777 $pageInfo['revisionCount'],
778 $pageInfo['successfulRevisionCount'],
779 $pageInfo );
780 }
781 }
782
783 /**
784 * @param array $pageInfo
785 */
786 private function handleRevision( &$pageInfo ) {
787 $this->debug( "Enter revision handler" );
788 $revisionInfo = array();
789
790 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
791
792 $skip = false;
793
794 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
795 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
796 $this->reader->localName == 'revision' ) {
797 break;
798 }
799
800 $tag = $this->reader->localName;
801
802 if ( !Hooks::run( 'ImportHandleRevisionXMLTag', array(
803 $this, $pageInfo, $revisionInfo
804 ) ) ) {
805 // Do nothing
806 } elseif ( in_array( $tag, $normalFields ) ) {
807 $revisionInfo[$tag] = $this->nodeContents();
808 } elseif ( $tag == 'contributor' ) {
809 $revisionInfo['contributor'] = $this->handleContributor();
810 } elseif ( $tag != '#text' ) {
811 $this->warn( "Unhandled revision XML tag $tag" );
812 $skip = true;
813 }
814 }
815
816 $pageInfo['revisionCount']++;
817 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
818 $pageInfo['successfulRevisionCount']++;
819 }
820 }
821
822 /**
823 * @param array $pageInfo
824 * @param array $revisionInfo
825 * @return bool|mixed
826 */
827 private function processRevision( $pageInfo, $revisionInfo ) {
828 $revision = new WikiRevision( $this->config );
829
830 if ( isset( $revisionInfo['id'] ) ) {
831 $revision->setID( $revisionInfo['id'] );
832 }
833 if ( isset( $revisionInfo['model'] ) ) {
834 $revision->setModel( $revisionInfo['model'] );
835 }
836 if ( isset( $revisionInfo['format'] ) ) {
837 $revision->setFormat( $revisionInfo['format'] );
838 }
839 $revision->setTitle( $pageInfo['_title'] );
840
841 if ( isset( $revisionInfo['text'] ) ) {
842 $handler = $revision->getContentHandler();
843 $text = $handler->importTransform(
844 $revisionInfo['text'],
845 $revision->getFormat() );
846
847 $revision->setText( $text );
848 }
849 if ( isset( $revisionInfo['timestamp'] ) ) {
850 $revision->setTimestamp( $revisionInfo['timestamp'] );
851 } else {
852 $revision->setTimestamp( wfTimestampNow() );
853 }
854
855 if ( isset( $revisionInfo['comment'] ) ) {
856 $revision->setComment( $revisionInfo['comment'] );
857 }
858
859 if ( isset( $revisionInfo['minor'] ) ) {
860 $revision->setMinor( true );
861 }
862 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
863 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
864 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
865 $revision->setUserName( $revisionInfo['contributor']['username'] );
866 } else {
867 $revision->setUserName( 'Unknown user' );
868 }
869 $revision->setNoUpdates( $this->mNoUpdates );
870
871 return $this->revisionCallback( $revision );
872 }
873
874 /**
875 * @param array $pageInfo
876 * @return mixed
877 */
878 private function handleUpload( &$pageInfo ) {
879 $this->debug( "Enter upload handler" );
880 $uploadInfo = array();
881
882 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
883 'src', 'size', 'sha1base36', 'archivename', 'rel' );
884
885 $skip = false;
886
887 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
888 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
889 $this->reader->localName == 'upload' ) {
890 break;
891 }
892
893 $tag = $this->reader->localName;
894
895 if ( !Hooks::run( 'ImportHandleUploadXMLTag', array(
896 $this, $pageInfo
897 ) ) ) {
898 // Do nothing
899 } elseif ( in_array( $tag, $normalFields ) ) {
900 $uploadInfo[$tag] = $this->nodeContents();
901 } elseif ( $tag == 'contributor' ) {
902 $uploadInfo['contributor'] = $this->handleContributor();
903 } elseif ( $tag == 'contents' ) {
904 $contents = $this->nodeContents();
905 $encoding = $this->reader->getAttribute( 'encoding' );
906 if ( $encoding === 'base64' ) {
907 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
908 $uploadInfo['isTempSrc'] = true;
909 }
910 } elseif ( $tag != '#text' ) {
911 $this->warn( "Unhandled upload XML tag $tag" );
912 $skip = true;
913 }
914 }
915
916 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
917 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
918 if ( file_exists( $path ) ) {
919 $uploadInfo['fileSrc'] = $path;
920 $uploadInfo['isTempSrc'] = false;
921 }
922 }
923
924 if ( $this->mImportUploads ) {
925 return $this->processUpload( $pageInfo, $uploadInfo );
926 }
927 }
928
929 /**
930 * @param string $contents
931 * @return string
932 */
933 private function dumpTemp( $contents ) {
934 $filename = tempnam( wfTempDir(), 'importupload' );
935 file_put_contents( $filename, $contents );
936 return $filename;
937 }
938
939 /**
940 * @param array $pageInfo
941 * @param array $uploadInfo
942 * @return mixed
943 */
944 private function processUpload( $pageInfo, $uploadInfo ) {
945 $revision = new WikiRevision( $this->config );
946 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
947
948 $revision->setTitle( $pageInfo['_title'] );
949 $revision->setID( $pageInfo['id'] );
950 $revision->setTimestamp( $uploadInfo['timestamp'] );
951 $revision->setText( $text );
952 $revision->setFilename( $uploadInfo['filename'] );
953 if ( isset( $uploadInfo['archivename'] ) ) {
954 $revision->setArchiveName( $uploadInfo['archivename'] );
955 }
956 $revision->setSrc( $uploadInfo['src'] );
957 if ( isset( $uploadInfo['fileSrc'] ) ) {
958 $revision->setFileSrc( $uploadInfo['fileSrc'],
959 !empty( $uploadInfo['isTempSrc'] ) );
960 }
961 if ( isset( $uploadInfo['sha1base36'] ) ) {
962 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
963 }
964 $revision->setSize( intval( $uploadInfo['size'] ) );
965 $revision->setComment( $uploadInfo['comment'] );
966
967 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
968 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
969 }
970 if ( isset( $uploadInfo['contributor']['username'] ) ) {
971 $revision->setUserName( $uploadInfo['contributor']['username'] );
972 }
973 $revision->setNoUpdates( $this->mNoUpdates );
974
975 return call_user_func( $this->mUploadCallback, $revision );
976 }
977
978 /**
979 * @return array
980 */
981 private function handleContributor() {
982 $fields = array( 'id', 'ip', 'username' );
983 $info = array();
984
985 if ( $this->reader->isEmptyElement ) {
986 return $info;
987 }
988 while ( $this->reader->read() ) {
989 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
990 $this->reader->localName == 'contributor' ) {
991 break;
992 }
993
994 $tag = $this->reader->localName;
995
996 if ( in_array( $tag, $fields ) ) {
997 $info[$tag] = $this->nodeContents();
998 }
999 }
1000
1001 return $info;
1002 }
1003
1004 /**
1005 * @param string $text
1006 * @param string|null $ns
1007 * @return array|bool
1008 */
1009 private function processTitle( $text, $ns = null ) {
1010 if ( is_null( $this->foreignNamespaces ) ) {
1011 $foreignTitleFactory = new NaiveForeignTitleFactory();
1012 } else {
1013 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1014 $this->foreignNamespaces );
1015 }
1016
1017 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1018 intval( $ns ) );
1019
1020 $title = $this->importTitleFactory->createTitleFromForeignTitle(
1021 $foreignTitle );
1022
1023 $commandLineMode = $this->config->get( 'CommandLineMode' );
1024 if ( is_null( $title ) ) {
1025 # Invalid page title? Ignore the page
1026 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1027 return false;
1028 } elseif ( $title->isExternal() ) {
1029 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1030 return false;
1031 } elseif ( !$title->canExist() ) {
1032 $this->notice( 'import-error-special', $title->getPrefixedText() );
1033 return false;
1034 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1035 # Do not import if the importing wiki user cannot edit this page
1036 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1037 return false;
1038 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1039 # Do not import if the importing wiki user cannot create this page
1040 $this->notice( 'import-error-create', $title->getPrefixedText() );
1041 return false;
1042 }
1043
1044 return array( $title, $foreignTitle );
1045 }
1046 }
1047
1048 /** This is a horrible hack used to keep source compatibility */
1049 class UploadSourceAdapter {
1050 /** @var array */
1051 public static $sourceRegistrations = array();
1052
1053 /** @var string */
1054 private $mSource;
1055
1056 /** @var string */
1057 private $mBuffer;
1058
1059 /** @var int */
1060 private $mPosition;
1061
1062 /**
1063 * @param ImportSource $source
1064 * @return string
1065 */
1066 static function registerSource( ImportSource $source ) {
1067 $id = wfRandomString();
1068
1069 self::$sourceRegistrations[$id] = $source;
1070
1071 return $id;
1072 }
1073
1074 /**
1075 * @param string $path
1076 * @param string $mode
1077 * @param array $options
1078 * @param string $opened_path
1079 * @return bool
1080 */
1081 function stream_open( $path, $mode, $options, &$opened_path ) {
1082 $url = parse_url( $path );
1083 $id = $url['host'];
1084
1085 if ( !isset( self::$sourceRegistrations[$id] ) ) {
1086 return false;
1087 }
1088
1089 $this->mSource = self::$sourceRegistrations[$id];
1090
1091 return true;
1092 }
1093
1094 /**
1095 * @param int $count
1096 * @return string
1097 */
1098 function stream_read( $count ) {
1099 $return = '';
1100 $leave = false;
1101
1102 while ( !$leave && !$this->mSource->atEnd() &&
1103 strlen( $this->mBuffer ) < $count ) {
1104 $read = $this->mSource->readChunk();
1105
1106 if ( !strlen( $read ) ) {
1107 $leave = true;
1108 }
1109
1110 $this->mBuffer .= $read;
1111 }
1112
1113 if ( strlen( $this->mBuffer ) ) {
1114 $return = substr( $this->mBuffer, 0, $count );
1115 $this->mBuffer = substr( $this->mBuffer, $count );
1116 }
1117
1118 $this->mPosition += strlen( $return );
1119
1120 return $return;
1121 }
1122
1123 /**
1124 * @param string $data
1125 * @return bool
1126 */
1127 function stream_write( $data ) {
1128 return false;
1129 }
1130
1131 /**
1132 * @return mixed
1133 */
1134 function stream_tell() {
1135 return $this->mPosition;
1136 }
1137
1138 /**
1139 * @return bool
1140 */
1141 function stream_eof() {
1142 return $this->mSource->atEnd();
1143 }
1144
1145 /**
1146 * @return array
1147 */
1148 function url_stat() {
1149 $result = array();
1150
1151 $result['dev'] = $result[0] = 0;
1152 $result['ino'] = $result[1] = 0;
1153 $result['mode'] = $result[2] = 0;
1154 $result['nlink'] = $result[3] = 0;
1155 $result['uid'] = $result[4] = 0;
1156 $result['gid'] = $result[5] = 0;
1157 $result['rdev'] = $result[6] = 0;
1158 $result['size'] = $result[7] = 0;
1159 $result['atime'] = $result[8] = 0;
1160 $result['mtime'] = $result[9] = 0;
1161 $result['ctime'] = $result[10] = 0;
1162 $result['blksize'] = $result[11] = 0;
1163 $result['blocks'] = $result[12] = 0;
1164
1165 return $result;
1166 }
1167 }
1168
1169 /**
1170 * @todo document (e.g. one-sentence class description).
1171 * @ingroup SpecialPage
1172 */
1173 class WikiRevision {
1174 /** @todo Unused? */
1175 public $importer = null;
1176
1177 /** @var Title */
1178 public $title = null;
1179
1180 /** @var int */
1181 public $id = 0;
1182
1183 /** @var string */
1184 public $timestamp = "20010115000000";
1185
1186 /**
1187 * @var int
1188 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1189 public $user = 0;
1190
1191 /** @var string */
1192 public $user_text = "";
1193
1194 /** @var string */
1195 public $model = null;
1196
1197 /** @var string */
1198 public $format = null;
1199
1200 /** @var string */
1201 public $text = "";
1202
1203 /** @var int */
1204 protected $size;
1205
1206 /** @var Content */
1207 public $content = null;
1208
1209 /** @var ContentHandler */
1210 protected $contentHandler = null;
1211
1212 /** @var string */
1213 public $comment = "";
1214
1215 /** @var bool */
1216 public $minor = false;
1217
1218 /** @var string */
1219 public $type = "";
1220
1221 /** @var string */
1222 public $action = "";
1223
1224 /** @var string */
1225 public $params = "";
1226
1227 /** @var string */
1228 public $fileSrc = '';
1229
1230 /** @var bool|string */
1231 public $sha1base36 = false;
1232
1233 /**
1234 * @var bool
1235 * @todo Unused?
1236 */
1237 public $isTemp = false;
1238
1239 /** @var string */
1240 public $archiveName = '';
1241
1242 protected $filename;
1243
1244 /** @var mixed */
1245 protected $src;
1246
1247 /** @todo Unused? */
1248 public $fileIsTemp;
1249
1250 /** @var bool */
1251 private $mNoUpdates = false;
1252
1253 /** @var Config $config */
1254 private $config;
1255
1256 public function __construct( Config $config ) {
1257 $this->config = $config;
1258 }
1259
1260 /**
1261 * @param Title $title
1262 * @throws MWException
1263 */
1264 function setTitle( $title ) {
1265 if ( is_object( $title ) ) {
1266 $this->title = $title;
1267 } elseif ( is_null( $title ) ) {
1268 throw new MWException( "WikiRevision given a null title in import. "
1269 . "You may need to adjust \$wgLegalTitleChars." );
1270 } else {
1271 throw new MWException( "WikiRevision given non-object title in import." );
1272 }
1273 }
1274
1275 /**
1276 * @param int $id
1277 */
1278 function setID( $id ) {
1279 $this->id = $id;
1280 }
1281
1282 /**
1283 * @param string $ts
1284 */
1285 function setTimestamp( $ts ) {
1286 # 2003-08-05T18:30:02Z
1287 $this->timestamp = wfTimestamp( TS_MW, $ts );
1288 }
1289
1290 /**
1291 * @param string $user
1292 */
1293 function setUsername( $user ) {
1294 $this->user_text = $user;
1295 }
1296
1297 /**
1298 * @param string $ip
1299 */
1300 function setUserIP( $ip ) {
1301 $this->user_text = $ip;
1302 }
1303
1304 /**
1305 * @param string $model
1306 */
1307 function setModel( $model ) {
1308 $this->model = $model;
1309 }
1310
1311 /**
1312 * @param string $format
1313 */
1314 function setFormat( $format ) {
1315 $this->format = $format;
1316 }
1317
1318 /**
1319 * @param string $text
1320 */
1321 function setText( $text ) {
1322 $this->text = $text;
1323 }
1324
1325 /**
1326 * @param string $text
1327 */
1328 function setComment( $text ) {
1329 $this->comment = $text;
1330 }
1331
1332 /**
1333 * @param bool $minor
1334 */
1335 function setMinor( $minor ) {
1336 $this->minor = (bool)$minor;
1337 }
1338
1339 /**
1340 * @param mixed $src
1341 */
1342 function setSrc( $src ) {
1343 $this->src = $src;
1344 }
1345
1346 /**
1347 * @param string $src
1348 * @param bool $isTemp
1349 */
1350 function setFileSrc( $src, $isTemp ) {
1351 $this->fileSrc = $src;
1352 $this->fileIsTemp = $isTemp;
1353 }
1354
1355 /**
1356 * @param string $sha1base36
1357 */
1358 function setSha1Base36( $sha1base36 ) {
1359 $this->sha1base36 = $sha1base36;
1360 }
1361
1362 /**
1363 * @param string $filename
1364 */
1365 function setFilename( $filename ) {
1366 $this->filename = $filename;
1367 }
1368
1369 /**
1370 * @param string $archiveName
1371 */
1372 function setArchiveName( $archiveName ) {
1373 $this->archiveName = $archiveName;
1374 }
1375
1376 /**
1377 * @param int $size
1378 */
1379 function setSize( $size ) {
1380 $this->size = intval( $size );
1381 }
1382
1383 /**
1384 * @param string $type
1385 */
1386 function setType( $type ) {
1387 $this->type = $type;
1388 }
1389
1390 /**
1391 * @param string $action
1392 */
1393 function setAction( $action ) {
1394 $this->action = $action;
1395 }
1396
1397 /**
1398 * @param array $params
1399 */
1400 function setParams( $params ) {
1401 $this->params = $params;
1402 }
1403
1404 /**
1405 * @param bool $noupdates
1406 */
1407 public function setNoUpdates( $noupdates ) {
1408 $this->mNoUpdates = $noupdates;
1409 }
1410
1411 /**
1412 * @return Title
1413 */
1414 function getTitle() {
1415 return $this->title;
1416 }
1417
1418 /**
1419 * @return int
1420 */
1421 function getID() {
1422 return $this->id;
1423 }
1424
1425 /**
1426 * @return string
1427 */
1428 function getTimestamp() {
1429 return $this->timestamp;
1430 }
1431
1432 /**
1433 * @return string
1434 */
1435 function getUser() {
1436 return $this->user_text;
1437 }
1438
1439 /**
1440 * @return string
1441 *
1442 * @deprecated Since 1.21, use getContent() instead.
1443 */
1444 function getText() {
1445 ContentHandler::deprecated( __METHOD__, '1.21' );
1446
1447 return $this->text;
1448 }
1449
1450 /**
1451 * @return ContentHandler
1452 */
1453 function getContentHandler() {
1454 if ( is_null( $this->contentHandler ) ) {
1455 $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
1456 }
1457
1458 return $this->contentHandler;
1459 }
1460
1461 /**
1462 * @return Content
1463 */
1464 function getContent() {
1465 if ( is_null( $this->content ) ) {
1466 $handler = $this->getContentHandler();
1467 $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
1468 }
1469
1470 return $this->content;
1471 }
1472
1473 /**
1474 * @return string
1475 */
1476 function getModel() {
1477 if ( is_null( $this->model ) ) {
1478 $this->model = $this->getTitle()->getContentModel();
1479 }
1480
1481 return $this->model;
1482 }
1483
1484 /**
1485 * @return string
1486 */
1487 function getFormat() {
1488 if ( is_null( $this->format ) ) {
1489 $this->format = $this->getContentHandler()->getDefaultFormat();
1490 }
1491
1492 return $this->format;
1493 }
1494
1495 /**
1496 * @return string
1497 */
1498 function getComment() {
1499 return $this->comment;
1500 }
1501
1502 /**
1503 * @return bool
1504 */
1505 function getMinor() {
1506 return $this->minor;
1507 }
1508
1509 /**
1510 * @return mixed
1511 */
1512 function getSrc() {
1513 return $this->src;
1514 }
1515
1516 /**
1517 * @return bool|string
1518 */
1519 function getSha1() {
1520 if ( $this->sha1base36 ) {
1521 return Wikimedia\base_convert( $this->sha1base36, 36, 16 );
1522 }
1523 return false;
1524 }
1525
1526 /**
1527 * @return string
1528 */
1529 function getFileSrc() {
1530 return $this->fileSrc;
1531 }
1532
1533 /**
1534 * @return bool
1535 */
1536 function isTempSrc() {
1537 return $this->isTemp;
1538 }
1539
1540 /**
1541 * @return mixed
1542 */
1543 function getFilename() {
1544 return $this->filename;
1545 }
1546
1547 /**
1548 * @return string
1549 */
1550 function getArchiveName() {
1551 return $this->archiveName;
1552 }
1553
1554 /**
1555 * @return mixed
1556 */
1557 function getSize() {
1558 return $this->size;
1559 }
1560
1561 /**
1562 * @return string
1563 */
1564 function getType() {
1565 return $this->type;
1566 }
1567
1568 /**
1569 * @return string
1570 */
1571 function getAction() {
1572 return $this->action;
1573 }
1574
1575 /**
1576 * @return string
1577 */
1578 function getParams() {
1579 return $this->params;
1580 }
1581
1582 /**
1583 * @return bool
1584 */
1585 function importOldRevision() {
1586 $dbw = wfGetDB( DB_MASTER );
1587
1588 # Sneak a single revision into place
1589 $user = User::newFromName( $this->getUser() );
1590 if ( $user ) {
1591 $userId = intval( $user->getId() );
1592 $userText = $user->getName();
1593 $userObj = $user;
1594 } else {
1595 $userId = 0;
1596 $userText = $this->getUser();
1597 $userObj = new User;
1598 }
1599
1600 // avoid memory leak...?
1601 Title::clearCaches();
1602
1603 $page = WikiPage::factory( $this->title );
1604 $page->loadPageData( 'fromdbmaster' );
1605 if ( !$page->exists() ) {
1606 # must create the page...
1607 $pageId = $page->insertOn( $dbw );
1608 $created = true;
1609 $oldcountable = null;
1610 } else {
1611 $pageId = $page->getId();
1612 $created = false;
1613
1614 $prior = $dbw->selectField( 'revision', '1',
1615 array( 'rev_page' => $pageId,
1616 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1617 'rev_user_text' => $userText,
1618 'rev_comment' => $this->getComment() ),
1619 __METHOD__
1620 );
1621 if ( $prior ) {
1622 // @todo FIXME: This could fail slightly for multiple matches :P
1623 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1624 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1625 return false;
1626 }
1627 }
1628
1629 // Select previous version to make size diffs correct
1630 $prevId = $dbw->selectField( 'revision', 'rev_id',
1631 array(
1632 'rev_page' => $pageId,
1633 'rev_timestamp <= ' . $dbw->timestamp( $this->timestamp ),
1634 ),
1635 __METHOD__,
1636 array( 'ORDER BY' => array(
1637 'rev_timestamp DESC',
1638 'rev_id DESC', // timestamp is not unique per page
1639 )
1640 )
1641 );
1642
1643 # @todo FIXME: Use original rev_id optionally (better for backups)
1644 # Insert the row
1645 $revision = new Revision( array(
1646 'title' => $this->title,
1647 'page' => $pageId,
1648 'content_model' => $this->getModel(),
1649 'content_format' => $this->getFormat(),
1650 // XXX: just set 'content' => $this->getContent()?
1651 'text' => $this->getContent()->serialize( $this->getFormat() ),
1652 'comment' => $this->getComment(),
1653 'user' => $userId,
1654 'user_text' => $userText,
1655 'timestamp' => $this->timestamp,
1656 'minor_edit' => $this->minor,
1657 'parent_id' => $prevId,
1658 ) );
1659 $revision->insertOn( $dbw );
1660 $changed = $page->updateIfNewerOn( $dbw, $revision );
1661
1662 if ( $changed !== false && !$this->mNoUpdates ) {
1663 wfDebug( __METHOD__ . ": running updates\n" );
1664 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
1665 $page->doEditUpdates(
1666 $revision,
1667 $userObj,
1668 array( 'created' => $created, 'oldcountable' => 'no-change' )
1669 );
1670 }
1671
1672 return true;
1673 }
1674
1675 function importLogItem() {
1676 $dbw = wfGetDB( DB_MASTER );
1677
1678 $user = User::newFromName( $this->getUser() );
1679 if ( $user ) {
1680 $userId = intval( $user->getId() );
1681 $userText = $user->getName();
1682 } else {
1683 $userId = 0;
1684 $userText = $this->getUser();
1685 }
1686
1687 # @todo FIXME: This will not record autoblocks
1688 if ( !$this->getTitle() ) {
1689 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1690 $this->timestamp . "\n" );
1691 return;
1692 }
1693 # Check if it exists already
1694 // @todo FIXME: Use original log ID (better for backups)
1695 $prior = $dbw->selectField( 'logging', '1',
1696 array( 'log_type' => $this->getType(),
1697 'log_action' => $this->getAction(),
1698 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1699 'log_namespace' => $this->getTitle()->getNamespace(),
1700 'log_title' => $this->getTitle()->getDBkey(),
1701 'log_comment' => $this->getComment(),
1702 # 'log_user_text' => $this->user_text,
1703 'log_params' => $this->params ),
1704 __METHOD__
1705 );
1706 // @todo FIXME: This could fail slightly for multiple matches :P
1707 if ( $prior ) {
1708 wfDebug( __METHOD__
1709 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1710 . $this->timestamp . "\n" );
1711 return;
1712 }
1713 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1714 $data = array(
1715 'log_id' => $log_id,
1716 'log_type' => $this->type,
1717 'log_action' => $this->action,
1718 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1719 'log_user' => $userId,
1720 'log_user_text' => $userText,
1721 'log_namespace' => $this->getTitle()->getNamespace(),
1722 'log_title' => $this->getTitle()->getDBkey(),
1723 'log_comment' => $this->getComment(),
1724 'log_params' => $this->params
1725 );
1726 $dbw->insert( 'logging', $data, __METHOD__ );
1727 }
1728
1729 /**
1730 * @return bool
1731 */
1732 function importUpload() {
1733 # Construct a file
1734 $archiveName = $this->getArchiveName();
1735 if ( $archiveName ) {
1736 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1737 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1738 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1739 } else {
1740 $file = wfLocalFile( $this->getTitle() );
1741 $file->load( File::READ_LATEST );
1742 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1743 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1744 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1745 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1746 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1747 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1748 }
1749 }
1750 if ( !$file ) {
1751 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1752 return false;
1753 }
1754
1755 # Get the file source or download if necessary
1756 $source = $this->getFileSrc();
1757 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1758 if ( !$source ) {
1759 $source = $this->downloadSource();
1760 $flags |= File::DELETE_SOURCE;
1761 }
1762 if ( !$source ) {
1763 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1764 return false;
1765 }
1766 $sha1 = $this->getSha1();
1767 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1768 if ( $flags & File::DELETE_SOURCE ) {
1769 # Broken file; delete it if it is a temporary file
1770 unlink( $source );
1771 }
1772 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1773 return false;
1774 }
1775
1776 $user = User::newFromName( $this->user_text );
1777
1778 # Do the actual upload
1779 if ( $archiveName ) {
1780 $status = $file->uploadOld( $source, $archiveName,
1781 $this->getTimestamp(), $this->getComment(), $user, $flags );
1782 } else {
1783 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1784 $flags, false, $this->getTimestamp(), $user );
1785 }
1786
1787 if ( $status->isGood() ) {
1788 wfDebug( __METHOD__ . ": Successful\n" );
1789 return true;
1790 } else {
1791 wfDebug( __METHOD__ . ': failed: ' . $status->getHTML() . "\n" );
1792 return false;
1793 }
1794 }
1795
1796 /**
1797 * @return bool|string
1798 */
1799 function downloadSource() {
1800 if ( !$this->config->get( 'EnableUploads' ) ) {
1801 return false;
1802 }
1803
1804 $tempo = tempnam( wfTempDir(), 'download' );
1805 $f = fopen( $tempo, 'wb' );
1806 if ( !$f ) {
1807 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1808 return false;
1809 }
1810
1811 // @todo FIXME!
1812 $src = $this->getSrc();
1813 $data = Http::get( $src, array(), __METHOD__ );
1814 if ( !$data ) {
1815 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1816 fclose( $f );
1817 unlink( $tempo );
1818 return false;
1819 }
1820
1821 fwrite( $f, $data );
1822 fclose( $f );
1823
1824 return $tempo;
1825 }
1826
1827 }
1828
1829 /**
1830 * Source interface for XML import.
1831 */
1832 interface ImportSource {
1833
1834 /**
1835 * Indicates whether the end of the input has been reached.
1836 * Will return true after a finite number of calls to readChunk.
1837 *
1838 * @return bool true if there is no more input, false otherwise.
1839 */
1840 function atEnd();
1841
1842 /**
1843 * Return a chunk of the input, as a (possibly empty) string.
1844 * When the end of input is reached, readChunk() returns false.
1845 * If atEnd() returns false, readChunk() will return a string.
1846 * If atEnd() returns true, readChunk() will return false.
1847 *
1848 * @return bool|string
1849 */
1850 function readChunk();
1851 }
1852
1853 /**
1854 * Used for importing XML dumps where the content of the dump is in a string.
1855 * This class is ineffecient, and should only be used for small dumps.
1856 * For larger dumps, ImportStreamSource should be used instead.
1857 *
1858 * @ingroup SpecialPage
1859 */
1860 class ImportStringSource implements ImportSource {
1861 function __construct( $string ) {
1862 $this->mString = $string;
1863 $this->mRead = false;
1864 }
1865
1866 /**
1867 * @return bool
1868 */
1869 function atEnd() {
1870 return $this->mRead;
1871 }
1872
1873 /**
1874 * @return bool|string
1875 */
1876 function readChunk() {
1877 if ( $this->atEnd() ) {
1878 return false;
1879 }
1880 $this->mRead = true;
1881 return $this->mString;
1882 }
1883 }
1884
1885 /**
1886 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1887 * @ingroup SpecialPage
1888 */
1889 class ImportStreamSource implements ImportSource {
1890 function __construct( $handle ) {
1891 $this->mHandle = $handle;
1892 }
1893
1894 /**
1895 * @return bool
1896 */
1897 function atEnd() {
1898 return feof( $this->mHandle );
1899 }
1900
1901 /**
1902 * @return string
1903 */
1904 function readChunk() {
1905 return fread( $this->mHandle, 32768 );
1906 }
1907
1908 /**
1909 * @param string $filename
1910 * @return Status
1911 */
1912 static function newFromFile( $filename ) {
1913 MediaWiki\suppressWarnings();
1914 $file = fopen( $filename, 'rt' );
1915 MediaWiki\restoreWarnings();
1916 if ( !$file ) {
1917 return Status::newFatal( "importcantopen" );
1918 }
1919 return Status::newGood( new ImportStreamSource( $file ) );
1920 }
1921
1922 /**
1923 * @param string $fieldname
1924 * @return Status
1925 */
1926 static function newFromUpload( $fieldname = "xmlimport" ) {
1927 $upload =& $_FILES[$fieldname];
1928
1929 if ( $upload === null || !$upload['name'] ) {
1930 return Status::newFatal( 'importnofile' );
1931 }
1932 if ( !empty( $upload['error'] ) ) {
1933 switch ( $upload['error'] ) {
1934 case 1:
1935 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1936 return Status::newFatal( 'importuploaderrorsize' );
1937 case 2:
1938 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1939 # was specified in the HTML form.
1940 return Status::newFatal( 'importuploaderrorsize' );
1941 case 3:
1942 # The uploaded file was only partially uploaded
1943 return Status::newFatal( 'importuploaderrorpartial' );
1944 case 6:
1945 # Missing a temporary folder.
1946 return Status::newFatal( 'importuploaderrortemp' );
1947 # case else: # Currently impossible
1948 }
1949
1950 }
1951 $fname = $upload['tmp_name'];
1952 if ( is_uploaded_file( $fname ) ) {
1953 return ImportStreamSource::newFromFile( $fname );
1954 } else {
1955 return Status::newFatal( 'importnofile' );
1956 }
1957 }
1958
1959 /**
1960 * @param string $url
1961 * @param string $method
1962 * @return Status
1963 */
1964 static function newFromURL( $url, $method = 'GET' ) {
1965 wfDebug( __METHOD__ . ": opening $url\n" );
1966 # Use the standard HTTP fetch function; it times out
1967 # quicker and sorts out user-agent problems which might
1968 # otherwise prevent importing from large sites, such
1969 # as the Wikimedia cluster, etc.
1970 $data = Http::request( $method, $url, array( 'followRedirects' => true ), __METHOD__ );
1971 if ( $data !== false ) {
1972 $file = tmpfile();
1973 fwrite( $file, $data );
1974 fflush( $file );
1975 fseek( $file, 0 );
1976 return Status::newGood( new ImportStreamSource( $file ) );
1977 } else {
1978 return Status::newFatal( 'importcantopen' );
1979 }
1980 }
1981
1982 /**
1983 * @param string $interwiki
1984 * @param string $page
1985 * @param bool $history
1986 * @param bool $templates
1987 * @param int $pageLinkDepth
1988 * @return Status
1989 */
1990 public static function newFromInterwiki( $interwiki, $page, $history = false,
1991 $templates = false, $pageLinkDepth = 0
1992 ) {
1993 if ( $page == '' ) {
1994 return Status::newFatal( 'import-noarticle' );
1995 }
1996
1997 # Look up the first interwiki prefix, and let the foreign site handle
1998 # subsequent interwiki prefixes
1999 $firstIwPrefix = strtok( $interwiki, ':' );
2000 $firstIw = Interwiki::fetch( $firstIwPrefix );
2001 if ( !$firstIw ) {
2002 return Status::newFatal( 'importbadinterwiki' );
2003 }
2004
2005 $additionalIwPrefixes = strtok( '' );
2006 if ( $additionalIwPrefixes ) {
2007 $additionalIwPrefixes .= ':';
2008 }
2009 # Have to do a DB-key replacement ourselves; otherwise spaces get
2010 # URL-encoded to +, which is wrong in this case. Similar to logic in
2011 # Title::getLocalURL
2012 $link = $firstIw->getURL( strtr( "${additionalIwPrefixes}Special:Export/$page",
2013 ' ', '_' ) );
2014
2015 $params = array();
2016 if ( $history ) {
2017 $params['history'] = 1;
2018 }
2019 if ( $templates ) {
2020 $params['templates'] = 1;
2021 }
2022 if ( $pageLinkDepth ) {
2023 $params['pagelink-depth'] = $pageLinkDepth;
2024 }
2025
2026 $url = wfAppendQuery( $link, $params );
2027 # For interwikis, use POST to avoid redirects.
2028 return ImportStreamSource::newFromURL( $url, "POST" );
2029 }
2030 }