Don't look for pipes in the root node.
[lhc/web/wiklou.git] / includes / ImportXMLReader.php
1 <?php
2 /**
3 * XML file reader for the page data importer
4 *
5 * @file
6 */
7
8 /**
9 * implements Special:Import
10 * @ingroup SpecialPage
11 */
12 class WikiImporter {
13 private $reader = null;
14 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
15 private $mSiteInfoCallback, $mTargetNamespace, $mPageOutCallback;
16 private $mDebug;
17
18 /**
19 * Creates an ImportXMLReader drawing from the source provided
20 */
21 function __construct( $source ) {
22 $this->reader = new XMLReader2();
23
24 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
25 $id = UploadSourceAdapter::registerSource( $source );
26 $this->reader->open( "uploadsource://$id" );
27
28 // Default callbacks
29 $this->setRevisionCallback( array( $this, "importRevision" ) );
30 $this->setUploadCallback( array( $this, 'importUpload' ) );
31 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
32 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
33 }
34
35 private function throwXmlError( $err ) {
36 $this->debug( "FAILURE: $err" );
37 wfDebug( "WikiImporter XML error: $err\n" );
38 }
39
40 private function debug( $data ) {
41 if( $this->mDebug ) {
42 wfDebug( "IMPORT: $data\n" );
43 }
44 }
45
46 private function warn( $data ) {
47 wfDebug( "IMPORT: $data\n" );
48 }
49
50 private function notice( $data ) {
51 global $wgCommandLineMode;
52 if( $wgCommandLineMode ) {
53 print "$data\n";
54 } else {
55 global $wgOut;
56 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
57 }
58 }
59
60 /**
61 * Set debug mode...
62 */
63 function setDebug( $debug ) {
64 $this->mDebug = $debug;
65 }
66
67 /**
68 * Sets the action to perform as each new page in the stream is reached.
69 * @param $callback callback
70 * @return callback
71 */
72 public function setPageCallback( $callback ) {
73 $previous = $this->mPageCallback;
74 $this->mPageCallback = $callback;
75 return $previous;
76 }
77
78 /**
79 * Sets the action to perform as each page in the stream is completed.
80 * Callback accepts the page title (as a Title object), a second object
81 * with the original title form (in case it's been overridden into a
82 * local namespace), and a count of revisions.
83 *
84 * @param $callback callback
85 * @return callback
86 */
87 public function setPageOutCallback( $callback ) {
88 $previous = $this->mPageOutCallback;
89 $this->mPageOutCallback = $callback;
90 return $previous;
91 }
92
93 /**
94 * Sets the action to perform as each page revision is reached.
95 * @param $callback callback
96 * @return callback
97 */
98 public function setRevisionCallback( $callback ) {
99 $previous = $this->mRevisionCallback;
100 $this->mRevisionCallback = $callback;
101 return $previous;
102 }
103
104 /**
105 * Sets the action to perform as each file upload version is reached.
106 * @param $callback callback
107 * @return callback
108 */
109 public function setUploadCallback( $callback ) {
110 $previous = $this->mUploadCallback;
111 $this->mUploadCallback = $callback;
112 return $previous;
113 }
114
115 /**
116 * Sets the action to perform as each log item reached.
117 * @param $callback callback
118 * @return callback
119 */
120 public function setLogItemCallback( $callback ) {
121 $previous = $this->mLogItemCallback;
122 $this->mLogItemCallback = $callback;
123 return $previous;
124 }
125
126 /**
127 * Sets the action to perform when site info is encountered
128 * @param $callback callback
129 * @return callback
130 */
131 public function setSiteInfoCallback( $callback ) {
132 $previous = $this->mSiteInfoCallback;
133 $this->mSiteInfoCallback = $callback;
134 return $previous;
135 }
136
137 /**
138 * Set a target namespace to override the defaults
139 */
140 public function setTargetNamespace( $namespace ) {
141 if( is_null( $namespace ) ) {
142 // Don't override namespaces
143 $this->mTargetNamespace = null;
144 } elseif( $namespace >= 0 ) {
145 // FIXME: Check for validity
146 $this->mTargetNamespace = intval( $namespace );
147 } else {
148 return false;
149 }
150 }
151
152 /**
153 * Default per-revision callback, performs the import.
154 * @param $revision WikiRevision
155 */
156 public function importRevision( $revision ) {
157 $dbw = wfGetDB( DB_MASTER );
158 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
159 }
160
161 /**
162 * Default per-revision callback, performs the import.
163 * @param $rev WikiRevision
164 */
165 public function importLogItem( $rev ) {
166 $dbw = wfGetDB( DB_MASTER );
167 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
168 }
169
170 /**
171 * Dummy for now...
172 */
173 public function importUpload( $revision ) {
174 //$dbw = wfGetDB( DB_MASTER );
175 //return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
176 return false;
177 }
178
179 /**
180 * Mostly for hook use
181 */
182 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
183 $args = func_get_args();
184 return wfRunHooks( 'AfterImportPage', $args );
185 }
186
187 /**
188 * Alternate per-revision callback, for debugging.
189 * @param $revision WikiRevision
190 */
191 public function debugRevisionHandler( &$revision ) {
192 $this->debug( "Got revision:" );
193 if( is_object( $revision->title ) ) {
194 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
195 } else {
196 $this->debug( "-- Title: <invalid>" );
197 }
198 $this->debug( "-- User: " . $revision->user_text );
199 $this->debug( "-- Timestamp: " . $revision->timestamp );
200 $this->debug( "-- Comment: " . $revision->comment );
201 $this->debug( "-- Text: " . $revision->text );
202 }
203
204 /**
205 * Notify the callback function when a new <page> is reached.
206 * @param $title Title
207 */
208 function pageCallback( $title ) {
209 if( isset( $this->mPageCallback ) ) {
210 call_user_func( $this->mPageCallback, $title );
211 }
212 }
213
214 /**
215 * Notify the callback function when a </page> is closed.
216 * @param $title Title
217 * @param $origTitle Title
218 * @param $revCount Integer
219 * @param $sucCount Int: number of revisions for which callback returned true
220 * @param $pageInfo Array: associative array of page information
221 */
222 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
223 if( isset( $this->mPageOutCallback ) ) {
224 $args = func_get_args();
225 call_user_func_array( $this->mPageOutCallback, $args );
226 }
227 }
228
229 /**
230 * Notify the callback function of a revision
231 * @param $revision A WikiRevision object
232 */
233 private function revisionCallback( $revision ) {
234 if ( isset( $this->mRevisionCallback ) ) {
235 return call_user_func_array( $this->mRevisionCallback,
236 array( $revision, $this ) );
237 } else {
238 return false;
239 }
240 }
241
242 /**
243 * Notify the callback function of a new log item
244 * @param $revision A WikiRevision object
245 */
246 private function logItemCallback( $revision ) {
247 if ( isset( $this->mLogItemCallback ) ) {
248 return call_user_func_array( $this->mLogItemCallback,
249 array( $revision, $this ) );
250 } else {
251 return false;
252 }
253 }
254
255 /**
256 * Shouldn't something like this be built-in to XMLReader?
257 * Fetches text contents of the current element, assuming
258 * no sub-elements or such scary things.
259 * @return string
260 * @access private
261 */
262 private function nodeContents() {
263 return $this->reader->nodeContents();
264 }
265
266 # --------------
267
268 /** Left in for debugging */
269 private function dumpElement() {
270 static $lookup = null;
271 if (!$lookup) {
272 $xmlReaderConstants = array(
273 "NONE",
274 "ELEMENT",
275 "ATTRIBUTE",
276 "TEXT",
277 "CDATA",
278 "ENTITY_REF",
279 "ENTITY",
280 "PI",
281 "COMMENT",
282 "DOC",
283 "DOC_TYPE",
284 "DOC_FRAGMENT",
285 "NOTATION",
286 "WHITESPACE",
287 "SIGNIFICANT_WHITESPACE",
288 "END_ELEMENT",
289 "END_ENTITY",
290 "XML_DECLARATION",
291 );
292 $lookup = array();
293
294 foreach( $xmlReaderConstants as $name ) {
295 $lookup[constant("XmlReader::$name")] = $name;
296 }
297 }
298
299 print( var_dump(
300 $lookup[$this->reader->nodeType],
301 $this->reader->name,
302 $this->reader->value
303 )."\n\n" );
304 }
305
306 /**
307 * Primary entry point
308 */
309 public function doImport() {
310 $this->reader->read();
311
312 if ( $this->reader->name != 'mediawiki' ) {
313 throw new MWException( "Expected <mediawiki> tag, got ".
314 $this->reader->name );
315 }
316 $this->debug( "<mediawiki> tag is correct." );
317
318 $this->debug( "Starting primary dump processing loop." );
319
320 $keepReading = $this->reader->read();
321 $skip = false;
322 while ( $keepReading ) {
323 $tag = $this->reader->name;
324 $type = $this->reader->nodeType;
325
326 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this->reader ) ) {
327 // Do nothing
328 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
329 break;
330 } elseif ( $tag == 'siteinfo' ) {
331 $this->handleSiteInfo();
332 } elseif ( $tag == 'page' ) {
333 $this->handlePage();
334 } elseif ( $tag == 'logitem' ) {
335 $this->handleLogItem();
336 } elseif ( $tag != '#text' ) {
337 $this->warn( "Unhandled top-level XML tag $tag" );
338
339 $skip = true;
340 }
341
342 if ($skip) {
343 $keepReading = $this->reader->next();
344 $skip = false;
345 $this->debug( "Skip" );
346 } else {
347 $keepReading = $this->reader->read();
348 }
349 }
350
351 return true;
352 }
353
354 private function handleSiteInfo() {
355 // Site info is useful, but not actually used for dump imports.
356 // Includes a quick short-circuit to save performance.
357 if ( ! $this->mSiteInfoCallback ) {
358 $this->reader->next();
359 return true;
360 }
361 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
362 }
363
364 private function handleLogItem() {
365 $this->debug( "Enter log item handler." );
366 $logInfo = array();
367
368 // Fields that can just be stuffed in the pageInfo object
369 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
370 'logtitle', 'params' );
371
372 while ( $this->reader->read() ) {
373 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
374 $this->reader->name == 'logitem') {
375 break;
376 }
377
378 $tag = $this->reader->name;
379
380 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
381 $this->reader, $logInfo ) ) {
382 // Do nothing
383 } elseif ( in_array( $tag, $normalFields ) ) {
384 $logInfo[$tag] = $this->nodeContents();
385 } elseif ( $tag == 'contributor' ) {
386 $logInfo['contributor'] = $this->handleContributor();
387 } elseif ( $tag != '#text' ) {
388 $this->warn( "Unhandled log-item XML tag $tag" );
389 }
390 }
391
392 $this->processLogItem( $logInfo );
393 }
394
395 private function processLogItem( $logInfo ) {
396 $revision = new WikiRevision;
397
398 $revision->setID( $logInfo['id'] );
399 $revision->setType( $logInfo['type'] );
400 $revision->setAction( $logInfo['action'] );
401 $revision->setTimestamp( $logInfo['timestamp'] );
402 $revision->setParams( $logInfo['params'] );
403 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
404
405 if ( isset( $logInfo['comment'] ) ) {
406 $revision->setComment( $logInfo['comment'] );
407 }
408
409 if ( isset( $logInfo['contributor']['ip'] ) ) {
410 $revision->setUserIP( $logInfo['contributor']['ip'] );
411 }
412 if ( isset( $logInfo['contributor']['username'] ) ) {
413 $revision->setUserName( $logInfo['contributor']['username'] );
414 }
415
416 return $this->logItemCallback( $revision );
417 }
418
419 private function handlePage() {
420 // Handle page data.
421 $this->debug( "Enter page handler." );
422 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
423
424 // Fields that can just be stuffed in the pageInfo object
425 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
426
427 $skip = false;
428 $badTitle = false;
429
430 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
431 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
432 $this->reader->name == 'page') {
433 break;
434 }
435
436 $tag = $this->reader->name;
437
438 if ( $badTitle ) {
439 // The title is invalid, bail out of this page
440 $skip = true;
441 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this->reader,
442 &$pageInfo ) ) ) {
443 // Do nothing
444 } elseif ( in_array( $tag, $normalFields ) ) {
445 $pageInfo[$tag] = $this->nodeContents();
446 if ( $tag == 'title' ) {
447 $title = $this->processTitle( $pageInfo['title'] );
448
449 if ( !$title ) {
450 $badTitle = true;
451 $skip = true;
452 }
453
454 $this->pageCallback( $title );
455 list( $pageInfo['_title'], $origTitle ) = $title;
456 }
457 } elseif ( $tag == 'revision' ) {
458 $this->handleRevision( $pageInfo );
459 } elseif ( $tag == 'upload' ) {
460 $this->handleUpload( $pageInfo );
461 } elseif ( $tag != '#text' ) {
462 $this->warn( "Unhandled page XML tag $tag" );
463 $skip = true;
464 }
465 }
466
467 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
468 $pageInfo['revisionCount'],
469 $pageInfo['successfulRevisionCount'],
470 $pageInfo );
471 }
472
473 private function handleRevision( &$pageInfo ) {
474 $this->debug( "Enter revision handler" );
475 $revisionInfo = array();
476
477 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
478
479 $skip = false;
480
481 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
482 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
483 $this->reader->name == 'revision') {
484 break;
485 }
486
487 $tag = $this->reader->name;
488
489 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this->reader,
490 $pageInfo, $revisionInfo ) ) {
491 // Do nothing
492 } elseif ( in_array( $tag, $normalFields ) ) {
493 $revisionInfo[$tag] = $this->nodeContents();
494 } elseif ( $tag == 'contributor' ) {
495 $revisionInfo['contributor'] = $this->handleContributor();
496 } elseif ( $tag != '#text' ) {
497 $this->warn( "Unhandled revision XML tag $tag" );
498 $skip = true;
499 }
500 }
501
502 $pageInfo['revisionCount']++;
503 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
504 $pageInfo['successfulRevisionCount']++;
505 }
506 }
507
508 private function processRevision( $pageInfo, $revisionInfo ) {
509 $revision = new WikiRevision;
510
511 $revision->setID( $revisionInfo['id'] );
512 $revision->setText( $revisionInfo['text'] );
513 $revision->setTitle( $pageInfo['_title'] );
514 $revision->setTimestamp( $revisionInfo['timestamp'] );
515
516 if ( isset( $revisionInfo['comment'] ) ) {
517 $revision->setComment( $revisionInfo['comment'] );
518 }
519
520 if ( isset( $revisionInfo['minor'] ) )
521 $revision->setMinor( true );
522
523 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
524 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
525 }
526 if ( isset( $revisionInfo['contributor']['username'] ) ) {
527 $revision->setUserName( $revisionInfo['contributor']['username'] );
528 }
529
530 return $this->revisionCallback( $revision );
531 }
532
533 private function handleUpload( &$pageInfo ) {
534 $this->debug( "Enter upload handler" );
535 $uploadInfo = array();
536
537 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
538 'src', 'size' );
539
540 $skip = false;
541
542 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
543 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
544 $this->reader->name == 'upload') {
545 break;
546 }
547
548 $tag = $this->reader->name;
549
550 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this->reader,
551 $pageInfo ) ) {
552 // Do nothing
553 } elseif ( in_array( $tag, $normalFields ) ) {
554 $uploadInfo[$tag] = $this->nodeContents();
555 } elseif ( $tag == 'contributor' ) {
556 $uploadInfo['contributor'] = $this->handleContributor();
557 } elseif ( $tag != '#text' ) {
558 $this->warn( "Unhandled upload XML tag $tag" );
559 $skip = true;
560 }
561 }
562
563 return $this->processUpload( $pageInfo, $uploadInfo );
564 }
565
566 private function processUpload( $pageInfo, $uploadInfo ) {
567 $revision = new WikiRevision;
568
569 $revision->setTitle( $pageInfo['_title'] );
570 $revision->setID( $uploadInfo['id'] );
571 $revision->setTimestamp( $uploadInfo['timestamp'] );
572 $revision->setText( $uploadInfo['text'] );
573 $revision->setFilename( $uploadInfo['filename'] );
574 $revision->setSrc( $uploadInfo['src'] );
575 $revision->setSize( intval( $uploadInfo['size'] ) );
576 $revision->setComment( $uploadInfo['comment'] );
577
578 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
579 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
580 }
581 if ( isset( $uploadInfo['contributor']['username'] ) ) {
582 $revision->setUserName( $uploadInfo['contributor']['username'] );
583 }
584
585 return $this->uploadCallback( $revision );
586 }
587
588 private function handleContributor() {
589 $fields = array( 'id', 'ip', 'username' );
590 $info = array();
591
592 while ( $this->reader->read() ) {
593 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
594 $this->reader->name == 'contributor') {
595 break;
596 }
597
598 $tag = $this->reader->name;
599
600 if ( in_array( $tag, $fields ) ) {
601 $info[$tag] = $this->nodeContents();
602 }
603 }
604
605 return $info;
606 }
607
608 private function processTitle( $text ) {
609 $workTitle = $text;
610 $origTitle = Title::newFromText( $workTitle );
611
612 if( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
613 $title = Title::makeTitle( $this->mTargetNamespace,
614 $origTitle->getDBkey() );
615 } else {
616 $title = Title::newFromText( $workTitle );
617 }
618
619 if( is_null( $title ) ) {
620 // Invalid page title? Ignore the page
621 $this->notice( "Skipping invalid page title '$workTitle'" );
622 return false;
623 } elseif( $title->getInterwiki() != '' ) {
624 $this->notice( "Skipping interwiki page title '$workTitle'" );
625 return false;
626 }
627
628 return array( $origTitle, $title );
629 }
630 }
631
632 /** This is a horrible hack used to keep source compatibility */
633 class UploadSourceAdapter {
634 static $sourceRegistrations = array();
635
636 private $mSource;
637 private $mBuffer;
638 private $mPosition;
639
640 static function registerSource( $source ) {
641 $id = wfGenerateToken();
642
643 self::$sourceRegistrations[$id] = $source;
644
645 return $id;
646 }
647
648 function stream_open( $path, $mode, $options, &$opened_path ) {
649 $url = parse_url($path);
650 $id = $url['host'];
651
652 if ( !isset( self::$sourceRegistrations[$id] ) ) {
653 return false;
654 }
655
656 $this->mSource = self::$sourceRegistrations[$id];
657
658 return true;
659 }
660
661 function stream_read( $count ) {
662 $return = '';
663 $leave = false;
664
665 while ( !$leave && !$this->mSource->atEnd() &&
666 strlen($this->mBuffer) < $count ) {
667 $read = $this->mSource->readChunk();
668
669 if ( !strlen($read) ) {
670 $leave = true;
671 }
672
673 $this->mBuffer .= $read;
674 }
675
676 if ( strlen($this->mBuffer) ) {
677 $return = substr( $this->mBuffer, 0, $count );
678 $this->mBuffer = substr( $this->mBuffer, $count );
679 }
680
681 $this->mPosition += strlen($return);
682
683 return $return;
684 }
685
686 function stream_write( $data ) {
687 return false;
688 }
689
690 function stream_tell() {
691 return $this->mPosition;
692 }
693
694 function stream_eof() {
695 return $this->mSource->atEnd();
696 }
697
698 function url_stat() {
699 $result = array();
700
701 $result['dev'] = $result[0] = 0;
702 $result['ino'] = $result[1] = 0;
703 $result['mode'] = $result[2] = 0;
704 $result['nlink'] = $result[3] = 0;
705 $result['uid'] = $result[4] = 0;
706 $result['gid'] = $result[5] = 0;
707 $result['rdev'] = $result[6] = 0;
708 $result['size'] = $result[7] = 0;
709 $result['atime'] = $result[8] = 0;
710 $result['mtime'] = $result[9] = 0;
711 $result['ctime'] = $result[10] = 0;
712 $result['blksize'] = $result[11] = 0;
713 $result['blocks'] = $result[12] = 0;
714
715 return $result;
716 }
717 }
718
719 class XMLReader2 extends XMLReader {
720 function nodeContents() {
721 if( $this->isEmptyElement ) {
722 return "";
723 }
724 $buffer = "";
725 while( $this->read() ) {
726 switch( $this->nodeType ) {
727 case XmlReader::TEXT:
728 case XmlReader::SIGNIFICANT_WHITESPACE:
729 $buffer .= $this->value;
730 break;
731 case XmlReader::END_ELEMENT:
732 return $buffer;
733 }
734 }
735 return $this->close();
736 }
737 }