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 22 23 24 25 26 27
        'default_image' => 0,
      ),
      'instance_settings' => array(
        'file_extensions' => 'png gif jpg jpeg',
        'file_directory' => '',
        'max_filesize' => '',
        'alt_field' => 0,
28
        'alt_field_required' => 0,
29
        'title_field' => 0,
30
        'title_field_required' => 0,
31 32
        'max_resolution' => '',
        'min_resolution' => '',
33
        'default_image' => 0,
34 35 36 37 38 39 40 41
      ),
      'default_widget' => 'image_image',
      'default_formatter' => 'image',
    ),
  );
}

/**
42
 * Implements hook_field_settings_form().
43 44 45 46 47 48
 */
function image_field_settings_form($field, $instance) {
  $defaults = field_info_field_settings($field['type']);
  $settings = array_merge($defaults, $field['settings']);

  $scheme_options = array();
49 50
  foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
    $scheme_options[$scheme] = $stream_wrapper['name'];
51 52 53 54 55 56 57 58 59
  }
  $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.'),
  );

60 61 62
  // 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.
63 64 65 66 67
  $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.'),
    '#default_value' => $field['settings']['default_image'],
68
    '#upload_location' => $settings['uri_scheme'] . '://default_images/',
69 70 71 72 73 74
  );

  return $form;
}

/**
75
 * Implements hook_field_instance_settings_form().
76 77 78 79 80 81 82 83 84 85
 */
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(
86
    '#type' => 'item',
87 88 89
    '#title' => t('Maximum image resolution'),
    '#element_validate' => array('_image_field_resolution_validate'),
    '#weight' => 4.1,
90 91
    '#field_prefix' => '<div class="container-inline">',
    '#field_suffix' => '</div>',
92
    '#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')),
93 94
  );
  $form['max_resolution']['x'] = array(
95
    '#type' => 'number',
96 97
    '#title' => t('Maximum width'),
    '#title_display' => 'invisible',
98
    '#default_value' => $max_resolution[0],
99
    '#min' => 1,
100 101 102
    '#field_suffix' => ' x ',
  );
  $form['max_resolution']['y'] = array(
103
    '#type' => 'number',
104 105
    '#title' => t('Maximum height'),
    '#title_display' => 'invisible',
106
    '#default_value' => $max_resolution[1],
107
    '#min' => 1,
108 109 110 111 112
    '#field_suffix' => ' ' . t('pixels'),
  );

  $min_resolution = explode('x', $settings['min_resolution']) + array('', '');
  $form['min_resolution'] = array(
113
    '#type' => 'item',
114 115 116
    '#title' => t('Minimum image resolution'),
    '#element_validate' => array('_image_field_resolution_validate'),
    '#weight' => 4.2,
117 118
    '#field_prefix' => '<div class="container-inline">',
    '#field_suffix' => '</div>',
119 120 121
    '#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(
122
    '#type' => 'number',
123 124
    '#title' => t('Minimum width'),
    '#title_display' => 'invisible',
125
    '#default_value' => $min_resolution[0],
126
    '#min' => 1,
127 128 129
    '#field_suffix' => ' x ',
  );
  $form['min_resolution']['y'] = array(
130
    '#type' => 'number',
131 132
    '#title' => t('Minimum height'),
    '#title_display' => 'invisible',
133
    '#default_value' => $min_resolution[1],
134
    '#min' => 1,
135 136 137 138 139 140 141 142 143 144 145 146
    '#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.'),
147 148 149 150 151 152
    '#weight' => 9,
  );
  $form['alt_field_required'] = array(
    '#type' => 'checkbox',
    '#title' => t('<em>Alt</em> field required'),
    '#default_value' => $settings['alt_field_required'],
153
    '#weight' => 10,
154 155 156 157 158
    '#states' => array(
      'visible' => array(
        ':input[name="instance[settings][alt_field]"]' => array('checked' => TRUE),
      ),
    ),
159 160 161 162 163 164 165 166
  );
  $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,
  );
167 168 169 170 171 172 173 174 175 176 177 178
  $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),
      ),
    ),
  );

179

180 181 182 183 184 185 186 187 188
  // 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."),
    '#default_value' => $settings['default_image'],
    '#upload_location' => $field['settings']['uri_scheme'] . '://default_images/',
  );

189 190 191 192 193 194 195 196 197
  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) {
198
      if (!$element[$dimension]['#value']) {
199 200 201 202
        form_error($element[$dimension], t('Both a height and width value must be specified in the !name field.', array('!name' => $element['#title'])));
        return;
      }
    }
203
    form_set_value($element, $element['x']['#value'] . 'x' . $element['y']['#value'], $form_state);
204 205 206 207 208 209 210
  }
  else {
    form_set_value($element, '', $form_state);
  }
}

/**
211
 * Implements hook_field_prepare_view().
212
 */
213
function image_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
214 215
  // Load the images.
  file_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, $items);
216
  // If there are no files specified at all, use the default.
217
  foreach ($entities as $id => $entity) {
218 219 220
    if (empty($items[$id])) {
      $fid = 0;
      // Use the default for the instance if one is available.
221
      if (!empty($instances[$id]['settings']['default_image'])) {
222 223 224
        $fid = $instances[$id]['settings']['default_image'];
      }
      // Otherwise, use the default for the field.
225
      elseif (!empty($field['settings']['default_image'])) {
226 227 228 229 230
        $fid = $field['settings']['default_image'];
      }

      // Add the default image if one is found.
      if ($fid && ($file = file_load($fid))) {
231 232 233 234 235 236
        $items[$id][0] = (array) $file + array(
          'is_default' => TRUE,
          'alt' => '',
          'title' => '',
        );
      }
237 238 239 240
    }
  }
}

241 242 243
/**
 * Implements hook_field_presave().
 */
244
function image_field_presave(EntityInterface $entity, $field, $instance, $langcode, &$items) {
245 246 247 248 249 250 251 252 253 254 255 256

  // Determine the dimensions if necessary.
  foreach ($items as &$item) {
    if (!isset($item['width']) || !isset($item['height'])) {
      $info = image_get_info(file_load($item['fid'])->uri);

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

259 260 261
/**
 * Implements hook_field_insert().
 */
262 263
function image_field_insert(EntityInterface $entity, $field, $instance, $langcode, &$items) {
  file_field_insert($entity, $field, $instance, $langcode, $items);
264 265
}

266
/**
267
 * Implements hook_field_update().
268
 */
269 270
function image_field_update(EntityInterface $entity, $field, $instance, $langcode, &$items) {
  file_field_update($entity, $field, $instance, $langcode, $items);
271 272 273
}

/**
274
 * Implements hook_field_delete().
275
 */
276 277
function image_field_delete(EntityInterface $entity, $field, $instance, $langcode, &$items) {
  file_field_delete($entity, $field, $instance, $langcode, $items);
278 279 280
}

/**
281
 * Implements hook_field_delete_revision().
282
 */
283 284
function image_field_delete_revision(EntityInterface $entity, $field, $instance, $langcode, &$items) {
  file_field_delete_revision($entity, $field, $instance, $langcode, $items);
285 286 287
}

/**
288
 * Implements hook_field_is_empty().
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
 */
function image_field_is_empty($item, $field) {
  return file_field_is_empty($item, $field);
}

/**
 * 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'];
  $item['fid'] = $element['fid']['#value'];

  $element['#theme'] = 'image_widget';
304
  $element['#attached']['css'][] = drupal_get_path('module', 'image') . '/image.theme.css';
305 306

  // Add the image preview.
307
  if ($element['#file'] && $element['#preview_image_style']) {
308
    $variables = array(
309
      'style_name' => $element['#preview_image_style'],
310
      'uri' => $element['#file']->uri,
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    );

    // Determine image dimensions.
    if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
      $variables['width'] = $element['#value']['width'];
      $variables['height'] = $element['#value']['height'];
    }
    else {
      $info = image_get_info($element['#file']->uri);

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

330 331
    $element['preview'] = array(
      '#type' => 'markup',
332 333 334 335 336 337 338 339 340 341 342 343
      '#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'],
344 345 346
    );
  }

347 348 349 350
  // Get field settings.
  $instance = field_widget_instance($element, $form_state);
  $settings = $instance['settings'];

351 352 353 354 355 356
  // 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.'),
357
    // @see http://www.gawds.org/show.php?contentid=28
358
    '#maxlength' => 512,
359
    '#weight' => -2,
360
    '#access' => (bool) $item['fid'] && $element['#alt_field'],
361
    '#element_validate' => $settings['alt_field_required'] == 1 ? array('_image_field_required_fields_validate') : array(),
362 363 364 365 366 367
  );
  $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.'),
368
    '#maxlength' => 1024,
369
    '#weight' => -1,
370
    '#access' => (bool) $item['fid'] && $element['#title_field'],
371
    '#element_validate' => $settings['alt_field_required'] == 1 ? array('_image_field_required_fields_validate') : array(),
372 373 374 375 376
  );

  return $element;
}

377 378 379 380 381 382 383 384 385 386 387 388 389
/**
 * 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);
390
    $image_field = NestedArray::getValue($form_state['input'], $parents);
391 392 393 394 395 396 397 398 399 400 401 402 403
    // 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;
    }
  }
}

404
/**
405 406
 * Returns HTML for an image field widget.
 *
407
 * @param array $variables
408 409 410 411
 *   An associative array containing:
 *   - element: A render element representing the image field widget.
 *
 * @ingroup themeable
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
 */
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">';
  if ($element['fid']['#value'] != 0) {
    $element['filename']['#markup'] .= ' <span class="file-size">(' . format_size($element['#file']->filesize) . ')</span> ';
  }
  $output .= drupal_render_children($element);
  $output .= '</div>';
  $output .= '</div>';

  return $output;
}

/**
436 437
 * Returns HTML for an image field formatter.
 *
438
 * @param array $variables
439 440 441
 *   An associative array containing:
 *   - item: An array of image data.
 *   - image_style: An optional image style.
442
 *   - path: An optional array containing the link 'path' and link 'options'.
443 444
 *
 * @ingroup themeable
445
 */
446 447
function theme_image_formatter($variables) {
  $item = $variables['item'];
448

449
  // Do not output an empty 'title' attribute.
450
  if (isset($item['title']) && drupal_strlen($item['title']) == 0) {
451
    unset($item['title']);
452
  }
453 454

  if ($variables['image_style']) {
455 456
    $item['style_name'] = $variables['image_style'];
    $output = theme('image_style', $item);
457 458
  }
  else {
459
    $output = theme('image', $item);
460 461
  }

462 463 464
  // 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'])) {
465
    $path = $variables['path']['path'];
466
    $options = isset($variables['path']['options']) ? $variables['path']['options'] : array();
467 468 469
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
    $output = l($output, $path, $options);
470 471 472
  }

  return $output;
473
}