(Bug 25872) Rename HttpRequest class to MWHttpRequest to avoid conflict with php...
[lhc/web/wiklou.git] / includes / upload / UploadBase.php
1 <?php
2 /**
3 * @file
4 * @ingroup upload
5 *
6 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
7 * The frontends are formed by ApiUpload and SpecialUpload.
8 *
9 * See also includes/docs/upload.txt
10 *
11 * @author Brion Vibber
12 * @author Bryan Tong Minh
13 * @author Michael Dale
14 */
15
16 abstract class UploadBase {
17 protected $mTempPath;
18 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
19 protected $mTitle = false, $mTitleError = 0;
20 protected $mFilteredName, $mFinalExtension;
21 protected $mLocalFile;
22
23 const SUCCESS = 0;
24 const OK = 0;
25 const EMPTY_FILE = 3;
26 const MIN_LENGTH_PARTNAME = 4;
27 const ILLEGAL_FILENAME = 5;
28 const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyPermissions()
29 const FILETYPE_MISSING = 8;
30 const FILETYPE_BADTYPE = 9;
31 const VERIFICATION_ERROR = 10;
32
33 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
34 const UPLOAD_VERIFICATION_ERROR = 11;
35 const HOOK_ABORTED = 11;
36 const FILE_TOO_LARGE = 12;
37
38 const SESSION_VERSION = 2;
39 const SESSION_KEYNAME = 'wsUploadData';
40
41 static public function getSessionKeyname() {
42 return self::SESSION_KEYNAME;
43 }
44
45 public function getVerificationErrorCode( $error ) {
46 $code_to_status = array(self::EMPTY_FILE => 'empty-file',
47 self::FILE_TOO_LARGE => 'file-too-large',
48 self::FILETYPE_MISSING => 'filetype-missing',
49 self::FILETYPE_BADTYPE => 'filetype-banned',
50 self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
51 self::ILLEGAL_FILENAME => 'illegal-filename',
52 self::OVERWRITE_EXISTING_FILE => 'overwrite',
53 self::VERIFICATION_ERROR => 'verification-error',
54 self::HOOK_ABORTED => 'hookaborted',
55 );
56 if( isset( $code_to_status[$error] ) ) {
57 return $code_to_status[$error];
58 }
59
60 return 'unknown-error';
61 }
62
63 /**
64 * Returns true if uploads are enabled.
65 * Can be override by subclasses.
66 */
67 public static function isEnabled() {
68 global $wgEnableUploads;
69 if ( !$wgEnableUploads ) {
70 return false;
71 }
72
73 # Check php's file_uploads setting
74 if( !wfIniGetBool( 'file_uploads' ) ) {
75 return false;
76 }
77 return true;
78 }
79
80 /**
81 * Returns an array of permissions that is required to upload a file
82 *
83 * @return array
84 */
85 public static function getRequiredPermissions() {
86 return array( 'upload', 'edit' );
87 }
88 /**
89 * Returns true if the user can use this upload module or else a string
90 * identifying the missing permission.
91 * Can be overriden by subclasses.
92 */
93 public static function isAllowed( $user ) {
94 foreach ( self::getRequiredPermissions() as $permission ) {
95 if ( !$user->isAllowed( $permission ) ) {
96 return $permission;
97 }
98 }
99 return true;
100 }
101
102 // Upload handlers. Should probably just be a global.
103 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
104
105 /**
106 * Create a form of UploadBase depending on wpSourceType and initializes it
107 */
108 public static function createFromRequest( &$request, $type = null ) {
109 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
110
111 if( !$type ) {
112 return null;
113 }
114
115 // Get the upload class
116 $type = ucfirst( $type );
117
118 // Give hooks the chance to handle this request
119 $className = null;
120 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
121 if ( is_null( $className ) ) {
122 $className = 'UploadFrom' . $type;
123 wfDebug( __METHOD__ . ": class name: $className\n" );
124 if( !in_array( $type, self::$uploadHandlers ) ) {
125 return null;
126 }
127 }
128
129 // Check whether this upload class is enabled
130 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
131 return null;
132 }
133
134 // Check whether the request is valid
135 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
136 return null;
137 }
138
139 $handler = new $className;
140
141 $handler->initializeFromRequest( $request );
142 return $handler;
143 }
144
145 /**
146 * Check whether a request if valid for this handler
147 */
148 public static function isValidRequest( $request ) {
149 return false;
150 }
151
152 public function __construct() {}
153
154 /**
155 * Initialize the path information
156 * @param $name string the desired destination name
157 * @param $tempPath string the temporary path
158 * @param $fileSize int the file size
159 * @param $removeTempFile bool (false) remove the temporary file?
160 * @return null
161 */
162 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
163 $this->mDesiredDestName = $name;
164 $this->mTempPath = $tempPath;
165 $this->mFileSize = $fileSize;
166 $this->mRemoveTempFile = $removeTempFile;
167 }
168
169 /**
170 * Initialize from a WebRequest. Override this in a subclass.
171 */
172 public abstract function initializeFromRequest( &$request );
173
174 /**
175 * Fetch the file. Usually a no-op
176 */
177 public function fetchFile() {
178 return Status::newGood();
179 }
180
181 /**
182 * Return true if the file is empty
183 * @return bool
184 */
185 public function isEmptyFile() {
186 return empty( $this->mFileSize );
187 }
188
189 /**
190 * Return the file size
191 * @return integer
192 */
193 public function getFileSize() {
194 return $this->mFileSize;
195 }
196
197 /**
198 * Append a file to the Repo file
199 *
200 * @param $srcPath String: path to source file
201 * @param $toAppendPath String: path to the Repo file that will be appended to.
202 * @return Status Status
203 */
204 protected function appendToUploadFile( $srcPath, $toAppendPath ) {
205 $repo = RepoGroup::singleton()->getLocalRepo();
206 $status = $repo->append( $srcPath, $toAppendPath );
207 return $status;
208 }
209
210 /**
211 * @param $srcPath String: the source path
212 * @return the real path if it was a virtual URL
213 */
214 function getRealPath( $srcPath ) {
215 $repo = RepoGroup::singleton()->getLocalRepo();
216 if ( $repo->isVirtualUrl( $srcPath ) ) {
217 return $repo->resolveVirtualUrl( $srcPath );
218 }
219 return $srcPath;
220 }
221
222 /**
223 * Verify whether the upload is sane.
224 * @return mixed self::OK or else an array with error information
225 */
226 public function verifyUpload() {
227 /**
228 * If there was no filename or a zero size given, give up quick.
229 */
230 if( $this->isEmptyFile() ) {
231 return array( 'status' => self::EMPTY_FILE );
232 }
233
234 /**
235 * Honor $wgMaxUploadSize
236 */
237 global $wgMaxUploadSize;
238 if( $this->mFileSize > $wgMaxUploadSize ) {
239 return array(
240 'status' => self::FILE_TOO_LARGE,
241 'max' => $wgMaxUploadSize,
242 );
243 }
244
245 /**
246 * Look at the contents of the file; if we can recognize the
247 * type but it's corrupt or data of the wrong type, we should
248 * probably not accept it.
249 */
250 $verification = $this->verifyFile();
251 if( $verification !== true ) {
252 return array(
253 'status' => self::VERIFICATION_ERROR,
254 'details' => $verification
255 );
256 }
257
258 /**
259 * Make sure this file can be created
260 */
261 $result = $this->validateName();
262 if( $result !== true ) {
263 return $result;
264 }
265
266 $error = '';
267 if( !wfRunHooks( 'UploadVerification',
268 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
269 return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
270 }
271
272 return array( 'status' => self::OK );
273 }
274
275 /**
276 * Verify that the name is valid and, if necessary, that we can overwrite
277 *
278 * @return mixed true if valid, otherwise and array with 'status'
279 * and other keys
280 **/
281 protected function validateName() {
282 $nt = $this->getTitle();
283 if( is_null( $nt ) ) {
284 $result = array( 'status' => $this->mTitleError );
285 if( $this->mTitleError == self::ILLEGAL_FILENAME ) {
286 $result['filtered'] = $this->mFilteredName;
287 }
288 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
289 $result['finalExt'] = $this->mFinalExtension;
290 }
291 return $result;
292 }
293 $this->mDestName = $this->getLocalFile()->getName();
294
295 return true;
296 }
297
298 /**
299 * Verify the mime type
300 *
301 * @param $mime string representing the mime
302 * @return mixed true if the file is verified, an array otherwise
303 */
304 protected function verifyMimeType( $mime ) {
305 global $wgVerifyMimeType;
306 if ( $wgVerifyMimeType ) {
307 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
308 if ( !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
309 return array( 'filetype-mime-mismatch' );
310 }
311
312 global $wgMimeTypeBlacklist;
313 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
314 return array( 'filetype-badmime', $mime );
315 }
316
317 # Check IE type
318 $fp = fopen( $this->mTempPath, 'rb' );
319 $chunk = fread( $fp, 256 );
320 fclose( $fp );
321
322 $magic = MimeMagic::singleton();
323 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
324 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
325 foreach ( $ieTypes as $ieType ) {
326 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
327 return array( 'filetype-bad-ie-mime', $ieType );
328 }
329 }
330 }
331
332 return true;
333 }
334
335 /**
336 * Verifies that it's ok to include the uploaded file
337 *
338 * @return mixed true of the file is verified, array otherwise.
339 */
340 protected function verifyFile() {
341 # get the title, even though we are doing nothing with it, because
342 # we need to populate mFinalExtension
343 $this->getTitle();
344
345 $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
346 $this->checkMacBinary();
347
348 # check mime type, if desired
349 $mime = $this->mFileProps[ 'file-mime' ];
350 $status = $this->verifyMimeType( $mime );
351 if ( $status !== true ) {
352 return $status;
353 }
354
355 # check for htmlish code and javascript
356 if( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
357 return array( 'uploadscripted' );
358 }
359 if( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
360 if( $this->detectScriptInSvg( $this->mTempPath ) ) {
361 return array( 'uploadscripted' );
362 }
363 }
364
365 /**
366 * Scan the uploaded file for viruses
367 */
368 $virus = $this->detectVirus( $this->mTempPath );
369 if ( $virus ) {
370 return array( 'uploadvirus', $virus );
371 }
372
373 $handler = MediaHandler::getHandler( $mime );
374 if ( $handler ) {
375 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
376 if ( !$handlerStatus->isOK() ) {
377 $errors = $handlerStatus->getErrorsArray();
378 return reset( $errors );
379 }
380 }
381
382 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
383 if ( $status !== true ) {
384 return $status;
385 }
386
387 wfDebug( __METHOD__ . ": all clear; passing.\n" );
388 return true;
389 }
390
391 /**
392 * Check whether the user can edit, upload and create the image. This
393 * checks only against the current title; if it returns errors, it may
394 * very well be that another title will not give errors. Therefore
395 * isAllowed() should be called as well for generic is-user-blocked or
396 * can-user-upload checking.
397 *
398 * @param $user the User object to verify the permissions against
399 * @return mixed An array as returned by getUserPermissionsErrors or true
400 * in case the user has proper permissions.
401 */
402 public function verifyPermissions( $user ) {
403 /**
404 * If the image is protected, non-sysop users won't be able
405 * to modify it by uploading a new revision.
406 */
407 $nt = $this->getTitle();
408 if( is_null( $nt ) ) {
409 return true;
410 }
411 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
412 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
413 if ( $nt->exists() ) {
414 $permErrorsCreate = $nt->getUserPermissionsErrors( 'createpage', $user );
415 } else {
416 $permErrorsCreate = array();
417 }
418 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
419 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
420 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
421 return $permErrors;
422 }
423
424 $overwriteError = $this->checkOverwrite( $user );
425 if ( $overwriteError !== true ) {
426 return array( array( $overwriteError ) );
427 }
428
429 return true;
430 }
431
432 /**
433 * Check for non fatal problems with the file
434 *
435 * @return Array of warnings
436 */
437 public function checkWarnings() {
438 $warnings = array();
439
440 $localFile = $this->getLocalFile();
441 $filename = $localFile->getName();
442 $n = strrpos( $filename, '.' );
443 $partname = $n ? substr( $filename, 0, $n ) : $filename;
444
445 /**
446 * Check whether the resulting filename is different from the desired one,
447 * but ignore things like ucfirst() and spaces/underscore things
448 */
449 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
450 $comparableName = Title::capitalize( $comparableName, NS_FILE );
451
452 if( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
453 $warnings['badfilename'] = $filename;
454 }
455
456 // Check whether the file extension is on the unwanted list
457 global $wgCheckFileExtensions, $wgFileExtensions;
458 if ( $wgCheckFileExtensions ) {
459 if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) {
460 $warnings['filetype-unwanted-type'] = $this->mFinalExtension;
461 }
462 }
463
464 global $wgUploadSizeWarning;
465 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
466 $warnings['large-file'] = $wgUploadSizeWarning;
467 }
468
469 if ( $this->mFileSize == 0 ) {
470 $warnings['emptyfile'] = true;
471 }
472
473 $exists = self::getExistsWarning( $localFile );
474 if( $exists !== false ) {
475 $warnings['exists'] = $exists;
476 }
477
478 // Check dupes against existing files
479 $hash = File::sha1Base36( $this->mTempPath );
480 $dupes = RepoGroup::singleton()->findBySha1( $hash );
481 $title = $this->getTitle();
482 // Remove all matches against self
483 foreach ( $dupes as $key => $dupe ) {
484 if( $title->equals( $dupe->getTitle() ) ) {
485 unset( $dupes[$key] );
486 }
487 }
488 if( $dupes ) {
489 $warnings['duplicate'] = $dupes;
490 }
491
492 // Check dupes against archives
493 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
494 if ( $archivedImage->getID() > 0 ) {
495 $warnings['duplicate-archive'] = $archivedImage->getName();
496 }
497
498 return $warnings;
499 }
500
501 /**
502 * Really perform the upload. Stores the file in the local repo, watches
503 * if necessary and runs the UploadComplete hook.
504 *
505 * @return mixed Status indicating the whether the upload succeeded.
506 */
507 public function performUpload( $comment, $pageText, $watch, $user ) {
508 wfDebug( "\n\n\performUpload: sum: " . $comment . ' c: ' . $pageText .
509 ' w: ' . $watch );
510 $status = $this->getLocalFile()->upload( $this->mTempPath, $comment, $pageText,
511 File::DELETE_SOURCE, $this->mFileProps, false, $user );
512
513 if( $status->isGood() ) {
514 if ( $watch ) {
515 $user->addWatch( $this->getLocalFile()->getTitle() );
516 }
517
518 wfRunHooks( 'UploadComplete', array( &$this ) );
519 }
520
521 return $status;
522 }
523
524 /**
525 * Returns the title of the file to be uploaded. Sets mTitleError in case
526 * the name was illegal.
527 *
528 * @return Title The title of the file or null in case the name was illegal
529 */
530 public function getTitle() {
531 if ( $this->mTitle !== false ) {
532 return $this->mTitle;
533 }
534
535 /**
536 * Chop off any directories in the given filename. Then
537 * filter out illegal characters, and try to make a legible name
538 * out of it. We'll strip some silently that Title would die on.
539 */
540 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mDesiredDestName );
541 /* Normalize to title form before we do any further processing */
542 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
543 if( is_null( $nt ) ) {
544 $this->mTitleError = self::ILLEGAL_FILENAME;
545 return $this->mTitle = null;
546 }
547 $this->mFilteredName = $nt->getDBkey();
548
549 /**
550 * We'll want to blacklist against *any* 'extension', and use
551 * only the final one for the whitelist.
552 */
553 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
554
555 if( count( $ext ) ) {
556 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
557 } else {
558 $this->mFinalExtension = '';
559 }
560
561 /* Don't allow users to override the blacklist (check file extension) */
562 global $wgCheckFileExtensions, $wgStrictFileExtensions;
563 global $wgFileExtensions, $wgFileBlacklist;
564 if ( $this->mFinalExtension == '' ) {
565 $this->mTitleError = self::FILETYPE_MISSING;
566 return $this->mTitle = null;
567 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
568 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
569 !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) ) {
570 $this->mTitleError = self::FILETYPE_BADTYPE;
571 return $this->mTitle = null;
572 }
573
574 # If there was more than one "extension", reassemble the base
575 # filename to prevent bogus complaints about length
576 if( count( $ext ) > 1 ) {
577 for( $i = 0; $i < count( $ext ) - 1; $i++ ) {
578 $partname .= '.' . $ext[$i];
579 }
580 }
581
582 if( strlen( $partname ) < 1 ) {
583 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
584 return $this->mTitle = null;
585 }
586
587 return $this->mTitle = $nt;
588 }
589
590 /**
591 * Return the local file and initializes if necessary.
592 */
593 public function getLocalFile() {
594 if( is_null( $this->mLocalFile ) ) {
595 $nt = $this->getTitle();
596 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
597 }
598 return $this->mLocalFile;
599 }
600
601 /**
602 * NOTE: Probably should be deprecated in favor of UploadStash, but this is sometimes
603 * called outside that context.
604 *
605 * Stash a file in a temporary directory for later processing
606 * after the user has confirmed it.
607 *
608 * If the user doesn't explicitly cancel or accept, these files
609 * can accumulate in the temp directory.
610 *
611 * @param $saveName String: the destination filename
612 * @param $tempSrc String: the source temporary file to save
613 * @return String: full path the stashed file, or false on failure
614 */
615 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
616 $repo = RepoGroup::singleton()->getLocalRepo();
617 $status = $repo->storeTemp( $saveName, $tempSrc );
618 return $status;
619 }
620
621 /**
622 * If the user does not supply all necessary information in the first upload form submission (either by accident or
623 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
624 *
625 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
626 * into the user's session.
627 * This method returns the file object, which also has a 'sessionKey' property which can be passed through a form or
628 * API request to find this stashed file again.
629 *
630 * @param {String}: $key (optional) the session key used to find the file info again. If not supplied, a key will be autogenerated.
631 * @return {File}: stashed file
632 */
633 public function stashSessionFile( $key = null ) {
634 $stash = new UploadStash();
635 $data = array(
636 'mFileProps' => $this->mFileProps
637 );
638 $file = $stash->stashFile( $this->mTempPath, $data, $key );
639 // TODO should we change the "local file" here?
640 // $this->mLocalFile = $file;
641 return $file;
642 }
643
644 /**
645 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashSessionFile().
646 *
647 * @param {String}: $key (optional) the session key used to find the file info again. If not supplied, a key will be autogenerated.
648 * @return {String}: session key
649 */
650 public function stashSession( $key = null ) {
651 return $this->stashSessionFile( $key )->getSessionKey();
652 }
653
654 /**
655 * If we've modified the upload file we need to manually remove it
656 * on exit to clean up.
657 */
658 public function cleanupTempFile() {
659 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
660 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
661 unlink( $this->mTempPath );
662 }
663 }
664
665 public function getTempPath() {
666 return $this->mTempPath;
667 }
668
669 /**
670 * Split a file into a base name and all dot-delimited 'extensions'
671 * on the end. Some web server configurations will fall back to
672 * earlier pseudo-'extensions' to determine type and execute
673 * scripts, so the blacklist needs to check them all.
674 *
675 * @return array
676 */
677 public static function splitExtensions( $filename ) {
678 $bits = explode( '.', $filename );
679 $basename = array_shift( $bits );
680 return array( $basename, $bits );
681 }
682
683 /**
684 * Perform case-insensitive match against a list of file extensions.
685 * Returns true if the extension is in the list.
686 *
687 * @param $ext String
688 * @param $list Array
689 * @return Boolean
690 */
691 public static function checkFileExtension( $ext, $list ) {
692 return in_array( strtolower( $ext ), $list );
693 }
694
695 /**
696 * Perform case-insensitive match against a list of file extensions.
697 * Returns true if any of the extensions are in the list.
698 *
699 * @param $ext Array
700 * @param $list Array
701 * @return Boolean
702 */
703 public static function checkFileExtensionList( $ext, $list ) {
704 foreach( $ext as $e ) {
705 if( in_array( strtolower( $e ), $list ) ) {
706 return true;
707 }
708 }
709 return false;
710 }
711
712 /**
713 * Checks if the mime type of the uploaded file matches the file extension.
714 *
715 * @param $mime String: the mime type of the uploaded file
716 * @param $extension String: the filename extension that the file is to be served with
717 * @return Boolean
718 */
719 public static function verifyExtension( $mime, $extension ) {
720 $magic = MimeMagic::singleton();
721
722 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
723 if ( !$magic->isRecognizableExtension( $extension ) ) {
724 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
725 "unrecognized extension '$extension', can't verify\n" );
726 return true;
727 } else {
728 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
729 "recognized extension '$extension', so probably invalid file\n" );
730 return false;
731 }
732
733 $match = $magic->isMatchingExtension( $extension, $mime );
734
735 if ( $match === null ) {
736 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
737 return true;
738 } elseif( $match === true ) {
739 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
740
741 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
742 return true;
743
744 } else {
745 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
746 return false;
747 }
748 }
749
750 /**
751 * Heuristic for detecting files that *could* contain JavaScript instructions or
752 * things that may look like HTML to a browser and are thus
753 * potentially harmful. The present implementation will produce false
754 * positives in some situations.
755 *
756 * @param $file String: pathname to the temporary upload file
757 * @param $mime String: the mime type of the file
758 * @param $extension String: the extension of the file
759 * @return Boolean: true if the file contains something looking like embedded scripts
760 */
761 public static function detectScript( $file, $mime, $extension ) {
762 global $wgAllowTitlesInSVG;
763
764 # ugly hack: for text files, always look at the entire file.
765 # For binary field, just check the first K.
766
767 if( strpos( $mime,'text/' ) === 0 ) {
768 $chunk = file_get_contents( $file );
769 } else {
770 $fp = fopen( $file, 'rb' );
771 $chunk = fread( $fp, 1024 );
772 fclose( $fp );
773 }
774
775 $chunk = strtolower( $chunk );
776
777 if( !$chunk ) {
778 return false;
779 }
780
781 # decode from UTF-16 if needed (could be used for obfuscation).
782 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
783 $enc = 'UTF-16BE';
784 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
785 $enc = 'UTF-16LE';
786 } else {
787 $enc = null;
788 }
789
790 if( $enc ) {
791 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
792 }
793
794 $chunk = trim( $chunk );
795
796 # FIXME: convert from UTF-16 if necessarry!
797 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
798
799 # check for HTML doctype
800 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
801 return true;
802 }
803
804 /**
805 * Internet Explorer for Windows performs some really stupid file type
806 * autodetection which can cause it to interpret valid image files as HTML
807 * and potentially execute JavaScript, creating a cross-site scripting
808 * attack vectors.
809 *
810 * Apple's Safari browser also performs some unsafe file type autodetection
811 * which can cause legitimate files to be interpreted as HTML if the
812 * web server is not correctly configured to send the right content-type
813 * (or if you're really uploading plain text and octet streams!)
814 *
815 * Returns true if IE is likely to mistake the given file for HTML.
816 * Also returns true if Safari would mistake the given file for HTML
817 * when served with a generic content-type.
818 */
819 $tags = array(
820 '<a href',
821 '<body',
822 '<head',
823 '<html', #also in safari
824 '<img',
825 '<pre',
826 '<script', #also in safari
827 '<table'
828 );
829
830 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
831 $tags[] = '<title';
832 }
833
834 foreach( $tags as $tag ) {
835 if( false !== strpos( $chunk, $tag ) ) {
836 return true;
837 }
838 }
839
840 /*
841 * look for JavaScript
842 */
843
844 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
845 $chunk = Sanitizer::decodeCharReferences( $chunk );
846
847 # look for script-types
848 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
849 return true;
850 }
851
852 # look for html-style script-urls
853 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
854 return true;
855 }
856
857 # look for css-style script-urls
858 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
859 return true;
860 }
861
862 wfDebug( __METHOD__ . ": no scripts found\n" );
863 return false;
864 }
865
866 protected function detectScriptInSvg( $filename ) {
867 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
868 return $check->filterMatch;
869 }
870
871 /**
872 * @todo Replace this with a whitelist filter!
873 */
874 public function checkSvgScriptCallback( $element, $attribs ) {
875 $stripped = $this->stripXmlNamespace( $element );
876
877 if( $stripped == 'script' ) {
878 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
879 return true;
880 }
881
882 foreach( $attribs as $attrib => $value ) {
883 $stripped = $this->stripXmlNamespace( $attrib );
884 if( substr( $stripped, 0, 2 ) == 'on' ) {
885 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
886 return true;
887 }
888 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
889 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
890 return true;
891 }
892 }
893 }
894
895 private function stripXmlNamespace( $name ) {
896 // 'http://www.w3.org/2000/svg:script' -> 'script'
897 $parts = explode( ':', strtolower( $name ) );
898 return array_pop( $parts );
899 }
900
901 /**
902 * Generic wrapper function for a virus scanner program.
903 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
904 * $wgAntivirusRequired may be used to deny upload if the scan fails.
905 *
906 * @param $file String: pathname to the temporary upload file
907 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
908 * or a string containing feedback from the virus scanner if a virus was found.
909 * If textual feedback is missing but a virus was found, this function returns true.
910 */
911 public static function detectVirus( $file ) {
912 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
913
914 if ( !$wgAntivirus ) {
915 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
916 return null;
917 }
918
919 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
920 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
921 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
922 array( 'virus-badscanner', $wgAntivirus ) );
923 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
924 }
925
926 # look up scanner configuration
927 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
928 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
929 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
930 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
931
932 if ( strpos( $command, "%f" ) === false ) {
933 # simple pattern: append file to scan
934 $command .= " " . wfEscapeShellArg( $file );
935 } else {
936 # complex pattern: replace "%f" with file to scan
937 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
938 }
939
940 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
941
942 # execute virus scanner
943 $exitCode = false;
944
945 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
946 # that does not seem to be worth the pain.
947 # Ask me (Duesentrieb) about it if it's ever needed.
948 $output = wfShellExec( "$command 2>&1", $exitCode );
949
950 # map exit code to AV_xxx constants.
951 $mappedCode = $exitCode;
952 if ( $exitCodeMap ) {
953 if ( isset( $exitCodeMap[$exitCode] ) ) {
954 $mappedCode = $exitCodeMap[$exitCode];
955 } elseif ( isset( $exitCodeMap["*"] ) ) {
956 $mappedCode = $exitCodeMap["*"];
957 }
958 }
959
960 if ( $mappedCode === AV_SCAN_FAILED ) {
961 # scan failed (code was mapped to false by $exitCodeMap)
962 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
963
964 if ( $wgAntivirusRequired ) {
965 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
966 } else {
967 return null;
968 }
969 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
970 # scan failed because filetype is unknown (probably imune)
971 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
972 return null;
973 } elseif ( $mappedCode === AV_NO_VIRUS ) {
974 # no virus found
975 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
976 return false;
977 } else {
978 $output = trim( $output );
979
980 if ( !$output ) {
981 $output = true; #if there's no output, return true
982 } elseif ( $msgPattern ) {
983 $groups = array();
984 if ( preg_match( $msgPattern, $output, $groups ) ) {
985 if ( $groups[1] ) {
986 $output = $groups[1];
987 }
988 }
989 }
990
991 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
992 return $output;
993 }
994 }
995
996 /**
997 * Check if the temporary file is MacBinary-encoded, as some uploads
998 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
999 * If so, the data fork will be extracted to a second temporary file,
1000 * which will then be checked for validity and either kept or discarded.
1001 */
1002 private function checkMacBinary() {
1003 $macbin = new MacBinary( $this->mTempPath );
1004 if( $macbin->isValid() ) {
1005 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
1006 $dataHandle = fopen( $dataFile, 'wb' );
1007
1008 wfDebug( __METHOD__ . ": Extracting MacBinary data fork to $dataFile\n" );
1009 $macbin->extractData( $dataHandle );
1010
1011 $this->mTempPath = $dataFile;
1012 $this->mFileSize = $macbin->dataForkLength();
1013
1014 // We'll have to manually remove the new file if it's not kept.
1015 $this->mRemoveTempFile = true;
1016 }
1017 $macbin->close();
1018 }
1019
1020 /**
1021 * Check if there's an overwrite conflict and, if so, if restrictions
1022 * forbid this user from performing the upload.
1023 *
1024 * @return mixed true on success, error string on failure
1025 */
1026 private function checkOverwrite( $user ) {
1027 // First check whether the local file can be overwritten
1028 $file = $this->getLocalFile();
1029 if( $file->exists() ) {
1030 if( !self::userCanReUpload( $user, $file ) ) {
1031 return 'fileexists-forbidden';
1032 } else {
1033 return true;
1034 }
1035 }
1036
1037 /* Check shared conflicts: if the local file does not exist, but
1038 * wfFindFile finds a file, it exists in a shared repository.
1039 */
1040 $file = wfFindFile( $this->getTitle() );
1041 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1042 return 'fileexists-shared-forbidden';
1043 }
1044
1045 return true;
1046 }
1047
1048 /**
1049 * Check if a user is the last uploader
1050 *
1051 * @param $user User object
1052 * @param $img String: image name
1053 * @return Boolean
1054 */
1055 public static function userCanReUpload( User $user, $img ) {
1056 if( $user->isAllowed( 'reupload' ) ) {
1057 return true; // non-conditional
1058 }
1059 if( !$user->isAllowed( 'reupload-own' ) ) {
1060 return false;
1061 }
1062 if( is_string( $img ) ) {
1063 $img = wfLocalFile( $img );
1064 }
1065 if ( !( $img instanceof LocalFile ) ) {
1066 return false;
1067 }
1068
1069 return $user->getId() == $img->getUser( 'id' );
1070 }
1071
1072 /**
1073 * Helper function that does various existence checks for a file.
1074 * The following checks are performed:
1075 * - The file exists
1076 * - Article with the same name as the file exists
1077 * - File exists with normalized extension
1078 * - The file looks like a thumbnail and the original exists
1079 *
1080 * @param $file The File object to check
1081 * @return mixed False if the file does not exists, else an array
1082 */
1083 public static function getExistsWarning( $file ) {
1084 if( $file->exists() ) {
1085 return array( 'warning' => 'exists', 'file' => $file );
1086 }
1087
1088 if( $file->getTitle()->getArticleID() ) {
1089 return array( 'warning' => 'page-exists', 'file' => $file );
1090 }
1091
1092 if ( $file->wasDeleted() && !$file->exists() ) {
1093 return array( 'warning' => 'was-deleted', 'file' => $file );
1094 }
1095
1096 if( strpos( $file->getName(), '.' ) == false ) {
1097 $partname = $file->getName();
1098 $extension = '';
1099 } else {
1100 $n = strrpos( $file->getName(), '.' );
1101 $extension = substr( $file->getName(), $n + 1 );
1102 $partname = substr( $file->getName(), 0, $n );
1103 }
1104 $normalizedExtension = File::normalizeExtension( $extension );
1105
1106 if ( $normalizedExtension != $extension ) {
1107 // We're not using the normalized form of the extension.
1108 // Normal form is lowercase, using most common of alternate
1109 // extensions (eg 'jpg' rather than 'JPEG').
1110 //
1111 // Check for another file using the normalized form...
1112 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1113 $file_lc = wfLocalFile( $nt_lc );
1114
1115 if( $file_lc->exists() ) {
1116 return array(
1117 'warning' => 'exists-normalized',
1118 'file' => $file,
1119 'normalizedFile' => $file_lc
1120 );
1121 }
1122 }
1123
1124 if ( self::isThumbName( $file->getName() ) ) {
1125 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1126 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $extension, NS_FILE );
1127 $file_thb = wfLocalFile( $nt_thb );
1128 if( $file_thb->exists() ) {
1129 return array(
1130 'warning' => 'thumb',
1131 'file' => $file,
1132 'thumbFile' => $file_thb
1133 );
1134 } else {
1135 // File does not exist, but we just don't like the name
1136 return array(
1137 'warning' => 'thumb-name',
1138 'file' => $file,
1139 'thumbFile' => $file_thb
1140 );
1141 }
1142 }
1143
1144
1145 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
1146 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1147 return array(
1148 'warning' => 'bad-prefix',
1149 'file' => $file,
1150 'prefix' => $prefix
1151 );
1152 }
1153 }
1154
1155 return false;
1156 }
1157
1158 /**
1159 * Helper function that checks whether the filename looks like a thumbnail
1160 */
1161 public static function isThumbName( $filename ) {
1162 $n = strrpos( $filename, '.' );
1163 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1164 return (
1165 substr( $partname , 3, 3 ) == 'px-' ||
1166 substr( $partname , 2, 3 ) == 'px-'
1167 ) &&
1168 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1169 }
1170
1171 /**
1172 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1173 *
1174 * @return array list of prefixes
1175 */
1176 public static function getFilenamePrefixBlacklist() {
1177 $blacklist = array();
1178 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1179 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
1180 $lines = explode( "\n", $message );
1181 foreach( $lines as $line ) {
1182 // Remove comment lines
1183 $comment = substr( trim( $line ), 0, 1 );
1184 if ( $comment == '#' || $comment == '' ) {
1185 continue;
1186 }
1187 // Remove additional comments after a prefix
1188 $comment = strpos( $line, '#' );
1189 if ( $comment > 0 ) {
1190 $line = substr( $line, 0, $comment-1 );
1191 }
1192 $blacklist[] = trim( $line );
1193 }
1194 }
1195 return $blacklist;
1196 }
1197
1198 /**
1199 * Gets image info about the file just uploaded.
1200 *
1201 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1202 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1203 * with the appropriate format, presumably.
1204 *
1205 * @param {ApiResult}
1206 * @return {Array} image info
1207 */
1208 public function getImageInfo( $result ) {
1209 $file = $this->getLocalFile();
1210 $imParam = ApiQueryImageInfo::getPropertyNames();
1211 return ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1212 }
1213
1214
1215 public function convertVerifyErrorToStatus( $error ) {
1216 $code = $error['status'];
1217 unset( $code['status'] );
1218 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1219 }
1220 }