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