3 namespace Drupal\dblog\Tests;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Core\Logger\RfcLogLevel;
9 use Drupal\dblog\Controller\DbLogController;
10 use Drupal\simpletest\WebTestBase;
13 * Generate events and verify dblog entries; verify user access to log reports
14 * based on permissions.
18 class DbLogTest extends WebTestBase {
25 public static $modules = ['dblog', 'node', 'forum', 'help', 'block'];
28 * A user with some relevant administrative permissions.
30 * @var \Drupal\user\UserInterface
35 * A user without any permissions.
37 * @var \Drupal\user\UserInterface
44 protected function setUp() {
46 $this->drupalPlaceBlock('system_breadcrumb_block');
47 $this->drupalPlaceBlock('page_title_block');
49 // Create users with specific permissions.
50 $this->adminUser = $this->drupalCreateUser(['administer site configuration', 'access administration pages', 'access site reports', 'administer users']);
51 $this->webUser = $this->drupalCreateUser([]);
55 * Tests Database Logging module functionality through interfaces.
57 * First logs in users, then creates database log events, and finally tests
58 * Database Logging module functionality through both the admin and user
61 public function testDbLog() {
62 // Log in the admin user.
63 $this->drupalLogin($this->adminUser);
66 $this->verifyRowLimit($row_limit);
67 $this->verifyCron($row_limit);
68 $this->verifyEvents();
69 $this->verifyReports();
70 $this->verifyBreadcrumbs();
71 $this->verifyLinkEscaping();
72 // Verify the overview table sorting.
73 $orders = ['Date', 'Type', 'User'];
74 $sorts = ['asc', 'desc'];
75 foreach ($orders as $order) {
76 foreach ($sorts as $sort) {
77 $this->verifySort($sort, $order);
81 // Log in the regular user.
82 $this->drupalLogin($this->webUser);
83 $this->verifyReports(403);
87 * Test individual log event page.
89 public function testLogEventPage() {
90 // Login the admin user.
91 $this->drupalLogin($this->adminUser);
93 // Since referrer and location links vary by how the tests are run, inject
94 // fake log data to test these.
96 'request_uri' => 'http://example.com?dblog=1',
97 'referer' => 'http://example.org?dblog=2',
99 'channel' => 'testing',
102 'timestamp' => REQUEST_TIME,
104 \Drupal::service('logger.dblog')->log(RfcLogLevel::NOTICE, 'Test message', $context);
105 $wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
107 // Verify the links appear correctly.
108 $this->drupalGet('admin/reports/dblog/event/' . $wid);
109 $this->assertLinkByHref($context['request_uri']);
110 $this->assertLinkByHref($context['referer']);
113 $this->assertRaw($context['ip'], 'Found hostname on the detail page.');
116 $this->assertText('Notice', 'The severity was properly displayed on the detail page.');
120 * Verifies setting of the database log row limit.
122 * @param int $row_limit
125 private function verifyRowLimit($row_limit) {
126 // Change the database log row limit.
128 $edit['dblog_row_limit'] = $row_limit;
129 $this->drupalPostForm('admin/config/development/logging', $edit, t('Save configuration'));
130 $this->assertResponse(200);
132 // Check row limit variable.
133 $current_limit = $this->config('dblog.settings')->get('row_limit');
134 $this->assertTrue($current_limit == $row_limit, format_string('[Cache] Row limit variable of @count equals row limit of @limit', ['@count' => $current_limit, '@limit' => $row_limit]));
138 * Verifies that cron correctly applies the database log row limit.
140 * @param int $row_limit
143 private function verifyCron($row_limit) {
144 // Generate additional log entries.
145 $this->generateLogEntries($row_limit + 10);
146 // Verify that the database log row count exceeds the row limit.
147 $count = db_query('SELECT COUNT(wid) FROM {watchdog}')->fetchField();
148 $this->assertTrue($count > $row_limit, format_string('Dblog row count of @count exceeds row limit of @limit', ['@count' => $count, '@limit' => $row_limit]));
150 // Get the number of enabled modules. Cron adds a log entry for each module.
151 $list = \Drupal::moduleHandler()->getImplementations('cron');
152 $module_count = count($list);
153 $cron_detailed_count = $this->runCron();
154 $this->assertTrue($cron_detailed_count == $module_count + 2, format_string('Cron added @count of @expected new log entries', ['@count' => $cron_detailed_count, '@expected' => $module_count + 2]));
156 // Test disabling of detailed cron logging.
157 $this->config('system.cron')->set('logging', 0)->save();
158 $cron_count = $this->runCron();
159 $this->assertTrue($cron_count = 1, format_string('Cron added @count of @expected new log entries', ['@count' => $cron_count, '@expected' => 1]));
163 * Runs cron and returns number of new log entries.
166 * Number of new watchdog entries.
168 private function runCron() {
169 // Get last ID to compare against; log entries get deleted, so we can't
170 // reliably add the number of newly created log entries to the current count
171 // to measure number of log entries created by cron.
172 $last_id = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
177 // Get last ID after cron was run.
178 $current_id = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
180 return $current_id - $last_id;
184 * Generates a number of random database log events.
187 * Number of watchdog entries to generate.
188 * @param array $options
189 * These options are used to override the defaults for the test.
190 * An associative array containing any of the following keys:
191 * - 'channel': String identifying the log channel to be output to.
192 * If the channel is not set, the default of 'custom' will be used.
193 * - 'message': String containing a message to be output to the log.
194 * A simple default message is used if not provided.
195 * - 'variables': Array of variables that match the message string.
196 * - 'severity': Log severity level as defined in logging_severity_levels.
197 * - 'link': String linking to view the result of the event.
198 * - 'user': String identifying the username.
199 * - 'uid': Int identifying the user id for the user.
200 * - 'request_uri': String identifying the location of the request.
201 * - 'referer': String identifying the referring url.
202 * - 'ip': String The ip address of the client machine triggering the log
204 * - 'timestamp': Int unix timestamp.
206 private function generateLogEntries($count, $options = []) {
209 // This long URL makes it just a little bit harder to pass the link part of
210 // the test with a mix of English words and a repeating series of random
211 // percent-encoded Chinese characters.
212 $link = urldecode('/content/xo%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A%E9%85%B1%E5%87%89%E6%8B%8C%E7%B4%A0%E9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%E7%B4%A0%E9%B8%A1%E7%85%A7%E7%83%A7%E9%B8%A1%E9%BB%84%E7%8E%AB%E7%91%B0-%E7%A7%91%E5%B7%9E%E7%9A%84%E5%B0%8F%E4%B9%9D%E5%AF%A8%E6%B2%9F%E7%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A-lake-isabelle');
214 // Prepare the fields to be logged
216 'channel' => 'custom',
217 'message' => 'Dblog test log message',
219 'severity' => RfcLogLevel::NOTICE,
221 'user' => $this->adminUser,
222 'uid' => $this->adminUser->id(),
223 'request_uri' => $base_root . \Drupal::request()->getRequestUri(),
224 'referer' => \Drupal::request()->server->get('HTTP_REFERER'),
226 'timestamp' => REQUEST_TIME,
229 $logger = $this->container->get('logger.dblog');
230 $message = $log['message'] . ' Entry #';
231 for ($i = 0; $i < $count; $i++) {
232 $log['message'] = $message . $i;
233 $logger->log($log['severity'], $log['message'], $log);
238 * Clear the entry logs by clicking on 'Clear log messages' button.
240 protected function clearLogsEntries() {
241 $this->drupalGet(Url::fromRoute('dblog.confirm'));
245 * Filters the logs according to the specific severity and log entry type.
247 * @param string $type
248 * (optional) The log entry type.
249 * @param string $severity
250 * (optional) The log entry severity.
252 protected function filterLogsEntries($type = NULL, $severity = NULL) {
254 if (!is_null($type)) {
255 $edit['type[]'] = $type;
257 if (!is_null($severity)) {
258 $edit['severity[]'] = $severity;
260 $this->drupalPostForm(NULL, $edit, t('Filter'));
264 * Confirms that database log reports are displayed at the correct paths.
266 * @param int $response
267 * (optional) HTTP response code. Defaults to 200.
269 private function verifyReports($response = 200) {
270 // View the database log help page.
271 $this->drupalGet('admin/help/dblog');
272 $this->assertResponse($response);
273 if ($response == 200) {
274 $this->assertText(t('Database Logging'), 'DBLog help was displayed');
277 // View the database log report page.
278 $this->drupalGet('admin/reports/dblog');
279 $this->assertResponse($response);
280 if ($response == 200) {
281 $this->assertText(t('Recent log messages'), 'DBLog report was displayed');
284 // View the database log page-not-found report page.
285 $this->drupalGet('admin/reports/page-not-found');
286 $this->assertResponse($response);
287 if ($response == 200) {
288 $this->assertText("Top 'page not found' errors", 'DBLog page-not-found report was displayed');
291 // View the database log access-denied report page.
292 $this->drupalGet('admin/reports/access-denied');
293 $this->assertResponse($response);
294 if ($response == 200) {
295 $this->assertText("Top 'access denied' errors", 'DBLog access-denied report was displayed');
298 // View the database log event page.
299 $wid = db_query('SELECT MIN(wid) FROM {watchdog}')->fetchField();
300 $this->drupalGet('admin/reports/dblog/event/' . $wid);
301 $this->assertResponse($response);
302 if ($response == 200) {
303 $this->assertText(t('Details'), 'DBLog event node was displayed');
308 * Generates and then verifies breadcrumbs.
310 private function verifyBreadcrumbs() {
311 // View the database log event page.
312 $wid = db_query('SELECT MIN(wid) FROM {watchdog}')->fetchField();
313 $this->drupalGet('admin/reports/dblog/event/' . $wid);
314 $xpath = '//nav[@class="breadcrumb"]/ol/li[last()]/a';
315 $this->assertEqual(current($this->xpath($xpath)), 'Recent log messages', 'DBLogs link displayed at breadcrumb in event page.');
319 * Generates and then verifies various types of events.
321 private function verifyEvents() {
324 $this->drupalCreateContentType(['type' => 'article', 'name' => t('Article')]);
325 $this->drupalCreateContentType(['type' => 'page', 'name' => t('Basic page')]);
326 $this->doNode('article');
327 $this->doNode('page');
328 $this->doNode('forum');
330 // When a user account is canceled, any content they created remains but the
331 // uid = 0. Records in the watchdog table related to that user have the uid
336 * Verifies the sorting functionality of the database logging reports table.
338 * @param string $sort
339 * The sort direction.
340 * @param string $order
341 * The order by which the table should be sorted.
343 public function verifySort($sort = 'asc', $order = 'Date') {
344 $this->drupalGet('admin/reports/dblog', ['query' => ['sort' => $sort, 'order' => $order]]);
345 $this->assertResponse(200);
346 $this->assertText(t('Recent log messages'), 'DBLog report was displayed correctly and sorting went fine.');
350 * Tests the escaping of links in the operation row of a database log detail
353 private function verifyLinkEscaping() {
354 $link = \Drupal::l('View', Url::fromRoute('entity.node.canonical', ['node' => 1]));
355 $message = 'Log entry added to do the verifyLinkEscaping test.';
356 $this->generateLogEntries(1, [
357 'message' => $message,
361 $result = db_query_range('SELECT wid FROM {watchdog} ORDER BY wid DESC', 0, 1);
362 $this->drupalGet('admin/reports/dblog/event/' . $result->fetchField());
364 // Check if the link exists (unescaped).
365 $this->assertRaw($link);
369 * Generates and then verifies some user events.
371 private function doUser() {
372 // Set user variables.
373 $name = $this->randomMachineName();
374 $pass = user_password();
375 // Add a user using the form to generate an add user event (which is not
376 // triggered by drupalCreateUser).
378 $edit['name'] = $name;
379 $edit['mail'] = $name . '@example.com';
380 $edit['pass[pass1]'] = $pass;
381 $edit['pass[pass2]'] = $pass;
383 $this->drupalPostForm('admin/people/create', $edit, t('Create new account'));
384 $this->assertResponse(200);
385 // Retrieve the user object.
386 $user = user_load_by_name($name);
387 $this->assertTrue($user != NULL, format_string('User @name was loaded', ['@name' => $name]));
388 // pass_raw property is needed by drupalLogin.
389 $user->pass_raw = $pass;
391 $this->drupalLogin($user);
393 $this->drupalLogout();
394 // Fetch the row IDs in watchdog that relate to the user.
395 $result = db_query('SELECT wid FROM {watchdog} WHERE uid = :uid', [':uid' => $user->id()]);
396 foreach ($result as $row) {
399 $count_before = (isset($ids)) ? count($ids) : 0;
400 $this->assertTrue($count_before > 0, format_string('DBLog contains @count records for @name', ['@count' => $count_before, '@name' => $user->getUsername()]));
402 // Log in the admin user.
403 $this->drupalLogin($this->adminUser);
404 // Delete the user created at the start of this test.
405 // We need to POST here to invoke batch_process() in the internal browser.
406 $this->drupalPostForm('user/' . $user->id() . '/cancel', ['user_cancel_method' => 'user_cancel_reassign'], t('Cancel account'));
408 // View the database log report.
409 $this->drupalGet('admin/reports/dblog');
410 $this->assertResponse(200);
412 // Verify that the expected events were recorded.
414 // Default display includes name and email address; if too long, the email
415 // address is replaced by three periods.
416 $this->assertLogMessage(t('New user: %name %email.', ['%name' => $name, '%email' => '<' . $user->getEmail() . '>']), 'DBLog event was recorded: [add user]');
418 $this->assertLogMessage(t('Session opened for %name.', ['%name' => $name]), 'DBLog event was recorded: [login user]');
420 $this->assertLogMessage(t('Session closed for %name.', ['%name' => $name]), 'DBLog event was recorded: [logout user]');
422 $message = t('Deleted user: %name %email.', ['%name' => $name, '%email' => '<' . $user->getEmail() . '>']);
423 $message_text = Unicode::truncate(Html::decodeEntities(strip_tags($message)), 56, TRUE, TRUE);
424 // Verify that the full message displays on the details page.
426 if ($links = $this->xpath('//a[text()="' . $message_text . '"]')) {
427 // Found link with the message text.
428 $links = array_shift($links);
429 foreach ($links->attributes() as $attr => $value) {
430 if ($attr == 'href') {
431 // Extract link to details page.
432 $link = Unicode::substr($value, strpos($value, 'admin/reports/dblog/event/'));
433 $this->drupalGet($link);
434 // Check for full message text on the details page.
435 $this->assertRaw($message, 'DBLog event details was found: [delete user]');
440 $this->assertTrue($link, 'DBLog event was recorded: [delete user]');
441 // Visit random URL (to generate page not found event).
442 $not_found_url = $this->randomMachineName(60);
443 $this->drupalGet($not_found_url);
444 $this->assertResponse(404);
445 // View the database log page-not-found report page.
446 $this->drupalGet('admin/reports/page-not-found');
447 $this->assertResponse(200);
448 // Check that full-length URL displayed.
449 $this->assertText($not_found_url, 'DBLog event was recorded: [page not found]');
453 * Generates and then verifies some node events.
455 * @param string $type
456 * A node type (e.g., 'article', 'page' or 'forum').
458 private function doNode($type) {
460 $perm = ['create ' . $type . ' content', 'edit own ' . $type . ' content', 'delete own ' . $type . ' content'];
461 $user = $this->drupalCreateUser($perm);
463 $this->drupalLogin($user);
465 // Create a node using the form in order to generate an add content event
466 // (which is not triggered by drupalCreateNode).
467 $edit = $this->getContent($type);
468 $title = $edit['title[0][value]'];
469 $this->drupalPostForm('node/add/' . $type, $edit, t('Save'));
470 $this->assertResponse(200);
471 // Retrieve the node object.
472 $node = $this->drupalGetNodeByTitle($title);
473 $this->assertTrue($node != NULL, format_string('Node @title was loaded', ['@title' => $title]));
475 $edit = $this->getContentUpdate($type);
476 $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save'));
477 $this->assertResponse(200);
479 $this->drupalPostForm('node/' . $node->id() . '/delete', [], t('Delete'));
480 $this->assertResponse(200);
481 // View the node (to generate page not found event).
482 $this->drupalGet('node/' . $node->id());
483 $this->assertResponse(404);
484 // View the database log report (to generate access denied event).
485 $this->drupalGet('admin/reports/dblog');
486 $this->assertResponse(403);
488 // Log in the admin user.
489 $this->drupalLogin($this->adminUser);
490 // View the database log report.
491 $this->drupalGet('admin/reports/dblog');
492 $this->assertResponse(200);
494 // Verify that node events were recorded.
495 // Was node content added?
496 $this->assertLogMessage(t('@type: added %title.', ['@type' => $type, '%title' => $title]), 'DBLog event was recorded: [content added]');
497 // Was node content updated?
498 $this->assertLogMessage(t('@type: updated %title.', ['@type' => $type, '%title' => $title]), 'DBLog event was recorded: [content updated]');
499 // Was node content deleted?
500 $this->assertLogMessage(t('@type: deleted %title.', ['@type' => $type, '%title' => $title]), 'DBLog event was recorded: [content deleted]');
502 // View the database log access-denied report page.
503 $this->drupalGet('admin/reports/access-denied');
504 $this->assertResponse(200);
505 // Verify that the 'access denied' event was recorded.
506 $this->assertText('admin/reports/dblog', 'DBLog event was recorded: [access denied]');
508 // View the database log page-not-found report page.
509 $this->drupalGet('admin/reports/page-not-found');
510 $this->assertResponse(200);
511 // Verify that the 'page not found' event was recorded.
512 $this->assertText('node/' . $node->id(), 'DBLog event was recorded: [page not found]');
516 * Creates random content based on node content type.
518 * @param string $type
519 * Node content type (e.g., 'article').
522 * Random content needed by various node types.
524 private function getContent($type) {
528 'title[0][value]' => $this->randomMachineName(8),
529 'taxonomy_forums' => [1],
530 'body[0][value]' => $this->randomMachineName(32),
536 'title[0][value]' => $this->randomMachineName(8),
537 'body[0][value]' => $this->randomMachineName(32),
545 * Creates random content as an update based on node content type.
547 * @param string $type
548 * Node content type (e.g., 'article').
551 * Random content needed by various node types.
553 private function getContentUpdate($type) {
555 'body[0][value]' => $this->randomMachineName(32),
561 * Tests the addition and clearing of log events through the admin interface.
563 * Logs in the admin user, creates a database log event, and tests the
564 * functionality of clearing the database log through the admin interface.
566 public function testDBLogAddAndClear() {
568 // Get a count of how many watchdog entries already exist.
569 $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
571 'channel' => 'system',
572 'message' => 'Log entry added to test the doClearTest clear down.',
574 'severity' => RfcLogLevel::NOTICE,
576 'user' => $this->adminUser,
577 'uid' => $this->adminUser->id(),
578 'request_uri' => $base_root . \Drupal::request()->getRequestUri(),
579 'referer' => \Drupal::request()->server->get('HTTP_REFERER'),
581 'timestamp' => REQUEST_TIME,
583 // Add a watchdog entry.
584 $this->container->get('logger.dblog')->log($log['severity'], $log['message'], $log);
585 // Make sure the table count has actually been incremented.
586 $this->assertEqual($count + 1, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), format_string('\Drupal\dblog\Logger\DbLog->log() added an entry to the dblog :count', [':count' => $count]));
587 // Log in the admin user.
588 $this->drupalLogin($this->adminUser);
589 // Post in order to clear the database table.
590 $this->clearLogsEntries();
591 // Confirm that the logs should be cleared.
592 $this->drupalPostForm(NULL, [], 'Confirm');
593 // Count the rows in watchdog that previously related to the deleted user.
594 $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
595 $this->assertEqual($count, 0, format_string('DBLog contains :count records after a clear.', [':count' => $count]));
599 * Tests the database log filter functionality at admin/reports/dblog.
601 public function testFilter() {
602 $this->drupalLogin($this->adminUser);
604 // Clear the log to ensure that only generated entries will be found.
605 db_delete('watchdog')->execute();
607 // Generate 9 random watchdog entries.
610 for ($i = 0; $i < 3; $i++) {
611 $type_names[] = $type_name = $this->randomMachineName();
612 $severity = RfcLogLevel::EMERGENCY;
613 for ($j = 0; $j < 3; $j++) {
616 'type' => $type_name,
617 'severity' => $severity++,
619 $this->generateLogEntries($type['count'], [
620 'channel' => $type['type'],
621 'severity' => $type['severity'],
626 // View the database log page.
627 $this->drupalGet('admin/reports/dblog');
629 // Confirm that all the entries are displayed.
630 $count = $this->getTypeCount($types);
631 foreach ($types as $key => $type) {
632 $this->assertEqual($count[$key], $type['count'], 'Count matched');
635 // Filter by each type and confirm that entries with various severities are
637 foreach ($type_names as $type_name) {
638 $this->filterLogsEntries($type_name);
640 // Count the number of entries of this type.
642 foreach ($types as $type) {
643 if ($type['type'] == $type_name) {
644 $type_count += $type['count'];
648 $count = $this->getTypeCount($types);
649 $this->assertEqual(array_sum($count), $type_count, 'Count matched');
652 // Set the filter to match each of the two filter-type attributes and
653 // confirm the correct number of entries are displayed.
654 foreach ($types as $type) {
655 $this->filterLogsEntries($type['type'], $type['severity']);
657 $count = $this->getTypeCount($types);
658 $this->assertEqual(array_sum($count), $type['count'], 'Count matched');
661 $this->drupalGet('admin/reports/dblog', ['query' => ['order' => 'Type']]);
662 $this->assertResponse(200);
663 $this->assertText(t('Operations'), 'Operations text found');
665 // Clear all logs and make sure the confirmation message is found.
666 $this->clearLogsEntries();
667 // Confirm that the logs should be cleared.
668 $this->drupalPostForm(NULL, [], 'Confirm');
669 $this->assertText(t('Database log cleared.'), 'Confirmation message found');
673 * Gets the database log event information from the browser page.
676 * List of log events where each event is an array with following keys:
677 * - severity: (int) A database log severity constant.
678 * - type: (string) The type of database log event.
679 * - message: (string) The message for this database log event.
680 * - user: (string) The user associated with this database log event.
682 protected function getLogEntries() {
684 if ($table = $this->getLogsEntriesTable()) {
685 $table = array_shift($table);
686 foreach ($table->tbody->tr as $row) {
688 'severity' => $this->getSeverityConstant($row['class']),
689 'type' => $this->asText($row->td[1]),
690 'message' => $this->asText($row->td[3]),
691 'user' => $this->asText($row->td[4]),
699 * Find the Logs table in the DOM.
701 * @return \SimpleXMLElement[]
702 * The return value of a xpath search.
704 protected function getLogsEntriesTable() {
705 return $this->xpath('.//table[@id="admin-dblog"]');
709 * Gets the count of database log entries by database log event type.
711 * @param array $types
712 * The type information to compare against.
715 * The count of each type keyed by the key of the $types array.
717 protected function getTypeCount(array $types) {
718 $entries = $this->getLogEntries();
719 $count = array_fill(0, count($types), 0);
720 foreach ($entries as $entry) {
721 foreach ($types as $key => $type) {
722 if ($entry['type'] == $type['type'] && $entry['severity'] == $type['severity']) {
732 * Gets the watchdog severity constant corresponding to the CSS class.
734 * @param string $class
735 * CSS class attribute.
738 * The watchdog severity constant or NULL if not found.
740 protected function getSeverityConstant($class) {
741 $map = array_flip(DbLogController::getLogLevelClassMap());
743 // Find the class that contains the severity.
744 $classes = explode(' ', $class);
745 foreach ($classes as $class) {
746 if (isset($map[$class])) {
754 * Extracts the text contained by the XHTML element.
756 * @param \SimpleXMLElement $element
757 * Element to extract text from.
762 protected function asText(\SimpleXMLElement $element) {
763 if (!is_object($element)) {
764 return $this->fail('The element is not an element.');
766 return trim(html_entity_decode(strip_tags($element->asXML())));
770 * Confirms that a log message appears on the database log overview screen.
772 * This function should only be used for the admin/reports/dblog page, because
773 * it checks for the message link text truncated to 56 characters. Other log
774 * pages have no detail links so they contain the full message text.
776 * @param string $log_message
777 * The database log message to check.
778 * @param string $message
779 * The message to pass to simpletest.
781 protected function assertLogMessage($log_message, $message) {
782 $message_text = Unicode::truncate(Html::decodeEntities(strip_tags($log_message)), 56, TRUE, TRUE);
783 $this->assertLink($message_text, 0, $message);
787 * Tests that the details page displays correctly for a temporary user.
789 public function testTemporaryUser() {
790 // Create a temporary user.
791 $tempuser = $this->drupalCreateUser();
792 $tempuser_uid = $tempuser->id();
794 // Log in as the admin user.
795 $this->drupalLogin($this->adminUser);
797 // Generate a single watchdog entry.
798 $this->generateLogEntries(1, ['user' => $tempuser, 'uid' => $tempuser_uid]);
799 $wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
801 // Check if the full message displays on the details page.
802 $this->drupalGet('admin/reports/dblog/event/' . $wid);
803 $this->assertText('Dblog test log message');
806 user_delete($tempuser->id());
807 $this->drupalGet('user/' . $tempuser_uid);
808 $this->assertResponse(404);
810 // Check if the full message displays on the details page.
811 $this->drupalGet('admin/reports/dblog/event/' . $wid);
812 $this->assertText('Dblog test log message');
816 * Make sure HTML tags are filtered out in the log overview links.
818 public function testOverviewLinks() {
819 $this->drupalLogin($this->adminUser);
820 $this->generateLogEntries(1, ['message' => "<script>alert('foo');</script><strong>Lorem</strong> ipsum dolor sit amet, consectetur adipiscing & elit."]);
821 $this->drupalGet('admin/reports/dblog');
822 $this->assertResponse(200);
823 // Make sure HTML tags are filtered out.
824 $this->assertRaw('title="alert('foo');Lorem ipsum dolor sit amet, consectetur adipiscing & elit. Entry #0"><script>alert('foo');</script>Lorem ipsum dolor sit…</a>');
825 $this->assertNoRaw("<script>alert('foo');</script>");
827 // Make sure HTML tags are filtered out in admin/reports/dblog/event/ too.
828 $this->generateLogEntries(1, ['message' => "<script>alert('foo');</script> <strong>Lorem ipsum</strong>"]);
829 $wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
830 $this->drupalGet('admin/reports/dblog/event/' . $wid);
831 $this->assertNoRaw("<script>alert('foo');</script>");
832 $this->assertRaw("alert('foo'); <strong>Lorem ipsum</strong>");