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