forked from ec-europa/rdf_entity
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rdf_entity.module
executable file
·591 lines (532 loc) · 20.2 KB
/
rdf_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
<?php
/**
* @file
* Main functions and hook implementations of the RDF Entity module.
*/
declare(strict_types = 1);
use Drupal\Core\Config\Entity\ConfigEntityBundleBase;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Database\Database;
use Drupal\Core\Entity\BundleEntityFormBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Url;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\FieldStorageConfigInterface;
use Drupal\rdf_entity\Entity\RdfEntityMapping;
use Drupal\rdf_entity\Entity\RdfEntitySparqlStorage;
use Drupal\rdf_entity\RdfEntityGraphInterface;
use Drupal\rdf_entity\RdfFieldHandler;
use Drupal\rdf_entity\RdfInterface;
use EasyRdf\Http;
/**
* Implements hook_entity_base_field_info_alter().
*/
function rdf_entity_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
if (!(\Drupal::entityManager()->getStorage($entity_type->id()) instanceof RdfEntitySparqlStorage)) {
return;
}
$fields['graph'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('The graph where the entity is stored.'))
->setTargetEntityTypeId('rdf_entity')
->setName('graph')
->setComputed(TRUE)
->setSetting('target_type', 'rdf_entity_graph');
}
/**
* Implements hook_entity_type_alter().
*/
function rdf_entity_entity_type_alter(array &$entity_types) {
if (isset($entity_types['field_storage_config'])) {
// Swap out the field storage settings form.
$entity_types['field_storage_config']->setFormClass('edit', '\Drupal\rdf_entity\Form\RdfFieldStorageConfigEditForm');
}
}
/**
* Implements hook_form_alter().
*/
function rdf_entity_form_field_storage_config_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Only add mapping form element to fields of entities implementing
// RdfEntitySparqlStorage.
$id = $form_state->get('entity_type_id');
if (!$id) {
return;
}
$storage = \Drupal::entityManager()->getStorage($id);
if (!$storage instanceof RdfEntitySparqlStorage) {
return;
}
$form_obj = $form_state->getFormObject();
/** @var \Drupal\field\Entity\FieldStorageConfig $entity */
$entity = $form_obj->getEntity();
$schema = $entity->getSchema();
$form['rdf_mapping'] = [
'#type' => 'details',
'#title' => t('Rdf field mapping'),
'#description' => t('This field uses a Sparql backend. Please map the fields to their corresponding rdf properties.'),
'#weight' => 99,
];
$form_state->set('rdf_mapping_columns', array_keys($schema['columns']));
foreach ($schema['columns'] as $column => $column_desc) {
$description = isset($column_desc['description']) ? $column_desc['description'] . "<br>" : '';
foreach (['type', 'length', 'size', 'serialize'] as $key) {
if (!empty($column_desc[$key])) {
$description .= '<strong>' . $key . "</strong>: " . $column_desc[$key] . ' ';
}
}
$settings = rdf_entity_get_mapping_property($entity, 'mapping', $column);
$form['rdf_mapping'][$column] = [
'#type' => 'details',
'#title' => $column,
'#description' => $description,
];
$form['rdf_mapping'][$column]['predicate_' . $column] = [
'#type' => 'url',
'#title' => t('Mapping'),
'#weight' => 150,
'#default_value' => isset($settings['predicate']) ? $settings['predicate'] : '',
];
$form['rdf_mapping'][$column]['format_' . $column] = [
'#type' => 'select',
'#title' => t('Value format'),
'#options' => RdfFieldHandler::getSupportedDataTypes(),
'#empty_value' => 'no_format',
'#weight' => 151,
'#default_value' => isset($settings['format']) ? $settings['format'] : NULL,
];
}
$form['#entity_builders'][] = 'rdf_entity_form_alter_builder';
$form['#validate'][] = 'rdf_entity_field_storage_form_validate';
}
/**
* Validation callback for the field storage form.
*
* @param array $form
* Form definition.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*/
function rdf_entity_field_storage_form_validate(array &$form, FormStateInterface $form_state) {
$cardinality = (int) $form_state->getValue('cardinality_number');
if ($cardinality < 2 && (int) $form_state->getValue('cardinality') !== FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
return;
}
$columns = $form_state->get('rdf_mapping_columns');
// We can only have 1 predicate mapped if the cardinality is higher than 1.
$predicate_count = 0;
foreach ($columns as $column) {
$predicate = $form_state->getValue('predicate_' . $column);
if ($predicate) {
$predicate_count++;
}
if ($predicate_count > 1) {
$form_state->setErrorByName('rdf_mapping', t('Multiple RDF mapping predicates are not supported with a field cardinality higher than 1.'));
break;
}
}
}
/**
* Retrieve nested third party settings from object.
*
* @param \Drupal\Core\Config\Entity\ConfigEntityInterface $object
* The object may be either a bundle entity or a field storage config entity.
* @param string $property
* The property for which to retrieve the mapping.
* @param string $column
* The field column.
* @param mixed $default
* (optional) The default value. Defaults to NULL.
*
* @return mixed
* The mapping.
*
* @todo Move this to a service (or to RDF storage?)
*/
function rdf_entity_get_mapping_property(ConfigEntityInterface $object, string $property, string $column, $default = NULL) {
// Mapping data requested for a configurable field.
if ($object instanceof FieldStorageConfigInterface) {
$property_value = $object->getThirdPartySetting('rdf_entity', $property, FALSE);
}
// Mapping data requested for a bundle entity.
else {
$entity_type_id = $object->getEntityType()->getBundleOf();
$bundle = $object->id();
$mapping = RdfEntityMapping::loadByName($entity_type_id, $bundle);
$property_value = $mapping->get($property) ?: FALSE;
}
if (!is_array($property_value) || !isset($property_value[$column])) {
return $default;
}
return $property_value[$column];
}
/**
* Entity builder callback: Save rdf field mapping.
*/
function rdf_entity_form_alter_builder($entity_type, FieldStorageConfig $entity, array &$form, FormStateInterface $form_state) {
$schema = $entity->getSchema();
$data = [];
foreach ($schema['columns'] as $column => $column_desc) {
$data[$column]['predicate'] = $form_state->getValue('predicate_' . $column);
$data[$column]['format'] = $form_state->getValue('format_' . $column);
}
$entity->setThirdPartySetting('rdf_entity', 'mapping', $data);
}
/**
* Implements hook_form_alter().
*
* Configurations for the RDF entity bundle.
*/
function rdf_entity_form_alter(&$form, FormStateInterface $form_state) {
$form_object = $form_state->getFormObject();
if (!$form_object instanceof BundleEntityFormBase) {
return;
}
/** @var \Drupal\Core\Config\Entity\ConfigEntityBundleBase $bundle_entity */
$bundle_entity = $form_object->getEntity();
if (!$bundle_entity instanceof ConfigEntityBundleBase) {
return;
}
$entity_type_id = $bundle_entity->getEntityType()->getBundleOf();
$form_state->set('entity_type_id', $entity_type_id);
/** @var \Drupal\rdf_entity\Entity\RdfEntitySparqlStorage $storage */
$storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);
if (!$storage instanceof RdfEntitySparqlStorage) {
return;
}
$base_fields = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions($entity_type_id);
$id_key = $storage->getEntityType()->getKey('id');
$form_state->set('bundle_id_key', $storage->getEntityType()->getKey('bundle'));
$form['rdf_entity'] = [
'#type' => 'details',
'#title' => t('RDF Entity'),
'#description' => t('RDF entity configurations.'),
'#open' => TRUE,
'#weight' => 99,
'#tree' => TRUE,
];
// When creating a new bundle we can't yet use it for creating a mapping. In
// this case we defer to the custom submit handler.
$mapping = NULL;
if (!$bundle_entity->isNew()) {
$mapping = RdfEntityMapping::loadByName($entity_type_id, $bundle_entity->id());
if (!$mapping) {
$mapping = RdfEntityMapping::create([
'entity_type_id' => $entity_type_id,
'bundle' => !$bundle_entity->isNew() ? $bundle_entity->id() : NULL,
]);
}
$form_state->set('rdf_entity_mapping', $mapping);
}
$form['rdf_entity']['rdf_type'] = [
'#type' => 'textfield',
'#title' => t('RDF type mapping'),
'#default_value' => $mapping ? $mapping->getRdfType() : NULL,
];
/** @var \Drupal\rdf_entity\RdfEntityIdPluginManager $id_plugin_manager */
$id_plugin_manager = \Drupal::service('plugin.manager.rdf_entity.id');
$plugins = array_map(function (array $definition) use ($id_plugin_manager) {
return $definition['name'];
}, $id_plugin_manager->getDefinitions());
$form['rdf_entity']['entity_id_plugin'] = [
'#type' => 'select',
'#title' => t('Entity ID generator'),
'#description' => t("The generator used to create IDs for new entities."),
'#options' => $plugins,
'#default_value' => $mapping && $mapping->getEntityIdPlugin() ? $mapping->getEntityIdPlugin() : $id_plugin_manager->getFallbackPluginId(NULL),
];
$form['rdf_entity']['graph'] = [
'#type' => 'details',
'#title' => t('Graphs'),
'#description' => t('Graph URI mapping'),
];
foreach ($storage->getGraphDefinitions() as $graph_id => $graph) {
$form['rdf_entity']['graph'][$graph_id] = [
'#type' => 'url',
'#title' => t('@title (@id)', ['@title' => $graph['title'], '@id' => $graph_id]),
'#description' => $graph['description'],
'#default_value' => $mapping ? $mapping->getGraphUri($graph_id) : NULL,
'#required' => $graph_id === RdfEntityGraphInterface::DEFAULT,
];
}
$form['rdf_entity']['base_fields_mapping'] = [
'#type' => 'details',
'#title' => t('Field mapping'),
'#description' => t('This entity type uses a Sparql backend. Please map the bundle base fields to their corresponding RDF properties.'),
];
/** @var \Drupal\Core\Field\BaseFieldDefinition $base_field */
foreach ($base_fields as $field_name => $base_field) {
// The entity id doesn't need a mapping as it's the subject of the triple.
if ($field_name === $id_key) {
continue;
}
$columns = $base_field->getColumns();
foreach ($columns as $column_name => $column) {
$title = $base_field->getLabel();
if (count($columns) > 1) {
$title .= ' (' . $column_name . ')';
}
$form['rdf_entity']['base_fields_mapping'][$field_name] = [
'#type' => 'details',
'#title' => $title,
'#description' => $base_field->getDescription(),
];
$form['rdf_entity']['base_fields_mapping'][$field_name][$column_name]['predicate'] = [
'#type' => 'url',
'#title' => t('Mapping'),
'#description' => t('The rdf predicate.'),
'#weight' => 150,
'#default_value' => $mapping ? $mapping->getMapping($field_name, $column_name)['predicate'] : NULL,
];
$form['rdf_entity']['base_fields_mapping'][$field_name][$column_name]['format'] = [
'#type' => 'select',
'#title' => t('Value format'),
'#description' => t('The rdf format. Required if format is filled.'),
'#options' => RdfFieldHandler::getSupportedDataTypes(),
'#empty_value' => '',
'#weight' => 151,
'#default_value' => $mapping ? $mapping->getMapping($field_name, $column_name)['format'] : NULL,
];
}
}
$form['actions']['submit']['#submit'][] = 'rdf_entity_type_mapping_submit';
}
/**
* Stores the mapping of base fields and RDF properties.
*
* @param array $form
* The form API form render array.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state object.
*
* @throws \Exception
* If the mapping fails to save.
*
* @see rdf_entity_form_alter()
*/
function rdf_entity_type_mapping_submit(array &$form, FormStateInterface $form_state): void {
$values = $form_state->getValue('rdf_entity');
/** @var \Drupal\rdf_entity\RdfEntityMappingInterface $mapping */
$mapping = $form_state->get('rdf_entity_mapping');
if (!$mapping) {
/** @var \Drupal\rdf_entity\RdfEntityTypeInterface $entity */
$bundle_entity = $form_state->getFormObject()->getEntity();
$mapping = RdfEntityMapping::create([
'entity_type_id' => $bundle_entity->getEntityType()->getBundleOf() ,
'bundle' => $form_state->getFormObject()->getEntity()->id(),
]);
}
$mapping
->setRdfType($values['rdf_type'])
->setEntityIdPlugin($values['entity_id_plugin'])
// Add only non-empty values.
->setGraphs(array_filter($values['graph']))
->setMappings($values['base_fields_mapping'])
->save();
}
/**
* Implements hook_theme().
*/
function rdf_entity_theme() {
return [
'rdf_entity' => [
'render element' => 'elements',
],
'rdf_add_list' => [
'variables' => ['content' => NULL],
],
];
}
/**
* Prepares variables for rdf entity templates.
*
* Default template: rdf-entity.html.twig.
*
* Themes should use their own copy of rdf-entity.html.twig.
* The default is located inside "templates/rdf-entity.html.twig".
*
* @param array $variables
* An associative array containing:
* - elements: An array of elements to display in view mode.
* - rdf_entity: The rdf_entity object.
* - view_mode: View mode; e.g., 'full', 'teaser', etc.
*/
function template_preprocess_rdf_entity(array &$variables) {
$variables['view_mode'] = $variables['elements']['#view_mode'];
// Provide a distinct $teaser boolean.
$variables['teaser'] = $variables['view_mode'] == 'teaser';
$variables['rdf_entity'] = $variables['elements']['#rdf_entity'];
/** @var \Drupal\rdf_entity\RdfInterface $rdf_entity */
$rdf_entity = $variables['rdf_entity'];
$variables['date'] = drupal_render($variables['elements']['created']);
unset($variables['elements']['created']);
$variables['author_name'] = drupal_render($variables['elements']['uid']);
unset($variables['elements']['uid']);
$variables['url'] = $rdf_entity->url('canonical', [
'language' => $rdf_entity->language(),
]);
$variables['label'] = !empty($variables['elements']['label']) ? $variables['elements']['label'] : ['#markup' => $rdf_entity->label()];
unset($variables['elements']['label']);
// The view mode is 'full' and we are on the 'rdf_entity.view' route.
$variables['page'] = ($variables['view_mode'] == 'full' && (rdf_entity_is_page($rdf_entity)));
// Helpful $content variable for templates.
$variables += ['content' => []];
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
// Add article ARIA role.
$variables['attributes']['role'] = 'article';
}
/**
* Prepares variables for list of available rdf type templates.
*
* Default template: rdf-add-list.html.twig.
*
* @param array $variables
* An associative array containing:
* - content: An array of rdf bundles.
*/
function template_preprocess_rdf_add_list(array &$variables) {
$variables['types'] = [];
if (!empty($variables['content'])) {
foreach ($variables['content'] as $type) {
$variables['types'][$type->id()] = [
'type' => $type->id(),
'add_link' => \Drupal::l($type->label(), new Url('rdf_entity.rdf_add', ['rdf_type' => $type->id()])),
'description' => [
'#markup' => $type->getDescription(),
],
];
}
}
}
/**
* Is the current page the full page view of the passed-in RDF entity?
*
* @param \Drupal\rdf_entity\RdfInterface $rdf_entity
* An RDF entity.
*
* @return int|false
* The ID of the RDF entity if this is a full page view, otherwise FALSE.
*/
function rdf_entity_is_page(RdfInterface $rdf_entity) {
$route_match = \Drupal::routeMatch();
if ($route_match->getRouteName() == 'entity.rdf_entity.canonical') {
$page_rdf_entity = $route_match->getParameter('rdf_entity');
}
return (!empty($page_rdf_entity) ? $page_rdf_entity->id() == $rdf_entity->id() : FALSE);
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function rdf_entity_theme_suggestions_rdf_entity(array $variables) {
$suggestions = [];
$rdf_entity = $variables['elements']['#rdf_entity'];
$sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
$suggestions[] = 'rdf_entity__' . $sanitized_view_mode;
$suggestions[] = 'rdf_entity__' . $rdf_entity->bundle();
$suggestions[] = 'rdf_entity__' . $rdf_entity->bundle() . '__' . $sanitized_view_mode;
$suggestions[] = 'rdf_entity__' . $rdf_entity->id();
$suggestions[] = 'rdf_entity__' . $rdf_entity->id() . '__' . $sanitized_view_mode;
return $suggestions;
}
/**
* Returns the requirements related to virtuoso version.
*
* @return array
* The virtuoso version requirements.
*/
function rdf_entity_virtuoso_version_requirements() {
$minimum_version = '07.00.0000';
$requirements = [
'rdf_entity_endpoint' => [
'title' => t('Virtuoso endpoint availability'),
'description' => t('Virtuoso endpoint is available.'),
],
'rdf_entity_virtuoso_version' => [
'title' => t('Virtuoso version'),
'description' => t('Virtuoso version meets minimum requirements.'),
],
];
/** @var \Drupal\rdf_entity\Database\Driver\sparql\ConnectionInterface $connection */
$connection = Database::getConnection('default', 'sparql_default');
$client = Http::getDefaultHttpClient();
$client->resetParameters(TRUE);
$client->setUri($connection->getQueryUri());
$client->setMethod('GET');
try {
$response = $client->request();
}
catch (Exception $e) {
// If the endpoint could not be reached, return early.
$requirements['rdf_entity_endpoint']['description'] = t('Virtuoso endpoint could not be reached.');
$requirements['rdf_entity_endpoint']['severity'] = REQUIREMENT_ERROR;
return $requirements;
}
$server_header = $response->getHeader('Server');
preg_match('/Virtuoso\/(.*?)\s/', $server_header, $matches);
$version = (is_array($matches) && count($matches) === 2) ? $matches[1] : [];
if (version_compare($version, $minimum_version, 'lt')) {
$description = t('The minimum virtuoso version supported is :version', [
':version' => $minimum_version,
]);
$requirements['rdf_entity_virtuoso_version']['description'] = $description;
$requirements['rdf_entity_virtuoso_version']['severity'] = REQUIREMENT_ERROR;
$requirements['rdf_entity_virtuoso_version']['value'] = $version;
}
return $requirements;
}
/**
* Returns the requirements related to virtuoso query permissions.
*
* Since there is no direct way to draw information from the virtuoso instance
* the function simply tries to create a triple in a random graph and then
* delete the whole graph.
*
* @return array
* The virtuoso query requirements.
*/
function rdf_entity_virtuoso_permission_requirements() {
$rand = random_int(10000, 50000);
$uri = 'http://example.com/id/rdf_entity_' . $rand;
$query = <<<QUERY
WITH <{$uri}>
INSERT { <{$uri}> <http://example.com/predicate> "test value" }
CLEAR GRAPH <{$uri}>
QUERY;
/** @var \Drupal\rdf_entity\Database\Driver\sparql\ConnectionInterface $connection */
$connection = Database::getConnection('default', 'sparql_default');
$requirements = [
'rdf_entity_virtuoso_query' => [
'title' => t('Virtuoso permissions'),
'description' => t('Virtuoso update/delete permissions are properly set.'),
'value' => $query,
],
];
try {
$connection->query($query);
}
catch (Exception $e) {
$requirements['rdf_entity_virtuoso_query']['description'] = $e->getMessage();
$requirements['rdf_entity_virtuoso_query']['severity'] = REQUIREMENT_ERROR;
}
return $requirements;
}
/**
* Implements hook_pathauto_alias_types_alter().
*/
function rdf_entity_pathauto_alias_types_alter(array &$definitions) {
// Remove the automatically generated Pathauto alias type, we offer our own
// alias type.
// @see \Drupal\pathauto\Plugin\Deriver\EntityAliasTypeDeriver::getDerivativeDefinitions()
// @see \Drupal\rdf_entity\Plugin\pathauto\AliasType\RdfEntityAliasType
unset($definitions['canonical_entities:rdf_entity']);
}
/**
* Implements hook_cache_flush().
*/
function rdf_entity_cache_flush() {
\Drupal::service('sparql.graph_handler')->clearCache();
}