-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathos2web_logging.module
executable file
·198 lines (164 loc) · 6 KB
/
os2web_logging.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
<?php
/**
* @file
* OS2Web Logging module file.
*/
use Drupal\Component\Datetime\DateTimePlus;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\os2web_logging\Controller\LoggingController;
use Drupal\os2web_logging\Form\SettingsForm;
/**
* Implements hook_webform_element_access().
*/
function os2web_logging_webform_element_access($operation, array &$element, AccountInterface $account = NULL, array $context = []) {
// Ignoring requests from CLI.
if (PHP_SAPI === 'cli') {
return AccessResult::neutral();
}
// Ignoring if operation is not view or update.
if ($operation != 'view' && $operation != 'update') {
return AccessResult::neutral();
}
$config = \Drupal::config(SettingsForm::$configName);
// Ignore anonymous user.
$logAnonymUser = $config->get('log_anonymous_user');
if (!$logAnonymUser && \Drupal::currentUser()->isAnonymous()) {
return AccessResult::neutral();
}
// Filter on element type.
if ($webform_elements = $config->get('logged_webform_elements')) {
if (in_array($element['#type'], $webform_elements, TRUE)) {
// Log entry.
$logger = \Drupal::logger('os2web_logging.access_log');
$logger->info('CPR accessed');
}
}
// As we are hooking into access, we make sure the return value is not altered.
return AccessResult::neutral();
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function os2web_logging_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form['#id'] == 'views-exposed-form-os2web-logging-access-logs-os2web-logging-logs-page') {
$form['from']['#type'] = 'datetime';
$form['to']['#type'] = 'datetime';
$request = \Drupal::request();
// Setting FROM date, if it's empty.
if (is_null($request->get('from'))) {
$userInput = $form_state->getUserInput();
$lastWeek = new DateTimePlus('-7 days');
$userInput['from'] = [
'date' => $lastWeek->format('Y-m-d'),
'time' => $lastWeek->format('H:i:s'),
];
$form_state->setUserInput($userInput);
}
}
}
/**
* Implements hook_mail().
*/
function os2web_logging_mail($key, &$message, $params) {
switch ($key) {
case 'os2web_logging_mail':
$message['from'] = $params['from'];
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
break;
}
}
/**
* Implements hook_cron().
*/
function os2web_logging_cron() {
$last_cleanup_run_ts = \Drupal::state()
->get('os2web_logging.last_cleanup_run', 0);
$last_cleanup_run = DateTimePlus::createFromTimestamp($last_cleanup_run_ts);
$now = DateTimePlus::createFromTimestamp(time());
$cleanupDiff = $last_cleanup_run->diff($now);
// Proceed if the last cleanup happened more than a day ago.
if ($cleanupDiff->days > 0) {
// Do a cleanup.
_os2web_logging_dblogs_cleanup();
\Drupal::state()
->set('os2web_logging.last_cleanup_run', time());
}
$last_requirements_check_run_ts = \Drupal::state()
->get('os2web_logging.last_requirements_check_run', 0);
$last_requirements_check_run = DateTimePlus::createFromTimestamp($last_requirements_check_run_ts);
$requirementsCheckDiff = $last_requirements_check_run->diff($now);
// Proceed if the last requirements check happened more than a day ago.
if ($requirementsCheckDiff->days > 0) {
// Checking requirements.
$requirements = LoggingController::getCheckedRequirements();
if (!empty($requirements['error'])) {
_os2web_logging_send_status_failed_email($requirements['error']);
\Drupal::state()
->set('os2web_logging.last_requirements_check_run', time());
}
}
}
/**
* Performs deletion of the AccessLogs that are older than allowed time.
*/
function _os2web_logging_dblogs_cleanup() {
$config = \Drupal::config(SettingsForm::$configName);
$dblogs_store_period = $config->get('dblogs_store_period');
$acceptedStorageDate = new DateTimePlus("-$dblogs_store_period days");
// Getting all access logs before accepted storage date.
$query = \Drupal::entityQuery('os2web_logging_access_log')
->accessCheck(FALSE)
->condition('created', $acceptedStorageDate->getTimestamp(), '<');
$logIds = $query->execute();
if (!empty($logIds)) {
$storage = \Drupal::entityTypeManager()->getStorage('os2web_logging_access_log');
// Deleting logs entity in chunks of 100.
foreach (array_chunk($logIds, 100) as $chunk) {
$logsToDelete = $storage->loadMultiple($chunk);
$storage->delete($logsToDelete);
}
}
}
/**
* Sends email to site email with error report.
*
* @param array $errors
* Array of errors formatted as
* [
* 0 => [
* 'title' => 'Requirement title',
* 'value' => 'Requirement value',
* 'description' => 'Additional info'
* ],
* ].
*/
function _os2web_logging_send_status_failed_email(array $errors) {
$errors_combined = [];
foreach ($errors as $error) {
$errors_combined[] = $error['title'] . ' - ' . $error['value'];
}
$errors_build = [
'#theme' => 'item_list',
'#title' => t('Errors'),
'#items' => $errors_combined,
];
$errors_build = \Drupal::service('renderer')->renderPlain($errors_build);
$body = t('OS2Web Logging status check failed with the following errors: @errors', ['@errors' => $errors_build]);
$siteName = \Drupal::config('system.site')->get('name');
$siteMail = \Drupal::config('system.site')->get('mail');
$messageVariables = [
'to' => $siteMail,
'from' => "$siteName <$siteMail>",
'subject' => 'OS2Web Logging status check FAILED',
'body' => $body,
];
/** @var \Drupal\Core\Mail\MailManagerInterface $mailManager */
$mailManager = \Drupal::service('plugin.manager.mail');
$langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
if (!$mailManager->mail('os2web_logging', 'os2web_logging_mail', $siteMail, $langcode, $messageVariables)) {
\Drupal::logger('os2web_logging')->warning(t('There was a problem sending email to %email', ['%email' => $siteMail]));
}
}