Drupal investigation

image.module 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. <?php
  2. /**
  3. * @file
  4. * Exposes global functionality for creating image styles.
  5. */
  6. use Drupal\Core\Entity\EntityInterface;
  7. use Drupal\Core\Routing\RouteMatchInterface;
  8. use Drupal\file\Entity\File;
  9. use Drupal\field\FieldStorageConfigInterface;
  10. use Drupal\field\FieldConfigInterface;
  11. use Drupal\image\Entity\ImageStyle;
  12. /**
  13. * Image style constant for user presets in the database.
  14. *
  15. * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
  16. */
  17. const IMAGE_STORAGE_NORMAL = 1;
  18. /**
  19. * Image style constant for user presets that override module-defined presets.
  20. *
  21. * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
  22. */
  23. const IMAGE_STORAGE_OVERRIDE = 2;
  24. /**
  25. * Image style constant for module-defined presets in code.
  26. *
  27. * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
  28. */
  29. const IMAGE_STORAGE_DEFAULT = 4;
  30. /**
  31. * Image style constant to represent an editable preset.
  32. *
  33. * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
  34. */
  35. define('IMAGE_STORAGE_EDITABLE', IMAGE_STORAGE_NORMAL | IMAGE_STORAGE_OVERRIDE);
  36. /**
  37. * Image style constant to represent any module-based preset.
  38. *
  39. * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
  40. */
  41. define('IMAGE_STORAGE_MODULE', IMAGE_STORAGE_OVERRIDE | IMAGE_STORAGE_DEFAULT);
  42. /**
  43. * The name of the query parameter for image derivative tokens.
  44. */
  45. define('IMAGE_DERIVATIVE_TOKEN', 'itok');
  46. /**
  47. * Implements hook_help().
  48. */
  49. function image_help($route_name, RouteMatchInterface $route_match) {
  50. switch ($route_name) {
  51. case 'help.page.image':
  52. $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#';
  53. $output = '';
  54. $output .= '<h3>' . t('About') . '</h3>';
  55. $output .= '<p>' . t('The Image module allows you to create fields that contain image files and to configure <a href=":image_styles">Image styles</a> that can be used to manipulate the display of images. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for terminology and general information on entities, fields, and how to create and manage fields. For more information, see the <a href=":image_documentation">online documentation for the Image module</a>.', [':image_styles' => \Drupal::url('entity.image_style.collection'), ':field' => \Drupal::url('help.page', ['name' => 'field']), ':field_ui' => $field_ui_url, ':image_documentation' => 'https://www.drupal.org/documentation/modules/image']) . '</p>';
  56. $output .= '<h3>' . t('Uses') . '</h3>';
  57. $output .= '<dt>' . t('Defining image styles') . '</dt>';
  58. $output .= '<dd>' . t('The concept of image styles is that you can upload a single image but display it in several ways; each display variation, or <em>image style</em>, is the result of applying one or more <em>effects</em> to the original image. As an example, you might upload a high-resolution image with a 4:3 aspect ratio, and display it scaled down, square cropped, or black-and-white (or any combination of these effects). The Image module provides a way to do this efficiently: you configure an image style with the desired effects on the <a href=":image">Image styles page</a>, and the first time a particular image is requested in that style, the effects are applied. The resulting image is saved, and the next time that same style is requested, the saved image is retrieved without the need to recalculate the effects. Drupal core provides several effects that you can use to define styles; others may be provided by contributed modules.', [':image' => \Drupal::url('entity.image_style.collection')]);
  59. $output .= '<dt>' . t('Naming image styles') . '</dt>';
  60. $output .= '<dd>' . t('When you define an image style, you will need to choose a displayed name and a machine name. The displayed name is shown in administrative pages, and the machine name is used to generate the URL for accessing an image processed in that style. There are two common approaches to naming image styles: either based on the effects being applied (for example, <em>Square 85x85</em>), or based on where you plan to use it (for example, <em>Profile picture</em>).') . '</dd>';
  61. $output .= '<dt>' . t('Configuring image fields') . '</dt>';
  62. $output .= '<dd>' . t('A few of the settings for image fields are defined once when you create the field and cannot be changed later; these include the choice of public or private file storage and the number of images that can be stored in the field. The rest of the settings can be edited later; these settings include the field label, help text, allowed file extensions, image resolution restrictions, and the subdirectory in the public or private file storage where the images will be stored. The editable settings can also have different values for different entity sub-types; for instance, if your image field is used on both Page and Article content types, you can store the files in a different subdirectory for the two content types.') . '</dd>';
  63. $output .= '<dd>' . t('For accessibility and search engine optimization, all images that convey meaning on web sites should have alternate text. Drupal also allows entry of title text for images, but it can lead to confusion for screen reader users and its use is not recommended. Image fields can be configured so that alternate and title text fields are enabled or disabled; if enabled, the fields can be set to be required. The recommended setting is to enable and require alternate text and disable title text.') . '</dd>';
  64. $output .= '<dd>' . t('When you create an image field, you will need to choose whether the uploaded images will be stored in the public or private file directory defined in your settings.php file and shown on the <a href=":file-system">File system page</a>. This choice cannot be changed later. You can also configure your field to store files in a subdirectory of the public or private directory; this setting can be changed later and can be different for each entity sub-type using the field. For more information on file storage, see the <a href=":system-help">System module help page</a>.', [':file-system' => \Drupal::url('system.file_system_settings'), ':system-help' => \Drupal::url('help.page', ['name' => 'system'])]) . '</dd>';
  65. $output .= '<dd>' . t('The maximum file size that can be uploaded is limited by PHP settings of the server, but you can restrict it further by configuring a <em>Maximum upload size</em> in the field settings (this setting can be changed later). The maximum file size, either from PHP server settings or field configuration, is automatically displayed to users in the help text of the image field.') . '</dd>';
  66. $output .= '<dd>' . t('You can also configure a minimum and/or maximum resolution for uploaded images. Images that are too small will be rejected. Images that are to large will be resized. During the resizing the <a href="http://wikipedia.org/wiki/Exchangeable_image_file_format">EXIF data</a> in the image will be lost.') . '</dd>';
  67. $output .= '<dd>' . t('You can also configure a default image that will be used if no image is uploaded in an image field. This default can be defined for all instances of the field in the field storage settings when you create a field, and the setting can be overridden for each entity sub-type that uses the field.') . '</dd>';
  68. $output .= '<dt>' . t('Configuring displays and form displays') . '</dt>';
  69. $output .= '<dd>' . t('On the <em>Manage display</em> page, you can choose the image formatter, which determines the image style used to display the image in each display mode and whether or not to display the image as a link. On the <em>Manage form display</em> page, you can configure the image upload widget, including setting the preview image style shown on the entity edit form.') . '</dd>';
  70. $output .= '</dl>';
  71. return $output;
  72. case 'entity.image_style.collection':
  73. 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>';
  74. case 'image.effect_add_form':
  75. $effect = \Drupal::service('plugin.manager.image.effect')->getDefinition($route_match->getParameter('image_effect'));
  76. return isset($effect['description']) ? ('<p>' . $effect['description'] . '</p>') : NULL;
  77. case 'image.effect_edit_form':
  78. $effect = $route_match->getParameter('image_style')->getEffect($route_match->getParameter('image_effect'));
  79. $effect_definition = $effect->getPluginDefinition();
  80. return isset($effect_definition['description']) ? ('<p>' . $effect_definition['description'] . '</p>') : NULL;
  81. }
  82. }
  83. /**
  84. * Implements hook_theme().
  85. */
  86. function image_theme() {
  87. return [
  88. // Theme functions in image.module.
  89. 'image_style' => [
  90. // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
  91. // allows the alt attribute to be omitted in some cases. Therefore,
  92. // default the alt attribute to an empty string, but allow code using
  93. // '#theme' => 'image_style' to pass explicit NULL for it to be omitted.
  94. // Usually, neither omission nor an empty string satisfies accessibility
  95. // requirements, so it is strongly encouraged for code using '#theme' =>
  96. // 'image_style' to pass a meaningful value for the alt variable.
  97. // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
  98. // - http://www.w3.org/TR/xhtml1/dtds.html
  99. // - http://dev.w3.org/html5/spec/Overview.html#alt
  100. // The title attribute is optional in all cases, so it is omitted by
  101. // default.
  102. 'variables' => [
  103. 'style_name' => NULL,
  104. 'uri' => NULL,
  105. 'width' => NULL,
  106. 'height' => NULL,
  107. 'alt' => '',
  108. 'title' => NULL,
  109. 'attributes' => [],
  110. ],
  111. ],
  112. // Theme functions in image.admin.inc.
  113. 'image_style_preview' => [
  114. 'variables' => ['style' => NULL],
  115. 'file' => 'image.admin.inc',
  116. ],
  117. 'image_anchor' => [
  118. 'render element' => 'element',
  119. 'file' => 'image.admin.inc',
  120. ],
  121. 'image_resize_summary' => [
  122. 'variables' => ['data' => NULL, 'effect' => []],
  123. ],
  124. 'image_scale_summary' => [
  125. 'variables' => ['data' => NULL, 'effect' => []],
  126. ],
  127. 'image_crop_summary' => [
  128. 'variables' => ['data' => NULL, 'effect' => []],
  129. ],
  130. 'image_rotate_summary' => [
  131. 'variables' => ['data' => NULL, 'effect' => []],
  132. ],
  133. // Theme functions in image.field.inc.
  134. 'image_widget' => [
  135. 'render element' => 'element',
  136. 'file' => 'image.field.inc',
  137. ],
  138. 'image_formatter' => [
  139. 'variables' => ['item' => NULL, 'item_attributes' => NULL, 'url' => NULL, 'image_style' => NULL],
  140. 'file' => 'image.field.inc',
  141. ],
  142. ];
  143. }
  144. /**
  145. * Implements hook_file_download().
  146. *
  147. * Control the access to files underneath the styles directory.
  148. */
  149. function image_file_download($uri) {
  150. $path = file_uri_target($uri);
  151. // Private file access for image style derivatives.
  152. if (strpos($path, 'styles/') === 0) {
  153. $args = explode('/', $path);
  154. // Discard "styles", style name, and scheme from the path
  155. $args = array_slice($args, 3);
  156. // Then the remaining parts are the path to the image.
  157. $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
  158. // Check that the file exists and is an image.
  159. $image = \Drupal::service('image.factory')->get($uri);
  160. if ($image->isValid()) {
  161. // Check the permissions of the original to grant access to this image.
  162. $headers = \Drupal::moduleHandler()->invokeAll('file_download', [$original_uri]);
  163. // Confirm there's at least one module granting access and none denying access.
  164. if (!empty($headers) && !in_array(-1, $headers)) {
  165. return [
  166. // Send headers describing the image's size, and MIME-type.
  167. 'Content-Type' => $image->getMimeType(),
  168. 'Content-Length' => $image->getFileSize(),
  169. // By not explicitly setting them here, this uses normal Drupal
  170. // Expires, Cache-Control and ETag headers to prevent proxy or
  171. // browser caching of private images.
  172. ];
  173. }
  174. }
  175. return -1;
  176. }
  177. }
  178. /**
  179. * Implements hook_file_move().
  180. */
  181. function image_file_move(File $file, File $source) {
  182. // Delete any image derivatives at the original image path.
  183. image_path_flush($source->getFileUri());
  184. }
  185. /**
  186. * Implements hook_ENTITY_TYPE_predelete() for file entities.
  187. */
  188. function image_file_predelete(File $file) {
  189. // Delete any image derivatives of this image.
  190. image_path_flush($file->getFileUri());
  191. }
  192. /**
  193. * Clears cached versions of a specific file in all styles.
  194. *
  195. * @param $path
  196. * The Drupal file path to the original image.
  197. */
  198. function image_path_flush($path) {
  199. $styles = ImageStyle::loadMultiple();
  200. foreach ($styles as $style) {
  201. $style->flush($path);
  202. }
  203. }
  204. /**
  205. * Gets an array of image styles suitable for using as select list options.
  206. *
  207. * @param $include_empty
  208. * If TRUE a '- None -' option will be inserted in the options array.
  209. * @return
  210. * Array of image styles both key and value are set to style name.
  211. */
  212. function image_style_options($include_empty = TRUE) {
  213. $styles = ImageStyle::loadMultiple();
  214. $options = [];
  215. if ($include_empty && !empty($styles)) {
  216. $options[''] = t('- None -');
  217. }
  218. foreach ($styles as $name => $style) {
  219. $options[$name] = $style->label();
  220. }
  221. if (empty($options)) {
  222. $options[''] = t('No defined styles');
  223. }
  224. return $options;
  225. }
  226. /**
  227. * Prepares variables for image style templates.
  228. *
  229. * Default template: image-style.html.twig.
  230. *
  231. * @param array $variables
  232. * An associative array containing:
  233. * - width: The width of the image.
  234. * - height: The height of the image.
  235. * - style_name: The name of the image style to be applied.
  236. * - attributes: Additional attributes to apply to the image.
  237. * - uri: URI of the source image before styling.
  238. * - alt: The alternative text for text-based browsers. HTML 4 and XHTML 1.0
  239. * always require an alt attribute. The HTML 5 draft allows the alt
  240. * attribute to be omitted in some cases. Therefore, this variable defaults
  241. * to an empty string, but can be set to NULL for the attribute to be
  242. * omitted. Usually, neither omission nor an empty string satisfies
  243. * accessibility requirements, so it is strongly encouraged for code using
  244. * '#theme' => 'image_style' to pass a meaningful value for this variable.
  245. * - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
  246. * - http://www.w3.org/TR/xhtml1/dtds.html
  247. * - http://dev.w3.org/html5/spec/Overview.html#alt
  248. * - title: The title text is displayed when the image is hovered in some
  249. * popular browsers.
  250. * - attributes: Associative array of attributes to be placed in the img tag.
  251. */
  252. function template_preprocess_image_style(&$variables) {
  253. $style = ImageStyle::load($variables['style_name']);
  254. // Determine the dimensions of the styled image.
  255. $dimensions = [
  256. 'width' => $variables['width'],
  257. 'height' => $variables['height'],
  258. ];
  259. $style->transformDimensions($dimensions, $variables['uri']);
  260. $variables['image'] = [
  261. '#theme' => 'image',
  262. '#width' => $dimensions['width'],
  263. '#height' => $dimensions['height'],
  264. '#attributes' => $variables['attributes'],
  265. '#uri' => $style->buildUrl($variables['uri']),
  266. '#style_name' => $variables['style_name'],
  267. ];
  268. if (isset($variables['alt']) || array_key_exists('alt', $variables)) {
  269. $variables['image']['#alt'] = $variables['alt'];
  270. }
  271. if (isset($variables['title']) || array_key_exists('title', $variables)) {
  272. $variables['image']['#title'] = $variables['title'];
  273. }
  274. }
  275. /**
  276. * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
  277. *
  278. * @param $value
  279. * @param $current_pixels
  280. * @param $new_pixels
  281. */
  282. function image_filter_keyword($value, $current_pixels, $new_pixels) {
  283. switch ($value) {
  284. case 'top':
  285. case 'left':
  286. return 0;
  287. case 'bottom':
  288. case 'right':
  289. return $current_pixels - $new_pixels;
  290. case 'center':
  291. return $current_pixels / 2 - $new_pixels / 2;
  292. }
  293. return $value;
  294. }
  295. /**
  296. * Implements hook_entity_presave().
  297. *
  298. * Transforms default image of image field from array into single value at save.
  299. */
  300. function image_entity_presave(EntityInterface $entity) {
  301. // Get the default image settings, return if not saving an image field storage
  302. // or image field entity.
  303. $default_image = [];
  304. if (($entity instanceof FieldStorageConfigInterface || $entity instanceof FieldConfigInterface) && $entity->getType() == 'image') {
  305. $default_image = $entity->getSetting('default_image');
  306. }
  307. else {
  308. return;
  309. }
  310. if ($entity->isSyncing()) {
  311. return;
  312. }
  313. $uuid = $default_image['uuid'];
  314. if ($uuid) {
  315. $original_uuid = isset($entity->original) ? $entity->original->getSetting('default_image')['uuid'] : NULL;
  316. if ($uuid != $original_uuid) {
  317. $file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid);
  318. if ($file) {
  319. $image = \Drupal::service('image.factory')->get($file->getFileUri());
  320. $default_image['width'] = $image->getWidth();
  321. $default_image['height'] = $image->getHeight();
  322. }
  323. else {
  324. $default_image['uuid'] = NULL;
  325. }
  326. }
  327. }
  328. // Both FieldStorageConfigInterface and FieldConfigInterface have a
  329. // setSetting() method.
  330. $entity->setSetting('default_image', $default_image);
  331. }
  332. /**
  333. * Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.
  334. */
  335. function image_field_storage_config_update(FieldStorageConfigInterface $field_storage) {
  336. if ($field_storage->getType() != 'image') {
  337. // Only act on image fields.
  338. return;
  339. }
  340. $prior_field_storage = $field_storage->original;
  341. // The value of a managed_file element can be an array if #extended == TRUE.
  342. $uuid_new = $field_storage->getSetting('default_image')['uuid'];
  343. $uuid_old = $prior_field_storage->getSetting('default_image')['uuid'];
  344. $file_new = $uuid_new ? \Drupal::entityManager()->loadEntityByUuid('file', $uuid_new) : FALSE;
  345. if ($uuid_new != $uuid_old) {
  346. // Is there a new file?
  347. if ($file_new) {
  348. $file_new->status = FILE_STATUS_PERMANENT;
  349. $file_new->save();
  350. \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field_storage->uuid());
  351. }
  352. // Is there an old file?
  353. if ($uuid_old && ($file_old = \Drupal::entityManager()->loadEntityByUuid('file', $uuid_old))) {
  354. \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field_storage->uuid());
  355. }
  356. }
  357. // If the upload destination changed, then move the file.
  358. if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
  359. $directory = $field_storage->getSetting('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_ENTITY_TYPE_update() for 'field_config'.
  366. */
  367. function image_field_config_update(FieldConfigInterface $field) {
  368. $field_storage = $field->getFieldStorageDefinition();
  369. if ($field_storage->getType() != 'image') {
  370. // Only act on image fields.
  371. return;
  372. }
  373. $prior_instance = $field->original;
  374. $uuid_new = $field->getSetting('default_image')['uuid'];
  375. $uuid_old = $prior_instance->getSetting('default_image')['uuid'];
  376. // If the old and new files do not match, update the default accordingly.
  377. $file_new = $uuid_new ? \Drupal::entityManager()->loadEntityByUuid('file', $uuid_new) : FALSE;
  378. if ($uuid_new != $uuid_old) {
  379. // Save the new file, if present.
  380. if ($file_new) {
  381. $file_new->status = FILE_STATUS_PERMANENT;
  382. $file_new->save();
  383. \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field->uuid());
  384. }
  385. // Delete the old file, if present.
  386. if ($uuid_old && ($file_old = \Drupal::entityManager()->loadEntityByUuid('file', $uuid_old))) {
  387. \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field->uuid());
  388. }
  389. }
  390. // If the upload destination changed, then move the file.
  391. if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
  392. $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
  393. file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  394. file_move($file_new, $directory . $file_new->filename);
  395. }
  396. }
  397. /**
  398. * Implements hook_ENTITY_TYPE_delete() for 'field_storage_config'.
  399. */
  400. function image_field_storage_config_delete(FieldStorageConfigInterface $field) {
  401. if ($field->getType() != 'image') {
  402. // Only act on image fields.
  403. return;
  404. }
  405. // The value of a managed_file element can be an array if #extended == TRUE.
  406. $uuid = $field->getSetting('default_image')['uuid'];
  407. if ($uuid && ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid))) {
  408. \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
  409. }
  410. }
  411. /**
  412. * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
  413. */
  414. function image_field_config_delete(FieldConfigInterface $field) {
  415. $field_storage = $field->getFieldStorageDefinition();
  416. if ($field_storage->getType() != 'image') {
  417. // Only act on image fields.
  418. return;
  419. }
  420. // The value of a managed_file element can be an array if #extended == TRUE.
  421. $uuid = $field->getSetting('default_image')['uuid'];
  422. // Remove the default image when the instance is deleted.
  423. if ($uuid && ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid))) {
  424. \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
  425. }
  426. }