You are here

function mostpopular_items_ajax in Drupal Most Popular 7

Same name and namespace in other branches
  1. 6 mostpopular.block.inc \mostpopular_items_ajax()
1 string reference to 'mostpopular_items_ajax'
mostpopular_menu in ./mostpopular.module
Implements hook_menu().

File

./mostpopular.module, line 896
The main file for the Most Popular module.

Code

function mostpopular_items_ajax($bid, $sid, $iid) {
  $rendered =& drupal_static(__FUNCTION__);
  $block = mostpopular_blocks($bid);
  $cid = "mostpopular_items:{$bid}:{$sid}:{$iid}";
  if (!isset($rendered[$bid][$sid][$iid])) {
    $cached = cache_get($cid, 'cache_block');
    if ($cached && $cached->expire > time()) {
      $rendered[$bid][$sid][$iid] = $cached->data;
    }
  }
  if (!isset($rendered[$bid][$sid][$iid])) {
    if (!empty($block->data['remote_database'])) {
      if (!db_set_active($block->data['remote_database'])) {
        watchdog('mostpopular', 'Missing remote database @database', array(
          '@database' => $block->data['remote_database'],
        ), WATCHDOG_ERROR);
        db_set_active('default');
        drupal_json_output('');
        return;
      }
    }
    try {
      $items = db_select('mostpopular_item', 'i')
        ->fields('i')
        ->condition('sid', $sid)
        ->condition('iid', $iid)
        ->orderBy('count', 'DESC')
        ->execute()
        ->fetchAll();
      $out = array(
        '#theme' => 'mostpopular_items',
        '#service' => mostpopular_service_load($sid),
        '#interval' => mostpopular_intervals($iid),
        '#items' => $items,
      );

      // Cache the rendered items until the next update
      $next_run = db_select('mostpopular_last_run', 'm')
        ->fields('m', array(
        'next_run',
      ))
        ->condition('sid', $sid)
        ->condition('iid', $iid)
        ->execute()
        ->fetchColumn();
    } catch (Exception $ex) {
      watchdog('mostpopular', 'Failed to load @source mostpopular items: %message', array(
        '@source' => !empty($block->data['remote_database']) ? t('remote') : t('local'),
        '%message' => $ex
          ->getMessage(),
      ), WATCHDOG_WARNING);
    }
    db_set_active('default');
    $rendered[$bid][$sid][$iid] = drupal_render($out);
    cache_set($cid, $rendered[$bid][$sid][$iid], 'cache_block', $next_run > 0 ? $next_run : CACHE_TEMPORARY);
  }
  if (isset($rendered[$bid][$sid][$iid])) {
    drupal_json_output($rendered[$bid][$sid][$iid]);
  }
  else {
    drupal_json_output('');
  }
}