How to Limit the Number of File Uploads and Apply Disk Quota Limits
Sometimes you'll need to apply some more control over what your users are doing.
If you're providing access to a WordPress site there will be users who will over consume resources.
Actually, this is exactly what happened with some of the users that were using qSandbox.
Several users were using 10x the allowed amount. It is not their fault.
The system that should've stopped them earlier.
The code below can be added into a (mu)plugin or functions.php.
The code works on Linux/Unix primarily. If you want to get it working on Windows you'll need to download UnxUtils from http://sourceforge.net/projects/unxutils/
[code]
add_filter( 'wp_handle_upload_prefilter', 'orbisius_sandbox_limit_admin_uploads' );
/**
* Limits file uploads for the free plan to 25
* Limits disk usage to 100MB
* @see http://wordpress.stackexchange.com/questions/47580/give-users-a-maximum-upload-capacity-limit-the-number-of-files-a-user-can-uploa
*/
function orbisius_sandbox_limit_admin_uploads($file) {
try {
$count = 0;
$counts_obj = wp_count_attachments();
$counts_array = (array) $counts_obj;
foreach ($counts_array as $mime_type => $cnt) {
$count += $cnt;
}
if ($count >= 100) {
throw new Exception("Max file number reached.");
}
$site_dir = ABSPATH;
$site_dir = rtrim($site_dir, "/\\");
$site_dir_esc = escapeshellarg($site_dir);
// -s is for summary
// -b is to show sizes in bytes
$usage = `du -bs $site_dir_esc 2>&1`; // must not have a trailing slash!
$disk_usage = preg_replace('#(\d+[a-z]?).*#si', '$1', $usage); // leave just the numbers.
$disk_usage_limit = 100 * 1024 * 1024; // 100MB
if ($disk_usage >= $disk_usage_limit) {
$disk_usage_hr = orbisius_sandbox_limit_admin_uploads_format_file_size($disk_usage);
throw new Exception("Disk space limit reached. Current usage: $disk_usage_hr");
}
} catch (Exception $e) {
$file['error'] = $e->getMessage();
}
return $file;
}
/**
* proto str orbisius_sandbox_limit_admin_uploads_format_file_size( int $size )
*
* @param string
* @return string 1 KB/ MB
*/
function orbisius_sandbox_limit_admin_uploads_format_file_size($size) {
$size_suff = 'Bytes';
if ($size > 1024 ) {
$size /= 1024;
$size_suff = 'KB';
}
if ( $size > 1024 ) {
$size /= 1024;
$size_suff = 'MB';
}
if ( $size > 1024 ) {
$size /= 1024;
$size_suff = 'GB';
}
if ( $size > 1024 ) {
$size /= 1024;
$size_suff = 'TB';
}
$size = number_format( $size, 2);
$size = preg_replace('#\.00$#', '', $size);
return $size . " $size_suff";
}
[/code]
Of course there is many ways to achive this Quota limitations for by setting the linux quota for that user.