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