<?php
// $Id: user_relationship_views.module,v 1.1.2.4 2009/10/15 15:23:26 aufumy Exp $

/**
 * @file
 * User Relationships Views integration.
 * @author Alex Karshakevich http://drupal.org/user/183217
 */

/**
 *  Implementation of hook_views_api().
 */
function user_relationship_views_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'user_relationship_views'),
  );
}

/**
 * Implementation of hook_menu().
 */
function user_relationship_views_menu() {
  // Path is not admin/build/views due to menu complications with the wildcards from
  // the generic ajax callback.
  $items['admin/views/ajax/autocomplete/user_relationships_type'] = array(
    'page callback' => 'user_relationship_views_ajax_autocomplete_relationships_type',
    'access callback' => 'user_access',
    'access arguments' => array('view user relationships'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Page callback for views user relationship types autocomplete
 */
function user_relationship_views_ajax_autocomplete_relationships_type($string = '') {
  // The same implementation as in admin/views/ajax/autocomplete/user
  // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  $array = drupal_explode_tags($string);

  // Fetch last tag
  $last_string = trim(array_pop($array));
  $matches = array();
  if ($last_string != '') {
    $prefix = count($array) ? implode(', ', $array) .', ' : '';

    $result = db_query_range("SELECT rtid, name FROM {user_relationship_types} WHERE LOWER(name) LIKE LOWER('%s%%')", $last_string, 0, 10);

    while ($rtype = db_fetch_object($result)) {
      $n = $rtype->name;
      // Commas and quotes in terms are special cases, so encode 'em.
      if (strpos($rtype->name, ',') !== FALSE || strpos($rtype->name, '"') !== FALSE) {
        $n = '"'. str_replace('"', '""', $rtype->name) .'"';
      }
      $matches[$prefix . $n] = check_plain(ur_tt("user_relationships:rtid:$rtype->rtid:name", $rtype->name));
    }
  }

  drupal_json($matches);
}
