imagecache.module

Tracking 6.x-2.x branch
  1. drupal
    1. 5 contributions/imagecache/imagecache.module
    2. 6 contributions/imagecache/imagecache.module

Dynamic image resizer and image cacher.

ImageCache allows you to setup presets for image processing. If an ImageCache derivative doesn't exist the web server's rewrite rules will pass the request to Drupal which in turn hands it off to imagecache to dynamically generate the file.

To view a derivative image you request a special url containing 'imagecache/<presetname>/path/to/file.ext.

Presets can be managed at http://example.com/admin/build/imagecache.

To view a derivative image you request a special url containing 'imagecache/<presetname>/path/to/file.ext.

If you had a preset names 'thumbnail' and you wanted to see the thumbnail version of http://example.com/files/path/to/myimage.jpg you would use http://example.com/files/imagecache/thumbnail/path/to/myimage.jpg

ImageCache provides formatters for CCK Imagefields and is leveraged by several other modules. ImageCache also relies heavily on ImageAPI for it's image processing. If there are errors with actual image processing look to ImageAPI first.

@todo: add watermarking capabilities.

Functions & methods

NameDescription
imagecache_action
imagecache_action_definition
imagecache_action_definitionsPull in actions exposed by other modules using hook_imagecache_actions().
imagecache_action_delete
imagecache_action_infoImplementation of hook_action_info().
imagecache_action_load
imagecache_action_save
imagecache_add_jsImagecache JS settings and theme function.
imagecache_build_derivativeCreate a new image based on an image preset.
imagecache_cachecallback for handling public files imagecache requests.
imagecache_cache_privatecallback for handling private files imagecache requests
imagecache_create_pathReturn a file system location that points to the location of a derivative of the original image at @p $path, transformed with the given @p $preset. Keep in mind that the image might not yet exist and won't be created.
imagecache_create_urlReturn a URL that points to the location of a derivative of the original image transformed with the given preset.
imagecache_field_formatter_infoImplementation of hook_field_formatter_info().
imagecache_file_deleteImplementation of filefield.module's hook_file_delete().
imagecache_flush_actionFlush all imagecache presets for a given node.
imagecache_form_system_file_system_settings_alterImplementation of hook_form_FORM_ID_alter.
imagecache_form_system_modules_alterImplementation of hook_form_FORM_ID_alter.
imagecache_generate_actionGenerate imagecache presets for the given node and presets.
imagecache_generate_action_formForm for configuring the generate action.
imagecache_generate_all_actionGenerate all imagecache presets for the given node.
imagecache_generate_imageGenerate a derivative image given presetname and filepath.
imagecache_get_images_in_nodeGiven a node, get all images associated with it.
imagecache_imagecache_actionsImplementation of hook_imagecache_actions.
imagecache_image_flushClear cached versions of a specific file in all presets.
imagecache_menuImplementation of hook_menu().
imagecache_permImplementation of hook_perm().
imagecache_presetLoad a preset by preset_id.
imagecache_presetsGet an array of all presets and their settings.
imagecache_preset_actions
imagecache_preset_by_name
imagecache_preset_delete
imagecache_preset_flushFlush cached media for a preset.
imagecache_preset_saveSave an ImageCache preset.
imagecache_system_file_system_submitRebuild menus to ensure we've got the right files directory callback.
imagecache_themeImplementation of hook_theme().
imagecache_transfer
imagecache_userImplementation of hook_user().
theme_imagecacheCreate and image tag for an imagecache derivative
theme_imagecache_formatter_default
theme_imagecache_formatter_imagelink
theme_imagecache_formatter_linked
theme_imagecache_formatter_path
theme_imagecache_formatter_url
theme_imagecache_imagelinkCreate a link the original image that wraps the derivative image.
_imagecache_apply_actionApply an action to an image.
_imagecache_cacheHandle request validation and responses to ImageCache requests.
_imagecache_cache_set_cache_headersSet file headers that handle "If-Modified-Since" correctly for the given fileinfo.
_imagecache_definitions_sort
_imagecache_keyword_filterAccept a keyword (center, top, left, etc) and return it as an offset in pixels.
_imagecache_menu_access_public_filesMenu access callback for public file transfers.
_imagecache_percent_filterAccept a percentage and return it in pixels.
_imagecache_recursive_deleteRecursively delete all files and folders in the specified filepath, then delete the containing folder.
_imagecache_strip_file_directoryRemove a possible leading file directory path from the given path.

Constants

NameDescription
IMAGECACHE_STORAGE_DEFAULTImagecache preset storage constant for module-defined presets in code.
IMAGECACHE_STORAGE_NORMALImagecache preset storage constant for user-defined presets in the DB.
IMAGECACHE_STORAGE_OVERRIDEImagecache preset storage constant for user-defined presets that override module-defined presets.

File

View source
  1. <?php
  2. /**
  3. * @file
  4. * Dynamic image resizer and image cacher.
  5. *
  6. * ImageCache allows you to setup presets for image processing.
  7. * If an ImageCache derivative doesn't exist the web server's
  8. * rewrite rules will pass the request to Drupal which in turn
  9. * hands it off to imagecache to dynamically generate the file.
  10. *
  11. * To view a derivative image you request a special url containing
  12. * 'imagecache/<presetname>/path/to/file.ext.
  13. *
  14. * Presets can be managed at http://example.com/admin/build/imagecache.
  15. *
  16. * To view a derivative image you request a special url containing
  17. * 'imagecache/<presetname>/path/to/file.ext.
  18. *
  19. * If you had a preset names 'thumbnail' and you wanted to see the
  20. * thumbnail version of http://example.com/files/path/to/myimage.jpg you
  21. * would use http://example.com/files/imagecache/thumbnail/path/to/myimage.jpg
  22. *
  23. * ImageCache provides formatters for CCK Imagefields and is leveraged by several
  24. * other modules. ImageCache also relies heavily on ImageAPI for it's image processing.
  25. * If there are errors with actual image processing look to ImageAPI first.
  26. *
  27. * @todo: add watermarking capabilities.
  28. *
  29. */
  30. /**
  31. * Imagecache preset storage constant for user-defined presets in the DB.
  32. */
  33. define('IMAGECACHE_STORAGE_NORMAL', 0);
  34. /**
  35. * Imagecache preset storage constant for module-defined presets in code.
  36. */
  37. define('IMAGECACHE_STORAGE_DEFAULT', 1);
  38. /**
  39. * Imagecache preset storage constant for user-defined presets that override
  40. * module-defined presets.
  41. */
  42. define('IMAGECACHE_STORAGE_OVERRIDE', 2);
  43. /*********************************************************************************************
  44. * Drupal Hooks
  45. *********************************************************************************************/
  46. /**
  47. * Implementation of hook_perm().
  48. */
  49. function imagecache_perm() {
  50. $perms = array('administer imagecache', 'flush imagecache');
  51. foreach (imagecache_presets() as $preset) {
  52. $perms[] = 'view imagecache '. $preset['presetname'];
  53. }
  54. return $perms;
  55. }
  56. /**
  57. * Implementation of hook_menu().
  58. */
  59. function imagecache_menu() {
  60. $items = array();
  61. // standard imagecache callback.
  62. $items[file_directory_path() .'/imagecache'] = array(
  63. 'page callback' => 'imagecache_cache',
  64. 'access callback' => '_imagecache_menu_access_public_files',
  65. 'type' => MENU_CALLBACK
  66. );
  67. // private downloads imagecache callback
  68. $items['system/files/imagecache'] = array(
  69. 'page callback' => 'imagecache_cache_private',
  70. 'access callback' => TRUE,
  71. 'type' => MENU_CALLBACK
  72. );
  73. return $items;
  74. }
  75. /**
  76. * Menu access callback for public file transfers.
  77. */
  78. function _imagecache_menu_access_public_files() {
  79. return (FILE_DOWNLOADS_PUBLIC == variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC));
  80. }
  81. /**
  82. * Implementation of hook_form_FORM_ID_alter.
  83. *
  84. * Clear imagecache presets cache on admin/build/modules form.
  85. */
  86. function imagecache_form_system_modules_alter(&$form, $form_state) {
  87. imagecache_presets(TRUE);
  88. }
  89. /**
  90. * Implementation of hook_form_FORM_ID_alter.
  91. *
  92. * The file system form is modified to include an extra submit handler, so
  93. * that imagecache can rebuild the menu after the filesystem path is changed.
  94. */
  95. function imagecache_form_system_file_system_settings_alter(&$form, &$form_state) {
  96. $form['#submit'][] = 'imagecache_system_file_system_submit';
  97. }
  98. /**
  99. * Rebuild menus to ensure we've got the right files directory callback.
  100. */
  101. function imagecache_system_file_system_submit($form, &$form_state) {
  102. menu_rebuild();
  103. }
  104. /**
  105. * Implementation of hook_theme().
  106. */
  107. function imagecache_theme() {
  108. $theme = array(
  109. 'imagecache' => array(
  110. 'arguments' => array(
  111. 'namespace' => NULL,
  112. 'path' => NULL,
  113. 'alt' => NULL,
  114. 'title' => NULL,
  115. )),
  116. 'imagecache_imagelink' => array(
  117. 'arguments' => array(
  118. 'namespace' => NULL,
  119. 'path' => NULL,
  120. 'alt' => NULL,
  121. 'title' => NULL,
  122. 'attributes' => array(),
  123. )),
  124. 'imagecache_resize' => array(
  125. 'file' => 'imagecache_actions.inc',
  126. 'arguments' => array('element' => NULL),
  127. ),
  128. 'imagecache_scale' => array(
  129. 'file' => 'imagecache_actions.inc',
  130. 'arguments' => array('element' => NULL),
  131. ),
  132. 'imagecache_scale_and_crop' => array(
  133. 'file' => 'imagecache_actions.inc',
  134. 'arguments' => array('element' => NULL),
  135. ),
  136. 'imagecache_deprecated_scale' => array(
  137. 'file' => 'imagecache_actions.inc',
  138. 'arguments' => array('element' => NULL),
  139. ),
  140. 'imagecache_crop' => array(
  141. 'file' => 'imagecache_actions.inc',
  142. 'arguments' => array('element' => NULL),
  143. ),
  144. 'imagecache_desaturate' => array(
  145. 'file' => 'imagecache_actions.inc',
  146. 'arguments' => array('element' => NULL),
  147. ),
  148. 'imagecache_rotate' => array(
  149. 'file' => 'imagecache_actions.inc',
  150. 'arguments' => array('element' => NULL),
  151. ),
  152. 'imagecache_sharpen' => array(
  153. 'file' => 'imagecache_actions.inc',
  154. 'arguments' => array('element' => NULL),
  155. ),
  156. );
  157. foreach (imagecache_presets() as $preset) {
  158. $theme['imagecache_formatter_'. $preset['presetname'] .'_default'] = array(
  159. 'arguments' => array('element' => NULL),
  160. 'function' => 'theme_imagecache_formatter_default',
  161. );
  162. $theme['imagecache_formatter_'. $preset['presetname'] .'_linked'] = array(
  163. 'arguments' => array('element' => NULL),
  164. 'function' => 'theme_imagecache_formatter_linked',
  165. );
  166. $theme['imagecache_formatter_'. $preset['presetname'] .'_imagelink'] = array(
  167. 'arguments' => array('element' => NULL),
  168. 'function' => 'theme_imagecache_formatter_imagelink',
  169. );
  170. $theme['imagecache_formatter_'. $preset['presetname'] .'_path'] = array(
  171. 'arguments' => array('element' => NULL),
  172. 'function' => 'theme_imagecache_formatter_path',
  173. );
  174. $theme['imagecache_formatter_'. $preset['presetname'] .'_url'] = array(
  175. 'arguments' => array('element' => NULL),
  176. 'function' => 'theme_imagecache_formatter_url',
  177. );
  178. }
  179. return $theme;
  180. }
  181. /**
  182. * Implementation of hook_imagecache_actions.
  183. *
  184. * @return array
  185. * An array of information on the actions implemented by a module. The array
  186. * contains a sub-array for each action node type, with the machine-readable
  187. * action name as the key. Each sub-array has up to 3 attributes. Possible
  188. * attributes:
  189. *
  190. * "name": the human-readable name of the action. Required.
  191. * "description": a brief description of the action. Required.
  192. * "file": the name of the include file the action can be found
  193. * in relative to the implementing module's path.
  194. */
  195. function imagecache_imagecache_actions() {
  196. $actions = array(
  197. 'imagecache_resize' => array(
  198. 'name' => 'Resize',
  199. 'description' => 'Resize an image to an exact set of dimensions, ignoring aspect ratio.',
  200. 'file' => 'imagecache_actions.inc',
  201. ),
  202. 'imagecache_scale' => array(
  203. 'name' => 'Scale',
  204. 'description' => 'Resize an image maintaining the original aspect-ratio (only one value necessary).',
  205. 'file' => 'imagecache_actions.inc',
  206. ),
  207. 'imagecache_deprecated_scale' => array(
  208. 'name' => 'Deprecated Scale',
  209. 'description' => 'Precursor to Scale and Crop. Has inside and outside dimension support. This action will be removed in ImageCache 2.1).',
  210. 'file' => 'imagecache_actions.inc',
  211. ),
  212. 'imagecache_scale_and_crop' => array(
  213. 'name' => 'Scale And Crop',
  214. 'description' => 'Resize an image while maintaining aspect ratio, then crop it to the specified dimensions.',
  215. 'file' => 'imagecache_actions.inc',
  216. ),
  217. 'imagecache_crop' => array(
  218. 'name' => 'Crop',
  219. 'description' => 'Crop an image to the rectangle specified by the given offsets and dimensions.',
  220. 'file' => 'imagecache_actions.inc',
  221. ),
  222. 'imagecache_desaturate' => array(
  223. 'name' => 'Desaturate',
  224. 'description' => 'Convert an image to grey scale.',
  225. 'file' => 'imagecache_actions.inc',
  226. ),
  227. 'imagecache_rotate' => array(
  228. 'name' => 'Rotate',
  229. 'description' => 'Rotate an image.',
  230. 'file' => 'imagecache_actions.inc',
  231. ),
  232. 'imagecache_sharpen' => array(
  233. 'name' => 'Sharpen',
  234. 'description' => 'Sharpen an image using unsharp masking.',
  235. 'file' => 'imagecache_actions.inc',
  236. ),
  237. );
  238. return $actions;
  239. }
  240. /**
  241. * Pull in actions exposed by other modules using hook_imagecache_actions().
  242. *
  243. * @param $reset
  244. * Boolean flag indicating whether the cached data should be
  245. * wiped and recalculated.
  246. *
  247. * @return
  248. * An array of actions to be used when transforming images.
  249. */
  250. function imagecache_action_definitions($reset = FALSE) {
  251. static $actions = array();
  252. if (!isset($actions) || $reset) {
  253. if (!$reset && ($cache = cache_get('imagecache_actions')) && !empty($cache->data)) {
  254. $actions = $cache->data;
  255. }
  256. else {
  257. foreach (module_implements('imagecache_actions') as $module) {
  258. foreach (module_invoke($module, 'imagecache_actions') as $key => $action) {
  259. $action['module'] = $module;
  260. if (!empty($action['file'])) {
  261. $action['file'] = drupal_get_path('module', $action['module']) .'/'. $action['file'];
  262. }
  263. $actions[$key] = $action;
  264. };
  265. }
  266. uasort($actions, '_imagecache_definitions_sort');
  267. cache_set('imagecache_actions', $actions);
  268. }
  269. }
  270. return $actions;
  271. }
  272. function _imagecache_definitions_sort($a, $b) {
  273. $a = $a['name'];
  274. $b = $b['name'];
  275. if ($a == $b) {
  276. return 0;
  277. }
  278. return ($a < $b) ? -1 : 1;
  279. }
  280. function imagecache_action_definition($action) {
  281. static $definition_cache = array();
  282. if (!isset($definition_cache[$action])) {
  283. $definitions = imagecache_action_definitions();
  284. $definition = (isset($definitions[$action])) ? $definitions[$action] : array();
  285. if (isset($definition['file'])) {
  286. require_once($definition['file']);
  287. }
  288. $definition_cache[$action] = $definition;
  289. }
  290. return $definition_cache[$action];
  291. }
  292. /**
  293. * Return a URL that points to the location of a derivative of the original
  294. * image transformed with the given preset.
  295. *
  296. * Special care is taken to make this work with the possible combinations of
  297. * Clean URLs and public/private downloads. For example, when Clean URLs are not
  298. * available an URL with query should be returned, like
  299. * http://example.com/?q=files/imagecache/foo.jpg, so that ImageCache is able
  300. * intercept the request for this file.
  301. *
  302. * This code began similarly to Drupal core's function file_create_url(), but
  303. * handles the case of Clean URLs and public downloads differently however.
  304. * It also implements hook_file_url_alter() which was added to Drupal 7 and
  305. * backported to PressFlow 6.x.
  306. *
  307. * @param $presetname
  308. * String specifying an ImageCache preset name.
  309. * @param $filepath
  310. * String specifying the path to the image file.
  311. * @param $bypass_browser_cache
  312. * A Boolean indicating that the URL for the image should be distinct so that
  313. * the visitors browser will not be able to use a previously cached version.
  314. * Defaults to FALSE.
  315. * @param $absolute
  316. * A Boolean indicating that the URL should be absolute. Defaults to TRUE.
  317. */
  318. function imagecache_create_url($presetname, $filepath, $bypass_browser_cache = FALSE, $absolute = TRUE) {
  319. $args = array(
  320. 'query' => empty($bypass_browser_cache) ? NULL : time(),
  321. // Little hack to avoid having language_url_rewrite() prefix the path with the
  322. // language code, but preserve the domain rewriting.
  323. 'language' => (object) array('language' => '', 'domain' => $GLOBALS['language']->domain),
  324. );
  325. $file_directory = file_directory_path();
  326. // Determine the path of the derivative inside the files directory.
  327. $derivative_path = 'imagecache/'. $presetname .'/'. _imagecache_strip_file_directory($filepath);
  328. // Then construct a full path and see if anyone wants to alter it.
  329. $altered_path = $old_path = $file_directory .'/'. $derivative_path;
  330. drupal_alter('file_url', $altered_path);
  331. // If any module has altered the path, then return the alteration...
  332. if ($altered_path != $old_path) {
  333. // ...but use url() so our $bypass_browser_cache parameter is honored.
  334. return url($altered_path, $args);
  335. }
  336. // It was unchanged so use the download method's prefix.
  337. $prefix = array(
  338. FILE_DOWNLOADS_PUBLIC => $file_directory,
  339. FILE_DOWNLOADS_PRIVATE => 'system/files',
  340. );
  341. $path = $prefix[variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC)] .'/'. $derivative_path;
  342. return url($path, $args + array('absolute' => $absolute));
  343. }
  344. /**
  345. * Return a file system location that points to the location of a derivative
  346. * of the original image at @p $path, transformed with the given @p $preset.
  347. * Keep in mind that the image might not yet exist and won't be created.
  348. */
  349. function imagecache_create_path($presetname, $path) {
  350. $path = _imagecache_strip_file_directory($path);
  351. return file_create_path() .'/imagecache/'. $presetname .'/'. $path;
  352. }
  353. /**
  354. * Remove a possible leading file directory path from the given path.
  355. */
  356. function _imagecache_strip_file_directory($path) {
  357. $dirpath = file_directory_path();
  358. $dirlen = strlen($dirpath);
  359. if (substr($path, 0, $dirlen + 1) == $dirpath .'/') {
  360. $path = substr($path, $dirlen + 1);
  361. }
  362. return $path;
  363. }
  364. /**
  365. * callback for handling public files imagecache requests.
  366. */
  367. function imagecache_cache() {
  368. $args = func_get_args();
  369. $preset = check_plain(array_shift($args));
  370. $path = implode('/', $args);
  371. _imagecache_cache($preset, $path);
  372. }
  373. /**
  374. * callback for handling private files imagecache requests
  375. */
  376. function imagecache_cache_private() {
  377. $args = func_get_args();
  378. $preset = check_plain(array_shift($args));
  379. $source = implode('/', $args);
  380. if (user_access('view imagecache '. $preset) && !in_array(-1, module_invoke_all('file_download', $source))) {
  381. _imagecache_cache($preset, $source);
  382. }
  383. else {
  384. // if there is a 403 image, display it.
  385. $accesspath = file_create_path('imagecache/'. $preset .'.403.png');
  386. if (is_file($accesspath)) {
  387. imagecache_transfer($accesspath);
  388. exit;
  389. }
  390. header('HTTP/1.0 403 Forbidden');
  391. exit;
  392. }
  393. }
  394. /**
  395. * Handle request validation and responses to ImageCache requests.
  396. *
  397. * @see imagecache_generate_image() if you're writing code that needs to have
  398. * ImageCache generate images but not send them to a browser.
  399. */
  400. function _imagecache_cache($presetname, $path) {
  401. if (!$preset = imagecache_preset_by_name($presetname)) {
  402. // Send a 404 if we don't know of a preset.
  403. header("HTTP/1.0 404 Not Found");
  404. exit;
  405. }
  406. // umm yeah deliver it early if it is there. especially useful
  407. // to prevent lock files from being created when delivering private files.
  408. $dst = imagecache_create_path($preset['presetname'], $path);
  409. if (is_file($dst)) {
  410. imagecache_transfer($dst);
  411. }
  412. // preserve path for watchdog.
  413. $src = $path;
  414. // Check if the path to the file exists.
  415. if (!is_file($src) && !is_file($src = file_create_path($src))) {
  416. watchdog('imagecache', '404: Unable to find %image ', array('%image' => $src), WATCHDOG_ERROR);
  417. header("HTTP/1.0 404 Not Found");
  418. exit;
  419. };
  420. // Bail if the requested file isn't an image you can't request .php files
  421. // etc...
  422. if (!getimagesize($src)) {
  423. watchdog('imagecache', '403: File is not an image %image ', array('%image' => $src), WATCHDOG_ERROR);
  424. header('HTTP/1.0 403 Forbidden');
  425. exit;
  426. }
  427. $lockfile = file_directory_temp() .'/'. $preset['presetname'] . basename($src);
  428. if (file_exists($lockfile)) {
  429. watchdog('imagecache', 'ImageCache already generating: %dst, Lock file: %tmp.', array('%dst' => $dst, '%tmp' => $lockfile), WATCHDOG_NOTICE);
  430. // 307 Temporary Redirect, to myself. Lets hope the image is done next time around.
  431. header('Location: '. request_uri(), TRUE, 307);
  432. exit;
  433. }
  434. touch($lockfile);
  435. // register the shtdown function to clean up lock files. by the time shutdown
  436. // functions are being called the cwd has changed from document root, to
  437. // server root so absolute paths must be used for files in shutdown functions.
  438. register_shutdown_function('file_delete', realpath($lockfile));
  439. // check if deriv exists... (file was created between apaches request handler and reaching this code)
  440. // otherwise try to create the derivative.
  441. if (file_exists($dst) || imagecache_build_derivative($preset['actions'], $src, $dst)) {
  442. imagecache_transfer($dst);
  443. }
  444. // Generate an error if image could not generate.
  445. watchdog('imagecache', 'Failed generating an image from %image using imagecache preset %preset.', array('%image' => $path, '%preset' => $preset['presetname']), WATCHDOG_ERROR);
  446. header("HTTP/1.0 500 Internal Server Error");
  447. exit;
  448. }
  449. /**
  450. * Apply an action to an image.
  451. *
  452. * @param $action
  453. * Action array
  454. * @param $image
  455. * Image object
  456. * @return
  457. * Boolean, TRUE indicating success and FALSE failure.
  458. */
  459. function _imagecache_apply_action($action, &$image) {
  460. if (imagecache_action_definition($action['action'])) {
  461. $function = $action['action'] .'_image';
  462. if (function_exists($function)) {
  463. return $function($image, $action['data']);
  464. }
  465. }
  466. // skip undefined actions.. module probably got uninstalled or disabled.
  467. watchdog('imagecache', 'non-existant action %action', array('%action' => $action['action']), WATCHDOG_NOTICE);
  468. return TRUE;
  469. }
  470. /**
  471. * Helper function to transfer files from imagecache.
  472. *
  473. * Determines MIME type and sets a last modified header.
  474. *
  475. * @param $path
  476. * String containing the path to file to be transferred.
  477. * @return
  478. * This function does not return. It calls exit().
  479. */
  480. function imagecache_transfer($path) {
  481. $size = getimagesize($path);
  482. $headers = array('Content-Type: '. mime_header_encode($size['mime']));
  483. if ($fileinfo = stat($path)) {
  484. $headers[] = 'Content-Length: '. $fileinfo[7];
  485. $headers[] = 'Expires: ' . gmdate('D, d M Y H:i:s', time() + 1209600) .' GMT';
  486. $headers[] = 'Cache-Control: max-age=1209600, private, must-revalidate';
  487. _imagecache_cache_set_cache_headers($fileinfo, $headers);
  488. }
  489. file_transfer($path, $headers);
  490. exit;
  491. }
  492. /**
  493. * Set file headers that handle "If-Modified-Since" correctly for the
  494. * given fileinfo.
  495. *
  496. * Note that this function may return or may call exit().
  497. *
  498. * Most code has been taken from drupal_page_cache_header().
  499. *
  500. * @param $fileinfo
  501. * Array returned by stat().
  502. * @param
  503. * Array of existing headers.
  504. * @return
  505. * Nothing but beware that this function may not return.
  506. */
  507. function _imagecache_cache_set_cache_headers($fileinfo, &$headers) {
  508. // Set default values:
  509. $last_modified = gmdate('D, d M Y H:i:s', $fileinfo[9]) .' GMT';
  510. $etag = '"'. md5($last_modified) .'"';
  511. // See if the client has provided the required HTTP headers:
  512. $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])
  513. ? stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE'])
  514. : FALSE;
  515. $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH'])
  516. ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])
  517. : FALSE;
  518. if ($if_modified_since && $if_none_match
  519. && $if_none_match == $etag // etag must match
  520. && $if_modified_since == $last_modified) { // if-modified-since must match
  521. header('HTTP/1.1 304 Not Modified');
  522. // All 304 responses must send an etag if the 200 response
  523. // for the same object contained an etag
  524. header('Etag: '. $etag);
  525. // We must also set Last-Modified again, so that we overwrite Drupal's
  526. // default Last-Modified header with the right one
  527. header('Last-Modified: '. $last_modified);
  528. exit;
  529. }
  530. // Send appropriate response:
  531. $headers[] = 'Last-Modified: '. $last_modified;
  532. $headers[] = 'ETag: '. $etag;
  533. }
  534. /**
  535. * Create a new image based on an image preset.
  536. *
  537. * @param $preset
  538. * An image preset array.
  539. * @param $source
  540. * Path of the source file.
  541. * @param $destination
  542. * Path of the destination file.
  543. * @return
  544. * TRUE if an image derivative is generated, FALSE if no image
  545. * derivative is generated. NULL if the derivative is being generated.
  546. */
  547. function imagecache_build_derivative($actions, $src, $dst) {
  548. // get the folder for the final location of this preset...
  549. $dir = dirname($dst);
  550. // Build the destination folder tree if it doesn't already exists.
  551. if (!file_check_directory($dir, FILE_CREATE_DIRECTORY) && !mkdir($dir, 0775, TRUE)) {
  552. watchdog('imagecache', 'Failed to create imagecache directory: %dir', array('%dir' => $dir), WATCHDOG_ERROR);
  553. return FALSE;
  554. }
  555. // file_check_directory() has an annoying habit of displaying "directory ...
  556. // has been created" status messages. To avoid confusing visitors we clear
  557. // out all the status messages for non-ImageCache admins. This might affect
  558. // some other messages but errors and warnings should still be displayed.
  559. if (!user_access('administer imagecache')) {
  560. drupal_get_messages('status', TRUE);
  561. }
  562. // Simply copy the file if there are no actions.
  563. if (empty($actions)) {
  564. return file_copy($src, $dst, FILE_EXISTS_REPLACE);
  565. }
  566. if (!$image = imageapi_image_open($src)) {
  567. return FALSE;
  568. }
  569. if (file_exists($dst)) {
  570. watchdog('imagecache', 'Cached image file %dst already exists but is being regenerated. There may be an issue with your rewrite configuration.', array('%dst' => $dst), WATCHDOG_WARNING);
  571. }
  572. foreach ($actions as $action) {
  573. if (!empty($action['data'])) {
  574. // Make sure the width and height are computed first so they can be used
  575. // in relative x/yoffsets like 'center' or 'bottom'.
  576. if (isset($action['data']['width'])) {
  577. $action['data']['width'] = _imagecache_percent_filter($action['data']['width'], $image->info['width']);
  578. }
  579. if (isset($action['data']['height'])) {
  580. $action['data']['height'] = _imagecache_percent_filter($action['data']['height'], $image->info['height']);
  581. }
  582. if (isset($action['data']['xoffset'])) {
  583. $action['data']['xoffset'] = _imagecache_keyword_filter($action['data']['xoffset'], $image->info['width'], $action['data']['width']);
  584. }
  585. if (isset($action['data']['yoffset'])) {
  586. $action['data']['yoffset'] = _imagecache_keyword_filter($action['data']['yoffset'], $image->info['height'], $action['data']['height']);
  587. }
  588. }
  589. if (!_imagecache_apply_action($action, $image)) {
  590. watchdog('imagecache', 'action(id:%id): %action failed for %src', array('%id' => $action['actionid'], '%action' => $action['action'], '%src' => $src), WATCHDOG_ERROR);
  591. return FALSE;
  592. }
  593. }
  594. if (!imageapi_image_close($image, $dst)) {
  595. watchdog('imagecache', 'There was an error saving the new image file %dst.', array('%dst' => $dst), WATCHDOG_ERROR);
  596. return FALSE;
  597. }
  598. return TRUE;
  599. }
  600. /**
  601. * Implementation of hook_user().
  602. */
  603. function imagecache_user($op, &$edit, &$account, $category = NULL) {
  604. // Flush cached old user picture.
  605. if ($op == 'update' && !empty($account->picture)) {
  606. imagecache_image_flush($account->picture);
  607. }
  608. }
  609. /**
  610. * Implementation of filefield.module's hook_file_delete().
  611. *
  612. * Remove derivative images after the originals are deleted by filefield.
  613. */
  614. function imagecache_file_delete($file) {
  615. if (isset($file->filepath)) {
  616. imagecache_image_flush($file->filepath);
  617. }
  618. }
  619. /**
  620. * Implementation of hook_field_formatter_info().
  621. *
  622. * imagecache formatters are named as $presetname_$style
  623. * $style is used to determine how the preset should be rendered.
  624. * If you are implementing custom imagecache formatters please treat _ as
  625. * reserved.
  626. *
  627. * @todo: move the linking functionality up to imagefield and clean up the default image
  628. * integration.
  629. */
  630. function imagecache_field_formatter_info() {
  631. $formatters = array();
  632. foreach (imagecache_presets() as $preset) {
  633. $formatters[$preset['presetname'] .'_default'] = array(
  634. 'label' => t('@preset image', array('@preset' => $preset['presetname'])),
  635. 'field types' => array('image', 'filefield'),
  636. );
  637. $formatters[$preset['presetname'] .'_linked'] = array(
  638. 'label' => t('@preset image linked to node', array('@preset' => $preset['presetname'])),
  639. 'field types' => array('image', 'filefield'),
  640. );
  641. $formatters[$preset['presetname'] .'_imagelink'] = array(
  642. 'label' => t('@preset image linked to image', array('@preset' => $preset['presetname'])),
  643. 'field types' => array('image', 'filefield'),
  644. );
  645. $formatters[$preset['presetname'] .'_path'] = array(
  646. 'label' => t('@preset file path', array('@preset' => $preset['presetname'])),
  647. 'field types' => array('image', 'filefield'),
  648. );
  649. $formatters[$preset['presetname'] .'_url'] = array(
  650. 'label' => t('@preset URL', array('@preset' => $preset['presetname'])),
  651. 'field types' => array('image', 'filefield'),
  652. );
  653. }
  654. return $formatters;
  655. }
  656. function theme_imagecache_formatter_default($element) {
  657. // Inside a view $element may contain NULL data. In that case, just return.
  658. if (empty($element['#item']['fid'])) {
  659. return '';
  660. }
  661. // Extract the preset name from the formatter name.
  662. $presetname = substr($element['#formatter'], 0, strrpos($element['#formatter'], '_'));
  663. $style = 'linked';
  664. $style = 'default';
  665. $item = $element['#item'];
  666. $item['data']['alt'] = isset($item['data']['alt']) ? $item['data']['alt'] : '';
  667. $item['data']['title'] = isset($item['data']['title']) ? $item['data']['title'] : NULL;
  668. $class = "imagecache imagecache-$presetname imagecache-$style imagecache-{$element['#formatter']}";
  669. return theme('imagecache', $presetname, $item['filepath'], $item['data']['alt'], $item['data']['title'], array('class' => $class));
  670. }
  671. function theme_imagecache_formatter_linked($element) {
  672. // Inside a view $element may contain NULL data. In that case, just return.
  673. if (empty($element['#item']['fid'])) {
  674. return '';
  675. }
  676. // Extract the preset name from the formatter name.
  677. $presetname = substr($element['#formatter'], 0, strrpos($element['#formatter'], '_'));
  678. $style = 'linked';
  679. $item = $element['#item'];
  680. $item['data']['alt'] = isset($item['data']['alt']) ? $item['data']['alt'] : '';
  681. $item['data']['title'] = isset($item['data']['title']) ? $item['data']['title'] : NULL;
  682. $imagetag = theme('imagecache', $presetname, $item['filepath'], $item['data']['alt'], $item['data']['title']);
  683. $path = empty($item['nid']) ? '' : 'node/'. $item['nid'];
  684. $class = "imagecache imagecache-$presetname imagecache-$style imagecache-{$element['#formatter']}";
  685. return l($imagetag, $path, array('attributes' => array('class' => $class), 'html' => TRUE));
  686. }
  687. function theme_imagecache_formatter_imagelink($element) {
  688. // Inside a view $element may contain NULL data. In that case, just return.
  689. if (empty($element['#item']['fid'])) {
  690. return '';
  691. }
  692. // Extract the preset name from the formatter name.
  693. $presetname = substr($element['#formatter'], 0, strrpos($element['#formatter'], '_'));
  694. $style = 'imagelink';
  695. $item = $element['#item'];
  696. $item['data']['alt'] = isset($item['data']['alt']) ? $item['data']['alt'] : '';
  697. $item['data']['title'] = isset($item['data']['title']) ? $item['data']['title'] : NULL;
  698. $imagetag = theme('imagecache', $presetname, $item['filepath'], $item['data']['alt'], $item['data']['title']);
  699. $path = file_create_url($item['filepath']);
  700. $class = "imagecache imagecache-$presetname imagecache-$style imagecache-{$element['#formatter']}";
  701. return l($imagetag, $path, array('attributes' => array('class' => $class), 'html' => TRUE));
  702. }
  703. function theme_imagecache_formatter_path($element) {
  704. // Inside a view $element may contain NULL data. In that case, just return.
  705. if (empty($element['#item']['fid'])) {
  706. return '';
  707. }
  708. // Extract the preset name from the formatter name.
  709. $presetname = substr($element['#formatter'], 0, strrpos($element['#formatter'], '_'));
  710. return imagecache_create_path($presetname, $element['#item']['filepath']);
  711. }
  712. function theme_imagecache_formatter_url($element) {
  713. // Inside a view $element may contain NULL data. In that case, just return.
  714. if (empty($element['#item']['fid'])) {
  715. return '';
  716. }
  717. // Extract the preset name from the formatter name.
  718. $presetname = substr($element['#formatter'], 0, strrpos($element['#formatter'], '_'));
  719. return imagecache_create_url($presetname, $element['#item']['filepath']);
  720. }
  721. /**
  722. * Accept a percentage and return it in pixels.
  723. */
  724. function _imagecache_percent_filter($value, $current_pixels) {
  725. if (strpos($value, '%') !== FALSE) {
  726. $value = str_replace('%', '', $value) * 0.01 * $current_pixels;
  727. }
  728. return $value;
  729. }
  730. /**
  731. * Accept a keyword (center, top, left, etc) and return it as an offset in pixels.
  732. */
  733. function _imagecache_keyword_filter($value, $current_pixels, $new_pixels) {
  734. switch ($value) {
  735. case 'top':
  736. case 'left':
  737. $value = 0;
  738. break;
  739. case 'bottom':
  740. case 'right':
  741. $value = $current_pixels - $new_pixels;
  742. break;
  743. case 'center':
  744. $value = $current_pixels/2 - $new_pixels/2;
  745. break;
  746. }
  747. return $value;
  748. }
  749. /**
  750. * Recursively delete all files and folders in the specified filepath, then
  751. * delete the containing folder.
  752. *
  753. * Note that this only deletes visible files with write permission.
  754. *
  755. * @param string $path
  756. * A filepath relative to file_directory_path.
  757. */
  758. function _imagecache_recursive_delete($path) {
  759. if (is_file($path) || is_link($path)) {
  760. unlink($path);
  761. }
  762. elseif (is_dir($path)) {
  763. $d = dir($path);
  764. while (($entry = $d->read()) !== FALSE) {
  765. if ($entry == '.' || $entry == '..') continue;
  766. $entry_path = $path .'/'. $entry;
  767. _imagecache_recursive_delete($entry_path);
  768. }
  769. $d->close();
  770. rmdir($path);
  771. }
  772. else {
  773. watchdog('imagecache', 'Unknown file type(%path) stat: %stat ',
  774. array('%path' => $path, '%stat' => print_r(stat($path),1)), WATCHDOG_ERROR);
  775. }
  776. }
  777. /**
  778. * Create and image tag for an imagecache derivative
  779. *
  780. * @param $presetname
  781. * String with the name of the preset used to generate the derivative image.
  782. * @param $path
  783. * String path to the original image you wish to create a derivative image
  784. * tag for.
  785. * @param $alt
  786. * Optional string with alternate text for the img element.
  787. * @param $title
  788. * Optional string with title for the img element.
  789. * @param $attributes
  790. * Optional drupal_attributes() array. If $attributes is an array then the
  791. * default imagecache classes will not be set automatically, you must do this
  792. * manually.
  793. * @param $getsize
  794. * If set to TRUE, the image's dimension are fetched and added as width/height
  795. * attributes.
  796. * @param $absolute
  797. * A Boolean indicating that the URL should be absolute. Defaults to TRUE.
  798. * @return
  799. * HTML img element string.
  800. */
  801. function theme_imagecache($presetname, $path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE, $absolute = TRUE) {
  802. // Check is_null() so people can intentionally pass an empty array of
  803. // to override the defaults completely.
  804. if (is_null($attributes)) {
  805. $attributes = array('class' => 'imagecache imagecache-'. $presetname);
  806. }
  807. $ours = array(
  808. 'src' => imagecache_create_url($presetname, $path, FALSE, $absolute),
  809. 'alt' => $alt,
  810. 'title' => $title,
  811. );
  812. if ($getsize && ($image = image_get_info(imagecache_create_path($presetname, $path)))) {
  813. $ours += array('width' => $image['width'], 'height' => $image['height']);
  814. }
  815. return '<img' . drupal_attributes($ours + $attributes) . '/>';
  816. }
  817. /**
  818. * Create a link the original image that wraps the derivative image.
  819. *
  820. * @param $presetname
  821. * String with the name of the preset used to generate the derivative image.
  822. * @param $path
  823. * String path to the original image you wish to create a derivative image
  824. * tag for.
  825. * @param $alt
  826. * Optional string with alternate text for the img element.
  827. * @param $title
  828. * Optional string with title for the img element.
  829. * @param attributes
  830. * Optional drupal_attributes() array for the link.
  831. * @return
  832. * An HTML string.
  833. */
  834. function theme_imagecache_imagelink($presetname, $path, $alt = '', $title = '', $attributes = NULL) {
  835. $image = theme('imagecache', $presetname, $path, $alt, $title);
  836. $original_image_url = file_create_url($path);
  837. return l($image, $original_image_url, array('absolute' => FALSE, 'html' => TRUE, 'attributes' => $attributes));
  838. }
  839. /**
  840. * Imagecache JS settings and theme function.
  841. */
  842. function imagecache_add_js() {
  843. static $added = false;
  844. if (!$added) {
  845. $added = TRUE;
  846. drupal_add_js(drupal_get_path('module', 'imagecache') .'/imagecache.js');
  847. $mode = variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC);
  848. if ($mode == FILE_DOWNLOADS_PUBLIC) {
  849. $settings['filesUrl'] = $GLOBALS['base_path'] . file_directory_path();
  850. }
  851. elseif ($mode == FILE_DOWNLOADS_PRIVATE) {
  852. $settings['filesUrl'] = 'system/files';
  853. }
  854. $settings['filesDirectory'] = file_directory_path();
  855. $settings['presets'] = array_keys(imagecache_presets());
  856. drupal_add_js(array('imagecache' => $settings), 'setting');
  857. }
  858. }
  859. /**
  860. * ImageCache 2.x API
  861. *
  862. * The API for imagecache has changed. The 2.x API returns more structured
  863. * data, has shorter function names, and implements more aggressive metadata
  864. * caching.
  865. *
  866. */
  867. /**
  868. * Get an array of all presets and their settings.
  869. *
  870. * @param reset
  871. * if set to TRUE it will clear the preset cache
  872. *
  873. * @return
  874. * array of presets array( $preset_id => array('presetid' => integer, 'presetname' => string))
  875. */
  876. function imagecache_presets($reset = FALSE) {
  877. static $presets = array();
  878. // Clear caches if $reset is TRUE;
  879. if ($reset) {
  880. $presets = array();
  881. cache_clear_all('imagecache:presets', 'cache');
  882. // Clear the content.module cache (refreshes the list of formatters provided by imagefield.module).
  883. if (module_exists('content')) {
  884. content_clear_type_cache();
  885. }
  886. }
  887. // Return presets if the array is populated.
  888. if (!empty($presets)) {
  889. return $presets;
  890. }
  891. // Grab from cache or build the array. To ensure that the Drupal 5 upgrade
  892. // path works, we also check whether the presets list is an array.
  893. if (($cache = cache_get('imagecache:presets', 'cache')) && is_array($cache->data)) {
  894. $presets = $cache->data;
  895. }
  896. else {
  897. $normal_presets = array();
  898. $result = db_query('SELECT * FROM {imagecache_preset} ORDER BY presetname');
  899. while ($preset = db_fetch_array($result)) {
  900. $presets[$preset['presetid']] = $preset;
  901. $presets[$preset['presetid']]['actions'] = imagecache_preset_actions($preset);
  902. $presets[$preset['presetid']]['storage'] = IMAGECACHE_STORAGE_NORMAL;
  903. // Collect normal preset names so we can skip defaults and mark overrides accordingly
  904. $normal_presets[$preset['presetname']] = $preset['presetid'];
  905. }
  906. // Collect default presets and allow modules to modify them before they
  907. // are cached.
  908. $default_presets = module_invoke_all('imagecache_default_presets');
  909. drupal_alter('imagecache_default_presets', $default_presets);
  910. // Add in default presets if they don't conflict with any normal presets.
  911. // Mark normal presets that take the same preset namespace as overrides.
  912. foreach ($default_presets as $preset) {
  913. if (!empty($preset['presetname'])) {
  914. if (!isset($normal_presets[$preset['presetname']])) {
  915. $preset['storage'] = IMAGECACHE_STORAGE_DEFAULT;
  916. // Use a string preset identifier
  917. $preset['presetid'] = $preset['presetname'];
  918. $presets[$preset['presetname']] = $preset;
  919. }
  920. else {
  921. $presetid = $normal_presets[$preset['presetname']];
  922. $presets[$presetid]['storage'] = IMAGECACHE_STORAGE_OVERRIDE;
  923. }
  924. }
  925. }
  926. cache_set('imagecache:presets', $presets);
  927. }
  928. return $presets;
  929. }
  930. /**
  931. * Load a preset by preset_id.
  932. *
  933. * @param preset_id
  934. * The numeric id of a preset.
  935. *
  936. * @return
  937. * preset array( 'presetname' => string, 'presetid' => integet)
  938. * empty array if preset_id is an invalid preset
  939. */
  940. function imagecache_preset($preset_id, $reset = FALSE) {
  941. $presets = imagecache_presets($reset);
  942. return (isset($presets[$preset_id])) ? $presets[$preset_id] : array();
  943. }
  944. /**
  945. * Load a preset by name.
  946. *
  947. * @param preset_name
  948. *
  949. * @return
  950. * preset array( 'presetname' => string, 'presetid' => integer)
  951. * empty array if preset_name is an invalid preset
  952. */
  953. function imagecache_preset_by_name($preset_name) {
  954. static $presets_by_name = array();
  955. if (!$presets_by_name && $presets = imagecache_presets()) {
  956. foreach ($presets as $preset) {
  957. $presets_by_name[$preset['presetname']] = $preset;
  958. }
  959. }
  960. return (isset($presets_by_name[$preset_name])) ? $presets_by_name[$preset_name] : array();
  961. }
  962. /**
  963. * Save an ImageCache preset.
  964. *
  965. * @param preset
  966. * an imagecache preset array.
  967. * @return
  968. * a preset array. In the case of a new preset, 'presetid' will be populated.
  969. */
  970. function imagecache_preset_save($preset) {
  971. // @todo: CRUD level validation?
  972. if (isset($preset['presetid']) && is_numeric($preset['presetid'])) {
  973. drupal_write_record('imagecache_preset', $preset, 'presetid');
  974. }
  975. else {
  976. drupal_write_record('imagecache_preset', $preset);
  977. }
  978. // Reset presets cache.
  979. imagecache_preset_flush($preset);
  980. imagecache_presets(TRUE);
  981. // Rebuild Theme Registry
  982. drupal_rebuild_theme_registry();
  983. return $preset;
  984. }
  985. function imagecache_preset_delete($preset) {
  986. imagecache_preset_flush($preset);
  987. db_query('DELETE FROM {imagecache_action} where presetid = %d', $preset['presetid']);
  988. db_query('DELETE FROM {imagecache_preset} where presetid = %d', $preset['presetid']);
  989. imagecache_presets(TRUE);
  990. return TRUE;
  991. }
  992. function imagecache_preset_actions($preset, $reset = FALSE) {
  993. static $actions_cache = array();
  994. if ($reset || empty($actions_cache[$preset['presetid']])) {
  995. $result = db_query('SELECT * FROM {imagecache_action} where presetid = %d order by weight', $preset['presetid']);
  996. while ($row = db_fetch_array($result)) {
  997. $row['data'] = unserialize($row['data']);
  998. $actions_cache[$preset['presetid']][] = $row;
  999. }
  1000. }
  1001. return isset($actions_cache[$preset['presetid']]) ? $actions_cache[$preset['presetid']] : array();
  1002. }
  1003. /**
  1004. * Flush cached media for a preset.
  1005. *
  1006. * @param preset
  1007. * an imagecache preset array.
  1008. */
  1009. function imagecache_preset_flush($preset) {
  1010. if (user_access('flush imagecache')) {
  1011. $presetdir = realpath(file_directory_path() .'/imagecache/'. $preset['presetname']);
  1012. if (is_dir($presetdir)) {
  1013. module_invoke_all('imagecache_preset_flush', $presetdir, $preset);
  1014. _imagecache_recursive_delete($presetdir);
  1015. }
  1016. }
  1017. }
  1018. /**
  1019. * Clear cached versions of a specific file in all presets.
  1020. * @param $path
  1021. * The Drupal file path to the original image.
  1022. */
  1023. function imagecache_image_flush($path) {
  1024. foreach (imagecache_presets() as $preset) {
  1025. $derivative_path = imagecache_create_path($preset['presetname'], $path);
  1026. module_invoke_all('imagecache_image_flush', $derivative_path, $preset, $path);
  1027. file_delete($derivative_path);
  1028. }
  1029. }
  1030. function imagecache_action($actionid) {
  1031. static $actions = array();
  1032. if (!isset($actions[$actionid])) {
  1033. $action = array();
  1034. $result = db_query('SELECT * FROM {imagecache_action} WHERE actionid=%d', $actionid);
  1035. if ($row = db_fetch_array($result)) {
  1036. $action = $row;
  1037. $action['data'] = unserialize($action['data']);
  1038. $definition = imagecache_action_definition($action['action']);
  1039. $action = array_merge($definition, $action);
  1040. $actions[$actionid] = $action;
  1041. }
  1042. }
  1043. return $actions[$actionid];
  1044. }
  1045. function imagecache_action_load($actionid) {
  1046. return imagecache_action($actionid, TRUE);
  1047. }
  1048. function imagecache_action_save($action) {
  1049. $definition = imagecache_action_definition($action['action']);
  1050. $action = array_merge($definition, $action);
  1051. // Some actions don't have data. Make an empty one to prevent SQL errors.
  1052. if (!isset($action['data'])) {
  1053. $action['data'] = array();
  1054. }
  1055. if (!empty($action['actionid'])) {
  1056. drupal_write_record('imagecache_action', $action, 'actionid');
  1057. }
  1058. else {
  1059. drupal_write_record('imagecache_action', $action);
  1060. }
  1061. $preset = imagecache_preset($action['presetid']);
  1062. imagecache_preset_flush($preset);
  1063. imagecache_presets(TRUE);
  1064. return $action;
  1065. }
  1066. function imagecache_action_delete($action) {
  1067. db_query('DELETE FROM {imagecache_action} WHERE actionid=%d', $action['actionid']);
  1068. $preset = imagecache_preset($action['presetid']);
  1069. imagecache_preset_flush($preset);
  1070. imagecache_presets(TRUE);
  1071. }
  1072. /**
  1073. * Implementation of hook_action_info().
  1074. *
  1075. * Note: These are actions in the Drupal core trigger.module sense, not
  1076. * ImageCache actions.
  1077. */
  1078. function imagecache_action_info() {
  1079. $actions = array();
  1080. if (module_exists('filefield')) {
  1081. $actions['imagecache_flush_action'] = array(
  1082. 'type' => 'node',
  1083. 'description' => t("ImageCache: Flush ALL presets for this node's filefield images"),
  1084. 'configurable' => FALSE,
  1085. 'hooks' => array(
  1086. 'nodeapi' => array('presave', 'delete', 'insert', 'update'),
  1087. )
  1088. );
  1089. $actions['imagecache_generate_all_action'] = array(
  1090. 'type' => 'node',
  1091. 'description' => t("ImageCache: Generate ALL presets for this node's filefield images"),
  1092. 'configurable' => FALSE,
  1093. 'hooks' => array(
  1094. 'nodeapi' => array('presave', 'insert', 'update'),
  1095. )
  1096. );
  1097. $actions['imagecache_generate_action'] = array(
  1098. 'type' => 'node',
  1099. 'description' => t("ImageCache: Generate configured preset(s) for this node's filefield images"),
  1100. 'configurable' => TRUE,
  1101. 'hooks' => array(
  1102. 'nodeapi' => array('presave', 'insert', 'update'),
  1103. )
  1104. );
  1105. }
  1106. return $actions;
  1107. }
  1108. /**
  1109. * Flush all imagecache presets for a given node.
  1110. *
  1111. * @param $node
  1112. * A node object.
  1113. * @param $context
  1114. * Contains values from the calling action.
  1115. *
  1116. * @see imagecache_action_info()
  1117. */
  1118. function imagecache_flush_action(&$node, $context) {
  1119. $files = imagecache_get_images_in_node($node);
  1120. if (!empty($files)) {
  1121. foreach ($files as $file) {
  1122. imagecache_image_flush($file['filepath']);
  1123. }
  1124. }
  1125. }
  1126. /**
  1127. * Generate all imagecache presets for the given node.
  1128. *
  1129. * @param $node
  1130. * A node object.
  1131. * @param $context
  1132. * Contains values from the calling action.
  1133. *
  1134. * @see imagecache_action_info()
  1135. */
  1136. function imagecache_generate_all_action(&$node, $context) {
  1137. $files = imagecache_get_images_in_node($node);
  1138. $presets = imagecache_presets();
  1139. if (!empty($files) && !empty($presets)) {
  1140. foreach ($files as $file) {
  1141. foreach ($presets as $presetname) {
  1142. imagecache_generate_image($presetname['presetname'], $file['filepath']);
  1143. }
  1144. }
  1145. }
  1146. }
  1147. /**
  1148. * Generate imagecache presets for the given node and presets.
  1149. *
  1150. * @param $node
  1151. * A node object.
  1152. * @param $context
  1153. * Contains values from the calling action.
  1154. *
  1155. * @see imagecache_action_info()
  1156. * @see imagecache_generate_action_form()
  1157. */
  1158. function imagecache_generate_action(&$node, $context) {
  1159. $files = imagecache_get_images_in_node($node);
  1160. if (!empty($files) && !empty($context['imagecache_presets'])) {
  1161. foreach ($files as $file) {
  1162. foreach ($context['imagecache_presets'] as $presetname) {
  1163. imagecache_generate_image($presetname, $file['filepath']);
  1164. }
  1165. }
  1166. }
  1167. }
  1168. /**
  1169. * Form for configuring the generate action.
  1170. *
  1171. * @see imagecache_generate_action()
  1172. */
  1173. function imagecache_generate_action_form($context) {
  1174. $options = array();
  1175. foreach (imagecache_presets() as $preset) {
  1176. $options[$preset['presetname']] = $preset['presetname'];
  1177. }
  1178. $form['presets'] = array(
  1179. '#type' => 'checkboxes',
  1180. '#options' => $options,
  1181. '#description' => t('Select which imagecache presets will be effected'),
  1182. '#required' => TRUE,
  1183. '#default_value' => isset($context['imagecache_presets']) ? $context['imagecache_presets'] : array(),
  1184. );
  1185. // Filter out false checkboxes: http://drupal.org/node/61760#comment-402631
  1186. $form['array_filter'] = array('#type' => 'value', '#value' => TRUE);
  1187. return $form;
  1188. }
  1189. /**
  1190. * Generate a derivative image given presetname and filepath.
  1191. *
  1192. * This is a developer friendly version of _imagecache_cache(), it doesn't worry
  1193. * about sending HTTP headers or an image back to the client so it's much
  1194. * simpler.
  1195. *
  1196. * @param $presetname
  1197. * ImageCache preset array.
  1198. * @param $filepath
  1199. * String filepath from the files table.
  1200. * @return
  1201. * A Boolean indicating if the operation succeeded.
  1202. */
  1203. function imagecache_generate_image($presetname, $filepath) {
  1204. $preset = imagecache_preset_by_name($presetname);
  1205. if (empty($preset['presetname'])) {
  1206. return FALSE;
  1207. }
  1208. $destination = imagecache_create_path($preset['presetname'], $filepath);
  1209. if (file_exists($destination)) {
  1210. return TRUE;
  1211. }
  1212. return imagecache_build_derivative($preset['actions'], $filepath, $destination);
  1213. }
  1214. /**
  1215. * Given a node, get all images associated with it.
  1216. *
  1217. * Currently this only works with images stored in filefields.
  1218. *
  1219. * @param $node
  1220. * Node object.
  1221. * @return
  1222. * An array of info from the files table.
  1223. */
  1224. function imagecache_get_images_in_node(&$node) {
  1225. $files = array();
  1226. if (module_exists('filefield')) {
  1227. $data = filefield_get_node_files($node);
  1228. foreach ($data as $key => $value) {
  1229. if (stristr($value['filemime'], 'image')) {
  1230. $files[$key] = $value;
  1231. }
  1232. }
  1233. }
  1234. return $files;
  1235. }