Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions web/modules/custom/server_general/server_general.module
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* Module file.
*/

use Drupal\Component\Utility\Bytes;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\ContentEntityFormInterface;
use Drupal\Core\Entity\EntityInterface;
Expand Down Expand Up @@ -373,4 +374,72 @@ function server_general_page_attachments(array &$attachments) {
];
$attachments['#attached']['html_head'][] = [$noindex_tag, 'noindex_error_pages'];
}

// Attach file size validation settings for client-side validation of file
// uploads. The library itself is loaded via hook_library_info_alter() as a
// dependency of core's drupal.file, ensuring our change handler fires before
// core's auto-upload handler.
$attachments['#attached']['drupalSettings']['fileSizeValidation'] = [
'maxFileSize' => server_general_get_max_upload_size(),
];
}

/**
* Implements hook_element_info_alter().
*/
function server_general_element_info_alter(array &$info): void {
// Add a process callback to managed_file elements to pass the per-field
// file size limit to the client as a data attribute.
if (isset($info['managed_file'])) {
$info['managed_file']['#process'][] = 'server_general_managed_file_process';
}
}

/**
* Process callback for managed_file elements.
*
* Adds a data-max-filesize attribute to the upload input so client-side
* validation can use the per-field limit (which is already the min of the
* PHP limit and the configured field limit).
*/
function server_general_managed_file_process(array &$element, FormStateInterface &$form_state, array &$form): array {
// D10.2+ uses 'FileSizeLimit', earlier versions use 'file_validate_size'.
if (isset($element['#upload_validators']['FileSizeLimit']['fileLimit'])) {
$element['upload']['#attributes']['data-max-filesize'] = (int) $element['#upload_validators']['FileSizeLimit']['fileLimit'];
}
elseif (isset($element['#upload_validators']['file_validate_size'][0])) {
$element['upload']['#attributes']['data-max-filesize'] = (int) $element['#upload_validators']['file_validate_size'][0];
}
return $element;
}

/**
* Implements hook_library_info_alter().
*/
function server_general_library_info_alter(array &$libraries, string $extension): void {
// Make our file size validation library load before core's file JS, so our
// change event handler is registered first and can prevent the upload.
if ($extension === 'file' && isset($libraries['drupal.file'])) {
$libraries['drupal.file']['dependencies'][] = 'server_theme/file-size-validation';
}
}

/**
* Get the maximum file upload size in bytes.
*
* Returns the smaller of upload_max_filesize and post_max_size PHP settings.
*
* @return int
* Maximum upload size in bytes.
*/
function server_general_get_max_upload_size(): int {
$upload_max = Bytes::toNumber(ini_get('upload_max_filesize'));
$post_max = Bytes::toNumber(ini_get('post_max_size'));

// post_max_size of 0 means unlimited.
if ($post_max == 0) {
return (int) $upload_max;
}

return (int) min($upload_max, $post_max);
}
9 changes: 9 additions & 0 deletions web/themes/custom/server_theme/server_theme.libraries.yml
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,12 @@ expanding-text:
- core/drupal
- core/jquery
- core/once

file-size-validation:
js:
dist/js/file-size-validation.js: {}
dependencies:
- core/drupal
- core/drupalSettings
- core/jquery
- core/once
90 changes: 90 additions & 0 deletions web/themes/custom/server_theme/src/js/file-size-validation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* @file
* Client-side file size validation to prevent upload errors.
*
* Validates file size before upload to show a user-friendly error message
* instead of cryptic AJAX errors when files exceed PHP limits.
*/
(function ($, Drupal, once) {

/**
* Validates file size before upload.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.fileSizeValidation = {
attach: function (context, settings) {
const maxFileSize = settings.fileSizeValidation?.maxFileSize;
if (!maxFileSize) {
return;
}

const $fileInputs = $(
once('file-size-validate', 'input[type="file"]', context)
);

if (!$fileInputs.length) {
return;
}

$fileInputs.on('change.fileSizeValidation', function (event) {
const input = this;
const files = input.files;

if (!files || !files.length) {
return;
}

// Use per-field limit if available (min of PHP and field config),
// otherwise fall back to the global PHP limit.
const fieldLimit = parseInt(input.getAttribute('data-max-filesize'), 10);
const effectiveMax = fieldLimit > 0 ? fieldLimit : maxFileSize;

// Remove any previous file size errors.
$(input)
.closest('div.js-form-managed-file, .form-item')
.find('.file-size-error')
.remove();

// Check each file's size.
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.size > effectiveMax) {
const fileSizeMB = (file.size / (1024 * 1024)).toFixed(2);
const maxSizeMB = (effectiveMax / (1024 * 1024)).toFixed(0);

const error = Drupal.t(
'The file "@filename" (@filesize MB) exceeds the maximum upload size of @maxsize MB. Please choose a smaller file.',
{
'@filename': file.name,
'@filesize': fileSizeMB,
'@maxsize': maxSizeMB,
}
);

$(input)
.closest('div.js-form-managed-file, .form-item')
.prepend(
'<div class="messages messages--error file-size-error" aria-live="polite">' + error + '</div>'
);

// Clear the file input to prevent upload attempt.
input.value = '';

// Stop processing and prevent upload.
event.stopImmediatePropagation();
return;
}
}
});
},
detach: function (context, settings, trigger) {
if (trigger === 'unload') {
$(once.remove('file-size-validate', 'input[type="file"]', context)).off(
'.fileSizeValidation'
);
}
},
};

})(jQuery, Drupal, once);
Loading