image.module 37.3 KB
Newer Older
1
2
3
4
5
6
7
<?php

/**
 * @file
 * Exposes global functionality for creating image styles.
 */

8
9
10
/**
 * Image style constant for user presets in the database.
 */
11
const IMAGE_STORAGE_NORMAL = 1;
12
13
14
15

/**
 * Image style constant for user presets that override module-defined presets.
 */
16
const IMAGE_STORAGE_OVERRIDE = 2;
17
18
19
20

/**
 * Image style constant for module-defined presets in code.
 */
21
const IMAGE_STORAGE_DEFAULT = 4;
22
23
24
25
26
27
28
29
30
31
32

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

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

33
// Load all Field module hooks for Image.
34
require_once DRUPAL_ROOT . '/core/modules/image/image.field.inc';
35

36
37
38
39
40
41
42
/**
 * Implement of hook_help().
 */
function image_help($path, $arg) {
  switch ($path) {
    case 'admin/help#image':
      $output = '';
43
      $output .= '<h3>' . t('About') . '</h3>';
44
      $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>';
45
46
47
48
49
50
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Manipulating images') . '</dt>';
      $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')));
      $output .= '<ul><li>' . t('Based on where it will be used: eg. <em>profile-picture</em>') . '</li>';
      $output .= '<li>' . t('Describing its appearance: eg. <em>square-85x85</em>') . '</li></ul>';
51
      $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>';
52
53
      $output .= '<dt>' . t('Attaching images to content as fields') . '</dt>';
      $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>';
54
      $output .= '</dl>';
55
      return $output;
56
    case 'admin/config/media/image-styles':
57
      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>';
58
    case 'admin/config/media/image-styles/edit/%/add/%':
59
60
      $effect = image_effect_definition_load($arg[7]);
      return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
61
    case 'admin/config/media/image-styles/edit/%/effects/%':
62
      $effect = ($arg[5] == 'add') ? image_effect_definition_load($arg[6]) : image_effect_load($arg[6], $arg[4]);
63
64
65
66
      return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
  }
}

67
/**
68
 * Implements hook_menu().
69
70
71
72
 */
function image_menu() {
  $items = array();

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

  return $items;
}

/**
170
 * Implements hook_theme().
171
172
173
 */
function image_theme() {
  return array(
174
    // Theme functions in image.module.
175
    'image_style' => array(
176
      'variables' => array(
177
        'style_name' => NULL,
178
        'path' => NULL,
179
180
        'width' => NULL,
        'height' => NULL,
181
        'alt' => '',
182
        'title' => NULL,
183
184
        'attributes' => array(),
      ),
185
    ),
186
187

    // Theme functions in image.admin.inc.
188
    'image_style_list' => array(
189
      'variables' => array('styles' => NULL),
190
191
    ),
    'image_style_effects' => array(
192
      'render element' => 'form',
193
194
    ),
    'image_style_preview' => array(
195
      'variables' => array('style' => NULL),
196
197
    ),
    'image_anchor' => array(
198
      'render element' => 'element',
199
200
    ),
    'image_resize_summary' => array(
201
      'variables' => array('data' => NULL),
202
203
    ),
    'image_scale_summary' => array(
204
      'variables' => array('data' => NULL),
205
206
    ),
    'image_crop_summary' => array(
207
      'variables' => array('data' => NULL),
208
209
    ),
    'image_rotate_summary' => array(
210
      'variables' => array('data' => NULL),
211
    ),
212
213
214

    // Theme functions in image.field.inc.
    'image_widget' => array(
215
      'render element' => 'element',
216
    ),
217
218
    'image_formatter' => array(
      'variables' => array('item' => NULL, 'path' => NULL, 'image_style' => NULL),
219
    ),
220
221
222
223
  );
}

/**
224
 * Implements hook_permission().
225
226
227
228
229
230
231
 */
function image_permission() {
  return array(
    'administer image styles' => array(
      'title' => t('Administer image styles'),
      'description' => t('Create and modify styles for generating image modifications such as thumbnails.'),
    ),
232
233
234
  );
}

235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/**
 * Implements hook_form_FORM_ID_alter().
 */
function image_form_system_file_system_settings_alter(&$form, &$form_state) {
  $form['#submit'][] = 'image_system_file_system_settings_submit';
}

/**
 * Submit handler for the file system settings form.
 *
 * Adds a menu rebuild after the public file path has been changed, so that the
 * menu router item depending on that file path will be regenerated.
 */
function image_system_file_system_settings_submit($form, &$form_state) {
  if ($form['file_public_path']['#default_value'] !== $form_state['values']['file_public_path']) {
    variable_set('menu_rebuild_needed', TRUE);
  }
}

254
/**
255
 * Implements hook_file_download().
256
257
258
 *
 * Control the access to files underneath the styles directory.
 */
259
260
261
262
263
264
function image_file_download($uri) {
  $path = file_uri_target($uri);

  // Private file access for image style derivatives.
  if (strpos($path, 'styles/') === 0) {
    $args = explode('/', $path);
265
266
267
268
    // Discard the first part of the path (styles).
    array_shift($args);
    // Get the style name from the second part.
    $style_name = array_shift($args);
269
270
271
    // Remove the scheme from the path.
    array_shift($args);

272
    // Then the remaining parts are the path to the image.
273
    $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
274
275

    // Check that the file exists and is an image.
276
    if ($info = image_get_info($uri)) {
277
      // Check the permissions of the original to grant access to this image.
278
      $headers = module_invoke_all('file_download', $original_uri);
279
280
      if (!in_array(-1, $headers)) {
        return array(
281
          // Send headers describing the image's size, and MIME-type...
282
283
          'Content-Type' => $info['mime_type'],
          'Content-Length' => $info['file_size'],
284
          // ...and allow the file to be cached for two weeks (matching the
285
          // value we/ use for the mod_expires settings in .htaccess) and
286
287
          // ensure that caching proxies do not share the image with other
          // users.
288
          'Expires' => gmdate(DATE_RFC1123, REQUEST_TIME + 1209600),
289
          'Cache-Control' => 'max-age=1209600, private, must-revalidate',
290
291
292
293
294
        );
      }
    }
    return -1;
  }
295
296
297
298
299
300
301
302
303
304
305

  // Private file access for the original files. Note that we only
  // check access for non-temporary images, since file.module will
  // grant access for all temporary files.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    $file = reset($files);
    if ($file->status) {
      return file_file_download($uri, 'image');
    }
  }
306
307
308
}

/**
309
 * Implements hook_file_move().
310
311
312
 */
function image_file_move($file, $source) {
  // Delete any image derivatives at the original image path.
313
  image_path_flush($source->uri);
314
315
316
}

/**
317
 * Implements hook_file_predelete().
318
 */
319
function image_file_predelete($file) {
320
  // Delete any image derivatives of this image.
321
  image_path_flush($file->uri);
322
323
}

324
325
326
327
328
329
330
331
332
333
334
335
/**
 * Implements hook_image_style_save().
 */
function image_image_style_save($style) {
  if (isset($style['old_name']) && $style['old_name'] != $style['name']) {
    $instances = field_read_instances();
    // Loop through all fields searching for image fields.
    foreach ($instances as $instance) {
      if ($instance['widget']['module'] == 'image') {
        $instance_changed = FALSE;
        foreach ($instance['display'] as $view_mode => $display) {
          // Check if the formatter involves an image style.
336
          if ($display['type'] == 'image' && $display['settings']['image_style'] == $style['old_name']) {
337
338
            // Update display information for any instance using the image
            // style that was just deleted.
339
340
            $instance['display'][$view_mode]['settings']['image_style'] = $style['name'];
            $instance_changed = TRUE;
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
          }
        }
        if ($instance['widget']['settings']['preview_image_style'] == $style['old_name']) {
          $instance['widget']['settings']['preview_image_style'] = $style['name'];
          $instance_changed = TRUE;
        }
        if ($instance_changed) {
          field_update_instance($instance);
        }
      }
    }
  }
}

/**
 * Implements hook_image_style_delete().
 */
function image_image_style_delete($style) {
  image_image_style_save($style);
}

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
/**
 * Implements hook_field_delete_field().
 */
function image_field_delete_field($field) {
  if ($field['type'] != 'image') {
    return;
  }

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

/**
 * Implements hook_field_update_field().
 */
function image_field_update_field($field, $prior_field, $has_data) {
  if ($field['type'] != 'image') {
    return;
  }

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

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

  if ($fid_new != $fid_old) {

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

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

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

414
415
416
417
418
419
420
421
422
/**
 * Clear cached versions of a specific file in all styles.
 *
 * @param $path
 *   The Drupal file path to the original image.
 */
function image_path_flush($path) {
  $styles = image_styles();
  foreach ($styles as $style) {
423
424
425
    $image_path = image_style_path($style['name'], $path);
    if (file_exists($image_path)) {
      file_unmanaged_delete($image_path);
426
427
428
429
430
431
432
433
434
435
436
437
    }
  }
}

/**
 * Get an array of all styles and their settings.
 *
 * @return
 *   An array of styles keyed by the image style ID (isid).
 * @see image_style_load()
 */
function image_styles() {
438
439
440
441
442
443
444
445
446
447
448
  // @todo Configuration must not be statically cached nor cache-system cached.
  //   However, there's a drupal_alter() involved here.

//  $styles = &drupal_static(__FUNCTION__);
//
//  // Grab from cache or build the array.
//  if (!isset($styles)) {
//    if ($cache = cache()->get('image_styles')) {
//      $styles = $cache->data;
//    }
//    else {
449
      $styles = array();
450

451
      // Select the styles we have configured.
452
      $configured_styles = config_get_verified_storage_names_with_prefix('image.style');
453
454
      foreach ($configured_styles as $config_name) {
        // @todo Allow to retrieve the name without prefix only.
455
        $style = image_style_load(str_replace('image.style.', '', $config_name));
456
        $styles[$style['name']] = $style;
457
      }
458
      drupal_alter('image_styles', $styles);
459
460
461
//      cache()->set('image_styles', $styles);
//    }
//  }
462
463
464
465
466
467
468
469
470
471
472
473

  return $styles;
}

/**
 * Load a style by style name or ID. May be used as a loader for menu items.
 *
 * @param $name
 *   The name of the style.
 * @return
 *   An image style array containing the following keys:
 *   - "name": The unique image style name.
474
 *   - "effects": An array of image effects within this image style.
475
 *   If the image style name is not valid, an empty array is returned.
476
477
 * @see image_effect_load()
 */
478
function image_style_load($name) {
479
  $style = config('image.style.' . $name)->get();
gdd's avatar
gdd committed
480

481
482
483
484
  // @todo Requires a more reliable + generic method to check for whether the
  //   configuration object exists.
  if (!isset($style['name'])) {
    return FALSE;
485
486
  }

487
488
489
490
491
492
493
494
495
  foreach ($style['effects'] as $ieid => $effect) {
    $definition = image_effect_definition_load($effect['name']);
    $effect = array_merge($definition, $effect);
    $style['effects'][$ieid] = $effect;
  }
  // Sort effects by weight.
  uasort($style['effects'], 'drupal_sort_weight');

  return $style;
496
497
498
499
500
501
502
503
}

/**
 * Save an image style.
 *
 * @param style
 *   An image style array.
 * @return
504
 *   An image style array.
505
506
 */
function image_style_save($style) {
507
  $config = config('image.style.' . $style['name']);
508
  $config->set('name', $style['name']);
509
  if (isset($style['effects'])) {
gdd's avatar
gdd committed
510
511
512
    $config->set('effects', $style['effects']);
  }
  else {
513
    $config->set('effects', array());
gdd's avatar
gdd committed
514
  }
515
  $config->save();
516
517
  // @todo is_new must only be set when the configuration object did not exist
  //   yet.
518
  $style['is_new'] = TRUE;
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542

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

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

  return $style;
}

/**
 * Delete an image style.
 *
 * @param $style
 *   An image style array.
 * @param $replacement_style_name
 *   (optional) When deleting a style, specify a replacement style name so
 *   that existing settings (if any) may be converted to a new style.
 * @return
 *   TRUE on success.
 */
function image_style_delete($style, $replacement_style_name = '') {
  image_style_flush($style);

543
  $config = config('image.style.' . $style['name']);
gdd's avatar
gdd committed
544
  $config->delete();
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559

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

  return TRUE;
}

/**
 * Load all the effects for an image style.
 *
 * @param $style
 *   An image style array.
 * @return
560
561
562
 *   An array of image effects associated with specified image style in the
 *   format array('isid' => array()), or an empty array if the specified style
 *   has no effects.
563
 *
564
 * @todo Remove this function; it's entirely obsolete.
565
566
 */
function image_style_effects($style) {
567
  return $style['effects'];
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
}

/**
 * Get an array of image styles suitable for using as select list options.
 *
 * @param $include_empty
 *   If TRUE a <none> option will be inserted in the options array.
 * @return
 *   Array of image styles both key and value are set to style name.
 */
function image_style_options($include_empty = TRUE) {
  $styles = image_styles();
  $options = array();
  if ($include_empty && !empty($styles)) {
    $options[''] = t('<none>');
  }
  $options = array_merge($options, drupal_map_assoc(array_keys($styles)));
  if (empty($options)) {
    $options[''] = t('No defined styles');
  }
  return $options;
}

/**
 * Menu callback; Given a style and image path, generate a derivative.
 *
594
 * After generating an image, transfer it to the requesting agent.
595
 *
596
597
 * @param $style
 *   The image style
598
 */
599
600
601
function image_style_deliver($style, $scheme) {
  // Check that the style is defined and the scheme is valid.
  if (!$style || !file_stream_wrapper_valid_scheme($scheme)) {
602
    drupal_exit();
603
  }
604

605
606
607
608
609
610
611
  $args = func_get_args();
  array_shift($args);
  array_shift($args);
  $target = implode('/', $args);

  $image_uri = $scheme . '://' . $target;
  $derivative_uri = image_style_path($style['name'], $image_uri);
612
613

  // If using the private scheme, let other modules provide headers and
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
  // control access to the file.
  if ($scheme == 'private') {
    if (file_exists($derivative_uri)) {
      file_download($scheme, file_uri_target($derivative_uri));
    }
    else {
      $headers = module_invoke_all('file_download', $image_uri);
      if (in_array(-1, $headers) || empty($headers)) {
        return drupal_access_denied();
      }
      if (count($headers)) {
        foreach ($headers as $name => $value) {
          drupal_add_http_header($name, $value);
        }
      }
    }
  }
631

632
  // Don't start generating the image if the derivative already exists or if
633
  // generation is in progress in another thread.
634
635
  $lock_name = 'image_style_deliver:' . $style['name'] . ':' . drupal_hash_base64($image_uri);
  if (!file_exists($derivative_uri)) {
636
637
638
639
    $lock_acquired = lock_acquire($lock_name);
    if (!$lock_acquired) {
      // Tell client to retry again in 3 seconds. Currently no browsers are known
      // to support Retry-After.
640
      drupal_add_http_header('Status', '503 Service Unavailable');
641
      drupal_add_http_header('Retry-After', 3);
642
      print t('Image generation in progress. Try again shortly.');
643
      drupal_exit();
644
    }
645
646
  }

647
648
  // Try to generate the image, unless another thread just did it while we were
  // acquiring the lock.
649
  $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
650

651
  if (!empty($lock_acquired)) {
652
653
    lock_release($lock_name);
  }
654

655
  if ($success) {
656
    $image = image_load($derivative_uri);
657
    file_transfer($image->source, array('Content-Type' => $image->info['mime_type'], 'Content-Length' => $image->info['file_size']));
658
659
  }
  else {
660
    watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
661
    drupal_add_http_header('Status', '500 Internal Server Error');
662
    print t('Error generating image.');
663
    drupal_exit();
664
665
666
667
  }
}

/**
668
669
670
671
672
 * Creates a new image derivative based on an image style.
 *
 * Generates an image derivative by creating the destination folder (if it does
 * not already exist), applying all image effects defined in $style['effects'],
 * and saving a cached version of the resulting image.
673
674
675
676
677
678
 *
 * @param $style
 *   An image style array.
 * @param $source
 *   Path of the source file.
 * @param $destination
679
 *   Path or URI of the destination file.
680
 *
681
 * @return
682
683
684
685
 *   TRUE if an image derivative was generated, or FALSE if the image derivative
 *   could not be generated.
 *
 * @see image_style_load()
686
687
688
 */
function image_style_create_derivative($style, $source, $destination) {
  // Get the folder for the final location of this style.
689
  $directory = drupal_dirname($destination);
690
691

  // Build the destination folder tree if it doesn't already exist.
692
  if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
693
    watchdog('image', 'Failed to create style directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
694
695
696
697
698
699
700
701
702
703
704
705
706
    return FALSE;
  }

  if (!$image = image_load($source)) {
    return FALSE;
  }

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

  if (!image_save($image, $destination)) {
    if (file_exists($destination)) {
707
      watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $destination), WATCHDOG_ERROR);
708
709
710
711
712
713
714
    }
    return FALSE;
  }

  return TRUE;
}

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
/**
 * Determines the dimensions of the styled image.
 *
 * Applies all of an image style's effects to $dimensions.
 *
 * @param $style_name
 *   The name of the style to be applied.
 * @param $dimensions
 *   Dimensions to be modified - an array with components width and height, in
 *   pixels.
 */
function image_style_transform_dimensions($style_name, array &$dimensions) {
  module_load_include('inc', 'image', 'image.effects');
  $style = image_style_load($style_name);

  if (!is_array($style)) {
    return;
  }

  foreach ($style['effects'] as $effect) {
    if (isset($effect['dimensions passthrough'])) {
      continue;
    }

    if (isset($effect['dimensions callback'])) {
      $effect['dimensions callback']($dimensions, $effect['data']);
    }
    else {
      $dimensions['width'] = $dimensions['height'] = NULL;
    }
  }
}

748
749
750
751
752
753
754
/**
 * Flush cached media for a style.
 *
 * @param $style
 *   An image style array.
 */
function image_style_flush($style) {
755
  $style_directory = drupal_realpath(file_default_scheme() . '://styles/' . $style['name']);
756
757
758
759
760
761
762
  if (is_dir($style_directory)) {
    file_unmanaged_delete_recursive($style_directory);
  }

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

763
764
765
766
767
//  // Clear image style and effect caches.
//  cache()->delete('image_styles');
//  cache()->deletePrefix('image_effects:');
//  drupal_static_reset('image_styles');
//  drupal_static_reset('image_effects');
768

769
770
771
772
  // Clear field caches so that formatters may be added for this style.
  field_info_cache_clear();
  drupal_theme_rebuild();

773
774
  // Clear page caches when flushing.
  if (module_exists('block')) {
775
    cache('block')->flush();
776
  }
777
  cache('page')->flush();
778
779
780
781
782
783
784
}

/**
 * Return the URL for an image derivative given a style and image path.
 *
 * @param $style_name
 *   The name of the style to be used with this image.
785
 * @param $path
786
787
788
789
 *   The path to the image.
 * @return
 *   The absolute URL where a style image can be downloaded, suitable for use
 *   in an <img> tag. Requesting the URL will cause the image to be created.
790
 * @see image_style_deliver()
791
 */
792
793
function image_style_url($style_name, $path) {
  $uri = image_style_path($style_name, $path);
794
795
796
797
798
799
800
801

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

  return file_create_url($uri);
805
806
807
}

/**
808
 * Return the URI of an image when using a style.
809
810
811
812
813
814
 *
 * The path returned by this function may not exist. The default generation
 * method only creates images when they are requested by a user's browser.
 *
 * @param $style_name
 *   The name of the style to be used with this image.
815
816
 * @param $uri
 *   The URI or path to the image.
817
 * @return
818
 *   The URI to an image style image.
819
820
 * @see image_style_url()
 */
821
function image_style_path($style_name, $uri) {
822
823
824
825
826
827
  $scheme = file_uri_scheme($uri);
  if ($scheme) {
    $path = file_uri_target($uri);
  }
  else {
    $path = $uri;
828
    $scheme = file_default_scheme();
829
  }
830
  return $scheme . '://styles/' . $style_name . '/' . $scheme . '/' . $path;
831
832
833
}

/**
834
 * Pull in image effects exposed by modules implementing hook_image_effect_info().
835
836
 *
 * @return
837
 *   An array of image effects to be used when transforming images.
838
839
840
841
 * @see hook_image_effect_info()
 * @see image_effect_definition_load()
 */
function image_effect_definitions() {
842
  global $language_interface;
843
844
845

  // hook_image_effect_info() includes translated strings, so each language is
  // cached separately.
846
  $langcode = $language_interface->langcode;
847

848
849
850
  $effects = &drupal_static(__FUNCTION__);

  if (!isset($effects)) {
851
    if ($cache = cache()->get("image_effects:$langcode") && !empty($cache->data)) {
852
853
854
855
      $effects = $cache->data;
    }
    else {
      $effects = array();
856
      include_once DRUPAL_ROOT . '/core/modules/image/image.effects.inc';
857
858
859
860
861
862
863
      foreach (module_implements('image_effect_info') as $module) {
        foreach (module_invoke($module, 'image_effect_info') as $name => $effect) {
          // Ensure the current toolkit supports the effect.
          $effect['module'] = $module;
          $effect['name'] = $name;
          $effect['data'] = isset($effect['data']) ? $effect['data'] : array();
          $effects[$name] = $effect;
864
        }
865
866
      }
      uasort($effects, '_image_effect_definitions_sort');
867
      drupal_alter('image_effect_info', $effects);
868
      cache()->set("image_effects:$langcode", $effects);
869
870
871
872
873
874
875
    }
  }

  return $effects;
}

/**
876
 * Load the definition for an image effect.
877
 *
878
 * The effect definition is a set of core properties for an image effect, not
879
 * containing any user-settings. The definition defines various functions to
880
 * call when configuring or executing an image effect. This loader is mostly for
881
 * internal use within image.module. Use image_effect_load() or
882
 * image_style_load() to get image effects that contain configuration.
883
884
885
886
887
888
889
890
891
892
 *
 * @param $effect
 *   The name of the effect definition to load.
 * @return
 *   An array containing the image effect definition with the following keys:
 *   - "effect": The unique name for the effect being performed. Usually prefixed
 *     with the name of the module providing the effect.
 *   - "module": The module providing the effect.
 *   - "help": A description of the effect.
 *   - "function": The name of the function that will execute the effect.
893
 *   - "form": (optional) The name of a function to configure the effect.
894
895
896
 *   - "summary": (optional) The name of a theme function that will display a
 *     one-line summary of the effect. Does not include the "theme_" prefix.
 */
897
function image_effect_definition_load($effect) {
898
899
900
901
902
903
904
905
906
907
  $definitions = image_effect_definitions();
  return isset($definitions[$effect]) ? $definitions[$effect] : FALSE;
}

/**
 * Load all image effects from the database.
 *
 * @return
 *   An array of all image effects.
 * @see image_effect_load()
908
909
 *
 * @todo Remove after moving/resolving the todo.
910
911
912
913
914
915
916
917
 */
function image_effects() {
  $effects = &drupal_static(__FUNCTION__);

  if (!isset($effects)) {
    $effects = array();

    // Add database image effects.
918
919
920
    // @todo Strictly speaking, this is obsolete. However, it demonstrates a
    //   use-case for retrieving/listing configuration objects using a wildcard
    //   within the name (instead of only the suffix).
921
922
923
924
925
926
927
    $result = db_select('image_effects', NULL, array('fetch' => PDO::FETCH_ASSOC))
      ->fields('image_effects')
      ->orderBy('image_effects.weight', 'ASC')
      ->execute();
    foreach ($result as $effect) {
      $effect['data'] = unserialize($effect['data']);
      $definition = image_effect_definition_load($effect['name']);
928
      // Do not load image effects whose definition cannot be found.
929
930
931
932
933
934
935
936
937
938
939
940
941
      if ($definition) {
        $effect = array_merge($definition, $effect);
        $effects[$effect['ieid']] = $effect;
      }
    }
  }

  return $effects;
}

/**
 * Load a single image effect.
 *
942
943
 * @param $ieid
 *   The image effect ID.
944
945
 * @param $style_name
 *   The image style name.
946
 *
947
948
949
 * @return
 *   An image effect array, consisting of the following keys:
 *   - "ieid": The unique image effect ID.
950
951
952
 *   - "weight": The weight of this image effect within the image style.
 *   - "name": The name of the effect definition that powers this image effect.
 *   - "data": An array of configuration options for this image effect.
953
954
955
956
957
958
 *   Besides these keys, the entirety of the image definition is merged into
 *   the image effect array. Returns FALSE if the specified effect cannot be
 *   found.
 * @see image_style_load()
 * @see image_effect_definition_load()
 */
959
960
961
962
963
964
965
966
967
968
969
970
971
972
function image_effect_load($ieid, $style_name) {
  if (($style = image_style_load($style_name)) && isset($style['effects'][$ieid])) {
    $effect = $style['effects'][$ieid];
    $definition = image_effect_definition_load($effect['name']);
    $effect = array_merge($definition, $effect);
    // @todo The effect's key name within the style is unknown. It *should* be
    //   identical to the ieid, but that is in no way guaranteed. And of course,
    //   the ieid key *within* the effect is senseless duplication in the first
    //   place. This problem can be eliminated in many places, but especially
    //   for loaded menu arguments like %image_effect, the actual router
    //   callbacks don't have access to 'ieid' anymore (unless resorting to
    //   dirty %index and %map tricks).
    $effect['ieid'] = $ieid;
    return $effect;
973
974
  }
  return FALSE;
975
976
977
978
979
}

/**
 * Save an image effect.
 *
980
981
 * @param $style_name
 *   The image style this effect belongs to.
982
983
984
 * @param $effect
 *   An image effect array.
 * @return
985
 *   An image effect array. In the case of a new effect, 'ieid' will be set.
986
 */
987
function image_effect_save($style_name, $effect) {
988
  $config = config('image.style.' . $style_name);
gdd's avatar
gdd committed
989

gdd's avatar
gdd committed
990
  if (!isset($effect['ieid']) || empty($effect['ieid'])) {
gdd's avatar
gdd committed
991
992
    // We need to generate the ieid and save the new effect.
    // The machine name is all the elements of the data array concatenated
993
    // together, delimited by underscores.
994
    $effect['ieid'] = $effect['name'];
gdd's avatar
gdd committed
995
    foreach ($effect['data'] as $key => $value) {
996
      $effect['ieid'] .= '_' . $value;
gdd's avatar
gdd committed
997
    }
998
999
1000
    // @todo The machine name must not use any special non-alphanumeric
    //   characters, and may also not contain dots/periods, as that is the
    //   config system's nested key syntax.
For faster browsing, not all history is shown. View entire blame