* Removed Skin::reallyGenerateUserStylesheet() nothing uses it and nothing overrides it
[mediawiki.git] / includes / upload / UploadBase.php
blob0741326bb116e2d9e566b6efd939e282c63ad550
1 <?php
2 /**
3 * @file
4 * @ingroup upload
6 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
7 * The frontends are formed by ApiUpload and SpecialUpload.
9 * See also includes/docs/upload.txt
11 * @author Brion Vibber
12 * @author Bryan Tong Minh
13 * @author Michael Dale
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, $mFileSize, $mFileProps;
22 protected $mBlackListedExtensions;
23 protected $mJavaDetected;
25 const SUCCESS = 0;
26 const OK = 0;
27 const EMPTY_FILE = 3;
28 const MIN_LENGTH_PARTNAME = 4;
29 const ILLEGAL_FILENAME = 5;
30 const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
31 const FILETYPE_MISSING = 8;
32 const FILETYPE_BADTYPE = 9;
33 const VERIFICATION_ERROR = 10;
35 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
36 const UPLOAD_VERIFICATION_ERROR = 11;
37 const HOOK_ABORTED = 11;
38 const FILE_TOO_LARGE = 12;
40 const SESSION_VERSION = 2;
41 const SESSION_KEYNAME = 'wsUploadData';
43 static public function getSessionKeyname() {
44 return self::SESSION_KEYNAME;
47 public function getVerificationErrorCode( $error ) {
48 $code_to_status = array(self::EMPTY_FILE => 'empty-file',
49 self::FILE_TOO_LARGE => 'file-too-large',
50 self::FILETYPE_MISSING => 'filetype-missing',
51 self::FILETYPE_BADTYPE => 'filetype-banned',
52 self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
53 self::ILLEGAL_FILENAME => 'illegal-filename',
54 self::OVERWRITE_EXISTING_FILE => 'overwrite',
55 self::VERIFICATION_ERROR => 'verification-error',
56 self::HOOK_ABORTED => 'hookaborted',
58 if( isset( $code_to_status[$error] ) ) {
59 return $code_to_status[$error];
62 return 'unknown-error';
65 /**
66 * Returns true if uploads are enabled.
67 * Can be override by subclasses.
69 public static function isEnabled() {
70 global $wgEnableUploads;
71 if ( !$wgEnableUploads ) {
72 return false;
75 # Check php's file_uploads setting
76 if( !wfIniGetBool( 'file_uploads' ) ) {
77 return false;
79 return true;
82 /**
83 * Returns true if the user can use this upload module or else a string
84 * identifying the missing permission.
85 * Can be overriden by subclasses.
87 * @param $user User
89 public static function isAllowed( $user ) {
90 foreach ( array( 'upload', 'edit' ) as $permission ) {
91 if ( !$user->isAllowed( $permission ) ) {
92 return $permission;
95 return true;
98 // Upload handlers. Should probably just be a global.
99 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
102 * Create a form of UploadBase depending on wpSourceType and initializes it
104 * @param $request WebRequest
106 public static function createFromRequest( &$request, $type = null ) {
107 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
109 if( !$type ) {
110 return null;
113 // Get the upload class
114 $type = ucfirst( $type );
116 // Give hooks the chance to handle this request
117 $className = null;
118 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
119 if ( is_null( $className ) ) {
120 $className = 'UploadFrom' . $type;
121 wfDebug( __METHOD__ . ": class name: $className\n" );
122 if( !in_array( $type, self::$uploadHandlers ) ) {
123 return null;
127 // Check whether this upload class is enabled
128 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
129 return null;
132 // Check whether the request is valid
133 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
134 return null;
137 $handler = new $className;
139 $handler->initializeFromRequest( $request );
140 return $handler;
144 * Check whether a request if valid for this handler
146 public static function isValidRequest( $request ) {
147 return false;
150 public function __construct() {}
153 * Returns the upload type. Should be overridden by child classes
155 * @since 1.18
156 * @return string
158 public function getSourceType() { return null; }
161 * Initialize the path information
162 * @param $name string the desired destination name
163 * @param $tempPath string the temporary path
164 * @param $fileSize int the file size
165 * @param $removeTempFile bool (false) remove the temporary file?
166 * @return null
168 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
169 $this->mDesiredDestName = $name;
170 $this->mTempPath = $tempPath;
171 $this->mFileSize = $fileSize;
172 $this->mRemoveTempFile = $removeTempFile;
176 * Initialize from a WebRequest. Override this in a subclass.
178 public abstract function initializeFromRequest( &$request );
181 * Fetch the file. Usually a no-op
183 public function fetchFile() {
184 return Status::newGood();
188 * Return true if the file is empty
189 * @return bool
191 public function isEmptyFile() {
192 return empty( $this->mFileSize );
196 * Return the file size
197 * @return integer
199 public function getFileSize() {
200 return $this->mFileSize;
204 * Append a file to the Repo file
206 * @param $srcPath String: path to source file
207 * @param $toAppendPath String: path to the Repo file that will be appended to.
208 * @return Status Status
210 protected function appendToUploadFile( $srcPath, $toAppendPath ) {
211 $repo = RepoGroup::singleton()->getLocalRepo();
212 $status = $repo->append( $srcPath, $toAppendPath );
213 return $status;
217 * @param $srcPath String: the source path
218 * @return the real path if it was a virtual URL
220 function getRealPath( $srcPath ) {
221 $repo = RepoGroup::singleton()->getLocalRepo();
222 if ( $repo->isVirtualUrl( $srcPath ) ) {
223 return $repo->resolveVirtualUrl( $srcPath );
225 return $srcPath;
229 * Verify whether the upload is sane.
230 * @return mixed self::OK or else an array with error information
232 public function verifyUpload() {
234 * If there was no filename or a zero size given, give up quick.
236 if( $this->isEmptyFile() ) {
237 return array( 'status' => self::EMPTY_FILE );
241 * Honor $wgMaxUploadSize
243 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
244 if( $this->mFileSize > $maxSize ) {
245 return array(
246 'status' => self::FILE_TOO_LARGE,
247 'max' => $maxSize,
252 * Look at the contents of the file; if we can recognize the
253 * type but it's corrupt or data of the wrong type, we should
254 * probably not accept it.
256 $verification = $this->verifyFile();
257 if( $verification !== true ) {
258 return array(
259 'status' => self::VERIFICATION_ERROR,
260 'details' => $verification
265 * Make sure this file can be created
267 $result = $this->validateName();
268 if( $result !== true ) {
269 return $result;
272 $error = '';
273 if( !wfRunHooks( 'UploadVerification',
274 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
275 return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
278 return array( 'status' => self::OK );
282 * Verify that the name is valid and, if necessary, that we can overwrite
284 * @return mixed true if valid, otherwise and array with 'status'
285 * and other keys
287 protected function validateName() {
288 $nt = $this->getTitle();
289 if( is_null( $nt ) ) {
290 $result = array( 'status' => $this->mTitleError );
291 if( $this->mTitleError == self::ILLEGAL_FILENAME ) {
292 $result['filtered'] = $this->mFilteredName;
294 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
295 $result['finalExt'] = $this->mFinalExtension;
296 if ( count( $this->mBlackListedExtensions ) ) {
297 $result['blacklistedExt'] = $this->mBlackListedExtensions;
300 return $result;
302 $this->mDestName = $this->getLocalFile()->getName();
304 return true;
308 * Verify the mime type
310 * @param $mime string representing the mime
311 * @return mixed true if the file is verified, an array otherwise
313 protected function verifyMimeType( $mime ) {
314 global $wgVerifyMimeType;
315 if ( $wgVerifyMimeType ) {
316 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
317 global $wgMimeTypeBlacklist;
318 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
319 return array( 'filetype-badmime', $mime );
322 # XXX: Missing extension will be caught by validateName() via getTitle()
323 if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
324 return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime );
327 # Check IE type
328 $fp = fopen( $this->mTempPath, 'rb' );
329 $chunk = fread( $fp, 256 );
330 fclose( $fp );
332 $magic = MimeMagic::singleton();
333 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
334 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
335 foreach ( $ieTypes as $ieType ) {
336 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
337 return array( 'filetype-bad-ie-mime', $ieType );
342 return true;
346 * Verifies that it's ok to include the uploaded file
348 * @return mixed true of the file is verified, array otherwise.
350 protected function verifyFile() {
351 global $wgAllowJavaUploads;
352 # get the title, even though we are doing nothing with it, because
353 # we need to populate mFinalExtension
354 $this->getTitle();
356 $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
357 $this->checkMacBinary();
359 # check mime type, if desired
360 $mime = $this->mFileProps[ 'file-mime' ];
361 $status = $this->verifyMimeType( $mime );
362 if ( $status !== true ) {
363 return $status;
366 # check for htmlish code and javascript
367 if( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
368 return array( 'uploadscripted' );
370 if( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
371 if( $this->detectScriptInSvg( $this->mTempPath ) ) {
372 return array( 'uploadscripted' );
376 # Check for Java applets, which if uploaded can bypass cross-site
377 # restrictions.
378 if ( !$wgAllowJavaUploads ) {
379 $this->mJavaDetected = false;
380 $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
381 array( $this, 'zipEntryCallback' ) );
382 if ( !$zipStatus->isOK() ) {
383 $errors = $zipStatus->getErrorsArray();
384 $error = reset( $errors );
385 if ( $error[0] !== 'zip-wrong-format' ) {
386 return $error;
389 if ( $this->mJavaDetected ) {
390 return array( 'uploadjava' );
394 # Scan the uploaded file for viruses
395 $virus = $this->detectVirus( $this->mTempPath );
396 if ( $virus ) {
397 return array( 'uploadvirus', $virus );
400 $handler = MediaHandler::getHandler( $mime );
401 if ( $handler ) {
402 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
403 if ( !$handlerStatus->isOK() ) {
404 $errors = $handlerStatus->getErrorsArray();
405 return reset( $errors );
409 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
410 if ( $status !== true ) {
411 return $status;
414 wfDebug( __METHOD__ . ": all clear; passing.\n" );
415 return true;
419 * Callback for ZipDirectoryReader to detect Java class files.
421 function zipEntryCallback( $entry ) {
422 $names = array( $entry['name'] );
424 // If there is a null character, cut off the name at it, because JDK's
425 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
426 // were constructed which had ".class\0" followed by a string chosen to
427 // make the hash collide with the truncated name, that file could be
428 // returned in response to a request for the .class file.
429 $nullPos = strpos( $entry['name'], "\000" );
430 if ( $nullPos !== false ) {
431 $names[] = substr( $entry['name'], 0, $nullPos );
434 // If there is a trailing slash in the file name, we have to strip it,
435 // because that's what ZIP_GetEntry() does.
436 if ( preg_grep( '!\.class/?$!', $names ) ) {
437 $this->mJavaDetected = true;
442 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
443 * but that suggests it's checking the user, when it's really checking the title + user combination.
444 * @param $user User object to verify the permissions against
445 * @return mixed An array as returned by getUserPermissionsErrors or true
446 * in case the user has proper permissions.
448 public function verifyPermissions( $user ) {
449 return $this->verifyTitlePermissions( $user );
453 * Check whether the user can edit, upload and create the image. This
454 * checks only against the current title; if it returns errors, it may
455 * very well be that another title will not give errors. Therefore
456 * isAllowed() should be called as well for generic is-user-blocked or
457 * can-user-upload checking.
459 * @param $user User object to verify the permissions against
460 * @return mixed An array as returned by getUserPermissionsErrors or true
461 * in case the user has proper permissions.
463 public function verifyTitlePermissions( $user ) {
465 * If the image is protected, non-sysop users won't be able
466 * to modify it by uploading a new revision.
468 $nt = $this->getTitle();
469 if( is_null( $nt ) ) {
470 return true;
472 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
473 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
474 if ( !$nt->exists() ) {
475 $permErrorsCreate = $nt->getUserPermissionsErrors( 'createpage', $user );
476 } else {
477 $permErrorsCreate = array();
479 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
480 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
481 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
482 return $permErrors;
485 $overwriteError = $this->checkOverwrite( $user );
486 if ( $overwriteError !== true ) {
487 return array( $overwriteError );
490 return true;
494 * Check for non fatal problems with the file
496 * @return Array of warnings
498 public function checkWarnings() {
499 $warnings = array();
501 $localFile = $this->getLocalFile();
502 $filename = $localFile->getName();
505 * Check whether the resulting filename is different from the desired one,
506 * but ignore things like ucfirst() and spaces/underscore things
508 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
509 $comparableName = Title::capitalize( $comparableName, NS_FILE );
511 if( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
512 $warnings['badfilename'] = $filename;
515 // Check whether the file extension is on the unwanted list
516 global $wgCheckFileExtensions, $wgFileExtensions;
517 if ( $wgCheckFileExtensions ) {
518 if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) {
519 $warnings['filetype-unwanted-type'] = $this->mFinalExtension;
523 global $wgUploadSizeWarning;
524 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
525 $warnings['large-file'] = $wgUploadSizeWarning;
528 if ( $this->mFileSize == 0 ) {
529 $warnings['emptyfile'] = true;
532 $exists = self::getExistsWarning( $localFile );
533 if( $exists !== false ) {
534 $warnings['exists'] = $exists;
537 // Check dupes against existing files
538 $hash = File::sha1Base36( $this->mTempPath );
539 $dupes = RepoGroup::singleton()->findBySha1( $hash );
540 $title = $this->getTitle();
541 // Remove all matches against self
542 foreach ( $dupes as $key => $dupe ) {
543 if( $title->equals( $dupe->getTitle() ) ) {
544 unset( $dupes[$key] );
547 if( $dupes ) {
548 $warnings['duplicate'] = $dupes;
551 // Check dupes against archives
552 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
553 if ( $archivedImage->getID() > 0 ) {
554 $warnings['duplicate-archive'] = $archivedImage->getName();
557 return $warnings;
561 * Really perform the upload. Stores the file in the local repo, watches
562 * if necessary and runs the UploadComplete hook.
564 * @param $user User
566 * @return Status indicating the whether the upload succeeded.
568 public function performUpload( $comment, $pageText, $watch, $user ) {
569 $status = $this->getLocalFile()->upload(
570 $this->mTempPath,
571 $comment,
572 $pageText,
573 File::DELETE_SOURCE,
574 $this->mFileProps,
575 false,
576 $user
579 if( $status->isGood() ) {
580 if ( $watch ) {
581 $user->addWatch( $this->getLocalFile()->getTitle() );
584 wfRunHooks( 'UploadComplete', array( &$this ) );
587 return $status;
591 * Returns the title of the file to be uploaded. Sets mTitleError in case
592 * the name was illegal.
594 * @return Title The title of the file or null in case the name was illegal
596 public function getTitle() {
597 if ( $this->mTitle !== false ) {
598 return $this->mTitle;
602 * Chop off any directories in the given filename. Then
603 * filter out illegal characters, and try to make a legible name
604 * out of it. We'll strip some silently that Title would die on.
606 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mDesiredDestName );
607 /* Normalize to title form before we do any further processing */
608 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
609 if( is_null( $nt ) ) {
610 $this->mTitleError = self::ILLEGAL_FILENAME;
611 return $this->mTitle = null;
613 $this->mFilteredName = $nt->getDBkey();
616 * We'll want to blacklist against *any* 'extension', and use
617 * only the final one for the whitelist.
619 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
621 if( count( $ext ) ) {
622 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
623 } else {
624 $this->mFinalExtension = '';
626 # No extension, try guessing one
627 $magic = MimeMagic::singleton();
628 $mime = $magic->guessMimeType( $this->mTempPath );
629 if ( $mime !== 'unknown/unknown' ) {
630 # Get a space separated list of extensions
631 $extList = $magic->getExtensionsForType( $mime );
632 if ( $extList ) {
633 # Set the extension to the canonical extension
634 $this->mFinalExtension = strtok( $extList, ' ' );
636 # Fix up the other variables
637 $this->mFilteredName .= ".{$this->mFinalExtension}";
638 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
639 $ext = array( $this->mFinalExtension );
645 /* Don't allow users to override the blacklist (check file extension) */
646 global $wgCheckFileExtensions, $wgStrictFileExtensions;
647 global $wgFileExtensions, $wgFileBlacklist;
649 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
651 if ( $this->mFinalExtension == '' ) {
652 $this->mTitleError = self::FILETYPE_MISSING;
653 return $this->mTitle = null;
654 } elseif ( $blackListedExtensions ||
655 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
656 !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) ) {
657 $this->mBlackListedExtensions = $blackListedExtensions;
658 $this->mTitleError = self::FILETYPE_BADTYPE;
659 return $this->mTitle = null;
662 # If there was more than one "extension", reassemble the base
663 # filename to prevent bogus complaints about length
664 if( count( $ext ) > 1 ) {
665 for( $i = 0; $i < count( $ext ) - 1; $i++ ) {
666 $partname .= '.' . $ext[$i];
670 if( strlen( $partname ) < 1 ) {
671 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
672 return $this->mTitle = null;
675 return $this->mTitle = $nt;
679 * Return the local file and initializes if necessary.
681 * @return LocalFile
683 public function getLocalFile() {
684 if( is_null( $this->mLocalFile ) ) {
685 $nt = $this->getTitle();
686 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
688 return $this->mLocalFile;
692 * NOTE: Probably should be deprecated in favor of UploadStash, but this is sometimes
693 * called outside that context.
695 * Stash a file in a temporary directory for later processing
696 * after the user has confirmed it.
698 * If the user doesn't explicitly cancel or accept, these files
699 * can accumulate in the temp directory.
701 * @param $saveName String: the destination filename
702 * @param $tempSrc String: the source temporary file to save
703 * @return String: full path the stashed file, or false on failure
705 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
706 $repo = RepoGroup::singleton()->getLocalRepo();
707 $status = $repo->storeTemp( $saveName, $tempSrc );
708 return $status;
712 * If the user does not supply all necessary information in the first upload form submission (either by accident or
713 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
715 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
716 * into the user's session.
717 * This method returns the file object, which also has a 'sessionKey' property which can be passed through a form or
718 * API request to find this stashed file again.
720 * @param $key String: (optional) the session key used to find the file info again. If not supplied, a key will be autogenerated.
721 * @return UploadStashFile stashed file
723 public function stashSessionFile( $key = null ) {
724 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash();
725 $data = array(
726 'mFileProps' => $this->mFileProps,
727 'mSourceType' => $this->getSourceType(),
729 $file = $stash->stashFile( $this->mTempPath, $data, $key );
730 $this->mLocalFile = $file;
731 return $file;
735 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashSessionFile().
737 * @param $key String: (optional) the session key used to find the file info again. If not supplied, a key will be autogenerated.
738 * @return String: session key
740 public function stashSession( $key = null ) {
741 return $this->stashSessionFile( $key )->getSessionKey();
745 * If we've modified the upload file we need to manually remove it
746 * on exit to clean up.
748 public function cleanupTempFile() {
749 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
750 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
751 unlink( $this->mTempPath );
755 public function getTempPath() {
756 return $this->mTempPath;
760 * Split a file into a base name and all dot-delimited 'extensions'
761 * on the end. Some web server configurations will fall back to
762 * earlier pseudo-'extensions' to determine type and execute
763 * scripts, so the blacklist needs to check them all.
765 * @return array
767 public static function splitExtensions( $filename ) {
768 $bits = explode( '.', $filename );
769 $basename = array_shift( $bits );
770 return array( $basename, $bits );
774 * Perform case-insensitive match against a list of file extensions.
775 * Returns true if the extension is in the list.
777 * @param $ext String
778 * @param $list Array
779 * @return Boolean
781 public static function checkFileExtension( $ext, $list ) {
782 return in_array( strtolower( $ext ), $list );
786 * Perform case-insensitive match against a list of file extensions.
787 * Returns an array of matching extensions.
789 * @param $ext Array
790 * @param $list Array
791 * @return Boolean
793 public static function checkFileExtensionList( $ext, $list ) {
794 return array_intersect( array_map( 'strtolower', $ext ), $list );
798 * Checks if the mime type of the uploaded file matches the file extension.
800 * @param $mime String: the mime type of the uploaded file
801 * @param $extension String: the filename extension that the file is to be served with
802 * @return Boolean
804 public static function verifyExtension( $mime, $extension ) {
805 $magic = MimeMagic::singleton();
807 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
808 if ( !$magic->isRecognizableExtension( $extension ) ) {
809 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
810 "unrecognized extension '$extension', can't verify\n" );
811 return true;
812 } else {
813 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
814 "recognized extension '$extension', so probably invalid file\n" );
815 return false;
818 $match = $magic->isMatchingExtension( $extension, $mime );
820 if ( $match === null ) {
821 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
822 return true;
823 } elseif( $match === true ) {
824 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
826 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
827 return true;
829 } else {
830 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
831 return false;
836 * Heuristic for detecting files that *could* contain JavaScript instructions or
837 * things that may look like HTML to a browser and are thus
838 * potentially harmful. The present implementation will produce false
839 * positives in some situations.
841 * @param $file String: pathname to the temporary upload file
842 * @param $mime String: the mime type of the file
843 * @param $extension String: the extension of the file
844 * @return Boolean: true if the file contains something looking like embedded scripts
846 public static function detectScript( $file, $mime, $extension ) {
847 global $wgAllowTitlesInSVG;
849 # ugly hack: for text files, always look at the entire file.
850 # For binary field, just check the first K.
852 if( strpos( $mime,'text/' ) === 0 ) {
853 $chunk = file_get_contents( $file );
854 } else {
855 $fp = fopen( $file, 'rb' );
856 $chunk = fread( $fp, 1024 );
857 fclose( $fp );
860 $chunk = strtolower( $chunk );
862 if( !$chunk ) {
863 return false;
866 # decode from UTF-16 if needed (could be used for obfuscation).
867 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
868 $enc = 'UTF-16BE';
869 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
870 $enc = 'UTF-16LE';
871 } else {
872 $enc = null;
875 if( $enc ) {
876 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
879 $chunk = trim( $chunk );
881 # FIXME: convert from UTF-16 if necessarry!
882 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
884 # check for HTML doctype
885 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
886 return true;
890 * Internet Explorer for Windows performs some really stupid file type
891 * autodetection which can cause it to interpret valid image files as HTML
892 * and potentially execute JavaScript, creating a cross-site scripting
893 * attack vectors.
895 * Apple's Safari browser also performs some unsafe file type autodetection
896 * which can cause legitimate files to be interpreted as HTML if the
897 * web server is not correctly configured to send the right content-type
898 * (or if you're really uploading plain text and octet streams!)
900 * Returns true if IE is likely to mistake the given file for HTML.
901 * Also returns true if Safari would mistake the given file for HTML
902 * when served with a generic content-type.
904 $tags = array(
905 '<a href',
906 '<body',
907 '<head',
908 '<html', #also in safari
909 '<img',
910 '<pre',
911 '<script', #also in safari
912 '<table'
915 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
916 $tags[] = '<title';
919 foreach( $tags as $tag ) {
920 if( false !== strpos( $chunk, $tag ) ) {
921 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
922 return true;
927 * look for JavaScript
930 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
931 $chunk = Sanitizer::decodeCharReferences( $chunk );
933 # look for script-types
934 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
935 wfDebug( __METHOD__ . ": found script types\n" );
936 return true;
939 # look for html-style script-urls
940 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
941 wfDebug( __METHOD__ . ": found html-style script urls\n" );
942 return true;
945 # look for css-style script-urls
946 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
947 wfDebug( __METHOD__ . ": found css-style script urls\n" );
948 return true;
951 wfDebug( __METHOD__ . ": no scripts found\n" );
952 return false;
955 protected function detectScriptInSvg( $filename ) {
956 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
957 return $check->filterMatch;
961 * @todo Replace this with a whitelist filter!
963 public function checkSvgScriptCallback( $element, $attribs ) {
964 $stripped = $this->stripXmlNamespace( $element );
966 if( $stripped == 'script' ) {
967 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
968 return true;
971 foreach( $attribs as $attrib => $value ) {
972 $stripped = $this->stripXmlNamespace( $attrib );
973 if( substr( $stripped, 0, 2 ) == 'on' ) {
974 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
975 return true;
977 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
978 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
979 return true;
984 private function stripXmlNamespace( $name ) {
985 // 'http://www.w3.org/2000/svg:script' -> 'script'
986 $parts = explode( ':', strtolower( $name ) );
987 return array_pop( $parts );
991 * Generic wrapper function for a virus scanner program.
992 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
993 * $wgAntivirusRequired may be used to deny upload if the scan fails.
995 * @param $file String: pathname to the temporary upload file
996 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
997 * or a string containing feedback from the virus scanner if a virus was found.
998 * If textual feedback is missing but a virus was found, this function returns true.
1000 public static function detectVirus( $file ) {
1001 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1003 if ( !$wgAntivirus ) {
1004 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1005 return null;
1008 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1009 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1010 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1011 array( 'virus-badscanner', $wgAntivirus ) );
1012 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
1015 # look up scanner configuration
1016 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1017 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1018 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1019 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1021 if ( strpos( $command, "%f" ) === false ) {
1022 # simple pattern: append file to scan
1023 $command .= " " . wfEscapeShellArg( $file );
1024 } else {
1025 # complex pattern: replace "%f" with file to scan
1026 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1029 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1031 # execute virus scanner
1032 $exitCode = false;
1034 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1035 # that does not seem to be worth the pain.
1036 # Ask me (Duesentrieb) about it if it's ever needed.
1037 $output = wfShellExec( "$command 2>&1", $exitCode );
1039 # map exit code to AV_xxx constants.
1040 $mappedCode = $exitCode;
1041 if ( $exitCodeMap ) {
1042 if ( isset( $exitCodeMap[$exitCode] ) ) {
1043 $mappedCode = $exitCodeMap[$exitCode];
1044 } elseif ( isset( $exitCodeMap["*"] ) ) {
1045 $mappedCode = $exitCodeMap["*"];
1049 if ( $mappedCode === AV_SCAN_FAILED ) {
1050 # scan failed (code was mapped to false by $exitCodeMap)
1051 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1053 if ( $wgAntivirusRequired ) {
1054 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
1055 } else {
1056 return null;
1058 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1059 # scan failed because filetype is unknown (probably imune)
1060 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1061 return null;
1062 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1063 # no virus found
1064 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1065 return false;
1066 } else {
1067 $output = trim( $output );
1069 if ( !$output ) {
1070 $output = true; #if there's no output, return true
1071 } elseif ( $msgPattern ) {
1072 $groups = array();
1073 if ( preg_match( $msgPattern, $output, $groups ) ) {
1074 if ( $groups[1] ) {
1075 $output = $groups[1];
1080 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1081 return $output;
1086 * Check if the temporary file is MacBinary-encoded, as some uploads
1087 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1088 * If so, the data fork will be extracted to a second temporary file,
1089 * which will then be checked for validity and either kept or discarded.
1091 private function checkMacBinary() {
1092 $macbin = new MacBinary( $this->mTempPath );
1093 if( $macbin->isValid() ) {
1094 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
1095 $dataHandle = fopen( $dataFile, 'wb' );
1097 wfDebug( __METHOD__ . ": Extracting MacBinary data fork to $dataFile\n" );
1098 $macbin->extractData( $dataHandle );
1100 $this->mTempPath = $dataFile;
1101 $this->mFileSize = $macbin->dataForkLength();
1103 // We'll have to manually remove the new file if it's not kept.
1104 $this->mRemoveTempFile = true;
1106 $macbin->close();
1110 * Check if there's an overwrite conflict and, if so, if restrictions
1111 * forbid this user from performing the upload.
1113 * @param $user User
1115 * @return mixed true on success, array on failure
1117 private function checkOverwrite( $user ) {
1118 // First check whether the local file can be overwritten
1119 $file = $this->getLocalFile();
1120 if( $file->exists() ) {
1121 if( !self::userCanReUpload( $user, $file ) ) {
1122 return array( 'fileexists-forbidden', $file->getName() );
1123 } else {
1124 return true;
1128 /* Check shared conflicts: if the local file does not exist, but
1129 * wfFindFile finds a file, it exists in a shared repository.
1131 $file = wfFindFile( $this->getTitle() );
1132 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1133 return array( 'fileexists-shared-forbidden', $file->getName() );
1136 return true;
1140 * Check if a user is the last uploader
1142 * @param $user User object
1143 * @param $img String: image name
1144 * @return Boolean
1146 public static function userCanReUpload( User $user, $img ) {
1147 if( $user->isAllowed( 'reupload' ) ) {
1148 return true; // non-conditional
1150 if( !$user->isAllowed( 'reupload-own' ) ) {
1151 return false;
1153 if( is_string( $img ) ) {
1154 $img = wfLocalFile( $img );
1156 if ( !( $img instanceof LocalFile ) ) {
1157 return false;
1160 return $user->getId() == $img->getUser( 'id' );
1164 * Helper function that does various existence checks for a file.
1165 * The following checks are performed:
1166 * - The file exists
1167 * - Article with the same name as the file exists
1168 * - File exists with normalized extension
1169 * - The file looks like a thumbnail and the original exists
1171 * @param $file File The File object to check
1172 * @return mixed False if the file does not exists, else an array
1174 public static function getExistsWarning( $file ) {
1175 if( $file->exists() ) {
1176 return array( 'warning' => 'exists', 'file' => $file );
1179 if( $file->getTitle()->getArticleID() ) {
1180 return array( 'warning' => 'page-exists', 'file' => $file );
1183 if ( $file->wasDeleted() && !$file->exists() ) {
1184 return array( 'warning' => 'was-deleted', 'file' => $file );
1187 if( strpos( $file->getName(), '.' ) == false ) {
1188 $partname = $file->getName();
1189 $extension = '';
1190 } else {
1191 $n = strrpos( $file->getName(), '.' );
1192 $extension = substr( $file->getName(), $n + 1 );
1193 $partname = substr( $file->getName(), 0, $n );
1195 $normalizedExtension = File::normalizeExtension( $extension );
1197 if ( $normalizedExtension != $extension ) {
1198 // We're not using the normalized form of the extension.
1199 // Normal form is lowercase, using most common of alternate
1200 // extensions (eg 'jpg' rather than 'JPEG').
1202 // Check for another file using the normalized form...
1203 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1204 $file_lc = wfLocalFile( $nt_lc );
1206 if( $file_lc->exists() ) {
1207 return array(
1208 'warning' => 'exists-normalized',
1209 'file' => $file,
1210 'normalizedFile' => $file_lc
1215 if ( self::isThumbName( $file->getName() ) ) {
1216 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1217 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $extension, NS_FILE );
1218 $file_thb = wfLocalFile( $nt_thb );
1219 if( $file_thb->exists() ) {
1220 return array(
1221 'warning' => 'thumb',
1222 'file' => $file,
1223 'thumbFile' => $file_thb
1225 } else {
1226 // File does not exist, but we just don't like the name
1227 return array(
1228 'warning' => 'thumb-name',
1229 'file' => $file,
1230 'thumbFile' => $file_thb
1236 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
1237 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1238 return array(
1239 'warning' => 'bad-prefix',
1240 'file' => $file,
1241 'prefix' => $prefix
1246 return false;
1250 * Helper function that checks whether the filename looks like a thumbnail
1252 public static function isThumbName( $filename ) {
1253 $n = strrpos( $filename, '.' );
1254 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1255 return (
1256 substr( $partname , 3, 3 ) == 'px-' ||
1257 substr( $partname , 2, 3 ) == 'px-'
1258 ) &&
1259 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1263 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1265 * @return array list of prefixes
1267 public static function getFilenamePrefixBlacklist() {
1268 $blacklist = array();
1269 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1270 if( !$message->isDisabled() ) {
1271 $lines = explode( "\n", $message->plain() );
1272 foreach( $lines as $line ) {
1273 // Remove comment lines
1274 $comment = substr( trim( $line ), 0, 1 );
1275 if ( $comment == '#' || $comment == '' ) {
1276 continue;
1278 // Remove additional comments after a prefix
1279 $comment = strpos( $line, '#' );
1280 if ( $comment > 0 ) {
1281 $line = substr( $line, 0, $comment-1 );
1283 $blacklist[] = trim( $line );
1286 return $blacklist;
1290 * Gets image info about the file just uploaded.
1292 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1293 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1294 * with the appropriate format, presumably.
1296 * @param $result ApiResult:
1297 * @return Array: image info
1299 public function getImageInfo( $result ) {
1300 $file = $this->getLocalFile();
1301 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1302 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1303 if ( $file instanceof UploadStashFile ) {
1304 $imParam = ApiQueryStashImageInfo::getPropertyNames();
1305 $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1306 } else {
1307 $imParam = ApiQueryImageInfo::getPropertyNames();
1308 $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1310 return $info;
1314 public function convertVerifyErrorToStatus( $error ) {
1315 $code = $error['status'];
1316 unset( $code['status'] );
1317 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1320 public static function getMaxUploadSize( $forType = null ) {
1321 global $wgMaxUploadSize;
1323 if ( is_array( $wgMaxUploadSize ) ) {
1324 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1325 return $wgMaxUploadSize[$forType];
1326 } else {
1327 return $wgMaxUploadSize['*'];
1329 } else {
1330 return intval( $wgMaxUploadSize );