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

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

8
9
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
10
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
11
use Drupal\Component\Uuid\Uuid;
12
use Drupal\file\File;
13
use Drupal\image\ImageStyle;
14

15
16
17
/**
 * Image style constant for user presets in the database.
 */
18
const IMAGE_STORAGE_NORMAL = 1;
19
20
21
22

/**
 * Image style constant for user presets that override module-defined presets.
 */
23
const IMAGE_STORAGE_OVERRIDE = 2;
24
25
26
27

/**
 * Image style constant for module-defined presets in code.
 */
28
const IMAGE_STORAGE_DEFAULT = 4;
29
30
31
32
33
34
35
36
37
38
39

/**
 * 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);

40
// Load all Field module hooks for Image.
41
require_once DRUPAL_ROOT . '/core/modules/image/image.field.inc';
42

43
/**
44
 * Implements hook_help().
45
46
47
48
49
 */
function image_help($path, $arg) {
  switch ($path) {
    case 'admin/help#image':
      $output = '';
50
      $output .= '<h3>' . t('About') . '</h3>';
51
      $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>';
52
53
54
55
56
57
      $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>';
58
      $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>';
59
60
      $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>';
61
      $output .= '</dl>';
62
      return $output;
63
    case 'admin/config/media/image-styles':
64
      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>';
65
    case 'admin/config/media/image-styles/edit/%/add/%':
66
67
      $effect = image_effect_definition_load($arg[7]);
      return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
68
    case 'admin/config/media/image-styles/edit/%/effects/%':
69
      $effect = ($arg[5] == 'add') ? image_effect_definition_load($arg[6]) : image_effect_load($arg[6], $arg[4]);
70
71
72
73
      return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
  }
}

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

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

  return $items;
}

/**
177
 * Implements hook_theme().
178
179
180
 */
function image_theme() {
  return array(
181
    // Theme functions in image.module.
182
    'image_style' => array(
183
      'variables' => array(
184
        'style_name' => NULL,
185
        'uri' => NULL,
186
187
        'width' => NULL,
        'height' => NULL,
188
        'alt' => '',
189
        'title' => NULL,
190
191
        'attributes' => array(),
      ),
192
    ),
193
194

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

    // Theme functions in image.field.inc.
    'image_widget' => array(
222
      'render element' => 'element',
223
    ),
224
225
    'image_formatter' => array(
      'variables' => array('item' => NULL, 'path' => NULL, 'image_style' => NULL),
226
    ),
227
228
229
230
  );
}

/**
231
 * Implements hook_permission().
232
233
234
235
236
237
238
 */
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.'),
    ),
239
240
241
  );
}

242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/**
 * 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']) {
257
    state()->set('menu_rebuild_needed', TRUE);
258
259
260
  }
}

261
/**
262
 * Implements hook_file_download().
263
264
265
 *
 * Control the access to files underneath the styles directory.
 */
266
267
268
269
270
271
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);
272
273
274
275
    // Discard the first part of the path (styles).
    array_shift($args);
    // Get the style name from the second part.
    $style_name = array_shift($args);
276
277
278
    // Remove the scheme from the path.
    array_shift($args);

279
    // Then the remaining parts are the path to the image.
280
    $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
281
282

    // Check that the file exists and is an image.
283
    if ($info = image_get_info($uri)) {
284
      // Check the permissions of the original to grant access to this image.
285
      $headers = module_invoke_all('file_download', $original_uri);
286
287
      if (!in_array(-1, $headers)) {
        return array(
288
          // Send headers describing the image's size, and MIME-type...
289
290
          'Content-Type' => $info['mime_type'],
          'Content-Length' => $info['file_size'],
291
292
293
          // By not explicitly setting them here, this uses normal Drupal
          // Expires, Cache-Control and ETag headers to prevent proxy or
          // browser caching of private images.
294
295
296
297
298
        );
      }
    }
    return -1;
  }
299
300
301
302

  // 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.
303
  $files = entity_load_multiple_by_properties('file', array('uri' => $uri));
304
305
306
307
308
309
  if (count($files)) {
    $file = reset($files);
    if ($file->status) {
      return file_file_download($uri, 'image');
    }
  }
310
311
312
}

/**
313
 * Implements hook_file_move().
314
 */
315
function image_file_move(File $file, File $source) {
316
  // Delete any image derivatives at the original image path.
317
  image_path_flush($source->uri);
318
319
320
}

/**
321
 * Implements hook_file_predelete().
322
 */
323
function image_file_predelete(File $file) {
324
  // Delete any image derivatives of this image.
325
  image_path_flush($file->uri);
326
327
}

328
329
330
331
/**
 * Implements hook_image_style_save().
 */
function image_image_style_save($style) {
332
  if ($style->id() != $style->getOriginalID()) {
333
334
335
336
337
338
339
    $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.
340
          if ($display['type'] == 'image' && $display['settings']['image_style'] == $style->getOriginalID()) {
341
342
            // Update display information for any instance using the image
            // style that was just deleted.
343
            $instance['display'][$view_mode]['settings']['image_style'] = $style->id();
344
            $instance_changed = TRUE;
345
346
          }
        }
347
348
        if ($instance['widget']['settings']['preview_image_style'] == $style->getOriginalID()) {
          $instance['widget']['settings']['preview_image_style'] = $style->id();
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
          $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);
364
365
  // Flush cached media for the style.
  image_style_flush($style);
366
367
}

368
369
370
371
372
373
374
375
376
377
378
/**
 * 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))) {
379
    file_usage()->delete($file, 'image', 'default_image', $field['id']);
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
  }
}

/**
 * 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;
402
      $file_new->save();
403
      file_usage()->add($file_new, 'image', 'default_image', $field['id']);
404
405
406
407
    }

    // Is there an old file?
    if ($fid_old && ($file_old = file_load($fid_old))) {
408
      file_usage()->delete($file_old, 'image', 'default_image', $field['id']);
409
410
411
412
413
414
415
    }
  }

  // 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);
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
    file_move($file_new, $directory . $file_new->filename);
  }
}

/**
 * Implements hook_field_delete_instance().
 */
function image_field_delete_instance($instance) {
  // Only act on image fields.
  $field = field_read_field($instance['field_name']);
  if ($field['type'] != 'image') {
    return;
  }

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

  // Remove the default image when the instance is deleted.
  if ($fid && ($file = file_load($fid))) {
439
    file_usage()->delete($file, 'image', 'default_image', $instance['id']);
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
  }
}

/**
 * Implements hook_field_update_instance().
 */
function image_field_update_instance($instance, $prior_instance) {
  // Only act on image fields.
  $field = field_read_field($instance['field_name']);
  if ($field['type'] != 'image') {
    return;
  }

  // The value of a managed_file element can be an array if the #extended
  // property is set to TRUE.
  $fid_new = $instance['settings']['default_image'];
  if (is_array($fid_new)) {
    $fid_new = $fid_new['fid'];
  }
  $fid_old = $prior_instance['settings']['default_image'];
  if (is_array($fid_old)) {
    $fid_old = $fid_old['fid'];
  }

  // If the old and new files do not match, update the default accordingly.
  $file_new = $fid_new ? file_load($fid_new) : FALSE;
  if ($fid_new != $fid_old) {
    // Save the new file, if present.
    if ($file_new) {
      $file_new->status = FILE_STATUS_PERMANENT;
470
      $file_new->save();
471
      file_usage()->add($file_new, 'image', 'default_image', $instance['id']);
472
473
474
    }
    // Delete the old file, if present.
    if ($fid_old && ($file_old = file_load($fid_old))) {
475
      file_usage()->delete($file_old, 'image', 'default_image', $instance['id']);
476
477
478
479
480
481
482
    }
  }

  // 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);
483
484
485
486
    file_move($file_new, $directory . $file_new->filename);
  }
}

487
488
489
490
491
492
493
/**
 * 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) {
494
  $styles = entity_load_multiple('image_style');
495
  foreach ($styles as $style) {
496
    $image_path = image_style_path($style->id(), $path);
497
498
    if (file_exists($image_path)) {
      file_unmanaged_delete($image_path);
499
500
501
502
    }
  }
}

503
/**
504
 * Implements hook_config_import_create().
505
506
507
508
509
510
511
 */
function image_config_import_create($name, $new_config, $old_config) {
  // Only image styles require custom handling. Any other module settings can be
  // synchronized directly.
  if (strpos($name, 'image.style.') !== 0) {
    return FALSE;
  }
512
513
514
  $style = entity_create('image_style', $new_config->get());
  $style->save();
  return TRUE;
515
516
517
}

/**
518
 * Implements hook_config_import_change().
519
520
521
522
523
524
525
 */
function image_config_import_change($name, $new_config, $old_config) {
  // Only image styles require custom handling. Any other module settings can be
  // synchronized directly.
  if (strpos($name, 'image.style.') !== 0) {
    return FALSE;
  }
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540

  list(, , $id) = explode('.', $name);
  $style = entity_load('image_style', $id);

  $style->original = clone $style;
  foreach ($old_config->get() as $property => $value) {
    $style->original->$property = $value;
  }

  foreach ($new_config->get() as $property => $value) {
    $style->$property = $value;
  }

  $style->save();
  return TRUE;
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
}

/**
 * Implements MODULE_config_import_delete().
 */
function image_config_import_delete($name, $new_config, $old_config) {
  // Only image styles require custom handling. Any other module settings can be
  // synchronized directly.
  if (strpos($name, 'image.style.') !== 0) {
    return FALSE;
  }
  // @todo image_style_delete() supports the notion of a "replacement style"
  //   to be used by other modules instead of the deleted style. Essential!
  //   But that is impossible currently, since the config system only knows
  //   about deleted and added changes. Introduce an 'old_ID' key within
  //   config objects as a standard?
557
558
  list(, , $id) = explode('.', $name);
  $style = entity_load('image_style', $id);
559
560
561
  return image_style_delete($style);
}

562
/**
563
 * Loads an ImageStyle object.
564
 *
565
566
 * @param string $name
 *   The ID of the ImageStyle object to load.
567
 */
568
569
function image_style_load($name) {
  return entity_load('image_style', $name);
570
571
572
}

/**
573
 * Implements hook_image_style_load.
574
 */
575
576
577
578
579
580
581
582
583
584
function image_image_style_load($styles) {
  foreach ($styles as $style) {
    if (!empty($style->effects)) {
      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');
585
    }
586
  }
587
588
589
}

/**
590
 * Implements hook_image_style_update().
591
 */
592
593
function image_image_style_update($style) {
  // Flush cached media for the style.
594
595
596
597
598
599
  image_style_flush($style);
}

/**
 * Delete an image style.
 *
600
 * @param Drupal\image\ImageStyle $style
601
602
603
604
 *   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.
605
 *
606
607
608
609
 * @return
 *   TRUE on success.
 */
function image_style_delete($style, $replacement_style_name = '') {
610
  $style->delete();
611
612

  // Let other modules update as necessary on save.
613
614
615
  if ($replacement_style_name) {
    $style->set('name', $replacement_style_name);
  }
616
617
618
619
620
621
622
623
624
625
626
627
628
629
  module_invoke_all('image_style_delete', $style);

  return TRUE;
}

/**
 * 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) {
630
  $styles = entity_load_multiple('image_style');
631
632
633
634
  $options = array();
  if ($include_empty && !empty($styles)) {
    $options[''] = t('<none>');
  }
635
  foreach ($styles as $name => $style) {
636
    $options[$name] = $style->label();
637
638
  }

639
640
641
642
643
644
645
646
647
  if (empty($options)) {
    $options[''] = t('No defined styles');
  }
  return $options;
}

/**
 * Menu callback; Given a style and image path, generate a derivative.
 *
648
 * After generating an image, transfer it to the requesting agent.
649
 *
650
651
 * @param $style
 *   The image style
652
 */
653
654
655
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)) {
656
    drupal_exit();
657
  }
658

659
660
661
662
663
664
  $args = func_get_args();
  array_shift($args);
  array_shift($args);
  $target = implode('/', $args);

  $image_uri = $scheme . '://' . $target;
665
  $derivative_uri = image_style_path($style->id(), $image_uri);
666
667

  // If using the private scheme, let other modules provide headers and
668
669
670
671
672
673
674
675
  // 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)) {
676
        throw new AccessDeniedHttpException();
677
678
679
680
681
682
683
684
      }
      if (count($headers)) {
        foreach ($headers as $name => $value) {
          drupal_add_http_header($name, $value);
        }
      }
    }
  }
685

686
687
688
689
690
691
  // Don't try to generate file if source is missing.
  if (!file_exists($image_uri)) {
    watchdog('image', 'Unable to generate the derived image from image at %path.', array('%path' => $derivative_uri));
    return new Response(t('Error generating image, missing source file.'), 404);
  }

692
  // Don't start generating the image if the derivative already exists or if
693
  // generation is in progress in another thread.
694
  $lock_name = 'image_style_deliver:' . $style->id() . ':' . drupal_hash_base64($image_uri);
695
  if (!file_exists($derivative_uri)) {
696
    $lock_acquired = lock()->acquire($lock_name);
697
698
699
    if (!$lock_acquired) {
      // Tell client to retry again in 3 seconds. Currently no browsers are known
      // to support Retry-After.
700
      drupal_add_http_header('Status', '503 Service Unavailable');
701
      drupal_add_http_header('Retry-After', 3);
702
      print t('Image generation in progress. Try again shortly.');
703
      drupal_exit();
704
    }
705
706
  }

707
708
  // Try to generate the image, unless another thread just did it while we were
  // acquiring the lock.
709
  $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
710

711
  if (!empty($lock_acquired)) {
712
    lock()->release($lock_name);
713
  }
714

715
  if ($success) {
716
    $image = image_load($derivative_uri);
717
718
719
720
721
    $uri = $image->source;
    $headers = array(
      'Content-Type' => $image->info['mime_type'],
      'Content-Length' => $image->info['file_size'],
    );
722
    return file_transfer($uri, $headers);
723
724
  }
  else {
725
    watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
726
    return new Response(t('Error generating image.'), 500);
727
728
729
730
  }
}

/**
731
732
733
 * Creates a new image derivative based on an image style.
 *
 * Generates an image derivative by creating the destination folder (if it does
734
 * not already exist), applying all image effects defined in $style->effects,
735
 * and saving a cached version of the resulting image.
736
737
738
739
740
741
 *
 * @param $style
 *   An image style array.
 * @param $source
 *   Path of the source file.
 * @param $destination
742
 *   Path or URI of the destination file.
743
 *
744
 * @return
745
746
747
748
 *   TRUE if an image derivative was generated, or FALSE if the image derivative
 *   could not be generated.
 *
 * @see image_style_load()
749
750
751
 */
function image_style_create_derivative($style, $source, $destination) {
  // Get the folder for the final location of this style.
752
  $directory = drupal_dirname($destination);
753
754

  // Build the destination folder tree if it doesn't already exist.
755
  if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
756
    watchdog('image', 'Failed to create style directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
757
758
759
760
761
762
763
    return FALSE;
  }

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

764
765
  if (!empty($style->effects)) {
    foreach ($style->effects as $effect) {
766
767
      image_effect_apply($image, $effect);
    }
768
769
770
771
  }

  if (!image_save($image, $destination)) {
    if (file_exists($destination)) {
772
      watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $destination), WATCHDOG_ERROR);
773
774
775
776
777
778
779
    }
    return FALSE;
  }

  return TRUE;
}

780
781
782
783
784
785
786
787
788
789
790
791
792
/**
 * 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');
793
  $style = entity_load('image_style', $style_name);
794

795
796
  if (!empty($style->effects)) {
    foreach ($style->effects as $effect) {
797
798
799
      if (isset($effect['dimensions passthrough'])) {
        continue;
      }
800

801
802
803
804
805
806
      if (isset($effect['dimensions callback'])) {
        $effect['dimensions callback']($dimensions, $effect['data']);
      }
      else {
        $dimensions['width'] = $dimensions['height'] = NULL;
      }
807
808
809
810
    }
  }
}

811
812
813
814
815
816
817
/**
 * Flush cached media for a style.
 *
 * @param $style
 *   An image style array.
 */
function image_style_flush($style) {
818
  $style_directory = drupal_realpath(file_default_scheme() . '://styles/' . $style->id());
819
820
821
822
823
824
825
  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);

826
827
828
829
830
//  // Clear image style and effect caches.
//  cache()->delete('image_styles');
//  cache()->deletePrefix('image_effects:');
//  drupal_static_reset('image_styles');
//  drupal_static_reset('image_effects');
831

832
833
834
835
  // Clear field caches so that formatters may be added for this style.
  field_info_cache_clear();
  drupal_theme_rebuild();

836
837
  // Clear page caches when flushing.
  if (module_exists('block')) {
838
    cache('block')->flush();
839
  }
840
  cache('page')->flush();
841
842
843
844
845
846
847
}

/**
 * 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.
848
 * @param $path
849
850
851
852
 *   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.
853
 * @see image_style_deliver()
854
 */
855
856
function image_style_url($style_name, $path) {
  $uri = image_style_path($style_name, $path);
857
858

  // If not using clean URLs, the image derivative callback is only available
859
  // with the script path. If the file does not exist, use url() to ensure
860
861
  // 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.
862
  if ($GLOBALS['script_path'] && file_uri_scheme($uri) == 'public' && !file_exists($uri)) {
863
864
    $directory_path = file_stream_wrapper_get_instance_by_uri($uri)->getDirectoryPath();
    return url($directory_path . '/' . file_uri_target($uri), array('absolute' => TRUE));
865
  }
866
867

  return file_create_url($uri);
868
869
870
}

/**
871
 * Return the URI of an image when using a style.
872
873
874
875
876
877
 *
 * 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.
878
879
 * @param $uri
 *   The URI or path to the image.
880
 * @return
881
 *   The URI to an image style image.
882
883
 * @see image_style_url()
 */
884
function image_style_path($style_name, $uri) {
885
886
887
888
889
890
  $scheme = file_uri_scheme($uri);
  if ($scheme) {
    $path = file_uri_target($uri);
  }
  else {
    $path = $uri;
891
    $scheme = file_default_scheme();
892
  }
893
  return $scheme . '://styles/' . $style_name . '/' . $scheme . '/' . $path;
894
895
896
}

/**
897
 * Pull in image effects exposed by modules implementing hook_image_effect_info().
898
899
 *
 * @return
900
 *   An array of image effects to be used when transforming images.
901
902
903
904
 * @see hook_image_effect_info()
 * @see image_effect_definition_load()
 */
function image_effect_definitions() {
905
  $language_interface = language(LANGUAGE_TYPE_INTERFACE);
906
907
908

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

911
912
913
  $effects = &drupal_static(__FUNCTION__);

  if (!isset($effects)) {
914
    if ($cache = cache()->get("image_effects:$langcode")) {
915
916
917
918
      $effects = $cache->data;
    }
    else {
      $effects = array();
919
      include_once DRUPAL_ROOT . '/core/modules/image/image.effects.inc';
920
921
922
923
924
925
926
      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;
927
        }
928
929
      }
      uasort($effects, '_image_effect_definitions_sort');
930
      drupal_alter('image_effect_info', $effects);
931
      cache()->set("image_effects:$langcode", $effects);
932
933
934
935
936
937
938
    }
  }

  return $effects;
}

/**
939
 * Load the definition for an image effect.
940
 *
941
 * The effect definition is a set of core properties for an image effect, not
942
 * containing any user-settings. The definition defines various functions to
943
 * call when configuring or executing an image effect. This loader is mostly for
944
 * internal use within image.module. Use image_effect_load() or
945
 * entity_load() to get image effects that contain configuration.
946
947
948
949
950
951
952
953
954
955
 *
 * @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.
956
 *   - "form": (optional) The name of a function to configure the effect.
957
958
959
 *   - "summary": (optional) The name of a theme function that will display a
 *     one-line summary of the effect. Does not include the "theme_" prefix.
 */
960
function image_effect_definition_load($effect) {
961
962
963
964
965
966
967
968
969
970
  $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()
971
972
 *
 * @todo Remove after moving/resolving the todo.
973
974
975
976
977
978
979
980
 */
function image_effects() {
  $effects = &drupal_static(__FUNCTION__);

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

    // Add database image effects.
981
982
983
    // @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).
984
985
986
987
988
989
990
    $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']);
991
      // Do not load image effects whose definition cannot be found.
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
      if ($definition) {
        $effect = array_merge($definition, $effect);
        $effects[$effect['ieid']] = $effect;
      }
    }
  }

  return $effects;
}

/**
 * Load a single image effect.
 *
1005
1006
 * @param $ieid
 *   The image effect ID.
1007
1008
 * @param $style_name
 *   The image style name.
1009
 *
1010
1011
1012
 * @return
 *   An image effect array, consisting of the following keys:
 *   - "ieid": The unique image effect ID.
1013
1014
1015
 *   - "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.
1016
1017
1018
1019
1020
 *   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_effect_definition_load()
 */
1021
function image_effect_load($ieid, $style_name) {
1022
1023
  if (($style = entity_load('image_style', $style_name)) && isset($style->effects[$ieid])) {
    $effect = $style->effects[$ieid];
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
    $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;
1035
1036
  }
  return FALSE;
1037
1038
1039
1040
1041
}

/**
 * Save an image effect.
 *
1042
 * @param ImageStyle $style
1043
 *   The image style this effect belongs to.
1044
1045
1046
1047
1048
 * @param array $effect
 *   An image effect array. Passed by reference.
 *
 * @return array
 *   The saved image effect array. The 'ieid' key will be set for the effect.
1049
 */
1050
function image_effect_save($style, &$effect) {
1051
1052
1053
1054
  // Generate a unique image effect ID for a new effect.
  if (empty($effect['ieid'])) {
    $uuid = new Uuid();
    $effect['ieid'] = $uuid->generate();
1055
  }
1056
1057
  $style->effects[$effect['ieid']] = $effect;
  $style->save();
1058
1059
1060

  // Flush all derivatives that exist for this style, so they are regenerated
  // with the new or updated effect.
1061
1062
1063
1064
1065
1066
  image_style_flush($style);
}

/**
 * Delete an image effect.
 *
1067
 * @param ImageStyle $style
1068
 *   The image style this effect belongs to.
1069
1070
1071
 * @param $effect
 *   An image effect array.
 */
1072
function image_effect_delete($style, $effect) {
1073
  unset($style->effects[$effect['ieid']]);
1074
  $style->save();
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
  image_style_flush($style);
}

/**
 * Given an image object and effect, perform the effect on the file.
 *
 * @param $image
 *   An image object returned by image_load().
 * @param $effect
 *   An image effect array.
 * @return
1086
 *   TRUE on success. FALSE if unable to perform the image effect on the image.
1087
 */
1088
function image_effect_apply($image, $effect) {
1089
  module_load_include('inc', 'image', 'image.effects');
1090
  $function = $effect['effect callback'];
1091
  return $function($image, $effect['data']);
1092
1093
1094
}

/**
1095
 * Returns HTML for an image using a specific image style.
1096
 *
1097
1098
1099
 * @param $variables
 *   An associative array containing:
 *   - style_name: The name of the style to be used to alter the original image.