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 );
198 if( !wfRunHooks( 'UploadVerification',
199 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
200 // This status needs another name...
201 return array( 'status' => self
::UPLOAD_VERIFICATION_ERROR
, 'error' => $error );
204 return array( 'status' => self
::OK
);
208 * Verifies that it's ok to include the uploaded file
210 * FIXME: this function seems to intermixes tmpfile and $this->mTempPath .. no idea why this is
212 * @param string $tmpfile the full path of the temporary file to verify
213 * @return mixed true of the file is verified, a string or array otherwise.
215 protected function verifyFile() {
216 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
217 $this->checkMacBinary();
219 #magically determine mime type
220 $magic = MimeMagic
::singleton();
221 $mime = $magic->guessMimeType( $this->mTempPath
, false );
223 #check mime type, if desired
224 global $wgVerifyMimeType;
225 if ( $wgVerifyMimeType ) {
226 global $wgMimeTypeBlacklist;
227 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
228 return array( 'filetype-badmime', $mime );
231 $fp = fopen( $this->mTempPath
, 'rb' );
232 $chunk = fread( $fp, 256 );
234 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
235 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
236 foreach ( $ieTypes as $ieType ) {
237 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
238 return array( 'filetype-bad-ie-mime', $ieType );
243 #check for htmlish code and javascript
244 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
245 return 'uploadscripted';
247 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
248 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
249 return 'uploadscripted';
254 * Scan the uploaded file for viruses
256 $virus = $this->detectVirus( $this->mTempPath
);
258 return array( 'uploadvirus', $virus );
260 wfDebug( __METHOD__
. ": all clear; passing.\n" );
265 * Check whether the user can edit, upload and create the image.
267 * @param User $user the user to verify the permissions against
268 * @return mixed An array as returned by getUserPermissionsErrors or true
269 * in case the user has proper permissions.
271 public function verifyPermissions( $user ) {
273 * If the image is protected, non-sysop users won't be able
274 * to modify it by uploading a new revision.
276 $nt = $this->getTitle();
279 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
280 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
281 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
282 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
283 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
284 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
291 * Check for non fatal problems with the file
293 * @return array Array of warnings
295 public function checkWarnings() {
298 $localFile = $this->getLocalFile();
299 $filename = $localFile->getName();
300 $n = strrpos( $filename, '.' );
301 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
304 * Check whether the resulting filename is different from the desired one,
305 * but ignore things like ucfirst() and spaces/underscore things
307 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
308 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
309 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename )
310 $warnings['badfilename'] = $filename;
312 // Check whether the file extension is on the unwanted list
313 global $wgCheckFileExtensions, $wgFileExtensions;
314 if ( $wgCheckFileExtensions ) {
315 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
316 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
319 global $wgUploadSizeWarning;
320 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) )
321 $warnings['large-file'] = $wgUploadSizeWarning;
323 if ( $this->mFileSize
== 0 )
324 $warnings['emptyfile'] = true;
327 $exists = self
::getExistsWarning( $localFile );
328 if( $exists !== false )
329 $warnings['exists'] = $exists;
331 // Check dupes against existing files
332 $hash = File
::sha1Base36( $this->mTempPath
);
333 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
334 $title = $this->getTitle();
335 // Remove all matches against self
336 foreach ( $dupes as $key => $dupe ) {
337 if( $title->equals( $dupe->getTitle() ) )
338 unset( $dupes[$key] );
341 $warnings['duplicate'] = $dupes;
343 // Check dupes against archives
344 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
345 if ( $archivedImage->getID() > 0 )
346 $warnings['duplicate-archive'] = $archivedImage->getName();
352 * Really perform the upload. Stores the file in the local repo, watches
353 * if necessary and runs the UploadComplete hook.
355 * @return mixed Status indicating the whether the upload succeeded.
357 public function performUpload( $comment, $pageText, $watch, $user ) {
358 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
359 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
360 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
362 if( $status->isGood() && $watch )
363 $user->addWatch( $this->getLocalFile()->getTitle() );
365 if( $status->isGood() )
366 wfRunHooks( 'UploadComplete', array( &$this ) );
372 * Returns the title of the file to be uploaded. Sets mTitleError in case
373 * the name was illegal.
375 * @return Title The title of the file or null in case the name was illegal
377 public function getTitle() {
378 if ( $this->mTitle
!== false )
379 return $this->mTitle
;
382 * Chop off any directories in the given filename. Then
383 * filter out illegal characters, and try to make a legible name
384 * out of it. We'll strip some silently that Title would die on.
386 $basename = $this->mDesiredDestName
;
388 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
389 /* Normalize to title form before we do any further processing */
390 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
391 if( is_null( $nt ) ) {
392 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
393 return $this->mTitle
= null;
395 $this->mFilteredName
= $nt->getDBkey();
398 * We'll want to blacklist against *any* 'extension', and use
399 * only the final one for the whitelist.
401 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
403 if( count( $ext ) ) {
404 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
406 $this->mFinalExtension
= '';
409 /* Don't allow users to override the blacklist (check file extension) */
410 global $wgCheckFileExtensions, $wgStrictFileExtensions;
411 global $wgFileExtensions, $wgFileBlacklist;
412 if ( $this->mFinalExtension
== '' ) {
413 $this->mTitleError
= self
::FILETYPE_MISSING
;
414 return $this->mTitle
= null;
415 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
416 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
417 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
418 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
419 return $this->mTitle
= null;
422 # If there was more than one "extension", reassemble the base
423 # filename to prevent bogus complaints about length
424 if( count( $ext ) > 1 ) {
425 for( $i = 0; $i < count( $ext ) - 1; $i++
)
426 $partname .= '.' . $ext[$i];
429 if( strlen( $partname ) < 1 ) {
430 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
431 return $this->mTitle
= null;
434 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
435 if( is_null( $nt ) ) {
436 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
437 return $this->mTitle
= null;
439 return $this->mTitle
= $nt;
443 * Return the local file and initializes if necessary.
445 public function getLocalFile() {
446 if( is_null( $this->mLocalFile
) ) {
447 $nt = $this->getTitle();
448 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
450 return $this->mLocalFile
;
454 * Stash a file in a temporary directory for later processing
455 * after the user has confirmed it.
457 * If the user doesn't explicitly cancel or accept, these files
458 * can accumulate in the temp directory.
460 * @param string $saveName - the destination filename
461 * @param string $tempSrc - the source temporary file to save
462 * @return string - full path the stashed file, or false on failure
465 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
466 $repo = RepoGroup
::singleton()->getLocalRepo();
467 $status = $repo->storeTemp( $saveName, $tempSrc );
472 * Append a file to a stashed file.
474 * @param string $srcPath Path to file to append from
475 * @param string $toAppendPath Path to file to append to
476 * @return Status Status
478 public function appendToUploadFile( $srcPath, $toAppendPath ){
479 $repo = RepoGroup
::singleton()->getLocalRepo();
480 $status = $repo->append( $srcPath, $toAppendPath );
485 * Stash a file in a temporary directory for later processing,
486 * and save the necessary descriptive info into the session.
487 * Returns a key value which will be passed through a form
488 * to pick up the path info on a later invocation.
490 * @return int Session key
492 public function stashSession() {
493 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
494 if( !$status->isOK() ) {
495 # Couldn't save the file.
498 if(!isset($_SESSION))
499 session_start(); // start up the session (might have been previously closed to prevent php session locking)
500 $key = $this->getSessionKey();
501 $_SESSION['wsUploadData'][$key] = array(
502 'mTempPath' => $status->value
,
503 'mFileSize' => $this->mFileSize
,
504 'mFileProps' => $this->mFileProps
,
505 'version' => self
::SESSION_VERSION
,
511 * Generate a random session key from stash in cases where we want to start an upload without much information
513 protected function getSessionKey(){
514 $key = mt_rand( 0, 0x7fffffff );
515 $_SESSION['wsUploadData'][$key] = array();
520 * Remove a temporarily kept file stashed by saveTempUploadedFile().
523 public function unsaveUploadedFile() {
524 $repo = RepoGroup
::singleton()->getLocalRepo();
525 $success = $repo->freeTemp( $this->mTempPath
);
530 * If we've modified the upload file we need to manually remove it
531 * on exit to clean up.
534 public function cleanupTempFile() {
535 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
536 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
537 unlink( $this->mTempPath
);
541 public function getTempPath() {
542 return $this->mTempPath
;
546 * Split a file into a base name and all dot-delimited 'extensions'
547 * on the end. Some web server configurations will fall back to
548 * earlier pseudo-'extensions' to determine type and execute
549 * scripts, so the blacklist needs to check them all.
553 public static function splitExtensions( $filename ) {
554 $bits = explode( '.', $filename );
555 $basename = array_shift( $bits );
556 return array( $basename, $bits );
560 * Perform case-insensitive match against a list of file extensions.
561 * Returns true if the extension is in the list.
567 public static function checkFileExtension( $ext, $list ) {
568 return in_array( strtolower( $ext ), $list );
572 * Perform case-insensitive match against a list of file extensions.
573 * Returns true if any of the extensions are in the list.
579 public static function checkFileExtensionList( $ext, $list ) {
580 foreach( $ext as $e ) {
581 if( in_array( strtolower( $e ), $list ) ) {
589 * Checks if the mime type of the uploaded file matches the file extension.
591 * @param string $mime the mime type of the uploaded file
592 * @param string $extension The filename extension that the file is to be served with
595 public static function verifyExtension( $mime, $extension ) {
596 $magic = MimeMagic
::singleton();
598 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
599 if ( !$magic->isRecognizableExtension( $extension ) ) {
600 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
601 "unrecognized extension '$extension', can't verify\n" );
604 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
605 "recognized extension '$extension', so probably invalid file\n" );
609 $match = $magic->isMatchingExtension( $extension, $mime );
611 if ( $match === NULL ) {
612 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
614 } elseif( $match === true ) {
615 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
617 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
621 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
627 * Heuristic for detecting files that *could* contain JavaScript instructions or
628 * things that may look like HTML to a browser and are thus
629 * potentially harmful. The present implementation will produce false positives in some situations.
631 * @param string $file Pathname to the temporary upload file
632 * @param string $mime The mime type of the file
633 * @param string $extension The extension of the file
634 * @return bool true if the file contains something looking like embedded scripts
636 public static function detectScript( $file, $mime, $extension ) {
637 global $wgAllowTitlesInSVG;
639 #ugly hack: for text files, always look at the entire file.
640 #For binary field, just check the first K.
642 if( strpos( $mime,'text/' ) === 0 )
643 $chunk = file_get_contents( $file );
645 $fp = fopen( $file, 'rb' );
646 $chunk = fread( $fp, 1024 );
650 $chunk = strtolower( $chunk );
655 #decode from UTF-16 if needed (could be used for obfuscation).
656 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
658 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
664 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
666 $chunk = trim( $chunk );
668 #FIXME: convert from UTF-16 if necessarry!
669 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
671 #check for HTML doctype
672 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
676 * Internet Explorer for Windows performs some really stupid file type
677 * autodetection which can cause it to interpret valid image files as HTML
678 * and potentially execute JavaScript, creating a cross-site scripting
681 * Apple's Safari browser also performs some unsafe file type autodetection
682 * which can cause legitimate files to be interpreted as HTML if the
683 * web server is not correctly configured to send the right content-type
684 * (or if you're really uploading plain text and octet streams!)
686 * Returns true if IE is likely to mistake the given file for HTML.
687 * Also returns true if Safari would mistake the given file for HTML
688 * when served with a generic content-type.
694 '<html', #also in safari
697 '<script', #also in safari
701 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
705 foreach( $tags as $tag ) {
706 if( false !== strpos( $chunk, $tag ) ) {
712 * look for JavaScript
715 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
716 $chunk = Sanitizer
::decodeCharReferences( $chunk );
718 #look for script-types
719 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
722 #look for html-style script-urls
723 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
726 #look for css-style script-urls
727 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
730 wfDebug( __METHOD__
. ": no scripts found\n" );
734 protected function detectScriptInSvg( $filename ) {
735 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
736 return $check->filterMatch
;
740 * @todo Replace this with a whitelist filter!
742 public function checkSvgScriptCallback( $element, $attribs ) {
743 $stripped = $this->stripXmlNamespace( $element );
745 if( $stripped == 'script' ) {
746 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
750 foreach( $attribs as $attrib => $value ) {
751 $stripped = $this->stripXmlNamespace( $attrib );
752 if( substr( $stripped, 0, 2 ) == 'on' ) {
753 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
756 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
757 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
763 private function stripXmlNamespace( $name ) {
764 // 'http://www.w3.org/2000/svg:script' -> 'script'
765 $parts = explode( ':', strtolower( $name ) );
766 return array_pop( $parts );
770 * Generic wrapper function for a virus scanner program.
771 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
772 * $wgAntivirusRequired may be used to deny upload if the scan fails.
774 * @param string $file Pathname to the temporary upload file
775 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
776 * or a string containing feedback from the virus scanner if a virus was found.
777 * If textual feedback is missing but a virus was found, this function returns true.
779 public static function detectVirus( $file ) {
780 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
782 if ( !$wgAntivirus ) {
783 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
787 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
788 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
789 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
790 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
793 # look up scanner configuration
794 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
795 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
796 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
797 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
799 if ( strpos( $command,"%f" ) === false ) {
800 # simple pattern: append file to scan
801 $command .= " " . wfEscapeShellArg( $file );
803 # complex pattern: replace "%f" with file to scan
804 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
807 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
809 # execute virus scanner
812 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
813 # that does not seem to be worth the pain.
814 # Ask me (Duesentrieb) about it if it's ever needed.
816 $output = wfShellExec($command, $exitCode);
819 # map exit code to AV_xxx constants.
820 $mappedCode = $exitCode;
821 if ( $exitCodeMap ) {
822 if ( isset( $exitCodeMap[$exitCode] ) ) {
823 $mappedCode = $exitCodeMap[$exitCode];
824 } elseif ( isset( $exitCodeMap["*"] ) ) {
825 $mappedCode = $exitCodeMap["*"];
830 if ( $mappedCode === AV_SCAN_FAILED
) {
831 # scan failed (code was mapped to false by $exitCodeMap)
832 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
834 if ( $wgAntivirusRequired ) {
835 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
839 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
840 # scan failed because filetype is unknown (probably imune)
841 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
843 } else if ( $mappedCode === AV_NO_VIRUS
) {
845 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
848 $output = join( "\n", $output );
849 $output = trim( $output );
852 $output = true; #if there's no output, return true
853 } elseif ( $msgPattern ) {
855 if ( preg_match( $msgPattern, $output, $groups ) ) {
857 $output = $groups[1];
862 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
868 * Check if the temporary file is MacBinary-encoded, as some uploads
869 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
870 * If so, the data fork will be extracted to a second temporary file,
871 * which will then be checked for validity and either kept or discarded.
875 private function checkMacBinary() {
876 $macbin = new MacBinary( $this->mTempPath
);
877 if( $macbin->isValid() ) {
878 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
879 $dataHandle = fopen( $dataFile, 'wb' );
881 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
882 $macbin->extractData( $dataHandle );
884 $this->mTempPath
= $dataFile;
885 $this->mFileSize
= $macbin->dataForkLength();
887 // We'll have to manually remove the new file if it's not kept.
888 $this->mRemoveTempFile
= true;
894 * Check if there's an overwrite conflict and, if so, if restrictions
895 * forbid this user from performing the upload.
897 * @return mixed true on success, error string on failure
900 private function checkOverwrite() {
902 // First check whether the local file can be overwritten
903 $file = $this->getLocalFile();
904 if( $file->exists() ) {
905 if( !self
::userCanReUpload( $wgUser, $file ) )
906 return 'fileexists-forbidden';
911 /* Check shared conflicts: if the local file does not exist, but
912 * wfFindFile finds a file, it exists in a shared repository.
914 $file = wfFindFile( $this->getTitle() );
915 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) )
916 return 'fileexists-shared-forbidden';
922 * Check if a user is the last uploader
925 * @param string $img, image name
928 public static function userCanReUpload( User
$user, $img ) {
929 if( $user->isAllowed( 'reupload' ) )
930 return true; // non-conditional
931 if( !$user->isAllowed( 'reupload-own' ) )
933 if( is_string( $img ) )
934 $img = wfLocalFile( $img );
935 if ( !( $img instanceof LocalFile
) )
938 return $user->getId() == $img->getUser( 'id' );
942 * Helper function that does various existence checks for a file.
943 * The following checks are performed:
945 * - Article with the same name as the file exists
946 * - File exists with normalized extension
947 * - The file looks like a thumbnail and the original exists
949 * @param File $file The file to check
950 * @return mixed False if the file does not exists, else an array
952 public static function getExistsWarning( $file ) {
953 if( $file->exists() )
954 return array( 'warning' => 'exists', 'file' => $file );
956 if( $file->getTitle()->getArticleID() )
957 return array( 'warning' => 'page-exists', 'file' => $file );
959 if ( $file->wasDeleted() && !$file->exists() )
960 return array( 'warning' => 'was-deleted', 'file' => $file );
962 if( strpos( $file->getName(), '.' ) == false ) {
963 $partname = $file->getName();
966 $n = strrpos( $file->getName(), '.' );
967 $extension = substr( $file->getName(), $n +
1 );
968 $partname = substr( $file->getName(), 0, $n );
970 $normalizedExtension = File
::normalizeExtension( $extension );
972 if ( $normalizedExtension != $extension ) {
973 // We're not using the normalized form of the extension.
974 // Normal form is lowercase, using most common of alternate
975 // extensions (eg 'jpg' rather than 'JPEG').
977 // Check for another file using the normalized form...
978 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
979 $file_lc = wfLocalFile( $nt_lc );
981 if( $file_lc->exists() )
982 return array( 'warning' => 'exists-normalized', 'file' => $file, 'normalizedFile' => $file_lc );
985 if ( self
::isThumbName( $file->getName() ) ) {
986 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
987 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
988 $file_thb = wfLocalFile( $nt_thb );
989 if( $file_thb->exists() )
990 return array( 'warning' => 'thumb', 'file' => $file, 'thumbFile' => $file_thb );
992 // File does not exist, but we just don't like the name
993 return array( 'warning' => 'thumb-name', 'file' => $file, 'thumbFile' => $file_thb );
997 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
998 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix )
999 return array( 'warning' => 'bad-prefix', 'file' => $file, 'prefix' => $prefix );
1008 * Helper function that checks whether the filename looks like a thumbnail
1010 public static function isThumbName( $filename ) {
1011 $n = strrpos( $filename, '.' );
1012 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1014 substr( $partname , 3, 3 ) == 'px-' ||
1015 substr( $partname , 2, 3 ) == 'px-'
1017 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1021 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1023 * @return array list of prefixes
1025 public static function getFilenamePrefixBlacklist() {
1026 $blacklist = array();
1027 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1028 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1029 $lines = explode( "\n", $message );
1030 foreach( $lines as $line ) {
1031 // Remove comment lines
1032 $comment = substr( trim( $line ), 0, 1 );
1033 if ( $comment == '#' ||
$comment == '' ) {
1036 // Remove additional comments after a prefix
1037 $comment = strpos( $line, '#' );
1038 if ( $comment > 0 ) {
1039 $line = substr( $line, 0, $comment-1 );
1041 $blacklist[] = trim( $line );