View source
<?php
namespace Drupal\Tests\dblog\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Database\Database;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\dblog\Controller\DbLogController;
use Drupal\error_test\Controller\ErrorTestController;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\system\Functional\Menu\AssertBreadcrumbTrait;
class DbLogTest extends BrowserTestBase {
use FakeLogEntries;
use AssertBreadcrumbTrait;
protected static $modules = [
'dblog',
'error_test',
'node',
'forum',
'help',
'block',
];
protected $defaultTheme = 'stark';
protected $adminUser;
protected $webUser;
protected function setUp() : void {
parent::setUp();
$this
->drupalPlaceBlock('system_breadcrumb_block');
$this
->drupalPlaceBlock('page_title_block');
$this->adminUser = $this
->drupalCreateUser([
'administer site configuration',
'access administration pages',
'access site reports',
'administer users',
]);
$this->webUser = $this
->drupalCreateUser([]);
}
public function testDbLog() {
$this
->drupalLogin($this->adminUser);
$row_limit = 100;
$this
->verifyRowLimit($row_limit);
$this
->verifyEvents();
$this
->verifyReports();
$this
->verifyBreadcrumbs();
$this
->verifyLinkEscaping();
$orders = [
'Date',
'Type',
'User',
];
$sorts = [
'asc',
'desc',
];
foreach ($orders as $order) {
foreach ($sorts as $sort) {
$this
->verifySort($sort, $order);
}
}
$this
->drupalLogin($this->webUser);
$this
->verifyReports(403);
}
public function testLogEventPage() {
$this
->drupalLogin($this->adminUser);
$context = [
'request_uri' => 'http://example.com?dblog=1',
'referer' => 'http://example.org?dblog=2',
'uid' => 0,
'channel' => 'testing',
'link' => 'foo/bar',
'ip' => '0.0.1.0',
'timestamp' => REQUEST_TIME,
];
\Drupal::service('logger.dblog')
->log(RfcLogLevel::NOTICE, 'Test message', $context);
$query = Database::getConnection()
->select('watchdog');
$query
->addExpression('MAX([wid])');
$wid = $query
->execute()
->fetchField();
$this
->drupalGet('admin/reports/dblog/event/' . $wid);
$this
->assertSession()
->linkByHrefExists($context['request_uri']);
$this
->assertSession()
->linkByHrefExists($context['referer']);
$this
->assertSession()
->pageTextContains($context['ip']);
$this
->assertSession()
->pageTextContains($context['request_uri']);
$this
->assertSession()
->pageTextContains('Notice');
}
public function test403LogEventPage() {
$assert_session = $this
->assertSession();
$uri = 'admin/reports';
$this
->drupalLogin($this->webUser);
$this
->drupalGet($uri);
$assert_session
->statusCodeEquals(403);
$this
->drupalLogin($this->adminUser);
$query = Database::getConnection()
->select('watchdog')
->condition('type', 'access denied');
$query
->addExpression('MAX([wid])');
$wid = $query
->execute()
->fetchField();
$this
->drupalGet('admin/reports/dblog/event/' . $wid);
$table = $this
->xpath("//table[@class='dblog-event']");
$this
->assertCount(1, $table);
$type = $table[0]
->findAll('xpath', "//tr/th[contains(text(), 'Type')]/../td");
$this
->assertCount(1, $type);
$this
->assertEquals('access denied', $type[0]
->getText());
$severity = $table[0]
->findAll('xpath', "//tr/th[contains(text(), 'Severity')]/../td");
$this
->assertCount(1, $severity);
$this
->assertEquals('Warning', $severity[0]
->getText());
$location = $table[0]
->findAll('xpath', "//tr/th[contains(text(), 'Location')]/../td/a");
$this
->assertCount(1, $location);
$href = $location[0]
->getAttribute('href');
$this
->assertEquals($this->baseUrl . '/' . $uri, $href);
$message = $table[0]
->findAll('xpath', "//tr/th[contains(text(), 'Message')]/../td");
$this
->assertCount(1, $message);
$regex = "@Path: .+admin/reports\\. Drupal\\\\Core\\\\Http\\\\Exception\\\\CacheableAccessDeniedHttpException: The 'access site reports' permission is required\\. in Drupal\\\\Core\\\\Routing\\\\AccessAwareRouter->checkAccess\\(\\) \\(line \\d+ of .+/core/lib/Drupal/Core/Routing/AccessAwareRouter\\.php\\)\\.@";
$this
->assertMatchesRegularExpression($regex, $message[0]
->getText());
}
public function testLogEventNotFoundPage() {
$this
->drupalLogin($this->adminUser);
$this
->drupalGet('admin/reports/dblog/event/999999');
$this
->assertSession()
->statusCodeEquals(404);
}
public function testLogEventPageWithMissingInfo() {
$this
->drupalLogin($this->adminUser);
$connection = Database::getConnection();
$this
->generateLogEntries(1, [
'referer' => NULL,
]);
$query = $connection
->select('watchdog');
$query
->addExpression('MAX([wid])');
$wid = $query
->execute()
->fetchField();
$this
->drupalGet('admin/reports/dblog/event/' . $wid);
$this
->assertSession()
->pageTextContains('Referrer');
$this
->assertSession()
->pageTextContains('Notice');
$request_uri = '/some/incorrect/url';
$this
->generateLogEntries(1, [
'request_uri' => $request_uri,
]);
$query = $connection
->select('watchdog');
$query
->addExpression('MAX([wid])');
$wid = $query
->execute()
->fetchField();
$this
->drupalGet('admin/reports/dblog/event/' . $wid);
$this
->assertSession()
->pageTextContains('Location');
$this
->assertSession()
->pageTextContains('Notice');
$this
->assertEquals($request_uri, $this
->cssSelect('table.dblog-event > tbody > tr:nth-child(4) > td')[0]
->getHtml());
$this
->assertSession()
->linkNotExists($request_uri);
}
public function testMessageParsing() {
$this
->drupalLogin($this->adminUser);
\Drupal::service('logger.factory')
->get("php")
->error('Incorrect parameter {{foo}} in path {path}: {value}', [
'foo' => 'bar',
'path' => '/baz',
'value' => 'horse',
]);
$wid = \Drupal::database()
->query('SELECT MAX(wid) FROM {watchdog}')
->fetchField();
$this
->drupalGet('admin/reports/dblog/event/' . $wid);
$this
->assertSession()
->responseContains('Incorrect parameter {bar} in path /baz: horse');
}
private function verifyRowLimit($row_limit) {
$edit = [];
$edit['dblog_row_limit'] = $row_limit;
$this
->drupalGet('admin/config/development/logging');
$this
->submitForm($edit, 'Save configuration');
$this
->assertSession()
->statusCodeEquals(200);
$current_limit = $this
->config('dblog.settings')
->get('row_limit');
$this
->assertEquals($current_limit, $row_limit, new FormattableMarkup('[Cache] Row limit variable of @count equals row limit of @limit', [
'@count' => $current_limit,
'@limit' => $row_limit,
]));
}
protected function clearLogsEntries() {
$this
->drupalGet(Url::fromRoute('dblog.confirm'));
}
protected function filterLogsEntries($type = NULL, $severity = NULL) {
$edit = [];
if (isset($type)) {
$edit['type[]'] = $type;
}
if (isset($severity)) {
$edit['severity[]'] = $severity;
}
$this
->submitForm($edit, 'Filter');
}
private function verifyReports($response = 200) {
$this
->drupalGet('admin/help/dblog');
$this
->assertSession()
->statusCodeEquals($response);
if ($response == 200) {
$this
->assertSession()
->pageTextContains('Database Logging');
}
$this
->drupalGet('admin/reports/dblog');
$this
->assertSession()
->statusCodeEquals($response);
if ($response == 200) {
$this
->assertSession()
->pageTextContains('Recent log messages');
}
$this
->drupalGet('admin/reports/dblog/confirm');
$this
->assertSession()
->statusCodeEquals($response);
if ($response == 200) {
$this
->assertSession()
->pageTextContains('Are you sure you want to delete the recent logs?');
}
$this
->drupalGet('admin/reports/page-not-found');
$this
->assertSession()
->statusCodeEquals($response);
if ($response == 200) {
$this
->assertSession()
->pageTextContains("Top 'page not found' errors");
}
$this
->drupalGet('admin/reports/access-denied');
$this
->assertSession()
->statusCodeEquals($response);
if ($response == 200) {
$this
->assertSession()
->pageTextContains("Top 'access denied' errors");
}
$query = Database::getConnection()
->select('watchdog');
$query
->addExpression('MIN([wid])');
$wid = $query
->execute()
->fetchField();
$this
->drupalGet('admin/reports/dblog/event/' . $wid);
$this
->assertSession()
->statusCodeEquals($response);
if ($response == 200) {
$this
->assertSession()
->pageTextContains('Details');
}
}
private function verifyBreadcrumbs() {
$query = Database::getConnection()
->select('watchdog');
$query
->addExpression('MIN([wid])');
$wid = $query
->execute()
->fetchField();
$trail = [
'' => 'Home',
'admin' => 'Administration',
'admin/reports' => 'Reports',
'admin/reports/dblog' => 'Recent log messages',
];
$this
->assertBreadcrumb('admin/reports/dblog/event/' . $wid, $trail);
}
private function verifyEvents() {
$this
->doUser();
$this
->drupalCreateContentType([
'type' => 'article',
'name' => 'Article',
]);
$this
->drupalCreateContentType([
'type' => 'page',
'name' => 'Basic page',
]);
$this
->doNode('article');
$this
->doNode('page');
$this
->doNode('forum');
}
public function verifySort($sort = 'asc', $order = 'Date') {
$this
->drupalGet('admin/reports/dblog', [
'query' => [
'sort' => $sort,
'order' => $order,
],
]);
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->pageTextContains('Recent log messages');
}
private function verifyLinkEscaping() {
$link = Link::fromTextAndUrl('View', Url::fromRoute('entity.node.canonical', [
'node' => 1,
]))
->toString();
$message = 'Log entry added to do the verifyLinkEscaping test.';
$this
->generateLogEntries(1, [
'message' => $message,
'link' => $link,
]);
$result = Database::getConnection()
->select('watchdog', 'w')
->fields('w', [
'wid',
])
->orderBy('wid', 'DESC')
->range(0, 1)
->execute();
$this
->drupalGet('admin/reports/dblog/event/' . $result
->fetchField());
$this
->assertSession()
->responseContains($link);
}
private function doUser() {
$name = $this
->randomMachineName();
$pass = \Drupal::service('password_generator')
->generate();
$edit = [];
$edit['name'] = $name;
$edit['mail'] = $name . '@example.com';
$edit['pass[pass1]'] = $pass;
$edit['pass[pass2]'] = $pass;
$edit['status'] = 1;
$this
->drupalGet('admin/people/create');
$this
->submitForm($edit, 'Create new account');
$this
->assertSession()
->statusCodeEquals(200);
$user = user_load_by_name($name);
$this
->assertNotNull($user, new FormattableMarkup('User @name was loaded', [
'@name' => $name,
]));
$user->passRaw = $pass;
$this
->drupalLogin($user);
$this
->drupalLogout();
$result = Database::getConnection()
->select('watchdog', 'w')
->fields('w', [
'wid',
])
->condition('uid', $user
->id())
->execute();
foreach ($result as $row) {
$ids[] = $row->wid;
}
$count_before = isset($ids) ? count($ids) : 0;
$this
->assertGreaterThan(0, $count_before, new FormattableMarkup('DBLog contains @count records for @name', [
'@count' => $count_before,
'@name' => $user
->getAccountName(),
]));
$this
->drupalLogin($this->adminUser);
$this
->drupalGet('user/' . $user
->id() . '/cancel');
$this
->submitForm([
'user_cancel_method' => 'user_cancel_reassign',
], 'Confirm');
$this
->drupalGet('admin/reports/dblog');
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertLogMessage("New user: {$name} <{$user->getEmail()}>.", 'DBLog event was recorded: [add user]');
$this
->assertLogMessage("Session opened for {$name}.", 'DBLog event was recorded: [login user]');
$this
->assertLogMessage("Session closed for {$name}.", 'DBLog event was recorded: [logout user]');
$message = "Deleted user: {$name} <{$user->getEmail()}>.";
$message_text = Unicode::truncate($message, 56, TRUE, TRUE);
$link = FALSE;
if ($links = $this
->xpath('//a[text()="' . $message_text . '"]')) {
$links = array_shift($links);
$value = $links
->getAttribute('href');
$link = mb_substr($value, strpos($value, 'admin/reports/dblog/event/'));
$this
->drupalGet($link);
$this
->assertSession()
->pageTextContains($message);
}
$this
->assertNotEmpty($link, 'DBLog event was recorded: [delete user]');
$not_found_url = $this
->randomMachineName(60);
$this
->drupalGet($not_found_url);
$this
->assertSession()
->statusCodeEquals(404);
$this
->drupalGet('admin/reports/page-not-found');
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->pageTextContains($not_found_url);
}
private function doNode($type) {
$perm = [
'create ' . $type . ' content',
'edit own ' . $type . ' content',
'delete own ' . $type . ' content',
];
$user = $this
->drupalCreateUser($perm);
$this
->drupalLogin($user);
$edit = $this
->getContent($type);
$title = $edit['title[0][value]'];
$this
->drupalGet('node/add/' . $type);
$this
->submitForm($edit, 'Save');
$this
->assertSession()
->statusCodeEquals(200);
$node = $this
->drupalGetNodeByTitle($title);
$this
->assertNotNull($node, new FormattableMarkup('Node @title was loaded', [
'@title' => $title,
]));
$edit = $this
->getContentUpdate($type);
$this
->drupalGet('node/' . $node
->id() . '/edit');
$this
->submitForm($edit, 'Save');
$this
->assertSession()
->statusCodeEquals(200);
$this
->drupalGet('node/' . $node
->id() . '/delete');
$this
->submitForm([], 'Delete');
$this
->assertSession()
->statusCodeEquals(200);
$this
->drupalGet('node/' . $node
->id());
$this
->assertSession()
->statusCodeEquals(404);
$this
->drupalGet('admin/reports/dblog');
$this
->assertSession()
->statusCodeEquals(403);
$this
->drupalLogin($this->adminUser);
$this
->drupalGet('admin/reports/dblog');
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertLogMessage("{$type}: added {$title}.", 'DBLog event was recorded: [content added]');
$this
->assertLogMessage("{$type}: updated {$title}.", 'DBLog event was recorded: [content updated]');
$this
->assertLogMessage("{$type}: deleted {$title}.", 'DBLog event was recorded: [content deleted]');
$this
->drupalGet('admin/reports/access-denied');
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->pageTextContains('admin/reports/dblog');
$this
->drupalGet('admin/reports/page-not-found');
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->pageTextContains('node/' . $node
->id());
}
private function getContent($type) {
switch ($type) {
case 'forum':
$content = [
'title[0][value]' => $this
->randomMachineName(8),
'taxonomy_forums' => 1,
'body[0][value]' => $this
->randomMachineName(32),
];
break;
default:
$content = [
'title[0][value]' => $this
->randomMachineName(8),
'body[0][value]' => $this
->randomMachineName(32),
];
break;
}
return $content;
}
private function getContentUpdate($type) {
$content = [
'body[0][value]' => $this
->randomMachineName(32),
];
return $content;
}
public function testDBLogAddAndClear() {
global $base_root;
$connection = Database::getConnection();
$count = $connection
->select('watchdog')
->countQuery()
->execute()
->fetchField();
$log = [
'channel' => 'system',
'message' => 'Log entry added to test the doClearTest clear down.',
'variables' => [],
'severity' => RfcLogLevel::NOTICE,
'link' => NULL,
'uid' => $this->adminUser
->id(),
'request_uri' => $base_root . \Drupal::request()
->getRequestUri(),
'referer' => \Drupal::request()->server
->get('HTTP_REFERER'),
'ip' => '127.0.0.1',
'timestamp' => REQUEST_TIME,
];
$this->container
->get('logger.dblog')
->log($log['severity'], $log['message'], $log);
$this
->assertEquals($count + 1, (int) $connection
->select('watchdog')
->countQuery()
->execute()
->fetchField(), new FormattableMarkup('\\Drupal\\dblog\\Logger\\DbLog->log() added an entry to the dblog :count', [
':count' => $count,
]));
$this
->drupalLogin($this->adminUser);
$this
->clearLogsEntries();
$this
->submitForm([], 'Confirm');
$count = $connection
->select('watchdog')
->countQuery()
->execute()
->fetchField();
$this
->assertEquals(0, $count, new FormattableMarkup('DBLog contains :count records after a clear.', [
':count' => $count,
]));
}
public function testFilter() {
$this
->drupalLogin($this->adminUser);
Database::getConnection()
->delete('watchdog')
->execute();
$type_names = [];
$types = [];
for ($i = 0; $i < 3; $i++) {
$type_names[] = $type_name = $this
->randomMachineName();
$severity = RfcLogLevel::EMERGENCY;
for ($j = 0; $j < 3; $j++) {
$types[] = $type = [
'count' => $j + 1,
'type' => $type_name,
'severity' => $severity++,
];
$this
->generateLogEntries($type['count'], [
'channel' => $type['type'],
'severity' => $type['severity'],
]);
}
}
$this
->drupalGet('admin/reports/dblog');
$count = $this
->getTypeCount($types);
foreach ($types as $key => $type) {
$this
->assertEquals($type['count'], $count[$key], 'Count matched');
}
foreach ($type_names as $type_name) {
$this
->filterLogsEntries($type_name);
$type_count = 0;
foreach ($types as $type) {
if ($type['type'] == $type_name) {
$type_count += $type['count'];
}
}
$count = $this
->getTypeCount($types);
$this
->assertEquals($type_count, array_sum($count), 'Count matched');
}
foreach ($types as $type) {
$this
->filterLogsEntries($type['type'], $type['severity']);
$count = $this
->getTypeCount($types);
$this
->assertEquals($type['count'], array_sum($count), 'Count matched');
}
$this
->drupalGet('admin/reports/dblog', [
'query' => [
'order' => 'Type',
],
]);
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->pageTextContains('Operations');
$this
->clearLogsEntries();
$this
->submitForm([], 'Confirm');
$this
->assertSession()
->pageTextContains('Database log cleared.');
}
protected function getLogEntries() {
$entries = [];
if ($table = $this
->getLogsEntriesTable()) {
foreach ($table as $row) {
$cells = $row
->findAll('css', 'td');
$entries[] = [
'severity' => $this
->getSeverityConstant($row
->getAttribute('class')),
'type' => $cells[1]
->getText(),
'message' => $cells[3]
->getText(),
'user' => $cells[4]
->getText(),
];
}
}
return $entries;
}
protected function getLogsEntriesTable() {
return $this
->xpath('.//table[@id="admin-dblog"]/tbody/tr');
}
protected function getTypeCount(array $types) {
$entries = $this
->getLogEntries();
$count = array_fill(0, count($types), 0);
foreach ($entries as $entry) {
foreach ($types as $key => $type) {
if ($entry['type'] == $type['type'] && $entry['severity'] == $type['severity']) {
$count[$key]++;
break;
}
}
}
return $count;
}
protected function getSeverityConstant($class) {
$map = array_flip(DbLogController::getLogLevelClassMap());
$classes = explode(' ', $class);
foreach ($classes as $class) {
if (isset($map[$class])) {
return $map[$class];
}
}
return NULL;
}
protected function assertLogMessage(string $log_message, string $message) : void {
$message_text = Unicode::truncate($log_message, 56, TRUE, TRUE);
$this
->assertSession()
->linkExists($message_text, 0, $message);
}
public function testTemporaryUser() {
$tempuser = $this
->drupalCreateUser();
$tempuser_uid = $tempuser
->id();
$this
->drupalLogin($this->adminUser);
$this
->generateLogEntries(1, [
'user' => $tempuser,
'uid' => $tempuser_uid,
]);
$query = Database::getConnection()
->select('watchdog');
$query
->addExpression('MAX([wid])');
$wid = $query
->execute()
->fetchField();
$this
->drupalGet('admin/reports/dblog/event/' . $wid);
$this
->assertSession()
->pageTextContains('Dblog test log message');
$tempuser
->delete();
$this
->drupalGet('user/' . $tempuser_uid);
$this
->assertSession()
->statusCodeEquals(404);
$this
->drupalGet('admin/reports/dblog/event/' . $wid);
$this
->assertSession()
->pageTextContains('Dblog test log message');
}
public function testOverviewLinks() {
$this
->drupalLogin($this->adminUser);
$this
->generateLogEntries(1, [
'message' => "<script>alert('foo');</script><strong>Lorem</strong> ipsum dolor sit amet, consectetur adipiscing & elit.",
]);
$this
->drupalGet('admin/reports/dblog');
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->responseContains('title="alert('foo');Lorem');
$this
->assertSession()
->responseNotContains("<script>alert('foo');</script>");
$this
->generateLogEntries(1, [
'message' => "<script>alert('foo');</script> <strong>Lorem ipsum</strong>",
]);
$query = Database::getConnection()
->select('watchdog');
$query
->addExpression('MAX([wid])');
$wid = $query
->execute()
->fetchField();
$this
->drupalGet('admin/reports/dblog/event/' . $wid);
$this
->assertSession()
->responseNotContains("<script>alert('foo');</script>");
$this
->assertSession()
->responseContains("alert('foo'); <strong>Lorem ipsum</strong>");
}
public function testSameTimestampEntries() {
$this
->drupalLogin($this->adminUser);
$this
->generateLogEntries(1, [
'timestamp' => 1498062000,
'type' => 'same_time',
'message' => 'First',
]);
$this
->generateLogEntries(1, [
'timestamp' => 1498062000,
'type' => 'same_time',
'message' => 'Second',
]);
$this
->generateLogEntries(1, [
'timestamp' => 1498062000,
'type' => 'same_time',
'message' => 'Third',
]);
$this
->drupalGet('admin/reports/dblog');
$entries = $this
->getLogEntries();
$this
->assertEquals('Third Entry #0', $entries[0]['message']);
$this
->assertEquals('Second Entry #0', $entries[1]['message']);
$this
->assertEquals('First Entry #0', $entries[2]['message']);
}
public function testBacktrace() {
$this
->drupalLogin($this->adminUser);
$this
->drupalGet('/error-test/generate-warnings');
$query = Database::getConnection()
->select('watchdog');
$query
->addExpression('MAX([wid])');
$wid = $query
->execute()
->fetchField();
$this
->drupalGet('admin/reports/dblog/event/' . $wid);
$error_user_notice = [
'%type' => 'User warning',
'@message' => 'Drupal & awesome',
'%function' => ErrorTestController::class . '->generateWarnings()',
'%file' => $this
->getModulePath('error_test') . '/error_test.module',
];
$message = new FormattableMarkup('%type: @message in %function (line', $error_user_notice);
$this
->assertSession()
->responseContains($message);
$this
->assertSession()
->responseContains('<pre class="backtrace">');
}
}