$now = time();
// Figure out if it's been 24 hours since our last daily processing.
if (state_get('project_usage_last_daily', 0) <= $now - PROJECT_USAGE_DAY) {
    project_usage_process_daily();
    state_set('project_usage_last_daily', $now);
}
// We can't process the weekly data until the week has completed. To see if
// there's data available: determine the last time we completed the weekly
// processing and compare that to the start of this week. If the last
// weekly processing occurred before the current week began then there should
// be one (or more) week's worth of data ready to process.
$default = $now - config_get('project_usage.settings', 'life_daily');
$last_weekly = state_get('project_usage_last_weekly', $default);
$current_week_start = project_usage_weekly_timestamp(NULL, 0);
if ($last_weekly <= $current_week_start) {
    project_usage_process_weekly($last_weekly);
    state_set('project_usage_last_weekly', $now);
    // Reset the list of active weeks.
    project_usage_get_active_weeks(TRUE);
}
// Wipe the cache of all expired usage pages.
cache('project_usage')->flush();
/**
 * Process all the raw data up to the previous day.
 *
 * The primary key on the {project_usage_raw} table will prevent duplicate
 * records provided we process them once the day is complete. If we pull them
 * out too soon and the site checks in again they will be counted twice.
 */
function project_usage_process_daily()
{
    state_set('project_usage_last_daily', $daily_timestamp);
    $tables_updated = TRUE;
}
// Process the weekly data up until the current week. Data for the current
// (partial) week is not calculated.
$last_processed_weekly_timestamp = state_get('project_usage_last_weekly', REQUEST_TIME - PROJECT_USAGE_YEAR);
$start_of_current_week = project_usage_weekly_timestamp();
if ($last_processed_weekly_timestamp < $start_of_current_week) {
    // Start with the week following last processed one.
    $next_weekly_timestamp = project_usage_weekly_timestamp($last_processed_weekly_timestamp, 1);
    // Process all weeks up until the current one.
    while ($next_weekly_timestamp < $start_of_current_week) {
        // Increment the timestamp to the next week.
        $last_weekly_timestamp = $next_weekly_timestamp;
        $next_weekly_timestamp = project_usage_weekly_timestamp($last_weekly_timestamp, 1);
        project_usage_process_weekly($last_weekly_timestamp);
        state_set('project_usage_last_weekly', $last_weekly_timestamp);
    }
    // Reset the list of active weeks.
    project_usage_get_active_weeks(TRUE);
    $tables_updated = TRUE;
}
// Wipe the cache of all expired usage pages.
if ($tables_updated) {
    project_usage_remove_expired_data();
    cache('project_usage')->flush();
}
// All done.
exit;
/**
 * Assign node IDs to all the raw data that has been written.