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
);
142 * @param string $srcPath the source path
143 * @returns the real path if it was a virtual url
145 function getRealPath( $srcPath ){
146 $repo = RepoGroup
::singleton()->getLocalRepo();
147 if ( $repo->isVirtualUrl( $srcPath ) ) {
148 return $repo->resolveVirtualUrl( $srcPath );
154 * Verify whether the upload is sane.
155 * Returns self::OK or else an array with error information
157 public function verifyUpload() {
159 * If there was no filename or a zero size given, give up quick.
161 if( $this->isEmptyFile() )
162 return array( 'status' => self
::EMPTY_FILE
);
164 $nt = $this->getTitle();
165 if( is_null( $nt ) ) {
166 $result = array( 'status' => $this->mTitleError
);
167 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
)
168 $result['filtered'] = $this->mFilteredName
;
169 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
)
170 $result['finalExt'] = $this->mFinalExtension
;
173 $this->mDestName
= $this->getLocalFile()->getName();
176 * In some cases we may forbid overwriting of existing files.
178 $overwrite = $this->checkOverwrite();
179 if( $overwrite !== true )
180 return array( 'status' => self
::OVERWRITE_EXISTING_FILE
, 'overwrite' => $overwrite );
183 * Look at the contents of the file; if we can recognize the
184 * type but it's corrupt or data of the wrong type, we should
185 * probably not accept it.
187 $verification = $this->verifyFile();
189 if( $verification !== true ) {
190 if( !is_array( $verification ) )
191 $verification = array( $verification );
192 return array( 'status' => self
::VERIFICATION_ERROR
,
193 'details' => $verification );
197 if( !wfRunHooks( 'UploadVerification',
198 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
199 // This status needs another name...
200 return array( 'status' => self
::UPLOAD_VERIFICATION_ERROR
, 'error' => $error );
203 return array( 'status' => self
::OK
);
207 * Verifies that it's ok to include the uploaded file
209 * FIXME: this function seems to intermixes tmpfile and $this->mTempPath .. no idea why this is
211 * @param string $tmpfile the full path of the temporary file to verify
212 * @return mixed true of the file is verified, a string or array otherwise.
214 protected function verifyFile() {
215 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
216 $this->checkMacBinary();
218 #magically determine mime type
219 $magic = MimeMagic
::singleton();
220 $mime = $magic->guessMimeType( $this->mTempPath
, false );
222 #check mime type, if desired
223 global $wgVerifyMimeType;
224 if ( $wgVerifyMimeType ) {
225 global $wgMimeTypeBlacklist;
226 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
227 return array( 'filetype-badmime', $mime );
230 $fp = fopen( $this->mTempPath
, 'rb' );
231 $chunk = fread( $fp, 256 );
233 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
234 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
235 foreach ( $ieTypes as $ieType ) {
236 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
237 return array( 'filetype-bad-ie-mime', $ieType );
242 #check for htmlish code and javascript
243 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
244 return 'uploadscripted';
246 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
247 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
248 return 'uploadscripted';
253 * Scan the uploaded file for viruses
255 $virus = $this->detectVirus( $this->mTempPath
);
257 return array( 'uploadvirus', $virus );
259 wfDebug( __METHOD__
. ": all clear; passing.\n" );
264 * Check whether the user can edit, upload and create the image.
266 * @param User $user the user to verify the permissions against
267 * @return mixed An array as returned by getUserPermissionsErrors or true
268 * in case the user has proper permissions.
270 public function verifyPermissions( $user ) {
272 * If the image is protected, non-sysop users won't be able
273 * to modify it by uploading a new revision.
275 $nt = $this->getTitle();
278 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
279 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
280 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
281 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
282 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
283 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
290 * Check for non fatal problems with the file
292 * @return array Array of warnings
294 public function checkWarnings() {
297 $localFile = $this->getLocalFile();
298 $filename = $localFile->getName();
299 $n = strrpos( $filename, '.' );
300 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
303 * Check whether the resulting filename is different from the desired one,
304 * but ignore things like ucfirst() and spaces/underscore things
306 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
307 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
308 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename )
309 $warnings['badfilename'] = $filename;
311 // Check whether the file extension is on the unwanted list
312 global $wgCheckFileExtensions, $wgFileExtensions;
313 if ( $wgCheckFileExtensions ) {
314 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
315 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
318 global $wgUploadSizeWarning;
319 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) )
320 $warnings['large-file'] = $wgUploadSizeWarning;
322 if ( $this->mFileSize
== 0 )
323 $warnings['emptyfile'] = true;
326 $exists = self
::getExistsWarning( $localFile );
327 if( $exists !== false )
328 $warnings['exists'] = $exists;
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();
351 * Really perform the upload. Stores the file in the local repo, watches
352 * if necessary and runs the UploadComplete hook.
354 * @return mixed Status indicating the whether the upload succeeded.
356 public function performUpload( $comment, $pageText, $watch, $user ) {
357 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
358 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
359 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
361 if( $status->isGood() && $watch ){
362 //make sure the watch commit happens inline
363 $dbw = wfGetDB(DB_MASTER
);
365 $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();
524 * Remove a temporarily kept file stashed by saveTempUploadedFile().
527 public function unsaveUploadedFile() {
528 $repo = RepoGroup
::singleton()->getLocalRepo();
529 $success = $repo->freeTemp( $this->mTempPath
);
534 * If we've modified the upload file we need to manually remove it
535 * on exit to clean up.
538 public function cleanupTempFile() {
539 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
540 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
541 unlink( $this->mTempPath
);
545 public function getTempPath() {
546 return $this->mTempPath
;
550 * Split a file into a base name and all dot-delimited 'extensions'
551 * on the end. Some web server configurations will fall back to
552 * earlier pseudo-'extensions' to determine type and execute
553 * scripts, so the blacklist needs to check them all.
557 public static function splitExtensions( $filename ) {
558 $bits = explode( '.', $filename );
559 $basename = array_shift( $bits );
560 return array( $basename, $bits );
564 * Perform case-insensitive match against a list of file extensions.
565 * Returns true if the extension is in the list.
571 public static function checkFileExtension( $ext, $list ) {
572 return in_array( strtolower( $ext ), $list );
576 * Perform case-insensitive match against a list of file extensions.
577 * Returns true if any of the extensions are in the list.
583 public static function checkFileExtensionList( $ext, $list ) {
584 foreach( $ext as $e ) {
585 if( in_array( strtolower( $e ), $list ) ) {
593 * Checks if the mime type of the uploaded file matches the file extension.
595 * @param string $mime the mime type of the uploaded file
596 * @param string $extension The filename extension that the file is to be served with
599 public static function verifyExtension( $mime, $extension ) {
600 $magic = MimeMagic
::singleton();
602 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
603 if ( !$magic->isRecognizableExtension( $extension ) ) {
604 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
605 "unrecognized extension '$extension', can't verify\n" );
608 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
609 "recognized extension '$extension', so probably invalid file\n" );
613 $match = $magic->isMatchingExtension( $extension, $mime );
615 if ( $match === NULL ) {
616 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
618 } elseif( $match === true ) {
619 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
621 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
625 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
631 * Heuristic for detecting files that *could* contain JavaScript instructions or
632 * things that may look like HTML to a browser and are thus
633 * potentially harmful. The present implementation will produce false positives in some situations.
635 * @param string $file Pathname to the temporary upload file
636 * @param string $mime The mime type of the file
637 * @param string $extension The extension of the file
638 * @return bool true if the file contains something looking like embedded scripts
640 public static function detectScript( $file, $mime, $extension ) {
641 global $wgAllowTitlesInSVG;
643 #ugly hack: for text files, always look at the entire file.
644 #For binary field, just check the first K.
646 if( strpos( $mime,'text/' ) === 0 )
647 $chunk = file_get_contents( $file );
649 $fp = fopen( $file, 'rb' );
650 $chunk = fread( $fp, 1024 );
654 $chunk = strtolower( $chunk );
659 #decode from UTF-16 if needed (could be used for obfuscation).
660 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
662 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
668 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
670 $chunk = trim( $chunk );
672 #FIXME: convert from UTF-16 if necessarry!
673 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
675 #check for HTML doctype
676 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
680 * Internet Explorer for Windows performs some really stupid file type
681 * autodetection which can cause it to interpret valid image files as HTML
682 * and potentially execute JavaScript, creating a cross-site scripting
685 * Apple's Safari browser also performs some unsafe file type autodetection
686 * which can cause legitimate files to be interpreted as HTML if the
687 * web server is not correctly configured to send the right content-type
688 * (or if you're really uploading plain text and octet streams!)
690 * Returns true if IE is likely to mistake the given file for HTML.
691 * Also returns true if Safari would mistake the given file for HTML
692 * when served with a generic content-type.
698 '<html', #also in safari
701 '<script', #also in safari
705 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
709 foreach( $tags as $tag ) {
710 if( false !== strpos( $chunk, $tag ) ) {
716 * look for JavaScript
719 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
720 $chunk = Sanitizer
::decodeCharReferences( $chunk );
722 #look for script-types
723 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
726 #look for html-style script-urls
727 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
730 #look for css-style script-urls
731 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
734 wfDebug( __METHOD__
. ": no scripts found\n" );
738 protected function detectScriptInSvg( $filename ) {
739 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
740 return $check->filterMatch
;
744 * @todo Replace this with a whitelist filter!
746 public function checkSvgScriptCallback( $element, $attribs ) {
747 $stripped = $this->stripXmlNamespace( $element );
749 if( $stripped == 'script' ) {
750 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
754 foreach( $attribs as $attrib => $value ) {
755 $stripped = $this->stripXmlNamespace( $attrib );
756 if( substr( $stripped, 0, 2 ) == 'on' ) {
757 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
760 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
761 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
767 private function stripXmlNamespace( $name ) {
768 // 'http://www.w3.org/2000/svg:script' -> 'script'
769 $parts = explode( ':', strtolower( $name ) );
770 return array_pop( $parts );
774 * Generic wrapper function for a virus scanner program.
775 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
776 * $wgAntivirusRequired may be used to deny upload if the scan fails.
778 * @param string $file Pathname to the temporary upload file
779 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
780 * or a string containing feedback from the virus scanner if a virus was found.
781 * If textual feedback is missing but a virus was found, this function returns true.
783 public static function detectVirus( $file ) {
784 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
786 if ( !$wgAntivirus ) {
787 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
791 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
792 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
793 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
794 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
797 # look up scanner configuration
798 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
799 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
800 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
801 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
803 if ( strpos( $command,"%f" ) === false ) {
804 # simple pattern: append file to scan
805 $command .= " " . wfEscapeShellArg( $file );
807 # complex pattern: replace "%f" with file to scan
808 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
811 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
813 # execute virus scanner
816 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
817 # that does not seem to be worth the pain.
818 # Ask me (Duesentrieb) about it if it's ever needed.
820 $output = wfShellExec("$command 2>&1", $exitCode);
823 # map exit code to AV_xxx constants.
824 $mappedCode = $exitCode;
825 if ( $exitCodeMap ) {
826 if ( isset( $exitCodeMap[$exitCode] ) ) {
827 $mappedCode = $exitCodeMap[$exitCode];
828 } elseif ( isset( $exitCodeMap["*"] ) ) {
829 $mappedCode = $exitCodeMap["*"];
834 if ( $mappedCode === AV_SCAN_FAILED
) {
835 # scan failed (code was mapped to false by $exitCodeMap)
836 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
838 if ( $wgAntivirusRequired ) {
839 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
843 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
844 # scan failed because filetype is unknown (probably imune)
845 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
847 } else if ( $mappedCode === AV_NO_VIRUS
) {
849 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
852 $output = join( "\n", $output );
853 $output = trim( $output );
856 $output = true; #if there's no output, return true
857 } elseif ( $msgPattern ) {
859 if ( preg_match( $msgPattern, $output, $groups ) ) {
861 $output = $groups[1];
866 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
872 * Check if the temporary file is MacBinary-encoded, as some uploads
873 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
874 * If so, the data fork will be extracted to a second temporary file,
875 * which will then be checked for validity and either kept or discarded.
879 private function checkMacBinary() {
880 $macbin = new MacBinary( $this->mTempPath
);
881 if( $macbin->isValid() ) {
882 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
883 $dataHandle = fopen( $dataFile, 'wb' );
885 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
886 $macbin->extractData( $dataHandle );
888 $this->mTempPath
= $dataFile;
889 $this->mFileSize
= $macbin->dataForkLength();
891 // We'll have to manually remove the new file if it's not kept.
892 $this->mRemoveTempFile
= true;
898 * Check if there's an overwrite conflict and, if so, if restrictions
899 * forbid this user from performing the upload.
901 * @return mixed true on success, error string on failure
904 private function checkOverwrite() {
906 // First check whether the local file can be overwritten
907 $file = $this->getLocalFile();
908 if( $file->exists() ) {
909 if( !self
::userCanReUpload( $wgUser, $file ) )
910 return 'fileexists-forbidden';
915 /* Check shared conflicts: if the local file does not exist, but
916 * wfFindFile finds a file, it exists in a shared repository.
918 $file = wfFindFile( $this->getTitle() );
919 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) )
920 return 'fileexists-shared-forbidden';
926 * Check if a user is the last uploader
929 * @param string $img, image name
932 public static function userCanReUpload( User
$user, $img ) {
933 if( $user->isAllowed( 'reupload' ) )
934 return true; // non-conditional
935 if( !$user->isAllowed( 'reupload-own' ) )
937 if( is_string( $img ) )
938 $img = wfLocalFile( $img );
939 if ( !( $img instanceof LocalFile
) )
942 return $user->getId() == $img->getUser( 'id' );
946 * Helper function that does various existence checks for a file.
947 * The following checks are performed:
949 * - Article with the same name as the file exists
950 * - File exists with normalized extension
951 * - The file looks like a thumbnail and the original exists
953 * @param File $file The file to check
954 * @return mixed False if the file does not exists, else an array
956 public static function getExistsWarning( $file ) {
957 if( $file->exists() )
958 return array( 'warning' => 'exists', 'file' => $file );
960 if( $file->getTitle()->getArticleID() )
961 return array( 'warning' => 'page-exists', 'file' => $file );
963 if ( $file->wasDeleted() && !$file->exists() )
964 return array( 'warning' => 'was-deleted', 'file' => $file );
966 if( strpos( $file->getName(), '.' ) == false ) {
967 $partname = $file->getName();
970 $n = strrpos( $file->getName(), '.' );
971 $extension = substr( $file->getName(), $n +
1 );
972 $partname = substr( $file->getName(), 0, $n );
974 $normalizedExtension = File
::normalizeExtension( $extension );
976 if ( $normalizedExtension != $extension ) {
977 // We're not using the normalized form of the extension.
978 // Normal form is lowercase, using most common of alternate
979 // extensions (eg 'jpg' rather than 'JPEG').
981 // Check for another file using the normalized form...
982 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
983 $file_lc = wfLocalFile( $nt_lc );
985 if( $file_lc->exists() )
986 return array( 'warning' => 'exists-normalized', 'file' => $file, 'normalizedFile' => $file_lc );
989 if ( self
::isThumbName( $file->getName() ) ) {
990 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
991 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
992 $file_thb = wfLocalFile( $nt_thb );
993 if( $file_thb->exists() )
994 return array( 'warning' => 'thumb', 'file' => $file, 'thumbFile' => $file_thb );
996 // File does not exist, but we just don't like the name
997 return array( 'warning' => 'thumb-name', 'file' => $file, 'thumbFile' => $file_thb );
1001 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1002 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix )
1003 return array( 'warning' => 'bad-prefix', 'file' => $file, 'prefix' => $prefix );
1012 * Helper function that checks whether the filename looks like a thumbnail
1014 public static function isThumbName( $filename ) {
1015 $n = strrpos( $filename, '.' );
1016 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1018 substr( $partname , 3, 3 ) == 'px-' ||
1019 substr( $partname , 2, 3 ) == 'px-'
1021 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1025 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1027 * @return array list of prefixes
1029 public static function getFilenamePrefixBlacklist() {
1030 $blacklist = array();
1031 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1032 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1033 $lines = explode( "\n", $message );
1034 foreach( $lines as $line ) {
1035 // Remove comment lines
1036 $comment = substr( trim( $line ), 0, 1 );
1037 if ( $comment == '#' ||
$comment == '' ) {
1040 // Remove additional comments after a prefix
1041 $comment = strpos( $line, '#' );
1042 if ( $comment > 0 ) {
1043 $line = substr( $line, 0, $comment-1 );
1045 $blacklist[] = trim( $line );