Kill NamespaceCompat. Nothing, anywhere (not even comments, since r70692) still refer...
[mediawiki.git] / includes / ImportXMLReader.php
blobcdb7f7f218b10cad0b3c9e9d1b737298a23c1c69
1 <?php
2 /**
3 * implements Special:Import
4 * @ingroup SpecialPage
5 */
6 class WikiImporter {
7 private $reader = null;
8 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
9 private $mSiteInfoCallback, $mTargetNamespace, $mPageOutCallback;
10 private $mDebug;
12 /**
13 * Creates an ImportXMLReader drawing from the source provided
15 function __construct( $source ) {
16 $this->reader = new XMLReader2();
18 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
19 $id = UploadSourceAdapter::registerSource( $source );
20 $this->reader->open( "uploadsource://$id" );
22 // Default callbacks
23 $this->setRevisionCallback( array( $this, "importRevision" ) );
24 $this->setUploadCallback( array( $this, 'importUpload' ) );
25 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
26 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
29 private function throwXmlError( $err ) {
30 $this->debug( "FAILURE: $err" );
31 wfDebug( "WikiImporter XML error: $err\n" );
34 private function debug( $data ) {
35 if( $this->mDebug ) {
36 wfDebug( "IMPORT: $data\n" );
40 private function warn( $data ) {
41 wfDebug( "IMPORT: $data\n" );
44 private function notice( $data ) {
45 global $wgCommandLineMode;
46 if( $wgCommandLineMode ) {
47 print "$data\n";
48 } else {
49 global $wgOut;
50 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
54 /**
55 * Set debug mode...
57 function setDebug( $debug ) {
58 $this->mDebug = $debug;
61 /**
62 * Sets the action to perform as each new page in the stream is reached.
63 * @param $callback callback
64 * @return callback
66 public function setPageCallback( $callback ) {
67 $previous = $this->mPageCallback;
68 $this->mPageCallback = $callback;
69 return $previous;
72 /**
73 * Sets the action to perform as each page in the stream is completed.
74 * Callback accepts the page title (as a Title object), a second object
75 * with the original title form (in case it's been overridden into a
76 * local namespace), and a count of revisions.
78 * @param $callback callback
79 * @return callback
81 public function setPageOutCallback( $callback ) {
82 $previous = $this->mPageOutCallback;
83 $this->mPageOutCallback = $callback;
84 return $previous;
87 /**
88 * Sets the action to perform as each page revision is reached.
89 * @param $callback callback
90 * @return callback
92 public function setRevisionCallback( $callback ) {
93 $previous = $this->mRevisionCallback;
94 $this->mRevisionCallback = $callback;
95 return $previous;
98 /**
99 * Sets the action to perform as each file upload version is reached.
100 * @param $callback callback
101 * @return callback
103 public function setUploadCallback( $callback ) {
104 $previous = $this->mUploadCallback;
105 $this->mUploadCallback = $callback;
106 return $previous;
110 * Sets the action to perform as each log item reached.
111 * @param $callback callback
112 * @return callback
114 public function setLogItemCallback( $callback ) {
115 $previous = $this->mLogItemCallback;
116 $this->mLogItemCallback = $callback;
117 return $previous;
121 * Sets the action to perform when site info is encountered
122 * @param $callback callback
123 * @return callback
125 public function setSiteInfoCallback( $callback ) {
126 $previous = $this->mSiteInfoCallback;
127 $this->mSiteInfoCallback = $callback;
128 return $previous;
132 * Set a target namespace to override the defaults
134 public function setTargetNamespace( $namespace ) {
135 if( is_null( $namespace ) ) {
136 // Don't override namespaces
137 $this->mTargetNamespace = null;
138 } elseif( $namespace >= 0 ) {
139 // FIXME: Check for validity
140 $this->mTargetNamespace = intval( $namespace );
141 } else {
142 return false;
147 * Default per-revision callback, performs the import.
148 * @param $revision WikiRevision
150 public function importRevision( $revision ) {
151 $dbw = wfGetDB( DB_MASTER );
152 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
156 * Default per-revision callback, performs the import.
157 * @param $rev WikiRevision
159 public function importLogItem( $rev ) {
160 $dbw = wfGetDB( DB_MASTER );
161 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
165 * Dummy for now...
167 public function importUpload( $revision ) {
168 //$dbw = wfGetDB( DB_MASTER );
169 //return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
170 return false;
174 * Mostly for hook use
176 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
177 $args = func_get_args();
178 return wfRunHooks( 'AfterImportPage', $args );
182 * Alternate per-revision callback, for debugging.
183 * @param $revision WikiRevision
185 public function debugRevisionHandler( &$revision ) {
186 $this->debug( "Got revision:" );
187 if( is_object( $revision->title ) ) {
188 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
189 } else {
190 $this->debug( "-- Title: <invalid>" );
192 $this->debug( "-- User: " . $revision->user_text );
193 $this->debug( "-- Timestamp: " . $revision->timestamp );
194 $this->debug( "-- Comment: " . $revision->comment );
195 $this->debug( "-- Text: " . $revision->text );
199 * Notify the callback function when a new <page> is reached.
200 * @param $title Title
202 function pageCallback( $title ) {
203 if( isset( $this->mPageCallback ) ) {
204 call_user_func( $this->mPageCallback, $title );
209 * Notify the callback function when a </page> is closed.
210 * @param $title Title
211 * @param $origTitle Title
212 * @param $revCount Integer
213 * @param $sucCount Int: number of revisions for which callback returned true
214 * @param $pageInfo Array: associative array of page information
216 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
217 if( isset( $this->mPageOutCallback ) ) {
218 $args = func_get_args();
219 call_user_func_array( $this->mPageOutCallback, $args );
224 * Notify the callback function of a revision
225 * @param $revision A WikiRevision object
227 private function revisionCallback( $revision ) {
228 if ( isset( $this->mRevisionCallback ) ) {
229 return call_user_func_array( $this->mRevisionCallback,
230 array( $revision, $this ) );
231 } else {
232 return false;
237 * Notify the callback function of a new log item
238 * @param $revision A WikiRevision object
240 private function logItemCallback( $revision ) {
241 if ( isset( $this->mLogItemCallback ) ) {
242 return call_user_func_array( $this->mLogItemCallback,
243 array( $revision, $this ) );
244 } else {
245 return false;
250 * Shouldn't something like this be built-in to XMLReader?
251 * Fetches text contents of the current element, assuming
252 * no sub-elements or such scary things.
253 * @return string
254 * @access private
256 private function nodeContents() {
257 return $this->reader->nodeContents();
260 # --------------
262 /** Left in for debugging */
263 private function dumpElement() {
264 static $lookup = null;
265 if (!$lookup) {
266 $xmlReaderConstants = array(
267 "NONE",
268 "ELEMENT",
269 "ATTRIBUTE",
270 "TEXT",
271 "CDATA",
272 "ENTITY_REF",
273 "ENTITY",
274 "PI",
275 "COMMENT",
276 "DOC",
277 "DOC_TYPE",
278 "DOC_FRAGMENT",
279 "NOTATION",
280 "WHITESPACE",
281 "SIGNIFICANT_WHITESPACE",
282 "END_ELEMENT",
283 "END_ENTITY",
284 "XML_DECLARATION",
286 $lookup = array();
288 foreach( $xmlReaderConstants as $name ) {
289 $lookup[constant("XmlReader::$name")] = $name;
293 print( var_dump(
294 $lookup[$this->reader->nodeType],
295 $this->reader->name,
296 $this->reader->value
297 )."\n\n" );
301 * Primary entry point
303 public function doImport() {
304 $this->reader->read();
306 if ( $this->reader->name != 'mediawiki' ) {
307 throw new MWException( "Expected <mediawiki> tag, got ".
308 $this->reader->name );
310 $this->debug( "<mediawiki> tag is correct." );
312 $this->debug( "Starting primary dump processing loop." );
314 $keepReading = $this->reader->read();
315 $skip = false;
316 while ( $keepReading ) {
317 $tag = $this->reader->name;
318 $type = $this->reader->nodeType;
320 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this->reader ) ) {
321 // Do nothing
322 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
323 break;
324 } elseif ( $tag == 'siteinfo' ) {
325 $this->handleSiteInfo();
326 } elseif ( $tag == 'page' ) {
327 $this->handlePage();
328 } elseif ( $tag == 'logitem' ) {
329 $this->handleLogItem();
330 } elseif ( $tag != '#text' ) {
331 $this->warn( "Unhandled top-level XML tag $tag" );
333 $skip = true;
336 if ($skip) {
337 $keepReading = $this->reader->next();
338 $skip = false;
339 $this->debug( "Skip" );
340 } else {
341 $keepReading = $this->reader->read();
345 return true;
348 private function handleSiteInfo() {
349 // Site info is useful, but not actually used for dump imports.
350 // Includes a quick short-circuit to save performance.
351 if ( ! $this->mSiteInfoCallback ) {
352 $this->reader->next();
353 return true;
355 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
358 private function handleLogItem() {
359 $this->debug( "Enter log item handler." );
360 $logInfo = array();
362 // Fields that can just be stuffed in the pageInfo object
363 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
364 'logtitle', 'params' );
366 while ( $this->reader->read() ) {
367 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
368 $this->reader->name == 'logitem') {
369 break;
372 $tag = $this->reader->name;
374 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
375 $this->reader, $logInfo ) ) {
376 // Do nothing
377 } elseif ( in_array( $tag, $normalFields ) ) {
378 $logInfo[$tag] = $this->nodeContents();
379 } elseif ( $tag == 'contributor' ) {
380 $logInfo['contributor'] = $this->handleContributor();
381 } elseif ( $tag != '#text' ) {
382 $this->warn( "Unhandled log-item XML tag $tag" );
386 $this->processLogItem( $logInfo );
389 private function processLogItem( $logInfo ) {
390 $revision = new WikiRevision;
392 $revision->setID( $logInfo['id'] );
393 $revision->setType( $logInfo['type'] );
394 $revision->setAction( $logInfo['action'] );
395 $revision->setTimestamp( $logInfo['timestamp'] );
396 $revision->setParams( $logInfo['params'] );
397 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
399 if ( isset( $logInfo['comment'] ) ) {
400 $revision->setComment( $logInfo['comment'] );
403 if ( isset( $logInfo['contributor']['ip'] ) ) {
404 $revision->setUserIP( $logInfo['contributor']['ip'] );
406 if ( isset( $logInfo['contributor']['username'] ) ) {
407 $revision->setUserName( $logInfo['contributor']['username'] );
410 return $this->logItemCallback( $revision );
413 private function handlePage() {
414 // Handle page data.
415 $this->debug( "Enter page handler." );
416 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
418 // Fields that can just be stuffed in the pageInfo object
419 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
421 $skip = false;
422 $badTitle = false;
424 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
425 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
426 $this->reader->name == 'page') {
427 break;
430 $tag = $this->reader->name;
432 if ( $badTitle ) {
433 // The title is invalid, bail out of this page
434 $skip = true;
435 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this->reader,
436 &$pageInfo ) ) ) {
437 // Do nothing
438 } elseif ( in_array( $tag, $normalFields ) ) {
439 $pageInfo[$tag] = $this->nodeContents();
440 if ( $tag == 'title' ) {
441 $title = $this->processTitle( $pageInfo['title'] );
443 if ( !$title ) {
444 $badTitle = true;
445 $skip = true;
448 $this->pageCallback( $title );
449 list( $pageInfo['_title'], $origTitle ) = $title;
451 } elseif ( $tag == 'revision' ) {
452 $this->handleRevision( $pageInfo );
453 } elseif ( $tag == 'upload' ) {
454 $this->handleUpload( $pageInfo );
455 } elseif ( $tag != '#text' ) {
456 $this->warn( "Unhandled page XML tag $tag" );
457 $skip = true;
461 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
462 $pageInfo['revisionCount'],
463 $pageInfo['successfulRevisionCount'],
464 $pageInfo );
467 private function handleRevision( &$pageInfo ) {
468 $this->debug( "Enter revision handler" );
469 $revisionInfo = array();
471 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
473 $skip = false;
475 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
476 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
477 $this->reader->name == 'revision') {
478 break;
481 $tag = $this->reader->name;
483 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this->reader,
484 $pageInfo, $revisionInfo ) ) {
485 // Do nothing
486 } elseif ( in_array( $tag, $normalFields ) ) {
487 $revisionInfo[$tag] = $this->nodeContents();
488 } elseif ( $tag == 'contributor' ) {
489 $revisionInfo['contributor'] = $this->handleContributor();
490 } elseif ( $tag != '#text' ) {
491 $this->warn( "Unhandled revision XML tag $tag" );
492 $skip = true;
496 $pageInfo['revisionCount']++;
497 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
498 $pageInfo['successfulRevisionCount']++;
502 private function processRevision( $pageInfo, $revisionInfo ) {
503 $revision = new WikiRevision;
505 $revision->setID( $revisionInfo['id'] );
506 $revision->setText( $revisionInfo['text'] );
507 $revision->setTitle( $pageInfo['_title'] );
508 $revision->setTimestamp( $revisionInfo['timestamp'] );
510 if ( isset( $revisionInfo['comment'] ) ) {
511 $revision->setComment( $revisionInfo['comment'] );
514 if ( isset( $revisionInfo['minor'] ) )
515 $revision->setMinor( true );
517 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
518 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
520 if ( isset( $revisionInfo['contributor']['username'] ) ) {
521 $revision->setUserName( $revisionInfo['contributor']['username'] );
524 return $this->revisionCallback( $revision );
527 private function handleUpload( &$pageInfo ) {
528 $this->debug( "Enter upload handler" );
529 $uploadInfo = array();
531 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
532 'src', 'size' );
534 $skip = false;
536 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
537 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
538 $this->reader->name == 'upload') {
539 break;
542 $tag = $this->reader->name;
544 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this->reader,
545 $pageInfo, $revisionInfo ) ) {
546 // Do nothing
547 } elseif ( in_array( $tag, $normalFields ) ) {
548 $uploadInfo[$tag] = $this->nodeContents();
549 } elseif ( $tag == 'contributor' ) {
550 $uploadInfo['contributor'] = $this->handleContributor();
551 } elseif ( $tag != '#text' ) {
552 $this->warn( "Unhandled upload XML tag $tag" );
553 $skip = true;
557 return $this->processUpload( $pageInfo, $uploadInfo );
560 private function processUpload( $pageInfo, $uploadInfo ) {
561 $revision = new WikiRevision;
563 $revision->setTitle( $pageInfo['_title'] );
564 $revision->setID( $uploadInfo['id'] );
565 $revision->setTimestamp( $uploadInfo['timestamp'] );
566 $revision->setText( $uploadInfo['text'] );
567 $revision->setFilename( $uploadInfo['filename'] );
568 $revision->setSrc( $uploadInfo['src'] );
569 $revision->setSize( intval( $uploadInfo['size'] ) );
570 $revision->setComment( $uploadInfo['comment'] );
572 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
573 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
575 if ( isset( $uploadInfo['contributor']['username'] ) ) {
576 $revision->setUserName( $revisionInfo['contributor']['username'] );
579 return $this->uploadCallback( $revision );
582 private function handleContributor() {
583 $fields = array( 'id', 'ip', 'username' );
584 $info = array();
586 while ( $this->reader->read() ) {
587 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
588 $this->reader->name == 'contributor') {
589 break;
592 $tag = $this->reader->name;
594 if ( in_array( $tag, $fields ) ) {
595 $info[$tag] = $this->nodeContents();
599 return $info;
602 private function processTitle( $text ) {
603 $workTitle = $text;
604 $origTitle = Title::newFromText( $workTitle );
605 $title = null;
607 if( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
608 $title = Title::makeTitle( $this->mTargetNamespace,
609 $origTitle->getDBkey() );
610 } else {
611 $title = Title::newFromText( $workTitle );
614 if( is_null( $title ) ) {
615 // Invalid page title? Ignore the page
616 $this->notice( "Skipping invalid page title '$workTitle'" );
617 } elseif( $title->getInterwiki() != '' ) {
618 $this->notice( "Skipping interwiki page title '$workTitle'" );
619 $title = null;
622 return array( $origTitle, $title );
626 /** This is a horrible hack used to keep source compatibility */
627 class UploadSourceAdapter {
628 static $sourceRegistrations = array();
630 private $mSource;
631 private $mBuffer;
632 private $mPosition;
634 static function registerSource( $source ) {
635 $id = wfGenerateToken();
637 self::$sourceRegistrations[$id] = $source;
639 return $id;
642 function stream_open( $path, $mode, $options, &$opened_path ) {
643 $url = parse_url($path);
644 $id = $url['host'];
646 if ( !isset( self::$sourceRegistrations[$id] ) ) {
647 return false;
650 $this->mSource = self::$sourceRegistrations[$id];
652 return true;
655 function stream_read( $count ) {
656 $return = '';
657 $leave = false;
659 while ( !$leave && !$this->mSource->atEnd() &&
660 strlen($this->mBuffer) < $count ) {
661 $read = $this->mSource->readChunk();
663 if ( !strlen($read) ) {
664 $leave = true;
667 $this->mBuffer .= $read;
670 if ( strlen($this->mBuffer) ) {
671 $return = substr( $this->mBuffer, 0, $count );
672 $this->mBuffer = substr( $this->mBuffer, $count );
675 $this->mPosition += strlen($return);
677 return $return;
680 function stream_write( $data ) {
681 return false;
684 function stream_tell() {
685 return $this->mPosition;
688 function stream_eof() {
689 return $this->mSource->atEnd();
692 function url_stat() {
693 $result = array();
695 $result['dev'] = $result[0] = 0;
696 $result['ino'] = $result[1] = 0;
697 $result['mode'] = $result[2] = 0;
698 $result['nlink'] = $result[3] = 0;
699 $result['uid'] = $result[4] = 0;
700 $result['gid'] = $result[5] = 0;
701 $result['rdev'] = $result[6] = 0;
702 $result['size'] = $result[7] = 0;
703 $result['atime'] = $result[8] = 0;
704 $result['mtime'] = $result[9] = 0;
705 $result['ctime'] = $result[10] = 0;
706 $result['blksize'] = $result[11] = 0;
707 $result['blocks'] = $result[12] = 0;
709 return $result;
713 class XMLReader2 extends XMLReader {
714 function nodeContents() {
715 if( $this->isEmptyElement ) {
716 return "";
718 $buffer = "";
719 while( $this->read() ) {
720 switch( $this->nodeType ) {
721 case XmlReader::TEXT:
722 case XmlReader::SIGNIFICANT_WHITESPACE:
723 $buffer .= $this->value;
724 break;
725 case XmlReader::END_ELEMENT:
726 return $buffer;
729 return $this->close();