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;
24 const BEFORE_PROCESSING
= 1;
25 const LARGE_FILE_SERVER
= 2;
27 const MIN_LENGTH_PARTNAME
= 4;
28 const ILLEGAL_FILENAME
= 5;
29 const PROTECTED_PAGE
= 6;
30 const OVERWRITE_EXISTING_FILE
= 7;
31 const FILETYPE_MISSING
= 8;
32 const FILETYPE_BADTYPE
= 9;
33 const VERIFICATION_ERROR
= 10;
34 const UPLOAD_VERIFICATION_ERROR
= 11;
35 const UPLOAD_WARNING
= 12;
36 const INTERNAL_ERROR
= 13;
37 const MIN_LENGHT_PARTNAME
= 14;
39 const SESSION_VERSION
= 2;
42 * Returns true if uploads are enabled.
43 * Can be override by subclasses.
45 public static function isEnabled() {
46 global $wgEnableUploads;
47 if ( !$wgEnableUploads )
50 # Check php's file_uploads setting
51 if( !wfIniGetBool( 'file_uploads' ) ) {
58 * Returns true if the user can use this upload module or else a string
59 * identifying the missing permission.
60 * Can be overriden by subclasses.
62 public static function isAllowed( $user ) {
63 if( !$user->isAllowed( 'upload' ) )
68 // Upload handlers. Should probably just be a global
69 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
72 * Create a form of UploadBase depending on wpSourceType and initializes it
74 public static function createFromRequest( &$request, $type = null ) {
75 $type = $type ?
$type : $request->getVal( 'wpSourceType' );
80 // Get the upload class
81 $type = ucfirst( $type );
82 $className = 'UploadFrom' . $type;
83 wfDebug( __METHOD__
. ": class name: $className\n" );
84 if( !in_array( $type, self
::$uploadHandlers ) )
87 // Check whether this upload class is enabled
88 if( !call_user_func( array( $className, 'isEnabled' ) ) )
91 // Check whether the request is valid
92 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
95 $handler = new $className;
97 $handler->initializeFromRequest( $request );
102 * Check whether a request if valid for this handler
104 public static function isValidRequest( $request ) {
108 public function __construct() {}
111 * Do the real variable initialization
113 public function initialize( $name, $tempPath, $fileSize, $removeTempFile = false ) {
114 $this->mDesiredDestName
= $name;
115 $this->mTempPath
= $tempPath;
116 $this->mFileSize
= $fileSize;
117 $this->mRemoveTempFile
= $removeTempFile;
121 * Initialize from a WebRequest. Override this in a subclass.
123 public abstract function initializeFromRequest( &$request );
126 * Fetch the file. Usually a no-op
128 public function fetchFile() {
129 return Status
::newGood();
133 * Return the file size
135 public function isEmptyFile(){
136 return empty( $this->mFileSize
);
140 * Verify whether the upload is sane.
141 * Returns self::OK or else an array with error information
143 public function verifyUpload() {
145 * If there was no filename or a zero size given, give up quick.
147 if( $this->isEmptyFile() )
148 return array( 'status' => self
::EMPTY_FILE
);
150 $nt = $this->getTitle();
151 if( is_null( $nt ) ) {
152 $result = array( 'status' => $this->mTitleError
);
153 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
)
154 $result['filtered'] = $this->mFilteredName
;
155 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
)
156 $result['finalExt'] = $this->mFinalExtension
;
159 $this->mDestName
= $this->getLocalFile()->getName();
162 * In some cases we may forbid overwriting of existing files.
164 $overwrite = $this->checkOverwrite();
165 if( $overwrite !== true )
166 return array( 'status' => self
::OVERWRITE_EXISTING_FILE
, 'overwrite' => $overwrite );
169 * Look at the contents of the file; if we can recognize the
170 * type but it's corrupt or data of the wrong type, we should
171 * probably not accept it.
173 $verification = $this->verifyFile( $this->mTempPath
);
175 if( $verification !== true ) {
176 if( !is_array( $verification ) )
177 $verification = array( $verification );
178 $verification['status'] = self
::VERIFICATION_ERROR
;
179 return $verification;
183 if( !wfRunHooks( 'UploadVerification',
184 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
185 return array( 'status' => self
::UPLOAD_VERIFICATION_ERROR
, 'error' => $error );
192 * Verifies that it's ok to include the uploaded file
194 * FIXME: this function seems to intermixes tmpfile and $this->mTempPath .. no idea why this is
196 * @param string $tmpfile the full path of the temporary file to verify
197 * @return mixed true of the file is verified, a string or array otherwise.
199 protected function verifyFile( $tmpfile ) {
200 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
201 $this->checkMacBinary();
203 #magically determine mime type
204 $magic = MimeMagic
::singleton();
205 $mime = $magic->guessMimeType( $tmpfile, false );
207 #check mime type, if desired
208 global $wgVerifyMimeType;
209 if ( $wgVerifyMimeType ) {
210 global $wgMimeTypeBlacklist;
211 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
212 return array( 'filetype-badmime', $mime );
215 $fp = fopen( $tmpfile, 'rb' );
216 $chunk = fread( $fp, 256 );
218 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
219 $ieTypes = $magic->getIEMimeTypes( $tmpfile, $chunk, $extMime );
220 foreach ( $ieTypes as $ieType ) {
221 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
222 return array( 'filetype-bad-ie-mime', $ieType );
227 #check for htmlish code and javascript
228 if( self
::detectScript( $tmpfile, $mime, $this->mFinalExtension
) ) {
229 return 'uploadscripted';
231 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
232 if( self
::detectScriptInSvg( $tmpfile ) ) {
233 return 'uploadscripted';
238 * Scan the uploaded file for viruses
240 $virus = $this->detectVirus( $tmpfile );
242 return array( 'uploadvirus', $virus );
244 wfDebug( __METHOD__
. ": all clear; passing.\n" );
249 * Check whether the user can edit, upload and create the image.
251 * @param User $user the user to verify the permissions against
252 * @return mixed An array as returned by getUserPermissionsErrors or true
253 * in case the user has proper permissions.
255 public function verifyPermissions( $user ) {
257 * If the image is protected, non-sysop users won't be able
258 * to modify it by uploading a new revision.
260 $nt = $this->getTitle();
263 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
264 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
265 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
266 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
267 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
268 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
275 * Check for non fatal problems with the file
277 * @return array Array of warnings
279 public function checkWarnings() {
282 $localFile = $this->getLocalFile();
283 $filename = $localFile->getName();
284 $n = strrpos( $filename, '.' );
285 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
288 * Check whether the resulting filename is different from the desired one,
289 * but ignore things like ucfirst() and spaces/underscore things
291 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
292 global $wgCapitalLinks, $wgContLang;
293 if ( $wgCapitalLinks ) {
294 $comparableName = $wgContLang->ucfirst( $comparableName );
296 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename )
297 $warning['badfilename'] = $filename;
299 // Check whether the file extension is on the unwanted list
300 global $wgCheckFileExtensions, $wgFileExtensions;
301 if ( $wgCheckFileExtensions ) {
302 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
303 $warning['filetype-unwanted-type'] = $this->mFinalExtension
;
306 global $wgUploadSizeWarning;
307 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) )
308 $warning['large-file'] = $wgUploadSizeWarning;
310 if ( $this->mFileSize
== 0 )
311 $warning['emptyfile'] = true;
314 $exists = self
::getExistsWarning( $localFile );
315 if( $exists !== false )
316 $warning['exists'] = $exists;
318 // Check whether this may be a thumbnail
319 if( $exists !== false && $exists[0] != 'thumb'
320 && self
::isThumbName( $filename ) ){
322 $nt = $this->getTitle();
323 $warning['file-thumbnail-no'] = substr( $filename, 0,
324 strpos( $nt->getText() , '-' ) +
1 );
327 // Check dupes against existing files
328 $hash = File
::sha1Base36( $this->mTempPath
);
329 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
330 $title = $this->getTitle();
331 // Remove all matches against self
332 foreach ( $dupes as $key => $dupe ) {
333 if( $title->equals( $dupe->getTitle() ) )
334 unset( $dupes[$key] );
337 $warning['duplicate'] = $dupes;
339 // Check dupes against archives
340 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
341 if ( $archivedImage->getID() > 0 )
342 $warning['duplicate-archive'] = $archivedImage->getName();
344 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
345 foreach( $filenamePrefixBlacklist as $prefix ) {
346 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
347 $warning['filename-bad-prefix'] = $prefix;
352 # If the file existed before and was deleted, warn the user of this
353 # Don't bother doing so if the file exists now, however
354 if( $localFile->wasDeleted() && !$localFile->exists() )
355 $warning['filewasdeleted'] = $localFile->getTitle();
361 * Really perform the upload. Stores the file in the local repo, watches
362 * if necessary and runs the UploadComplete hook.
364 * @return mixed Status indicating the whether the upload succeeded.
366 public function performUpload( $comment, $pageText, $watch, $user ) {
367 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
368 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
369 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
371 if( $status->isGood() && $watch )
372 $user->addWatch( $this->getLocalFile()->getTitle() );
374 if( $status->isGood() )
375 wfRunHooks( 'UploadComplete', array( &$this ) );
381 * Returns the title of the file to be uploaded. Sets mTitleError in case
382 * the name was illegal.
384 * @return Title The title of the file or null in case the name was illegal
386 public function getTitle() {
387 if ( $this->mTitle
!== false )
388 return $this->mTitle
;
391 * Chop off any directories in the given filename. Then
392 * filter out illegal characters, and try to make a legible name
393 * out of it. We'll strip some silently that Title would die on.
395 $basename = $this->mDesiredDestName
;
397 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
398 /* Normalize to title form before we do any further processing */
399 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
400 if( is_null( $nt ) ) {
401 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
402 return $this->mTitle
= null;
404 $this->mFilteredName
= $nt->getDBkey();
407 * We'll want to blacklist against *any* 'extension', and use
408 * only the final one for the whitelist.
410 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
412 if( count( $ext ) ) {
413 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
415 $this->mFinalExtension
= '';
418 /* Don't allow users to override the blacklist (check file extension) */
419 global $wgCheckFileExtensions, $wgStrictFileExtensions;
420 global $wgFileExtensions, $wgFileBlacklist;
421 if ( $this->mFinalExtension
== '' ) {
422 $this->mTitleError
= self
::FILETYPE_MISSING
;
423 return $this->mTitle
= null;
424 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
425 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
426 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
427 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
428 return $this->mTitle
= null;
431 # If there was more than one "extension", reassemble the base
432 # filename to prevent bogus complaints about length
433 if( count( $ext ) > 1 ) {
434 for( $i = 0; $i < count( $ext ) - 1; $i++
)
435 $partname .= '.' . $ext[$i];
438 if( strlen( $partname ) < 1 ) {
439 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
440 return $this->mTitle
= null;
443 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
444 if( is_null( $nt ) ) {
445 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
446 return $this->mTitle
= null;
448 return $this->mTitle
= $nt;
452 * Return the local file and initializes if necessary.
454 public function getLocalFile() {
455 if( is_null( $this->mLocalFile
) ) {
456 $nt = $this->getTitle();
457 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
459 return $this->mLocalFile
;
463 * Stash a file in a temporary directory for later processing
464 * after the user has confirmed it.
466 * If the user doesn't explicitly cancel or accept, these files
467 * can accumulate in the temp directory.
469 * @param string $saveName - the destination filename
470 * @param string $tempName - the source temporary file to save
471 * @return string - full path the stashed file, or false on failure
474 protected function saveTempUploadedFile( $saveName, $tempName ) {
475 $repo = RepoGroup
::singleton()->getLocalRepo();
476 $status = $repo->storeTemp( $saveName, $tempName );
481 * Append a file to a stashed file.
483 * @param string $srcPath Path to file to append from
484 * @param string $toAppendPath Path to file to append to
485 * @return Status Status
487 public function appendToUploadFile( $srcPath, $toAppendPath ){
488 $repo = RepoGroup
::singleton()->getLocalRepo();
489 $status = $repo->append( $srcPath, $toAppendPath );
494 * Stash a file in a temporary directory for later processing,
495 * and save the necessary descriptive info into the session.
496 * Returns a key value which will be passed through a form
497 * to pick up the path info on a later invocation.
499 * @return int Session key
501 public function stashSession() {
502 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
503 if( !$status->isOK() ) {
504 # Couldn't save the file.
507 if(!isset($_SESSION))
508 session_start(); // start up the session (might have been previously closed to prevent php session locking)
509 $key = $this->getSessionKey();
510 $_SESSION['wsUploadData'][$key] = array(
511 'mTempPath' => $status->value
,
512 'mFileSize' => $this->mFileSize
,
513 'mFileProps' => $this->mFileProps
,
514 'version' => self
::SESSION_VERSION
,
520 * Generate a random session key from stash in cases where we want to start an upload without much information
522 protected function getSessionKey(){
523 $key = mt_rand( 0, 0x7fffffff );
524 $_SESSION['wsUploadData'][$key] = array();
529 * Remove a temporarily kept file stashed by saveTempUploadedFile().
532 public function unsaveUploadedFile() {
533 $repo = RepoGroup
::singleton()->getLocalRepo();
534 $success = $repo->freeTemp( $this->mTempPath
);
539 * If we've modified the upload file we need to manually remove it
540 * on exit to clean up.
543 public function cleanupTempFile() {
544 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
545 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
546 unlink( $this->mTempPath
);
550 public function getTempPath() {
551 return $this->mTempPath
;
555 * Split a file into a base name and all dot-delimited 'extensions'
556 * on the end. Some web server configurations will fall back to
557 * earlier pseudo-'extensions' to determine type and execute
558 * scripts, so the blacklist needs to check them all.
562 public static function splitExtensions( $filename ) {
563 $bits = explode( '.', $filename );
564 $basename = array_shift( $bits );
565 return array( $basename, $bits );
569 * Perform case-insensitive match against a list of file extensions.
570 * Returns true if the extension is in the list.
576 public static function checkFileExtension( $ext, $list ) {
577 return in_array( strtolower( $ext ), $list );
581 * Perform case-insensitive match against a list of file extensions.
582 * Returns true if any of the extensions are in the list.
588 public static function checkFileExtensionList( $ext, $list ) {
589 foreach( $ext as $e ) {
590 if( in_array( strtolower( $e ), $list ) ) {
598 * Checks if the mime type of the uploaded file matches the file extension.
600 * @param string $mime the mime type of the uploaded file
601 * @param string $extension The filename extension that the file is to be served with
604 public static function verifyExtension( $mime, $extension ) {
605 $magic = MimeMagic
::singleton();
607 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
608 if ( !$magic->isRecognizableExtension( $extension ) ) {
609 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
610 "unrecognized extension '$extension', can't verify\n" );
613 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
614 "recognized extension '$extension', so probably invalid file\n" );
618 $match = $magic->isMatchingExtension( $extension, $mime );
620 if ( $match === NULL ) {
621 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
623 } elseif( $match === true ) {
624 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
626 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
630 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
636 * Heuristic for detecting files that *could* contain JavaScript instructions or
637 * things that may look like HTML to a browser and are thus
638 * potentially harmful. The present implementation will produce false positives in some situations.
640 * @param string $file Pathname to the temporary upload file
641 * @param string $mime The mime type of the file
642 * @param string $extension The extension of the file
643 * @return bool true if the file contains something looking like embedded scripts
645 public static function detectScript( $file, $mime, $extension ) {
646 global $wgAllowTitlesInSVG;
648 #ugly hack: for text files, always look at the entire file.
649 #For binary field, just check the first K.
651 if( strpos( $mime,'text/' ) === 0 )
652 $chunk = file_get_contents( $file );
654 $fp = fopen( $file, 'rb' );
655 $chunk = fread( $fp, 1024 );
659 $chunk = strtolower( $chunk );
664 #decode from UTF-16 if needed (could be used for obfuscation).
665 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
667 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
673 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
675 $chunk = trim( $chunk );
677 #FIXME: convert from UTF-16 if necessarry!
678 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
680 #check for HTML doctype
681 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
685 * Internet Explorer for Windows performs some really stupid file type
686 * autodetection which can cause it to interpret valid image files as HTML
687 * and potentially execute JavaScript, creating a cross-site scripting
690 * Apple's Safari browser also performs some unsafe file type autodetection
691 * which can cause legitimate files to be interpreted as HTML if the
692 * web server is not correctly configured to send the right content-type
693 * (or if you're really uploading plain text and octet streams!)
695 * Returns true if IE is likely to mistake the given file for HTML.
696 * Also returns true if Safari would mistake the given file for HTML
697 * when served with a generic content-type.
703 '<html', #also in safari
706 '<script', #also in safari
710 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
714 foreach( $tags as $tag ) {
715 if( false !== strpos( $chunk, $tag ) ) {
721 * look for JavaScript
724 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
725 $chunk = Sanitizer
::decodeCharReferences( $chunk );
727 #look for script-types
728 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
731 #look for html-style script-urls
732 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
735 #look for css-style script-urls
736 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
739 wfDebug( __METHOD__
. ": no scripts found\n" );
743 protected function detectScriptInSvg( $filename ) {
744 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
745 return $check->filterMatch
;
749 * @todo Replace this with a whitelist filter!
751 public function checkSvgScriptCallback( $element, $attribs ) {
752 $stripped = $this->stripXmlNamespace( $element );
754 if( $stripped == 'script' ) {
755 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
759 foreach( $attribs as $attrib => $value ) {
760 $stripped = $this->stripXmlNamespace( $attrib );
761 if( substr( $stripped, 0, 2 ) == 'on' ) {
762 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
765 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
766 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
772 private function stripXmlNamespace( $name ) {
773 // 'http://www.w3.org/2000/svg:script' -> 'script'
774 $parts = explode( ':', strtolower( $name ) );
775 return array_pop( $parts );
779 * Generic wrapper function for a virus scanner program.
780 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
781 * $wgAntivirusRequired may be used to deny upload if the scan fails.
783 * @param string $file Pathname to the temporary upload file
784 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
785 * or a string containing feedback from the virus scanner if a virus was found.
786 * If textual feedback is missing but a virus was found, this function returns true.
788 public static function detectVirus( $file ) {
789 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
791 if ( !$wgAntivirus ) {
792 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
796 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
797 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
798 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
799 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
802 # look up scanner configuration
803 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
804 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
805 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
806 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
808 if ( strpos( $command,"%f" ) === false ) {
809 # simple pattern: append file to scan
810 $command .= " " . wfEscapeShellArg( $file );
812 # complex pattern: replace "%f" with file to scan
813 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
816 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
818 # execute virus scanner
821 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
822 # that does not seem to be worth the pain.
823 # Ask me (Duesentrieb) about it if it's ever needed.
825 if ( wfIsWindows() ) {
826 exec( "$command", $output, $exitCode );
828 exec( "$command 2>&1", $output, $exitCode );
831 # map exit code to AV_xxx constants.
832 $mappedCode = $exitCode;
833 if ( $exitCodeMap ) {
834 if ( isset( $exitCodeMap[$exitCode] ) ) {
835 $mappedCode = $exitCodeMap[$exitCode];
836 } elseif ( isset( $exitCodeMap["*"] ) ) {
837 $mappedCode = $exitCodeMap["*"];
841 if ( $mappedCode === AV_SCAN_FAILED
) {
842 # scan failed (code was mapped to false by $exitCodeMap)
843 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
845 if ( $wgAntivirusRequired ) {
846 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
850 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
851 # scan failed because filetype is unknown (probably imune)
852 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
854 } else if ( $mappedCode === AV_NO_VIRUS
) {
856 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
859 $output = join( "\n", $output );
860 $output = trim( $output );
863 $output = true; #if there's no output, return true
864 } elseif ( $msgPattern ) {
866 if ( preg_match( $msgPattern, $output, $groups ) ) {
868 $output = $groups[1];
873 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
879 * Check if the temporary file is MacBinary-encoded, as some uploads
880 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
881 * If so, the data fork will be extracted to a second temporary file,
882 * which will then be checked for validity and either kept or discarded.
886 private function checkMacBinary() {
887 $macbin = new MacBinary( $this->mTempPath
);
888 if( $macbin->isValid() ) {
889 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
890 $dataHandle = fopen( $dataFile, 'wb' );
892 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
893 $macbin->extractData( $dataHandle );
895 $this->mTempPath
= $dataFile;
896 $this->mFileSize
= $macbin->dataForkLength();
898 // We'll have to manually remove the new file if it's not kept.
899 $this->mRemoveTempFile
= true;
905 * Check if there's an overwrite conflict and, if so, if restrictions
906 * forbid this user from performing the upload.
908 * @return mixed true on success, error string on failure
911 private function checkOverwrite() {
913 // First check whether the local file can be overwritten
914 $file = $this->getLocalFile();
915 if( $file->exists() )
916 if( !self
::userCanReUpload( $wgUser, $file ) )
917 return 'fileexists-forbidden';
919 // Check shared conflicts
920 $file = wfFindFile( $file->getName() );
921 if ( $file && ( !$wgUser->isAllowed( 'reupload' ) ||
922 !$wgUser->isAllowed( 'reupload-shared' ) ) )
923 return 'fileexists-shared-forbidden';
929 * Check if a user is the last uploader
932 * @param string $img, image name
935 public static function userCanReUpload( User
$user, $img ) {
936 if( $user->isAllowed( 'reupload' ) )
937 return true; // non-conditional
938 if( !$user->isAllowed( 'reupload-own' ) )
940 if( is_string( $img ) )
941 $img = wfLocalFile( $img );
942 if ( !( $img instanceof LocalFile
) )
945 return $user->getId() == $img->getUser( 'id' );
949 * Helper function that does various existence checks for a file.
950 * The following checks are performed:
952 * - Article with the same name as the file exists
953 * - File exists with normalized extension
954 * - The file looks like a thumbnail and the original exists
956 * @param File $file The file to check
957 * @return mixed False if the file does not exists, else an array
959 public static function getExistsWarning( $file ) {
960 if( $file->exists() )
961 return array( 'exists', $file );
963 if( $file->getTitle()->getArticleID() )
964 return array( 'page-exists', $file );
966 if( strpos( $file->getName(), '.' ) == false ) {
967 $partname = $file->getName();
970 $n = strrpos( $file->getName(), '.' );
971 $rawExtension = substr( $file->getName(), $n +
1 );
972 $partname = substr( $file->getName(), 0, $n );
975 if ( $rawExtension != $file->getExtension() ) {
976 // We're not using the normalized form of the extension.
977 // Normal form is lowercase, using most common of alternate
978 // extensions (eg 'jpg' rather than 'JPEG').
980 // Check for another file using the normalized form...
981 $nt_lc = Title
::makeTitle( NS_FILE
, $partname . '.' . $file->getExtension() );
982 $file_lc = wfLocalFile( $nt_lc );
984 if( $file_lc->exists() )
985 return array( 'exists-normalized', $file_lc );
988 if ( self
::isThumbName( $file->getName() ) ) {
989 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
990 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
991 $file_thb = wfLocalFile( $nt_thb );
992 if( $file_thb->exists() )
993 return array( 'thumb', $file_thb );
1000 * Helper function that checks whether the filename looks like a thumbnail
1002 public static function isThumbName( $filename ) {
1003 $n = strrpos( $filename, '.' );
1004 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1006 substr( $partname , 3, 3 ) == 'px-' ||
1007 substr( $partname , 2, 3 ) == 'px-'
1009 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1013 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1015 * @return array list of prefixes
1017 public static function getFilenamePrefixBlacklist() {
1018 $blacklist = array();
1019 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1020 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1021 $lines = explode( "\n", $message );
1022 foreach( $lines as $line ) {
1023 // Remove comment lines
1024 $comment = substr( trim( $line ), 0, 1 );
1025 if ( $comment == '#' ||
$comment == '' ) {
1028 // Remove additional comments after a prefix
1029 $comment = strpos( $line, '#' );
1030 if ( $comment > 0 ) {
1031 $line = substr( $line, 0, $comment-1 );
1033 $blacklist[] = trim( $line );