Automatically resizes images uploaded through the MODX File Manager if they exceed the dimensions specified in the config settings below and the file extension is included in the upload_images System Setting. Provides basic filename sanitization.
Dependancies: Resizer Extra (http://modx.com/extras/package/resizer)
<?php
/**
* autoResizeOnUpload
*
* Description: Automatically resizes images uploaded through the MODX File Manager
* if they exceed the dimensions specified in the config settings below and the
* file extension is included in the upload_images System Setting.
*
* Provides basic filename sanitization.
*
* How it works: plugin is called on each OnFileManagerUpload event. if multiple files are uploaded simultaneously the plugin is called for each file.
*
* Dependancies: Resizer Extra (http://modx.com/extras/package/resizer)
*
* Configuration: set plugin to fire on system event: OnFileManagerUpload
* adjust variables in Settings section below to suit your requirements.
*
* Credit: Inspired by the work of Vasiliy Naumkin <bezumkin@yandex.ru> (https://bezumkin.ru/sections/components/118/)
* Credit: Forum posts by Bruno (http://forums.modx.com/u/Bruno17)
* Credit: Forum posts by LuK (http://forums.modx.com/u/exside)
* Author: Chris Dempsey
*
*
*/
if ( !isset( $modx ) ) return;
if( $modx->Event->name != 'OnFileManagerUpload' ) {
return;
}
/**
* Settings
*
* Adjust as required.
* Disable logging in production environment otherwise MODX error log will fill up with
* unnecessary entries.
*
*/
// logging
$logging = false; // perform logging both in MODX and Resizer debug
// config to pass to Resizer which supports a subset of phpThumb options (https://github.com/oo12/Resizer#options)
$config = array (
'w' => 1600, // max width
'h' => 1600, // max height
'zc' => 0, // zoom crop
'bg' => '#FFF', // backgroud, only required if zc = 0
'q' => 78, // quality
'scale' => 1 // scale
);
/*********************************
* No need to edit below this line
********************************/
$file = $modx->event->params[ 'files' ][ 'file' ];
// abort on error
if ( $file['error'] != 0 ) {
$modx->log( modX::LOG_LEVEL_ERROR, 'autoResizeOnUpload: $file["error"] occured.' );
return;
}
$directory_uploaded_to = $modx->event->params [ 'directory' ]; // get upload directory from OnFileManagerUpload event
$file_name = $file[ 'name' ]; // get the filename eg. picture.jpg
/**
* sanitize file_name
*/
// replace non alphanumeric characters with dash
$file_name_safe = preg_replace( '/[^a-zA-Z0-9-_\.]/','-', $file_name );
// file_name could end up with consecutive dashes for replaced characters eg.
// image (2014).jpg becomes: image--2014-.jpg so remove consecutive dashes
$file_name_safe = preg_replace( '/--+/', '-', $file_name_safe );
// create array of upload_images extensions from system settings
$allowed_extensions = explode ( ',' , $modx->getOption ( 'upload_images' ) );
// trim white space
$allowed_extensions = array_map('trim', $allowed_extensions);
/**
* Get media source properties for default media source
*
*/
// get id of default_media_source
$default_media_source = $modx->getOption('default_media_source');
// get modMediaSource object using default_media_source id
$obj_media_source = $modx->getObject( 'modMediaSource', array( 'id' => $default_media_source ) );
// get modMediaSource properties
$ms_props = $obj_media_source->get( 'properties' );
$ms_basePath = $ms_props[ 'basePath' ][ 'value' ];
$file_path_abs = MODX_BASE_PATH . $ms_basePath . $directory_uploaded_to . $file_name;
$file_path_abs_safe = MODX_BASE_PATH . $ms_basePath . $directory_uploaded_to . $file_name_safe;
// extension of uploaded file
$file_ext = substr ( strrchr( $file_name, '.' ), 1 );
// get properties of image as array, includes file type and a height/width text string
$file_dimensions = getimagesize ( $file_path_abs );
/**
* Final check before running Resizer
*
* Is image filetype is in allowed extensions +
* are dimensions of uploaded file greater than sizes allowed in config
*
*/
if ( (in_array ($file_ext, $allowed_extensions) ) && ( ($file_dimensions[0] > $config['w'] || $file_dimensions[1] > $config['h']) ) ) {
// example code source for resizer: https://github.com/oo12/Resizer#snippet-developers
//$modx->loadClass( 'Resizer', MODX_CORE_PATH . 'components/resizer/model/', true, true );
if (!$modx->loadClass( 'Resizer', MODX_CORE_PATH . 'components/resizer/model/', true, true )) {
// Resizer not installed, log error and exit
$modx->log(modX::LOG_LEVEL_ERROR, 'Error: autoResizeOnUpload Plugin - Resizer component not found.');
return;
}
$resizer = new Resizer( $modx ); // pass in the modx object
if ( $logging == true ) {
$resizer->debug = true; // (optional) Enable debugging messages.
}
$resizer->processImage(
$file_path_abs, // input image file (path can be absolute or relative to MODX_BASE_PATH)
$file_path_abs_safe, // output image file. Extension determines image format.
$config // config array
);
// now have a copy of the uploaded file with safe name, delete the original image file but only if
// the filename does not match the original, otherwise we'll delete the resized image.
if( $file_path_abs !== $file_path_abs_safe ) {
if ( !unlink( $file_path_abs ) ) {
if ( $logging == true ) {
$log_resizer .= 'Delete original file: failed.' . PHP_EOL;
}
} else {
if ( $logging == true ) {
$log_resizer .= 'Delete original file: success.' . PHP_EOL;
}
}
}
// (optional) record Resizer debug message array for the modx error log
if ( $logging == true ) {
$log_resizer .= PHP_EOL . '=======[ Resizer Log ]=======' . PHP_EOL;
$log_resizer .= substr(print_r($resizer->debugmessages, TRUE), 7, -2);
}
}
/**
* Debug logging
*/
if ( $logging == true ) {
$log_autoResizeOnUpload .= PHP_EOL . '=======[ autoResizeOnUpload Plugin - Debug Log ]=======' . PHP_EOL;
// OnFileManagerUpload fired
$log_autoResizeOnUpload .= 'OnFileManagerUpload event fired.' . PHP_EOL;
// ms_basePath
$log_autoResizeOnUpload .= '$ms_basePath = ' . $ms_basePath . PHP_EOL;
// file
$log_autoResizeOnUpload .= '$file = ' . $file . PHP_EOL;
// directory_uploaded_to
$log_autoResizeOnUpload .= '$directory_uploaded_to = ' . $directory_uploaded_to . PHP_EOL;
// file_path_abs
$log_autoResizeOnUpload .= '$file_path_abs = ' . $file_path_abs . PHP_EOL;
// file_path_abs_safe
$log_autoResizeOnUpload .= '$file_path_abs_safe = ' . $file_path_abs_safe . PHP_EOL;
// file_name
$log_autoResizeOnUpload .= '$file_name = ' . $file_name . PHP_EOL;
// file_ext
$log_autoResizeOnUpload .= '$file_ext = ' . $file_ext . PHP_EOL;
// file_dimensions
$log_autoResizeOnUpload .= '$file_dimensions = ' . $file_dimensions . PHP_EOL;
// width of uploaded file
$log_autoResizeOnUpload .= 'WIDTH = ' . $file_dimensions[0] . PHP_EOL;
// heght of uploaded file
$log_autoResizeOnUpload .= 'HEIGHT = ' . $file_dimensions[1] . PHP_EOL;
// resizer log
$log_autoResizeOnUpload .= PHP_EOL . '$resizer_log: ' . PHP_EOL . $log_resizer;
// commit details to MODX error log
$modx->log( modX::LOG_LEVEL_ERROR, $log_autoResizeOnUpload );
}
<?php
/**
* ResizeOnUpload Plugin
*
* Events: OnFileManagerUpload
* Author: Vasiliy Naumkin <bezumkin@yandex.ru>
* Required: PhpThumbOf snippet for resizing images
*/
if ($modx->event->name != 'OnFileManagerUpload') {return;}
/* Settings */
$config = array(
'/' => array( // default config
'w' => 800 // max width of uploaded images
,'h' => 600 // max height of uploaded images
,'zc' => 0 // zoom & crop
,'bg' => '#fff' // backgroud, needed only for zc=0
,'q' => 100 // quality
)
//,'/assets/images/' => array()
);
/*----------*/
$file = $modx->event->params['files']['file'];
$directory = $modx->event->params['directory'];
if ($file['error'] != 0) {return;}
$name = $file['name'];
$extensions = explode(',', $modx->getOption('upload_images'));
if (array_key_exists($directory, $config)) {
$config = $config[$directory];
}
else {
$config = $config['/'];
}
$filename = MODX_BASE_PATH . $directory . $name;
$ext = substr(strrchr($name, '.'), 1);
if (in_array($ext, $extensions)) {
$sizes = getimagesize($filename);
$format = substr($sizes['mime'],6);
if ($sizes[0] > $config['w'] || $sizes[1] > $config['h']) {
if ($sizes[0] < $config['w']) {$config['w'] = $sizes[0];}
if ($sizes[1] < $config['h']) {$config['h'] = $sizes[1];}
$options = '';
foreach ($config as $k => $v) {
$options .= '&'.$k.'='.$v;
}
$resized = $modx->runSnippet('PhpThumbOf', array(
'input' => $directory.$name
,'options' => $options
));
rename(MODX_BASE_PATH . substr($resized, 1), $filename);
}
}
// source: https://bezumkin.ru/sections/components/118/