forked from md-systems/file_entity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_entity.module
1801 lines (1645 loc) · 61.6 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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\file\FileInterface;
use Drupal\file_entity\Entity\FileType;
/**
* As part of extending Drupal core's file entity API, this module adds some
* functions to the 'file' namespace. For organization, those are kept in the
* 'file_entity.file_api.inc' file.
*/
require_once dirname(__FILE__) . '/file_entity.file_api.inc';
// @todo Remove when http://drupal.org/node/977052 is fixed.
require_once dirname(__FILE__) . '/file_entity.field.inc';
/**
* Implements hook_hook_info().
*/
function file_entity_hook_info() {
$hooks = array(
'file_operations',
'file_type_info',
'file_type_info_alter',
'file_formatter_info',
'file_formatter_info_alter',
'file_view',
'file_view_alter',
'file_displays_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($path, $arg) {
switch ($path) {
case 'admin/structure/file-types':
$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;
case 'admin/structure/file-types/manage/%/display/preview':
case 'admin/structure/file-types/manage/%/file-display/preview':
drupal_set_message(t('Some modules rely on the Preview view mode to function correctly. Changing these settings may break parts of your site.'), 'warning');
break;
}
}
/**
* Implements hook_menu().
*/
function file_entity_menu() {
// File Configuration
// @todo Move this back to admin/config/media/file-types in Drupal 8 if
// MENU_MAX_DEPTH is increased to a value higher than 9.
$items['admin/structure/file-types/manage/%file_type'] = array(
'title' => 'Manage file types',
'description' => 'Manage settings for the type of files used on your site.',
);
$items['file/add/upload/file'] = array(
'title' => 'File',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items['file/add/upload/archive'] = array(
'title' => 'Archive',
'page callback' => 'drupal_get_form',
'page arguments' => array('file_entity_upload_archive_form'),
'access arguments' => array('administer files'),
'file' => 'file_entity.pages.inc',
'type' => MENU_LOCAL_TASK,
'weight' => -5,
);
// Attach a "Manage file display" tab to each file type in the same way that
// Field UI attaches "Manage fields" and "Manage display" tabs. Note that
// Field UI does not have to be enabled; we're just using the same IA pattern
// here for attaching the "Manage file display" page.
$bundles = \Drupal::entityManager()->getBundleInfo('file');
foreach ($bundles as $file_type => $bundle_info) {
if (isset($bundle_info['admin'])) {
// Get the base path and access.
$path = $bundle_info['admin']['path'];
$access = array_intersect_key($bundle_info['admin'], array('access callback' => NULL, 'access argument' => NULL));
$access += array(
'access callback' => 'user_access',
'access arguments' => array('administer file types'),
);
// The file type must be passed to the page callbacks. It might be
// configured as a wildcard (multiple file types sharing the same menu
// router path).
$file_type_argument = isset($bundle_info['admin']['bundle argument']) ? $bundle_info['admin']['bundle argument'] : $file_type;
$items[$path] = array(
'title' => 'Edit file type',
'title callback' => 'file_entity_type_get_name',
'title arguments' => array(4),
'page callback' => 'drupal_get_form',
'page arguments' => array('file_entity_file_type_form', $file_type_argument),
'file' => 'file_entity.admin.inc',
) + $access;
// Add the 'File type settings' tab.
$items["$path/edit"] = array(
'title' => 'Edit',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
// Add the 'Manage file display' tab.
$items["$path/file-display"] = array(
'title' => 'Manage file display',
'page callback' => 'drupal_get_form',
'page arguments' => array('file_entity_file_display_form', $file_type_argument, 'default'),
'type' => MENU_LOCAL_TASK,
'weight' => 3,
'file' => 'file_entity.admin.inc',
) + $access;
// Add a secondary tab for each view mode.
$weight = 0;
$view_modes = array('default' => array('label' => t('Default'))) + $entity_info['view modes'];
foreach ($view_modes as $view_mode => $view_mode_info) {
$items["$path/file-display/$view_mode"] = array(
'title' => $view_mode_info['label'],
'page arguments' => array('file_entity_file_display_form', $file_type_argument, $view_mode),
'type' => ($view_mode == 'default' ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK),
'weight' => ($view_mode == 'default' ? -10 : $weight++),
'file' => 'file_entity.admin.inc',
// View modes for which the 'custom settings' flag isn't TRUE are
// disabled via this access callback. This needs to extend, rather
// than override normal $access rules.
'access callback' => '_file_entity_view_mode_menu_access',
'access arguments' => array_merge(array($file_type_argument, $view_mode, $access['access callback']), $access['access arguments']),
);
}
}
}
// Optional devel module integration
if (\Drupal::moduleHandler()->moduleExists('devel')) {
$items['file/%file/devel'] = array(
'title' => 'Devel',
'page callback' => 'devel_load_object',
'page arguments' => array('file', 1),
'access arguments' => array('access devel information'),
'type' => MENU_LOCAL_TASK,
'file' => 'devel.pages.inc',
'file path' => drupal_get_path('module', 'devel'),
'weight' => 100,
);
$items['file/%file/devel/load'] = array(
'title' => 'Load',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['file/%file/devel/render'] = array(
'title' => 'Render',
'page callback' => 'devel_render_object',
'page arguments' => array('file', 1),
'access arguments' => array('access devel information'),
'file' => 'devel.pages.inc',
'file path' => drupal_get_path('module', 'devel'),
'type' => MENU_LOCAL_TASK,
'weight' => 100,
);
if (\Drupal::moduleHandler()->moduleExists('token')) {
$items['file/%file/devel/token'] = array(
'title' => 'Tokens',
'page callback' => 'token_devel_token_object',
'page arguments' => array('file', 1),
'access arguments' => array('access devel information'),
'type' => MENU_LOCAL_TASK,
'file' => 'token.pages.inc',
'file path' => drupal_get_path('module', 'token'),
'weight' => 5,
);
}
}
return $items;
}
/**
* Gather the rankings from the the hook_ranking implementations.
*
* @param $query
* A query object that has been extended with the Search DB Extender.
*/
function _file_entity_rankings(SelectQueryExtender $query) {
if ($ranking = \Drupal::moduleHandler()->invokeAll('file_ranking')) {
$tables = &$query->getTables();
foreach ($ranking as $rank => $values) {
if ($file_rank = \Drupal::config('file_entity.settings')->get('rank_' . $rank, 0)) {
// If the table defined in the ranking isn't already joined, then add it.
if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
$query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
}
$arguments = isset($values['arguments']) ? $values['arguments'] : array();
$query->addScore($values['score'], $arguments, $file_rank);
}
}
}
}
/**
* Implements hook_search_info().
*/
function file_entity_search_info() {
return array(
'title' => 'Files',
'path' => 'file',
);
}
/**
* Implements hook_search_access().
*/
function file_entity_search_access() {
return user_access('view own private files') || user_access('view own files') || user_access('view private files') || user_access('view files');
}
/**
* Implements hook_search_reset().
*/
function file_entity_search_reset() {
db_update('search_dataset')
->fields(array('reindex' => REQUEST_TIME))
->condition('type', 'file')
->execute();
}
/**
* Implements hook_search_status().
*/
function file_entity_search_status() {
$total = db_query('SELECT COUNT(*) FROM {file_managed}')->fetchField();
$remaining = db_query("SELECT COUNT(*) FROM {file_managed} fm LEFT JOIN {search_dataset} d ON d.type = 'file' AND d.sid = fm.fid WHERE d.sid IS NULL OR d.reindex <> 0")->fetchField();
return array('remaining' => $remaining, 'total' => $total);
}
/**
* Implements hook_search_admin().
*/
function file_entity_search_admin() {
// Output form for defining rank factor weights.
$form['file_ranking'] = array(
'#type' => 'fieldset',
'#title' => t('File ranking'),
);
$form['file_ranking']['#theme'] = 'file_entity_search_admin';
$form['file_ranking']['info'] = array(
'#value' => '<em>' . t('The following numbers control which properties the file search should favor when ordering the results. Higher numbers mean more influence, zero means the property is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em>'
);
// Note: reversed to reflect that higher number = higher ranking.
$options = drupal_map_assoc(range(0, 10));
foreach (module_invoke_all('file_ranking') as $var => $values) {
$form['file_ranking']['factors']['file_entity_rank_' . $var] = array(
'#title' => $values['title'],
'#type' => 'select',
'#options' => $options,
'#default_value' => \Drupal::config('file_entity.settings')->get('rank_' . $var, 0),
);
}
return $form;
}
/**
* Implements hook_search_execute().
*/
function file_entity_search_execute($keys = NULL, $conditions = NULL) {
global $user;
// Build matching conditions
$query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
$query->join('file_managed', 'fm', 'fm.fid = i.sid');
$query->searchExpression($keys, 'file');
// Insert special keywords.
$query->setOption('type', 'fm.type');
if ($query->setOption('term', 'ti.tid')) {
$query->join('taxonomy_index', 'ti', 'fm.fid = ti.fid');
}
// Only continue if the first pass query matches.
if (!$query->executeFirstPass()) {
return array();
}
// Add the ranking expressions.
_file_entity_rankings($query);
// Load results.
$find = $query
->limit(10)
->addTag('file_access')
->execute();
$results = array();
foreach ($find as $item) {
// Render the file.
$file = file_load($item->sid);
$build = file_view($file, 'search_result');
unset($build['#theme']);
$file->rendered = drupal_render($build);
$extra = module_invoke_all('file_entity_search_result', $file);
$types = file_entity_type_get_names();
$uri = entity_uri('file', $file);
$results[] = array(
'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
'type' => check_plain($types[$file->type]),
'title' => $file->filename,
'user' => theme('username', array('account' => user_load($file->uid))),
'date' => $file->timestamp,
'file' => $file,
'extra' => $extra,
'score' => $item->calculated_score,
'snippet' => search_excerpt($keys, $file->rendered),
'language' => function_exists('entity_language') ? entity_language('file', $file) : NULL,
);
}
return $results;
}
/**
* Implements hook_file_ranking().
*/
function file_entity_file_ranking() {
// Create the ranking array and add the basic ranking options.
$ranking = array(
'relevance' => array(
'title' => t('Keyword relevance'),
// Average relevance values hover around 0.15
'score' => 'i.relevance',
),
);
// Add relevance based on creation date.
if ($file_cron_last = \Drupal::config('file_entity.settings')->get('cron_last', 0)) {
$ranking['timestamp'] = array(
'title' => t('Recently posted'),
// Exponential decay with half-life of 6 months, starting at last indexed file
'score' => 'POW(2.0, (fm.timestamp - :file_cron_last) * 6.43e-8)',
'arguments' => array(':file_cron_last' => $file_cron_last),
);
}
return $ranking;
}
/**
* Returns HTML for the file ranking part of the search settings admin page.
*
* @param $variables
* An associative array containing:
* - form: A render element representing the form.
*
* @ingroup themeable
*/
function theme_file_entity_search_admin($variables) {
$form = $variables['form'];
$output = drupal_render($form['info']);
$header = array(t('Factor'), t('Weight'));
foreach (element_children($form['factors']) as $key) {
$row = array();
$row[] = $form['factors'][$key]['#title'];
$form['factors'][$key]['#title_display'] = 'invisible';
$row[] = drupal_render($form['factors'][$key]);
$rows[] = $row;
}
$output .= theme('table', array('header' => $header, 'rows' => $rows));
$output .= drupal_render_children($form);
return $output;
}
/**
* Implements hook_update_index().
*/
function file_entity_update_index() {
$limit = (int)variable_get('search_cron_limit', 100);
$result = db_query_range("SELECT fm.fid FROM {file_managed} fm LEFT JOIN {search_dataset} d ON d.type = 'file' AND d.sid = fm.fid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, fm.fid ASC", 0, $limit, array(), array('target' => 'slave'));
foreach ($result as $file) {
_file_entity_index_file($file);
}
}
/**
* Index a single file.
*
* @param $file
* The file to index.
*/
function _file_entity_index_file($file) {
$file = file_load($file->fid);
// Save the creation time of the most recent indexed file, for the search
// results half-life calculation.
\Drupal::config('file_entity.settings')->set('cron_last', $file->timestamp);
// Render the file.
$build = file_view($file, 'search_index');
unset($build['#theme']);
$file->rendered = drupal_render($build);
$text = '<h1>' . check_plain($file->filename) . '</h1>' . $file->rendered;
// Fetch extra data normally not visible
$extra = module_invoke_all('file_entity_update_index', $file);
foreach ($extra as $t) {
$text .= $t;
}
// Update index
search_index($file->fid, 'file', $text);
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function file_entity_form_search_form_alter(&$form, $form_state) {
if (isset($form['module']) && $form['module']['#value'] == 'file_entity' && user_access('use advanced search')) {
// Keyword boxes:
$form['advanced'] = array(
'#type' => 'fieldset',
'#title' => t('Advanced search'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#attributes' => array('class' => array('search-advanced')),
);
$form['advanced']['keywords'] = array(
'#prefix' => '<div class="criterion">',
'#suffix' => '</div>',
);
$form['advanced']['keywords']['or'] = array(
'#type' => 'textfield',
'#title' => t('Containing any of the words'),
'#size' => 30,
'#maxlength' => 255,
);
$form['advanced']['keywords']['phrase'] = array(
'#type' => 'textfield',
'#title' => t('Containing the phrase'),
'#size' => 30,
'#maxlength' => 255,
);
$form['advanced']['keywords']['negative'] = array(
'#type' => 'textfield',
'#title' => t('Containing none of the words'),
'#size' => 30,
'#maxlength' => 255,
);
// File types:
$types = array_map('check_plain', file_entity_type_get_names());
$form['advanced']['type'] = array(
'#type' => 'checkboxes',
'#title' => t('Only of the type(s)'),
'#prefix' => '<div class="criterion">',
'#suffix' => '</div>',
'#options' => $types,
);
$form['advanced']['submit'] = array(
'#type' => 'submit',
'#value' => t('Advanced search'),
'#prefix' => '<div class="action">',
'#suffix' => '</div>',
'#weight' => 100,
);
$form['#validate'][] = 'file_entity_search_validate';
}
}
/**
* Form API callback for the search form. Registered in file_entity_form_alter().
*/
function file_entity_search_validate($form, &$form_state) {
// Initialize using any existing basic search keywords.
$keys = $form_state['values']['processed_keys'];
// Insert extra restrictions into the search keywords string.
if (isset($form_state['values']['type']) && is_array($form_state['values']['type'])) {
// Retrieve selected types - Form API sets the value of unselected
// checkboxes to 0.
$form_state['values']['type'] = array_filter($form_state['values']['type']);
if (count($form_state['values']['type'])) {
$keys = search_expression_insert($keys, 'type', implode(',', array_keys($form_state['values']['type'])));
}
}
if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
$keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
}
if ($form_state['values']['or'] != '') {
if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['or'], $matches)) {
$keys .= ' ' . implode(' OR ', $matches[1]);
}
}
if ($form_state['values']['negative'] != '') {
if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['negative'], $matches)) {
$keys .= ' -' . implode(' -', $matches[1]);
}
}
if ($form_state['values']['phrase'] != '') {
$keys .= ' "' . str_replace('"', ' ', $form_state['values']['phrase']) . '"';
}
if (!empty($keys)) {
form_set_value($form['basic']['processed_keys'], trim($keys), $form_state);
}
}
/**
* 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_theme().
*/
function file_entity_theme() {
return array(
'file' => array(
'render element' => 'elements',
'template' => 'file',
),
'file_entity_search_admin' => array(
'render element' => 'form',
),
'file_entity_file_type_overview' => array(
'variables' => array('label' => NULL, 'description' => NULL),
'file' => 'file_entity.admin.inc',
),
'file_entity_file_display_order' => array(
'render element' => 'element',
'file' => 'file_entity.admin.inc',
),
'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, 'icon_directory' => NULL, 'text' => NULL),
'file' => 'file_entity.theme.inc',
),
'file_entity_file_audio' => array(
'variables' => array(
'files' => array(),
'controls' => TRUE,
'autoplay' => FALSE,
'loop' => FALSE,
),
'file' => 'file_entity.theme.inc',
),
'file_entity_file_video' => array(
'variables' => array(
'files' => array(),
'controls' => TRUE,
'autoplay' => FALSE,
'loop' => FALSE,
'muted' => FALSE,
'width' => NULL,
'height' => NULL,
),
'file' => 'file_entity.theme.inc',
),
);
}
/**
* 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('fieldable', TRUE)
->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('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')
->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,
);*/
// Search integration is provided by file_entity.module, so search-related
// view modes for files are defined here and not in search.module.
/*if (module_exists('search')) {
$entity_types['file']['view modes']['search_index'] = array(
'label' => t('Search index'),
'custom settings' => FALSE,
);
$entity_types['file']['view modes']['search_result'] = array(
'label' => t('Search result'),
'custom settings' => FALSE,
);
}*/
// Enable Metatag support.
//$entity_types['file']['metatags'] = TRUE;
}
/**
* Implements hook_field_display_ENTITY_TYPE_alter().
*/
function file_entity_field_display_file_alter(&$display, $context) {
// Hide field labels in search index.
if ($context['view_mode'] == 'search_index') {
$display['label'] = 'hidden';
}
}
/**
* Entity API callback to get the form of a file entity.
*/
function file_entity_metadata_form_file($file) {
// Pre-populate the form-state with the right form include.
$form_state['build_info']['args'] = array($file);
form_load_include($form_state, 'inc', 'file_entity', 'file_entity.pages');
return drupal_build_form('file_entity_edit', $form_state);
}
/**
* Implements hook_ctools_plugin_directory().
*/
function file_entity_ctools_plugin_directory($module, $type) {
if ($module == 'ctools' && $type == 'content_types') {
return 'plugins/' . $type;
}
}
/**
* Implements hook_file_formatter_info().
*/
function file_entity_file_formatter_info() {
$formatters = array();
// Allow file field formatters to be reused for displaying the file entity's
// file pseudo-field.
foreach (field_info_formatter_types() as $key => $formatter) {
if (array_intersect($formatter['field types'], array('file', 'image'))) {
$key = 'file_field_' . $key;
$formatters[$key] = array(
'label' => $formatter['label'],
'description' => !empty($formatter['description']) ? $formatter['description'] : '',
'view callback' => 'file_entity_file_formatter_file_field_view',
);
if (!empty($formatter['settings'])) {
$formatters[$key] += array(
'default settings' => $formatter['settings'],
'settings callback' => 'file_entity_file_formatter_file_field_settings',
);
}
if (!empty($formatter['file formatter'])) {
$formatters[$key] += $formatter['file formatter'];
}
}
}
// Add a simple file formatter for displaying an image in a chosen style.
if (\Drupal::moduleHandler()->moduleExists('image')) {
$formatters['file_image'] = array(
'label' => t('Image'),
'default settings' => array(
'image_style' => '',
'alt' => '[file:field_file_image_alt_text]',
'title' => '[file:field_file_image_title_text]'
),
'view callback' => 'file_entity_file_formatter_file_image_view',
'settings callback' => 'file_entity_file_formatter_file_image_settings',
'hidden' => TRUE,
'mime types' => array('image/*'),
);
}
return $formatters;
}
/**
* Implements hook_file_formatter_FORMATTER_view().
*
* This function provides a bridge to the field formatter API, so that file
* field formatters can be reused for displaying the file entity's file
* pseudo-field.
*/
function file_entity_file_formatter_file_field_view($file, $display, $langcode) {
if (strpos($display['type'], 'file_field_') === 0) {
$field_formatter_type = substr($display['type'], strlen('file_field_'));
$field_formatter_info = field_info_formatter_types($field_formatter_type);
if (isset($field_formatter_info['module'])) {
// Set $display['type'] to what hook_field_formatter_*() expects.
$display['type'] = $field_formatter_type;
// Set $items to what file field formatters expect. See file_field_load(),
// and note that, here, $file is already a fully loaded entity.
$items = array((array) $file);
// Invoke hook_field_formatter_prepare_view() and
// hook_field_formatter_view(). Note that we are reusing field formatter
// functions, but we are not displaying a Field API field, so we set
// $field and $instance accordingly, and do not invoke
// hook_field_prepare_view(). This assumes that the formatter functions do
// not rely on $field or $instance. A module that implements formatter
// functions that rely on $field or $instance (and therefore, can only be
// used for real fields) can prevent this formatter from being used on the
// pseudo-field by removing it within hook_file_formatter_info_alter().
$field = $instance = NULL;
if (($function = ($field_formatter_info['module'] . '_field_formatter_prepare_view')) && function_exists($function)) {
$fid = $file->fid;
// hook_field_formatter_prepare_view() alters $items by reference.
$grouped_items = array($fid => &$items);
$function('file', array($fid => $file), $field, array($fid => $instance), $langcode, $grouped_items, array($fid => $display));
}
if (($function = ($field_formatter_info['module'] . '_field_formatter_view')) && function_exists($function)) {
$element = $function('file', $file, $field, $instance, $langcode, $items, $display);
// We passed the file as $items[0], so return the corresponding element.
if (isset($element[0])) {
return $element[0];
}
}
}
}
}
/**
* Implements hook_file_formatter_FORMATTER_settings().
*
* This function provides a bridge to the field formatter API, so that file
* field formatters can be reused for displaying the file entity's file
* pseudo-field.
*/
function file_entity_file_formatter_file_field_settings($form, &$form_state, $settings, $formatter_type, $file_type, $view_mode) {
if (strpos($formatter_type, 'file_field_') === 0) {
$field_formatter_type = substr($formatter_type, strlen('file_field_'));
$field_formatter_info = field_info_formatter_types($field_formatter_type);
// Invoke hook_field_formatter_settings_form(). We are reusing field
// formatter functions, but we are not working with a Field API field, so
// set $field accordingly. Unfortunately, the API is for $settings to be
// transfered via the $instance parameter, so we must mock it.
if (isset($field_formatter_info['module']) && ($function = ($field_formatter_info['module'] . '_field_formatter_settings_form')) && function_exists($function)) {
$field = NULL;
$mock_instance = array(
'display' => array(
$view_mode => array(
'type' => $field_formatter_type,
'settings' => $settings,
),
),
'entity_type' => 'file',
'bundle' => $file_type,
);
return $function($field, $mock_instance, $view_mode, $form, $form_state);
}
}
}
/**
* Implements hook_file_formatter_FORMATTER_view().
*
* Returns a drupal_render() array to display an image of the chosen style.
*
* This formatter is only capable of displaying local images. If the passed in
* file is either not local or not an image, nothing is returned, so that
* file_view_file() can try another formatter.
*/
function file_entity_file_formatter_file_image_view($file, $display, $langcode) {
// Prevent PHP notices when trying to read empty files.
// @see http://drupal.org/node/681042
if (!$file->filesize) {
return;
}
// Do not bother proceeding if this file does not have an image mime type.
if (file_entity_file_get_mimetype_type($file) != 'image') {
return;
}
if (file_entity_file_is_readable($file)) {
// We don't sanitize here.
// @see http://drupal.org/node/1553094#comment-6257382
// Theme function will take care of escaping.
if (!isset($file->metadata)) {
$file->metadata = array();
}
$file->metadata += array('width' => NULL, 'height' => NULL);
$replace_options = array(
'clear' => TRUE,
'sanitize' => FALSE,
);
if (!empty($display['settings']['image_style'])) {
$element = array(
'#theme' => 'image_style',
'#style_name' => $display['settings']['image_style'],
'#path' => $file->uri,
'#width' => isset($file->override['attributes']['width']) ? $file->override['attributes']['width'] : $file->metadata['width'],
'#height' => isset($file->override['attributes']['height']) ? $file->override['attributes']['height'] : $file->metadata['height'],
'#alt' => token_replace($display['settings']['alt'], array('file' => $file), $replace_options),
'#title' => token_replace($display['settings']['title'], array('file' => $file), $replace_options),
);
}
else {
$element = array(
'#theme' => 'image',
'#path' => $file->uri,
'#width' => isset($file->override['attributes']['width']) ? $file->override['attributes']['width'] : $file->metadata['width'],
'#height' => isset($file->override['attributes']['height']) ? $file->override['attributes']['height'] : $file->metadata['height'],
'#alt' => token_replace($display['settings']['alt'], array('file' => $file), $replace_options),
'#title' => token_replace($display['settings']['title'], array('file' => $file), $replace_options),
);
}
return $element;
}
}
/**
* Check if a file entity is readable or not.
*
* @param object $file
* A file entity object from file_load().
*
* @return boolean
* TRUE if the file is using a readable stream wrapper, or FALSE otherwise.
*/
function file_entity_file_is_readable($file) {
$scheme = file_uri_scheme($file->uri);
$wrappers = \Drupal::service('stream_wrapper_manager')->getWrappers(StreamWrapperInterface::READ);
return !empty($wrappers[$scheme]);
}
/**
* Implements hook_file_formatter_FORMATTER_settings().
*
* Returns form elements for configuring the 'file_image' formatter.
*/
function file_entity_file_formatter_file_image_settings($form, &$form_state, $settings) {
$element = array();
$element['image_style'] = array(
'#title' => t('Image style'),
'#type' => 'select',
'#options' => image_style_options(FALSE),
'#default_value' => $settings['image_style'],
'#empty_option' => t('None (original image)'),
);
// For image files we allow the alt attribute (required in HTML).
$element['alt'] = array(
'#title' => t('Alt attribute'),
'#description' => t('The text to use as value for the <em>img</em> tag <em>alt</em> attribute.'),
'#type' => 'textfield',
'#default_value' => $settings['alt'],
);
// Allow the setting of the title attribute.
$element['title'] = array(
'#title' => t('Title attribute'),
'#description' => t('The text to use as value for the <em>img</em> tag <em>title</em> attribute.'),
'#type' => 'textfield',
'#default_value' => $settings['title'],
);
if (\Drupal::moduleHandler()->moduleExists('token')) {
$element['alt']['#description'] .= t('This field supports tokens.');
$element['title']['#description'] .= t('This field supports tokens.');
$element['tokens'] = array(
'#theme' => 'token_tree',
'#token_types' => array('file'),
'#dialog' => TRUE,
);
}
return $element;
}
/**
* Menu access callback for the 'view mode file display settings' pages.
*
* Based on _field_ui_view_mode_menu_access(), but the Field UI module might not
* be enabled.
*/
function _file_entity_view_mode_menu_access($file_type, $view_mode, $access_callback) {
// Deny access if the view mode isn't configured to use custom display
// settings.
$view_mode_settings = field_view_mode_settings('file', $file_type->type);
$visibility = ($view_mode == 'default') || !empty($view_mode_settings[$view_mode]['custom_settings']);
if (!$visibility) {
return FALSE;
}
// Otherwise, continue to an $access_callback check.
$args = array_slice(func_get_args(), 3);
$callback = empty($access_callback) ? 0 : trim($access_callback);
if (is_numeric($callback)) {
return (bool) $callback;
}
elseif (function_exists($access_callback)) {
return call_user_func_array($access_callback, $args);
}
}
/**
* Implements hook_modules_enabled().
*/
function file_entity_modules_enabled($modules) {
file_info_cache_clear();
}
/**
* Implements hook_modules_disabled().
*/
function file_entity_modules_disabled($modules) {
file_info_cache_clear();
}