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