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