dblog.test 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. <?php
  2. /**
  3. * @file
  4. * Tests for dblog.module.
  5. */
  6. /**
  7. * Tests logging messages to the database.
  8. */
  9. class DBLogTestCase extends DrupalWebTestCase {
  10. /**
  11. * A user with some relevant administrative permissions.
  12. *
  13. * @var object
  14. */
  15. protected $big_user;
  16. /**
  17. * A user without any permissions.
  18. *
  19. * @var object
  20. */
  21. protected $any_user;
  22. public static function getInfo() {
  23. return array(
  24. 'name' => 'DBLog functionality',
  25. 'description' => 'Generate events and verify dblog entries; verify user access to log reports based on persmissions.',
  26. 'group' => 'DBLog',
  27. );
  28. }
  29. /**
  30. * Enable modules and create users with specific permissions.
  31. */
  32. function setUp() {
  33. parent::setUp('dblog', 'blog', 'poll');
  34. // Create users.
  35. $this->big_user = $this->drupalCreateUser(array('administer site configuration', 'access administration pages', 'access site reports', 'administer users'));
  36. $this->any_user = $this->drupalCreateUser(array());
  37. }
  38. /**
  39. * Tests Database Logging module functionality through interfaces.
  40. *
  41. * First logs in users, then creates database log events, and finally tests
  42. * Database Logging module functionality through both the admin and user
  43. * interfaces.
  44. */
  45. function testDBLog() {
  46. // Login the admin user.
  47. $this->drupalLogin($this->big_user);
  48. $row_limit = 100;
  49. $this->verifyRowLimit($row_limit);
  50. $this->verifyCron($row_limit);
  51. $this->verifyEvents();
  52. $this->verifyReports();
  53. // Login the regular user.
  54. $this->drupalLogin($this->any_user);
  55. $this->verifyReports(403);
  56. }
  57. /**
  58. * Verifies setting of the database log row limit.
  59. *
  60. * @param int $row_limit
  61. * The row limit.
  62. */
  63. private function verifyRowLimit($row_limit) {
  64. // Change the database log row limit.
  65. $edit = array();
  66. $edit['dblog_row_limit'] = $row_limit;
  67. $this->drupalPost('admin/config/development/logging', $edit, t('Save configuration'));
  68. $this->assertResponse(200);
  69. // Check row limit variable.
  70. $current_limit = variable_get('dblog_row_limit', 1000);
  71. $this->assertTrue($current_limit == $row_limit, format_string('[Cache] Row limit variable of @count equals row limit of @limit', array('@count' => $current_limit, '@limit' => $row_limit)));
  72. // Verify dblog row limit equals specified row limit.
  73. $current_limit = unserialize(db_query("SELECT value FROM {variable} WHERE name = :dblog_limit", array(':dblog_limit' => 'dblog_row_limit'))->fetchField());
  74. $this->assertTrue($current_limit == $row_limit, format_string('[Variable table] Row limit variable of @count equals row limit of @limit', array('@count' => $current_limit, '@limit' => $row_limit)));
  75. }
  76. /**
  77. * Verifies that cron correctly applies the database log row limit.
  78. *
  79. * @param int $row_limit
  80. * The row limit.
  81. */
  82. private function verifyCron($row_limit) {
  83. // Generate additional log entries.
  84. $this->generateLogEntries($row_limit + 10);
  85. // Verify that the database log row count exceeds the row limit.
  86. $count = db_query('SELECT COUNT(wid) FROM {watchdog}')->fetchField();
  87. $this->assertTrue($count > $row_limit, format_string('Dblog row count of @count exceeds row limit of @limit', array('@count' => $count, '@limit' => $row_limit)));
  88. // Run a cron job.
  89. $this->cronRun();
  90. // Verify that the database log row count equals the row limit plus one
  91. // because cron adds a record after it runs.
  92. $count = db_query('SELECT COUNT(wid) FROM {watchdog}')->fetchField();
  93. $this->assertTrue($count == $row_limit + 1, format_string('Dblog row count of @count equals row limit of @limit plus one', array('@count' => $count, '@limit' => $row_limit)));
  94. }
  95. /**
  96. * Generates a number of random database log events.
  97. *
  98. * @param int $count
  99. * Number of watchdog entries to generate.
  100. * @param string $type
  101. * (optional) The type of watchdog entry. Defaults to 'custom'.
  102. * @param int $severity
  103. * (optional) The severity of the watchdog entry. Defaults to WATCHDOG_NOTICE.
  104. */
  105. private function generateLogEntries($count, $type = 'custom', $severity = WATCHDOG_NOTICE) {
  106. global $base_root;
  107. // This long URL makes it just a little bit harder to pass the link part of
  108. // the test with a mix of English words and a repeating series of random
  109. // percent-encoded Chinese characters.
  110. $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%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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');
  111. // Prepare the fields to be logged
  112. $log = array(
  113. 'type' => $type,
  114. 'message' => 'Log entry added to test the dblog row limit.',
  115. 'variables' => array(),
  116. 'severity' => $severity,
  117. 'link' => $link,
  118. 'user' => $this->big_user,
  119. 'uid' => isset($this->big_user->uid) ? $this->big_user->uid : 0,
  120. 'request_uri' => $base_root . request_uri(),
  121. 'referer' => $_SERVER['HTTP_REFERER'],
  122. 'ip' => ip_address(),
  123. 'timestamp' => REQUEST_TIME,
  124. );
  125. $message = 'Log entry added to test the dblog row limit. Entry #';
  126. for ($i = 0; $i < $count; $i++) {
  127. $log['message'] = $message . $i;
  128. dblog_watchdog($log);
  129. }
  130. }
  131. /**
  132. * Confirms that database log reports are displayed at the correct paths.
  133. *
  134. * @param int $response
  135. * (optional) HTTP response code. Defaults to 200.
  136. */
  137. private function verifyReports($response = 200) {
  138. $quote = '&#039;';
  139. // View the database log help page.
  140. $this->drupalGet('admin/help/dblog');
  141. $this->assertResponse($response);
  142. if ($response == 200) {
  143. $this->assertText(t('Database logging'), 'DBLog help was displayed');
  144. }
  145. // View the database log report page.
  146. $this->drupalGet('admin/reports/dblog');
  147. $this->assertResponse($response);
  148. if ($response == 200) {
  149. $this->assertText(t('Recent log messages'), 'DBLog report was displayed');
  150. }
  151. // View the database log page-not-found report page.
  152. $this->drupalGet('admin/reports/page-not-found');
  153. $this->assertResponse($response);
  154. if ($response == 200) {
  155. $this->assertText(t('Top ' . $quote . 'page not found' . $quote . ' errors'), 'DBLog page-not-found report was displayed');
  156. }
  157. // View the database log access-denied report page.
  158. $this->drupalGet('admin/reports/access-denied');
  159. $this->assertResponse($response);
  160. if ($response == 200) {
  161. $this->assertText(t('Top ' . $quote . 'access denied' . $quote . ' errors'), 'DBLog access-denied report was displayed');
  162. }
  163. // View the database log event page.
  164. $this->drupalGet('admin/reports/event/1');
  165. $this->assertResponse($response);
  166. if ($response == 200) {
  167. $this->assertText(t('Details'), 'DBLog event node was displayed');
  168. }
  169. }
  170. /**
  171. * Generates and then verifies various types of events.
  172. */
  173. private function verifyEvents() {
  174. // Invoke events.
  175. $this->doUser();
  176. $this->doNode('article');
  177. $this->doNode('blog');
  178. $this->doNode('page');
  179. $this->doNode('poll');
  180. // When a user account is canceled, any content they created remains but the
  181. // uid = 0. Their blog entry shows as "'s blog" on the home page. Records
  182. // in the watchdog table related to that user have the uid set to zero.
  183. }
  184. /**
  185. * Generates and then verifies some user events.
  186. */
  187. private function doUser() {
  188. // Set user variables.
  189. $name = $this->randomName();
  190. $pass = user_password();
  191. // Add a user using the form to generate an add user event (which is not
  192. // triggered by drupalCreateUser).
  193. $edit = array();
  194. $edit['name'] = $name;
  195. $edit['mail'] = $name . '@example.com';
  196. $edit['pass[pass1]'] = $pass;
  197. $edit['pass[pass2]'] = $pass;
  198. $edit['status'] = 1;
  199. $this->drupalPost('admin/people/create', $edit, t('Create new account'));
  200. $this->assertResponse(200);
  201. // Retrieve the user object.
  202. $user = user_load_by_name($name);
  203. $this->assertTrue($user != NULL, format_string('User @name was loaded', array('@name' => $name)));
  204. // pass_raw property is needed by drupalLogin.
  205. $user->pass_raw = $pass;
  206. // Login user.
  207. $this->drupalLogin($user);
  208. // Logout user.
  209. $this->drupalLogout();
  210. // Fetch the row IDs in watchdog that relate to the user.
  211. $result = db_query('SELECT wid FROM {watchdog} WHERE uid = :uid', array(':uid' => $user->uid));
  212. foreach ($result as $row) {
  213. $ids[] = $row->wid;
  214. }
  215. $count_before = (isset($ids)) ? count($ids) : 0;
  216. $this->assertTrue($count_before > 0, format_string('DBLog contains @count records for @name', array('@count' => $count_before, '@name' => $user->name)));
  217. // Login the admin user.
  218. $this->drupalLogin($this->big_user);
  219. // Delete the user created at the start of this test.
  220. // We need to POST here to invoke batch_process() in the internal browser.
  221. $this->drupalPost('user/' . $user->uid . '/cancel', array('user_cancel_method' => 'user_cancel_reassign'), t('Cancel account'));
  222. // View the database log report.
  223. $this->drupalGet('admin/reports/dblog');
  224. $this->assertResponse(200);
  225. // Verify that the expected events were recorded.
  226. // Add user.
  227. // Default display includes name and email address; if too long, the email
  228. // address is replaced by three periods.
  229. $this->assertLogMessage(t('New user: %name (%email).', array('%name' => $name, '%email' => $user->mail)), 'DBLog event was recorded: [add user]');
  230. // Login user.
  231. $this->assertLogMessage(t('Session opened for %name.', array('%name' => $name)), 'DBLog event was recorded: [login user]');
  232. // Logout user.
  233. $this->assertLogMessage(t('Session closed for %name.', array('%name' => $name)), 'DBLog event was recorded: [logout user]');
  234. // Delete user.
  235. $message = t('Deleted user: %name %email.', array('%name' => $name, '%email' => '<' . $user->mail . '>'));
  236. $message_text = truncate_utf8(filter_xss($message, array()), 56, TRUE, TRUE);
  237. // Verify that the full message displays on the details page.
  238. $link = FALSE;
  239. if ($links = $this->xpath('//a[text()="' . html_entity_decode($message_text) . '"]')) {
  240. // Found link with the message text.
  241. $links = array_shift($links);
  242. foreach ($links->attributes() as $attr => $value) {
  243. if ($attr == 'href') {
  244. // Extract link to details page.
  245. $link = drupal_substr($value, strpos($value, 'admin/reports/event/'));
  246. $this->drupalGet($link);
  247. // Check for full message text on the details page.
  248. $this->assertRaw($message, 'DBLog event details was found: [delete user]');
  249. break;
  250. }
  251. }
  252. }
  253. $this->assertTrue($link, 'DBLog event was recorded: [delete user]');
  254. // Visit random URL (to generate page not found event).
  255. $not_found_url = $this->randomName(60);
  256. $this->drupalGet($not_found_url);
  257. $this->assertResponse(404);
  258. // View the database log page-not-found report page.
  259. $this->drupalGet('admin/reports/page-not-found');
  260. $this->assertResponse(200);
  261. // Check that full-length URL displayed.
  262. $this->assertText($not_found_url, 'DBLog event was recorded: [page not found]');
  263. }
  264. /**
  265. * Generates and then verifies some node events.
  266. *
  267. * @param string $type
  268. * A node type (e.g., 'article', 'page' or 'poll').
  269. */
  270. private function doNode($type) {
  271. // Create user.
  272. $perm = array('create ' . $type . ' content', 'edit own ' . $type . ' content', 'delete own ' . $type . ' content');
  273. $user = $this->drupalCreateUser($perm);
  274. // Login user.
  275. $this->drupalLogin($user);
  276. // Create a node using the form in order to generate an add content event
  277. // (which is not triggered by drupalCreateNode).
  278. $edit = $this->getContent($type);
  279. $langcode = LANGUAGE_NONE;
  280. $title = $edit["title"];
  281. $this->drupalPost('node/add/' . $type, $edit, t('Save'));
  282. $this->assertResponse(200);
  283. // Retrieve the node object.
  284. $node = $this->drupalGetNodeByTitle($title);
  285. $this->assertTrue($node != NULL, format_string('Node @title was loaded', array('@title' => $title)));
  286. // Edit the node.
  287. $edit = $this->getContentUpdate($type);
  288. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  289. $this->assertResponse(200);
  290. // Delete the node.
  291. $this->drupalPost('node/' . $node->nid . '/delete', array(), t('Delete'));
  292. $this->assertResponse(200);
  293. // View the node (to generate page not found event).
  294. $this->drupalGet('node/' . $node->nid);
  295. $this->assertResponse(404);
  296. // View the database log report (to generate access denied event).
  297. $this->drupalGet('admin/reports/dblog');
  298. $this->assertResponse(403);
  299. // Login the admin user.
  300. $this->drupalLogin($this->big_user);
  301. // View the database log report.
  302. $this->drupalGet('admin/reports/dblog');
  303. $this->assertResponse(200);
  304. // Verify that node events were recorded.
  305. // Was node content added?
  306. $this->assertLogMessage(t('@type: added %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content added]');
  307. // Was node content updated?
  308. $this->assertLogMessage(t('@type: updated %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content updated]');
  309. // Was node content deleted?
  310. $this->assertLogMessage(t('@type: deleted %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content deleted]');
  311. // View the database log access-denied report page.
  312. $this->drupalGet('admin/reports/access-denied');
  313. $this->assertResponse(200);
  314. // Verify that the 'access denied' event was recorded.
  315. $this->assertText(t('admin/reports/dblog'), 'DBLog event was recorded: [access denied]');
  316. // View the database log page-not-found report page.
  317. $this->drupalGet('admin/reports/page-not-found');
  318. $this->assertResponse(200);
  319. // Verify that the 'page not found' event was recorded.
  320. $this->assertText(t('node/@nid', array('@nid' => $node->nid)), 'DBLog event was recorded: [page not found]');
  321. }
  322. /**
  323. * Creates random content based on node content type.
  324. *
  325. * @param string $type
  326. * Node content type (e.g., 'article').
  327. *
  328. * @return array
  329. * Random content needed by various node types.
  330. */
  331. private function getContent($type) {
  332. $langcode = LANGUAGE_NONE;
  333. switch ($type) {
  334. case 'poll':
  335. $content = array(
  336. "title" => $this->randomName(8),
  337. 'choice[new:0][chtext]' => $this->randomName(32),
  338. 'choice[new:1][chtext]' => $this->randomName(32),
  339. );
  340. break;
  341. default:
  342. $content = array(
  343. "title" => $this->randomName(8),
  344. "body[$langcode][0][value]" => $this->randomName(32),
  345. );
  346. break;
  347. }
  348. return $content;
  349. }
  350. /**
  351. * Creates random content as an update based on node content type.
  352. *
  353. * @param string $type
  354. * Node content type (e.g., 'article').
  355. *
  356. * @return array
  357. * Random content needed by various node types.
  358. */
  359. private function getContentUpdate($type) {
  360. switch ($type) {
  361. case 'poll':
  362. $content = array(
  363. 'choice[chid:1][chtext]' => $this->randomName(32),
  364. 'choice[chid:2][chtext]' => $this->randomName(32),
  365. );
  366. break;
  367. default:
  368. $langcode = LANGUAGE_NONE;
  369. $content = array(
  370. "body[$langcode][0][value]" => $this->randomName(32),
  371. );
  372. break;
  373. }
  374. return $content;
  375. }
  376. /**
  377. * Tests the addition and clearing of log events through the admin interface.
  378. *
  379. * Logs in the admin user, creates a database log event, and tests the
  380. * functionality of clearing the database log through the admin interface.
  381. */
  382. protected function testDBLogAddAndClear() {
  383. global $base_root;
  384. // Get a count of how many watchdog entries already exist.
  385. $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
  386. $log = array(
  387. 'type' => 'custom',
  388. 'message' => 'Log entry added to test the doClearTest clear down.',
  389. 'variables' => array(),
  390. 'severity' => WATCHDOG_NOTICE,
  391. 'link' => NULL,
  392. 'user' => $this->big_user,
  393. 'uid' => isset($this->big_user->uid) ? $this->big_user->uid : 0,
  394. 'request_uri' => $base_root . request_uri(),
  395. 'referer' => $_SERVER['HTTP_REFERER'],
  396. 'ip' => ip_address(),
  397. 'timestamp' => REQUEST_TIME,
  398. );
  399. // Add a watchdog entry.
  400. dblog_watchdog($log);
  401. // Make sure the table count has actually been incremented.
  402. $this->assertEqual($count + 1, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), format_string('dblog_watchdog() added an entry to the dblog :count', array(':count' => $count)));
  403. // Login the admin user.
  404. $this->drupalLogin($this->big_user);
  405. // Post in order to clear the database table.
  406. $this->drupalPost('admin/reports/dblog', array(), t('Clear log messages'));
  407. // Count the rows in watchdog that previously related to the deleted user.
  408. $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
  409. $this->assertEqual($count, 0, format_string('DBLog contains :count records after a clear.', array(':count' => $count)));
  410. }
  411. /**
  412. * Tests the database log filter functionality at admin/reports/dblog.
  413. */
  414. protected function testFilter() {
  415. $this->drupalLogin($this->big_user);
  416. // Clear the log to ensure that only generated entries will be found.
  417. db_delete('watchdog')->execute();
  418. // Generate 9 random watchdog entries.
  419. $type_names = array();
  420. $types = array();
  421. for ($i = 0; $i < 3; $i++) {
  422. $type_names[] = $type_name = $this->randomName();
  423. $severity = WATCHDOG_EMERGENCY;
  424. for ($j = 0; $j < 3; $j++) {
  425. $types[] = $type = array(
  426. 'count' => $j + 1,
  427. 'type' => $type_name,
  428. 'severity' => $severity++,
  429. );
  430. $this->generateLogEntries($type['count'], $type['type'], $type['severity']);
  431. }
  432. }
  433. // View the database log page.
  434. $this->drupalGet('admin/reports/dblog');
  435. // Confirm that all the entries are displayed.
  436. $count = $this->getTypeCount($types);
  437. foreach ($types as $key => $type) {
  438. $this->assertEqual($count[$key], $type['count'], 'Count matched');
  439. }
  440. // Filter by each type and confirm that entries with various severities are
  441. // displayed.
  442. foreach ($type_names as $type_name) {
  443. $edit = array(
  444. 'type[]' => array($type_name),
  445. );
  446. $this->drupalPost(NULL, $edit, t('Filter'));
  447. // Count the number of entries of this type.
  448. $type_count = 0;
  449. foreach ($types as $type) {
  450. if ($type['type'] == $type_name) {
  451. $type_count += $type['count'];
  452. }
  453. }
  454. $count = $this->getTypeCount($types);
  455. $this->assertEqual(array_sum($count), $type_count, 'Count matched');
  456. }
  457. // Set the filter to match each of the two filter-type attributes and
  458. // confirm the correct number of entries are displayed.
  459. foreach ($types as $key => $type) {
  460. $edit = array(
  461. 'type[]' => array($type['type']),
  462. 'severity[]' => array($type['severity']),
  463. );
  464. $this->drupalPost(NULL, $edit, t('Filter'));
  465. $count = $this->getTypeCount($types);
  466. $this->assertEqual(array_sum($count), $type['count'], 'Count matched');
  467. }
  468. // Clear all logs and make sure the confirmation message is found.
  469. $this->drupalPost('admin/reports/dblog', array(), t('Clear log messages'));
  470. $this->assertText(t('Database log cleared.'), 'Confirmation message found');
  471. }
  472. /**
  473. * Verifies that exceptions are caught in dblog_watchdog().
  474. */
  475. protected function testDBLogException() {
  476. $log = array(
  477. 'type' => 'custom',
  478. 'message' => 'Log entry added to test watchdog handling of Exceptions.',
  479. 'variables' => array(),
  480. 'severity' => WATCHDOG_NOTICE,
  481. 'link' => NULL,
  482. 'user' => $this->big_user,
  483. 'uid' => isset($this->big_user->uid) ? $this->big_user->uid : 0,
  484. 'request_uri' => request_uri(),
  485. 'referer' => $_SERVER['HTTP_REFERER'],
  486. 'ip' => ip_address(),
  487. 'timestamp' => REQUEST_TIME,
  488. );
  489. // Remove watchdog table temporarily to simulate it missing during
  490. // installation.
  491. db_query("DROP TABLE {watchdog}");
  492. // Add a watchdog entry.
  493. // This should not throw an Exception, but fail silently.
  494. dblog_watchdog($log);
  495. }
  496. /**
  497. * Gets the database log event information from the browser page.
  498. *
  499. * @return array
  500. * List of log events where each event is an array with following keys:
  501. * - severity: (int) A database log severity constant.
  502. * - type: (string) The type of database log event.
  503. * - message: (string) The message for this database log event.
  504. * - user: (string) The user associated with this database log event.
  505. */
  506. protected function getLogEntries() {
  507. $entries = array();
  508. if ($table = $this->xpath('.//table[@id="admin-dblog"]')) {
  509. $table = array_shift($table);
  510. foreach ($table->tbody->tr as $row) {
  511. $entries[] = array(
  512. 'severity' => $this->getSeverityConstant($row['class']),
  513. 'type' => $this->asText($row->td[1]),
  514. 'message' => $this->asText($row->td[3]),
  515. 'user' => $this->asText($row->td[4]),
  516. );
  517. }
  518. }
  519. return $entries;
  520. }
  521. /**
  522. * Gets the count of database log entries by database log event type.
  523. *
  524. * @param array $types
  525. * The type information to compare against.
  526. *
  527. * @return array
  528. * The count of each type keyed by the key of the $types array.
  529. */
  530. protected function getTypeCount(array $types) {
  531. $entries = $this->getLogEntries();
  532. $count = array_fill(0, count($types), 0);
  533. foreach ($entries as $entry) {
  534. foreach ($types as $key => $type) {
  535. if ($entry['type'] == $type['type'] && $entry['severity'] == $type['severity']) {
  536. $count[$key]++;
  537. break;
  538. }
  539. }
  540. }
  541. return $count;
  542. }
  543. /**
  544. * Gets the watchdog severity constant corresponding to the CSS class.
  545. *
  546. * @param string $class
  547. * CSS class attribute.
  548. *
  549. * @return int|null
  550. * The watchdog severity constant or NULL if not found.
  551. *
  552. * @ingroup logging_severity_levels
  553. */
  554. protected function getSeverityConstant($class) {
  555. // Reversed array from dblog_overview().
  556. $map = array(
  557. 'dblog-debug' => WATCHDOG_DEBUG,
  558. 'dblog-info' => WATCHDOG_INFO,
  559. 'dblog-notice' => WATCHDOG_NOTICE,
  560. 'dblog-warning' => WATCHDOG_WARNING,
  561. 'dblog-error' => WATCHDOG_ERROR,
  562. 'dblog-critical' => WATCHDOG_CRITICAL,
  563. 'dblog-alert' => WATCHDOG_ALERT,
  564. 'dblog-emerg' => WATCHDOG_EMERGENCY,
  565. );
  566. // Find the class that contains the severity.
  567. $classes = explode(' ', $class);
  568. foreach ($classes as $class) {
  569. if (isset($map[$class])) {
  570. return $map[$class];
  571. }
  572. }
  573. return NULL;
  574. }
  575. /**
  576. * Extracts the text contained by the XHTML element.
  577. *
  578. * @param SimpleXMLElement $element
  579. * Element to extract text from.
  580. *
  581. * @return string
  582. * Extracted text.
  583. */
  584. protected function asText(SimpleXMLElement $element) {
  585. if (!is_object($element)) {
  586. return $this->fail('The element is not an element.');
  587. }
  588. return trim(html_entity_decode(strip_tags($element->asXML())));
  589. }
  590. /**
  591. * Confirms that a log message appears on the database log overview screen.
  592. *
  593. * This function should only be used for the admin/reports/dblog page, because
  594. * it checks for the message link text truncated to 56 characters. Other log
  595. * pages have no detail links so they contain the full message text.
  596. *
  597. * @param string $log_message
  598. * The database log message to check.
  599. * @param string $message
  600. * The message to pass to simpletest.
  601. */
  602. protected function assertLogMessage($log_message, $message) {
  603. $message_text = truncate_utf8(filter_xss($log_message, array()), 56, TRUE, TRUE);
  604. // After filter_xss(), HTML entities should be converted to their character
  605. // equivalents because assertLink() uses this string in xpath() to query the
  606. // Document Object Model (DOM).
  607. $this->assertLink(html_entity_decode($message_text), 0, $message);
  608. }
  609. /**
  610. * Make sure HTML tags are filtered out in the log detail page.
  611. */
  612. public function testLogMessageSanitized() {
  613. $this->drupalLogin($this->big_user);
  614. // Make sure dangerous HTML tags are filtered out in log detail page.
  615. $log = array(
  616. 'uid' => 0,
  617. 'type' => 'custom',
  618. 'message' => "<script>alert('foo');</script> <strong>Lorem ipsum</strong>",
  619. 'variables' => NULL,
  620. 'severity' => WATCHDOG_NOTICE,
  621. 'link' => 'foo/bar',
  622. 'request_uri' => 'http://example.com?dblog=1',
  623. 'referer' => 'http://example.org?dblog=2',
  624. 'ip' => '0.0.1.0',
  625. 'timestamp' => REQUEST_TIME,
  626. );
  627. dblog_watchdog($log);
  628. $wid = db_query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
  629. $this->drupalGet('admin/reports/event/' . $wid);
  630. $this->assertResponse(200);
  631. $this->assertNoRaw("<script>alert('foo');</script>");
  632. $this->assertRaw("alert('foo'); <strong>Lorem ipsum</strong>");
  633. }
  634. }