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
{
18 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
19 protected $mTitle = false, $mTitleError = 0;
20 protected $mFilteredName, $mFinalExtension;
21 protected $mLocalFile;
26 const MIN_LENGTH_PARTNAME
= 4;
27 const ILLEGAL_FILENAME
= 5;
28 const OVERWRITE_EXISTING_FILE
= 7;
29 const FILETYPE_MISSING
= 8;
30 const FILETYPE_BADTYPE
= 9;
31 const VERIFICATION_ERROR
= 10;
32 const UPLOAD_VERIFICATION_ERROR
= 11;
33 const HOOK_ABORTED
= 11;
35 const SESSION_VERSION
= 2;
36 const SESSION_KEYNAME
= 'wsUploadData';
38 static public function getSessionKeyname() {
39 return self
::SESSION_KEYNAME
;
43 * Returns true if uploads are enabled.
44 * Can be override by subclasses.
46 public static function isEnabled() {
47 global $wgEnableUploads;
48 if ( !$wgEnableUploads ) {
52 # Check php's file_uploads setting
53 if( !wfIniGetBool( 'file_uploads' ) ) {
60 * Returns true if the user can use this upload module or else a string
61 * identifying the missing permission.
62 * Can be overriden by subclasses.
64 public static function isAllowed( $user ) {
65 if( !$user->isAllowed( 'upload' ) ) {
71 // Upload handlers. Should probably just be a global.
72 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
75 * Create a form of UploadBase depending on wpSourceType and initializes it
77 public static function createFromRequest( &$request, $type = null ) {
78 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
84 // Get the upload class
85 $type = ucfirst( $type );
87 // Give hooks the chance to handle this request
89 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
90 if ( is_null( $className ) ) {
91 $className = 'UploadFrom' . $type;
92 wfDebug( __METHOD__
. ": class name: $className\n" );
93 if( !in_array( $type, self
::$uploadHandlers ) ) {
98 // Check whether this upload class is enabled
99 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
103 // Check whether the request is valid
104 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
108 $handler = new $className;
110 $handler->initializeFromRequest( $request );
115 * Check whether a request if valid for this handler
117 public static function isValidRequest( $request ) {
121 public function __construct() {}
124 * Initialize the path information
125 * @param $name string the desired destination name
126 * @param $tempPath string the temporary path
127 * @param $fileSize int the file size
128 * @param $removeTempFile bool (false) remove the temporary file?
131 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
132 $this->mDesiredDestName
= $name;
133 $this->mTempPath
= $tempPath;
134 $this->mFileSize
= $fileSize;
135 $this->mRemoveTempFile
= $removeTempFile;
139 * Initialize from a WebRequest. Override this in a subclass.
141 public abstract function initializeFromRequest( &$request );
144 * Fetch the file. Usually a no-op
146 public function fetchFile() {
147 return Status
::newGood();
151 * Return true if the file is empty
154 public function isEmptyFile() {
155 return empty( $this->mFileSize
);
159 * Return the file size
162 public function getFileSize() {
163 return $this->mFileSize
;
167 * Append a file to the Repo file
169 * @param string $srcPath Path to source file
170 * @param string $toAppendPath Path to the Repo file that will be appended to.
171 * @return Status Status
173 protected function appendToUploadFile( $srcPath, $toAppendPath ) {
174 $repo = RepoGroup
::singleton()->getLocalRepo();
175 $status = $repo->append( $srcPath, $toAppendPath );
180 * @param $srcPath String: the source path
181 * @return the real path if it was a virtual URL
183 function getRealPath( $srcPath ) {
184 $repo = RepoGroup
::singleton()->getLocalRepo();
185 if ( $repo->isVirtualUrl( $srcPath ) ) {
186 return $repo->resolveVirtualUrl( $srcPath );
192 * Verify whether the upload is sane.
193 * @return mixed self::OK or else an array with error information
195 public function verifyUpload( ) {
197 * If there was no filename or a zero size given, give up quick.
199 if( $this->isEmptyFile() ) {
200 return array( 'status' => self
::EMPTY_FILE
);
204 * Look at the contents of the file; if we can recognize the
205 * type but it's corrupt or data of the wrong type, we should
206 * probably not accept it.
208 $verification = $this->verifyFile();
209 if( $verification !== true ) {
210 if( !is_array( $verification ) ) {
211 $verification = array( $verification );
214 'status' => self
::VERIFICATION_ERROR
,
215 'details' => $verification
220 * Make sure this file can be created
222 $result = $this->validateNameAndOverwrite();
223 if( $result !== true ) {
228 if( !wfRunHooks( 'UploadVerification',
229 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
230 // @fixme This status needs another name...
231 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
234 return array( 'status' => self
::OK
);
238 * Verify that the name is valid and, if necessary, that we can overwrite
240 * @return mixed true if valid, otherwise and array with 'status'
243 public function validateNameAndOverwrite() {
244 $nt = $this->getTitle();
245 if( is_null( $nt ) ) {
246 $result = array( 'status' => $this->mTitleError
);
247 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
248 $result['filtered'] = $this->mFilteredName
;
250 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
251 $result['finalExt'] = $this->mFinalExtension
;
255 $this->mDestName
= $this->getLocalFile()->getName();
258 * In some cases we may forbid overwriting of existing files.
260 $overwrite = $this->checkOverwrite();
261 if( $overwrite !== true ) {
263 'status' => self
::OVERWRITE_EXISTING_FILE
,
264 'overwrite' => $overwrite
271 * Verifies that it's ok to include the uploaded file
273 * @return mixed true of the file is verified, a string or array otherwise.
275 protected function verifyFile() {
276 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
277 $this->checkMacBinary();
279 # magically determine mime type
280 $magic = MimeMagic
::singleton();
281 $mime = $magic->guessMimeType( $this->mTempPath
, false );
283 # check mime type, if desired
284 global $wgVerifyMimeType;
285 if ( $wgVerifyMimeType ) {
286 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
287 if ( !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
288 return array( 'filetype-mime-mismatch' );
291 global $wgMimeTypeBlacklist;
292 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
293 return array( 'filetype-badmime', $mime );
297 $fp = fopen( $this->mTempPath
, 'rb' );
298 $chunk = fread( $fp, 256 );
300 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
301 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
302 foreach ( $ieTypes as $ieType ) {
303 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
304 return array( 'filetype-bad-ie-mime', $ieType );
309 # check for htmlish code and javascript
310 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
311 return 'uploadscripted';
313 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
314 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
315 return 'uploadscripted';
320 * Scan the uploaded file for viruses
322 $virus = $this->detectVirus( $this->mTempPath
);
324 return array( 'uploadvirus', $virus );
326 wfDebug( __METHOD__
. ": all clear; passing.\n" );
331 * Check whether the user can edit, upload and create the image.
333 * @param $user the User object to verify the permissions against
334 * @return mixed An array as returned by getUserPermissionsErrors or true
335 * in case the user has proper permissions.
337 public function verifyPermissions( $user ) {
339 * If the image is protected, non-sysop users won't be able
340 * to modify it by uploading a new revision.
342 $nt = $this->getTitle();
343 if( is_null( $nt ) ) {
346 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
347 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
348 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
349 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
350 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
351 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
358 * Check for non fatal problems with the file
360 * @return Array of warnings
362 public function checkWarnings() {
365 $localFile = $this->getLocalFile();
366 $filename = $localFile->getName();
367 $n = strrpos( $filename, '.' );
368 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
371 * Check whether the resulting filename is different from the desired one,
372 * but ignore things like ucfirst() and spaces/underscore things
374 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
375 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
377 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
378 $warnings['badfilename'] = $filename;
381 // Check whether the file extension is on the unwanted list
382 global $wgCheckFileExtensions, $wgFileExtensions;
383 if ( $wgCheckFileExtensions ) {
384 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
385 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
389 global $wgUploadSizeWarning;
390 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
391 $warnings['large-file'] = $wgUploadSizeWarning;
394 if ( $this->mFileSize
== 0 ) {
395 $warnings['emptyfile'] = true;
398 $exists = self
::getExistsWarning( $localFile );
399 if( $exists !== false ) {
400 $warnings['exists'] = $exists;
403 // Check dupes against existing files
404 $hash = File
::sha1Base36( $this->mTempPath
);
405 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
406 $title = $this->getTitle();
407 // Remove all matches against self
408 foreach ( $dupes as $key => $dupe ) {
409 if( $title->equals( $dupe->getTitle() ) ) {
410 unset( $dupes[$key] );
414 $warnings['duplicate'] = $dupes;
417 // Check dupes against archives
418 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
419 if ( $archivedImage->getID() > 0 ) {
420 $warnings['duplicate-archive'] = $archivedImage->getName();
427 * Really perform the upload. Stores the file in the local repo, watches
428 * if necessary and runs the UploadComplete hook.
430 * @return mixed Status indicating the whether the upload succeeded.
432 public function performUpload( $comment, $pageText, $watch, $user ) {
433 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
434 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
435 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
437 if( $status->isGood() ) {
439 $user->addWatch( $this->getLocalFile()->getTitle() );
442 wfRunHooks( 'UploadComplete', array( &$this ) );
449 * Returns the title of the file to be uploaded. Sets mTitleError in case
450 * the name was illegal.
452 * @return Title The title of the file or null in case the name was illegal
454 public function getTitle() {
455 if ( $this->mTitle
!== false ) {
456 return $this->mTitle
;
460 * Chop off any directories in the given filename. Then
461 * filter out illegal characters, and try to make a legible name
462 * out of it. We'll strip some silently that Title would die on.
464 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mDesiredDestName
);
465 /* Normalize to title form before we do any further processing */
466 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
467 if( is_null( $nt ) ) {
468 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
469 return $this->mTitle
= null;
471 $this->mFilteredName
= $nt->getDBkey();
474 * We'll want to blacklist against *any* 'extension', and use
475 * only the final one for the whitelist.
477 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
479 if( count( $ext ) ) {
480 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
482 $this->mFinalExtension
= '';
485 /* Don't allow users to override the blacklist (check file extension) */
486 global $wgCheckFileExtensions, $wgStrictFileExtensions;
487 global $wgFileExtensions, $wgFileBlacklist;
488 if ( $this->mFinalExtension
== '' ) {
489 $this->mTitleError
= self
::FILETYPE_MISSING
;
490 return $this->mTitle
= null;
491 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
492 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
493 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
494 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
495 return $this->mTitle
= null;
498 # If there was more than one "extension", reassemble the base
499 # filename to prevent bogus complaints about length
500 if( count( $ext ) > 1 ) {
501 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
502 $partname .= '.' . $ext[$i];
506 if( strlen( $partname ) < 1 ) {
507 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
508 return $this->mTitle
= null;
511 return $this->mTitle
= $nt;
515 * Return the local file and initializes if necessary.
517 public function getLocalFile() {
518 if( is_null( $this->mLocalFile
) ) {
519 $nt = $this->getTitle();
520 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
522 return $this->mLocalFile
;
526 * Stash a file in a temporary directory for later processing
527 * after the user has confirmed it.
529 * If the user doesn't explicitly cancel or accept, these files
530 * can accumulate in the temp directory.
532 * @param $saveName String: the destination filename
533 * @param $tempSrc String: the source temporary file to save
534 * @return String: full path the stashed file, or false on failure
536 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
537 $repo = RepoGroup
::singleton()->getLocalRepo();
538 $status = $repo->storeTemp( $saveName, $tempSrc );
543 * Stash a file in a temporary directory for later processing,
544 * and save the necessary descriptive info into the session.
545 * Returns a key value which will be passed through a form
546 * to pick up the path info on a later invocation.
548 * @return Integer: session key
550 public function stashSession() {
551 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
552 if( !$status->isOK() ) {
553 # Couldn't save the file.
557 $key = $this->getSessionKey();
558 $_SESSION[self
::SESSION_KEYNAME
][$key] = array(
559 'mTempPath' => $status->value
,
560 'mFileSize' => $this->mFileSize
,
561 'mFileProps' => $this->mFileProps
,
562 'version' => self
::SESSION_VERSION
,
568 * Generate a random session key from stash in cases where we want to start an upload without much information
570 protected function getSessionKey() {
571 $key = mt_rand( 0, 0x7fffffff );
572 $_SESSION[self
::SESSION_KEYNAME
][$key] = array();
577 * If we've modified the upload file we need to manually remove it
578 * on exit to clean up.
580 public function cleanupTempFile() {
581 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
582 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
583 unlink( $this->mTempPath
);
587 public function getTempPath() {
588 return $this->mTempPath
;
592 * Split a file into a base name and all dot-delimited 'extensions'
593 * on the end. Some web server configurations will fall back to
594 * earlier pseudo-'extensions' to determine type and execute
595 * scripts, so the blacklist needs to check them all.
599 public static function splitExtensions( $filename ) {
600 $bits = explode( '.', $filename );
601 $basename = array_shift( $bits );
602 return array( $basename, $bits );
606 * Perform case-insensitive match against a list of file extensions.
607 * Returns true if the extension is in the list.
613 public static function checkFileExtension( $ext, $list ) {
614 return in_array( strtolower( $ext ), $list );
618 * Perform case-insensitive match against a list of file extensions.
619 * Returns true if any of the extensions are in the list.
625 public static function checkFileExtensionList( $ext, $list ) {
626 foreach( $ext as $e ) {
627 if( in_array( strtolower( $e ), $list ) ) {
635 * Checks if the mime type of the uploaded file matches the file extension.
637 * @param $mime String: the mime type of the uploaded file
638 * @param $extension String: the filename extension that the file is to be served with
641 public static function verifyExtension( $mime, $extension ) {
642 $magic = MimeMagic
::singleton();
644 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
645 if ( !$magic->isRecognizableExtension( $extension ) ) {
646 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
647 "unrecognized extension '$extension', can't verify\n" );
650 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
651 "recognized extension '$extension', so probably invalid file\n" );
655 $match = $magic->isMatchingExtension( $extension, $mime );
657 if ( $match === null ) {
658 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
660 } elseif( $match === true ) {
661 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
663 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
667 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
673 * Heuristic for detecting files that *could* contain JavaScript instructions or
674 * things that may look like HTML to a browser and are thus
675 * potentially harmful. The present implementation will produce false
676 * positives in some situations.
678 * @param $file String: pathname to the temporary upload file
679 * @param $mime String: the mime type of the file
680 * @param $extension String: the extension of the file
681 * @return Boolean: true if the file contains something looking like embedded scripts
683 public static function detectScript( $file, $mime, $extension ) {
684 global $wgAllowTitlesInSVG;
686 # ugly hack: for text files, always look at the entire file.
687 # For binary field, just check the first K.
689 if( strpos( $mime,'text/' ) === 0 ) {
690 $chunk = file_get_contents( $file );
692 $fp = fopen( $file, 'rb' );
693 $chunk = fread( $fp, 1024 );
697 $chunk = strtolower( $chunk );
703 # decode from UTF-16 if needed (could be used for obfuscation).
704 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
706 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
713 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
716 $chunk = trim( $chunk );
718 # FIXME: convert from UTF-16 if necessarry!
719 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
721 # check for HTML doctype
722 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
727 * Internet Explorer for Windows performs some really stupid file type
728 * autodetection which can cause it to interpret valid image files as HTML
729 * and potentially execute JavaScript, creating a cross-site scripting
732 * Apple's Safari browser also performs some unsafe file type autodetection
733 * which can cause legitimate files to be interpreted as HTML if the
734 * web server is not correctly configured to send the right content-type
735 * (or if you're really uploading plain text and octet streams!)
737 * Returns true if IE is likely to mistake the given file for HTML.
738 * Also returns true if Safari would mistake the given file for HTML
739 * when served with a generic content-type.
745 '<html', #also in safari
748 '<script', #also in safari
752 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
756 foreach( $tags as $tag ) {
757 if( false !== strpos( $chunk, $tag ) ) {
763 * look for JavaScript
766 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
767 $chunk = Sanitizer
::decodeCharReferences( $chunk );
769 # look for script-types
770 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
774 # look for html-style script-urls
775 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
779 # look for css-style script-urls
780 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
784 wfDebug( __METHOD__
. ": no scripts found\n" );
788 protected function detectScriptInSvg( $filename ) {
789 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
790 return $check->filterMatch
;
794 * @todo Replace this with a whitelist filter!
796 public function checkSvgScriptCallback( $element, $attribs ) {
797 $stripped = $this->stripXmlNamespace( $element );
799 if( $stripped == 'script' ) {
800 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
804 foreach( $attribs as $attrib => $value ) {
805 $stripped = $this->stripXmlNamespace( $attrib );
806 if( substr( $stripped, 0, 2 ) == 'on' ) {
807 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
810 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
811 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
817 private function stripXmlNamespace( $name ) {
818 // 'http://www.w3.org/2000/svg:script' -> 'script'
819 $parts = explode( ':', strtolower( $name ) );
820 return array_pop( $parts );
824 * Generic wrapper function for a virus scanner program.
825 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
826 * $wgAntivirusRequired may be used to deny upload if the scan fails.
828 * @param $file String: pathname to the temporary upload file
829 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
830 * or a string containing feedback from the virus scanner if a virus was found.
831 * If textual feedback is missing but a virus was found, this function returns true.
833 public static function detectVirus( $file ) {
834 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
836 if ( !$wgAntivirus ) {
837 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
841 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
842 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
843 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>", array( 'virus-badscanner', $wgAntivirus ) );
844 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
847 # look up scanner configuration
848 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
849 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
850 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
851 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
853 if ( strpos( $command, "%f" ) === false ) {
854 # simple pattern: append file to scan
855 $command .= " " . wfEscapeShellArg( $file );
857 # complex pattern: replace "%f" with file to scan
858 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
861 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
863 # execute virus scanner
866 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
867 # that does not seem to be worth the pain.
868 # Ask me (Duesentrieb) about it if it's ever needed.
869 $output = wfShellExec( "$command 2>&1", $exitCode );
871 # map exit code to AV_xxx constants.
872 $mappedCode = $exitCode;
873 if ( $exitCodeMap ) {
874 if ( isset( $exitCodeMap[$exitCode] ) ) {
875 $mappedCode = $exitCodeMap[$exitCode];
876 } elseif ( isset( $exitCodeMap["*"] ) ) {
877 $mappedCode = $exitCodeMap["*"];
881 if ( $mappedCode === AV_SCAN_FAILED
) {
882 # scan failed (code was mapped to false by $exitCodeMap)
883 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
885 if ( $wgAntivirusRequired ) {
886 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
890 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
891 # scan failed because filetype is unknown (probably imune)
892 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
894 } elseif ( $mappedCode === AV_NO_VIRUS
) {
896 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
899 $output = trim( $output );
902 $output = true; #if there's no output, return true
903 } elseif ( $msgPattern ) {
905 if ( preg_match( $msgPattern, $output, $groups ) ) {
907 $output = $groups[1];
912 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
918 * Check if the temporary file is MacBinary-encoded, as some uploads
919 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
920 * If so, the data fork will be extracted to a second temporary file,
921 * which will then be checked for validity and either kept or discarded.
923 private function checkMacBinary() {
924 $macbin = new MacBinary( $this->mTempPath
);
925 if( $macbin->isValid() ) {
926 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
927 $dataHandle = fopen( $dataFile, 'wb' );
929 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
930 $macbin->extractData( $dataHandle );
932 $this->mTempPath
= $dataFile;
933 $this->mFileSize
= $macbin->dataForkLength();
935 // We'll have to manually remove the new file if it's not kept.
936 $this->mRemoveTempFile
= true;
942 * Check if there's an overwrite conflict and, if so, if restrictions
943 * forbid this user from performing the upload.
945 * @return mixed true on success, error string on failure
947 private function checkOverwrite() {
949 // First check whether the local file can be overwritten
950 $file = $this->getLocalFile();
951 if( $file->exists() ) {
952 if( !self
::userCanReUpload( $wgUser, $file ) ) {
953 return 'fileexists-forbidden';
959 /* Check shared conflicts: if the local file does not exist, but
960 * wfFindFile finds a file, it exists in a shared repository.
962 $file = wfFindFile( $this->getTitle() );
963 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) ) {
964 return 'fileexists-shared-forbidden';
971 * Check if a user is the last uploader
973 * @param $user User object
974 * @param $img String: image name
977 public static function userCanReUpload( User
$user, $img ) {
978 if( $user->isAllowed( 'reupload' ) ) {
979 return true; // non-conditional
981 if( !$user->isAllowed( 'reupload-own' ) ) {
984 if( is_string( $img ) ) {
985 $img = wfLocalFile( $img );
987 if ( !( $img instanceof LocalFile
) ) {
991 return $user->getId() == $img->getUser( 'id' );
995 * Helper function that does various existence checks for a file.
996 * The following checks are performed:
998 * - Article with the same name as the file exists
999 * - File exists with normalized extension
1000 * - The file looks like a thumbnail and the original exists
1002 * @param $file The File object to check
1003 * @return mixed False if the file does not exists, else an array
1005 public static function getExistsWarning( $file ) {
1006 if( $file->exists() ) {
1007 return array( 'warning' => 'exists', 'file' => $file );
1010 if( $file->getTitle()->getArticleID() ) {
1011 return array( 'warning' => 'page-exists', 'file' => $file );
1014 if ( $file->wasDeleted() && !$file->exists() ) {
1015 return array( 'warning' => 'was-deleted', 'file' => $file );
1018 if( strpos( $file->getName(), '.' ) == false ) {
1019 $partname = $file->getName();
1022 $n = strrpos( $file->getName(), '.' );
1023 $extension = substr( $file->getName(), $n +
1 );
1024 $partname = substr( $file->getName(), 0, $n );
1026 $normalizedExtension = File
::normalizeExtension( $extension );
1028 if ( $normalizedExtension != $extension ) {
1029 // We're not using the normalized form of the extension.
1030 // Normal form is lowercase, using most common of alternate
1031 // extensions (eg 'jpg' rather than 'JPEG').
1033 // Check for another file using the normalized form...
1034 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1035 $file_lc = wfLocalFile( $nt_lc );
1037 if( $file_lc->exists() ) {
1039 'warning' => 'exists-normalized',
1041 'normalizedFile' => $file_lc
1046 if ( self
::isThumbName( $file->getName() ) ) {
1047 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1048 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1049 $file_thb = wfLocalFile( $nt_thb );
1050 if( $file_thb->exists() ) {
1052 'warning' => 'thumb',
1054 'thumbFile' => $file_thb
1057 // File does not exist, but we just don't like the name
1059 'warning' => 'thumb-name',
1061 'thumbFile' => $file_thb
1067 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1068 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1070 'warning' => 'bad-prefix',
1081 * Helper function that checks whether the filename looks like a thumbnail
1083 public static function isThumbName( $filename ) {
1084 $n = strrpos( $filename, '.' );
1085 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1087 substr( $partname , 3, 3 ) == 'px-' ||
1088 substr( $partname , 2, 3 ) == 'px-'
1090 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1094 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1096 * @return array list of prefixes
1098 public static function getFilenamePrefixBlacklist() {
1099 $blacklist = array();
1100 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1101 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1102 $lines = explode( "\n", $message );
1103 foreach( $lines as $line ) {
1104 // Remove comment lines
1105 $comment = substr( trim( $line ), 0, 1 );
1106 if ( $comment == '#' ||
$comment == '' ) {
1109 // Remove additional comments after a prefix
1110 $comment = strpos( $line, '#' );
1111 if ( $comment > 0 ) {
1112 $line = substr( $line, 0, $comment-1 );
1114 $blacklist[] = trim( $line );
1120 public function getImageInfo( $result ) {
1121 $file = $this->getLocalFile();
1122 $imParam = ApiQueryImageInfo
::getPropertyNames();
1123 return ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );