-
Notifications
You must be signed in to change notification settings - Fork 14
/
file_entity.module
757 lines (686 loc) · 26 KB
/
file_entity.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
<?php
/**
* @file
* Extends Drupal file entities to be fieldable and viewable.
*/
use Drupal\Component\Utility\Html;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\file\FileInterface;
use Drupal\file_entity\Entity\FileType;
/**
* The {file_managed}.type value when the file type has not yet been determined.
*/
define('FILE_TYPE_NONE', 'undefined');
/**
* Implements hook_hook_info().
*/
function file_entity_hook_info() {
$hooks = array(
'file_operations',
'file_type_info',
'file_type_info_alter',
'file_view',
'file_view_alter',
'file_type',
'file_type_alter',
'file_download_headers_alter',
);
return array_fill_keys($hooks, array('group' => 'file'));
}
/**
* Implements hook_hook_info_alter().
*
* Add support for existing core hooks to be located in modulename.file.inc.
*/
function file_entity_hook_info_alter(&$info) {
$hooks = array(
// File API hooks
'file_copy',
'file_move',
'file_validate',
// File access
'file_download',
'file_download_access',
'file_download_access_alter',
// File entity hooks
'file_load',
'file_presave',
'file_insert',
'file_update',
'file_delete',
// Miscellaneous hooks
'file_mimetype_mapping_alter',
'file_url_alter',
);
$info += array_fill_keys($hooks, array('group' => 'file'));
}
/**
* Implements hook_help().
*/
function file_entity_help($route_name, RouteMatchInterface $route_match) {
switch ($route_match) {
case 'entity.file_type.collection':
$output = '<p>' . t('When a file is uploaded to this website, it is assigned one of the following types, based on what kind of file it is.') . '</p>';
return $output;
}
}
/**
* Implements hook_action_info_alter().
*/
function file_entity_action_info_alter(&$actions) {
if (\Drupal::moduleHandler()->moduleExists('pathauto')) {
$actions['pathauto_file_update_action'] = array(
'type' => 'file',
'label' => t('Update file alias'),
'configurable' => FALSE,
);
}
}
/**
* Implements hook_field_formatter_info_alter().
*/
function file_entity_field_formatter_info_alter(array &$info) {
// Make the entity reference view formatter available for files and images.
if (!empty($info['entity_reference_entity_view'])) {
$info['entity_reference_entity_view']['field_types'][] = 'file';
$info['entity_reference_entity_view']['field_types'][] = 'image';
}
// Add descriptions to core formatters.
$descriptions = array(
'file_default' => t('Create a simple link to the file. The link is prefixed by a file type icon and the name of the file is used as the link text.'),
'file_table' => t('Build a two-column table where the first column contains a generic link to the file and the second column displays the size of the file.'),
'file_url_plain' => t('Display a plain text URL to the file.'),
'image' => t('Format the file as an image. The image can be displayed using an image style and can optionally be linked to the image file itself or its parent content.'),
);
foreach ($descriptions as $key => $description) {
if (isset($info[$key]) && empty($info[$key]['description'])) {
$info[$key]['description'] = $description;
}
}
}
/**
* Implements hook_theme().
*/
function file_entity_theme() {
return array(
'file' => array(
'render element' => 'elements',
'template' => 'file',
),
'file_entity_file_link' => array(
'variables' => array('file' => NULL, 'icon_directory' => NULL),
'file' => 'file_entity.theme.inc',
),
'file_entity_download_link' => array(
'variables' => array('file' => NULL, 'download_link' => NULL, 'icon' => '', 'file_size' => NULL, 'attributes' => NULL),
),
'file_entity_audio' => array(
'variables' => array( 'files' => array(), 'attributes' => NULL),
),
'file_entity_video' => array(
'variables' => array( 'files' => array(), 'attributes' => NULL),
),
);
}
/**
* Implements hook_entity_info_alter().
*
* Extends the core file entity to be fieldable. The file type is used as the
* bundle key.
*/
function file_entity_entity_type_alter(&$entity_types) {
/** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
$keys = $entity_types['file']->getKeys();
$keys['bundle'] = 'type';
$entity_types['file']
->set('entity_keys', $keys)
->set('bundle_entity_type', 'file_type')
->set('admin_permission', 'administer files')
->setClass('Drupal\file_entity\Entity\FileEntity')
->setHandlerClass('storage_schema', 'Drupal\file_entity\FileEntityStorageSchema')
->setFormClass('default', 'Drupal\file_entity\Form\FileEditForm')
->setFormClass('edit', 'Drupal\file_entity\Form\FileEditForm')
->setFormClass('inline_edit', 'Drupal\file_entity\Form\FileInlineEditForm')
->setFormClass('delete', 'Drupal\Core\Entity\ContentEntityDeleteForm')
->setAccessClass('Drupal\file_entity\FileEntityAccessControlHandler')
->set('field_ui_base_route', 'entity.file_type.edit_form')
->setLinkTemplate('canonical', '/file/{file}')
->setLinkTemplate('collection', '/admin/content/files')
->setLinkTemplate('edit-form', '/file/{file}/edit')
->setLinkTemplate('delete-form', '/file/{file}/delete')
->setLinkTemplate('inline-edit-form', '/file/{file}/inline-edit')
->setViewBuilderClass('Drupal\file_entity\Entity\FileEntityViewBuilder')
->setListBuilderClass('Drupal\Core\Entity\EntityListBuilder');
/*$entity_types['file']['view modes']['teaser'] = array(
'label' => t('Teaser'),
'custom settings' => TRUE,
);
$entity_types['file']['view modes']['full'] = array(
'label' => t('Full content'),
'custom settings' => FALSE,
);
$entity_types['file']['view modes']['preview'] = array(
'label' => t('Preview'),
'custom settings' => TRUE,
);
$entity_types['file']['view modes']['rss'] = array(
'label' => t('RSS'),
'custom settings' => FALSE,
);*/
// Enable Metatag support.
//$entity_types['file']['metatags'] = TRUE;
}
/**
* Prepares variables for file templates.
*
* Default template: file.html.twig.
*
* @param array $variables
* An associative array containing:
* - elements: An array of elements to display in view mode.
* - file: The file object.
*/
function template_preprocess_file(&$variables) {
$view_mode = $variables['view_mode'] = $variables['elements']['#view_mode'];
$variables['file'] = $variables['elements']['#file'];
/** @var FileInterface $file */
$file = $variables['file'];
$variables['id'] = $file->id();
$variables['date'] = format_date($file->getCreatedTime()); // @TODO: Check this out
$username = array(
'#theme' => 'username',
'#account' => $file->getOwner(),
'#link_options' => array('attributes' => array('rel' => 'author')),
);
$variables['name'] = drupal_render($username);
$variables['file_url'] = $file->url('canonical');
$label = $file->label();
$variables['label'] = \Drupal\Component\Utility\SafeMarkup::checkPlain($label);
$variables['page'] = $view_mode == 'full' && $file->isPage();
// Hide the file name from being displayed until we can figure out a better
// way to control this. We cannot simply not output the title since
// contextual links require $title_suffix to be output in the template.
// @see http://drupal.org/node/1245266
if (!$variables['page']) {
$variables['title_attributes_array']['class'][] = 'element-invisible';
}
// Flatten the file object's member fields.
$variables = array_merge((array) $file, $variables);
// Helpful $content variable for templates.
$variables += array('content' => array());
foreach (\Drupal\Core\Render\Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
// Make the field variables available with the appropriate language.
//field_attach_preprocess('file', $file, $variables['content'], $variables);
// Attach the file object to the content element.
$variables['content']['file']['#file'] = $file;
// Display post information only on certain file types.
//if (variable_get('file_submitted_' . $file->type, FALSE)) { @TODO: What todo with this?
if (FALSE) {
$variables['display_submitted'] = TRUE;
$variables['submitted'] = t('Uploaded by @username on @datetime', array('@username' => $variables['name'], '@datetime' => $variables['date']));
$variables['user_picture'] = theme_get_setting('toggle_file_user_picture') ? theme('user_picture', array('account' => $account)) : '';
}
else {
$variables['display_submitted'] = FALSE;
$variables['submitted'] = '';
$variables['user_picture'] = '';
}
// Gather file classes.
$variables['classes_array'][] = Html::getClass('file-' . $file->bundle());
$variables['classes_array'][] = Html::getClass('file-' . $file->getMimeType());
if (!$file->isPermanent()) {
$variables['classes_array'][] = 'file-temporary';
}
// Change the 'file-entity' class into 'file'
if ($variables['classes_array'][0] == 'file-entity') {
$variables['classes_array'][0] = 'file';
}
}
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function file_entity_theme_suggestions_file_alter(array &$suggestions, array $variables) {
$view_mode = $variables['view_mode'] = $variables['elements']['#view_mode'];
/** @var FileInterface $file */
$file = $variables['elements']['#file'];
// Clean up name so there are no underscores.
$suggestions[] = 'file__' . $file->bundle();
$suggestions[] = 'file__' . $file->bundle() . '__' . $view_mode;
$suggestions[] = 'file__' . str_replace(array('/', '-'), array('__', '_'), $file->getMimeType());
$suggestions[] = 'file__' . str_replace(array('/', '-'), array('__', '_'), $file->getMimeType()) . '__' . $view_mode;
$suggestions[] = 'file__' . $file->id();
$suggestions[] = 'file__' . $file->id() . '__' . $view_mode;
}
/**
* Returns a list of available file type names.
*
* @return
* An array of file type names, keyed by the type.
*/
function file_entity_type_get_names() {
$names = &drupal_static(__FUNCTION__);
if (!isset($names)) {
foreach (FileType::loadMultiple() as $id => $type) {
$names[$id] = $type->label();
}
}
return $names;
}
/**
* Return the label for a specific file entity view mode.
*/
function file_entity_view_mode_label($view_mode, $default = FALSE) {
$labels = \Drupal::entityManager()->getViewModeOptions('file');
return isset($labels[$view_mode]) ? $labels[$view_mode] : $default;
}
/**
* @defgroup file_entity_access File access rights
* @{
* The file access system determines who can do what to which files.
*
* In determining access rights for a file, file_entity_access() first checks
* whether the user has the "bypass file access" permission. Such users have
* unrestricted access to all files. user 1 will always pass this check.
*
* Next, all implementations of hook_file_entity_access() will be called. Each
* implementation may explicitly allow, explicitly deny, or ignore the access
* request. If at least one module says to deny the request, it will be rejected.
* If no modules deny the request and at least one says to allow it, the request
* will be permitted.
*
* There is no access grant system for files.
*
* In file listings, the process above is followed except that
* hook_file_entity_access() is not called on each file for performance reasons
* and for proper functioning of the pager system. When adding a filelisting to
* your module, be sure to use a dynamic query created by db_select()
* and add a tag of "file_entity_access". This will allow modules dealing
* with file access to ensure only files to which the user has access
* are retrieved, through the use of hook_query_TAG_alter().
*
* Note: Even a single module returning FILE_ENTITY_ACCESS_DENY from
* hook_file_entity_access() will block access to the file. Therefore,
* implementers should take care to not deny access unless they really intend to.
* Unless a module wishes to actively deny access it should return
* FILE_ENTITY_ACCESS_IGNORE (or simply return nothing)
* to allow other modules to control access.
*
* Stream wrappers that are considered private should implement a 'private'
* flag equal to TRUE in hook_stream_wrappers().
*/
/**
* Implements hook_query_TAG_alter().
*
* This is the hook_query_alter() for queries tagged with 'file_access'. It adds
* file access checks for the user account given by the 'account' meta-data (or
* global $user if not provided).
*/
function file_entity_query_file_access_alter(SelectInterface $query) {
_file_entity_query_file_entity_access_alter($query, 'file');
}
/**
* Helper for file entity access functions.
*
* @param $query
* The query to add conditions to.
* @param $type
* Either 'file' or 'entity' depending on what sort of query it is. See
* file_entity_query_file_entity_access_alter() and
* file_entity_query_entity_field_access_alter() for more.
*/
function _file_entity_query_file_entity_access_alter($query, $type) {
$user = \Drupal::currentUser();
// Read meta-data from query, if provided.
if (!$account = $query->getMetaData('account')) {
$account = $user;
}
// If $account can bypass file access, we don't need to alter the query.
if ($account->hasPermission('bypass file access')) {
return;
}
$tables = $query->getTables();
$base_table = $query->getMetaData('base_table');
// If no base table is specified explicitly, search for one.
if (!$base_table) {
$fallback = '';
foreach ($tables as $alias => $table_info) {
if (!($table_info instanceof SelectInterface)) {
$table = $table_info['table'];
// If the file_managed table is in the query, it wins immediately.
if ($table == 'file_managed') {
$base_table = $table;
break;
}
// Check whether the table has a foreign key to file_managed.fid. If it
// does, do not run this check again as we found a base table and only
// file_managed can triumph that.
if (!$base_table) {
// The schema is cached.
$schema = drupal_get_schema($table);
if (isset($schema['fields']['fid'])) {
if (isset($schema['foreign keys'])) {
foreach ($schema['foreign keys'] as $relation) {
if ($relation['table'] === 'file_managed' && $relation['columns'] === array('fid' => 'fid')) {
$base_table = $table;
}
}
}
else {
// At least it's a fid. A table with a field called fid is very
// very likely to be a file_managed.fid in a file access query.
$fallback = $table;
}
}
}
}
}
// If there is nothing else, use the fallback.
if (!$base_table) {
if ($fallback) {
watchdog('security', 'Your file listing query is using @fallback as a base table in a query tagged for file access. This might not be secure and might not even work. Specify foreign keys in your schema to file_managed.fid ', array('@fallback' => $fallback), WATCHDOG_WARNING);
$base_table = $fallback;
}
else {
throw new Exception(t('Query tagged for file access but there is no fid. Add foreign keys to file_managed.fid in schema to fix.'));
}
}
}
if ($type == 'entity') {
// The original query looked something like:
// @code
// SELECT fid FROM sometable s
// WHERE ($file_access_conditions)
// @endcode
//
// Our query will look like:
// @code
// SELECT entity_type, entity_id
// FROM field_data_something s
// WHERE (entity_type = 'file' AND $file_access_conditions) OR (entity_type <> 'file')
// @endcode
//
// So instead of directly adding to the query object, we need to collect
// all of the file access conditions in a separate db_and() object and
// then add it to the query at the end.
$file_conditions = db_and();
}
foreach ($tables as $falias => $tableinfo) {
$table = $tableinfo['table'];
if (!($table instanceof SelectInterface) && $table == $base_table) {
$subquery = db_select('file_managed', 'fm_access')->fields('fm_access', array('fid'));
$subquery_conditions = db_or();
$wrappers = file_entity_get_public_and_private_stream_wrapper_names();
if (!empty($wrappers['public'])) {
if ($account->hasPermission('view files')) {
foreach (array_keys($wrappers['public']) as $wrapper) {
$subquery_conditions->condition('fm_access.uri', $wrapper . '%', 'LIKE');
}
}
elseif ($account->hasPermission('view own files')) {
foreach (array_keys($wrappers['public']) as $wrapper) {
$subquery_conditions->condition(db_and()
->condition('fm_access.uri', $wrapper . '%', 'LIKE')
->condition('fm_access.uid', $account->id())
);
}
}
}
if (!empty($wrappers['private'])) {
if ($account->hasPermission('view private files')) {
foreach (array_keys($wrappers['private']) as $wrapper) {
$subquery_conditions->condition('fm_access.uri', $wrapper . '%', 'LIKE');
}
}
elseif ($account->hasPermission('view own private files')) {
foreach (array_keys($wrappers['private']) as $wrapper) {
$subquery_conditions->condition(db_and()
->condition('fm_access.uri', $wrapper . '%', 'LIKE')
->condition('fm_access.uid', $account->id())
);
}
}
}
if ($subquery_conditions->count()) {
$subquery->condition($subquery_conditions);
$field = 'fid';
// Now handle entities.
if ($type == 'entity') {
// Set a common alias for entities.
$base_alias = $falias;
$field = 'entity_id';
}
$subquery->where("$falias.$field = fm_access.fid");
// For an entity query, attach the subquery to entity conditions.
if ($type == 'entity') {
$file_conditions->exists($subquery);
}
// Otherwise attach it to the node query itself.
elseif ($table == 'file_managed') {
// Fix for https://drupal.org/node/2073085
$db_or = db_or();
$db_or->exists($subquery);
$db_or->isNull($falias . '.' . $field);
$query->condition($db_or);
}
else {
$query->exists($subquery);
}
}
}
}
if ($type == 'entity' && $file_conditions->count()) {
// All the file access conditions are only for field values belonging to
// files.
$file_conditions->condition("$base_alias.entity_type", 'file');
$or = db_or();
$or->condition($file_conditions);
// If the field value belongs to a non-file entity type then this function
// does not do anything with it.
$or->condition("$base_alias.entity_type", 'file', '<>');
// Add the compiled set of rules to the query.
$query->condition($or);
}
}
/**
* Implements hook_file_download().
*/
function file_entity_file_download($uri) {
// Load the file from the URI.
$file = file_uri_to_object($uri);
// An existing file wasn't found, so we don't control access.
// E.g. image derivatives will fall here.
if (empty($file)) {
return NULL;
}
// Allow the user to download the file if they have appropriate permissions.
if ($file->access('view')) {
return file_get_content_headers($file);
}
return -1;
}
/**
* @} End of "defgroup file_entity_access".
*/
/**
* @name pathauto_file Pathauto integration for the core file module.
* @{
*/
// @todo move
function file_entity_entity_base_field_info(EntityTypeInterface $entity_type) {
// @todo: Make this configurable and/or remove if
// https://drupal.org/node/476294 is resolved.
if (\Drupal::moduleHandler()->moduleExists('pathauto') && $entity_type->id() == 'file') {
$fields = array();
$fields['path'] = BaseFieldDefinition::create('path')
->setCustomStorage(TRUE)
->setLabel(t('URL alias'))
->setTranslatable(TRUE)
->setDisplayOptions('form', array(
'type' => 'path',
'weight' => 30,
))
->setDisplayConfigurable('form', TRUE);
return $fields;
}
}
/**
* @} End of "name pathauto_file".
*/
/**
* Checks if pattern(s) match mimetype(s).
*/
function file_entity_match_mimetypes($needle, $haystack) {
$needle = is_array($needle) ? $needle : array($needle);
$haystack = is_array($haystack) ? $haystack : array($haystack);
foreach ($haystack as $mimetype) {
foreach ($needle as $search) {
if (fnmatch($search, $mimetype) || fnmatch($mimetype, $search)) {
return TRUE;
}
}
}
return FALSE;
}
/**
* Implements hook_admin_menu_map().
*/
function file_entity_admin_menu_map() {
if (!user_access('administer file types')) {
return;
}
$map['admin/structure/file-types/manage/%file_type'] = array(
'parent' => 'admin/structure/file-types',
'arguments' => array(
array('%file_type' => array_keys(file_entity_type_get_names())),
),
);
return $map;
}
/**
* Implements hook_entity_storage_load().
*/
function file_entity_entity_storage_load($entities, $entity_type) {
// Loop over all the entities looking for entities with attached images.
foreach ($entities as $entity) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
// Examine every image field instance attached to this entity's bundle.
foreach ($entity->getFieldDefinitions() as $field_definition) {
if ($field_definition->getSetting('target_type') == 'file' && $field_definition->getType() != 'image') {
$field_name = $field_definition->getName();
if (!empty($entity->{$field_name})) {
foreach ($entity->$field_name as $delta => $item) {
// If alt and title text is not specified, fall back to alt and
// title text on the file.
if (!empty($item->target_id) && (empty($item->alt) || empty($item->title))) {
$file = $item->entity;
foreach (array('alt', 'title') as $key) {
if (empty($item->$key) && !empty($file->{$key})) {
$item->key = $file->$key;
}
}
}
}
}
}
}
}
}
function file_entity_get_public_and_private_stream_wrapper_names($flag = StreamWrapperInterface::VISIBLE) {
$wrappers = array('public' => [], 'private' => []);
// @todo Make the set of private schemes/stream wrappers extendable.
$private_schemes = ['private', 'temporary'];
foreach (\Drupal::service('stream_wrapper_manager')->getWrappers($flag) as $key => $wrapper) {
// Some wrappers, e.g. those set in KernelTestBase, do not provide a name.
$wrapper_name = isset($wrapper['name']) ? $wrapper['name'] : substr(strrchr($wrapper['class'], '\\'), 1);
if (in_array($key, $private_schemes)) {
$wrappers['private'][$key] = $wrapper_name;
}
else {
$wrappers['public'][$key] = $wrapper_name;
}
}
return $wrappers;
}
/**
* Implements hook_file_load().
*/
function file_entity_file_load($files) {
// $alt = variable_get('file_entity_alt', '[file:field_file_image_alt_text]');
// $title = variable_get('file_entity_title', '[file:field_file_image_title_text]');
$alt = '[file:field_image_alt_text]';
$title = '[file:field_image_title_text]';
$replace_options = array(
'clear' => TRUE,
'sanitize' => FALSE,
);
/** @var \Drupal\Core\Utility\Token::replace $token_service */
$token_service = \Drupal::service('token');
/** @var \Drupal\file_entity\Entity\FileEntity $file */
foreach ($files as $file) {
$file->metadata = array();
// Load alt and title text from fields.
if (!empty($alt)) {
$token_bubbleable_metadata = new BubbleableMetadata();
$file->alt = $token_service->replace($alt, array('file' => $file), $replace_options, $token_bubbleable_metadata);
// Add the cacheability metadata of the token to the file entity. This
// means attachments are discarded, but it does not ever make sense to
// have attachments for an image's "alt" attribute anyway, so this is
// acceptable.
$file->addCacheableDependency($token_bubbleable_metadata);
}
if (!empty($title)) {
$token_bubbleable_metadata = new BubbleableMetadata();
$file->title = $token_service->replace($title, array('file' => $file), $replace_options, $token_bubbleable_metadata);
// Similar to the above, but for the "title" attribute.
$file->addCacheableDependency($token_bubbleable_metadata);
}
}
// Load and unserialize metadata.
$results = db_query("SELECT * FROM {file_metadata} WHERE fid IN (:fids[])", array(':fids[]' => array_keys($files)));
foreach ($results as $result) {
$files[$result->fid]->metadata[$result->name] = unserialize($result->value);
}
}
/**
* Returns a file object which can be passed to file_save().
*
* @param string $uri
* A string containing the URI, path, or filename.
* @param bool $use_existing
* (Optional) If TRUE and there's an existing file in the {file_managed}
* table with the passed in URI, then that file object is returned.
* Otherwise, a new file object is returned. Default is TRUE.
*
* @return FileInterface|bool
* A file object, or FALSE on error.
*
* @todo This should probably be named
* file_load_by_uri($uri, $create_if_not_exists).
* @todo Remove this function when http://drupal.org/node/685818 is fixed.
*/
function file_uri_to_object($uri, $use_existing = TRUE) {
$file = FALSE;
$uri = file_stream_wrapper_uri_normalize($uri);
if ($use_existing) {
// We should always attempt to re-use a file if possible.
$files = entity_load_multiple_by_properties('file', array('uri' => $uri));
$file = !empty($files) ? reset($files) : FALSE;
}
if (empty($file)) {
$file = File::create(array(
'uid' => \Drupal::currentUser()->id(),
'uri' => $uri,
'status' => FILE_STATUS_PERMANENT,
));
}
return $file;
}