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