image.module 47 KB

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