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 * Initialize the path information
114 * @param $name string the desired destination name
115 * @param $tempPath string the temporary path
116 * @param $fileSize int the file size
117 * @param $removeTempFile bool (false) remove the temporary file?
120 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
121 $this->mDesiredDestName
= $name;
122 $this->mTempPath
= $tempPath;
123 $this->mFileSize
= $fileSize;
124 $this->mRemoveTempFile
= $removeTempFile;
128 * Initialize from a WebRequest. Override this in a subclass.
130 public abstract function initializeFromRequest( &$request );
133 * Fetch the file. Usually a no-op
135 public function fetchFile() {
136 return Status
::newGood();
140 * Return the file size
142 public function isEmptyFile(){
143 return empty( $this->mFileSize
);
148 * @param string $srcPath the source path
149 * @returns the real path if it was a virtual url
151 function getRealPath( $srcPath ){
152 $repo = RepoGroup
::singleton()->getLocalRepo();
153 if ( $repo->isVirtualUrl( $srcPath ) ) {
154 return $repo->resolveVirtualUrl( $srcPath );
160 * Verify whether the upload is sane.
161 * Returns self::OK or else an array with error information
163 public function verifyUpload() {
165 * If there was no filename or a zero size given, give up quick.
167 if( $this->isEmptyFile() )
168 return array( 'status' => self
::EMPTY_FILE
);
171 * Look at the contents of the file; if we can recognize the
172 * type but it's corrupt or data of the wrong type, we should
173 * probably not accept it.
175 $verification = $this->verifyFile();
176 if( $verification !== true ) {
177 if( !is_array( $verification ) )
178 $verification = array( $verification );
179 return array( 'status' => self
::VERIFICATION_ERROR
,
180 'details' => $verification );
184 $nt = $this->getTitle();
185 if( is_null( $nt ) ) {
186 $result = array( 'status' => $this->mTitleError
);
187 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
)
188 $result['filtered'] = $this->mFilteredName
;
189 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
)
190 $result['finalExt'] = $this->mFinalExtension
;
193 $this->mDestName
= $this->getLocalFile()->getName();
196 * In some cases we may forbid overwriting of existing files.
198 $overwrite = $this->checkOverwrite();
199 if( $overwrite !== true )
200 return array( 'status' => self
::OVERWRITE_EXISTING_FILE
, 'overwrite' => $overwrite );
203 if( !wfRunHooks( 'UploadVerification',
204 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
205 // This status needs another name...
206 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
209 return array( 'status' => self
::OK
);
213 * Verifies that it's ok to include the uploaded file
215 * @return mixed true of the file is verified, a string or array otherwise.
217 protected function verifyFile() {
218 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
219 $this->checkMacBinary();
221 #magically determine mime type
222 $magic = MimeMagic
::singleton();
223 $mime = $magic->guessMimeType( $this->mTempPath
, false );
225 #check mime type, if desired
226 global $wgVerifyMimeType;
227 if ( $wgVerifyMimeType ) {
228 global $wgMimeTypeBlacklist;
229 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
230 return array( 'filetype-badmime', $mime );
233 $fp = fopen( $this->mTempPath
, 'rb' );
234 $chunk = fread( $fp, 256 );
236 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
237 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
238 foreach ( $ieTypes as $ieType ) {
239 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
240 return array( 'filetype-bad-ie-mime', $ieType );
245 #check for htmlish code and javascript
246 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
247 return 'uploadscripted';
249 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
250 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
251 return 'uploadscripted';
256 * Scan the uploaded file for viruses
258 $virus = $this->detectVirus( $this->mTempPath
);
260 return array( 'uploadvirus', $virus );
262 wfDebug( __METHOD__
. ": all clear; passing.\n" );
267 * Check whether the user can edit, upload and create the image.
269 * @param User $user the user to verify the permissions against
270 * @return mixed An array as returned by getUserPermissionsErrors or true
271 * in case the user has proper permissions.
273 public function verifyPermissions( $user ) {
275 * If the image is protected, non-sysop users won't be able
276 * to modify it by uploading a new revision.
278 $nt = $this->getTitle();
281 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
282 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
283 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
284 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
285 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
286 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
293 * Check for non fatal problems with the file
295 * @return array Array of warnings
297 public function checkWarnings() {
300 $localFile = $this->getLocalFile();
301 $filename = $localFile->getName();
302 $n = strrpos( $filename, '.' );
303 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
306 * Check whether the resulting filename is different from the desired one,
307 * but ignore things like ucfirst() and spaces/underscore things
309 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
310 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
312 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename )
313 $warnings['badfilename'] = $filename;
315 // Check whether the file extension is on the unwanted list
316 global $wgCheckFileExtensions, $wgFileExtensions;
317 if ( $wgCheckFileExtensions ) {
318 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
319 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
322 global $wgUploadSizeWarning;
323 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) )
324 $warnings['large-file'] = $wgUploadSizeWarning;
326 if ( $this->mFileSize
== 0 )
327 $warnings['emptyfile'] = true;
330 $exists = self
::getExistsWarning( $localFile );
331 if( $exists !== false )
332 $warnings['exists'] = $exists;
334 // Check dupes against existing files
335 $hash = File
::sha1Base36( $this->mTempPath
);
336 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
337 $title = $this->getTitle();
338 // Remove all matches against self
339 foreach ( $dupes as $key => $dupe ) {
340 if( $title->equals( $dupe->getTitle() ) )
341 unset( $dupes[$key] );
344 $warnings['duplicate'] = $dupes;
346 // Check dupes against archives
347 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
348 if ( $archivedImage->getID() > 0 )
349 $warnings['duplicate-archive'] = $archivedImage->getName();
355 * Really perform the upload. Stores the file in the local repo, watches
356 * if necessary and runs the UploadComplete hook.
358 * @return mixed Status indicating the whether the upload succeeded.
360 public function performUpload( $comment, $pageText, $watch, $user ) {
361 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
362 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
363 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
365 if( $status->isGood() && $watch )
366 $user->addWatch( $this->getLocalFile()->getTitle() );
368 if( $status->isGood() )
369 wfRunHooks( 'UploadComplete', array( &$this ) );
375 * Returns the title of the file to be uploaded. Sets mTitleError in case
376 * the name was illegal.
378 * @return Title The title of the file or null in case the name was illegal
380 public function getTitle() {
381 if ( $this->mTitle
!== false )
382 return $this->mTitle
;
385 * Chop off any directories in the given filename. Then
386 * filter out illegal characters, and try to make a legible name
387 * out of it. We'll strip some silently that Title would die on.
389 $basename = $this->mDesiredDestName
;
391 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
392 /* Normalize to title form before we do any further processing */
393 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
394 if( is_null( $nt ) ) {
395 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
396 return $this->mTitle
= null;
398 $this->mFilteredName
= $nt->getDBkey();
401 * We'll want to blacklist against *any* 'extension', and use
402 * only the final one for the whitelist.
404 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
406 if( count( $ext ) ) {
407 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
409 $this->mFinalExtension
= '';
412 /* Don't allow users to override the blacklist (check file extension) */
413 global $wgCheckFileExtensions, $wgStrictFileExtensions;
414 global $wgFileExtensions, $wgFileBlacklist;
415 if ( $this->mFinalExtension
== '' ) {
416 $this->mTitleError
= self
::FILETYPE_MISSING
;
417 return $this->mTitle
= null;
418 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
419 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
420 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
421 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
422 return $this->mTitle
= null;
425 # If there was more than one "extension", reassemble the base
426 # filename to prevent bogus complaints about length
427 if( count( $ext ) > 1 ) {
428 for( $i = 0; $i < count( $ext ) - 1; $i++
)
429 $partname .= '.' . $ext[$i];
432 if( strlen( $partname ) < 1 ) {
433 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
434 return $this->mTitle
= null;
437 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
438 if( is_null( $nt ) ) {
439 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
440 return $this->mTitle
= null;
442 return $this->mTitle
= $nt;
446 * Return the local file and initializes if necessary.
448 public function getLocalFile() {
449 if( is_null( $this->mLocalFile
) ) {
450 $nt = $this->getTitle();
451 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
453 return $this->mLocalFile
;
457 * Stash a file in a temporary directory for later processing
458 * after the user has confirmed it.
460 * If the user doesn't explicitly cancel or accept, these files
461 * can accumulate in the temp directory.
463 * @param string $saveName - the destination filename
464 * @param string $tempSrc - the source temporary file to save
465 * @return string - full path the stashed file, or false on failure
468 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
469 $repo = RepoGroup
::singleton()->getLocalRepo();
470 $status = $repo->storeTemp( $saveName, $tempSrc );
475 * Stash a file in a temporary directory for later processing,
476 * and save the necessary descriptive info into the session.
477 * Returns a key value which will be passed through a form
478 * to pick up the path info on a later invocation.
480 * @return int Session key
482 public function stashSession() {
483 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
484 if( !$status->isOK() ) {
485 # Couldn't save the file.
488 if(!isset($_SESSION))
489 session_start(); // start up the session (might have been previously closed to prevent php session locking)
490 $key = $this->getSessionKey();
491 $_SESSION['wsUploadData'][$key] = array(
492 'mTempPath' => $status->value
,
493 'mFileSize' => $this->mFileSize
,
494 'mFileProps' => $this->mFileProps
,
495 'version' => self
::SESSION_VERSION
,
501 * Generate a random session key from stash in cases where we want to start an upload without much information
503 protected function getSessionKey(){
504 $key = mt_rand( 0, 0x7fffffff );
505 $_SESSION['wsUploadData'][$key] = array();
511 * If we've modified the upload file we need to manually remove it
512 * on exit to clean up.
515 public function cleanupTempFile() {
516 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
517 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
518 unlink( $this->mTempPath
);
522 public function getTempPath() {
523 return $this->mTempPath
;
527 * Split a file into a base name and all dot-delimited 'extensions'
528 * on the end. Some web server configurations will fall back to
529 * earlier pseudo-'extensions' to determine type and execute
530 * scripts, so the blacklist needs to check them all.
534 public static function splitExtensions( $filename ) {
535 $bits = explode( '.', $filename );
536 $basename = array_shift( $bits );
537 return array( $basename, $bits );
541 * Perform case-insensitive match against a list of file extensions.
542 * Returns true if the extension is in the list.
548 public static function checkFileExtension( $ext, $list ) {
549 return in_array( strtolower( $ext ), $list );
553 * Perform case-insensitive match against a list of file extensions.
554 * Returns true if any of the extensions are in the list.
560 public static function checkFileExtensionList( $ext, $list ) {
561 foreach( $ext as $e ) {
562 if( in_array( strtolower( $e ), $list ) ) {
570 * Checks if the mime type of the uploaded file matches the file extension.
572 * @param string $mime the mime type of the uploaded file
573 * @param string $extension The filename extension that the file is to be served with
576 public static function verifyExtension( $mime, $extension ) {
577 $magic = MimeMagic
::singleton();
579 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
580 if ( !$magic->isRecognizableExtension( $extension ) ) {
581 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
582 "unrecognized extension '$extension', can't verify\n" );
585 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
586 "recognized extension '$extension', so probably invalid file\n" );
590 $match = $magic->isMatchingExtension( $extension, $mime );
592 if ( $match === null ) {
593 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
595 } elseif( $match === true ) {
596 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
598 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
602 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
608 * Heuristic for detecting files that *could* contain JavaScript instructions or
609 * things that may look like HTML to a browser and are thus
610 * potentially harmful. The present implementation will produce false positives in some situations.
612 * @param string $file Pathname to the temporary upload file
613 * @param string $mime The mime type of the file
614 * @param string $extension The extension of the file
615 * @return bool true if the file contains something looking like embedded scripts
617 public static function detectScript( $file, $mime, $extension ) {
618 global $wgAllowTitlesInSVG;
620 #ugly hack: for text files, always look at the entire file.
621 #For binary field, just check the first K.
623 if( strpos( $mime,'text/' ) === 0 )
624 $chunk = file_get_contents( $file );
626 $fp = fopen( $file, 'rb' );
627 $chunk = fread( $fp, 1024 );
631 $chunk = strtolower( $chunk );
636 #decode from UTF-16 if needed (could be used for obfuscation).
637 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
639 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
645 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
647 $chunk = trim( $chunk );
649 #FIXME: convert from UTF-16 if necessarry!
650 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
652 #check for HTML doctype
653 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
657 * Internet Explorer for Windows performs some really stupid file type
658 * autodetection which can cause it to interpret valid image files as HTML
659 * and potentially execute JavaScript, creating a cross-site scripting
662 * Apple's Safari browser also performs some unsafe file type autodetection
663 * which can cause legitimate files to be interpreted as HTML if the
664 * web server is not correctly configured to send the right content-type
665 * (or if you're really uploading plain text and octet streams!)
667 * Returns true if IE is likely to mistake the given file for HTML.
668 * Also returns true if Safari would mistake the given file for HTML
669 * when served with a generic content-type.
675 '<html', #also in safari
678 '<script', #also in safari
682 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
686 foreach( $tags as $tag ) {
687 if( false !== strpos( $chunk, $tag ) ) {
693 * look for JavaScript
696 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
697 $chunk = Sanitizer
::decodeCharReferences( $chunk );
699 #look for script-types
700 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
703 #look for html-style script-urls
704 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
707 #look for css-style script-urls
708 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
711 wfDebug( __METHOD__
. ": no scripts found\n" );
715 protected function detectScriptInSvg( $filename ) {
716 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
717 return $check->filterMatch
;
721 * @todo Replace this with a whitelist filter!
723 public function checkSvgScriptCallback( $element, $attribs ) {
724 $stripped = $this->stripXmlNamespace( $element );
726 if( $stripped == 'script' ) {
727 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
731 foreach( $attribs as $attrib => $value ) {
732 $stripped = $this->stripXmlNamespace( $attrib );
733 if( substr( $stripped, 0, 2 ) == 'on' ) {
734 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
737 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
738 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
744 private function stripXmlNamespace( $name ) {
745 // 'http://www.w3.org/2000/svg:script' -> 'script'
746 $parts = explode( ':', strtolower( $name ) );
747 return array_pop( $parts );
751 * Generic wrapper function for a virus scanner program.
752 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
753 * $wgAntivirusRequired may be used to deny upload if the scan fails.
755 * @param string $file Pathname to the temporary upload file
756 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
757 * or a string containing feedback from the virus scanner if a virus was found.
758 * If textual feedback is missing but a virus was found, this function returns true.
760 public static function detectVirus( $file ) {
761 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
763 if ( !$wgAntivirus ) {
764 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
768 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
769 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
770 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>", array( 'virus-badscanner', $wgAntivirus ) );
771 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
774 # look up scanner configuration
775 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
776 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
777 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
778 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
780 if ( strpos( $command,"%f" ) === false ) {
781 # simple pattern: append file to scan
782 $command .= " " . wfEscapeShellArg( $file );
784 # complex pattern: replace "%f" with file to scan
785 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
788 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
790 # execute virus scanner
793 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
794 # that does not seem to be worth the pain.
795 # Ask me (Duesentrieb) about it if it's ever needed.
796 $output = wfShellExec( "$command 2>&1", $exitCode );
798 # map exit code to AV_xxx constants.
799 $mappedCode = $exitCode;
800 if ( $exitCodeMap ) {
801 if ( isset( $exitCodeMap[$exitCode] ) ) {
802 $mappedCode = $exitCodeMap[$exitCode];
803 } elseif ( isset( $exitCodeMap["*"] ) ) {
804 $mappedCode = $exitCodeMap["*"];
808 if ( $mappedCode === AV_SCAN_FAILED
) {
809 # scan failed (code was mapped to false by $exitCodeMap)
810 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
812 if ( $wgAntivirusRequired ) {
813 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
817 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
818 # scan failed because filetype is unknown (probably imune)
819 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
821 } else if ( $mappedCode === AV_NO_VIRUS
) {
823 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
826 $output = trim( $output );
829 $output = true; #if there's no output, return true
830 } elseif ( $msgPattern ) {
832 if ( preg_match( $msgPattern, $output, $groups ) ) {
834 $output = $groups[1];
839 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
845 * Check if the temporary file is MacBinary-encoded, as some uploads
846 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
847 * If so, the data fork will be extracted to a second temporary file,
848 * which will then be checked for validity and either kept or discarded.
852 private function checkMacBinary() {
853 $macbin = new MacBinary( $this->mTempPath
);
854 if( $macbin->isValid() ) {
855 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
856 $dataHandle = fopen( $dataFile, 'wb' );
858 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
859 $macbin->extractData( $dataHandle );
861 $this->mTempPath
= $dataFile;
862 $this->mFileSize
= $macbin->dataForkLength();
864 // We'll have to manually remove the new file if it's not kept.
865 $this->mRemoveTempFile
= true;
871 * Check if there's an overwrite conflict and, if so, if restrictions
872 * forbid this user from performing the upload.
874 * @return mixed true on success, error string on failure
877 private function checkOverwrite() {
879 // First check whether the local file can be overwritten
880 $file = $this->getLocalFile();
881 if( $file->exists() ) {
882 if( !self
::userCanReUpload( $wgUser, $file ) )
883 return 'fileexists-forbidden';
888 /* Check shared conflicts: if the local file does not exist, but
889 * wfFindFile finds a file, it exists in a shared repository.
891 $file = wfFindFile( $this->getTitle() );
892 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) )
893 return 'fileexists-shared-forbidden';
899 * Check if a user is the last uploader
902 * @param string $img, image name
905 public static function userCanReUpload( User
$user, $img ) {
906 if( $user->isAllowed( 'reupload' ) )
907 return true; // non-conditional
908 if( !$user->isAllowed( 'reupload-own' ) )
910 if( is_string( $img ) )
911 $img = wfLocalFile( $img );
912 if ( !( $img instanceof LocalFile
) )
915 return $user->getId() == $img->getUser( 'id' );
919 * Helper function that does various existence checks for a file.
920 * The following checks are performed:
922 * - Article with the same name as the file exists
923 * - File exists with normalized extension
924 * - The file looks like a thumbnail and the original exists
926 * @param File $file The file to check
927 * @return mixed False if the file does not exists, else an array
929 public static function getExistsWarning( $file ) {
930 if( $file->exists() )
931 return array( 'warning' => 'exists', 'file' => $file );
933 if( $file->getTitle()->getArticleID() )
934 return array( 'warning' => 'page-exists', 'file' => $file );
936 if ( $file->wasDeleted() && !$file->exists() )
937 return array( 'warning' => 'was-deleted', 'file' => $file );
939 if( strpos( $file->getName(), '.' ) == false ) {
940 $partname = $file->getName();
943 $n = strrpos( $file->getName(), '.' );
944 $extension = substr( $file->getName(), $n +
1 );
945 $partname = substr( $file->getName(), 0, $n );
947 $normalizedExtension = File
::normalizeExtension( $extension );
949 if ( $normalizedExtension != $extension ) {
950 // We're not using the normalized form of the extension.
951 // Normal form is lowercase, using most common of alternate
952 // extensions (eg 'jpg' rather than 'JPEG').
954 // Check for another file using the normalized form...
955 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
956 $file_lc = wfLocalFile( $nt_lc );
958 if( $file_lc->exists() )
959 return array( 'warning' => 'exists-normalized', 'file' => $file, 'normalizedFile' => $file_lc );
962 if ( self
::isThumbName( $file->getName() ) ) {
963 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
964 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
965 $file_thb = wfLocalFile( $nt_thb );
966 if( $file_thb->exists() )
967 return array( 'warning' => 'thumb', 'file' => $file, 'thumbFile' => $file_thb );
969 // File does not exist, but we just don't like the name
970 return array( 'warning' => 'thumb-name', 'file' => $file, 'thumbFile' => $file_thb );
974 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
975 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix )
976 return array( 'warning' => 'bad-prefix', 'file' => $file, 'prefix' => $prefix );
985 * Helper function that checks whether the filename looks like a thumbnail
987 public static function isThumbName( $filename ) {
988 $n = strrpos( $filename, '.' );
989 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
991 substr( $partname , 3, 3 ) == 'px-' ||
992 substr( $partname , 2, 3 ) == 'px-'
994 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
998 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1000 * @return array list of prefixes
1002 public static function getFilenamePrefixBlacklist() {
1003 $blacklist = array();
1004 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1005 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1006 $lines = explode( "\n", $message );
1007 foreach( $lines as $line ) {
1008 // Remove comment lines
1009 $comment = substr( trim( $line ), 0, 1 );
1010 if ( $comment == '#' ||
$comment == '' ) {
1013 // Remove additional comments after a prefix
1014 $comment = strpos( $line, '#' );
1015 if ( $comment > 0 ) {
1016 $line = substr( $line, 0, $comment-1 );
1018 $blacklist[] = trim( $line );
1024 public function getImageInfo($result) {
1025 $file = $this->getLocalFile();
1026 $imParam = ApiQueryImageInfo
::getPropertyNames();
1027 return ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );