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