image.field.inc 15.7 KB
Newer Older
1
2
3
4
5
6
7
<?php

/**
 * @file
 * Implement an image field, based on the file module's file field.
 */

8
use Drupal\Component\Utility\NestedArray;
9
use Drupal\Core\Entity\EntityInterface;
10

11
/**
12
 * Implements hook_field_info().
13
14
15
16
17
18
19
 */
function image_field_info() {
  return array(
    'image' => array(
      'label' => t('Image'),
      'description' => t('This field stores the ID of an image file as an integer value.'),
      'settings' => array(
20
        'uri_scheme' => file_default_scheme(),
21
        'default_image' => 0,
22
23
24
        'column_groups' => array(
          'file' => array(
            'label' => t('File'),
25
            'columns' => array('target_id', 'width', 'height'),
26
27
28
29
30
31
32
33
34
35
          ),
          'alt' => array(
            'label' => t('Alt'),
            'translatable' => TRUE,
          ),
          'title' => array(
            'label' => t('Title'),
            'translatable' => TRUE,
          ),
        ),
36
37
38
39
40
41
      ),
      'instance_settings' => array(
        'file_extensions' => 'png gif jpg jpeg',
        'file_directory' => '',
        'max_filesize' => '',
        'alt_field' => 0,
42
        'alt_field_required' => 0,
43
        'title_field' => 0,
44
        'title_field_required' => 0,
45
46
        'max_resolution' => '',
        'min_resolution' => '',
47
        'default_image' => 0,
48
49
50
      ),
      'default_widget' => 'image_image',
      'default_formatter' => 'image',
51
      'class' => '\Drupal\image\Type\ImageItem',
52
53
54
55
56
    ),
  );
}

/**
57
 * Implements hook_field_settings_form().
58
59
 */
function image_field_settings_form($field, $instance) {
60
  $defaults = \Drupal::service('plugin.manager.entity.field.field_type')->getDefaultSettings($field['type']);
61
62
63
  $settings = array_merge($defaults, $field['settings']);

  $scheme_options = array();
64
65
  foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
    $scheme_options[$scheme] = $stream_wrapper['name'];
66
67
68
69
70
71
72
73
74
  }
  $form['uri_scheme'] = array(
    '#type' => 'radios',
    '#title' => t('Upload destination'),
    '#options' => $scheme_options,
    '#default_value' => $settings['uri_scheme'],
    '#description' => t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
  );

75
76
77
  // When the user sets the scheme on the UI, even for the first time, it's
  // updating a field because fields are created on the "Manage fields"
  // page. So image_field_update_field() can handle this change.
78
79
80
81
  $form['default_image'] = array(
    '#title' => t('Default image'),
    '#type' => 'managed_file',
    '#description' => t('If no image is uploaded, this image will be shown on display.'),
82
    '#default_value' => empty($field['settings']['default_image']) ? array() : array($field['settings']['default_image']),
83
    '#upload_location' => $settings['uri_scheme'] . '://default_images/',
84
85
86
87
88
89
  );

  return $form;
}

/**
90
 * Implements hook_field_instance_settings_form().
91
92
93
94
95
96
97
98
99
100
 */
function image_field_instance_settings_form($field, $instance) {
  $settings = $instance['settings'];

  // Use the file field instance settings form as a basis.
  $form = file_field_instance_settings_form($field, $instance);

  // Add maximum and minimum resolution settings.
  $max_resolution = explode('x', $settings['max_resolution']) + array('', '');
  $form['max_resolution'] = array(
101
    '#type' => 'item',
102
103
104
    '#title' => t('Maximum image resolution'),
    '#element_validate' => array('_image_field_resolution_validate'),
    '#weight' => 4.1,
105
106
    '#field_prefix' => '<div class="container-inline">',
    '#field_suffix' => '</div>',
107
    '#description' => t('The maximum allowed image size expressed as WIDTHxHEIGHT (e.g. 640x480). Leave blank for no restriction. If a larger image is uploaded, it will be resized to reflect the given width and height. Resizing images on upload will cause the loss of <a href="@url">EXIF data</a> in the image.', array('@url' => 'http://en.wikipedia.org/wiki/Exchangeable_image_file_format')),
108
109
  );
  $form['max_resolution']['x'] = array(
110
    '#type' => 'number',
111
112
    '#title' => t('Maximum width'),
    '#title_display' => 'invisible',
113
    '#default_value' => $max_resolution[0],
114
    '#min' => 1,
115
116
117
    '#field_suffix' => ' x ',
  );
  $form['max_resolution']['y'] = array(
118
    '#type' => 'number',
119
120
    '#title' => t('Maximum height'),
    '#title_display' => 'invisible',
121
    '#default_value' => $max_resolution[1],
122
    '#min' => 1,
123
124
125
126
127
    '#field_suffix' => ' ' . t('pixels'),
  );

  $min_resolution = explode('x', $settings['min_resolution']) + array('', '');
  $form['min_resolution'] = array(
128
    '#type' => 'item',
129
130
131
    '#title' => t('Minimum image resolution'),
    '#element_validate' => array('_image_field_resolution_validate'),
    '#weight' => 4.2,
132
133
    '#field_prefix' => '<div class="container-inline">',
    '#field_suffix' => '</div>',
134
135
136
    '#description' => t('The minimum allowed image size expressed as WIDTHxHEIGHT (e.g. 640x480). Leave blank for no restriction. If a smaller image is uploaded, it will be rejected.'),
  );
  $form['min_resolution']['x'] = array(
137
    '#type' => 'number',
138
139
    '#title' => t('Minimum width'),
    '#title_display' => 'invisible',
140
    '#default_value' => $min_resolution[0],
141
    '#min' => 1,
142
143
144
    '#field_suffix' => ' x ',
  );
  $form['min_resolution']['y'] = array(
145
    '#type' => 'number',
146
147
    '#title' => t('Minimum height'),
    '#title_display' => 'invisible',
148
    '#default_value' => $min_resolution[1],
149
    '#min' => 1,
150
151
152
153
154
155
156
157
158
159
160
161
    '#field_suffix' => ' ' . t('pixels'),
  );

  // Remove the description option.
  unset($form['description_field']);

  // Add title and alt configuration options.
  $form['alt_field'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable <em>Alt</em> field'),
    '#default_value' => $settings['alt_field'],
    '#description' => t('The alt attribute may be used by search engines, screen readers, and when the image cannot be loaded.'),
162
163
164
165
166
167
    '#weight' => 9,
  );
  $form['alt_field_required'] = array(
    '#type' => 'checkbox',
    '#title' => t('<em>Alt</em> field required'),
    '#default_value' => $settings['alt_field_required'],
168
    '#weight' => 10,
169
170
171
172
173
    '#states' => array(
      'visible' => array(
        ':input[name="instance[settings][alt_field]"]' => array('checked' => TRUE),
      ),
    ),
174
175
176
177
178
179
180
181
  );
  $form['title_field'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable <em>Title</em> field'),
    '#default_value' => $settings['title_field'],
    '#description' => t('The title attribute is used as a tooltip when the mouse hovers over the image.'),
    '#weight' => 11,
  );
182
183
184
185
186
187
188
189
190
191
192
193
  $form['title_field_required'] = array(
    '#type' => 'checkbox',
    '#title' => t('<em>Title</em> field required'),
    '#default_value' => $settings['title_field_required'],
    '#weight' => 12,
    '#states' => array(
      'visible' => array(
        ':input[name="instance[settings][title_field]"]' => array('checked' => TRUE),
      ),
    ),
  );

194

195
196
197
198
199
  // Add the default image to the instance.
  $form['default_image'] = array(
    '#title' => t('Default image'),
    '#type' => 'managed_file',
    '#description' => t("If no image is uploaded, this image will be shown on display and will override the field's default image."),
200
    '#default_value' => empty($settings['default_image']) ? array() : array($settings['default_image']),
201
202
203
    '#upload_location' => $field['settings']['uri_scheme'] . '://default_images/',
  );

204
205
206
207
208
209
210
211
212
  return $form;
}

/**
 * Element validate function for resolution fields.
 */
function _image_field_resolution_validate($element, &$form_state) {
  if (!empty($element['x']['#value']) || !empty($element['y']['#value'])) {
    foreach (array('x', 'y') as $dimension) {
213
      if (!$element[$dimension]['#value']) {
214
215
216
217
        form_error($element[$dimension], t('Both a height and width value must be specified in the !name field.', array('!name' => $element['#title'])));
        return;
      }
    }
218
    form_set_value($element, $element['x']['#value'] . 'x' . $element['y']['#value'], $form_state);
219
220
221
222
223
224
  }
  else {
    form_set_value($element, '', $form_state);
  }
}

225
226
227
/**
 * Implements hook_field_presave().
 */
228
function image_field_presave(EntityInterface $entity, $field, $instance, $langcode, &$items) {
229
230
231
232

  // Determine the dimensions if necessary.
  foreach ($items as &$item) {
    if (!isset($item['width']) || !isset($item['height'])) {
233
      $info = image_get_info(file_load($item['target_id'])->getFileUri());
234
235
236
237
238
239
240

      if (is_array($info)) {
        $item['width'] = $info['width'];
        $item['height'] = $info['height'];
      }
    }
  }
241
242
}

243
244
245
/**
 * Implements hook_field_insert().
 */
246
247
function image_field_insert(EntityInterface $entity, $field, $instance, $langcode, &$items) {
  file_field_insert($entity, $field, $instance, $langcode, $items);
248
249
}

250
/**
251
 * Implements hook_field_update().
252
 */
253
254
function image_field_update(EntityInterface $entity, $field, $instance, $langcode, &$items) {
  file_field_update($entity, $field, $instance, $langcode, $items);
255
256
257
}

/**
258
 * Implements hook_field_delete().
259
 */
260
261
function image_field_delete(EntityInterface $entity, $field, $instance, $langcode, &$items) {
  file_field_delete($entity, $field, $instance, $langcode, $items);
262
263
264
}

/**
265
 * Implements hook_field_delete_revision().
266
 */
267
268
function image_field_delete_revision(EntityInterface $entity, $field, $instance, $langcode, &$items) {
  file_field_delete_revision($entity, $field, $instance, $langcode, $items);
269
270
271
}

/**
272
 * Implements hook_field_is_empty().
273
 */
274
275
function image_field_is_empty($item, $field_type) {
  return file_field_is_empty($item, $field_type);
276
277
278
279
280
281
282
283
284
}

/**
 * An element #process callback for the image_image field type.
 *
 * Expands the image_image type to include the alt and title fields.
 */
function image_field_widget_process($element, &$form_state, $form) {
  $item = $element['#value'];
285
  $item['fids'] = $element['fids']['#value'];
286
287

  $element['#theme'] = 'image_widget';
288
  $element['#attached']['css'][] = drupal_get_path('module', 'image') . '/css/image.theme.css';
289
290

  // Add the image preview.
291
292
  if (!empty($element['#files']) && $element['#preview_image_style']) {
    $file = reset($element['#files']);
293
    $variables = array(
294
      'style_name' => $element['#preview_image_style'],
295
      'uri' => $file->getFileUri(),
296
297
298
299
300
301
302
303
    );

    // Determine image dimensions.
    if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
      $variables['width'] = $element['#value']['width'];
      $variables['height'] = $element['#value']['height'];
    }
    else {
304
      $info = image_get_info($file->getFileUri());
305
306
307
308
309
310
311
312
313
314

      if (is_array($info)) {
        $variables['width'] = $info['width'];
        $variables['height'] = $info['height'];
      }
      else {
        $variables['width'] = $variables['height'] = NULL;
      }
    }

315
    $element['preview'] = array(
316
317
318
319
320
321
322
323
324
325
326
327
      '#markup' => theme('image_style', $variables),
    );

    // Store the dimensions in the form so the file doesn't have to be accessed
    // again. This is important for remote files.
    $element['width'] = array(
      '#type' => 'hidden',
      '#value' => $variables['width'],
    );
    $element['height'] = array(
      '#type' => 'hidden',
      '#value' => $variables['height'],
328
329
330
331
332
333
334
335
336
    );
  }

  // Add the additional alt and title fields.
  $element['alt'] = array(
    '#title' => t('Alternate text'),
    '#type' => 'textfield',
    '#default_value' => isset($item['alt']) ? $item['alt'] : '',
    '#description' => t('This text will be used by screen readers, search engines, or when the image cannot be loaded.'),
337
    // @see http://www.gawds.org/show.php?contentid=28
338
    '#maxlength' => 512,
339
    '#weight' => -2,
340
    '#access' => (bool) $item['fids'] && $element['#alt_field'],
341
    '#element_validate' => $element['#alt_field_required'] == 1 ? array('_image_field_required_fields_validate') : array(),
342
343
344
345
346
347
  );
  $element['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#default_value' => isset($item['title']) ? $item['title'] : '',
    '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'),
348
    '#maxlength' => 1024,
349
    '#weight' => -1,
350
    '#access' => (bool) $item['fids'] && $element['#title_field'],
351
    '#element_validate' => $element['#alt_field_required'] == 1 ? array('_image_field_required_fields_validate') : array(),
352
353
354
355
356
  );

  return $element;
}

357
358
359
360
361
362
363
364
365
366
367
368
369
/**
 * Validate callback for alt and title field, if the user wants them required.
 *
 * This is separated in a validate function instead of a #required flag to avoid
 * being validated on the process callback.
 */
function _image_field_required_fields_validate($element, &$form_state) {
  // Only do validation if the function is triggered from other places than
  // the image process form.
  if (!in_array('file_managed_file_submit', $form_state['triggering_element']['#submit'])) {
    // If the image is not there, we do not check for empty values.
    $parents = $element['#parents'];
    $field = array_pop($parents);
370
    $image_field = NestedArray::getValue($form_state['input'], $parents);
371
372
373
374
375
376
377
378
379
380
381
382
383
    // We check for the array key, so that it can be NULL (like if the user
    // submits the form without using the "upload" button).
    if (!array_key_exists($field, $image_field)) {
      return;
    }
    // Check if field is left emtpy.
    elseif (empty($image_field[$field])) {
      form_error($element, t('The field !title is required', array('!title' => $element['#title'])));
      return;
    }
  }
}

384
/**
385
386
 * Returns HTML for an image field widget.
 *
387
 * @param array $variables
388
389
390
391
 *   An associative array containing:
 *   - element: A render element representing the image field widget.
 *
 * @ingroup themeable
392
393
394
395
396
397
398
399
400
401
402
403
404
 */
function theme_image_widget($variables) {
  $element = $variables['element'];
  $output = '';
  $output .= '<div class="image-widget form-managed-file clearfix">';

  if (isset($element['preview'])) {
    $output .= '<div class="image-preview">';
    $output .= drupal_render($element['preview']);
    $output .= '</div>';
  }

  $output .= '<div class="image-widget-data">';
405
406
  if (!empty($element['fids']['#value'])) {
    $file = reset($element['#files']);
407
    $element['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
408
409
410
411
412
413
414
415
416
  }
  $output .= drupal_render_children($element);
  $output .= '</div>';
  $output .= '</div>';

  return $output;
}

/**
417
418
 * Returns HTML for an image field formatter.
 *
419
 * @param array $variables
420
421
422
 *   An associative array containing:
 *   - item: An array of image data.
 *   - image_style: An optional image style.
423
 *   - path: An optional array containing the link 'path' and link 'options'.
424
425
 *
 * @ingroup themeable
426
 */
427
428
function theme_image_formatter($variables) {
  $item = $variables['item'];
429
  $image = array();
430

431
  // Do not output an empty 'title' attribute.
432
433
  if (isset($item['title']) && drupal_strlen($item['title']) != 0) {
    $image['#title'] = $item['title'];
434
  }
435

436
  if (isset($item['entity']) && empty($item['uri'])) {
437
438
439
440
441
442
443
    $image['#uri'] = $item['entity']->getFileUri();
  }
  else {
    $image['#uri'] = $item['uri'];
  }

  foreach (array('width', 'height', 'alt', 'attributes') as $key) {
444
    if (isset($item[$key]) || array_key_exists($key, $item)) {
445
446
      $image["#$key"] = $item[$key];
    }
447
448
  }

449
  if ($variables['image_style']) {
450
451
    $image['#theme'] = 'image_style';
    $image['#style_name'] = $variables['image_style'];
452
453
  }
  else {
454
    $image['#theme'] = 'image';
455
456
  }

457
458
459
  // The link path and link options are both optional, but for the options to be
  // processed, the link path must at least be an empty string.
  if (isset($variables['path']['path'])) {
460
    $path = $variables['path']['path'];
461
    $options = isset($variables['path']['options']) ? $variables['path']['options'] : array();
462
463
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
464
465
466
467
    $output = l($image, $path, $options);
  }
  else {
    $output = drupal_render($image);
468
469
470
  }

  return $output;
471
}