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