-
Notifications
You must be signed in to change notification settings - Fork 5
/
strawberryfield.module
378 lines (351 loc) · 15.4 KB
/
strawberryfield.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
<?php
/**
* @file
* Contains strawberryfield.module.
*/
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Render\Markup;
use Drupal\strawberryfield\Event\StrawberryfieldCrudEvent;
use Drupal\strawberryfield\StrawberryfieldEventType;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\strawberryfield\Field\StrawberryFieldFileComputedItemList;
use Drupal\strawberryfield\Field\StrawberryFieldEntityComputedItemList;
use Drupal\strawberryfield\StrawberryfieldRenderCallbacks;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\NodeInterface;
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function strawberryfield_node_presave(ContentEntityInterface $entity) {
if ($sbf_fields = \Drupal::service('strawberryfield.utility')->bearsStrawberryfield($entity)) {
$config = \Drupal::config('strawberryfield.general');
$bench = FALSE;
// When benchmark is enabled a simple but effective report will be found in
// the reports/logs.
if ($config->get('benchmark')) {
$bench = TRUE;
$start_time = microtime(true);
}
// Introducing our newest development, the processing time stats!
// Starting on PHP 7.3 we should use hrtime for docker and VMS.
// https://www.php.net/manual/en/function.microtime.php
// @TODO make bench simply an Event Method! That way we can measure every
// event by calling it and for new ones. Etc.
$event_type = StrawberryfieldEventType::PRESAVE;
$event = new StrawberryfieldCrudEvent($event_type, $entity, $sbf_fields);
\Drupal::service('event_dispatcher')->dispatch($event, $event_type);
if ($bench) {
$end_time = microtime(TRUE);
// Removed bsuc.
$time = round($end_time - $start_time, 4);
$max_memory = memory_get_peak_usage(TRUE);
$events = '';
foreach ($event->getProcessedBy() as $event_info) {
$success = $event_info['success'] ? 'Successful' : 'Failure';
$events .= '<li>' . $event_info['class'] . ' => ' . $success . '</li>';
}
\Drupal::logger('strawberryfield')->notice(
'ADO with UUID @uuid spent @time seconds on all presave event subscriber processing and max memory usage was @maxmem. <br> Event Subscribers that could run were the following: <br><ul>@events</ul>',
[
'@uuid' => $entity->uuid(),
'@time' => $time,
'@maxmem' => \Drupal::service('strawberryfield.utility')->formatBytes($max_memory, 2),
'@events' => Markup::create($events),
]
);
}
}
}
/**
* Implements hook_ENTITY_TYPE_update().
*/
function strawberryfield_node_update(ContentEntityInterface $entity) {
if ($sbf_fields = \Drupal::service('strawberryfield.utility')->bearsStrawberryfield($entity)) {
$event_type = StrawberryfieldEventType::SAVE;
$event = new StrawberryfieldCrudEvent($event_type, $entity, $sbf_fields);
\Drupal::service('event_dispatcher')->dispatch($event, $event_type);
}
}
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function strawberryfield_node_insert(ContentEntityInterface $entity) {
// @TODO move this to an event subscriber.
strawberryfield_invalidate_fieldefinition_caches($entity);
if ($sbf_fields = \Drupal::service('strawberryfield.utility')->bearsStrawberryfield($entity)) {
$event_type = StrawberryfieldEventType::INSERT;
$event = new StrawberryfieldCrudEvent($event_type, $entity, $sbf_fields);
\Drupal::service('event_dispatcher')->dispatch($event, $event_type);
// @TODO use updated $event object to debug things if an event failed.
// via $event->getProcessedBy();
}
}
/**
* Implements hook_ENTITY_TYPE_revision_create().
*/
function strawberryfield_node_revision_create(ContentEntityInterface $new_revision, ContentEntityInterface $entity, $keep_untranslatable_fields) {
if ($sbf_fields = \Drupal::service('strawberryfield.utility')->bearsStrawberryfield($entity)) {
$event_type = StrawberryfieldEventType::NEW_REVISION;
$event = new StrawberryfieldCrudEvent($event_type, $new_revision, $sbf_fields);
\Drupal::service('event_dispatcher')->dispatch($event, $event_type);
}
}
/**
* Implements hook_ENTITY_TYPE_delete().
*/
function strawberryfield_node_delete(ContentEntityInterface $entity) {
if ($sbf_fields = \Drupal::service('strawberryfield.utility')->bearsStrawberryfield($entity)) {
$event_type = StrawberryfieldEventType::DELETE;
$event = new StrawberryfieldCrudEvent($event_type, $entity, $sbf_fields);
\Drupal::service('event_dispatcher')->dispatch($event, $event_type);
}
}
/**
* Implements hook_ENTITY_TYPE_revision_delete().
*/
function strawberryfield_node_revision_delete(ContentEntityInterface $entity) {
if ($sbf_fields = \Drupal::service('strawberryfield.utility')->bearsStrawberryfield($entity)) {
$event_type = StrawberryfieldEventType::DELETE;
$event = new StrawberryfieldCrudEvent($event_type, $entity, $sbf_fields);
\Drupal::service('event_dispatcher')->dispatch($event, $event_type);
}
// @TODO move this to an event subscriber.
strawberryfield_invalidate_fieldefinition_caches($entity);
}
/**
* Invalidate the cache for strawberryfields field type defintions.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity to invalidate cache.
*/
function strawberryfield_invalidate_fieldefinition_caches(ContentEntityInterface $entity) {
// @TODO do the same for StrawberryfieldKeyNameProvider Plugins
if ($entity instanceof EntityPublishedInterface && $entity->isPublished() && $entity->isDefaultRevision()) {
$needscleaning = FALSE;
$strawberry_field_class = $class = \Drupal::service('plugin.manager.field.field_type')->getPluginClass('strawberryfield_field');
foreach ($entity->getFieldDefinitions() as $field) {
$class = $field->getItemDefinition()->getClass();
$is_ripe = ($class === $strawberry_field_class) || is_subclass_of($class, $strawberry_field_class);
if ($is_ripe) {
$needscleaning = TRUE;
}
}
if ($needscleaning) {
\Drupal::service('plugin.manager.field.field_type')->clearCachedDefinitions();
}
}
}
/**
* Implements hook_entity_base_field_info().
*/
function strawberryfield_entity_base_field_info(EntityTypeInterface $entity_type) {
if ($entity_type->id() != 'node') {
return [];
}
$scheme_options = \Drupal::service('stream_wrapper_manager')->getNames(StreamWrapperInterface::WRITE_VISIBLE);
if (isset($scheme_options['private'])) {
$schema = 'private';
}
elseif (isset($scheme_options['public'])) {
$schema = 'public';
}
else {
$schema = 'public';
}
$fields = [];
// Add a field that serves as a drop box for any entities that bear a SBF.
// @see https://www.drupal.org/project/drupal/issues/2346347
// (still WIP as June 2020)
// know why we can't use \Drupal\Core\Field\BaseFieldDefinition
// @TODO If we try to make this Bundle specific?
// @Update 20202: https://www.previousnext.com.au/blog/how-create-and-expose-computed-properties-rest-api-drupal-8
// Issue with that approach is we need to have a hook update for every
// bundle Which makes adding new bundles and attaching automagically super
// complex.
// @TODO future work on exposing other JSON properties as other REAL field types
// Dynamically can be achieved by creating a new Class extending
// BaseFieldDefinition.
// That manages without hickups the 'Bundle' option
// \Drupal\Core\Field\BaseFieldDefinition::setTargetBundle
$fields['field_file_drop'] = BaseFieldDefinition::create('entity_reference')
->setName('field_file_drop')
->setLabel(t('Drop Files'))
->setComputed(TRUE)
->setRevisionable(FALSE)
->setTranslatable(FALSE)
->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
->setReadOnly(FALSE)
->setTargetEntityTypeId($entity_type->id())
->setSettings(
[
'target_type' => 'file',
'file_directory' => 'sbf_tmp',
'uri_scheme' => $schema,
]
)
->setClass(StrawberryFieldFileComputedItemList::class)
->setDisplayConfigurable('view', FALSE)
->setDisplayConfigurable('form', FALSE);
// A computed field to store customly detected Node references from a SBF.
$fields['field_sbf_nodetonode'] = BaseFieldDefinition::create('entity_reference')
->setName('field_sbf_nodetonode')
->setLabel('Related ADOs')
->setSetting('target_type', 'node')
->setTargetEntityTypeId('node')
->setDescription(t('Computed Node to Node relationships'))
->setComputed(TRUE)
->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
->setRevisionable(FALSE)
->setReadOnly(TRUE)
->setTranslatable(FALSE)
->setClass(StrawberryFieldEntityComputedItemList::class);
return $fields;
}
/**
* Implements hook_entity_bundle_field_info().
*/
function strawberryfield_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
// This is a good workaround for ISSUE-86
// Will basically attach the base field as a bundled one and by doing so
// Allow our bundle based permissions to be evaluated.
if (($entity_type->id() == 'node') && isset($base_field_definitions['field_file_drop'])) {
if (\Drupal::service('strawberryfield.utility')->bundleHasStrawberryfield($bundle)) {
// Add the target bundle to the field_file_drop base field
// only if it carries a Strawberryfield
// In practice this will allow Bundle specific create access permissions
// to work and force anything not Strawberryfield to either have the node
// access override or simply not work.
$base_field_definitions['field_file_drop']->setTargetBundle($bundle);
return [
'field_file_drop' => $base_field_definitions['field_file_drop'],
];
}
}
// Ask around. Do we need to expose this virtual creature the same way given
// that is its read only?
if (($entity_type->id() == 'node') && isset($base_field_definitions['field_sbf_nodetonode'])) {
if (\Drupal::service('strawberryfield.utility')
->bundleHasStrawberryfield($bundle)) {
// Add the target bundle to the field_file_drop base field
// only if it carries a Strawberryfield
// In practice this will allow Bundle specific create access permissions
// to work and force anything not Strawberryfield to either have the node
// access override or simply not work.
$base_field_definitions['field_sbf_nodetonode']->setTargetBundle($bundle);
return [
'field_sbf_nodetonode' => $base_field_definitions['field_sbf_nodetonode'],
];
}
}
}
/**
* Implements hook_entity_field_access().
*/
function strawberryfield_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
if ($field_definition->getName() == 'field_file_drop') {
return AccessResult::allowedIfHasPermission($account, 'upload to Digital Object file dropbox field');
}
return AccessResult::neutral();
}
/**
* Implements hook_file_mimetype_mapping_alter().
*/
function strawberryfield_file_mimetype_mapping_alter(&$mapping) {
// Add relevant Repository Mimetypes missing from D8.
$mapping['mimetypes']['json_mimetype'] = 'application/json';
$mapping['extensions']['json'] = 'json_mimetype';
$mapping['mimetypes']['jsonld_mimetype'] = 'application/ld+json';
$mapping['extensions']['jsonld'] = 'jsonld_mimetype';
$mapping['mimetypes']['jpeg2000_mimetype'] = 'image/jp2';
$mapping['extensions']['jp2'] = 'jpeg2000_mimetype';
$mapping['mimetypes']['fits_image_mimetype'] = 'image/fits';
// @see https://en.wikipedia.org/wiki/FITS
$mapping['extensions']['fits'] = 'fits_image_mimetype';
$mapping['extensions']['fit'] = 'fits_image_mimetype';
$mapping['extensions']['fts'] = 'fits_image_mimetype';
$mapping['extensions']['stl'] = 'stl_model_mimetype';
// @see https://www.iana.org/assignments/media-types/media-types.xhtml
$mapping['mimetypes']['stl_model_mimetype'] = 'model/stl';
// @ WACZ WIP.
$mapping['mimetypes']['wacz_mimetype'] = 'application/vnd.datapackage+zip';
$mapping['extensions']['wacz'] = 'wacz_mimetype';
}
/**
* Implements hook_s3fs_url_settings_alter().
*/
function strawberryfield_s3fs_url_settings_alter(array &$url_settings, $s3_file_path) {
// @TODO This is a soft dependency. Means if we have no s3fs module all good.
// Idea here is to allow in the future
// signed urls to be generated given a certain condition
// Or to force AWS S3 metatags to control maybe object lifecycle.
// if ($s3_file_path == 'myfile.jpg') {
// $url_settings['presigned_url'] = TRUE;
// $url_settings['timeout'] = 10;
// }
// An example of adding a custom GET argument to all S3 URLs that
// records the name of the currently logged in user.
// $account = Drupal::currentUser();
// $url_settings['custom_GET_args']['x-user'] = $account->getAccountName();
}
/**
* Implements hook_cron().
*/
function strawberryfield_cron() {
// @TODO: Drush calls to CRON do not release the background process? Wait
// For ever for the exec() to return, even if calling with nohup.
// @Giancarlobi.. not sure why. So this will only run if normal CRON/web based
// Is invoked but never with `drush cron`
if (PHP_SAPI != 'cli') {
\Drupal::getContainer()->get('strawberryfield.hydroponics')->run();
}
}
/**
* Implements hook_entity_view_alter().
*/
function strawberryfield_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
$excerpt_component = $display->getComponent('search_api_excerpt');
if ($excerpt_component !== NULL && $entity instanceof NodeInterface && $entity->view ?? NULL) {
if (\Drupal::request()->getMethod() == 'GET' ) {
// if mixing SQL/Search API (e.g the result row is rendered using a View that is not Search API
// But the listing is obviously an Search API view i can't trust that getQuery() will
// be driven by searchAPI, so might not have an index.
// @TODO. Review every call to ->getIndex() everywhere. Bc method is specific to that plugin (no interface)
if ($entity->view instanceof \Drupal\views\ViewExecutable) {
if ($entity->view->getQuery() instanceof \Drupal\search_api\Plugin\views\query\SearchApiQuery) {
// Check if the current index has lazy_excerpt enabled...
if ($processor = ($entity->view->getQuery()->getIndex()->getProcessors(
)['sbf_highlight'] ?? NULL)
) {
if ($processor->getConfiguration()['lazy_excerpt'] ?? NULL) {
$cid = 'entity:' . $entity->getEntityTypeId() . '/' . $entity->id()
. ':'
. $entity->language()->getId();
$build['search_api_excerpt'] = [
'#lazy_builder' => [
'strawberryfield.lazy_builders:renderExcerpt',
[$cid, 'node:'.$entity->id()]
],
'#create_placeholder' => TRUE,
];
}
}
}
}
}
}
}
/**
* Implements hook_element_info_alter().
*/
function strawberryfield_element_info_alter(array &$info): void {
array_unshift($info['view']['#pre_render'], 'Drupal\strawberryfield\StrawberryfieldRenderCallbacks::preRender');
}