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;
38 * Returns true if uploads are enabled.
39 * Can be override by subclasses.
41 public static function isEnabled() {
42 global $wgEnableUploads;
43 if ( !$wgEnableUploads )
46 # Check php's file_uploads setting
47 if( !wfIniGetBool( 'file_uploads' ) ) {
54 * Returns true if the user can use this upload module or else a string
55 * identifying the missing permission.
56 * Can be overriden by subclasses.
58 public static function isAllowed( $user ) {
59 if( !$user->isAllowed( 'upload' ) )
64 // Upload handlers. Should probably just be a global.
65 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
68 * Create a form of UploadBase depending on wpSourceType and initializes it
70 public static function createFromRequest( &$request, $type = null ) {
71 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
76 // Get the upload class
77 $type = ucfirst( $type );
79 // Give hooks the chance to handle this request
81 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
82 if ( is_null( $className ) ) {
83 $className = 'UploadFrom' . $type;
84 wfDebug( __METHOD__
. ": class name: $className\n" );
85 if( !in_array( $type, self
::$uploadHandlers ) )
89 // Check whether this upload class is enabled
90 if( !call_user_func( array( $className, 'isEnabled' ) ) )
93 // Check whether the request is valid
94 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
97 $handler = new $className;
99 $handler->initializeFromRequest( $request );
104 * Check whether a request if valid for this handler
106 public static function isValidRequest( $request ) {
110 public function __construct() {}
113 * Do the real variable initialization
115 public function initialize( $name, $tempPath, $fileSize, $removeTempFile = false ) {
116 $this->mDesiredDestName
= $name;
117 $this->mTempPath
= $tempPath;
118 $this->mFileSize
= $fileSize;
119 $this->mRemoveTempFile
= $removeTempFile;
123 * Initialize from a WebRequest. Override this in a subclass.
125 public abstract function initializeFromRequest( &$request );
128 * Fetch the file. Usually a no-op
130 public function fetchFile() {
131 return Status
::newGood();
135 * Return the file size
137 public function isEmptyFile(){
138 return empty( $this->mFileSize
);
143 * @param string $srcPath the source path
144 * @returns the real path if it was a virtual url
146 function getRealPath( $srcPath ){
147 $repo = RepoGroup
::singleton()->getLocalRepo();
148 if ( $repo->isVirtualUrl( $srcPath ) ) {
149 return $repo->resolveVirtualUrl( $srcPath );
155 * Verify whether the upload is sane.
156 * Returns self::OK or else an array with error information
158 public function verifyUpload() {
160 * If there was no filename or a zero size given, give up quick.
162 if( $this->isEmptyFile() )
163 return array( 'status' => self
::EMPTY_FILE
);
166 * Look at the contents of the file; if we can recognize the
167 * type but it's corrupt or data of the wrong type, we should
168 * probably not accept it.
170 $verification = $this->verifyFile();
171 if( $verification !== true ) {
172 if( !is_array( $verification ) )
173 $verification = array( $verification );
174 return array( 'status' => self
::VERIFICATION_ERROR
,
175 'details' => $verification );
179 $nt = $this->getTitle();
180 if( is_null( $nt ) ) {
181 $result = array( 'status' => $this->mTitleError
);
182 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
)
183 $result['filtered'] = $this->mFilteredName
;
184 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
)
185 $result['finalExt'] = $this->mFinalExtension
;
188 $this->mDestName
= $this->getLocalFile()->getName();
191 * In some cases we may forbid overwriting of existing files.
193 $overwrite = $this->checkOverwrite();
194 if( $overwrite !== true )
195 return array( 'status' => self
::OVERWRITE_EXISTING_FILE
, 'overwrite' => $overwrite );
198 if( !wfRunHooks( 'UploadVerification',
199 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
200 // This status needs another name...
201 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
204 return array( 'status' => self
::OK
);
208 * Verifies that it's ok to include the uploaded file
210 * FIXME: this function seems to intermixes tmpfile and $this->mTempPath .. no idea why this is
212 * @param string $tmpfile the full path of the temporary file to verify
213 * @return mixed true of the file is verified, a string or array otherwise.
215 protected function verifyFile() {
216 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
217 $this->checkMacBinary();
219 #magically determine mime type
220 $magic = MimeMagic
::singleton();
221 $mime = $magic->guessMimeType( $this->mTempPath
, false );
223 #check mime type, if desired
224 global $wgVerifyMimeType;
225 if ( $wgVerifyMimeType ) {
226 global $wgMimeTypeBlacklist;
227 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
228 return array( 'filetype-badmime', $mime );
231 $fp = fopen( $this->mTempPath
, 'rb' );
232 $chunk = fread( $fp, 256 );
234 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
235 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
236 foreach ( $ieTypes as $ieType ) {
237 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
238 return array( 'filetype-bad-ie-mime', $ieType );
243 #check for htmlish code and javascript
244 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
245 return 'uploadscripted';
247 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
248 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
249 return 'uploadscripted';
254 * Scan the uploaded file for viruses
256 $virus = $this->detectVirus( $this->mTempPath
);
258 return array( 'uploadvirus', $virus );
260 wfDebug( __METHOD__
. ": all clear; passing.\n" );
265 * Check whether the user can edit, upload and create the image.
267 * @param User $user the user to verify the permissions against
268 * @return mixed An array as returned by getUserPermissionsErrors or true
269 * in case the user has proper permissions.
271 public function verifyPermissions( $user ) {
273 * If the image is protected, non-sysop users won't be able
274 * to modify it by uploading a new revision.
276 $nt = $this->getTitle();
279 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
280 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
281 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
282 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
283 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
284 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
291 * Check for non fatal problems with the file
293 * @return array Array of warnings
295 public function checkWarnings() {
298 $localFile = $this->getLocalFile();
299 $filename = $localFile->getName();
300 $n = strrpos( $filename, '.' );
301 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
304 * Check whether the resulting filename is different from the desired one,
305 * but ignore things like ucfirst() and spaces/underscore things
307 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
308 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
310 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename )
311 $warnings['badfilename'] = $filename;
313 // Check whether the file extension is on the unwanted list
314 global $wgCheckFileExtensions, $wgFileExtensions;
315 if ( $wgCheckFileExtensions ) {
316 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
317 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
320 global $wgUploadSizeWarning;
321 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) )
322 $warnings['large-file'] = $wgUploadSizeWarning;
324 if ( $this->mFileSize
== 0 )
325 $warnings['emptyfile'] = true;
328 $exists = self
::getExistsWarning( $localFile );
329 if( $exists !== false )
330 $warnings['exists'] = $exists;
332 // Check dupes against existing files
333 $hash = File
::sha1Base36( $this->mTempPath
);
334 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
335 $title = $this->getTitle();
336 // Remove all matches against self
337 foreach ( $dupes as $key => $dupe ) {
338 if( $title->equals( $dupe->getTitle() ) )
339 unset( $dupes[$key] );
342 $warnings['duplicate'] = $dupes;
344 // Check dupes against archives
345 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
346 if ( $archivedImage->getID() > 0 )
347 $warnings['duplicate-archive'] = $archivedImage->getName();
353 * Really perform the upload. Stores the file in the local repo, watches
354 * if necessary and runs the UploadComplete hook.
356 * @return mixed Status indicating the whether the upload succeeded.
358 public function performUpload( $comment, $pageText, $watch, $user ) {
359 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
360 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
361 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
363 if( $status->isGood() && $watch )
364 $user->addWatch( $this->getLocalFile()->getTitle() );
366 if( $status->isGood() )
367 wfRunHooks( 'UploadComplete', array( &$this ) );
373 * Returns the title of the file to be uploaded. Sets mTitleError in case
374 * the name was illegal.
376 * @return Title The title of the file or null in case the name was illegal
378 public function getTitle() {
379 if ( $this->mTitle
!== false )
380 return $this->mTitle
;
383 * Chop off any directories in the given filename. Then
384 * filter out illegal characters, and try to make a legible name
385 * out of it. We'll strip some silently that Title would die on.
387 $basename = $this->mDesiredDestName
;
389 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
390 /* Normalize to title form before we do any further processing */
391 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
392 if( is_null( $nt ) ) {
393 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
394 return $this->mTitle
= null;
396 $this->mFilteredName
= $nt->getDBkey();
399 * We'll want to blacklist against *any* 'extension', and use
400 * only the final one for the whitelist.
402 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
404 if( count( $ext ) ) {
405 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
407 $this->mFinalExtension
= '';
410 /* Don't allow users to override the blacklist (check file extension) */
411 global $wgCheckFileExtensions, $wgStrictFileExtensions;
412 global $wgFileExtensions, $wgFileBlacklist;
413 if ( $this->mFinalExtension
== '' ) {
414 $this->mTitleError
= self
::FILETYPE_MISSING
;
415 return $this->mTitle
= null;
416 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
417 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
418 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
419 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
420 return $this->mTitle
= null;
423 # If there was more than one "extension", reassemble the base
424 # filename to prevent bogus complaints about length
425 if( count( $ext ) > 1 ) {
426 for( $i = 0; $i < count( $ext ) - 1; $i++
)
427 $partname .= '.' . $ext[$i];
430 if( strlen( $partname ) < 1 ) {
431 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
432 return $this->mTitle
= null;
435 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
436 if( is_null( $nt ) ) {
437 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
438 return $this->mTitle
= null;
440 return $this->mTitle
= $nt;
444 * Return the local file and initializes if necessary.
446 public function getLocalFile() {
447 if( is_null( $this->mLocalFile
) ) {
448 $nt = $this->getTitle();
449 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
451 return $this->mLocalFile
;
455 * Stash a file in a temporary directory for later processing
456 * after the user has confirmed it.
458 * If the user doesn't explicitly cancel or accept, these files
459 * can accumulate in the temp directory.
461 * @param string $saveName - the destination filename
462 * @param string $tempSrc - the source temporary file to save
463 * @return string - full path the stashed file, or false on failure
466 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
467 $repo = RepoGroup
::singleton()->getLocalRepo();
468 $status = $repo->storeTemp( $saveName, $tempSrc );
473 * Stash a file in a temporary directory for later processing,
474 * and save the necessary descriptive info into the session.
475 * Returns a key value which will be passed through a form
476 * to pick up the path info on a later invocation.
478 * @return int Session key
480 public function stashSession() {
481 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
482 if( !$status->isOK() ) {
483 # Couldn't save the file.
486 if(!isset($_SESSION))
487 session_start(); // start up the session (might have been previously closed to prevent php session locking)
488 $key = $this->getSessionKey();
489 $_SESSION['wsUploadData'][$key] = array(
490 'mTempPath' => $status->value
,
491 'mFileSize' => $this->mFileSize
,
492 'mFileProps' => $this->mFileProps
,
493 'version' => self
::SESSION_VERSION
,
499 * Generate a random session key from stash in cases where we want to start an upload without much information
501 protected function getSessionKey(){
502 $key = mt_rand( 0, 0x7fffffff );
503 $_SESSION['wsUploadData'][$key] = array();
509 * If we've modified the upload file we need to manually remove it
510 * on exit to clean up.
513 public function cleanupTempFile() {
514 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
515 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
516 unlink( $this->mTempPath
);
520 public function getTempPath() {
521 return $this->mTempPath
;
525 * Split a file into a base name and all dot-delimited 'extensions'
526 * on the end. Some web server configurations will fall back to
527 * earlier pseudo-'extensions' to determine type and execute
528 * scripts, so the blacklist needs to check them all.
532 public static function splitExtensions( $filename ) {
533 $bits = explode( '.', $filename );
534 $basename = array_shift( $bits );
535 return array( $basename, $bits );
539 * Perform case-insensitive match against a list of file extensions.
540 * Returns true if the extension is in the list.
546 public static function checkFileExtension( $ext, $list ) {
547 return in_array( strtolower( $ext ), $list );
551 * Perform case-insensitive match against a list of file extensions.
552 * Returns true if any of the extensions are in the list.
558 public static function checkFileExtensionList( $ext, $list ) {
559 foreach( $ext as $e ) {
560 if( in_array( strtolower( $e ), $list ) ) {
568 * Checks if the mime type of the uploaded file matches the file extension.
570 * @param string $mime the mime type of the uploaded file
571 * @param string $extension The filename extension that the file is to be served with
574 public static function verifyExtension( $mime, $extension ) {
575 $magic = MimeMagic
::singleton();
577 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
578 if ( !$magic->isRecognizableExtension( $extension ) ) {
579 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
580 "unrecognized extension '$extension', can't verify\n" );
583 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
584 "recognized extension '$extension', so probably invalid file\n" );
588 $match = $magic->isMatchingExtension( $extension, $mime );
590 if ( $match === null ) {
591 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
593 } elseif( $match === true ) {
594 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
596 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
600 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
606 * Heuristic for detecting files that *could* contain JavaScript instructions or
607 * things that may look like HTML to a browser and are thus
608 * potentially harmful. The present implementation will produce false positives in some situations.
610 * @param string $file Pathname to the temporary upload file
611 * @param string $mime The mime type of the file
612 * @param string $extension The extension of the file
613 * @return bool true if the file contains something looking like embedded scripts
615 public static function detectScript( $file, $mime, $extension ) {
616 global $wgAllowTitlesInSVG;
618 #ugly hack: for text files, always look at the entire file.
619 #For binary field, just check the first K.
621 if( strpos( $mime,'text/' ) === 0 )
622 $chunk = file_get_contents( $file );
624 $fp = fopen( $file, 'rb' );
625 $chunk = fread( $fp, 1024 );
629 $chunk = strtolower( $chunk );
634 #decode from UTF-16 if needed (could be used for obfuscation).
635 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
637 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
643 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
645 $chunk = trim( $chunk );
647 #FIXME: convert from UTF-16 if necessarry!
648 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
650 #check for HTML doctype
651 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
655 * Internet Explorer for Windows performs some really stupid file type
656 * autodetection which can cause it to interpret valid image files as HTML
657 * and potentially execute JavaScript, creating a cross-site scripting
660 * Apple's Safari browser also performs some unsafe file type autodetection
661 * which can cause legitimate files to be interpreted as HTML if the
662 * web server is not correctly configured to send the right content-type
663 * (or if you're really uploading plain text and octet streams!)
665 * Returns true if IE is likely to mistake the given file for HTML.
666 * Also returns true if Safari would mistake the given file for HTML
667 * when served with a generic content-type.
673 '<html', #also in safari
676 '<script', #also in safari
680 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
684 foreach( $tags as $tag ) {
685 if( false !== strpos( $chunk, $tag ) ) {
691 * look for JavaScript
694 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
695 $chunk = Sanitizer
::decodeCharReferences( $chunk );
697 #look for script-types
698 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
701 #look for html-style script-urls
702 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
705 #look for css-style script-urls
706 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
709 wfDebug( __METHOD__
. ": no scripts found\n" );
713 protected function detectScriptInSvg( $filename ) {
714 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
715 return $check->filterMatch
;
719 * @todo Replace this with a whitelist filter!
721 public function checkSvgScriptCallback( $element, $attribs ) {
722 $stripped = $this->stripXmlNamespace( $element );
724 if( $stripped == 'script' ) {
725 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
729 foreach( $attribs as $attrib => $value ) {
730 $stripped = $this->stripXmlNamespace( $attrib );
731 if( substr( $stripped, 0, 2 ) == 'on' ) {
732 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
735 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
736 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
742 private function stripXmlNamespace( $name ) {
743 // 'http://www.w3.org/2000/svg:script' -> 'script'
744 $parts = explode( ':', strtolower( $name ) );
745 return array_pop( $parts );
749 * Generic wrapper function for a virus scanner program.
750 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
751 * $wgAntivirusRequired may be used to deny upload if the scan fails.
753 * @param string $file Pathname to the temporary upload file
754 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
755 * or a string containing feedback from the virus scanner if a virus was found.
756 * If textual feedback is missing but a virus was found, this function returns true.
758 public static function detectVirus( $file ) {
759 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
761 if ( !$wgAntivirus ) {
762 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
766 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
767 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
768 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>", array( 'virus-badscanner', $wgAntivirus ) );
769 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
772 # look up scanner configuration
773 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
774 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
775 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
776 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
778 if ( strpos( $command,"%f" ) === false ) {
779 # simple pattern: append file to scan
780 $command .= " " . wfEscapeShellArg( $file );
782 # complex pattern: replace "%f" with file to scan
783 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
786 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
788 # execute virus scanner
791 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
792 # that does not seem to be worth the pain.
793 # Ask me (Duesentrieb) about it if it's ever needed.
794 $output = wfShellExec( "$command 2>&1", $exitCode );
796 # map exit code to AV_xxx constants.
797 $mappedCode = $exitCode;
798 if ( $exitCodeMap ) {
799 if ( isset( $exitCodeMap[$exitCode] ) ) {
800 $mappedCode = $exitCodeMap[$exitCode];
801 } elseif ( isset( $exitCodeMap["*"] ) ) {
802 $mappedCode = $exitCodeMap["*"];
806 if ( $mappedCode === AV_SCAN_FAILED
) {
807 # scan failed (code was mapped to false by $exitCodeMap)
808 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
810 if ( $wgAntivirusRequired ) {
811 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
815 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
816 # scan failed because filetype is unknown (probably imune)
817 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
819 } else if ( $mappedCode === AV_NO_VIRUS
) {
821 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
824 $output = trim( $output );
827 $output = true; #if there's no output, return true
828 } elseif ( $msgPattern ) {
830 if ( preg_match( $msgPattern, $output, $groups ) ) {
832 $output = $groups[1];
837 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
843 * Check if the temporary file is MacBinary-encoded, as some uploads
844 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
845 * If so, the data fork will be extracted to a second temporary file,
846 * which will then be checked for validity and either kept or discarded.
850 private function checkMacBinary() {
851 $macbin = new MacBinary( $this->mTempPath
);
852 if( $macbin->isValid() ) {
853 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
854 $dataHandle = fopen( $dataFile, 'wb' );
856 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
857 $macbin->extractData( $dataHandle );
859 $this->mTempPath
= $dataFile;
860 $this->mFileSize
= $macbin->dataForkLength();
862 // We'll have to manually remove the new file if it's not kept.
863 $this->mRemoveTempFile
= true;
869 * Check if there's an overwrite conflict and, if so, if restrictions
870 * forbid this user from performing the upload.
872 * @return mixed true on success, error string on failure
875 private function checkOverwrite() {
877 // First check whether the local file can be overwritten
878 $file = $this->getLocalFile();
879 if( $file->exists() ) {
880 if( !self
::userCanReUpload( $wgUser, $file ) )
881 return 'fileexists-forbidden';
886 /* Check shared conflicts: if the local file does not exist, but
887 * wfFindFile finds a file, it exists in a shared repository.
889 $file = wfFindFile( $this->getTitle() );
890 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) )
891 return 'fileexists-shared-forbidden';
897 * Check if a user is the last uploader
900 * @param string $img, image name
903 public static function userCanReUpload( User
$user, $img ) {
904 if( $user->isAllowed( 'reupload' ) )
905 return true; // non-conditional
906 if( !$user->isAllowed( 'reupload-own' ) )
908 if( is_string( $img ) )
909 $img = wfLocalFile( $img );
910 if ( !( $img instanceof LocalFile
) )
913 return $user->getId() == $img->getUser( 'id' );
917 * Helper function that does various existence checks for a file.
918 * The following checks are performed:
920 * - Article with the same name as the file exists
921 * - File exists with normalized extension
922 * - The file looks like a thumbnail and the original exists
924 * @param File $file The file to check
925 * @return mixed False if the file does not exists, else an array
927 public static function getExistsWarning( $file ) {
928 if( $file->exists() )
929 return array( 'warning' => 'exists', 'file' => $file );
931 if( $file->getTitle()->getArticleID() )
932 return array( 'warning' => 'page-exists', 'file' => $file );
934 if ( $file->wasDeleted() && !$file->exists() )
935 return array( 'warning' => 'was-deleted', 'file' => $file );
937 if( strpos( $file->getName(), '.' ) == false ) {
938 $partname = $file->getName();
941 $n = strrpos( $file->getName(), '.' );
942 $extension = substr( $file->getName(), $n +
1 );
943 $partname = substr( $file->getName(), 0, $n );
945 $normalizedExtension = File
::normalizeExtension( $extension );
947 if ( $normalizedExtension != $extension ) {
948 // We're not using the normalized form of the extension.
949 // Normal form is lowercase, using most common of alternate
950 // extensions (eg 'jpg' rather than 'JPEG').
952 // Check for another file using the normalized form...
953 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
954 $file_lc = wfLocalFile( $nt_lc );
956 if( $file_lc->exists() )
957 return array( 'warning' => 'exists-normalized', 'file' => $file, 'normalizedFile' => $file_lc );
960 if ( self
::isThumbName( $file->getName() ) ) {
961 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
962 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
963 $file_thb = wfLocalFile( $nt_thb );
964 if( $file_thb->exists() )
965 return array( 'warning' => 'thumb', 'file' => $file, 'thumbFile' => $file_thb );
967 // File does not exist, but we just don't like the name
968 return array( 'warning' => 'thumb-name', 'file' => $file, 'thumbFile' => $file_thb );
972 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
973 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix )
974 return array( 'warning' => 'bad-prefix', 'file' => $file, 'prefix' => $prefix );
983 * Helper function that checks whether the filename looks like a thumbnail
985 public static function isThumbName( $filename ) {
986 $n = strrpos( $filename, '.' );
987 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
989 substr( $partname , 3, 3 ) == 'px-' ||
990 substr( $partname , 2, 3 ) == 'px-'
992 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
996 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
998 * @return array list of prefixes
1000 public static function getFilenamePrefixBlacklist() {
1001 $blacklist = array();
1002 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1003 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1004 $lines = explode( "\n", $message );
1005 foreach( $lines as $line ) {
1006 // Remove comment lines
1007 $comment = substr( trim( $line ), 0, 1 );
1008 if ( $comment == '#' ||
$comment == '' ) {
1011 // Remove additional comments after a prefix
1012 $comment = strpos( $line, '#' );
1013 if ( $comment > 0 ) {
1014 $line = substr( $line, 0, $comment-1 );
1016 $blacklist[] = trim( $line );
1022 public function getImageInfo($result) {
1023 $file = $this->getLocalFile();
1024 $imParam = ApiQueryImageInfo
::getPropertyNames();
1025 return ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );