You are here

function alchemy_get_elements in Alchemy 7

Same name and namespace in other branches
  1. 6 alchemy.module \alchemy_get_elements()

@todo Please document this function.

See also

http://drupal.org/node/1354

2 calls to alchemy_get_elements()
alchemy_contentanalysis_analyzer in modules/alchemy_contentanalysis/alchemy_contentanalysis.module
Implements hook_analyzer() via custom define callback().
alchemy_get_elements_from_node in ./alchemy.module

File

./alchemy.module, line 84
$Id: alchemy.module,v 1.1.2.3 2010/11/17 21:17:48 tomdude48 Exp $

Code

function alchemy_get_elements($text, $type = 'keywords', $output = 'normalized', $cid = 0, $use_cache = FALSE) {

  // Clean tags.
  $text = strip_tags($text);
  $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
  $text = str_ireplace(' ', ' ', $text);
  if ($use_cache && $cid) {
    $resultstr = alchemy_cache_get($cid, $type);
  }
  if (!isset($resultstr) || empty($resultstr)) {
    if (!($alchemy_obj = alchemy_new_alchemy_obj())) {
      return FALSE;
    }

    // Extract topic keywords from a text string.
    try {
      switch ($type) {
        case 'entities':
          $resultstr = $alchemy_obj
            ->TextGetRankedNamedEntities($text);
          break;
        case 'categories':
          $resultstr = $alchemy_obj
            ->TextGetCategory($text);
          break;
        case 'concepts':
          $resultstr = $alchemy_obj
            ->TextGetRankedConcepts($text);
          break;
        case 'keywords':
          $resultstr = $alchemy_obj
            ->TextGetRankedKeywords($text);
          break;
      }
    } catch (Exception $exc) {
      drupal_set_message($exc
        ->getMessage(), 'warning');
      return;
    }
    if ($cid) {
      alchemy_cache_set($cid, $type, $resultstr);
    }
  }
  if ($output == 'xml') {
    return $resultstr;
  }
  $result = alchemy_xml2array($resultstr);
  if ($output == 'array') {
    return $result;
  }
  $elements = array();
  switch ($type) {
    case 'entities':
      $elms = $result->entities->entity;
      break;
    case 'categories':

      // TODO.
      $elms = array();
      break;
    case 'concepts':
      $elms = $result->concepts->concept;
      break;
    case 'keywords':
      $elms = $result->keywords->keyword;
      break;
  }
  if (is_object($elms)) {
    foreach ($elms as $v) {
      $hash = (string) $v->text;
      $elements[$hash] = array(
        'term' => (string) $v->text,
        'relevance' => (double) $v->relevance,
      );
      if ($v->type) {
        $elements[$hash]['type'] = (string) $v->type;
      }
      if ($v->count) {
        $elements[$hash]['count'] = (string) $v->count;
      }
      if ($v->disambiguated) {
        $elements[$hash]['disambiguated'] = $v->disambiguated;
      }
    }
  }
  return $elements;
}