"<p id="userloginlink"><p>Don't have an account" is illegal xhtml
[mediawiki.git] / includes / ImportXMLReader.php
blobd445a28365f00df24cacd99da57c670af3a497c1
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 XMLReader();
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' ) );
28 private function throwXmlError( $err ) {
29 $this->debug( "FAILURE: $err" );
30 wfDebug( "WikiImporter XML error: $err\n" );
33 private function debug( $data ) {
34 if( $this->mDebug ) {
35 wfDebug( "IMPORT: $data\n" );
39 private function warn( $data ) {
40 wfDebug( "IMPORT: $data\n" );
43 private function notice( $data ) {
44 global $wgCommandLineMode;
45 if( $wgCommandLineMode ) {
46 print "$data\n";
47 } else {
48 global $wgOut;
49 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
53 /**
54 * Set debug mode...
56 function setDebug( $debug ) {
57 $this->mDebug = $debug;
60 /**
61 * Sets the action to perform as each new page in the stream is reached.
62 * @param $callback callback
63 * @return callback
65 public function setPageCallback( $callback ) {
66 $previous = $this->mPageCallback;
67 $this->mPageCallback = $callback;
68 return $previous;
71 /**
72 * Sets the action to perform as each page in the stream is completed.
73 * Callback accepts the page title (as a Title object), a second object
74 * with the original title form (in case it's been overridden into a
75 * local namespace), and a count of revisions.
77 * @param $callback callback
78 * @return callback
80 public function setPageOutCallback( $callback ) {
81 $previous = $this->mPageOutCallback;
82 $this->mPageOutCallback = $callback;
83 return $previous;
86 /**
87 * Sets the action to perform as each page revision is reached.
88 * @param $callback callback
89 * @return callback
91 public function setRevisionCallback( $callback ) {
92 $previous = $this->mRevisionCallback;
93 $this->mRevisionCallback = $callback;
94 return $previous;
97 /**
98 * Sets the action to perform as each file upload version is reached.
99 * @param $callback callback
100 * @return callback
102 public function setUploadCallback( $callback ) {
103 $previous = $this->mUploadCallback;
104 $this->mUploadCallback = $callback;
105 return $previous;
109 * Sets the action to perform as each log item reached.
110 * @param $callback callback
111 * @return callback
113 public function setLogItemCallback( $callback ) {
114 $previous = $this->mLogItemCallback;
115 $this->mLogItemCallback = $callback;
116 return $previous;
120 * Sets the action to perform when site info is encountered
121 * @param $callback callback
122 * @return callback
124 public function setSiteInfoCallback( $callback ) {
125 $previous = $this->mSiteInfoCallback;
126 $this->mSiteInfoCallback = $callback;
127 return $previous;
131 * Set a target namespace to override the defaults
133 public function setTargetNamespace( $namespace ) {
134 if( is_null( $namespace ) ) {
135 // Don't override namespaces
136 $this->mTargetNamespace = null;
137 } elseif( $namespace >= 0 ) {
138 // FIXME: Check for validity
139 $this->mTargetNamespace = intval( $namespace );
140 } else {
141 return false;
146 * Default per-revision callback, performs the import.
147 * @param $revision WikiRevision
149 public function importRevision( $revision ) {
150 $dbw = wfGetDB( DB_MASTER );
151 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
155 * Default per-revision callback, performs the import.
156 * @param $rev WikiRevision
158 public function importLogItem( $rev ) {
159 $dbw = wfGetDB( DB_MASTER );
160 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
164 * Dummy for now...
166 public function importUpload( $revision ) {
167 //$dbw = wfGetDB( DB_MASTER );
168 //return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
169 return false;
173 * Alternate per-revision callback, for debugging.
174 * @param $revision WikiRevision
176 public function debugRevisionHandler( &$revision ) {
177 $this->debug( "Got revision:" );
178 if( is_object( $revision->title ) ) {
179 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
180 } else {
181 $this->debug( "-- Title: <invalid>" );
183 $this->debug( "-- User: " . $revision->user_text );
184 $this->debug( "-- Timestamp: " . $revision->timestamp );
185 $this->debug( "-- Comment: " . $revision->comment );
186 $this->debug( "-- Text: " . $revision->text );
190 * Notify the callback function when a new <page> is reached.
191 * @param $title Title
193 function pageCallback( $title ) {
194 if( is_callable( $this->mPageCallback ) ) {
195 call_user_func( $this->mPageCallback, $title );
200 * Notify the callback function when a </page> is closed.
201 * @param $title Title
202 * @param $origTitle Title
203 * @param $revisionCount int
204 * @param $successCount Int: number of revisions for which callback returned true
206 private function pageOutCallback( $title, $origTitle, $revisionCount, $successCount ) {
207 if( is_callable( $this->mPageOutCallback ) ) {
208 call_user_func_array( $this->mPageOutCallback,
209 array( $title, $origTitle, $revisionCount, $successCount ) );
214 * Notify the callback function of a revision
215 * @param $revision A WikiRevision object
217 private function revisionCallback( $revision ) {
218 if ( is_callable( $this->mRevisionCallback ) ) {
219 return call_user_func_array( $this->mRevisionCallback,
220 array( $revision, $this ) );
221 } else {
222 return false;
227 * Notify the callback function of a new log item
228 * @param $revision A WikiRevision object
230 private function logItemCallback( $revision ) {
231 if ( is_callable( $this->mLogItemCallback ) ) {
232 return call_user_func_array( $this->mLogItemCallback,
233 array( $revision, $this ) );
234 } else {
235 return false;
240 * Shouldn't something like this be built-in to XMLReader?
241 * Fetches text contents of the current element, assuming
242 * no sub-elements or such scary things.
243 * @return string
244 * @access private
246 private function nodeContents() {
247 if( $this->reader->isEmptyElement ) {
248 return "";
250 $buffer = "";
251 while( $this->reader->read() ) {
252 switch( $this->reader->nodeType ) {
253 case XmlReader::TEXT:
254 case XmlReader::SIGNIFICANT_WHITESPACE:
255 $buffer .= $this->reader->value;
256 break;
257 case XmlReader::END_ELEMENT:
258 return $buffer;
261 return $this->close();
264 # --------------
266 /** Left in for debugging */
267 private function dumpElement() {
268 static $lookup = null;
269 if (!$lookup) {
270 $xmlReaderConstants = array(
271 "NONE",
272 "ELEMENT",
273 "ATTRIBUTE",
274 "TEXT",
275 "CDATA",
276 "ENTITY_REF",
277 "ENTITY",
278 "PI",
279 "COMMENT",
280 "DOC",
281 "DOC_TYPE",
282 "DOC_FRAGMENT",
283 "NOTATION",
284 "WHITESPACE",
285 "SIGNIFICANT_WHITESPACE",
286 "END_ELEMENT",
287 "END_ENTITY",
288 "XML_DECLARATION",
290 $lookup = array();
292 foreach( $xmlReaderConstants as $name ) {
293 $lookup[constant("XmlReader::$name")] = $name;
297 print( var_dump(
298 $lookup[$this->reader->nodeType],
299 $this->reader->name,
300 $this->reader->value
301 )."\n\n" );
305 * Primary entry point
307 public function doImport() {
308 $this->reader->read();
310 if ( $this->reader->name != 'mediawiki' ) {
311 throw new MWException( "Expected <mediawiki> tag, got ".
312 $this->reader->name );
314 $this->debug( "<mediawiki> tag is correct." );
316 $this->debug( "Starting primary dump processing loop." );
318 $keepReading = $this->reader->read();
319 $skip = false;
320 while ( $keepReading ) {
321 $tag = $this->reader->name;
322 $type = $this->reader->nodeType;
324 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this->reader ) ) {
325 // Do nothing
326 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
327 break;
328 } elseif ( $tag == 'siteinfo' ) {
329 $this->handleSiteInfo();
330 } elseif ( $tag == 'page' ) {
331 $this->handlePage();
332 } elseif ( $tag == 'logitem' ) {
333 $this->handleLogItem();
334 } elseif ( $tag != '#text' ) {
335 $this->warn( "Unhandled top-level XML tag $tag" );
337 $skip = true;
340 if ($skip) {
341 $keepReading = $this->reader->next();
342 $skip = false;
343 $this->debug( "Skip" );
344 } else {
345 $keepReading = $this->reader->read();
349 return true;
352 private function handleSiteInfo() {
353 // Site info is useful, but not actually used for dump imports.
354 // Includes a quick short-circuit to save performance.
355 if ( ! $this->mSiteInfoCallback ) {
356 $this->reader->next();
357 return true;
359 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
362 private function handleLogItem() {
363 $this->debug( "Enter log item handler." );
364 $logInfo = array();
366 // Fields that can just be stuffed in the pageInfo object
367 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
368 'logtitle', 'params' );
370 while ( $this->reader->read() ) {
371 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
372 $this->reader->name == 'logitem') {
373 break;
376 $tag = $this->reader->name;
378 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
379 $this->reader, $logInfo ) ) {
380 // Do nothing
381 } if ( in_array( $tag, $normalFields ) ) {
382 $logInfo[$tag] = $this->nodeContents();
383 } elseif ( $tag == 'contributor' ) {
384 $logInfo['contributor'] = $this->handleContributor();
385 } elseif ( $tag != '#text' ) {
386 $this->warn( "Unhandled log-item XML tag $tag" );
390 $this->processLogItem( $logInfo );
393 private function processLogItem( $logInfo ) {
394 $revision = new WikiRevision;
396 $revision->setID( $logInfo['id'] );
397 $revision->setType( $logInfo['type'] );
398 $revision->setAction( $logInfo['action'] );
399 $revision->setTimestamp( $logInfo['timestamp'] );
400 $revision->setParams( $logInfo['params'] );
401 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
403 if ( isset( $logInfo['comment'] ) ) {
404 $revision->setComment( $logInfo['comment'] );
407 if ( isset( $logInfo['contributor']['ip'] ) ) {
408 $revision->setUserIP( $logInfo['contributor']['ip'] );
410 if ( isset( $logInfo['contributor']['username'] ) ) {
411 $revision->setUserName( $logInfo['contributor']['username'] );
414 return $this->logItemCallback( $revision );
417 private function handlePage() {
418 // Handle page data.
419 $this->debug( "Enter page handler." );
420 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
422 // Fields that can just be stuffed in the pageInfo object
423 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
425 $skip = false;
426 $badTitle = false;
428 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
429 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
430 $this->reader->name == 'page') {
431 break;
434 $tag = $this->reader->name;
436 if ( $badTitle ) {
437 // The title is invalid, bail out of this page
438 $skip = true;
439 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', $this->reader,
440 $pageInfo ) ) {
441 // Do nothing
442 } if ( in_array( $tag, $normalFields ) ) {
443 $pageInfo[$tag] = $this->nodeContents();
444 if ( $tag == 'title' ) {
445 $title = $this->processTitle( $pageInfo['title'] );
447 if ( !$title ) {
448 $badTitle = true;
449 $skip = true;
452 $this->pageCallback( $title );
453 list( $pageInfo['_title'], $origTitle ) = $title;
455 } elseif ( $tag == 'revision' ) {
456 $this->handleRevision( $pageInfo );
457 } elseif ( $tag == 'upload' ) {
458 $this->handleUpload( $pageInfo );
459 } elseif ( $tag != '#text' ) {
460 $this->warn( "Unhandled page XML tag $tag" );
461 $skip = true;
465 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
466 $pageInfo['revisionCount'],
467 $pageInfo['successfulRevisionCount'] );
470 private function handleRevision( &$pageInfo ) {
471 $this->debug( "Enter revision handler" );
472 $revisionInfo = array();
474 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
476 $skip = false;
478 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
479 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
480 $this->reader->name == 'revision') {
481 break;
484 $tag = $this->reader->name;
486 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this->reader,
487 $pageInfo, $revisionInfo ) ) {
488 // Do nothing
489 } if ( in_array( $tag, $normalFields ) ) {
490 $revisionInfo[$tag] = $this->nodeContents();
491 } elseif ( $tag == 'contributor' ) {
492 $revisionInfo['contributor'] = $this->handleContributor();
493 } elseif ( $tag != '#text' ) {
494 $this->warn( "Unhandled revision XML tag $tag" );
495 $skip = true;
499 $pageInfo['revisionCount']++;
500 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
501 $pageInfo['successfulRevisionCount']++;
505 private function processRevision( $pageInfo, $revisionInfo ) {
506 $revision = new WikiRevision;
508 $revision->setID( $revisionInfo['id'] );
509 $revision->setText( $revisionInfo['text'] );
510 $revision->setTitle( $pageInfo['_title'] );
511 $revision->setTimestamp( $revisionInfo['timestamp'] );
513 if ( isset( $revisionInfo['comment'] ) ) {
514 $revision->setComment( $revisionInfo['comment'] );
517 if ( isset( $revisionInfo['minor'] ) )
518 $revision->setMinor( true );
520 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
521 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
523 if ( isset( $revisionInfo['contributor']['username'] ) ) {
524 $revision->setUserName( $revisionInfo['contributor']['username'] );
527 return $this->revisionCallback( $revision );
530 private function handleUpload( &$pageInfo ) {
531 $this->debug( "Enter upload handler" );
532 $uploadInfo = array();
534 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
535 'src', 'size' );
537 $skip = false;
539 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
540 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
541 $this->reader->name == 'upload') {
542 break;
545 $tag = $this->reader->name;
547 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this->reader,
548 $pageInfo, $revisionInfo ) ) {
549 // Do nothing
550 } if ( in_array( $tag, $normalFields ) ) {
551 $uploadInfo[$tag] = $this->nodeContents();
552 } elseif ( $tag == 'contributor' ) {
553 $uploadInfo['contributor'] = $this->handleContributor();
554 } elseif ( $tag != '#text' ) {
555 $this->warn( "Unhandled upload XML tag $tag" );
556 $skip = true;
560 return $this->processUpload( $pageInfo, $uploadInfo );
563 private function processUpload( $pageInfo, $uploadInfo ) {
564 $revision = new WikiRevision;
566 $revision->setTitle( $pageInfo['_title'] );
567 $revision->setID( $uploadInfo['id'] );
568 $revision->setTimestamp( $uploadInfo['timestamp'] );
569 $revision->setText( $uploadInfo['text'] );
570 $revision->setFilename( $uploadInfo['filename'] );
571 $revision->setSrc( $uploadInfo['src'] );
572 $revision->setSize( intval( $uploadInfo['size'] ) );
573 $revision->setComment( $uploadInfo['comment'] );
575 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
576 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
578 if ( isset( $uploadInfo['contributor']['username'] ) ) {
579 $revision->setUserName( $revisionInfo['contributor']['username'] );
582 return $this->uploadCallback( $revision );
585 private function handleContributor() {
586 $fields = array( 'id', 'ip', 'username' );
587 $info = array();
589 while ( $this->reader->read() ) {
590 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
591 $this->reader->name == 'contributor') {
592 break;
595 $tag = $this->reader->name;
597 if ( in_array( $tag, $fields ) ) {
598 $info[$tag] = $this->nodeContents();
602 return $info;
605 private function processTitle( $text ) {
606 $workTitle = $text;
607 $origTitle = Title::newFromText( $workTitle );
608 $title = null;
610 if( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
611 $title = Title::makeTitle( $this->mTargetNamespace,
612 $origTitle->getDBkey() );
613 } else {
614 $title = Title::newFromText( $workTitle );
617 if( is_null( $title ) ) {
618 // Invalid page title? Ignore the page
619 $this->notice( "Skipping invalid page title '$workTitle'" );
620 } elseif( $title->getInterwiki() != '' ) {
621 $this->notice( "Skipping interwiki page title '$workTitle'" );
622 $title = null;
625 return array( $origTitle, $title );
629 /** This is a horrible hack used to keep source compatibility */
630 class UploadSourceAdapter {
631 static $sourceRegistrations = array();
633 private $mSource;
634 private $mBuffer;
635 private $mPosition;
637 static function registerSource( $source ) {
638 $id = wfGenerateToken();
640 self::$sourceRegistrations[$id] = $source;
642 return $id;
645 function stream_open( $path, $mode, $options, &$opened_path ) {
646 $url = parse_url($path);
647 $id = $url['host'];
649 if ( !isset( self::$sourceRegistrations[$id] ) ) {
650 return false;
653 $this->mSource = self::$sourceRegistrations[$id];
655 return true;
658 function stream_read( $count ) {
659 $return = '';
660 $leave = false;
662 while ( !$leave && !$this->mSource->atEnd() &&
663 count($this->mBuffer) < $count ) {
664 $read = $this->mSource->readChunk();
666 if ( !count($read) ) {
667 $leave = true;
670 $this->mBuffer .= $read;
673 if ( count($this->mBuffer) ) {
674 $return = substr( $this->mBuffer, 0, $count );
675 $this->mBuffer = substr( $this->mBuffer, $count );
678 $this->mPosition += strlen($return);
680 return $return;
683 function stream_write( $data ) {
684 return false;
687 function stream_tell() {
688 return $this->mPosition;
691 function stream_eof() {
692 return $this->mSource->atEnd();
695 function url_stat() {
696 $result = array();
698 $result['dev'] = $result[0] = 0;
699 $result['ino'] = $result[1] = 0;
700 $result['mode'] = $result[2] = 0;
701 $result['nlink'] = $result[3] = 0;
702 $result['uid'] = $result[4] = 0;
703 $result['gid'] = $result[5] = 0;
704 $result['rdev'] = $result[6] = 0;
705 $result['size'] = $result[7] = 0;
706 $result['atime'] = $result[8] = 0;
707 $result['mtime'] = $result[9] = 0;
708 $result['ctime'] = $result[10] = 0;
709 $result['blksize'] = $result[11] = 0;
710 $result['blocks'] = $result[12] = 0;
712 return $result;