-
Notifications
You must be signed in to change notification settings - Fork 0
/
os2web_hearings.module
591 lines (522 loc) · 20.5 KB
/
os2web_hearings.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
* OS2Web Hearings module file.
*/
use Drupal\comment\CommentManagerInterface;
use Drupal\Component\Utility\Mail as MailHelper;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
use Drupal\node\Entity\Node;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\os2web_hearings\Form\SettingsForm;
define('OS2WEB_HEARINGS_STATUS_ACTIVE_NAME', 'I gang');
define('OS2WEB_HEARINGS_STATUS_CLOSED_NAME', 'Afsluttet');
define('OS2WEB_HEARINGS_TYPE_HEARINGS', 'Høringer');
define('OS2WEB_HEARINGS_TYPE_DECISIONS', 'Afgørelserr');
define('OS2WEB_HEARINGS_CATEGORIES_BUDGET', 'Budget');
define('OS2WEB_HEARINGS_TYPE_LANDZONETILLADELSE', 'Landzonetilladelse');
/**
* Implements hook_preprocess_paragraph().
*
* Adding meeting search form into paragraph.
*/
function os2web_hearings_preprocess_paragraph__os2web_hearings_search(&$variables) {
if ($variables['view_mode'] == 'preview') {
return;
}
$paragraph = $variables['paragraph'];
// Getting the view type.
$type = 'os2web_hearings_embed_search_simple';
$type_value = $paragraph->get('field_os2web_hearings_search_typ')->getValue();
if (!empty($type_value[0]['value'])) {
$type = $type_value[0]['value'];
}
$view = \Drupal\views\Views::getView('os2web_hearings');
$view->setDisplay($type);
$view->preExecute();
$view->execute();
// Get Headers.
$headers = $view->display_handler->getHandlers('header');
$rendered_headers = [];
if (!empty($headers)) {
foreach ($headers as $header) {
$rendered_headers[] = $header->render();
}
}
$variables['content'][] = $rendered_headers;
$variables['content'][] = $view->render();
$variables['#cache']['tags'][] = 'os2web_hearings_search_cache';
}
/**
* Implements hook_cron().
*/
function os2web_hearings_cron() {
// Close hearing if end_date is reached.
$tids = \Drupal::entityQuery('taxonomy_term')
->condition('vid', 'os2web_hearings_status')
->condition('name', OS2WEB_HEARINGS_STATUS_ACTIVE_NAME)
->execute();
if (empty($tids)) {
\Drupal::logger('os2web_horing')
->error('Term for active hearings status not found');
return;
}
$active_tid = reset($tids);
$now = new DrupalDateTime('now');
$now->setTimezone(new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));
// Fetching nodes with active status.
$ids = \Drupal::entityQuery('node')
->condition('type', 'os2web_hearings_hearing_case')
->condition('field_os2web_hearings_end_date', $now->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT), '<')
->condition('field_os2web_hearings_status', $active_tid)
->execute();
// Fetching nodes with empty status.
$ids_empty = \Drupal::entityQuery('node')
->condition('type', 'os2web_hearings_hearing_case')
->condition('field_os2web_hearings_end_date', $now->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT), '<')
->notExists('field_os2web_hearings_status')
->execute();
$ids = array_unique(array_merge($ids, $ids_empty));
if (empty($ids)) {
return;
}
$tids = \Drupal::entityQuery('taxonomy_term')
->condition('vid', 'os2web_hearings_status')
->condition('name', OS2WEB_HEARINGS_STATUS_CLOSED_NAME)
->execute();
if (empty($tids)) {
\Drupal::logger('os2web_horing')
->error('Term for closed hearings status not found');
return;
}
$closed_tid = reset($tids);
$tids = \Drupal::entityQuery('taxonomy_term')
->condition('vid', 'os2web_hearings_type')
->condition('name', OS2WEB_HEARINGS_TYPE_HEARINGS)
->execute();
if (empty($tids)) {
\Drupal::logger('os2web_horing')
->error('Term for hearings type not found');
return;
}
$hearing_type_tid = reset($tids);
$settingFormConfig = \Drupal::config(SettingsForm::$configName);
/** @var \Drupal\node\NodeInterface $node */
foreach (Node::loadMultiple($ids) as $node) {
$node->set('field_os2web_hearings_status', $closed_tid);
$node->save();
if ($settingFormConfig->get('disable_sbsys_email_for_decision')) {
$hearing_type = $node->field_os2web_hearings_type->getValue();
if ($hearing_type[0]['target_id'] == $hearing_type_tid) {
_os2web_hearings_send_email_notification($node);
}
}
else {
_os2web_hearings_send_email_notification($node);
}
}
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function os2web_hearings_node_presave(EntityInterface $entity) {
if ($entity->bundle() != 'os2web_hearings_hearing_case') {
return;
}
// Invalidating cache for all hearing search paragraphs.
Cache::invalidateTags(['os2web_hearings_search_cache']);
if ($entity->isNew()) {
// If header is empty, use the title.
if (empty($entity->field_os2web_hearings_heading->value)) {
$entity->field_os2web_hearings_heading->value = $entity->label();
}
}
/** @var Drupal\Core\Datetime\DrupalDateTime $endDate */
$endDate = $entity->field_os2web_hearings_end_date->date;
// Activate hearing when end date is changed.
if (empty($endDate) || $endDate->getTimestamp() < time()) {
return;
}
$tids = \Drupal::entityQuery('taxonomy_term')
->condition('vid', 'os2web_hearings_status')
->condition('name', OS2WEB_HEARINGS_STATUS_ACTIVE_NAME)
->execute();
if (empty($tids)) {
\Drupal::logger('os2web_horing')
->error('Can not set correct active status on new hearing');
return;
}
$active_tid = reset($tids);
$entity->set('field_os2web_hearings_status', $active_tid);
if ($entity->status->value && empty($entity->field_os2web_hearings_published->value)) {
$entity->set('field_os2web_hearings_published', date(DateTimeItemInterface::DATE_STORAGE_FORMAT, strtotime('now')));
}
}
/**
* Implements hook_theme().
*/
function os2web_hearings_theme() {
return [
'hearings_og_afgeorelse_case__mail' => [
'variables' => [
'node' => NULL,
'attachments' => NULL,
'comments' => NULL,
'comments_files' => NULL,
],
],
'hearings_og_afgeorelse_case__comment_mail_notification' => [
'variables' => [
'node' => NULL,
'node_url' => NULL,
],
],
];
}
/**
* Implements hook_mail().
*
* Captures the outgoing mail and sets appropriate message body and headers.
*/
function os2web_hearings_mail($key, &$message, $params) {
if (isset($params['headers'])) {
$message['headers'] = array_merge($message['headers'], $params['headers']);
}
$message['from'] = $params['from'];
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function os2web_hearings_form_taxonomy_term_os2web_hearings_status_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Status terms names are using as key for changing status.
// It shouldn't be possible to change name on term that is used for statuses.
/** @var \Drupal\taxonomy\Entity\Term $term */
$term = $form_state->getFormObject()->getEntity();
if (in_array($term->label(), [OS2WEB_HEARINGS_STATUS_CLOSED_NAME, OS2WEB_HEARINGS_STATUS_ACTIVE_NAME])) {
$form['name']['widget'][0]['#disabled'] = TRUE;
$form['name']['widget']['description'] = ['#markup' => t('This taxonomy term is used for hearing status field and can not be renamed')];
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function os2web_hearings_form_taxonomy_term_os2web_hearings_status_delete_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Status terms names are using as key for changing status.
// It shouldn't be possible to delete term that is used for statuses.
/** @var \Drupal\taxonomy\Entity\Term $term */
$term = $form_state->getFormObject()->getEntity();
if (in_array($term->label(), [OS2WEB_HEARINGS_STATUS_CLOSED_NAME, OS2WEB_HEARINGS_STATUS_ACTIVE_NAME])) {
$form['description'] = [
'#markup' => t('This taxonomy term is used for hearing status field and can not be deleted'),
];
$form['#disabled'] = TRUE;
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Changes the fields position.
*/
function os2web_hearings_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if (in_array($form['#id'],
['views-exposed-form-os2web-hearings-os2web-hearings-embed-search-tender-category',
'views-exposed-form-os2web-hearings-os2web-hearings-embed-search-category',
'views-exposed-form-os2web-hearings-os2web-hearings-embed-search-tender',
'views-exposed-form-os2web-hearings-os2web-hearings-embed-search-simple'
])) {
$terms = \Drupal::service('entity_type.manager')
->getStorage('taxonomy_term')
->loadByProperties(['vid' => 'os2web_hearings_status', 'name'=> OS2WEB_HEARINGS_STATUS_ACTIVE_NAME]);
$term = reset($terms);
$request = \Drupal::request();
if ($term && is_null($request->get('field_os2web_hearings_status_target_id'))) {
// get all input fields first then modify the one you want to change
$input = $form_state->getUserInput();
$input['field_os2web_hearings_status_target_id'] = $term->id();
$form_state->setUserInput($input);
}
}
if ($form['#id'] == 'views-exposed-form-os2web-hearings-os2web-hearings-embed-search-simple') {
// Making sure status filter is in the bottom.
$status_filter = $form['field_os2web_hearings_status_target_id'];
unset($form['field_os2web_hearings_status_target_id']);
$form['field_os2web_hearings_status_target_id'] = $status_filter;
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function os2web_hearings_form_comment_os2web_hearings_hearing_reply_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['comment_body']['widget']['#after_build'][] = '_os2web_hearings_remove_textarea_help';
/** @var \Drupal\Core\Entity\EntityForm $form_object */
$form_object = $form_state->getFormObject();
if ($form_object instanceof EntityForm) {
/** @var \Drupal\comment\Entity\Comment $entity */
$comment = $form_object->getEntity();
$node = $comment->getCommentedEntity();
if (!$node->field_os2web_hearings_sp_rol_ena->value) {
unset($form['field_os2web_hearings_reply_sp_r']);
} else {
// Making select html5 required.
unset($form['field_os2web_hearings_reply_sp_r']['widget']['#options']['_none']);
$form['field_os2web_hearings_reply_sp_r']['widget']['#options'] = ['' => '- Vælg -'] + $form['field_os2web_hearings_reply_sp_r']['widget']['#options'];
$form['field_os2web_hearings_reply_sp_r']['widget']['#required'] = TRUE;
}
}
}
/**
* Hides the field format help text.
*
* @param array $form_element
* Form element to hide the help text from.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*
* @return mixed
* Form element without help text from.
*/
function _os2web_hearings_remove_textarea_help(array $form_element, FormStateInterface $form_state) {
if (isset($form_element[0]['format'])) {
// All this stuff is needed to hide the help text.
unset($form_element[0]['format']['guidelines']);
unset($form_element[0]['format']['help']);
unset($form_element[0]['format']['#type']);
unset($form_element[0]['format']['#theme_wrappers']);
$form_element[0]['format']['format']['#access'] = FALSE;
}
return $form_element;
}
function _os2web_hearings_send_email_notification($node) {
$type = t('Høringe elle Afgørelse');
if (!empty($node->field_os2web_hearings_type) && $node->field_os2web_hearings_type instanceof EntityReferenceFieldItemListInterface) {
$type_value = $node->field_os2web_hearings_type->referencedEntities();
$type = $type_value[0]->label();
}
$site_config = \Drupal::service('config.factory')->get('system.site');
$renderer = \Drupal::service('renderer');
$params = [
'headers' => [
'Content-Type' => 'text/html; charset=UTF-8;',
'Content-Transfer-Encoding' => '8Bit',
],
'from' => MailHelper::formatDisplayName($site_config->get('name')) . ' <' . $site_config->get('mail') . '>',
'subject' => t('@type #@nid', [
'@nid' => $node->id(),
'@type' => $type,
]),
];
// Gathering hearing attachments.
$hearing_attachments = [];
if (!empty($node->field_os2web_hearings_attac_doc)) {
foreach ($node->field_os2web_hearings_attac_doc->referencedEntities() as $file) {
if (!file_exists($file->getFileUri())) {
continue;
}
$params['files'][] = (object) [
'filename' => $file->getFilename(),
'uri' => $file->getFileUri(),
'filemime' => $file->getMimeType(),
];
$hearing_attachments[] = [
'name' => $file->getFilename(),
'url' => $file->createFileUrl(FALSE),
];
}
}
// Gathering comments.
$comments = \Drupal::service('entity_type.manager')->getStorage('comment')->loadThread($node, 'field_os2web_hearings_reply', CommentManagerInterface::COMMENT_MODE_FLAT);
// Gathering comments files.
$comments_files = [];
foreach ($comments as $comment) {
if (empty($comment->field_os2web_hearings_reply_docs)) {
continue;
}
foreach ($comment->field_os2web_hearings_reply_docs->referencedEntities() as $file) {
if (!file_exists($file->getFileUri())) {
continue;
}
$params['files'][] = (object) [
'filename' => $file->getFilename(),
'uri' => $file->getFileUri(),
'filemime' => $file->getMimeType(),
];
$comments_files[$comment->id()][] = [
'name' => $file->getFilename(),
'url' => $file->createFileUrl(FALSE),
];
}
}
// Creating theme build array.
$build = [
'#theme' => 'hearings_og_afgeorelse_case__mail',
'#node' => $node,
'#attachments' => $hearing_attachments,
'#comments' => $comments,
'#comments_files' => $comments_files,
];
$params['body'] = $renderer->renderRoot($build);
/** @var \Drupal\os2web_hearings\SbsysGenerator $sbsys_generator */
$sbsys_generator = \Drupal::service('os2web_hearings.sbsys_generator');
$xmlFileUri = $sbsys_generator->generateFile('os2formsFormular', $node, $params['body']->__toString());
// Attaching SBSYS XML.
if ($xmlFileUri) {
$xmlFile = (object) [
'filename' => 'sbsys.xml',
'uri' => $xmlFileUri,
'filemime' => 'application/xml',
];
$params['files'][] = $xmlFile;
}
$langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
$settingFormConfig = \Drupal::config(SettingsForm::$configName);
$mailto = $settingFormConfig->get('sbsys_email');
if (empty($mailto)) {
\Drupal::logger('os2web_hearings')->warning(t('Notification email is empty. Can not send email notification for os2web_hearings_hearing_case with id @nid.', ['@nid' => $node->id()]));
return;
}
$mail_manager = \Drupal::service('plugin.manager.mail');
if (!$mail_manager->mail('os2web_hearings', 'default', $mailto, $langcode, $params)) {
\Drupal::logger('os2web_hearings')->error(t('Sending of email notification for os2web_hearings_hearing_case with id @nid failed.', ['@nid' => $node->id()]));
}
}
/**
* Implements hook_preprocess_node().
*/
function os2web_hearings_preprocess_node(&$variables) {
if ($variables['node']->getType() == 'os2web_hearings_hearing_case') {
$hearing = $variables['node'];
/** @var \Drupal\Core\Datetime\DrupalDateTime $endDate */
$endDate = $hearing->field_os2web_hearings_end_date->date;
$type_value = $hearing->field_os2web_hearings_type->referencedEntities();
$type = $type_value[0]->label();
$variables['content']['#is_decision'] = ($type == OS2WEB_HEARINGS_TYPE_DECISIONS);
$tender_value = $hearing->field_os2web_hearings_tender->referencedEntities();
$reply_text = null;
if (!empty($tender_value[0])) {
$tender = $tender_value[0];
if (is_object($tender)) {
if ($tender->id() == 4563) // udbud
{
$reply_text = 'Send dit tilbud.';
}
else if ($tender->id() == 4564) // høring
{
$reply_text = 'Send dit høringssvar.';
}
}
}
$variables['content']['#reply_text'] = $reply_text;
if ($endDate->getTimestamp() < time()) {
$variables['content']['#closed'] = TRUE;
}
else {
$variables['content']['#closed'] = FALSE;
}
$settingFormConfig = \Drupal::config(SettingsForm::$configName);
if ($settingFormConfig->get('disable_comments')) {
$variables['content']['#closed'] = TRUE;
}
$variables['content']['destination'] = \Drupal::request()->server->get('HTTP_REFERER');
}
}
/**
* Implements hook_preprocess_field().
*/
function os2web_hearings_preprocess_field(&$variables) {
$element = $variables['element'];
if ($element['#field_name'] == 'field_os2web_hearings_reply') {
foreach ($variables['items'][0]['content']['comments'] as $commentRendered) {
// Check if the rendered comment exists.
if (!isset($commentRendered['#comment'])) {
continue;
}
/** @var \Drupal\comment\Entity\Comment $comment */
$comment = $commentRendered['#comment'];
$speakerRoles = $comment->get('field_os2web_hearings_reply_sp_r')->referencedEntities();
// If there are no speaker roles, skip this iteration.
if (empty($speakerRoles)) {
continue;
}
/** @var \Drupal\taxonomy\Plugin\views\wizard\TaxonomyTerm $speakerRole */
$speakerRole = reset($speakerRoles);
// Initialize the speaker role section if it doesn't exist.
if (!isset($variables['#comments_speaker_role'][$speakerRole->id()])) {
$variables['#comments_speaker_role'][$speakerRole->id()] = [
'role' => $speakerRole->label(),
'comments_section' => [
[
'content' => [
'comments' => [
'#sorted' => $variables['items'][0]['content']['comments']['#sorted'],
'#pre_render' => $variables['items'][0]['content']['comments']['#pre_render'],
'pager' => $variables['items'][0]['content']['comments']['pager'],
],
'#comment_type' => 'os2web_hearings_hearing_reply',
'#comment_display_mode' => 0,
'comment_form' => []
],
'attributes' => $variables['items'][0]['attributes']
]
]
];
}
// Add the rendered comment to the speaker role section.
$variables['#comments_speaker_role'][$speakerRole->id()]['comments_section'][0]['content']['comments'][$comment->id()] = $commentRendered;
// Remove the comment from the original comments array.
unset($variables['items'][0]['content']['comments'][$comment->id()]);
}
}
}
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function os2web_hearings_comment_insert(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getCommentedEntityTypeId() != 'node') {
return;
}
/** @var \Drupal\node\NodeInterface $node */
$node = $entity->getCommentedEntity();
if ($node->getType() != 'os2web_hearings_hearing_case') {
return;
}
// Do not send notifications if no recipient.
if (empty($node->field_os2web_hearings_not_email) || $node->field_os2web_hearings_not_email->isEmpty()) {
return;
}
$type = t('Høringe eller Afgørelse');
if (!empty($node->field_os2web_hearings_type) && $node->field_os2web_hearings_type instanceof EntityReferenceFieldItemListInterface) {
$type_value = $node->field_os2web_hearings_type->referencedEntities();
$type = $type_value[0]->label();
}
$language = \Drupal::languageManager()->getDefaultLanguage();
$site_config = \Drupal::service('config.factory')->get('system.site');
$build = [
'#theme' => 'hearings_og_afgeorelse_case__comment_mail_notification',
'#node' => $node,
'#node_url' => $node->toUrl('canonical')->setAbsolute()->toString(),
];
$params = [
'headers' => [
'Content-Type' => 'text/html; charset=UTF-8;',
'Content-Transfer-Encoding' => '8Bit',
],
'from' => MailHelper::formatDisplayName($site_config->get('name')) . ' <' . $site_config->get('mail') . '>',
'subject' => t('Nyt kommentar på @type #@nid', [
'@nid' => $node->id(),
'@type' => $type,
]),
'body' => \Drupal::service('renderer')->renderRoot($build),
];
$mailto = $node->field_os2web_hearings_not_email->first()->value;
$mail_manager = \Drupal::service('plugin.manager.mail');
if (!$mail_manager->mail('os2web_hearings', 'default', $mailto, $language->getId(), $params)) {
\Drupal::logger('os2web_hearings')->error(t('Sending of email notification for os2web_hearings_hearing_case with id @nid failed.', ['@nid' => $node->id()]));
}
}