<?php
// $Id: apachesolr_og.module,v 1.1.2.10 2010/05/03 19:08:13 jpmckinney Exp $

/**
 * @file
 *   Integrates Organic Group info with Apache Solr search application.
 */

/**
 * Implementation of hook_menu().
 */
function apachesolr_og_menu() {
  return array(
    'admin/og/apachesolr_og' => array(
      'title'            => 'Apache Solr OG configuration ',
      'description'      => 'Apache Solr OG facet settings for group posts.',
      'page callback'    => 'drupal_get_form',
      'page arguments'   => array('apachesolr_og_admin'),
      'access arguments' => array('administer search'),
    ),
  );
}

/**
 * Build a settings form.
 */
function apachesolr_og_admin() {
  $form = array();
  $form['apachesolr_og_groupnode'] = array(
    '#type' => 'radios',
    '#title' => t('Is the group node "included" within a group along with that group\'s posts'),
    '#description' => t('Should group nodes be indexed as belonging to their own group for the purposes of faceting?'),
    '#options' => array(0 => t('Not included'), 1 => t('Included')),
    '#default_value' => variable_get('apachesolr_og_groupnode', 0),
  );
  $form = system_settings_form($form);
  $form['#submit'][] = 'apachesolr_og_reindex';
  return $form;
}

/**
 * Submit function to make group nodes as needing re-indexing.
 */
function apachesolr_og_reindex() {
  $result = db_query("SELECT nid FROM {og}");
  while ($og = db_fetch_array($result)) {
    apachesolr_mark_node($og['nid']);
  }
  drupal_set_message(t('All group nodes marked for re-indexing'));
}

/**
 * Implementation of hook_apachesolr_update_index().
 */
function apachesolr_og_apachesolr_update_index(&$document, $node) {
  // Index group posts
  if (!empty($node->og_groups)) {
    foreach ($node->og_groups as $gid) {
      $document->setMultiValue(_apachesolr_og_gid_key(), $gid);
    }
  }
  elseif (isset($node->og_description) && variable_get('apachesolr_og_groupnode', 0)) {
    // Index the group node itself as in the group.
    $document->setMultiValue(_apachesolr_og_gid_key(), $node->nid);
  }
}

/**
 * Implementation of hook_apachesolr_modify_query().
 */
function apachesolr_og_apachesolr_modify_query(&$query, &$params, $caller) {
  // Fetch the group ID in results - however, this is currently not used.
  // May be useful for custom theming.
  if ($caller == 'apachesolr_search') {
    $params['fl'] .= ',' . _apachesolr_og_gid_key();
  }
}

/**
 * Implementation of hook_apachesolr_process_results().
 */
function apachesolr_og_apachesolr_process_results(&$results) {
  $key = _apachesolr_og_gid_key();
  $groups = array();
  foreach ($results as $idx => $r) {
    if (!is_array($r['node']->$key)) {
      $results[$idx]['node']->$key = $r['node']->$key ? array($r['node']->$key) : array();
    }
    foreach ($results[$idx]['node']->$key as $gid) {
      $groups[$gid] = $gid;
    }
  }

  if ($groups) {
    // Copied code from og_node_groups_distinguish() and og_nodeapi().
    $accessible_groups = array();
    $placeholders = db_placeholders($groups);
    $result = db_query(db_rewrite_sql('SELECT n.nid FROM {node} n WHERE n.nid IN (' . $placeholders . ')'), $groups);
    while ($row = db_fetch_object($result)) {
      $accessible_groups[] = $row->nid;
    }
    foreach ($results as $idx => $r) {
      $accessible = array_intersect($results[$idx]['node']->$key, $accessible_groups);
      if ($accessible) {
        $results[$idx]['extra'][] = format_plural(count($accessible), '1 group', '@count groups');
      }
    }
  }
}

/**
 * Apachesolr index name for Organic group id
 */
function _apachesolr_og_gid_key() {
  $group_id = array(
    'name'       => 'og_gid',
    'multiple'   => TRUE,
    'index_type' => 'integer',
  );
  // Returns im_og_gid.
  return apachesolr_index_key($group_id);
}

/**
 * Implementation of hook_apachesolr_facets().
 */
function apachesolr_og_apachesolr_facets() {
  $key = _apachesolr_og_gid_key();
  $facets[$key] = array(
    'info' => t('Apache Solr OG: Filter by Organic Group'),
    'facet_field' => $key,
  );
  return $facets;
}

/**
 * Implementation of hook_block().
 */
function apachesolr_og_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      $enabled_facets = apachesolr_get_enabled_facets('apachesolr_og');
      $facets = apachesolr_og_apachesolr_facets();
      // Add the blocks
      $blocks = array();
      foreach ($enabled_facets as $delta => $facet_field) {
        if (isset($facets[$delta])) {
          $blocks[$delta] = $facets[$delta] + array('cache' => BLOCK_CACHE_PER_PAGE);
        }
      }
      return $blocks;

    case 'view':
      if (apachesolr_has_searched()) {
        if ($delta != _apachesolr_og_gid_key()) {
          return;
        }

        $response = apachesolr_static_response_cache();
        if (empty($response)) {
          return;
        }
        $query = apachesolr_current_query();

        return apachesolr_facet_block($response, $query, 'apachesolr_og', $delta, $delta, t('Filter by Group'), 'apachesolr_og_group_name');
      }
      break;

    case 'configure':
      return apachesolr_facetcount_form('apachesolr_og', $delta);
    case 'save':
      apachesolr_facetcount_save($edit);
      break;
  }
}

/**
 * Callback function for the 'Filter by group' facet block.
 */
function apachesolr_og_group_name($facet, &$options) {
  if (!is_numeric($facet)) {
    $options['html'] = TRUE;
    return theme('placeholder', t('No group'));
  }

  return db_result(db_query("SELECT title FROM {node} WHERE nid = %d", $facet));
}

/**
 * Implementation of hook_theme().
 *
 * The breadcrumb function assumes that _apachesolr_og_gid_key() returns im_og_gid
 * If that changes, modify the theme name appropriately
 */
function apachesolr_og_theme() {
  return array(
    'apachesolr_breadcrumb_im_og_gid' => array('arguments' => array('group_id' => NULL)),
  );
}

/**
 * Theme the breadcrumb.
 */
function theme_apachesolr_breadcrumb_im_og_gid($group_id) {
  if (!is_numeric($group_id)) {
    return t('No group');
  }

  return db_result(db_query("SELECT title FROM {node} WHERE nid = %d", $group_id));
}

