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