image.module

Exposes global functionality for creating image styles.

File

drupal/core/modules/image/image.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Exposes global functionality for creating image styles.
  5. */
  6. use Drupal\Core\Entity\EntityInterface;
  7. use Drupal\Core\Language\Language;
  8. use Drupal\field\Plugin\Core\Entity\Field;
  9. use Drupal\field\Plugin\Core\Entity\FieldInstance;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  12. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  13. use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
  14. use Drupal\Component\Utility\Crypt;
  15. use Drupal\Component\Uuid\Uuid;
  16. use Drupal\file\Plugin\Core\Entity\File;
  17. use Drupal\image\Plugin\Core\Entity\ImageStyle;
  18. /**
  19. * Image style constant for user presets in the database.
  20. */
  21. const IMAGE_STORAGE_NORMAL = 1;
  22. /**
  23. * Image style constant for user presets that override module-defined presets.
  24. */
  25. const IMAGE_STORAGE_OVERRIDE = 2;
  26. /**
  27. * Image style constant for module-defined presets in code.
  28. */
  29. const IMAGE_STORAGE_DEFAULT = 4;
  30. /**
  31. * Image style constant to represent an editable preset.
  32. */
  33. define('IMAGE_STORAGE_EDITABLE', IMAGE_STORAGE_NORMAL | IMAGE_STORAGE_OVERRIDE);
  34. /**
  35. * Image style constant to represent any module-based preset.
  36. */
  37. define('IMAGE_STORAGE_MODULE', IMAGE_STORAGE_OVERRIDE | IMAGE_STORAGE_DEFAULT);
  38. /**
  39. * The name of the query parameter for image derivative tokens.
  40. */
  41. define('IMAGE_DERIVATIVE_TOKEN', 'itok');
  42. // Load all Field module hooks for Image.
  43. require_once __DIR__ . '/image.field.inc';
  44. /**
  45. * Implements hook_help().
  46. */
  47. function image_help($path, $arg) {
  48. switch ($path) {
  49. case 'admin/help#image':
  50. $output = '';
  51. $output .= '<h3>' . t('About') . '</h3>';
  52. $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>';
  53. $output .= '<h3>' . t('Uses') . '</h3>';
  54. $output .= '<dl>';
  55. $output .= '<dt>' . t('Manipulating images') . '</dt>';
  56. $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')));
  57. $output .= '<ul><li>' . t('Based on where it will be used: eg. <em>profile-picture</em>') . '</li>';
  58. $output .= '<li>' . t('Describing its appearance: eg. <em>square-85x85</em>') . '</li></ul>';
  59. $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>';
  60. $output .= '<dt>' . t('Attaching images to content as fields') . '</dt>';
  61. $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>';
  62. $output .= '</dl>';
  63. return $output;
  64. case 'admin/config/media/image-styles':
  65. 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>';
  66. case 'admin/config/media/image-styles/manage/%/add/%':
  67. $effect = image_effect_definition_load($arg[7]);
  68. return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
  69. case 'admin/config/media/image-styles/manage/%/effects/%':
  70. $effect = ($arg[5] == 'add') ? image_effect_definition_load($arg[6]) : image_effect_load($arg[6], $arg[4]);
  71. return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
  72. }
  73. }
  74. /**
  75. * Entity URI callback for image style.
  76. */
  77. function image_style_entity_uri(ImageStyle $style) {
  78. return array(
  79. 'path' => 'admin/config/media/image-styles/manage/' . $style->id(),
  80. );
  81. }
  82. /**
  83. * Implements hook_menu().
  84. */
  85. function image_menu() {
  86. $items = array();
  87. // Generate image derivatives of publicly available files.
  88. // If clean URLs are disabled, image derivatives will always be served
  89. // through the menu system.
  90. // If clean URLs are enabled and the image derivative already exists,
  91. // PHP will be bypassed.
  92. $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  93. $items[$directory_path . '/styles/%image_style'] = array(
  94. 'title' => 'Generate image style',
  95. 'page callback' => 'image_style_deliver',
  96. 'page arguments' => array(count(explode('/', $directory_path)) + 1),
  97. 'access callback' => TRUE,
  98. 'type' => MENU_CALLBACK,
  99. );
  100. // Generate and deliver image derivatives of private files.
  101. // These image derivatives are always delivered through the menu system.
  102. $items['system/files/styles/%image_style'] = array(
  103. 'title' => 'Generate image style',
  104. 'page callback' => 'image_style_deliver',
  105. 'page arguments' => array(3),
  106. 'access callback' => TRUE,
  107. 'type' => MENU_CALLBACK,
  108. );
  109. $items['admin/config/media/image-styles'] = array(
  110. 'title' => 'Image styles',
  111. 'description' => 'Configure styles that can be used for resizing or adjusting images on display.',
  112. 'page callback' => 'image_style_list',
  113. 'access arguments' => array('administer image styles'),
  114. 'file' => 'image.admin.inc',
  115. );
  116. $items['admin/config/media/image-styles/list'] = array(
  117. 'title' => 'List',
  118. 'description' => 'List the current image styles on the site.',
  119. 'page callback' => 'image_style_list',
  120. 'access arguments' => array('administer image styles'),
  121. 'type' => MENU_DEFAULT_LOCAL_TASK,
  122. 'file' => 'image.admin.inc',
  123. );
  124. $items['admin/config/media/image-styles/add'] = array(
  125. 'title' => 'Add style',
  126. 'description' => 'Add a new image style.',
  127. 'page callback' => 'drupal_get_form',
  128. 'page arguments' => array('image_style_add_form'),
  129. 'access arguments' => array('administer image styles'),
  130. 'type' => MENU_LOCAL_ACTION,
  131. 'weight' => 2,
  132. 'file' => 'image.admin.inc',
  133. );
  134. $items['admin/config/media/image-styles/manage/%image_style'] = array(
  135. 'title' => 'Edit style',
  136. 'title callback' => 'entity_page_label',
  137. 'title arguments' => array(5),
  138. 'description' => 'Configure an image style.',
  139. 'page callback' => 'drupal_get_form',
  140. 'page arguments' => array('image_style_form', 5),
  141. 'access arguments' => array('administer image styles'),
  142. 'file' => 'image.admin.inc',
  143. );
  144. $items['admin/config/media/image-styles/manage/%image_style/edit'] = array(
  145. 'title' => 'Edit',
  146. 'type' => MENU_DEFAULT_LOCAL_TASK,
  147. 'weight' => -10,
  148. );
  149. $items['admin/config/media/image-styles/manage/%image_style/delete'] = array(
  150. 'title' => 'Delete',
  151. 'description' => 'Delete an image style.',
  152. 'type' => MENU_LOCAL_TASK,
  153. 'weight' => 10,
  154. 'route_name' => 'image_style_delete',
  155. );
  156. $items['admin/config/media/image-styles/manage/%image_style/effects/%image_effect'] = array(
  157. 'title' => 'Edit image effect',
  158. 'description' => 'Edit an existing effect within a style.',
  159. 'load arguments' => array(5, (string) IMAGE_STORAGE_EDITABLE),
  160. 'page callback' => 'drupal_get_form',
  161. 'page arguments' => array('image_effect_form', 5, 7),
  162. 'access arguments' => array('administer image styles'),
  163. 'file' => 'image.admin.inc',
  164. );
  165. $items['admin/config/media/image-styles/manage/%image_style/effects/%image_effect/delete'] = array(
  166. 'title' => 'Delete image effect',
  167. 'description' => 'Delete an existing effect from a style.',
  168. 'route_name' => 'image_effect_delete',
  169. );
  170. $items['admin/config/media/image-styles/manage/%image_style/add/%image_effect_definition'] = array(
  171. 'title' => 'Add image effect',
  172. 'description' => 'Add a new effect to a style.',
  173. 'load arguments' => array(5),
  174. 'page callback' => 'drupal_get_form',
  175. 'page arguments' => array('image_effect_form', 5, 7),
  176. 'access arguments' => array('administer image styles'),
  177. 'file' => 'image.admin.inc',
  178. );
  179. return $items;
  180. }
  181. /**
  182. * Implements hook_theme().
  183. */
  184. function image_theme() {
  185. return array(
  186. // Theme functions in image.module.
  187. 'image_style' => array(
  188. 'variables' => array(
  189. 'style_name' => NULL,
  190. 'uri' => NULL,
  191. 'width' => NULL,
  192. 'height' => NULL,
  193. 'alt' => '',
  194. 'title' => NULL,
  195. 'attributes' => array(),
  196. ),
  197. ),
  198. // Theme functions in image.admin.inc.
  199. 'image_style_list' => array(
  200. 'variables' => array('styles' => NULL),
  201. ),
  202. 'image_style_effects' => array(
  203. 'render element' => 'form',
  204. ),
  205. 'image_style_preview' => array(
  206. 'variables' => array('style' => NULL),
  207. ),
  208. 'image_anchor' => array(
  209. 'render element' => 'element',
  210. ),
  211. 'image_resize_summary' => array(
  212. 'variables' => array('data' => NULL),
  213. ),
  214. 'image_scale_summary' => array(
  215. 'variables' => array('data' => NULL),
  216. ),
  217. 'image_crop_summary' => array(
  218. 'variables' => array('data' => NULL),
  219. ),
  220. 'image_rotate_summary' => array(
  221. 'variables' => array('data' => NULL),
  222. ),
  223. // Theme functions in image.field.inc.
  224. 'image_widget' => array(
  225. 'render element' => 'element',
  226. ),
  227. 'image_formatter' => array(
  228. 'variables' => array('item' => NULL, 'path' => NULL, 'image_style' => NULL),
  229. ),
  230. );
  231. }
  232. /**
  233. * Implements hook_permission().
  234. */
  235. function image_permission() {
  236. return array(
  237. 'administer image styles' => array(
  238. 'title' => t('Administer image styles'),
  239. 'description' => t('Create and modify styles for generating image modifications such as thumbnails.'),
  240. ),
  241. );
  242. }
  243. /**
  244. * Implements hook_form_FORM_ID_alter().
  245. */
  246. function image_form_system_file_system_settings_alter(&$form, &$form_state) {
  247. $form['#submit'][] = 'image_system_file_system_settings_submit';
  248. }
  249. /**
  250. * Form submission handler for system_file_system_settings().
  251. *
  252. * Adds a menu rebuild after the public file path has been changed, so that the
  253. * menu router item depending on that file path will be regenerated.
  254. */
  255. function image_system_file_system_settings_submit($form, &$form_state) {
  256. if ($form['file_public_path']['#default_value'] !== $form_state['values']['file_public_path']) {
  257. Drupal::state()->set('menu_rebuild_needed', TRUE);
  258. }
  259. }
  260. /**
  261. * Implements hook_file_download().
  262. *
  263. * Control the access to files underneath the styles directory.
  264. */
  265. function image_file_download($uri) {
  266. $path = file_uri_target($uri);
  267. // Private file access for image style derivatives.
  268. if (strpos($path, 'styles/') === 0) {
  269. $args = explode('/', $path);
  270. // Discard the first part of the path (styles).
  271. array_shift($args);
  272. // Get the style name from the second part.
  273. $style_name = array_shift($args);
  274. // Remove the scheme from the path.
  275. array_shift($args);
  276. // Then the remaining parts are the path to the image.
  277. $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
  278. // Check that the file exists and is an image.
  279. if ($info = image_get_info($uri)) {
  280. // Check the permissions of the original to grant access to this image.
  281. $headers = module_invoke_all('file_download', $original_uri);
  282. // Confirm there's at least one module granting access and none denying access.
  283. if (!empty($headers) && !in_array(-1, $headers)) {
  284. return array(
  285. // Send headers describing the image's size, and MIME-type...
  286. 'Content-Type' => $info['mime_type'],
  287. 'Content-Length' => $info['file_size'],
  288. // By not explicitly setting them here, this uses normal Drupal
  289. // Expires, Cache-Control and ETag headers to prevent proxy or
  290. // browser caching of private images.
  291. );
  292. }
  293. }
  294. return -1;
  295. }
  296. // Private file access for the original files. Note that we only
  297. // check access for non-temporary images, since file.module will
  298. // grant access for all temporary files.
  299. $files = entity_load_multiple_by_properties('file', array('uri' => $uri));
  300. if (count($files)) {
  301. $file = reset($files);
  302. if ($file->status) {
  303. return file_file_download($uri, 'image');
  304. }
  305. }
  306. }
  307. /**
  308. * Implements hook_file_move().
  309. */
  310. function image_file_move(File $file, File $source) {
  311. // Delete any image derivatives at the original image path.
  312. image_path_flush($source->uri);
  313. }
  314. /**
  315. * Implements hook_file_predelete().
  316. */
  317. function image_file_predelete(File $file) {
  318. // Delete any image derivatives of this image.
  319. image_path_flush($file->uri);
  320. }
  321. /**
  322. * Implements hook_field_delete_field().
  323. */
  324. function image_field_delete_field($field) {
  325. if ($field['type'] != 'image') {
  326. return;
  327. }
  328. // The value of a managed_file element can be an array if #extended == TRUE.
  329. $fid = (isset($field['settings']['default_image']['fids']) ? $field['settings']['default_image']['fids'] : $field['settings']['default_image']);
  330. if ($fid && ($file = file_load($fid[0]))) {
  331. file_usage()->delete($file, 'image', 'default_image', $field['id']);
  332. }
  333. }
  334. /**
  335. * Implements hook_field_update_field().
  336. */
  337. function image_field_update_field($field, $prior_field, $has_data) {
  338. if ($field['type'] != 'image') {
  339. return;
  340. }
  341. // The value of a managed_file element can be an array if #extended == TRUE.
  342. $fid_new = (isset($field['settings']['default_image']['fids']) ? $field['settings']['default_image']['fids'] : $field['settings']['default_image']);
  343. $fid_old = (isset($prior_field['settings']['default_image']['fids']) ? $prior_field['settings']['default_image']['fids'] : $prior_field['settings']['default_image']);
  344. $file_new = $fid_new ? file_load($fid_new) : FALSE;
  345. if ($fid_new != $fid_old) {
  346. // Is there a new file?
  347. if ($file_new) {
  348. $file_new->status = FILE_STATUS_PERMANENT;
  349. $file_new->save();
  350. file_usage()->add($file_new, 'image', 'default_image', $field['uuid']);
  351. }
  352. // Is there an old file?
  353. if ($fid_old && ($file_old = file_load($fid_old[0]))) {
  354. file_usage()->delete($file_old, 'image', 'default_image', $field['uuid']);
  355. }
  356. }
  357. // If the upload destination changed, then move the file.
  358. if ($file_new && (file_uri_scheme($file_new->uri) != $field['settings']['uri_scheme'])) {
  359. $directory = $field['settings']['uri_scheme'] . '://default_images/';
  360. file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  361. file_move($file_new, $directory . $file_new->filename);
  362. }
  363. }
  364. /**
  365. * Implements hook_field_delete_instance().
  366. */
  367. function image_field_delete_instance($instance) {
  368. // Only act on image fields.
  369. $field = field_read_field($instance['field_name']);
  370. if ($field['type'] != 'image') {
  371. return;
  372. }
  373. // The value of a managed_file element can be an array if the #extended
  374. // property is set to TRUE.
  375. $fid = $instance['settings']['default_image'];
  376. if (is_array($fid)) {
  377. $fid = $fid['fid'];
  378. }
  379. // Remove the default image when the instance is deleted.
  380. if ($fid && ($file = file_load($fid))) {
  381. file_usage()->delete($file, 'image', 'default_image', $instance['id']);
  382. }
  383. }
  384. /**
  385. * Implements hook_field_update_instance().
  386. */
  387. function image_field_update_instance($instance, $prior_instance) {
  388. // Only act on image fields.
  389. $field = field_read_field($instance['field_name']);
  390. if ($field['type'] != 'image') {
  391. return;
  392. }
  393. // The value of a managed_file element can be an array if the #extended
  394. // property is set to TRUE.
  395. $fid_new = $instance['settings']['default_image'];
  396. if (isset($fid_new['fids'])) {
  397. $fid_new = $fid_new['fids'];
  398. }
  399. $fid_old = $prior_instance['settings']['default_image'];
  400. if (isset($fid_old['fids'])) {
  401. $fid_old = $fid_old['fids'];
  402. }
  403. // If the old and new files do not match, update the default accordingly.
  404. $file_new = $fid_new ? file_load($fid_new[0]) : FALSE;
  405. if ($fid_new != $fid_old) {
  406. // Save the new file, if present.
  407. if ($file_new) {
  408. $file_new->status = FILE_STATUS_PERMANENT;
  409. $file_new->save();
  410. file_usage()->add($file_new, 'image', 'default_image', $instance['uuid']);
  411. }
  412. // Delete the old file, if present.
  413. if ($fid_old && ($file_old = file_load($fid_old[0]))) {
  414. file_usage()->delete($file_old, 'image', 'default_image', $instance['uuid']);
  415. }
  416. }
  417. // If the upload destination changed, then move the file.
  418. if ($file_new && (file_uri_scheme($file_new->uri) != $field['settings']['uri_scheme'])) {
  419. $directory = $field['settings']['uri_scheme'] . '://default_images/';
  420. file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  421. file_move($file_new, $directory . $file_new->filename);
  422. }
  423. }
  424. /**
  425. * Clears cached versions of a specific file in all styles.
  426. *
  427. * @param $path
  428. * The Drupal file path to the original image.
  429. */
  430. function image_path_flush($path) {
  431. $styles = entity_load_multiple('image_style');
  432. foreach ($styles as $style) {
  433. $image_path = image_style_path($style->id(), $path);
  434. if (file_exists($image_path)) {
  435. file_unmanaged_delete($image_path);
  436. }
  437. }
  438. }
  439. /**
  440. * Loads an ImageStyle object.
  441. *
  442. * @param string $name
  443. * The ID of the ImageStyle object to load.
  444. */
  445. function image_style_load($name) {
  446. return entity_load('image_style', $name);
  447. }
  448. /**
  449. * Gets an array of image styles suitable for using as select list options.
  450. *
  451. * @param $include_empty
  452. * If TRUE a '- None -' option will be inserted in the options array.
  453. * @return
  454. * Array of image styles both key and value are set to style name.
  455. */
  456. function image_style_options($include_empty = TRUE) {
  457. $styles = entity_load_multiple('image_style');
  458. $options = array();
  459. if ($include_empty && !empty($styles)) {
  460. $options[''] = t('- None -');
  461. }
  462. foreach ($styles as $name => $style) {
  463. $options[$name] = $style->label();
  464. }
  465. if (empty($options)) {
  466. $options[''] = t('No defined styles');
  467. }
  468. return $options;
  469. }
  470. /**
  471. * Page callback: Generates a derivative, given a style and image path.
  472. *
  473. * After generating an image, transfer it to the requesting agent.
  474. *
  475. * @param $style
  476. * The image style
  477. */
  478. function image_style_deliver($style, $scheme) {
  479. $args = func_get_args();
  480. array_shift($args);
  481. array_shift($args);
  482. $target = implode('/', $args);
  483. // Check that the style is defined, the scheme is valid, and the image
  484. // derivative token is valid. (Sites which require image derivatives to be
  485. // generated without a token can set the
  486. // 'image.settings:allow_insecure_derivatives' configuration to TRUE to bypass
  487. // the latter check, but this will increase the site's vulnerability to
  488. // denial-of-service attacks.)
  489. $valid = !empty($style) && file_stream_wrapper_valid_scheme($scheme);
  490. if (!config('image.settings')->get('allow_insecure_derivatives')) {
  491. $valid = $valid && isset($_GET[IMAGE_DERIVATIVE_TOKEN]) && $_GET[IMAGE_DERIVATIVE_TOKEN] === image_style_path_token($style->name, $scheme . '://' . $target);
  492. }
  493. if (!$valid) {
  494. throw new AccessDeniedHttpException();
  495. }
  496. $image_uri = $scheme . '://' . $target;
  497. $derivative_uri = image_style_path($style->id(), $image_uri);
  498. // If using the private scheme, let other modules provide headers and
  499. // control access to the file.
  500. if ($scheme == 'private') {
  501. if (file_exists($derivative_uri)) {
  502. file_download($scheme, file_uri_target($derivative_uri));
  503. }
  504. else {
  505. $headers = module_invoke_all('file_download', $image_uri);
  506. if (in_array(-1, $headers) || empty($headers)) {
  507. throw new AccessDeniedHttpException();
  508. }
  509. if (count($headers)) {
  510. foreach ($headers as $name => $value) {
  511. drupal_add_http_header($name, $value);
  512. }
  513. }
  514. }
  515. }
  516. // Don't try to generate file if source is missing.
  517. if (!file_exists($image_uri)) {
  518. watchdog('image', 'Source image at %source_image_path not found while trying to generate derivative image at %derivative_path.', array('%source_image_path' => $image_uri, '%derivative_path' => $derivative_uri));
  519. return new Response(t('Error generating image, missing source file.'), 404);
  520. }
  521. // Don't start generating the image if the derivative already exists or if
  522. // generation is in progress in another thread.
  523. $lock_name = 'image_style_deliver:' . $style->id() . ':' . Crypt::hashBase64($image_uri);
  524. if (!file_exists($derivative_uri)) {
  525. $lock_acquired = lock()->acquire($lock_name);
  526. if (!$lock_acquired) {
  527. // Tell client to retry again in 3 seconds. Currently no browsers are known
  528. // to support Retry-After.
  529. throw new ServiceUnavailableHttpException(3, t('Image generation in progress. Try again shortly.'));
  530. }
  531. }
  532. // Try to generate the image, unless another thread just did it while we were
  533. // acquiring the lock.
  534. $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
  535. if (!empty($lock_acquired)) {
  536. lock()->release($lock_name);
  537. }
  538. if ($success) {
  539. $image = image_load($derivative_uri);
  540. $uri = $image->source;
  541. $headers = array(
  542. 'Content-Type' => $image->info['mime_type'],
  543. 'Content-Length' => $image->info['file_size'],
  544. );
  545. return new BinaryFileResponse($uri, 200, $headers);
  546. }
  547. else {
  548. watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
  549. return new Response(t('Error generating image.'), 500);
  550. }
  551. }
  552. /**
  553. * Creates a new image derivative based on an image style.
  554. *
  555. * Generates an image derivative by creating the destination folder (if it does
  556. * not already exist), applying all image effects defined in $style->effects,
  557. * and saving a cached version of the resulting image.
  558. *
  559. * @param $style
  560. * An image style array.
  561. * @param $source
  562. * Path of the source file.
  563. * @param $destination
  564. * Path or URI of the destination file.
  565. *
  566. * @return
  567. * TRUE if an image derivative was generated, or FALSE if the image derivative
  568. * could not be generated.
  569. *
  570. * @see image_style_load()
  571. */
  572. function image_style_create_derivative($style, $source, $destination) {
  573. // Get the folder for the final location of this style.
  574. $directory = drupal_dirname($destination);
  575. // Build the destination folder tree if it doesn't already exist.
  576. if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  577. watchdog('image', 'Failed to create style directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
  578. return FALSE;
  579. }
  580. if (!$image = image_load($source)) {
  581. return FALSE;
  582. }
  583. if (!empty($style->effects)) {
  584. foreach ($style->effects as $effect) {
  585. image_effect_apply($image, $effect);
  586. }
  587. }
  588. if (!image_save($image, $destination)) {
  589. if (file_exists($destination)) {
  590. watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $destination), WATCHDOG_ERROR);
  591. }
  592. return FALSE;
  593. }
  594. return TRUE;
  595. }
  596. /**
  597. * Determines the dimensions of the styled image.
  598. *
  599. * Applies all of an image style's effects to $dimensions.
  600. *
  601. * @param $style_name
  602. * The name of the style to be applied.
  603. * @param $dimensions
  604. * Dimensions to be modified - an array with components width and height, in
  605. * pixels.
  606. */
  607. function image_style_transform_dimensions($style_name, array &$dimensions) {
  608. module_load_include('inc', 'image', 'image.effects');
  609. $style = entity_load('image_style', $style_name);
  610. if (!empty($style->effects)) {
  611. foreach ($style->effects as $effect) {
  612. if (isset($effect['dimensions passthrough'])) {
  613. continue;
  614. }
  615. if (isset($effect['dimensions callback'])) {
  616. $effect['dimensions callback']($dimensions, $effect['data']);
  617. }
  618. else {
  619. $dimensions['width'] = $dimensions['height'] = NULL;
  620. }
  621. }
  622. }
  623. }
  624. /**
  625. * Flushes cached media for a style.
  626. *
  627. * @param $style
  628. * An image style array.
  629. */
  630. function image_style_flush($style) {
  631. // Delete the style directory in each registered wrapper.
  632. $wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE);
  633. foreach ($wrappers as $wrapper => $wrapper_data) {
  634. file_unmanaged_delete_recursive($wrapper . '://styles/' . $style->id());
  635. }
  636. // Let other modules update as necessary on flush.
  637. module_invoke_all('image_style_flush', $style);
  638. // Clear field caches so that formatters may be added for this style.
  639. field_info_cache_clear();
  640. drupal_theme_rebuild();
  641. // Clear page caches when flushing.
  642. if (module_exists('block')) {
  643. cache('block')->deleteAll();
  644. }
  645. cache('page')->deleteAll();
  646. }
  647. /**
  648. * Returns the URL for an image derivative given a style and image path.
  649. *
  650. * @param $style_name
  651. * The name of the style to be used with this image.
  652. * @param $path
  653. * The path to the image.
  654. * @param $clean_urls
  655. * (optional) Whether clean URLs are in use.
  656. * @return
  657. * The absolute URL where a style image can be downloaded, suitable for use
  658. * in an <img> tag. Requesting the URL will cause the image to be created.
  659. * @see image_style_deliver()
  660. */
  661. function image_style_url($style_name, $path, $clean_urls = NULL) {
  662. $uri = image_style_path($style_name, $path);
  663. // The token query is added even if the
  664. // 'image.settings:allow_insecure_derivatives' configuration is TRUE, so that
  665. // the emitted links remain valid if it is changed back to the default FALSE.
  666. // However, sites which need to prevent the token query from being emitted at
  667. // all can additionally set the 'image.settings:suppress_itok_output'
  668. // configuration to TRUE to achieve that (if both are set, the security token
  669. // will neither be emitted in the image derivative URL nor checked for in
  670. // image_style_deliver()).
  671. $token_query = array();
  672. if (!config('image.settings')->get('suppress_itok_output')) {
  673. $token_query = array(IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, file_stream_wrapper_uri_normalize($path)));
  674. }
  675. if ($clean_urls === NULL) {
  676. // Assume clean URLs unless the request tells us otherwise.
  677. $clean_urls = TRUE;
  678. try {
  679. $request = Drupal::request();
  680. $clean_urls = $request->attributes->get('clean_urls');
  681. }
  682. catch (ServiceNotFoundException $e) {
  683. }
  684. }
  685. // If not using clean URLs, the image derivative callback is only available
  686. // with the script path. If the file does not exist, use url() to ensure
  687. // that it is included. Once the file exists it's fine to fall back to the
  688. // actual file path, this avoids bootstrapping PHP once the files are built.
  689. if ($clean_urls === FALSE && file_uri_scheme($uri) == 'public' && !file_exists($uri)) {
  690. $directory_path = file_stream_wrapper_get_instance_by_uri($uri)->getDirectoryPath();
  691. return url($directory_path . '/' . file_uri_target($uri), array('absolute' => TRUE, 'query' => $token_query));
  692. }
  693. $file_url = file_create_url($uri);
  694. // Append the query string with the token, if necessary.
  695. if ($token_query) {
  696. $file_url .= (strpos($file_url, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($token_query);
  697. }
  698. return $file_url;
  699. }
  700. /**
  701. * Generates a token to protect an image style derivative.
  702. *
  703. * This prevents unauthorized generation of an image style derivative,
  704. * which can be costly both in CPU time and disk space.
  705. *
  706. * @param string $style_name
  707. * The name of the image style.
  708. * @param string $uri
  709. * The URI of the image for this style, for example as returned by
  710. * image_style_path().
  711. *
  712. * @return string
  713. * An eight-character token which can be used to protect image style
  714. * derivatives against denial-of-service attacks.
  715. */
  716. function image_style_path_token($style_name, $uri) {
  717. // Return the first eight characters.
  718. return substr(Crypt::hmacBase64($style_name . ':' . $uri, drupal_get_private_key() . drupal_get_hash_salt()), 0, 8);
  719. }
  720. /**
  721. * Returns the URI of an image when using a style.
  722. *
  723. * The path returned by this function may not exist. The default generation
  724. * method only creates images when they are requested by a user's browser.
  725. *
  726. * @param $style_name
  727. * The name of the style to be used with this image.
  728. * @param $uri
  729. * The URI or path to the image.
  730. * @return
  731. * The URI to an image style image.
  732. * @see image_style_url()
  733. */
  734. function image_style_path($style_name, $uri) {
  735. $scheme = file_uri_scheme($uri);
  736. if ($scheme) {
  737. $path = file_uri_target($uri);
  738. }
  739. else {
  740. $path = $uri;
  741. $scheme = file_default_scheme();
  742. }
  743. return $scheme . '://styles/' . $style_name . '/' . $scheme . '/' . $path;
  744. }
  745. /**
  746. * Returns a set of image effects.
  747. *
  748. * These image effects are exposed by modules implementing
  749. * hook_image_effect_info().
  750. *
  751. * @return
  752. * An array of image effects to be used when transforming images.
  753. * @see hook_image_effect_info()
  754. * @see image_effect_definition_load()
  755. */
  756. function image_effect_definitions() {
  757. $language_interface = language(Language::TYPE_INTERFACE);
  758. // hook_image_effect_info() includes translated strings, so each language is
  759. // cached separately.
  760. $langcode = $language_interface->langcode;
  761. $effects = &drupal_static(__FUNCTION__);
  762. if (!isset($effects)) {
  763. if ($cache = cache()->get("image_effects:$langcode")) {
  764. $effects = $cache->data;
  765. }
  766. else {
  767. $effects = array();
  768. include_once __DIR__ . '/image.effects.inc';
  769. foreach (module_implements('image_effect_info') as $module) {
  770. foreach (module_invoke($module, 'image_effect_info') as $name => $effect) {
  771. // Ensure the current toolkit supports the effect.
  772. $effect['module'] = $module;
  773. $effect['name'] = $name;
  774. $effect['data'] = isset($effect['data']) ? $effect['data'] : array();
  775. $effects[$name] = $effect;
  776. }
  777. }
  778. uasort($effects, '_image_effect_definitions_sort');
  779. drupal_alter('image_effect_info', $effects);
  780. cache()->set("image_effects:$langcode", $effects);
  781. }
  782. }
  783. return $effects;
  784. }
  785. /**
  786. * Loads the definition for an image effect.
  787. *
  788. * The effect definition is a set of core properties for an image effect, not
  789. * containing any user-settings. The definition defines various functions to
  790. * call when configuring or executing an image effect. This loader is mostly for
  791. * internal use within image.module. Use image_effect_load() or
  792. * entity_load() to get image effects that contain configuration.
  793. *
  794. * @param $effect
  795. * The name of the effect definition to load.
  796. * @return
  797. * An array containing the image effect definition with the following keys:
  798. * - "effect": The unique name for the effect being performed. Usually prefixed
  799. * with the name of the module providing the effect.
  800. * - "module": The module providing the effect.
  801. * - "help": A description of the effect.
  802. * - "function": The name of the function that will execute the effect.
  803. * - "form": (optional) The name of a function to configure the effect.
  804. * - "summary": (optional) The name of a theme function that will display a
  805. * one-line summary of the effect. Does not include the "theme_" prefix.
  806. */
  807. function image_effect_definition_load($effect) {
  808. $definitions = image_effect_definitions();
  809. return isset($definitions[$effect]) ? $definitions[$effect] : FALSE;
  810. }
  811. /**
  812. * Loads a single image effect.
  813. *
  814. * @param $ieid
  815. * The image effect ID.
  816. * @param $style_name
  817. * The image style name.
  818. *
  819. * @return
  820. * An image effect array, consisting of the following keys:
  821. * - "ieid": The unique image effect ID.
  822. * - "weight": The weight of this image effect within the image style.
  823. * - "name": The name of the effect definition that powers this image effect.
  824. * - "data": An array of configuration options for this image effect.
  825. * Besides these keys, the entirety of the image definition is merged into
  826. * the image effect array. Returns FALSE if the specified effect cannot be
  827. * found.
  828. * @see image_effect_definition_load()
  829. */
  830. function image_effect_load($ieid, $style_name) {
  831. if (($style = entity_load('image_style', $style_name)) && isset($style->effects[$ieid])) {
  832. $effect = $style->effects[$ieid];
  833. $definition = image_effect_definition_load($effect['name']);
  834. $effect = array_merge($definition, $effect);
  835. // @todo The effect's key name within the style is unknown. It *should* be
  836. // identical to the ieid, but that is in no way guaranteed. And of course,
  837. // the ieid key *within* the effect is senseless duplication in the first
  838. // place. This problem can be eliminated in many places, but especially
  839. // for loaded menu arguments like %image_effect, the actual router
  840. // callbacks don't have access to 'ieid' anymore (unless resorting to
  841. // dirty %index and %map tricks).
  842. $effect['ieid'] = $ieid;
  843. return $effect;
  844. }
  845. return FALSE;
  846. }
  847. /**
  848. * Saves an image effect.
  849. *
  850. * @param ImageStyle $style
  851. * The image style this effect belongs to.
  852. * @param array $effect
  853. * An image effect array. Passed by reference.
  854. *
  855. * @return array
  856. * The saved image effect array. The 'ieid' key will be set for the effect.
  857. */
  858. function image_effect_save($style, &$effect) {
  859. // Remove all values that are not properties of an image effect.
  860. // @todo Convert image effects into plugins.
  861. $effect = array_intersect_key($effect, array_flip(array('ieid', 'module', 'name', 'data', 'weight')));
  862. // Generate a unique image effect ID for a new effect.
  863. if (empty($effect['ieid'])) {
  864. $uuid = new Uuid();
  865. $effect['ieid'] = $uuid->generate();
  866. }
  867. $style->effects[$effect['ieid']] = $effect;
  868. $style->save();
  869. // Flush all derivatives that exist for this style, so they are regenerated
  870. // with the new or updated effect.
  871. image_style_flush($style);
  872. }
  873. /**
  874. * Deletes an image effect.
  875. *
  876. * @param ImageStyle $style
  877. * The image style this effect belongs to.
  878. * @param $effect
  879. * An image effect array.
  880. */
  881. function image_effect_delete($style, $effect) {
  882. unset($style->effects[$effect['ieid']]);
  883. $style->save();
  884. image_style_flush($style);
  885. }
  886. /**
  887. * Applies an image effect to the image object.
  888. *
  889. * @param $image
  890. * An image object returned by image_load().
  891. * @param $effect
  892. * An image effect array.
  893. * @return
  894. * TRUE on success. FALSE if unable to perform the image effect on the image.
  895. */
  896. function image_effect_apply($image, $effect) {
  897. module_load_include('inc', 'image', 'image.effects');
  898. $function = $effect['effect callback'];
  899. return $function($image, $effect['data']);
  900. }
  901. /**
  902. * Returns HTML for an image using a specific image style.
  903. *
  904. * @param $variables
  905. * An associative array containing:
  906. * - style_name: The name of the style to be used to alter the original image.
  907. * - uri: The path of the image file relative to the Drupal files directory.
  908. * This function does not work with images outside the files directory nor
  909. * with remotely hosted images. This should be in a format such as
  910. * 'images/image.jpg', or using a stream wrapper such as
  911. * 'public://images/image.jpg'.
  912. * - width: The width of the source image (if known).
  913. * - height: The height of the source image (if known).
  914. * - alt: The alternative text for text-based browsers.
  915. * - title: The title text is displayed when the image is hovered in some
  916. * popular browsers.
  917. * - attributes: Associative array of attributes to be placed in the img tag.
  918. *
  919. * @ingroup themeable
  920. */
  921. function theme_image_style($variables) {
  922. // Determine the dimensions of the styled image.
  923. $dimensions = array(
  924. 'width' => $variables['width'],
  925. 'height' => $variables['height'],
  926. );
  927. image_style_transform_dimensions($variables['style_name'], $dimensions);
  928. $variables['width'] = $dimensions['width'];
  929. $variables['height'] = $dimensions['height'];
  930. // Add in the image style name as an HTML class.
  931. $variables['attributes']['class'][] = 'image-style-' . drupal_html_class($variables['style_name']);
  932. // Determine the URL for the styled image.
  933. $variables['uri'] = image_style_url($variables['style_name'], $variables['uri']);
  934. return theme('image', $variables);
  935. }
  936. /**
  937. * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
  938. *
  939. * @param $value
  940. * @param $current_pixels
  941. * @param $new_pixels
  942. */
  943. function image_filter_keyword($value, $current_pixels, $new_pixels) {
  944. switch ($value) {
  945. case 'top':
  946. case 'left':
  947. return 0;
  948. case 'bottom':
  949. case 'right':
  950. return $current_pixels - $new_pixels;
  951. case 'center':
  952. return $current_pixels / 2 - $new_pixels / 2;
  953. }
  954. return $value;
  955. }
  956. /**
  957. * Internal function for sorting image effect definitions through uasort().
  958. *
  959. * @see image_effect_definitions()
  960. */
  961. function _image_effect_definitions_sort($a, $b) {
  962. return strcasecmp($a['name'], $b['name']);
  963. }
  964. /**
  965. * Implements hook_entity_presave().
  966. *
  967. * Transforms default image of image field from array into single value at save.
  968. */
  969. function image_entity_presave(EntityInterface $entity, $type) {
  970. $field = FALSE;
  971. if ($entity instanceof FieldInstance) {
  972. $field = $entity->getField();
  973. }
  974. elseif ($entity instanceof Field) {
  975. $field = $entity;
  976. }
  977. if ($field && $field->type == 'image' && is_array($entity->settings['default_image'])) {
  978. if (!empty($entity->settings['default_image'][0])) {
  979. $entity->settings['default_image'] = $entity->settings['default_image'][0];
  980. }
  981. else {
  982. $entity->settings['default_image'] = 0;
  983. }
  984. }
  985. }

Functions

Namesort descending Description
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_entity_presave Implements hook_entity_presave().
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_download Implements hook_file_download().
image_file_move Implements hook_file_move().
image_file_predelete Implements hook_file_predelete().
image_filter_keyword Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
image_form_system_file_system_settings_alter Implements hook_form_FORM_ID_alter().
image_help Implements hook_help().
image_menu Implements hook_menu().
image_path_flush Clears cached versions of a specific file in all styles.
image_permission Implements hook_permission().
image_style_create_derivative Creates a new image derivative based on an image style.
image_style_deliver Page callback: Generates a derivative, given a style and image path.
image_style_entity_uri Entity URI callback for image style.
image_style_flush Flushes cached media for a style.
image_style_load Loads an ImageStyle object.
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_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.