Project

General

Profile

Paste
Download (47.1 KB) Statistics
| Branch: | Revision:

root / drupal7 / modules / image / image.module @ db2d93dd

1
<?php
2

    
3
/**
4
 * @file
5
 * Exposes global functionality for creating image styles.
6
 */
7

    
8
/**
9
 * Image style constant for user presets in the database.
10
 */
11
define('IMAGE_STORAGE_NORMAL', 1);
12

    
13
/**
14
 * Image style constant for user presets that override module-defined presets.
15
 */
16
define('IMAGE_STORAGE_OVERRIDE', 2);
17

    
18
/**
19
 * Image style constant for module-defined presets in code.
20
 */
21
define('IMAGE_STORAGE_DEFAULT', 4);
22

    
23
/**
24
 * Image style constant to represent an editable preset.
25
 */
26
define('IMAGE_STORAGE_EDITABLE', IMAGE_STORAGE_NORMAL | IMAGE_STORAGE_OVERRIDE);
27

    
28
/**
29
 * Image style constant to represent any module-based preset.
30
 */
31
define('IMAGE_STORAGE_MODULE', IMAGE_STORAGE_OVERRIDE | IMAGE_STORAGE_DEFAULT);
32

    
33
/**
34
 * The name of the query parameter for image derivative tokens.
35
 */
36
define('IMAGE_DERIVATIVE_TOKEN', 'itok');
37

    
38
// Load all Field module hooks for Image.
39
require_once DRUPAL_ROOT . '/modules/image/image.field.inc';
40

    
41
/**
42
 * Implements hook_help().
43
 */
44
function image_help($path, $arg) {
45
  switch ($path) {
46
    case 'admin/help#image':
47
      $output = '';
48
      $output .= '<h3>' . t('About') . '</h3>';
49
      $output .= '<p>' . t('The Image module allows you to manipulate images on your website. It exposes a setting for using the <em>Image toolkit</em>, allows you to configure <em>Image styles</em> that can be used for resizing or adjusting images on display, and provides an <em>Image</em> field for attaching images to content. For more information, see the online handbook entry for <a href="@image">Image module</a>.', array('@image' => 'http://drupal.org/documentation/modules/image')) . '</p>';
50
      $output .= '<h3>' . t('Uses') . '</h3>';
51
      $output .= '<dl>';
52
      $output .= '<dt>' . t('Manipulating images') . '</dt>';
53
      $output .= '<dd>' . t('With the Image module you can scale, crop, resize, rotate and desaturate images without affecting the original image using <a href="@image">image styles</a>. When you change an image style, the module automatically refreshes all created images. Every image style must have a name, which will be used in the URL of the generated images. There are two common approaches to naming image styles (which you use will depend on how the image style is being applied):',array('@image' => url('admin/config/media/image-styles')));
54
      $output .= '<ul><li>' . t('Based on where it will be used: eg. <em>profile-picture</em>') . '</li>';
55
      $output .= '<li>' . t('Describing its appearance: eg. <em>square-85x85</em>') . '</li></ul>';
56
      $output .=  t('After you create an image style, you can add effects: crop, scale, resize, rotate, and desaturate (other contributed modules provide additional effects). For example, by combining effects as crop, scale, and desaturate, you can create square, grayscale thumbnails.') . '<dd>';
57
      $output .= '<dt>' . t('Attaching images to content as fields') . '</dt>';
58
      $output .= '<dd>' . t("Image module also allows you to attach images to content as fields. To add an image field to a <a href='@content-type'>content type</a>, go to the content type's <em>manage fields</em> page, and add a new field of type <em>Image</em>. Attaching images to content this way allows image styles to be applied and maintained, and also allows you more flexibility when theming.", array('@content-type' => url('admin/structure/types'))) . '</dd>';
59
      $output .= '</dl>';
60
      return $output;
61
    case 'admin/config/media/image-styles':
62
      return '<p>' . t('Image styles commonly provide thumbnail sizes by scaling and cropping images, but can also add various effects before an image is displayed. When an image is displayed with a style, a new file is created and the original image is left unchanged.') . '</p>';
63
    case 'admin/config/media/image-styles/edit/%/add/%':
64
      $effect = image_effect_definition_load($arg[7]);
65
      return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
66
    case 'admin/config/media/image-styles/edit/%/effects/%':
67
      $effect = ($arg[5] == 'add') ? image_effect_definition_load($arg[6]) : image_effect_load($arg[6], $arg[4]);
68
      return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
69
  }
70
}
71

    
72
/**
73
 * Implements hook_menu().
74
 */
75
function image_menu() {
76
  $items = array();
77

    
78
  // Generate image derivatives of publicly available files.
79
  // If clean URLs are disabled, image derivatives will always be served
80
  // through the menu system.
81
  // If clean URLs are enabled and the image derivative already exists,
82
  // PHP will be bypassed.
83
  $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
84
  $items[$directory_path . '/styles/%image_style'] = array(
85
    'title' => 'Generate image style',
86
    'page callback' => 'image_style_deliver',
87
    'page arguments' => array(count(explode('/', $directory_path)) + 1),
88
    'access callback' => TRUE,
89
    'type' => MENU_CALLBACK,
90
  );
91
  // Generate and deliver image derivatives of private files.
92
  // These image derivatives are always delivered through the menu system.
93
  $items['system/files/styles/%image_style'] = array(
94
    'title' => 'Generate image style',
95
    'page callback' => 'image_style_deliver',
96
    'page arguments' => array(3),
97
    'access callback' => TRUE,
98
    'type' => MENU_CALLBACK,
99
  );
100
  $items['admin/config/media/image-styles'] = array(
101
    'title' => 'Image styles',
102
    'description' => 'Configure styles that can be used for resizing or adjusting images on display.',
103
    'page callback' => 'image_style_list',
104
    'access arguments' => array('administer image styles'),
105
    'file' => 'image.admin.inc',
106
  );
107
  $items['admin/config/media/image-styles/list'] = array(
108
    'title' => 'List',
109
    'description' => 'List the current image styles on the site.',
110
    'page callback' => 'image_style_list',
111
    'access arguments' => array('administer image styles'),
112
    'type' => MENU_DEFAULT_LOCAL_TASK,
113
    'weight' => 1,
114
    'file' => 'image.admin.inc',
115
  );
116
  $items['admin/config/media/image-styles/add'] = array(
117
    'title' => 'Add style',
118
    'description' => 'Add a new image style.',
119
    'page callback' => 'drupal_get_form',
120
    'page arguments' => array('image_style_add_form'),
121
    'access arguments' => array('administer image styles'),
122
    'type' => MENU_LOCAL_ACTION,
123
    'weight' => 2,
124
    'file' => 'image.admin.inc',
125
  );
126
  $items['admin/config/media/image-styles/edit/%image_style'] = array(
127
    'title' => 'Edit style',
128
    'description' => 'Configure an image style.',
129
    'page callback' => 'drupal_get_form',
130
    'page arguments' => array('image_style_form', 5),
131
    'access arguments' => array('administer image styles'),
132
    'file' => 'image.admin.inc',
133
  );
134
  $items['admin/config/media/image-styles/delete/%image_style'] = array(
135
    'title' => 'Delete style',
136
    'description' => 'Delete an image style.',
137
    'load arguments' => array(NULL, (string) IMAGE_STORAGE_NORMAL),
138
    'page callback' => 'drupal_get_form',
139
    'page arguments' => array('image_style_delete_form', 5),
140
    'access arguments' => array('administer image styles'),
141
    'file' => 'image.admin.inc',
142
  );
143
  $items['admin/config/media/image-styles/revert/%image_style'] = array(
144
    'title' => 'Revert style',
145
    'description' => 'Revert an image style.',
146
    'load arguments' => array(NULL, (string) IMAGE_STORAGE_OVERRIDE),
147
    'page callback' => 'drupal_get_form',
148
    'page arguments' => array('image_style_revert_form', 5),
149
    'access arguments' => array('administer image styles'),
150
    'file' => 'image.admin.inc',
151
  );
152
  $items['admin/config/media/image-styles/edit/%image_style/effects/%image_effect'] = array(
153
    'title' => 'Edit image effect',
154
    'description' => 'Edit an existing effect within a style.',
155
    'load arguments' => array(5, (string) IMAGE_STORAGE_EDITABLE),
156
    'page callback' => 'drupal_get_form',
157
    'page arguments' => array('image_effect_form', 5, 7),
158
    'access arguments' => array('administer image styles'),
159
    'file' => 'image.admin.inc',
160
  );
161
  $items['admin/config/media/image-styles/edit/%image_style/effects/%image_effect/delete'] = array(
162
    'title' => 'Delete image effect',
163
    'description' => 'Delete an existing effect from a style.',
164
    'load arguments' => array(5, (string) IMAGE_STORAGE_EDITABLE),
165
    'page callback' => 'drupal_get_form',
166
    'page arguments' => array('image_effect_delete_form', 5, 7),
167
    'access arguments' => array('administer image styles'),
168
    'file' => 'image.admin.inc',
169
  );
170
  $items['admin/config/media/image-styles/edit/%image_style/add/%image_effect_definition'] = array(
171
    'title' => 'Add image effect',
172
    'description' => 'Add a new effect to a style.',
173
    'load arguments' => array(5),
174
    'page callback' => 'drupal_get_form',
175
    'page arguments' => array('image_effect_form', 5, 7),
176
    'access arguments' => array('administer image styles'),
177
    'file' => 'image.admin.inc',
178
  );
179

    
180
  return $items;
181
}
182

    
183
/**
184
 * Implements hook_theme().
185
 */
186
function image_theme() {
187
  return array(
188
    // Theme functions in image.module.
189
    'image_style' => array(
190
      'variables' => array(
191
        'style_name' => NULL,
192
        'path' => NULL,
193
        'width' => NULL,
194
        'height' => NULL,
195
        'alt' => '',
196
        'title' => NULL,
197
        'attributes' => array(),
198
      ),
199
    ),
200

    
201
    // Theme functions in image.admin.inc.
202
    'image_style_list' => array(
203
      'variables' => array('styles' => NULL),
204
    ),
205
    'image_style_effects' => array(
206
      'render element' => 'form',
207
    ),
208
    'image_style_preview' => array(
209
      'variables' => array('style' => NULL),
210
    ),
211
    'image_anchor' => array(
212
      'render element' => 'element',
213
    ),
214
    'image_resize_summary' => array(
215
      'variables' => array('data' => NULL),
216
    ),
217
    'image_scale_summary' => array(
218
      'variables' => array('data' => NULL),
219
    ),
220
    'image_crop_summary' => array(
221
      'variables' => array('data' => NULL),
222
    ),
223
    'image_rotate_summary' => array(
224
      'variables' => array('data' => NULL),
225
    ),
226

    
227
    // Theme functions in image.field.inc.
228
    'image_widget' => array(
229
      'render element' => 'element',
230
    ),
231
    'image_formatter' => array(
232
      'variables' => array('item' => NULL, 'path' => NULL, 'image_style' => NULL),
233
    ),
234
  );
235
}
236

    
237
/**
238
 * Implements hook_permission().
239
 */
240
function image_permission() {
241
  return array(
242
    'administer image styles' => array(
243
      'title' => t('Administer image styles'),
244
      'description' => t('Create and modify styles for generating image modifications such as thumbnails.'),
245
    ),
246
  );
247
}
248

    
249
/**
250
 * Implements hook_form_FORM_ID_alter().
251
 */
252
function image_form_system_file_system_settings_alter(&$form, &$form_state) {
253
  $form['#submit'][] = 'image_system_file_system_settings_submit';
254
}
255

    
256
/**
257
 * Form submission handler for system_file_system_settings().
258
 *
259
 * Adds a menu rebuild after the public file path has been changed, so that the
260
 * menu router item depending on that file path will be regenerated.
261
 */
262
function image_system_file_system_settings_submit($form, &$form_state) {
263
  if ($form['file_public_path']['#default_value'] !== $form_state['values']['file_public_path']) {
264
    variable_set('menu_rebuild_needed', TRUE);
265
  }
266
}
267

    
268
/**
269
 * Implements hook_flush_caches().
270
 */
271
function image_flush_caches() {
272
  return array('cache_image');
273
}
274

    
275
/**
276
 * Implements hook_file_download().
277
 *
278
 * Control the access to files underneath the styles directory.
279
 */
280
function image_file_download($uri) {
281
  $path = file_uri_target($uri);
282

    
283
  // Private file access for image style derivatives.
284
  if (strpos($path, 'styles/') === 0) {
285
    $args = explode('/', $path);
286
    // Discard the first part of the path (styles).
287
    array_shift($args);
288
    // Get the style name from the second part.
289
    $style_name = array_shift($args);
290
    // Remove the scheme from the path.
291
    array_shift($args);
292

    
293
    // Then the remaining parts are the path to the image.
294
    $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
295

    
296
    // Check that the file exists and is an image.
297
    if ($info = image_get_info($uri)) {
298
      // Check the permissions of the original to grant access to this image.
299
      $headers = module_invoke_all('file_download', $original_uri);
300
      // Confirm there's at least one module granting access and none denying access.
301
      if (!empty($headers) && !in_array(-1, $headers)) {
302
        return array(
303
          // Send headers describing the image's size, and MIME-type...
304
          'Content-Type' => $info['mime_type'],
305
          'Content-Length' => $info['file_size'],
306
          // By not explicitly setting them here, this uses normal Drupal
307
          // Expires, Cache-Control and ETag headers to prevent proxy or
308
          // browser caching of private images.
309
        );
310
      }
311
    }
312
    return -1;
313
  }
314

    
315
  // Private file access for the original files. Note that we only check access
316
  // for non-temporary images, since file.module will grant access for all
317
  // temporary files.
318
  $files = file_load_multiple(array(), array('uri' => $uri));
319
  if (count($files)) {
320
    $file = reset($files);
321
    if ($file->status) {
322
      return file_file_download($uri, 'image');
323
    }
324
  }
325
}
326

    
327
/**
328
 * Implements hook_file_move().
329
 */
330
function image_file_move($file, $source) {
331
  // Delete any image derivatives at the original image path.
332
  image_path_flush($source->uri);
333
}
334

    
335
/**
336
 * Implements hook_file_delete().
337
 */
338
function image_file_delete($file) {
339
  // Delete any image derivatives of this image.
340
  image_path_flush($file->uri);
341
}
342

    
343
/**
344
 * Implements hook_image_default_styles().
345
 */
346
function image_image_default_styles() {
347
  $styles = array();
348

    
349
  $styles['thumbnail'] = array(
350
    'label' => 'Thumbnail (100x100)',
351
    'effects' => array(
352
      array(
353
        'name' => 'image_scale',
354
        'data' => array('width' => 100, 'height' => 100, 'upscale' => 1),
355
        'weight' => 0,
356
      ),
357
    )
358
  );
359

    
360
  $styles['medium'] = array(
361
    'label' => 'Medium (220x220)',
362
    'effects' => array(
363
      array(
364
        'name' => 'image_scale',
365
        'data' => array('width' => 220, 'height' => 220, 'upscale' => 1),
366
        'weight' => 0,
367
      ),
368
    )
369
  );
370

    
371
  $styles['large'] = array(
372
    'label' => 'Large (480x480)',
373
    'effects' => array(
374
      array(
375
        'name' => 'image_scale',
376
        'data' => array('width' => 480, 'height' => 480, 'upscale' => 0),
377
        'weight' => 0,
378
      ),
379
    )
380
  );
381

    
382
  return $styles;
383
}
384

    
385
/**
386
 * Implements hook_image_style_save().
387
 */
388
function image_image_style_save($style) {
389
  if (isset($style['old_name']) && $style['old_name'] != $style['name']) {
390
    $instances = field_read_instances();
391
    // Loop through all fields searching for image fields.
392
    foreach ($instances as $instance) {
393
      if ($instance['widget']['module'] == 'image') {
394
        $instance_changed = FALSE;
395
        foreach ($instance['display'] as $view_mode => $display) {
396
          // Check if the formatter involves an image style.
397
          if ($display['type'] == 'image' && $display['settings']['image_style'] == $style['old_name']) {
398
            // Update display information for any instance using the image
399
            // style that was just deleted.
400
            $instance['display'][$view_mode]['settings']['image_style'] = $style['name'];
401
            $instance_changed = TRUE;
402
          }
403
        }
404
        if ($instance['widget']['settings']['preview_image_style'] == $style['old_name']) {
405
          $instance['widget']['settings']['preview_image_style'] = $style['name'];
406
          $instance_changed = TRUE;
407
        }
408
        if ($instance_changed) {
409
          field_update_instance($instance);
410
        }
411
      }
412
    }
413
  }
414
}
415

    
416
/**
417
 * Implements hook_image_style_delete().
418
 */
419
function image_image_style_delete($style) {
420
  image_image_style_save($style);
421
}
422

    
423
/**
424
 * Implements hook_field_delete_field().
425
 */
426
function image_field_delete_field($field) {
427
  if ($field['type'] != 'image') {
428
    return;
429
  }
430

    
431
  // The value of a managed_file element can be an array if #extended == TRUE.
432
  $fid = (is_array($field['settings']['default_image']) ? $field['settings']['default_image']['fid'] : $field['settings']['default_image']);
433
  if ($fid && ($file = file_load($fid))) {
434
    file_usage_delete($file, 'image', 'default_image', $field['id']);
435
  }
436
}
437

    
438
/**
439
 * Implements hook_field_update_field().
440
 */
441
function image_field_update_field($field, $prior_field, $has_data) {
442
  if ($field['type'] != 'image') {
443
    return;
444
  }
445

    
446
  // The value of a managed_file element can be an array if #extended == TRUE.
447
  $fid_new = (is_array($field['settings']['default_image']) ? $field['settings']['default_image']['fid'] : $field['settings']['default_image']);
448
  $fid_old = (is_array($prior_field['settings']['default_image']) ? $prior_field['settings']['default_image']['fid'] : $prior_field['settings']['default_image']);
449

    
450
  $file_new = $fid_new ? file_load($fid_new) : FALSE;
451

    
452
  if ($fid_new != $fid_old) {
453

    
454
    // Is there a new file?
455
    if ($file_new) {
456
      $file_new->status = FILE_STATUS_PERMANENT;
457
      file_save($file_new);
458
      file_usage_add($file_new, 'image', 'default_image', $field['id']);
459
    }
460

    
461
    // Is there an old file?
462
    if ($fid_old && ($file_old = file_load($fid_old))) {
463
      file_usage_delete($file_old, 'image', 'default_image', $field['id']);
464
    }
465
  }
466

    
467
  // If the upload destination changed, then move the file.
468
  if ($file_new && (file_uri_scheme($file_new->uri) != $field['settings']['uri_scheme'])) {
469
    $directory = $field['settings']['uri_scheme'] . '://default_images/';
470
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
471
    file_move($file_new, $directory . $file_new->filename);
472
  }
473
}
474

    
475
/**
476
 * Implements hook_field_delete_instance().
477
 */
478
function image_field_delete_instance($instance) {
479
  // Only act on image fields.
480
  $field = field_read_field($instance['field_name']);
481
  if ($field['type'] != 'image') {
482
    return;
483
  }
484

    
485
  // The value of a managed_file element can be an array if the #extended
486
  // property is set to TRUE.
487
  $fid = $instance['settings']['default_image'];
488
  if (is_array($fid)) {
489
    $fid = $fid['fid'];
490
  }
491

    
492
  // Remove the default image when the instance is deleted.
493
  if ($fid && ($file = file_load($fid))) {
494
    file_usage_delete($file, 'image', 'default_image', $instance['id']);
495
  }
496
}
497

    
498
/**
499
 * Implements hook_field_update_instance().
500
 */
501
function image_field_update_instance($instance, $prior_instance) {
502
  // Only act on image fields.
503
  $field = field_read_field($instance['field_name']);
504
  if ($field['type'] != 'image') {
505
    return;
506
  }
507

    
508
  // The value of a managed_file element can be an array if the #extended
509
  // property is set to TRUE.
510
  $fid_new = $instance['settings']['default_image'];
511
  if (is_array($fid_new)) {
512
    $fid_new = $fid_new['fid'];
513
  }
514
  $fid_old = $prior_instance['settings']['default_image'];
515
  if (is_array($fid_old)) {
516
    $fid_old = $fid_old['fid'];
517
  }
518

    
519
  // If the old and new files do not match, update the default accordingly.
520
  $file_new = $fid_new ? file_load($fid_new) : FALSE;
521
  if ($fid_new != $fid_old) {
522
    // Save the new file, if present.
523
    if ($file_new) {
524
      $file_new->status = FILE_STATUS_PERMANENT;
525
      file_save($file_new);
526
      file_usage_add($file_new, 'image', 'default_image', $instance['id']);
527
    }
528
    // Delete the old file, if present.
529
    if ($fid_old && ($file_old = file_load($fid_old))) {
530
      file_usage_delete($file_old, 'image', 'default_image', $instance['id']);
531
    }
532
  }
533

    
534
  // If the upload destination changed, then move the file.
535
  if ($file_new && (file_uri_scheme($file_new->uri) != $field['settings']['uri_scheme'])) {
536
    $directory = $field['settings']['uri_scheme'] . '://default_images/';
537
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
538
    file_move($file_new, $directory . $file_new->filename);
539
  }
540
}
541

    
542
/**
543
 * Clears cached versions of a specific file in all styles.
544
 *
545
 * @param $path
546
 *   The Drupal file path to the original image.
547
 */
548
function image_path_flush($path) {
549
  $styles = image_styles();
550
  foreach ($styles as $style) {
551
    $image_path = image_style_path($style['name'], $path);
552
    if (file_exists($image_path)) {
553
      file_unmanaged_delete($image_path);
554
    }
555
  }
556
}
557

    
558
/**
559
 * Gets an array of all styles and their settings.
560
 *
561
 * @return
562
 *   An array of styles keyed by the image style ID (isid).
563
 * @see image_style_load()
564
 */
565
function image_styles() {
566
  $styles = &drupal_static(__FUNCTION__);
567

    
568
  // Grab from cache or build the array.
569
  if (!isset($styles)) {
570
    if ($cache = cache_get('image_styles', 'cache')) {
571
      $styles = $cache->data;
572
    }
573
    else {
574
      $styles = array();
575

    
576
      // Select the module-defined styles.
577
      foreach (module_implements('image_default_styles') as $module) {
578
        $module_styles = module_invoke($module, 'image_default_styles');
579
        foreach ($module_styles as $style_name => $style) {
580
          $style['name'] = $style_name;
581
          $style['label'] = empty($style['label']) ? $style_name : $style['label'];
582
          $style['module'] = $module;
583
          $style['storage'] = IMAGE_STORAGE_DEFAULT;
584
          foreach ($style['effects'] as $key => $effect) {
585
            $definition = image_effect_definition_load($effect['name']);
586
            $effect = array_merge($definition, $effect);
587
            $style['effects'][$key] = $effect;
588
          }
589
          $styles[$style_name] = $style;
590
        }
591
      }
592

    
593
      // Select all the user-defined styles.
594
      $user_styles = db_select('image_styles', NULL, array('fetch' => PDO::FETCH_ASSOC))
595
        ->fields('image_styles')
596
        ->orderBy('name')
597
        ->execute()
598
        ->fetchAllAssoc('name', PDO::FETCH_ASSOC);
599

    
600
      // Allow the user styles to override the module styles.
601
      foreach ($user_styles as $style_name => $style) {
602
        $style['module'] = NULL;
603
        $style['storage'] = IMAGE_STORAGE_NORMAL;
604
        $style['effects'] = image_style_effects($style);
605
        if (isset($styles[$style_name]['module'])) {
606
          $style['module'] = $styles[$style_name]['module'];
607
          $style['storage'] = IMAGE_STORAGE_OVERRIDE;
608
        }
609
        $styles[$style_name] = $style;
610
      }
611

    
612
      drupal_alter('image_styles', $styles);
613
      cache_set('image_styles', $styles);
614
    }
615
  }
616

    
617
  return $styles;
618
}
619

    
620
/**
621
 * Loads a style by style name or ID.
622
 *
623
 * May be used as a loader for menu items.
624
 *
625
 * @param $name
626
 *   The name of the style.
627
 * @param $isid
628
 *   Optional. The numeric id of a style if the name is not known.
629
 * @param $include
630
 *   If set, this loader will restrict to a specific type of image style, may be
631
 *   one of the defined Image style storage constants.
632
 *
633
 * @return
634
 *   An image style array containing the following keys:
635
 *   - "isid": The unique image style ID.
636
 *   - "name": The unique image style name.
637
 *   - "effects": An array of image effects within this image style.
638
 *   If the image style name or ID is not valid, an empty array is returned.
639
 * @see image_effect_load()
640
 */
641
function image_style_load($name = NULL, $isid = NULL, $include = NULL) {
642
  $styles = image_styles();
643

    
644
  // If retrieving by name.
645
  if (isset($name) && isset($styles[$name])) {
646
    $style = $styles[$name];
647
  }
648

    
649
  // If retrieving by image style id.
650
  if (!isset($name) && isset($isid)) {
651
    foreach ($styles as $name => $database_style) {
652
      if (isset($database_style['isid']) && $database_style['isid'] == $isid) {
653
        $style = $database_style;
654
        break;
655
      }
656
    }
657
  }
658

    
659
  // Restrict to the specific type of flag. This bitwise operation basically
660
  // states "if the storage is X, then allow".
661
  if (isset($style) && (!isset($include) || ($style['storage'] & (int) $include))) {
662
    return $style;
663
  }
664

    
665
  // Otherwise the style was not found.
666
  return FALSE;
667
}
668

    
669
/**
670
 * Saves an image style.
671
 *
672
 * @param array $style
673
 *   An image style array containing:
674
 *   - name: A unique name for the style.
675
 *   - isid: (optional) An image style ID.
676
 *
677
 * @return array
678
 *   An image style array containing:
679
 *   - name: An unique name for the style.
680
 *   - old_name: The original name for the style.
681
 *   - isid: An image style ID.
682
 *   - is_new: TRUE if this is a new style, and FALSE if it is an existing
683
 *     style.
684
 */
685
function image_style_save($style) {
686
  if (isset($style['isid']) && is_numeric($style['isid'])) {
687
    // Load the existing style to make sure we account for renamed styles.
688
    $old_style = image_style_load(NULL, $style['isid']);
689
    image_style_flush($old_style);
690
    drupal_write_record('image_styles', $style, 'isid');
691
    if ($old_style['name'] != $style['name']) {
692
      $style['old_name'] = $old_style['name'];
693
    }
694
  }
695
  else {
696
    // Add a default label when not given.
697
    if (empty($style['label'])) {
698
      $style['label'] = $style['name'];
699
    }
700
    drupal_write_record('image_styles', $style);
701
    $style['is_new'] = TRUE;
702
  }
703

    
704
  // Let other modules update as necessary on save.
705
  module_invoke_all('image_style_save', $style);
706

    
707
  // Clear all caches and flush.
708
  image_style_flush($style);
709

    
710
  return $style;
711
}
712

    
713
/**
714
 * Deletes an image style.
715
 *
716
 * @param $style
717
 *   An image style array.
718
 * @param $replacement_style_name
719
 *   (optional) When deleting a style, specify a replacement style name so
720
 *   that existing settings (if any) may be converted to a new style.
721
 *
722
 * @return
723
 *   TRUE on success.
724
 */
725
function image_style_delete($style, $replacement_style_name = '') {
726
  image_style_flush($style);
727

    
728
  db_delete('image_effects')->condition('isid', $style['isid'])->execute();
729
  db_delete('image_styles')->condition('isid', $style['isid'])->execute();
730

    
731
  // Let other modules update as necessary on save.
732
  $style['old_name'] = $style['name'];
733
  $style['name'] = $replacement_style_name;
734
  module_invoke_all('image_style_delete', $style);
735

    
736
  return TRUE;
737
}
738

    
739
/**
740
 * Loads all the effects for an image style.
741
 *
742
 * @param array $style
743
 *   An image style array containing:
744
 *   - isid: The unique image style ID that contains this image effect.
745
 *
746
 * @return array
747
 *   An array of image effects associated with specified image style in the
748
 *   format array('isid' => array()), or an empty array if the specified style
749
 *   has no effects.
750
 * @see image_effects()
751
 */
752
function image_style_effects($style) {
753
  $effects = image_effects();
754
  $style_effects = array();
755
  foreach ($effects as $effect) {
756
    if ($style['isid'] == $effect['isid']) {
757
      $style_effects[$effect['ieid']] = $effect;
758
    }
759
  }
760

    
761
  return $style_effects;
762
}
763

    
764
/**
765
 * Gets an array of image styles suitable for using as select list options.
766
 *
767
 * @param $include_empty
768
 *   If TRUE a <none> option will be inserted in the options array.
769
 * @param $output
770
 *   Optional flag determining how the options will be sanitized on output.
771
 *   Leave this at the default (CHECK_PLAIN) if you are using the output of
772
 *   this function directly in an HTML context, such as for checkbox or radio
773
 *   button labels, and do not plan to sanitize it on your own. If using the
774
 *   output of this function as select list options (its primary use case), you
775
 *   should instead set this flag to PASS_THROUGH to avoid double-escaping of
776
 *   the output (the form API sanitizes select list options by default).
777
 *
778
 * @return
779
 *   Array of image styles with the machine name as key and the label as value.
780
 */
781
function image_style_options($include_empty = TRUE, $output = CHECK_PLAIN) {
782
  $styles = image_styles();
783
  $options = array();
784
  if ($include_empty && !empty($styles)) {
785
    $options[''] = t('<none>');
786
  }
787
  foreach ($styles as $name => $style) {
788
    $options[$name] = ($output == PASS_THROUGH) ? $style['label'] : check_plain($style['label']);
789
  }
790

    
791
  if (empty($options)) {
792
    $options[''] = t('No defined styles');
793
  }
794
  return $options;
795
}
796

    
797
/**
798
 * Page callback: Generates a derivative, given a style and image path.
799
 *
800
 * After generating an image, transfer it to the requesting agent.
801
 *
802
 * @param $style
803
 *   The image style
804
 */
805
function image_style_deliver($style, $scheme) {
806
  $args = func_get_args();
807
  array_shift($args);
808
  array_shift($args);
809
  $target = implode('/', $args);
810

    
811
  // Check that the style is defined, the scheme is valid, and the image
812
  // derivative token is valid. (Sites which require image derivatives to be
813
  // generated without a token can set the 'image_allow_insecure_derivatives'
814
  // variable to TRUE to bypass the latter check, but this will increase the
815
  // site's vulnerability to denial-of-service attacks. To prevent this
816
  // variable from leaving the site vulnerable to the most serious attacks, a
817
  // token is always required when a derivative of a derivative is requested.)
818
  $valid = !empty($style) && file_stream_wrapper_valid_scheme($scheme);
819
  if (!variable_get('image_allow_insecure_derivatives', FALSE) || strpos(ltrim($target, '\/'), 'styles/') === 0) {
820
    $valid = $valid && isset($_GET[IMAGE_DERIVATIVE_TOKEN]) && $_GET[IMAGE_DERIVATIVE_TOKEN] === image_style_path_token($style['name'], $scheme . '://' . $target);
821
  }
822
  if (!$valid) {
823
    return MENU_ACCESS_DENIED;
824
  }
825

    
826
  $image_uri = $scheme . '://' . $target;
827
  $derivative_uri = image_style_path($style['name'], $image_uri);
828

    
829
  // If using the private scheme, let other modules provide headers and
830
  // control access to the file.
831
  if ($scheme == 'private') {
832
    if (file_exists($derivative_uri)) {
833
      file_download($scheme, file_uri_target($derivative_uri));
834
    }
835
    else {
836
      $headers = module_invoke_all('file_download', $image_uri);
837
      if (in_array(-1, $headers) || empty($headers)) {
838
        return MENU_ACCESS_DENIED;
839
      }
840
      if (count($headers)) {
841
        foreach ($headers as $name => $value) {
842
          drupal_add_http_header($name, $value);
843
        }
844
      }
845
    }
846
  }
847

    
848
  // Confirm that the original source image exists before trying to process it.
849
  if (!is_file($image_uri)) {
850
    watchdog('image', 'Source image at %source_image_path not found while trying to generate derivative image at %derivative_path.',  array('%source_image_path' => $image_uri, '%derivative_path' => $derivative_uri));
851
    return MENU_NOT_FOUND;
852
  }
853

    
854
  // Don't start generating the image if the derivative already exists or if
855
  // generation is in progress in another thread.
856
  $lock_name = 'image_style_deliver:' . $style['name'] . ':' . drupal_hash_base64($image_uri);
857
  if (!file_exists($derivative_uri)) {
858
    $lock_acquired = lock_acquire($lock_name);
859
    if (!$lock_acquired) {
860
      // Tell client to retry again in 3 seconds. Currently no browsers are known
861
      // to support Retry-After.
862
      drupal_add_http_header('Status', '503 Service Unavailable');
863
      drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
864
      drupal_add_http_header('Retry-After', 3);
865
      print t('Image generation in progress. Try again shortly.');
866
      drupal_exit();
867
    }
868
  }
869

    
870
  // Try to generate the image, unless another thread just did it while we were
871
  // acquiring the lock.
872
  $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
873

    
874
  if (!empty($lock_acquired)) {
875
    lock_release($lock_name);
876
  }
877

    
878
  if ($success) {
879
    $image = image_load($derivative_uri);
880
    file_transfer($image->source, array('Content-Type' => $image->info['mime_type'], 'Content-Length' => $image->info['file_size']));
881
  }
882
  else {
883
    watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
884
    drupal_add_http_header('Status', '500 Internal Server Error');
885
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
886
    print t('Error generating image.');
887
    drupal_exit();
888
  }
889
}
890

    
891
/**
892
 * Creates a new image derivative based on an image style.
893
 *
894
 * Generates an image derivative by creating the destination folder (if it does
895
 * not already exist), applying all image effects defined in $style['effects'],
896
 * and saving a cached version of the resulting image.
897
 *
898
 * @param $style
899
 *   An image style array.
900
 * @param $source
901
 *   Path of the source file.
902
 * @param $destination
903
 *   Path or URI of the destination file.
904
 *
905
 * @return
906
 *   TRUE if an image derivative was generated, or FALSE if the image derivative
907
 *   could not be generated.
908
 *
909
 * @see image_style_load()
910
 */
911
function image_style_create_derivative($style, $source, $destination) {
912
  // If the source file doesn't exist, return FALSE without creating folders.
913
  if (!$image = image_load($source)) {
914
    return FALSE;
915
  }
916

    
917
  // Get the folder for the final location of this style.
918
  $directory = drupal_dirname($destination);
919

    
920
  // Build the destination folder tree if it doesn't already exist.
921
  if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
922
    watchdog('image', 'Failed to create style directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
923
    return FALSE;
924
  }
925

    
926
  foreach ($style['effects'] as $effect) {
927
    image_effect_apply($image, $effect);
928
  }
929

    
930
  if (!image_save($image, $destination)) {
931
    if (file_exists($destination)) {
932
      watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $destination), WATCHDOG_ERROR);
933
    }
934
    return FALSE;
935
  }
936

    
937
  return TRUE;
938
}
939

    
940
/**
941
 * Determines the dimensions of the styled image.
942
 *
943
 * Applies all of an image style's effects to $dimensions.
944
 *
945
 * @param $style_name
946
 *   The name of the style to be applied.
947
 * @param $dimensions
948
 *   Dimensions to be modified - an array with components width and height, in
949
 *   pixels.
950
 */
951
function image_style_transform_dimensions($style_name, array &$dimensions) {
952
  module_load_include('inc', 'image', 'image.effects');
953
  $style = image_style_load($style_name);
954

    
955
  if (!is_array($style)) {
956
    return;
957
  }
958

    
959
  foreach ($style['effects'] as $effect) {
960
    if (isset($effect['dimensions passthrough'])) {
961
      continue;
962
    }
963

    
964
    if (isset($effect['dimensions callback'])) {
965
      $effect['dimensions callback']($dimensions, $effect['data']);
966
    }
967
    else {
968
      $dimensions['width'] = $dimensions['height'] = NULL;
969
    }
970
  }
971
}
972

    
973
/**
974
 * Flushes cached media for a style.
975
 *
976
 * @param $style
977
 *   An image style array.
978
 */
979
function image_style_flush($style) {
980
  // Delete the style directory in each registered wrapper.
981
  $wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE);
982
  foreach ($wrappers as $wrapper => $wrapper_data) {
983
    if (file_exists($directory = $wrapper . '://styles/' . $style['name'])) {
984
      file_unmanaged_delete_recursive($directory);
985
    }
986
  }
987

    
988
  // Let other modules update as necessary on flush.
989
  module_invoke_all('image_style_flush', $style);
990

    
991
  // Clear image style and effect caches.
992
  cache_clear_all('image_styles', 'cache');
993
  cache_clear_all('image_effects:', 'cache', TRUE);
994
  drupal_static_reset('image_styles');
995
  drupal_static_reset('image_effects');
996

    
997
  // Clear field caches so that formatters may be added for this style.
998
  field_info_cache_clear();
999
  drupal_theme_rebuild();
1000

    
1001
  // Clear page caches when flushing.
1002
  if (module_exists('block')) {
1003
    cache_clear_all('*', 'cache_block', TRUE);
1004
  }
1005
  cache_clear_all('*', 'cache_page', TRUE);
1006
}
1007

    
1008
/**
1009
 * Returns the URL for an image derivative given a style and image path.
1010
 *
1011
 * @param $style_name
1012
 *   The name of the style to be used with this image.
1013
 * @param $path
1014
 *   The path to the image.
1015
 *
1016
 * @return
1017
 *   The absolute URL where a style image can be downloaded, suitable for use
1018
 *   in an <img> tag. Requesting the URL will cause the image to be created.
1019
 * @see image_style_deliver()
1020
 */
1021
function image_style_url($style_name, $path) {
1022
  $uri = image_style_path($style_name, $path);
1023

    
1024
  // The passed-in $path variable can be either a relative path or a full URI.
1025
  $original_uri = file_uri_scheme($path) ? file_stream_wrapper_uri_normalize($path) : file_build_uri($path);
1026

    
1027
  // The token query is added even if the 'image_allow_insecure_derivatives'
1028
  // variable is TRUE, so that the emitted links remain valid if it is changed
1029
  // back to the default FALSE.
1030
  // However, sites which need to prevent the token query from being emitted at
1031
  // all can additionally set the 'image_suppress_itok_output' variable to TRUE
1032
  // to achieve that (if both are set, the security token will neither be
1033
  // emitted in the image derivative URL nor checked for in
1034
  // image_style_deliver()).
1035
  $token_query = array();
1036
  if (!variable_get('image_suppress_itok_output', FALSE)) {
1037
    $token_query = array(IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, $original_uri));
1038
  }
1039

    
1040
  // If not using clean URLs, the image derivative callback is only available
1041
  // with the query string. If the file does not exist, use url() to ensure
1042
  // that it is included. Once the file exists it's fine to fall back to the
1043
  // actual file path, this avoids bootstrapping PHP once the files are built.
1044
  if (!variable_get('clean_url') && file_uri_scheme($uri) == 'public' && !file_exists($uri)) {
1045
    $directory_path = file_stream_wrapper_get_instance_by_uri($uri)->getDirectoryPath();
1046
    return url($directory_path . '/' . file_uri_target($uri), array('absolute' => TRUE, 'query' => $token_query));
1047
  }
1048

    
1049
  $file_url = file_create_url($uri);
1050
  // Append the query string with the token, if necessary.
1051
  if ($token_query) {
1052
    $file_url .= (strpos($file_url, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($token_query);
1053
  }
1054

    
1055
  return $file_url;
1056
}
1057

    
1058
/**
1059
 * Generates a token to protect an image style derivative.
1060
 *
1061
 * This prevents unauthorized generation of an image style derivative,
1062
 * which can be costly both in CPU time and disk space.
1063
 *
1064
 * @param $style_name
1065
 *   The name of the image style.
1066
 * @param $uri
1067
 *   The URI of the image for this style, for example as returned by
1068
 *   image_style_path().
1069
 *
1070
 * @return
1071
 *   An eight-character token which can be used to protect image style
1072
 *   derivatives against denial-of-service attacks.
1073
 */
1074
function image_style_path_token($style_name, $uri) {
1075
  // Return the first eight characters.
1076
  return substr(drupal_hmac_base64($style_name . ':' . $uri, drupal_get_private_key() . drupal_get_hash_salt()), 0, 8);
1077
}
1078

    
1079
/**
1080
 * Returns the URI of an image when using a style.
1081
 *
1082
 * The path returned by this function may not exist. The default generation
1083
 * method only creates images when they are requested by a user's browser.
1084
 *
1085
 * @param $style_name
1086
 *   The name of the style to be used with this image.
1087
 * @param $uri
1088
 *   The URI or path to the image.
1089
 *
1090
 * @return
1091
 *   The URI to an image style image.
1092
 * @see image_style_url()
1093
 */
1094
function image_style_path($style_name, $uri) {
1095
  $scheme = file_uri_scheme($uri);
1096
  if ($scheme) {
1097
    $path = file_uri_target($uri);
1098
  }
1099
  else {
1100
    $path = $uri;
1101
    $scheme = file_default_scheme();
1102
  }
1103
  return $scheme . '://styles/' . $style_name . '/' . $scheme . '/' . $path;
1104
}
1105

    
1106
/**
1107
 * Saves a default image style to the database.
1108
 *
1109
 * @param style
1110
 *   An image style array provided by a module.
1111
 *
1112
 * @return
1113
 *   An image style array. The returned style array will include the new 'isid'
1114
 *   assigned to the style.
1115
 */
1116
function image_default_style_save($style) {
1117
  $style = image_style_save($style);
1118
  $effects = array();
1119
  foreach ($style['effects'] as $effect) {
1120
    $effect['isid'] = $style['isid'];
1121
    $effect = image_effect_save($effect);
1122
    $effects[$effect['ieid']] = $effect;
1123
  }
1124
  $style['effects'] = $effects;
1125
  return $style;
1126
}
1127

    
1128
/**
1129
 * Reverts the changes made by users to a default image style.
1130
 *
1131
 * @param style
1132
 *   An image style array.
1133
 * @return
1134
 *   Boolean TRUE if the operation succeeded.
1135
 */
1136
function image_default_style_revert($style) {
1137
  image_style_flush($style);
1138

    
1139
  db_delete('image_effects')->condition('isid', $style['isid'])->execute();
1140
  db_delete('image_styles')->condition('isid', $style['isid'])->execute();
1141

    
1142
  return TRUE;
1143
}
1144

    
1145
/**
1146
 * Returns a set of image effects.
1147
 *
1148
 * These image effects are exposed by modules implementing
1149
 * hook_image_effect_info().
1150
 *
1151
 * @return
1152
 *   An array of image effects to be used when transforming images.
1153
 * @see hook_image_effect_info()
1154
 * @see image_effect_definition_load()
1155
 */
1156
function image_effect_definitions() {
1157
  global $language;
1158

    
1159
  // hook_image_effect_info() includes translated strings, so each language is
1160
  // cached separately.
1161
  $langcode = $language->language;
1162

    
1163
  $effects = &drupal_static(__FUNCTION__);
1164

    
1165
  if (!isset($effects)) {
1166
    if ($cache = cache_get("image_effects:$langcode")) {
1167
      $effects = $cache->data;
1168
    }
1169
    else {
1170
      $effects = array();
1171
      include_once DRUPAL_ROOT . '/modules/image/image.effects.inc';
1172
      foreach (module_implements('image_effect_info') as $module) {
1173
        foreach (module_invoke($module, 'image_effect_info') as $name => $effect) {
1174
          // Ensure the current toolkit supports the effect.
1175
          $effect['module'] = $module;
1176
          $effect['name'] = $name;
1177
          $effect['data'] = isset($effect['data']) ? $effect['data'] : array();
1178
          $effects[$name] = $effect;
1179
        }
1180
      }
1181
      uasort($effects, '_image_effect_definitions_sort');
1182
      drupal_alter('image_effect_info', $effects);
1183
      cache_set("image_effects:$langcode", $effects);
1184
    }
1185
  }
1186

    
1187
  return $effects;
1188
}
1189

    
1190
/**
1191
 * Loads the definition for an image effect.
1192
 *
1193
 * The effect definition is a set of core properties for an image effect, not
1194
 * containing any user-settings. The definition defines various functions to
1195
 * call when configuring or executing an image effect. This loader is mostly for
1196
 * internal use within image.module. Use image_effect_load() or
1197
 * image_style_load() to get image effects that contain configuration.
1198
 *
1199
 * @param $effect
1200
 *   The name of the effect definition to load.
1201
 * @param $style
1202
 *   An image style array to which this effect will be added.
1203
 *
1204
 * @return
1205
 *   An array containing the image effect definition with the following keys:
1206
 *   - "effect": The unique name for the effect being performed. Usually prefixed
1207
 *     with the name of the module providing the effect.
1208
 *   - "module": The module providing the effect.
1209
 *   - "help": A description of the effect.
1210
 *   - "function": The name of the function that will execute the effect.
1211
 *   - "form": (optional) The name of a function to configure the effect.
1212
 *   - "summary": (optional) The name of a theme function that will display a
1213
 *     one-line summary of the effect. Does not include the "theme_" prefix.
1214
 */
1215
function image_effect_definition_load($effect, $style_name = NULL) {
1216
  $definitions = image_effect_definitions();
1217

    
1218
  // If a style is specified, do not allow loading of default style
1219
  // effects.
1220
  if (isset($style_name)) {
1221
    $style = image_style_load($style_name, NULL);
1222
    if ($style['storage'] == IMAGE_STORAGE_DEFAULT) {
1223
      return FALSE;
1224
    }
1225
  }
1226

    
1227
  return isset($definitions[$effect]) ? $definitions[$effect] : FALSE;
1228
}
1229

    
1230
/**
1231
 * Loads all image effects from the database.
1232
 *
1233
 * @return
1234
 *   An array of all image effects.
1235
 * @see image_effect_load()
1236
 */
1237
function image_effects() {
1238
  $effects = &drupal_static(__FUNCTION__);
1239

    
1240
  if (!isset($effects)) {
1241
    $effects = array();
1242

    
1243
    // Add database image effects.
1244
    $result = db_select('image_effects', NULL, array('fetch' => PDO::FETCH_ASSOC))
1245
      ->fields('image_effects')
1246
      ->orderBy('image_effects.weight', 'ASC')
1247
      ->execute();
1248
    foreach ($result as $effect) {
1249
      $effect['data'] = unserialize($effect['data']);
1250
      $definition = image_effect_definition_load($effect['name']);
1251
      // Do not load image effects whose definition cannot be found.
1252
      if ($definition) {
1253
        $effect = array_merge($definition, $effect);
1254
        $effects[$effect['ieid']] = $effect;
1255
      }
1256
    }
1257
  }
1258

    
1259
  return $effects;
1260
}
1261

    
1262
/**
1263
 * Loads a single image effect.
1264
 *
1265
 * @param $ieid
1266
 *   The image effect ID.
1267
 * @param $style_name
1268
 *   The image style name.
1269
 * @param $include
1270
 *   If set, this loader will restrict to a specific type of image style, may be
1271
 *   one of the defined Image style storage constants.
1272
 *
1273
 * @return
1274
 *   An image effect array, consisting of the following keys:
1275
 *   - "ieid": The unique image effect ID.
1276
 *   - "isid": The unique image style ID that contains this image effect.
1277
 *   - "weight": The weight of this image effect within the image style.
1278
 *   - "name": The name of the effect definition that powers this image effect.
1279
 *   - "data": An array of configuration options for this image effect.
1280
 *   Besides these keys, the entirety of the image definition is merged into
1281
 *   the image effect array. Returns FALSE if the specified effect cannot be
1282
 *   found.
1283
 * @see image_style_load()
1284
 * @see image_effect_definition_load()
1285
 */
1286
function image_effect_load($ieid, $style_name, $include = NULL) {
1287
  if (($style = image_style_load($style_name, NULL, $include)) && isset($style['effects'][$ieid])) {
1288
    return $style['effects'][$ieid];
1289
  }
1290
  return FALSE;
1291
}
1292

    
1293
/**
1294
 * Saves an image effect.
1295
 *
1296
 * @param $effect
1297
 *   An image effect array.
1298
 *
1299
 * @return
1300
 *   An image effect array. In the case of a new effect, 'ieid' will be set.
1301
 */
1302
function image_effect_save($effect) {
1303
  if (!empty($effect['ieid'])) {
1304
    drupal_write_record('image_effects', $effect, 'ieid');
1305
  }
1306
  else {
1307
    drupal_write_record('image_effects', $effect);
1308
  }
1309
  $style = image_style_load(NULL, $effect['isid']);
1310
  image_style_flush($style);
1311
  return $effect;
1312
}
1313

    
1314
/**
1315
 * Deletes an image effect.
1316
 *
1317
 * @param $effect
1318
 *   An image effect array.
1319
 */
1320
function image_effect_delete($effect) {
1321
  db_delete('image_effects')->condition('ieid', $effect['ieid'])->execute();
1322
  $style = image_style_load(NULL, $effect['isid']);
1323
  image_style_flush($style);
1324
}
1325

    
1326
/**
1327
 * Applies an image effect to the image object.
1328
 *
1329
 * @param $image
1330
 *   An image object returned by image_load().
1331
 * @param $effect
1332
 *   An image effect array.
1333
 *
1334
 * @return
1335
 *   TRUE on success. FALSE if unable to perform the image effect on the image.
1336
 */
1337
function image_effect_apply($image, $effect) {
1338
  module_load_include('inc', 'image', 'image.effects');
1339
  $function = $effect['effect callback'];
1340
  if (function_exists($function)) {
1341
    return $function($image, $effect['data']);
1342
  }
1343
  return FALSE;
1344
}
1345

    
1346
/**
1347
 * Returns HTML for an image using a specific image style.
1348
 *
1349
 * @param $variables
1350
 *   An associative array containing:
1351
 *   - style_name: The name of the style to be used to alter the original image.
1352
 *   - path: The path of the image file relative to the Drupal files directory.
1353
 *     This function does not work with images outside the files directory nor
1354
 *     with remotely hosted images. This should be in a format such as
1355
 *     'images/image.jpg', or using a stream wrapper such as
1356
 *     'public://images/image.jpg'.
1357
 *   - width: The width of the source image (if known).
1358
 *   - height: The height of the source image (if known).
1359
 *   - alt: The alternative text for text-based browsers.
1360
 *   - title: The title text is displayed when the image is hovered in some
1361
 *     popular browsers.
1362
 *   - attributes: Associative array of attributes to be placed in the img tag.
1363
 *
1364
 * @ingroup themeable
1365
 */
1366
function theme_image_style($variables) {
1367
  // Determine the dimensions of the styled image.
1368
  $dimensions = array(
1369
    'width' => $variables['width'],
1370
    'height' => $variables['height'],
1371
  );
1372

    
1373
  image_style_transform_dimensions($variables['style_name'], $dimensions);
1374

    
1375
  $variables['width'] = $dimensions['width'];
1376
  $variables['height'] = $dimensions['height'];
1377

    
1378
  // Determine the URL for the styled image.
1379
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);
1380
  return theme('image', $variables);
1381
}
1382

    
1383
/**
1384
 * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
1385
 *
1386
 * @param $value
1387
 * @param $current_pixels
1388
 * @param $new_pixels
1389
 */
1390
function image_filter_keyword($value, $current_pixels, $new_pixels) {
1391
  switch ($value) {
1392
    case 'top':
1393
    case 'left':
1394
      return 0;
1395

    
1396
    case 'bottom':
1397
    case 'right':
1398
      return $current_pixels - $new_pixels;
1399

    
1400
    case 'center':
1401
      return $current_pixels / 2 - $new_pixels / 2;
1402
  }
1403
  return $value;
1404
}
1405

    
1406
/**
1407
 * Internal function for sorting image effect definitions through uasort().
1408
 *
1409
 * @see image_effect_definitions()
1410
 */
1411
function _image_effect_definitions_sort($a, $b) {
1412
  return strcasecmp($a['name'], $b['name']);
1413
}