sepiariver
7/12/2015 - 11:03 PM

Process MODX Resource Image OnDocFormSave with pthumb

Process MODX Resource Image OnDocFormSave with pthumb

<?php
// In case the wrong event is enabled
if ($modx->context->key !== 'mgr' || $modx->event->name !== 'OnDocFormSave') return;

// We really need a resource object and the pthumb snippet
if (!is_object($resource) || $modx->getCount('modSnippet', array('name' => 'phpthumbof')) !== 1) {
    $modx->log(modX::LOG_LEVEL_ERROR, 'ResourceImageThumbnails plugin requires phpthumbof and a valid resource object.');
    return;
}

// Check template ID condition
$templateIds = array_map('trim', explode(',', $modx->getOption('templateIds', $scriptProperties, '')));
// If templateIds property is empty this will always return here
if (!in_array($resource->get('template'), $templateIds)) return;

// We need an image (expect it in a TV)
$tv = $modx->getOption('tv', $scriptProperties, 'image');
// We're gonna rely on pthumb to qualify the image file
$imageFile = $resource->getTVValue($tv);

// See if there's a zc setting in a TV
$zc = $modx->getOption('zc', $scriptProperties, 'crop');
$crop = $resource->getTVValue($zc);
if (empty($crop)) $crop = '1';

// Options
$options = array(
    'small' => implode('&', array('w=640','h=360','hp=854','zc=' . $crop,'q=60','aoe=1')),
    'medium' => implode('&', array('w=1280','h=720','hp=1280','zc=' . $crop,'q=60','aoe=1')),
    'large' => implode('&', array('w=1920','h=1080','hp=1920','zc=' . $crop,'q=60','aoe=1')),
    );

// Create thumbnails and store results in resource properties
$thumbs = array();
foreach($options as $size => $opts) {
    $thumbs[$size] = $modx->runSnippet('phpthumbof', array('options' => $opts, 'input' => $imageFile));
}
$image = array(
    'original' => $imageFile,
    'thumbs' => $thumbs,
    );
$resource->setProperties($image, 'resourceimage');
$resource->set('introtext', $modx->toJSON($image));
$resource->save();