annotate core/modules/dblog/src/Controller/DbLogController.php @ 0:4c8ae668cc8c

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