You are here

function recently_read_exit in Recently Read 7.2

Same name and namespace in other branches
  1. 6 recently_read.module \recently_read_exit()
  2. 7 recently_read.module \recently_read_exit()

Implements hook_exit().

File

./recently_read.module, line 129
Recently read module file. Displays a history of recently read nodes by currently logged in user.

Code

function recently_read_exit($destination = NULL) {
  global $user;

  //  drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH);
  // track history for authenticated user
  if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == '' && ($node = node_load(arg(1)))) {
    $nid = arg(1);

    // Get node type from statically cached loaded node.
    $type = $node->type;

    // track history for authenticated user
    if (recently_read_is_enabled($type) && $user->uid) {

      // Save the database record for corresponding node and user.
      db_merge('recently_read_nodes')
        ->key(array(
        'nid' => $nid,
        'uid' => $user->uid,
      ))
        ->fields(array(
        'type' => $type,
        'timestamp' => REQUEST_TIME,
      ))
        ->execute();
    }

    // track history for anonymous user
    if (recently_read_is_enabled($type) && !$user->uid && variable_get('recently_read_anonymous_enabled', FALSE)) {
      $key = "recently_read-{$type}";
      if (!isset($_SESSION[$key])) {
        $_SESSION[$key] = array();
      }

      // remove previous entry, if present
      unset($_SESSION[$key][$nid]);

      // add new entry at the beginning of array
      $title = db_query('SELECT title FROM {node} WHERE nid = :nid', array(
        ':nid' => $nid,
      ))
        ->fetchField();
      $entry = array(
        'nid' => $nid,
        'title' => $title,
        'type' => $type,
        'timestamp' => time(),
      );
      $_SESSION[$key] = array(
        $nid => $entry,
      ) + $_SESSION[$key];
      while (count($_SESSION[$key]) > variable_get('recently_read_max_entries', 10)) {
        array_pop($_SESSION[$key]);
      }
    }

    // remove old entries
    $nids = array();
    $first = variable_get('recently_read_max_entries', 10) + 1;
    $result = db_query_range("SELECT nid FROM {recently_read_nodes}\n      WHERE uid = :uid ORDER BY timestamp DESC", $first, 1000, array(
      ':uid' => $user->uid,
    ));
    while ($nid = $result
      ->fetchField()) {
      $nids[] = $nid;
    }
    if (count($nids)) {
      db_query("DELETE FROM {recently_read_nodes} WHERE uid = :uid AND nid IN(:nids)", array(
        ':uid' => $user->uid,
        ':nids' => $nids,
      ));
    }
  }
}