| Drupal | PHP Cross Reference | Content Management Systems |
1 <?php 2 3 /** 4 * @file 5 * Tests for dblog.module. 6 */ 7 8 class DBLogTestCase extends DrupalWebTestCase { 9 protected $big_user; 10 protected $any_user; 11 12 public static function getInfo() { 13 return array( 14 'name' => 'DBLog functionality', 15 'description' => 'Generate events and verify dblog entries; verify user access to log reports based on persmissions.', 16 'group' => 'DBLog', 17 ); 18 } 19 20 /** 21 * Enable modules and create users with specific permissions. 22 */ 23 function setUp() { 24 parent::setUp('dblog', 'blog', 'poll'); 25 // Create users. 26 $this->big_user = $this->drupalCreateUser(array('administer site configuration', 'access administration pages', 'access site reports', 'administer users')); 27 $this->any_user = $this->drupalCreateUser(array()); 28 } 29 30 /** 31 * Login users, create dblog events, and test dblog functionality through the admin and user interfaces. 32 */ 33 function testDBLog() { 34 // Login the admin user. 35 $this->drupalLogin($this->big_user); 36 37 $row_limit = 100; 38 $this->verifyRowLimit($row_limit); 39 $this->verifyCron($row_limit); 40 $this->verifyEvents(); 41 $this->verifyReports(); 42 43 // Login the regular user. 44 $this->drupalLogin($this->any_user); 45 $this->verifyReports(403); 46 } 47 48 /** 49 * Verify setting of the dblog row limit. 50 * 51 * @param integer $count Log row limit. 52 */ 53 private function verifyRowLimit($row_limit) { 54 // Change the dblog row limit. 55 $edit = array(); 56 $edit['dblog_row_limit'] = $row_limit; 57 $this->drupalPost('admin/config/development/logging', $edit, t('Save configuration')); 58 $this->assertResponse(200); 59 60 // Check row limit variable. 61 $current_limit = variable_get('dblog_row_limit', 1000); 62 $this->assertTrue($current_limit == $row_limit, t('[Cache] Row limit variable of @count equals row limit of @limit', array('@count' => $current_limit, '@limit' => $row_limit))); 63 // Verify dblog row limit equals specified row limit. 64 $current_limit = unserialize(db_query("SELECT value FROM {variable} WHERE name = :dblog_limit", array(':dblog_limit' => 'dblog_row_limit'))->fetchField()); 65 $this->assertTrue($current_limit == $row_limit, t('[Variable table] Row limit variable of @count equals row limit of @limit', array('@count' => $current_limit, '@limit' => $row_limit))); 66 } 67 68 /** 69 * Verify cron applies the dblog row limit. 70 * 71 * @param integer $count Log row limit. 72 */ 73 private function verifyCron($row_limit) { 74 // Generate additional log entries. 75 $this->generateLogEntries($row_limit + 10); 76 // Verify dblog row count exceeds row limit. 77 $count = db_query('SELECT COUNT(wid) FROM {watchdog}')->fetchField(); 78 $this->assertTrue($count > $row_limit, t('Dblog row count of @count exceeds row limit of @limit', array('@count' => $count, '@limit' => $row_limit))); 79 80 // Run cron job. 81 $this->cronRun(); 82 // Verify dblog row count equals row limit plus one because cron adds a record after it runs. 83 $count = db_query('SELECT COUNT(wid) FROM {watchdog}')->fetchField(); 84 $this->assertTrue($count == $row_limit + 1, t('Dblog row count of @count equals row limit of @limit plus one', array('@count' => $count, '@limit' => $row_limit))); 85 } 86 87 /** 88 * Generate dblog entries. 89 * 90 * @param integer $count 91 * Number of log entries to generate. 92 * @param $type 93 * The type of watchdog entry. 94 * @param $severity 95 * The severity of the watchdog entry. 96 */ 97 private function generateLogEntries($count, $type = 'custom', $severity = WATCHDOG_NOTICE) { 98 global $base_root; 99 100 // Prepare the fields to be logged 101 $log = array( 102 'type' => $type, 103 'message' => 'Log entry added to test the dblog row limit.', 104 'variables' => array(), 105 'severity' => $severity, 106 'link' => NULL, 107 'user' => $this->big_user, 108 'uid' => isset($this->big_user->uid) ? $this->big_user->uid : 0, 109 'request_uri' => $base_root . request_uri(), 110 'referer' => $_SERVER['HTTP_REFERER'], 111 'ip' => ip_address(), 112 'timestamp' => REQUEST_TIME, 113 ); 114 $message = 'Log entry added to test the dblog row limit. Entry #'; 115 for ($i = 0; $i < $count; $i++) { 116 $log['message'] = $message . $i; 117 dblog_watchdog($log); 118 } 119 } 120 121 /** 122 * Verify the logged in user has the desired access to the various dblog nodes. 123 * 124 * @param integer $response HTTP response code. 125 */ 126 private function verifyReports($response = 200) { 127 $quote = '''; 128 129 // View dblog help node. 130 $this->drupalGet('admin/help/dblog'); 131 $this->assertResponse($response); 132 if ($response == 200) { 133 $this->assertText(t('Database logging'), t('DBLog help was displayed')); 134 } 135 136 // View dblog report node. 137 $this->drupalGet('admin/reports/dblog'); 138 $this->assertResponse($response); 139 if ($response == 200) { 140 $this->assertText(t('Recent log messages'), t('DBLog report was displayed')); 141 } 142 143 // View dblog page-not-found report node. 144 $this->drupalGet('admin/reports/page-not-found'); 145 $this->assertResponse($response); 146 if ($response == 200) { 147 $this->assertText(t('Top ' . $quote . 'page not found' . $quote . ' errors'), t('DBLog page-not-found report was displayed')); 148 } 149 150 // View dblog access-denied report node. 151 $this->drupalGet('admin/reports/access-denied'); 152 $this->assertResponse($response); 153 if ($response == 200) { 154 $this->assertText(t('Top ' . $quote . 'access denied' . $quote . ' errors'), t('DBLog access-denied report was displayed')); 155 } 156 157 // View dblog event node. 158 $this->drupalGet('admin/reports/event/1'); 159 $this->assertResponse($response); 160 if ($response == 200) { 161 $this->assertText(t('Details'), t('DBLog event node was displayed')); 162 } 163 } 164 165 /** 166 * Verify events. 167 */ 168 private function verifyEvents() { 169 // Invoke events. 170 $this->doUser(); 171 $this->doNode('article'); 172 $this->doNode('blog'); 173 $this->doNode('page'); 174 $this->doNode('poll'); 175 176 // When a user account is canceled, any content they created remains but the 177 // uid = 0. Their blog entry shows as "'s blog" on the home page. Records 178 // in the watchdog table related to that user have the uid set to zero. 179 } 180 181 /** 182 * Generate and verify user events. 183 * 184 */ 185 private function doUser() { 186 // Set user variables. 187 $name = $this->randomName(); 188 $pass = user_password(); 189 // Add user using form to generate add user event (which is not triggered by drupalCreateUser). 190 $edit = array(); 191 $edit['name'] = $name; 192 $edit['mail'] = $name . '@example.com'; 193 $edit['pass[pass1]'] = $pass; 194 $edit['pass[pass2]'] = $pass; 195 $edit['status'] = 1; 196 $this->drupalPost('admin/people/create', $edit, t('Create new account')); 197 $this->assertResponse(200); 198 // Retrieve user object. 199 $user = user_load_by_name($name); 200 $this->assertTrue($user != NULL, t('User @name was loaded', array('@name' => $name))); 201 $user->pass_raw = $pass; // Needed by drupalLogin. 202 // Login user. 203 $this->drupalLogin($user); 204 // Logout user. 205 $this->drupalLogout(); 206 // Fetch row ids in watchdog that relate to the user. 207 $result = db_query('SELECT wid FROM {watchdog} WHERE uid = :uid', array(':uid' => $user->uid)); 208 foreach ($result as $row) { 209 $ids[] = $row->wid; 210 } 211 $count_before = (isset($ids)) ? count($ids) : 0; 212 $this->assertTrue($count_before > 0, t('DBLog contains @count records for @name', array('@count' => $count_before, '@name' => $user->name))); 213 214 // Login the admin user. 215 $this->drupalLogin($this->big_user); 216 // Delete user. 217 // We need to POST here to invoke batch_process() in the internal browser. 218 $this->drupalPost('user/' . $user->uid . '/cancel', array('user_cancel_method' => 'user_cancel_reassign'), t('Cancel account')); 219 220 // View the dblog report. 221 $this->drupalGet('admin/reports/dblog'); 222 $this->assertResponse(200); 223 224 // Verify events were recorded. 225 // Add user. 226 // Default display includes name and email address; if too long then email is replaced by three periods. 227 $this->assertLogMessage(t('New user: %name (%email).', array('%name' => $name, '%email' => $user->mail)), t('DBLog event was recorded: [add user]')); 228 // Login user. 229 $this->assertLogMessage(t('Session opened for %name.', array('%name' => $name)), t('DBLog event was recorded: [login user]')); 230 // Logout user. 231 $this->assertLogMessage(t('Session closed for %name.', array('%name' => $name)), t('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 full message on 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, t('DBLog event details was found: [delete user]')); 247 break; 248 } 249 } 250 } 251 $this->assertTrue($link, t('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 dblog 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, t('DBLog event was recorded: [page not found]')); 261 } 262 263 /** 264 * Generate and verify node events. 265 * 266 * @param string $type Content type. 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 275 // Create node using form to generate add content event (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 node object. 282 $node = $this->drupalGetNodeByTitle($title); 283 $this->assertTrue($node != NULL, t('Node @title was loaded', array('@title' => $title))); 284 // Edit node. 285 $edit = $this->getContentUpdate($type); 286 $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save')); 287 $this->assertResponse(200); 288 // Delete node. 289 $this->drupalPost('node/' . $node->nid . '/delete', array(), t('Delete')); 290 $this->assertResponse(200); 291 // View node (to generate page not found event). 292 $this->drupalGet('node/' . $node->nid); 293 $this->assertResponse(404); 294 // View the dblog report (to generate access denied event). 295 $this->drupalGet('admin/reports/dblog'); 296 $this->assertResponse(403); 297 298 // Login the admin user. 299 $this->drupalLogin($this->big_user); 300 // View the dblog report. 301 $this->drupalGet('admin/reports/dblog'); 302 $this->assertResponse(200); 303 304 // Verify events were recorded. 305 // Content added. 306 $this->assertLogMessage(t('@type: added %title.', array('@type' => $type, '%title' => $title)), t('DBLog event was recorded: [content added]')); 307 // Content updated. 308 $this->assertLogMessage(t('@type: updated %title.', array('@type' => $type, '%title' => $title)), t('DBLog event was recorded: [content updated]')); 309 // Content deleted. 310 $this->assertLogMessage(t('@type: deleted %title.', array('@type' => $type, '%title' => $title)), t('DBLog event was recorded: [content deleted]')); 311 312 // View dblog access-denied report node. 313 $this->drupalGet('admin/reports/access-denied'); 314 $this->assertResponse(200); 315 // Access denied. 316 $this->assertText(t('admin/reports/dblog'), t('DBLog event was recorded: [access denied]')); 317 318 // View dblog page-not-found report node. 319 $this->drupalGet('admin/reports/page-not-found'); 320 $this->assertResponse(200); 321 // Page not found. 322 $this->assertText(t('node/@nid', array('@nid' => $node->nid)), t('DBLog event was recorded: [page not found]')); 323 } 324 325 /** 326 * Create content based on content type. 327 * 328 * @param string $type Content type. 329 * @return array Content. 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 342 default: 343 $content = array( 344 "title" => $this->randomName(8), 345 "body[$langcode][0][value]" => $this->randomName(32), 346 ); 347 break; 348 } 349 return $content; 350 } 351 352 /** 353 * Create content update based on content type. 354 * 355 * @param string $type Content type. 356 * @return array Content. 357 */ 358 private function getContentUpdate($type) { 359 switch ($type) { 360 case 'poll': 361 $content = array( 362 'choice[chid:1][chtext]' => $this->randomName(32), 363 'choice[chid:2][chtext]' => $this->randomName(32), 364 ); 365 break; 366 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 /** 378 * Login an admin user, create dblog event, and test clearing dblog functionality through the admin interface. 379 */ 380 protected function testDBLogAddAndClear() { 381 global $base_root; 382 // Get a count of how many watchdog entries there are. 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 incremented. 400 $this->assertEqual($count + 1, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), t('dblog_watchdog() added an entry to the dblog :count', array(':count' => $count))); 401 // Login the admin user. 402 $this->drupalLogin($this->big_user); 403 // Now post to clear the db table. 404 $this->drupalPost('admin/reports/dblog', array(), t('Clear log messages')); 405 // Count rows in watchdog that previously related to the deleted user. 406 $count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(); 407 $this->assertEqual($count, 0, t('DBLog contains :count records after a clear.', array(':count' => $count))); 408 } 409 410 /** 411 * Test the dblog filter on admin/reports/dblog. 412 */ 413 protected function testFilter() { 414 $this->drupalLogin($this->big_user); 415 416 // Clear log to ensure that only generated entries are found. 417 db_delete('watchdog')->execute(); 418 419 // Generate watchdog entries. 420 $type_names = array(); 421 $types = array(); 422 for ($i = 0; $i < 3; $i++) { 423 $type_names[] = $type_name = $this->randomName(); 424 $severity = WATCHDOG_EMERGENCY; 425 for ($j = 0; $j < 3; $j++) { 426 $types[] = $type = array( 427 'count' => $j + 1, 428 'type' => $type_name, 429 'severity' => $severity++, 430 ); 431 $this->generateLogEntries($type['count'], $type['type'], $type['severity']); 432 } 433 } 434 435 // View the dblog. 436 $this->drupalGet('admin/reports/dblog'); 437 438 // Confirm all the entries are displayed. 439 $count = $this->getTypeCount($types); 440 foreach ($types as $key => $type) { 441 $this->assertEqual($count[$key], $type['count'], 'Count matched'); 442 } 443 444 // Filter by each type and confirm that entries with various severities are 445 // displayed. 446 foreach ($type_names as $type_name) { 447 $edit = array( 448 'type[]' => array($type_name), 449 ); 450 $this->drupalPost(NULL, $edit, t('Filter')); 451 452 // Count the number of entries of this type. 453 $type_count = 0; 454 foreach ($types as $type) { 455 if ($type['type'] == $type_name) { 456 $type_count += $type['count']; 457 } 458 } 459 460 $count = $this->getTypeCount($types); 461 $this->assertEqual(array_sum($count), $type_count, 'Count matched'); 462 } 463 464 // Set filter to match each of the three type attributes and confirm the 465 // number of entries displayed. 466 foreach ($types as $key => $type) { 467 $edit = array( 468 'type[]' => array($type['type']), 469 'severity[]' => array($type['severity']), 470 ); 471 $this->drupalPost(NULL, $edit, t('Filter')); 472 473 $count = $this->getTypeCount($types); 474 $this->assertEqual(array_sum($count), $type['count'], 'Count matched'); 475 } 476 477 // Clear all logs and make sure the confirmation message is found. 478 $this->drupalPost('admin/reports/dblog', array(), t('Clear log messages')); 479 $this->assertText(t('Database log cleared.'), t('Confirmation message found')); 480 } 481 482 /** 483 * Get the log entry information form the page. 484 * 485 * @return 486 * List of entries and their information. 487 */ 488 protected function getLogEntries() { 489 $entries = array(); 490 if ($table = $this->xpath('.//table[@id="admin-dblog"]')) { 491 $table = array_shift($table); 492 foreach ($table->tbody->tr as $row) { 493 $entries[] = array( 494 'severity' => $this->getSeverityConstant($row['class']), 495 'type' => $this->asText($row->td[1]), 496 'message' => $this->asText($row->td[3]), 497 'user' => $this->asText($row->td[4]), 498 ); 499 } 500 } 501 return $entries; 502 } 503 504 /** 505 * Get the count of entries per type. 506 * 507 * @param $types 508 * The type information to compare against. 509 * @return 510 * The count of each type keyed by the key of the $types array. 511 */ 512 protected function getTypeCount(array $types) { 513 $entries = $this->getLogEntries(); 514 $count = array_fill(0, count($types), 0); 515 foreach ($entries as $entry) { 516 foreach ($types as $key => $type) { 517 if ($entry['type'] == $type['type'] && $entry['severity'] == $type['severity']) { 518 $count[$key]++; 519 break; 520 } 521 } 522 } 523 return $count; 524 } 525 526 /** 527 * Get the watchdog severity constant corresponding to the CSS class. 528 * 529 * @param $class 530 * CSS class attribute. 531 * @return 532 * The watchdog severity constant or NULL if not found. 533 * 534 * @ingroup logging_severity_levels 535 */ 536 protected function getSeverityConstant($class) { 537 // Reversed array from dblog_overview(). 538 $map = array( 539 'dblog-debug' => WATCHDOG_DEBUG, 540 'dblog-info' => WATCHDOG_INFO, 541 'dblog-notice' => WATCHDOG_NOTICE, 542 'dblog-warning' => WATCHDOG_WARNING, 543 'dblog-error' => WATCHDOG_ERROR, 544 'dblog-critical' => WATCHDOG_CRITICAL, 545 'dblog-alert' => WATCHDOG_ALERT, 546 'dblog-emerg' => WATCHDOG_EMERGENCY, 547 ); 548 549 // Find the class that contains the severity. 550 $classes = explode(' ', $class); 551 foreach ($classes as $class) { 552 if (isset($map[$class])) { 553 return $map[$class]; 554 } 555 } 556 return NULL; 557 } 558 559 /** 560 * Extract the text contained by the element. 561 * 562 * @param $element 563 * Element to extract text from. 564 * @return 565 * Extracted text. 566 */ 567 protected function asText(SimpleXMLElement $element) { 568 if (!is_object($element)) { 569 return $this->fail('The element is not an element.'); 570 } 571 return trim(html_entity_decode(strip_tags($element->asXML()))); 572 } 573 574 /** 575 * Assert messages appear on the log overview screen. 576 * 577 * This function should be used only for admin/reports/dblog page, because it 578 * check for the message link text truncated to 56 characters. Other dblog 579 * pages have no detail links so contains a full message text. 580 * 581 * @param $log_message 582 * The message to check. 583 * @param $message 584 * The message to pass to simpletest. 585 */ 586 protected function assertLogMessage($log_message, $message) { 587 $message_text = truncate_utf8(filter_xss($log_message, array()), 56, TRUE, TRUE); 588 // After filter_xss() HTML entities should be converted to their characters 589 // because assertLink() uses this string in xpath() to query DOM. 590 $this->assertLink(html_entity_decode($message_text), 0, $message); 591 } 592 } 593
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
title