Merge pull request #4708 from christianbeeznest/UCO-20689-3

Upload: Add size limit to upload files for trainers - refs BT#20689
pull/4712/head
Nicolas Ducoulombier 2 years ago committed by GitHub
commit 8a35a0c156
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      main/document/upload.php
  2. 4
      main/dropbox/dropbox_functions.inc.php
  3. 72
      main/forum/forumfunction.inc.php
  4. 39
      main/inc/lib/fileUpload.lib.php
  5. 3
      main/inc/lib/formvalidator/Element/BigUpload.php
  6. 37
      main/inc/lib/formvalidator/FormValidator.class.php
  7. 2
      main/inc/lib/formvalidator/Rule/MaxFileSize.php
  8. 9
      main/inc/lib/javascript/bigupload/js/bigUpload.js
  9. 10
      main/inc/lib/message.lib.php
  10. 6
      main/inc/lib/pear/HTML/QuickForm/RuleRegistry.php
  11. 3
      main/install/configuration.dist.php
  12. 14
      main/messages/new_message.php
  13. 10
      src/Chamilo/CoreBundle/Component/Editor/Driver/CourseDriver.php

@ -257,7 +257,7 @@ $form->addElement('hidden', 'curdirpath', $path);
$courseQuota = format_file_size(DocumentManager::get_course_quota() - DocumentManager::documents_total_space());
$label =
get_lang('MaxFileSize').': '.ini_get('upload_max_filesize').'<br/>'.
get_lang('MaxFileSize').': '.getIniMaxFileSizeInBytes(true).'<br/>'.
get_lang('DocumentQuota').': '.$courseQuota;
$form->addElement('BigUpload', 'file', [get_lang('File'), $label], ['id' => 'bigUploadFile', 'data-origin' => 'document']);

@ -540,7 +540,7 @@ function display_add_form($viewReceivedCategory, $viewSentCategory, $view, $id =
$form->addElement('hidden', 'sec_token', $token);
$form->addElement('hidden', 'origin', $origin);
if ('add' == $action) {
$maxFileSize = api_get_setting('dropbox_max_filesize');
$maxFileSize = getIniMaxFileSizeInBytes();
$form->addElement('hidden', 'MAX_FILE_SIZE', $maxFileSize);
$form->addElement(
'file',
@ -1070,7 +1070,7 @@ function store_add_dropbox($file = [], $work = null)
$dropbox_filetmpname = $file['tmp_name'];
// check if the filesize does not exceed the allowed size.
$maxFileSize = api_get_setting('dropbox_max_filesize');
$maxFileSize = getIniMaxFileSizeInBytes();
if ($dropbox_filesize <= 0 || $dropbox_filesize > $maxFileSize) {
Display::addFlash(Display::return_message(get_lang('DropboxFileTooBig'), 'warning'));

@ -749,7 +749,9 @@ function store_forum($values, $courseInfo = [], $returnId = false)
// Forum images
$has_attachment = false;
$image_moved = true;
if (!empty($_FILES['picture']['name'])) {
$maxFileSize = getIniMaxFileSizeInBytes();
if (!empty($_FILES['picture']['name']) && !($maxFileSize > 0 && $_FILES['picture']['size'] > $maxFileSize)) {
$upload_ok = process_uploaded_file($_FILES['picture']);
$has_attachment = true;
}
@ -822,7 +824,7 @@ function store_forum($values, $courseInfo = [], $returnId = false)
// Move groups from one group to another
if (isset($values['group_forum'])) {
$forumData = get_forums($values['forum_id']);
$currentGroupId = $forumData['forum_of_group'];
$currentGroupId = $forumData['forum_of_group'] ?? 0;
if ($currentGroupId != $values['group_forum']) {
$threads = get_threads($values['forum_id']);
$toGroupId = 'NULL';
@ -2868,16 +2870,22 @@ function store_thread(
$upload_ok = 1;
$has_attachment = false;
$maxFileSize = getIniMaxFileSizeInBytes();
if (!empty($_FILES['user_upload']['name'])) {
$upload_ok = process_uploaded_file($_FILES['user_upload']);
$has_attachment = true;
$upload_ok = 0;
$has_attachment = false;
if ($maxFileSize > 0 && $_FILES['user_upload']['size'] <= $maxFileSize) {
$upload_ok = process_uploaded_file($_FILES['user_upload']);
$has_attachment = true;
}
}
if (!$upload_ok) {
if ($showMessage) {
$errorUploadMessage = get_lang('FileSizeIsTooBig').' '.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true);
Display::addFlash(
Display::return_message(
get_lang('UplNoFileUploaded'),
$errorUploadMessage,
'error',
false
)
@ -3314,8 +3322,10 @@ function show_add_post_form($current_forum, $action, $form_values = [], $showPre
null,
['id' => 'reply-add-attachment']
);
$form->addRule('user_upload[]', get_lang('FileSizeIsTooBig').' '.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true), 'maxfilesize', getIniMaxFileSizeInBytes());
} else {
$form->addFile('user_upload', get_lang('Attachment'));
$form->addFile('user_upload', get_lang('Attachment').' ('.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true).')');
$form->addRule('user_upload', get_lang('FileSizeIsTooBig').' '.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true), 'maxfilesize', getIniMaxFileSizeInBytes());
}
if ($giveRevision) {
@ -3393,6 +3403,15 @@ function show_add_post_form($current_forum, $action, $form_values = [], $showPre
}
}
if (isset($_REQUEST['action']) && 'replythread' === $_REQUEST['action']) {
if (isset($_REQUEST['post_title'])) {
$defaults['post_title'] = $_REQUEST['post_title'];
}
if (isset($_REQUEST['post_text'])) {
$defaults['post_text'] = $_REQUEST['post_text'];
}
}
$form->setDefaults(isset($defaults) ? $defaults : []);
// The course admin can make a thread sticky (=appears with special icon and always on top).
@ -3435,6 +3454,9 @@ function show_add_post_form($current_forum, $action, $form_values = [], $showPre
$threadId = $myThread->getIid();
Skill::saveSkills($form, ITEM_TYPE_FORUM_THREAD, $threadId);
$postId = $myThread->getThreadLastPost();
} else {
header('Location: '.api_request_uri());
exit;
}
break;
case 'quote':
@ -3849,6 +3871,29 @@ function store_reply($current_forum, $values, $courseId = 0, $userId = 0)
$upload_ok = 1;
$new_post_id = 0;
$errMessage = get_lang('UplNoFileUploaded').' '.get_lang('UplSelectFileFirst');
$maxFileSize = getIniMaxFileSizeInBytes();
if (!empty($_FILES['user_upload']['name'])) {
if (is_array($_FILES['user_upload']['name'])) {
$totalFileSize = 0;
for ($i = 0; $i < count($_FILES['user_upload']['name']); $i++) {
$totalFileSize += $_FILES['user_upload']['size'][$i];
}
if ($totalFileSize > $maxFileSize) {
$upload_ok = 0;
$errMessage = get_lang('FileSizeIsTooBig').' '.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true);
}
} else {
if ($maxFileSize > 0 && $_FILES['user_upload']['size'] <= $maxFileSize) {
$upload_ok = process_uploaded_file($_FILES['user_upload']);
} else {
$upload_ok = 0;
$errMessage = get_lang('FileSizeIsTooBig').' '.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true);
}
}
}
if ($upload_ok) {
// We first store an entry in the forum_post table.
$new_post_id = Database::insert(
@ -3954,10 +3999,12 @@ function store_reply($current_forum, $values, $courseId = 0, $userId = 0)
} else {
Display::addFlash(
Display::return_message(
get_lang('UplNoFileUploaded').' '.get_lang('UplSelectFileFirst'),
$errMessage,
'error'
)
);
return false;
}
return $new_post_id;
@ -5251,11 +5298,16 @@ function add_forum_attachment_file($file_comment, $last_id)
}
}
$maxFileSize = getIniMaxFileSizeInBytes();
foreach ($filesData as $attachment) {
if (empty($attachment['name'])) {
continue;
}
if ($maxFileSize > 0 && $attachment['size'] > $maxFileSize) {
continue;
}
$upload_ok = process_uploaded_file($attachment);
if (!$upload_ok) {
@ -5347,13 +5399,17 @@ function edit_forum_attachment_file($file_comment, $post_id, $id_attach)
}
}
$maxFileSize = getIniMaxFileSizeInBytes();
foreach ($filesData as $attachment) {
if (empty($attachment['name'])) {
continue;
}
$upload_ok = process_uploaded_file($attachment);
if ($maxFileSize > 0 && $attachment['size'] > $maxFileSize) {
continue;
}
$upload_ok = process_uploaded_file($attachment);
if (!$upload_ok) {
continue;
}

@ -2183,10 +2183,29 @@ function add_all_documents_in_folder_to_database(
*
* @return int
*/
function getIniMaxFileSizeInBytes()
function getIniMaxFileSizeInBytes($humanReadable = false, $checkMessageSetting = false)
{
$maxSize = 0;
if (preg_match('/^([0-9]+)([a-zA-Z]*)$/', ini_get('upload_max_filesize'), $matches)) {
$uploadMaxFilesize = ini_get('upload_max_filesize');
$fileSizeForTeacher = getFileUploadSizeLimitForTeacher();
if (!empty($fileSizeForTeacher)) {
$uploadMaxFilesize = $fileSizeForTeacher.'M';
}
if (empty($fileSizeForTeacher) && $checkMessageSetting) {
$uploadMaxFilesize = api_get_setting('message_max_upload_filesize'); // in bytes
if ($humanReadable) {
$uploadMaxFilesize = format_file_size($uploadMaxFilesize);
}
return $uploadMaxFilesize;
}
if ($humanReadable) {
return $uploadMaxFilesize;
}
if (preg_match('/^([0-9]+)([a-zA-Z]*)$/', $uploadMaxFilesize, $matches)) {
// see http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
switch (strtoupper($matches['2'])) {
case 'G':
@ -2206,3 +2225,19 @@ function getIniMaxFileSizeInBytes()
return $maxSize;
}
/**
* Get the uploax max filesize from configuration.php for trainers in bytes.
*
* @return int
*/
function getFileUploadSizeLimitForTeacher()
{
$size = 0;
$settingValue = (int) api_get_configuration_value('file_upload_size_limit_for_teacher'); // setting value in MB
if ($settingValue > 0 && (api_is_allowed_to_create_course() && !api_is_platform_admin())) {
$size = $settingValue;
}
return $size;
}

@ -26,6 +26,7 @@ class BigUpload extends HTML_QuickForm_file
$origin = $this->getAttribute('data-origin');
$id = $this->getAttribute('id');
$maxSize = getIniMaxFileSizeInBytes();
$errorUploadMessage = get_lang('FileSizeIsTooBig').' '.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true);
$html = parent::toHtml();
$html .= '<div id="'.$id.'-bigUploadProgressBarContainer">
<div id="'.$id.'-bigUploadProgressBarFilled"></div>
@ -75,6 +76,8 @@ class BigUpload extends HTML_QuickForm_file
bigUpload.settings.formParams = uploadForm.serialize();
//Max file size allowed
bigUpload.settings.maxFileSize = "'.$maxSize.'";
// Message error upload filesize
bigUpload.settings.errMessageFileSize = "'.$errorUploadMessage.'";
}
</script>';

@ -1820,7 +1820,9 @@ EOT;
if (!empty($urlToRedirect)) {
$redirectCondition = "window.location.replace('$urlToRedirect'); ";
}
$maxFileSize = getIniMaxFileSizeInBytes();
$icon = Display::return_icon('file_txt.gif');
$errorUploadMessage = get_lang('FileSizeIsTooBig').' '.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true);
$this->addHtml("
<script>
$(function () {
@ -1853,6 +1855,7 @@ EOT;
});
});
var maxFileSize = parseInt('".$maxFileSize."');
var counter = 0,
total = 0;
$('#".$inputName."').fileupload({
@ -1885,19 +1888,39 @@ EOT;
}).on('fileuploadadd', function (e, data) {
data.context = $('<div class=\"row\" />').appendTo('#files');
var errs = [];
$.each(data.files, function (index, file) {
var node = $('<div class=\"col-sm-5 file_name\">').text(file.name);
node.appendTo(data.context);
var iconLoading = $('<div class=\"col-sm-3\">').html(
$('<span id=\"image-loading'+index+'\"/>').html('".Display::return_icon('loading1.gif', get_lang('Uploading'), [], ICON_SIZE_MEDIUM)."')
);
$(data.context.children()[index]).parent().append(iconLoading);
total++;
// check size
if (maxFileSize > 0 && data.files[index]['size'] > maxFileSize) {
errs.push('".$errorUploadMessage."');
} else {
// array for all errors
var node = $('<div class=\"col-sm-5 file_name\">').text(file.name);
node.appendTo(data.context);
var iconLoading = $('<div class=\"col-sm-3\">').html(
$('<span id=\"image-loading'+index+'\"/>').html('".Display::return_icon('loading1.gif', get_lang('Uploading'), [], ICON_SIZE_MEDIUM)."')
);
$(data.context.children()[index]).parent().append(iconLoading);
total++;
}
});
// Output errors or submit data
if (errs.length > 0) {
alert('".get_lang('AnErrorOccured')."' + errs.join(' '));
return false;
} else {
data.submit();
}
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (maxFileSize > 0 && data.files[index]['size'] > maxFileSize) {
return false;
}
if (file.preview) {
data.context.prepend($('<div class=\"col-sm-4\">').html(file.preview));
} else {

@ -14,7 +14,7 @@ class HTML_QuickForm_Rule_MaxFileSize extends HTML_QuickForm_Rule
*
* @return bool
*/
public function validate($elementValue, $maxSize)
public function validate($elementValue, $maxSize = 0)
{
if (!empty($elementValue['error']) &&
(UPLOAD_ERR_FORM_SIZE == $elementValue['error'] || UPLOAD_ERR_INI_SIZE == $elementValue['error'])

@ -49,7 +49,11 @@ function bigUpload () {
'maxFileSize': 2147483648,
//CidReq
'cidReq': ''
'cidReq': '',
// Message error upload filesize
'errMessageFileSize': '',
};
//Upload specific variables
@ -133,7 +137,8 @@ function bigUpload () {
//But this should be good enough to catch any immediate errors
var fileSize = this.uploadData.file.size;
if(fileSize > this.settings.maxFileSize) {
this.printResponse('The file you have chosen is too large.', true);
this.printResponse(this.settings.errMessageFileSize, true);
this.$(this.settings.submitButton).disabled = false;
return;
}

@ -666,13 +666,9 @@ class MessageManager
);
return false;
} elseif ($totalFileSize > (int) api_get_setting('message_max_upload_filesize')) {
$warning = sprintf(
get_lang('FilesSizeExceedsX'),
format_file_size(api_get_setting('message_max_upload_filesize'))
);
Display::addFlash(Display::return_message($warning, 'warning'));
} elseif ($totalFileSize > (int) getIniMaxFileSizeInBytes(false, true)) {
$warning = get_lang('FileSizeIsTooBig').' '.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true, true);
Display::addFlash(Display::return_message($warning, 'error'));
return false;
}

@ -148,9 +148,9 @@ class HTML_QuickForm_RuleRegistry
'date' => 'HTML_QuickForm_Rule_Date',
'compare_datetime_text' => 'HTML_QuickForm_Rule_CompareDateTimeText',
'uploadedfile' => 'HTML_QuickForm_Rule_UploadFile',
'maxfilesize', 'HTML_QuickForm_Rule_MaxFileSize',
'mimetype', 'HTML_QuickForm_Rule_MimeType',
'filename', 'HTML_QuickForm_Rule_FileName',
'maxfilesize'=> 'HTML_QuickForm_Rule_MaxFileSize',
'mimetype' => 'HTML_QuickForm_Rule_MimeType',
'filename' => 'HTML_QuickForm_Rule_FileName',
'validquestiontype' => 'HTML_QuickForm_Rule_QuestionType',
'mintext' => 'Html_Quickform_Rule_MinText'
);

@ -2451,6 +2451,9 @@ INSERT INTO extra_field_options (field_id, option_value, display_text, priority,
// Display the Portal News link in the admin page to session admin users
//$_configuration['session_admin_access_system_announcement'] = false;
// File upload size limit in MB for teachers (set to 1024 for 1GB, 5120 for 5GB, etc).
//$_configuration['file_upload_size_limit_for_teacher'] = 0;
// KEEP THIS AT THE END
// -------- Custom DB changes
// Add user activation by confirmation email

@ -119,6 +119,10 @@ function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl
$onlyTeachers = true;
}
if (isset($_SESSION['form_values'])) {
$default = $_SESSION['form_values'];
}
$form = new FormValidator(
'compose_message',
null,
@ -272,7 +276,7 @@ function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl
get_lang('AddOneMoreFile').'</a></span>&nbsp;('.
sprintf(
get_lang('MaximunFileSizeX'),
format_file_size(api_get_setting('message_max_upload_filesize'))
getIniMaxFileSizeInBytes(true, true)
).')'
);
}
@ -301,6 +305,10 @@ function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl
}
if ($check) {
if (isset($_SESSION['form_values'])) {
unset($_SESSION['form_values']);
}
$user_list = $default['users'];
$file_comments = $_POST['legend'];
$title = $default['title'];
@ -349,6 +357,10 @@ function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl
'confirmation',
false
));
} else {
$_SESSION['form_values'] = $default;
header('Location: '.api_request_uri());
exit;
}
}
MessageManager::cleanAudioMessage();

@ -267,6 +267,16 @@ class CourseDriver extends Driver implements DriverInterface
if ($this->allowToEdit()) {
// upload file by elfinder.
$size = filesize($tmpname);
// check the max filesize.
$maxFileSize = getIniMaxFileSizeInBytes();
if ($maxFileSize > 0 && $size > $maxFileSize) {
$errorUploadMessage = get_lang('FileSizeIsTooBig').' '.get_lang('MaxFileSize').' : '.getIniMaxFileSizeInBytes(true);
$this->addError($errorUploadMessage);
return false;
}
$maxSpace = \DocumentManager::get_course_quota($this->connector->course['code']);
// Check if there is enough space to save the file.
if (!\DocumentManager::enough_space($size, $maxSpace)) {

Loading…
Cancel
Save