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