<?php
/*
  Copyright (C) 2008 by Phase2 Technology.
  Author(s): Frank Febbraro, Irakli Nadareishvili

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License.
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY. See the LICENSE.txt file for more details.

  $Id: calais_api.module,v 1.3.2.10.2.14.2.6 2010/08/09 19:27:05 febbraro Exp $
*/
/**
 * @file
 */


/**
 * Implementation of hook_init().
 */
function calais_api_init() {
  // Only load these if it is not a cached page
  module_load_include('inc', 'calais_api', 'includes/Calais');
  module_load_include('inc', 'calais_api', 'includes/CalaisMetadata');
  module_load_include('inc', 'calais_api', 'includes/CalaisRdfProcessor');
  module_load_include('inc', 'calais_api', 'includes/SemanticProxy');
}

/**
 * Implementation of hook_perm().
 */
function calais_api_perm() {
  return array('administer calais api');
}

/**
 * Implementation of hook_menu().
 */
function calais_api_menu() {
  $items = array();
  
  $items['admin/settings/calais'] = array(
    'title' => 'Calais configuration',
    'description' => 'Configurations for Calais',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('calais_api_admin_settings'),
    'access arguments' => array('administer calais api'),
  );

  $items['admin/settings/calais/calais-api'] = array(
    'title' => 'Calais API Settings',
    'description' => 'Configurations for Calais API',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  return $items;
}

/**
 * Build the admin settings form.
 */
function calais_api_admin_settings() {
  $form = array();
  $calais_url = array(
    '!calaisurl' => l(t('Need One'), 'http://www.opencalais.com/user/register')
    );
  
  $form['calais_api_key'] = array(
    '#type' => 'textfield',
    '#title' => t('Calais API Key'),
    '#default_value' => variable_get('calais_api_key', NULL),
    '#size' => 60,
    '#description' => t('Required to utilize the Calais service. !calaisurl?', $calais_url),
  );
  $form['calais_api_server'] = array(
    '#type' => 'textfield',
    '#title' => t('Calais Server'),
    '#default_value' => variable_get('calais_api_server', 'api1.opencalais.com'),
    '#size' => 60,
    '#description' => t('The domain name for the server to use.  Typically you will not have to change this unless you want to test beta functionality.'),
  );
  
  $form = system_settings_form($form);
  return $form;
}

/**
* 
* Checks if Calais API Key is set
*
* @param $show_warning
*   Whether to display a warning
*/
function is_calais_api_key_set($show_warning = TRUE) {

  $apikey = variable_get('calais_api_key', FALSE);

  if (empty($apikey)) {
    if ($show_warning) {
      drupal_set_message(t('Calais semantic analysis skipped because Calais API Key is not set. Please configure it at: !link', 
                              array('!link' => l('admin/settings/calais','admin/settings/calais', 
                                                array('attributes' => array('target' => '_blank'))
                                                )
                                    )
                          ),
                        $type = 'warning', $repeat = FALSE);
    }
    return FALSE;
  }

  return TRUE;

}

/**
 * Analyze the content via Calais.
 *
 * @param $content The content to ship off to Calais for analysis
 * @param $parameters Array of Calais parameters for overriding defaults.
 * @see http://www.opencalais.com/APIcalls#inputparameters
 *
 * @return The analyzed content
 */
function calais_api_analyze($content, $parameters = array()) {

  if (!is_calais_api_key_set()) {
    return array();
  }

  $calais = new Calais($parameters);
  return $calais->analyze($content);
}

/**
 * Analyze the content via the Calais XML interface.
 *
 * @param $title The title of the content
 * @param $body The entire body of the content
 * @param $date The date of the content (can be created or updated date) 
 *    This date is used to base calculations of words like "tomorrow" or "yesterday"
 * @param $parameters Array of Calais parameters for overriding defaults.
 * @see http://www.opencalais.com/APIcalls#inputparameters
 *
 * @return The analyzed content
 */
function calais_api_analyze_xml($title, $body, $date, $parameters = array()) {

  if (!is_calais_api_key_set()) {
    return array();
  }

  $calais = new Calais($parameters);
  return $calais->analyzeXML($title, $body, $date);
}

/**
 * Takes a CamelCase word and adds spaces to make it Camel Case
 *
 * @return an formated string
 */
function calais_api_make_readable($camel_case) {
  return preg_replace('/(.*?[a-z]{1})([A-Z]{1}.*?)/', '${1} ${2}', $camel_case);
}

/**
 * Declare the Calais namespace to the RDF API module (in case we use it)
 */
function calais_api_rdf_namespaces() {
  return array(
    'c' => 'http://s.opencalais.com/1/pred/',
    'sys' => 'http://s.opencalais.com/1/type/sys/',
    'lid' => 'http://s.opencalais.com/1/type/lid/',
    'cat' => 'http://s.opencalais.com/1/type/cat/',
    'resolved' => 'http://s.opencalais.com/1/type/er/',
    'cgeo' => 'http://s.opencalais.com/1/type/er/Geo/',
    'eventfact' => 'http://s.opencalais.com/1/type/em/r/',
    'entity' => 'http://s.opencalais.com/1/type/em/e/',
    'cld' => "http://s.opencalais.com/1/linkeddata/pred/",
  );
}

/**
 * Get a list of the entities that Calais API defines:
 * http://opencalais.mashery.com/page/calaissemanticmetadata
 *
 * TODO: When Calais updates to have a static list at a URL or via API call, return that instead.
 *
 * @return flat array listing of Calais entities
 */
function calais_api_get_all_entities() {
  return array(
    'Anniversary',
    'City',
    'Company',
    'Continent',
    'Country',
    'Currency',
    'EmailAddress',
    'EntertainmentAwardEvent',
    'Facility',
    'FaxNumber',
    'Holiday',
    'IndustryTerm',
    'MarketIndex',
    'MedicalCondition',
    'MedicalTreatment',
    'Movie',
    'MusicAlbum',
    'MusicGroup',
    'NaturalDisaster',
    'NaturalFeature',
    'OperatingSystem',
    'Organization',
    'Person',
    'PhoneNumber',
    'Position',
    'Product',
    'ProgrammingLanguage',
    'ProvinceOrState',
    'PublishedMedium',
    'RadioProgram',
    'RadioStation',
    'Region',
    'SportsEvent',
    'SportsGame',
    'SportsLeague',
    'Technology',
    'TVShow',
    'TVStation',
    'URL',
    'SocialTags', // Special reserved vocab for Calais Social Tags
    'CalaisDocumentCategory', // Special reserved vocab for Calais Document Categorization
    'EventsFacts', // Special reserved vocab for Events & Facts
  );
}
