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