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