Index: modules/system/system.module =================================================================== RCS file: /cvs/drupal/drupal/modules/system/system.module,v retrieving revision 1.667 diff -u -r1.667 system.module --- modules/system/system.module 11 Feb 2009 05:33:18 -0000 1.667 +++ modules/system/system.module 16 Feb 2009 09:10:45 -0000 @@ -155,6 +155,38 @@ 'arguments' => array('content' => NULL), 'file' => 'system.admin.inc', ), + 'admin_image_presets' => array( + 'arguments' => array('presets' => NULL), + 'file' => 'system.admin.inc', + ), + 'admin_image_preset_actions' => array( + 'arguments' => array('form' => NULL), + 'file' => 'system.admin.inc', + ), + 'admin_image_preset_actions_add' => array( + 'arguments' => array('form' => NULL), + 'file' => 'system.admin.inc', + ), + 'system_image_resize_summary' => array( + 'arguments' => array('data' => NULL), + 'file' => 'image.actions.inc', + ), + 'system_image_scale_summary' => array( + 'arguments' => array('data' => NULL), + 'file' => 'image.actions.inc', + ), + 'system_image_crop_summary' => array( + 'arguments' => array('data' => NULL), + 'file' => 'image.actions.inc', + ), + 'system_image_desaturate_summary' => array( + 'arguments' => array('data' => NULL), + 'file' => 'image.actions.inc', + ), + 'system_image_rotate_summary' => array( + 'arguments' => array('data' => NULL), + 'file' => 'image.actions.inc', + ), 'system_admin_by_module' => array( 'arguments' => array('menu_items' => NULL), 'file' => 'system.admin.inc', @@ -189,6 +221,10 @@ 'title' => t('Administer files'), 'description' => t('Manage user-uploaded files.'), ), + 'administer image presets' => array( + 'title' => t('Administer image presets'), + 'description' => t('Create and modify presets for generating image modifications such as thumbnails.'), + ), 'access administration pages' => array( 'title' => t('Access administration pages'), 'description' => t('View the administration panel and browse the help system.'), @@ -453,6 +489,12 @@ 'access callback' => TRUE, 'type' => MENU_CALLBACK, ); + $items['system/image'] = array( + 'title' => 'Generate image preset', + 'page callback' => 'system_image_preset_generate', + 'access callback' => TRUE, + 'type' => MENU_CALLBACK, + ); $items['admin'] = array( 'title' => 'Administer', 'access arguments' => array('access administration pages'), @@ -663,12 +705,105 @@ 'page arguments' => array('system_file_system_settings'), 'access arguments' => array('administer site configuration'), ); - $items['admin/settings/image-toolkit'] = array( + $items['admin/settings/images'] = array( + 'title' => 'Image handling', + 'description' => 'Configure presets for generating image thumbnails and select an image toolkit.', + 'page callback' => 'system_image_presets', + 'access arguments' => array('administer image presets'), + ); + $items['admin/settings/images/presets'] = array( + 'title' => 'Image presets', + 'description' => 'Configure presets for generating image thumbnails and other manipulations.', + 'page callback' => 'system_image_presets', + 'access arguments' => array('administer image presets'), + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'weight' => 1, + ); + $items['admin/settings/images/presets/%image_preset'] = array( + 'title' => 'Edit preset', + 'title callback' => 'system_image_preset_title', + 'title arguments' => array('Edit preset !name', 4), + 'description' => 'Configure an image preset.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('system_image_preset_form', 4), + 'access arguments' => array('administer image presets'), + 'type' => MENU_CALLBACK, + ); + $items['admin/settings/images/presets/%image_preset/delete'] = array( + 'title' => 'Delete preset', + 'title callback' => 'system_image_preset_title', + 'title arguments' => array('Delete preset !name', 4), + 'description' => 'Configure presets for generating image thumbnails and other manipulations.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('system_image_preset_delete_form', 4, TRUE), + 'access arguments' => array('administer image presets'), + 'type' => MENU_CALLBACK, + ); + $items['admin/settings/images/presets/%image_preset/flush'] = array( + 'title' => 'Flush preset', + 'title callback' => 'system_image_preset_title', + 'title arguments' => array('Flush preset !name', 4), + 'description' => 'Flush all the created images for a preset.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('system_image_preset_flush_form', 4, TRUE), + 'access arguments' => array('administer image presets'), + 'type' => MENU_CALLBACK, + ); + $items['admin/settings/images/presets/%image_preset/%image_action'] = array( + 'title' => 'Edit image action', + 'title callback' => 'system_image_action_title', + 'title arguments' => array('Edit !name action', 5), + 'description' => 'Edit an exiting action within a preset.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('system_image_action_form', 4, 5), + 'access arguments' => array('administer image presets'), + 'type' => MENU_CALLBACK, + ); + $items['admin/settings/images/presets/%image_preset/%image_action/delete'] = array( + 'title' => 'Delete image action', + 'title callback' => 'system_image_action_title', + 'title arguments' => array('Delete !name action', 5), + 'description' => 'Delete an exiting action from a preset.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('system_image_action_delete_form', 4, 5), + 'access arguments' => array('administer image presets'), + 'type' => MENU_CALLBACK, + ); + $items['admin/settings/images/presets/%image_preset/add/%image_action_definition'] = array( + 'title' => 'Add image action', + 'title callback' => 'system_image_action_title', + 'title arguments' => array('Add !name action', 6), + 'description' => 'Add a new action to a preset.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('system_image_action_form', 4, 6), + 'access arguments' => array('administer image presets'), + 'type' => MENU_CALLBACK, + ); + $items['admin/settings/images/presets/list'] = array( + 'title' => 'List', + 'description' => 'List the current image presets on the site.', + 'page callback' => 'system_image_presets', + 'access arguments' => array('administer image presets'), + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'weight' => 1, + ); + $items['admin/settings/images/presets/add'] = array( + 'title' => 'Add preset', + 'description' => 'Add a new image preset.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('system_image_preset_add_form'), + 'access arguments' => array('administer image presets'), + 'type' => MENU_LOCAL_TASK, + 'weight' => 2, + ); + $items['admin/settings/images/toolkit'] = array( 'title' => 'Image toolkit', 'description' => 'Choose which image toolkit to use if you have installed optional toolkits.', 'page callback' => 'drupal_get_form', 'page arguments' => array('system_image_toolkit_settings'), 'access arguments' => array('administer site configuration'), + 'type' => MENU_LOCAL_TASK, + 'weight' => 2, ); $items['admin/content/rss-publishing'] = array( 'title' => 'RSS publishing', @@ -1073,6 +1208,49 @@ } /** + * Implementation of hook_file_download(). + * + * Control the access to files underneath the system/files/presets directory. + */ +function system_file_download($filepath) { + if (strpos($filepath, 'presets/') === 0) { + $args = explode('/', $filepath); + array_shift($args); // Toss the "presets" item. + $preset_name = array_shift($args); + $original_path = implode('/', $args); + + // Check that the file exists and is an image. + if ($info = image_get_info(file_create_path($filepath))) { + // Check the permissions of the original image to grant access to this image. + $headers = module_invoke_all('file_download', $original_path); + if (!in_array(-1, $headers)) { + return array( + 'Content-Type: ' . $info['mime_type'], + 'Content-Length: ' . $info['file_size'], + ); + } + } + return -1; + } +} + +/** + * Implementation of hook_file_move(). + */ +function system_file_move($file, $source) { + // Delete any image derivatives at the original image path. + image_path_flush($file->filepath); +} + +/** + * Implementation of hook_file_delete(). + */ +function system_file_delete($file) { + // Delete any image derivatives of this image. + image_path_flush($file->filepath); +} + +/** * Prepare defaults for themes. * * @return Index: modules/system/system.install =================================================================== RCS file: /cvs/drupal/drupal/modules/system/system.install,v retrieving revision 1.306 diff -u -r1.306 system.install --- modules/system/system.install 3 Feb 2009 12:30:14 -0000 1.306 +++ modules/system/system.install 16 Feb 2009 09:10:44 -0000 @@ -726,6 +726,63 @@ 'nid' => array('nid'), ), ); + + $schema['image_presets'] = array( + 'fields' => array( + 'ipid' => array( + 'description' => t('The primary identifier for an image preset.'), + 'type' => 'serial', + 'unsigned' => TRUE, + 'not null' => TRUE), + 'name' => array( + 'description' => t('The primary identifier for a node.'), + 'type' => 'varchar', + 'length' => 255, + 'not null' => TRUE), + ), + 'primary key' => array('ipid'), + 'indexes' => array( + 'name' => array('name'), + ), + ); + + $schema['image_actions'] = array( + 'fields' => array( + 'iaid' => array( + 'description' => t('The primary identifier for an image action.'), + 'type' => 'serial', + 'unsigned' => TRUE, + 'not null' => TRUE), + 'ipid' => array( + 'description' => t('The primary identifier for an image preset.'), + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'default' => 0), + 'weight' => array( + 'description' => t('The weight of the action in the preset.'), + 'type' => 'int', + 'unsigned' => FALSE, + 'not null' => TRUE, + 'default' => 0), + 'action' => array( + 'description' => t('The unique ID of the action to be executed.'), + 'type' => 'varchar', + 'length' => 255, + 'not null' => TRUE), + 'data' => array( + 'description' => t('The configuration data for the action.'), + 'type' => 'text', + 'not null' => TRUE, + 'size' => 'big', + 'serialize' => TRUE), + ), + 'primary key' => array('iaid'), + 'indexes' => array( + 'ipid' => array('ipid'), + ), + ); + $schema['menu_router'] = array( 'description' => 'Maps paths to various callbacks (access, page and title)', 'fields' => array( @@ -3213,6 +3270,74 @@ } /** + * Add tables for image presets and actions. + */ +function system_update_7019() { + $ret = array(); + $schema = array(); + + $schema['image_presets'] = array( + 'fields' => array( + 'ipid' => array( + 'description' => t('The primary identifier for an image preset.'), + 'type' => 'serial', + 'unsigned' => TRUE, + 'not null' => TRUE), + 'name' => array( + 'description' => t('The primary identifier for a node.'), + 'type' => 'varchar', + 'length' => 255, + 'not null' => TRUE), + ), + 'primary key' => array('ipid'), + 'indexes' => array( + 'name' => array('name'), + ), + ); + + $schema['image_actions'] = array( + 'fields' => array( + 'iaid' => array( + 'description' => t('The primary identifier for an image action.'), + 'type' => 'serial', + 'unsigned' => TRUE, + 'not null' => TRUE), + 'ipid' => array( + 'description' => t('The primary identifier for an image preset.'), + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'default' => 0), + 'weight' => array( + 'description' => t('The weight of the action in the preset.'), + 'type' => 'int', + 'unsigned' => FALSE, + 'not null' => TRUE, + 'default' => 0), + 'action' => array( + 'description' => t('The unique ID of the action to be executed.'), + 'type' => 'varchar', + 'length' => 255, + 'not null' => TRUE), + 'data' => array( + 'description' => t('The configuration data for the action.'), + 'type' => 'text', + 'not null' => TRUE, + 'size' => 'big', + 'serialize' => TRUE), + ), + 'primary key' => array('iaid'), + 'indexes' => array( + 'ipid' => array('ipid'), + ), + ); + + db_create_table($ret, 'image_presets', $schema['image_presets']); + db_create_table($ret, 'image_actions', $schema['image_actions']); + return $ret; +} + +/** * @} End of "defgroup updates-6.x-to-7.x" * The next series of updates should start at 8000. */ Index: modules/system/system.info =================================================================== RCS file: /cvs/drupal/drupal/modules/system/system.info,v retrieving revision 1.11 diff -u -r1.11 system.info --- modules/system/system.info 12 Oct 2008 01:23:06 -0000 1.11 +++ modules/system/system.info 16 Feb 2009 09:10:42 -0000 @@ -6,6 +6,8 @@ core = 7.x files[] = system.module files[] = system.admin.inc +files[] = system.admin_image.inc files[] = image.gd.inc +files[] = image.actions.inc files[] = system.install required = TRUE Index: modules/system/image.gd.inc =================================================================== RCS file: /cvs/drupal/drupal/modules/system/image.gd.inc,v retrieving revision 1.3 diff -u -r1.3 image.gd.inc --- modules/system/image.gd.inc 30 Dec 2008 16:43:19 -0000 1.3 +++ modules/system/image.gd.inc 16 Feb 2009 09:10:42 -0000 @@ -15,7 +15,12 @@ * Retrieve information about the toolkit. */ function image_gd_info() { - return array('name' => 'gd', 'title' => t('GD2 image manipulation toolkit')); + if (image_gd_check_settings()) { + return array( + 'name' => 'gd', + 'title' => t('GD2 image manipulation toolkit'), + ); + } } /** @@ -76,146 +81,231 @@ /** * Scale an image to the specified size using GD. + * + * @param $image + * An image object. The $image->resource, $image->info['width'], and + * $image->info['height'] values will be modified by this call. + * @param $width + * The new width of the resized image, in pixels. + * @param $height + * The new height of the resized image, in pixels. + * @return + * TRUE or FALSE, based on success. */ -function image_gd_resize($source, $destination, $width, $height) { - if (!file_exists($source)) { - return FALSE; - } +function image_gd_resize(stdClass $image, $width, $height) { + $res = image_gd_create_tmp($image, $width, $height); - $info = image_get_info($source); - if (!$info) { + if (!imagecopyresampled($res, $image->resource, 0, 0, 0, 0, $width, $height, $image->info['width'], $image->info['height'])) { return FALSE; } - $im = image_gd_open($source, $info['extension']); - if (!$im) { - return FALSE; - } - - $res = imagecreatetruecolor($width, $height); - if ($info['extension'] == 'png') { - $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127); - imagealphablending($res, FALSE); - imagefilledrectangle($res, 0, 0, $width, $height, $transparency); - imagealphablending($res, TRUE); - imagesavealpha($res, TRUE); - } - elseif ($info['extension'] == 'gif') { - // If we have a specific transparent color. - $transparency_index = imagecolortransparent($im); - if ($transparency_index >= 0) { - // Get the original image's transparent color's RGB values. - $transparent_color = imagecolorsforindex($im, $transparency_index); - // Allocate the same color in the new image resource. - $transparency_index = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']); - // Completely fill the background of the new image with allocated color. - imagefill($res, 0, 0, $transparency_index); - // Set the background color for new image to transparent. - imagecolortransparent($res, $transparency_index); - // Find number of colors in the images palette. - $number_colors = imagecolorstotal($im); - // Convert from true color to palette to fix transparency issues. - imagetruecolortopalette($res, TRUE, $number_colors); - } - } - imagecopyresampled($res, $im, 0, 0, 0, 0, $width, $height, $info['width'], $info['height']); - $result = image_gd_close($res, $destination, $info['extension']); - - imagedestroy($res); - imagedestroy($im); - - return $result; + imagedestroy($image->resource); + // Update image object. + $image->resource = $res; + $image->info['width'] = $width; + $image->info['height'] = $height; + return TRUE; } /** * Rotate an image the given number of degrees. + * + * @param $image + * An image object. The $image->resource, $image->info['width'], and + * $image->info['height'] values will be modified by this call. + * @param $degress + * The number of degrees to rotate the image. + * @param $background + * The color of the exposed background when rotating. + * @return + * TRUE or FALSE, based on success. */ -function image_gd_rotate($source, $destination, $degrees, $background = 0x000000) { - if (!function_exists('imageRotate')) { - return FALSE; +function image_gd_rotate(stdClass $image, $degrees, $background = NULL) { + $width = $image->info['width']; + $height = $image->info['height']; + + // Convert the hexadecimal background value to a color index value. + if (isset($background)) { + $rgb = array(); + for ($i = 16; $i >= 0; $i -= 8) { + $rgb[] = (($background >> $i) & 0xFF); + } + $background = imagecolorallocatealpha($image->resource, $rgb[0], $rgb[1], $rgb[2], 0); } + // Set the background color as transparent if $background is NULL. + else { + // Get the current transparent color. + $background = imagecolortransparent($image->resource); - $info = image_get_info($source); - if (!$info) { - return FALSE; + // If no transparent colors, use white. + if ($background == 0) { + $background = imagecolorallocatealpha($image->resource, 255, 255, 255, 0); + } } - $im = image_gd_open($source, $info['extension']); - if (!$im) { - return FALSE; + // Images are assigned a new color pallete when rotating, removing any + // transparency flags. For GIF images, keep a record of the transparent color. + if ($image->info['extension'] == 'gif') { + $transparent_index = imagecolortransparent($image->resource); + if ($transparent_index != 0) { + $transparent_gif_color = imagecolorsforindex($image->resource, $transparent_index); + } } - $res = imageRotate($im, $degrees, $background); - $result = image_gd_close($res, $destination, $info['extension']); + $image->resource = imagerotate($image->resource, 360 - $degrees, $background); + + // GIFs need to reassign the transparent color after performing the rotate. + if (isset($transparent_gif_color)) { + $background = imagecolorexactalpha($image->resource, $transparent_gif_color['red'], $transparent_gif_color['green'], $transparent_gif_color['blue'], $transparent_gif_color['alpha']); + imagecolortransparent($image->resource, $background); + } - return $result; + $image->info['width'] = imagesx($image->resource); + $image->info['height'] = imagesy($image->resource); + return TRUE; } /** * Crop an image using the GD toolkit. + * + * @param $image + * An image object. The $image->resource, $image->info['width'], and + * $image->info['height'] values will be modified by this call. + * @param $x + * The starting x offset at which to start the crop, in pixels. + * @param $y + * The starting y offset at which to start the crop, in pixels. + * @param $width + * The width of the cropped area, in pixels. + * @param $height + * The height of the cropped area, in pixels. + * @return + * TRUE or FALSE, based on success. */ -function image_gd_crop($source, $destination, $x, $y, $width, $height) { - $info = image_get_info($source); - if (!$info) { +function image_gd_crop(stdClass $image, $x, $y, $width, $height) { + $res = image_gd_create_tmp($image, $width, $height); + + if (!imagecopyresampled($res, $image->resource, 0, 0, $x, $y, $width, $height, $width, $height)) { return FALSE; } - $im = image_gd_open($source, $info['extension']); - $res = imageCreateTrueColor($width, $height); - imageCopy($res, $im, 0, 0, $x, $y, $width, $height); - $result = image_gd_close($res, $destination, $info['extension']); - - imageDestroy($res); - imageDestroy($im); + // Destroy the original image and return the modified image. + imagedestroy($image->resource); + $image->resource = $res; + $image->info['width'] = $width; + $image->info['height'] = $height; + return TRUE; +} - return $result; +/** + * Convert an image resource to grayscale. + * + * Note that transparent GIFs loose transparency when desaturated. + * + * @param $image + * An image object. The $image->resource value will be modified by this call. + * @return + * TRUE or FALSE, based on success. + */ +function image_gd_desaturate(stdClass $image) { + return imagefilter($image->resource, IMG_FILTER_GRAYSCALE); } /** * GD helper function to create an image resource from a file. * - * @param $file - * A string file path where the image should be saved. - * @param $extension - * A string containing one of the following extensions: gif, jpg, jpeg, png. + * @param $image + * An image object. The $image->resource value will populated by this call. * @return * An image resource, or FALSE on error. + * + * @see image_open() */ -function image_gd_open($file, $extension) { - $extension = str_replace('jpg', 'jpeg', $extension); - $open_func = 'imageCreateFrom' . $extension; - if (!function_exists($open_func)) { - return FALSE; +function image_gd_open(stdClass $image) { + $extension = str_replace('jpg', 'jpeg', $image->info['extension']); + $function = 'imagecreatefrom'. $extension; + if (function_exists($function) && $image->resource = $function($image->source)) { + return $image; } - return $open_func($file); + return FALSE; } /** * GD helper to write an image resource to a destination file. * - * @param $res - * An image resource created with image_gd_open(). + * @param $image + * An image object. * @param $destination * A string file path where the image should be saved. * @param $extension * A string containing one of the following extensions: gif, jpg, jpeg, png. * @return - * Boolean indicating success. + * TRUE or FALSE, based on success. + * + * @see image_close() */ -function image_gd_close($res, $destination, $extension) { - $extension = str_replace('jpg', 'jpeg', $extension); - $close_func = 'image' . $extension; - if (!function_exists($close_func)) { +function image_gd_close(stdClass $image, $destination) { + $extension = str_replace('jpg', 'jpeg', $image->info['extension']); + $function = 'image'. $extension; + if (!function_exists($function)) { return FALSE; } if ($extension == 'jpeg') { - return $close_func($res, $destination, variable_get('image_jpeg_quality', 75)); + return $function($image->resource, $destination, variable_get('image_jpeg_quality', 75)); } else { - return $close_func($res, $destination); + // Always save PNG images with full transparency. + if ($extension == 'png') { + imagealphablending($image->resource, FALSE); + imagesavealpha($image->resource, TRUE); + } + return $function($image->resource, $destination); } } /** + * Create a truecolor image preserving transparency from a provided image. + * + * @param $image + * An image object. + * @param $width + * The new width of the new image, in pixels. + * @param $height + * The new height of the new image, in pixels. + * @return + * A GD image handle. + */ +function image_gd_create_tmp(stdClass $image, $width, $height) { + $res = imagecreatetruecolor($width, $height); + + if ($image->info['extension'] == 'gif') { + // Grab transparent color index from image resource. + $transparent = imagecolortransparent($image->resource); + + if ($transparent >= 0) { + // The original must have a transparent color, allocate to the new image. + $transparent_color = imagecolorsforindex($image->resource, $transparent); + $transparent = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']); + + // Flood with our new transparent color. + imagefill($res, 0, 0, $transparent); + imagecolortransparent($res, $transparent); + } + } + elseif ($image->info['extension'] == 'png') { + imagealphablending($res, FALSE); + $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127); + imagefill($res, 0, 0, $transparency); + imagealphablending($res, TRUE); + imagesavealpha($res, TRUE); + } + else { + imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255)); + } + + return $res; +} + +/** * @} End of "ingroup image". */ Index: modules/system/system.admin.inc =================================================================== RCS file: /cvs/drupal/drupal/modules/system/system.admin.inc,v retrieving revision 1.125 diff -u -r1.125 system.admin.inc --- modules/system/system.admin.inc 11 Feb 2009 05:33:18 -0000 1.125 +++ modules/system/system.admin.inc 16 Feb 2009 09:10:42 -0000 @@ -1462,6 +1462,15 @@ */ function system_image_toolkit_settings() { $toolkits_available = image_get_available_toolkits(); + + if (count($toolkits_available) == 0) { + variable_del('image_toolkit'); + $form['image_toolkit_help'] = array( + '#markup' => t("No image toolkits were detected. Drupal includes support for PHP's built-in image processing functions but they were not detected on this system. You should consult your system administrator to have them enabled, or try using a third party toolkit.", array('gd-link' => url('http://php.net/gd'))), + ); + return $form; + } + if (count($toolkits_available) > 1) { $form['image_toolkit'] = array( '#type' => 'radios', @@ -1470,12 +1479,11 @@ '#options' => $toolkits_available ); } - elseif (count($toolkits_available) == 1) { + else { variable_set('image_toolkit', key($toolkits_available)); } $form['image_toolkit_settings'] = image_toolkit_invoke('settings'); - return system_settings_form($form, TRUE); } Index: modules/system/system.test =================================================================== RCS file: /cvs/drupal/drupal/modules/system/system.test,v retrieving revision 1.39 diff -u -r1.39 system.test --- modules/system/system.test 11 Feb 2009 05:33:18 -0000 1.39 +++ modules/system/system.test 16 Feb 2009 09:10:45 -0000 @@ -412,6 +412,217 @@ } /** + * Tests creation, deletion, and editing of image presets and actions. + */ +class AdminImagePresets extends DrupalWebTestCase { + + /** + * Implementation of getInfo(). + */ + function getInfo() { + return array( + 'name' => t('Image presets and actions configuration'), + 'description' => t('Tests creation, deletion, and editing of image presets and actions.'), + 'group' => t('System') + ); + } + + /** + * Implementation of setUp(). + */ + function setUp() { + parent::setUp(); + + // Create an administrative user. + $this->admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer image presets')); + $this->drupalLogin($this->admin_user); + } + + /** + * Given an image preset, generate an image. + */ + function createSampleImage($preset) { + static $file_path; + + // First, we need to make sure we have an image in our testing + // file directory. Copy over an image on the first run. + if (!isset($file_path)) { + $file = reset($this->drupalGetTestFiles('image')); + $file_path = file_unmanaged_copy($file->filename); + } + + return image_preset_generate($preset['name'], $file_path) ? $file_path : FALSE; + } + + /** + * Count the number of images currently create for a preset. + */ + function getImageCount($preset) { + $directory = file_directory_path() . '/presets/' . $preset['name']; + return count(file_scan_directory($directory, '/.*/')); + } + + function testPreset() { + // Setup a preset to be created and actions to add to it. + $preset_name = strtolower($this->randomName(10)); + $preset_path = 'admin/settings/images/presets/' . $preset_name; + $action_edits = array( + 'system_image_resize' => array( + 'data[width]' => 100, + 'data[height]' => 101, + ), + 'system_image_scale' => array( + 'data[width]' => 110, + 'data[height]' => 111, + 'data[upscale]' => 1, + ), + 'system_image_scale_and_crop' => array( + 'data[width]' => 120, + 'data[height]' => 121, + ), + 'system_image_crop' => array( + 'data[width]' => 130, + 'data[height]' => 131, + 'data[xoffset]' => 1, + 'data[yoffset]' => 2, + ), + 'system_image_desaturate' => array( + // No options for desaturate. + ), + 'system_image_rotate' => array( + 'data[degrees]' => 5, + 'data[random]' => 1, + 'data[bgcolor]' => '#FFFF00', + ), + ); + + /* Add preset form. */ + + $edit = array( + 'name' => $preset_name, + ); + $this->drupalPost('admin/settings/images/presets/add', $edit, t('Create new preset')); + $this->assertRaw(t('Preset %name was created.', array('%name' => $preset_name)), t('Image preset successfully created.')); + + /* Add action form. */ + + // Add each sample action to the preset. + foreach ($action_edits as $action => $edit) { + // Add the action. + $this->drupalPost($preset_path . '/add/' . $action, $edit, t('Add action')); + } + + /* Edit action form. */ + + // Revisit each form to make sure the action was saved. + $preset = image_preset_load($preset_name); + + foreach ($preset['actions'] as $iaid => $action) { + $this->drupalGet($preset_path . '/' . $iaid); + foreach ($action_edits[$action['action']] as $field => $value) { + $this->assertFieldByName($field, $value, t('The %field field in the %action action has the correct value of %value.', array('%field' => $field, '%action' => $action['action'], '%value' => $value))); + } + } + + /* Image preset overview form (ordering and renaming). */ + + // Confirm the order of actions is maintained according to the order we + // added the fields. + $action_edits_order = array_keys($action_edits); + $actions_order = array_values($preset['actions']); + $order_correct = TRUE; + foreach ($actions_order as $index => $action) { + if ($action_edits_order[$index] != $action['action']) { + $order_correct = FALSE; + } + } + $this->assertTrue($order_correct, t('The order of the actions is correctly set by default.')); + + // Test the preset overview form. + // Change the name of the preset and adjust the weights of actions. + $preset_name = strtolower($this->randomName(10)); + $weight = count($action_edits); + $edit = array( + 'name' => $preset_name, + ); + foreach ($preset['actions'] as $iaid => $action) { + $edit['actions[' . $iaid . '][weight]'] = $weight; + $weight--; + } + + // Create an image to make sure it gets flushed after saving. + $image_path = $this->createSampleImage($preset); + $this->assertEqual($this->getImageCount($preset), 1, t('Image preset %preset image %file successfully generated.', array('%preset' => $preset['name'], '%file' => $image_path))); + + $this->drupalPost($preset_path, $edit, t('Update preset')); + + // Note that after changing the preset name, the preset path is changed. + $preset_path = 'admin/settings/images/presets/' . $preset_name; + + // Check that the URL was updated. + $this->drupalGet($preset_path); + $this->assertResponse(200, t('Image preset %original renamed to %new', array('%original' => $preset['name'], '%new' => $preset_name))); + + // Check that the image was flushed after updating the preset. + // This is especially important when renaming the preset. Make sure that + // the old image directory has been deleted. + $this->assertEqual($this->getImageCount($preset), 0, t('Image preset %preset was flushed after renaming the preset and updating the order of actions.', array('%preset' => $preset['name']))); + + // Load the preset by the new name with the new weights. + $preset = image_preset_load($preset_name, NULL, TRUE); + + // Confirm the new preset order was saved. + $action_edits_order = array_reverse($action_edits_order); + $actions_order = array_values($preset['actions']); + $order_correct = TRUE; + foreach ($actions_order as $index => $action) { + if ($action_edits_order[$index] != $action['action']) { + $order_correct = FALSE; + } + } + $this->assertTrue($order_correct, t('The order of the actions is correctly set by default.')); + + /* Image action deletion form. */ + + // Create an image to make sure it gets flushed after deleting an action. + $image_path = $this->createSampleImage($preset); + $this->assertEqual($this->getImageCount($preset), 1, t('Image preset %preset image %file successfully generated.', array('%preset' => $preset['name'], '%file' => $image_path))); + + // Test action deletion form. + $action = array_pop($preset['actions']); + $this->drupalPost($preset_path . '/' . $action['iaid'] . '/delete', array(), t('Delete')); + $this->assertRaw(t('The image action %name has been deleted.', array('%name' => $action['name'])), t('Image action deleted.')); + + // Check that the preset was flushed after deleting an action. + $this->assertEqual($this->getImageCount($preset), 0, t('Image preset %preset was flushed after deleting an action.', array('%preset' => $preset['name']))); + + /* Preset flush form. */ + + // Create an image to make sure it gets flushed after deleting an action. + $image_path = $this->createSampleImage($preset); + $this->assertEqual($this->getImageCount($preset), 1, t('Image preset %preset image %file successfully generated.', array('%preset' => $preset['name'], '%file' => $image_path))); + + $this->drupalPost($preset_path . '/flush', array(), t('Flush')); + $this->assertRaw(t('Preset %name was flushed.', array('%name' => $preset['name'])), t('Image preset %preset flush form submitted.')); + + $this->assertEqual($this->getImageCount($preset), 0, t('Image preset %preset was flushed after submitting the flush form.', array('%preset' => $preset['name']))); + + /* Preset deletion form. */ + + // Delete the preset. + $this->drupalPost($preset_path . '/delete', array(), t('Delete')); + + // Confirm the preset directory has been removed. + $directory = file_directory_path() . '/presets/' . $preset_name; + $this->assertFalse(is_dir($directory), t('Image preset %preset directory removed on preset deletion.', array('%preset' => $preset['name']))); + + // Confirm the preset is no longer available. + $this->assertFalse(image_preset_load($preset_name), t('Image preset %preset successfully deleted.', array('%preset' => $preset['name']))); + + } +} + +/** * Tests custom access denied functionality. */ class AccessDeniedTestCase extends DrupalWebTestCase { Index: modules/simpletest/drupal_web_test_case.php =================================================================== RCS file: /cvs/drupal/drupal/modules/simpletest/drupal_web_test_case.php,v retrieving revision 1.84 diff -u -r1.84 drupal_web_test_case.php --- modules/simpletest/drupal_web_test_case.php 13 Feb 2009 00:39:01 -0000 1.84 +++ modules/simpletest/drupal_web_test_case.php 16 Feb 2009 09:10:41 -0000 @@ -902,7 +902,7 @@ global $db_prefix, $user; if (preg_match('/simpletest\d+/', $db_prefix)) { // Delete temporary files directory and reset files directory path. - file_unmanaged_delete_recursive(file_directory_path()); + //file_unmanaged_delete_recursive(file_directory_path()); variable_set('file_directory_path', $this->originalFileDirectory); // Remove all prefixed tables (all the tables in the schema). Index: modules/user/user.admin.inc =================================================================== RCS file: /cvs/drupal/drupal/modules/user/user.admin.inc,v retrieving revision 1.37 diff -u -r1.37 user.admin.inc --- modules/user/user.admin.inc 3 Feb 2009 18:55:32 -0000 1.37 +++ modules/user/user.admin.inc 16 Feb 2009 09:10:46 -0000 @@ -508,10 +508,17 @@ '#maxlength' => 255, '#description' => t('URL of picture to display for users with no custom picture selected. Leave blank for none.'), ); + $form['pictures']['settings']['user_picture_preset'] = array( + '#type' => 'select', + '#title' => t('Upload picture preset'), + '#options' => image_preset_options(), + '#default_value' => variable_get('user_picture_preset', ''), + '#description' => t('Select an image preset to scale user images down without modifying the original image. Image presets may be set up in the Image handling administration area.', array('!url' => url('admin/settings/images'))), + ); $form['pictures']['settings']['user_picture_dimensions'] = array( '#type' => 'textfield', '#title' => t('Picture maximum dimensions'), - '#default_value' => variable_get('user_picture_dimensions', '85x85'), + '#default_value' => variable_get('user_picture_dimensions', '1024x1024'), '#size' => 15, '#maxlength' => 10, '#description' => t('Maximum dimensions for pictures, in pixels.'), @@ -519,7 +526,7 @@ $form['pictures']['settings']['user_picture_file_size'] = array( '#type' => 'textfield', '#title' => t('Picture maximum file size'), - '#default_value' => variable_get('user_picture_file_size', '30'), + '#default_value' => variable_get('user_picture_file_size', '800'), '#size' => 15, '#maxlength' => 10, '#description' => t('Maximum file size for pictures, in kB.'), Index: modules/user/user.test =================================================================== RCS file: /cvs/drupal/drupal/modules/user/user.test,v retrieving revision 1.28 diff -u -r1.28 user.test --- modules/user/user.test 9 Feb 2009 07:36:15 -0000 1.28 +++ modules/user/user.test 16 Feb 2009 09:10:47 -0000 @@ -547,8 +547,14 @@ // user's profile page. $text = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $test_dim)); $this->assertRaw($text, t('Image was resized.')); + if ($preset = variable_get('user_picture_preset', '')) { + $url_path = image_preset_path($preset, $pic_path, FALSE); + } + else { + $url_path = $pic_path; + } $alt = t("@user's picture", array('@user' => $this->user->name)); - $this->assertRaw(theme('image', $pic_path, $alt, $alt, '', FALSE), t("Image is displayed in user's edit page")); + $this->assertRaw(theme('image', $url_path, $alt, $alt, NULL, FALSE), t("Image is displayed in user's edit page")); // Check if file is located in proper directory. $this->assertTrue(is_file($pic_path), t("File is located in proper directory")); @@ -568,7 +574,9 @@ $this->drupalLogin($this->user); - $image = current($this->drupalGetTestFiles('image')); + // Images are sorted first by size then by name. We need an image + // bigger than 1 KB so we'll grab the last one. + $image = end($this->drupalGetTestFiles('image')); $info = image_get_info($image->filename); // Set new variables: valid dimensions, invalid filesize. @@ -679,8 +687,14 @@ $pic_path = $this->saveUserPicture($image); // Check if image is displayed in user's profile page. + if ($preset = variable_get('user_picture_preset', '')) { + $url_path = image_preset_path($preset, $pic_path, FALSE); + } + else { + $url_path = $pic_path; + } $this->drupalGet('user'); - $this->assertRaw($pic_path, t("Image is displayed in user's profile page")); + $this->assertRaw($url_path, t("Image is displayed in user's profile page")); // Check if file is located in proper directory. $this->assertTrue(is_file($pic_path), t('File is located in proper directory')); Index: modules/user/user.module =================================================================== RCS file: /cvs/drupal/drupal/modules/user/user.module,v retrieving revision 1.963 diff -u -r1.963 user.module --- modules/user/user.module 9 Feb 2009 07:36:15 -0000 1.963 +++ modules/user/user.module 16 Feb 2009 09:10:47 -0000 @@ -493,8 +493,8 @@ // If required, validate the uploaded picture. $validators = array( 'file_validate_is_image' => array(), - 'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')), - 'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024), + 'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '1024x1024')), + 'file_validate_size' => array(variable_get('user_picture_file_size', '800') * 1024), ); // Save the file as a temporary file. @@ -1062,7 +1062,12 @@ } if (isset($filepath)) { $alt = t("@user's picture", array('@user' => $account->name ? $account->name : variable_get('anonymous', t('Anonymous')))); - $variables['picture'] = theme('image', $filepath, $alt, $alt, '', FALSE); + if ($preset = variable_get('user_picture_preset', '')) { + $variables['picture'] = theme('image_preset', $preset, $filepath, $alt, $alt, NULL, FALSE); + } + else { + $variables['picture'] = theme('image', $filepath, $alt, $alt, NULL, FALSE); + } if (!empty($account->uid) && user_access('access user profiles')) { $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE); $variables['picture'] = l($variables['picture'], "user/$account->uid", $attributes); @@ -1771,7 +1776,7 @@ '#type' => 'file', '#title' => t('Upload picture'), '#size' => 48, - '#description' => t('Your virtual face or picture. Maximum dimensions are %dimensions pixels and the maximum size is %size kB.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'), '%size' => variable_get('user_picture_file_size', '30'))) . ' ' . variable_get('user_picture_guidelines', ''), + '#description' => t('Your virtual face or picture. Maximum dimensions are %dimensions pixels and the maximum size is %size kB.', array('%dimensions' => variable_get('user_picture_dimensions', '1024x1024'), '%size' => variable_get('user_picture_file_size', '800'))) . ' ' . variable_get('user_picture_guidelines', ''), ); $form['#validate'][] = 'user_validate_picture'; } @@ -1863,6 +1868,9 @@ db_delete('users')->condition('uid', $account->uid)->execute(); db_delete('users_roles')->condition('uid', $account->uid)->execute(); db_delete('authmap')->condition('uid', $account->uid)->execute(); + if ($account->picture) { + file_delete($account->picture); + } drupal_set_message(t('%name has been deleted.', array('%name' => $account->name))); watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE); break; Index: includes/image.inc =================================================================== RCS file: /cvs/drupal/drupal/includes/image.inc,v retrieving revision 1.28 diff -u -r1.28 image.inc --- includes/image.inc 30 Dec 2008 16:43:14 -0000 1.28 +++ includes/image.inc 16 Feb 2009 09:10:40 -0000 @@ -36,7 +36,7 @@ * Return a list of available toolkits. * * @return - * An array of toolkit name => descriptive title. + * An array with the toolkit names as keys and the descriptions as values. */ function image_get_available_toolkits() { // hook_image_toolkits returns an array of toolkit names. @@ -46,10 +46,12 @@ foreach ($toolkits as $name) { $function = 'image_' . $name . '_info'; if (drupal_function_exists($function)) { - $info = $function(); - $output[$info['name']] = $info['title']; + if ($info = $function()) { + $output[$info['name']] = $info['title']; + } } } + return $output; } @@ -62,14 +64,13 @@ function image_get_toolkit() { static $toolkit; - if (!$toolkit) { + if (!isset($toolkit)) { + $toolkits = image_get_available_toolkits(); $toolkit = variable_get('image_toolkit', 'gd'); - if (isset($toolkit) && - drupal_function_exists("image_" . $toolkit . "_resize")) { - } - elseif (!drupal_function_exists("image_gd_check_settings") || - !image_gd_check_settings()) { - $toolkit = FALSE; + if (!isset($toolkits[$toolkit]) || !drupal_function_exists('image_' . $toolkit . '_open')) { + // The selected toolkit isn't available so return the first one found. If + // none are available this will return FALSE. + $toolkit = reset($toolkits); } } @@ -87,19 +88,16 @@ * Mixed values (typically Boolean indicating successful operation). */ function image_toolkit_invoke($method, $params = array()) { - if ($toolkit = image_get_toolkit()) { - $function = 'image_' . $toolkit . '_' . $method; - if (drupal_function_exists($function)) { - return call_user_func_array($function, $params); - } - else { - watchdog('php', 'The selected image handling toolkit %toolkit can not correctly process %function.', array('%toolkit' => $toolkit, '%function' => $function), WATCHDOG_ERROR); - return FALSE; - } + // If the image specifies a toolkit, use that one. + $toolkit = isset($params[0]->toolkit) ? $params[0]->toolkit : image_get_toolkit(); + $function = 'image_' . $toolkit . '_' . $method; + if (drupal_function_exists($function)) { + return call_user_func_array($function, $params); } + watchdog('image', 'The selected image handling toolkit %toolkit can not correctly process %function.', array('%toolkit' => $toolkit, '%function' => $function), WATCHDOG_ERROR); + return FALSE; } - /** * Get details about an image. * @@ -108,8 +106,8 @@ * @return * FALSE, if the file could not be found or is not an image. Otherwise, a * keyed array containing information about the image: - * 'width' - Width in pixels. - * 'height' - Height in pixels. + * 'width' - Width, in pixels. + * 'height' - Height, in pixels. * 'extension' - Commonly used file extension for the image. * 'mime_type' - MIME type ('image/jpeg', 'image/gif', 'image/png'). * 'file_size' - File size in bytes. @@ -137,133 +135,770 @@ } /** - * Scales an image to the exact width and height given. Achieves the - * target aspect ratio by cropping the original image equally on both - * sides, or equally on the top and bottom. This function is, for - * example, useful to create uniform sized avatars from larger images. + * Scales an image to the exact width and height given. + * + * This function achieves the target aspect ratio by cropping the original image + * equally on both sides, or equally on the top and bottom. This function is + * useful to create uniform sized avatars from larger images. * * The resulting image always has the exact target dimensions. * - * @param $source - * The file path of the source image. - * @param $destination - * The file path of the destination image. + * @param $image + * An image object returned by image_open(). * @param $width * The target width, in pixels. * @param $height * The target height, in pixels. * @return * TRUE or FALSE, based on success. + * + * @see image_open() */ -function image_scale_and_crop($source, $destination, $width, $height) { - $info = image_get_info($source); +function image_scale_and_crop(stdClass $image, $width, $height) { + $aspect = $image->info['height'] / $image->info['width']; + if (empty($height)) $height = $width / $aspect; + if (empty($width)) $width = $height * $aspect; + + $scale = max($width / $image->info['width'], $height / $image->info['height']); + $x = (int) round(($image->info['width'] * $scale - $width) / 2); + $y = (int) round(($image->info['height'] * $scale - $height) / 2); - $scale = max($width / $info['width'], $height / $info['height']); - $x = round(($info['width'] * $scale - $width) / 2); - $y = round(($info['height'] * $scale - $height) / 2); - - if (image_toolkit_invoke('resize', array($source, $destination, $info['width'] * $scale, $info['height'] * $scale))) { - return image_toolkit_invoke('crop', array($destination, $destination, $x, $y, $width, $height)); + if (image_resize($image, $image->info['width'] * $scale, $image->info['height'] * $scale)) { + return image_crop($image, $x, $y, $width, $height); } return FALSE; } /** - * Scales an image to the given width and height while maintaining aspect - * ratio. + * Scales an image to the given width and height while maintaining aspect ratio. * * The resulting image can be smaller for one or both target dimensions. * - * @param $source - * The file path of the source image. - * @param $destination - * The file path of the destination image. + * @param $image + * An image object returned by image_open(). * @param $width * The target width, in pixels. * @param $height * The target height, in pixels. + * @param $upscale + * Allow upscaling. * @return * TRUE or FALSE, based on success. + * + * @see image_open() + * @see image_scale_and_crop() */ -function image_scale($source, $destination, $width, $height) { - $info = image_get_info($source); +function image_scale(stdClass $image, $width = NULL, $height = NULL, $upscale = FALSE) { + $aspect = $image->info['height'] / $image->info['width']; - // Don't scale up. - if ($width >= $info['width'] && $height >= $info['height']) { - return FALSE; + if ($upscale) { + // Set width/height according to aspect ratio if either is empty. + $width = !empty($width) ? $width : $height / $aspect; + $height = !empty($height) ? $height : $width / $aspect; + } + else { + // Set impossibly large values if the width and height aren't set. + $width = !empty($width) ? $width : 9999999; + $height = !empty($height) ? $height : 9999999; + + // Don't scale up. + if (round($width) >= $image->info['width'] && round($height) >= $image->info['height']) { + return TRUE; + } } - $aspect = $info['height'] / $info['width']; if ($aspect < $height / $width) { - $width = (int)min($width, $info['width']); - $height = (int)round($width * $aspect); + $height = $width * $aspect; } else { - $height = (int)min($height, $info['height']); - $width = (int)round($height / $aspect); + $width = $height / $aspect; } - return image_toolkit_invoke('resize', array($source, $destination, $width, $height)); + return image_resize($image, $width, $height); } /** * Resize an image to the given dimensions (ignoring aspect ratio). * - * @param $source - * The file path of the source image. - * @param $destination - * The file path of the destination image. + * @param $image + * An image object returned by image_open(). * @param $width * The target width, in pixels. * @param $height * The target height, in pixels. - * @return + * @param $toolkit + * An optional override of the default image toolkit. + * @return * TRUE or FALSE, based on success. + * + * @see image_open() */ -function image_resize($source, $destination, $width, $height) { - return image_toolkit_invoke('resize', array($source, $destination, $width, $height)); +function image_resize(stdClass $image, $width, $height) { + $width = (int) round($width); + $height = (int) round($height); + + return image_toolkit_invoke('resize', array($image, $width, $height), $image->toolkit); } /** * Rotate an image by the given number of degrees. * - * @param $source - * The file path of the source image. - * @param $destination - * The file path of the destination image. + * @param $image + * An image object returned by image_open(). * @param $degrees * The number of (clockwise) degrees to rotate the image. * @param $background * An hexadecimal integer specifying the background color to use for the * uncovered area of the image after the rotation. E.g. 0x000000 for black, - * 0xff00ff for magenta, and 0xffffff for white. + * 0xff00ff for magenta, and 0xffffff for white. For images that support + * transparency, this will default to transparent. Otherwise it will + * be white. * @return * TRUE or FALSE, based on success. + * + * @see image_open() */ -function image_rotate($source, $destination, $degrees, $background = 0x000000) { - return image_toolkit_invoke('rotate', array($source, $destination, $degrees, $background)); +function image_rotate(stdClass $image, $degrees, $background = NULL) { + return image_toolkit_invoke('rotate', array($image, $degrees, $background)); } /** * Crop an image to the rectangle specified by the given rectangle. * - * @param $source - * The file path of the source image. - * @param $destination - * The file path of the destination image. + * @param $image + * An image object returned by image_open(). * @param $x - * The top left co-ordinate, in pixels, of the crop area (x axis value). + * The top left coordinate of the crop area (x axis value). * @param $y - * The top left co-ordinate, in pixels, of the crop area (y axis value). + * The top left coordinate of the crop area (y axis value). * @param $width * The target width, in pixels. * @param $height * The target height, in pixels. * @return * TRUE or FALSE, based on success. + * + * @see image_open() + * @see image_scale_and_crop() + */ +function image_crop(stdClass $image, $x, $y, $width, $height) { + $aspect = $image->info['height'] / $image->info['width']; + if (empty($height)) $height = $width / $aspect; + if (empty($width)) $width = $height * $aspect; + + $width = (int) round($width); + $height = (int) round($height); + + return image_toolkit_invoke('crop', array($image, $x, $y, $width, $height), $image->toolkit); +} + +/** + * Convert an image to grayscale. + * + * @param $image + * An image object returned by image_open(). + * @return + * TRUE or FALSE, based on success. + * + * @see image_open() + */ +function image_desaturate(stdClass $image) { + return image_toolkit_invoke('desaturate', array($image), $image->toolkit); +} + + +/** + * Open an image file and return an image object. + * + * Any changes to the file are not saved until image_close() is called. + * + * @param $file + * Path to an image file. + * @param $toolkit + * An optional, image toolkit name to override the default. + * @return + * An image object or FALSE if there was a problem opening the file. The + * image object has the following properties: + * - 'source' - The original file path. + * - 'info' - The array of information returned by image_get_info() + * - 'toolkit' - The name of the image toolkit requested when the image was + * opened. + * Image tookits may add additional properties. The caller is advised not to + * monkey about with them. + * + * @see image_close() + * @see image_get_info() + */ +function image_open($file, $toolkit = FALSE) { + if (!$toolkit) { + $toolkit = image_get_toolkit(); + } + if ($toolkit) { + $image = new stdClass(); + $image->source = $file; + $image->info = image_get_info($file); + $image->toolkit = $toolkit; + if ($image = image_toolkit_invoke('open', array($image), $toolkit)) { + return $image; + } + } + return FALSE; +} + +/** + * Close the image and save the changes to a file. + * + * @param $image + * An image object returned by image_open(). The object's 'info' property + * will be updated if the file is saved successfully. + * @param $destination + * Destination path where the image should be saved. If it is empty the + * original image file will be overwritten. + * @return + * TRUE or FALSE, based on success. + * + * @see image_open() + */ +function image_close(stdClass $image, $destination = NULL) { + if (empty($destination)) { + $destination = $image->source; + } + if ($return = image_toolkit_invoke('close', array($image, $destination), $image->toolkit)) { + // Clear the cached file size and refresh the image information. + clearstatcache(); + $image->info = image_get_info($destination); + + if (@chmod($destination, 0664)) { + return $return; + } + watchdog('image', 'Could not set permissions on destination file: %file', array('%file' => $destination)); + } + return FALSE; +} + +/** + * Get an array of all presets and their settings. + * + * @param $reset + * If set to TRUE the internal preset cache will be cleared. + * @return + * Array of presets array($pid => array('id' => integer, 'name' => string)). + */ +function image_presets($reset = FALSE) { + static $presets = array(); + + // Clear caches if $reset is true; + if ($reset) { + $presets = array(); + cache_clear_all('image_presets', 'cache'); + } + + // Grab from cache or build the array. + if ($cache = cache_get('image_presets', 'cache')) { + $presets = $cache->data; + } + else { + $result = db_query('SELECT * FROM {image_presets} ORDER BY name'); + while ($preset = db_fetch_array($result)) { + $presets[$preset['name']] = $preset; + $presets[$preset['name']]['actions'] = image_preset_actions($preset, $reset); + } + cache_set('image_presets', $presets); + } + + return $presets; +} + +/** + * Get an array of image presets suitable for using as select list options. + */ +function image_preset_options($include_empty = TRUE) { + $presets = image_presets(); + $options = array(); + if ($include_empty && !empty($presets)) { + $options[''] = t(''); + } + $options = array_merge($options, drupal_map_assoc(array_keys($presets))); + if (empty($options)) { + $options[''] = t('No defined presets'); + } + return $options; +} + +/** + * Load a preset by preset name or ID. May be used as a loader for menu items. + * + * @param $name + * The name of the preset. + * @param $pid + * Optional. The numeric id of a preset if the name is not known. + * + * @return + * An image preset with the format of + * array('name' => string, 'id' => integer). + * If the preset name or ID is not valid, an empty array is returned. + */ +function image_preset_load($name = NULL, $pid = NULL, $reset = FALSE) { + $presets = image_presets($reset); + + // If retrieving by name. + if (isset($name) && isset($presets[$name])) { + return $presets[$name]; + } + + // If retrieving by PID. + if (isset($pid)) { + foreach ($presets as $name => $preset) { + if ($preset['ipid'] == $pid) { + return $preset; + } + } + } + + // Otherwise the preset was not found. + return FALSE; +} + +/** + * Save an image preset. + * + * @param preset + * An image preset array. + * @return + * A preset array. In the case of a new preset, 'ipid' will be populated. + */ +function image_preset_save($preset) { + if (isset($preset['ipid']) && is_numeric($preset['ipid'])) { + // Load the existing preset to make sure we account for renamed presets. + $old_preset = image_preset_load(NULL, $preset['ipid']); + image_preset_flush($old_preset); + drupal_write_record('image_presets', $preset, 'ipid'); + } + else { + drupal_write_record('image_presets', $preset); + } + + // Reset presets cache. + image_presets(TRUE); + menu_rebuild(); + + return $preset; +} + +/** + * Delete an image preset. + * + * @param preset + * An image preset array. + */ +function image_preset_delete($preset) { + image_preset_flush($preset); + db_query('DELETE FROM {image_actions} where ipid = %d', $preset['ipid']); + db_query('DELETE FROM {image_presets} where ipid = %d', $preset['ipid']); + image_presets(TRUE); + menu_rebuild(); + return TRUE; +} + +/** + * Load all the actions for an image preset. + * + * @param $preset + * An image preset array. + * @param $reset + * If set to TRUE the internal cache image actions will be reset. + */ +function image_preset_actions($preset, $reset = FALSE) { + static $actions; + + if ($reset || !isset($actions)) { + $actions = array(); + $definitions = image_action_definitions($reset); + $result = db_query('SELECT * FROM {image_actions} where ipid = %d ORDER BY weight ASC', $preset['ipid']); + while ($action = db_fetch_array($result)) { + $action['data'] = unserialize($action['data']); + $action = array_merge($definitions[$action['action']], $action); + $actions[$preset['ipid']][$action['iaid']] = $action; + } + } + + return isset($actions[$preset['ipid']]) ? $actions[$preset['ipid']] : array(); +} + +/** + * Flush cached media for a preset. + * + * @param $preset + * An image preset. + */ +function image_preset_flush($preset) { + $preset_directory = realpath(file_directory_path() .'/presets/'. $preset['name']); + if (is_dir($preset_directory)) { + file_unmanaged_delete_recursive($preset_directory); + } +} + +/** + * Return a complete URL to an image when using a preset. + * + * @param $preset_name + * The name of the preset to be used with this image. + * @param $path + * The path to the image. + * @return + * The complete absolute URL to a preset image. + */ +function image_preset_url($preset_name, $path) { + $path = _image_strip_file_directory($path); + return file_create_url(file_create_path() .'/presets/'. $preset_name .'/'. $path); +} + +/** + * Return a relative path to an image when using a preset. + * + * @param $preset_name + * The name of the preset to be used with this image. + * @param $path + * The path to the image. + * @param $file_system + * Optional. By default this will return the file system path, which may be + * relative to the Drupal root or an absolute path on the server. If set to + * FALSE, this will return the Drupal path instead, suitable for requesting + * the image. + * @param + * The path to an image preset image. If $file_system is TRUE the path may + * be used in an is_file() request. If $file_system is FALSE the path may + * be used in theme('image_preset') or url() requests since it contains a + * Drupal path. + */ +function image_preset_path($preset_name, $path, $file_system = TRUE) { + $path = _image_strip_file_directory($path); + if ($file_system || variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC) { + return file_directory_path() . '/presets/' . $preset_name . '/' . $path; + } + else { + return 'system/files/presets/' . $preset_name . '/' . $path; + } +} + +/** + * Given an image preset and path, generate an image derivative. + * + * @param $preset_name + * The name of the preset to be used with this image. + * @param $path + * The path to the image. + * @return + * TRUE if the image is able to be generated successfully or FALSE if unable + * to create the image. This function may return NULL when the image + * generation is in progress but not complete. + */ +function image_preset_generate($preset_name, $path) { + $default_method = 'system_image_preset_request'; + $path = _image_strip_file_directory($path); + $method = variable_get('image_preset_generation_method', $default_method); + $preset = image_preset_load($preset_name); + + if (empty($preset)) { + watchdog('image', 'A derivative of the image %path could not be generated because the preset %preset does not exist.', array('%path' => $path, '%preset' => $preset_name), WATCHDOG_ERROR); + return FALSE; + } + + if (drupal_function_exists($method)) { + return $method($preset, $path); + } + else { + return $default_method($preset, $path); + } +} + +/** + * Create a new image based on an image preset. + * + * @param $preset + * An image preset array. + * @param $source + * Path of the source file. + * @param $destination + * Path of the destination file. + * @return + * TRUE if an image derivative is generated, FALSE if no image + * derivative is generated. NULL if the derivative is being generated. + */ +function image_preset_create_derivative($preset, $source, $destination) { + // Get the folder for the final location of this preset. + $directory = dirname($destination); + + // Build the destination folder tree if it doesn't already exists. + if (!file_check_directory($directory, FILE_CREATE_DIRECTORY) && !mkdir($directory, 0775, TRUE)) { + watchdog('image', 'Failed to create preset directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR); + return FALSE; + } + + if (!$image = image_open($source)) { + return FALSE; + } + + foreach ($preset['actions'] as $action) { + if (!empty($action['data'])) { + // Find new width and height of the image if available. This helps + // generate appropriate offsets when using keyword values like "center". + if (isset($action['data']['width'])) { + $width = image_filter_value('width', $action['data']['width'], $image->info['width'], $image->info['height']); + } + if (isset($action['data']['height'])) { + $height = image_filter_value('height', $action['data']['height'], $image->info['width'], $image->info['height']); + } + // Run image filter on each value. + foreach ($action['data'] as $key => $value) { + $action['data'][$key] = image_filter_value($key, $value, $image->info['width'], $image->info['height'], $width, $height); + } + } + image_action_apply($image, $action); + } + + if (!image_close($image, $destination)) { + if (file_exists($destination)) { + watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $destination), WATCHDOG_ERROR); + } + return FALSE; + } + + return TRUE; +} + +/** + * Clear cached versions of a specific file in all presets. + * + * @param $path + * The Drupal file path to the original image. + */ +function image_path_flush($path) { + $path = _image_strip_file_directory($path); + foreach (image_presets() as $preset) { + if ($path = file_create_path('presets/'. $preset['name'] .'/'. $path)) { + file_unmanaged_delete($path); + } + } +} + +/** + * Load all image actions from the database. + * + * @param $reset + * If TRUE, the internal list of actions will be regenerated. + */ +function image_actions($reset = FALSE) { + static $actions; + + if (!isset($actions) || $reset) { + $actions = array(); + + // Add database image actions. + $result = db_query('SELECT * FROM {image_actions}', NULL, array('fetch' => PDO::FETCH_ASSOC)); + foreach ($result as $action) { + $action['data'] = unserialize($action['data']); + $definition = image_action_definition_load($action['action'], $reset); + // Do not load actions whose definition cannot be found. + if ($definition) { + $action = array_merge($definition, $action); + $actions[$action['iaid']] = $action; + } + } + } + + return $actions; +} + +/** + * Pull in actions exposed by other modules using hook_image_actions(). + * + * @param $reset + * If TRUE, regenerate the internal cache of action definitions. + * @return + * An array of actions to be used when transforming images. + */ +function image_action_definitions($toolkit = NULL, $reset = FALSE) { + static $actions; + + if (!isset($toolkit)) { + $toolkit = image_get_toolkit(); + } + + if (!isset($actions) || $reset) { + if (!$reset && ($cache = cache_get('image_actions')) && !empty($cache->data)) { + $actions = $cache->data; + } + else { + $actions = array(); + foreach (module_implements('image_actions') as $module) { + foreach (module_invoke($module, 'image_actions') as $key => $action) { + // Ensure the current toolkit supports the + $action['module'] = $module; + $action['action'] = $key; + $action['data'] = isset($action['data']) ? $action['data'] : array(); + $actions[$key] = $action; + }; + } + uasort($actions, '_image_actions_definitions_sort'); + cache_set('image_actions', $actions); + } + } + + return $actions; +} + +/** + * Load the definition for an action. + * + * The action definition is a set of default values that applies to an action + * regardless of user settings. This definition consists of an array containing + * at least the following values: + * - action: The unique name for the action being performed. Usually prefixed + * with the name of the module providing the action. + * - module: The module providing the action. + * - description: A description of the action. + * + * @param $action + * The name of the action definition to load. + * @param $reset + * If TRUE, regenerate the internal cache of action definitions. + */ +function image_action_definition_load($action, $reset = FALSE) { + static $definition_cache; + + if (!isset($definition_cache[$action]) || $reset) { + $definitions = image_action_definitions($reset); + $definition = (isset($definitions[$action])) ? $definitions[$action] : array(); + $definition_cache[$action] = $definition; + } + + return isset($definition_cache[$action]) ? $definition_cache[$action] : FALSE; +} + +/** + * Load a single image action. + * + * @param $iaid + * The image action ID. + */ +function image_action_load($iaid) { + $actions = image_actions(); + return isset($actions[$iaid]) ? $actions[$iaid] : FALSE; +} + +/** + * Save an image action. + * + * @param $action + * An image action array. + */ +function image_action_save($action) { + if (!empty($action['iaid'])) { + drupal_write_record('image_actions', $action, 'iaid'); + } + else { + drupal_write_record('image_actions', $action); + } + $preset = image_preset_load(NULL, $action['ipid']); + image_preset_flush($preset); + image_presets(TRUE); + return $action; +} + +/** + * Delete an image action. + * + * @param $action + * An image action array. + */ +function image_action_delete($action) { + db_query('DELETE FROM {image_actions} WHERE iaid = %d', $action['iaid']); + $preset = image_preset_load(NULL, $action['ipid']); + image_preset_flush($preset); + image_presets(TRUE); +} + +/** + * Given an image object and action, perform the action on the file. + */ +function image_action_apply(&$image, $action) { + if (drupal_function_exists($action['function'])) { + return call_user_func($action['function'], $image, $action['data']); + } + return FALSE; +} + +/** + * Filter key word values such as 'top', 'right', 'center', and percentages. + * + * All returned values are in pixels relative to the passed in height and width. + */ +function image_filter_value($key, $value, $current_width, $current_height, $new_width = null, $new_height = null) { + switch ($key) { + case 'width': + $value = _image_filter_percent($value, $current_width); + break; + case 'height': + $value = _image_filter_percent($value, $current_height); + break; + case 'xoffset': + $value = _image_filter_keyword($value, $current_width, $new_width); + break; + case 'yoffset': + $value = _image_filter_keyword($value, $current_height, $new_height); + break; + } + return $value; +} + +/** + * Accept a percentage and return it in pixels. + */ +function _image_filter_percent($value, $current_pixels) { + if (strpos($value, '%') !== false) { + $value = str_replace('%', '', $value) * 0.01 * $current_pixels; + } + return $value; +} + +/** + * Accept a keyword (center, top, left, etc) and return it as an offset in pixels. + */ +function _image_filter_keyword($value, $current_pixels, $new_pixels) { + switch ($value) { + case 'top': + case 'left': + $value = 0; + break; + case 'bottom': + case 'right': + $value = $current_pixels - $new_pixels; + break; + case 'center': + $value = $current_pixels/2 - $new_pixels/2; + break; + } + return $value; +} + +/** + * Remove a possible leading file directory path from the given path. + */ +function _image_strip_file_directory($path) { + $dirpath = file_directory_path(); + $dirlen = strlen($dirpath); + if (substr($path, 0, $dirlen + 1) == $dirpath .'/') { + $path = substr($path, $dirlen + 1); + } + return $path; +} + +/** + * Internal function for sorting image action definitions through uasort(). */ -function image_crop($source, $destination, $x, $y, $width, $height) { - return image_toolkit_invoke('crop', array($source, $destination, $x, $y, $width, $height)); +function _image_actions_definitions_sort($a, $b) { + return strcasecmp($a['name'], $b['name']); } /** Index: includes/theme.inc =================================================================== RCS file: /cvs/drupal/drupal/includes/theme.inc,v retrieving revision 1.469 diff -u -r1.469 theme.inc --- includes/theme.inc 5 Feb 2009 03:42:56 -0000 1.469 +++ includes/theme.inc 16 Feb 2009 09:10:40 -0000 @@ -1211,11 +1211,44 @@ * A string containing the image tag. */ function theme_image($path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) { - if (!$getsize || (is_file($path) && (list($width, $height, $type, $image_attributes) = @getimagesize($path)))) { - $attributes = drupal_attributes($attributes); - $url = (url($path) == $path) ? $path : (base_path() . $path); - return '' . check_plain($alt) . ''; + if ($getsize && (is_file($path))) { + list($width, $height, $type, $image_attributes) = @getimagesize($path); } + + $attributes = drupal_attributes($attributes); + $url = (url($path) == $path) ? $path : (base_path() . $path); + return '' . check_plain($alt) . ''; +} + +/** + * Return a themed image using a specific image preset. + * + * @param $preset + * The name of the preset to be used to alter the original image. + * @param $path + * The path of the image file relative to the Drupal files directory. + * This function does not work with images outside the files directory nor + * with remotely hosted images. + * @param $alt + * The alternative text for text-based browsers. + * @param $title + * The title text is displayed when the image is hovered in some popular browsers. + * @param $attributes + * Associative array of attributes to be placed in the img tag. + * @param $getsize + * If set to TRUE, the image's dimension are fetched and added as width/height attributes. + * @return + * A string containing the image tag. + */ +function theme_image_preset($preset, $path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) { + $real_path = image_preset_path($preset, $path); + $url_path = image_preset_path($preset, $path, FALSE); + + if (!file_exists($real_path)) { + image_preset_generate($preset, $path); + } + + return theme('image', $url_path, $alt, $title, $attributes, $getsize); } /** Index: includes/file.inc =================================================================== RCS file: /cvs/drupal/drupal/includes/file.inc,v retrieving revision 1.157 diff -u -r1.157 file.inc --- includes/file.inc 13 Feb 2009 00:39:01 -0000 1.157 +++ includes/file.inc 16 Feb 2009 09:10:39 -0000 @@ -1183,13 +1183,11 @@ list($width, $height) = explode('x', $maximum_dimensions); if ($info['width'] > $width || $info['height'] > $height) { // Try to resize the image to fit the dimensions. - if (image_get_toolkit() && image_scale($file->filepath, $file->filepath, $width, $height)) { + if ($image = image_open($file->filepath)) { + image_scale($image, $width, $height); + image_close($image); + $file->filesize = $image->info['file_size']; drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions))); - - // Clear the cached filesize and refresh the image information. - clearstatcache(); - $info = image_get_info($file->filepath); - $file->filesize = $info['file_size']; } else { $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions)); Index: includes/common.inc =================================================================== RCS file: /cvs/drupal/drupal/includes/common.inc,v retrieving revision 1.867 diff -u -r1.867 common.inc --- includes/common.inc 13 Feb 2009 04:43:00 -0000 1.867 +++ includes/common.inc 16 Feb 2009 09:10:39 -0000 @@ -3546,6 +3546,9 @@ 'image' => array( 'arguments' => array('path' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE), ), + 'image_preset' => array( + 'arguments' => array('preset' => NULL, 'path' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE), + ), 'breadcrumb' => array( 'arguments' => array('breadcrumb' => NULL), ), Index: profiles/default/default.profile =================================================================== RCS file: /cvs/drupal/drupal/profiles/default/default.profile,v retrieving revision 1.37 diff -u -r1.37 default.profile --- profiles/default/default.profile 3 Feb 2009 12:30:14 -0000 1.37 +++ profiles/default/default.profile 16 Feb 2009 09:10:47 -0000 @@ -132,6 +132,25 @@ // Don't display date and author information for page nodes by default. variable_set('node_submitted_page', FALSE); + // Create an image preset. + $preset = array('name' => 'thumbnail_square'); + $preset = image_preset_save($preset); + $action = array( + 'ipid' => $preset['ipid'], + 'action' => 'system_image_scale_and_crop', + 'data' => array('width' => '85', 'height' => '85'), + ); + image_action_save($action); + + // Enable user picture support and set the default to a square thumbnail option. + variable_set('user_pictures', '1'); + variable_set('user_picture_preset', 'thumbnail_square'); + + $theme_settings = theme_get_settings(); + $theme_settings['toggle_node_user_picture'] = '1'; + $theme_settings['toggle_comment_user_picture'] = '1'; + variable_set('theme_settings', $theme_settings); + // Create a default vocabulary named "Tags", enabled for the 'article' content type. $description = st('Use tags to group articles on similar topics into categories.'); $help = st('Enter a comma-separated list of words.'); Index: modules/system/system.admin_image.inc =================================================================== RCS file: modules/system/system.admin_image.inc diff -N modules/system/system.admin_image.inc --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ modules/system/system.admin_image.inc 1 Jan 1970 00:00:00 -0000 @@ -0,0 +1,651 @@ + $preset['name'])); +} + +/** + * Form builder; Edit a preset name and action order. + * + * @ingroup forms + * @see system_image_preset_form_submit() + */ +function system_image_preset_form($form_state, $preset = array()) { + $form = array(); + + $form['name'] = array( + '#type' => 'textfield', + '#size' => '64', + '#title' => t('Preset name'), + '#default_value' => $preset['name'], + '#description' => t('The name is used in URLs for generated images. Only use lowercase alphanumeric characters, underscores (_), and hyphens (-) for preset names.'), + '#element_validate' => array('system_image_preset_name_validate'), + ); + + $form['preview'] = array( + '#markup' => theme('image_preset', 'thumbnail', 'picture.jpg'), + ); + + $form['ipid'] = array( + '#type' => 'value', + '#value' => $preset['ipid'], + ); + + $form['actions'] = array( + '#tree' => TRUE, + '#type' => 'markup', + '#theme' => 'admin_image_preset_actions', + ); + + foreach ($preset['actions'] as $i => $action) { + $action_form['name'] = array( + '#markup' => $action['name'], + ); + $action_form['action'] = array( + '#type' => 'value', + '#value' => $action['action'], + ); + $action_form['iaid'] = array( + '#type' => 'value', + '#value' => $action['iaid'], + ); + $action_form['ipid'] = array( + '#type' => 'value', + '#value' => $action['ipid'], + ); + + $action_form['summary'] = array( + '#markup' => theme($action['summary'], $action['data']), + ); + $action_form['data'] = array( + '#type' => 'value', + '#value' => $action['data'], + ); + $action_form['weight'] = array( + '#type' => 'weight', + '#default_value' => $action['weight'], + ); + $action_form['configure'] = array( + '#markup' => l(t('Configure'), 'admin/settings/images/presets/'. $preset['name'] .'/'. $action['iaid'] ), + ); + $action_form['remove'] = array( + '#markup' => l(t('Delete'), 'admin/settings/images/presets/'. $preset['name'] .'/'. $action['iaid'] .'/delete'), + ); + $form['actions'][$i] = $action_form; + } + + $form['new_actions'] = array( + '#tree' => TRUE, + '#type' => 'fieldset', + '#title' => t('New actions'), + '#collapsible' => FALSE, + '#theme' => 'admin_image_preset_actions_add', + '#preset' => $preset, + ); + + foreach (image_action_definitions() as $action => $definition) { + $form['new_actions'][$action] = array( + '#type' => 'value', + '#value' => $definition, + ); + } + + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Update preset'), + ); + return $form; +} + +/** + * Submit handler for saving an image preset name and action weights. + */ +function system_image_preset_form_submit($form, &$form_state) { + // Update the preset name if it has changed. + if ($preset = image_preset_load(NULL, $form_state['values']['ipid'])) { + if ($preset['name'] != $form_state['values']['name']) { + $preset['name'] = $form_state['values']['name']; + image_preset_save($preset); + $form_state['redirect'] = 'admin/settings/images/presets/' . $preset['name']; + } + } + + // Update the individual action weights. + foreach ($form_state['values']['actions'] as $new_action) { + $action = image_action_load($new_action['iaid']); + $action['weight'] = $new_action['weight']; + image_action_save($action); + } + + drupal_set_message('Changes to the preset have been saved.'); +} + +/** + * Form builder; Form for adding and editing image actions. + * + * @ingroup forms + * @see system_image_preset_add_form_submit() + */ +function system_image_preset_add_form($form_state) { + $form = array(); + $form['name'] = array( + '#type' => 'textfield', + '#size' => '64', + '#title' => t('Preset name'), + '#default_value' => '', + '#description' => t('The name is used in URLs for generated images. Only use lowercase alphanumeric characters, underscores (_), and hyphens (-) for preset names.'), + '#element_validate' => array('system_image_preset_name_validate'), + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Create new preset'), + ); + return $form; +} + +/** + * Submit handler for adding a new preset. + */ +function system_image_preset_add_form_submit($form, &$form_state) { + $preset = array('name' => $form_state['values']['name']); + $preset = image_preset_save($preset); + drupal_set_message(t('Preset %name was created.', array('%name' => $preset['name']))); + $form_state['redirect'] = 'admin/settings/images/presets/'. $preset['name']; +} + +/** + * Element validate function to ensure unique, safe preset names. + */ +function system_image_preset_name_validate($element, $form_state) { + // Check for duplicates. + $presets = image_presets(); + if (isset($presets[$element['#value']]) && (!isset($form_state['values']['ipid']) || $presets[$element['#value']]['ipid'] != $form_state['values']['ipid'])) { + form_set_error($element['#name'], t('The image preset name %name is already in use.', array('%name' => $element['#value']))); + } + + // Check for illegal characters in preset names. + if (preg_match('/[^0-9a-z_\-]/', $element['#value'])) { + form_set_error($element['#name'], t('Please only use lowercase alphanumeric characters, underscores (_), and hyphens (-) for preset names.')); + } +} + +/** + * Form builder; Form for deleting an image preset. + * + * @ingroup forms + * @see system_image_preset_delete_form_submit() + */ +function system_image_preset_delete_form($form_state, $preset = array()) { + if (empty($preset)) { + drupal_set_message(t('The specified preset was not found.'), 'error'); + drupal_goto('admin/settings/images/presets'); + } + + $form = array(); + $form['name'] = array( + '#type' => 'value', + '#value' => $preset['name'], + ); + $form['ipid'] = array( + '#type' => 'value', + '#value' => $preset['ipid'], + ); + return confirm_form( + $form, + t('Are you sure you want to delete the preset %preset?', array('%preset' => $preset['name'])), + 'admin/settings/images/presets', + t('All images that have been generated for this preset will be permanently deleted.'), + t('Delete'), t('Cancel') + ); +} + +/** + * Submit handler to delete an image preset. + */ +function system_image_preset_delete_form_submit($form, &$form_state) { + $preset = image_preset_load(NULL, $form_state['values']['ipid']); + image_preset_delete($preset); + drupal_set_message(t('Preset %name was deleted.', array('%name' => $preset['name']))); + $form_state['redirect'] = 'admin/settings/images/presets'; +} + +/** + * Form builder; Confirm flushing a preset's cached images. + * + * @ingroup forms + * @see system_image_preset_flush_form_submit() + */ +function system_image_preset_flush_form(&$form_state, $preset = array()) { + if (empty($preset)) { + drupal_set_message(t('The specified preset was not found.'), 'error'); + $form_state['redirect'] = 'admin/settings/images/presets'; + } + + $form = array(); + $form['name'] = array( + '#type' => 'value', + '#value' => $preset['name'], + ); + $form['ipid'] = array( + '#type' => 'value', + '#value' => $preset['ipid'], + ); + return confirm_form( + $form, + t('Are you sure you want to flush the %preset preset?', array('%preset' => $preset['name'])), + 'admin/settings/images/presets', + t('This will delete all the generated images for the %preset preset. Regenerating the images may cause a temporary increase in your server\'s load.', array('%preset' => $preset['name'])), + t('Flush'), t('Cancel') + ); +} + +/** + * Submit handler for flushing an image preset's cached files. + */ +function system_image_preset_flush_form_submit($form, &$form_state) { + $preset = image_preset_load(NULL, $form_state['values']['ipid']); + image_preset_flush($preset); + drupal_set_message(t('Preset %name was flushed.', array('%name' => $preset['name']))); + $form_state['redirect'] = 'admin/settings/images/presets'; +} + +/** + * Menu title callback; Title for editing, deleting, and adding image actions. + */ +function system_image_action_title($string, $action) { + return t($string, array('!name' => $action['name'])); +} + +/** + * Form builder; Form for adding and editing image actions. + * + * This form is used universally for editing all actions. Each action adds its + * own custom section to the form by calling the form function specified in + * hook_image_actions(). + * + * @ingroup forms + * @see hook_image_actions() + * @see system_image_actions() + * @see system_image_resize_form() + * @see system_image_scale_form() + * @see system_image_crop_form() + * @see system_image_desaturate_form() + * @see system_image_action_form_submit() + */ +function system_image_action_form($form_state, $preset, $action) { + $form = array( + '#tree' => TRUE, + '#image_preset' => $preset, + '#image_action' => $action, + ); + + if (drupal_function_exists($action['form'])) { + $form['data'] = call_user_func($action['form'], $action['data']); + } + + $form['submit'] = array( + '#type' => 'submit', + '#value' => isset($action['iaid']) ? t('Update action') : t('Add action'), + ); + return $form; +} + +/** + * Submit handler for updating an image action. + */ +function system_image_action_form_submit($form, &$form_state) { + $preset = $form['#image_preset']; + $action = array_merge($form['#image_action'], $form_state['values']); + $action['ipid'] = $preset['ipid']; + if (empty($action['iaid'])) { + $action['weight'] = count($preset['actions']); + } + + image_action_save($action); + drupal_set_message(t('The action was successfully updated.')); + $form_state['redirect'] = 'admin/settings/images/presets/' . $preset['name']; +} + +/** + * Form builder; Form for deleting an image action. + * + * @ingroup forms + * @see system_image_action_delete_form_submit() + */ +function system_image_action_delete_form($form_state, $preset, $action) { + $form = array( + '#image_preset' => $preset, + '#image_action' => $action, + ); + + $question = t('Are you sure you want to delete the @action action from the %preset preset?', array('%preset' => $preset['name'], '@action' => $action['name'])); + $description = t('Deleting this action will regenerate all images for the %preset preset.', array('%preset' => $preset['name'])); + return confirm_form($form, $question, 'admin/settings/images/presets/' . $preset['name'], $description, t('Delete')); +} + +/** + * Submit handler to delete an image action. + */ +function system_image_action_delete_form_submit($form, &$form_state) { + $preset = $form['#image_preset']; + $action = $form['#image_action']; + + image_action_delete($action); + drupal_set_message(t('The image action %name has been deleted.', array('%name' => $action['name']))); + $form_state['redirect'] = 'admin/settings/images/presets/'. $preset['name']; +} + +/** + * Form structure for the image resize form. + * + * Note that this is not a complete form, it only contains the portion of the + * form for configuring the resize options. Therefor it does not not need to + * include metadata about the action, nor a submit button. + * + * @param $data + * The current configuration for this resize action. + */ +function system_image_resize_form($action) { + $form['width'] = array( + '#type' => 'textfield', + '#title' => t('Width'), + '#default_value' => isset($action['width']) ? $action['width'] : '', + '#description' => t('Enter a width in pixels or as a percentage. i.e. 500 or 80%.'), + '#required' => TRUE, + ); + $form['height'] = array( + '#type' => 'textfield', + '#title' => t('Height'), + '#default_value' => isset($action['height']) ? $action['height'] : '', + '#description' => t('Enter a height in pixels or as a percentage. i.e. 500 or 80%.'), + '#required' => TRUE, + ); + return $form; +} + +/** + * Form structure for the image scale form. + * + * Note that this is not a complete form, it only contains the portion of the + * form for configuring the scale options. Therefor it does not not need to + * include metadata about the action, nor a submit button. + * + * @param $data + * The current configuration for this scale action. + */ +function system_image_scale_form($data) { + $form = system_image_resize_form($data); + $form['width']['#required'] = FALSE; + $form['height']['#required'] = FALSE; + $form['upscale'] = array( + '#type' => 'checkbox', + '#default_value' => (isset($data['upscale'])) ? $data['upscale'] : 0, + '#title' => t('Allow Upscaling'), + '#description' => t('Let scale make images larger than their original size'), + ); + return $form; +} + +/** + * Form structure for the image crop form. + * + * Note that this is not a complete form, it only contains the portion of the + * form for configuring the crop options. Therefor it does not not need to + * include metadata about the action, nor a submit button. + * + * @param $data + * The current configuration for this crop action. + */ +function system_image_crop_form($data) { + $data += array( + 'width' => '', + 'height' => '', + 'xoffset' => '', + 'yoffset' => '', + ); + + $form['width'] = array( + '#type' => 'textfield', + '#title' => t('Width'), + '#default_value' => $data['width'], + '#description' => t('Enter a width in pixels or as a percentage. i.e. 500 or 80%.'), + '#required' => TRUE, + ); + $form['height'] = array( + '#type' => 'textfield', + '#title' => t('Height'), + '#default_value' => $data['height'], + '#description' => t('Enter a height in pixels or as a percentage. i.e. 500 or 80%.'), + '#required' => TRUE, + ); + $form['xoffset'] = array( + '#type' => 'textfield', + '#title' => t('X offset'), + '#default_value' => $data['xoffset'], + '#description' => t('Enter an offset in pixels or use a keyword: left, center, or right.'), + ); + $form['yoffset'] = array( + '#type' => 'textfield', + '#title' => t('Y offset'), + '#default_value' => $data['yoffset'], + '#description' => t('Enter an offset in pixels or use a keyword: top, center, or bottom.'), + ); + return $form; +} + +function system_image_desaturate_form($data) { + return array( + '#markup' => '
' . t('The desaturate action needs no configuration. Confirm the addition of this action.') . '
', + ); +} + +/** + * Form structure for the image rotate form. + * + * Note that this is not a complete form, it only contains the portion of the + * form for configuring the rotate options. Therefor it does not not need to + * include metadata about the action, nor a submit button. + * + * @param $data + * The current configuration for this rotate action. + */ +function system_image_rotate_form($data) { + $form['degrees'] = array( + '#type' => 'textfield', + '#default_value' => (isset($data['degrees'])) ? $data['degrees'] : 0, + '#title' => t('Rotation angle'), + '#description' => t('The number of degrees the image should be rotated. Positive numbers are clockwise, negative are counter-clockwise.'), + '#required' => TRUE, + ); + $form['random'] = array( + '#type' => 'checkbox', + '#default_value' => (isset($data['random'])) ? $data['random'] : 0, + '#title' => t('Randomize'), + '#description' => t('Randomize the rotation angle for each image. The angle specified above is used as a maximum.'), + ); + $form['bgcolor'] = array( + '#type' => 'textfield', + '#default_value' => (isset($data['bgcolor'])) ? $data['bgcolor'] : '#FFFFFF', + '#title' => t('Background color'), + '#description' => t('The background color to use for exposed areas of the image. Use web-style hex colors (#FFFFFF for white, #000000 for black).'), + '#required' => TRUE, + ); + return $form; +} + +/** + * Display the page containing the list of image presets. + * + * @param $presets + * An array of all the image presets returned by image_get_presets(). + * @see image_get_presets() + * @ingroup themeable + */ +function theme_admin_image_presets($presets) { + $header = array(t('Preset name'), array('data' => t('Operations'), 'colspan' => 3)); + $rows = array(); + foreach ($presets as $preset) { + $row = array(); + $row[] = l($preset['name'], 'admin/settings/images/presets/'. $preset['name']); + $link_attributes = array( + 'attributes' => array( + 'class' => 'image-preset-link', + ), + ); + $row[] = l(t('Edit'), 'admin/settings/images/presets/'. $preset['name'], $link_attributes); + $row[] = l(t('Delete'), 'admin/settings/images/presets/'. $preset['name'] .'/delete', $link_attributes); + $row[] = l(t('Flush'), 'admin/settings/images/presets/'. $preset['name'] .'/flush', $link_attributes); + $rows[] = $row; + } + + if (empty($rows)) { + $rows[] = array(array( + 'colspan' => 4, + 'data' => t('There are currently no presets. Add a new one.', array('!url' => url('admin/settings/images/presets/add'))), + )); + } + + return theme('table', $header, $rows); +} + +/** + * Theme callback for listing the actions within a specific image preset. + * + * @param $form + * An associative array containing the structure of the actions group. + * @ingroup themeable + */ +function theme_admin_image_preset_actions($form) { + $header = array(t('Action'), t('Settings'), t('Weight'), '',''); + $rows = array(); + foreach(element_children($form) as $key) { + if (!is_numeric($key)) { + continue; + } + $row = array(); + $form[$key]['weight']['#attributes']['class'] = 'image-action-order-weight'; + $row[] = drupal_render($form[$key]['name']); + $row[] = drupal_render($form[$key]['summary']); + $row[] = drupal_render($form[$key]['weight']); + $row[] = drupal_render($form[$key]['configure']); + $row[] = drupal_render($form[$key]['remove']); + $rows[] = array( + 'data' => $row, + 'class' => 'draggable', + ); + } + + if (empty($rows)) { + $rows[] = array(array( + 'colspan' => 5, + 'data' => t('There are currently no actions in this preset. Add one by selecting a preset from the New actions fieldset.'), + )); + } + + $output = theme('table', $header, $rows, array('id' => 'image-preset-actions')); + drupal_add_tabledrag('image-preset-actions', 'order', 'sibling', 'image-action-order-weight'); + return $output; +} + +/** + * Theme callback for adding new actions to a preset. + * + * @param $form + * An associative array containing the structure of the new actions fieldset. + * @ingroup themeable + */ +function theme_admin_image_preset_actions_add($form) { + $preset = $form['#preset']; + + $output = '
'; + foreach (element_children($form) as $action) { + $definition = $form[$action]['#value']; + $output .= '
' . l(t('Add !action', array('!action' => $definition['name'])), 'admin/settings/images/presets/' . $preset['name'] . '/add/' . $action) . '
'; + $output .= '
' . $definition['description'] .'
'; + } + $output .= '
'; + return $output; +} + +/** + * Image resize action summary output. + * + * @param $data + * The current configuration for this resize action. + * @ingroup themeable + */ +function theme_system_image_resize_summary($data) { + return t('width') . ': '. $data['width'] . ', ' . t('height') . ': ' . $data['height']; +} + +/** + * Image scale action summary output. + * + * @param $data + * The current configuration for this scale action. + * @ingroup themeable + */ +function theme_system_image_scale_summary($data) { + $output = theme('system_image_resize_summary', $data); + $output .= ', ' . t('upscale') . ': '; + $output .= $data['upscale'] ? t('Yes') : t('No'); + return $output; +} + +/** + * Image crop action summary output. + * + * @param $data + * The current configuration for this crop action. + * @ingroup themeable + */ +function theme_system_image_crop_summary($data) { + $output = ''; + $output .= t('width') . ': ' . ($data['width'] ? $data['width'] : t('auto')); + $output .= ', ' . t('height') . ': ' . ($data['height'] ? $data['height'] : t('auto')); + $output .= ', ' . t('x offset') . ': ' . (empty($data['xoffset']) ? 0 : $data['xoffset']); + $output .= ', ' . t('y offset') . ': ' . (empty($data['yoffset']) ? 0 : $data['yoffset']); + return $output; +} + +/** + * Image desaturate action summary output. + * + * @param $data + * The current configuration for this desaturate action. + * @ingroup themeable + */ +function theme_system_image_desaturate_summary($data) { + return ''; +} + +/** + * Image rotate action summary output. + * + * @param $data + * The current configuration for this rotate action. + * @ingroup themeable + */ +function theme_system_image_rotate_summary($data) { + $output = t('degrees: ') . $data['degrees'] .', '; + $output .= t('randomize: ') . (($data['random']) ? t('Yes') : t('No')) .', '; + $output .= t('background: ') . $data['bgcolor']; + return $output; +} Index: modules/simpletest/tests/image.test =================================================================== RCS file: modules/simpletest/tests/image.test diff -N modules/simpletest/tests/image.test --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ modules/simpletest/tests/image.test 1 Jan 1970 00:00:00 -0000 @@ -0,0 +1,266 @@ + $value) { + if ($color_b[$key] != $value) { + return FALSE; + } + } + + return TRUE; + } + +} + +/** + * Test the core image manipulation functions. + */ +class ImageManipulateTestCase extends ImageTestCase { + function getInfo() { + return array( + 'name' => t('Image manipulation tests'), + 'description' => t('Check that core image manipulations work properly: scale, resize, rotate, crop, scale and crop, and desaturate.'), + 'group' => t('Image API'), + ); + } + + /** + * Function for finding a pixel's RGBa values. + */ + function getPixelColor($image, $x, $y) { + $color_index = imagecolorat($image->resource, $x, $y); + + $transparent_index = imagecolortransparent($image->resource); + if ($color_index == $transparent_index) { + return array(0, 0, 0, 127); + } + + return array_values(imagecolorsforindex($image->resource, $color_index)); + } + + /** + * Since PHP can't visually check that our images have been manipulated + * properly, build a list of expected color values for each of the corners and + * the expected height and widths for the final images. + */ + function testGdManipulations() { + // If GD isn't available don't bother testing this. + if (!drupal_function_exists('image_gd_check_settings') || !image_gd_check_settings()) { + $this->pass(t('Image manipulations for the GD toolkit were skipped because the GD toolkit is not available.')); + return; + } + + // Typically the corner colors will be unchanged. These colors are in the + // order of top-left, top-right, bottom-right, bottom-left. + $default_corners = array($this->red, $this->green, $this->blue, $this->transparent); + + // A list of files that will be tested. + $files = array( + 'image-test.png', + 'image-test.gif', + 'image-test.jpg', + ); + + // Setup a list of tests to perform on each type. + $operations = array( + 'resize' => array( + 'function' => 'resize', + 'arguments' => array(20, 10), + 'width' => 20, + 'height' => 10, + 'corners' => $default_corners, + ), + 'scale_x' => array( + 'function' => 'scale', + 'arguments' => array(20, NULL), + 'width' => 20, + 'height' => 10, + 'corners' => $default_corners, + ), + 'scale_y' => array( + 'function' => 'scale', + 'arguments' => array(NULL, 10), + 'width' => 20, + 'height' => 10, + 'corners' => $default_corners, + ), + 'upscale_x' => array( + 'function' => 'scale', + 'arguments' => array(80, NULL, TRUE), + 'width' => 80, + 'height' => 40, + 'corners' => $default_corners, + ), + 'upscale_y' => array( + 'function' => 'scale', + 'arguments' => array(NULL, 40, TRUE), + 'width' => 80, + 'height' => 40, + 'corners' => $default_corners, + ), + 'crop' => array( + 'function' => 'crop', + 'arguments' => array(12, 4, 16, 12), + 'width' => 16, + 'height' => 12, + 'corners' => array_fill(0, 4, $this->white), + ), + 'scale_and_crop' => array( + 'function' => 'scale_and_crop', + 'arguments' => array(10, 8), + 'width' => 10, + 'height' => 8, + 'corners' => array_fill(0, 4, $this->black), + ), + 'rotate_5' => array( + 'function' => 'rotate', + 'arguments' => array(5, 0xFF00FF), // Fuchsia background. + 'width' => 42, + 'height' => 24, + 'corners' => array_fill(0, 4, $this->fuchsia), + ), + 'rotate_90' => array( + 'function' => 'rotate', + 'arguments' => array(90, 0xFF00FF), // Fuchsia background. + 'width' => 20, + 'height' => 40, + 'corners' => array($this->fuchsia, $this->red, $this->green, $this->blue), + ), + 'rotate_transparent_5' => array( + 'function' => 'rotate', + 'arguments' => array(5), + 'width' => 42, + 'height' => 24, + 'corners' => array_fill(0, 4, $this->transparent), + ), + 'rotate_transparent_90' => array( + 'function' => 'rotate', + 'arguments' => array(90), + 'width' => 20, + 'height' => 40, + 'corners' => array($this->transparent, $this->red, $this->green, $this->blue), + ), + 'desaturate' => array( + 'function' => 'desaturate', + 'arguments' => array(), + 'height' => 20, + 'width' => 40, + // Grayscale corners are a bit funky. Each of the corners are a shade of + // gray. The values of these were determined simply by looking at the + // final image to see what desaturated colors end up being. + 'corners' => array(array_fill(0, 3, 76) + array(3 => 0), array_fill(0, 3, 149) + array(3 => 0), array_fill(0, 3, 29) + array(3 => 0), array_fill(0, 3, 0) + array(3 => 127)), + ), + ); + + foreach ($files as $file) { + foreach ($operations as $op => $values) { + // Open up a fresh image. + $image = image_open($this->originalFileDirectory . '/simpletest/' . $file, 'gd'); + if (!$image) { + $this->fail(t('Could not open image %file.', array('%file' => $file))); + continue 2; + } + + // Transparent GIFs and the imagefilter function don't work together. + // There is a todo in image.gd.inc to correct this. + if ($image->info['extension'] == 'gif') { + if ($op == 'desaturate') { + $values['corners'][3] = $this->white; + } + } + + // Perform our operation. + $function = 'image_'. $values['function']; + $arguments = array(); + $arguments[] = &$image; + $arguments = array_merge($arguments, $values['arguments']); + call_user_func_array($function, $arguments); + + // To keep from flooding the test with assert values, make a general value + // for whether each group of values fail. + $correct_dimensions_real = TRUE; + $correct_dimensions_object = TRUE; + $correct_colors = TRUE; + + // Check the real dimensions of the image first. + if (imagesy($image->resource) != $values['height'] || imagesx($image->resource) != $values['width']) { + $correct_dimensions_real = FALSE; + } + + // Check that the image object has an accurate record of the dimensions. + if ($image->info['width'] != $values['width'] || $image->info['height'] != $values['height']) { + $correct_dimensions_object = FALSE; + } + // Now check each of the corners to assure actions like rotate and + // desaturate had the proper actions apply. + foreach ($values['corners'] as $key => $corner) { + // Get the location of the corner. + switch ($key) { + case 0: + $x = 0; + $y = 0; + break; + case 1: + $x = $values['width'] - 1; + $y = 0; + break; + case 2: + $x = $values['width'] - 1; + $y = $values['height'] - 1; + break; + case 3: + $x = 0; + $y = $values['height'] - 1; + break; + } + $color = $this->getPixelColor($image, $x, $y); + $correct_colors = $this->colorsAreEqual($color, $corner); + } + + $directory = file_directory_path() . '/imagetests'; + file_check_directory($directory, FILE_CREATE_DIRECTORY); + image_close($image,$directory . '/' . $op . '.' . $image->info['extension']); + + $this->assertTrue($correct_dimensions_real, t('Image %file after %action action has proper dimensions.', array('%file' => $file, '%action' => $op))); + $this->assertTrue($correct_dimensions_object, t('Image %file object after %action action is reporting the proper height and width values.', array('%file' => $file, '%action' => $op))); + // JPEG colors will always be messed up due to compression. + if ($image->info['extension'] != 'jpg') { + $this->assertTrue($correct_colors, t('Image %file object after %action action has the correct color placement.', array('%file' => $file, '%action' => $op))); + } + } + } + + } +} Index: modules/system/image.actions.inc =================================================================== RCS file: modules/system/image.actions.inc diff -N modules/system/image.actions.inc --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ modules/system/image.actions.inc 1 Jan 1970 00:00:00 -0000 @@ -0,0 +1,228 @@ + array( + 'name' => t('Resize'), + 'description' => t('Resize an image to an exact set of dimensions, ignoring aspect ratio.'), + 'function' => 'system_image_resize_image', + 'form' => 'system_image_resize_form', + 'summary' => 'system_image_resize_summary', + ), + 'system_image_scale' => array( + 'name' => t('Scale'), + 'description' => t('Resize an image maintaining the original aspect-ratio (only one value necessary).'), + 'function' => 'system_image_scale_image', + 'form' => 'system_image_scale_form', + 'summary' => 'system_image_scale_summary', + ), + 'system_image_scale_and_crop' => array( + 'name' => t('Scale and Crop'), + 'description' => t('Resize an image maintaining the original aspect-ratio, then crop the center of the image to specific dimensions.'), + 'function' => 'system_image_scale_and_crop_image', + 'form' => 'system_image_resize_form', + 'summary' => 'system_image_resize_summary', + ), + 'system_image_crop' => array( + 'name' => t('Crop'), + 'description' => t('Crop an image to the rectangle specified by the given offsets and dimensions.'), + 'function' => 'system_image_crop_image', + 'form' => 'system_image_crop_form', + 'summary' => 'system_image_crop_summary', + ), + 'system_image_desaturate' => array( + 'name' => t('Desaturate'), + 'description' => t('Convert an image to grey scale.'), + 'function' => 'system_image_desaturate_image', + 'form' => 'system_image_desaturate_form', + 'summary' => 'system_image_desaturate_summary', + ), + 'system_image_rotate' => array( + 'name' => t('Rotate'), + 'description' => t('Rotate an image.'), + 'function' => 'system_image_rotate_image', + 'form' => 'system_image_rotate_form', + 'summary' => 'system_image_rotate_summary', + ), + ); + + return $actions; +} + +/** + * Image generation callback. Given a preset and image, request a derivative. + * + * This function is the default image generation method. It generates individual + * images by making separate HTTP requests to system/image/[preset_name]/[path]. + * This allows each image to have it's own PHP instance (and memory limit) for + * generation of the new images. Upon successful generation, the path to the + * new image is returned. + * + * @param $preset + * An image preset array. + * @param $path + * The local path of the image to be generated, excluding the files directory. + * @return + * TRUE if the image was generated successfully. Returns FALSE if the image + * could not be generated. + * @see system_image_preset_generate() + * @see image_preset_generate() + */ +function system_image_preset_request($preset, $path) { + $destination = image_preset_path($preset['name'], $path); + $image_url = image_preset_url($preset['name'], $path); + + // Check that the image doesn't already exist. If so, just return the path. + if (file_exists($destination)) { + return TRUE; + } + + // Generate an HTTP request to create the new image. + $token = drupal_get_token($path); + $session_id = session_id(); + $url = url('system/image/' . $preset['name'] . '/' . $path, array('absolute' => TRUE, 'query' => array('token' => $token, 'session' => $session_id))); + $result = drupal_http_request($url); + + return $result->code == 200 ? TRUE : FALSE; +} + +/** + * Menu callback. Given a preset and image path, generate a derivative. + */ +function system_image_preset_generate() { + $args = func_get_args(); + $preset_name = array_shift($args); + $preset = image_preset_load($preset_name); + $path = implode('/', $args); + $source = file_create_path($path); + $destination = image_preset_path($preset['name'], $path); + + if (!$preset || !isset($_GET['session']) || !isset($_GET['token'])) { + drupal_access_denied(); + exit(); + } + + // We have to manually generate the valid token, since the server is making + // the request as an anonymous user with a different session id. + $valid_token = md5($_GET['session'] . $path . drupal_get_private_key()); + + if ($_GET['token'] != $valid_token) { + drupal_access_denied(); + exit; + } + + $result = image_preset_create_derivative($preset, $source, $destination); + switch ($result) { + case TRUE: + print 'TRUE'; + exit; + case FALSE: + print 'FALSE'; + exit; + case NULL: + print 'IN PROGRESS'; + exit; + } +} + +/** + * Access callback for system/image. Ensure this request is made by Drupal. + */ +function system_image_preset_generate_access() { + $args = func_get_args(); + $preset_name = array_shift($args); + $path = implode('/', $args); + + return isset($_GET['token']) && drupal_valid_token($_GET['token'], $path); +} + +function system_image_resize_image(&$image, $data) { + if (!image_resize($image, $data['width'], $data['height'])) { + watchdog('image', 'Image resize failed. image: %image, data: %data.', array('%path' => $image, '%data' => print_r($data, TRUE)), WATCHDOG_ERROR); + return FALSE; + } + return TRUE; +} + +function system_image_scale_image(&$image, $data) { + // Set impossibly large values if the width and height aren't set. + $data['width'] = $data['width'] ? $data['width'] : 9999999; + $data['height'] = $data['height'] ? $data['height'] : 9999999; + if (!image_scale($image, $data['width'], $data['height'], $data['upscale'])) { + watchdog('image', 'Image scale failed. image: %image, data: %data.', array('%path' => $image, '%data' => print_r($data, true)), WATCHDOG_ERROR); + return FALSE; + } + return TRUE; +} + +function system_image_crop_image(&$image, $data) { + if (!image_crop($image, $data['xoffset'], $data['yoffset'], $data['width'], $data['height'])) { + watchdog('image', 'Image crop failed. image: %image, data: %data.', array('%path' => $image, '%data' => print_r($data, true)), WATCHDOG_ERROR); + return FALSE; + } + return TRUE; +} + +function system_image_scale_and_crop_image(&$image, $data) { + if (!image_scale_and_crop($image, $data['width'], $data['height'])) { + watchdog('image', t('Image scale and crop failed. image: %image, data: %data.', array('%path' => $image, '%data' => print_r($data, true))), WATCHDOG_ERROR); + return FALSE; + } + return TRUE; +} + +function system_image_desaturate_image(&$image, $data) { + if (!image_desaturate($image)) { + watchdog('image', 'Image desaturate failed. image: %image, data: %data.', array('%path' => $image, '%data' => print_r($data, true)), WATCHDOG_ERROR); + return FALSE; + } + return TRUE; +} + +function system_image_rotate_image(&$image, $data) { + // Set sane default values. + $data['degrees'] = $data['degrees'] ? $data['degrees'] : 0; + $data['random'] = $data['random'] ? $data['random'] : false; + $data['bgcolor'] = $data['bgcolor'] ? $data['bgcolor'] : '#FFFFFF'; + + // Manipulate the if we need to randomize, and convert to proper colors. + $data['bgcolor'] = '0x'. str_replace('#', '', $data['bgcolor']); + + if (!empty($data['random'])) { + $degrees = abs((float)$data['degrees']); + $data['degrees'] = rand(-1 * $degrees, $degrees); + } + + if (!image_rotate($image, $data['degrees'], $data['bgcolor'])) { + watchdog('image', t('Image rotate failed. image: %image, data: %data.', array('%path' => $image, '%data' => print_r($data, true))), WATCHDOG_ERROR); + return FALSE; + } + return TRUE; +}