Revert r91426 and followups r91427, r91430: Breaks Gallery-related parser tests
[mediawiki.git] / includes / Import.php
blob2a864382d55e34588cc26a2ddb4a6163bb553c3e
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;
38 private $mImportUploads, $mImageBasePath;
40 /**
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" );
50 // Default callbacks
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 ) {
63 if( $this->mDebug ) {
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 ) {
75 print "$data\n";
76 } else {
77 global $wgOut;
78 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
82 /**
83 * Set debug mode...
85 function setDebug( $debug ) {
86 $this->mDebug = $debug;
89 /**
90 * Sets the action to perform as each new page in the stream is reached.
91 * @param $callback callback
92 * @return callback
94 public function setPageCallback( $callback ) {
95 $previous = $this->mPageCallback;
96 $this->mPageCallback = $callback;
97 return $previous;
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
107 * @return callback
109 public function setPageOutCallback( $callback ) {
110 $previous = $this->mPageOutCallback;
111 $this->mPageOutCallback = $callback;
112 return $previous;
116 * Sets the action to perform as each page revision is reached.
117 * @param $callback callback
118 * @return callback
120 public function setRevisionCallback( $callback ) {
121 $previous = $this->mRevisionCallback;
122 $this->mRevisionCallback = $callback;
123 return $previous;
127 * Sets the action to perform as each file upload version is reached.
128 * @param $callback callback
129 * @return callback
131 public function setUploadCallback( $callback ) {
132 $previous = $this->mUploadCallback;
133 $this->mUploadCallback = $callback;
134 return $previous;
138 * Sets the action to perform as each log item reached.
139 * @param $callback callback
140 * @return callback
142 public function setLogItemCallback( $callback ) {
143 $previous = $this->mLogItemCallback;
144 $this->mLogItemCallback = $callback;
145 return $previous;
149 * Sets the action to perform when site info is encountered
150 * @param $callback callback
151 * @return callback
153 public function setSiteInfoCallback( $callback ) {
154 $previous = $this->mSiteInfoCallback;
155 $this->mSiteInfoCallback = $callback;
156 return $previous;
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 );
169 } else {
170 return false;
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' ) );
203 * Dummy for now...
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() );
226 } else {
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 ) );
268 } else {
269 return false;
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 ) );
281 } else {
282 return false;
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.
290 * @return string
291 * @access private
293 private function nodeContents() {
294 if( $this->reader->isEmptyElement ) {
295 return "";
297 $buffer = "";
298 while( $this->reader->read() ) {
299 switch( $this->reader->nodeType ) {
300 case XmlReader::TEXT:
301 case XmlReader::SIGNIFICANT_WHITESPACE:
302 $buffer .= $this->reader->value;
303 break;
304 case XmlReader::END_ELEMENT:
305 return $buffer;
309 $this->reader->close();
310 return '';
313 # --------------
315 /** Left in for debugging */
316 private function dumpElement() {
317 static $lookup = null;
318 if (!$lookup) {
319 $xmlReaderConstants = array(
320 "NONE",
321 "ELEMENT",
322 "ATTRIBUTE",
323 "TEXT",
324 "CDATA",
325 "ENTITY_REF",
326 "ENTITY",
327 "PI",
328 "COMMENT",
329 "DOC",
330 "DOC_TYPE",
331 "DOC_FRAGMENT",
332 "NOTATION",
333 "WHITESPACE",
334 "SIGNIFICANT_WHITESPACE",
335 "END_ELEMENT",
336 "END_ENTITY",
337 "XML_DECLARATION",
339 $lookup = array();
341 foreach( $xmlReaderConstants as $name ) {
342 $lookup[constant("XmlReader::$name")] = $name;
346 print( var_dump(
347 $lookup[$this->reader->nodeType],
348 $this->reader->name,
349 $this->reader->value
350 )."\n\n" );
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();
368 $skip = false;
369 while ( $keepReading ) {
370 $tag = $this->reader->name;
371 $type = $this->reader->nodeType;
373 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
374 // Do nothing
375 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
376 break;
377 } elseif ( $tag == 'siteinfo' ) {
378 $this->handleSiteInfo();
379 } elseif ( $tag == 'page' ) {
380 $this->handlePage();
381 } elseif ( $tag == 'logitem' ) {
382 $this->handleLogItem();
383 } elseif ( $tag != '#text' ) {
384 $this->warn( "Unhandled top-level XML tag $tag" );
386 $skip = true;
389 if ($skip) {
390 $keepReading = $this->reader->next();
391 $skip = false;
392 $this->debug( "Skip" );
393 } else {
394 $keepReading = $this->reader->read();
398 return true;
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();
406 return true;
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." );
413 $logInfo = array();
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') {
422 break;
425 $tag = $this->reader->name;
427 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
428 $this, $logInfo ) ) {
429 // Do nothing
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() {
467 // Handle page data.
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' );
474 $skip = false;
475 $badTitle = false;
477 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
478 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
479 $this->reader->name == 'page') {
480 break;
483 $tag = $this->reader->name;
485 if ( $badTitle ) {
486 // The title is invalid, bail out of this page
487 $skip = true;
488 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
489 &$pageInfo ) ) ) {
490 // Do nothing
491 } elseif ( in_array( $tag, $normalFields ) ) {
492 $pageInfo[$tag] = $this->nodeContents();
493 if ( $tag == 'title' ) {
494 $title = $this->processTitle( $pageInfo['title'] );
496 if ( !$title ) {
497 $badTitle = true;
498 $skip = true;
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" );
510 $skip = true;
514 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
515 $pageInfo['revisionCount'],
516 $pageInfo['successfulRevisionCount'],
517 $pageInfo );
520 private function handleRevision( &$pageInfo ) {
521 $this->debug( "Enter revision handler" );
522 $revisionInfo = array();
524 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
526 $skip = false;
528 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
529 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
530 $this->reader->name == 'revision') {
531 break;
534 $tag = $this->reader->name;
536 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
537 $pageInfo, $revisionInfo ) ) {
538 // Do nothing
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" );
545 $skip = true;
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'] );
568 } else {
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' );
596 $skip = false;
598 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
599 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
600 $this->reader->name == 'upload') {
601 break;
604 $tag = $this->reader->name;
606 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
607 $pageInfo ) ) {
608 // Do nothing
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" );
622 $skip = true;
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 );
642 return $filename;
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' );
681 $info = array();
683 while ( $this->reader->read() ) {
684 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
685 $this->reader->name == 'contributor') {
686 break;
689 $tag = $this->reader->name;
691 if ( in_array( $tag, $fields ) ) {
692 $info[$tag] = $this->nodeContents();
696 return $info;
699 private function processTitle( $text ) {
700 $workTitle = $text;
701 $origTitle = Title::newFromText( $workTitle );
703 if( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
704 $title = Title::makeTitle( $this->mTargetNamespace,
705 $origTitle->getDBkey() );
706 } else {
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'" );
713 return false;
714 } elseif( $title->getInterwiki() != '' ) {
715 $this->notice( "Skipping interwiki page title '$workTitle'" );
716 return false;
719 return array( $title, $origTitle );
723 /** This is a horrible hack used to keep source compatibility */
724 class UploadSourceAdapter {
725 static $sourceRegistrations = array();
727 private $mSource;
728 private $mBuffer;
729 private $mPosition;
731 static function registerSource( $source ) {
732 $id = wfGenerateToken();
734 self::$sourceRegistrations[$id] = $source;
736 return $id;
739 function stream_open( $path, $mode, $options, &$opened_path ) {
740 $url = parse_url($path);
741 $id = $url['host'];
743 if ( !isset( self::$sourceRegistrations[$id] ) ) {
744 return false;
747 $this->mSource = self::$sourceRegistrations[$id];
749 return true;
752 function stream_read( $count ) {
753 $return = '';
754 $leave = false;
756 while ( !$leave && !$this->mSource->atEnd() &&
757 strlen($this->mBuffer) < $count ) {
758 $read = $this->mSource->readChunk();
760 if ( !strlen($read) ) {
761 $leave = true;
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);
774 return $return;
777 function stream_write( $data ) {
778 return false;
781 function stream_tell() {
782 return $this->mPosition;
785 function stream_eof() {
786 return $this->mSource->atEnd();
789 function url_stat() {
790 $result = array();
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;
806 return $result;
810 class XMLReader2 extends XMLReader {
811 function nodeContents() {
812 if( $this->isEmptyElement ) {
813 return "";
815 $buffer = "";
816 while( $this->read() ) {
817 switch( $this->nodeType ) {
818 case XmlReader::TEXT:
819 case XmlReader::SIGNIFICANT_WHITESPACE:
820 $buffer .= $this->value;
821 break;
822 case XmlReader::END_ELEMENT:
823 return $buffer;
826 return $this->close();
831 * @todo document (e.g. one-sentence class description).
832 * @ingroup SpecialPage
834 class WikiRevision {
835 var $importer = null;
836 var $title = null;
837 var $id = 0;
838 var $timestamp = "20010115000000";
839 var $user = 0;
840 var $user_text = "";
841 var $text = "";
842 var $comment = "";
843 var $minor = false;
844 var $type = "";
845 var $action = "";
846 var $params = "";
847 var $fileSrc = '';
848 var $sha1base36 = false;
849 var $isTemp = 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." );
857 } else {
858 throw new MWException( "WikiRevision given non-object title in import." );
862 function setID( $id ) {
863 $this->id = $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 ) {
880 $this->text = $text;
883 function setComment( $text ) {
884 $this->comment = $text;
887 function setMinor( $minor ) {
888 $this->minor = (bool)$minor;
891 function setSrc( $src ) {
892 $this->src = $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 ) {
914 $this->type = $type;
917 function setAction( $action ) {
918 $this->action = $action;
921 function setParams( $params ) {
922 $this->params = $params;
926 * @return Title
928 function getTitle() {
929 return $this->title;
932 function getID() {
933 return $this->id;
936 function getTimestamp() {
937 return $this->timestamp;
940 function getUser() {
941 return $this->user_text;
944 function getText() {
945 return $this->text;
948 function getComment() {
949 return $this->comment;
952 function getMinor() {
953 return $this->minor;
956 function getSrc() {
957 return $this->src;
959 function getSha1() {
960 if ( $this->sha1base36 ) {
961 return wfBaseConvert( $this->sha1base36, 36, 16 );
963 return false;
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;
979 function getSize() {
980 return $this->size;
983 function getType() {
984 return $this->type;
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() );
1000 if( $user ) {
1001 $userId = intval( $user->getId() );
1002 $userText = $user->getName();
1003 $userObj = $user;
1004 } else {
1005 $userId = 0;
1006 $userText = $this->getUser();
1007 $userObj = new User;
1010 // avoid memory leak...?
1011 $linkCache = LinkCache::singleton();
1012 $linkCache->clear();
1014 $article = new Article( $this->title );
1015 $pageId = $article->getId();
1016 if( $pageId == 0 ) {
1017 # must create the page...
1018 $pageId = $article->insertOn( $dbw );
1019 $created = true;
1020 $oldcountable = null;
1021 } else {
1022 $created = false;
1024 $prior = $dbw->selectField( 'revision', '1',
1025 array( 'rev_page' => $pageId,
1026 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1027 'rev_user_text' => $userText,
1028 'rev_comment' => $this->getComment() ),
1029 __METHOD__
1031 if( $prior ) {
1032 // @todo FIXME: This could fail slightly for multiple matches :P
1033 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1034 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1035 return false;
1037 $oldcountable = $article->isCountable();
1040 # @todo FIXME: Use original rev_id optionally (better for backups)
1041 # Insert the row
1042 $revision = new Revision( array(
1043 'page' => $pageId,
1044 'text' => $this->getText(),
1045 'comment' => $this->getComment(),
1046 'user' => $userId,
1047 'user_text' => $userText,
1048 'timestamp' => $this->timestamp,
1049 'minor_edit' => $this->minor,
1050 ) );
1051 $revision->insertOn( $dbw );
1052 $changed = $article->updateIfNewerOn( $dbw, $revision );
1054 if ( $changed !== false ) {
1055 wfDebug( __METHOD__ . ": running updates\n" );
1056 $article->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1059 return true;
1062 function importLogItem() {
1063 $dbw = wfGetDB( DB_MASTER );
1064 # @todo FIXME: This will not record autoblocks
1065 if( !$this->getTitle() ) {
1066 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1067 $this->timestamp . "\n" );
1068 return;
1070 # Check if it exists already
1071 // @todo FIXME: Use original log ID (better for backups)
1072 $prior = $dbw->selectField( 'logging', '1',
1073 array( 'log_type' => $this->getType(),
1074 'log_action' => $this->getAction(),
1075 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1076 'log_namespace' => $this->getTitle()->getNamespace(),
1077 'log_title' => $this->getTitle()->getDBkey(),
1078 'log_comment' => $this->getComment(),
1079 #'log_user_text' => $this->user_text,
1080 'log_params' => $this->params ),
1081 __METHOD__
1083 // @todo FIXME: This could fail slightly for multiple matches :P
1084 if( $prior ) {
1085 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1086 $this->timestamp . "\n" );
1087 return false;
1089 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1090 $data = array(
1091 'log_id' => $log_id,
1092 'log_type' => $this->type,
1093 'log_action' => $this->action,
1094 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1095 'log_user' => User::idFromName( $this->user_text ),
1096 #'log_user_text' => $this->user_text,
1097 'log_namespace' => $this->getTitle()->getNamespace(),
1098 'log_title' => $this->getTitle()->getDBkey(),
1099 'log_comment' => $this->getComment(),
1100 'log_params' => $this->params
1102 $dbw->insert( 'logging', $data, __METHOD__ );
1105 function importUpload() {
1106 # Construct a file
1107 $archiveName = $this->getArchiveName();
1108 if ( $archiveName ) {
1109 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1110 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1111 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1112 } else {
1113 $file = wfLocalFile( $this->getTitle() );
1114 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1115 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1116 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1117 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1118 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1119 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1122 if( !$file ) {
1123 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1124 return false;
1127 # Get the file source or download if necessary
1128 $source = $this->getFileSrc();
1129 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1130 if ( !$source ) {
1131 $source = $this->downloadSource();
1132 $flags |= File::DELETE_SOURCE;
1134 if( !$source ) {
1135 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1136 return false;
1138 $sha1 = $this->getSha1();
1139 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1140 if ( $flags & File::DELETE_SOURCE ) {
1141 # Broken file; delete it if it is a temporary file
1142 unlink( $source );
1144 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1145 return false;
1148 $user = User::newFromName( $this->user_text );
1150 # Do the actual upload
1151 if ( $archiveName ) {
1152 $status = $file->uploadOld( $source, $archiveName,
1153 $this->getTimestamp(), $this->getComment(), $user, $flags );
1154 } else {
1155 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1156 $flags, false, $this->getTimestamp(), $user );
1159 if ( $status->isGood() ) {
1160 wfDebug( __METHOD__ . ": Succesful\n" );
1161 return true;
1162 } else {
1163 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1164 return false;
1168 function downloadSource() {
1169 global $wgEnableUploads;
1170 if( !$wgEnableUploads ) {
1171 return false;
1174 $tempo = tempnam( wfTempDir(), 'download' );
1175 $f = fopen( $tempo, 'wb' );
1176 if( !$f ) {
1177 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1178 return false;
1181 // @todo FIXME!
1182 $src = $this->getSrc();
1183 $data = Http::get( $src );
1184 if( !$data ) {
1185 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1186 fclose( $f );
1187 unlink( $tempo );
1188 return false;
1191 fwrite( $f, $data );
1192 fclose( $f );
1194 return $tempo;
1200 * @todo document (e.g. one-sentence class description).
1201 * @ingroup SpecialPage
1203 class ImportStringSource {
1204 function __construct( $string ) {
1205 $this->mString = $string;
1206 $this->mRead = false;
1209 function atEnd() {
1210 return $this->mRead;
1213 function readChunk() {
1214 if( $this->atEnd() ) {
1215 return false;
1216 } else {
1217 $this->mRead = true;
1218 return $this->mString;
1224 * @todo document (e.g. one-sentence class description).
1225 * @ingroup SpecialPage
1227 class ImportStreamSource {
1228 function __construct( $handle ) {
1229 $this->mHandle = $handle;
1232 function atEnd() {
1233 return feof( $this->mHandle );
1236 function readChunk() {
1237 return fread( $this->mHandle, 32768 );
1240 static function newFromFile( $filename ) {
1241 wfSuppressWarnings();
1242 $file = fopen( $filename, 'rt' );
1243 wfRestoreWarnings();
1244 if( !$file ) {
1245 return Status::newFatal( "importcantopen" );
1247 return Status::newGood( new ImportStreamSource( $file ) );
1250 static function newFromUpload( $fieldname = "xmlimport" ) {
1251 $upload =& $_FILES[$fieldname];
1253 if( !isset( $upload ) || !$upload['name'] ) {
1254 return Status::newFatal( 'importnofile' );
1256 if( !empty( $upload['error'] ) ) {
1257 switch($upload['error']){
1258 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1259 return Status::newFatal( 'importuploaderrorsize' );
1260 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1261 return Status::newFatal( 'importuploaderrorsize' );
1262 case 3: # The uploaded file was only partially uploaded
1263 return Status::newFatal( 'importuploaderrorpartial' );
1264 case 6: #Missing a temporary folder.
1265 return Status::newFatal( 'importuploaderrortemp' );
1266 # case else: # Currently impossible
1270 $fname = $upload['tmp_name'];
1271 if( is_uploaded_file( $fname ) ) {
1272 return ImportStreamSource::newFromFile( $fname );
1273 } else {
1274 return Status::newFatal( 'importnofile' );
1278 static function newFromURL( $url, $method = 'GET' ) {
1279 wfDebug( __METHOD__ . ": opening $url\n" );
1280 # Use the standard HTTP fetch function; it times out
1281 # quicker and sorts out user-agent problems which might
1282 # otherwise prevent importing from large sites, such
1283 # as the Wikimedia cluster, etc.
1284 $data = Http::request( $method, $url );
1285 if( $data !== false ) {
1286 $file = tmpfile();
1287 fwrite( $file, $data );
1288 fflush( $file );
1289 fseek( $file, 0 );
1290 return Status::newGood( new ImportStreamSource( $file ) );
1291 } else {
1292 return Status::newFatal( 'importcantopen' );
1296 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1297 if( $page == '' ) {
1298 return Status::newFatal( 'import-noarticle' );
1300 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1301 if( is_null( $link ) || $link->getInterwiki() == '' ) {
1302 return Status::newFatal( 'importbadinterwiki' );
1303 } else {
1304 $params = array();
1305 if ( $history ) $params['history'] = 1;
1306 if ( $templates ) $params['templates'] = 1;
1307 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1308 $url = $link->getFullUrl( $params );
1309 # For interwikis, use POST to avoid redirects.
1310 return ImportStreamSource::newFromURL( $url, "POST" );