Project

General

Profile

Revision 1f142f4f

Added by Florent Torregrosa over 8 years ago

Issue #592: Update file_entity to version 7.x-2.0-beta2.

View differences:

drupal7/sites/all/modules/file_entity/file_entity.admin.inc
331 331
  $query = db_select('file_managed', 'fm')->extend('PagerDefault')->extend('TableSort');
332 332
  $query->leftJoin('file_usage', 'fu', 'fm.fid = fu.fid');
333 333
  $query->groupBy('fm.fid');
334
  $query->groupBy('fm.uid');
335
  $query->groupBy('fm.timestamp');
334 336
  $query->addExpression('SUM(fu.count)', 'total_count');
335 337
  file_entity_build_filter_query($query);
336 338

  
......
354 356
  $options = array();
355 357
  foreach ($files as $file) {
356 358
    $file_type = file_type_load($file->type);
359
    $account = isset($accounts[$file->uid]) ? $accounts[$file->uid] : NULL;
357 360
    $options[$file->fid] = array(
358 361
      'title' => array(
359 362
        'data' => array(
......
364 367
      ),
365 368
      'type' => $file_type ? check_plain($file_type->label) : FILE_TYPE_NONE,
366 369
      'size' => format_size($file->filesize),
367
      'author' => theme('username', array('account' => $accounts[$file->uid])),
370
      'author' => theme('username', array('account' => $account)),
368 371
      'timestamp' => format_date($file->timestamp, 'short'),
369 372
      'usage' => format_plural((int) $result[$file->fid]->total_count, '1 place', '@count places'),
370 373
    );
drupal7/sites/all/modules/file_entity/file_entity.field.inc
36 36
      'controls' => TRUE,
37 37
      'autoplay' => FALSE,
38 38
      'loop' => FALSE,
39
      'preload' => '',
39 40
      'multiple_file_behavior' => 'tags',
40 41
    ),
41 42
    'file formatter' => array(
......
53 54
      'muted' => FALSE,
54 55
      'width' => NULL,
55 56
      'height' => NULL,
57
      'preload' => '',
56 58
      'multiple_file_behavior' => 'tags',
57 59
    ),
58 60
    'file formatter' => array(
......
131 133
      '#type' => 'checkbox',
132 134
      '#default_value' => $settings['loop'],
133 135
    );
136
    $element['preload'] = array(
137
      '#title' => t('Preload'),
138
      '#type' => 'select',
139
      '#default_value' => $settings['preload'],
140
      '#options' => drupal_map_assoc(array('none', 'auto', 'metadata')),
141
      '#empty_option' => 'unspecified',
142
    );
134 143
    $element['multiple_file_behavior'] = array(
135 144
      '#title' => t('Display of multiple files'),
136 145
      '#type' => 'radios',
......
181 190
      '#maxlength' => 5,
182 191
      '#field_suffix' => t('pixels'),
183 192
    );
193
    $element['preload'] = array(
194
      '#title' => t('Preload'),
195
      '#type' => 'select',
196
      '#default_value' => $settings['preload'],
197
      '#options' => drupal_map_assoc(array('none', 'auto', 'metadata')),
198
      '#empty_option' => 'unspecified',
199
    );
184 200
    $element['multiple_file_behavior'] = array(
185 201
      '#title' => t('Display of multiple files'),
186 202
      '#type' => 'radios',
......
222 238
    if (isset($settings['loop'])) {
223 239
      $summary[] = t('Loop: %loop', array('%loop' => $settings['loop'] ? t('yes') : t('no')));
224 240
    }
241
    if (!empty($settings['preload'])) {
242
      $summary[] = t('Preload: %preload', array('%preload' => $settings['preload']));
243
    }
225 244
    if (isset($settings['multiple_file_behavior'])) {
226 245
      $summary[] = t('Multiple files: %multiple', array('%multiple' => $settings['multiple_file_behavior']));
227 246
    }
......
242 261
    if ($settings['width'] && $settings['height']) {
243 262
      $summary[] = t('Size: %width x %height', array('%width' => $settings['width'], '%height' => $settings['height']));
244 263
    }
264
    if (!empty($settings['preload'])) {
265
      $summary[] = t('Preload: %preload', array('%preload' => $settings['preload']));
266
    }
245 267
    if (isset($settings['multiple_file_behavior'])) {
246 268
      $summary[] = t('Multiple files: %multiple', array('%multiple' => $settings['multiple_file_behavior']));
247 269
    }
......
357 379
        '#controls' => $settings['controls'],
358 380
        '#autoplay' => $settings['autoplay'],
359 381
        '#loop' => $settings['loop'],
382
        '#preload' => $settings['preload'],
360 383
      );
361 384
    }
362 385
  }
......
394 417
        '#muted' => $settings['muted'],
395 418
        '#width' => $settings['width'],
396 419
        '#height' => $settings['height'],
420
        '#preload' => $settings['preload'],
397 421
      );
398 422
    }
399 423
  }
drupal7/sites/all/modules/file_entity/file_entity.file.inc
166 166
 * Implements hook_file_load().
167 167
 */
168 168
function file_entity_file_load($files) {
169
  // Add alt and title text to images.
169 170
  $alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
170 171
  $title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
171 172

  
......
179 180

  
180 181
    // Load alt and title text from fields.
181 182
    if (!empty($alt)) {
182
      $file->alt = token_replace($alt, array('file' => $file), $replace_options);
183
      $output = token_replace($alt, array('file' => $file), $replace_options);
184

  
185
      // @todo Remove once https://www.drupal.org/node/1713164 is fixed.
186
      // There is currently no way to get the raw alt text returned from the
187
      // token so we revert the encoding done during tokenization.
188
      $file->alt = decode_entities($output);
183 189
    }
184 190
    if (!empty($title)) {
185
      $file->title = token_replace($title, array('file' => $file), $replace_options);
191
      $output = token_replace($title, array('file' => $file), $replace_options);
192

  
193
      // @todo Remove once https://www.drupal.org/node/1713164 is fixed.
194
      // There is currently no way to get the raw title text returned from the
195
      // token so we revert the encoding done during tokenization.
196
      $file->title = decode_entities($output);
186 197
    }
187 198
  }
188 199

  
189 200
  // Load and unserialize metadata.
190 201
  $results = db_query("SELECT * FROM {file_metadata} WHERE fid IN (:fids)", array(':fids' => array_keys($files)));
202

  
191 203
  foreach ($results as $result) {
192
    $files[$result->fid]->metadata[$result->name] = unserialize($result->value);
204
    $name = $result->name;
205

  
206
    // image.module required height and width to be properties of the file.
207
    if ($name == 'height' || $name == 'width') {
208
      $files[$result->fid]->$name = unserialize($result->value);
209
    }
210

  
211
    $files[$result->fid]->metadata[$name] = unserialize($result->value);
193 212
  }
194 213
}
195 214

  
drupal7/sites/all/modules/file_entity/file_entity.file_default_displays.inc
99 99
    $file_display = new stdClass();
100 100
    $file_display->api_version = 1;
101 101
    $file_display->name = 'image__default__file_field_image';
102
    $file_display->weight = 49;
102
    $file_display->weight = 48;
103 103
    $file_display->status = TRUE;
104 104
    $file_display->settings = array(
105 105
      'image_style' => '',
......
111 111
    $file_display = new stdClass();
112 112
    $file_display->api_version = 1;
113 113
    $file_display->name = 'image__preview__file_field_image';
114
    $file_display->weight = 49;
114
    $file_display->weight = 48;
115 115
    $file_display->status = TRUE;
116 116
    $file_display->settings = array(
117 117
      'image_style' => 'thumbnail',
......
123 123
    $file_display = new stdClass();
124 124
    $file_display->api_version = 1;
125 125
    $file_display->name = 'image__teaser__file_field_image';
126
    $file_display->weight = 49;
126
    $file_display->weight = 48;
127 127
    $file_display->status = TRUE;
128 128
    $file_display->settings = array(
129 129
      'image_style' => 'medium',
drupal7/sites/all/modules/file_entity/file_entity.info
1
name = File entity
1
name = File Entity
2 2
description = "Extends Drupal file entities to be fieldable and viewable."
3 3
package = Media
4 4
core = 7.x
5

  
5 6
dependencies[] = field
6 7
dependencies[] = file
7 8
dependencies[] = ctools
8 9
dependencies[] = system (>=7.9)
10

  
11
test_dependencies[] = token
12

  
9 13
files[] = views/views_handler_argument_file_type.inc
10 14
files[] = views/views_handler_field_file_rendered.inc
11 15
files[] = views/views_handler_field_file_type.inc
......
20 24
files[] = views/views_plugin_row_file_rss.inc
21 25
files[] = views/views_plugin_row_file_view.inc
22 26
files[] = file_entity.test
27

  
23 28
configure = admin/config/media/file-settings
24 29

  
25 30
; We have to add a fake version so Git checkouts do not fail Media dependencies
26 31
version = 7.x-2.x-dev
27 32

  
28
; Information added by Drupal.org packaging script on 2014-10-04
29
version = "7.x-2.0-beta1"
33
; Information added by Drupal.org packaging script on 2015-07-14
34
version = "7.x-2.0-beta2"
30 35
core = "7.x"
31 36
project = "file_entity"
32
datestamp = "1412420930"
37
datestamp = "1436896443"
33 38

  
drupal7/sites/all/modules/file_entity/file_entity.install
1070 1070
  db_add_primary_key('file_metadata', array('fid', 'name'));
1071 1071
  db_drop_index('file_metadata', 'temp');
1072 1072
}
1073

  
1074
/**
1075
 * This update has been removed and will not run.
1076
 */
1077
function file_entity_update_7216() {
1078
  // This update function previously saved default file displays into the
1079
  // database. It has been removed due to reported problems and is better
1080
  // addressed by adding support for ctools default content to features.
1081
}
drupal7/sites/all/modules/file_entity/file_entity.module
79 79
    // Miscellaneous hooks
80 80
    'file_mimetype_mapping_alter',
81 81
    'file_url_alter',
82
    // Stream wrappers
83
    'stream_wrappers',
84
    'stream_wrappers_alter',
82 85
  );
83 86
  $info += array_fill_keys($hooks, array('group' => 'file'));
84 87
}
......
875 878
        'controls' => TRUE,
876 879
        'autoplay' => FALSE,
877 880
        'loop' => FALSE,
881
        'preload' => NULL,
878 882
      ),
879 883
      'file' => 'file_entity.theme.inc',
880 884
    ),
......
887 891
        'muted' => FALSE,
888 892
        'width' => NULL,
889 893
        'height' => NULL,
894
        'preload' => NULL,
890 895
      ),
891 896
      'file' => 'file_entity.theme.inc',
892 897
    ),
......
954 959

  
955 960
  // Ensure some of the Entity API callbacks are supported.
956 961
  $entity_info['file']['creation callback'] = 'entity_metadata_create_object';
957
  $entity_info['file']['view callback'] = 'file_view_multiple';
958
  $entity_info['file']['edit callback'] = 'file_entity_metadata_form_file';
962
  $entity_info['file']['view callback'] = 'file_entity_metadata_view_file';
963
  $entity_info['file']['form callback'] = 'file_entity_metadata_form_file';
959 964
  $entity_info['file']['access callback'] = 'file_entity_access';
960 965

  
961 966
  // Add integration with the Title module for file name replacement support.
......
1023 1028
  return $uri;
1024 1029
}
1025 1030

  
1031
/**
1032
 * Entity API callback to view files.
1033
 */
1034
function file_entity_metadata_view_file($entities, $view_mode = 'full', $langcode = NULL) {
1035
  $result = file_view_multiple($entities, $view_mode, 0, $langcode);
1036
  // Make sure to key the result with 'file' instead of 'files'.
1037
  return array('file' => reset($result));
1038
}
1039

  
1026 1040
/**
1027 1041
 * Entity API callback to get the form of a file entity.
1028 1042
 */
......
1036 1050
/**
1037 1051
 * Implements hook_ctools_plugin_directory().
1038 1052
 */
1039

  
1040
function file_entity_ctools_plugin_directory($module, $type) {
1041
  if ($module == 'ctools' && $type == 'content_types') {
1042
    return 'plugins/' . $type;
1053
function file_entity_ctools_plugin_directory($module, $plugin) {
1054
  if (in_array($module, array('panelizer', 'ctools', 'page_manager'))) {
1055
    return 'plugins/' . $plugin;
1043 1056
  }
1044 1057
}
1045 1058

  
......
1491 1504
  $names = &drupal_static(__FUNCTION__);
1492 1505

  
1493 1506
  if (!isset($names)) {
1507
    $names = array();
1494 1508
    $info = entity_get_info('file');
1495 1509
    foreach ($info['bundles'] as $bundle => $bundle_info) {
1496 1510
      $names[$bundle] = $bundle_info['label'];
......
1563 1577
/**
1564 1578
 * Implements hook_ctools_plugin_api().
1565 1579
 */
1566
function file_entity_ctools_plugin_api($owner, $api) {
1567
  if ($owner == 'file_entity' && $api == 'file_type') {
1580
function file_entity_ctools_plugin_api($module, $api) {
1581
  if (($module == 'file_entity' && $api == 'file_type') || ($module == 'page_manager' && $api == 'pages_default') || $module == 'panelizer') {
1568 1582
    return array('version' => 1);
1569 1583
  }
1570
  if ($owner == 'file_entity' && $api == 'file_default_displays') {
1584
  if ($module == 'file_entity' && $api == 'file_default_displays') {
1571 1585
    return array('version' => 1);
1572 1586
  }
1573 1587
}
......
1955 1969
    return file_get_content_headers($file);
1956 1970
  }
1957 1971

  
1958
  return -1;
1972
  return NULL;
1959 1973
}
1960 1974

  
1961 1975
/**
drupal7/sites/all/modules/file_entity/file_entity.pages.inc
165 165

  
166 166
  // Remove any schemes not found in the instance settings.
167 167
  if (!empty($options['schemes'])) {
168
    $schemes = array_intersect_key($schemes, $options['schemes']);
168
    $schemes = array_intersect_key($schemes, array_flip($options['schemes']));
169 169
  }
170 170

  
171 171
  // Determine which scheme to use as the default value.
......
245 245
  $rows = array();
246 246
  $occured_entities = array();
247 247

  
248
  foreach (file_usage_list($file) as $module => $usage) {
249
    $info = system_get_info('module', $module);
250

  
251
    // There are cases where the actual entity doesn't exist.
252
    // We have to handle this.
253
    foreach ($usage as $entity_type => $entity_ids) {
248
  // Determine all of the locations where a file is used, then loop through the
249
  // occurrences and filter out any duplicates.
250
  foreach (file_usage_list($file) as $module => $type) {
251
    foreach ($type as $entity_type => $entity_ids) {
252
      // There are cases where the actual entity doesn't exist.
253
      // We have to handle this.
254 254
      $entity_info = entity_get_info($entity_type);
255 255
      $entities = empty($entity_info) ? NULL : entity_load($entity_type, array_keys($entity_ids));
256 256

  
257 257
      foreach ($entity_ids as $entity_id => $count) {
258
        // If some other module already added this entity just sum all counts.
258
        // If this entity has already been listed in the table, just add any
259
        // additional usage to the total count column in the table row and
260
        // continue on to the next iteration of the loop.
259 261
        if (isset($occured_entities[$entity_type][$entity_id])) {
260 262
          $rows[$occured_entities[$entity_type][$entity_id]][2] += $count;
261 263
          continue;
262 264
        }
263 265

  
266
        // Retrieve the label and the URI of the entity.
264 267
        $label = empty($entities[$entity_id]) ? $module : entity_label($entity_type, $entities[$entity_id]);
265 268
        $entity_uri = empty($entities[$entity_id]) ? NULL : entity_uri($entity_type, $entities[$entity_id]);
266 269

  
267
        // Some entities do not have URL.
270
        // Link the label to the URI when possible.
268 271
        if (empty($entity_uri)) {
269
          $rows[] = array(check_plain($label), $entity_type, $module, $count);
272
          $entity = check_plain($label);
270 273
        }
271 274
        else {
272
          $uri = $entity_uri['path'];
273
          $rows[] = array(l($label, $uri), $entity_type, $module, $count);
275
          $entity = l($label, $entity_uri['path']);
274 276
        }
275 277

  
278
        $rows[] = array($entity, $entity_type, $count);
279

  
280
        // Record the occurrence of the entity to ensure that it isn't listed in
281
        // the table again.
276 282
        $occured_entities[$entity_type][$entity_id] = count($rows) - 1;
277 283
      }
278 284
    }
279 285
  }
280
  $header[] = array(
281
    'data' => t('Entity'),
282
  );
283
  $header[] = array(
284
    'data' => t('Entity type'),
285
  );
286
  $header[] = array(
287
    'data' => t('Registering module'),
288
  );
289
  $header[] = array(
290
    'data' => t('Use count'),
291
  );
286

  
287
  $header = array(t('Entity'), t('Entity type'), t('Use count'));
292 288
  $build['usage_table'] = array(
293 289
    '#theme' => 'table',
294 290
    '#header' => $header,
295 291
    '#rows' => $rows,
296
    '#caption' => t('This table lists all of the places where @filename is used.',
297
    array('@filename' => $file->filename)),
292
    '#caption' => t('This table lists all of the places where @filename is used.', array('@filename' => $file->filename)),
298 293
    '#empty' => t('This file is not currently used.'),
299 294
  );
295

  
300 296
  return $build;
301 297
}
302 298

  
......
428 424
    $file = file_load($form_state['storage']['upload']);
429 425
    if ($file) {
430 426
      if (file_uri_scheme($file->uri) != $form_state['storage']['scheme']) {
431
        if ($moved_file = file_move($file, $form_state['storage']['scheme'] . '://' . file_uri_target($file->uri), FILE_EXISTS_RENAME)) {
427
        $file_destination = $form_state['storage']['scheme'] . '://' . file_uri_target($file->uri);
428
        $file_destination = file_stream_wrapper_uri_normalize($file_destination);
429
        if ($moved_file = file_move($file, $file_destination, FILE_EXISTS_RENAME)) {
432 430
          // Only re-assign the file object if file_move() did not fail.
433 431
          $file = $moved_file;
434 432
        }
......
455 453
    }
456 454

  
457 455
    // Figure out destination.
458
    if (isset($_GET['destination'])) {
459
      $destination = drupal_get_destination();
460
      unset($_GET['destination']);
461
    }
462
    elseif (user_access('administer files')) {
463
      $destination = array('destination' => 'admin/content/file');
456
    if (user_access('administer files')) {
457
      $path = 'admin/content/file';
464 458
    }
465 459
    else {
466
      $destination = array('destination' => 'file/' . $file->fid);
460
      $path = 'file/' . $file->fid;
467 461
    }
468
    $form_state['redirect'] = $destination['destination'];
462
    $form_state['redirect'] = $path;
469 463
  }
470 464
  else {
471 465
    $form_state['rebuild'] = TRUE;
......
558 552
      $file->status = FILE_STATUS_PERMANENT;
559 553
      file_save($file);
560 554

  
561
      $saved_files[] = $file;
562 555
      $form_state['files'][$file->fid] = $file;
563 556
    }
564 557
    else {
......
568 561
  }
569 562

  
570 563
  // Redirect to the file edit page.
571
  if (file_entity_access('update', $file) && module_exists('multiform') && module_exists('media')) {
564
  if (file_entity_access('update', $file) && module_exists('media_bulk_upload')) {
572 565
    $destination = array();
573 566
    if (isset($_GET['destination'])) {
574 567
      $destination = drupal_get_destination();
......
807 800
  if (!empty($form_state['values']['replace_upload'])) {
808 801
    $replacement = $form_state['values']['replace_upload'];
809 802
    // Move file from temp to permanent home.
810
    $destination_uri = file_uri_scheme($file->uri) . '://' . file_uri_target($replacement->uri);
803
    $destination_uri = rtrim($file->uri, drupal_basename($file->uri)) . drupal_basename($replacement->uri);
811 804
    $replace_mode = $destination_uri == $file->uri ? FILE_EXISTS_REPLACE : FILE_EXISTS_RENAME;
812 805
    if ($new_file_uri = file_unmanaged_copy($replacement->uri, $destination_uri, $replace_mode)) {
813 806
      // @todo Add watchdog() about replaced file here?
......
848 841
  }
849 842

  
850 843
  if (file_uri_scheme($file->uri) != $form_state['values']['scheme']) {
851
    if ($moved_file = file_move($file, $form_state['values']['scheme'] . '://' . file_uri_target($file->uri), FILE_EXISTS_RENAME)) {
844
    $file_destination = $form_state['storage']['scheme'] . '://' . file_uri_target($file->uri);
845
    $file_destination = file_stream_wrapper_uri_normalize($file_destination);
846
    if ($moved_file = file_move($file, $file_destination, FILE_EXISTS_RENAME)) {
852 847
      // Only re-assign the file object if file_move() did not fail.
853 848
      $file = $moved_file;
854 849
    }
drupal7/sites/all/modules/file_entity/file_entity.test
6 6
 */
7 7

  
8 8
class FileEntityTestHelper extends DrupalWebTestCase {
9
  protected $files = array();
10

  
11 9
  function setUp() {
12 10
    $modules = func_get_args();
13 11
    if (isset($modules[0]) && is_array($modules[0])) {
......
17 15
    parent::setUp($modules);
18 16
  }
19 17

  
20
  protected function setUpFiles($defaults = array()) {
21
    // Populate defaults array.
22
    $defaults += array(
23
      'uid' => 1,
24
      'status' => FILE_STATUS_PERMANENT,
25
    );
26

  
27
    $types = array('text', 'image');
28
    foreach ($types as $type) {
29
      foreach ($this->drupalGetTestFiles($type) as $file) {
30
        foreach ($defaults as $key => $value) {
31
          $file->$key = $value;
32
        }
33
        $this->files[$type][] = file_save($file);
34
      }
35
    }
36
  }
37

  
38
  protected function createFileType($overrides = array()) {
39
    $type = new stdClass();
40
    $type->type = 'test';
41
    $type->label = "Test";
42
    $type->description = '';
43
    $type->mimetypes = array('image/jpeg', 'image/gif', 'image/png', 'image/tiff');
44

  
45
    foreach ($overrides as $k => $v) {
46
      $type->$k = $v;
47
    }
48

  
49
    file_type_save($type);
50
    return $type;
51
  }
52

  
53
  /**
54
   * Helper for testFileEntityPrivateDownloadAccess() test.
55
   *
56
   * Defines several cases for accesing private files.
57
   *
58
   * @return array
59
   *   Array of associative arrays, each one having the next keys:
60
   *   - "message" string with the assertion message.
61
   *   - "permissions" array of permissions or NULL for anonymous user.
62
   *   - "expect" expected HTTP response code.
63
   *   - "owner" Optional boolean indicating if the user is a file owner.
64
   */
65
  protected function getPrivateDownloadAccessCases() {
66
    return array(
67
      array(
68
        'message' => "File owners cannot download their own files unless they are granted the 'view own private files' permission.",
69
        'permissions' => array(),
70
        'expect' => 403,
71
        'owner' => TRUE,
72
      ),
73
      array(
74
        'message' => "File owners can download their own files as they have been granted the 'view own private files' permission.",
75
        'permissions' => array('view own private files'),
76
        'expect' => 200,
77
        'owner' => TRUE,
78
      ),
79
      array(
80
        'message' => "Anonymous users cannot download private files.",
81
        'permissions' => NULL,
82
        'expect' => 403,
83
      ),
84
      array(
85
        'message' => "Authenticated users cannot download each other's private files.",
86
        'permissions' => array(),
87
        'expect' => 403,
88
      ),
89
      array(
90
        'message' => "Users who can view public files are not able to download private files.",
91
        'permissions' => array('view files'),
92
        'expect' => 403,
93
      ),
94
      array(
95
        'message' => "Users who bypass file access can download any file.",
96
        'permissions' => array('bypass file access'),
97
        'expect' => 200,
98
      ),
99
    );
100
  }
101

  
102 18
  /**
103 19
   * Retrieves a sample file of the specified type.
104 20
   */
......
112 28
    return $file;
113 29
  }
114 30

  
31
  /**
32
   * Retrieves the fid of the last inserted file.
33
   */
34
  function getLastFileId() {
35
    return (int) db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField();
36
  }
37

  
115 38
  /**
116 39
   * Get a file from the database based on its filename.
117 40
   *
......
131 54
  }
132 55

  
133 56
  protected function createFileEntity($settings = array()) {
134
    $file = new stdClass();
135

  
136 57
    // Populate defaults array.
137 58
    $settings += array(
138 59
      'filepath' => 'Файл для тестирования ' . $this->randomName(), // Prefix with non-latin characters to ensure that all file-related tests work with international filenames.
......
181 102
    return $file;
182 103
  }
183 104

  
105
  protected function createFileType($overrides = array()) {
106
    $type = new stdClass();
107
    $type->type = 'test';
108
    $type->label = "Test";
109
    $type->description = '';
110
    $type->mimetypes = array('image/jpeg', 'image/gif', 'image/png', 'image/tiff');
111

  
112
    foreach ($overrides as $k => $v) {
113
      $type->$k = $v;
114
    }
115

  
116
    file_type_save($type);
117
    return $type;
118
  }
119

  
184 120
  /**
185 121
   * Overrides DrupalWebTestCase::drupalGetToken() to support the hash salt.
186 122
   *
......
192 128
  }
193 129
}
194 130

  
131
/**
132
 * Tests file type classification functionality.
133
 */
195 134
class FileEntityFileTypeClassificationTestCase extends DrupalWebTestCase {
196 135
  public static function getInfo() {
197 136
    return array(
......
205 144
    parent::setUp();
206 145
  }
207 146

  
208
  /**
209
   * Get the file type of a given file.
210
   *
211
   * @param $file
212
   *   A file object.
213
   *
214
   * @return
215
   *   The file's file type as a string.
216
   */
217
  function getFileType($file) {
218
    $type = db_select('file_managed', 'fm')
219
      ->fields('fm', array('type'))
220
      ->condition('fid', $file->fid, '=')
221
      ->execute()
222
      ->fetchAssoc();
223

  
224
    return $type;
225
  }
226

  
227 147
  /**
228 148
   * Test that existing files are properly classified by file type.
229 149
   */
......
257 177
    $file_type = $this->getFileType($image_file);
258 178
    $this->assertEqual($file_type['type'], 'image', t('The image file was properly assigned the Image file type.'));
259 179
  }
180

  
181
  /**
182
   * Get the file type of a given file.
183
   *
184
   * @param $file
185
   *   A file object.
186
   *
187
   * @return
188
   *   The file's file type as a string.
189
   */
190
  function getFileType($file) {
191
    $type = db_select('file_managed', 'fm')
192
      ->fields('fm', array('type'))
193
      ->condition('fid', $file->fid, '=')
194
      ->execute()
195
      ->fetchAssoc();
196

  
197
    return $type;
198
  }
260 199
}
261 200

  
201
/**
202
 * Tests basic file entity functionality.
203
 */
262 204
class FileEntityUnitTestCase extends FileEntityTestHelper {
263 205
  public static function getInfo() {
264 206
    return array(
......
268 210
    );
269 211
  }
270 212

  
271
  function setUp() {
272
    parent::setUp();
273
    $this->setUpFiles();
274
  }
275

  
276 213
  /**
277 214
   * Regression tests for core issue http://drupal.org/node/1239376.
278 215
   */
......
289 226
    }
290 227
  }
291 228

  
229
  /**
230
   * Tests basic file entity properties.
231
   */
292 232
  function testFileEntity() {
293
    $file = reset($this->files['text']);
233
    // Save a raw file, turning it into a file entity.
234
    $file = $this->getTestFile('text');
235
    $file->uid = 1;
236
    $file->status = FILE_STATUS_PERMANENT;
237
    file_save($file);
294 238

  
295 239
    // Test entity ID, revision ID, and bundle.
296 240
    $ids = entity_extract_ids('file', $file);
......
301 245
    $this->assertEqual($uri['path'], "file/{$file->fid}");
302 246
  }
303 247

  
248
  /**
249
   * Tests storing image height and width as file metadata.
250
   */
304 251
  function testImageDimensions() {
305
    $files = array();
306
    $text_fids = array();
307 252
    // Test hook_file_insert().
308
    // Files have been saved as part of setup (in FileEntityTestHelper::setUpFiles).
309
    foreach ($this->files['image'] as $file) {
310
      $files[$file->fid] = $file->metadata;
311
      $this->assertTrue(isset($file->metadata['height']), 'Image height retrieved on file_save() for an image file.');
312
      $this->assertTrue(isset($file->metadata['width']), 'Image width retrieved on file_save() for an image file.');
313
    }
314
    foreach ($this->files['text'] as $file) {
315
      $text_fids[] = $file->fid;
316
      $this->assertFalse(isset($file->metadata['height']), 'No image height retrieved on file_save() for an text file.');
317
      $this->assertFalse(isset($file->metadata['width']), 'No image width retrieved on file_save() for an text file.');
318
    }
253
    $file = current($this->drupalGetTestFiles('image'));
254
    $image_file = file_save($file);
255
    $this->assertTrue(isset($image_file->metadata['height']), 'Image height retrieved on file_save() for an image file.');
256
    $this->assertTrue(isset($image_file->metadata['width']), 'Image width retrieved on file_save() for an image file.');
257

  
258
    $file = current($this->drupalGetTestFiles('text'));
259
    $text_file = file_save($file);
260
    $this->assertFalse(isset($text_file->metadata['height']), 'No image height retrieved on file_save() for an text file.');
261
    $this->assertFalse(isset($text_file->metadata['width']), 'No image width retrieved on file_save() for an text file.');
319 262

  
320 263
    // Test hook_file_load().
321 264
    // Clear the cache and load fresh files objects to test file_load behavior.
322 265
    entity_get_controller('file')->resetCache();
323
    foreach (file_load_multiple(array_keys($files)) as $file) {
324
      $this->assertTrue(isset($file->metadata['height']), 'Image dimensions retrieved on file_load() for an image file.');
325
      $this->assertTrue(isset($file->metadata['width']), 'Image dimensions retrieved on file_load() for an image file.');
326
      $this->assertEqual($file->metadata['height'], $files[$file->fid]['height'], 'Loaded image height is equal to saved image height.');
327
      $this->assertEqual($file->metadata['width'], $files[$file->fid]['width'], 'Loaded image width is equal to saved image width.');
328
    }
329
    foreach (file_load_multiple($text_fids) as $file) {
330
      $this->assertFalse(isset($file->metadata['height']), 'No image height retrieved on file_load() for an text file.');
331
      $this->assertFalse(isset($file->metadata['width']), 'No image width retrieved on file_load() for an text file.');
332
    }
266

  
267
    $file = file_load($image_file->fid);
268
    $this->assertTrue(isset($file->metadata['height']), 'Image dimensions retrieved on file_load() for an image file.');
269
    $this->assertTrue(isset($file->metadata['width']), 'Image dimensions retrieved on file_load() for an image file.');
270

  
271
    $this->assertEqual($file->metadata['height'], $image_file->metadata['height'], 'Loaded image height is equal to saved image height.');
272
    $this->assertEqual($file->metadata['width'], $image_file->metadata['width'], 'Loaded image width is equal to saved image width.');
273

  
274
    $file = file_load($text_file->fid);
275
    $this->assertFalse(isset($file->metadata['height']), 'No image height retrieved on file_load() for an text file.');
276
    $this->assertFalse(isset($file->metadata['width']), 'No image width retrieved on file_load() for an text file.');
333 277

  
334 278
    // Test hook_file_update().
335 279
    // Load the first image file and resize it.
336
    $image_files = array_keys($files);
337
    $file = file_load(reset($image_files));
338
    $image = image_load($file->uri);
339
    image_resize($image, $file->metadata['width'] / 2, $file->metadata['height'] / 2);
280
    $height = $image_file->metadata['width'] / 2;
281
    $width = $image_file->metadata['height'] / 2;
282
    $image = image_load($image_file->uri);
283
    image_resize($image, $width, $height);
340 284
    image_save($image);
341
    file_save($file);
342
    $this->assertEqual($file->metadata['height'], $files[$file->fid]['height'] / 2, 'Image file height updated by file_save().');
343
    $this->assertEqual($file->metadata['width'], $files[$file->fid]['width'] / 2, 'Image file width updated by file_save().');
285
    file_save($image_file);
286

  
287
    $this->assertEqual($image_file->metadata['height'], $height, 'Image file height updated by file_save().');
288
    $this->assertEqual($image_file->metadata['width'], $width, 'Image file width updated by file_save().');
289

  
344 290
    // Clear the cache and reload the file.
345 291
    entity_get_controller('file')->resetCache();
346
    $file = file_load($file->fid);
347
    $this->assertEqual($file->metadata['height'], $files[$file->fid]['height'] / 2, 'Updated image height retrieved by file_load().');
348
    $this->assertEqual($file->metadata['width'], $files[$file->fid]['width'] / 2, 'Updated image width retrieved by file_load().');
349 292

  
350
    //Test hook_file_delete().
293
    $file = file_load($image_file->fid);
294
    $this->assertEqual($file->metadata['height'], $height, 'Updated image height retrieved by file_load().');
295
    $this->assertEqual($file->metadata['width'], $width, 'Updated image width retrieved by file_load().');
296

  
297
    // Verify that the image dimension metadata is removed on file deletion.
351 298
    file_delete($file, TRUE);
352
    $this->assertFalse(db_query('SELECT COUNT(*) FROM {file_metadata} WHERE fid = :fid', array(':fid' => 'fid'))->fetchField(), 'Row deleted in {file_dimensions} on file_delete().');
299
    $this->assertFalse(db_query('SELECT COUNT(*) FROM {file_metadata} WHERE fid = :fid', array(':fid' => 'fid'))->fetchField(), 'Row deleted in {file_metadata} on file_delete().');
353 300
  }
354 301
}
355 302

  
303
/**
304
 * Tests editing existing file entities.
305
 */
356 306
class FileEntityEditTestCase extends FileEntityTestHelper {
357 307
  protected $web_user;
358 308
  protected $admin_user;
......
463 413
  }
464 414
}
465 415

  
466
class FileEntityCreationTestCase extends FileEntityTestHelper {
416
/**
417
 * Tests creating new file entities through the file upload wizard.
418
 */
419
class FileEntityUploadWizardTestCase extends FileEntityTestHelper {
467 420
  public static function getInfo() {
468 421
    return array(
469
      'name' => 'File entity creation',
470
      'description' => 'Create a file and test saving it.',
422
      'name' => 'File entity upload wizard',
423
      'description' => 'Upload a file using the multi-step wizard.',
471 424
      'group' => 'File entity',
425
      'dependencies' => array('token'),
472 426
    );
473 427
  }
474 428

  
475 429
  function setUp() {
476
    parent::setUp();
430
    parent::setUp('token');
477 431

  
478
    $web_user = $this->drupalCreateUser(array('create files', 'edit own document files'));
432
    // Disable the private file system which is automatically enabled by
433
    // DrupalTestCase so we can test the upload wizard correctly.
434
    variable_del('file_private_path');
435

  
436
    $web_user = $this->drupalCreateUser(array('create files', 'view own private files'));
479 437
    $this->drupalLogin($web_user);
480 438
  }
481 439

  
482 440
  /**
483
   * Create a "document" file and verify its consistency in the database.
441
   * Test the basic file upload wizard functionality.
484 442
   */
485
  function testFileEntityCreation() {
443
  function testFileEntityUploadWizardBasic() {
486 444
    $test_file = $this->getTestFile('text');
487
    // Create a file.
445

  
446
    // Step 1: Upload a basic document file.
488 447
    $edit = array();
489 448
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
490 449
    $this->drupalPost('file/add', $edit, t('Next'));
491 450

  
492
    // Step 2: Scheme selection
493
    if ($this->xpath('//input[@name="scheme"]')) {
494
      $this->drupalPost(NULL, array(), t('Next'));
495
    }
451
    // Check that the file exists in the database.
452
    $fid = $this->getLastFileId();
453
    $file = file_load($fid);
454
    $this->assertTrue($file, t('File found in database.'));
496 455

  
497 456
    // Check that the document file has been uploaded.
498
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Document', '%name' => $test_file->filename)), t('Document file uploaded.'));
457
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Document', '%name' => $file->filename)), t('Document file uploaded.'));
458
  }
459

  
460
  /**
461
   * Test the file upload wizard type step.
462
   */
463
  function testFileEntityUploadWizardTypes() {
464
    $test_file = $this->getTestFile('text');
465

  
466
    // Create multiple file types with the same mime types.
467
    $this->createFileType(array('type' => 'document1', 'label' => 'Document 1', 'mimetypes' => array('text/plain')));
468
    $this->createFileType(array('type' => 'document2', 'label' => 'Document 2', 'mimetypes' => array('text/plain')));
469

  
470
    // Step 1: Upload a basic document file.
471
    $edit = array();
472
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
473
    $this->drupalPost('file/add', $edit, t('Next'));
474

  
475
    // Step 2: File type selection.
476
    $edit = array();
477
    $edit['type'] = 'document2';
478
    $this->drupalPost(NULL, $edit, t('Next'));
499 479

  
500 480
    // Check that the file exists in the database.
501
    $file = $this->getFileByFilename($test_file->filename);
481
    $fid = $this->getLastFileId();
482
    $file = file_load($fid);
483
    $this->assertTrue($file, t('File found in database.'));
484

  
485
    // Check that the document file has been uploaded.
486
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Document 2', '%name' => $file->filename)), t('Document 2 file uploaded.'));
487
  }
488

  
489
  /**
490
   * Test the file upload wizard scheme step.
491
   */
492
  function testFileEntityUploadWizardSchemes() {
493
    $test_file = $this->getTestFile('text');
494

  
495
    // Enable the private file system.
496
    variable_set('file_private_path', $this->private_files_directory);
497

  
498
    // Step 1: Upload a basic document file.
499
    $edit = array();
500
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
501
    $this->drupalPost('file/add', $edit, t('Next'));
502

  
503
    // Step 3: Scheme selection.
504
    $edit = array();
505
    $edit['scheme'] = 'private';
506
    $this->drupalPost(NULL, $edit, t('Next'));
507

  
508
    // Check that the file exists in the database.
509
    $fid = $this->getLastFileId();
510
    $file = file_load($fid);
511
    $this->assertTrue($file, t('File found in database.'));
512

  
513
    // Check that the document file has been uploaded.
514
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Document', '%name' => $file->filename)), t('Document file uploaded.'));
515
  }
516

  
517
  /**
518
   * Test the file upload wizard field step.
519
   */
520
  function testFileEntityUploadWizardFields() {
521
    $test_file = $this->getTestFile('image');
522
    $filename = $this->randomName();
523
    $alt = $this->randomName();
524
    $title = $this->randomName();
525

  
526
    // Step 1: Upload a basic image file.
527
    $edit = array();
528
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
529
    $this->drupalPost('file/add', $edit, t('Next'));
530

  
531
    // Step 4: Attached fields.
532
    $edit = array();
533
    $edit['filename'] = $filename;
534
    $edit['field_file_image_alt_text[' . LANGUAGE_NONE . '][0][value]'] = $alt;
535
    $edit['field_file_image_title_text[' . LANGUAGE_NONE . '][0][value]'] = $title;
536
    $this->drupalPost(NULL, $edit, t('Save'));
537

  
538
    // Check that the file exists in the database.
539
    $fid = $this->getLastFileId();
540
    $file = file_load($fid);
502 541
    $this->assertTrue($file, t('File found in database.'));
542

  
543
    // Check that the image file has been uploaded.
544
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Image', '%name' => $filename)), t('Image file uploaded.'));
545

  
546
    // Check that the alt and title text was loaded from the fields.
547
    $this->assertEqual($file->alt, $alt, t('Alt text was stored as file metadata.'));
548
    $this->assertEqual($file->title, $title, t('Title text was stored as file metadata.'));
549
  }
550

  
551
  /**
552
   * Test skipping each of the file upload wizard steps.
553
   */
554
  function testFileEntityUploadWizardStepSkipping() {
555
    $test_file = $this->getTestFile('image');
556
    $filename = $this->randomName();
557

  
558
    // Ensure that the file is affected by every step.
559
    variable_set('file_private_path', $this->private_files_directory);
560

  
561
    $this->createFileType(array('type' => 'image1', 'label' => 'Image 1', 'mimetypes' => array('image/jpeg', 'image/gif', 'image/png', 'image/tiff')));
562
    $this->createFileType(array('type' => 'image2', 'label' => 'Image 2', 'mimetypes' => array('image/jpeg', 'image/gif', 'image/png', 'image/tiff')));
563

  
564
    $field_name = drupal_strtolower($this->randomName() . '_field_name');
565
    $field = array('field_name' => $field_name, 'type' => 'text');
566
    field_create_field($field);
567
    $instance = array(
568
      'field_name' => $field_name,
569
      'entity_type' => 'file',
570
      'bundle' => 'image2',
571
      'label' => $this->randomName() . '_label',
572
    );
573
    field_create_instance($instance);
574

  
575
    // Test skipping each upload wizard step.
576
    foreach (array('types', 'schemes', 'fields') as $step) {
577
      // Step to skip.
578
      switch ($step) {
579
        case 'types':
580
          variable_set('file_entity_file_upload_wizard_skip_file_type', TRUE);
581
          break;
582
        case 'schemes':
583
          variable_set('file_entity_file_upload_wizard_skip_scheme', TRUE);
584
          break;
585
        case 'fields':
586
          variable_set('file_entity_file_upload_wizard_skip_fields', TRUE);
587
          break;
588
      }
589

  
590
      // Step 1: Upload a basic image file.
591
      $edit = array();
592
      $edit['files[upload]'] = drupal_realpath($test_file->uri);
593
      $this->drupalPost('file/add', $edit, t('Next'));
594

  
595
      // Step 2: File type selection.
596
      if ($step != 'types') {
597
        $edit = array();
598
        $edit['type'] = 'image2';
599
        $this->drupalPost(NULL, $edit, t('Next'));
600
      }
601

  
602
      // Step 3: Scheme selection.
603
      if ($step != 'schemes') {
604
        $edit = array();
605
        $edit['scheme'] = 'private';
606
        $this->drupalPost(NULL, $edit, t('Next'));
607
      }
608

  
609
      // Step 4: Attached fields.
610
      if ($step != 'fields') {
611
        // Skipping file type selection essentially skips this step as well
612
        // because the file will not be assigned a type so no fields will be
613
        // available.
614
        if ($step != 'types') {
615
          $edit = array();
616
          $edit['filename'] = $filename;
617
          $edit[$field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $this->randomName();
618
          $this->drupalPost(NULL, $edit, t('Save'));
619
        }
620
      }
621

  
622
      // Check that the file exists in the database.
623
      $fid = $this->getLastFileId();
624
      $file = file_load($fid);
625
      $this->assertTrue($file, t('File found in database.'));
626

  
627
      // Determine the file's file type.
628
      $type = file_type_load($file->type);
629

  
630
      // Check that the image file has been uploaded.
631
      $this->assertRaw(t('!type %name was uploaded.', array('!type' => $type->label, '%name' => $file->filename)), t('Image file uploaded.'));
632

  
633
      // Reset 'skip' variables.
634
      variable_del('file_entity_file_upload_wizard_skip_file_type');
635
      variable_del('file_entity_file_upload_wizard_skip_scheme');
636
      variable_del('file_entity_file_upload_wizard_skip_fields');
637
    }
503 638
  }
504 639
}
505 640

  
......
585 720
    $files['private_image'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_1->uid, 'type' => 'image'));
586 721
    $files['private_document'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_2->uid, 'type' => 'document'));
587 722

  
588
    // Verify view, edit, and delete links for any file.
723
    // Verify view, usage, edit, and delete links for any file.
589 724
    $this->drupalGet('admin/content/file');
590 725
    $this->assertResponse(200);
591 726
    foreach ($files as $file) {
592 727
      $this->assertLinkByHref('file/' . $file->fid);
728
      $this->assertLinkByHref('file/' . $file->fid . '/usage');
593 729
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
594 730
      $this->assertLinkByHref('file/' . $file->fid . '/delete');
595 731
      // Verify tableselect.
......
646 782
    $this->assertResponse(200);
647 783
    foreach ($files as $file) {
648 784
      $this->assertLinkByHref('file/' . $file->fid);
785
      $this->assertLinkByHref('file/' . $file->fid . '/usage');
649 786
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
650 787
      $this->assertLinkByHref('file/' . $file->fid . '/delete');
651 788
    }
......
657 794
    $this->assertResponse(200);
658 795
    foreach ($files as $file) {
659 796
      $this->assertLinkByHref('file/' . $file->fid);
797
      $this->assertLinkByHref('file/' . $file->fid . '/usage');
660 798
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
661 799
      $this->assertLinkByHref('file/' . $file->fid . '/delete');
662 800
    }
663 801
  }
664 802
}
665 803

  
666
class FileEntityReplaceTestCase extends FileEntityTestHelper {
804
/**
805
 * Tests the file usage page.
806
 */
807
class FileEntityUsageTestCase extends FileEntityTestHelper {
808
  public static function getInfo() {
809
    return array(
810
      'name' => 'File entity usage',
811
      'description' => 'Create a file and verify its usage.',
812
      'group' => 'File entity',
813
    );
814
  }
815

  
816
  function setUp() {
817
    parent::setUp();
818

  
819
    $web_user = $this->drupalCreateUser(array('create files', 'bypass file access', 'edit own article content'));
820
    $this->drupalLogin($web_user);
821
  }
822

  
823
  /**
824
   * Create a file and verify its usage information.
825
   */
826
  function testFileEntityUsagePage() {
827
    $image_field = 'field_image';
828
    $image = $this->getTestFile('image');
829

  
830
    // Create a node, save it, then edit it to upload a file.
831
    $edit = array(
832
      "files[" . $image_field . "_" . LANGUAGE_NONE . "_0]" => drupal_realpath($image->uri),
833
    );
834
    $node = $this->drupalCreateNode(array('type' => 'article'));
835
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
836

  
837
    // Load the uploaded file.
838
    $fid = $this->getLastFileId();
839
    $file = file_load($fid);
840

  
841
    // View the file's usage page.
842
    $this->drupalGet('file/' . $file->fid . '/usage');
843

  
844
    // Verify that a link to the entity is available.
845
    $this->assertLink($node->title);
846
    $this->assertLinkByHref('node/' . $node->nid);
847

  
848
    // Verify that the entity type and use count information is also present.
849
    $expected_values = array(
850
      'type' => 'node',
851
      'count' => 1,
852
    );
853
    foreach ($expected_values as $name => $value) {
854
      $this->assertTrue($this->xpath('//table/tbody/tr/td[normalize-space(text())=:text]', array(':text' => $value)), t('File usage @name was found in the table.', array('@name' => $name)));
855
    }
856

  
857
    // Add a reference to the file from the same entity but registered by a
858
    // different module to ensure that the usage count is incremented and no
859
    // additional table rows are created.
860
    file_usage_add($file, 'example_module', 'node', $node->nid, 2);
861

  
862
    // Reload the page and verify that the expected values are present.
863
    $this->drupalGet('file/' . $file->fid . '/usage');
864
    $expected_values['count'] = 3;
865
    foreach ($expected_values as $name => $value) {
866
      $this->assertTrue($this->xpath('//table/tbody/tr/td[normalize-space(text())=:text]', array(':text' => $value)), t('File usage @name was found in the table.', array('@name' => $name)));
867
    }
868

  
869
    // Add a reference to the file from an entity that doesn't exist to ensure
870
    // that this case is handled.
871
    file_usage_add($file, 'test_module', 'imaginary', 1);
872

  
873
    // Reload the page.
874
    $this->drupalGet('file/' . $file->fid . '/usage');
875

  
876
    // Verify that the module name is used in place of a link to the entity.
877
    $this->assertNoLink('test_module');
878
    $this->assertRaw('test_module', 'Module name used in place of link to the entity.');
879

  
880
    // Verify that the entity type and use count information is also present.
881
    $expected_values = array(
882
      'type' => 'imaginary',
883
      'count' => 1,
884
    );
885
    foreach ($expected_values as $name => $value) {
886
      $this->assertTrue($this->xpath('//table/tbody/tr/td[normalize-space(text())=:text]', array(':text' => $value)), t('File usage @name was found in the table.', array('@name' => $name)));
887
    }
888
  }
889
}
890

  
891
/**
892
 * Tests image alt and title text.
893
 */
894
class FileEntityAltTitleTestCase extends FileEntityTestHelper {
895
  public static function getInfo() {
896
    return array(
897
      'name' => 'File entity alt and title text',
898
      'description' => 'Create an image file with alt and title text.',
899
      'group' => 'File entity',
900
      'dependencies' => array('token'),
901
    );
902
  }
903

  
904
  function setUp() {
905
    parent::setUp('token');
906

  
907
    $web_user = $this->drupalCreateUser(array('create files', 'edit own image files'));
908
    $this->drupalLogin($web_user);
909
  }
910

  
911
  /**
912
   * Create an "image" file and verify its associated alt and title text.
913
   */
914
  function testFileEntityAltTitle() {
915
    $test_file = $this->getTestFile('image');
916
    $alt_field_name = 'field_file_image_alt_text'; // Name of the default alt text field added to the image file type.
917
    $title_field_name = 'field_file_image_title_text'; // Name of the default title text field added to the image file type.
918

  
919
    // Create a file.
920
    $edit = array();
921
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
922
    $this->drupalPost('file/add', $edit, t('Next'));
923

  
924
    // Step 2: Scheme selection.
925
    if ($this->xpath('//input[@name="scheme"]')) {
926
      $this->drupalPost(NULL, array(), t('Next'));
927
    }
928

  
929
    // Step 3: Attached fields.
930
    $alt = 'Quote" Amp& ' . 'Файл для тестирования ' . $this->randomName(); // Generate alt text containing HTML entities, spaces and non-latin characters.
931
    $title = 'Quote" Amp& ' . 'Файл для тестирования ' . $this->randomName(); // Generate title text containing HTML entities, spaces and non-latin characters.
932

  
933
    $edit = array();
934
    $edit[$alt_field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $alt;
935
    $edit[$title_field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $title;
936
    $this->drupalPost(NULL, $edit, t('Save'));
937

  
938
    // Check that the image file has been uploaded.
939
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Image', '%name' => $test_file->filename)), t('Image file uploaded.'));
940

  
941
    // Check that the file exists in the database.
942
    $file = $this->getFileByFilename($test_file->filename);
943
    $this->assertTrue($file, t('File found in database.'));
944

  
945
    // Check that the alt and title text was loaded from the fields.
946
    $this->assertEqual($file->alt, $alt, t('Alt text was stored as file metadata.'));
947
    $this->assertEqual($file->title, $title, t('Title text was stored as file metadata.'));
948

  
949
    // Verify that the alt and title text is present on the page.
950
    $image_info = array(
951
      'path' => $file->uri,
952
      'alt' => $alt,
953
      'title' => $title,
954
      'width' => $file->width,
955
      'height' => $file->height,
956
    );
957
    $default_output = theme('image', $image_info);
958
    $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
959

  
960
    // Verify that the alt and title text can be edited.
961
    $new_alt = $this->randomName();
962
    $new_title = $this->randomName();
963

  
964
    $edit = array();
965
    $edit[$alt_field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $new_alt;
966
    $edit[$title_field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $new_title;
967
    $this->drupalPost('file/' . $file->fid . '/edit', $edit, t('Save'));
968

  
969
    $image_info = array(
970
      'path' => $file->uri,
971
      'alt' => $new_alt,
972
      'title' => $new_title,
973
      'width' => $file->width,
974
      'height' => $file->height,
975
    );
976
    $default_output = theme('image', $image_info);
977
    $this->assertRaw($default_output, 'Image displayed using updated alt and title attributes.');
978
  }
979
}
980

  
981
/**
982
 * Tests replacing the file associated with a file entity.
983
 */
984
class FileEntityReplaceTestCase extends FileEntityTestHelper {
667 985
  public static function getInfo() {
668 986
    return array(
669 987
      'name' => 'File replacement',
......
674 992

  
675 993
  function setUp() {
676 994
    parent::setUp();
677
    $this->setUpFiles();
678 995
  }
679 996

  
680 997
  /**
......
683 1000
   */
684 1001
  function testReplaceFile() {
685 1002
    // Select the first text test file to use.
686
    $file = reset($this->files['text']);
1003
    $file = $this->createFileEntity(array('type' => 'document'));
687 1004

  
688 1005
    // Create a user with file edit permissions.
689 1006
    $user = $this->drupalCreateUser(array('edit any document files'));
......
697 1014
    $this->drupalPost(NULL, array(), t('Save'));
698 1015
    $this->assertText(t('Document @file has been updated.', array('@file' => $file->filename)), 'File was updated without file upload.');
699 1016

  
700
    // Get the next text file to use as a replacement.
1017
    // Get a text file to use as a replacement.
701 1018
    $original = clone $file;
702
    $replacement = next($this->files['text']);
1019
    $replacement = $this->getTestFile('text');
703 1020

  
704 1021
    // Test that the file saves when uploading a replacement file.
705 1022
    $edit = array();
......
718 1035
    $this->assertFalse(entity_load('file', FALSE, array('status' => 0)), 'Temporary file used for replacement was deleted.');
719 1036

  
720 1037
    // Get an image file.
721
    $image = reset($this->files['image']);
1038
    $image = $this->getTestFile('image');
722 1039
    $edit['files[replace_upload]'] = drupal_realpath($image->uri);
723 1040

  
724 1041
    // Test that validation works by uploading a non-text file as a replacement.
......
745 1062
  }
746 1063
}
747 1064

  
1065
/**
1066
 * Tests file entity tokens.
1067
 */
748 1068
class FileEntityTokenTestCase extends FileEntityTestHelper {
749 1069
  public static function getInfo() {
750 1070
    return array(
......
756 1076

  
757 1077
  function setUp() {
758 1078
    parent::setUp();
759
    $this->setUpFiles();
760 1079
  }
761 1080

  
762 1081
  function testFileEntityTokens() {
1082
    $file = $this->createFileEntity(array('type' => 'document'));
763 1083
    $tokens = array(
764 1084
      'type' => 'Document',
765 1085
      'type:name' => 'Document',
766 1086
      'type:machine-name' => 'document',
767
      'type:count' => count($this->files['text']),
1087
      'type:count' => 1,
768 1088
    );
769
    $this->assertTokens('file', array('file' => $this->files['text'][0]), $tokens);
1089
    $this->assertTokens('file', array('file' => $file), $tokens);
770 1090

  
1091
    $file = $this->createFileEntity(array('type' => 'image'));
771 1092
    $tokens = array(
772 1093
      'type' => 'Image',
773 1094
      'type:name' => 'Image',
774 1095
      'type:machine-name' => 'image',
775
      'type:count' => count($this->files['image']),
1096
      'type:count' => 1,
776 1097
    );
777
    $this->assertTokens('file', array('file' => $this->files['image'][0]), $tokens);
1098
    $this->assertTokens('file', array('file' => $file), $tokens);
778 1099
  }
779 1100

  
780 1101
  function assertTokens($type, array $data, array $tokens, array $options = array()) {
......
799 1120
  }
800 1121
}
801 1122

  
1123
/**
1124
 * Tests adding support for bundles to the core 'file' entity.
1125
 */
802 1126
class FileEntityTypeTestCase extends FileEntityTestHelper {
803 1127
  public static function getInfo() {
804 1128
    return array(
......
810 1134

  
811 1135
  function setUp() {
812 1136
    parent::setUp();
813
    $this->setUpFiles();
814 1137
  }
815 1138

  
816 1139
  /**
......
836 1159
    $this->assertEqual($loaded_type->label, $type_machine_label, "Was able to create a type and retreive it.");
837 1160
  }
838 1161

  
839

  
840
  /**
841
   * Ensures that the weight is respected when types are created.
842
   * @return unknown_type
843
   */
844
  function testOrder() {
845
//    $type = $this->createFileType(array('name' => 'last', 'label' => 'Last', 'weight' => 100));
846
//    $type = $this->createFileType(array('name' => 'first', 'label' => 'First'));
847
//    $types = media_type_get_types();
848
//    $keys = array_keys($types);
849
//    $this->assertTrue(isset($types['last']) && isset($types['first']), "Both types saved");
850
//    $this->assertTrue(array_search('last', $keys) > array_search('first', $keys), 'Type which was supposed to be first came first');
851
  }
852

  
853
  /**
854
   * Test view mode assignment.  Currently fails, don't know why.
855
   * @return unknown_type
856
   */
857
  function testViewModesAssigned() {
858
  }
859

  
860
  /**
861
   * Make sure candidates are presented in the case of multiple
862
   * file types.
863
   */
864
  function testTypeWithCandidates() {
865
    // Create multiple file types with the same mime types.
866
    $types = array(
867
      'image1' => $this->createFileType(array('type' => 'image1', 'label' => 'Image 1')),
868
      'image2' => $this->createFileType(array('type' => 'image2', 'label' => 'Image 2'))
869
    );
870

  
871
    // Attach a text field to one of the file types.
872
    $field = array(
873
      'field_name' => drupal_strtolower($this->randomName()),
874
      'type' => 'text',
875
      'settings' => array(
876
        'max_length' => 255,
877
      )
878
    );
879
    field_create_field($field);
880
    $instance = array(
881
      'field_name' => $field['field_name'],
882
      'entity_type' => 'file',
883
      'bundle' => 'image2',
884
      'widget' => array(
885
        'type' => 'text_textfield',
886
      ),
887
      'display' => array(
888
        'default' => array(
889
          'type' => 'text_default',
890
        ),
891
      ),
892
    );
893
    field_create_instance($instance);
894

  
895
    // Create a user with file creation access.
896
    $user = $this->drupalCreateUser(array('create files'));
897
    $this->drupalLogin($user);
898

  
899
    // Step 1: Upload file
900
    $file = reset($this->files['image']);
901
    $edit = array();
902
    $edit['files[upload]'] = drupal_realpath($file->uri);
903
    $this->drupalPost('file/add', $edit, t('Next'));
904

  
905
    // Step 2: Select file type candidate
906
    $this->assertText('Image 1', 'File type candidate list item found.');
907
    $this->assertText('Image 2', 'File type candidate list item found.');
908
    $edit = array();
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff