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