Skip to content

Instantly share code, notes, and snippets.

@chrisdempsey
Last active March 23, 2022 15:19
Show Gist options
  • Save chrisdempsey/39254982aeaba5a305d5339ff258fc70 to your computer and use it in GitHub Desktop.
Save chrisdempsey/39254982aeaba5a305d5339ff258fc70 to your computer and use it in GitHub Desktop.
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/
@pawelpvi
Copy link

pawelpvi commented Oct 10, 2020

Hello, I can't get this plugin work.
Error log:
OnFileManagerUpload event fired.
$ms_basePath = pliki/
$file = Array
$directory_uploaded_to = aktualnosci/2020/
$file_path_abs = /home/admin/domains/test.pvi.pl/public_html/pliki/aktualnosci/2020/IMG_0148d.JPG
$file_path_abs_safe = /home/admin/domains/test.pvi.pl/public_html/pliki/aktualnosci/2020/IMG_0148d.JPG
$file_name = IMG_0148d.JPG
$file_ext = JPG
$file_dimensions = Array
WIDTH = 6000
HEIGHT = 4000

$resizer_log:

I reinstalled Resizer, here is log from console afrer install:

Attempting to install package with signature: resizer-1.0.2-beta
Package found...now preparing to install.
Grabbing package workspace...
Workspace environment initiated, now installing package...
Skipping vehicle object of class modSystemSetting (data object exists and cannot be upgraded); criteria: Array ( [key] => resizer.graphics_library )
[Resizer]
PHP version: 5.6.40 [OK]
Availabe graphics libraries:

  • ImageMagick 6.8.9-9 Q16 x86_64 2016-06-01 http://www.imagemagick.org
  • GD: bundled (2.1.0 compatible)
    Attempting to preserve files at /home/admin/domains/test.pvi.pl/public_html/core/components/resizer into archive /home/admin/domains/test.pvi.pl/public_html/core/packages/resizer-1.0.2-beta/modCategory/989bdd719e81c8f179cace597f93b351.0.preserved.zip
    Successfully installed package resizer-1.0.2-beta

Thanks in advance for help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment