dblog.test 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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. // Make it just a little bit harder to pass the link part of the test.
  108. $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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%BB%9D%E7%BE%8E%E9%AB%98%E5%B1%B1%E6%B9%96%E6%B3%8A-lake-isabelle');
  109. // Prepare the fields to be logged
  110. $log = array(
  111. 'type' => $type,
  112. 'message' => 'Log entry added to test the dblog row limit.',
  113. 'variables' => array(),
  114. 'severity' => $severity,
  115. 'link' => $link,
  116. 'user' => $this->big_user,
  117. 'uid' => isset($this->big_user->uid) ? $this->big_user->uid : 0,
  118. 'request_uri' => $base_root . request_uri(),
  119. 'referer' => $_SERVER['HTTP_REFERER'],
  120. 'ip' => ip_address(),
  121. 'timestamp' => REQUEST_TIME,
  122. );
  123. $message = 'Log entry added to test the dblog row limit. Entry #';
  124. for ($i = 0; $i < $count; $i++) {
  125. $log['message'] = $message . $i;
  126. dblog_watchdog($log);
  127. }
  128. }
  129. /**
  130. * Confirms that database log reports are displayed at the correct paths.
  131. *
  132. * @param int $response
  133. * (optional) HTTP response code. Defaults to 200.
  134. */
  135. private function verifyReports($response = 200) {
  136. $quote = '&#039;';
  137. // View the database log help page.
  138. $this->drupalGet('admin/help/dblog');
  139. $this->assertResponse($response);
  140. if ($response == 200) {
  141. $this->assertText(t('Database logging'), 'DBLog help was displayed');
  142. }
  143. // View the database log report page.
  144. $this->drupalGet('admin/reports/dblog');
  145. $this->assertResponse($response);
  146. if ($response == 200) {
  147. $this->assertText(t('Recent log messages'), 'DBLog report was displayed');
  148. }
  149. // View the database log page-not-found report page.
  150. $this->drupalGet('admin/reports/page-not-found');
  151. $this->assertResponse($response);
  152. if ($response == 200) {
  153. $this->assertText(t('Top ' . $quote . 'page not found' . $quote . ' errors'), 'DBLog page-not-found report was displayed');
  154. }
  155. // View the database log access-denied report page.
  156. $this->drupalGet('admin/reports/access-denied');
  157. $this->assertResponse($response);
  158. if ($response == 200) {
  159. $this->assertText(t('Top ' . $quote . 'access denied' . $quote . ' errors'), 'DBLog access-denied report was displayed');
  160. }
  161. // View the database log event page.
  162. $this->drupalGet('admin/reports/event/1');
  163. $this->assertResponse($response);
  164. if ($response == 200) {
  165. $this->assertText(t('Details'), 'DBLog event node was displayed');
  166. }
  167. }
  168. /**
  169. * Generates and then verifies various types of events.
  170. */
  171. private function verifyEvents() {
  172. // Invoke events.
  173. $this->doUser();
  174. $this->doNode('article');
  175. $this->doNode('blog');
  176. $this->doNode('page');
  177. $this->doNode('poll');
  178. // When a user account is canceled, any content they created remains but the
  179. // uid = 0. Their blog entry shows as "'s blog" on the home page. Records
  180. // in the watchdog table related to that user have the uid set to zero.
  181. }
  182. /**
  183. * Generates and then verifies some user events.
  184. */
  185. private function doUser() {
  186. // Set user variables.
  187. $name = $this->randomName();
  188. $pass = user_password();
  189. // Add a user using the form to generate an add user event (which is not
  190. // triggered by drupalCreateUser).
  191. $edit = array();
  192. $edit['name'] = $name;
  193. $edit['mail'] = $name . '@example.com';
  194. $edit['pass[pass1]'] = $pass;
  195. $edit['pass[pass2]'] = $pass;
  196. $edit['status'] = 1;
  197. $this->drupalPost('admin/people/create', $edit, t('Create new account'));
  198. $this->assertResponse(200);
  199. // Retrieve the user object.
  200. $user = user_load_by_name($name);
  201. $this->assertTrue($user != NULL, format_string('User @name was loaded', array('@name' => $name)));
  202. // pass_raw property is needed by drupalLogin.
  203. $user->pass_raw = $pass;
  204. // Login user.
  205. $this->drupalLogin($user);
  206. // Logout user.
  207. $this->drupalLogout();
  208. // Fetch the row IDs in watchdog that relate to the user.
  209. $result = db_query('SELECT wid FROM {watchdog} WHERE uid = :uid', array(':uid' => $user->uid));
  210. foreach ($result as $row) {
  211. $ids[] = $row->wid;
  212. }
  213. $count_before = (isset($ids)) ? count($ids) : 0;
  214. $this->assertTrue($count_before > 0, format_string('DBLog contains @count records for @name', array('@count' => $count_before, '@name' => $user->name)));
  215. // Login the admin user.
  216. $this->drupalLogin($this->big_user);
  217. // Delete the user created at the start of this test.
  218. // We need to POST here to invoke batch_process() in the internal browser.
  219. $this->drupalPost('user/' . $user->uid . '/cancel', array('user_cancel_method' => 'user_cancel_reassign'), t('Cancel account'));
  220. // View the database log report.
  221. $this->drupalGet('admin/reports/dblog');
  222. $this->assertResponse(200);
  223. // Verify that the expected events were recorded.
  224. // Add user.
  225. // Default display includes name and email address; if too long, the email
  226. // address is replaced by three periods.
  227. $this->assertLogMessage(t('New user: %name (%email).', array('%name' => $name, '%email' => $user->mail)), 'DBLog event was recorded: [add user]');
  228. // Login user.
  229. $this->assertLogMessage(t('Session opened for %name.', array('%name' => $name)), 'DBLog event was recorded: [login user]');
  230. // Logout user.
  231. $this->assertLogMessage(t('Session closed for %name.', array('%name' => $name)), 'DBLog event was recorded: [logout user]');
  232. // Delete user.
  233. $message = t('Deleted user: %name %email.', array('%name' => $name, '%email' => '<' . $user->mail . '>'));
  234. $message_text = truncate_utf8(filter_xss($message, array()), 56, TRUE, TRUE);
  235. // Verify that the full message displays on the details page.
  236. $link = FALSE;
  237. if ($links = $this->xpath('//a[text()="' . html_entity_decode($message_text) . '"]')) {
  238. // Found link with the message text.
  239. $links = array_shift($links);
  240. foreach ($links->attributes() as $attr => $value) {
  241. if ($attr == 'href') {
  242. // Extract link to details page.
  243. $link = drupal_substr($value, strpos($value, 'admin/reports/event/'));
  244. $this->drupalGet($link);
  245. // Check for full message text on the details page.
  246. $this->assertRaw($message, 'DBLog event details was found: [delete user]');
  247. break;
  248. }
  249. }
  250. }
  251. $this->assertTrue($link, 'DBLog event was recorded: [delete user]');
  252. // Visit random URL (to generate page not found event).
  253. $not_found_url = $this->randomName(60);
  254. $this->drupalGet($not_found_url);
  255. $this->assertResponse(404);
  256. // View the database log page-not-found report page.
  257. $this->drupalGet('admin/reports/page-not-found');
  258. $this->assertResponse(200);
  259. // Check that full-length URL displayed.
  260. $this->assertText($not_found_url, 'DBLog event was recorded: [page not found]');
  261. }
  262. /**
  263. * Generates and then verifies some node events.
  264. *
  265. * @param string $type
  266. * A node type (e.g., 'article', 'page' or 'poll').
  267. */
  268. private function doNode($type) {
  269. // Create user.
  270. $perm = array('create ' . $type . ' content', 'edit own ' . $type . ' content', 'delete own ' . $type . ' content');
  271. $user = $this->drupalCreateUser($perm);
  272. // Login user.
  273. $this->drupalLogin($user);
  274. // Create a node using the form in order to generate an add content event
  275. // (which is not triggered by drupalCreateNode).
  276. $edit = $this->getContent($type);
  277. $langcode = LANGUAGE_NONE;
  278. $title = $edit["title"];
  279. $this->drupalPost('node/add/' . $type, $edit, t('Save'));
  280. $this->assertResponse(200);
  281. // Retrieve the node object.
  282. $node = $this->drupalGetNodeByTitle($title);
  283. $this->assertTrue($node != NULL, format_string('Node @title was loaded', array('@title' => $title)));
  284. // Edit the node.
  285. $edit = $this->getContentUpdate($type);
  286. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  287. $this->assertResponse(200);
  288. // Delete the node.
  289. $this->drupalPost('node/' . $node->nid . '/delete', array(), t('Delete'));
  290. $this->assertResponse(200);
  291. // View the node (to generate page not found event).
  292. $this->drupalGet('node/' . $node->nid);
  293. $this->assertResponse(404);
  294. // View the database log report (to generate access denied event).
  295. $this->drupalGet('admin/reports/dblog');
  296. $this->assertResponse(403);
  297. // Login the admin user.
  298. $this->drupalLogin($this->big_user);
  299. // View the database log report.
  300. $this->drupalGet('admin/reports/dblog');
  301. $this->assertResponse(200);
  302. // Verify that node events were recorded.
  303. // Was node content added?
  304. $this->assertLogMessage(t('@type: added %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content added]');
  305. // Was node content updated?
  306. $this->assertLogMessage(t('@type: updated %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content updated]');
  307. // Was node content deleted?
  308. $this->assertLogMessage(t('@type: deleted %title.', array('@type' => $type, '%title' => $title)), 'DBLog event was recorded: [content deleted]');
  309. // View the database log access-denied report page.
  310. $this->drupalGet('admin/reports/access-denied');
  311. $this->assertResponse(200);
  312. // Verify that the 'access denied' event was recorded.
  313. $this->assertText(t('admin/reports/dblog'), 'DBLog event was recorded: [access denied]');
  314. // View the database log page-not-found report page.
  315. $this->drupalGet('admin/reports/page-not-found');
  316. $this->assertResponse(200);
  317. // Verify that the 'page not found' event was recorded.
  318. $this->assertText(t('node/@nid', array('@nid' => $node->nid)), 'DBLog event was recorded: [page not found]');
  319. }
  320. /**
  321. * Creates random content based on node content type.
  322. *
  323. * @param string $type
  324. * Node content type (e.g., 'article').
  325. *
  326. * @return array
  327. * Random content needed by various node types.
  328. */
  329. private function getContent($type) {
  330. $langcode = LANGUAGE_NONE;
  331. switch ($type) {
  332. case 'poll':
  333. $content = array(
  334. "title" => $this->randomName(8),
  335. 'choice[new:0][chtext]' => $this->randomName(32),
  336. 'choice[new:1][chtext]' => $this->randomName(32),
  337. );
  338. break;
  339. default:
  340. $content = array(
  341. "title" => $this->randomName(8),
  342. "body[$langcode][0][value]" => $this->randomName(32),
  343. );
  344. break;
  345. }
  346. return $content;
  347. }
  348. /**
  349. * Creates random content as an update based on node content type.
  350. *
  351. * @param string $type
  352. * Node content type (e.g., 'article').
  353. *
  354. * @return array
  355. * Random content needed by various node types.
  356. */
  357. private function getContentUpdate($type) {
  358. switch ($type) {
  359. case 'poll':
  360. $content = array(
  361. 'choice[chid:1][chtext]' => $this->randomName(32),
  362. 'choice[chid:2][chtext]' => $this->randomName(32),
  363. );
  364. break;
  365. default:
  366. $langcode = LANGUAGE_NONE;
  367. $content = array(
  368. "body[$langcode][0][value]" => $this->randomName(32),
  369. );
  370. break;
  371. }
  372. return $content;
  373. }
  374. /**
  375. * Tests the addition and clearing of log events through the admin interface.
  376. *
  377. * Logs in the admin user, creates a database log event, and tests the
  378. * functionality of clearing the database log through the admin interface.
  379. */
  380. protected function testDBLogAddAndClear() {
  381. global $base_root;
  382. // Get a count of how many watchdog entries already exist.
  383. $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
  384. $log = array(
  385. 'type' => 'custom',
  386. 'message' => 'Log entry added to test the doClearTest clear down.',
  387. 'variables' => array(),
  388. 'severity' => WATCHDOG_NOTICE,
  389. 'link' => NULL,
  390. 'user' => $this->big_user,
  391. 'uid' => isset($this->big_user->uid) ? $this->big_user->uid : 0,
  392. 'request_uri' => $base_root . request_uri(),
  393. 'referer' => $_SERVER['HTTP_REFERER'],
  394. 'ip' => ip_address(),
  395. 'timestamp' => REQUEST_TIME,
  396. );
  397. // Add a watchdog entry.
  398. dblog_watchdog($log);
  399. // Make sure the table count has actually been incremented.
  400. $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)));
  401. // Login the admin user.
  402. $this->drupalLogin($this->big_user);
  403. // Post in order to clear the database table.
  404. $this->drupalPost('admin/reports/dblog', array(), t('Clear log messages'));
  405. // Count the rows in watchdog that previously related to the deleted user.
  406. $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
  407. $this->assertEqual($count, 0, format_string('DBLog contains :count records after a clear.', array(':count' => $count)));
  408. }
  409. /**
  410. * Tests the database log filter functionality at admin/reports/dblog.
  411. */
  412. protected function testFilter() {
  413. $this->drupalLogin($this->big_user);
  414. // Clear the log to ensure that only generated entries will be found.
  415. db_delete('watchdog')->execute();
  416. // Generate 9 random watchdog entries.
  417. $type_names = array();
  418. $types = array();
  419. for ($i = 0; $i < 3; $i++) {
  420. $type_names[] = $type_name = $this->randomName();
  421. $severity = WATCHDOG_EMERGENCY;
  422. for ($j = 0; $j < 3; $j++) {
  423. $types[] = $type = array(
  424. 'count' => $j + 1,
  425. 'type' => $type_name,
  426. 'severity' => $severity++,
  427. );
  428. $this->generateLogEntries($type['count'], $type['type'], $type['severity']);
  429. }
  430. }
  431. // View the database log page.
  432. $this->drupalGet('admin/reports/dblog');
  433. // Confirm that all the entries are displayed.
  434. $count = $this->getTypeCount($types);
  435. foreach ($types as $key => $type) {
  436. $this->assertEqual($count[$key], $type['count'], 'Count matched');
  437. }
  438. // Filter by each type and confirm that entries with various severities are
  439. // displayed.
  440. foreach ($type_names as $type_name) {
  441. $edit = array(
  442. 'type[]' => array($type_name),
  443. );
  444. $this->drupalPost(NULL, $edit, t('Filter'));
  445. // Count the number of entries of this type.
  446. $type_count = 0;
  447. foreach ($types as $type) {
  448. if ($type['type'] == $type_name) {
  449. $type_count += $type['count'];
  450. }
  451. }
  452. $count = $this->getTypeCount($types);
  453. $this->assertEqual(array_sum($count), $type_count, 'Count matched');
  454. }
  455. // Set the filter to match each of the two filter-type attributes and
  456. // confirm the correct number of entries are displayed.
  457. foreach ($types as $key => $type) {
  458. $edit = array(
  459. 'type[]' => array($type['type']),
  460. 'severity[]' => array($type['severity']),
  461. );
  462. $this->drupalPost(NULL, $edit, t('Filter'));
  463. $count = $this->getTypeCount($types);
  464. $this->assertEqual(array_sum($count), $type['count'], 'Count matched');
  465. }
  466. // Clear all logs and make sure the confirmation message is found.
  467. $this->drupalPost('admin/reports/dblog', array(), t('Clear log messages'));
  468. $this->assertText(t('Database log cleared.'), 'Confirmation message found');
  469. }
  470. /**
  471. * Gets the database log event information from the browser page.
  472. *
  473. * @return array
  474. * List of log events where each event is an array with following keys:
  475. * - severity: (int) A database log severity constant.
  476. * - type: (string) The type of database log event.
  477. * - message: (string) The message for this database log event.
  478. * - user: (string) The user associated with this database log event.
  479. */
  480. protected function getLogEntries() {
  481. $entries = array();
  482. if ($table = $this->xpath('.//table[@id="admin-dblog"]')) {
  483. $table = array_shift($table);
  484. foreach ($table->tbody->tr as $row) {
  485. $entries[] = array(
  486. 'severity' => $this->getSeverityConstant($row['class']),
  487. 'type' => $this->asText($row->td[1]),
  488. 'message' => $this->asText($row->td[3]),
  489. 'user' => $this->asText($row->td[4]),
  490. );
  491. }
  492. }
  493. return $entries;
  494. }
  495. /**
  496. * Gets the count of database log entries by database log event type.
  497. *
  498. * @param array $types
  499. * The type information to compare against.
  500. *
  501. * @return array
  502. * The count of each type keyed by the key of the $types array.
  503. */
  504. protected function getTypeCount(array $types) {
  505. $entries = $this->getLogEntries();
  506. $count = array_fill(0, count($types), 0);
  507. foreach ($entries as $entry) {
  508. foreach ($types as $key => $type) {
  509. if ($entry['type'] == $type['type'] && $entry['severity'] == $type['severity']) {
  510. $count[$key]++;
  511. break;
  512. }
  513. }
  514. }
  515. return $count;
  516. }
  517. /**
  518. * Gets the watchdog severity constant corresponding to the CSS class.
  519. *
  520. * @param string $class
  521. * CSS class attribute.
  522. *
  523. * @return int|null
  524. * The watchdog severity constant or NULL if not found.
  525. *
  526. * @ingroup logging_severity_levels
  527. */
  528. protected function getSeverityConstant($class) {
  529. // Reversed array from dblog_overview().
  530. $map = array(
  531. 'dblog-debug' => WATCHDOG_DEBUG,
  532. 'dblog-info' => WATCHDOG_INFO,
  533. 'dblog-notice' => WATCHDOG_NOTICE,
  534. 'dblog-warning' => WATCHDOG_WARNING,
  535. 'dblog-error' => WATCHDOG_ERROR,
  536. 'dblog-critical' => WATCHDOG_CRITICAL,
  537. 'dblog-alert' => WATCHDOG_ALERT,
  538. 'dblog-emerg' => WATCHDOG_EMERGENCY,
  539. );
  540. // Find the class that contains the severity.
  541. $classes = explode(' ', $class);
  542. foreach ($classes as $class) {
  543. if (isset($map[$class])) {
  544. return $map[$class];
  545. }
  546. }
  547. return NULL;
  548. }
  549. /**
  550. * Extracts the text contained by the XHTML element.
  551. *
  552. * @param SimpleXMLElement $element
  553. * Element to extract text from.
  554. *
  555. * @return string
  556. * Extracted text.
  557. */
  558. protected function asText(SimpleXMLElement $element) {
  559. if (!is_object($element)) {
  560. return $this->fail('The element is not an element.');
  561. }
  562. return trim(html_entity_decode(strip_tags($element->asXML())));
  563. }
  564. /**
  565. * Confirms that a log message appears on the database log overview screen.
  566. *
  567. * This function should only be used for the admin/reports/dblog page, because
  568. * it checks for the message link text truncated to 56 characters. Other log
  569. * pages have no detail links so they contain the full message text.
  570. *
  571. * @param string $log_message
  572. * The database log message to check.
  573. * @param string $message
  574. * The message to pass to simpletest.
  575. */
  576. protected function assertLogMessage($log_message, $message) {
  577. $message_text = truncate_utf8(filter_xss($log_message, array()), 56, TRUE, TRUE);
  578. // After filter_xss(), HTML entities should be converted to their character
  579. // equivalents because assertLink() uses this string in xpath() to query the
  580. // Document Object Model (DOM).
  581. $this->assertLink(html_entity_decode($message_text), 0, $message);
  582. }
  583. }