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;
25 const BEFORE_PROCESSING
= 1;
26 const LARGE_FILE_SERVER
= 2;
28 const MIN_LENGTH_PARTNAME
= 4;
29 const ILLEGAL_FILENAME
= 5;
30 const PROTECTED_PAGE
= 6;
31 const OVERWRITE_EXISTING_FILE
= 7;
32 const FILETYPE_MISSING
= 8;
33 const FILETYPE_BADTYPE
= 9;
34 const VERIFICATION_ERROR
= 10;
35 const UPLOAD_VERIFICATION_ERROR
= 11;
36 const UPLOAD_WARNING
= 12;
37 const INTERNAL_ERROR
= 13;
38 const MIN_LENGHT_PARTNAME
= 14;
40 const SESSION_VERSION
= 2;
43 * Returns true if uploads are enabled.
44 * Can be override by subclasses.
46 public static function isEnabled() {
47 global $wgEnableUploads;
48 if ( !$wgEnableUploads )
51 # Check php's file_uploads setting
52 if( !wfIniGetBool( 'file_uploads' ) ) {
59 * Returns true if the user can use this upload module or else a string
60 * identifying the missing permission.
61 * Can be overriden by subclasses.
63 public static function isAllowed( $user ) {
64 if( !$user->isAllowed( 'upload' ) )
69 // Upload handlers. Should probably just be a global
70 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
73 * Create a form of UploadBase depending on wpSourceType and initializes it
75 public static function createFromRequest( &$request, $type = null ) {
76 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
81 // Get the upload class
82 $type = ucfirst( $type );
83 $className = 'UploadFrom' . $type;
84 wfDebug( __METHOD__
. ": class name: $className\n" );
85 if( !in_array( $type, self
::$uploadHandlers ) )
88 // Check whether this upload class is enabled
89 if( !call_user_func( array( $className, 'isEnabled' ) ) )
92 // Check whether the request is valid
93 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
96 $handler = new $className;
98 $handler->initializeFromRequest( $request );
103 * Check whether a request if valid for this handler
105 public static function isValidRequest( $request ) {
109 public function __construct() {}
112 * Do the real variable initialization
114 public function initialize( $name, $tempPath, $fileSize, $removeTempFile = false ) {
115 $this->mDesiredDestName
= $name;
116 $this->mTempPath
= $tempPath;
117 $this->mFileSize
= $fileSize;
118 $this->mRemoveTempFile
= $removeTempFile;
122 * Initialize from a WebRequest. Override this in a subclass.
124 public abstract function initializeFromRequest( &$request );
127 * Fetch the file. Usually a no-op
129 public function fetchFile() {
130 return Status
::newGood();
134 * Return the file size
136 public function isEmptyFile(){
137 return empty( $this->mFileSize
);
141 * Verify whether the upload is sane.
142 * Returns self::OK or else an array with error information
144 public function verifyUpload() {
146 * If there was no filename or a zero size given, give up quick.
148 if( $this->isEmptyFile() )
149 return array( 'status' => self
::EMPTY_FILE
);
151 $nt = $this->getTitle();
152 if( is_null( $nt ) ) {
153 $result = array( 'status' => $this->mTitleError
);
154 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
)
155 $result['filtered'] = $this->mFilteredName
;
156 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
)
157 $result['finalExt'] = $this->mFinalExtension
;
160 $this->mDestName
= $this->getLocalFile()->getName();
163 * In some cases we may forbid overwriting of existing files.
165 $overwrite = $this->checkOverwrite();
166 if( $overwrite !== true )
167 return array( 'status' => self
::OVERWRITE_EXISTING_FILE
, 'overwrite' => $overwrite );
170 * Look at the contents of the file; if we can recognize the
171 * type but it's corrupt or data of the wrong type, we should
172 * probably not accept it.
174 $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 );
185 if( !wfRunHooks( 'UploadVerification',
186 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
187 // This status needs another name...
188 return array( 'status' => self
::UPLOAD_VERIFICATION_ERROR
, 'error' => $error );
191 return array( 'status' => self
::OK
);
195 * Verifies that it's ok to include the uploaded file
197 * FIXME: this function seems to intermixes tmpfile and $this->mTempPath .. no idea why this is
199 * @param string $tmpfile the full path of the temporary file to verify
200 * @return mixed true of the file is verified, a string or array otherwise.
202 protected function verifyFile() {
203 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
204 $this->checkMacBinary();
206 #magically determine mime type
207 $magic = MimeMagic
::singleton();
208 $mime = $magic->guessMimeType( $this->mTempPath
, false );
210 #check mime type, if desired
211 global $wgVerifyMimeType;
212 if ( $wgVerifyMimeType ) {
213 global $wgMimeTypeBlacklist;
214 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
215 return array( 'filetype-badmime', $mime );
218 $fp = fopen( $this->mTempPath
, 'rb' );
219 $chunk = fread( $fp, 256 );
221 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
222 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
223 foreach ( $ieTypes as $ieType ) {
224 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
225 return array( 'filetype-bad-ie-mime', $ieType );
230 #check for htmlish code and javascript
231 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
232 return 'uploadscripted';
234 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
235 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
236 return 'uploadscripted';
241 * Scan the uploaded file for viruses
243 $virus = $this->detectVirus( $this->mTempPath
);
245 return array( 'uploadvirus', $virus );
247 wfDebug( __METHOD__
. ": all clear; passing.\n" );
252 * Check whether the user can edit, upload and create the image.
254 * @param User $user the user to verify the permissions against
255 * @return mixed An array as returned by getUserPermissionsErrors or true
256 * in case the user has proper permissions.
258 public function verifyPermissions( $user ) {
260 * If the image is protected, non-sysop users won't be able
261 * to modify it by uploading a new revision.
263 $nt = $this->getTitle();
266 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
267 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
268 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
269 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
270 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
271 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
278 * Check for non fatal problems with the file
280 * @return array Array of warnings
282 public function checkWarnings() {
285 $localFile = $this->getLocalFile();
286 $filename = $localFile->getName();
287 $n = strrpos( $filename, '.' );
288 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
291 * Check whether the resulting filename is different from the desired one,
292 * but ignore things like ucfirst() and spaces/underscore things
294 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
295 global $wgCapitalLinks, $wgContLang;
296 if ( $wgCapitalLinks ) {
297 $comparableName = $wgContLang->ucfirst( $comparableName );
299 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename )
300 $warnings['badfilename'] = $filename;
302 // Check whether the file extension is on the unwanted list
303 global $wgCheckFileExtensions, $wgFileExtensions;
304 if ( $wgCheckFileExtensions ) {
305 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
306 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
309 global $wgUploadSizeWarning;
310 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) )
311 $warnings['large-file'] = $wgUploadSizeWarning;
313 if ( $this->mFileSize
== 0 )
314 $warnings['emptyfile'] = true;
317 $exists = self
::getExistsWarning( $localFile );
318 if( $exists !== false )
319 $warnings['exists'] = $exists;
321 // Check whether this may be a thumbnail
322 if( $exists !== false && $exists[0] != 'thumb'
323 && self
::isThumbName( $filename ) ){
325 $nt = $this->getTitle();
326 $warnings['file-thumbnail-no'] = substr( $filename, 0,
327 strpos( $nt->getText() , '-' ) +
1 );
330 // Check dupes against existing files
331 $hash = File
::sha1Base36( $this->mTempPath
);
332 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
333 $title = $this->getTitle();
334 // Remove all matches against self
335 foreach ( $dupes as $key => $dupe ) {
336 if( $title->equals( $dupe->getTitle() ) )
337 unset( $dupes[$key] );
340 $warnings['duplicate'] = $dupes;
342 // Check dupes against archives
343 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
344 if ( $archivedImage->getID() > 0 )
345 $warnings['duplicate-archive'] = $archivedImage->getName();
347 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
348 foreach( $filenamePrefixBlacklist as $prefix ) {
349 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
350 $warnings['filename-bad-prefix'] = $prefix;
355 # If the file existed before and was deleted, warn the user of this
356 # Don't bother doing so if the file exists now, however
357 if( $localFile->wasDeleted() && !$localFile->exists() )
358 $warnings['filewasdeleted'] = $localFile->getTitle();
364 * Really perform the upload. Stores the file in the local repo, watches
365 * if necessary and runs the UploadComplete hook.
367 * @return mixed Status indicating the whether the upload succeeded.
369 public function performUpload( $comment, $pageText, $watch, $user ) {
370 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
371 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
372 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
374 if( $status->isGood() && $watch )
375 $user->addWatch( $this->getLocalFile()->getTitle() );
377 if( $status->isGood() )
378 wfRunHooks( 'UploadComplete', array( &$this ) );
384 * Returns the title of the file to be uploaded. Sets mTitleError in case
385 * the name was illegal.
387 * @return Title The title of the file or null in case the name was illegal
389 public function getTitle() {
390 if ( $this->mTitle
!== false )
391 return $this->mTitle
;
394 * Chop off any directories in the given filename. Then
395 * filter out illegal characters, and try to make a legible name
396 * out of it. We'll strip some silently that Title would die on.
398 $basename = $this->mDesiredDestName
;
400 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
401 /* Normalize to title form before we do any further processing */
402 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
403 if( is_null( $nt ) ) {
404 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
405 return $this->mTitle
= null;
407 $this->mFilteredName
= $nt->getDBkey();
410 * We'll want to blacklist against *any* 'extension', and use
411 * only the final one for the whitelist.
413 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
415 if( count( $ext ) ) {
416 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
418 $this->mFinalExtension
= '';
421 /* Don't allow users to override the blacklist (check file extension) */
422 global $wgCheckFileExtensions, $wgStrictFileExtensions;
423 global $wgFileExtensions, $wgFileBlacklist;
424 if ( $this->mFinalExtension
== '' ) {
425 $this->mTitleError
= self
::FILETYPE_MISSING
;
426 return $this->mTitle
= null;
427 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
428 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
429 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
430 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
431 return $this->mTitle
= null;
434 # If there was more than one "extension", reassemble the base
435 # filename to prevent bogus complaints about length
436 if( count( $ext ) > 1 ) {
437 for( $i = 0; $i < count( $ext ) - 1; $i++
)
438 $partname .= '.' . $ext[$i];
441 if( strlen( $partname ) < 1 ) {
442 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
443 return $this->mTitle
= null;
446 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
447 if( is_null( $nt ) ) {
448 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
449 return $this->mTitle
= null;
451 return $this->mTitle
= $nt;
455 * Return the local file and initializes if necessary.
457 public function getLocalFile() {
458 if( is_null( $this->mLocalFile
) ) {
459 $nt = $this->getTitle();
460 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
462 return $this->mLocalFile
;
466 * Stash a file in a temporary directory for later processing
467 * after the user has confirmed it.
469 * If the user doesn't explicitly cancel or accept, these files
470 * can accumulate in the temp directory.
472 * @param string $saveName - the destination filename
473 * @param string $tempSrc - the source temporary file to save
474 * @return string - full path the stashed file, or false on failure
477 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
478 $repo = RepoGroup
::singleton()->getLocalRepo();
479 $status = $repo->storeTemp( $saveName, $tempSrc );
484 * Append a file to a stashed file.
486 * @param string $srcPath Path to file to append from
487 * @param string $toAppendPath Path to file to append to
488 * @return Status Status
490 public function appendToUploadFile( $srcPath, $toAppendPath ){
491 $repo = RepoGroup
::singleton()->getLocalRepo();
492 $status = $repo->append( $srcPath, $toAppendPath );
497 * Stash a file in a temporary directory for later processing,
498 * and save the necessary descriptive info into the session.
499 * Returns a key value which will be passed through a form
500 * to pick up the path info on a later invocation.
502 * @return int Session key
504 public function stashSession() {
505 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
506 if( !$status->isOK() ) {
507 # Couldn't save the file.
510 if(!isset($_SESSION))
511 session_start(); // start up the session (might have been previously closed to prevent php session locking)
512 $key = $this->getSessionKey();
513 $_SESSION['wsUploadData'][$key] = array(
514 'mTempPath' => $status->value
,
515 'mFileSize' => $this->mFileSize
,
516 'mFileProps' => $this->mFileProps
,
517 'version' => self
::SESSION_VERSION
,
523 * Generate a random session key from stash in cases where we want to start an upload without much information
525 protected function getSessionKey(){
526 $key = mt_rand( 0, 0x7fffffff );
527 $_SESSION['wsUploadData'][$key] = array();
532 * Remove a temporarily kept file stashed by saveTempUploadedFile().
535 public function unsaveUploadedFile() {
536 $repo = RepoGroup
::singleton()->getLocalRepo();
537 $success = $repo->freeTemp( $this->mTempPath
);
542 * If we've modified the upload file we need to manually remove it
543 * on exit to clean up.
546 public function cleanupTempFile() {
547 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
548 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
549 unlink( $this->mTempPath
);
553 public function getTempPath() {
554 return $this->mTempPath
;
558 * Split a file into a base name and all dot-delimited 'extensions'
559 * on the end. Some web server configurations will fall back to
560 * earlier pseudo-'extensions' to determine type and execute
561 * scripts, so the blacklist needs to check them all.
565 public static function splitExtensions( $filename ) {
566 $bits = explode( '.', $filename );
567 $basename = array_shift( $bits );
568 return array( $basename, $bits );
572 * Perform case-insensitive match against a list of file extensions.
573 * Returns true if the extension is in the list.
579 public static function checkFileExtension( $ext, $list ) {
580 return in_array( strtolower( $ext ), $list );
584 * Perform case-insensitive match against a list of file extensions.
585 * Returns true if any of the extensions are in the list.
591 public static function checkFileExtensionList( $ext, $list ) {
592 foreach( $ext as $e ) {
593 if( in_array( strtolower( $e ), $list ) ) {
601 * Checks if the mime type of the uploaded file matches the file extension.
603 * @param string $mime the mime type of the uploaded file
604 * @param string $extension The filename extension that the file is to be served with
607 public static function verifyExtension( $mime, $extension ) {
608 $magic = MimeMagic
::singleton();
610 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
611 if ( !$magic->isRecognizableExtension( $extension ) ) {
612 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
613 "unrecognized extension '$extension', can't verify\n" );
616 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
617 "recognized extension '$extension', so probably invalid file\n" );
621 $match = $magic->isMatchingExtension( $extension, $mime );
623 if ( $match === NULL ) {
624 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
626 } elseif( $match === true ) {
627 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
629 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
633 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
639 * Heuristic for detecting files that *could* contain JavaScript instructions or
640 * things that may look like HTML to a browser and are thus
641 * potentially harmful. The present implementation will produce false positives in some situations.
643 * @param string $file Pathname to the temporary upload file
644 * @param string $mime The mime type of the file
645 * @param string $extension The extension of the file
646 * @return bool true if the file contains something looking like embedded scripts
648 public static function detectScript( $file, $mime, $extension ) {
649 global $wgAllowTitlesInSVG;
651 #ugly hack: for text files, always look at the entire file.
652 #For binary field, just check the first K.
654 if( strpos( $mime,'text/' ) === 0 )
655 $chunk = file_get_contents( $file );
657 $fp = fopen( $file, 'rb' );
658 $chunk = fread( $fp, 1024 );
662 $chunk = strtolower( $chunk );
667 #decode from UTF-16 if needed (could be used for obfuscation).
668 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
670 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
676 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
678 $chunk = trim( $chunk );
680 #FIXME: convert from UTF-16 if necessarry!
681 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
683 #check for HTML doctype
684 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
688 * Internet Explorer for Windows performs some really stupid file type
689 * autodetection which can cause it to interpret valid image files as HTML
690 * and potentially execute JavaScript, creating a cross-site scripting
693 * Apple's Safari browser also performs some unsafe file type autodetection
694 * which can cause legitimate files to be interpreted as HTML if the
695 * web server is not correctly configured to send the right content-type
696 * (or if you're really uploading plain text and octet streams!)
698 * Returns true if IE is likely to mistake the given file for HTML.
699 * Also returns true if Safari would mistake the given file for HTML
700 * when served with a generic content-type.
706 '<html', #also in safari
709 '<script', #also in safari
713 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
717 foreach( $tags as $tag ) {
718 if( false !== strpos( $chunk, $tag ) ) {
724 * look for JavaScript
727 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
728 $chunk = Sanitizer
::decodeCharReferences( $chunk );
730 #look for script-types
731 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
734 #look for html-style script-urls
735 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
738 #look for css-style script-urls
739 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
742 wfDebug( __METHOD__
. ": no scripts found\n" );
746 protected function detectScriptInSvg( $filename ) {
747 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
748 return $check->filterMatch
;
752 * @todo Replace this with a whitelist filter!
754 public function checkSvgScriptCallback( $element, $attribs ) {
755 $stripped = $this->stripXmlNamespace( $element );
757 if( $stripped == 'script' ) {
758 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
762 foreach( $attribs as $attrib => $value ) {
763 $stripped = $this->stripXmlNamespace( $attrib );
764 if( substr( $stripped, 0, 2 ) == 'on' ) {
765 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
768 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
769 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
775 private function stripXmlNamespace( $name ) {
776 // 'http://www.w3.org/2000/svg:script' -> 'script'
777 $parts = explode( ':', strtolower( $name ) );
778 return array_pop( $parts );
782 * Generic wrapper function for a virus scanner program.
783 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
784 * $wgAntivirusRequired may be used to deny upload if the scan fails.
786 * @param string $file Pathname to the temporary upload file
787 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
788 * or a string containing feedback from the virus scanner if a virus was found.
789 * If textual feedback is missing but a virus was found, this function returns true.
791 public static function detectVirus( $file ) {
792 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
794 if ( !$wgAntivirus ) {
795 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
799 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
800 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
801 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
802 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
805 # look up scanner configuration
806 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
807 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
808 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
809 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
811 if ( strpos( $command,"%f" ) === false ) {
812 # simple pattern: append file to scan
813 $command .= " " . wfEscapeShellArg( $file );
815 # complex pattern: replace "%f" with file to scan
816 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
819 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
821 # execute virus scanner
824 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
825 # that does not seem to be worth the pain.
826 # Ask me (Duesentrieb) about it if it's ever needed.
828 if ( wfIsWindows() ) {
829 exec( "$command", $output, $exitCode );
831 exec( "$command 2>&1", $output, $exitCode );
834 # map exit code to AV_xxx constants.
835 $mappedCode = $exitCode;
836 if ( $exitCodeMap ) {
837 if ( isset( $exitCodeMap[$exitCode] ) ) {
838 $mappedCode = $exitCodeMap[$exitCode];
839 } elseif ( isset( $exitCodeMap["*"] ) ) {
840 $mappedCode = $exitCodeMap["*"];
844 if ( $mappedCode === AV_SCAN_FAILED
) {
845 # scan failed (code was mapped to false by $exitCodeMap)
846 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
848 if ( $wgAntivirusRequired ) {
849 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
853 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
854 # scan failed because filetype is unknown (probably imune)
855 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
857 } else if ( $mappedCode === AV_NO_VIRUS
) {
859 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
862 $output = join( "\n", $output );
863 $output = trim( $output );
866 $output = true; #if there's no output, return true
867 } elseif ( $msgPattern ) {
869 if ( preg_match( $msgPattern, $output, $groups ) ) {
871 $output = $groups[1];
876 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
882 * Check if the temporary file is MacBinary-encoded, as some uploads
883 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
884 * If so, the data fork will be extracted to a second temporary file,
885 * which will then be checked for validity and either kept or discarded.
889 private function checkMacBinary() {
890 $macbin = new MacBinary( $this->mTempPath
);
891 if( $macbin->isValid() ) {
892 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
893 $dataHandle = fopen( $dataFile, 'wb' );
895 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
896 $macbin->extractData( $dataHandle );
898 $this->mTempPath
= $dataFile;
899 $this->mFileSize
= $macbin->dataForkLength();
901 // We'll have to manually remove the new file if it's not kept.
902 $this->mRemoveTempFile
= true;
908 * Check if there's an overwrite conflict and, if so, if restrictions
909 * forbid this user from performing the upload.
911 * @return mixed true on success, error string on failure
914 private function checkOverwrite() {
916 // First check whether the local file can be overwritten
917 $file = $this->getLocalFile();
918 if( $file->exists() )
919 if( !self
::userCanReUpload( $wgUser, $file ) )
920 return 'fileexists-forbidden';
922 // Check shared conflicts
923 $file = wfFindFile( $file->getName() );
924 if ( $file && ( !$wgUser->isAllowed( 'reupload' ) ||
925 !$wgUser->isAllowed( 'reupload-shared' ) ) )
926 return 'fileexists-shared-forbidden';
932 * Check if a user is the last uploader
935 * @param string $img, image name
938 public static function userCanReUpload( User
$user, $img ) {
939 if( $user->isAllowed( 'reupload' ) )
940 return true; // non-conditional
941 if( !$user->isAllowed( 'reupload-own' ) )
943 if( is_string( $img ) )
944 $img = wfLocalFile( $img );
945 if ( !( $img instanceof LocalFile
) )
948 return $user->getId() == $img->getUser( 'id' );
952 * Helper function that does various existence checks for a file.
953 * The following checks are performed:
955 * - Article with the same name as the file exists
956 * - File exists with normalized extension
957 * - The file looks like a thumbnail and the original exists
959 * @param File $file The file to check
960 * @return mixed False if the file does not exists, else an array
962 public static function getExistsWarning( $file ) {
963 if( $file->exists() )
964 return array( 'exists', $file );
966 if( $file->getTitle()->getArticleID() )
967 return array( 'page-exists', $file );
969 if( strpos( $file->getName(), '.' ) == false ) {
970 $partname = $file->getName();
973 $n = strrpos( $file->getName(), '.' );
974 $rawExtension = substr( $file->getName(), $n +
1 );
975 $partname = substr( $file->getName(), 0, $n );
978 if ( $rawExtension != $file->getExtension() ) {
979 // We're not using the normalized form of the extension.
980 // Normal form is lowercase, using most common of alternate
981 // extensions (eg 'jpg' rather than 'JPEG').
983 // Check for another file using the normalized form...
984 $nt_lc = Title
::makeTitle( NS_FILE
, $partname . '.' . $file->getExtension() );
985 $file_lc = wfLocalFile( $nt_lc );
987 if( $file_lc->exists() )
988 return array( 'exists-normalized', $file_lc );
991 if ( self
::isThumbName( $file->getName() ) ) {
992 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
993 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
994 $file_thb = wfLocalFile( $nt_thb );
995 if( $file_thb->exists() )
996 return array( 'thumb', $file_thb );
998 // File does not exist, but we just don't like the name
999 return array( 'thumb-name', $file_thb );
1006 * Helper function that checks whether the filename looks like a thumbnail
1008 public static function isThumbName( $filename ) {
1009 $n = strrpos( $filename, '.' );
1010 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1012 substr( $partname , 3, 3 ) == 'px-' ||
1013 substr( $partname , 2, 3 ) == 'px-'
1015 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1019 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1021 * @return array list of prefixes
1023 public static function getFilenamePrefixBlacklist() {
1024 $blacklist = array();
1025 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1026 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1027 $lines = explode( "\n", $message );
1028 foreach( $lines as $line ) {
1029 // Remove comment lines
1030 $comment = substr( trim( $line ), 0, 1 );
1031 if ( $comment == '#' ||
$comment == '' ) {
1034 // Remove additional comments after a prefix
1035 $comment = strpos( $line, '#' );
1036 if ( $comment > 0 ) {
1037 $line = substr( $line, 0, $comment-1 );
1039 $blacklist[] = trim( $line );