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