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 )
46 # Check php's file_uploads setting
47 if( !wfIniGetBool( 'file_uploads' ) ) {
54 * Returns true if the user can use this upload module or else a string
55 * identifying the missing permission.
56 * Can be overriden by subclasses.
58 public static function isAllowed( $user ) {
59 if( !$user->isAllowed( 'upload' ) )
64 // Upload handlers. Should probably just be a global.
65 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
68 * Create a form of UploadBase depending on wpSourceType and initializes it
70 public static function createFromRequest( &$request, $type = null ) {
71 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
76 // Get the upload class
77 $type = ucfirst( $type );
79 // Give hooks the chance to handle this request
81 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
82 if ( is_null( $className ) ) {
83 $className = 'UploadFrom' . $type;
84 wfDebug( __METHOD__
. ": class name: $className\n" );
85 if( !in_array( $type, self
::$uploadHandlers ) )
89 // Check whether this upload class is enabled
90 if( !call_user_func( array( $className, 'isEnabled' ) ) )
93 // Check whether the request is valid
94 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) )
97 $handler = new $className;
99 $handler->initializeFromRequest( $request );
104 * Check whether a request if valid for this handler
106 public static function isValidRequest( $request ) {
110 public function __construct() {}
113 * Initialize the path information
114 * @param $name string the desired destination name
115 * @param $tempPath string the temporary path
116 * @param $fileSize int the file size
117 * @param $removeTempFile bool (false) remove the temporary file?
120 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
121 $this->mDesiredDestName
= $name;
122 $this->mTempPath
= $tempPath;
123 $this->mFileSize
= $fileSize;
124 $this->mRemoveTempFile
= $removeTempFile;
128 * Initialize from a WebRequest. Override this in a subclass.
130 public abstract function initializeFromRequest( &$request );
133 * Fetch the file. Usually a no-op
135 public function fetchFile() {
136 return Status
::newGood();
140 * Return the file size
142 public function isEmptyFile(){
143 return empty( $this->mFileSize
);
148 * @param string $srcPath the source path
149 * @returns the real path if it was a virtual url
151 function getRealPath( $srcPath ){
152 $repo = RepoGroup
::singleton()->getLocalRepo();
153 if ( $repo->isVirtualUrl( $srcPath ) ) {
154 return $repo->resolveVirtualUrl( $srcPath );
160 * Verify whether the upload is sane.
161 * Returns self::OK or else an array with error information
163 public function verifyUpload() {
165 * If there was no filename or a zero size given, give up quick.
167 if( $this->isEmptyFile() )
168 return array( 'status' => self
::EMPTY_FILE
);
171 * Look at the contents of the file; if we can recognize the
172 * type but it's corrupt or data of the wrong type, we should
173 * probably not accept it.
175 $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 );
184 $nt = $this->getTitle();
185 if( is_null( $nt ) ) {
186 $result = array( 'status' => $this->mTitleError
);
187 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
)
188 $result['filtered'] = $this->mFilteredName
;
189 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
)
190 $result['finalExt'] = $this->mFinalExtension
;
193 $this->mDestName
= $this->getLocalFile()->getName();
196 * In some cases we may forbid overwriting of existing files.
198 $overwrite = $this->checkOverwrite();
199 if( $overwrite !== true )
200 return array( 'status' => self
::OVERWRITE_EXISTING_FILE
, 'overwrite' => $overwrite );
203 if( !wfRunHooks( 'UploadVerification',
204 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
205 // This status needs another name...
206 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
209 return array( 'status' => self
::OK
);
213 * Verifies that it's ok to include the uploaded file
215 * FIXME: this function seems to intermixes tmpfile and $this->mTempPath .. no idea why this is
217 * @param string $tmpfile the full path of the temporary file to verify
218 * @return mixed true of the file is verified, a string or array otherwise.
220 protected function verifyFile() {
221 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
222 $this->checkMacBinary();
224 #magically determine mime type
225 $magic = MimeMagic
::singleton();
226 $mime = $magic->guessMimeType( $this->mTempPath
, false );
228 #check mime type, if desired
229 global $wgVerifyMimeType;
230 if ( $wgVerifyMimeType ) {
231 global $wgMimeTypeBlacklist;
232 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) )
233 return array( 'filetype-badmime', $mime );
236 $fp = fopen( $this->mTempPath
, 'rb' );
237 $chunk = fread( $fp, 256 );
239 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
240 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
241 foreach ( $ieTypes as $ieType ) {
242 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
243 return array( 'filetype-bad-ie-mime', $ieType );
248 #check for htmlish code and javascript
249 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
250 return 'uploadscripted';
252 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
253 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
254 return 'uploadscripted';
259 * Scan the uploaded file for viruses
261 $virus = $this->detectVirus( $this->mTempPath
);
263 return array( 'uploadvirus', $virus );
265 wfDebug( __METHOD__
. ": all clear; passing.\n" );
270 * Check whether the user can edit, upload and create the image.
272 * @param User $user the user to verify the permissions against
273 * @return mixed An array as returned by getUserPermissionsErrors or true
274 * in case the user has proper permissions.
276 public function verifyPermissions( $user ) {
278 * If the image is protected, non-sysop users won't be able
279 * to modify it by uploading a new revision.
281 $nt = $this->getTitle();
284 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
285 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
286 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
287 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
288 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
289 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
296 * Check for non fatal problems with the file
298 * @return array Array of warnings
300 public function checkWarnings() {
303 $localFile = $this->getLocalFile();
304 $filename = $localFile->getName();
305 $n = strrpos( $filename, '.' );
306 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
309 * Check whether the resulting filename is different from the desired one,
310 * but ignore things like ucfirst() and spaces/underscore things
312 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
313 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
315 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename )
316 $warnings['badfilename'] = $filename;
318 // Check whether the file extension is on the unwanted list
319 global $wgCheckFileExtensions, $wgFileExtensions;
320 if ( $wgCheckFileExtensions ) {
321 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
322 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
325 global $wgUploadSizeWarning;
326 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) )
327 $warnings['large-file'] = $wgUploadSizeWarning;
329 if ( $this->mFileSize
== 0 )
330 $warnings['emptyfile'] = true;
333 $exists = self
::getExistsWarning( $localFile );
334 if( $exists !== false )
335 $warnings['exists'] = $exists;
337 // Check dupes against existing files
338 $hash = File
::sha1Base36( $this->mTempPath
);
339 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
340 $title = $this->getTitle();
341 // Remove all matches against self
342 foreach ( $dupes as $key => $dupe ) {
343 if( $title->equals( $dupe->getTitle() ) )
344 unset( $dupes[$key] );
347 $warnings['duplicate'] = $dupes;
349 // Check dupes against archives
350 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
351 if ( $archivedImage->getID() > 0 )
352 $warnings['duplicate-archive'] = $archivedImage->getName();
358 * Really perform the upload. Stores the file in the local repo, watches
359 * if necessary and runs the UploadComplete hook.
361 * @return mixed Status indicating the whether the upload succeeded.
363 public function performUpload( $comment, $pageText, $watch, $user ) {
364 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
365 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
366 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
368 if( $status->isGood() && $watch )
369 $user->addWatch( $this->getLocalFile()->getTitle() );
371 if( $status->isGood() )
372 wfRunHooks( 'UploadComplete', array( &$this ) );
378 * Returns the title of the file to be uploaded. Sets mTitleError in case
379 * the name was illegal.
381 * @return Title The title of the file or null in case the name was illegal
383 public function getTitle() {
384 if ( $this->mTitle
!== false )
385 return $this->mTitle
;
388 * Chop off any directories in the given filename. Then
389 * filter out illegal characters, and try to make a legible name
390 * out of it. We'll strip some silently that Title would die on.
392 $basename = $this->mDesiredDestName
;
394 $this->mFilteredName
= wfStripIllegalFilenameChars( $basename );
395 /* Normalize to title form before we do any further processing */
396 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
397 if( is_null( $nt ) ) {
398 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
399 return $this->mTitle
= null;
401 $this->mFilteredName
= $nt->getDBkey();
404 * We'll want to blacklist against *any* 'extension', and use
405 * only the final one for the whitelist.
407 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
409 if( count( $ext ) ) {
410 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
412 $this->mFinalExtension
= '';
415 /* Don't allow users to override the blacklist (check file extension) */
416 global $wgCheckFileExtensions, $wgStrictFileExtensions;
417 global $wgFileExtensions, $wgFileBlacklist;
418 if ( $this->mFinalExtension
== '' ) {
419 $this->mTitleError
= self
::FILETYPE_MISSING
;
420 return $this->mTitle
= null;
421 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
422 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
423 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
424 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
425 return $this->mTitle
= null;
428 # If there was more than one "extension", reassemble the base
429 # filename to prevent bogus complaints about length
430 if( count( $ext ) > 1 ) {
431 for( $i = 0; $i < count( $ext ) - 1; $i++
)
432 $partname .= '.' . $ext[$i];
435 if( strlen( $partname ) < 1 ) {
436 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
437 return $this->mTitle
= null;
440 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
441 if( is_null( $nt ) ) {
442 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
443 return $this->mTitle
= null;
445 return $this->mTitle
= $nt;
449 * Return the local file and initializes if necessary.
451 public function getLocalFile() {
452 if( is_null( $this->mLocalFile
) ) {
453 $nt = $this->getTitle();
454 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
456 return $this->mLocalFile
;
460 * Stash a file in a temporary directory for later processing
461 * after the user has confirmed it.
463 * If the user doesn't explicitly cancel or accept, these files
464 * can accumulate in the temp directory.
466 * @param string $saveName - the destination filename
467 * @param string $tempSrc - the source temporary file to save
468 * @return string - full path the stashed file, or false on failure
471 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
472 $repo = RepoGroup
::singleton()->getLocalRepo();
473 $status = $repo->storeTemp( $saveName, $tempSrc );
478 * Stash a file in a temporary directory for later processing,
479 * and save the necessary descriptive info into the session.
480 * Returns a key value which will be passed through a form
481 * to pick up the path info on a later invocation.
483 * @return int Session key
485 public function stashSession() {
486 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
487 if( !$status->isOK() ) {
488 # Couldn't save the file.
491 if(!isset($_SESSION))
492 session_start(); // start up the session (might have been previously closed to prevent php session locking)
493 $key = $this->getSessionKey();
494 $_SESSION['wsUploadData'][$key] = array(
495 'mTempPath' => $status->value
,
496 'mFileSize' => $this->mFileSize
,
497 'mFileProps' => $this->mFileProps
,
498 'version' => self
::SESSION_VERSION
,
504 * Generate a random session key from stash in cases where we want to start an upload without much information
506 protected function getSessionKey(){
507 $key = mt_rand( 0, 0x7fffffff );
508 $_SESSION['wsUploadData'][$key] = array();
514 * If we've modified the upload file we need to manually remove it
515 * on exit to clean up.
518 public function cleanupTempFile() {
519 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
520 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
521 unlink( $this->mTempPath
);
525 public function getTempPath() {
526 return $this->mTempPath
;
530 * Split a file into a base name and all dot-delimited 'extensions'
531 * on the end. Some web server configurations will fall back to
532 * earlier pseudo-'extensions' to determine type and execute
533 * scripts, so the blacklist needs to check them all.
537 public static function splitExtensions( $filename ) {
538 $bits = explode( '.', $filename );
539 $basename = array_shift( $bits );
540 return array( $basename, $bits );
544 * Perform case-insensitive match against a list of file extensions.
545 * Returns true if the extension is in the list.
551 public static function checkFileExtension( $ext, $list ) {
552 return in_array( strtolower( $ext ), $list );
556 * Perform case-insensitive match against a list of file extensions.
557 * Returns true if any of the extensions are in the list.
563 public static function checkFileExtensionList( $ext, $list ) {
564 foreach( $ext as $e ) {
565 if( in_array( strtolower( $e ), $list ) ) {
573 * Checks if the mime type of the uploaded file matches the file extension.
575 * @param string $mime the mime type of the uploaded file
576 * @param string $extension The filename extension that the file is to be served with
579 public static function verifyExtension( $mime, $extension ) {
580 $magic = MimeMagic
::singleton();
582 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
583 if ( !$magic->isRecognizableExtension( $extension ) ) {
584 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
585 "unrecognized extension '$extension', can't verify\n" );
588 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
589 "recognized extension '$extension', so probably invalid file\n" );
593 $match = $magic->isMatchingExtension( $extension, $mime );
595 if ( $match === null ) {
596 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
598 } elseif( $match === true ) {
599 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
601 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
605 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
611 * Heuristic for detecting files that *could* contain JavaScript instructions or
612 * things that may look like HTML to a browser and are thus
613 * potentially harmful. The present implementation will produce false positives in some situations.
615 * @param string $file Pathname to the temporary upload file
616 * @param string $mime The mime type of the file
617 * @param string $extension The extension of the file
618 * @return bool true if the file contains something looking like embedded scripts
620 public static function detectScript( $file, $mime, $extension ) {
621 global $wgAllowTitlesInSVG;
623 #ugly hack: for text files, always look at the entire file.
624 #For binary field, just check the first K.
626 if( strpos( $mime,'text/' ) === 0 )
627 $chunk = file_get_contents( $file );
629 $fp = fopen( $file, 'rb' );
630 $chunk = fread( $fp, 1024 );
634 $chunk = strtolower( $chunk );
639 #decode from UTF-16 if needed (could be used for obfuscation).
640 if( substr( $chunk, 0, 2 ) == "\xfe\xff" )
642 elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" )
648 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
650 $chunk = trim( $chunk );
652 #FIXME: convert from UTF-16 if necessarry!
653 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
655 #check for HTML doctype
656 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) )
660 * Internet Explorer for Windows performs some really stupid file type
661 * autodetection which can cause it to interpret valid image files as HTML
662 * and potentially execute JavaScript, creating a cross-site scripting
665 * Apple's Safari browser also performs some unsafe file type autodetection
666 * which can cause legitimate files to be interpreted as HTML if the
667 * web server is not correctly configured to send the right content-type
668 * (or if you're really uploading plain text and octet streams!)
670 * Returns true if IE is likely to mistake the given file for HTML.
671 * Also returns true if Safari would mistake the given file for HTML
672 * when served with a generic content-type.
678 '<html', #also in safari
681 '<script', #also in safari
685 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
689 foreach( $tags as $tag ) {
690 if( false !== strpos( $chunk, $tag ) ) {
696 * look for JavaScript
699 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
700 $chunk = Sanitizer
::decodeCharReferences( $chunk );
702 #look for script-types
703 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) )
706 #look for html-style script-urls
707 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
710 #look for css-style script-urls
711 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) )
714 wfDebug( __METHOD__
. ": no scripts found\n" );
718 protected function detectScriptInSvg( $filename ) {
719 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
720 return $check->filterMatch
;
724 * @todo Replace this with a whitelist filter!
726 public function checkSvgScriptCallback( $element, $attribs ) {
727 $stripped = $this->stripXmlNamespace( $element );
729 if( $stripped == 'script' ) {
730 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
734 foreach( $attribs as $attrib => $value ) {
735 $stripped = $this->stripXmlNamespace( $attrib );
736 if( substr( $stripped, 0, 2 ) == 'on' ) {
737 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
740 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
741 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
747 private function stripXmlNamespace( $name ) {
748 // 'http://www.w3.org/2000/svg:script' -> 'script'
749 $parts = explode( ':', strtolower( $name ) );
750 return array_pop( $parts );
754 * Generic wrapper function for a virus scanner program.
755 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
756 * $wgAntivirusRequired may be used to deny upload if the scan fails.
758 * @param string $file Pathname to the temporary upload file
759 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
760 * or a string containing feedback from the virus scanner if a virus was found.
761 * If textual feedback is missing but a virus was found, this function returns true.
763 public static function detectVirus( $file ) {
764 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
766 if ( !$wgAntivirus ) {
767 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
771 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
772 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
773 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>", array( 'virus-badscanner', $wgAntivirus ) );
774 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
777 # look up scanner configuration
778 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
779 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
780 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
781 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
783 if ( strpos( $command,"%f" ) === false ) {
784 # simple pattern: append file to scan
785 $command .= " " . wfEscapeShellArg( $file );
787 # complex pattern: replace "%f" with file to scan
788 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
791 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
793 # execute virus scanner
796 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
797 # that does not seem to be worth the pain.
798 # Ask me (Duesentrieb) about it if it's ever needed.
799 $output = wfShellExec( "$command 2>&1", $exitCode );
801 # map exit code to AV_xxx constants.
802 $mappedCode = $exitCode;
803 if ( $exitCodeMap ) {
804 if ( isset( $exitCodeMap[$exitCode] ) ) {
805 $mappedCode = $exitCodeMap[$exitCode];
806 } elseif ( isset( $exitCodeMap["*"] ) ) {
807 $mappedCode = $exitCodeMap["*"];
811 if ( $mappedCode === AV_SCAN_FAILED
) {
812 # scan failed (code was mapped to false by $exitCodeMap)
813 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
815 if ( $wgAntivirusRequired ) {
816 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
820 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
821 # scan failed because filetype is unknown (probably imune)
822 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
824 } else if ( $mappedCode === AV_NO_VIRUS
) {
826 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
829 $output = trim( $output );
832 $output = true; #if there's no output, return true
833 } elseif ( $msgPattern ) {
835 if ( preg_match( $msgPattern, $output, $groups ) ) {
837 $output = $groups[1];
842 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
848 * Check if the temporary file is MacBinary-encoded, as some uploads
849 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
850 * If so, the data fork will be extracted to a second temporary file,
851 * which will then be checked for validity and either kept or discarded.
855 private function checkMacBinary() {
856 $macbin = new MacBinary( $this->mTempPath
);
857 if( $macbin->isValid() ) {
858 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
859 $dataHandle = fopen( $dataFile, 'wb' );
861 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
862 $macbin->extractData( $dataHandle );
864 $this->mTempPath
= $dataFile;
865 $this->mFileSize
= $macbin->dataForkLength();
867 // We'll have to manually remove the new file if it's not kept.
868 $this->mRemoveTempFile
= true;
874 * Check if there's an overwrite conflict and, if so, if restrictions
875 * forbid this user from performing the upload.
877 * @return mixed true on success, error string on failure
880 private function checkOverwrite() {
882 // First check whether the local file can be overwritten
883 $file = $this->getLocalFile();
884 if( $file->exists() ) {
885 if( !self
::userCanReUpload( $wgUser, $file ) )
886 return 'fileexists-forbidden';
891 /* Check shared conflicts: if the local file does not exist, but
892 * wfFindFile finds a file, it exists in a shared repository.
894 $file = wfFindFile( $this->getTitle() );
895 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) )
896 return 'fileexists-shared-forbidden';
902 * Check if a user is the last uploader
905 * @param string $img, image name
908 public static function userCanReUpload( User
$user, $img ) {
909 if( $user->isAllowed( 'reupload' ) )
910 return true; // non-conditional
911 if( !$user->isAllowed( 'reupload-own' ) )
913 if( is_string( $img ) )
914 $img = wfLocalFile( $img );
915 if ( !( $img instanceof LocalFile
) )
918 return $user->getId() == $img->getUser( 'id' );
922 * Helper function that does various existence checks for a file.
923 * The following checks are performed:
925 * - Article with the same name as the file exists
926 * - File exists with normalized extension
927 * - The file looks like a thumbnail and the original exists
929 * @param File $file The file to check
930 * @return mixed False if the file does not exists, else an array
932 public static function getExistsWarning( $file ) {
933 if( $file->exists() )
934 return array( 'warning' => 'exists', 'file' => $file );
936 if( $file->getTitle()->getArticleID() )
937 return array( 'warning' => 'page-exists', 'file' => $file );
939 if ( $file->wasDeleted() && !$file->exists() )
940 return array( 'warning' => 'was-deleted', 'file' => $file );
942 if( strpos( $file->getName(), '.' ) == false ) {
943 $partname = $file->getName();
946 $n = strrpos( $file->getName(), '.' );
947 $extension = substr( $file->getName(), $n +
1 );
948 $partname = substr( $file->getName(), 0, $n );
950 $normalizedExtension = File
::normalizeExtension( $extension );
952 if ( $normalizedExtension != $extension ) {
953 // We're not using the normalized form of the extension.
954 // Normal form is lowercase, using most common of alternate
955 // extensions (eg 'jpg' rather than 'JPEG').
957 // Check for another file using the normalized form...
958 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
959 $file_lc = wfLocalFile( $nt_lc );
961 if( $file_lc->exists() )
962 return array( 'warning' => 'exists-normalized', 'file' => $file, 'normalizedFile' => $file_lc );
965 if ( self
::isThumbName( $file->getName() ) ) {
966 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
967 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
968 $file_thb = wfLocalFile( $nt_thb );
969 if( $file_thb->exists() )
970 return array( 'warning' => 'thumb', 'file' => $file, 'thumbFile' => $file_thb );
972 // File does not exist, but we just don't like the name
973 return array( 'warning' => 'thumb-name', 'file' => $file, 'thumbFile' => $file_thb );
977 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
978 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix )
979 return array( 'warning' => 'bad-prefix', 'file' => $file, 'prefix' => $prefix );
988 * Helper function that checks whether the filename looks like a thumbnail
990 public static function isThumbName( $filename ) {
991 $n = strrpos( $filename, '.' );
992 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
994 substr( $partname , 3, 3 ) == 'px-' ||
995 substr( $partname , 2, 3 ) == 'px-'
997 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1001 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
1003 * @return array list of prefixes
1005 public static function getFilenamePrefixBlacklist() {
1006 $blacklist = array();
1007 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1008 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1009 $lines = explode( "\n", $message );
1010 foreach( $lines as $line ) {
1011 // Remove comment lines
1012 $comment = substr( trim( $line ), 0, 1 );
1013 if ( $comment == '#' ||
$comment == '' ) {
1016 // Remove additional comments after a prefix
1017 $comment = strpos( $line, '#' );
1018 if ( $comment > 0 ) {
1019 $line = substr( $line, 0, $comment-1 );
1021 $blacklist[] = trim( $line );
1027 public function getImageInfo($result) {
1028 $file = $this->getLocalFile();
1029 $imParam = ApiQueryImageInfo
::getPropertyNames();
1030 return ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );