summaryrefslogtreecommitdiffstats
path: root/imagecache.module
blob: 07a554fc6dcfdb29326e2aac401dd2a314f52bff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
<?php
// $Id$

/**
 * @file
 * Dynamic image resizer and image cacher.
 *
 * Imagecache allows you to setup specialized identifiers for dynamic image
 * processing and caching. It abuses the rewrite rules used for drupal's clean
 * URLs to provide dynamic image generation.
 * 
 * Earlier security flaws were overcome by using 'presets' similar to
 * image.module. We don't fuss with the database, and creating data that we have
 * to keep up within Drupal. We do it on the fly and flush it when we want to,
 * or when a preset changes.
 * 
 * URLs are of the form: files/imagecache/<preset>/path
 * 
 * @todo: improve image resizing, reduce distortion.
 * @todo: add watermarking capabilities.
 * @todo: split action/handlers into their own little .inc files.
 * @todo: enforce permissions.
 * 
 * Notes:
 *   To add a new handler,
 *     add fields and select option to _imagecache_actions_form;
 *     add handling code to imagecache_cache
 * 
 */


/*********************************************************************************************
 * Drupal Hooks
 *********************************************************************************************/

/**
 * Implementation of hook_perm().
 */
function imagecache_perm() {
  $perms =  array('administer imagecache', 'flush imagecache');
  foreach(imagecache_presets() as $preset) {
    $perms[] =  'view imagecache '. $preset['presetname'];
  }
  return $perms;
}

/**
 * Implementation of hook_menu().
 */
function imagecache_menu($may_cache) {
  $items = array();
  if ($may_cache) {

    // standard imagecache callback.
    $items[] = array(
      'path' => file_directory_path() .'/imagecache', 
      'callback' => 'imagecache_cache',
      'access' => TRUE,
      'type' => MENU_CALLBACK
    );

    // private downloads imagecache callback 
    $items[] = array( 
      'path' => 'system/files/imagecache',
      'callback' => 'imagecache_cache_private',
      'access' => TRUE,
      'type' => MENU_CALLBACK
    );     

    // settings form.
    $items[] = array(
      'path' => 'admin/settings/imagecache',
      'title' => t('Image cache'),
      'description' => t('Configure rulesets and actions for imagecache.'),
      'access' => user_access('administer imagecache'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array('imagecache_admin'),
    );
  }

  return $items;
}


/**
 * Implementation of hook_requirements().
 */
function imagecache_requirements($phase) {
  $requirements = array();
  // Ensure translations don't break at install time.
  $t = get_t();

  if ($phase == 'runtime') {
    // Check for an image library.
    if (count(image_get_available_toolkits()) == 0) {
      $requirements['clean_urls'] = array(
        'title' => $t('Image Toolkit'),
        'value' => $t('No image toolkits available'),
        'severity' => REQUIREMENT_ERROR,
        'description' => $t('Imagecache requires an imagetoolkit such as <a href="http://php.net/gd">GD2</a> or <a href="http://www.imagemagick.org">Imagemagick</a> be installed on your server.'),
      );
    }
    // Check for JPEG/PNG/GIF support.
    if ('gd' == image_get_toolkit()) {
      foreach (array('gif', 'jpeg', 'png') as $format) {
        if (!function_exists('imagecreatefrom'. $format)) {
          $requirements['gd_'. $format] = array(
            'title' => $t('GD !format Support', array('!format' => drupal_ucfirst($format))),
            'value' => $t('Not installed'),
            'severity' => REQUIREMENT_INFO,
            'description' => $t('PHP was not compiled with %format support. Imagecache will not be able to process %format images.', array('%format' => $format)), 
          );
        }
      } 
    }
  }
  return $requirements;
}


/**
 * Implementation of hook_imagecache_actions.
 *
 * @return array
 *   An array of information on the actions implemented by a module. The array contains a 
 *   sub-array for each action node type, with the machine-readable action name as the key. 
 *   Each sub-array has up to 3 attributes. Possible attributes:
 * 
 *     "name": the human-readable name of the action. Required.
 *     "description": a brief description of the action. Required.
 *     "file": the name of the include file the action can be found 
 *             in relative to the implementing module's path.
 */
function imagecache_imagecache_actions() {
  $actions = array(
    'imagecache_resize' => array(
      'name' => 'Resize',
      'description' => 'Resize an image to an exact set of dimensions, ignoring aspect ratio.',
    ),
    'imagecache_scale' => array(
      'name' => 'Scale',
      'description' => 'Resize an image maintaining the original aspect-ratio (only one value necessary).',
      'file' => 'imagecache_actions.inc',
    ),
    'imagecache_deprecated_scale' => array(
      'name' => 'Deprecated Scale',
      'description' => 'Precursor to Scale and Crop. Has inside and outside dimension support. This action will be removed in Imagecache 2.1).',
      'file' => 'imagecache_actions.inc',
    ),
    'imagecache_scale_and_crop' => array(
      'name' => 'Scale And Crop',
      'description' => 'Resize an image to an exact set of dimensions, ignoring aspect ratio.',
      'file' => 'imagecache_actions.inc',
    ),
    'imagecache_crop' => array(
      'name' => 'Crop',
      'description' => 'Crop an image to the rectangle specified by the given offsets and dimensions.',
      'file' => 'imagecache_actions.inc',
    ),
    'imagecache_desaturate' => array(
      'name' => 'Desaturate',
      'description' => 'Convert an image to grey scale.',
      'file' => 'imagecache_actions.inc',
    ),
  );

  return $actions;
}

/**
 * Pull in actions exposed by other modules using hook_imagecache_actions().
 *
 * @param $reset
 *   Boolean flag indicating whether the cached data should be
 *   wiped and recalculated.
 *
 * @return
 *   An array of actions to be used when transforming images.
 */
function imagecache_action_definitions($reset = FALSE) {
  static $actions;
  if (!isset($actions) || $reset) {
    if (!$reset && ($cache = cache_get('imagecache_actions')) && !empty($cache->data)) {
      $actions = unserialize($cache->data);
    }
    else {
      foreach(module_implements('imagecache_actions') as $module) {
        foreach (module_invoke($module, 'imagecache_actions') as $key => $action) {
          $action['module'] = $module;
          if ($action['file']) {
            $action['file'] = drupal_get_path('module', $action['module']) .'/'. $action['file'];
          }
          $actions[$key] = $action;
        };
      }
      uasort($actions, '_imagecache_definitions_sort');
      cache_set('imagecache_actions', 'cache', serialize($actions));
    }
  }
  return $actions;
}

function _imagecache_definitions_sort($a, $b) {
  $a = $a['name'];
  $b = $b['name'];
  if ($a == $b) {
    return 0;
  }
  return ($a < $b) ? -1 : 1;
}

function imagecache_action_definition($action) {
  static $definition_cache;
  if (!isset($definition_cache[$action])) {
    $definitions = imagecache_action_definitions();
    $definition = (isset($definitions[$action])) ? $definitions[$action] : array();
    
    if ($definition && $definition['file']) {
      require_once($definition['file']);
    }
    $definition_cache[$action] = $definition;
  }
  return $definition_cache[$action];
} 

/**
 * Return a URL that points to the location of a derivative of the
 * original image at @p $path, transformed with the given @p $preset.
 */
function imagecache_create_url($presetname, $path) {
  $path = _imagecache_strip_file_directory($path);
  return file_create_url(file_directory_path() .'/imagecache/'. $presetname .'/'. $path);
}

/**
 * Return 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.
 */
function imagecache_create_path($presetname, $path) {
  $path = _imagecache_strip_file_directory($path);
  return file_create_path() .'/imagecache/'. $presetname .'/'. $path;
}

/**
 * Remove a possible leading file directory path from the given path.
 */
function _imagecache_strip_file_directory($path) {
  $dirpath = file_directory_path();
  $dirlen = strlen($dirpath);
  if (substr($path, 0, $dirlen + 1) == $dirpath .'/') {
    $path = substr($path, $dirlen + 1);
  }
  return $path;
}


/** 
 * callback for handling public files imagecache requests.
 */
function imagecache_cache() {
  $args = func_get_args();
  $preset = check_plain(array_shift($args));
  $path = implode('/', $args);
  _imagecache_cache($preset, $path);
}

/**
 * callback for handling private files imagecache requests
 */
function imagecache_cache_private() {
  $args = func_get_args();
  $preset = check_plain(array_shift($args));
  $source = implode('/', $args);

  if (user_access('view imagecache '. $preset)) {
    _imagecache_cache($preset, $source);
  } 
  else {
    // if there is a 40333mage uploaded for the preset display it.
    $accesspath = file_create_path('imagecache/'. $preset .'.403.png');
    if (file_exists($accesspath)) {
      imagecache_transfer($accesspath);
      exit;
    }
    header('HTTP/1.0 403 Forbidden');
    exit;
  }
}

/**
 * handle request validation and responses to imagecache requests. 
 */
function _imagecache_cache($presetname, $path) {
  if (!$preset = imagecache_preset_by_name($presetname)) {
    // send a 404 if we dont' know of a preset. 
    header("HTTP/1.0 404 Not Found");
    exit;
  }
  $src = file_create_path($path);
  if (!is_file($src)) {
    // if there is a 404 image uploaded for the preset display it.
    $notfoundpath = file_create_path('imagecache/'. $preset['presetname'] .'.404.png');
    if (file_exists($notfoundpath)) {
      imagecache_transfer($notfoundpath);
      exit;
    }
    // otherwise send a 404.
    header("HTTP/1.0 404 Not Found");
    exit;
  }

  $dst = imagecache_create_path($preset['presetname'], $path);
  $tmp = file_directory_temp() .'/'. $preset['presetname'] . str_replace(dirname($src) .'/', '', $src);

  if (file_exists($tmp)) {
    watchdog('imagecache', t('Imagecache already generating: %dst, Lock file: %tmp.', array('%dst' => $dst, '%tmp' => $tmp)), WATCHDOG_NOTICE);
    // send a response code that will make the browser wait and reload in a 1/2 sec. 
    // header()
    exit;
  }
 
  // check if deriv exists... (file was created between apaches request handler and reaching this code)
  // otherwise try to create the derivative. 
  if (!file_exists($dst) && !imagecache_build_derivative($preset['actions'], $src, $dst, $tmp)) {
    // Generate an error if image could not generate.
    watchdog('imagecache', t('Failed generating an image from %image using imagecache preset %preset.', array('%image' => $path, '%preset' => $preset)), WATCHDOG_ERROR);
    header("HTTP/1.0 500 Internal Server Error");
    // remove lock file on error.
    unlink($tmp);
    exit;
  } 
  imagecache_transfer($dst);
}

function _imagecache_apply_action($action, $image) {
  $actions = imagecache_action_definitions();
 
  if ($definition = imagecache_action_definition($action['action'])) {
    return call_user_func($action['action'] .'_image', $image, $action['data']);
  }
  // skip undefined actions.. module probably got uninstalled or disabled.
  watchdog('imagecache', t('non-existant action %action', array('%action' => $action['action'])), WATCHDOG_NOTICE);
  return TRUE;
}

/**
 * helper function to transfer files from imagecache. Determines mime type and sets a last modified header.
 * @param $path path to file to be transferred.
 * @return <exit>
 */

function imagecache_transfer($path) {
  if (function_exists('mime_content_type')) {
       $mime = mime_content_type($path);
  }
  else {
    $size = getimagesize($path);
    $mime = $size['mime'];
  }
  $headers = array('Content-Type: '. mime_header_encode($mime));
  if ($fileinfo = stat($path)) {
    $headers[] = 'Last-Modified: '. gmdate('D, d M Y H:i:s', $fileinfo[9]) .' GMT';
  }
  file_transfer($path, $headers);
  exit;
}

/**
 * A recursive mkdir.
 */
function _imagecache_mkdir($dir) {
  $folders = explode("/", $dir);

  foreach ($folders as $folder) {
    $dirs[] = $folder;
    $path = implode("/", $dirs);
    if (is_dir($path)) {
      continue;
    }
    if (is_file($path)) {
      watchdog('imagecache', t('file exists where we would like a directory: %path', array('%path' => $path)), WATCHDOG_ERROR);
      return FALSE;
    } 
    if (!@mkdir($path)) {
      watchdog('imagecache', t('Could not create destination: %dir halted at: %path', array('%dir' => $dir, '%path' => $path)), WATCHDOG_ERROR);
      return FALSE;
    }
  }
  return TRUE;
}
 
/**
 * build an image cache derivative
 * 
 * @param $actions, array of imagecache actions.
 * @param $source, source file.
 * @param $dest, $destination file.
 * @return TRUE - derivative generated, FALSE - no derivative generated, NULL - derivative being generated
 */
function imagecache_build_derivative($actions, $src, $dst, $tmp) {
  // Copy src to tmp. We use the existence of tmp as a lock.
  if (!file_copy($src, $tmp)) {
    // can't copy source to temp... ack..
    watchdog('imagecache', t('Could not create temporary file: %path', array('%path' => $tmp)), WATCHDOG_ERROR);
    return FALSE;
  }

  // get the folder for the final location of this preset...
  $dir = dirname($dst);

  // Build the destination folder tree if it doesn't already exists.
  if (!file_check_directory($dir) && !_imagecache_mkdir($dir)) {
    watchdog('imagecache', t('Failed to create imagecache directory: %dir', array('%dir' => $dir)), WATCHDOG_ERROR);
    return FALSE;
  }

  foreach ($actions as $action) {
    $size = getimagesize($tmp);
    if (count($action['data'])) {
      $new_width = _imagecache_filter('width', $action['data']['width'], $size[0], $size[1]);
      $new_height = _imagecache_filter('height', $action['data']['height'], $size[0], $size[1]);
      foreach ($action['data'] as $key => $value) {
        $action['data'][$key] = _imagecache_filter($key, $value, $size[0], $size[1], $new_width, $new_height);
      }
    }
    if (!_imagecache_apply_action($action, $tmp)) {
      watchdog( 'imagecache', t('action(id:%id): %action failed for %src', array('%id' => $action['actionid'], '%action' => $action['action'], '%src' => $src)), WATCHDOG_ERROR);
      return FALSE;
    }
  }
  if (!file_move($tmp, $dst)) {
    watchdog('imagecache', t('failed to move tmp(%tmp) to dst(%dst)', array('%tmp' => $tmp, '%dst' => $dst)), WATCHDOG_ERROR);
    return FALSE;
  }
  return TRUE;
}

  



/**
 * Implementation of hook_field_formatter_info().
 */
function imagecache_field_formatter_info() {
  foreach (imagecache_presets() as $preset) {
    $formatters[$preset['presetname']] = array(
      'label' => $preset['presetname'],
      'field types' => array('image'),
    );
    $formatters[$preset['presetname'] .'_linked'] = array(
      'label' => $preset['presetname'] .' as link',
      'field types' => array('image'),
    );
  }
  return $formatters;
}

/**
 * Implementation of hook_field_formatter().
 */
function imagecache_field_formatter($field, $item, $formatter) {
  if (!isset($item['fid'])) {
    return '';
  }
  // Views does not load the file for us, while CCK display fields does.
  if (!isset($item['filepath'])) {
    $file = _imagecache_file_load($item['fid']);
    $item = array_merge($item, $file);
  }

  $presetname = preg_replace('/_linked$/', '', $formatter);
  if ($preset = imagecache_preset_by_name($presetname)) {
    return theme('imagecache_formatter', $field, $item, $formatter);
  }
}

function _imagecache_file_load($fid = NULL) {
  // Don't bother if we weren't passed an fid.
  if (isset($fid) && is_numeric($fid)) {
    $result = db_query('SELECT * FROM {files} WHERE fid = %d', $fid);
    $file = db_fetch_array($result);
  }
  return ($file) ? $file : array();
}


/**
 * Filter key word values such as 'top', 'right', 'center', and also percentages.
 * All returned values are in pixels relative to the passed in height and width.
 */
function _imagecache_filter($key, $value, $current_width, $current_height, $new_width = NULL, $new_height = NULL) {
  switch ($key) {
    case 'width':
      $value = _imagecache_percent_filter($value, $current_width);
      break;
    case 'height':
      $value = _imagecache_percent_filter($value, $current_height);
      break;
    case 'xoffset':
      $value = _imagecache_keyword_filter($value, $current_width, $new_width);
      break;
    case 'yoffset':
      $value = _imagecache_keyword_filter($value, $current_height, $new_height);
      break;
  }
  return $value;
}

/**
 * Accept a percentage and return it in pixels.
 */
function _imagecache_percent_filter($value, $current_pixels) {
  if (strpos($value, '%') !== FALSE) {
    $value = str_replace('%', '', $value) * 0.01 * $current_pixels;
  }
  return $value;
}

/**
 * Accept a keyword (center, top, left, etc) and return it as an offset in pixels.
 */
function _imagecache_keyword_filter($value, $current_pixels, $new_pixels) {
  switch ($value) {
    case 'top':
    case 'left':
      $value = 0;
      break;
    case 'bottom':
    case 'right':
      $value = $current_pixels - $new_pixels;
      break;
    case 'center':
      $value = $current_pixels/2 - $new_pixels/2;
      break;
  }
  return $value;
}

/**
 * Recursively delete all files and folders in the specified filepath, then
 * delete the containing folder.
 *
 * Note that this only deletes visible files with write permission.
 *
 * @param string $path
 *   A filepath relative to file_directory_path.
 */
function _imagecache_recursive_delete($path) {
  $listing = $path .'/*';
  foreach (glob($listing) as $file) {
    if (is_file($file) === TRUE) {
      @unlink($file);
    }
    elseif (is_dir($file) === TRUE) {
      _imagecache_recursive_delete($file);
    }
  }
  @rmdir($path);
}

function _imagecache_action_create($action) {
  $preset = imagecache_preset($action['presetid']);
  imagecache_preset_flush($preset);
  $next_id = db_next_id('{imagecache_action}_actionid');
  db_query("INSERT INTO {imagecache_action} (actionid, presetid, weight, action, data) VALUES (%d, %d, %d,'%s', '%s')", $next_id, $action['presetid'], $action['weight'], $action['action'], serialize($action['data']));
}

function _imagecache_action_update($action) {
  $preset = imagecache_preset($action['presetid']);
  imagecache_preset_flush($preset);
  db_query("UPDATE {imagecache_action} SET weight=%d, data='%s' WHERE actionid=%d", $action['weight'], serialize($action['data']), $action['actionid']);
}

function _imagecache_action_delete($action) {
  $preset = imagecache_preset($action['presetid']);
  imagecache_preset_flush($preset);
  db_query('DELETE FROM {imagecache_action} WHERE actionid = %d', $action['actionid']);
}

/**
  * Theme an img tag for displaying the image.
  */
function theme_imagecache_display($node, $label, $url, $attributes) {
  return '<img src="'. check_url($url) .'" alt="'. check_plain($node->title) .'" title="'. check_plain($node->title) .'" '. drupal_attributes($attributes) .' />';
}

/**
 * Verify the image module and toolkit settings.
 */
function _imagecache_check_settings() {
  // Sanity check : make sure we've got a working toolkit.
  if (!image_get_toolkit()) {
    drupal_set_message(t('Make sure you have a working image toolkit installed and enabled, for more information see: %settings.', array('%settings' => l(t('Image toolkit settings'), 'admin/settings/image-toolkit'))), 'error');
    return FALSE;
  }
  return TRUE;
}


function theme_imagecache_formatter($field, $item, $formatter) {
  if (preg_match('/_linked$/', $formatter)) {
    $formatter = preg_replace('/_linked$/', '', $formatter);
    $image = theme('imagecache', $formatter, $item['filepath'], $item['alt'], $item['title']);
    $output = l($image, 'node/'. $item['nid'], array(), NULL, NULL, FALSE, TRUE);
  }
  else {
    $output = theme('imagecache', $formatter, $item['filepath'], $item['alt'], $item['title']);
  }
  return $output;
}

function theme_imagecache($namespace, $path, $alt = '', $title = '', $attributes = NULL) {
  $attributes = drupal_attributes($attributes);

  $imagecache_path = imagecache_create_url($namespace, $path);
  return '<img src="'. $imagecache_path .'" alt="'. check_plain($alt) .'" title="'. check_plain($title) .'" '. $attributes .' />';
}


/************************************************************************************
 * ImageCache action implementation example in module.
 */
function imagecache_resize_image($image, $data) {
  if (!image_resize($image, $image, $data['width'], $data['height'])) {
    watchdog('imagecache', t('imagecache_resize_image failed. image: %image, data: %data.', array('%path' => $image, '%data' => print_r($data, TRUE))), WATCHDOG_ERROR);
    return FALSE;
  }
  return TRUE;
}

function imagecache_resize_form($action) {
  $form['width'] = array(
    '#type' => 'textfield',
    '#title' => t('Width'),
    '#default_value' => $action['width'],
    '#description' => t('Enter a width in pixels or as a percentage. i.e. 500 or 80%.'),
  );
  $form['height'] = array(
    '#type' => 'textfield',
    '#title' => t('Height'),
    '#default_value' => $action['height'],
    '#description' => t('Enter a height in pixels or as a percentage. i.e. 500 or 80%.'),
  );
  return $form;
}

function theme_imagecache_resize($element) {
  $data = $element['#value'];
  return 'width: '. $data['width'] .', height: '. $data['height'];
}



/**
 *  ImageCache 2.x API
 *
 *  The API for imagecache has changed. There is a compatibility layer for 
 *  imagecache 1.x. Please see the imagecache_compat.module
 * 
 *  The 2.x API returns more structured data, has shorter function names, and 
 *  implements more aggressive metadata caching.
 *
 */

/**
 * Get an array of all presets and their settings.
 *
 * @param reset
 *   if set to true it will clear the preset cache
 * 
 * @return
 *   array of presets array( $preset_id => array('presetid' => integer, 'presetname' => string))
 */
function imagecache_presets($reset = FALSE) {
  static $presets = array();

  // Clear  caches if $reset is TRUE;
  if ($reset) {
    $presets = array();
    cache_clear_all('imagecache:presets', 'cache');

    // Clear the content.module cache (refreshes the list of formatters provided by imagefield.module).
    if (module_exists('content')) {
      content_clear_type_cache();
    }
  }
  // Return presets if the array is populated.
  if (!empty($presets)) {
    return $presets;
  }

  // Grab from cache or build the array.
  if ($cache = cache_get('imagecache:presets', 'cache')) {
    $presets = unserialize($cache->data);
  }
  else {
    $result = db_query('SELECT * FROM {imagecache_preset} ORDER BY presetname');
    while ($preset = db_fetch_array($result)) {
      $presets[$preset['presetid']] = $preset;
      $presets[$preset['presetid']]['actions'] = imagecache_preset_actions($preset);
    }
    cache_set('imagecache:presets', 'cache', serialize($presets));
  }
  return $presets;
}

/**
 * Load a preset by preset_id.
 *
 * @param preset_id
 *   The numeric id of a preset.
 * 
 * @return
 *   preset array( 'presetname' => string, 'presetid' => integet)
 *   empty array if preset_id is an invalid preset
 */
function imagecache_preset($preset_id, $reset = FALSE) {
  $presets = imagecache_presets($reset);
  return (isset($presets[$preset_id])) ? $presets[$preset_id] : array();
}

/**
 * Load a preset by name.
 *
 * @param preset_name
 *
 * @return
 *   preset array( 'presetname' => string, 'presetid' => integer)
 *   empty array if preset_name is an invalid preset
 */
 
function imagecache_preset_by_name($preset_name) {
  static $presets_by_name = array();
  if (!$presets_by_name &&  $presets = imagecache_presets()) {
    foreach ($presets as $preset) {
      $presets_by_name[$preset['presetname']] = $preset;
    }
  }
  return (isset($presets_by_name[$preset_name])) ? $presets_by_name[$preset_name] : array(); 
}

/**
 * Save an ImageCache preset.
 *
 * @param preset
 *   an imagecache preset array.
 * @return
 *   a preset array.  In the case of a new preset, 'presetid' will be populated.
 */
function imagecache_preset_save($preset) {
  // @todo: CRUD level validation?
  if (isset($preset['presetid']) && is_numeric($preset['presetid'])) {
    db_query('UPDATE {imagecache_preset} SET presetname =\'%s\' WHERE presetid = %d', $preset['presetname'], $preset['presetid']);
  }
  else {
    $preset['presetid'] = db_next_id('{imagecache_preset}_presetid');
    db_query('INSERT INTO {imagecache_preset} (presetid, presetname) VALUES (%d, \'%s\')', $preset['presetid'], $preset['presetname']);
  }

  // Reset presets cache.
  imagecache_preset_flush($preset);
  imagecache_presets(TRUE);
  return $preset;
}

function imagecache_preset_delete($preset) {
  imagecache_preset_flush($preset['presetid']);
  db_query('DELETE FROM {imagecache_action} where presetid = %d', $preset['presetid']);
  db_query('DELETE FROM {imagecache_preset} where presetid = %d', $preset['presetid']);
  imagecache_presets(TRUE);
  return TRUE;
}

function imagecache_preset_actions($preset, $reset = FALSE) {
  static $actions_cache = array();

  if ($reset || empty($actions_cache[$preset['presetid']])) {
    $result = db_query('SELECT * FROM {imagecache_action} where presetid = %d order by weight', $preset['presetid']);
    while ($row = db_fetch_array($result)) {
      $row['data'] = unserialize($row['data']);
      $actions_cache[$preset['presetid']][] = $row;
    } 
  }

  return isset($actions_cache[$preset['presetid']]) ? $actions_cache[$preset['presetid']] : array();
}

/**
 * Flush cached media for a preset.
 * @param id
 *   A preset id.
 */
function imagecache_preset_flush($preset) {
  if (user_access('flush imagecache')) {
    $presetdir = realpath(file_directory_path() .'/imagecache/'. $preset['presetname']);
    if (is_dir($presetdir)) {
      _imagecache_recursive_delete($presetdir);
    }
  }
}

/**
 * Clear cached versions of a specific file in all presets.
 * @param $path
 *   The Drupal file path to the original image.
 */
function imagecache_image_flush($path) {
  foreach (imagecache_presets() as $preset) {
    $ipath = file_directory_path() .'/imagecache/'. $preset['presetname'] .'/'. $path;
    file_delete($ipath);
  }
}

function imagecache_action($actionid) {
  static $actions;

  if (!isset($actions[$actionid])) {
    $action = array();

    $result = db_query('SELECT * FROM {imagecache_action} WHERE actionid=%d', $actionid);
    if ($row = db_fetch_array($result)) {
      $action = $row;
      $action['data'] = unserialize($action['data']);

      $definition = imagecache_action_definition($action['action']);
      $action = array_merge($definition, $action);
      $actions[$actionid] = $action;
    }
  }  
  return $actions[$actionid];
}

function imagecache_action_save($action) {
  if ($action['actionid']) {
    db_query("UPDATE {imagecache_action} SET weight=%d, data='%s' WHERE actionid=%d", $action['weight'], serialize($action['data']), $action['actionid']);
  }
  else {
    $action['actionid'] = db_next_id('{imagecache_action}_actionid');
    db_query("INSERT INTO {imagecache_action} (actionid, presetid, weight, action, data) VALUES (%d, %d, %d,'%s', '%s')", $action['actionid'], $action['presetid'], $action['weight'], $action['action'], serialize($action['data']));
  }
  $preset = imagecache_preset($action['presetid']);
  imagecache_preset_flush($preset);
  imagecache_presets(TRUE);
  return $action; 
}

function imagecache_action_delete($action) {
  db_query("DELETE FROM {imagecache_action} WHERE actionid=%d", $action['actionid']);
  $preset = imagecache_preset($action['presetid']);
  imagecache_preset_flush($preset);
  imagecache_presets(TRUE);
}


/**
 * Imagecache 1.x Compatability Wrappers
 * 
 * *** Deprecated***
 *
 * Several functions got renamed in the 2.x upgrade. The following wrapper 
 * functions are available for compatability sake. They will be removed in
 * imagecache 2.1.
 *
 */

/**
 * Legacy get_presets function superceeded by imagecache_presets
 *
 * @deprecated
 * 
 * @return 
 *   array of presets in presetid => presetname format.
 */
function _imagecache_get_presets($reset = FALSE) {
  static $compat_presets = array();
  
  if ($reset) {
    $compat_presets = array();
  }

  if (empty($compat_presets)) {
    if ($presets = imagecache_presets($reset)) {
      foreach ($presets as $preset) {
        $compat_preset[$preset['presetid']] = $preset['name'];
      }
    }
  }
  return $compat_presets;
}

/**
 * Load a preset by id.
 * @param id
 *    Preset id.
 */
function _imagecache_preset_load($id) {
  return imagecache_preset($id);
}

/**
 * Load a preset by name.
 *  @param name
 *    Preset name.
 */
function _imagecache_preset_load_by_name($name) {
  return imagecache_preset_by_name($name);
}

/**
 * Create a preset.
 * @param name
 *    Name of the preset to be created.
 */
function _imagecache_preset_create($name) {
  $preset = array('presetname' => $name);
  return imagecache_preset_save($preset);
}

/**
 * Update a preset.
 * @param id
 *    Preset id.
 * @param name
 *    new name for the preset
 */
function _imagecache_preset_update($id, $name) {
  $preset = array('presetid' => $id, 'presetname' => $name);
  $return =  imagecache_preset_save($preset);
  drupal_set_message(t('Updated preset "%name" (ID: @id)', array('%name' => $name, '@id' => $id)));
  return $return;
}


function _imagecache_preset_delete($id, $name) {
  $preset = array('presetid' => $id, 'presetname' => $name);
  $return = imagecache_preset_delete($preset);
  drupal_set_message(t('Preset "%name" (ID: @id) deleted.', array('%name' => $name, '@id' => $id)));
  return $return;
}

function _imagecache_actions_get_by_presetid($presetid) {
  $presets = imagecache_presets();
  return (isset($presets[$presetid]['actions'])) ? $presets[$presetid]['actions'] : array();
}

function _imagecache_preset_flush($id) {
  $preset = imagecache_preset($id);
  imagecache_preset_flush($preset);
  drupal_set_message(t('Preset "%name" (ID: @id) flushed.', array('%name' => $preset['presetname'], '@id' => $preset['presetid'])));
}