Jump to content

Manual:Hooks/UploadVerifyFile

From mediawiki.org
UploadVerifyFile
Available from version 1.17.0
Called when a file is uploaded, to allow extra file verification to take place
Define function:
public static function onUploadVerifyFile( $upload, $mime, &$error ) { ... }
Attach hook: In extension.json:
{
	"Hooks": {
		"UploadVerifyFile": "MediaWiki\\Extension\\MyExtension\\Hooks::onUploadVerifyFile"
	}
}
Called from: File(s): UploadBase.php
Function(s): UploadBase::verifyFile()
Interface: UploadVerifyFileHook.php

For more information about attaching hooks, see Manual:Hooks .
For examples of extensions using this hook, see Category:UploadVerifyFile extensions.


Details

[edit]
  • $upload: an instance of UploadBase, with all info about the upload.
  • $mime: the uploaded file's mime type, as detected by MediaWiki. Handlers will typically only apply for specific mime types.
  • &$error: output true if the file is valid. Otherwise, an indexed array representing the problem with the file, where the first element is the message key and the remaining elements are used as parameters to the message.

Example

[edit]

Limit image size and dimensions for regular images, but bypass that size on webm videos. Note that this code doesn't override the wiki's predefined max upload size. Users with the custom uploadlimit-exempt right will bypass the checks done in this hook.

$wgHooks['UploadVerifyUpload'][] = function( UploadBase $upload, User $user, $props, $comment, $pageText, &$error ) {
	$maxWidth = 1024;
	$maxHeight = 1024;
	$maxSizeKB = 600;
	if ( !$props ) {
		$mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
		$props = $mwProps->getPropsFromPath( $upload->getTempPath(), true );
	}
	$title = $upload->getTitle();
	if ( !$props || !$title ) {
		return;
	}
	// UPGRADE: Pre 1.34: Use $user->isAllowed( 'uploadlimit-exempt' )
	if ( $user && MediaWiki\MediaWikiServices::getInstance()->getPermissionManager()->userHasRight( $user, 'uploadlimit-exempt' ) ) {
		# Skip verification for users with uploadlimit-exempt right
		return;
	}
	if ( preg_match( '/.webm$/i', $title->getText() ) ) {
		# Skip verification for webm videos
		return;
	}
	if ( $props['width'] > $maxWidth || $props['height'] > $maxHeight ) {
		wfDebugLog( 'xxx-uploadlimit', sprintf( '[dimensions] triggered by %s. Actual dimensions: %s x %s. %s', $user->getName(), $props['width'], $props['height'], $title->getText() ) );
		$error = new ApiMessage( [ 'custom-uploadlimit-dimensions', "$maxWidth x $maxHeight px" ], 'custom-uploadlimit-dimensions' );
	} elseif ( $props['size'] > $maxSizeKB * 1024 ) {
		wfDebugLog( 'xxx-uploadlimit', sprintf( '[size] triggered by %s. Actual size: %s. %s', $user->getName(), $props['size'], $title->getText() ) );
		$error = new ApiMessage( [ 'custom-uploadlimit-size', "$maxSizeKB KB" ], 'custom-uploadlimit-size' );
	}
};