10e2af8c5693caa4bf8fbd7aa61f6f82f436190d
[yaffs-website] / web / core / modules / dblog / src / Controller / DbLogController.php
1 <?php
2
3 namespace Drupal\dblog\Controller;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Component\Utility\Xss;
8 use Drupal\Core\Controller\ControllerBase;
9 use Drupal\Core\Database\Connection;
10 use Drupal\Core\Datetime\DateFormatterInterface;
11 use Drupal\Core\Extension\ModuleHandlerInterface;
12 use Drupal\Core\Form\FormBuilderInterface;
13 use Drupal\Core\Logger\RfcLogLevel;
14 use Drupal\Core\Url;
15 use Drupal\user\Entity\User;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
17
18 /**
19  * Returns responses for dblog routes.
20  */
21 class DbLogController extends ControllerBase {
22
23   /**
24    * The database service.
25    *
26    * @var \Drupal\Core\Database\Connection
27    */
28   protected $database;
29
30   /**
31    * The module handler service.
32    *
33    * @var \Drupal\Core\Extension\ModuleHandlerInterface
34    */
35   protected $moduleHandler;
36
37   /**
38    * The date formatter service.
39    *
40    * @var \Drupal\Core\Datetime\DateFormatterInterface
41    */
42   protected $dateFormatter;
43
44   /**
45    * The form builder service.
46    *
47    * @var \Drupal\Core\Form\FormBuilderInterface
48    */
49   protected $formBuilder;
50
51   /**
52    * The user storage.
53    *
54    * @var \Drupal\user\UserStorageInterface
55    */
56   protected $userStorage;
57
58   /**
59    * {@inheritdoc}
60    */
61   public static function create(ContainerInterface $container) {
62     return new static(
63       $container->get('database'),
64       $container->get('module_handler'),
65       $container->get('date.formatter'),
66       $container->get('form_builder')
67     );
68   }
69
70   /**
71    * Constructs a DbLogController object.
72    *
73    * @param \Drupal\Core\Database\Connection $database
74    *   A database connection.
75    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
76    *   A module handler.
77    * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
78    *   The date formatter service.
79    * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
80    *   The form builder service.
81    */
82   public function __construct(Connection $database, ModuleHandlerInterface $module_handler, DateFormatterInterface $date_formatter, FormBuilderInterface $form_builder) {
83     $this->database = $database;
84     $this->moduleHandler = $module_handler;
85     $this->dateFormatter = $date_formatter;
86     $this->formBuilder = $form_builder;
87     $this->userStorage = $this->entityManager()->getStorage('user');
88   }
89
90   /**
91    * Gets an array of log level classes.
92    *
93    * @return array
94    *   An array of log level classes.
95    */
96   public static function getLogLevelClassMap() {
97     return [
98       RfcLogLevel::DEBUG => 'dblog-debug',
99       RfcLogLevel::INFO => 'dblog-info',
100       RfcLogLevel::NOTICE => 'dblog-notice',
101       RfcLogLevel::WARNING => 'dblog-warning',
102       RfcLogLevel::ERROR => 'dblog-error',
103       RfcLogLevel::CRITICAL => 'dblog-critical',
104       RfcLogLevel::ALERT => 'dblog-alert',
105       RfcLogLevel::EMERGENCY => 'dblog-emergency',
106     ];
107   }
108
109   /**
110    * Displays a listing of database log messages.
111    *
112    * Messages are truncated at 56 chars.
113    * Full-length messages can be viewed on the message details page.
114    *
115    * @return array
116    *   A render array as expected by drupal_render().
117    *
118    * @see Drupal\dblog\Form\DblogClearLogConfirmForm
119    * @see Drupal\dblog\Controller\DbLogController::eventDetails()
120    */
121   public function overview() {
122
123     $filter = $this->buildFilterQuery();
124     $rows = [];
125
126     $classes = static::getLogLevelClassMap();
127
128     $this->moduleHandler->loadInclude('dblog', 'admin.inc');
129
130     $build['dblog_filter_form'] = $this->formBuilder->getForm('Drupal\dblog\Form\DblogFilterForm');
131
132     $header = [
133       // Icon column.
134       '',
135       [
136         'data' => $this->t('Type'),
137         'field' => 'w.type',
138         'class' => [RESPONSIVE_PRIORITY_MEDIUM]],
139       [
140         'data' => $this->t('Date'),
141         'field' => 'w.wid',
142         'sort' => 'desc',
143         'class' => [RESPONSIVE_PRIORITY_LOW]],
144       $this->t('Message'),
145       [
146         'data' => $this->t('User'),
147         'field' => 'ufd.name',
148         'class' => [RESPONSIVE_PRIORITY_MEDIUM]],
149       [
150         'data' => $this->t('Operations'),
151         'class' => [RESPONSIVE_PRIORITY_LOW]],
152     ];
153
154     $query = $this->database->select('watchdog', 'w')
155       ->extend('\Drupal\Core\Database\Query\PagerSelectExtender')
156       ->extend('\Drupal\Core\Database\Query\TableSortExtender');
157     $query->fields('w', [
158       'wid',
159       'uid',
160       'severity',
161       'type',
162       'timestamp',
163       'message',
164       'variables',
165       'link',
166     ]);
167     $query->leftJoin('users_field_data', 'ufd', 'w.uid = ufd.uid');
168
169     if (!empty($filter['where'])) {
170       $query->where($filter['where'], $filter['args']);
171     }
172     $result = $query
173       ->limit(50)
174       ->orderByHeader($header)
175       ->execute();
176
177     foreach ($result as $dblog) {
178       $message = $this->formatMessage($dblog);
179       if ($message && isset($dblog->wid)) {
180         $title = Unicode::truncate(Html::decodeEntities(strip_tags($message)), 256, TRUE, TRUE);
181         $log_text = Unicode::truncate($title, 56, TRUE, TRUE);
182         // The link generator will escape any unsafe HTML entities in the final
183         // text.
184         $message = $this->l($log_text, new Url('dblog.event', ['event_id' => $dblog->wid], [
185           'attributes' => [
186             // Provide a title for the link for useful hover hints. The
187             // Attribute object will escape any unsafe HTML entities in the
188             // final text.
189             'title' => $title,
190           ],
191         ]));
192       }
193       $username = [
194         '#theme' => 'username',
195         '#account' => $this->userStorage->load($dblog->uid),
196       ];
197       $rows[] = [
198         'data' => [
199           // Cells.
200           ['class' => ['icon']],
201           $this->t($dblog->type),
202           $this->dateFormatter->format($dblog->timestamp, 'short'),
203           $message,
204           ['data' => $username],
205           ['data' => ['#markup' => $dblog->link]],
206         ],
207         // Attributes for table row.
208         'class' => [Html::getClass('dblog-' . $dblog->type), $classes[$dblog->severity]],
209       ];
210     }
211
212     $build['dblog_table'] = [
213       '#type' => 'table',
214       '#header' => $header,
215       '#rows' => $rows,
216       '#attributes' => ['id' => 'admin-dblog', 'class' => ['admin-dblog']],
217       '#empty' => $this->t('No log messages available.'),
218       '#attached' => [
219         'library' => ['dblog/drupal.dblog'],
220       ],
221     ];
222     $build['dblog_pager'] = ['#type' => 'pager'];
223
224     return $build;
225
226   }
227
228   /**
229    * Displays details about a specific database log message.
230    *
231    * @param int $event_id
232    *   Unique ID of the database log message.
233    *
234    * @return array
235    *   If the ID is located in the Database Logging table, a build array in the
236    *   format expected by drupal_render();
237    */
238   public function eventDetails($event_id) {
239     $build = [];
240     if ($dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', [':id' => $event_id])->fetchObject()) {
241       $severity = RfcLogLevel::getLevels();
242       $message = $this->formatMessage($dblog);
243       $username = [
244         '#theme' => 'username',
245         '#account' => $dblog->uid ? $this->userStorage->load($dblog->uid) : User::getAnonymousUser(),
246       ];
247       $rows = [
248         [
249           ['data' => $this->t('Type'), 'header' => TRUE],
250           $this->t($dblog->type),
251         ],
252         [
253           ['data' => $this->t('Date'), 'header' => TRUE],
254           $this->dateFormatter->format($dblog->timestamp, 'long'),
255         ],
256         [
257           ['data' => $this->t('User'), 'header' => TRUE],
258           ['data' => $username],
259         ],
260         [
261           ['data' => $this->t('Location'), 'header' => TRUE],
262           $this->l($dblog->location, $dblog->location ? Url::fromUri($dblog->location) : Url::fromRoute('<none>')),
263         ],
264         [
265           ['data' => $this->t('Referrer'), 'header' => TRUE],
266           $this->l($dblog->referer, $dblog->referer ? Url::fromUri($dblog->referer) : Url::fromRoute('<none>')),
267         ],
268         [
269           ['data' => $this->t('Message'), 'header' => TRUE],
270           $message,
271         ],
272         [
273           ['data' => $this->t('Severity'), 'header' => TRUE],
274           $severity[$dblog->severity],
275         ],
276         [
277           ['data' => $this->t('Hostname'), 'header' => TRUE],
278           $dblog->hostname,
279         ],
280         [
281           ['data' => $this->t('Operations'), 'header' => TRUE],
282           ['data' => ['#markup' => $dblog->link]],
283         ],
284       ];
285       $build['dblog_table'] = [
286         '#type' => 'table',
287         '#rows' => $rows,
288         '#attributes' => ['class' => ['dblog-event']],
289         '#attached' => [
290           'library' => ['dblog/drupal.dblog'],
291         ],
292       ];
293     }
294
295     return $build;
296   }
297
298   /**
299    * Builds a query for database log administration filters based on session.
300    *
301    * @return array
302    *   An associative array with keys 'where' and 'args'.
303    */
304   protected function buildFilterQuery() {
305     if (empty($_SESSION['dblog_overview_filter'])) {
306       return;
307     }
308
309     $this->moduleHandler->loadInclude('dblog', 'admin.inc');
310
311     $filters = dblog_filters();
312
313     // Build query.
314     $where = $args = [];
315     foreach ($_SESSION['dblog_overview_filter'] as $key => $filter) {
316       $filter_where = [];
317       foreach ($filter as $value) {
318         $filter_where[] = $filters[$key]['where'];
319         $args[] = $value;
320       }
321       if (!empty($filter_where)) {
322         $where[] = '(' . implode(' OR ', $filter_where) . ')';
323       }
324     }
325     $where = !empty($where) ? implode(' AND ', $where) : '';
326
327     return [
328       'where' => $where,
329       'args' => $args,
330     ];
331   }
332
333   /**
334    * Formats a database log message.
335    *
336    * @param object $row
337    *   The record from the watchdog table. The object properties are: wid, uid,
338    *   severity, type, timestamp, message, variables, link, name.
339    *
340    * @return string|\Drupal\Core\StringTranslation\TranslatableMarkup|false
341    *   The formatted log message or FALSE if the message or variables properties
342    *   are not set.
343    */
344   public function formatMessage($row) {
345     // Check for required properties.
346     if (isset($row->message, $row->variables)) {
347       $variables = @unserialize($row->variables);
348       // Messages without variables or user specified text.
349       if ($variables === NULL) {
350         $message = Xss::filterAdmin($row->message);
351       }
352       elseif (!is_array($variables)) {
353         $message = $this->t('Log data is corrupted and cannot be unserialized: @message', ['@message' => Xss::filterAdmin($row->message)]);
354       }
355       // Message to translate with injected variables.
356       else {
357         $message = $this->t(Xss::filterAdmin($row->message), $variables);
358       }
359     }
360     else {
361       $message = FALSE;
362     }
363     return $message;
364   }
365
366   /**
367    * Shows the most frequent log messages of a given event type.
368    *
369    * Messages are not truncated on this page because events detailed herein do
370    * not have links to a detailed view.
371    *
372    * @param string $type
373    *   Type of database log events to display (e.g., 'search').
374    *
375    * @return array
376    *   A build array in the format expected by drupal_render().
377    */
378   public function topLogMessages($type) {
379     $header = [
380       ['data' => $this->t('Count'), 'field' => 'count', 'sort' => 'desc'],
381       ['data' => $this->t('Message'), 'field' => 'message'],
382     ];
383
384     $count_query = $this->database->select('watchdog');
385     $count_query->addExpression('COUNT(DISTINCT(message))');
386     $count_query->condition('type', $type);
387
388     $query = $this->database->select('watchdog', 'w')
389       ->extend('\Drupal\Core\Database\Query\PagerSelectExtender')
390       ->extend('\Drupal\Core\Database\Query\TableSortExtender');
391     $query->addExpression('COUNT(wid)', 'count');
392     $query = $query
393       ->fields('w', ['message', 'variables'])
394       ->condition('w.type', $type)
395       ->groupBy('message')
396       ->groupBy('variables')
397       ->limit(30)
398       ->orderByHeader($header);
399     $query->setCountQuery($count_query);
400     $result = $query->execute();
401
402     $rows = [];
403     foreach ($result as $dblog) {
404       if ($message = $this->formatMessage($dblog)) {
405         $rows[] = [$dblog->count, $message];
406       }
407     }
408
409     $build['dblog_top_table']  = [
410       '#type' => 'table',
411       '#header' => $header,
412       '#rows' => $rows,
413       '#empty' => $this->t('No log messages available.'),
414       '#attached' => [
415         'library' => ['dblog/drupal.dblog'],
416       ],
417     ];
418     $build['dblog_top_pager'] = ['#type' => 'pager'];
419
420     return $build;
421   }
422
423 }