<?php
/**
 * Implementation of hook_theme().
 */
function openpublish_popular_terms_theme() {
  return array(
    'popular_term_display' => array(
      'arguments' => array('pop_terms' => NULL, 'disregard' => NULL),
    ),
    'featured_topic_hubs_display' => array(
      'arguments' => array($topic_hubs => NULL),
    ),
  );
}

/**
 * Implementation of hook_menu().
 */
function openpublish_popular_terms_menu() {
  $items = array();
  $items['most-used-terms'] = array(
    'title' => t('Most Used Terms'),
    'page callback' => '_op_popular_terms',
    'access arguments' => array('access content'),
    'type' => MENU_LOCAL_TASK,
  );

  $items['admin/content/taxonomy/popular_terms/%taxonomy_vocabulary/filter'] = array(
    'title' => t('Popular Terms Filter'),
    'page arguments' => array(4),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_CALLBACK,
  
  );
  
  $items['admin/settings/popular_terms'] = array(
    'title' => t('Popular Terms Settings'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('_op_popular_terms_settings'),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_LOCAL_TASK,
  );  
  
  return $items;
}

/**
* Generate HTML for the list of popular terms
* @param op the operation from the URL
* @param delta offset
* @returns block HTML
*/
function openpublish_popular_terms_block($op = 'list', $delta = 0) {
  // listing of blocks, such as on the admin/block page
  if ($op == "list") {
    $blocks[0]["info"] = t('Most Used Terms');
    $blocks[1]["info"] = t('Featured Topic Hubs');
    return $blocks;
  }
  else if ($op == 'view') { 
    switch($delta) {
      case 0:
        $block['subject'] = t('Most Used Terms');
        $block['content'] .= _op_popular_terms(FALSE, 5);
        break;
      case 1:
        $block['subject'] = t('Featured Topic Hubs');
        $block['content'] .= _op_featured_topic_hubs();
        break;    
    }   
    return $block;
  }
}

/**
 * admin settings form for the module
 * set the default vocabularies to disregard.
 */
function _op_popular_terms_settings() {

  $form['global_settings']['markup'] = array(
    '#value' => l(t('View Popular Tags'), 'admin/content/taxonomy/popular_terms'),
  );

  $vocabs = taxonomy_get_vocabularies();
  $options = array();
  foreach($vocabs as $vocab) {
    $options["$vocab->vid"] = $vocab->name;
  }

  $form['global_settings']['pop_terms_disregard'] = array(
    '#type' => 'select',
    '#multiple' => TRUE,
    '#title' => t('Vocabularies to disregard'),
    '#description' => t('select vocabularies that should not be used on the popular tag tab.'),
    '#options' => $options,
    '#default_value' => variable_get('pop_terms_disregard', NULL),
  );


  return system_settings_form($form);
}

/**
 * Listing page for popular terms 
 */
function _op_popular_terms($display_pager = TRUE, $return_no = 25) {
  // remove the default filters for the display
  $default_filter = variable_get('pop_terms_disregard', NULL);
  $pop_terms = _get_popular_terms_by_node_count($default_filter, $return_no);
  
  return theme('popular_term_display', $pop_terms, $display_pager, $return_no, $default_filter);
}

function _op_featured_topic_hubs() {
  $topic_hubs = _get_topic_hubs_by_node_count();  
  return theme('featured_topic_hubs_display', $topic_hubs);
}

function theme_featured_topic_hubs_display($topic_hubs) {  
  return theme('item_list', $topic_hubs);
}  

/**
 * theme function for the display table
 */
function theme_popular_term_display($pop_terms, $display_pager, $return_no, $disregard) {      
  $header = array(    
    t('Term'),
    t('Count'),    
  );
  
  $attribs = array('class' => 'popular-tags');
  $intro_text = ($display_pager) ? t("Most Popular terms used on the site. Click on the term to view content tagged with that term.") : '';
  if ($display_pager) {
    $output .= theme('table', $header, $pop_terms, $attribs, $intro_text);
  }
  else {
    $output .= theme('item_list', $pop_terms);
  }
  if ($display_pager) $output .= theme('pager', array(), $return_no, 0);
  return $output;  
}

/**
 * Retrieve terms.
 * @param array disregard
 *  list of vocabulary ids excluded from the count.
 */
function _get_popular_terms_by_node_count($disregard, $per_page = 50) {
      
  $sql = "SELECT v.vid, td.name, t.tid, COUNT(n.nid) AS count ";  
  $sql .= "FROM {term_node} t ";
  $sql .= "INNER JOIN {node} n ON t.vid = n.vid ";  
  $sql .= "INNER JOIN {term_data} td ON t.tid = td.tid ";
  $sql .= "INNER JOIN {vocabulary} v ON v.vid = td.vid ";
  $sql .= "WHERE n.status = 1 ";

  if($disregard) {
    $sql .= "AND td.vid NOT IN(" . implode(",", $disregard) . ") ";
  }
  
  if(module_exists('calais_tagmods') && variable_get('calais_tag_blacklist', NULL)) {    
    $blacklist = explode(",", variable_get('calais_tag_blacklist', NULL));
    $sql .= "AND td.name NOT IN (";
    foreach($blacklist as $black_term) {
      $sql .= "'".$black_term."', ";
    }
    $sql = rtrim($sql, ", ");
    $sql .= ") ";
  }

  $sql .= "GROUP BY t.tid ";
  $sql .= "ORDER BY count DESC";

  $count_query = "SELECT COUNT(DISTINCT(t.tid)) FROM {term_node} t ";
  if($disregard) {
    $count_query .= "join {term_data} td on td.tid = t.tid where td.vid not in (". implode(",", $disregard) .")";
  }
  
  $result = pager_query($sql, $per_page, 0, $count_query);  

  $rows = array();

  while($item = db_fetch_array($result)) {    
    //unset($item['tid']);
    //unset($item['vid']);                
    //$item['name'] = l($item[name], 'topics/'.$item[name]);        
    $rows[] = l($item[name], 'topics/'.$item[name]);
  }  
  
  return $rows;
}

function _get_topic_hubs_by_node_count() {
  $sql = 'SELECT DISTINCT n.title, n.nid, COUNT(n.nid) as count ';
  $sql .= 'FROM {term_node} t ';
  $sql .= 'INNER JOIN {topichub_condition} thc ON thc.tid = t.tid ';
  $sql .= 'INNER JOIN {node} n ON n.nid = thc.nid ';
  $sql .= 'INNER JOIN {term_data} td ON t.tid = td.tid ';
  $sql .= 'INNER JOIN {vocabulary} v ON v.vid = td.vid ';
  $sql .= 'WHERE n.status = 1 and t.tid ';
  
  if(module_exists('calais_tagmods') && variable_get('calais_tag_blacklist', NULL)) {    
    $blacklist = explode(",", variable_get('calais_tag_blacklist', NULL));
    $sql .= "AND td.name NOT IN (";
    foreach($blacklist as $black_term) {
      $sql .= "'".$black_term."', ";
    }
    $sql = rtrim($sql, ", ");
    $sql .= ") ";
  }
  
  $sql .= 'GROUP BY n.title ';
  $sql .= 'ORDER BY count DESC ';
  $sql .= 'LIMIT 5';
  
  $results = db_query($sql);
  
  $rows = array();

  while($item = db_fetch_array($results)) {          
    $rows[] = l($item[title], 'node/'.$item[nid]);
  }  
 
  return $rows;
}