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 const UPLOAD_VERIFICATION_ERROR
= 11;
33 const HOOK_ABORTED
= 11;
35 const SESSION_VERSION
= 2;
38 * Returns true if uploads are enabled.
39 * Can be override by subclasses.
41 public static function isEnabled() {
42 global $wgEnableUploads;
43 if ( !$wgEnableUploads ) {
47 # Check php's file_uploads setting
48 if( !wfIniGetBool( 'file_uploads' ) ) {
55 * Returns true if the user can use this upload module or else a string
56 * identifying the missing permission.
57 * Can be overriden by subclasses.
59 public static function isAllowed( $user ) {
60 if( !$user->isAllowed( 'upload' ) ) {
66 // Upload handlers. Should probably just be a global.
67 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
70 * Create a form of UploadBase depending on wpSourceType and initializes it
72 public static function createFromRequest( &$request, $type = null ) {
73 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
79 // Get the upload class
80 $type = ucfirst( $type );
82 // Give hooks the chance to handle this request
84 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
85 if ( is_null( $className ) ) {
86 $className = 'UploadFrom' . $type;
87 wfDebug( __METHOD__
. ": class name: $className\n" );
88 if( !in_array( $type, self
::$uploadHandlers ) ) {
93 // Check whether this upload class is enabled
94 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
98 // Check whether the request is valid
99 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
103 $handler = new $className;
105 $handler->initializeFromRequest( $request );
110 * Check whether a request if valid for this handler
112 public static function isValidRequest( $request ) {
116 public function __construct() {}
119 * Initialize the path information
120 * @param $name string the desired destination name
121 * @param $tempPath string the temporary path
122 * @param $fileSize int the file size
123 * @param $removeTempFile bool (false) remove the temporary file?
126 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
127 $this->mDesiredDestName
= $name;
128 $this->mTempPath
= $tempPath;
129 $this->mFileSize
= $fileSize;
130 $this->mRemoveTempFile
= $removeTempFile;
134 * Initialize from a WebRequest. Override this in a subclass.
136 public abstract function initializeFromRequest( &$request );
139 * Fetch the file. Usually a no-op
141 public function fetchFile() {
142 return Status
::newGood();
146 * Return the file size
148 public function isEmptyFile() {
149 return empty( $this->mFileSize
);
153 * @param string $srcPath the source path
154 * @returns the real path if it was a virtual URL
156 function getRealPath( $srcPath ) {
157 $repo = RepoGroup
::singleton()->getLocalRepo();
158 if ( $repo->isVirtualUrl( $srcPath ) ) {
159 return $repo->resolveVirtualUrl( $srcPath );
165 * Verify whether the upload is sane.
166 * Returns self::OK or else an array with error information
168 public function verifyUpload() {
170 * If there was no filename or a zero size given, give up quick.
172 if( $this->isEmptyFile() ) {
173 return array( 'status' => self
::EMPTY_FILE
);
177 * Look at the contents of the file; if we can recognize the
178 * type but it's corrupt or data of the wrong type, we should
179 * probably not accept it.
181 $verification = $this->verifyFile();
182 if( $verification !== true ) {
183 if( !is_array( $verification ) ) {
184 $verification = array( $verification );
187 'status' => self
::VERIFICATION_ERROR
,
188 'details' => $verification
192 $nt = $this->getTitle();
193 if( is_null( $nt ) ) {
194 $result = array( 'status' => $this->mTitleError
);
195 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
196 $result['filtered'] = $this->mFilteredName
;
198 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
199 $result['finalExt'] = $this->mFinalExtension
;
203 $this->mDestName
= $this->getLocalFile()->getName();
206 * In some cases we may forbid overwriting of existing files.
208 $overwrite = $this->checkOverwrite();
209 if( $overwrite !== true ) {
211 'status' => self
::OVERWRITE_EXISTING_FILE
,
212 'overwrite' => $overwrite
217 if( !wfRunHooks( 'UploadVerification',
218 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
219 // This status needs another name...
220 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
223 return array( 'status' => self
::OK
);
227 * Verifies that it's ok to include the uploaded file
229 * @return mixed true of the file is verified, a string or array otherwise.
231 protected function verifyFile() {
232 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
233 $this->checkMacBinary();
235 # magically determine mime type
236 $magic = MimeMagic
::singleton();
237 $mime = $magic->guessMimeType( $this->mTempPath
, false );
239 # check mime type, if desired
240 global $wgVerifyMimeType;
241 if ( $wgVerifyMimeType ) {
242 global $wgMimeTypeBlacklist;
243 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
244 return array( 'filetype-badmime', $mime );
248 $fp = fopen( $this->mTempPath
, 'rb' );
249 $chunk = fread( $fp, 256 );
251 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
252 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
253 foreach ( $ieTypes as $ieType ) {
254 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
255 return array( 'filetype-bad-ie-mime', $ieType );
260 # check for htmlish code and javascript
261 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
262 return 'uploadscripted';
264 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
265 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
266 return 'uploadscripted';
271 * Scan the uploaded file for viruses
273 $virus = $this->detectVirus( $this->mTempPath
);
275 return array( 'uploadvirus', $virus );
277 wfDebug( __METHOD__
. ": all clear; passing.\n" );
282 * Check whether the user can edit, upload and create the image.
284 * @param User $user the user to verify the permissions against
285 * @return mixed An array as returned by getUserPermissionsErrors or true
286 * in case the user has proper permissions.
288 public function verifyPermissions( $user ) {
290 * If the image is protected, non-sysop users won't be able
291 * to modify it by uploading a new revision.
293 $nt = $this->getTitle();
294 if( is_null( $nt ) ) {
297 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
298 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
299 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
300 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
301 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
302 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
309 * Check for non fatal problems with the file
311 * @return array Array of warnings
313 public function checkWarnings() {
316 $localFile = $this->getLocalFile();
317 $filename = $localFile->getName();
318 $n = strrpos( $filename, '.' );
319 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
322 * Check whether the resulting filename is different from the desired one,
323 * but ignore things like ucfirst() and spaces/underscore things
325 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
326 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
328 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
329 $warnings['badfilename'] = $filename;
332 // Check whether the file extension is on the unwanted list
333 global $wgCheckFileExtensions, $wgFileExtensions;
334 if ( $wgCheckFileExtensions ) {
335 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
336 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
340 global $wgUploadSizeWarning;
341 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
342 $warnings['large-file'] = $wgUploadSizeWarning;
345 if ( $this->mFileSize
== 0 ) {
346 $warnings['emptyfile'] = true;
349 $exists = self
::getExistsWarning( $localFile );
350 if( $exists !== false ) {
351 $warnings['exists'] = $exists;
354 // Check dupes against existing files
355 $hash = File
::sha1Base36( $this->mTempPath
);
356 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
357 $title = $this->getTitle();
358 // Remove all matches against self
359 foreach ( $dupes as $key => $dupe ) {
360 if( $title->equals( $dupe->getTitle() ) ) {
361 unset( $dupes[$key] );
365 $warnings['duplicate'] = $dupes;
368 // Check dupes against archives
369 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
370 if ( $archivedImage->getID() > 0 ) {
371 $warnings['duplicate-archive'] = $archivedImage->getName();
378 * Really perform the upload. Stores the file in the local repo, watches
379 * if necessary and runs the UploadComplete hook.
381 * @return mixed Status indicating the whether the upload succeeded.
383 public function performUpload( $comment, $pageText, $watch, $user ) {
384 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
385 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
386 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
388 if( $status->isGood() && $watch ) {
389 $user->addWatch( $this->getLocalFile()->getTitle() );
392 if( $status->isGood() ) {
393 wfRunHooks( 'UploadComplete', array( &$this ) );
400 * Returns the title of the file to be uploaded. Sets mTitleError in case
401 * the name was illegal.
403 * @return Title The title of the file or null in case the name was illegal
405 public function getTitle() {
406 if ( $this->mTitle
!== false ) {
407 return $this->mTitle
;
411 * Chop off any directories in the given filename. Then
412 * filter out illegal characters, and try to make a legible name
413 * out of it. We'll strip some silently that Title would die on.
415 $basename = $this->mDesiredDestName
;
417 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
418 /* Normalize to title form before we do any further processing */
419 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
420 if( is_null( $nt ) ) {
421 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
422 return $this->mTitle
= null;
424 $this->mFilteredName
= $nt->getDBkey();
427 * We'll want to blacklist against *any* 'extension', and use
428 * only the final one for the whitelist.
430 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
432 if( count( $ext ) ) {
433 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
435 $this->mFinalExtension
= '';
438 /* Don't allow users to override the blacklist (check file extension) */
439 global $wgCheckFileExtensions, $wgStrictFileExtensions;
440 global $wgFileExtensions, $wgFileBlacklist;
441 if ( $this->mFinalExtension
== '' ) {
442 $this->mTitleError
= self
::FILETYPE_MISSING
;
443 return $this->mTitle
= null;
444 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
445 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
446 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
447 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
448 return $this->mTitle
= null;
451 # If there was more than one "extension", reassemble the base
452 # filename to prevent bogus complaints about length
453 if( count( $ext ) > 1 ) {
454 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
455 $partname .= '.' . $ext[$i];
459 if( strlen( $partname ) < 1 ) {
460 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
461 return $this->mTitle
= null;
464 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
465 if( is_null( $nt ) ) {
466 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
467 return $this->mTitle
= null;
469 return $this->mTitle
= $nt;
473 * Return the local file and initializes if necessary.
475 public function getLocalFile() {
476 if( is_null( $this->mLocalFile
) ) {
477 $nt = $this->getTitle();
478 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
480 return $this->mLocalFile
;
484 * Stash a file in a temporary directory for later processing
485 * after the user has confirmed it.
487 * If the user doesn't explicitly cancel or accept, these files
488 * can accumulate in the temp directory.
490 * @param string $saveName - the destination filename
491 * @param string $tempSrc - the source temporary file to save
492 * @return string - full path the stashed file, or false on failure
494 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
495 $repo = RepoGroup
::singleton()->getLocalRepo();
496 $status = $repo->storeTemp( $saveName, $tempSrc );
501 * Stash a file in a temporary directory for later processing,
502 * and save the necessary descriptive info into the session.
503 * Returns a key value which will be passed through a form
504 * to pick up the path info on a later invocation.
506 * @return int Session key
508 public function stashSession() {
509 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
510 if( !$status->isOK() ) {
511 # Couldn't save the file.
514 if( !isset( $_SESSION ) ) {
515 session_start(); // start up the session (might have been previously closed to prevent php session locking)
517 $key = $this->getSessionKey();
518 $_SESSION['wsUploadData'][$key] = array(
519 'mTempPath' => $status->value
,
520 'mFileSize' => $this->mFileSize
,
521 'mFileProps' => $this->mFileProps
,
522 'version' => self
::SESSION_VERSION
,
528 * Generate a random session key from stash in cases where we want to start an upload without much information
530 protected function getSessionKey() {
531 $key = mt_rand( 0, 0x7fffffff );
532 $_SESSION['wsUploadData'][$key] = array();
537 * If we've modified the upload file we need to manually remove it
538 * on exit to clean up.
540 public function cleanupTempFile() {
541 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
542 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
543 unlink( $this->mTempPath
);
547 public function getTempPath() {
548 return $this->mTempPath
;
552 * Split a file into a base name and all dot-delimited 'extensions'
553 * on the end. Some web server configurations will fall back to
554 * earlier pseudo-'extensions' to determine type and execute
555 * scripts, so the blacklist needs to check them all.
559 public static function splitExtensions( $filename ) {
560 $bits = explode( '.', $filename );
561 $basename = array_shift( $bits );
562 return array( $basename, $bits );
566 * Perform case-insensitive match against a list of file extensions.
567 * Returns true if the extension is in the list.
573 public static function checkFileExtension( $ext, $list ) {
574 return in_array( strtolower( $ext ), $list );
578 * Perform case-insensitive match against a list of file extensions.
579 * Returns true if any of the extensions are in the list.
585 public static function checkFileExtensionList( $ext, $list ) {
586 foreach( $ext as $e ) {
587 if( in_array( strtolower( $e ), $list ) ) {
595 * Checks if the mime type of the uploaded file matches the file extension.
597 * @param string $mime the mime type of the uploaded file
598 * @param string $extension The filename extension that the file is to be served with
601 public static function verifyExtension( $mime, $extension ) {
602 $magic = MimeMagic
::singleton();
604 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
605 if ( !$magic->isRecognizableExtension( $extension ) ) {
606 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
607 "unrecognized extension '$extension', can't verify\n" );
610 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
611 "recognized extension '$extension', so probably invalid file\n" );
615 $match = $magic->isMatchingExtension( $extension, $mime );
617 if ( $match === null ) {
618 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
620 } elseif( $match === true ) {
621 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
623 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
627 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
633 * Heuristic for detecting files that *could* contain JavaScript instructions or
634 * things that may look like HTML to a browser and are thus
635 * potentially harmful. The present implementation will produce false
636 * positives in some situations.
638 * @param string $file Pathname to the temporary upload file
639 * @param string $mime The mime type of the file
640 * @param string $extension The extension of the file
641 * @return bool true if the file contains something looking like embedded scripts
643 public static function detectScript( $file, $mime, $extension ) {
644 global $wgAllowTitlesInSVG;
646 # ugly hack: for text files, always look at the entire file.
647 # For binary field, just check the first K.
649 if( strpos( $mime,'text/' ) === 0 ) {
650 $chunk = file_get_contents( $file );
652 $fp = fopen( $file, 'rb' );
653 $chunk = fread( $fp, 1024 );
657 $chunk = strtolower( $chunk );
663 # decode from UTF-16 if needed (could be used for obfuscation).
664 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
666 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
673 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
676 $chunk = trim( $chunk );
678 # FIXME: convert from UTF-16 if necessarry!
679 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
681 # check for HTML doctype
682 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
687 * Internet Explorer for Windows performs some really stupid file type
688 * autodetection which can cause it to interpret valid image files as HTML
689 * and potentially execute JavaScript, creating a cross-site scripting
692 * Apple's Safari browser also performs some unsafe file type autodetection
693 * which can cause legitimate files to be interpreted as HTML if the
694 * web server is not correctly configured to send the right content-type
695 * (or if you're really uploading plain text and octet streams!)
697 * Returns true if IE is likely to mistake the given file for HTML.
698 * Also returns true if Safari would mistake the given file for HTML
699 * when served with a generic content-type.
705 '<html', #also in safari
708 '<script', #also in safari
712 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
716 foreach( $tags as $tag ) {
717 if( false !== strpos( $chunk, $tag ) ) {
723 * look for JavaScript
726 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
727 $chunk = Sanitizer
::decodeCharReferences( $chunk );
729 # look for script-types
730 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
734 # look for html-style script-urls
735 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
739 # look for css-style script-urls
740 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
744 wfDebug( __METHOD__
. ": no scripts found\n" );
748 protected function detectScriptInSvg( $filename ) {
749 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
750 return $check->filterMatch
;
754 * @todo Replace this with a whitelist filter!
756 public function checkSvgScriptCallback( $element, $attribs ) {
757 $stripped = $this->stripXmlNamespace( $element );
759 if( $stripped == 'script' ) {
760 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
764 foreach( $attribs as $attrib => $value ) {
765 $stripped = $this->stripXmlNamespace( $attrib );
766 if( substr( $stripped, 0, 2 ) == 'on' ) {
767 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
770 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
771 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
777 private function stripXmlNamespace( $name ) {
778 // 'http://www.w3.org/2000/svg:script' -> 'script'
779 $parts = explode( ':', strtolower( $name ) );
780 return array_pop( $parts );
784 * Generic wrapper function for a virus scanner program.
785 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
786 * $wgAntivirusRequired may be used to deny upload if the scan fails.
788 * @param string $file Pathname to the temporary upload file
789 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
790 * or a string containing feedback from the virus scanner if a virus was found.
791 * If textual feedback is missing but a virus was found, this function returns true.
793 public static function detectVirus( $file ) {
794 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
796 if ( !$wgAntivirus ) {
797 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
801 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
802 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
803 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>", array( 'virus-badscanner', $wgAntivirus ) );
804 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
807 # look up scanner configuration
808 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
809 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
810 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
811 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
813 if ( strpos( $command, "%f" ) === false ) {
814 # simple pattern: append file to scan
815 $command .= " " . wfEscapeShellArg( $file );
817 # complex pattern: replace "%f" with file to scan
818 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
821 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
823 # execute virus scanner
826 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
827 # that does not seem to be worth the pain.
828 # Ask me (Duesentrieb) about it if it's ever needed.
829 $output = wfShellExec( "$command 2>&1", $exitCode );
831 # map exit code to AV_xxx constants.
832 $mappedCode = $exitCode;
833 if ( $exitCodeMap ) {
834 if ( isset( $exitCodeMap[$exitCode] ) ) {
835 $mappedCode = $exitCodeMap[$exitCode];
836 } elseif ( isset( $exitCodeMap["*"] ) ) {
837 $mappedCode = $exitCodeMap["*"];
841 if ( $mappedCode === AV_SCAN_FAILED
) {
842 # scan failed (code was mapped to false by $exitCodeMap)
843 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
845 if ( $wgAntivirusRequired ) {
846 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
850 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
851 # scan failed because filetype is unknown (probably imune)
852 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
854 } elseif ( $mappedCode === AV_NO_VIRUS
) {
856 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
859 $output = trim( $output );
862 $output = true; #if there's no output, return true
863 } elseif ( $msgPattern ) {
865 if ( preg_match( $msgPattern, $output, $groups ) ) {
867 $output = $groups[1];
872 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
878 * Check if the temporary file is MacBinary-encoded, as some uploads
879 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
880 * If so, the data fork will be extracted to a second temporary file,
881 * which will then be checked for validity and either kept or discarded.
883 private function checkMacBinary() {
884 $macbin = new MacBinary( $this->mTempPath
);
885 if( $macbin->isValid() ) {
886 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
887 $dataHandle = fopen( $dataFile, 'wb' );
889 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
890 $macbin->extractData( $dataHandle );
892 $this->mTempPath
= $dataFile;
893 $this->mFileSize
= $macbin->dataForkLength();
895 // We'll have to manually remove the new file if it's not kept.
896 $this->mRemoveTempFile
= true;
902 * Check if there's an overwrite conflict and, if so, if restrictions
903 * forbid this user from performing the upload.
905 * @return mixed true on success, error string on failure
907 private function checkOverwrite() {
909 // First check whether the local file can be overwritten
910 $file = $this->getLocalFile();
911 if( $file->exists() ) {
912 if( !self
::userCanReUpload( $wgUser, $file ) ) {
913 return 'fileexists-forbidden';
919 /* Check shared conflicts: if the local file does not exist, but
920 * wfFindFile finds a file, it exists in a shared repository.
922 $file = wfFindFile( $this->getTitle() );
923 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) ) {
924 return 'fileexists-shared-forbidden';
931 * Check if a user is the last uploader
934 * @param string $img, image name
937 public static function userCanReUpload( User
$user, $img ) {
938 if( $user->isAllowed( 'reupload' ) ) {
939 return true; // non-conditional
941 if( !$user->isAllowed( 'reupload-own' ) ) {
944 if( is_string( $img ) ) {
945 $img = wfLocalFile( $img );
947 if ( !( $img instanceof LocalFile
) ) {
951 return $user->getId() == $img->getUser( 'id' );
955 * Helper function that does various existence checks for a file.
956 * The following checks are performed:
958 * - Article with the same name as the file exists
959 * - File exists with normalized extension
960 * - The file looks like a thumbnail and the original exists
962 * @param File $file The file to check
963 * @return mixed False if the file does not exists, else an array
965 public static function getExistsWarning( $file ) {
966 if( $file->exists() ) {
967 return array( 'warning' => 'exists', 'file' => $file );
970 if( $file->getTitle()->getArticleID() ) {
971 return array( 'warning' => 'page-exists', 'file' => $file );
974 if ( $file->wasDeleted() && !$file->exists() ) {
975 return array( 'warning' => 'was-deleted', 'file' => $file );
978 if( strpos( $file->getName(), '.' ) == false ) {
979 $partname = $file->getName();
982 $n = strrpos( $file->getName(), '.' );
983 $extension = substr( $file->getName(), $n +
1 );
984 $partname = substr( $file->getName(), 0, $n );
986 $normalizedExtension = File
::normalizeExtension( $extension );
988 if ( $normalizedExtension != $extension ) {
989 // We're not using the normalized form of the extension.
990 // Normal form is lowercase, using most common of alternate
991 // extensions (eg 'jpg' rather than 'JPEG').
993 // Check for another file using the normalized form...
994 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
995 $file_lc = wfLocalFile( $nt_lc );
997 if( $file_lc->exists() ) {
999 'warning' => 'exists-normalized',
1001 'normalizedFile' => $file_lc
1006 if ( self
::isThumbName( $file->getName() ) ) {
1007 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1008 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1009 $file_thb = wfLocalFile( $nt_thb );
1010 if( $file_thb->exists() ) {
1012 'warning' => 'thumb',
1014 'thumbFile' => $file_thb
1017 // File does not exist, but we just don't like the name
1019 'warning' => 'thumb-name',
1021 'thumbFile' => $file_thb
1027 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1028 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1030 'warning' => 'bad-prefix',
1041 * Helper function that checks whether the filename looks like a thumbnail
1043 public static function isThumbName( $filename ) {
1044 $n = strrpos( $filename, '.' );
1045 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1047 substr( $partname , 3, 3 ) == 'px-' ||
1048 substr( $partname , 2, 3 ) == 'px-'
1050 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1054 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1056 * @return array list of prefixes
1058 public static function getFilenamePrefixBlacklist() {
1059 $blacklist = array();
1060 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1061 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1062 $lines = explode( "\n", $message );
1063 foreach( $lines as $line ) {
1064 // Remove comment lines
1065 $comment = substr( trim( $line ), 0, 1 );
1066 if ( $comment == '#' ||
$comment == '' ) {
1069 // Remove additional comments after a prefix
1070 $comment = strpos( $line, '#' );
1071 if ( $comment > 0 ) {
1072 $line = substr( $line, 0, $comment-1 );
1074 $blacklist[] = trim( $line );
1080 public function getImageInfo( $result ) {
1081 $file = $this->getLocalFile();
1082 $imParam = ApiQueryImageInfo
::getPropertyNames();
1083 return ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );