I need to make sure my users are visiting a specific node. What could I accomplish this?
A counter would be nice (e.g. "viewed three times by User234 in the past week"). Would that be hard to implement?
The Statistics module that is part of Drupal already get that information. Its hook_exit()
implementation contains the following code.
if (variable_get('statistics_enable_access_log', 0)) {
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
// For anonymous users unicode.inc will not have been loaded.
include_once DRUPAL_ROOT . '/includes/unicode.inc';
// Log this page access.
db_insert('accesslog')
->fields(array(
'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
'path' => truncate_utf8($_GET['q'], 255),
'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
'hostname' => ip_address(),
'uid' => $user->uid,
'sid' => session_id(),
'timer' => (int) timer_read('page'),
'timestamp' => REQUEST_TIME,
))
->execute();
}
The data contained in that table are reset after 72 hours. statistics_cron() contains the following code.
// Clean up expired access logs (if applicable).
if (variable_get('statistics_flush_accesslog_timer', 259200) > 0) {
db_delete('accesslog')
->condition('timestamp', REQUEST_TIME - variable_get('statistics_flush_accesslog_timer', 259200), '<')
->execute();
}
The Statistics module has a setting page (admin/config/system/statistics) that allows you to decide when the access logs are discarded; you can choose to discard then when they are older than 1 week.
The Views module has code to expose in a view the data saved from the Statistics module; you can add a field to expose the number of times a node is viewed in a view.
Alternatively, you can create a custom module basing on the Statistics module's code. In this case, you would need to implement the code for integration with the Views module, if you need it.
As side note, hook_exit()
is probably going to be removed from Drupal 8; if you are using it in a Drupal 7 module, you will need to change your code when porting it to Drupal 8.
Because you need per-node per-user counts, the easiest approach I can think of is a small custom module. There were a few advanced statistic modules for Drupal 6 that might be able to track this info, but I'm not aware of any that accomplish this in Drupal 7. Writing a small module to simply increment a view count paired with uid and node vid in a table using hook_node_view would be a relatively small job for a drupal module developer.