dblog.test 30 KB

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