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 dupes against existing files
322 $hash = File
::sha1Base36( $this->mTempPath
);
323 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
324 $title = $this->getTitle();
325 // Remove all matches against self
326 foreach ( $dupes as $key => $dupe ) {
327 if( $title->equals( $dupe->getTitle() ) )
328 unset( $dupes[$key] );
331 $warnings['duplicate'] = $dupes;
333 // Check dupes against archives
334 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
335 if ( $archivedImage->getID() > 0 )
336 $warnings['duplicate-archive'] = $archivedImage->getName();
342 * Really perform the upload. Stores the file in the local repo, watches
343 * if necessary and runs the UploadComplete hook.
345 * @return mixed Status indicating the whether the upload succeeded.
347 public function performUpload( $comment, $pageText, $watch, $user ) {
348 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
349 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
350 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
352 if( $status->isGood() && $watch )
353 $user->addWatch( $this->getLocalFile()->getTitle() );
355 if( $status->isGood() )
356 wfRunHooks( 'UploadComplete', array( &$this ) );
362 * Returns the title of the file to be uploaded. Sets mTitleError in case
363 * the name was illegal.
365 * @return Title The title of the file or null in case the name was illegal
367 public function getTitle() {
368 if ( $this->mTitle
!== false )
369 return $this->mTitle
;
372 * Chop off any directories in the given filename. Then
373 * filter out illegal characters, and try to make a legible name
374 * out of it. We'll strip some silently that Title would die on.
376 $basename = $this->mDesiredDestName
;
378 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
379 /* Normalize to title form before we do any further processing */
380 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
381 if( is_null( $nt ) ) {
382 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
383 return $this->mTitle
= null;
385 $this->mFilteredName
= $nt->getDBkey();
388 * We'll want to blacklist against *any* 'extension', and use
389 * only the final one for the whitelist.
391 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
393 if( count( $ext ) ) {
394 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
396 $this->mFinalExtension
= '';
399 /* Don't allow users to override the blacklist (check file extension) */
400 global $wgCheckFileExtensions, $wgStrictFileExtensions;
401 global $wgFileExtensions, $wgFileBlacklist;
402 if ( $this->mFinalExtension
== '' ) {
403 $this->mTitleError
= self
::FILETYPE_MISSING
;
404 return $this->mTitle
= null;
405 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
406 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
407 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
408 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
409 return $this->mTitle
= null;
412 # If there was more than one "extension", reassemble the base
413 # filename to prevent bogus complaints about length
414 if( count( $ext ) > 1 ) {
415 for( $i = 0; $i < count( $ext ) - 1; $i++
)
416 $partname .= '.' . $ext[$i];
419 if( strlen( $partname ) < 1 ) {
420 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
421 return $this->mTitle
= null;
424 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
425 if( is_null( $nt ) ) {
426 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
427 return $this->mTitle
= null;
429 return $this->mTitle
= $nt;
433 * Return the local file and initializes if necessary.
435 public function getLocalFile() {
436 if( is_null( $this->mLocalFile
) ) {
437 $nt = $this->getTitle();
438 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
440 return $this->mLocalFile
;
444 * Stash a file in a temporary directory for later processing
445 * after the user has confirmed it.
447 * If the user doesn't explicitly cancel or accept, these files
448 * can accumulate in the temp directory.
450 * @param string $saveName - the destination filename
451 * @param string $tempSrc - the source temporary file to save
452 * @return string - full path the stashed file, or false on failure
455 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
456 $repo = RepoGroup
::singleton()->getLocalRepo();
457 $status = $repo->storeTemp( $saveName, $tempSrc );
462 * Append a file to a stashed file.
464 * @param string $srcPath Path to file to append from
465 * @param string $toAppendPath Path to file to append to
466 * @return Status Status
468 public function appendToUploadFile( $srcPath, $toAppendPath ){
469 $repo = RepoGroup
::singleton()->getLocalRepo();
470 $status = $repo->append( $srcPath, $toAppendPath );
475 * Stash a file in a temporary directory for later processing,
476 * and save the necessary descriptive info into the session.
477 * Returns a key value which will be passed through a form
478 * to pick up the path info on a later invocation.
480 * @return int Session key
482 public function stashSession() {
483 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
484 if( !$status->isOK() ) {
485 # Couldn't save the file.
488 if(!isset($_SESSION))
489 session_start(); // start up the session (might have been previously closed to prevent php session locking)
490 $key = $this->getSessionKey();
491 $_SESSION['wsUploadData'][$key] = array(
492 'mTempPath' => $status->value
,
493 'mFileSize' => $this->mFileSize
,
494 'mFileProps' => $this->mFileProps
,
495 'version' => self
::SESSION_VERSION
,
501 * Generate a random session key from stash in cases where we want to start an upload without much information
503 protected function getSessionKey(){
504 $key = mt_rand( 0, 0x7fffffff );
505 $_SESSION['wsUploadData'][$key] = array();
510 * Remove a temporarily kept file stashed by saveTempUploadedFile().
513 public function unsaveUploadedFile() {
514 $repo = RepoGroup
::singleton()->getLocalRepo();
515 $success = $repo->freeTemp( $this->mTempPath
);
520 * If we've modified the upload file we need to manually remove it
521 * on exit to clean up.
524 public function cleanupTempFile() {
525 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
526 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
527 unlink( $this->mTempPath
);
531 public function getTempPath() {
532 return $this->mTempPath
;
536 * Split a file into a base name and all dot-delimited 'extensions'
537 * on the end. Some web server configurations will fall back to
538 * earlier pseudo-'extensions' to determine type and execute
539 * scripts, so the blacklist needs to check them all.
543 public static function splitExtensions( $filename ) {
544 $bits = explode( '.', $filename );
545 $basename = array_shift( $bits );
546 return array( $basename, $bits );
550 * Perform case-insensitive match against a list of file extensions.
551 * Returns true if the extension is in the list.
557 public static function checkFileExtension( $ext, $list ) {
558 return in_array( strtolower( $ext ), $list );
562 * Perform case-insensitive match against a list of file extensions.
563 * Returns true if any of the extensions are in the list.
569 public static function checkFileExtensionList( $ext, $list ) {
570 foreach( $ext as $e ) {
571 if( in_array( strtolower( $e ), $list ) ) {
579 * Checks if the mime type of the uploaded file matches the file extension.
581 * @param string $mime the mime type of the uploaded file
582 * @param string $extension The filename extension that the file is to be served with
585 public static function verifyExtension( $mime, $extension ) {
586 $magic = MimeMagic
::singleton();
588 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
589 if ( !$magic->isRecognizableExtension( $extension ) ) {
590 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
591 "unrecognized extension '$extension', can't verify\n" );
594 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
595 "recognized extension '$extension', so probably invalid file\n" );
599 $match = $magic->isMatchingExtension( $extension, $mime );
601 if ( $match === NULL ) {
602 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
604 } elseif( $match === true ) {
605 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
607 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
611 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
617 * Heuristic for detecting files that *could* contain JavaScript instructions or
618 * things that may look like HTML to a browser and are thus
619 * potentially harmful. The present implementation will produce false positives in some situations.
621 * @param string $file Pathname to the temporary upload file
622 * @param string $mime The mime type of the file
623 * @param string $extension The extension of the file
624 * @return bool true if the file contains something looking like embedded scripts
626 public static function detectScript( $file, $mime, $extension ) {
627 global $wgAllowTitlesInSVG;
629 #ugly hack: for text files, always look at the entire file.
630 #For binary field, just check the first K.
632 if( strpos( $mime,'text/' ) === 0 )
633 $chunk = file_get_contents( $file );
635 $fp = fopen( $file, 'rb' );
636 $chunk = fread( $fp, 1024 );
640 $chunk = strtolower( $chunk );
645 #decode from UTF-16 if needed (could be used for obfuscation).
646 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
648 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
654 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
656 $chunk = trim( $chunk );
658 #FIXME: convert from UTF-16 if necessarry!
659 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
661 #check for HTML doctype
662 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
666 * Internet Explorer for Windows performs some really stupid file type
667 * autodetection which can cause it to interpret valid image files as HTML
668 * and potentially execute JavaScript, creating a cross-site scripting
671 * Apple's Safari browser also performs some unsafe file type autodetection
672 * which can cause legitimate files to be interpreted as HTML if the
673 * web server is not correctly configured to send the right content-type
674 * (or if you're really uploading plain text and octet streams!)
676 * Returns true if IE is likely to mistake the given file for HTML.
677 * Also returns true if Safari would mistake the given file for HTML
678 * when served with a generic content-type.
684 '<html', #also in safari
687 '<script', #also in safari
691 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
695 foreach( $tags as $tag ) {
696 if( false !== strpos( $chunk, $tag ) ) {
702 * look for JavaScript
705 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
706 $chunk = Sanitizer
::decodeCharReferences( $chunk );
708 #look for script-types
709 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
712 #look for html-style script-urls
713 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
716 #look for css-style script-urls
717 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
720 wfDebug( __METHOD__
. ": no scripts found\n" );
724 protected function detectScriptInSvg( $filename ) {
725 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
726 return $check->filterMatch
;
730 * @todo Replace this with a whitelist filter!
732 public function checkSvgScriptCallback( $element, $attribs ) {
733 $stripped = $this->stripXmlNamespace( $element );
735 if( $stripped == 'script' ) {
736 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
740 foreach( $attribs as $attrib => $value ) {
741 $stripped = $this->stripXmlNamespace( $attrib );
742 if( substr( $stripped, 0, 2 ) == 'on' ) {
743 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
746 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
747 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
753 private function stripXmlNamespace( $name ) {
754 // 'http://www.w3.org/2000/svg:script' -> 'script'
755 $parts = explode( ':', strtolower( $name ) );
756 return array_pop( $parts );
760 * Generic wrapper function for a virus scanner program.
761 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
762 * $wgAntivirusRequired may be used to deny upload if the scan fails.
764 * @param string $file Pathname to the temporary upload file
765 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
766 * or a string containing feedback from the virus scanner if a virus was found.
767 * If textual feedback is missing but a virus was found, this function returns true.
769 public static function detectVirus( $file ) {
770 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
772 if ( !$wgAntivirus ) {
773 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
777 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
778 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
779 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
780 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
783 # look up scanner configuration
784 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
785 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
786 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
787 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
789 if ( strpos( $command,"%f" ) === false ) {
790 # simple pattern: append file to scan
791 $command .= " " . wfEscapeShellArg( $file );
793 # complex pattern: replace "%f" with file to scan
794 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
797 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
799 # execute virus scanner
802 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
803 # that does not seem to be worth the pain.
804 # Ask me (Duesentrieb) about it if it's ever needed.
806 if ( wfIsWindows() ) {
807 exec( "$command", $output, $exitCode );
809 exec( "$command 2>&1", $output, $exitCode );
812 # map exit code to AV_xxx constants.
813 $mappedCode = $exitCode;
814 if ( $exitCodeMap ) {
815 if ( isset( $exitCodeMap[$exitCode] ) ) {
816 $mappedCode = $exitCodeMap[$exitCode];
817 } elseif ( isset( $exitCodeMap["*"] ) ) {
818 $mappedCode = $exitCodeMap["*"];
822 if ( $mappedCode === AV_SCAN_FAILED
) {
823 # scan failed (code was mapped to false by $exitCodeMap)
824 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
826 if ( $wgAntivirusRequired ) {
827 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
831 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
832 # scan failed because filetype is unknown (probably imune)
833 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
835 } else if ( $mappedCode === AV_NO_VIRUS
) {
837 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
840 $output = join( "\n", $output );
841 $output = trim( $output );
844 $output = true; #if there's no output, return true
845 } elseif ( $msgPattern ) {
847 if ( preg_match( $msgPattern, $output, $groups ) ) {
849 $output = $groups[1];
854 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
860 * Check if the temporary file is MacBinary-encoded, as some uploads
861 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
862 * If so, the data fork will be extracted to a second temporary file,
863 * which will then be checked for validity and either kept or discarded.
867 private function checkMacBinary() {
868 $macbin = new MacBinary( $this->mTempPath
);
869 if( $macbin->isValid() ) {
870 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
871 $dataHandle = fopen( $dataFile, 'wb' );
873 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
874 $macbin->extractData( $dataHandle );
876 $this->mTempPath
= $dataFile;
877 $this->mFileSize
= $macbin->dataForkLength();
879 // We'll have to manually remove the new file if it's not kept.
880 $this->mRemoveTempFile
= true;
886 * Check if there's an overwrite conflict and, if so, if restrictions
887 * forbid this user from performing the upload.
889 * @return mixed true on success, error string on failure
892 private function checkOverwrite() {
894 // First check whether the local file can be overwritten
895 $file = $this->getLocalFile();
896 if( $file->exists() ) {
897 if( !self
::userCanReUpload( $wgUser, $file ) )
898 return 'fileexists-forbidden';
903 /* Check shared conflicts: if the local file does not exist, but
904 * wfFindFile finds a file, it exists in a shared repository.
906 $file = wfFindFile( $this->getTitle() );
907 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) )
908 return 'fileexists-shared-forbidden';
914 * Check if a user is the last uploader
917 * @param string $img, image name
920 public static function userCanReUpload( User
$user, $img ) {
921 if( $user->isAllowed( 'reupload' ) )
922 return true; // non-conditional
923 if( !$user->isAllowed( 'reupload-own' ) )
925 if( is_string( $img ) )
926 $img = wfLocalFile( $img );
927 if ( !( $img instanceof LocalFile
) )
930 return $user->getId() == $img->getUser( 'id' );
934 * Helper function that does various existence checks for a file.
935 * The following checks are performed:
937 * - Article with the same name as the file exists
938 * - File exists with normalized extension
939 * - The file looks like a thumbnail and the original exists
941 * @param File $file The file to check
942 * @return mixed False if the file does not exists, else an array
944 public static function getExistsWarning( $file ) {
945 if( $file->exists() )
946 return array( 'warning' => 'exists', 'file' => $file );
948 if( $file->getTitle()->getArticleID() )
949 return array( 'warning' => 'page-exists', 'file' => $file );
951 if ( $file->wasDeleted() && !$file->exists() )
952 return array( 'warning' => 'was-deleted', 'file' => $file );
954 if( strpos( $file->getName(), '.' ) == false ) {
955 $partname = $file->getName();
958 $n = strrpos( $file->getName(), '.' );
959 $extension = substr( $file->getName(), $n +
1 );
960 $partname = substr( $file->getName(), 0, $n );
962 $normalizedExtension = File
::normalizeExtension( $extension );
964 if ( $normalizedExtension != $extension ) {
965 // We're not using the normalized form of the extension.
966 // Normal form is lowercase, using most common of alternate
967 // extensions (eg 'jpg' rather than 'JPEG').
969 // Check for another file using the normalized form...
970 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
971 $file_lc = wfLocalFile( $nt_lc );
973 if( $file_lc->exists() )
974 return array( 'warning' => 'exists-normalized', 'file' => $file, 'normalizedFile' => $file_lc );
977 if ( self
::isThumbName( $file->getName() ) ) {
978 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
979 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
980 $file_thb = wfLocalFile( $nt_thb );
981 if( $file_thb->exists() )
982 return array( 'warning' => 'thumb', 'file' => $file, 'thumbFile' => $file_thb );
984 // File does not exist, but we just don't like the name
985 return array( 'warning' => 'thumb-name', 'file' => $file, 'thumbFile' => $file_thb );
989 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
990 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix )
991 return array( 'warning' => 'bad-prefix', 'file' => $file, 'prefix' => $prefix );
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 );