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