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;
34 const MIN_LENGHT_PARTNAME
= 14;
36 const SESSION_VERSION
= 2;
39 * Returns true if uploads are enabled.
40 * Can be override by subclasses.
42 public static function isEnabled() {
43 global $wgEnableUploads;
44 if ( !$wgEnableUploads )
47 # Check php's file_uploads setting
48 if( !wfIniGetBool( 'file_uploads' ) ) {
55 * Returns true if the user can use this upload module or else a string
56 * identifying the missing permission.
57 * Can be overriden by subclasses.
59 public static function isAllowed( $user ) {
60 if( !$user->isAllowed( 'upload' ) )
65 // Upload handlers. Should probably just be a global
66 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
69 * Create a form of UploadBase depending on wpSourceType and initializes it
71 public static function createFromRequest( &$request, $type = null ) {
72 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
77 // Get the upload class
78 $type = ucfirst( $type );
80 // Give hooks the chance to handle this request
82 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
83 if ( is_null( $className ) ) {
84 $className = 'UploadFrom' . $type;
85 wfDebug( __METHOD__
. ": class name: $className\n" );
86 if( !in_array( $type, self
::$uploadHandlers ) )
90 // Check whether this upload class is enabled
91 if( !call_user_func( array( $className, 'isEnabled' ) ) )
94 // Check whether the request is valid
95 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
98 $handler = new $className;
100 $handler->initializeFromRequest( $request );
105 * Check whether a request if valid for this handler
107 public static function isValidRequest( $request ) {
111 public function __construct() {}
114 * Do the real variable initialization
116 public function initialize( $name, $tempPath, $fileSize, $removeTempFile = false ) {
117 $this->mDesiredDestName
= $name;
118 $this->mTempPath
= $tempPath;
119 $this->mFileSize
= $fileSize;
120 $this->mRemoveTempFile
= $removeTempFile;
124 * Initialize from a WebRequest. Override this in a subclass.
126 public abstract function initializeFromRequest( &$request );
129 * Fetch the file. Usually a no-op
131 public function fetchFile() {
132 return Status
::newGood();
136 * Return the file size
138 public function isEmptyFile(){
139 return empty( $this->mFileSize
);
144 * @param string $srcPath the source path
145 * @returns the real path if it was a virtual url
147 function getRealPath( $srcPath ){
148 $repo = RepoGroup
::singleton()->getLocalRepo();
149 if ( $repo->isVirtualUrl( $srcPath ) ) {
150 return $repo->resolveVirtualUrl( $srcPath );
156 * Verify whether the upload is sane.
157 * Returns self::OK or else an array with error information
159 public function verifyUpload() {
161 * If there was no filename or a zero size given, give up quick.
163 if( $this->isEmptyFile() )
164 return array( 'status' => self
::EMPTY_FILE
);
167 * Look at the contents of the file; if we can recognize the
168 * type but it's corrupt or data of the wrong type, we should
169 * probably not accept it.
171 $verification = $this->verifyFile();
172 if( $verification !== true ) {
173 if( !is_array( $verification ) )
174 $verification = array( $verification );
175 return array( 'status' => self
::VERIFICATION_ERROR
,
176 'details' => $verification );
180 $nt = $this->getTitle();
181 if( is_null( $nt ) ) {
182 $result = array( 'status' => $this->mTitleError
);
183 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
)
184 $result['filtered'] = $this->mFilteredName
;
185 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
)
186 $result['finalExt'] = $this->mFinalExtension
;
189 $this->mDestName
= $this->getLocalFile()->getName();
192 * In some cases we may forbid overwriting of existing files.
194 $overwrite = $this->checkOverwrite();
195 if( $overwrite !== true )
196 return array( 'status' => self
::OVERWRITE_EXISTING_FILE
, 'overwrite' => $overwrite );
199 if( !wfRunHooks( 'UploadVerification',
200 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
201 // This status needs another name...
202 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
205 return array( 'status' => self
::OK
);
209 * Verifies that it's ok to include the uploaded file
211 * FIXME: this function seems to intermixes tmpfile and $this->mTempPath .. no idea why this is
213 * @param string $tmpfile the full path of the temporary file to verify
214 * @return mixed true of the file is verified, a string or array otherwise.
216 protected function verifyFile() {
217 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
218 $this->checkMacBinary();
220 #magically determine mime type
221 $magic = MimeMagic
::singleton();
222 $mime = $magic->guessMimeType( $this->mTempPath
, false );
224 #check mime type, if desired
225 global $wgVerifyMimeType;
226 if ( $wgVerifyMimeType ) {
227 global $wgMimeTypeBlacklist;
228 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
229 return array( 'filetype-badmime', $mime );
232 $fp = fopen( $this->mTempPath
, 'rb' );
233 $chunk = fread( $fp, 256 );
235 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
236 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
237 foreach ( $ieTypes as $ieType ) {
238 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
239 return array( 'filetype-bad-ie-mime', $ieType );
244 #check for htmlish code and javascript
245 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
246 return 'uploadscripted';
248 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
249 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
250 return 'uploadscripted';
255 * Scan the uploaded file for viruses
257 $virus = $this->detectVirus( $this->mTempPath
);
259 return array( 'uploadvirus', $virus );
261 wfDebug( __METHOD__
. ": all clear; passing.\n" );
266 * Check whether the user can edit, upload and create the image.
268 * @param User $user the user to verify the permissions against
269 * @return mixed An array as returned by getUserPermissionsErrors or true
270 * in case the user has proper permissions.
272 public function verifyPermissions( $user ) {
274 * If the image is protected, non-sysop users won't be able
275 * to modify it by uploading a new revision.
277 $nt = $this->getTitle();
280 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
281 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
282 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
283 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
284 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
285 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
292 * Check for non fatal problems with the file
294 * @return array Array of warnings
296 public function checkWarnings() {
299 $localFile = $this->getLocalFile();
300 $filename = $localFile->getName();
301 $n = strrpos( $filename, '.' );
302 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
305 * Check whether the resulting filename is different from the desired one,
306 * but ignore things like ucfirst() and spaces/underscore things
308 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
309 global $wgCapitalLinks, $wgContLang;
310 if ( $wgCapitalLinks ) {
311 $comparableName = $wgContLang->ucfirst( $comparableName );
313 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename )
314 $warnings['badfilename'] = $filename;
316 // Check whether the file extension is on the unwanted list
317 global $wgCheckFileExtensions, $wgFileExtensions;
318 if ( $wgCheckFileExtensions ) {
319 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
320 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
323 global $wgUploadSizeWarning;
324 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) )
325 $warnings['large-file'] = $wgUploadSizeWarning;
327 if ( $this->mFileSize
== 0 )
328 $warnings['emptyfile'] = true;
331 $exists = self
::getExistsWarning( $localFile );
332 if( $exists !== false )
333 $warnings['exists'] = $exists;
335 // Check dupes against existing files
336 $hash = File
::sha1Base36( $this->mTempPath
);
337 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
338 $title = $this->getTitle();
339 // Remove all matches against self
340 foreach ( $dupes as $key => $dupe ) {
341 if( $title->equals( $dupe->getTitle() ) )
342 unset( $dupes[$key] );
345 $warnings['duplicate'] = $dupes;
347 // Check dupes against archives
348 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
349 if ( $archivedImage->getID() > 0 )
350 $warnings['duplicate-archive'] = $archivedImage->getName();
356 * Really perform the upload. Stores the file in the local repo, watches
357 * if necessary and runs the UploadComplete hook.
359 * @return mixed Status indicating the whether the upload succeeded.
361 public function performUpload( $comment, $pageText, $watch, $user ) {
362 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
363 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
364 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
366 if( $status->isGood() && $watch )
367 $user->addWatch( $this->getLocalFile()->getTitle() );
369 if( $status->isGood() )
370 wfRunHooks( 'UploadComplete', array( &$this ) );
376 * Returns the title of the file to be uploaded. Sets mTitleError in case
377 * the name was illegal.
379 * @return Title The title of the file or null in case the name was illegal
381 public function getTitle() {
382 if ( $this->mTitle
!== false )
383 return $this->mTitle
;
386 * Chop off any directories in the given filename. Then
387 * filter out illegal characters, and try to make a legible name
388 * out of it. We'll strip some silently that Title would die on.
390 $basename = $this->mDesiredDestName
;
392 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
393 /* Normalize to title form before we do any further processing */
394 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
395 if( is_null( $nt ) ) {
396 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
397 return $this->mTitle
= null;
399 $this->mFilteredName
= $nt->getDBkey();
402 * We'll want to blacklist against *any* 'extension', and use
403 * only the final one for the whitelist.
405 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
407 if( count( $ext ) ) {
408 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
410 $this->mFinalExtension
= '';
413 /* Don't allow users to override the blacklist (check file extension) */
414 global $wgCheckFileExtensions, $wgStrictFileExtensions;
415 global $wgFileExtensions, $wgFileBlacklist;
416 if ( $this->mFinalExtension
== '' ) {
417 $this->mTitleError
= self
::FILETYPE_MISSING
;
418 return $this->mTitle
= null;
419 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
420 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
421 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
422 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
423 return $this->mTitle
= null;
426 # If there was more than one "extension", reassemble the base
427 # filename to prevent bogus complaints about length
428 if( count( $ext ) > 1 ) {
429 for( $i = 0; $i < count( $ext ) - 1; $i++
)
430 $partname .= '.' . $ext[$i];
433 if( strlen( $partname ) < 1 ) {
434 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
435 return $this->mTitle
= null;
438 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
439 if( is_null( $nt ) ) {
440 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
441 return $this->mTitle
= null;
443 return $this->mTitle
= $nt;
447 * Return the local file and initializes if necessary.
449 public function getLocalFile() {
450 if( is_null( $this->mLocalFile
) ) {
451 $nt = $this->getTitle();
452 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
454 return $this->mLocalFile
;
458 * Stash a file in a temporary directory for later processing
459 * after the user has confirmed it.
461 * If the user doesn't explicitly cancel or accept, these files
462 * can accumulate in the temp directory.
464 * @param string $saveName - the destination filename
465 * @param string $tempSrc - the source temporary file to save
466 * @return string - full path the stashed file, or false on failure
469 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
470 $repo = RepoGroup
::singleton()->getLocalRepo();
471 $status = $repo->storeTemp( $saveName, $tempSrc );
476 * Append a file to a stashed file.
478 * @param string $srcPath Path to file to append from
479 * @param string $toAppendPath Path to file to append to
480 * @return Status Status
482 public function appendToUploadFile( $srcPath, $toAppendPath ){
483 $repo = RepoGroup
::singleton()->getLocalRepo();
484 $status = $repo->append( $srcPath, $toAppendPath );
489 * Stash a file in a temporary directory for later processing,
490 * and save the necessary descriptive info into the session.
491 * Returns a key value which will be passed through a form
492 * to pick up the path info on a later invocation.
494 * @return int Session key
496 public function stashSession() {
497 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
498 if( !$status->isOK() ) {
499 # Couldn't save the file.
502 if(!isset($_SESSION))
503 session_start(); // start up the session (might have been previously closed to prevent php session locking)
504 $key = $this->getSessionKey();
505 $_SESSION['wsUploadData'][$key] = array(
506 'mTempPath' => $status->value
,
507 'mFileSize' => $this->mFileSize
,
508 'mFileProps' => $this->mFileProps
,
509 'version' => self
::SESSION_VERSION
,
515 * Generate a random session key from stash in cases where we want to start an upload without much information
517 protected function getSessionKey(){
518 $key = mt_rand( 0, 0x7fffffff );
519 $_SESSION['wsUploadData'][$key] = array();
525 * If we've modified the upload file we need to manually remove it
526 * on exit to clean up.
529 public function cleanupTempFile() {
530 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
531 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
532 unlink( $this->mTempPath
);
536 public function getTempPath() {
537 return $this->mTempPath
;
541 * Split a file into a base name and all dot-delimited 'extensions'
542 * on the end. Some web server configurations will fall back to
543 * earlier pseudo-'extensions' to determine type and execute
544 * scripts, so the blacklist needs to check them all.
548 public static function splitExtensions( $filename ) {
549 $bits = explode( '.', $filename );
550 $basename = array_shift( $bits );
551 return array( $basename, $bits );
555 * Perform case-insensitive match against a list of file extensions.
556 * Returns true if the extension is in the list.
562 public static function checkFileExtension( $ext, $list ) {
563 return in_array( strtolower( $ext ), $list );
567 * Perform case-insensitive match against a list of file extensions.
568 * Returns true if any of the extensions are in the list.
574 public static function checkFileExtensionList( $ext, $list ) {
575 foreach( $ext as $e ) {
576 if( in_array( strtolower( $e ), $list ) ) {
584 * Checks if the mime type of the uploaded file matches the file extension.
586 * @param string $mime the mime type of the uploaded file
587 * @param string $extension The filename extension that the file is to be served with
590 public static function verifyExtension( $mime, $extension ) {
591 $magic = MimeMagic
::singleton();
593 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
594 if ( !$magic->isRecognizableExtension( $extension ) ) {
595 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
596 "unrecognized extension '$extension', can't verify\n" );
599 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
600 "recognized extension '$extension', so probably invalid file\n" );
604 $match = $magic->isMatchingExtension( $extension, $mime );
606 if ( $match === NULL ) {
607 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
609 } elseif( $match === true ) {
610 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
612 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
616 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
622 * Heuristic for detecting files that *could* contain JavaScript instructions or
623 * things that may look like HTML to a browser and are thus
624 * potentially harmful. The present implementation will produce false positives in some situations.
626 * @param string $file Pathname to the temporary upload file
627 * @param string $mime The mime type of the file
628 * @param string $extension The extension of the file
629 * @return bool true if the file contains something looking like embedded scripts
631 public static function detectScript( $file, $mime, $extension ) {
632 global $wgAllowTitlesInSVG;
634 #ugly hack: for text files, always look at the entire file.
635 #For binary field, just check the first K.
637 if( strpos( $mime,'text/' ) === 0 )
638 $chunk = file_get_contents( $file );
640 $fp = fopen( $file, 'rb' );
641 $chunk = fread( $fp, 1024 );
645 $chunk = strtolower( $chunk );
650 #decode from UTF-16 if needed (could be used for obfuscation).
651 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
653 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
659 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
661 $chunk = trim( $chunk );
663 #FIXME: convert from UTF-16 if necessarry!
664 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
666 #check for HTML doctype
667 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
671 * Internet Explorer for Windows performs some really stupid file type
672 * autodetection which can cause it to interpret valid image files as HTML
673 * and potentially execute JavaScript, creating a cross-site scripting
676 * Apple's Safari browser also performs some unsafe file type autodetection
677 * which can cause legitimate files to be interpreted as HTML if the
678 * web server is not correctly configured to send the right content-type
679 * (or if you're really uploading plain text and octet streams!)
681 * Returns true if IE is likely to mistake the given file for HTML.
682 * Also returns true if Safari would mistake the given file for HTML
683 * when served with a generic content-type.
689 '<html', #also in safari
692 '<script', #also in safari
696 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
700 foreach( $tags as $tag ) {
701 if( false !== strpos( $chunk, $tag ) ) {
707 * look for JavaScript
710 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
711 $chunk = Sanitizer
::decodeCharReferences( $chunk );
713 #look for script-types
714 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
717 #look for html-style script-urls
718 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
721 #look for css-style script-urls
722 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
725 wfDebug( __METHOD__
. ": no scripts found\n" );
729 protected function detectScriptInSvg( $filename ) {
730 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
731 return $check->filterMatch
;
735 * @todo Replace this with a whitelist filter!
737 public function checkSvgScriptCallback( $element, $attribs ) {
738 $stripped = $this->stripXmlNamespace( $element );
740 if( $stripped == 'script' ) {
741 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
745 foreach( $attribs as $attrib => $value ) {
746 $stripped = $this->stripXmlNamespace( $attrib );
747 if( substr( $stripped, 0, 2 ) == 'on' ) {
748 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
751 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
752 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
758 private function stripXmlNamespace( $name ) {
759 // 'http://www.w3.org/2000/svg:script' -> 'script'
760 $parts = explode( ':', strtolower( $name ) );
761 return array_pop( $parts );
765 * Generic wrapper function for a virus scanner program.
766 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
767 * $wgAntivirusRequired may be used to deny upload if the scan fails.
769 * @param string $file Pathname to the temporary upload file
770 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
771 * or a string containing feedback from the virus scanner if a virus was found.
772 * If textual feedback is missing but a virus was found, this function returns true.
774 public static function detectVirus( $file ) {
775 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
777 if ( !$wgAntivirus ) {
778 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
782 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
783 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
784 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
785 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
788 # look up scanner configuration
789 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
790 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
791 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
792 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
794 if ( strpos( $command,"%f" ) === false ) {
795 # simple pattern: append file to scan
796 $command .= " " . wfEscapeShellArg( $file );
798 # complex pattern: replace "%f" with file to scan
799 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
802 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
804 # execute virus scanner
807 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
808 # that does not seem to be worth the pain.
809 # Ask me (Duesentrieb) about it if it's ever needed.
811 if ( wfIsWindows() ) {
812 exec( "$command", $output, $exitCode );
814 exec( "$command 2>&1", $output, $exitCode );
817 # map exit code to AV_xxx constants.
818 $mappedCode = $exitCode;
819 if ( $exitCodeMap ) {
820 if ( isset( $exitCodeMap[$exitCode] ) ) {
821 $mappedCode = $exitCodeMap[$exitCode];
822 } elseif ( isset( $exitCodeMap["*"] ) ) {
823 $mappedCode = $exitCodeMap["*"];
827 if ( $mappedCode === AV_SCAN_FAILED
) {
828 # scan failed (code was mapped to false by $exitCodeMap)
829 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
831 if ( $wgAntivirusRequired ) {
832 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
836 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
837 # scan failed because filetype is unknown (probably imune)
838 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
840 } else if ( $mappedCode === AV_NO_VIRUS
) {
842 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
845 $output = join( "\n", $output );
846 $output = trim( $output );
849 $output = true; #if there's no output, return true
850 } elseif ( $msgPattern ) {
852 if ( preg_match( $msgPattern, $output, $groups ) ) {
854 $output = $groups[1];
859 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
865 * Check if the temporary file is MacBinary-encoded, as some uploads
866 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
867 * If so, the data fork will be extracted to a second temporary file,
868 * which will then be checked for validity and either kept or discarded.
872 private function checkMacBinary() {
873 $macbin = new MacBinary( $this->mTempPath
);
874 if( $macbin->isValid() ) {
875 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
876 $dataHandle = fopen( $dataFile, 'wb' );
878 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
879 $macbin->extractData( $dataHandle );
881 $this->mTempPath
= $dataFile;
882 $this->mFileSize
= $macbin->dataForkLength();
884 // We'll have to manually remove the new file if it's not kept.
885 $this->mRemoveTempFile
= true;
891 * Check if there's an overwrite conflict and, if so, if restrictions
892 * forbid this user from performing the upload.
894 * @return mixed true on success, error string on failure
897 private function checkOverwrite() {
899 // First check whether the local file can be overwritten
900 $file = $this->getLocalFile();
901 if( $file->exists() ) {
902 if( !self
::userCanReUpload( $wgUser, $file ) )
903 return 'fileexists-forbidden';
908 /* Check shared conflicts: if the local file does not exist, but
909 * wfFindFile finds a file, it exists in a shared repository.
911 $file = wfFindFile( $this->getTitle() );
912 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) )
913 return 'fileexists-shared-forbidden';
919 * Check if a user is the last uploader
922 * @param string $img, image name
925 public static function userCanReUpload( User
$user, $img ) {
926 if( $user->isAllowed( 'reupload' ) )
927 return true; // non-conditional
928 if( !$user->isAllowed( 'reupload-own' ) )
930 if( is_string( $img ) )
931 $img = wfLocalFile( $img );
932 if ( !( $img instanceof LocalFile
) )
935 return $user->getId() == $img->getUser( 'id' );
939 * Helper function that does various existence checks for a file.
940 * The following checks are performed:
942 * - Article with the same name as the file exists
943 * - File exists with normalized extension
944 * - The file looks like a thumbnail and the original exists
946 * @param File $file The file to check
947 * @return mixed False if the file does not exists, else an array
949 public static function getExistsWarning( $file ) {
950 if( $file->exists() )
951 return array( 'warning' => 'exists', 'file' => $file );
953 if( $file->getTitle()->getArticleID() )
954 return array( 'warning' => 'page-exists', 'file' => $file );
956 if ( $file->wasDeleted() && !$file->exists() )
957 return array( 'warning' => 'was-deleted', 'file' => $file );
959 if( strpos( $file->getName(), '.' ) == false ) {
960 $partname = $file->getName();
963 $n = strrpos( $file->getName(), '.' );
964 $extension = substr( $file->getName(), $n +
1 );
965 $partname = substr( $file->getName(), 0, $n );
967 $normalizedExtension = File
::normalizeExtension( $extension );
969 if ( $normalizedExtension != $extension ) {
970 // We're not using the normalized form of the extension.
971 // Normal form is lowercase, using most common of alternate
972 // extensions (eg 'jpg' rather than 'JPEG').
974 // Check for another file using the normalized form...
975 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
976 $file_lc = wfLocalFile( $nt_lc );
978 if( $file_lc->exists() )
979 return array( 'warning' => 'exists-normalized', 'file' => $file, 'normalizedFile' => $file_lc );
982 if ( self
::isThumbName( $file->getName() ) ) {
983 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
984 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
985 $file_thb = wfLocalFile( $nt_thb );
986 if( $file_thb->exists() )
987 return array( 'warning' => 'thumb', 'file' => $file, 'thumbFile' => $file_thb );
989 // File does not exist, but we just don't like the name
990 return array( 'warning' => 'thumb-name', 'file' => $file, 'thumbFile' => $file_thb );
994 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
995 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix )
996 return array( 'warning' => 'bad-prefix', 'file' => $file, 'prefix' => $prefix );
1005 * Helper function that checks whether the filename looks like a thumbnail
1007 public static function isThumbName( $filename ) {
1008 $n = strrpos( $filename, '.' );
1009 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1011 substr( $partname , 3, 3 ) == 'px-' ||
1012 substr( $partname , 2, 3 ) == 'px-'
1014 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1018 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1020 * @return array list of prefixes
1022 public static function getFilenamePrefixBlacklist() {
1023 $blacklist = array();
1024 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1025 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1026 $lines = explode( "\n", $message );
1027 foreach( $lines as $line ) {
1028 // Remove comment lines
1029 $comment = substr( trim( $line ), 0, 1 );
1030 if ( $comment == '#' ||
$comment == '' ) {
1033 // Remove additional comments after a prefix
1034 $comment = strpos( $line, '#' );
1035 if ( $comment > 0 ) {
1036 $line = substr( $line, 0, $comment-1 );
1038 $blacklist[] = trim( $line );