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
24 * @ingroup SpecialPage
28 * XML file reader for the page data importer
30 * implements Special:Import
31 * @ingroup SpecialPage
34 private $reader = null;
35 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
36 private $mSiteInfoCallback, $mTargetNamespace, $mPageOutCallback;
38 private $mImportUploads, $mImageBasePath;
41 * Creates an ImportXMLReader drawing from the source provided
43 function __construct( $source ) {
44 $this->reader
= new XMLReader();
46 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
47 $id = UploadSourceAdapter
::registerSource( $source );
48 $this->reader
->open( "uploadsource://$id" );
51 $this->setRevisionCallback( array( $this, "importRevision" ) );
52 $this->setUploadCallback( array( $this, 'importUpload' ) );
53 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
54 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
57 private function throwXmlError( $err ) {
58 $this->debug( "FAILURE: $err" );
59 wfDebug( "WikiImporter XML error: $err\n" );
62 private function debug( $data ) {
64 wfDebug( "IMPORT: $data\n" );
68 private function warn( $data ) {
69 wfDebug( "IMPORT: $data\n" );
72 private function notice( $data ) {
73 global $wgCommandLineMode;
74 if( $wgCommandLineMode ) {
78 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
85 function setDebug( $debug ) {
86 $this->mDebug
= $debug;
90 * Sets the action to perform as each new page in the stream is reached.
91 * @param $callback callback
94 public function setPageCallback( $callback ) {
95 $previous = $this->mPageCallback
;
96 $this->mPageCallback
= $callback;
101 * Sets the action to perform as each page in the stream is completed.
102 * Callback accepts the page title (as a Title object), a second object
103 * with the original title form (in case it's been overridden into a
104 * local namespace), and a count of revisions.
106 * @param $callback callback
109 public function setPageOutCallback( $callback ) {
110 $previous = $this->mPageOutCallback
;
111 $this->mPageOutCallback
= $callback;
116 * Sets the action to perform as each page revision is reached.
117 * @param $callback callback
120 public function setRevisionCallback( $callback ) {
121 $previous = $this->mRevisionCallback
;
122 $this->mRevisionCallback
= $callback;
127 * Sets the action to perform as each file upload version is reached.
128 * @param $callback callback
131 public function setUploadCallback( $callback ) {
132 $previous = $this->mUploadCallback
;
133 $this->mUploadCallback
= $callback;
138 * Sets the action to perform as each log item reached.
139 * @param $callback callback
142 public function setLogItemCallback( $callback ) {
143 $previous = $this->mLogItemCallback
;
144 $this->mLogItemCallback
= $callback;
149 * Sets the action to perform when site info is encountered
150 * @param $callback callback
153 public function setSiteInfoCallback( $callback ) {
154 $previous = $this->mSiteInfoCallback
;
155 $this->mSiteInfoCallback
= $callback;
160 * Set a target namespace to override the defaults
162 public function setTargetNamespace( $namespace ) {
163 if( is_null( $namespace ) ) {
164 // Don't override namespaces
165 $this->mTargetNamespace
= null;
166 } elseif( $namespace >= 0 ) {
167 // @todo FIXME: Check for validity
168 $this->mTargetNamespace
= intval( $namespace );
177 public function setImageBasePath( $dir ) {
178 $this->mImageBasePath
= $dir;
180 public function setImportUploads( $import ) {
181 $this->mImportUploads
= $import;
185 * Default per-revision callback, performs the import.
186 * @param $revision WikiRevision
188 public function importRevision( $revision ) {
189 $dbw = wfGetDB( DB_MASTER
);
190 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
194 * Default per-revision callback, performs the import.
195 * @param $rev WikiRevision
197 public function importLogItem( $rev ) {
198 $dbw = wfGetDB( DB_MASTER
);
199 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
205 public function importUpload( $revision ) {
206 $dbw = wfGetDB( DB_MASTER
);
207 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
211 * Mostly for hook use
213 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
214 $args = func_get_args();
215 return wfRunHooks( 'AfterImportPage', $args );
219 * Alternate per-revision callback, for debugging.
220 * @param $revision WikiRevision
222 public function debugRevisionHandler( &$revision ) {
223 $this->debug( "Got revision:" );
224 if( is_object( $revision->title
) ) {
225 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
227 $this->debug( "-- Title: <invalid>" );
229 $this->debug( "-- User: " . $revision->user_text
);
230 $this->debug( "-- Timestamp: " . $revision->timestamp
);
231 $this->debug( "-- Comment: " . $revision->comment
);
232 $this->debug( "-- Text: " . $revision->text
);
236 * Notify the callback function when a new <page> is reached.
237 * @param $title Title
239 function pageCallback( $title ) {
240 if( isset( $this->mPageCallback
) ) {
241 call_user_func( $this->mPageCallback
, $title );
246 * Notify the callback function when a </page> is closed.
247 * @param $title Title
248 * @param $origTitle Title
249 * @param $revCount Integer
250 * @param $sucCount Int: number of revisions for which callback returned true
251 * @param $pageInfo Array: associative array of page information
253 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
254 if( isset( $this->mPageOutCallback
) ) {
255 $args = func_get_args();
256 call_user_func_array( $this->mPageOutCallback
, $args );
261 * Notify the callback function of a revision
262 * @param $revision A WikiRevision object
264 private function revisionCallback( $revision ) {
265 if ( isset( $this->mRevisionCallback
) ) {
266 return call_user_func_array( $this->mRevisionCallback
,
267 array( $revision, $this ) );
274 * Notify the callback function of a new log item
275 * @param $revision A WikiRevision object
277 private function logItemCallback( $revision ) {
278 if ( isset( $this->mLogItemCallback
) ) {
279 return call_user_func_array( $this->mLogItemCallback
,
280 array( $revision, $this ) );
287 * Shouldn't something like this be built-in to XMLReader?
288 * Fetches text contents of the current element, assuming
289 * no sub-elements or such scary things.
293 private function nodeContents() {
294 if( $this->reader
->isEmptyElement
) {
298 while( $this->reader
->read() ) {
299 switch( $this->reader
->nodeType
) {
300 case XmlReader
::TEXT
:
301 case XmlReader
::SIGNIFICANT_WHITESPACE
:
302 $buffer .= $this->reader
->value
;
304 case XmlReader
::END_ELEMENT
:
309 $this->reader
->close();
315 /** Left in for debugging */
316 private function dumpElement() {
317 static $lookup = null;
319 $xmlReaderConstants = array(
334 "SIGNIFICANT_WHITESPACE",
341 foreach( $xmlReaderConstants as $name ) {
342 $lookup[constant("XmlReader::$name")] = $name;
347 $lookup[$this->reader
->nodeType
],
354 * Primary entry point
356 public function doImport() {
357 $this->reader
->read();
359 if ( $this->reader
->name
!= 'mediawiki' ) {
360 throw new MWException( "Expected <mediawiki> tag, got ".
361 $this->reader
->name
);
363 $this->debug( "<mediawiki> tag is correct." );
365 $this->debug( "Starting primary dump processing loop." );
367 $keepReading = $this->reader
->read();
369 while ( $keepReading ) {
370 $tag = $this->reader
->name
;
371 $type = $this->reader
->nodeType
;
373 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
375 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
377 } elseif ( $tag == 'siteinfo' ) {
378 $this->handleSiteInfo();
379 } elseif ( $tag == 'page' ) {
381 } elseif ( $tag == 'logitem' ) {
382 $this->handleLogItem();
383 } elseif ( $tag != '#text' ) {
384 $this->warn( "Unhandled top-level XML tag $tag" );
390 $keepReading = $this->reader
->next();
392 $this->debug( "Skip" );
394 $keepReading = $this->reader
->read();
401 private function handleSiteInfo() {
402 // Site info is useful, but not actually used for dump imports.
403 // Includes a quick short-circuit to save performance.
404 if ( ! $this->mSiteInfoCallback
) {
405 $this->reader
->next();
408 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
411 private function handleLogItem() {
412 $this->debug( "Enter log item handler." );
415 // Fields that can just be stuffed in the pageInfo object
416 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
417 'logtitle', 'params' );
419 while ( $this->reader
->read() ) {
420 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
421 $this->reader
->name
== 'logitem') {
425 $tag = $this->reader
->name
;
427 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
428 $this, $logInfo ) ) {
430 } elseif ( in_array( $tag, $normalFields ) ) {
431 $logInfo[$tag] = $this->nodeContents();
432 } elseif ( $tag == 'contributor' ) {
433 $logInfo['contributor'] = $this->handleContributor();
434 } elseif ( $tag != '#text' ) {
435 $this->warn( "Unhandled log-item XML tag $tag" );
439 $this->processLogItem( $logInfo );
442 private function processLogItem( $logInfo ) {
443 $revision = new WikiRevision
;
445 $revision->setID( $logInfo['id'] );
446 $revision->setType( $logInfo['type'] );
447 $revision->setAction( $logInfo['action'] );
448 $revision->setTimestamp( $logInfo['timestamp'] );
449 $revision->setParams( $logInfo['params'] );
450 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
452 if ( isset( $logInfo['comment'] ) ) {
453 $revision->setComment( $logInfo['comment'] );
456 if ( isset( $logInfo['contributor']['ip'] ) ) {
457 $revision->setUserIP( $logInfo['contributor']['ip'] );
459 if ( isset( $logInfo['contributor']['username'] ) ) {
460 $revision->setUserName( $logInfo['contributor']['username'] );
463 return $this->logItemCallback( $revision );
466 private function handlePage() {
468 $this->debug( "Enter page handler." );
469 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
471 // Fields that can just be stuffed in the pageInfo object
472 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
477 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
478 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
479 $this->reader
->name
== 'page') {
483 $tag = $this->reader
->name
;
486 // The title is invalid, bail out of this page
488 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
491 } elseif ( in_array( $tag, $normalFields ) ) {
492 $pageInfo[$tag] = $this->nodeContents();
493 if ( $tag == 'title' ) {
494 $title = $this->processTitle( $pageInfo['title'] );
501 $this->pageCallback( $title );
502 list( $pageInfo['_title'], $origTitle ) = $title;
504 } elseif ( $tag == 'revision' ) {
505 $this->handleRevision( $pageInfo );
506 } elseif ( $tag == 'upload' ) {
507 $this->handleUpload( $pageInfo );
508 } elseif ( $tag != '#text' ) {
509 $this->warn( "Unhandled page XML tag $tag" );
514 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
515 $pageInfo['revisionCount'],
516 $pageInfo['successfulRevisionCount'],
520 private function handleRevision( &$pageInfo ) {
521 $this->debug( "Enter revision handler" );
522 $revisionInfo = array();
524 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
528 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
529 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
530 $this->reader
->name
== 'revision') {
534 $tag = $this->reader
->name
;
536 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
537 $pageInfo, $revisionInfo ) ) {
539 } elseif ( in_array( $tag, $normalFields ) ) {
540 $revisionInfo[$tag] = $this->nodeContents();
541 } elseif ( $tag == 'contributor' ) {
542 $revisionInfo['contributor'] = $this->handleContributor();
543 } elseif ( $tag != '#text' ) {
544 $this->warn( "Unhandled revision XML tag $tag" );
549 $pageInfo['revisionCount']++
;
550 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
551 $pageInfo['successfulRevisionCount']++
;
555 private function processRevision( $pageInfo, $revisionInfo ) {
556 $revision = new WikiRevision
;
558 if( isset( $revisionInfo['id'] ) ) {
559 $revision->setID( $revisionInfo['id'] );
561 if ( isset( $revisionInfo['text'] ) ) {
562 $revision->setText( $revisionInfo['text'] );
564 $revision->setTitle( $pageInfo['_title'] );
566 if ( isset( $revisionInfo['timestamp'] ) ) {
567 $revision->setTimestamp( $revisionInfo['timestamp'] );
569 $revision->setTimestamp( wfTimestampNow() );
572 if ( isset( $revisionInfo['comment'] ) ) {
573 $revision->setComment( $revisionInfo['comment'] );
576 if ( isset( $revisionInfo['minor'] ) ) {
577 $revision->setMinor( true );
579 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
580 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
582 if ( isset( $revisionInfo['contributor']['username'] ) ) {
583 $revision->setUserName( $revisionInfo['contributor']['username'] );
586 return $this->revisionCallback( $revision );
589 private function handleUpload( &$pageInfo ) {
590 $this->debug( "Enter upload handler" );
591 $uploadInfo = array();
593 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
594 'src', 'size', 'sha1base36', 'archivename', 'rel' );
598 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
599 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
600 $this->reader
->name
== 'upload') {
604 $tag = $this->reader
->name
;
606 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
609 } elseif ( in_array( $tag, $normalFields ) ) {
610 $uploadInfo[$tag] = $this->nodeContents();
611 } elseif ( $tag == 'contributor' ) {
612 $uploadInfo['contributor'] = $this->handleContributor();
613 } elseif ( $tag == 'contents' ) {
614 $contents = $this->nodeContents();
615 $encoding = $this->reader
->getAttribute( 'encoding' );
616 if ( $encoding === 'base64' ) {
617 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
618 $uploadInfo['isTempSrc'] = true;
620 } elseif ( $tag != '#text' ) {
621 $this->warn( "Unhandled upload XML tag $tag" );
626 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
627 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
628 if ( file_exists( $path ) ) {
629 $uploadInfo['fileSrc'] = $path;
630 $uploadInfo['isTempSrc'] = false;
634 if ( $this->mImportUploads
) {
635 return $this->processUpload( $pageInfo, $uploadInfo );
639 private function dumpTemp( $contents ) {
640 $filename = tempnam( wfTempDir(), 'importupload' );
641 file_put_contents( $filename, $contents );
646 private function processUpload( $pageInfo, $uploadInfo ) {
647 $revision = new WikiRevision
;
648 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
650 $revision->setTitle( $pageInfo['_title'] );
651 $revision->setID( $pageInfo['id'] );
652 $revision->setTimestamp( $uploadInfo['timestamp'] );
653 $revision->setText( $text );
654 $revision->setFilename( $uploadInfo['filename'] );
655 if ( isset( $uploadInfo['archivename'] ) ) {
656 $revision->setArchiveName( $uploadInfo['archivename'] );
658 $revision->setSrc( $uploadInfo['src'] );
659 if ( isset( $uploadInfo['fileSrc'] ) ) {
660 $revision->setFileSrc( $uploadInfo['fileSrc'],
661 !empty( $uploadInfo['isTempSrc'] ) );
663 if ( isset( $uploadInfo['sha1base36'] ) ) {
664 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
666 $revision->setSize( intval( $uploadInfo['size'] ) );
667 $revision->setComment( $uploadInfo['comment'] );
669 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
670 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
672 if ( isset( $uploadInfo['contributor']['username'] ) ) {
673 $revision->setUserName( $uploadInfo['contributor']['username'] );
676 return call_user_func( $this->mUploadCallback
, $revision );
679 private function handleContributor() {
680 $fields = array( 'id', 'ip', 'username' );
683 while ( $this->reader
->read() ) {
684 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
685 $this->reader
->name
== 'contributor') {
689 $tag = $this->reader
->name
;
691 if ( in_array( $tag, $fields ) ) {
692 $info[$tag] = $this->nodeContents();
699 private function processTitle( $text ) {
701 $origTitle = Title
::newFromText( $workTitle );
703 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
704 $title = Title
::makeTitle( $this->mTargetNamespace
,
705 $origTitle->getDBkey() );
707 $title = Title
::newFromText( $workTitle );
710 if( is_null( $title ) ) {
711 // Invalid page title? Ignore the page
712 $this->notice( "Skipping invalid page title '$workTitle'" );
714 } elseif( $title->getInterwiki() != '' ) {
715 $this->notice( "Skipping interwiki page title '$workTitle'" );
719 return array( $title, $origTitle );
723 /** This is a horrible hack used to keep source compatibility */
724 class UploadSourceAdapter
{
725 static $sourceRegistrations = array();
731 static function registerSource( $source ) {
732 $id = wfGenerateToken();
734 self
::$sourceRegistrations[$id] = $source;
739 function stream_open( $path, $mode, $options, &$opened_path ) {
740 $url = parse_url($path);
743 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
747 $this->mSource
= self
::$sourceRegistrations[$id];
752 function stream_read( $count ) {
756 while ( !$leave && !$this->mSource
->atEnd() &&
757 strlen($this->mBuffer
) < $count ) {
758 $read = $this->mSource
->readChunk();
760 if ( !strlen($read) ) {
764 $this->mBuffer
.= $read;
767 if ( strlen($this->mBuffer
) ) {
768 $return = substr( $this->mBuffer
, 0, $count );
769 $this->mBuffer
= substr( $this->mBuffer
, $count );
772 $this->mPosition +
= strlen($return);
777 function stream_write( $data ) {
781 function stream_tell() {
782 return $this->mPosition
;
785 function stream_eof() {
786 return $this->mSource
->atEnd();
789 function url_stat() {
792 $result['dev'] = $result[0] = 0;
793 $result['ino'] = $result[1] = 0;
794 $result['mode'] = $result[2] = 0;
795 $result['nlink'] = $result[3] = 0;
796 $result['uid'] = $result[4] = 0;
797 $result['gid'] = $result[5] = 0;
798 $result['rdev'] = $result[6] = 0;
799 $result['size'] = $result[7] = 0;
800 $result['atime'] = $result[8] = 0;
801 $result['mtime'] = $result[9] = 0;
802 $result['ctime'] = $result[10] = 0;
803 $result['blksize'] = $result[11] = 0;
804 $result['blocks'] = $result[12] = 0;
810 class XMLReader2
extends XMLReader
{
811 function nodeContents() {
812 if( $this->isEmptyElement
) {
816 while( $this->read() ) {
817 switch( $this->nodeType
) {
818 case XmlReader
::TEXT
:
819 case XmlReader
::SIGNIFICANT_WHITESPACE
:
820 $buffer .= $this->value
;
822 case XmlReader
::END_ELEMENT
:
826 return $this->close();
831 * @todo document (e.g. one-sentence class description).
832 * @ingroup SpecialPage
835 var $importer = null;
838 var $timestamp = "20010115000000";
848 var $sha1base36 = false;
850 var $archiveName = '';
852 function setTitle( $title ) {
853 if( is_object( $title ) ) {
854 $this->title
= $title;
855 } elseif( is_null( $title ) ) {
856 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
858 throw new MWException( "WikiRevision given non-object title in import." );
862 function setID( $id ) {
866 function setTimestamp( $ts ) {
867 # 2003-08-05T18:30:02Z
868 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
871 function setUsername( $user ) {
872 $this->user_text
= $user;
875 function setUserIP( $ip ) {
876 $this->user_text
= $ip;
879 function setText( $text ) {
883 function setComment( $text ) {
884 $this->comment
= $text;
887 function setMinor( $minor ) {
888 $this->minor
= (bool)$minor;
891 function setSrc( $src ) {
894 function setFileSrc( $src, $isTemp ) {
895 $this->fileSrc
= $src;
896 $this->fileIsTemp
= $isTemp;
898 function setSha1Base36( $sha1base36 ) {
899 $this->sha1base36
= $sha1base36;
902 function setFilename( $filename ) {
903 $this->filename
= $filename;
905 function setArchiveName( $archiveName ) {
906 $this->archiveName
= $archiveName;
909 function setSize( $size ) {
910 $this->size
= intval( $size );
913 function setType( $type ) {
917 function setAction( $action ) {
918 $this->action
= $action;
921 function setParams( $params ) {
922 $this->params
= $params;
928 function getTitle() {
936 function getTimestamp() {
937 return $this->timestamp
;
941 return $this->user_text
;
948 function getComment() {
949 return $this->comment
;
952 function getMinor() {
960 if ( $this->sha1base36
) {
961 return wfBaseConvert( $this->sha1base36
, 36, 16 );
965 function getFileSrc() {
966 return $this->fileSrc
;
968 function isTempSrc() {
969 return $this->isTemp
;
972 function getFilename() {
973 return $this->filename
;
975 function getArchiveName() {
976 return $this->archiveName
;
987 function getAction() {
988 return $this->action
;
991 function getParams() {
992 return $this->params
;
995 function importOldRevision() {
996 $dbw = wfGetDB( DB_MASTER
);
998 # Sneak a single revision into place
999 $user = User
::newFromName( $this->getUser() );
1001 $userId = intval( $user->getId() );
1002 $userText = $user->getName();
1005 $userText = $this->getUser();
1008 // avoid memory leak...?
1009 $linkCache = LinkCache
::singleton();
1010 $linkCache->clear();
1012 $article = new Article( $this->title
);
1013 $pageId = $article->getId();
1014 if( $pageId == 0 ) {
1015 # must create the page...
1016 $pageId = $article->insertOn( $dbw );
1021 $prior = $dbw->selectField( 'revision', '1',
1022 array( 'rev_page' => $pageId,
1023 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1024 'rev_user_text' => $userText,
1025 'rev_comment' => $this->getComment() ),
1029 // @todo FIXME: This could fail slightly for multiple matches :P
1030 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1031 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1036 # @todo FIXME: Use original rev_id optionally (better for backups)
1038 $revision = new Revision( array(
1040 'text' => $this->getText(),
1041 'comment' => $this->getComment(),
1043 'user_text' => $userText,
1044 'timestamp' => $this->timestamp
,
1045 'minor_edit' => $this->minor
,
1047 $revId = $revision->insertOn( $dbw );
1048 $changed = $article->updateIfNewerOn( $dbw, $revision );
1050 # To be on the safe side...
1051 $tempTitle = $GLOBALS['wgTitle'];
1052 $GLOBALS['wgTitle'] = $this->title
;
1055 wfDebug( __METHOD__
. ": running onArticleCreate\n" );
1056 Article
::onArticleCreate( $this->title
);
1057 } elseif( $changed ) {
1058 wfDebug( __METHOD__
. ": running onArticleEdit\n" );
1059 Article
::onArticleEdit( $this->title
);
1062 wfDebug( __METHOD__
. ": running updates\n" );
1063 $article->editUpdates(
1065 $this->getComment(),
1073 $GLOBALS['wgTitle'] = $tempTitle;
1078 function importLogItem() {
1079 $dbw = wfGetDB( DB_MASTER
);
1080 # @todo FIXME: This will not record autoblocks
1081 if( !$this->getTitle() ) {
1082 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1083 $this->timestamp
. "\n" );
1086 # Check if it exists already
1087 // @todo FIXME: Use original log ID (better for backups)
1088 $prior = $dbw->selectField( 'logging', '1',
1089 array( 'log_type' => $this->getType(),
1090 'log_action' => $this->getAction(),
1091 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1092 'log_namespace' => $this->getTitle()->getNamespace(),
1093 'log_title' => $this->getTitle()->getDBkey(),
1094 'log_comment' => $this->getComment(),
1095 #'log_user_text' => $this->user_text,
1096 'log_params' => $this->params
),
1099 // @todo FIXME: This could fail slightly for multiple matches :P
1101 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1102 $this->timestamp
. "\n" );
1105 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1107 'log_id' => $log_id,
1108 'log_type' => $this->type
,
1109 'log_action' => $this->action
,
1110 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1111 'log_user' => User
::idFromName( $this->user_text
),
1112 #'log_user_text' => $this->user_text,
1113 'log_namespace' => $this->getTitle()->getNamespace(),
1114 'log_title' => $this->getTitle()->getDBkey(),
1115 'log_comment' => $this->getComment(),
1116 'log_params' => $this->params
1118 $dbw->insert( 'logging', $data, __METHOD__
);
1121 function importUpload() {
1123 $archiveName = $this->getArchiveName();
1124 if ( $archiveName ) {
1125 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1126 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1127 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1129 $file = wfLocalFile( $this->getTitle() );
1130 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1131 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1132 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1133 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1134 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1135 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1139 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1143 # Get the file source or download if necessary
1144 $source = $this->getFileSrc();
1145 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1147 $source = $this->downloadSource();
1148 $flags |
= File
::DELETE_SOURCE
;
1151 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1154 $sha1 = $this->getSha1();
1155 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1156 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1160 $user = User
::newFromName( $this->user_text
);
1162 # Do the actual upload
1163 if ( $archiveName ) {
1164 $status = $file->uploadOld( $source, $archiveName,
1165 $this->getTimestamp(), $this->getComment(), $user, $flags );
1167 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1168 $flags, false, $this->getTimestamp(), $user );
1171 if ( $status->isGood() ) {
1172 wfDebug( __METHOD__
. ": Succesful\n" );
1175 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1180 function downloadSource() {
1181 global $wgEnableUploads;
1182 if( !$wgEnableUploads ) {
1186 $tempo = tempnam( wfTempDir(), 'download' );
1187 $f = fopen( $tempo, 'wb' );
1189 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1194 $src = $this->getSrc();
1195 $data = Http
::get( $src );
1197 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1203 fwrite( $f, $data );
1212 * @todo document (e.g. one-sentence class description).
1213 * @ingroup SpecialPage
1215 class ImportStringSource
{
1216 function __construct( $string ) {
1217 $this->mString
= $string;
1218 $this->mRead
= false;
1222 return $this->mRead
;
1225 function readChunk() {
1226 if( $this->atEnd() ) {
1229 $this->mRead
= true;
1230 return $this->mString
;
1236 * @todo document (e.g. one-sentence class description).
1237 * @ingroup SpecialPage
1239 class ImportStreamSource
{
1240 function __construct( $handle ) {
1241 $this->mHandle
= $handle;
1245 return feof( $this->mHandle
);
1248 function readChunk() {
1249 return fread( $this->mHandle
, 32768 );
1252 static function newFromFile( $filename ) {
1253 $file = @fopen
( $filename, 'rt' );
1255 return Status
::newFatal( "importcantopen" );
1257 return Status
::newGood( new ImportStreamSource( $file ) );
1260 static function newFromUpload( $fieldname = "xmlimport" ) {
1261 $upload =& $_FILES[$fieldname];
1263 if( !isset( $upload ) ||
!$upload['name'] ) {
1264 return Status
::newFatal( 'importnofile' );
1266 if( !empty( $upload['error'] ) ) {
1267 switch($upload['error']){
1268 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1269 return Status
::newFatal( 'importuploaderrorsize' );
1270 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1271 return Status
::newFatal( 'importuploaderrorsize' );
1272 case 3: # The uploaded file was only partially uploaded
1273 return Status
::newFatal( 'importuploaderrorpartial' );
1274 case 6: #Missing a temporary folder.
1275 return Status
::newFatal( 'importuploaderrortemp' );
1276 # case else: # Currently impossible
1280 $fname = $upload['tmp_name'];
1281 if( is_uploaded_file( $fname ) ) {
1282 return ImportStreamSource
::newFromFile( $fname );
1284 return Status
::newFatal( 'importnofile' );
1288 static function newFromURL( $url, $method = 'GET' ) {
1289 wfDebug( __METHOD__
. ": opening $url\n" );
1290 # Use the standard HTTP fetch function; it times out
1291 # quicker and sorts out user-agent problems which might
1292 # otherwise prevent importing from large sites, such
1293 # as the Wikimedia cluster, etc.
1294 $data = Http
::request( $method, $url );
1295 if( $data !== false ) {
1297 fwrite( $file, $data );
1300 return Status
::newGood( new ImportStreamSource( $file ) );
1302 return Status
::newFatal( 'importcantopen' );
1306 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1308 return Status
::newFatal( 'import-noarticle' );
1310 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1311 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1312 return Status
::newFatal( 'importbadinterwiki' );
1315 if ( $history ) $params['history'] = 1;
1316 if ( $templates ) $params['templates'] = 1;
1317 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1318 $url = $link->getFullUrl( $params );
1319 # For interwikis, use POST to avoid redirects.
1320 return ImportStreamSource
::newFromURL( $url, "POST" );