Fixing some of the "@return true" or "@return false", need to be "@return bool" and...
[lhc/web/wiklou.git] / includes / Import.php
1 <?php
2 /**
3 * MediaWiki page data importer
4 *
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup SpecialPage
25 */
26
27 /**
28 * XML file reader for the page data importer
29 *
30 * implements Special:Import
31 * @ingroup SpecialPage
32 */
33 class WikiImporter {
34 private $reader = null;
35 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
36 private $mSiteInfoCallback, $mTargetNamespace, $mPageOutCallback;
37 private $mNoticeCallback, $mDebug;
38 private $mImportUploads, $mImageBasePath;
39 private $mNoUpdates = false;
40
41 /**
42 * Creates an ImportXMLReader drawing from the source provided
43 * @param $source
44 */
45 function __construct( $source ) {
46 $this->reader = new XMLReader();
47
48 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
49 $id = UploadSourceAdapter::registerSource( $source );
50 if (defined( 'LIBXML_PARSEHUGE' ) ) {
51 $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
52 } else {
53 $this->reader->open( "uploadsource://$id" );
54 }
55
56 // Default callbacks
57 $this->setRevisionCallback( array( $this, "importRevision" ) );
58 $this->setUploadCallback( array( $this, 'importUpload' ) );
59 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
60 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
61 }
62
63 private function throwXmlError( $err ) {
64 $this->debug( "FAILURE: $err" );
65 wfDebug( "WikiImporter XML error: $err\n" );
66 }
67
68 private function debug( $data ) {
69 if( $this->mDebug ) {
70 wfDebug( "IMPORT: $data\n" );
71 }
72 }
73
74 private function warn( $data ) {
75 wfDebug( "IMPORT: $data\n" );
76 }
77
78 private function notice( $msg /*, $param, ...*/ ) {
79 $params = func_get_args();
80 array_shift( $params );
81
82 if ( is_callable( $this->mNoticeCallback ) ) {
83 call_user_func( $this->mNoticeCallback, $msg, $params );
84 } else { # No ImportReporter -> CLI
85 echo wfMessage( $msg, $params )->text() . "\n";
86 }
87 }
88
89 /**
90 * Set debug mode...
91 * @param $debug bool
92 */
93 function setDebug( $debug ) {
94 $this->mDebug = $debug;
95 }
96
97 /**
98 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
99 * @param $noupdates bool
100 */
101 function setNoUpdates( $noupdates ) {
102 $this->mNoUpdates = $noupdates;
103 }
104
105 /**
106 * Set a callback that displays notice messages
107 *
108 * @param $callback callback
109 * @return callback
110 */
111 public function setNoticeCallback( $callback ) {
112 return wfSetVar( $this->mNoticeCallback, $callback );
113 }
114
115 /**
116 * Sets the action to perform as each new page in the stream is reached.
117 * @param $callback callback
118 * @return callback
119 */
120 public function setPageCallback( $callback ) {
121 $previous = $this->mPageCallback;
122 $this->mPageCallback = $callback;
123 return $previous;
124 }
125
126 /**
127 * Sets the action to perform as each page in the stream is completed.
128 * Callback accepts the page title (as a Title object), a second object
129 * with the original title form (in case it's been overridden into a
130 * local namespace), and a count of revisions.
131 *
132 * @param $callback callback
133 * @return callback
134 */
135 public function setPageOutCallback( $callback ) {
136 $previous = $this->mPageOutCallback;
137 $this->mPageOutCallback = $callback;
138 return $previous;
139 }
140
141 /**
142 * Sets the action to perform as each page revision is reached.
143 * @param $callback callback
144 * @return callback
145 */
146 public function setRevisionCallback( $callback ) {
147 $previous = $this->mRevisionCallback;
148 $this->mRevisionCallback = $callback;
149 return $previous;
150 }
151
152 /**
153 * Sets the action to perform as each file upload version is reached.
154 * @param $callback callback
155 * @return callback
156 */
157 public function setUploadCallback( $callback ) {
158 $previous = $this->mUploadCallback;
159 $this->mUploadCallback = $callback;
160 return $previous;
161 }
162
163 /**
164 * Sets the action to perform as each log item reached.
165 * @param $callback callback
166 * @return callback
167 */
168 public function setLogItemCallback( $callback ) {
169 $previous = $this->mLogItemCallback;
170 $this->mLogItemCallback = $callback;
171 return $previous;
172 }
173
174 /**
175 * Sets the action to perform when site info is encountered
176 * @param $callback callback
177 * @return callback
178 */
179 public function setSiteInfoCallback( $callback ) {
180 $previous = $this->mSiteInfoCallback;
181 $this->mSiteInfoCallback = $callback;
182 return $previous;
183 }
184
185 /**
186 * Set a target namespace to override the defaults
187 * @param $namespace
188 * @return bool
189 */
190 public function setTargetNamespace( $namespace ) {
191 if( is_null( $namespace ) ) {
192 // Don't override namespaces
193 $this->mTargetNamespace = null;
194 } elseif( $namespace >= 0 ) {
195 // @todo FIXME: Check for validity
196 $this->mTargetNamespace = intval( $namespace );
197 } else {
198 return false;
199 }
200 }
201
202 /**
203 * @param $dir
204 */
205 public function setImageBasePath( $dir ) {
206 $this->mImageBasePath = $dir;
207 }
208
209 /**
210 * @param $import
211 */
212 public function setImportUploads( $import ) {
213 $this->mImportUploads = $import;
214 }
215
216 /**
217 * Default per-revision callback, performs the import.
218 * @param $revision WikiRevision
219 * @return bool
220 */
221 public function importRevision( $revision ) {
222 $dbw = wfGetDB( DB_MASTER );
223 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
224 }
225
226 /**
227 * Default per-revision callback, performs the import.
228 * @param $rev WikiRevision
229 * @return bool
230 */
231 public function importLogItem( $rev ) {
232 $dbw = wfGetDB( DB_MASTER );
233 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
234 }
235
236 /**
237 * Dummy for now...
238 * @param $revision
239 * @return bool
240 */
241 public function importUpload( $revision ) {
242 $dbw = wfGetDB( DB_MASTER );
243 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
244 }
245
246 /**
247 * Mostly for hook use
248 * @param $title
249 * @param $origTitle
250 * @param $revCount
251 * @param $sRevCount
252 * @param $pageInfo
253 * @return
254 */
255 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
256 $args = func_get_args();
257 return wfRunHooks( 'AfterImportPage', $args );
258 }
259
260 /**
261 * Alternate per-revision callback, for debugging.
262 * @param $revision WikiRevision
263 */
264 public function debugRevisionHandler( &$revision ) {
265 $this->debug( "Got revision:" );
266 if( is_object( $revision->title ) ) {
267 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
268 } else {
269 $this->debug( "-- Title: <invalid>" );
270 }
271 $this->debug( "-- User: " . $revision->user_text );
272 $this->debug( "-- Timestamp: " . $revision->timestamp );
273 $this->debug( "-- Comment: " . $revision->comment );
274 $this->debug( "-- Text: " . $revision->text );
275 }
276
277 /**
278 * Notify the callback function when a new <page> is reached.
279 * @param $title Title
280 */
281 function pageCallback( $title ) {
282 if( isset( $this->mPageCallback ) ) {
283 call_user_func( $this->mPageCallback, $title );
284 }
285 }
286
287 /**
288 * Notify the callback function when a </page> is closed.
289 * @param $title Title
290 * @param $origTitle Title
291 * @param $revCount Integer
292 * @param $sucCount Int: number of revisions for which callback returned true
293 * @param $pageInfo Array: associative array of page information
294 */
295 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
296 if( isset( $this->mPageOutCallback ) ) {
297 $args = func_get_args();
298 call_user_func_array( $this->mPageOutCallback, $args );
299 }
300 }
301
302 /**
303 * Notify the callback function of a revision
304 * @param $revision |WikiRevision object
305 * @return bool|mixed
306 */
307 private function revisionCallback( $revision ) {
308 if ( isset( $this->mRevisionCallback ) ) {
309 return call_user_func_array( $this->mRevisionCallback,
310 array( $revision, $this ) );
311 } else {
312 return false;
313 }
314 }
315
316 /**
317 * Notify the callback function of a new log item
318 * @param $revision WikiRevision object
319 * @return bool|mixed
320 */
321 private function logItemCallback( $revision ) {
322 if ( isset( $this->mLogItemCallback ) ) {
323 return call_user_func_array( $this->mLogItemCallback,
324 array( $revision, $this ) );
325 } else {
326 return false;
327 }
328 }
329
330 /**
331 * Shouldn't something like this be built-in to XMLReader?
332 * Fetches text contents of the current element, assuming
333 * no sub-elements or such scary things.
334 * @return string
335 * @access private
336 */
337 private function nodeContents() {
338 if( $this->reader->isEmptyElement ) {
339 return "";
340 }
341 $buffer = "";
342 while( $this->reader->read() ) {
343 switch( $this->reader->nodeType ) {
344 case XmlReader::TEXT:
345 case XmlReader::SIGNIFICANT_WHITESPACE:
346 $buffer .= $this->reader->value;
347 break;
348 case XmlReader::END_ELEMENT:
349 return $buffer;
350 }
351 }
352
353 $this->reader->close();
354 return '';
355 }
356
357 # --------------
358
359 /** Left in for debugging */
360 private function dumpElement() {
361 static $lookup = null;
362 if (!$lookup) {
363 $xmlReaderConstants = array(
364 "NONE",
365 "ELEMENT",
366 "ATTRIBUTE",
367 "TEXT",
368 "CDATA",
369 "ENTITY_REF",
370 "ENTITY",
371 "PI",
372 "COMMENT",
373 "DOC",
374 "DOC_TYPE",
375 "DOC_FRAGMENT",
376 "NOTATION",
377 "WHITESPACE",
378 "SIGNIFICANT_WHITESPACE",
379 "END_ELEMENT",
380 "END_ENTITY",
381 "XML_DECLARATION",
382 );
383 $lookup = array();
384
385 foreach( $xmlReaderConstants as $name ) {
386 $lookup[constant("XmlReader::$name")] = $name;
387 }
388 }
389
390 print( var_dump(
391 $lookup[$this->reader->nodeType],
392 $this->reader->name,
393 $this->reader->value
394 )."\n\n" );
395 }
396
397 /**
398 * Primary entry point
399 */
400 public function doImport() {
401 $this->reader->read();
402
403 if ( $this->reader->name != 'mediawiki' ) {
404 throw new MWException( "Expected <mediawiki> tag, got ".
405 $this->reader->name );
406 }
407 $this->debug( "<mediawiki> tag is correct." );
408
409 $this->debug( "Starting primary dump processing loop." );
410
411 $keepReading = $this->reader->read();
412 $skip = false;
413 while ( $keepReading ) {
414 $tag = $this->reader->name;
415 $type = $this->reader->nodeType;
416
417 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
418 // Do nothing
419 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
420 break;
421 } elseif ( $tag == 'siteinfo' ) {
422 $this->handleSiteInfo();
423 } elseif ( $tag == 'page' ) {
424 $this->handlePage();
425 } elseif ( $tag == 'logitem' ) {
426 $this->handleLogItem();
427 } elseif ( $tag != '#text' ) {
428 $this->warn( "Unhandled top-level XML tag $tag" );
429
430 $skip = true;
431 }
432
433 if ($skip) {
434 $keepReading = $this->reader->next();
435 $skip = false;
436 $this->debug( "Skip" );
437 } else {
438 $keepReading = $this->reader->read();
439 }
440 }
441
442 return true;
443 }
444
445 /**
446 * @return bool
447 * @throws MWException
448 */
449 private function handleSiteInfo() {
450 // Site info is useful, but not actually used for dump imports.
451 // Includes a quick short-circuit to save performance.
452 if ( ! $this->mSiteInfoCallback ) {
453 $this->reader->next();
454 return true;
455 }
456 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
457 }
458
459 private function handleLogItem() {
460 $this->debug( "Enter log item handler." );
461 $logInfo = array();
462
463 // Fields that can just be stuffed in the pageInfo object
464 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
465 'logtitle', 'params' );
466
467 while ( $this->reader->read() ) {
468 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
469 $this->reader->name == 'logitem') {
470 break;
471 }
472
473 $tag = $this->reader->name;
474
475 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
476 $this, $logInfo ) ) {
477 // Do nothing
478 } elseif ( in_array( $tag, $normalFields ) ) {
479 $logInfo[$tag] = $this->nodeContents();
480 } elseif ( $tag == 'contributor' ) {
481 $logInfo['contributor'] = $this->handleContributor();
482 } elseif ( $tag != '#text' ) {
483 $this->warn( "Unhandled log-item XML tag $tag" );
484 }
485 }
486
487 $this->processLogItem( $logInfo );
488 }
489
490 /**
491 * @param $logInfo
492 * @return bool|mixed
493 */
494 private function processLogItem( $logInfo ) {
495 $revision = new WikiRevision;
496
497 $revision->setID( $logInfo['id'] );
498 $revision->setType( $logInfo['type'] );
499 $revision->setAction( $logInfo['action'] );
500 $revision->setTimestamp( $logInfo['timestamp'] );
501 $revision->setParams( $logInfo['params'] );
502 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
503 $revision->setNoUpdates( $this->mNoUpdates );
504
505 if ( isset( $logInfo['comment'] ) ) {
506 $revision->setComment( $logInfo['comment'] );
507 }
508
509 if ( isset( $logInfo['contributor']['ip'] ) ) {
510 $revision->setUserIP( $logInfo['contributor']['ip'] );
511 }
512 if ( isset( $logInfo['contributor']['username'] ) ) {
513 $revision->setUserName( $logInfo['contributor']['username'] );
514 }
515
516 return $this->logItemCallback( $revision );
517 }
518
519 private function handlePage() {
520 // Handle page data.
521 $this->debug( "Enter page handler." );
522 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
523
524 // Fields that can just be stuffed in the pageInfo object
525 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
526
527 $skip = false;
528 $badTitle = false;
529
530 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
531 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
532 $this->reader->name == 'page') {
533 break;
534 }
535
536 $tag = $this->reader->name;
537
538 if ( $badTitle ) {
539 // The title is invalid, bail out of this page
540 $skip = true;
541 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
542 &$pageInfo ) ) ) {
543 // Do nothing
544 } elseif ( in_array( $tag, $normalFields ) ) {
545 $pageInfo[$tag] = $this->nodeContents();
546 if ( $tag == 'title' ) {
547 $title = $this->processTitle( $pageInfo['title'] );
548
549 if ( !$title ) {
550 $badTitle = true;
551 $skip = true;
552 }
553
554 $this->pageCallback( $title );
555 list( $pageInfo['_title'], $origTitle ) = $title;
556 }
557 } elseif ( $tag == 'revision' ) {
558 $this->handleRevision( $pageInfo );
559 } elseif ( $tag == 'upload' ) {
560 $this->handleUpload( $pageInfo );
561 } elseif ( $tag != '#text' ) {
562 $this->warn( "Unhandled page XML tag $tag" );
563 $skip = true;
564 }
565 }
566
567 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
568 $pageInfo['revisionCount'],
569 $pageInfo['successfulRevisionCount'],
570 $pageInfo );
571 }
572
573 /**
574 * @param $pageInfo array
575 */
576 private function handleRevision( &$pageInfo ) {
577 $this->debug( "Enter revision handler" );
578 $revisionInfo = array();
579
580 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
581
582 $skip = false;
583
584 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
585 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
586 $this->reader->name == 'revision') {
587 break;
588 }
589
590 $tag = $this->reader->name;
591
592 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
593 $pageInfo, $revisionInfo ) ) {
594 // Do nothing
595 } elseif ( in_array( $tag, $normalFields ) ) {
596 $revisionInfo[$tag] = $this->nodeContents();
597 } elseif ( $tag == 'contributor' ) {
598 $revisionInfo['contributor'] = $this->handleContributor();
599 } elseif ( $tag != '#text' ) {
600 $this->warn( "Unhandled revision XML tag $tag" );
601 $skip = true;
602 }
603 }
604
605 $pageInfo['revisionCount']++;
606 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
607 $pageInfo['successfulRevisionCount']++;
608 }
609 }
610
611 /**
612 * @param $pageInfo
613 * @param $revisionInfo
614 * @return bool|mixed
615 */
616 private function processRevision( $pageInfo, $revisionInfo ) {
617 $revision = new WikiRevision;
618
619 if( isset( $revisionInfo['id'] ) ) {
620 $revision->setID( $revisionInfo['id'] );
621 }
622 if ( isset( $revisionInfo['text'] ) ) {
623 $revision->setText( $revisionInfo['text'] );
624 }
625 $revision->setTitle( $pageInfo['_title'] );
626
627 if ( isset( $revisionInfo['timestamp'] ) ) {
628 $revision->setTimestamp( $revisionInfo['timestamp'] );
629 } else {
630 $revision->setTimestamp( wfTimestampNow() );
631 }
632
633 if ( isset( $revisionInfo['comment'] ) ) {
634 $revision->setComment( $revisionInfo['comment'] );
635 }
636
637 if ( isset( $revisionInfo['minor'] ) ) {
638 $revision->setMinor( true );
639 }
640 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
641 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
642 }
643 if ( isset( $revisionInfo['contributor']['username'] ) ) {
644 $revision->setUserName( $revisionInfo['contributor']['username'] );
645 }
646 $revision->setNoUpdates( $this->mNoUpdates );
647
648 return $this->revisionCallback( $revision );
649 }
650
651 /**
652 * @param $pageInfo
653 * @return mixed
654 */
655 private function handleUpload( &$pageInfo ) {
656 $this->debug( "Enter upload handler" );
657 $uploadInfo = array();
658
659 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
660 'src', 'size', 'sha1base36', 'archivename', 'rel' );
661
662 $skip = false;
663
664 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
665 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
666 $this->reader->name == 'upload') {
667 break;
668 }
669
670 $tag = $this->reader->name;
671
672 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
673 $pageInfo ) ) {
674 // Do nothing
675 } elseif ( in_array( $tag, $normalFields ) ) {
676 $uploadInfo[$tag] = $this->nodeContents();
677 } elseif ( $tag == 'contributor' ) {
678 $uploadInfo['contributor'] = $this->handleContributor();
679 } elseif ( $tag == 'contents' ) {
680 $contents = $this->nodeContents();
681 $encoding = $this->reader->getAttribute( 'encoding' );
682 if ( $encoding === 'base64' ) {
683 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
684 $uploadInfo['isTempSrc'] = true;
685 }
686 } elseif ( $tag != '#text' ) {
687 $this->warn( "Unhandled upload XML tag $tag" );
688 $skip = true;
689 }
690 }
691
692 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
693 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
694 if ( file_exists( $path ) ) {
695 $uploadInfo['fileSrc'] = $path;
696 $uploadInfo['isTempSrc'] = false;
697 }
698 }
699
700 if ( $this->mImportUploads ) {
701 return $this->processUpload( $pageInfo, $uploadInfo );
702 }
703 }
704
705 /**
706 * @param $contents
707 * @return string
708 */
709 private function dumpTemp( $contents ) {
710 $filename = tempnam( wfTempDir(), 'importupload' );
711 file_put_contents( $filename, $contents );
712 return $filename;
713 }
714
715 /**
716 * @param $pageInfo
717 * @param $uploadInfo
718 * @return mixed
719 */
720 private function processUpload( $pageInfo, $uploadInfo ) {
721 $revision = new WikiRevision;
722 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
723
724 $revision->setTitle( $pageInfo['_title'] );
725 $revision->setID( $pageInfo['id'] );
726 $revision->setTimestamp( $uploadInfo['timestamp'] );
727 $revision->setText( $text );
728 $revision->setFilename( $uploadInfo['filename'] );
729 if ( isset( $uploadInfo['archivename'] ) ) {
730 $revision->setArchiveName( $uploadInfo['archivename'] );
731 }
732 $revision->setSrc( $uploadInfo['src'] );
733 if ( isset( $uploadInfo['fileSrc'] ) ) {
734 $revision->setFileSrc( $uploadInfo['fileSrc'],
735 !empty( $uploadInfo['isTempSrc'] ) );
736 }
737 if ( isset( $uploadInfo['sha1base36'] ) ) {
738 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
739 }
740 $revision->setSize( intval( $uploadInfo['size'] ) );
741 $revision->setComment( $uploadInfo['comment'] );
742
743 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
744 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
745 }
746 if ( isset( $uploadInfo['contributor']['username'] ) ) {
747 $revision->setUserName( $uploadInfo['contributor']['username'] );
748 }
749 $revision->setNoUpdates( $this->mNoUpdates );
750
751 return call_user_func( $this->mUploadCallback, $revision );
752 }
753
754 /**
755 * @return array
756 */
757 private function handleContributor() {
758 $fields = array( 'id', 'ip', 'username' );
759 $info = array();
760
761 while ( $this->reader->read() ) {
762 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
763 $this->reader->name == 'contributor') {
764 break;
765 }
766
767 $tag = $this->reader->name;
768
769 if ( in_array( $tag, $fields ) ) {
770 $info[$tag] = $this->nodeContents();
771 }
772 }
773
774 return $info;
775 }
776
777 /**
778 * @param $text string
779 * @return Array or false
780 */
781 private function processTitle( $text ) {
782 global $wgCommandLineMode;
783
784 $workTitle = $text;
785 $origTitle = Title::newFromText( $workTitle );
786
787 if( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
788 $title = Title::makeTitle( $this->mTargetNamespace,
789 $origTitle->getDBkey() );
790 } else {
791 $title = Title::newFromText( $workTitle );
792 }
793
794 if( is_null( $title ) ) {
795 # Invalid page title? Ignore the page
796 $this->notice( 'import-error-invalid', $workTitle );
797 return false;
798 } elseif( $title->isExternal() ) {
799 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
800 return false;
801 } elseif( !$title->canExist() ) {
802 $this->notice( 'import-error-special', $title->getPrefixedText() );
803 return false;
804 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
805 # Do not import if the importing wiki user cannot edit this page
806 $this->notice( 'import-error-edit', $title->getPrefixedText() );
807 return false;
808 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
809 # Do not import if the importing wiki user cannot create this page
810 $this->notice( 'import-error-create', $title->getPrefixedText() );
811 return false;
812 }
813
814 return array( $title, $origTitle );
815 }
816 }
817
818 /** This is a horrible hack used to keep source compatibility */
819 class UploadSourceAdapter {
820 static $sourceRegistrations = array();
821
822 private $mSource;
823 private $mBuffer;
824 private $mPosition;
825
826 /**
827 * @param $source
828 * @return string
829 */
830 static function registerSource( $source ) {
831 $id = wfGenerateToken();
832
833 self::$sourceRegistrations[$id] = $source;
834
835 return $id;
836 }
837
838 /**
839 * @param $path
840 * @param $mode
841 * @param $options
842 * @param $opened_path
843 * @return bool
844 */
845 function stream_open( $path, $mode, $options, &$opened_path ) {
846 $url = parse_url($path);
847 $id = $url['host'];
848
849 if ( !isset( self::$sourceRegistrations[$id] ) ) {
850 return false;
851 }
852
853 $this->mSource = self::$sourceRegistrations[$id];
854
855 return true;
856 }
857
858 /**
859 * @param $count
860 * @return string
861 */
862 function stream_read( $count ) {
863 $return = '';
864 $leave = false;
865
866 while ( !$leave && !$this->mSource->atEnd() &&
867 strlen($this->mBuffer) < $count ) {
868 $read = $this->mSource->readChunk();
869
870 if ( !strlen($read) ) {
871 $leave = true;
872 }
873
874 $this->mBuffer .= $read;
875 }
876
877 if ( strlen($this->mBuffer) ) {
878 $return = substr( $this->mBuffer, 0, $count );
879 $this->mBuffer = substr( $this->mBuffer, $count );
880 }
881
882 $this->mPosition += strlen($return);
883
884 return $return;
885 }
886
887 /**
888 * @param $data
889 * @return bool
890 */
891 function stream_write( $data ) {
892 return false;
893 }
894
895 /**
896 * @return mixed
897 */
898 function stream_tell() {
899 return $this->mPosition;
900 }
901
902 /**
903 * @return bool
904 */
905 function stream_eof() {
906 return $this->mSource->atEnd();
907 }
908
909 /**
910 * @return array
911 */
912 function url_stat() {
913 $result = array();
914
915 $result['dev'] = $result[0] = 0;
916 $result['ino'] = $result[1] = 0;
917 $result['mode'] = $result[2] = 0;
918 $result['nlink'] = $result[3] = 0;
919 $result['uid'] = $result[4] = 0;
920 $result['gid'] = $result[5] = 0;
921 $result['rdev'] = $result[6] = 0;
922 $result['size'] = $result[7] = 0;
923 $result['atime'] = $result[8] = 0;
924 $result['mtime'] = $result[9] = 0;
925 $result['ctime'] = $result[10] = 0;
926 $result['blksize'] = $result[11] = 0;
927 $result['blocks'] = $result[12] = 0;
928
929 return $result;
930 }
931 }
932
933 class XMLReader2 extends XMLReader {
934
935 /**
936 * @return bool|string
937 */
938 function nodeContents() {
939 if( $this->isEmptyElement ) {
940 return "";
941 }
942 $buffer = "";
943 while( $this->read() ) {
944 switch( $this->nodeType ) {
945 case XmlReader::TEXT:
946 case XmlReader::SIGNIFICANT_WHITESPACE:
947 $buffer .= $this->value;
948 break;
949 case XmlReader::END_ELEMENT:
950 return $buffer;
951 }
952 }
953 return $this->close();
954 }
955 }
956
957 /**
958 * @todo document (e.g. one-sentence class description).
959 * @ingroup SpecialPage
960 */
961 class WikiRevision {
962 var $importer = null;
963
964 /**
965 * @var Title
966 */
967 var $title = null;
968 var $id = 0;
969 var $timestamp = "20010115000000";
970 var $user = 0;
971 var $user_text = "";
972 var $text = "";
973 var $comment = "";
974 var $minor = false;
975 var $type = "";
976 var $action = "";
977 var $params = "";
978 var $fileSrc = '';
979 var $sha1base36 = false;
980 var $isTemp = false;
981 var $archiveName = '';
982 var $fileIsTemp;
983 private $mNoUpdates = false;
984
985 /**
986 * @param $title
987 * @throws MWException
988 */
989 function setTitle( $title ) {
990 if( is_object( $title ) ) {
991 $this->title = $title;
992 } elseif( is_null( $title ) ) {
993 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
994 } else {
995 throw new MWException( "WikiRevision given non-object title in import." );
996 }
997 }
998
999 /**
1000 * @param $id
1001 */
1002 function setID( $id ) {
1003 $this->id = $id;
1004 }
1005
1006 /**
1007 * @param $ts
1008 */
1009 function setTimestamp( $ts ) {
1010 # 2003-08-05T18:30:02Z
1011 $this->timestamp = wfTimestamp( TS_MW, $ts );
1012 }
1013
1014 /**
1015 * @param $user
1016 */
1017 function setUsername( $user ) {
1018 $this->user_text = $user;
1019 }
1020
1021 /**
1022 * @param $ip
1023 */
1024 function setUserIP( $ip ) {
1025 $this->user_text = $ip;
1026 }
1027
1028 /**
1029 * @param $text
1030 */
1031 function setText( $text ) {
1032 $this->text = $text;
1033 }
1034
1035 /**
1036 * @param $text
1037 */
1038 function setComment( $text ) {
1039 $this->comment = $text;
1040 }
1041
1042 /**
1043 * @param $minor
1044 */
1045 function setMinor( $minor ) {
1046 $this->minor = (bool)$minor;
1047 }
1048
1049 /**
1050 * @param $src
1051 */
1052 function setSrc( $src ) {
1053 $this->src = $src;
1054 }
1055
1056 /**
1057 * @param $src
1058 * @param $isTemp
1059 */
1060 function setFileSrc( $src, $isTemp ) {
1061 $this->fileSrc = $src;
1062 $this->fileIsTemp = $isTemp;
1063 }
1064
1065 /**
1066 * @param $sha1base36
1067 */
1068 function setSha1Base36( $sha1base36 ) {
1069 $this->sha1base36 = $sha1base36;
1070 }
1071
1072 /**
1073 * @param $filename
1074 */
1075 function setFilename( $filename ) {
1076 $this->filename = $filename;
1077 }
1078
1079 /**
1080 * @param $archiveName
1081 */
1082 function setArchiveName( $archiveName ) {
1083 $this->archiveName = $archiveName;
1084 }
1085
1086 /**
1087 * @param $size
1088 */
1089 function setSize( $size ) {
1090 $this->size = intval( $size );
1091 }
1092
1093 /**
1094 * @param $type
1095 */
1096 function setType( $type ) {
1097 $this->type = $type;
1098 }
1099
1100 /**
1101 * @param $action
1102 */
1103 function setAction( $action ) {
1104 $this->action = $action;
1105 }
1106
1107 /**
1108 * @param $params
1109 */
1110 function setParams( $params ) {
1111 $this->params = $params;
1112 }
1113
1114 /**
1115 * @param $noupdates
1116 */
1117 public function setNoUpdates( $noupdates ) {
1118 $this->mNoUpdates = $noupdates;
1119 }
1120
1121 /**
1122 * @return Title
1123 */
1124 function getTitle() {
1125 return $this->title;
1126 }
1127
1128 /**
1129 * @return int
1130 */
1131 function getID() {
1132 return $this->id;
1133 }
1134
1135 /**
1136 * @return string
1137 */
1138 function getTimestamp() {
1139 return $this->timestamp;
1140 }
1141
1142 /**
1143 * @return string
1144 */
1145 function getUser() {
1146 return $this->user_text;
1147 }
1148
1149 /**
1150 * @return string
1151 */
1152 function getText() {
1153 return $this->text;
1154 }
1155
1156 /**
1157 * @return string
1158 */
1159 function getComment() {
1160 return $this->comment;
1161 }
1162
1163 /**
1164 * @return bool
1165 */
1166 function getMinor() {
1167 return $this->minor;
1168 }
1169
1170 /**
1171 * @return mixed
1172 */
1173 function getSrc() {
1174 return $this->src;
1175 }
1176
1177 /**
1178 * @return bool|String
1179 */
1180 function getSha1() {
1181 if ( $this->sha1base36 ) {
1182 return wfBaseConvert( $this->sha1base36, 36, 16 );
1183 }
1184 return false;
1185 }
1186
1187 /**
1188 * @return string
1189 */
1190 function getFileSrc() {
1191 return $this->fileSrc;
1192 }
1193
1194 /**
1195 * @return bool
1196 */
1197 function isTempSrc() {
1198 return $this->isTemp;
1199 }
1200
1201 /**
1202 * @return mixed
1203 */
1204 function getFilename() {
1205 return $this->filename;
1206 }
1207
1208 /**
1209 * @return string
1210 */
1211 function getArchiveName() {
1212 return $this->archiveName;
1213 }
1214
1215 /**
1216 * @return mixed
1217 */
1218 function getSize() {
1219 return $this->size;
1220 }
1221
1222 /**
1223 * @return string
1224 */
1225 function getType() {
1226 return $this->type;
1227 }
1228
1229 /**
1230 * @return string
1231 */
1232 function getAction() {
1233 return $this->action;
1234 }
1235
1236 /**
1237 * @return string
1238 */
1239 function getParams() {
1240 return $this->params;
1241 }
1242
1243 /**
1244 * @return bool
1245 */
1246 function importOldRevision() {
1247 $dbw = wfGetDB( DB_MASTER );
1248
1249 # Sneak a single revision into place
1250 $user = User::newFromName( $this->getUser() );
1251 if( $user ) {
1252 $userId = intval( $user->getId() );
1253 $userText = $user->getName();
1254 $userObj = $user;
1255 } else {
1256 $userId = 0;
1257 $userText = $this->getUser();
1258 $userObj = new User;
1259 }
1260
1261 // avoid memory leak...?
1262 $linkCache = LinkCache::singleton();
1263 $linkCache->clear();
1264
1265 $page = WikiPage::factory( $this->title );
1266 if( !$page->exists() ) {
1267 # must create the page...
1268 $pageId = $page->insertOn( $dbw );
1269 $created = true;
1270 $oldcountable = null;
1271 } else {
1272 $pageId = $page->getId();
1273 $created = false;
1274
1275 $prior = $dbw->selectField( 'revision', '1',
1276 array( 'rev_page' => $pageId,
1277 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1278 'rev_user_text' => $userText,
1279 'rev_comment' => $this->getComment() ),
1280 __METHOD__
1281 );
1282 if( $prior ) {
1283 // @todo FIXME: This could fail slightly for multiple matches :P
1284 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1285 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1286 return false;
1287 }
1288 $oldcountable = $page->isCountable();
1289 }
1290
1291 # @todo FIXME: Use original rev_id optionally (better for backups)
1292 # Insert the row
1293 $revision = new Revision( array(
1294 'page' => $pageId,
1295 'text' => $this->getText(),
1296 'comment' => $this->getComment(),
1297 'user' => $userId,
1298 'user_text' => $userText,
1299 'timestamp' => $this->timestamp,
1300 'minor_edit' => $this->minor,
1301 ) );
1302 $revision->insertOn( $dbw );
1303 $changed = $page->updateIfNewerOn( $dbw, $revision );
1304
1305 if ( $changed !== false && !$this->mNoUpdates ) {
1306 wfDebug( __METHOD__ . ": running updates\n" );
1307 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1308 }
1309
1310 return true;
1311 }
1312
1313 /**
1314 * @return mixed
1315 */
1316 function importLogItem() {
1317 $dbw = wfGetDB( DB_MASTER );
1318 # @todo FIXME: This will not record autoblocks
1319 if( !$this->getTitle() ) {
1320 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1321 $this->timestamp . "\n" );
1322 return;
1323 }
1324 # Check if it exists already
1325 // @todo FIXME: Use original log ID (better for backups)
1326 $prior = $dbw->selectField( 'logging', '1',
1327 array( 'log_type' => $this->getType(),
1328 'log_action' => $this->getAction(),
1329 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1330 'log_namespace' => $this->getTitle()->getNamespace(),
1331 'log_title' => $this->getTitle()->getDBkey(),
1332 'log_comment' => $this->getComment(),
1333 #'log_user_text' => $this->user_text,
1334 'log_params' => $this->params ),
1335 __METHOD__
1336 );
1337 // @todo FIXME: This could fail slightly for multiple matches :P
1338 if( $prior ) {
1339 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1340 $this->timestamp . "\n" );
1341 return;
1342 }
1343 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1344 $data = array(
1345 'log_id' => $log_id,
1346 'log_type' => $this->type,
1347 'log_action' => $this->action,
1348 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1349 'log_user' => User::idFromName( $this->user_text ),
1350 #'log_user_text' => $this->user_text,
1351 'log_namespace' => $this->getTitle()->getNamespace(),
1352 'log_title' => $this->getTitle()->getDBkey(),
1353 'log_comment' => $this->getComment(),
1354 'log_params' => $this->params
1355 );
1356 $dbw->insert( 'logging', $data, __METHOD__ );
1357 }
1358
1359 /**
1360 * @return bool
1361 */
1362 function importUpload() {
1363 # Construct a file
1364 $archiveName = $this->getArchiveName();
1365 if ( $archiveName ) {
1366 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1367 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1368 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1369 } else {
1370 $file = wfLocalFile( $this->getTitle() );
1371 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1372 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1373 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1374 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1375 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1376 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1377 }
1378 }
1379 if( !$file ) {
1380 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1381 return false;
1382 }
1383
1384 # Get the file source or download if necessary
1385 $source = $this->getFileSrc();
1386 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1387 if ( !$source ) {
1388 $source = $this->downloadSource();
1389 $flags |= File::DELETE_SOURCE;
1390 }
1391 if( !$source ) {
1392 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1393 return false;
1394 }
1395 $sha1 = $this->getSha1();
1396 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1397 if ( $flags & File::DELETE_SOURCE ) {
1398 # Broken file; delete it if it is a temporary file
1399 unlink( $source );
1400 }
1401 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1402 return false;
1403 }
1404
1405 $user = User::newFromName( $this->user_text );
1406
1407 # Do the actual upload
1408 if ( $archiveName ) {
1409 $status = $file->uploadOld( $source, $archiveName,
1410 $this->getTimestamp(), $this->getComment(), $user, $flags );
1411 } else {
1412 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1413 $flags, false, $this->getTimestamp(), $user );
1414 }
1415
1416 if ( $status->isGood() ) {
1417 wfDebug( __METHOD__ . ": Succesful\n" );
1418 return true;
1419 } else {
1420 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1421 return false;
1422 }
1423 }
1424
1425 /**
1426 * @return bool|string
1427 */
1428 function downloadSource() {
1429 global $wgEnableUploads;
1430 if( !$wgEnableUploads ) {
1431 return false;
1432 }
1433
1434 $tempo = tempnam( wfTempDir(), 'download' );
1435 $f = fopen( $tempo, 'wb' );
1436 if( !$f ) {
1437 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1438 return false;
1439 }
1440
1441 // @todo FIXME!
1442 $src = $this->getSrc();
1443 $data = Http::get( $src );
1444 if( !$data ) {
1445 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1446 fclose( $f );
1447 unlink( $tempo );
1448 return false;
1449 }
1450
1451 fwrite( $f, $data );
1452 fclose( $f );
1453
1454 return $tempo;
1455 }
1456
1457 }
1458
1459 /**
1460 * @todo document (e.g. one-sentence class description).
1461 * @ingroup SpecialPage
1462 */
1463 class ImportStringSource {
1464 function __construct( $string ) {
1465 $this->mString = $string;
1466 $this->mRead = false;
1467 }
1468
1469 /**
1470 * @return bool
1471 */
1472 function atEnd() {
1473 return $this->mRead;
1474 }
1475
1476 /**
1477 * @return bool|string
1478 */
1479 function readChunk() {
1480 if( $this->atEnd() ) {
1481 return false;
1482 }
1483 $this->mRead = true;
1484 return $this->mString;
1485 }
1486 }
1487
1488 /**
1489 * @todo document (e.g. one-sentence class description).
1490 * @ingroup SpecialPage
1491 */
1492 class ImportStreamSource {
1493 function __construct( $handle ) {
1494 $this->mHandle = $handle;
1495 }
1496
1497 /**
1498 * @return bool
1499 */
1500 function atEnd() {
1501 return feof( $this->mHandle );
1502 }
1503
1504 /**
1505 * @return string
1506 */
1507 function readChunk() {
1508 return fread( $this->mHandle, 32768 );
1509 }
1510
1511 /**
1512 * @param $filename string
1513 * @return Status
1514 */
1515 static function newFromFile( $filename ) {
1516 wfSuppressWarnings();
1517 $file = fopen( $filename, 'rt' );
1518 wfRestoreWarnings();
1519 if( !$file ) {
1520 return Status::newFatal( "importcantopen" );
1521 }
1522 return Status::newGood( new ImportStreamSource( $file ) );
1523 }
1524
1525 /**
1526 * @param $fieldname string
1527 * @return Status
1528 */
1529 static function newFromUpload( $fieldname = "xmlimport" ) {
1530 $upload =& $_FILES[$fieldname];
1531
1532 if( !isset( $upload ) || !$upload['name'] ) {
1533 return Status::newFatal( 'importnofile' );
1534 }
1535 if( !empty( $upload['error'] ) ) {
1536 switch($upload['error']){
1537 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1538 return Status::newFatal( 'importuploaderrorsize' );
1539 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1540 return Status::newFatal( 'importuploaderrorsize' );
1541 case 3: # The uploaded file was only partially uploaded
1542 return Status::newFatal( 'importuploaderrorpartial' );
1543 case 6: #Missing a temporary folder.
1544 return Status::newFatal( 'importuploaderrortemp' );
1545 # case else: # Currently impossible
1546 }
1547
1548 }
1549 $fname = $upload['tmp_name'];
1550 if( is_uploaded_file( $fname ) ) {
1551 return ImportStreamSource::newFromFile( $fname );
1552 } else {
1553 return Status::newFatal( 'importnofile' );
1554 }
1555 }
1556
1557 /**
1558 * @param $url
1559 * @param $method string
1560 * @return Status
1561 */
1562 static function newFromURL( $url, $method = 'GET' ) {
1563 wfDebug( __METHOD__ . ": opening $url\n" );
1564 # Use the standard HTTP fetch function; it times out
1565 # quicker and sorts out user-agent problems which might
1566 # otherwise prevent importing from large sites, such
1567 # as the Wikimedia cluster, etc.
1568 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1569 if( $data !== false ) {
1570 $file = tmpfile();
1571 fwrite( $file, $data );
1572 fflush( $file );
1573 fseek( $file, 0 );
1574 return Status::newGood( new ImportStreamSource( $file ) );
1575 } else {
1576 return Status::newFatal( 'importcantopen' );
1577 }
1578 }
1579
1580 /**
1581 * @param $interwiki
1582 * @param $page
1583 * @param $history bool
1584 * @param $templates bool
1585 * @param $pageLinkDepth int
1586 * @return Status
1587 */
1588 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1589 if( $page == '' ) {
1590 return Status::newFatal( 'import-noarticle' );
1591 }
1592 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1593 if( is_null( $link ) || $link->getInterwiki() == '' ) {
1594 return Status::newFatal( 'importbadinterwiki' );
1595 } else {
1596 $params = array();
1597 if ( $history ) $params['history'] = 1;
1598 if ( $templates ) $params['templates'] = 1;
1599 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1600 $url = $link->getFullUrl( $params );
1601 # For interwikis, use POST to avoid redirects.
1602 return ImportStreamSource::newFromURL( $url, "POST" );
1603 }
1604 }
1605 }