<?php
/* $Id: aggregator2_autotaxonomy.module,v 1.8 2006/04/03 23:27:38 budda Exp $ */

/*
 * Aggregator2 Autotaxonomy
 *
 * @file
 * Allows Aggregator2 RSS items with <category> tags to auto create Drupal taxonomy terms.
 * @author Mike Carter <mike@ixis.co.uk>
 */

/**
* Implementation of hook_help().
*/
function aggregator2_autotaxonomy_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('Creates &amp; assign taxonomy terms to RSS feed items from &lt;category&gt; tags.');

    case 'admin/settings/aggregator2_autotaxonomy':
      return '<p>' . t('If the %url include %category tag information
      to organise the items, then this module will automatically create the same category in the
      %taxurl so that you can organise your aggregated posts.', array('%taxurl' => l('taxonomy system', 'admin/taxonomy'), '%url' => l('RSS feeds you are aggregating', 'admin/aggregator2'), '%category' => theme('placeholder', '<category>')) ) . '</p>';
  }
}


function aggregator2_autotaxonomy_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  static $cat_names = array();

  if($node->type == 'aggregator2-item' && isset($node->rss_item_data)) {
    $vocab = variable_get('aggregator2_autotaxonomy_vocabulary', FALSE);
    if(!$vocab) {
      watchdog('aggregator2', t('No vocabulary has been set for autotaxonomy to use.'), WATCHDOG_WARNING, l('set', 'admin/settings/aggregator2_autotaxonomy'));
      return;
    }
//[RSS:CATEGORY][][VALUE] && [RSS:CATEGORY][][DOMAIN] attrib
//[ATOM:CATEGORY][][TERM][][VALUE]
//[DC:SUBJECT][][VALUE]
    if ($node->rss_item_data['CATEGORY'][0]['VALUE']) $categories = $node->rss_item_data['CATEGORY']; // RSS 0.92, 2.0
    else if ($node->rss_item_data['CATEGORY'][0]['TERM'][0]['VALUE']) $categories = $node->rss_item_data['CATEGORY']; // ATOM 1.0
    else if ($node->rss_item_data['ATOM:CATEGORY'][0]['TERM'][0]['VALUE']) $categories = $node->rss_item_data['ATOM:CATEGORY']; // ATOM 1.0
    else if ($node->rss_item_data['SUBJECT']) $categories = $node->rss_item_data['SUBJECT']; // DublinCore
    else if ($node->rss_item_data['DC:SUBJECT']) $categories = $node->rss_item_data['DC:SUBJECT']; // DublinCore

    switch($op) {
      case 'insert':
      case 'update':
        // If the RSS item has any category tags, add new ones to taxonomy if needed
        if (count($categories) > 0) {
          if (!isset($node->taxonomy) || !is_array($node->taxonomy)) {
            $node->taxonomy = array();
          }

          foreach ($categories as $category_name) {
            if ($category_name['TERM']) { // ATOM 1.0
              $category_name = strtolower($category_name['TERM'][0]['VALUE']);
            }
            else { // RSS 0.92, RSS 2.0, DublinCore
              $category_name = strtolower($category_name['VALUE']);
            }

            if (trim($category_name) != '') {
              if (!isset($cat_names[$category_name])) {
                $cat_names[$category_name] = module_invoke('taxonomy', 'get_term_by_name', $category_name);
              }

              // Create a new category term
              if (count($cat_names[$category_name]) == 0) {
                $term = array();
                $term['name'] = $category_name;
                $term['description'] = t('Auto generated by aggregator2 autotaxonomy');
                $term['vid'] = $vocab;
                $term['weight'] = 0;
                $term = taxonomy_save_term($term);
                $node->taxonomy[] = $term['tid'];
                $cat_names[$category_name][0]->tid = $term['tid'];
              }
              else {
                // Use the existing category term in the database
                if (!in_array($cat_names[$category_name][0]->tid, $node->taxonomy)) {
                  $node->taxonomy[] = $cat_names[$category_name][0]->tid;
                }
              }
            }
          }
        }
        break;
    }
  }
}


function aggregator2_autotaxonomy_settings() {
  $vocabs = db_query("SELECT v.vid, v.name FROM {vocabulary} v INNER JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' ORDER BY v.weight, v.name", 'aggregator2_item');

  // Build list of available vocabularies
  $options = array();
  while ($vocabulary = db_fetch_object($vocabs)) {
    $options[$vocabulary->vid] = $vocabulary->name;
  }
  if($options) {
    $form['aggregator2_autotaxonomy_vocabulary'] = array(
    '#type' => 'select',
    '#title' => t('Vocabulary'),
    '#default_value' => variable_get('aggregator2_autotaxonomy_vocabulary', ''),
    '#options' => $options,
    '#description' => t('Which vocabulary should the auto created category names be associated with?')
    );
  }
  else {
    $form['helptext'] = array('#value' => '<p>' . t("You need to associate a %url with the node type %node to use this module.
                          If you don't have any vocabularies set-up you can %addurl now.",
                          array('%url' => l('vocabulary', 'admin/taxonomy'),
                                '%node' => theme('placeholder', 'feed item'),
                                '%addurl' => l('add one', 'admin/taxonomy/add/vocabulary')
                                )) . '</p>');
  }

  return $form;
}
?>
