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