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