chrisdempsey
2/23/2015 - 6:15 PM

Collection of MODX Plugins.

Collection of MODX Plugins.

<?php

/**
 * sets expires headers with plugin
 * 
 * fire on: OnLoadWebDocument or OnHandleRequest
 * 
 * Mark Hamstra notes: If OnLoadWebDocument works (and having access to the resource is a very good reason to use that one), than that's fine.
 * OnHandleRequest is my swiss armyknife of plugin events and from memory I was pretty sure you could use it to set the proper headers
 * 
 */
 
$days = 7;
$seconds_to_cache = $days*86400;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache, public");

// code extended from http://www.electrictoolbox.com/php-caching-headers/

// source: https://forums.modx.com/thread/81442/http-caching-headers---how-to-change
<?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.
 * 
 * Requirements: Resizer (modx.com/extras/package/resizer)
 *
 * Events: OnFileManagerUpload
 * Credit: Inspired by the work of Vasiliy Naumkin <bezumkin@yandex.ru> (https://bezumkin.ru/sections/components/118/)
 * Credit: Bruno (http://forums.modx.com/u/Bruno17)
 * Credit: LuK (http://forums.modx.com/u/exside)
 * Author: Chris Dempsey
 * 
 * Plugin called on each OnFileManagerUpload.
 * If multiple files are uploaded at the same time the plugin is called for each file.
 * 
 */

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 = true;            // 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 );
}
01-autoResizeOnUpload.php     - Plugin to automatically resize images uploaded via MODX that are larger than the dimensions specified
                                in the config within the plugin code.  This should be considered experimental but has been tested
                                successfully on MODX Revolution 2.3.2-pl (traditional) running on Windows Server 2008.
02-set-expires-headers.php    - Sets expires headers to value defined in plugin