Projet

Général

Profil

Paste
Télécharger (13 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / file_entity / file_entity.file.inc @ d1c64ea8

1
<?php
2

    
3
/**
4
 * @file
5
 * File hooks implemented by the File entity module.
6
 */
7

    
8
/**
9
 * Implements hook_file_presave().
10
 */
11
function file_entity_file_presave($file) {
12
  // Always ensure the filemime property is current.
13
  if (!empty($file->original) || empty($file->filemime)) {
14
    $file->filemime = file_get_mimetype($file->uri);
15
  }
16

    
17
  // The file type is used as a bundle key, and therefore, must not be NULL.
18
  // It defaults to FILE_TYPE_NONE when loaded via file_load(), but in case
19
  // file_save() is called on a new file object, default it here too.
20
  if (!isset($file->type)) {
21
    $file->type = FILE_TYPE_NONE;
22
  }
23

    
24
  // If the file isn't already assigned a real type, determine what type should
25
  // be assigned to it.
26
  if ($file->type === FILE_TYPE_NONE) {
27
    $type = file_get_type($file);
28
    if (isset($type)) {
29
      $file->type = $type;
30
    }
31
  }
32

    
33
  field_attach_presave('file', $file);
34

    
35
  // Fetch image dimensions.
36
  file_entity_metadata_fetch_image_dimensions($file);
37
}
38

    
39
/**
40
 * Implements hook_file_type().
41
 */
42
function file_entity_file_type($file) {
43
  $types = array();
44
  foreach (file_type_get_enabled_types() as $type) {
45
    if (file_entity_match_mimetypes($type->mimetypes, $file->filemime)) {
46
      $types[] = $type->type;
47
    }
48
  }
49

    
50
  return $types;
51
}
52

    
53
/**
54
 * Implements hook_file_insert().
55
 */
56
function file_entity_file_insert($file) {
57
  // Ensure field data is saved since file_save() does not in Drupal 7.
58
  field_attach_insert('file', $file);
59

    
60
  // Save file metadata.
61
  if (!empty($file->metadata)) {
62
    $query = db_insert('file_metadata')->fields(array('fid', 'name', 'value'));
63
    foreach ($file->metadata as $name => $value) {
64
      $query->values(array(
65
        'fid' => $file->fid,
66
        'name' => $name,
67
        'value' => serialize($value),
68
      ));
69
    }
70
    $query->execute();
71
  }
72

    
73
  // Clear any related field caches.
74
  file_entity_invalidate_field_caches($file);
75
}
76

    
77
/**
78
 * Implements hook_file_update().
79
 */
80
function file_entity_file_update($file) {
81
  // Ensure field data is saved since file_save() does not in Drupal 7.
82
  field_attach_update('file', $file);
83

    
84
  // Save file metadata.
85
  db_delete('file_metadata')->condition('fid', $file->fid)->execute();
86
  if (!empty($file->metadata)) {
87
    $query = db_insert('file_metadata')->fields(array('fid', 'name', 'value'));
88
    foreach ($file->metadata as $name => $value) {
89
      $query->values(array(
90
        'fid' => $file->fid,
91
        'name' => $name,
92
        'value' => serialize($value),
93
      ));
94
    }
95
    $query->execute();
96
  }
97

    
98
  if (module_exists('image') && file_entity_file_get_mimetype_type($file) == 'image' && $file->filesize && isset($file->original)) {
99
    if (!isset($file->metadata)) {
100
      $file->metadata = array();
101
    }
102

    
103
    if (!isset($file->original->metadata)) {
104
      if (!is_object($file->original)) {
105
        $file->original = new stdClass();
106
      }
107
      $file->original->metadata = array();
108
    }
109

    
110
    // If the file has changed dimensions or a new file has been uploaded,
111
    // update any image field reference to this file and flush image style
112
    // derivatives.
113
    $file->metadata += array('width' => NULL, 'height' => NULL);
114
    $file->original->metadata += array('width' => NULL, 'height' => NULL);
115
    if ($file->filesize != $file->original->filesize || $file->metadata['width'] != $file->original->metadata['width'] || $file->metadata['height'] != $file->original->metadata['height']) {
116
      _file_entity_update_image_field_dimensions($file);
117
    }
118

    
119
    // Flush image style derivatives whenever an image is updated.
120
    image_path_flush($file->uri);
121
  }
122

    
123
  // Clear any related field caches.
124
  file_entity_invalidate_field_caches($file);
125
}
126

    
127
/**
128
 * Implements hook_file_delete().
129
 */
130
function file_entity_file_delete($file) {
131
  field_attach_delete('file', $file);
132

    
133
  // This is safe to call since the file's records from the usage table have
134
  // not yet been deleted.
135
  file_entity_invalidate_field_caches($file);
136

    
137
  // Remove file metadata.
138
  db_delete('file_metadata')->condition('fid', $file->fid)->execute();
139

    
140
  // Remove this file from the search index if needed.
141
  // This code is implemented in file entity module rather than in search
142
  // module because file entity is implementing search module's API, not the
143
  // other way around.
144
  if (module_exists('search')) {
145
    search_reindex($file->fid, 'file');
146
  }
147
}
148

    
149
/**
150
 * Implements hook_file_mimetype_mapping_alter().
151
 */
152
function file_entity_file_mimetype_mapping_alter(&$mapping) {
153
  // For info on adding new mime-types to core: http://drupal.org/node/1443070.
154

    
155
  // @todo. Remove after fixing this in core http://drupal.org/node/2912875.
156
  // Add support for autocad drawings.
157
  $new_mappings['dwg'] = 'application/acad';
158
  // For info on adding new mime-types to file_entity: drupal.org/node/2900830.
159

    
160
  foreach ($new_mappings as $extension => $mime_type) {
161
    if (!in_array($mime_type, $mapping['mimetypes'])) {
162
      // If the mime type does not already exist, add it.
163
      $mapping['mimetypes'][] = $mime_type;
164
    }
165

    
166
    // Get the index of the mime type and assign the extension to that key.
167
    $index = array_search($mime_type, $mapping['mimetypes']);
168
    $mapping['extensions'][$extension] = $index;
169
  }
170
}
171

    
172
/**
173
 * Implements hook_file_load().
174
 */
175
function file_entity_file_load($files) {
176
  // Add alt and title text to images.
177
  file_entity_set_title_alt_properties($files);
178

    
179
  // Add metadata to each file.
180
  foreach ($files as $file) {
181
    $file->metadata = array();
182
  }
183
  $results = db_query("SELECT * FROM {file_metadata} WHERE fid IN (:fids)", array(':fids' => array_keys($files)));
184

    
185
  foreach ($results as $result) {
186
    $name = $result->name;
187

    
188
    // image.module required height and width to be properties of the file.
189
    if ($name == 'height' || $name == 'width') {
190
      $files[$result->fid]->$name = unserialize($result->value);
191
    }
192

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

    
197
/**
198
 * Implements hook_entitycache_ENTITY_TYPE_load().
199
 */
200
function file_entitycache_file_load($files) {
201
  // Integrates with entitycache - ensures the alt and title text on images is
202
  // localized.
203
  file_entity_set_title_alt_properties($files);
204
}
205

    
206
/**
207
 * Implements hook_entity_load().
208
 */
209
function file_entity_entity_load($entities, $entity_type) {
210
  file_entity_set_title_alt_properties_on_file_fields($entities, $entity_type);
211
}
212

    
213
/**
214
 * Implements hook_entitycache_load().
215
 */
216
function file_entity_entitycache_load($entities, $entity_type) {
217
  file_entity_set_title_alt_properties_on_file_fields($entities, $entity_type);
218
}
219

    
220
/**
221
 * Sets the title / alt properties on file fields attached to entities.
222
 *
223
 * Files attached to a file or image field can be stored in the field cache or
224
 * entity cache for whichever entity that the field is attached to. Because
225
 * $file->alt and $file->title are set in file_entity_file_load() based on the
226
 * current page language, they will go into the cache with that language as
227
 * well. To ensure that the correct language is used when the entity is later
228
 * loaded and displayed in a different language, the alt and title properties
229
 * can be set again using this function.
230
 *
231
 * @param array $entities
232
 *   An array of entity objects of the same type.
233
 * @param string $entity_type
234
 *   The type of entity.
235
 *
236
 * @see file_entity_entity_load()
237
 * @see file_entity_entitycache_load()
238
 */
239
function file_entity_set_title_alt_properties_on_file_fields($entities, $entity_type) {
240
  foreach ($entities as $entity) {
241
    list(, , $bundle) = entity_extract_ids($entity_type, $entity);
242
    foreach (field_info_instances($entity_type, $bundle) as $instance) {
243
      if (!empty($entity->{$instance['field_name']})) {
244
        foreach ($entity->{$instance['field_name']} as &$items) {
245
          foreach ($items as &$item) {
246
            // We need to detect any field items that passed through
247
            // file_field_load(), whether they are files, images, or something
248
            // else. There is no direct way to do that, but checking for a few
249
            // expected file properties on the field item should be sufficient.
250
            if (is_array($item) && !empty($item['fid']) && isset($item['uri']) && isset($item['filename'])) {
251
              $file = (object) $item;
252
              file_entity_set_title_alt_properties(array($file));
253
              $item = (array) $file;
254
            }
255
          }
256
        }
257
      }
258
    }
259
  }
260
}
261

    
262
/**
263
 * Set the title / alt properties of file objects.
264
 *
265
 * @param array $files
266
 *   List of file entities.
267
 * @param stdClass $language
268
 *   (optional) A language object to use for translating the title and alt
269
 *   properties. Defaults to the language of the current request.
270
 */
271
function file_entity_set_title_alt_properties($files, $language = NULL) {
272
  if (!isset($language)) {
273
    $language = $GLOBALS['language'];
274
  }
275

    
276
  $alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
277
  $title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
278

    
279
  $replace_options = array(
280
    'clear' => TRUE,
281
    'sanitize' => FALSE,
282
    'language' => $language,
283
  );
284

    
285
  foreach ($files as $file) {
286
    // Load alt and title text from fields.
287
    if (!empty($alt)) {
288
      $output = token_replace($alt, array('file' => $file), $replace_options);
289

    
290
      // @todo Remove once https://www.drupal.org/node/1713164 is fixed.
291
      // There is currently no way to get the raw alt text returned from the
292
      // token so we revert the encoding done during tokenization.
293
      $file->alt = decode_entities($output);
294
    }
295
    if (!empty($title)) {
296
      $output = token_replace($title, array('file' => $file), $replace_options);
297

    
298
      // @todo Remove once https://www.drupal.org/node/1713164 is fixed.
299
      // There is currently no way to get the raw title text returned from the
300
      // token so we revert the encoding done during tokenization.
301
      $file->title = decode_entities($output);
302
    }
303
  }
304
}
305

    
306
/**
307
 * Fetch the dimensions of an image and store them in the file metadata array.
308
 */
309
function file_entity_metadata_fetch_image_dimensions($file) {
310
  // Prevent PHP notices when trying to read empty files.
311
  // @see http://drupal.org/node/681042
312
  if (!$file->filesize) {
313
    return;
314
  }
315

    
316
  // Do not bother proceeding if this file does not have an image mime type.
317
  if (file_entity_file_get_mimetype_type($file) != 'image') {
318
    return;
319
  }
320

    
321
  // We have a non-empty image file.
322
  $image_info = image_get_info($file->uri);
323
  if ($image_info) {
324
    $file->metadata['width'] = $image_info['width'];
325
    $file->metadata['height'] = $image_info['height'];
326
  }
327
  else {
328
    // Fallback to NULL values.
329
    $file->metadata['width'] = NULL;
330
    $file->metadata['height'] = NULL;
331
  }
332
}
333

    
334
/**
335
 * Update the image dimensions stored in any image fields for a file.
336
 *
337
 * @param object $file
338
 *   A file object that is an image.
339
 *
340
 * @see http://drupal.org/node/1448124
341
 */
342
function _file_entity_update_image_field_dimensions($file) {
343
  // Prevent PHP notices when trying to read empty files.
344
  // @see http://drupal.org/node/681042
345
  if (!$file->filesize) {
346
    return;
347
  }
348

    
349
  // Do not bother proceeding if this file does not have an image mime type.
350
  if (file_entity_file_get_mimetype_type($file) != 'image') {
351
    return;
352
  }
353

    
354
  // Find all image field enabled on the site.
355
  $image_fields = _file_entity_get_fields_by_type('image');
356

    
357
  foreach ($image_fields as $image_field) {
358
    $query = new EntityFieldQuery();
359
    $query->fieldCondition($image_field, 'fid', $file->fid);
360
    $results = $query->execute();
361

    
362
    foreach ($results as $entity_type => $entities) {
363
      $entities = entity_load($entity_type, array_keys($entities));
364
      foreach ($entities as $entity) {
365
        foreach ($entity->{$image_field} as $langcode => $items) {
366
          foreach ($items as $delta => $item) {
367
            if ($item['fid'] == $file->fid) {
368
              $entity->{$image_field}[$langcode][$delta]['width'] = $file->metadata['width'];
369
              $entity->{$image_field}[$langcode][$delta]['height'] = $file->metadata['height'];
370
            }
371
          }
372
        }
373

    
374
        // Save the updated field column values.
375
        _file_entity_entity_fields_update($entity_type, $entity);
376
      }
377
    }
378
  }
379
}
380

    
381
/**
382
 * Update an entity's field values without changing anything on the entity.
383
 */
384
function _file_entity_entity_fields_update($entity_type, $entity) {
385
  list($id) = entity_extract_ids($entity_type, $entity);
386
  if (empty($id)) {
387
    throw new Exception(t('Cannot call _file_entity_update_entity_fields() on a new entity.'));
388
  }
389

    
390
  // Some modules use the original property.
391
  if (!isset($entity->original)) {
392
    $entity->original = $entity;
393
  }
394

    
395
  // Ensure that file_field_update() will not trigger additional usage.
396
  unset($entity->revision);
397

    
398
  // Invoke the field presave and update hooks.
399
  field_attach_presave($entity_type, $entity);
400
  field_attach_update($entity_type, $entity);
401

    
402
  // Clear the cache for this entity now.
403
  entity_get_controller($entity_type)->resetCache(array($id));
404
}
405

    
406
/**
407
 * Implements hook_file_metadata_info().
408
 */
409
function file_entity_file_metadata_info() {
410
  $info['width'] = array('label' => t('Width'), 'type' => 'integer');
411
  $info['height'] = array('label' => t('Height'), 'type' => 'integer');
412
  return $info;
413
}