Merge "Don't check namespace in SpecialWantedtemplates"
[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::SIGNIFICANT_WHITESPACE:
519 $buffer .= $this->reader->value;
520 break;
521 case XMLReader::END_ELEMENT:
522 return $buffer;
523 }
524 }
525
526 $this->reader->close();
527 return '';
528 }
529
530 /**
531 * Primary entry point
532 * @throws MWException
533 * @return bool
534 */
535 public function doImport() {
536 // Calls to reader->read need to be wrapped in calls to
537 // libxml_disable_entity_loader() to avoid local file
538 // inclusion attacks (bug 46932).
539 $oldDisable = libxml_disable_entity_loader( true );
540 $this->reader->read();
541
542 if ( $this->reader->localName != 'mediawiki' ) {
543 libxml_disable_entity_loader( $oldDisable );
544 throw new MWException( "Expected <mediawiki> tag, got " .
545 $this->reader->localName );
546 }
547 $this->debug( "<mediawiki> tag is correct." );
548
549 $this->debug( "Starting primary dump processing loop." );
550
551 $keepReading = $this->reader->read();
552 $skip = false;
553 $rethrow = null;
554 try {
555 while ( $keepReading ) {
556 $tag = $this->reader->localName;
557 $type = $this->reader->nodeType;
558
559 if ( !Hooks::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
560 // Do nothing
561 } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
562 break;
563 } elseif ( $tag == 'siteinfo' ) {
564 $this->handleSiteInfo();
565 } elseif ( $tag == 'page' ) {
566 $this->handlePage();
567 } elseif ( $tag == 'logitem' ) {
568 $this->handleLogItem();
569 } elseif ( $tag != '#text' ) {
570 $this->warn( "Unhandled top-level XML tag $tag" );
571
572 $skip = true;
573 }
574
575 if ( $skip ) {
576 $keepReading = $this->reader->next();
577 $skip = false;
578 $this->debug( "Skip" );
579 } else {
580 $keepReading = $this->reader->read();
581 }
582 }
583 } catch ( Exception $ex ) {
584 $rethrow = $ex;
585 }
586
587 // finally
588 libxml_disable_entity_loader( $oldDisable );
589 $this->reader->close();
590
591 if ( $rethrow ) {
592 throw $rethrow;
593 }
594
595 return true;
596 }
597
598 private function handleSiteInfo() {
599 $this->debug( "Enter site info handler." );
600 $siteInfo = array();
601
602 // Fields that can just be stuffed in the siteInfo object
603 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
604
605 while ( $this->reader->read() ) {
606 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
607 $this->reader->localName == 'siteinfo' ) {
608 break;
609 }
610
611 $tag = $this->reader->localName;
612
613 if ( $tag == 'namespace' ) {
614 $this->foreignNamespaces[$this->nodeAttribute( 'key' )] =
615 $this->nodeContents();
616 } elseif ( in_array( $tag, $normalFields ) ) {
617 $siteInfo[$tag] = $this->nodeContents();
618 }
619 }
620
621 $siteInfo['_namespaces'] = $this->foreignNamespaces;
622 $this->siteInfoCallback( $siteInfo );
623 }
624
625 private function handleLogItem() {
626 $this->debug( "Enter log item handler." );
627 $logInfo = array();
628
629 // Fields that can just be stuffed in the pageInfo object
630 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
631 'logtitle', 'params' );
632
633 while ( $this->reader->read() ) {
634 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
635 $this->reader->localName == 'logitem' ) {
636 break;
637 }
638
639 $tag = $this->reader->localName;
640
641 if ( !Hooks::run( 'ImportHandleLogItemXMLTag', array(
642 $this, $logInfo
643 ) ) ) {
644 // Do nothing
645 } elseif ( in_array( $tag, $normalFields ) ) {
646 $logInfo[$tag] = $this->nodeContents();
647 } elseif ( $tag == 'contributor' ) {
648 $logInfo['contributor'] = $this->handleContributor();
649 } elseif ( $tag != '#text' ) {
650 $this->warn( "Unhandled log-item XML tag $tag" );
651 }
652 }
653
654 $this->processLogItem( $logInfo );
655 }
656
657 /**
658 * @param array $logInfo
659 * @return bool|mixed
660 */
661 private function processLogItem( $logInfo ) {
662 $revision = new WikiRevision( $this->config );
663
664 $revision->setID( $logInfo['id'] );
665 $revision->setType( $logInfo['type'] );
666 $revision->setAction( $logInfo['action'] );
667 $revision->setTimestamp( $logInfo['timestamp'] );
668 $revision->setParams( $logInfo['params'] );
669 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
670 $revision->setNoUpdates( $this->mNoUpdates );
671
672 if ( isset( $logInfo['comment'] ) ) {
673 $revision->setComment( $logInfo['comment'] );
674 }
675
676 if ( isset( $logInfo['contributor']['ip'] ) ) {
677 $revision->setUserIP( $logInfo['contributor']['ip'] );
678 }
679 if ( isset( $logInfo['contributor']['username'] ) ) {
680 $revision->setUserName( $logInfo['contributor']['username'] );
681 }
682
683 return $this->logItemCallback( $revision );
684 }
685
686 private function handlePage() {
687 // Handle page data.
688 $this->debug( "Enter page handler." );
689 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
690
691 // Fields that can just be stuffed in the pageInfo object
692 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
693
694 $skip = false;
695 $badTitle = false;
696
697 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
698 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
699 $this->reader->localName == 'page' ) {
700 break;
701 }
702
703 $skip = false;
704
705 $tag = $this->reader->localName;
706
707 if ( $badTitle ) {
708 // The title is invalid, bail out of this page
709 $skip = true;
710 } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', array( $this,
711 &$pageInfo ) ) ) {
712 // Do nothing
713 } elseif ( in_array( $tag, $normalFields ) ) {
714 // An XML snippet:
715 // <page>
716 // <id>123</id>
717 // <title>Page</title>
718 // <redirect title="NewTitle"/>
719 // ...
720 // Because the redirect tag is built differently, we need special handling for that case.
721 if ( $tag == 'redirect' ) {
722 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
723 } else {
724 $pageInfo[$tag] = $this->nodeContents();
725 }
726 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
727 if ( !isset( $title ) ) {
728 $title = $this->processTitle( $pageInfo['title'],
729 isset( $pageInfo['ns'] ) ? $pageInfo['ns'] : null );
730
731 if ( !$title ) {
732 $badTitle = true;
733 $skip = true;
734 }
735
736 $this->pageCallback( $title );
737 list( $pageInfo['_title'], $foreignTitle ) = $title;
738 }
739
740 if ( $title ) {
741 if ( $tag == 'revision' ) {
742 $this->handleRevision( $pageInfo );
743 } else {
744 $this->handleUpload( $pageInfo );
745 }
746 }
747 } elseif ( $tag != '#text' ) {
748 $this->warn( "Unhandled page XML tag $tag" );
749 $skip = true;
750 }
751 }
752
753 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
754 $pageInfo['revisionCount'],
755 $pageInfo['successfulRevisionCount'],
756 $pageInfo );
757 }
758
759 /**
760 * @param array $pageInfo
761 */
762 private function handleRevision( &$pageInfo ) {
763 $this->debug( "Enter revision handler" );
764 $revisionInfo = array();
765
766 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
767
768 $skip = false;
769
770 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
771 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
772 $this->reader->localName == 'revision' ) {
773 break;
774 }
775
776 $tag = $this->reader->localName;
777
778 if ( !Hooks::run( 'ImportHandleRevisionXMLTag', array(
779 $this, $pageInfo, $revisionInfo
780 ) ) ) {
781 // Do nothing
782 } elseif ( in_array( $tag, $normalFields ) ) {
783 $revisionInfo[$tag] = $this->nodeContents();
784 } elseif ( $tag == 'contributor' ) {
785 $revisionInfo['contributor'] = $this->handleContributor();
786 } elseif ( $tag != '#text' ) {
787 $this->warn( "Unhandled revision XML tag $tag" );
788 $skip = true;
789 }
790 }
791
792 $pageInfo['revisionCount']++;
793 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
794 $pageInfo['successfulRevisionCount']++;
795 }
796 }
797
798 /**
799 * @param array $pageInfo
800 * @param array $revisionInfo
801 * @return bool|mixed
802 */
803 private function processRevision( $pageInfo, $revisionInfo ) {
804 $revision = new WikiRevision( $this->config );
805
806 if ( isset( $revisionInfo['id'] ) ) {
807 $revision->setID( $revisionInfo['id'] );
808 }
809 if ( isset( $revisionInfo['model'] ) ) {
810 $revision->setModel( $revisionInfo['model'] );
811 }
812 if ( isset( $revisionInfo['format'] ) ) {
813 $revision->setFormat( $revisionInfo['format'] );
814 }
815 $revision->setTitle( $pageInfo['_title'] );
816
817 if ( isset( $revisionInfo['text'] ) ) {
818 $handler = $revision->getContentHandler();
819 $text = $handler->importTransform(
820 $revisionInfo['text'],
821 $revision->getFormat() );
822
823 $revision->setText( $text );
824 }
825 if ( isset( $revisionInfo['timestamp'] ) ) {
826 $revision->setTimestamp( $revisionInfo['timestamp'] );
827 } else {
828 $revision->setTimestamp( wfTimestampNow() );
829 }
830
831 if ( isset( $revisionInfo['comment'] ) ) {
832 $revision->setComment( $revisionInfo['comment'] );
833 }
834
835 if ( isset( $revisionInfo['minor'] ) ) {
836 $revision->setMinor( true );
837 }
838 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
839 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
840 }
841 if ( isset( $revisionInfo['contributor']['username'] ) ) {
842 $revision->setUserName( $revisionInfo['contributor']['username'] );
843 }
844 $revision->setNoUpdates( $this->mNoUpdates );
845
846 return $this->revisionCallback( $revision );
847 }
848
849 /**
850 * @param array $pageInfo
851 * @return mixed
852 */
853 private function handleUpload( &$pageInfo ) {
854 $this->debug( "Enter upload handler" );
855 $uploadInfo = array();
856
857 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
858 'src', 'size', 'sha1base36', 'archivename', 'rel' );
859
860 $skip = false;
861
862 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
863 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
864 $this->reader->localName == 'upload' ) {
865 break;
866 }
867
868 $tag = $this->reader->localName;
869
870 if ( !Hooks::run( 'ImportHandleUploadXMLTag', array(
871 $this, $pageInfo
872 ) ) ) {
873 // Do nothing
874 } elseif ( in_array( $tag, $normalFields ) ) {
875 $uploadInfo[$tag] = $this->nodeContents();
876 } elseif ( $tag == 'contributor' ) {
877 $uploadInfo['contributor'] = $this->handleContributor();
878 } elseif ( $tag == 'contents' ) {
879 $contents = $this->nodeContents();
880 $encoding = $this->reader->getAttribute( 'encoding' );
881 if ( $encoding === 'base64' ) {
882 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
883 $uploadInfo['isTempSrc'] = true;
884 }
885 } elseif ( $tag != '#text' ) {
886 $this->warn( "Unhandled upload XML tag $tag" );
887 $skip = true;
888 }
889 }
890
891 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
892 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
893 if ( file_exists( $path ) ) {
894 $uploadInfo['fileSrc'] = $path;
895 $uploadInfo['isTempSrc'] = false;
896 }
897 }
898
899 if ( $this->mImportUploads ) {
900 return $this->processUpload( $pageInfo, $uploadInfo );
901 }
902 }
903
904 /**
905 * @param string $contents
906 * @return string
907 */
908 private function dumpTemp( $contents ) {
909 $filename = tempnam( wfTempDir(), 'importupload' );
910 file_put_contents( $filename, $contents );
911 return $filename;
912 }
913
914 /**
915 * @param array $pageInfo
916 * @param array $uploadInfo
917 * @return mixed
918 */
919 private function processUpload( $pageInfo, $uploadInfo ) {
920 $revision = new WikiRevision( $this->config );
921 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
922
923 $revision->setTitle( $pageInfo['_title'] );
924 $revision->setID( $pageInfo['id'] );
925 $revision->setTimestamp( $uploadInfo['timestamp'] );
926 $revision->setText( $text );
927 $revision->setFilename( $uploadInfo['filename'] );
928 if ( isset( $uploadInfo['archivename'] ) ) {
929 $revision->setArchiveName( $uploadInfo['archivename'] );
930 }
931 $revision->setSrc( $uploadInfo['src'] );
932 if ( isset( $uploadInfo['fileSrc'] ) ) {
933 $revision->setFileSrc( $uploadInfo['fileSrc'],
934 !empty( $uploadInfo['isTempSrc'] ) );
935 }
936 if ( isset( $uploadInfo['sha1base36'] ) ) {
937 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
938 }
939 $revision->setSize( intval( $uploadInfo['size'] ) );
940 $revision->setComment( $uploadInfo['comment'] );
941
942 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
943 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
944 }
945 if ( isset( $uploadInfo['contributor']['username'] ) ) {
946 $revision->setUserName( $uploadInfo['contributor']['username'] );
947 }
948 $revision->setNoUpdates( $this->mNoUpdates );
949
950 return call_user_func( $this->mUploadCallback, $revision );
951 }
952
953 /**
954 * @return array
955 */
956 private function handleContributor() {
957 $fields = array( 'id', 'ip', 'username' );
958 $info = array();
959
960 while ( $this->reader->read() ) {
961 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
962 $this->reader->localName == 'contributor' ) {
963 break;
964 }
965
966 $tag = $this->reader->localName;
967
968 if ( in_array( $tag, $fields ) ) {
969 $info[$tag] = $this->nodeContents();
970 }
971 }
972
973 return $info;
974 }
975
976 /**
977 * @param string $text
978 * @param string|null $ns
979 * @return array|bool
980 */
981 private function processTitle( $text, $ns = null ) {
982 if ( is_null( $this->foreignNamespaces ) ) {
983 $foreignTitleFactory = new NaiveForeignTitleFactory();
984 } else {
985 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
986 $this->foreignNamespaces );
987 }
988
989 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
990 intval( $ns ) );
991
992 $title = $this->importTitleFactory->createTitleFromForeignTitle(
993 $foreignTitle );
994
995 $commandLineMode = $this->config->get( 'CommandLineMode' );
996 if ( is_null( $title ) ) {
997 # Invalid page title? Ignore the page
998 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
999 return false;
1000 } elseif ( $title->isExternal() ) {
1001 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1002 return false;
1003 } elseif ( !$title->canExist() ) {
1004 $this->notice( 'import-error-special', $title->getPrefixedText() );
1005 return false;
1006 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1007 # Do not import if the importing wiki user cannot edit this page
1008 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1009 return false;
1010 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1011 # Do not import if the importing wiki user cannot create this page
1012 $this->notice( 'import-error-create', $title->getPrefixedText() );
1013 return false;
1014 }
1015
1016 return array( $title, $foreignTitle );
1017 }
1018 }
1019
1020 /** This is a horrible hack used to keep source compatibility */
1021 class UploadSourceAdapter {
1022 /** @var array */
1023 public static $sourceRegistrations = array();
1024
1025 /** @var string */
1026 private $mSource;
1027
1028 /** @var string */
1029 private $mBuffer;
1030
1031 /** @var int */
1032 private $mPosition;
1033
1034 /**
1035 * @param ImportSource $source
1036 * @return string
1037 */
1038 static function registerSource( ImportSource $source ) {
1039 $id = wfRandomString();
1040
1041 self::$sourceRegistrations[$id] = $source;
1042
1043 return $id;
1044 }
1045
1046 /**
1047 * @param string $path
1048 * @param string $mode
1049 * @param array $options
1050 * @param string $opened_path
1051 * @return bool
1052 */
1053 function stream_open( $path, $mode, $options, &$opened_path ) {
1054 $url = parse_url( $path );
1055 $id = $url['host'];
1056
1057 if ( !isset( self::$sourceRegistrations[$id] ) ) {
1058 return false;
1059 }
1060
1061 $this->mSource = self::$sourceRegistrations[$id];
1062
1063 return true;
1064 }
1065
1066 /**
1067 * @param int $count
1068 * @return string
1069 */
1070 function stream_read( $count ) {
1071 $return = '';
1072 $leave = false;
1073
1074 while ( !$leave && !$this->mSource->atEnd() &&
1075 strlen( $this->mBuffer ) < $count ) {
1076 $read = $this->mSource->readChunk();
1077
1078 if ( !strlen( $read ) ) {
1079 $leave = true;
1080 }
1081
1082 $this->mBuffer .= $read;
1083 }
1084
1085 if ( strlen( $this->mBuffer ) ) {
1086 $return = substr( $this->mBuffer, 0, $count );
1087 $this->mBuffer = substr( $this->mBuffer, $count );
1088 }
1089
1090 $this->mPosition += strlen( $return );
1091
1092 return $return;
1093 }
1094
1095 /**
1096 * @param string $data
1097 * @return bool
1098 */
1099 function stream_write( $data ) {
1100 return false;
1101 }
1102
1103 /**
1104 * @return mixed
1105 */
1106 function stream_tell() {
1107 return $this->mPosition;
1108 }
1109
1110 /**
1111 * @return bool
1112 */
1113 function stream_eof() {
1114 return $this->mSource->atEnd();
1115 }
1116
1117 /**
1118 * @return array
1119 */
1120 function url_stat() {
1121 $result = array();
1122
1123 $result['dev'] = $result[0] = 0;
1124 $result['ino'] = $result[1] = 0;
1125 $result['mode'] = $result[2] = 0;
1126 $result['nlink'] = $result[3] = 0;
1127 $result['uid'] = $result[4] = 0;
1128 $result['gid'] = $result[5] = 0;
1129 $result['rdev'] = $result[6] = 0;
1130 $result['size'] = $result[7] = 0;
1131 $result['atime'] = $result[8] = 0;
1132 $result['mtime'] = $result[9] = 0;
1133 $result['ctime'] = $result[10] = 0;
1134 $result['blksize'] = $result[11] = 0;
1135 $result['blocks'] = $result[12] = 0;
1136
1137 return $result;
1138 }
1139 }
1140
1141 /**
1142 * @todo document (e.g. one-sentence class description).
1143 * @ingroup SpecialPage
1144 */
1145 class WikiRevision {
1146 /** @todo Unused? */
1147 public $importer = null;
1148
1149 /** @var Title */
1150 public $title = null;
1151
1152 /** @var int */
1153 public $id = 0;
1154
1155 /** @var string */
1156 public $timestamp = "20010115000000";
1157
1158 /**
1159 * @var int
1160 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1161 public $user = 0;
1162
1163 /** @var string */
1164 public $user_text = "";
1165
1166 /** @var string */
1167 public $model = null;
1168
1169 /** @var string */
1170 public $format = null;
1171
1172 /** @var string */
1173 public $text = "";
1174
1175 /** @var int */
1176 protected $size;
1177
1178 /** @var Content */
1179 public $content = null;
1180
1181 /** @var ContentHandler */
1182 protected $contentHandler = null;
1183
1184 /** @var string */
1185 public $comment = "";
1186
1187 /** @var bool */
1188 public $minor = false;
1189
1190 /** @var string */
1191 public $type = "";
1192
1193 /** @var string */
1194 public $action = "";
1195
1196 /** @var string */
1197 public $params = "";
1198
1199 /** @var string */
1200 public $fileSrc = '';
1201
1202 /** @var bool|string */
1203 public $sha1base36 = false;
1204
1205 /**
1206 * @var bool
1207 * @todo Unused?
1208 */
1209 public $isTemp = false;
1210
1211 /** @var string */
1212 public $archiveName = '';
1213
1214 protected $filename;
1215
1216 /** @var mixed */
1217 protected $src;
1218
1219 /** @todo Unused? */
1220 public $fileIsTemp;
1221
1222 /** @var bool */
1223 private $mNoUpdates = false;
1224
1225 /** @var Config $config */
1226 private $config;
1227
1228 public function __construct( Config $config ) {
1229 $this->config = $config;
1230 }
1231
1232 /**
1233 * @param Title $title
1234 * @throws MWException
1235 */
1236 function setTitle( $title ) {
1237 if ( is_object( $title ) ) {
1238 $this->title = $title;
1239 } elseif ( is_null( $title ) ) {
1240 throw new MWException( "WikiRevision given a null title in import. "
1241 . "You may need to adjust \$wgLegalTitleChars." );
1242 } else {
1243 throw new MWException( "WikiRevision given non-object title in import." );
1244 }
1245 }
1246
1247 /**
1248 * @param int $id
1249 */
1250 function setID( $id ) {
1251 $this->id = $id;
1252 }
1253
1254 /**
1255 * @param string $ts
1256 */
1257 function setTimestamp( $ts ) {
1258 # 2003-08-05T18:30:02Z
1259 $this->timestamp = wfTimestamp( TS_MW, $ts );
1260 }
1261
1262 /**
1263 * @param string $user
1264 */
1265 function setUsername( $user ) {
1266 $this->user_text = $user;
1267 }
1268
1269 /**
1270 * @param string $ip
1271 */
1272 function setUserIP( $ip ) {
1273 $this->user_text = $ip;
1274 }
1275
1276 /**
1277 * @param string $model
1278 */
1279 function setModel( $model ) {
1280 $this->model = $model;
1281 }
1282
1283 /**
1284 * @param string $format
1285 */
1286 function setFormat( $format ) {
1287 $this->format = $format;
1288 }
1289
1290 /**
1291 * @param string $text
1292 */
1293 function setText( $text ) {
1294 $this->text = $text;
1295 }
1296
1297 /**
1298 * @param string $text
1299 */
1300 function setComment( $text ) {
1301 $this->comment = $text;
1302 }
1303
1304 /**
1305 * @param bool $minor
1306 */
1307 function setMinor( $minor ) {
1308 $this->minor = (bool)$minor;
1309 }
1310
1311 /**
1312 * @param mixed $src
1313 */
1314 function setSrc( $src ) {
1315 $this->src = $src;
1316 }
1317
1318 /**
1319 * @param string $src
1320 * @param bool $isTemp
1321 */
1322 function setFileSrc( $src, $isTemp ) {
1323 $this->fileSrc = $src;
1324 $this->fileIsTemp = $isTemp;
1325 }
1326
1327 /**
1328 * @param string $sha1base36
1329 */
1330 function setSha1Base36( $sha1base36 ) {
1331 $this->sha1base36 = $sha1base36;
1332 }
1333
1334 /**
1335 * @param string $filename
1336 */
1337 function setFilename( $filename ) {
1338 $this->filename = $filename;
1339 }
1340
1341 /**
1342 * @param string $archiveName
1343 */
1344 function setArchiveName( $archiveName ) {
1345 $this->archiveName = $archiveName;
1346 }
1347
1348 /**
1349 * @param int $size
1350 */
1351 function setSize( $size ) {
1352 $this->size = intval( $size );
1353 }
1354
1355 /**
1356 * @param string $type
1357 */
1358 function setType( $type ) {
1359 $this->type = $type;
1360 }
1361
1362 /**
1363 * @param string $action
1364 */
1365 function setAction( $action ) {
1366 $this->action = $action;
1367 }
1368
1369 /**
1370 * @param array $params
1371 */
1372 function setParams( $params ) {
1373 $this->params = $params;
1374 }
1375
1376 /**
1377 * @param bool $noupdates
1378 */
1379 public function setNoUpdates( $noupdates ) {
1380 $this->mNoUpdates = $noupdates;
1381 }
1382
1383 /**
1384 * @return Title
1385 */
1386 function getTitle() {
1387 return $this->title;
1388 }
1389
1390 /**
1391 * @return int
1392 */
1393 function getID() {
1394 return $this->id;
1395 }
1396
1397 /**
1398 * @return string
1399 */
1400 function getTimestamp() {
1401 return $this->timestamp;
1402 }
1403
1404 /**
1405 * @return string
1406 */
1407 function getUser() {
1408 return $this->user_text;
1409 }
1410
1411 /**
1412 * @return string
1413 *
1414 * @deprecated Since 1.21, use getContent() instead.
1415 */
1416 function getText() {
1417 ContentHandler::deprecated( __METHOD__, '1.21' );
1418
1419 return $this->text;
1420 }
1421
1422 /**
1423 * @return ContentHandler
1424 */
1425 function getContentHandler() {
1426 if ( is_null( $this->contentHandler ) ) {
1427 $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
1428 }
1429
1430 return $this->contentHandler;
1431 }
1432
1433 /**
1434 * @return Content
1435 */
1436 function getContent() {
1437 if ( is_null( $this->content ) ) {
1438 $handler = $this->getContentHandler();
1439 $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
1440 }
1441
1442 return $this->content;
1443 }
1444
1445 /**
1446 * @return string
1447 */
1448 function getModel() {
1449 if ( is_null( $this->model ) ) {
1450 $this->model = $this->getTitle()->getContentModel();
1451 }
1452
1453 return $this->model;
1454 }
1455
1456 /**
1457 * @return string
1458 */
1459 function getFormat() {
1460 if ( is_null( $this->format ) ) {
1461 $this->format = $this->getContentHandler()->getDefaultFormat();
1462 }
1463
1464 return $this->format;
1465 }
1466
1467 /**
1468 * @return string
1469 */
1470 function getComment() {
1471 return $this->comment;
1472 }
1473
1474 /**
1475 * @return bool
1476 */
1477 function getMinor() {
1478 return $this->minor;
1479 }
1480
1481 /**
1482 * @return mixed
1483 */
1484 function getSrc() {
1485 return $this->src;
1486 }
1487
1488 /**
1489 * @return bool|string
1490 */
1491 function getSha1() {
1492 if ( $this->sha1base36 ) {
1493 return wfBaseConvert( $this->sha1base36, 36, 16 );
1494 }
1495 return false;
1496 }
1497
1498 /**
1499 * @return string
1500 */
1501 function getFileSrc() {
1502 return $this->fileSrc;
1503 }
1504
1505 /**
1506 * @return bool
1507 */
1508 function isTempSrc() {
1509 return $this->isTemp;
1510 }
1511
1512 /**
1513 * @return mixed
1514 */
1515 function getFilename() {
1516 return $this->filename;
1517 }
1518
1519 /**
1520 * @return string
1521 */
1522 function getArchiveName() {
1523 return $this->archiveName;
1524 }
1525
1526 /**
1527 * @return mixed
1528 */
1529 function getSize() {
1530 return $this->size;
1531 }
1532
1533 /**
1534 * @return string
1535 */
1536 function getType() {
1537 return $this->type;
1538 }
1539
1540 /**
1541 * @return string
1542 */
1543 function getAction() {
1544 return $this->action;
1545 }
1546
1547 /**
1548 * @return string
1549 */
1550 function getParams() {
1551 return $this->params;
1552 }
1553
1554 /**
1555 * @return bool
1556 */
1557 function importOldRevision() {
1558 $dbw = wfGetDB( DB_MASTER );
1559
1560 # Sneak a single revision into place
1561 $user = User::newFromName( $this->getUser() );
1562 if ( $user ) {
1563 $userId = intval( $user->getId() );
1564 $userText = $user->getName();
1565 $userObj = $user;
1566 } else {
1567 $userId = 0;
1568 $userText = $this->getUser();
1569 $userObj = new User;
1570 }
1571
1572 // avoid memory leak...?
1573 Title::clearCaches();
1574
1575 $page = WikiPage::factory( $this->title );
1576 $page->loadPageData( 'fromdbmaster' );
1577 if ( !$page->exists() ) {
1578 # must create the page...
1579 $pageId = $page->insertOn( $dbw );
1580 $created = true;
1581 $oldcountable = null;
1582 } else {
1583 $pageId = $page->getId();
1584 $created = false;
1585
1586 $prior = $dbw->selectField( 'revision', '1',
1587 array( 'rev_page' => $pageId,
1588 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1589 'rev_user_text' => $userText,
1590 'rev_comment' => $this->getComment() ),
1591 __METHOD__
1592 );
1593 if ( $prior ) {
1594 // @todo FIXME: This could fail slightly for multiple matches :P
1595 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1596 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1597 return false;
1598 }
1599 }
1600
1601 # @todo FIXME: Use original rev_id optionally (better for backups)
1602 # Insert the row
1603 $revision = new Revision( array(
1604 'title' => $this->title,
1605 'page' => $pageId,
1606 'content_model' => $this->getModel(),
1607 'content_format' => $this->getFormat(),
1608 //XXX: just set 'content' => $this->getContent()?
1609 'text' => $this->getContent()->serialize( $this->getFormat() ),
1610 'comment' => $this->getComment(),
1611 'user' => $userId,
1612 'user_text' => $userText,
1613 'timestamp' => $this->timestamp,
1614 'minor_edit' => $this->minor,
1615 ) );
1616 $revision->insertOn( $dbw );
1617 $changed = $page->updateIfNewerOn( $dbw, $revision );
1618
1619 if ( $changed !== false && !$this->mNoUpdates ) {
1620 wfDebug( __METHOD__ . ": running updates\n" );
1621 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
1622 $page->doEditUpdates(
1623 $revision,
1624 $userObj,
1625 array( 'created' => $created, 'oldcountable' => 'no-change' )
1626 );
1627 }
1628
1629 return true;
1630 }
1631
1632 function importLogItem() {
1633 $dbw = wfGetDB( DB_MASTER );
1634 # @todo FIXME: This will not record autoblocks
1635 if ( !$this->getTitle() ) {
1636 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1637 $this->timestamp . "\n" );
1638 return;
1639 }
1640 # Check if it exists already
1641 // @todo FIXME: Use original log ID (better for backups)
1642 $prior = $dbw->selectField( 'logging', '1',
1643 array( 'log_type' => $this->getType(),
1644 'log_action' => $this->getAction(),
1645 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1646 'log_namespace' => $this->getTitle()->getNamespace(),
1647 'log_title' => $this->getTitle()->getDBkey(),
1648 'log_comment' => $this->getComment(),
1649 #'log_user_text' => $this->user_text,
1650 'log_params' => $this->params ),
1651 __METHOD__
1652 );
1653 // @todo FIXME: This could fail slightly for multiple matches :P
1654 if ( $prior ) {
1655 wfDebug( __METHOD__
1656 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1657 . $this->timestamp . "\n" );
1658 return;
1659 }
1660 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1661 $data = array(
1662 'log_id' => $log_id,
1663 'log_type' => $this->type,
1664 'log_action' => $this->action,
1665 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1666 'log_user' => User::idFromName( $this->user_text ),
1667 #'log_user_text' => $this->user_text,
1668 'log_namespace' => $this->getTitle()->getNamespace(),
1669 'log_title' => $this->getTitle()->getDBkey(),
1670 'log_comment' => $this->getComment(),
1671 'log_params' => $this->params
1672 );
1673 $dbw->insert( 'logging', $data, __METHOD__ );
1674 }
1675
1676 /**
1677 * @return bool
1678 */
1679 function importUpload() {
1680 # Construct a file
1681 $archiveName = $this->getArchiveName();
1682 if ( $archiveName ) {
1683 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1684 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1685 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1686 } else {
1687 $file = wfLocalFile( $this->getTitle() );
1688 $file->load( File::READ_LATEST );
1689 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1690 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1691 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1692 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1693 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1694 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1695 }
1696 }
1697 if ( !$file ) {
1698 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1699 return false;
1700 }
1701
1702 # Get the file source or download if necessary
1703 $source = $this->getFileSrc();
1704 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1705 if ( !$source ) {
1706 $source = $this->downloadSource();
1707 $flags |= File::DELETE_SOURCE;
1708 }
1709 if ( !$source ) {
1710 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1711 return false;
1712 }
1713 $sha1 = $this->getSha1();
1714 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1715 if ( $flags & File::DELETE_SOURCE ) {
1716 # Broken file; delete it if it is a temporary file
1717 unlink( $source );
1718 }
1719 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1720 return false;
1721 }
1722
1723 $user = User::newFromName( $this->user_text );
1724
1725 # Do the actual upload
1726 if ( $archiveName ) {
1727 $status = $file->uploadOld( $source, $archiveName,
1728 $this->getTimestamp(), $this->getComment(), $user, $flags );
1729 } else {
1730 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1731 $flags, false, $this->getTimestamp(), $user );
1732 }
1733
1734 if ( $status->isGood() ) {
1735 wfDebug( __METHOD__ . ": Successful\n" );
1736 return true;
1737 } else {
1738 wfDebug( __METHOD__ . ': failed: ' . $status->getHTML() . "\n" );
1739 return false;
1740 }
1741 }
1742
1743 /**
1744 * @return bool|string
1745 */
1746 function downloadSource() {
1747 if ( !$this->config->get( 'EnableUploads' ) ) {
1748 return false;
1749 }
1750
1751 $tempo = tempnam( wfTempDir(), 'download' );
1752 $f = fopen( $tempo, 'wb' );
1753 if ( !$f ) {
1754 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1755 return false;
1756 }
1757
1758 // @todo FIXME!
1759 $src = $this->getSrc();
1760 $data = Http::get( $src, array(), __METHOD__ );
1761 if ( !$data ) {
1762 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1763 fclose( $f );
1764 unlink( $tempo );
1765 return false;
1766 }
1767
1768 fwrite( $f, $data );
1769 fclose( $f );
1770
1771 return $tempo;
1772 }
1773
1774 }
1775
1776 /**
1777 * Source interface for XML import.
1778 */
1779 interface ImportSource {
1780
1781 /**
1782 * Indicates whether the end of the input has been reached.
1783 * Will return true after a finite number of calls to readChunk.
1784 *
1785 * @return bool true if there is no more input, false otherwise.
1786 */
1787 function atEnd();
1788
1789 /**
1790 * Return a chunk of the input, as a (possibly empty) string.
1791 * When the end of input is reached, readChunk() returns false.
1792 * If atEnd() returns false, readChunk() will return a string.
1793 * If atEnd() returns true, readChunk() will return false.
1794 *
1795 * @return bool|string
1796 */
1797 function readChunk();
1798 }
1799
1800 /**
1801 * Used for importing XML dumps where the content of the dump is in a string.
1802 * This class is ineffecient, and should only be used for small dumps.
1803 * For larger dumps, ImportStreamSource should be used instead.
1804 *
1805 * @ingroup SpecialPage
1806 */
1807 class ImportStringSource implements ImportSource {
1808 function __construct( $string ) {
1809 $this->mString = $string;
1810 $this->mRead = false;
1811 }
1812
1813 /**
1814 * @return bool
1815 */
1816 function atEnd() {
1817 return $this->mRead;
1818 }
1819
1820 /**
1821 * @return bool|string
1822 */
1823 function readChunk() {
1824 if ( $this->atEnd() ) {
1825 return false;
1826 }
1827 $this->mRead = true;
1828 return $this->mString;
1829 }
1830 }
1831
1832 /**
1833 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1834 * @ingroup SpecialPage
1835 */
1836 class ImportStreamSource implements ImportSource {
1837 function __construct( $handle ) {
1838 $this->mHandle = $handle;
1839 }
1840
1841 /**
1842 * @return bool
1843 */
1844 function atEnd() {
1845 return feof( $this->mHandle );
1846 }
1847
1848 /**
1849 * @return string
1850 */
1851 function readChunk() {
1852 return fread( $this->mHandle, 32768 );
1853 }
1854
1855 /**
1856 * @param string $filename
1857 * @return Status
1858 */
1859 static function newFromFile( $filename ) {
1860 MediaWiki\suppressWarnings();
1861 $file = fopen( $filename, 'rt' );
1862 MediaWiki\restoreWarnings();
1863 if ( !$file ) {
1864 return Status::newFatal( "importcantopen" );
1865 }
1866 return Status::newGood( new ImportStreamSource( $file ) );
1867 }
1868
1869 /**
1870 * @param string $fieldname
1871 * @return Status
1872 */
1873 static function newFromUpload( $fieldname = "xmlimport" ) {
1874 $upload =& $_FILES[$fieldname];
1875
1876 if ( $upload === null || !$upload['name'] ) {
1877 return Status::newFatal( 'importnofile' );
1878 }
1879 if ( !empty( $upload['error'] ) ) {
1880 switch ( $upload['error'] ) {
1881 case 1:
1882 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1883 return Status::newFatal( 'importuploaderrorsize' );
1884 case 2:
1885 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1886 # was specified in the HTML form.
1887 return Status::newFatal( 'importuploaderrorsize' );
1888 case 3:
1889 # The uploaded file was only partially uploaded
1890 return Status::newFatal( 'importuploaderrorpartial' );
1891 case 6:
1892 # Missing a temporary folder.
1893 return Status::newFatal( 'importuploaderrortemp' );
1894 # case else: # Currently impossible
1895 }
1896
1897 }
1898 $fname = $upload['tmp_name'];
1899 if ( is_uploaded_file( $fname ) ) {
1900 return ImportStreamSource::newFromFile( $fname );
1901 } else {
1902 return Status::newFatal( 'importnofile' );
1903 }
1904 }
1905
1906 /**
1907 * @param string $url
1908 * @param string $method
1909 * @return Status
1910 */
1911 static function newFromURL( $url, $method = 'GET' ) {
1912 wfDebug( __METHOD__ . ": opening $url\n" );
1913 # Use the standard HTTP fetch function; it times out
1914 # quicker and sorts out user-agent problems which might
1915 # otherwise prevent importing from large sites, such
1916 # as the Wikimedia cluster, etc.
1917 $data = Http::request( $method, $url, array( 'followRedirects' => true ), __METHOD__ );
1918 if ( $data !== false ) {
1919 $file = tmpfile();
1920 fwrite( $file, $data );
1921 fflush( $file );
1922 fseek( $file, 0 );
1923 return Status::newGood( new ImportStreamSource( $file ) );
1924 } else {
1925 return Status::newFatal( 'importcantopen' );
1926 }
1927 }
1928
1929 /**
1930 * @param string $interwiki
1931 * @param string $page
1932 * @param bool $history
1933 * @param bool $templates
1934 * @param int $pageLinkDepth
1935 * @return Status
1936 */
1937 public static function newFromInterwiki( $interwiki, $page, $history = false,
1938 $templates = false, $pageLinkDepth = 0
1939 ) {
1940 if ( $page == '' ) {
1941 return Status::newFatal( 'import-noarticle' );
1942 }
1943 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1944 if ( is_null( $link ) || !$link->isExternal() ) {
1945 return Status::newFatal( 'importbadinterwiki' );
1946 } else {
1947 $params = array();
1948 if ( $history ) {
1949 $params['history'] = 1;
1950 }
1951 if ( $templates ) {
1952 $params['templates'] = 1;
1953 }
1954 if ( $pageLinkDepth ) {
1955 $params['pagelink-depth'] = $pageLinkDepth;
1956 }
1957 $url = $link->getFullURL( $params );
1958 # For interwikis, use POST to avoid redirects.
1959 return ImportStreamSource::newFromURL( $url, "POST" );
1960 }
1961 }
1962 }