image.module

You are here

  1. 7 modules/image/image.module
  2. 8 core/modules/image/image.module

Exposes global functionality for creating image styles.

Functions

Namesort descending Description
image_default_style_revert Reverts the changes made by users to a default image style.
image_default_style_save Saves a default image style to the database.
image_effects Loads all image effects from the database.
image_effect_apply Applies an image effect to the image object.
image_effect_definitions Returns a set of image effects.
image_effect_definition_load Loads the definition for an image effect.
image_effect_delete Deletes an image effect.
image_effect_load Loads a single image effect.
image_effect_save Saves an image effect.
image_field_delete_field Implements hook_field_delete_field().
image_field_delete_instance Implements hook_field_delete_instance().
image_field_update_field Implements hook_field_update_field().
image_field_update_instance Implements hook_field_update_instance().
image_file_delete Implements hook_file_delete().
image_file_download Implements hook_file_download().
image_file_move Implements hook_file_move().
image_filter_keyword Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
image_flush_caches Implements hook_flush_caches().
image_form_system_file_system_settings_alter Implements hook_form_FORM_ID_alter().
image_help Implements hook_help().
image_image_default_styles Implements hook_image_default_styles().
image_image_style_delete Implements hook_image_style_delete().
image_image_style_save Implements hook_image_style_save().
image_menu Implements hook_menu().
image_path_flush Clears cached versions of a specific file in all styles.
image_permission Implements hook_permission().
image_styles Gets an array of all styles and their settings.
image_style_create_derivative Creates a new image derivative based on an image style.
image_style_delete Deletes an image style.
image_style_deliver Page callback: Generates a derivative, given a style and image path.
image_style_effects Loads all the effects for an image style.
image_style_flush Flushes cached media for a style.
image_style_load Loads a style by style name or ID.
image_style_options Gets an array of image styles suitable for using as select list options.
image_style_path Returns the URI of an image when using a style.
image_style_path_token Generates a token to protect an image style derivative.
image_style_save Saves an image style.
image_style_transform_dimensions Determines the dimensions of the styled image.
image_style_url Returns the URL for an image derivative given a style and image path.
image_system_file_system_settings_submit Form submission handler for system_file_system_settings().
image_theme Implements hook_theme().
theme_image_style Returns HTML for an image using a specific image style.
_image_effect_definitions_sort Internal function for sorting image effect definitions through uasort().

Constants

Namesort descending Description
IMAGE_DERIVATIVE_TOKEN The name of the query parameter for image derivative tokens.
IMAGE_STORAGE_DEFAULT Image style constant for module-defined presets in code.
IMAGE_STORAGE_EDITABLE Image style constant to represent an editable preset.
IMAGE_STORAGE_MODULE Image style constant to represent any module-based preset.
IMAGE_STORAGE_NORMAL Image style constant for user presets in the database.
IMAGE_STORAGE_OVERRIDE Image style constant for user presets that override module-defined presets.

File

modules/image/image.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Exposes global functionality for creating image styles.
  5. */
  6. /**
  7. * Image style constant for user presets in the database.
  8. */
  9. define('IMAGE_STORAGE_NORMAL', 1);
  10. /**
  11. * Image style constant for user presets that override module-defined presets.
  12. */
  13. define('IMAGE_STORAGE_OVERRIDE', 2);
  14. /**
  15. * Image style constant for module-defined presets in code.
  16. */
  17. define('IMAGE_STORAGE_DEFAULT', 4);
  18. /**
  19. * Image style constant to represent an editable preset.
  20. */
  21. define('IMAGE_STORAGE_EDITABLE', IMAGE_STORAGE_NORMAL | IMAGE_STORAGE_OVERRIDE);
  22. /**
  23. * Image style constant to represent any module-based preset.
  24. */
  25. define('IMAGE_STORAGE_MODULE', IMAGE_STORAGE_OVERRIDE | IMAGE_STORAGE_DEFAULT);
  26. /**
  27. * The name of the query parameter for image derivative tokens.
  28. */
  29. define('IMAGE_DERIVATIVE_TOKEN', 'itok');
  30. // Load all Field module hooks for Image.
  31. require_once DRUPAL_ROOT . '/modules/image/image.field.inc';
  32. /**
  33. * Implements hook_help().
  34. */
  35. function image_help($path, $arg) {
  36. switch ($path) {
  37. case 'admin/help#image':
  38. $output = '';
  39. $output .= '<h3>' . t('About') . '</h3>';
  40. $output .= '<p>' . t('The Image module allows you to manipulate images on your website. It exposes a setting for using the <em>Image toolkit</em>, allows you to configure <em>Image styles</em> that can be used for resizing or adjusting images on display, and provides an <em>Image</em> field for attaching images to content. For more information, see the online handbook entry for <a href="@image">Image module</a>.', array('@image' => 'http://drupal.org/documentation/modules/image')) . '</p>';
  41. $output .= '<h3>' . t('Uses') . '</h3>';
  42. $output .= '<dl>';
  43. $output .= '<dt>' . t('Manipulating images') . '</dt>';
  44. $output .= '<dd>' . t('With the Image module you can scale, crop, resize, rotate and desaturate images without affecting the original image using <a href="@image">image styles</a>. When you change an image style, the module automatically refreshes all created images. Every image style must have a name, which will be used in the URL of the generated images. There are two common approaches to naming image styles (which you use will depend on how the image style is being applied):',array('@image' => url('admin/config/media/image-styles')));
  45. $output .= '<ul><li>' . t('Based on where it will be used: eg. <em>profile-picture</em>') . '</li>';
  46. $output .= '<li>' . t('Describing its appearance: eg. <em>square-85x85</em>') . '</li></ul>';
  47. $output .= t('After you create an image style, you can add effects: crop, scale, resize, rotate, and desaturate (other contributed modules provide additional effects). For example, by combining effects as crop, scale, and desaturate, you can create square, grayscale thumbnails.') . '<dd>';
  48. $output .= '<dt>' . t('Attaching images to content as fields') . '</dt>';
  49. $output .= '<dd>' . t("Image module also allows you to attach images to content as fields. To add an image field to a <a href='@content-type'>content type</a>, go to the content type's <em>manage fields</em> page, and add a new field of type <em>Image</em>. Attaching images to content this way allows image styles to be applied and maintained, and also allows you more flexibility when theming.", array('@content-type' => url('admin/structure/types'))) . '</dd>';
  50. $output .= '</dl>';
  51. return $output;
  52. case 'admin/config/media/image-styles':
  53. return '<p>' . t('Image styles commonly provide thumbnail sizes by scaling and cropping images, but can also add various effects before an image is displayed. When an image is displayed with a style, a new file is created and the original image is left unchanged.') . '</p>';
  54. case 'admin/config/media/image-styles/edit/%/add/%':
  55. $effect = image_effect_definition_load($arg[7]);
  56. return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
  57. case 'admin/config/media/image-styles/edit/%/effects/%':
  58. $effect = ($arg[5] == 'add') ? image_effect_definition_load($arg[6]) : image_effect_load($arg[6], $arg[4]);
  59. return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
  60. }
  61. }
  62. /**
  63. * Implements hook_menu().
  64. */
  65. function image_menu() {
  66. $items = array();
  67. // Generate image derivatives of publicly available files.
  68. // If clean URLs are disabled, image derivatives will always be served
  69. // through the menu system.
  70. // If clean URLs are enabled and the image derivative already exists,
  71. // PHP will be bypassed.
  72. $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  73. $items[$directory_path . '/styles/%image_style'] = array(
  74. 'title' => 'Generate image style',
  75. 'page callback' => 'image_style_deliver',
  76. 'page arguments' => array(count(explode('/', $directory_path)) + 1),
  77. 'access callback' => TRUE,
  78. 'type' => MENU_CALLBACK,
  79. );
  80. // Generate and deliver image derivatives of private files.
  81. // These image derivatives are always delivered through the menu system.
  82. $items['system/files/styles/%image_style'] = array(
  83. 'title' => 'Generate image style',
  84. 'page callback' => 'image_style_deliver',
  85. 'page arguments' => array(3),
  86. 'access callback' => TRUE,
  87. 'type' => MENU_CALLBACK,
  88. );
  89. $items['admin/config/media/image-styles'] = array(
  90. 'title' => 'Image styles',
  91. 'description' => 'Configure styles that can be used for resizing or adjusting images on display.',
  92. 'page callback' => 'image_style_list',
  93. 'access arguments' => array('administer image styles'),
  94. 'file' => 'image.admin.inc',
  95. );
  96. $items['admin/config/media/image-styles/list'] = array(
  97. 'title' => 'List',
  98. 'description' => 'List the current image styles on the site.',
  99. 'page callback' => 'image_style_list',
  100. 'access arguments' => array('administer image styles'),
  101. 'type' => MENU_DEFAULT_LOCAL_TASK,
  102. 'weight' => 1,
  103. 'file' => 'image.admin.inc',
  104. );
  105. $items['admin/config/media/image-styles/add'] = array(
  106. 'title' => 'Add style',
  107. 'description' => 'Add a new image style.',
  108. 'page callback' => 'drupal_get_form',
  109. 'page arguments' => array('image_style_add_form'),
  110. 'access arguments' => array('administer image styles'),
  111. 'type' => MENU_LOCAL_ACTION,
  112. 'weight' => 2,
  113. 'file' => 'image.admin.inc',
  114. );
  115. $items['admin/config/media/image-styles/edit/%image_style'] = array(
  116. 'title' => 'Edit style',
  117. 'description' => 'Configure an image style.',
  118. 'page callback' => 'drupal_get_form',
  119. 'page arguments' => array('image_style_form', 5),
  120. 'access arguments' => array('administer image styles'),
  121. 'file' => 'image.admin.inc',
  122. );
  123. $items['admin/config/media/image-styles/delete/%image_style'] = array(
  124. 'title' => 'Delete style',
  125. 'description' => 'Delete an image style.',
  126. 'load arguments' => array(NULL, (string) IMAGE_STORAGE_NORMAL),
  127. 'page callback' => 'drupal_get_form',
  128. 'page arguments' => array('image_style_delete_form', 5),
  129. 'access arguments' => array('administer image styles'),
  130. 'file' => 'image.admin.inc',
  131. );
  132. $items['admin/config/media/image-styles/revert/%image_style'] = array(
  133. 'title' => 'Revert style',
  134. 'description' => 'Revert an image style.',
  135. 'load arguments' => array(NULL, (string) IMAGE_STORAGE_OVERRIDE),
  136. 'page callback' => 'drupal_get_form',
  137. 'page arguments' => array('image_style_revert_form', 5),
  138. 'access arguments' => array('administer image styles'),
  139. 'file' => 'image.admin.inc',
  140. );
  141. $items['admin/config/media/image-styles/edit/%image_style/effects/%image_effect'] = array(
  142. 'title' => 'Edit image effect',
  143. 'description' => 'Edit an existing effect within a style.',
  144. 'load arguments' => array(5, (string) IMAGE_STORAGE_EDITABLE),
  145. 'page callback' => 'drupal_get_form',
  146. 'page arguments' => array('image_effect_form', 5, 7),
  147. 'access arguments' => array('administer image styles'),
  148. 'file' => 'image.admin.inc',
  149. );
  150. $items['admin/config/media/image-styles/edit/%image_style/effects/%image_effect/delete'] = array(
  151. 'title' => 'Delete image effect',
  152. 'description' => 'Delete an existing effect from a style.',
  153. 'load arguments' => array(5, (string) IMAGE_STORAGE_EDITABLE),
  154. 'page callback' => 'drupal_get_form',
  155. 'page arguments' => array('image_effect_delete_form', 5, 7),
  156. 'access arguments' => array('administer image styles'),
  157. 'file' => 'image.admin.inc',
  158. );
  159. $items['admin/config/media/image-styles/edit/%image_style/add/%image_effect_definition'] = array(
  160. 'title' => 'Add image effect',
  161. 'description' => 'Add a new effect to a style.',
  162. 'load arguments' => array(5),
  163. 'page callback' => 'drupal_get_form',
  164. 'page arguments' => array('image_effect_form', 5, 7),
  165. 'access arguments' => array('administer image styles'),
  166. 'file' => 'image.admin.inc',
  167. );
  168. return $items;
  169. }
  170. /**
  171. * Implements hook_theme().
  172. */
  173. function image_theme() {
  174. return array(
  175. // Theme functions in image.module.
  176. 'image_style' => array(
  177. 'variables' => array(
  178. 'style_name' => NULL,
  179. 'path' => NULL,
  180. 'width' => NULL,
  181. 'height' => NULL,
  182. 'alt' => '',
  183. 'title' => NULL,
  184. 'attributes' => array(),
  185. ),
  186. ),
  187. // Theme functions in image.admin.inc.
  188. 'image_style_list' => array(
  189. 'variables' => array('styles' => NULL),
  190. ),
  191. 'image_style_effects' => array(
  192. 'render element' => 'form',
  193. ),
  194. 'image_style_preview' => array(
  195. 'variables' => array('style' => NULL),
  196. ),
  197. 'image_anchor' => array(
  198. 'render element' => 'element',
  199. ),
  200. 'image_resize_summary' => array(
  201. 'variables' => array('data' => NULL),
  202. ),
  203. 'image_scale_summary' => array(
  204. 'variables' => array('data' => NULL),
  205. ),
  206. 'image_crop_summary' => array(
  207. 'variables' => array('data' => NULL),
  208. ),
  209. 'image_rotate_summary' => array(
  210. 'variables' => array('data' => NULL),
  211. ),
  212. // Theme functions in image.field.inc.
  213. 'image_widget' => array(
  214. 'render element' => 'element',
  215. ),
  216. 'image_formatter' => array(
  217. 'variables' => array('item' => NULL, 'path' => NULL, 'image_style' => NULL),
  218. ),
  219. );
  220. }
  221. /**
  222. * Implements hook_permission().
  223. */
  224. function image_permission() {
  225. return array(
  226. 'administer image styles' => array(
  227. 'title' => t('Administer image styles'),
  228. 'description' => t('Create and modify styles for generating image modifications such as thumbnails.'),
  229. ),
  230. );
  231. }
  232. /**
  233. * Implements hook_form_FORM_ID_alter().
  234. */
  235. function image_form_system_file_system_settings_alter(&$form, &$form_state) {
  236. $form['#submit'][] = 'image_system_file_system_settings_submit';
  237. }
  238. /**
  239. * Form submission handler for system_file_system_settings().
  240. *
  241. * Adds a menu rebuild after the public file path has been changed, so that the
  242. * menu router item depending on that file path will be regenerated.
  243. */
  244. function image_system_file_system_settings_submit($form, &$form_state) {
  245. if ($form['file_public_path']['#default_value'] !== $form_state['values']['file_public_path']) {
  246. variable_set('menu_rebuild_needed', TRUE);
  247. }
  248. }
  249. /**
  250. * Implements hook_flush_caches().
  251. */
  252. function image_flush_caches() {
  253. return array('cache_image');
  254. }
  255. /**
  256. * Implements hook_file_download().
  257. *
  258. * Control the access to files underneath the styles directory.
  259. */
  260. function image_file_download($uri) {
  261. $path = file_uri_target($uri);
  262. // Private file access for image style derivatives.
  263. if (strpos($path, 'styles/') === 0) {
  264. $args = explode('/', $path);
  265. // Discard the first part of the path (styles).
  266. array_shift($args);
  267. // Get the style name from the second part.
  268. $style_name = array_shift($args);
  269. // Remove the scheme from the path.
  270. array_shift($args);
  271. // Then the remaining parts are the path to the image.
  272. $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
  273. // Check that the file exists and is an image.
  274. if ($info = image_get_info($uri)) {
  275. // Check the permissions of the original to grant access to this image.
  276. $headers = module_invoke_all('file_download', $original_uri);
  277. // Confirm there's at least one module granting access and none denying access.
  278. if (!empty($headers) && !in_array(-1, $headers)) {
  279. return array(
  280. // Send headers describing the image's size, and MIME-type...
  281. 'Content-Type' => $info['mime_type'],
  282. 'Content-Length' => $info['file_size'],
  283. // By not explicitly setting them here, this uses normal Drupal
  284. // Expires, Cache-Control and ETag headers to prevent proxy or
  285. // browser caching of private images.
  286. );
  287. }
  288. }
  289. return -1;
  290. }
  291. // Private file access for the original files. Note that we only check access
  292. // for non-temporary images, since file.module will grant access for all
  293. // temporary files.
  294. $files = file_load_multiple(array(), array('uri' => $uri));
  295. if (count($files)) {
  296. $file = reset($files);
  297. if ($file->status) {
  298. return file_file_download($uri, 'image');
  299. }
  300. }
  301. }
  302. /**
  303. * Implements hook_file_move().
  304. */
  305. function image_file_move($file, $source) {
  306. // Delete any image derivatives at the original image path.
  307. image_path_flush($source->uri);
  308. }
  309. /**
  310. * Implements hook_file_delete().
  311. */
  312. function image_file_delete($file) {
  313. // Delete any image derivatives of this image.
  314. image_path_flush($file->uri);
  315. }
  316. /**
  317. * Implements hook_image_default_styles().
  318. */
  319. function image_image_default_styles() {
  320. $styles = array();
  321. $styles['thumbnail'] = array(
  322. 'label' => 'Thumbnail (100x100)',
  323. 'effects' => array(
  324. array(
  325. 'name' => 'image_scale',
  326. 'data' => array('width' => 100, 'height' => 100, 'upscale' => 1),
  327. 'weight' => 0,
  328. ),
  329. )
  330. );
  331. $styles['medium'] = array(
  332. 'label' => 'Medium (220x220)',
  333. 'effects' => array(
  334. array(
  335. 'name' => 'image_scale',
  336. 'data' => array('width' => 220, 'height' => 220, 'upscale' => 1),
  337. 'weight' => 0,
  338. ),
  339. )
  340. );
  341. $styles['large'] = array(
  342. 'label' => 'Large (480x480)',
  343. 'effects' => array(
  344. array(
  345. 'name' => 'image_scale',
  346. 'data' => array('width' => 480, 'height' => 480, 'upscale' => 0),
  347. 'weight' => 0,
  348. ),
  349. )
  350. );
  351. return $styles;
  352. }
  353. /**
  354. * Implements hook_image_style_save().
  355. */
  356. function image_image_style_save($style) {
  357. if (isset($style['old_name']) && $style['old_name'] != $style['name']) {
  358. $instances = field_read_instances();
  359. // Loop through all fields searching for image fields.
  360. foreach ($instances as $instance) {
  361. if ($instance['widget']['module'] == 'image') {
  362. $instance_changed = FALSE;
  363. foreach ($instance['display'] as $view_mode => $display) {
  364. // Check if the formatter involves an image style.
  365. if ($display['type'] == 'image' && $display['settings']['image_style'] == $style['old_name']) {
  366. // Update display information for any instance using the image
  367. // style that was just deleted.
  368. $instance['display'][$view_mode]['settings']['image_style'] = $style['name'];
  369. $instance_changed = TRUE;
  370. }
  371. }
  372. if ($instance['widget']['settings']['preview_image_style'] == $style['old_name']) {
  373. $instance['widget']['settings']['preview_image_style'] = $style['name'];
  374. $instance_changed = TRUE;
  375. }
  376. if ($instance_changed) {
  377. field_update_instance($instance);
  378. }
  379. }
  380. }
  381. }
  382. }
  383. /**
  384. * Implements hook_image_style_delete().
  385. */
  386. function image_image_style_delete($style) {
  387. image_image_style_save($style);
  388. }
  389. /**
  390. * Implements hook_field_delete_field().
  391. */
  392. function image_field_delete_field($field) {
  393. if ($field['type'] != 'image') {
  394. return;
  395. }
  396. // The value of a managed_file element can be an array if #extended == TRUE.
  397. $fid = (is_array($field['settings']['default_image']) ? $field['settings']['default_image']['fid'] : $field['settings']['default_image']);
  398. if ($fid && ($file = file_load($fid))) {
  399. file_usage_delete($file, 'image', 'default_image', $field['id']);
  400. }
  401. }
  402. /**
  403. * Implements hook_field_update_field().
  404. */
  405. function image_field_update_field($field, $prior_field, $has_data) {
  406. if ($field['type'] != 'image') {
  407. return;
  408. }
  409. // The value of a managed_file element can be an array if #extended == TRUE.
  410. $fid_new = (is_array($field['settings']['default_image']) ? $field['settings']['default_image']['fid'] : $field['settings']['default_image']);
  411. $fid_old = (is_array($prior_field['settings']['default_image']) ? $prior_field['settings']['default_image']['fid'] : $prior_field['settings']['default_image']);
  412. $file_new = $fid_new ? file_load($fid_new) : FALSE;
  413. if ($fid_new != $fid_old) {
  414. // Is there a new file?
  415. if ($file_new) {
  416. $file_new->status = FILE_STATUS_PERMANENT;
  417. file_save($file_new);
  418. file_usage_add($file_new, 'image', 'default_image', $field['id']);
  419. }
  420. // Is there an old file?
  421. if ($fid_old && ($file_old = file_load($fid_old))) {
  422. file_usage_delete($file_old, 'image', 'default_image', $field['id']);
  423. }
  424. }
  425. // If the upload destination changed, then move the file.
  426. if ($file_new && (file_uri_scheme($file_new->uri) != $field['settings']['uri_scheme'])) {
  427. $directory = $field['settings']['uri_scheme'] . '://default_images/';
  428. file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  429. file_move($file_new, $directory . $file_new->filename);
  430. }
  431. }
  432. /**
  433. * Implements hook_field_delete_instance().
  434. */
  435. function image_field_delete_instance($instance) {
  436. // Only act on image fields.
  437. $field = field_read_field($instance['field_name']);
  438. if ($field['type'] != 'image') {
  439. return;
  440. }
  441. // The value of a managed_file element can be an array if the #extended
  442. // property is set to TRUE.
  443. $fid = $instance['settings']['default_image'];
  444. if (is_array($fid)) {
  445. $fid = $fid['fid'];
  446. }
  447. // Remove the default image when the instance is deleted.
  448. if ($fid && ($file = file_load($fid))) {
  449. file_usage_delete($file, 'image', 'default_image', $instance['id']);
  450. }
  451. }
  452. /**
  453. * Implements hook_field_update_instance().
  454. */
  455. function image_field_update_instance($instance, $prior_instance) {
  456. // Only act on image fields.
  457. $field = field_read_field($instance['field_name']);
  458. if ($field['type'] != 'image') {
  459. return;
  460. }
  461. // The value of a managed_file element can be an array if the #extended
  462. // property is set to TRUE.
  463. $fid_new = $instance['settings']['default_image'];
  464. if (is_array($fid_new)) {
  465. $fid_new = $fid_new['fid'];
  466. }
  467. $fid_old = $prior_instance['settings']['default_image'];
  468. if (is_array($fid_old)) {
  469. $fid_old = $fid_old['fid'];
  470. }
  471. // If the old and new files do not match, update the default accordingly.
  472. $file_new = $fid_new ? file_load($fid_new) : FALSE;
  473. if ($fid_new != $fid_old) {
  474. // Save the new file, if present.
  475. if ($file_new) {
  476. $file_new->status = FILE_STATUS_PERMANENT;
  477. file_save($file_new);
  478. file_usage_add($file_new, 'image', 'default_image', $instance['id']);
  479. }
  480. // Delete the old file, if present.
  481. if ($fid_old && ($file_old = file_load($fid_old))) {
  482. file_usage_delete($file_old, 'image', 'default_image', $instance['id']);
  483. }
  484. }
  485. // If the upload destination changed, then move the file.
  486. if ($file_new && (file_uri_scheme($file_new->uri) != $field['settings']['uri_scheme'])) {
  487. $directory = $field['settings']['uri_scheme'] . '://default_images/';
  488. file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  489. file_move($file_new, $directory . $file_new->filename);
  490. }
  491. }
  492. /**
  493. * Clears cached versions of a specific file in all styles.
  494. *
  495. * @param $path
  496. * The Drupal file path to the original image.
  497. */
  498. function image_path_flush($path) {
  499. $styles = image_styles();
  500. foreach ($styles as $style) {
  501. $image_path = image_style_path($style['name'], $path);
  502. if (file_exists($image_path)) {
  503. file_unmanaged_delete($image_path);
  504. }
  505. }
  506. }
  507. /**
  508. * Gets an array of all styles and their settings.
  509. *
  510. * @return
  511. * An array of styles keyed by the image style ID (isid).
  512. * @see image_style_load()
  513. */
  514. function image_styles() {
  515. $styles = &drupal_static(__FUNCTION__);
  516. // Grab from cache or build the array.
  517. if (!isset($styles)) {
  518. if ($cache = cache_get('image_styles', 'cache')) {
  519. $styles = $cache->data;
  520. }
  521. else {
  522. $styles = array();
  523. // Select the module-defined styles.
  524. foreach (module_implements('image_default_styles') as $module) {
  525. $module_styles = module_invoke($module, 'image_default_styles');
  526. foreach ($module_styles as $style_name => $style) {
  527. $style['name'] = $style_name;
  528. $style['label'] = empty($style['label']) ? $style_name : $style['label'];
  529. $style['module'] = $module;
  530. $style['storage'] = IMAGE_STORAGE_DEFAULT;
  531. foreach ($style['effects'] as $key => $effect) {
  532. $definition = image_effect_definition_load($effect['name']);
  533. $effect = array_merge($definition, $effect);
  534. $style['effects'][$key] = $effect;
  535. }
  536. $styles[$style_name] = $style;
  537. }
  538. }
  539. // Select all the user-defined styles.
  540. $user_styles = db_select('image_styles', NULL, array('fetch' => PDO::FETCH_ASSOC))
  541. ->fields('image_styles')
  542. ->orderBy('name')
  543. ->execute()
  544. ->fetchAllAssoc('name', PDO::FETCH_ASSOC);
  545. // Allow the user styles to override the module styles.
  546. foreach ($user_styles as $style_name => $style) {
  547. $style['module'] = NULL;
  548. $style['storage'] = IMAGE_STORAGE_NORMAL;
  549. $style['effects'] = image_style_effects($style);
  550. if (isset($styles[$style_name]['module'])) {
  551. $style['module'] = $styles[$style_name]['module'];
  552. $style['storage'] = IMAGE_STORAGE_OVERRIDE;
  553. }
  554. $styles[$style_name] = $style;
  555. }
  556. drupal_alter('image_styles', $styles);
  557. cache_set('image_styles', $styles);
  558. }
  559. }
  560. return $styles;
  561. }
  562. /**
  563. * Loads a style by style name or ID.
  564. *
  565. * May be used as a loader for menu items.
  566. *
  567. * @param $name
  568. * The name of the style.
  569. * @param $isid
  570. * Optional. The numeric id of a style if the name is not known.
  571. * @param $include
  572. * If set, this loader will restrict to a specific type of image style, may be
  573. * one of the defined Image style storage constants.
  574. *
  575. * @return
  576. * An image style array containing the following keys:
  577. * - "isid": The unique image style ID.
  578. * - "name": The unique image style name.
  579. * - "effects": An array of image effects within this image style.
  580. * If the image style name or ID is not valid, an empty array is returned.
  581. * @see image_effect_load()
  582. */
  583. function image_style_load($name = NULL, $isid = NULL, $include = NULL) {
  584. $styles = image_styles();
  585. // If retrieving by name.
  586. if (isset($name) && isset($styles[$name])) {
  587. $style = $styles[$name];
  588. }
  589. // If retrieving by image style id.
  590. if (!isset($name) && isset($isid)) {
  591. foreach ($styles as $name => $database_style) {
  592. if (isset($database_style['isid']) && $database_style['isid'] == $isid) {
  593. $style = $database_style;
  594. break;
  595. }
  596. }
  597. }
  598. // Restrict to the specific type of flag. This bitwise operation basically
  599. // states "if the storage is X, then allow".
  600. if (isset($style) && (!isset($include) || ($style['storage'] & (int) $include))) {
  601. return $style;
  602. }
  603. // Otherwise the style was not found.
  604. return FALSE;
  605. }
  606. /**
  607. * Saves an image style.
  608. *
  609. * @param array $style
  610. * An image style array containing:
  611. * - name: A unique name for the style.
  612. * - isid: (optional) An image style ID.
  613. *
  614. * @return array
  615. * An image style array containing:
  616. * - name: An unique name for the style.
  617. * - old_name: The original name for the style.
  618. * - isid: An image style ID.
  619. * - is_new: TRUE if this is a new style, and FALSE if it is an existing
  620. * style.
  621. */
  622. function image_style_save($style) {
  623. if (isset($style['isid']) && is_numeric($style['isid'])) {
  624. // Load the existing style to make sure we account for renamed styles.
  625. $old_style = image_style_load(NULL, $style['isid']);
  626. image_style_flush($old_style);
  627. drupal_write_record('image_styles', $style, 'isid');
  628. if ($old_style['name'] != $style['name']) {
  629. $style['old_name'] = $old_style['name'];
  630. }
  631. }
  632. else {
  633. // Add a default label when not given.
  634. if (empty($style['label'])) {
  635. $style['label'] = $style['name'];
  636. }
  637. drupal_write_record('image_styles', $style);
  638. $style['is_new'] = TRUE;
  639. }
  640. // Let other modules update as necessary on save.
  641. module_invoke_all('image_style_save', $style);
  642. // Clear all caches and flush.
  643. image_style_flush($style);
  644. return $style;
  645. }
  646. /**
  647. * Deletes an image style.
  648. *
  649. * @param $style
  650. * An image style array.
  651. * @param $replacement_style_name
  652. * (optional) When deleting a style, specify a replacement style name so
  653. * that existing settings (if any) may be converted to a new style.
  654. *
  655. * @return
  656. * TRUE on success.
  657. */
  658. function image_style_delete($style, $replacement_style_name = '') {
  659. image_style_flush($style);
  660. db_delete('image_effects')->condition('isid', $style['isid'])->execute();
  661. db_delete('image_styles')->condition('isid', $style['isid'])->execute();
  662. // Let other modules update as necessary on save.
  663. $style['old_name'] = $style['name'];
  664. $style['name'] = $replacement_style_name;
  665. module_invoke_all('image_style_delete', $style);
  666. return TRUE;
  667. }
  668. /**
  669. * Loads all the effects for an image style.
  670. *
  671. * @param array $style
  672. * An image style array containing:
  673. * - isid: The unique image style ID that contains this image effect.
  674. *
  675. * @return array
  676. * An array of image effects associated with specified image style in the
  677. * format array('isid' => array()), or an empty array if the specified style
  678. * has no effects.
  679. * @see image_effects()
  680. */
  681. function image_style_effects($style) {
  682. $effects = image_effects();
  683. $style_effects = array();
  684. foreach ($effects as $effect) {
  685. if ($style['isid'] == $effect['isid']) {
  686. $style_effects[$effect['ieid']] = $effect;
  687. }
  688. }
  689. return $style_effects;
  690. }
  691. /**
  692. * Gets an array of image styles suitable for using as select list options.
  693. *
  694. * @param $include_empty
  695. * If TRUE a <none> option will be inserted in the options array.
  696. * @param $output
  697. * Optional flag determining how the options will be sanitized on output.
  698. * Leave this at the default (CHECK_PLAIN) if you are using the output of
  699. * this function directly in an HTML context, such as for checkbox or radio
  700. * button labels, and do not plan to sanitize it on your own. If using the
  701. * output of this function as select list options (its primary use case), you
  702. * should instead set this flag to PASS_THROUGH to avoid double-escaping of
  703. * the output (the form API sanitizes select list options by default).
  704. *
  705. * @return
  706. * Array of image styles with the machine name as key and the label as value.
  707. */
  708. function image_style_options($include_empty = TRUE, $output = CHECK_PLAIN) {
  709. $styles = image_styles();
  710. $options = array();
  711. if ($include_empty && !empty($styles)) {
  712. $options[''] = t('<none>');
  713. }
  714. foreach ($styles as $name => $style) {
  715. $options[$name] = ($output == PASS_THROUGH) ? $style['label'] : check_plain($style['label']);
  716. }
  717. if (empty($options)) {
  718. $options[''] = t('No defined styles');
  719. }
  720. return $options;
  721. }
  722. /**
  723. * Page callback: Generates a derivative, given a style and image path.
  724. *
  725. * After generating an image, transfer it to the requesting agent.
  726. *
  727. * @param $style
  728. * The image style
  729. */
  730. function image_style_deliver($style, $scheme) {
  731. $args = func_get_args();
  732. array_shift($args);
  733. array_shift($args);
  734. $target = implode('/', $args);
  735. // Check that the style is defined, the scheme is valid, and the image
  736. // derivative token is valid. (Sites which require image derivatives to be
  737. // generated without a token can set the 'image_allow_insecure_derivatives'
  738. // variable to TRUE to bypass the latter check, but this will increase the
  739. // site's vulnerability to denial-of-service attacks. To prevent this
  740. // variable from leaving the site vulnerable to the most serious attacks, a
  741. // token is always required when a derivative of a derivative is requested.)
  742. $valid = !empty($style) && file_stream_wrapper_valid_scheme($scheme);
  743. if (!variable_get('image_allow_insecure_derivatives', FALSE) || strpos(ltrim($target, '\/'), 'styles/') === 0) {
  744. $valid = $valid && isset($_GET[IMAGE_DERIVATIVE_TOKEN]) && $_GET[IMAGE_DERIVATIVE_TOKEN] === image_style_path_token($style['name'], $scheme . '://' . $target);
  745. }
  746. if (!$valid) {
  747. return MENU_ACCESS_DENIED;
  748. }
  749. $image_uri = $scheme . '://' . $target;
  750. $derivative_uri = image_style_path($style['name'], $image_uri);
  751. // If using the private scheme, let other modules provide headers and
  752. // control access to the file.
  753. if ($scheme == 'private') {
  754. if (file_exists($derivative_uri)) {
  755. file_download($scheme, file_uri_target($derivative_uri));
  756. }
  757. else {
  758. $headers = module_invoke_all('file_download', $image_uri);
  759. if (in_array(-1, $headers) || empty($headers)) {
  760. return MENU_ACCESS_DENIED;
  761. }
  762. if (count($headers)) {
  763. foreach ($headers as $name => $value) {
  764. drupal_add_http_header($name, $value);
  765. }
  766. }
  767. }
  768. }
  769. // Don't start generating the image if the derivative already exists or if
  770. // generation is in progress in another thread.
  771. $lock_name = 'image_style_deliver:' . $style['name'] . ':' . drupal_hash_base64($image_uri);
  772. if (!file_exists($derivative_uri)) {
  773. $lock_acquired = lock_acquire($lock_name);
  774. if (!$lock_acquired) {
  775. // Tell client to retry again in 3 seconds. Currently no browsers are known
  776. // to support Retry-After.
  777. drupal_add_http_header('Status', '503 Service Unavailable');
  778. drupal_add_http_header('Retry-After', 3);
  779. print t('Image generation in progress. Try again shortly.');
  780. drupal_exit();
  781. }
  782. }
  783. // Try to generate the image, unless another thread just did it while we were
  784. // acquiring the lock.
  785. $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
  786. if (!empty($lock_acquired)) {
  787. lock_release($lock_name);
  788. }
  789. if ($success) {
  790. $image = image_load($derivative_uri);
  791. file_transfer($image->source, array('Content-Type' => $image->info['mime_type'], 'Content-Length' => $image->info['file_size']));
  792. }
  793. else {
  794. watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
  795. drupal_add_http_header('Status', '500 Internal Server Error');
  796. print t('Error generating image.');
  797. drupal_exit();
  798. }
  799. }
  800. /**
  801. * Creates a new image derivative based on an image style.
  802. *
  803. * Generates an image derivative by creating the destination folder (if it does
  804. * not already exist), applying all image effects defined in $style['effects'],
  805. * and saving a cached version of the resulting image.
  806. *
  807. * @param $style
  808. * An image style array.
  809. * @param $source
  810. * Path of the source file.
  811. * @param $destination
  812. * Path or URI of the destination file.
  813. *
  814. * @return
  815. * TRUE if an image derivative was generated, or FALSE if the image derivative
  816. * could not be generated.
  817. *
  818. * @see image_style_load()
  819. */
  820. function image_style_create_derivative($style, $source, $destination) {
  821. // If the source file doesn't exist, return FALSE without creating folders.
  822. if (!$image = image_load($source)) {
  823. return FALSE;
  824. }
  825. // Get the folder for the final location of this style.
  826. $directory = drupal_dirname($destination);
  827. // Build the destination folder tree if it doesn't already exist.
  828. if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  829. watchdog('image', 'Failed to create style directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
  830. return FALSE;
  831. }
  832. foreach ($style['effects'] as $effect) {
  833. image_effect_apply($image, $effect);
  834. }
  835. if (!image_save($image, $destination)) {
  836. if (file_exists($destination)) {
  837. watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $destination), WATCHDOG_ERROR);
  838. }
  839. return FALSE;
  840. }
  841. return TRUE;
  842. }
  843. /**
  844. * Determines the dimensions of the styled image.
  845. *
  846. * Applies all of an image style's effects to $dimensions.
  847. *
  848. * @param $style_name
  849. * The name of the style to be applied.
  850. * @param $dimensions
  851. * Dimensions to be modified - an array with components width and height, in
  852. * pixels.
  853. */
  854. function image_style_transform_dimensions($style_name, array &$dimensions) {
  855. module_load_include('inc', 'image', 'image.effects');
  856. $style = image_style_load($style_name);
  857. if (!is_array($style)) {
  858. return;
  859. }
  860. foreach ($style['effects'] as $effect) {
  861. if (isset($effect['dimensions passthrough'])) {
  862. continue;
  863. }
  864. if (isset($effect['dimensions callback'])) {
  865. $effect['dimensions callback']($dimensions, $effect['data']);
  866. }
  867. else {
  868. $dimensions['width'] = $dimensions['height'] = NULL;
  869. }
  870. }
  871. }
  872. /**
  873. * Flushes cached media for a style.
  874. *
  875. * @param $style
  876. * An image style array.
  877. */
  878. function image_style_flush($style) {
  879. // Delete the style directory in each registered wrapper.
  880. $wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE);
  881. foreach ($wrappers as $wrapper => $wrapper_data) {
  882. if (file_exists($directory = $wrapper . '://styles/' . $style['name'])) {
  883. file_unmanaged_delete_recursive($directory);
  884. }
  885. }
  886. // Let other modules update as necessary on flush.
  887. module_invoke_all('image_style_flush', $style);
  888. // Clear image style and effect caches.
  889. cache_clear_all('image_styles', 'cache');
  890. cache_clear_all('image_effects:', 'cache', TRUE);
  891. drupal_static_reset('image_styles');
  892. drupal_static_reset('image_effects');
  893. // Clear field caches so that formatters may be added for this style.
  894. field_info_cache_clear();
  895. drupal_theme_rebuild();
  896. // Clear page caches when flushing.
  897. if (module_exists('block')) {
  898. cache_clear_all('*', 'cache_block', TRUE);
  899. }
  900. cache_clear_all('*', 'cache_page', TRUE);
  901. }
  902. /**
  903. * Returns the URL for an image derivative given a style and image path.
  904. *
  905. * @param $style_name
  906. * The name of the style to be used with this image.
  907. * @param $path
  908. * The path to the image.
  909. *
  910. * @return
  911. * The absolute URL where a style image can be downloaded, suitable for use
  912. * in an <img> tag. Requesting the URL will cause the image to be created.
  913. * @see image_style_deliver()
  914. */
  915. function image_style_url($style_name, $path) {
  916. $uri = image_style_path($style_name, $path);
  917. // The passed-in $path variable can be either a relative path or a full URI.
  918. $original_uri = file_uri_scheme($path) ? file_stream_wrapper_uri_normalize($path) : file_build_uri($path);
  919. // The token query is added even if the 'image_allow_insecure_derivatives'
  920. // variable is TRUE, so that the emitted links remain valid if it is changed
  921. // back to the default FALSE.
  922. $token_query = array(IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, $original_uri));
  923. // If not using clean URLs, the image derivative callback is only available
  924. // with the query string. If the file does not exist, use url() to ensure
  925. // that it is included. Once the file exists it's fine to fall back to the
  926. // actual file path, this avoids bootstrapping PHP once the files are built.
  927. if (!variable_get('clean_url') && file_uri_scheme($uri) == 'public' && !file_exists($uri)) {
  928. $directory_path = file_stream_wrapper_get_instance_by_uri($uri)->getDirectoryPath();
  929. return url($directory_path . '/' . file_uri_target($uri), array('absolute' => TRUE, 'query' => $token_query));
  930. }
  931. $file_url = file_create_url($uri);
  932. // Append the query string with the token.
  933. return $file_url . (strpos($file_url, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($token_query);
  934. }
  935. /**
  936. * Generates a token to protect an image style derivative.
  937. *
  938. * This prevents unauthorized generation of an image style derivative,
  939. * which can be costly both in CPU time and disk space.
  940. *
  941. * @param $style_name
  942. * The name of the image style.
  943. * @param $uri
  944. * The URI of the image for this style, for example as returned by
  945. * image_style_path().
  946. *
  947. * @return
  948. * An eight-character token which can be used to protect image style
  949. * derivatives against denial-of-service attacks.
  950. */
  951. function image_style_path_token($style_name, $uri) {
  952. // Return the first eight characters.
  953. return substr(drupal_hmac_base64($style_name . ':' . $uri, drupal_get_private_key() . drupal_get_hash_salt()), 0, 8);
  954. }
  955. /**
  956. * Returns the URI of an image when using a style.
  957. *
  958. * The path returned by this function may not exist. The default generation
  959. * method only creates images when they are requested by a user's browser.
  960. *
  961. * @param $style_name
  962. * The name of the style to be used with this image.
  963. * @param $uri
  964. * The URI or path to the image.
  965. *
  966. * @return
  967. * The URI to an image style image.
  968. * @see image_style_url()
  969. */
  970. function image_style_path($style_name, $uri) {
  971. $scheme = file_uri_scheme($uri);
  972. if ($scheme) {
  973. $path = file_uri_target($uri);
  974. }
  975. else {
  976. $path = $uri;
  977. $scheme = file_default_scheme();
  978. }
  979. return $scheme . '://styles/' . $style_name . '/' . $scheme . '/' . $path;
  980. }
  981. /**
  982. * Saves a default image style to the database.
  983. *
  984. * @param style
  985. * An image style array provided by a module.
  986. *
  987. * @return
  988. * An image style array. The returned style array will include the new 'isid'
  989. * assigned to the style.
  990. */
  991. function image_default_style_save($style) {
  992. $style = image_style_save($style);
  993. $effects = array();
  994. foreach ($style['effects'] as $effect) {
  995. $effect['isid'] = $style['isid'];
  996. $effect = image_effect_save($effect);
  997. $effects[$effect['ieid']] = $effect;
  998. }
  999. $style['effects'] = $effects;
  1000. return $style;
  1001. }
  1002. /**
  1003. * Reverts the changes made by users to a default image style.
  1004. *
  1005. * @param style
  1006. * An image style array.
  1007. * @return
  1008. * Boolean TRUE if the operation succeeded.
  1009. */
  1010. function image_default_style_revert($style) {
  1011. image_style_flush($style);
  1012. db_delete('image_effects')->condition('isid', $style['isid'])->execute();
  1013. db_delete('image_styles')->condition('isid', $style['isid'])->execute();
  1014. return TRUE;
  1015. }
  1016. /**
  1017. * Returns a set of image effects.
  1018. *
  1019. * These image effects are exposed by modules implementing
  1020. * hook_image_effect_info().
  1021. *
  1022. * @return
  1023. * An array of image effects to be used when transforming images.
  1024. * @see hook_image_effect_info()
  1025. * @see image_effect_definition_load()
  1026. */
  1027. function image_effect_definitions() {
  1028. global $language;
  1029. // hook_image_effect_info() includes translated strings, so each language is
  1030. // cached separately.
  1031. $langcode = $language->language;
  1032. $effects = &drupal_static(__FUNCTION__);
  1033. if (!isset($effects)) {
  1034. if ($cache = cache_get("image_effects:$langcode")) {
  1035. $effects = $cache->data;
  1036. }
  1037. else {
  1038. $effects = array();
  1039. include_once DRUPAL_ROOT . '/modules/image/image.effects.inc';
  1040. foreach (module_implements('image_effect_info') as $module) {
  1041. foreach (module_invoke($module, 'image_effect_info') as $name => $effect) {
  1042. // Ensure the current toolkit supports the effect.
  1043. $effect['module'] = $module;
  1044. $effect['name'] = $name;
  1045. $effect['data'] = isset($effect['data']) ? $effect['data'] : array();
  1046. $effects[$name] = $effect;
  1047. }
  1048. }
  1049. uasort($effects, '_image_effect_definitions_sort');
  1050. drupal_alter('image_effect_info', $effects);
  1051. cache_set("image_effects:$langcode", $effects);
  1052. }
  1053. }
  1054. return $effects;
  1055. }
  1056. /**
  1057. * Loads the definition for an image effect.
  1058. *
  1059. * The effect definition is a set of core properties for an image effect, not
  1060. * containing any user-settings. The definition defines various functions to
  1061. * call when configuring or executing an image effect. This loader is mostly for
  1062. * internal use within image.module. Use image_effect_load() or
  1063. * image_style_load() to get image effects that contain configuration.
  1064. *
  1065. * @param $effect
  1066. * The name of the effect definition to load.
  1067. * @param $style
  1068. * An image style array to which this effect will be added.
  1069. *
  1070. * @return
  1071. * An array containing the image effect definition with the following keys:
  1072. * - "effect": The unique name for the effect being performed. Usually prefixed
  1073. * with the name of the module providing the effect.
  1074. * - "module": The module providing the effect.
  1075. * - "help": A description of the effect.
  1076. * - "function": The name of the function that will execute the effect.
  1077. * - "form": (optional) The name of a function to configure the effect.
  1078. * - "summary": (optional) The name of a theme function that will display a
  1079. * one-line summary of the effect. Does not include the "theme_" prefix.
  1080. */
  1081. function image_effect_definition_load($effect, $style_name = NULL) {
  1082. $definitions = image_effect_definitions();
  1083. // If a style is specified, do not allow loading of default style
  1084. // effects.
  1085. if (isset($style_name)) {
  1086. $style = image_style_load($style_name, NULL);
  1087. if ($style['storage'] == IMAGE_STORAGE_DEFAULT) {
  1088. return FALSE;
  1089. }
  1090. }
  1091. return isset($definitions[$effect]) ? $definitions[$effect] : FALSE;
  1092. }
  1093. /**
  1094. * Loads all image effects from the database.
  1095. *
  1096. * @return
  1097. * An array of all image effects.
  1098. * @see image_effect_load()
  1099. */
  1100. function image_effects() {
  1101. $effects = &drupal_static(__FUNCTION__);
  1102. if (!isset($effects)) {
  1103. $effects = array();
  1104. // Add database image effects.
  1105. $result = db_select('image_effects', NULL, array('fetch' => PDO::FETCH_ASSOC))
  1106. ->fields('image_effects')
  1107. ->orderBy('image_effects.weight', 'ASC')
  1108. ->execute();
  1109. foreach ($result as $effect) {
  1110. $effect['data'] = unserialize($effect['data']);
  1111. $definition = image_effect_definition_load($effect['name']);
  1112. // Do not load image effects whose definition cannot be found.
  1113. if ($definition) {
  1114. $effect = array_merge($definition, $effect);
  1115. $effects[$effect['ieid']] = $effect;
  1116. }
  1117. }
  1118. }
  1119. return $effects;
  1120. }
  1121. /**
  1122. * Loads a single image effect.
  1123. *
  1124. * @param $ieid
  1125. * The image effect ID.
  1126. * @param $style_name
  1127. * The image style name.
  1128. * @param $include
  1129. * If set, this loader will restrict to a specific type of image style, may be
  1130. * one of the defined Image style storage constants.
  1131. *
  1132. * @return
  1133. * An image effect array, consisting of the following keys:
  1134. * - "ieid": The unique image effect ID.
  1135. * - "isid": The unique image style ID that contains this image effect.
  1136. * - "weight": The weight of this image effect within the image style.
  1137. * - "name": The name of the effect definition that powers this image effect.
  1138. * - "data": An array of configuration options for this image effect.
  1139. * Besides these keys, the entirety of the image definition is merged into
  1140. * the image effect array. Returns FALSE if the specified effect cannot be
  1141. * found.
  1142. * @see image_style_load()
  1143. * @see image_effect_definition_load()
  1144. */
  1145. function image_effect_load($ieid, $style_name, $include = NULL) {
  1146. if (($style = image_style_load($style_name, NULL, $include)) && isset($style['effects'][$ieid])) {
  1147. return $style['effects'][$ieid];
  1148. }
  1149. return FALSE;
  1150. }
  1151. /**
  1152. * Saves an image effect.
  1153. *
  1154. * @param $effect
  1155. * An image effect array.
  1156. *
  1157. * @return
  1158. * An image effect array. In the case of a new effect, 'ieid' will be set.
  1159. */
  1160. function image_effect_save($effect) {
  1161. if (!empty($effect['ieid'])) {
  1162. drupal_write_record('image_effects', $effect, 'ieid');
  1163. }
  1164. else {
  1165. drupal_write_record('image_effects', $effect);
  1166. }
  1167. $style = image_style_load(NULL, $effect['isid']);
  1168. image_style_flush($style);
  1169. return $effect;
  1170. }
  1171. /**
  1172. * Deletes an image effect.
  1173. *
  1174. * @param $effect
  1175. * An image effect array.
  1176. */
  1177. function image_effect_delete($effect) {
  1178. db_delete('image_effects')->condition('ieid', $effect['ieid'])->execute();
  1179. $style = image_style_load(NULL, $effect['isid']);
  1180. image_style_flush($style);
  1181. }
  1182. /**
  1183. * Applies an image effect to the image object.
  1184. *
  1185. * @param $image
  1186. * An image object returned by image_load().
  1187. * @param $effect
  1188. * An image effect array.
  1189. *
  1190. * @return
  1191. * TRUE on success. FALSE if unable to perform the image effect on the image.
  1192. */
  1193. function image_effect_apply($image, $effect) {
  1194. module_load_include('inc', 'image', 'image.effects');
  1195. $function = $effect['effect callback'];
  1196. if (function_exists($function)) {
  1197. return $function($image, $effect['data']);
  1198. }
  1199. return FALSE;
  1200. }
  1201. /**
  1202. * Returns HTML for an image using a specific image style.
  1203. *
  1204. * @param $variables
  1205. * An associative array containing:
  1206. * - style_name: The name of the style to be used to alter the original image.
  1207. * - path: The path of the image file relative to the Drupal files directory.
  1208. * This function does not work with images outside the files directory nor
  1209. * with remotely hosted images. This should be in a format such as
  1210. * 'images/image.jpg', or using a stream wrapper such as
  1211. * 'public://images/image.jpg'.
  1212. * - width: The width of the source image (if known).
  1213. * - height: The height of the source image (if known).
  1214. * - alt: The alternative text for text-based browsers.
  1215. * - title: The title text is displayed when the image is hovered in some
  1216. * popular browsers.
  1217. * - attributes: Associative array of attributes to be placed in the img tag.
  1218. *
  1219. * @ingroup themeable
  1220. */
  1221. function theme_image_style($variables) {
  1222. // Determine the dimensions of the styled image.
  1223. $dimensions = array(
  1224. 'width' => $variables['width'],
  1225. 'height' => $variables['height'],
  1226. );
  1227. image_style_transform_dimensions($variables['style_name'], $dimensions);
  1228. $variables['width'] = $dimensions['width'];
  1229. $variables['height'] = $dimensions['height'];
  1230. // Determine the URL for the styled image.
  1231. $variables['path'] = image_style_url($variables['style_name'], $variables['path']);
  1232. return theme('image', $variables);
  1233. }
  1234. /**
  1235. * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
  1236. *
  1237. * @param $value
  1238. * @param $current_pixels
  1239. * @param $new_pixels
  1240. */
  1241. function image_filter_keyword($value, $current_pixels, $new_pixels) {
  1242. switch ($value) {
  1243. case 'top':
  1244. case 'left':
  1245. return 0;
  1246. case 'bottom':
  1247. case 'right':
  1248. return $current_pixels - $new_pixels;
  1249. case 'center':
  1250. return $current_pixels / 2 - $new_pixels / 2;
  1251. }
  1252. return $value;
  1253. }
  1254. /**
  1255. * Internal function for sorting image effect definitions through uasort().
  1256. *
  1257. * @see image_effect_definitions()
  1258. */
  1259. function _image_effect_definitions_sort($a, $b) {
  1260. return strcasecmp($a['name'], $b['name']);
  1261. }