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