Follow up r54225. DumpRenderer::handleRevision needs to be public in order to be...
[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 XMLReader();
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 }
27
28 private function throwXmlError( $err ) {
29 $this->debug( "FAILURE: $err" );
30 wfDebug( "WikiImporter XML error: $err\n" );
31 }
32
33 private function debug( $data ) {
34 if( $this->mDebug ) {
35 wfDebug( "IMPORT: $data\n" );
36 }
37 }
38
39 private function warn( $data ) {
40 wfDebug( "IMPORT: $data\n" );
41 }
42
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" );
50 }
51 }
52
53 /**
54 * Set debug mode...
55 */
56 function setDebug( $debug ) {
57 $this->mDebug = $debug;
58 }
59
60 /**
61 * Sets the action to perform as each new page in the stream is reached.
62 * @param $callback callback
63 * @return callback
64 */
65 public function setPageCallback( $callback ) {
66 $previous = $this->mPageCallback;
67 $this->mPageCallback = $callback;
68 return $previous;
69 }
70
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.
76 *
77 * @param $callback callback
78 * @return callback
79 */
80 public function setPageOutCallback( $callback ) {
81 $previous = $this->mPageOutCallback;
82 $this->mPageOutCallback = $callback;
83 return $previous;
84 }
85
86 /**
87 * Sets the action to perform as each page revision is reached.
88 * @param $callback callback
89 * @return callback
90 */
91 public function setRevisionCallback( $callback ) {
92 $previous = $this->mRevisionCallback;
93 $this->mRevisionCallback = $callback;
94 return $previous;
95 }
96
97 /**
98 * Sets the action to perform as each file upload version is reached.
99 * @param $callback callback
100 * @return callback
101 */
102 public function setUploadCallback( $callback ) {
103 $previous = $this->mUploadCallback;
104 $this->mUploadCallback = $callback;
105 return $previous;
106 }
107
108 /**
109 * Sets the action to perform as each log item reached.
110 * @param $callback callback
111 * @return callback
112 */
113 public function setLogItemCallback( $callback ) {
114 $previous = $this->mLogItemCallback;
115 $this->mLogItemCallback = $callback;
116 return $previous;
117 }
118
119 /**
120 * Sets the action to perform when site info is encountered
121 * @param $callback callback
122 * @return callback
123 */
124 public function setSiteInfoCallback( $callback ) {
125 $previous = $this->mSiteInfoCallback;
126 $this->mSiteInfoCallback = $callback;
127 return $previous;
128 }
129
130 /**
131 * Set a target namespace to override the defaults
132 */
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;
142 }
143 }
144
145 /**
146 * Default per-revision callback, performs the import.
147 * @param $revision WikiRevision
148 */
149 public function importRevision( $revision ) {
150 $dbw = wfGetDB( DB_MASTER );
151 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
152 }
153
154 /**
155 * Default per-revision callback, performs the import.
156 * @param $rev WikiRevision
157 */
158 public function importLogItem( $rev ) {
159 $dbw = wfGetDB( DB_MASTER );
160 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
161 }
162
163 /**
164 * Dummy for now...
165 */
166 public function importUpload( $revision ) {
167 //$dbw = wfGetDB( DB_MASTER );
168 //return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
169 return false;
170 }
171
172 /**
173 * Alternate per-revision callback, for debugging.
174 * @param $revision WikiRevision
175 */
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>" );
182 }
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 );
187 }
188
189 /**
190 * Notify the callback function when a new <page> is reached.
191 * @param $title Title
192 */
193 function pageCallback( $title ) {
194 if( isset( $this->mPageCallback ) ) {
195 call_user_func( $this->mPageCallback, $title );
196 }
197 }
198
199 /**
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
205 */
206 private function pageOutCallback( $title, $origTitle, $revisionCount, $successCount ) {
207 if( isset( $this->mPageOutCallback ) ) {
208 call_user_func_array( $this->mPageOutCallback,
209 array( $title, $origTitle, $revisionCount, $successCount ) );
210 }
211 }
212
213 /**
214 * Notify the callback function of a revision
215 * @param $revision A WikiRevision object
216 */
217 private function revisionCallback( $revision ) {
218 if ( isset( $this->mRevisionCallback ) ) {
219 return call_user_func_array( $this->mRevisionCallback,
220 array( $revision, $this ) );
221 } else {
222 return false;
223 }
224 }
225
226 /**
227 * Notify the callback function of a new log item
228 * @param $revision A WikiRevision object
229 */
230 private function logItemCallback( $revision ) {
231 if ( isset( $this->mLogItemCallback ) ) {
232 return call_user_func_array( $this->mLogItemCallback,
233 array( $revision, $this ) );
234 } else {
235 return false;
236 }
237 }
238
239 /**
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
245 */
246 private function nodeContents() {
247 if( $this->reader->isEmptyElement ) {
248 return "";
249 }
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;
259 }
260 }
261 return $this->close();
262 }
263
264 # --------------
265
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",
289 );
290 $lookup = array();
291
292 foreach( $xmlReaderConstants as $name ) {
293 $lookup[constant("XmlReader::$name")] = $name;
294 }
295 }
296
297 print( var_dump(
298 $lookup[$this->reader->nodeType],
299 $this->reader->name,
300 $this->reader->value
301 )."\n\n" );
302 }
303
304 /**
305 * Primary entry point
306 */
307 public function doImport() {
308 $this->reader->read();
309
310 if ( $this->reader->name != 'mediawiki' ) {
311 throw new MWException( "Expected <mediawiki> tag, got ".
312 $this->reader->name );
313 }
314 $this->debug( "<mediawiki> tag is correct." );
315
316 $this->debug( "Starting primary dump processing loop." );
317
318 $keepReading = $this->reader->read();
319 $skip = false;
320 while ( $keepReading ) {
321 $tag = $this->reader->name;
322 $type = $this->reader->nodeType;
323
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" );
336
337 $skip = true;
338 }
339
340 if ($skip) {
341 $keepReading = $this->reader->next();
342 $skip = false;
343 $this->debug( "Skip" );
344 } else {
345 $keepReading = $this->reader->read();
346 }
347 }
348
349 return true;
350 }
351
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;
358 }
359 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
360 }
361
362 private function handleLogItem() {
363 $this->debug( "Enter log item handler." );
364 $logInfo = array();
365
366 // Fields that can just be stuffed in the pageInfo object
367 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
368 'logtitle', 'params' );
369
370 while ( $this->reader->read() ) {
371 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
372 $this->reader->name == 'logitem') {
373 break;
374 }
375
376 $tag = $this->reader->name;
377
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" );
387 }
388 }
389
390 $this->processLogItem( $logInfo );
391 }
392
393 private function processLogItem( $logInfo ) {
394 $revision = new WikiRevision;
395
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'] ) );
402
403 if ( isset( $logInfo['comment'] ) ) {
404 $revision->setComment( $logInfo['comment'] );
405 }
406
407 if ( isset( $logInfo['contributor']['ip'] ) ) {
408 $revision->setUserIP( $logInfo['contributor']['ip'] );
409 }
410 if ( isset( $logInfo['contributor']['username'] ) ) {
411 $revision->setUserName( $logInfo['contributor']['username'] );
412 }
413
414 return $this->logItemCallback( $revision );
415 }
416
417 private function handlePage() {
418 // Handle page data.
419 $this->debug( "Enter page handler." );
420 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
421
422 // Fields that can just be stuffed in the pageInfo object
423 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
424
425 $skip = false;
426 $badTitle = false;
427
428 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
429 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
430 $this->reader->name == 'page') {
431 break;
432 }
433
434 $tag = $this->reader->name;
435
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'] );
446
447 if ( !$title ) {
448 $badTitle = true;
449 $skip = true;
450 }
451
452 $this->pageCallback( $title );
453 list( $pageInfo['_title'], $origTitle ) = $title;
454 }
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;
462 }
463 }
464
465 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
466 $pageInfo['revisionCount'],
467 $pageInfo['successfulRevisionCount'] );
468 }
469
470 private function handleRevision( &$pageInfo ) {
471 $this->debug( "Enter revision handler" );
472 $revisionInfo = array();
473
474 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
475
476 $skip = false;
477
478 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
479 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
480 $this->reader->name == 'revision') {
481 break;
482 }
483
484 $tag = $this->reader->name;
485
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;
496 }
497 }
498
499 $pageInfo['revisionCount']++;
500 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
501 $pageInfo['successfulRevisionCount']++;
502 }
503 }
504
505 private function processRevision( $pageInfo, $revisionInfo ) {
506 $revision = new WikiRevision;
507
508 $revision->setID( $revisionInfo['id'] );
509 $revision->setText( $revisionInfo['text'] );
510 $revision->setTitle( $pageInfo['_title'] );
511 $revision->setTimestamp( $revisionInfo['timestamp'] );
512
513 if ( isset( $revisionInfo['comment'] ) ) {
514 $revision->setComment( $revisionInfo['comment'] );
515 }
516
517 if ( isset( $revisionInfo['minor'] ) )
518 $revision->setMinor( true );
519
520 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
521 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
522 }
523 if ( isset( $revisionInfo['contributor']['username'] ) ) {
524 $revision->setUserName( $revisionInfo['contributor']['username'] );
525 }
526
527 return $this->revisionCallback( $revision );
528 }
529
530 private function handleUpload( &$pageInfo ) {
531 $this->debug( "Enter upload handler" );
532 $uploadInfo = array();
533
534 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
535 'src', 'size' );
536
537 $skip = false;
538
539 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
540 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
541 $this->reader->name == 'upload') {
542 break;
543 }
544
545 $tag = $this->reader->name;
546
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;
557 }
558 }
559
560 return $this->processUpload( $pageInfo, $uploadInfo );
561 }
562
563 private function processUpload( $pageInfo, $uploadInfo ) {
564 $revision = new WikiRevision;
565
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'] );
574
575 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
576 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
577 }
578 if ( isset( $uploadInfo['contributor']['username'] ) ) {
579 $revision->setUserName( $revisionInfo['contributor']['username'] );
580 }
581
582 return $this->uploadCallback( $revision );
583 }
584
585 private function handleContributor() {
586 $fields = array( 'id', 'ip', 'username' );
587 $info = array();
588
589 while ( $this->reader->read() ) {
590 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
591 $this->reader->name == 'contributor') {
592 break;
593 }
594
595 $tag = $this->reader->name;
596
597 if ( in_array( $tag, $fields ) ) {
598 $info[$tag] = $this->nodeContents();
599 }
600 }
601
602 return $info;
603 }
604
605 private function processTitle( $text ) {
606 $workTitle = $text;
607 $origTitle = Title::newFromText( $workTitle );
608 $title = null;
609
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 );
615 }
616
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;
623 }
624
625 return array( $origTitle, $title );
626 }
627 }
628
629 /** This is a horrible hack used to keep source compatibility */
630 class UploadSourceAdapter {
631 static $sourceRegistrations = array();
632
633 private $mSource;
634 private $mBuffer;
635 private $mPosition;
636
637 static function registerSource( $source ) {
638 $id = wfGenerateToken();
639
640 self::$sourceRegistrations[$id] = $source;
641
642 return $id;
643 }
644
645 function stream_open( $path, $mode, $options, &$opened_path ) {
646 $url = parse_url($path);
647 $id = $url['host'];
648
649 if ( !isset( self::$sourceRegistrations[$id] ) ) {
650 return false;
651 }
652
653 $this->mSource = self::$sourceRegistrations[$id];
654
655 return true;
656 }
657
658 function stream_read( $count ) {
659 $return = '';
660 $leave = false;
661
662 while ( !$leave && !$this->mSource->atEnd() &&
663 strlen($this->mBuffer) < $count ) {
664 $read = $this->mSource->readChunk();
665
666 if ( !strlen($read) ) {
667 $leave = true;
668 }
669
670 $this->mBuffer .= $read;
671 }
672
673 if ( strlen($this->mBuffer) ) {
674 $return = substr( $this->mBuffer, 0, $count );
675 $this->mBuffer = substr( $this->mBuffer, $count );
676 }
677
678 $this->mPosition += strlen($return);
679
680 return $return;
681 }
682
683 function stream_write( $data ) {
684 return false;
685 }
686
687 function stream_tell() {
688 return $this->mPosition;
689 }
690
691 function stream_eof() {
692 return $this->mSource->atEnd();
693 }
694
695 function url_stat() {
696 $result = array();
697
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;
711
712 return $result;
713 }
714 }