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;
26 const MIN_LENGTH_PARTNAME
= 4;
27 const ILLEGAL_FILENAME
= 5;
28 const OVERWRITE_EXISTING_FILE
= 7;
29 const FILETYPE_MISSING
= 8;
30 const FILETYPE_BADTYPE
= 9;
31 const VERIFICATION_ERROR
= 10;
32 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
33 const UPLOAD_VERIFICATION_ERROR
= 11;
34 const HOOK_ABORTED
= 11;
35 const FILE_TOO_LARGE
= 12;
37 const SESSION_VERSION
= 2;
38 const SESSION_KEYNAME
= 'wsUploadData';
40 static public function getSessionKeyname() {
41 return self
::SESSION_KEYNAME
;
45 * Returns true if uploads are enabled.
46 * Can be override by subclasses.
48 public static function isEnabled() {
49 global $wgEnableUploads;
50 if ( !$wgEnableUploads ) {
54 # Check php's file_uploads setting
55 if( !wfIniGetBool( 'file_uploads' ) ) {
62 * Returns true if the user can use this upload module or else a string
63 * identifying the missing permission.
64 * Can be overriden by subclasses.
66 public static function isAllowed( $user ) {
67 if( !$user->isAllowed( 'upload' ) ) {
73 // Upload handlers. Should probably just be a global.
74 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
77 * Create a form of UploadBase depending on wpSourceType and initializes it
79 public static function createFromRequest( &$request, $type = null ) {
80 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
86 // Get the upload class
87 $type = ucfirst( $type );
89 // Give hooks the chance to handle this request
91 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
92 if ( is_null( $className ) ) {
93 $className = 'UploadFrom' . $type;
94 wfDebug( __METHOD__
. ": class name: $className\n" );
95 if( !in_array( $type, self
::$uploadHandlers ) ) {
100 // Check whether this upload class is enabled
101 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
105 // Check whether the request is valid
106 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
110 $handler = new $className;
112 $handler->initializeFromRequest( $request );
117 * Check whether a request if valid for this handler
119 public static function isValidRequest( $request ) {
123 public function __construct() {}
126 * Initialize the path information
127 * @param $name string the desired destination name
128 * @param $tempPath string the temporary path
129 * @param $fileSize int the file size
130 * @param $removeTempFile bool (false) remove the temporary file?
133 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
134 $this->mDesiredDestName
= $name;
135 $this->mTempPath
= $tempPath;
136 $this->mFileSize
= $fileSize;
137 $this->mRemoveTempFile
= $removeTempFile;
141 * Initialize from a WebRequest. Override this in a subclass.
143 public abstract function initializeFromRequest( &$request );
146 * Fetch the file. Usually a no-op
148 public function fetchFile() {
149 return Status
::newGood();
153 * Return true if the file is empty
156 public function isEmptyFile() {
157 return empty( $this->mFileSize
);
161 * Return the file size
164 public function getFileSize() {
165 return $this->mFileSize
;
169 * Append a file to the Repo file
171 * @param $srcPath String: path to source file
172 * @param $toAppendPath String: path to the Repo file that will be appended to.
173 * @return Status Status
175 protected function appendToUploadFile( $srcPath, $toAppendPath ) {
176 $repo = RepoGroup
::singleton()->getLocalRepo();
177 $status = $repo->append( $srcPath, $toAppendPath );
182 * @param $srcPath String: the source path
183 * @return the real path if it was a virtual URL
185 function getRealPath( $srcPath ) {
186 $repo = RepoGroup
::singleton()->getLocalRepo();
187 if ( $repo->isVirtualUrl( $srcPath ) ) {
188 return $repo->resolveVirtualUrl( $srcPath );
194 * Verify whether the upload is sane.
195 * @return mixed self::OK or else an array with error information
197 public function verifyUpload( ) {
199 * If there was no filename or a zero size given, give up quick.
201 if( $this->isEmptyFile() ) {
202 return array( 'status' => self
::EMPTY_FILE
);
206 * Honor $wgMaxUploadSize
208 global $wgMaxUploadSize;
209 if( $this->mFileSize
> $wgMaxUploadSize ) {
210 return array( 'status' => self
::FILE_TOO_LARGE
);
214 * Look at the contents of the file; if we can recognize the
215 * type but it's corrupt or data of the wrong type, we should
216 * probably not accept it.
218 $verification = $this->verifyFile();
219 if( $verification !== true ) {
220 if( !is_array( $verification ) ) {
221 $verification = array( $verification );
224 'status' => self
::VERIFICATION_ERROR
,
225 'details' => $verification
230 * Make sure this file can be created
232 $result = $this->validateNameAndOverwrite();
233 if( $result !== true ) {
238 if( !wfRunHooks( 'UploadVerification',
239 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
240 // @fixme This status needs another name...
241 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
244 return array( 'status' => self
::OK
);
248 * Verify that the name is valid and, if necessary, that we can overwrite
250 * @return mixed true if valid, otherwise and array with 'status'
253 public function validateNameAndOverwrite() {
254 $nt = $this->getTitle();
255 if( is_null( $nt ) ) {
256 $result = array( 'status' => $this->mTitleError
);
257 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
258 $result['filtered'] = $this->mFilteredName
;
260 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
261 $result['finalExt'] = $this->mFinalExtension
;
265 $this->mDestName
= $this->getLocalFile()->getName();
268 * In some cases we may forbid overwriting of existing files.
270 $overwrite = $this->checkOverwrite();
271 if( $overwrite !== true ) {
273 'status' => self
::OVERWRITE_EXISTING_FILE
,
274 'overwrite' => $overwrite
281 * Verifies that it's ok to include the uploaded file
283 * @return mixed true of the file is verified, a string or array otherwise.
285 protected function verifyFile() {
286 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
287 $this->checkMacBinary();
289 # magically determine mime type
290 $magic = MimeMagic
::singleton();
291 $mime = $magic->guessMimeType( $this->mTempPath
, false );
293 # check mime type, if desired
294 global $wgVerifyMimeType;
295 if ( $wgVerifyMimeType ) {
296 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
297 if ( !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
298 return array( 'filetype-mime-mismatch' );
301 global $wgMimeTypeBlacklist;
302 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
303 return array( 'filetype-badmime', $mime );
307 $fp = fopen( $this->mTempPath
, 'rb' );
308 $chunk = fread( $fp, 256 );
310 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
311 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
312 foreach ( $ieTypes as $ieType ) {
313 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
314 return array( 'filetype-bad-ie-mime', $ieType );
319 # check for htmlish code and javascript
320 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
321 return 'uploadscripted';
323 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
324 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
325 return 'uploadscripted';
330 * Scan the uploaded file for viruses
332 $virus = $this->detectVirus( $this->mTempPath
);
334 return array( 'uploadvirus', $virus );
336 wfDebug( __METHOD__
. ": all clear; passing.\n" );
341 * Check whether the user can edit, upload and create the image.
343 * @param $user the User object to verify the permissions against
344 * @return mixed An array as returned by getUserPermissionsErrors or true
345 * in case the user has proper permissions.
347 public function verifyPermissions( $user ) {
349 * If the image is protected, non-sysop users won't be able
350 * to modify it by uploading a new revision.
352 $nt = $this->getTitle();
353 if( is_null( $nt ) ) {
356 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
357 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
358 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
359 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
360 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
361 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
368 * Check for non fatal problems with the file
370 * @return Array of warnings
372 public function checkWarnings() {
375 $localFile = $this->getLocalFile();
376 $filename = $localFile->getName();
377 $n = strrpos( $filename, '.' );
378 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
381 * Check whether the resulting filename is different from the desired one,
382 * but ignore things like ucfirst() and spaces/underscore things
384 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
385 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
387 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
388 $warnings['badfilename'] = $filename;
391 // Check whether the file extension is on the unwanted list
392 global $wgCheckFileExtensions, $wgFileExtensions;
393 if ( $wgCheckFileExtensions ) {
394 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
395 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
399 global $wgUploadSizeWarning;
400 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
401 $warnings['large-file'] = $wgUploadSizeWarning;
404 if ( $this->mFileSize
== 0 ) {
405 $warnings['emptyfile'] = true;
408 $exists = self
::getExistsWarning( $localFile );
409 if( $exists !== false ) {
410 $warnings['exists'] = $exists;
413 // Check dupes against existing files
414 $hash = File
::sha1Base36( $this->mTempPath
);
415 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
416 $title = $this->getTitle();
417 // Remove all matches against self
418 foreach ( $dupes as $key => $dupe ) {
419 if( $title->equals( $dupe->getTitle() ) ) {
420 unset( $dupes[$key] );
424 $warnings['duplicate'] = $dupes;
427 // Check dupes against archives
428 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
429 if ( $archivedImage->getID() > 0 ) {
430 $warnings['duplicate-archive'] = $archivedImage->getName();
437 * Really perform the upload. Stores the file in the local repo, watches
438 * if necessary and runs the UploadComplete hook.
440 * @return mixed Status indicating the whether the upload succeeded.
442 public function performUpload( $comment, $pageText, $watch, $user ) {
443 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
444 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
445 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
447 if( $status->isGood() ) {
449 $user->addWatch( $this->getLocalFile()->getTitle() );
452 wfRunHooks( 'UploadComplete', array( &$this ) );
459 * Returns the title of the file to be uploaded. Sets mTitleError in case
460 * the name was illegal.
462 * @return Title The title of the file or null in case the name was illegal
464 public function getTitle() {
465 if ( $this->mTitle
!== false ) {
466 return $this->mTitle
;
470 * Chop off any directories in the given filename. Then
471 * filter out illegal characters, and try to make a legible name
472 * out of it. We'll strip some silently that Title would die on.
474 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mDesiredDestName
);
475 /* Normalize to title form before we do any further processing */
476 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
477 if( is_null( $nt ) ) {
478 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
479 return $this->mTitle
= null;
481 $this->mFilteredName
= $nt->getDBkey();
484 * We'll want to blacklist against *any* 'extension', and use
485 * only the final one for the whitelist.
487 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
489 if( count( $ext ) ) {
490 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
492 $this->mFinalExtension
= '';
495 /* Don't allow users to override the blacklist (check file extension) */
496 global $wgCheckFileExtensions, $wgStrictFileExtensions;
497 global $wgFileExtensions, $wgFileBlacklist;
498 if ( $this->mFinalExtension
== '' ) {
499 $this->mTitleError
= self
::FILETYPE_MISSING
;
500 return $this->mTitle
= null;
501 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
502 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
503 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
504 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
505 return $this->mTitle
= null;
508 # If there was more than one "extension", reassemble the base
509 # filename to prevent bogus complaints about length
510 if( count( $ext ) > 1 ) {
511 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
512 $partname .= '.' . $ext[$i];
516 if( strlen( $partname ) < 1 ) {
517 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
518 return $this->mTitle
= null;
521 return $this->mTitle
= $nt;
525 * Return the local file and initializes if necessary.
527 public function getLocalFile() {
528 if( is_null( $this->mLocalFile
) ) {
529 $nt = $this->getTitle();
530 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
532 return $this->mLocalFile
;
536 * Stash a file in a temporary directory for later processing
537 * after the user has confirmed it.
539 * If the user doesn't explicitly cancel or accept, these files
540 * can accumulate in the temp directory.
542 * @param $saveName String: the destination filename
543 * @param $tempSrc String: the source temporary file to save
544 * @return String: full path the stashed file, or false on failure
546 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
547 $repo = RepoGroup
::singleton()->getLocalRepo();
548 $status = $repo->storeTemp( $saveName, $tempSrc );
553 * Stash a file in a temporary directory for later processing,
554 * and save the necessary descriptive info into the session.
555 * Returns a key value which will be passed through a form
556 * to pick up the path info on a later invocation.
558 * @return Integer: session key
560 public function stashSession() {
561 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
562 if( !$status->isOK() ) {
563 # Couldn't save the file.
567 $key = $this->getSessionKey();
568 $_SESSION[self
::SESSION_KEYNAME
][$key] = array(
569 'mTempPath' => $status->value
,
570 'mFileSize' => $this->mFileSize
,
571 'mFileProps' => $this->mFileProps
,
572 'version' => self
::SESSION_VERSION
,
578 * Generate a random session key from stash in cases where we want to start an upload without much information
580 protected function getSessionKey() {
581 $key = mt_rand( 0, 0x7fffffff );
582 $_SESSION[self
::SESSION_KEYNAME
][$key] = array();
587 * If we've modified the upload file we need to manually remove it
588 * on exit to clean up.
590 public function cleanupTempFile() {
591 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
592 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
593 unlink( $this->mTempPath
);
597 public function getTempPath() {
598 return $this->mTempPath
;
602 * Split a file into a base name and all dot-delimited 'extensions'
603 * on the end. Some web server configurations will fall back to
604 * earlier pseudo-'extensions' to determine type and execute
605 * scripts, so the blacklist needs to check them all.
609 public static function splitExtensions( $filename ) {
610 $bits = explode( '.', $filename );
611 $basename = array_shift( $bits );
612 return array( $basename, $bits );
616 * Perform case-insensitive match against a list of file extensions.
617 * Returns true if the extension is in the list.
623 public static function checkFileExtension( $ext, $list ) {
624 return in_array( strtolower( $ext ), $list );
628 * Perform case-insensitive match against a list of file extensions.
629 * Returns true if any of the extensions are in the list.
635 public static function checkFileExtensionList( $ext, $list ) {
636 foreach( $ext as $e ) {
637 if( in_array( strtolower( $e ), $list ) ) {
645 * Checks if the mime type of the uploaded file matches the file extension.
647 * @param $mime String: the mime type of the uploaded file
648 * @param $extension String: the filename extension that the file is to be served with
651 public static function verifyExtension( $mime, $extension ) {
652 $magic = MimeMagic
::singleton();
654 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
655 if ( !$magic->isRecognizableExtension( $extension ) ) {
656 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
657 "unrecognized extension '$extension', can't verify\n" );
660 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
661 "recognized extension '$extension', so probably invalid file\n" );
665 $match = $magic->isMatchingExtension( $extension, $mime );
667 if ( $match === null ) {
668 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
670 } elseif( $match === true ) {
671 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
673 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
677 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
683 * Heuristic for detecting files that *could* contain JavaScript instructions or
684 * things that may look like HTML to a browser and are thus
685 * potentially harmful. The present implementation will produce false
686 * positives in some situations.
688 * @param $file String: pathname to the temporary upload file
689 * @param $mime String: the mime type of the file
690 * @param $extension String: the extension of the file
691 * @return Boolean: true if the file contains something looking like embedded scripts
693 public static function detectScript( $file, $mime, $extension ) {
694 global $wgAllowTitlesInSVG;
696 # ugly hack: for text files, always look at the entire file.
697 # For binary field, just check the first K.
699 if( strpos( $mime,'text/' ) === 0 ) {
700 $chunk = file_get_contents( $file );
702 $fp = fopen( $file, 'rb' );
703 $chunk = fread( $fp, 1024 );
707 $chunk = strtolower( $chunk );
713 # decode from UTF-16 if needed (could be used for obfuscation).
714 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
716 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
723 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
726 $chunk = trim( $chunk );
728 # FIXME: convert from UTF-16 if necessarry!
729 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
731 # check for HTML doctype
732 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
737 * Internet Explorer for Windows performs some really stupid file type
738 * autodetection which can cause it to interpret valid image files as HTML
739 * and potentially execute JavaScript, creating a cross-site scripting
742 * Apple's Safari browser also performs some unsafe file type autodetection
743 * which can cause legitimate files to be interpreted as HTML if the
744 * web server is not correctly configured to send the right content-type
745 * (or if you're really uploading plain text and octet streams!)
747 * Returns true if IE is likely to mistake the given file for HTML.
748 * Also returns true if Safari would mistake the given file for HTML
749 * when served with a generic content-type.
755 '<html', #also in safari
758 '<script', #also in safari
762 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
766 foreach( $tags as $tag ) {
767 if( false !== strpos( $chunk, $tag ) ) {
773 * look for JavaScript
776 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
777 $chunk = Sanitizer
::decodeCharReferences( $chunk );
779 # look for script-types
780 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
784 # look for html-style script-urls
785 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
789 # look for css-style script-urls
790 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
794 wfDebug( __METHOD__
. ": no scripts found\n" );
798 protected function detectScriptInSvg( $filename ) {
799 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
800 return $check->filterMatch
;
804 * @todo Replace this with a whitelist filter!
806 public function checkSvgScriptCallback( $element, $attribs ) {
807 $stripped = $this->stripXmlNamespace( $element );
809 if( $stripped == 'script' ) {
810 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
814 foreach( $attribs as $attrib => $value ) {
815 $stripped = $this->stripXmlNamespace( $attrib );
816 if( substr( $stripped, 0, 2 ) == 'on' ) {
817 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
820 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
821 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
827 private function stripXmlNamespace( $name ) {
828 // 'http://www.w3.org/2000/svg:script' -> 'script'
829 $parts = explode( ':', strtolower( $name ) );
830 return array_pop( $parts );
834 * Generic wrapper function for a virus scanner program.
835 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
836 * $wgAntivirusRequired may be used to deny upload if the scan fails.
838 * @param $file String: pathname to the temporary upload file
839 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
840 * or a string containing feedback from the virus scanner if a virus was found.
841 * If textual feedback is missing but a virus was found, this function returns true.
843 public static function detectVirus( $file ) {
844 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
846 if ( !$wgAntivirus ) {
847 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
851 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
852 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
853 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>", array( 'virus-badscanner', $wgAntivirus ) );
854 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
857 # look up scanner configuration
858 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
859 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
860 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
861 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
863 if ( strpos( $command, "%f" ) === false ) {
864 # simple pattern: append file to scan
865 $command .= " " . wfEscapeShellArg( $file );
867 # complex pattern: replace "%f" with file to scan
868 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
871 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
873 # execute virus scanner
876 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
877 # that does not seem to be worth the pain.
878 # Ask me (Duesentrieb) about it if it's ever needed.
879 $output = wfShellExec( "$command 2>&1", $exitCode );
881 # map exit code to AV_xxx constants.
882 $mappedCode = $exitCode;
883 if ( $exitCodeMap ) {
884 if ( isset( $exitCodeMap[$exitCode] ) ) {
885 $mappedCode = $exitCodeMap[$exitCode];
886 } elseif ( isset( $exitCodeMap["*"] ) ) {
887 $mappedCode = $exitCodeMap["*"];
891 if ( $mappedCode === AV_SCAN_FAILED
) {
892 # scan failed (code was mapped to false by $exitCodeMap)
893 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
895 if ( $wgAntivirusRequired ) {
896 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
900 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
901 # scan failed because filetype is unknown (probably imune)
902 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
904 } elseif ( $mappedCode === AV_NO_VIRUS
) {
906 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
909 $output = trim( $output );
912 $output = true; #if there's no output, return true
913 } elseif ( $msgPattern ) {
915 if ( preg_match( $msgPattern, $output, $groups ) ) {
917 $output = $groups[1];
922 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
928 * Check if the temporary file is MacBinary-encoded, as some uploads
929 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
930 * If so, the data fork will be extracted to a second temporary file,
931 * which will then be checked for validity and either kept or discarded.
933 private function checkMacBinary() {
934 $macbin = new MacBinary( $this->mTempPath
);
935 if( $macbin->isValid() ) {
936 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
937 $dataHandle = fopen( $dataFile, 'wb' );
939 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
940 $macbin->extractData( $dataHandle );
942 $this->mTempPath
= $dataFile;
943 $this->mFileSize
= $macbin->dataForkLength();
945 // We'll have to manually remove the new file if it's not kept.
946 $this->mRemoveTempFile
= true;
952 * Check if there's an overwrite conflict and, if so, if restrictions
953 * forbid this user from performing the upload.
955 * @return mixed true on success, error string on failure
957 private function checkOverwrite() {
959 // First check whether the local file can be overwritten
960 $file = $this->getLocalFile();
961 if( $file->exists() ) {
962 if( !self
::userCanReUpload( $wgUser, $file ) ) {
963 return 'fileexists-forbidden';
969 /* Check shared conflicts: if the local file does not exist, but
970 * wfFindFile finds a file, it exists in a shared repository.
972 $file = wfFindFile( $this->getTitle() );
973 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) ) {
974 return 'fileexists-shared-forbidden';
981 * Check if a user is the last uploader
983 * @param $user User object
984 * @param $img String: image name
987 public static function userCanReUpload( User
$user, $img ) {
988 if( $user->isAllowed( 'reupload' ) ) {
989 return true; // non-conditional
991 if( !$user->isAllowed( 'reupload-own' ) ) {
994 if( is_string( $img ) ) {
995 $img = wfLocalFile( $img );
997 if ( !( $img instanceof LocalFile
) ) {
1001 return $user->getId() == $img->getUser( 'id' );
1005 * Helper function that does various existence checks for a file.
1006 * The following checks are performed:
1008 * - Article with the same name as the file exists
1009 * - File exists with normalized extension
1010 * - The file looks like a thumbnail and the original exists
1012 * @param $file The File object to check
1013 * @return mixed False if the file does not exists, else an array
1015 public static function getExistsWarning( $file ) {
1016 if( $file->exists() ) {
1017 return array( 'warning' => 'exists', 'file' => $file );
1020 if( $file->getTitle()->getArticleID() ) {
1021 return array( 'warning' => 'page-exists', 'file' => $file );
1024 if ( $file->wasDeleted() && !$file->exists() ) {
1025 return array( 'warning' => 'was-deleted', 'file' => $file );
1028 if( strpos( $file->getName(), '.' ) == false ) {
1029 $partname = $file->getName();
1032 $n = strrpos( $file->getName(), '.' );
1033 $extension = substr( $file->getName(), $n +
1 );
1034 $partname = substr( $file->getName(), 0, $n );
1036 $normalizedExtension = File
::normalizeExtension( $extension );
1038 if ( $normalizedExtension != $extension ) {
1039 // We're not using the normalized form of the extension.
1040 // Normal form is lowercase, using most common of alternate
1041 // extensions (eg 'jpg' rather than 'JPEG').
1043 // Check for another file using the normalized form...
1044 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1045 $file_lc = wfLocalFile( $nt_lc );
1047 if( $file_lc->exists() ) {
1049 'warning' => 'exists-normalized',
1051 'normalizedFile' => $file_lc
1056 if ( self
::isThumbName( $file->getName() ) ) {
1057 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1058 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1059 $file_thb = wfLocalFile( $nt_thb );
1060 if( $file_thb->exists() ) {
1062 'warning' => 'thumb',
1064 'thumbFile' => $file_thb
1067 // File does not exist, but we just don't like the name
1069 'warning' => 'thumb-name',
1071 'thumbFile' => $file_thb
1077 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1078 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1080 'warning' => 'bad-prefix',
1091 * Helper function that checks whether the filename looks like a thumbnail
1093 public static function isThumbName( $filename ) {
1094 $n = strrpos( $filename, '.' );
1095 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1097 substr( $partname , 3, 3 ) == 'px-' ||
1098 substr( $partname , 2, 3 ) == 'px-'
1100 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1104 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1106 * @return array list of prefixes
1108 public static function getFilenamePrefixBlacklist() {
1109 $blacklist = array();
1110 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1111 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1112 $lines = explode( "\n", $message );
1113 foreach( $lines as $line ) {
1114 // Remove comment lines
1115 $comment = substr( trim( $line ), 0, 1 );
1116 if ( $comment == '#' ||
$comment == '' ) {
1119 // Remove additional comments after a prefix
1120 $comment = strpos( $line, '#' );
1121 if ( $comment > 0 ) {
1122 $line = substr( $line, 0, $comment-1 );
1124 $blacklist[] = trim( $line );
1130 public function getImageInfo( $result ) {
1131 $file = $this->getLocalFile();
1132 $imParam = ApiQueryImageInfo
::getPropertyNames();
1133 return ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );