db backup prior to drupal security update
[yaffs-website] / web / core / modules / dblog / src / Tests / DbLogTest.php
1 <?php
2
3 namespace Drupal\dblog\Tests;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Core\Logger\RfcLogLevel;
8 use Drupal\Core\Url;
9 use Drupal\dblog\Controller\DbLogController;
10 use Drupal\simpletest\WebTestBase;
11
12 /**
13  * Generate events and verify dblog entries; verify user access to log reports
14  * based on permissions.
15  *
16  * @group dblog
17  */
18 class DbLogTest extends WebTestBase {
19
20   /**
21    * Modules to enable.
22    *
23    * @var array
24    */
25   public static $modules = ['dblog', 'node', 'forum', 'help', 'block'];
26
27   /**
28    * A user with some relevant administrative permissions.
29    *
30    * @var \Drupal\user\UserInterface
31    */
32   protected $adminUser;
33
34   /**
35    * A user without any permissions.
36    *
37    * @var \Drupal\user\UserInterface
38    */
39   protected $webUser;
40
41   /**
42    * {@inheritdoc}
43    */
44   protected function setUp() {
45     parent::setUp();
46     $this->drupalPlaceBlock('system_breadcrumb_block');
47     $this->drupalPlaceBlock('page_title_block');
48
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([]);
52   }
53
54   /**
55    * Tests Database Logging module functionality through interfaces.
56    *
57    * First logs in users, then creates database log events, and finally tests
58    * Database Logging module functionality through both the admin and user
59    * interfaces.
60    */
61   public function testDbLog() {
62     // Log in the admin user.
63     $this->drupalLogin($this->adminUser);
64
65     $row_limit = 100;
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);
78       }
79     }
80
81     // Log in the regular user.
82     $this->drupalLogin($this->webUser);
83     $this->verifyReports(403);
84   }
85
86   /**
87    * Test individual log event page.
88    */
89   public function testLogEventPage() {
90     // Login the admin user.
91     $this->drupalLogin($this->adminUser);
92
93     // Since referrer and location links vary by how the tests are run, inject
94     // fake log data to test these.
95     $context = [
96       'request_uri' => 'http://example.com?dblog=1',
97       'referer' => 'http://example.org?dblog=2',
98       'uid' => 0,
99       'channel' => 'testing',
100       'link' => 'foo/bar',
101       'ip' => '0.0.1.0',
102       'timestamp' => REQUEST_TIME,
103     ];
104     \Drupal::service('logger.dblog')->log(RfcLogLevel::NOTICE, 'Test message', $context);
105     $wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
106
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']);
111
112     // Verify hostname.
113     $this->assertRaw($context['ip'], 'Found hostname on the detail page.');
114
115     // Verify severity.
116     $this->assertText('Notice', 'The severity was properly displayed on the detail page.');
117   }
118
119   /**
120    * Verifies setting of the database log row limit.
121    *
122    * @param int $row_limit
123    *   The row limit.
124    */
125   private function verifyRowLimit($row_limit) {
126     // Change the database log row limit.
127     $edit = [];
128     $edit['dblog_row_limit'] = $row_limit;
129     $this->drupalPostForm('admin/config/development/logging', $edit, t('Save configuration'));
130     $this->assertResponse(200);
131
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]));
135   }
136
137   /**
138    * Verifies that cron correctly applies the database log row limit.
139    *
140    * @param int $row_limit
141    *   The row limit.
142    */
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]));
149
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]));
155
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]));
160   }
161
162   /**
163    * Runs cron and returns number of new log entries.
164    *
165    * @return int
166    *   Number of new watchdog entries.
167    */
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();
173
174     // Run a cron job.
175     $this->cronRun();
176
177     // Get last ID after cron was run.
178     $current_id = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
179
180     return $current_id - $last_id;
181   }
182
183   /**
184    * Generates a number of random database log events.
185    *
186    * @param int $count
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
203    *     entry.
204    *   - 'timestamp': Int unix timestamp.
205    */
206   private function generateLogEntries($count, $options = []) {
207     global $base_root;
208
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%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%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%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%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%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%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');
213
214     // Prepare the fields to be logged
215     $log = $options + [
216       'channel'     => 'custom',
217       'message'     => 'Dblog test log message',
218       'variables'   => [],
219       'severity'    => RfcLogLevel::NOTICE,
220       'link'        => $link,
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'),
225       'ip'          => '127.0.0.1',
226       'timestamp'   => REQUEST_TIME,
227     ];
228
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);
234     }
235   }
236
237   /**
238    * Clear the entry logs by clicking on 'Clear log messages' button.
239    */
240   protected function clearLogsEntries() {
241     $this->drupalGet(Url::fromRoute('dblog.confirm'));
242   }
243
244   /**
245    * Filters the logs according to the specific severity and log entry type.
246    *
247    * @param string $type
248    *   (optional) The log entry type.
249    * @param string $severity
250    *   (optional) The log entry severity.
251   */
252   protected function filterLogsEntries($type = NULL, $severity = NULL) {
253     $edit = [];
254     if (!is_null($type)) {
255       $edit['type[]'] = $type;
256     }
257     if (!is_null($severity)) {
258       $edit['severity[]'] = $severity;
259     }
260     $this->drupalPostForm(NULL, $edit, t('Filter'));
261   }
262
263   /**
264    * Confirms that database log reports are displayed at the correct paths.
265    *
266    * @param int $response
267    *   (optional) HTTP response code. Defaults to 200.
268    */
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');
275     }
276
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');
282     }
283
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');
289     }
290
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');
296     }
297
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');
304     }
305   }
306
307   /**
308    * Generates and then verifies breadcrumbs.
309    */
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.');
316   }
317
318   /**
319    * Generates and then verifies various types of events.
320    */
321   private function verifyEvents() {
322     // Invoke events.
323     $this->doUser();
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');
329
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
332     // set to zero.
333   }
334
335   /**
336    * Verifies the sorting functionality of the database logging reports table.
337    *
338    * @param string $sort
339    *   The sort direction.
340    * @param string $order
341    *   The order by which the table should be sorted.
342    */
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.');
347   }
348
349   /**
350    * Tests the escaping of links in the operation row of a database log detail
351    * page.
352    */
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,
358       'link' => $link,
359     ]);
360
361     $result = db_query_range('SELECT wid FROM {watchdog} ORDER BY wid DESC', 0, 1);
362     $this->drupalGet('admin/reports/dblog/event/' . $result->fetchField());
363
364     // Check if the link exists (unescaped).
365     $this->assertRaw($link);
366   }
367
368   /**
369    * Generates and then verifies some user events.
370    */
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).
377     $edit = [];
378     $edit['name'] = $name;
379     $edit['mail'] = $name . '@example.com';
380     $edit['pass[pass1]'] = $pass;
381     $edit['pass[pass2]'] = $pass;
382     $edit['status'] = 1;
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;
390     // Log in user.
391     $this->drupalLogin($user);
392     // Log out 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) {
397       $ids[] = $row->wid;
398     }
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()]));
401
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'));
407
408     // View the database log report.
409     $this->drupalGet('admin/reports/dblog');
410     $this->assertResponse(200);
411
412     // Verify that the expected events were recorded.
413     // Add user.
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]');
417     // Log in user.
418     $this->assertLogMessage(t('Session opened for %name.', ['%name' => $name]), 'DBLog event was recorded: [login user]');
419     // Log out user.
420     $this->assertLogMessage(t('Session closed for %name.', ['%name' => $name]), 'DBLog event was recorded: [logout user]');
421     // Delete 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.
425     $link = FALSE;
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]');
436           break;
437         }
438       }
439     }
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]');
450   }
451
452   /**
453    * Generates and then verifies some node events.
454    *
455    * @param string $type
456    *   A node type (e.g., 'article', 'page' or 'forum').
457    */
458   private function doNode($type) {
459     // Create user.
460     $perm = ['create ' . $type . ' content', 'edit own ' . $type . ' content', 'delete own ' . $type . ' content'];
461     $user = $this->drupalCreateUser($perm);
462     // Log in user.
463     $this->drupalLogin($user);
464
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]));
474     // Edit the node.
475     $edit = $this->getContentUpdate($type);
476     $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save'));
477     $this->assertResponse(200);
478     // Delete the node.
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);
487
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);
493
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]');
501
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]');
507
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]');
513   }
514
515   /**
516    * Creates random content based on node content type.
517    *
518    * @param string $type
519    *   Node content type (e.g., 'article').
520    *
521    * @return array
522    *   Random content needed by various node types.
523    */
524   private function getContent($type) {
525     switch ($type) {
526       case 'forum':
527         $content = [
528           'title[0][value]' => $this->randomMachineName(8),
529           'taxonomy_forums' => [1],
530           'body[0][value]' => $this->randomMachineName(32),
531         ];
532         break;
533
534       default:
535         $content = [
536           'title[0][value]' => $this->randomMachineName(8),
537           'body[0][value]' => $this->randomMachineName(32),
538         ];
539         break;
540     }
541     return $content;
542   }
543
544   /**
545    * Creates random content as an update based on node content type.
546    *
547    * @param string $type
548    *   Node content type (e.g., 'article').
549    *
550    * @return array
551    *   Random content needed by various node types.
552    */
553   private function getContentUpdate($type) {
554     $content = [
555       'body[0][value]' => $this->randomMachineName(32),
556     ];
557     return $content;
558   }
559
560   /**
561    * Tests the addition and clearing of log events through the admin interface.
562    *
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.
565    */
566   public function testDBLogAddAndClear() {
567     global $base_root;
568     // Get a count of how many watchdog entries already exist.
569     $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
570     $log = [
571       'channel'     => 'system',
572       'message'     => 'Log entry added to test the doClearTest clear down.',
573       'variables'   => [],
574       'severity'    => RfcLogLevel::NOTICE,
575       'link'        => NULL,
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'),
580       'ip'          => '127.0.0.1',
581       'timestamp'   => REQUEST_TIME,
582     ];
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]));
596   }
597
598   /**
599    * Tests the database log filter functionality at admin/reports/dblog.
600    */
601   public function testFilter() {
602     $this->drupalLogin($this->adminUser);
603
604     // Clear the log to ensure that only generated entries will be found.
605     db_delete('watchdog')->execute();
606
607     // Generate 9 random watchdog entries.
608     $type_names = [];
609     $types = [];
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++) {
614         $types[] = $type = [
615           'count' => $j + 1,
616           'type' => $type_name,
617           'severity' => $severity++,
618         ];
619         $this->generateLogEntries($type['count'], [
620           'channel' => $type['type'],
621           'severity' => $type['severity'],
622         ]);
623       }
624     }
625
626     // View the database log page.
627     $this->drupalGet('admin/reports/dblog');
628
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');
633     }
634
635     // Filter by each type and confirm that entries with various severities are
636     // displayed.
637     foreach ($type_names as $type_name) {
638       $this->filterLogsEntries($type_name);
639
640       // Count the number of entries of this type.
641       $type_count = 0;
642       foreach ($types as $type) {
643         if ($type['type'] == $type_name) {
644           $type_count += $type['count'];
645         }
646       }
647
648       $count = $this->getTypeCount($types);
649       $this->assertEqual(array_sum($count), $type_count, 'Count matched');
650     }
651
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']);
656
657       $count = $this->getTypeCount($types);
658       $this->assertEqual(array_sum($count), $type['count'], 'Count matched');
659     }
660
661     $this->drupalGet('admin/reports/dblog', ['query' => ['order' => 'Type']]);
662     $this->assertResponse(200);
663     $this->assertText(t('Operations'), 'Operations text found');
664
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');
670   }
671
672   /**
673    * Gets the database log event information from the browser page.
674    *
675    * @return array
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.
681    */
682   protected function getLogEntries() {
683     $entries = [];
684     if ($table = $this->getLogsEntriesTable()) {
685       $table = array_shift($table);
686       foreach ($table->tbody->tr as $row) {
687         $entries[] = [
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]),
692         ];
693       }
694     }
695     return $entries;
696   }
697
698   /**
699    * Find the Logs table in the DOM.
700    *
701    * @return \SimpleXMLElement[]
702    *   The return value of a xpath search.
703    */
704   protected function getLogsEntriesTable() {
705     return $this->xpath('.//table[@id="admin-dblog"]');
706   }
707
708   /**
709    * Gets the count of database log entries by database log event type.
710    *
711    * @param array $types
712    *   The type information to compare against.
713    *
714    * @return array
715    *   The count of each type keyed by the key of the $types array.
716    */
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']) {
723           $count[$key]++;
724           break;
725         }
726       }
727     }
728     return $count;
729   }
730
731   /**
732    * Gets the watchdog severity constant corresponding to the CSS class.
733    *
734    * @param string $class
735    *   CSS class attribute.
736    *
737    * @return int|null
738    *   The watchdog severity constant or NULL if not found.
739    */
740   protected function getSeverityConstant($class) {
741     $map = array_flip(DbLogController::getLogLevelClassMap());
742
743     // Find the class that contains the severity.
744     $classes = explode(' ', $class);
745     foreach ($classes as $class) {
746       if (isset($map[$class])) {
747         return $map[$class];
748       }
749     }
750     return NULL;
751   }
752
753   /**
754    * Extracts the text contained by the XHTML element.
755    *
756    * @param \SimpleXMLElement $element
757    *   Element to extract text from.
758    *
759    * @return string
760    *   Extracted text.
761    */
762   protected function asText(\SimpleXMLElement $element) {
763     if (!is_object($element)) {
764       return $this->fail('The element is not an element.');
765     }
766     return trim(html_entity_decode(strip_tags($element->asXML())));
767   }
768
769   /**
770    * Confirms that a log message appears on the database log overview screen.
771    *
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.
775    *
776    * @param string $log_message
777    *   The database log message to check.
778    * @param string $message
779    *   The message to pass to simpletest.
780    */
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);
784   }
785
786   /**
787    * Tests that the details page displays correctly for a temporary user.
788    */
789   public function testTemporaryUser() {
790     // Create a temporary user.
791     $tempuser = $this->drupalCreateUser();
792     $tempuser_uid = $tempuser->id();
793
794     // Log in as the admin user.
795     $this->drupalLogin($this->adminUser);
796
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();
800
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');
804
805     // Delete the user.
806     user_delete($tempuser->id());
807     $this->drupalGet('user/' . $tempuser_uid);
808     $this->assertResponse(404);
809
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');
813   }
814
815   /**
816    * Make sure HTML tags are filtered out in the log overview links.
817    */
818   public function testOverviewLinks() {
819     $this->drupalLogin($this->adminUser);
820     $this->generateLogEntries(1, ['message' => "&lt;script&gt;alert('foo');&lt;/script&gt;<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(&#039;foo&#039;);Lorem ipsum dolor sit amet, consectetur adipiscing &amp; elit. Entry #0">&lt;script&gt;alert(&#039;foo&#039;);&lt;/script&gt;Lorem ipsum dolor sit…</a>');
825     $this->assertNoRaw("<script>alert('foo');</script>");
826
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>");
833   }
834
835 }