image.module 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  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[7], $arg[5]);
  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. * @param $scheme
  730. * The file scheme, for example 'public' for public files.
  731. */
  732. function image_style_deliver($style, $scheme) {
  733. $args = func_get_args();
  734. array_shift($args);
  735. array_shift($args);
  736. $target = implode('/', $args);
  737. // Check that the style is defined, the scheme is valid, and the image
  738. // derivative token is valid. (Sites which require image derivatives to be
  739. // generated without a token can set the 'image_allow_insecure_derivatives'
  740. // variable to TRUE to bypass the latter check, but this will increase the
  741. // site's vulnerability to denial-of-service attacks. To prevent this
  742. // variable from leaving the site vulnerable to the most serious attacks, a
  743. // token is always required when a derivative of a derivative is requested.)
  744. $valid = !empty($style) && file_stream_wrapper_valid_scheme($scheme);
  745. if (!variable_get('image_allow_insecure_derivatives', FALSE) || strpos(ltrim($target, '\/'), 'styles/') === 0) {
  746. $valid = $valid && isset($_GET[IMAGE_DERIVATIVE_TOKEN]) && $_GET[IMAGE_DERIVATIVE_TOKEN] === image_style_path_token($style['name'], $scheme . '://' . $target);
  747. }
  748. if (!$valid) {
  749. return MENU_ACCESS_DENIED;
  750. }
  751. $image_uri = $scheme . '://' . $target;
  752. $derivative_uri = image_style_path($style['name'], $image_uri);
  753. // If using the private scheme, let other modules provide headers and
  754. // control access to the file.
  755. if ($scheme == 'private') {
  756. if (file_exists($derivative_uri)) {
  757. file_download($scheme, file_uri_target($derivative_uri));
  758. }
  759. else {
  760. $headers = file_download_headers($image_uri);
  761. if (empty($headers)) {
  762. return MENU_ACCESS_DENIED;
  763. }
  764. if (count($headers)) {
  765. foreach ($headers as $name => $value) {
  766. drupal_add_http_header($name, $value);
  767. }
  768. }
  769. }
  770. }
  771. // Confirm that the original source image exists before trying to process it.
  772. if (!is_file($image_uri)) {
  773. 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));
  774. return MENU_NOT_FOUND;
  775. }
  776. // Don't start generating the image if the derivative already exists or if
  777. // generation is in progress in another thread.
  778. $lock_name = 'image_style_deliver:' . $style['name'] . ':' . drupal_hash_base64($image_uri);
  779. if (!file_exists($derivative_uri)) {
  780. $lock_acquired = lock_acquire($lock_name);
  781. if (!$lock_acquired) {
  782. // Tell client to retry again in 3 seconds. Currently no browsers are known
  783. // to support Retry-After.
  784. drupal_add_http_header('Status', '503 Service Unavailable');
  785. drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
  786. drupal_add_http_header('Retry-After', 3);
  787. print t('Image generation in progress. Try again shortly.');
  788. drupal_exit();
  789. }
  790. }
  791. // Try to generate the image, unless another thread just did it while we were
  792. // acquiring the lock.
  793. $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
  794. if (!empty($lock_acquired)) {
  795. lock_release($lock_name);
  796. }
  797. if ($success) {
  798. $image = image_load($derivative_uri);
  799. file_transfer($image->source, array('Content-Type' => $image->info['mime_type'], 'Content-Length' => $image->info['file_size']));
  800. }
  801. else {
  802. watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
  803. drupal_add_http_header('Status', '500 Internal Server Error');
  804. drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
  805. print t('Error generating image.');
  806. drupal_exit();
  807. }
  808. }
  809. /**
  810. * Creates a new image derivative based on an image style.
  811. *
  812. * Generates an image derivative by creating the destination folder (if it does
  813. * not already exist), applying all image effects defined in $style['effects'],
  814. * and saving a cached version of the resulting image.
  815. *
  816. * @param $style
  817. * An image style array.
  818. * @param $source
  819. * Path of the source file.
  820. * @param $destination
  821. * Path or URI of the destination file.
  822. *
  823. * @return
  824. * TRUE if an image derivative was generated, or FALSE if the image derivative
  825. * could not be generated.
  826. *
  827. * @see image_style_load()
  828. */
  829. function image_style_create_derivative($style, $source, $destination) {
  830. // If the source file doesn't exist, return FALSE without creating folders.
  831. if (!$image = image_load($source)) {
  832. return FALSE;
  833. }
  834. // Get the folder for the final location of this style.
  835. $directory = drupal_dirname($destination);
  836. // Build the destination folder tree if it doesn't already exist.
  837. if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  838. watchdog('image', 'Failed to create style directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
  839. return FALSE;
  840. }
  841. foreach ($style['effects'] as $effect) {
  842. image_effect_apply($image, $effect);
  843. }
  844. if (!image_save($image, $destination)) {
  845. if (file_exists($destination)) {
  846. watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $destination), WATCHDOG_ERROR);
  847. }
  848. return FALSE;
  849. }
  850. return TRUE;
  851. }
  852. /**
  853. * Determines the dimensions of the styled image.
  854. *
  855. * Applies all of an image style's effects to $dimensions.
  856. *
  857. * @param $style_name
  858. * The name of the style to be applied.
  859. * @param $dimensions
  860. * Dimensions to be modified - an array with components width and height, in
  861. * pixels.
  862. */
  863. function image_style_transform_dimensions($style_name, array &$dimensions) {
  864. module_load_include('inc', 'image', 'image.effects');
  865. $style = image_style_load($style_name);
  866. if (!is_array($style)) {
  867. return;
  868. }
  869. foreach ($style['effects'] as $effect) {
  870. if (isset($effect['dimensions passthrough'])) {
  871. continue;
  872. }
  873. if (isset($effect['dimensions callback'])) {
  874. $effect['dimensions callback']($dimensions, $effect['data']);
  875. }
  876. else {
  877. $dimensions['width'] = $dimensions['height'] = NULL;
  878. }
  879. }
  880. }
  881. /**
  882. * Flushes cached media for a style.
  883. *
  884. * @param $style
  885. * An image style array.
  886. */
  887. function image_style_flush($style) {
  888. // Delete the style directory in each registered wrapper.
  889. $wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE);
  890. foreach ($wrappers as $wrapper => $wrapper_data) {
  891. if (file_exists($directory = $wrapper . '://styles/' . $style['name'])) {
  892. file_unmanaged_delete_recursive($directory);
  893. }
  894. }
  895. // Let other modules update as necessary on flush.
  896. module_invoke_all('image_style_flush', $style);
  897. // Clear image style and effect caches.
  898. cache_clear_all('image_styles', 'cache');
  899. cache_clear_all('image_effects:', 'cache', TRUE);
  900. drupal_static_reset('image_styles');
  901. drupal_static_reset('image_effects');
  902. // Clear field caches so that formatters may be added for this style.
  903. field_info_cache_clear();
  904. drupal_theme_rebuild();
  905. // Clear page caches when flushing.
  906. if (module_exists('block')) {
  907. cache_clear_all('*', 'cache_block', TRUE);
  908. }
  909. cache_clear_all('*', 'cache_page', TRUE);
  910. }
  911. /**
  912. * Returns the URL for an image derivative given a style and image path.
  913. *
  914. * @param $style_name
  915. * The name of the style to be used with this image.
  916. * @param $path
  917. * The path to the image.
  918. *
  919. * @return
  920. * The absolute URL where a style image can be downloaded, suitable for use
  921. * in an <img> tag. Requesting the URL will cause the image to be created.
  922. * @see image_style_deliver()
  923. */
  924. function image_style_url($style_name, $path) {
  925. $uri = image_style_path($style_name, $path);
  926. // The passed-in $path variable can be either a relative path or a full URI.
  927. $original_uri = file_uri_scheme($path) ? file_stream_wrapper_uri_normalize($path) : file_build_uri($path);
  928. // The token query is added even if the 'image_allow_insecure_derivatives'
  929. // variable is TRUE, so that the emitted links remain valid if it is changed
  930. // back to the default FALSE.
  931. // However, sites which need to prevent the token query from being emitted at
  932. // all can additionally set the 'image_suppress_itok_output' variable to TRUE
  933. // to achieve that (if both are set, the security token will neither be
  934. // emitted in the image derivative URL nor checked for in
  935. // image_style_deliver()).
  936. $token_query = array();
  937. if (!variable_get('image_suppress_itok_output', FALSE)) {
  938. $token_query = array(IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, $original_uri));
  939. }
  940. // If not using clean URLs, the image derivative callback is only available
  941. // with the query string. If the file does not exist, use url() to ensure
  942. // that it is included. Once the file exists it's fine to fall back to the
  943. // actual file path, this avoids bootstrapping PHP once the files are built.
  944. if (!variable_get('clean_url') && file_uri_scheme($uri) == 'public' && !file_exists($uri)) {
  945. $directory_path = file_stream_wrapper_get_instance_by_uri($uri)->getDirectoryPath();
  946. return url($directory_path . '/' . file_uri_target($uri), array('absolute' => TRUE, 'query' => $token_query));
  947. }
  948. $file_url = file_create_url($uri);
  949. // Append the query string with the token, if necessary.
  950. if ($token_query) {
  951. $file_url .= (strpos($file_url, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($token_query);
  952. }
  953. return $file_url;
  954. }
  955. /**
  956. * Generates a token to protect an image style derivative.
  957. *
  958. * This prevents unauthorized generation of an image style derivative,
  959. * which can be costly both in CPU time and disk space.
  960. *
  961. * @param $style_name
  962. * The name of the image style.
  963. * @param $uri
  964. * The URI of the image for this style, for example as returned by
  965. * image_style_path().
  966. *
  967. * @return
  968. * An eight-character token which can be used to protect image style
  969. * derivatives against denial-of-service attacks.
  970. */
  971. function image_style_path_token($style_name, $uri) {
  972. // Return the first eight characters.
  973. return substr(drupal_hmac_base64($style_name . ':' . $uri, drupal_get_private_key() . drupal_get_hash_salt()), 0, 8);
  974. }
  975. /**
  976. * Returns the URI of an image when using a style.
  977. *
  978. * The path returned by this function may not exist. The default generation
  979. * method only creates images when they are requested by a user's browser.
  980. *
  981. * @param $style_name
  982. * The name of the style to be used with this image.
  983. * @param $uri
  984. * The URI or path to the image.
  985. *
  986. * @return
  987. * The URI to an image style image.
  988. * @see image_style_url()
  989. */
  990. function image_style_path($style_name, $uri) {
  991. $scheme = file_uri_scheme($uri);
  992. if ($scheme) {
  993. $path = file_uri_target($uri);
  994. }
  995. else {
  996. $path = $uri;
  997. $scheme = file_default_scheme();
  998. }
  999. return $scheme . '://styles/' . $style_name . '/' . $scheme . '/' . $path;
  1000. }
  1001. /**
  1002. * Saves a default image style to the database.
  1003. *
  1004. * @param style
  1005. * An image style array provided by a module.
  1006. *
  1007. * @return
  1008. * An image style array. The returned style array will include the new 'isid'
  1009. * assigned to the style.
  1010. */
  1011. function image_default_style_save($style) {
  1012. $style = image_style_save($style);
  1013. $effects = array();
  1014. foreach ($style['effects'] as $effect) {
  1015. $effect['isid'] = $style['isid'];
  1016. $effect = image_effect_save($effect);
  1017. $effects[$effect['ieid']] = $effect;
  1018. }
  1019. $style['effects'] = $effects;
  1020. return $style;
  1021. }
  1022. /**
  1023. * Reverts the changes made by users to a default image style.
  1024. *
  1025. * @param style
  1026. * An image style array.
  1027. * @return
  1028. * Boolean TRUE if the operation succeeded.
  1029. */
  1030. function image_default_style_revert($style) {
  1031. image_style_flush($style);
  1032. db_delete('image_effects')->condition('isid', $style['isid'])->execute();
  1033. db_delete('image_styles')->condition('isid', $style['isid'])->execute();
  1034. return TRUE;
  1035. }
  1036. /**
  1037. * Returns a set of image effects.
  1038. *
  1039. * These image effects are exposed by modules implementing
  1040. * hook_image_effect_info().
  1041. *
  1042. * @return
  1043. * An array of image effects to be used when transforming images.
  1044. * @see hook_image_effect_info()
  1045. * @see image_effect_definition_load()
  1046. */
  1047. function image_effect_definitions() {
  1048. global $language;
  1049. // hook_image_effect_info() includes translated strings, so each language is
  1050. // cached separately.
  1051. $langcode = $language->language;
  1052. $effects = &drupal_static(__FUNCTION__);
  1053. if (!isset($effects)) {
  1054. if ($cache = cache_get("image_effects:$langcode")) {
  1055. $effects = $cache->data;
  1056. }
  1057. else {
  1058. $effects = array();
  1059. include_once DRUPAL_ROOT . '/modules/image/image.effects.inc';
  1060. foreach (module_implements('image_effect_info') as $module) {
  1061. foreach (module_invoke($module, 'image_effect_info') as $name => $effect) {
  1062. // Ensure the current toolkit supports the effect.
  1063. $effect['module'] = $module;
  1064. $effect['name'] = $name;
  1065. $effect['data'] = isset($effect['data']) ? $effect['data'] : array();
  1066. $effects[$name] = $effect;
  1067. }
  1068. }
  1069. uasort($effects, '_image_effect_definitions_sort');
  1070. drupal_alter('image_effect_info', $effects);
  1071. cache_set("image_effects:$langcode", $effects);
  1072. }
  1073. }
  1074. return $effects;
  1075. }
  1076. /**
  1077. * Loads the definition for an image effect.
  1078. *
  1079. * The effect definition is a set of core properties for an image effect, not
  1080. * containing any user-settings. The definition defines various functions to
  1081. * call when configuring or executing an image effect. This loader is mostly for
  1082. * internal use within image.module. Use image_effect_load() or
  1083. * image_style_load() to get image effects that contain configuration.
  1084. *
  1085. * @param $effect
  1086. * The name of the effect definition to load.
  1087. * @param $style
  1088. * An image style array to which this effect will be added.
  1089. *
  1090. * @return
  1091. * An array containing the image effect definition with the following keys:
  1092. * - "effect": The unique name for the effect being performed. Usually prefixed
  1093. * with the name of the module providing the effect.
  1094. * - "module": The module providing the effect.
  1095. * - "help": A description of the effect.
  1096. * - "function": The name of the function that will execute the effect.
  1097. * - "form": (optional) The name of a function to configure the effect.
  1098. * - "summary": (optional) The name of a theme function that will display a
  1099. * one-line summary of the effect. Does not include the "theme_" prefix.
  1100. */
  1101. function image_effect_definition_load($effect, $style_name = NULL) {
  1102. $definitions = image_effect_definitions();
  1103. // If a style is specified, do not allow loading of default style
  1104. // effects.
  1105. if (isset($style_name)) {
  1106. $style = image_style_load($style_name, NULL);
  1107. if ($style['storage'] == IMAGE_STORAGE_DEFAULT) {
  1108. return FALSE;
  1109. }
  1110. }
  1111. return isset($definitions[$effect]) ? $definitions[$effect] : FALSE;
  1112. }
  1113. /**
  1114. * Loads all image effects from the database.
  1115. *
  1116. * @return
  1117. * An array of all image effects.
  1118. * @see image_effect_load()
  1119. */
  1120. function image_effects() {
  1121. $effects = &drupal_static(__FUNCTION__);
  1122. if (!isset($effects)) {
  1123. $effects = array();
  1124. // Add database image effects.
  1125. $result = db_select('image_effects', NULL, array('fetch' => PDO::FETCH_ASSOC))
  1126. ->fields('image_effects')
  1127. ->orderBy('image_effects.weight', 'ASC')
  1128. ->execute();
  1129. foreach ($result as $effect) {
  1130. $effect['data'] = unserialize($effect['data']);
  1131. $definition = image_effect_definition_load($effect['name']);
  1132. // Do not load image effects whose definition cannot be found.
  1133. if ($definition) {
  1134. $effect = array_merge($definition, $effect);
  1135. $effects[$effect['ieid']] = $effect;
  1136. }
  1137. }
  1138. }
  1139. return $effects;
  1140. }
  1141. /**
  1142. * Loads a single image effect.
  1143. *
  1144. * @param $ieid
  1145. * The image effect ID.
  1146. * @param $style_name
  1147. * The image style name.
  1148. * @param $include
  1149. * If set, this loader will restrict to a specific type of image style, may be
  1150. * one of the defined Image style storage constants.
  1151. *
  1152. * @return
  1153. * An image effect array, consisting of the following keys:
  1154. * - "ieid": The unique image effect ID.
  1155. * - "isid": The unique image style ID that contains this image effect.
  1156. * - "weight": The weight of this image effect within the image style.
  1157. * - "name": The name of the effect definition that powers this image effect.
  1158. * - "data": An array of configuration options for this image effect.
  1159. * Besides these keys, the entirety of the image definition is merged into
  1160. * the image effect array. Returns FALSE if the specified effect cannot be
  1161. * found.
  1162. * @see image_style_load()
  1163. * @see image_effect_definition_load()
  1164. */
  1165. function image_effect_load($ieid, $style_name, $include = NULL) {
  1166. if (($style = image_style_load($style_name, NULL, $include)) && isset($style['effects'][$ieid])) {
  1167. return $style['effects'][$ieid];
  1168. }
  1169. return FALSE;
  1170. }
  1171. /**
  1172. * Saves an image effect.
  1173. *
  1174. * @param $effect
  1175. * An image effect array.
  1176. *
  1177. * @return
  1178. * An image effect array. In the case of a new effect, 'ieid' will be set.
  1179. */
  1180. function image_effect_save($effect) {
  1181. if (!empty($effect['ieid'])) {
  1182. drupal_write_record('image_effects', $effect, 'ieid');
  1183. }
  1184. else {
  1185. drupal_write_record('image_effects', $effect);
  1186. }
  1187. $style = image_style_load(NULL, $effect['isid']);
  1188. image_style_flush($style);
  1189. return $effect;
  1190. }
  1191. /**
  1192. * Deletes an image effect.
  1193. *
  1194. * @param $effect
  1195. * An image effect array.
  1196. */
  1197. function image_effect_delete($effect) {
  1198. db_delete('image_effects')->condition('ieid', $effect['ieid'])->execute();
  1199. $style = image_style_load(NULL, $effect['isid']);
  1200. image_style_flush($style);
  1201. }
  1202. /**
  1203. * Applies an image effect to the image object.
  1204. *
  1205. * @param $image
  1206. * An image object returned by image_load().
  1207. * @param $effect
  1208. * An image effect array.
  1209. *
  1210. * @return
  1211. * TRUE on success. FALSE if unable to perform the image effect on the image.
  1212. */
  1213. function image_effect_apply($image, $effect) {
  1214. module_load_include('inc', 'image', 'image.effects');
  1215. $function = $effect['effect callback'];
  1216. if (function_exists($function)) {
  1217. return $function($image, $effect['data']);
  1218. }
  1219. return FALSE;
  1220. }
  1221. /**
  1222. * Returns HTML for an image using a specific image style.
  1223. *
  1224. * @param $variables
  1225. * An associative array containing:
  1226. * - style_name: The name of the style to be used to alter the original image.
  1227. * - path: The path of the image file relative to the Drupal files directory.
  1228. * This function does not work with images outside the files directory nor
  1229. * with remotely hosted images. This should be in a format such as
  1230. * 'images/image.jpg', or using a stream wrapper such as
  1231. * 'public://images/image.jpg'.
  1232. * - width: The width of the source image (if known).
  1233. * - height: The height of the source image (if known).
  1234. * - alt: The alternative text for text-based browsers.
  1235. * - title: The title text is displayed when the image is hovered in some
  1236. * popular browsers.
  1237. * - attributes: Associative array of attributes to be placed in the img tag.
  1238. *
  1239. * @ingroup themeable
  1240. */
  1241. function theme_image_style($variables) {
  1242. // Determine the dimensions of the styled image.
  1243. $dimensions = array(
  1244. 'width' => $variables['width'],
  1245. 'height' => $variables['height'],
  1246. );
  1247. image_style_transform_dimensions($variables['style_name'], $dimensions);
  1248. $variables['width'] = $dimensions['width'];
  1249. $variables['height'] = $dimensions['height'];
  1250. // Determine the URL for the styled image.
  1251. $variables['path'] = image_style_url($variables['style_name'], $variables['path']);
  1252. return theme('image', $variables);
  1253. }
  1254. /**
  1255. * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
  1256. *
  1257. * @param $value
  1258. * @param $current_pixels
  1259. * @param $new_pixels
  1260. */
  1261. function image_filter_keyword($value, $current_pixels, $new_pixels) {
  1262. switch ($value) {
  1263. case 'top':
  1264. case 'left':
  1265. return 0;
  1266. case 'bottom':
  1267. case 'right':
  1268. return $current_pixels - $new_pixels;
  1269. case 'center':
  1270. return $current_pixels / 2 - $new_pixels / 2;
  1271. }
  1272. return $value;
  1273. }
  1274. /**
  1275. * Internal function for sorting image effect definitions through uasort().
  1276. *
  1277. * @see image_effect_definitions()
  1278. */
  1279. function _image_effect_definitions_sort($a, $b) {
  1280. return strcasecmp($a['name'], $b['name']);
  1281. }