* (bug 28417) Fix PHP notice when importing revision without a listed id
[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 if( isset( $revisionInfo['id'] ) ) {
550 $revision->setID( $revisionInfo['id'] );
551 }
552 if ( isset( $revisionInfo['text'] ) ) {
553 $revision->setText( $revisionInfo['text'] );
554 }
555 $revision->setTitle( $pageInfo['_title'] );
556
557 if ( isset( $revisionInfo['timestamp'] ) ) {
558 $revision->setTimestamp( $revisionInfo['timestamp'] );
559 } else {
560 $revision->setTimestamp( wfTimestampNow() );
561 }
562
563 if ( isset( $revisionInfo['comment'] ) ) {
564 $revision->setComment( $revisionInfo['comment'] );
565 }
566
567 if ( isset( $revisionInfo['minor'] ) ) {
568 $revision->setMinor( true );
569 }
570 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
571 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
572 }
573 if ( isset( $revisionInfo['contributor']['username'] ) ) {
574 $revision->setUserName( $revisionInfo['contributor']['username'] );
575 }
576
577 return $this->revisionCallback( $revision );
578 }
579
580 private function handleUpload( &$pageInfo ) {
581 $this->debug( "Enter upload handler" );
582 $uploadInfo = array();
583
584 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
585 'src', 'size' );
586
587 $skip = false;
588
589 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
590 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
591 $this->reader->name == 'upload') {
592 break;
593 }
594
595 $tag = $this->reader->name;
596
597 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
598 $pageInfo ) ) {
599 // Do nothing
600 } elseif ( in_array( $tag, $normalFields ) ) {
601 $uploadInfo[$tag] = $this->nodeContents();
602 } elseif ( $tag == 'contributor' ) {
603 $uploadInfo['contributor'] = $this->handleContributor();
604 } elseif ( $tag != '#text' ) {
605 $this->warn( "Unhandled upload XML tag $tag" );
606 $skip = true;
607 }
608 }
609
610 return $this->processUpload( $pageInfo, $uploadInfo );
611 }
612
613
614 private function processUpload( $pageInfo, $uploadInfo ) {
615 $revision = new WikiRevision;
616 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
617
618 $revision->setTitle( $pageInfo['_title'] );
619 $revision->setID( $pageInfo['id'] );
620 $revision->setTimestamp( $uploadInfo['timestamp'] );
621 $revision->setText( $text );
622 $revision->setFilename( $uploadInfo['filename'] );
623 $revision->setSrc( $uploadInfo['src'] );
624 $revision->setSize( intval( $uploadInfo['size'] ) );
625 $revision->setComment( $uploadInfo['comment'] );
626
627 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
628 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
629 }
630 if ( isset( $uploadInfo['contributor']['username'] ) ) {
631 $revision->setUserName( $uploadInfo['contributor']['username'] );
632 }
633
634 return call_user_func( $this->mUploadCallback, $revision );
635 }
636
637 private function handleContributor() {
638 $fields = array( 'id', 'ip', 'username' );
639 $info = array();
640
641 while ( $this->reader->read() ) {
642 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
643 $this->reader->name == 'contributor') {
644 break;
645 }
646
647 $tag = $this->reader->name;
648
649 if ( in_array( $tag, $fields ) ) {
650 $info[$tag] = $this->nodeContents();
651 }
652 }
653
654 return $info;
655 }
656
657 private function processTitle( $text ) {
658 $workTitle = $text;
659 $origTitle = Title::newFromText( $workTitle );
660
661 if( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
662 $title = Title::makeTitle( $this->mTargetNamespace,
663 $origTitle->getDBkey() );
664 } else {
665 $title = Title::newFromText( $workTitle );
666 }
667
668 if( is_null( $title ) ) {
669 // Invalid page title? Ignore the page
670 $this->notice( "Skipping invalid page title '$workTitle'" );
671 return false;
672 } elseif( $title->getInterwiki() != '' ) {
673 $this->notice( "Skipping interwiki page title '$workTitle'" );
674 return false;
675 }
676
677 return array( $title, $origTitle );
678 }
679 }
680
681 /** This is a horrible hack used to keep source compatibility */
682 class UploadSourceAdapter {
683 static $sourceRegistrations = array();
684
685 private $mSource;
686 private $mBuffer;
687 private $mPosition;
688
689 static function registerSource( $source ) {
690 $id = wfGenerateToken();
691
692 self::$sourceRegistrations[$id] = $source;
693
694 return $id;
695 }
696
697 function stream_open( $path, $mode, $options, &$opened_path ) {
698 $url = parse_url($path);
699 $id = $url['host'];
700
701 if ( !isset( self::$sourceRegistrations[$id] ) ) {
702 return false;
703 }
704
705 $this->mSource = self::$sourceRegistrations[$id];
706
707 return true;
708 }
709
710 function stream_read( $count ) {
711 $return = '';
712 $leave = false;
713
714 while ( !$leave && !$this->mSource->atEnd() &&
715 strlen($this->mBuffer) < $count ) {
716 $read = $this->mSource->readChunk();
717
718 if ( !strlen($read) ) {
719 $leave = true;
720 }
721
722 $this->mBuffer .= $read;
723 }
724
725 if ( strlen($this->mBuffer) ) {
726 $return = substr( $this->mBuffer, 0, $count );
727 $this->mBuffer = substr( $this->mBuffer, $count );
728 }
729
730 $this->mPosition += strlen($return);
731
732 return $return;
733 }
734
735 function stream_write( $data ) {
736 return false;
737 }
738
739 function stream_tell() {
740 return $this->mPosition;
741 }
742
743 function stream_eof() {
744 return $this->mSource->atEnd();
745 }
746
747 function url_stat() {
748 $result = array();
749
750 $result['dev'] = $result[0] = 0;
751 $result['ino'] = $result[1] = 0;
752 $result['mode'] = $result[2] = 0;
753 $result['nlink'] = $result[3] = 0;
754 $result['uid'] = $result[4] = 0;
755 $result['gid'] = $result[5] = 0;
756 $result['rdev'] = $result[6] = 0;
757 $result['size'] = $result[7] = 0;
758 $result['atime'] = $result[8] = 0;
759 $result['mtime'] = $result[9] = 0;
760 $result['ctime'] = $result[10] = 0;
761 $result['blksize'] = $result[11] = 0;
762 $result['blocks'] = $result[12] = 0;
763
764 return $result;
765 }
766 }
767
768 class XMLReader2 extends XMLReader {
769 function nodeContents() {
770 if( $this->isEmptyElement ) {
771 return "";
772 }
773 $buffer = "";
774 while( $this->read() ) {
775 switch( $this->nodeType ) {
776 case XmlReader::TEXT:
777 case XmlReader::SIGNIFICANT_WHITESPACE:
778 $buffer .= $this->value;
779 break;
780 case XmlReader::END_ELEMENT:
781 return $buffer;
782 }
783 }
784 return $this->close();
785 }
786 }
787
788 /**
789 * @todo document (e.g. one-sentence class description).
790 * @ingroup SpecialPage
791 */
792 class WikiRevision {
793 var $title = null;
794 var $id = 0;
795 var $timestamp = "20010115000000";
796 var $user = 0;
797 var $user_text = "";
798 var $text = "";
799 var $comment = "";
800 var $minor = false;
801 var $type = "";
802 var $action = "";
803 var $params = "";
804
805 function setTitle( $title ) {
806 if( is_object( $title ) ) {
807 $this->title = $title;
808 } elseif( is_null( $title ) ) {
809 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
810 } else {
811 throw new MWException( "WikiRevision given non-object title in import." );
812 }
813 }
814
815 function setID( $id ) {
816 $this->id = $id;
817 }
818
819 function setTimestamp( $ts ) {
820 # 2003-08-05T18:30:02Z
821 $this->timestamp = wfTimestamp( TS_MW, $ts );
822 }
823
824 function setUsername( $user ) {
825 $this->user_text = $user;
826 }
827
828 function setUserIP( $ip ) {
829 $this->user_text = $ip;
830 }
831
832 function setText( $text ) {
833 $this->text = $text;
834 }
835
836 function setComment( $text ) {
837 $this->comment = $text;
838 }
839
840 function setMinor( $minor ) {
841 $this->minor = (bool)$minor;
842 }
843
844 function setSrc( $src ) {
845 $this->src = $src;
846 }
847
848 function setFilename( $filename ) {
849 $this->filename = $filename;
850 }
851
852 function setSize( $size ) {
853 $this->size = intval( $size );
854 }
855
856 function setType( $type ) {
857 $this->type = $type;
858 }
859
860 function setAction( $action ) {
861 $this->action = $action;
862 }
863
864 function setParams( $params ) {
865 $this->params = $params;
866 }
867
868 function getTitle() {
869 return $this->title;
870 }
871
872 function getID() {
873 return $this->id;
874 }
875
876 function getTimestamp() {
877 return $this->timestamp;
878 }
879
880 function getUser() {
881 return $this->user_text;
882 }
883
884 function getText() {
885 return $this->text;
886 }
887
888 function getComment() {
889 return $this->comment;
890 }
891
892 function getMinor() {
893 return $this->minor;
894 }
895
896 function getSrc() {
897 return $this->src;
898 }
899
900 function getFilename() {
901 return $this->filename;
902 }
903
904 function getSize() {
905 return $this->size;
906 }
907
908 function getType() {
909 return $this->type;
910 }
911
912 function getAction() {
913 return $this->action;
914 }
915
916 function getParams() {
917 return $this->params;
918 }
919
920 function importOldRevision() {
921 $dbw = wfGetDB( DB_MASTER );
922
923 # Sneak a single revision into place
924 $user = User::newFromName( $this->getUser() );
925 if( $user ) {
926 $userId = intval( $user->getId() );
927 $userText = $user->getName();
928 } else {
929 $userId = 0;
930 $userText = $this->getUser();
931 }
932
933 // avoid memory leak...?
934 $linkCache = LinkCache::singleton();
935 $linkCache->clear();
936
937 $article = new Article( $this->title );
938 $pageId = $article->getId();
939 if( $pageId == 0 ) {
940 # must create the page...
941 $pageId = $article->insertOn( $dbw );
942 $created = true;
943 } else {
944 $created = false;
945
946 $prior = $dbw->selectField( 'revision', '1',
947 array( 'rev_page' => $pageId,
948 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
949 'rev_user_text' => $userText,
950 'rev_comment' => $this->getComment() ),
951 __METHOD__
952 );
953 if( $prior ) {
954 // FIXME: this could fail slightly for multiple matches :P
955 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
956 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
957 return false;
958 }
959 }
960
961 # FIXME: Use original rev_id optionally (better for backups)
962 # Insert the row
963 $revision = new Revision( array(
964 'page' => $pageId,
965 'text' => $this->getText(),
966 'comment' => $this->getComment(),
967 'user' => $userId,
968 'user_text' => $userText,
969 'timestamp' => $this->timestamp,
970 'minor_edit' => $this->minor,
971 ) );
972 $revId = $revision->insertOn( $dbw );
973 $changed = $article->updateIfNewerOn( $dbw, $revision );
974
975 # To be on the safe side...
976 $tempTitle = $GLOBALS['wgTitle'];
977 $GLOBALS['wgTitle'] = $this->title;
978
979 if( $created ) {
980 wfDebug( __METHOD__ . ": running onArticleCreate\n" );
981 Article::onArticleCreate( $this->title );
982
983 wfDebug( __METHOD__ . ": running create updates\n" );
984 $article->createUpdates( $revision );
985
986 } elseif( $changed ) {
987 wfDebug( __METHOD__ . ": running onArticleEdit\n" );
988 Article::onArticleEdit( $this->title );
989
990 wfDebug( __METHOD__ . ": running edit updates\n" );
991 $article->editUpdates(
992 $this->getText(),
993 $this->getComment(),
994 $this->minor,
995 $this->timestamp,
996 $revId );
997 }
998 $GLOBALS['wgTitle'] = $tempTitle;
999
1000 return true;
1001 }
1002
1003 function importLogItem() {
1004 $dbw = wfGetDB( DB_MASTER );
1005 # FIXME: this will not record autoblocks
1006 if( !$this->getTitle() ) {
1007 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1008 $this->timestamp . "\n" );
1009 return;
1010 }
1011 # Check if it exists already
1012 // FIXME: use original log ID (better for backups)
1013 $prior = $dbw->selectField( 'logging', '1',
1014 array( 'log_type' => $this->getType(),
1015 'log_action' => $this->getAction(),
1016 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1017 'log_namespace' => $this->getTitle()->getNamespace(),
1018 'log_title' => $this->getTitle()->getDBkey(),
1019 'log_comment' => $this->getComment(),
1020 #'log_user_text' => $this->user_text,
1021 'log_params' => $this->params ),
1022 __METHOD__
1023 );
1024 // FIXME: this could fail slightly for multiple matches :P
1025 if( $prior ) {
1026 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1027 $this->timestamp . "\n" );
1028 return false;
1029 }
1030 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1031 $data = array(
1032 'log_id' => $log_id,
1033 'log_type' => $this->type,
1034 'log_action' => $this->action,
1035 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1036 'log_user' => User::idFromName( $this->user_text ),
1037 #'log_user_text' => $this->user_text,
1038 'log_namespace' => $this->getTitle()->getNamespace(),
1039 'log_title' => $this->getTitle()->getDBkey(),
1040 'log_comment' => $this->getComment(),
1041 'log_params' => $this->params
1042 );
1043 $dbw->insert( 'logging', $data, __METHOD__ );
1044 }
1045
1046 function importUpload() {
1047 wfDebug( __METHOD__ . ": STUB\n" );
1048
1049 /**
1050 // from file revert...
1051 $source = $this->file->getArchiveVirtualUrl( $this->oldimage );
1052 $comment = $wgRequest->getText( 'wpComment' );
1053 // TODO: Preserve file properties from database instead of reloading from file
1054 $status = $this->file->upload( $source, $comment, $comment );
1055 if( $status->isGood() ) {
1056 */
1057
1058 /**
1059 // from file upload...
1060 $this->mLocalFile = wfLocalFile( $nt );
1061 $this->mDestName = $this->mLocalFile->getName();
1062 //....
1063 $status = $this->mLocalFile->upload( $this->mTempPath, $this->mComment, $pageText,
1064 File::DELETE_SOURCE, $this->mFileProps );
1065 if ( !$status->isGood() ) {
1066 $resultDetails = array( 'internal' => $status->getWikiText() );
1067 */
1068
1069 // @todo Fixme: it may create a page without our desire, also wrong potentially.
1070 // and, it will record a *current* upload, but we might want an archive version here
1071
1072 $file = wfLocalFile( $this->getTitle() );
1073 if( !$file ) {
1074 wfDebug( "IMPORT: Bad file. :(\n" );
1075 return false;
1076 }
1077
1078 $source = $this->downloadSource();
1079 if( !$source ) {
1080 wfDebug( "IMPORT: Could not fetch remote file. :(\n" );
1081 return false;
1082 }
1083
1084 $user = User::newFromName( $this->user_text );
1085
1086 $status = $file->upload( $source,
1087 $this->getComment(),
1088 $this->getComment(), // Initial page, if none present...
1089 File::DELETE_SOURCE,
1090 false, // props...
1091 $this->getTimestamp(),
1092 is_object( $user ) ? ( $user->isLoggedIn() ? $user : null ) : null );
1093
1094 if( $status->isGood() ) {
1095 // yay?
1096 wfDebug( "IMPORT: is ok?\n" );
1097 return true;
1098 }
1099
1100 wfDebug( "IMPORT: is bad? " . $status->getXml() . "\n" );
1101 return false;
1102
1103 }
1104
1105 function downloadSource() {
1106 global $wgEnableUploads;
1107 if( !$wgEnableUploads ) {
1108 return false;
1109 }
1110
1111 $tempo = tempnam( wfTempDir(), 'download' );
1112 $f = fopen( $tempo, 'wb' );
1113 if( !$f ) {
1114 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1115 return false;
1116 }
1117
1118 // @todo Fixme!
1119 $src = $this->getSrc();
1120 $data = Http::get( $src );
1121 if( !$data ) {
1122 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1123 fclose( $f );
1124 unlink( $tempo );
1125 return false;
1126 }
1127
1128 fwrite( $f, $data );
1129 fclose( $f );
1130
1131 return $tempo;
1132 }
1133
1134 }
1135
1136 /**
1137 * @todo document (e.g. one-sentence class description).
1138 * @ingroup SpecialPage
1139 */
1140 class ImportStringSource {
1141 function __construct( $string ) {
1142 $this->mString = $string;
1143 $this->mRead = false;
1144 }
1145
1146 function atEnd() {
1147 return $this->mRead;
1148 }
1149
1150 function readChunk() {
1151 if( $this->atEnd() ) {
1152 return false;
1153 } else {
1154 $this->mRead = true;
1155 return $this->mString;
1156 }
1157 }
1158 }
1159
1160 /**
1161 * @todo document (e.g. one-sentence class description).
1162 * @ingroup SpecialPage
1163 */
1164 class ImportStreamSource {
1165 function __construct( $handle ) {
1166 $this->mHandle = $handle;
1167 }
1168
1169 function atEnd() {
1170 return feof( $this->mHandle );
1171 }
1172
1173 function readChunk() {
1174 return fread( $this->mHandle, 32768 );
1175 }
1176
1177 static function newFromFile( $filename ) {
1178 $file = @fopen( $filename, 'rt' );
1179 if( !$file ) {
1180 return Status::newFatal( "importcantopen" );
1181 }
1182 return Status::newGood( new ImportStreamSource( $file ) );
1183 }
1184
1185 static function newFromUpload( $fieldname = "xmlimport" ) {
1186 $upload =& $_FILES[$fieldname];
1187
1188 if( !isset( $upload ) || !$upload['name'] ) {
1189 return Status::newFatal( 'importnofile' );
1190 }
1191 if( !empty( $upload['error'] ) ) {
1192 switch($upload['error']){
1193 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1194 return Status::newFatal( 'importuploaderrorsize' );
1195 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1196 return Status::newFatal( 'importuploaderrorsize' );
1197 case 3: # The uploaded file was only partially uploaded
1198 return Status::newFatal( 'importuploaderrorpartial' );
1199 case 6: #Missing a temporary folder.
1200 return Status::newFatal( 'importuploaderrortemp' );
1201 # case else: # Currently impossible
1202 }
1203
1204 }
1205 $fname = $upload['tmp_name'];
1206 if( is_uploaded_file( $fname ) ) {
1207 return ImportStreamSource::newFromFile( $fname );
1208 } else {
1209 return Status::newFatal( 'importnofile' );
1210 }
1211 }
1212
1213 static function newFromURL( $url, $method = 'GET' ) {
1214 wfDebug( __METHOD__ . ": opening $url\n" );
1215 # Use the standard HTTP fetch function; it times out
1216 # quicker and sorts out user-agent problems which might
1217 # otherwise prevent importing from large sites, such
1218 # as the Wikimedia cluster, etc.
1219 $data = Http::request( $method, $url );
1220 if( $data !== false ) {
1221 $file = tmpfile();
1222 fwrite( $file, $data );
1223 fflush( $file );
1224 fseek( $file, 0 );
1225 return Status::newGood( new ImportStreamSource( $file ) );
1226 } else {
1227 return Status::newFatal( 'importcantopen' );
1228 }
1229 }
1230
1231 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1232 if( $page == '' ) {
1233 return Status::newFatal( 'import-noarticle' );
1234 }
1235 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1236 if( is_null( $link ) || $link->getInterwiki() == '' ) {
1237 return Status::newFatal( 'importbadinterwiki' );
1238 } else {
1239 $params = array();
1240 if ( $history ) $params['history'] = 1;
1241 if ( $templates ) $params['templates'] = 1;
1242 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1243 $url = $link->getFullUrl( $params );
1244 # For interwikis, use POST to avoid redirects.
1245 return ImportStreamSource::newFromURL( $url, "POST" );
1246 }
1247 }
1248 }