Remove unreachable line in DifferenceEngine
[mediawiki.git] / includes / Import.php
bloba593702cb11b2a56c9098924e964d35ef22c46e9
1 <?php
2 /**
3 * MediaWiki page data importer
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
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.
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.
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
23 * @file
24 * @ingroup SpecialPage
27 /**
28 * XML file reader for the page data importer
30 * implements Special:Import
31 * @ingroup SpecialPage
33 class WikiImporter {
34 private $reader = null;
35 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
36 private $mSiteInfoCallback, $mTargetNamespace, $mPageOutCallback;
37 private $mDebug;
39 /**
40 * Creates an ImportXMLReader drawing from the source provided
42 function __construct( $source ) {
43 $this->reader = new XMLReader();
45 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
46 $id = UploadSourceAdapter::registerSource( $source );
47 $this->reader->open( "uploadsource://$id" );
49 // Default callbacks
50 $this->setRevisionCallback( array( $this, "importRevision" ) );
51 $this->setUploadCallback( array( $this, 'importUpload' ) );
52 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
53 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
56 private function throwXmlError( $err ) {
57 $this->debug( "FAILURE: $err" );
58 wfDebug( "WikiImporter XML error: $err\n" );
61 private function debug( $data ) {
62 if( $this->mDebug ) {
63 wfDebug( "IMPORT: $data\n" );
67 private function warn( $data ) {
68 wfDebug( "IMPORT: $data\n" );
71 private function notice( $data ) {
72 global $wgCommandLineMode;
73 if( $wgCommandLineMode ) {
74 print "$data\n";
75 } else {
76 global $wgOut;
77 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
81 /**
82 * Set debug mode...
84 function setDebug( $debug ) {
85 $this->mDebug = $debug;
88 /**
89 * Sets the action to perform as each new page in the stream is reached.
90 * @param $callback callback
91 * @return callback
93 public function setPageCallback( $callback ) {
94 $previous = $this->mPageCallback;
95 $this->mPageCallback = $callback;
96 return $previous;
99 /**
100 * Sets the action to perform as each page in the stream is completed.
101 * Callback accepts the page title (as a Title object), a second object
102 * with the original title form (in case it's been overridden into a
103 * local namespace), and a count of revisions.
105 * @param $callback callback
106 * @return callback
108 public function setPageOutCallback( $callback ) {
109 $previous = $this->mPageOutCallback;
110 $this->mPageOutCallback = $callback;
111 return $previous;
115 * Sets the action to perform as each page revision is reached.
116 * @param $callback callback
117 * @return callback
119 public function setRevisionCallback( $callback ) {
120 $previous = $this->mRevisionCallback;
121 $this->mRevisionCallback = $callback;
122 return $previous;
126 * Sets the action to perform as each file upload version is reached.
127 * @param $callback callback
128 * @return callback
130 public function setUploadCallback( $callback ) {
131 $previous = $this->mUploadCallback;
132 $this->mUploadCallback = $callback;
133 return $previous;
137 * Sets the action to perform as each log item reached.
138 * @param $callback callback
139 * @return callback
141 public function setLogItemCallback( $callback ) {
142 $previous = $this->mLogItemCallback;
143 $this->mLogItemCallback = $callback;
144 return $previous;
148 * Sets the action to perform when site info is encountered
149 * @param $callback callback
150 * @return callback
152 public function setSiteInfoCallback( $callback ) {
153 $previous = $this->mSiteInfoCallback;
154 $this->mSiteInfoCallback = $callback;
155 return $previous;
159 * Set a target namespace to override the defaults
161 public function setTargetNamespace( $namespace ) {
162 if( is_null( $namespace ) ) {
163 // Don't override namespaces
164 $this->mTargetNamespace = null;
165 } elseif( $namespace >= 0 ) {
166 // FIXME: Check for validity
167 $this->mTargetNamespace = intval( $namespace );
168 } else {
169 return false;
174 * Default per-revision callback, performs the import.
175 * @param $revision WikiRevision
177 public function importRevision( $revision ) {
178 $dbw = wfGetDB( DB_MASTER );
179 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
183 * Default per-revision callback, performs the import.
184 * @param $rev WikiRevision
186 public function importLogItem( $rev ) {
187 $dbw = wfGetDB( DB_MASTER );
188 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
192 * Dummy for now...
194 public function importUpload( $revision ) {
195 //$dbw = wfGetDB( DB_MASTER );
196 //return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
197 return false;
201 * Mostly for hook use
203 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
204 $args = func_get_args();
205 return wfRunHooks( 'AfterImportPage', $args );
209 * Alternate per-revision callback, for debugging.
210 * @param $revision WikiRevision
212 public function debugRevisionHandler( &$revision ) {
213 $this->debug( "Got revision:" );
214 if( is_object( $revision->title ) ) {
215 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
216 } else {
217 $this->debug( "-- Title: <invalid>" );
219 $this->debug( "-- User: " . $revision->user_text );
220 $this->debug( "-- Timestamp: " . $revision->timestamp );
221 $this->debug( "-- Comment: " . $revision->comment );
222 $this->debug( "-- Text: " . $revision->text );
226 * Notify the callback function when a new <page> is reached.
227 * @param $title Title
229 function pageCallback( $title ) {
230 if( isset( $this->mPageCallback ) ) {
231 call_user_func( $this->mPageCallback, $title );
236 * Notify the callback function when a </page> is closed.
237 * @param $title Title
238 * @param $origTitle Title
239 * @param $revCount Integer
240 * @param $sucCount Int: number of revisions for which callback returned true
241 * @param $pageInfo Array: associative array of page information
243 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
244 if( isset( $this->mPageOutCallback ) ) {
245 $args = func_get_args();
246 call_user_func_array( $this->mPageOutCallback, $args );
251 * Notify the callback function of a revision
252 * @param $revision A WikiRevision object
254 private function revisionCallback( $revision ) {
255 if ( isset( $this->mRevisionCallback ) ) {
256 return call_user_func_array( $this->mRevisionCallback,
257 array( $revision, $this ) );
258 } else {
259 return false;
264 * Notify the callback function of a new log item
265 * @param $revision A WikiRevision object
267 private function logItemCallback( $revision ) {
268 if ( isset( $this->mLogItemCallback ) ) {
269 return call_user_func_array( $this->mLogItemCallback,
270 array( $revision, $this ) );
271 } else {
272 return false;
277 * Shouldn't something like this be built-in to XMLReader?
278 * Fetches text contents of the current element, assuming
279 * no sub-elements or such scary things.
280 * @return string
281 * @access private
283 private function nodeContents() {
284 if( $this->reader->isEmptyElement ) {
285 return "";
287 $buffer = "";
288 while( $this->reader->read() ) {
289 switch( $this->reader->nodeType ) {
290 case XmlReader::TEXT:
291 case XmlReader::SIGNIFICANT_WHITESPACE:
292 $buffer .= $this->reader->value;
293 break;
294 case XmlReader::END_ELEMENT:
295 return $buffer;
299 $this->reader->close();
300 return '';
303 # --------------
305 /** Left in for debugging */
306 private function dumpElement() {
307 static $lookup = null;
308 if (!$lookup) {
309 $xmlReaderConstants = array(
310 "NONE",
311 "ELEMENT",
312 "ATTRIBUTE",
313 "TEXT",
314 "CDATA",
315 "ENTITY_REF",
316 "ENTITY",
317 "PI",
318 "COMMENT",
319 "DOC",
320 "DOC_TYPE",
321 "DOC_FRAGMENT",
322 "NOTATION",
323 "WHITESPACE",
324 "SIGNIFICANT_WHITESPACE",
325 "END_ELEMENT",
326 "END_ENTITY",
327 "XML_DECLARATION",
329 $lookup = array();
331 foreach( $xmlReaderConstants as $name ) {
332 $lookup[constant("XmlReader::$name")] = $name;
336 print( var_dump(
337 $lookup[$this->reader->nodeType],
338 $this->reader->name,
339 $this->reader->value
340 )."\n\n" );
344 * Primary entry point
346 public function doImport() {
347 $this->reader->read();
349 if ( $this->reader->name != 'mediawiki' ) {
350 throw new MWException( "Expected <mediawiki> tag, got ".
351 $this->reader->name );
353 $this->debug( "<mediawiki> tag is correct." );
355 $this->debug( "Starting primary dump processing loop." );
357 $keepReading = $this->reader->read();
358 $skip = false;
359 while ( $keepReading ) {
360 $tag = $this->reader->name;
361 $type = $this->reader->nodeType;
363 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
364 // Do nothing
365 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
366 break;
367 } elseif ( $tag == 'siteinfo' ) {
368 $this->handleSiteInfo();
369 } elseif ( $tag == 'page' ) {
370 $this->handlePage();
371 } elseif ( $tag == 'logitem' ) {
372 $this->handleLogItem();
373 } elseif ( $tag != '#text' ) {
374 $this->warn( "Unhandled top-level XML tag $tag" );
376 $skip = true;
379 if ($skip) {
380 $keepReading = $this->reader->next();
381 $skip = false;
382 $this->debug( "Skip" );
383 } else {
384 $keepReading = $this->reader->read();
388 return true;
391 private function handleSiteInfo() {
392 // Site info is useful, but not actually used for dump imports.
393 // Includes a quick short-circuit to save performance.
394 if ( ! $this->mSiteInfoCallback ) {
395 $this->reader->next();
396 return true;
398 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
401 private function handleLogItem() {
402 $this->debug( "Enter log item handler." );
403 $logInfo = array();
405 // Fields that can just be stuffed in the pageInfo object
406 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
407 'logtitle', 'params' );
409 while ( $this->reader->read() ) {
410 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
411 $this->reader->name == 'logitem') {
412 break;
415 $tag = $this->reader->name;
417 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
418 $this, $logInfo ) ) {
419 // Do nothing
420 } elseif ( in_array( $tag, $normalFields ) ) {
421 $logInfo[$tag] = $this->nodeContents();
422 } elseif ( $tag == 'contributor' ) {
423 $logInfo['contributor'] = $this->handleContributor();
424 } elseif ( $tag != '#text' ) {
425 $this->warn( "Unhandled log-item XML tag $tag" );
429 $this->processLogItem( $logInfo );
432 private function processLogItem( $logInfo ) {
433 $revision = new WikiRevision;
435 $revision->setID( $logInfo['id'] );
436 $revision->setType( $logInfo['type'] );
437 $revision->setAction( $logInfo['action'] );
438 $revision->setTimestamp( $logInfo['timestamp'] );
439 $revision->setParams( $logInfo['params'] );
440 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
442 if ( isset( $logInfo['comment'] ) ) {
443 $revision->setComment( $logInfo['comment'] );
446 if ( isset( $logInfo['contributor']['ip'] ) ) {
447 $revision->setUserIP( $logInfo['contributor']['ip'] );
449 if ( isset( $logInfo['contributor']['username'] ) ) {
450 $revision->setUserName( $logInfo['contributor']['username'] );
453 return $this->logItemCallback( $revision );
456 private function handlePage() {
457 // Handle page data.
458 $this->debug( "Enter page handler." );
459 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
461 // Fields that can just be stuffed in the pageInfo object
462 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
464 $skip = false;
465 $badTitle = false;
467 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
468 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
469 $this->reader->name == 'page') {
470 break;
473 $tag = $this->reader->name;
475 if ( $badTitle ) {
476 // The title is invalid, bail out of this page
477 $skip = true;
478 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
479 &$pageInfo ) ) ) {
480 // Do nothing
481 } elseif ( in_array( $tag, $normalFields ) ) {
482 $pageInfo[$tag] = $this->nodeContents();
483 if ( $tag == 'title' ) {
484 $title = $this->processTitle( $pageInfo['title'] );
486 if ( !$title ) {
487 $badTitle = true;
488 $skip = true;
491 $this->pageCallback( $title );
492 list( $pageInfo['_title'], $origTitle ) = $title;
494 } elseif ( $tag == 'revision' ) {
495 $this->handleRevision( $pageInfo );
496 } elseif ( $tag == 'upload' ) {
497 $this->handleUpload( $pageInfo );
498 } elseif ( $tag != '#text' ) {
499 $this->warn( "Unhandled page XML tag $tag" );
500 $skip = true;
504 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
505 $pageInfo['revisionCount'],
506 $pageInfo['successfulRevisionCount'],
507 $pageInfo );
510 private function handleRevision( &$pageInfo ) {
511 $this->debug( "Enter revision handler" );
512 $revisionInfo = array();
514 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
516 $skip = false;
518 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
519 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
520 $this->reader->name == 'revision') {
521 break;
524 $tag = $this->reader->name;
526 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
527 $pageInfo, $revisionInfo ) ) {
528 // Do nothing
529 } elseif ( in_array( $tag, $normalFields ) ) {
530 $revisionInfo[$tag] = $this->nodeContents();
531 } elseif ( $tag == 'contributor' ) {
532 $revisionInfo['contributor'] = $this->handleContributor();
533 } elseif ( $tag != '#text' ) {
534 $this->warn( "Unhandled revision XML tag $tag" );
535 $skip = true;
539 $pageInfo['revisionCount']++;
540 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
541 $pageInfo['successfulRevisionCount']++;
545 private function processRevision( $pageInfo, $revisionInfo ) {
546 $revision = new WikiRevision;
548 $revision->setID( $revisionInfo['id'] );
549 $revision->setText( $revisionInfo['text'] );
550 $revision->setTitle( $pageInfo['_title'] );
551 $revision->setTimestamp( $revisionInfo['timestamp'] );
553 if ( isset( $revisionInfo['comment'] ) ) {
554 $revision->setComment( $revisionInfo['comment'] );
557 if ( isset( $revisionInfo['minor'] ) )
558 $revision->setMinor( true );
560 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
561 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
563 if ( isset( $revisionInfo['contributor']['username'] ) ) {
564 $revision->setUserName( $revisionInfo['contributor']['username'] );
567 return $this->revisionCallback( $revision );
570 private function handleUpload( &$pageInfo ) {
571 $this->debug( "Enter upload handler" );
572 $uploadInfo = array();
574 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
575 'src', 'size' );
577 $skip = false;
579 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
580 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
581 $this->reader->name == 'upload') {
582 break;
585 $tag = $this->reader->name;
587 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
588 $pageInfo ) ) {
589 // Do nothing
590 } elseif ( in_array( $tag, $normalFields ) ) {
591 $uploadInfo[$tag] = $this->nodeContents();
592 } elseif ( $tag == 'contributor' ) {
593 $uploadInfo['contributor'] = $this->handleContributor();
594 } elseif ( $tag != '#text' ) {
595 $this->warn( "Unhandled upload XML tag $tag" );
596 $skip = true;
600 return $this->processUpload( $pageInfo, $uploadInfo );
603 private function processUpload( $pageInfo, $uploadInfo ) {
604 $revision = new WikiRevision;
606 $revision->setTitle( $pageInfo['_title'] );
607 $revision->setID( $uploadInfo['id'] );
608 $revision->setTimestamp( $uploadInfo['timestamp'] );
609 $revision->setText( $uploadInfo['text'] );
610 $revision->setFilename( $uploadInfo['filename'] );
611 $revision->setSrc( $uploadInfo['src'] );
612 $revision->setSize( intval( $uploadInfo['size'] ) );
613 $revision->setComment( $uploadInfo['comment'] );
615 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
616 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
618 if ( isset( $uploadInfo['contributor']['username'] ) ) {
619 $revision->setUserName( $uploadInfo['contributor']['username'] );
622 return $this->uploadCallback( $revision );
625 private function handleContributor() {
626 $fields = array( 'id', 'ip', 'username' );
627 $info = array();
629 while ( $this->reader->read() ) {
630 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
631 $this->reader->name == 'contributor') {
632 break;
635 $tag = $this->reader->name;
637 if ( in_array( $tag, $fields ) ) {
638 $info[$tag] = $this->nodeContents();
642 return $info;
645 private function processTitle( $text ) {
646 $workTitle = $text;
647 $origTitle = Title::newFromText( $workTitle );
649 if( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
650 $title = Title::makeTitle( $this->mTargetNamespace,
651 $origTitle->getDBkey() );
652 } else {
653 $title = Title::newFromText( $workTitle );
656 if( is_null( $title ) ) {
657 // Invalid page title? Ignore the page
658 $this->notice( "Skipping invalid page title '$workTitle'" );
659 return false;
660 } elseif( $title->getInterwiki() != '' ) {
661 $this->notice( "Skipping interwiki page title '$workTitle'" );
662 return false;
665 return array( $origTitle, $title );
669 /** This is a horrible hack used to keep source compatibility */
670 class UploadSourceAdapter {
671 static $sourceRegistrations = array();
673 private $mSource;
674 private $mBuffer;
675 private $mPosition;
677 static function registerSource( $source ) {
678 $id = wfGenerateToken();
680 self::$sourceRegistrations[$id] = $source;
682 return $id;
685 function stream_open( $path, $mode, $options, &$opened_path ) {
686 $url = parse_url($path);
687 $id = $url['host'];
689 if ( !isset( self::$sourceRegistrations[$id] ) ) {
690 return false;
693 $this->mSource = self::$sourceRegistrations[$id];
695 return true;
698 function stream_read( $count ) {
699 $return = '';
700 $leave = false;
702 while ( !$leave && !$this->mSource->atEnd() &&
703 strlen($this->mBuffer) < $count ) {
704 $read = $this->mSource->readChunk();
706 if ( !strlen($read) ) {
707 $leave = true;
710 $this->mBuffer .= $read;
713 if ( strlen($this->mBuffer) ) {
714 $return = substr( $this->mBuffer, 0, $count );
715 $this->mBuffer = substr( $this->mBuffer, $count );
718 $this->mPosition += strlen($return);
720 return $return;
723 function stream_write( $data ) {
724 return false;
727 function stream_tell() {
728 return $this->mPosition;
731 function stream_eof() {
732 return $this->mSource->atEnd();
735 function url_stat() {
736 $result = array();
738 $result['dev'] = $result[0] = 0;
739 $result['ino'] = $result[1] = 0;
740 $result['mode'] = $result[2] = 0;
741 $result['nlink'] = $result[3] = 0;
742 $result['uid'] = $result[4] = 0;
743 $result['gid'] = $result[5] = 0;
744 $result['rdev'] = $result[6] = 0;
745 $result['size'] = $result[7] = 0;
746 $result['atime'] = $result[8] = 0;
747 $result['mtime'] = $result[9] = 0;
748 $result['ctime'] = $result[10] = 0;
749 $result['blksize'] = $result[11] = 0;
750 $result['blocks'] = $result[12] = 0;
752 return $result;
756 class XMLReader2 extends XMLReader {
757 function nodeContents() {
758 if( $this->isEmptyElement ) {
759 return "";
761 $buffer = "";
762 while( $this->read() ) {
763 switch( $this->nodeType ) {
764 case XmlReader::TEXT:
765 case XmlReader::SIGNIFICANT_WHITESPACE:
766 $buffer .= $this->value;
767 break;
768 case XmlReader::END_ELEMENT:
769 return $buffer;
772 return $this->close();
777 * @todo document (e.g. one-sentence class description).
778 * @ingroup SpecialPage
780 class WikiRevision {
781 var $title = null;
782 var $id = 0;
783 var $timestamp = "20010115000000";
784 var $user = 0;
785 var $user_text = "";
786 var $text = "";
787 var $comment = "";
788 var $minor = false;
789 var $type = "";
790 var $action = "";
791 var $params = "";
793 function setTitle( $title ) {
794 if( is_object( $title ) ) {
795 $this->title = $title;
796 } elseif( is_null( $title ) ) {
797 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
798 } else {
799 throw new MWException( "WikiRevision given non-object title in import." );
803 function setID( $id ) {
804 $this->id = $id;
807 function setTimestamp( $ts ) {
808 # 2003-08-05T18:30:02Z
809 $this->timestamp = wfTimestamp( TS_MW, $ts );
812 function setUsername( $user ) {
813 $this->user_text = $user;
816 function setUserIP( $ip ) {
817 $this->user_text = $ip;
820 function setText( $text ) {
821 $this->text = $text;
824 function setComment( $text ) {
825 $this->comment = $text;
828 function setMinor( $minor ) {
829 $this->minor = (bool)$minor;
832 function setSrc( $src ) {
833 $this->src = $src;
836 function setFilename( $filename ) {
837 $this->filename = $filename;
840 function setSize( $size ) {
841 $this->size = intval( $size );
844 function setType( $type ) {
845 $this->type = $type;
848 function setAction( $action ) {
849 $this->action = $action;
852 function setParams( $params ) {
853 $this->params = $params;
856 function getTitle() {
857 return $this->title;
860 function getID() {
861 return $this->id;
864 function getTimestamp() {
865 return $this->timestamp;
868 function getUser() {
869 return $this->user_text;
872 function getText() {
873 return $this->text;
876 function getComment() {
877 return $this->comment;
880 function getMinor() {
881 return $this->minor;
884 function getSrc() {
885 return $this->src;
888 function getFilename() {
889 return $this->filename;
892 function getSize() {
893 return $this->size;
896 function getType() {
897 return $this->type;
900 function getAction() {
901 return $this->action;
904 function getParams() {
905 return $this->params;
908 function importOldRevision() {
909 $dbw = wfGetDB( DB_MASTER );
911 # Sneak a single revision into place
912 $user = User::newFromName( $this->getUser() );
913 if( $user ) {
914 $userId = intval( $user->getId() );
915 $userText = $user->getName();
916 } else {
917 $userId = 0;
918 $userText = $this->getUser();
921 // avoid memory leak...?
922 $linkCache = LinkCache::singleton();
923 $linkCache->clear();
925 $article = new Article( $this->title );
926 $pageId = $article->getId();
927 if( $pageId == 0 ) {
928 # must create the page...
929 $pageId = $article->insertOn( $dbw );
930 $created = true;
931 } else {
932 $created = false;
934 $prior = $dbw->selectField( 'revision', '1',
935 array( 'rev_page' => $pageId,
936 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
937 'rev_user_text' => $userText,
938 'rev_comment' => $this->getComment() ),
939 __METHOD__
941 if( $prior ) {
942 // FIXME: this could fail slightly for multiple matches :P
943 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
944 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
945 return false;
949 # FIXME: Use original rev_id optionally (better for backups)
950 # Insert the row
951 $revision = new Revision( array(
952 'page' => $pageId,
953 'text' => $this->getText(),
954 'comment' => $this->getComment(),
955 'user' => $userId,
956 'user_text' => $userText,
957 'timestamp' => $this->timestamp,
958 'minor_edit' => $this->minor,
959 ) );
960 $revId = $revision->insertOn( $dbw );
961 $changed = $article->updateIfNewerOn( $dbw, $revision );
963 # To be on the safe side...
964 $tempTitle = $GLOBALS['wgTitle'];
965 $GLOBALS['wgTitle'] = $this->title;
967 if( $created ) {
968 wfDebug( __METHOD__ . ": running onArticleCreate\n" );
969 Article::onArticleCreate( $this->title );
971 wfDebug( __METHOD__ . ": running create updates\n" );
972 $article->createUpdates( $revision );
974 } elseif( $changed ) {
975 wfDebug( __METHOD__ . ": running onArticleEdit\n" );
976 Article::onArticleEdit( $this->title );
978 wfDebug( __METHOD__ . ": running edit updates\n" );
979 $article->editUpdates(
980 $this->getText(),
981 $this->getComment(),
982 $this->minor,
983 $this->timestamp,
984 $revId );
986 $GLOBALS['wgTitle'] = $tempTitle;
988 return true;
991 function importLogItem() {
992 $dbw = wfGetDB( DB_MASTER );
993 # FIXME: this will not record autoblocks
994 if( !$this->getTitle() ) {
995 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
996 $this->timestamp . "\n" );
997 return;
999 # Check if it exists already
1000 // FIXME: use original log ID (better for backups)
1001 $prior = $dbw->selectField( 'logging', '1',
1002 array( 'log_type' => $this->getType(),
1003 'log_action' => $this->getAction(),
1004 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1005 'log_namespace' => $this->getTitle()->getNamespace(),
1006 'log_title' => $this->getTitle()->getDBkey(),
1007 'log_comment' => $this->getComment(),
1008 #'log_user_text' => $this->user_text,
1009 'log_params' => $this->params ),
1010 __METHOD__
1012 // FIXME: this could fail slightly for multiple matches :P
1013 if( $prior ) {
1014 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1015 $this->timestamp . "\n" );
1016 return false;
1018 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1019 $data = array(
1020 'log_id' => $log_id,
1021 'log_type' => $this->type,
1022 'log_action' => $this->action,
1023 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1024 'log_user' => User::idFromName( $this->user_text ),
1025 #'log_user_text' => $this->user_text,
1026 'log_namespace' => $this->getTitle()->getNamespace(),
1027 'log_title' => $this->getTitle()->getDBkey(),
1028 'log_comment' => $this->getComment(),
1029 'log_params' => $this->params
1031 $dbw->insert( 'logging', $data, __METHOD__ );
1034 function importUpload() {
1035 wfDebug( __METHOD__ . ": STUB\n" );
1038 // from file revert...
1039 $source = $this->file->getArchiveVirtualUrl( $this->oldimage );
1040 $comment = $wgRequest->getText( 'wpComment' );
1041 // TODO: Preserve file properties from database instead of reloading from file
1042 $status = $this->file->upload( $source, $comment, $comment );
1043 if( $status->isGood() ) {
1047 // from file upload...
1048 $this->mLocalFile = wfLocalFile( $nt );
1049 $this->mDestName = $this->mLocalFile->getName();
1050 //....
1051 $status = $this->mLocalFile->upload( $this->mTempPath, $this->mComment, $pageText,
1052 File::DELETE_SOURCE, $this->mFileProps );
1053 if ( !$status->isGood() ) {
1054 $resultDetails = array( 'internal' => $status->getWikiText() );
1057 // @todo Fixme: upload() uses $wgUser, which is wrong here
1058 // it may also create a page without our desire, also wrong potentially.
1059 // and, it will record a *current* upload, but we might want an archive version here
1061 $file = wfLocalFile( $this->getTitle() );
1062 if( !$file ) {
1063 wfDebug( "IMPORT: Bad file. :(\n" );
1064 return false;
1067 $source = $this->downloadSource();
1068 if( !$source ) {
1069 wfDebug( "IMPORT: Could not fetch remote file. :(\n" );
1070 return false;
1073 $status = $file->upload( $source,
1074 $this->getComment(),
1075 $this->getComment(), // Initial page, if none present...
1076 File::DELETE_SOURCE,
1077 false, // props...
1078 $this->getTimestamp() );
1080 if( $status->isGood() ) {
1081 // yay?
1082 wfDebug( "IMPORT: is ok?\n" );
1083 return true;
1086 wfDebug( "IMPORT: is bad? " . $status->getXml() . "\n" );
1087 return false;
1091 function downloadSource() {
1092 global $wgEnableUploads;
1093 if( !$wgEnableUploads ) {
1094 return false;
1097 $tempo = tempnam( wfTempDir(), 'download' );
1098 $f = fopen( $tempo, 'wb' );
1099 if( !$f ) {
1100 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1101 return false;
1104 // @todo Fixme!
1105 $src = $this->getSrc();
1106 $data = Http::get( $src );
1107 if( !$data ) {
1108 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1109 fclose( $f );
1110 unlink( $tempo );
1111 return false;
1114 fwrite( $f, $data );
1115 fclose( $f );
1117 return $tempo;
1123 * @todo document (e.g. one-sentence class description).
1124 * @ingroup SpecialPage
1126 class ImportStringSource {
1127 function __construct( $string ) {
1128 $this->mString = $string;
1129 $this->mRead = false;
1132 function atEnd() {
1133 return $this->mRead;
1136 function readChunk() {
1137 if( $this->atEnd() ) {
1138 return false;
1139 } else {
1140 $this->mRead = true;
1141 return $this->mString;
1147 * @todo document (e.g. one-sentence class description).
1148 * @ingroup SpecialPage
1150 class ImportStreamSource {
1151 function __construct( $handle ) {
1152 $this->mHandle = $handle;
1155 function atEnd() {
1156 return feof( $this->mHandle );
1159 function readChunk() {
1160 return fread( $this->mHandle, 32768 );
1163 static function newFromFile( $filename ) {
1164 $file = @fopen( $filename, 'rt' );
1165 if( !$file ) {
1166 return Status::newFatal( "importcantopen" );
1168 return Status::newGood( new ImportStreamSource( $file ) );
1171 static function newFromUpload( $fieldname = "xmlimport" ) {
1172 $upload =& $_FILES[$fieldname];
1174 if( !isset( $upload ) || !$upload['name'] ) {
1175 return Status::newFatal( 'importnofile' );
1177 if( !empty( $upload['error'] ) ) {
1178 switch($upload['error']){
1179 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1180 return Status::newFatal( 'importuploaderrorsize' );
1181 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1182 return Status::newFatal( 'importuploaderrorsize' );
1183 case 3: # The uploaded file was only partially uploaded
1184 return Status::newFatal( 'importuploaderrorpartial' );
1185 case 6: #Missing a temporary folder.
1186 return Status::newFatal( 'importuploaderrortemp' );
1187 # case else: # Currently impossible
1191 $fname = $upload['tmp_name'];
1192 if( is_uploaded_file( $fname ) ) {
1193 return ImportStreamSource::newFromFile( $fname );
1194 } else {
1195 return Status::newFatal( 'importnofile' );
1199 static function newFromURL( $url, $method = 'GET' ) {
1200 wfDebug( __METHOD__ . ": opening $url\n" );
1201 # Use the standard HTTP fetch function; it times out
1202 # quicker and sorts out user-agent problems which might
1203 # otherwise prevent importing from large sites, such
1204 # as the Wikimedia cluster, etc.
1205 $data = Http::request( $method, $url );
1206 if( $data !== false ) {
1207 $file = tmpfile();
1208 fwrite( $file, $data );
1209 fflush( $file );
1210 fseek( $file, 0 );
1211 return Status::newGood( new ImportStreamSource( $file ) );
1212 } else {
1213 return Status::newFatal( 'importcantopen' );
1217 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1218 if( $page == '' ) {
1219 return Status::newFatal( 'import-noarticle' );
1221 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1222 if( is_null( $link ) || $link->getInterwiki() == '' ) {
1223 return Status::newFatal( 'importbadinterwiki' );
1224 } else {
1225 $params = array();
1226 if ( $history ) $params['history'] = 1;
1227 if ( $templates ) $params['templates'] = 1;
1228 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1229 $url = $link->getFullUrl( $params );
1230 # For interwikis, use POST to avoid redirects.
1231 return ImportStreamSource::newFromURL( $url, "POST" );