-
Notifications
You must be signed in to change notification settings - Fork 0
/
triplestore_indexer.module
370 lines (327 loc) · 11.3 KB
/
triplestore_indexer.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
<?php
/**
* @file
* Contains triplestore_indexer.module.
*/
use Drupal\advancedqueue\Entity\Queue;
use Drupal\advancedqueue\Job;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\media\MediaInterface;
use Drupal\node\NodeInterface;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\TermInterface;
use GuzzleHttp\Exception\ClientException;
/**
* Implements hook_help().
*/
function triplestore_indexer_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
// Main module help for the triplestore_indexer module.
case 'help.page.triplestore_indexer':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('This module will listening to Content event and indexing it to RDF and send result to Triple store') . '</p>';
return $output;
default:
}
}
/**
* Implements hook_theme().
*/
function triplestore_indexer_theme() {
return [
'triplestore_indexer' => [
'render element' => 'children',
],
];
}
/**
* Implements hook_form_alter().
*/
function triplestore_indexer_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Matching the form id to node_[content_type]_delete_form.
// Adding validator only to the content type that is indexed.
if (preg_match('/^node_(.*)_delete_form$/', $form_id, $matches)) {
$originalId = $matches[1];
$entity_type_manager = \Drupal::service('entity_type.manager');
$content_types_list = $entity_type_manager->getStorage('node_type')->loadMultiple();
$content_types = [];
foreach ($content_types_list as $content_type) {
$content_types[] = $content_type->id();
}
if (in_array($originalId, $content_types)) {
$form['#validate'][] = 'triplestore_indexer_node_delete_form_validate';
}
}
}
/**
* Validation handler for node delete forms.
*/
function triplestore_indexer_node_delete_form_validate($form, FormStateInterface $form_state) {
global $base_url;
$node = $form_state->getFormObject()->getEntity();
$url = $node->toUrl()->toString();
$uri = $base_url . $url . '?_format=jsonld';
$config = \Drupal::config('triplestore_indexer.settings');
try {
switch ($config->get("method_of_auth")) {
case 'digest':
$headers = [
'auth' => [$config->get('admin_username'), base64_decode($config->get('admin_password'))],
];
\Drupal::httpClient()->get($uri, $headers);
break;
case 'jwt':
$headers = [
'Authorization' => 'Bearer ' . $config->get('jwt_token'),
];
\Drupal::httpClient()->get($uri, ['headers' => $headers]);
break;
default:
\Drupal::httpClient()->get($uri);
break;
}
}
catch (Exception $e) {
if ($e instanceof ClientException && $e->getCode() > 400 && $e->getCode() < 500) {
// Handling 4XX errors.
$triplestore_url = Url::fromRoute('triplestore_indexer.triplestore_indexer_config_form')->toString();
$form_state->setErrorByName('delete', t('Access Control is in place for this item. <a href="@url">Click here</a> to add authentication to Triplestore Indexer in order to proceed deletion.', ['@url' => $triplestore_url]));
}
elseif (str_contains($e->getResponse()->getBody()->getContents(), 'getKey()')) {
// Handling JWT key missing.
$jwt_url = Url::fromRoute('jwt.jwt_config_form')->toString();
$form_state->setErrorByName('delete', t('An error occurred: Your JWT Authentication Configurations are invalid! <a href="@url">Click Here</a> to configure them.', ['@url' => $jwt_url]));
}
else {
// General error.
$form_state->setErrorByName('delete', t('An error occurred: @error', ['@error' => $e->getMessage()]));
}
}
}
/**
* Implements hook_node_insert().
*/
function triplestore_indexer_node_insert(NodeInterface $node) {
$utils = \Drupal::service('triplestore_indexer.context_utils');
$utils->executeNodeReactions('\Drupal\triplestore_indexer\Plugin\ContextReaction\IndexReaction', $node);
}
/**
* Implements hook_node_update().
*/
function triplestore_indexer_node_update(NodeInterface $node) {
$utils = \Drupal::service('triplestore_indexer.context_utils');
$utils->executeNodeReactions('\Drupal\triplestore_indexer\Plugin\ContextReaction\IndexReaction', $node);
}
/**
* Implements hook_node_delete().
*/
function triplestore_indexer_node_delete(NodeInterface $node) {
$utils = \Drupal::service('triplestore_indexer.context_utils');
$utils->executeNodeReactions('\Drupal\triplestore_indexer\Plugin\ContextReaction\DeleteReaction', $node);
}
/**
* Implements hook_taxonomy_term_insert().
*/
function triplestore_indexer_taxonomy_term_insert(TermInterface $term) {
$utils = \Drupal::service('triplestore_indexer.context_utils');
$utils->executeTermReactions('\Drupal\triplestore_indexer\Plugin\ContextReaction\IndexReaction', $term);
}
/**
* Implements hook_taxonomy_term_update().
*/
function triplestore_indexer_taxonomy_term_update(TermInterface $term) {
$utils = \Drupal::service('triplestore_indexer.context_utils');
$utils->executeTermReactions('\Drupal\triplestore_indexer\Plugin\ContextReaction\IndexReaction', $term);
}
/**
* Implements hook_taxonomy_term_delete().
*/
function triplestore_indexer_taxonomy_term_delete(TermInterface $term) {
$utils = \Drupal::service('triplestore_indexer.context_utils');
$utils->executeTermReactions('\Drupal\triplestore_indexer\Plugin\ContextReaction\DeleteReaction', $term);
}
/**
* Implements hook_media_insert().
*/
function triplestore_indexer_media_insert(MediaInterface $media) {
$utils = \Drupal::service('triplestore_indexer.context_utils');
$utils->executeMediaReactions('\Drupal\triplestore_indexer\Plugin\ContextReaction\IndexReaction', $media);
}
/**
* Implements hook_media_update().
*/
function triplestore_indexer_media_update(MediaInterface $media) {
$utils = \Drupal::service('triplestore_indexer.context_utils');
$utils->executeMediaReactions('\Drupal\triplestore_indexer\Plugin\ContextReaction\IndexReaction', $media);
}
/**
* Implements hook_media_delete().
*/
function triplestore_indexer_media_delete(MediaInterface $media) {
$utils = \Drupal::service('triplestore_indexer.context_utils');
$utils->executeMediaReactions('\Drupal\triplestore_indexer\Plugin\ContextReaction\DeleteReaction', $media);
}
/**
* Debug function: display any variable to error log.
*
* @param $thing
*/
if (!function_exists('print_log')) {
/**
* Logging in apache log.
*/
function print_log($thing) {
error_log(print_r($thing, TRUE), 0);
}
}
/**
* Debug function: display any variable to current webpage.
*
* @param $thing
*/
if (!function_exists('logging')) {
/**
* Logging in webpage.
*/
function logging($thing) {
echo "<pre>";
print_r($thing);
echo "</pre>";
}
}
/**
* Debug function: display any variable to drupal Reports Log messages.
*/
if (!function_exists('drupal_log')) {
/**
* Logging in Recent Log messages.
*/
function drupal_log($msg, $type = "error") {
switch ($type) {
case "notice":
\Drupal::logger(basename(__FILE__, '.module'))->notice($msg);
break;
case "log":
\Drupal::logger(basename(__FILE__, '.module'))->log(RfcLogLevel::NOTICE, $msg);
break;
case "warning":
\Drupal::logger(basename(__FILE__, '.module'))->warning($msg);
break;
case "alert":
\Drupal::logger(basename(__FILE__, '.module'))->alert($msg);
break;
case "critical":
\Drupal::logger(basename(__FILE__, '.module'))->critical($msg);
break;
case "debug":
\Drupal::logger(basename(__FILE__, '.module'))->debug($msg);
break;
case "info":
\Drupal::logger(basename(__FILE__, '.module'))->info($msg);
break;
case "emergency":
\Drupal::logger(basename(__FILE__, '.module'))->emergency($msg);
break;
default:
\Drupal::logger(basename(__FILE__, '.module'))->error($msg);
break;
}
}
}
/**
* Funcation call embedded after hook_insert,hook_update,hook_delete executed.
*/
function queue_process(EntityInterface $entity, $action) {
$config = \Drupal::config('triplestore_indexer.settings');
// Fix warning when Config form hasn't been setup.
if (!isset($config) || empty($config->get("advancedqueue_id"))) {
return;
}
switch ($action) {
case 'insert':
case 'update':
if ($entity->getEntityTypeId() === 'node' || $entity->getEntityTypeId() === 'taxonomy_term' || $entity->getEntityTypeId() === 'media') {
// Create a job and add to Advanced Queue.
$payload = [
'nid' => $entity->id(),
'type' => $entity->getEntityTypeId(),
'action' => $action,
'max_tries' => $config->get("aqj_max_retries"),
'retry_delay' => $config->get("aqj_retry_delay"),
];
}
break;
case 'delete':
case '[Update] delete if exist':
if ($entity->getEntityTypeId() === 'node') {
// Get @id of other components associated with node.
$payload = [
'nid' => $entity->id(),
'type' => $entity->getEntityTypeId(),
'action' => $action,
'max_tries' => $config->get("aqj_max_retries"),
'retry_delay' => $config->get("aqj_retry_delay"),
];
$service = \Drupal::service('triplestore_indexer.indexing');
$others = $service->getOtherConmponentAssocNode($payload);
if (is_array($others) && count($others) > 0) {
$payload['others'] = $others;
}
}
else if ($entity->getEntityTypeId() === 'taxonomy_term') {
// Get @id of other components associated with term.
$payload = [
'nid' => $entity->id(),
'type' => $entity->getEntityTypeId(),
'action' => $action,
'max_tries' => $config->get("aqj_max_retries"),
'retry_delay' => $config->get("aqj_retry_delay"),
];
$service = \Drupal::service('triplestore_indexer.indexing');
$others = $service->getOtherComponentAssocTaxonomyTerm($payload);
if (is_array($others) && count($others) > 0) {
$payload['others'] = $others;
}
}
else if ($entity->getEntityTypeId() === 'media') {
// Create a job and add to Advanced Queue.
$payload = [
'nid' => $entity->id(),
'type' => $entity->getEntityTypeId(),
'action' => $action,
'max_tries' => $config->get("aqj_max_retries"),
'retry_delay' => $config->get("aqj_retry_delay"),
];
}
break;
default:
break;
}
if (isset($payload) && is_array($payload) && count($payload) > 0) {
// Create a job and add to Advanced Queue.
$job = Job::create('triplestore_index_job', $payload);
if ($job instanceof Job) {
$q = Queue::load($config->get("advancedqueue_id"));
$q->enqueueJob($job);
}
}
}
/**
* Get Term ID out of serialized URI.
*/
function get_termid_from_uri(string $uri) {
global $base_url;
return str_replace("?_format=jsonld", "", str_replace($base_url . "/taxonomy/term/", "", $uri));
}
/**
* Get Vocabulary from Term ID.
*/
function get_vocabulary_from_termid(int $term_id) {
$term = Term::load($term_id);
return $term->bundle();
}