Browse Source

Initial import of version 0.2

spficklin 15 years ago
parent
commit
01c437a68f

+ 19 - 0
tripal_library/reindex.php

@@ -0,0 +1,19 @@
+<?php
+//
+// Copyright 2009 Clemson University
+//
+
+
+/* 
+
+This script must be run at the base directory level of the drupal installation 
+in order to pick up all necessary dependencies 
+
+*/
+
+require_once './includes/bootstrap.inc';
+drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
+
+jlibrary_feature_reindex($argv[1]);
+
+?>

+ 18 - 0
tripal_library/taxonify.php

@@ -0,0 +1,18 @@
+<?php
+//
+// Copyright 2009 Clemson University
+//
+
+/* 
+
+This script must be run at the base directory level of the drupal installation 
+in order to pick up all necessary dependencies 
+
+*/
+
+require_once './includes/bootstrap.inc';
+drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
+
+jlibrary_feature_set_taxonomy($argv[1]);
+
+?>

+ 11 - 0
tripal_library/tripal_library.info

@@ -0,0 +1,11 @@
+; $Id: tripal_library.info,v 1.3 2009/10/23 02:12:42 ccheng Exp $
+name = Tripal Chado Library
+description = A module for interfacing the GMOD chado database with Drupal, providing viewing, inserting and editing of lbraries.
+core = 6.x
+project = tripal_library
+package = Tripal
+dependencies[] = tripal_core
+dependencies[] = tripal_organism
+dependencies[] = search
+dependencies[] = path
+version = "6.x-0.2b-m0.2"

+ 146 - 0
tripal_library/tripal_library.install

@@ -0,0 +1,146 @@
+<?php
+
+/*******************************************************************************
+*  Implementation of hook_install();
+*/
+function tripal_library_install(){
+   // create the module's data directory
+   tripal_create_moddir('tripal_library');
+
+   // create the tables that correlate drupal nodes with chado
+   // features, librarys, etc....
+   drupal_install_schema('tripal_library');
+
+   // Insert cvterm 'library_description' into cvterm table of chado
+   // database. This CV term is used to keep track of the library
+   // description in the libraryprop table.
+   tripal_add_cvterms('library_description','Description of a library');
+   
+   // Add CVTerms for the library types
+   tripal_add_cvterms('cdna_library','cDNA Library');
+   tripal_add_cvterms('bac_library','BAC Library');
+   tripal_add_cvterms('fosmid_library','FOSMID Library');
+   tripal_add_cvterms('cosmid_library','COSMID Library');
+   tripal_add_cvterms('yac_library','YAC Library');
+
+   // Add the materialized view needed to count the features for the library
+   // Drop the MView table if it exists
+   $previous_db = db_set_active('chado');
+   if (db_table_exists('library_feature_count')) {
+      $sql = "DROP TABLE library_feature_count";
+      db_query($sql);
+   }
+   db_set_active($previous_db);
+   // Create the MView
+   tripal_add_mview('library_feature_count','tripal_library',
+      'library_feature_count',
+      'library_id integer, name character varying(255), '.
+		'  num_features integer, feature_type character varying(255)',
+	   'library_id',
+	   'SELECT '.
+      '   L.library_id, '.
+      '   L.name, '.
+      '    count(F.feature_id) as num_features, '.
+      '    CVT.name as feature_type '.
+      'FROM {Library} L '.
+      '    INNER JOIN Library_Feature LF  ON LF.library_id = L.library_id '.
+      '    INNER JOIN Feature F           ON LF.feature_id = F.feature_id '.
+      '    INNER JOIN Cvterm CVT          ON F.type_id = CVT.cvterm_id '.
+      'GROUP BY L.library_id, L.name, CVT.name',
+	   ''
+   );
+
+}
+
+/*******************************************************************************
+ * Implementation of hook_schema().
+ */
+function tripal_library_schema() {
+   $schema = tripal_library_get_schemas();
+   return $schema;
+}
+
+/*******************************************************************************
+ * Implementation of hook_uninstall()
+ */
+function tripal_library_uninstall(){
+   drupal_uninstall_schema('tripal_library');
+
+   // remove the materialized view
+   $sql = "SELECT * FROM {tripal_mviews} ".
+          "WHERE name = 'library_feature_count'";
+
+   if (db_table_exists('tripal_mviews')) {
+      $mview = db_fetch_object(db_query($sql));
+      if($mview){
+         tripal_mviews_action('delete',$mview->mview_id);
+      }
+   }
+
+   // Get the list of nodes to remove
+   $sql_lib_id = "SELECT nid, vid ".
+                 "FROM {node} ".
+                 "WHERE type='chado_library'";
+   $result = db_query($sql_lib_id);
+   while ($node = db_fetch_object($result)) {
+      node_delete($node->nid);
+   }
+}
+
+/*******************************************************************************
+ * This function simply defines all tables needed for the module to work
+ * correctly.  By putting the table definitions in a separate function we
+ * can easily provide the entire list for hook_install or individual
+ * tables for an update.
+ */
+function tripal_library_get_schemas (){
+  $schema = array();
+  $schema['chado_library'] = array(
+      'fields' => array(
+         'vid' => array(
+            'type' => 'int',
+            'unsigned' => TRUE,
+            'not null' => TRUE,
+            'default' => 0
+         ),
+         'nid' => array(
+            'type' => 'int',
+            'unsigned' => TRUE,
+            'not null' => TRUE,
+            'default' => 0
+         ),
+         'library_id' => array(
+            'type' => 'int',
+            'not null' => TRUE,
+            'default' => 0
+         )
+      ),
+      'indexes' => array(
+         'library_id' => array('library_id')
+      ),
+      'unique keys' => array(
+         'nid_vid' => array('nid','vid'),
+         'vid' => array('vid')
+      ),
+      'primary key' => array('nid'),
+  );
+  return $schema;
+}
+
+/*******************************************************************************
+ * Implementation of hook_requirements(). Make sure 'Tripal Core' is enabled
+ * before installation
+ */
+function tripal_library_requirements($phase) {
+   $requirements = array();
+   if ($phase == 'install') {
+      if (!function_exists('tripal_create_moddir')) {
+         $requirements ['tripal_library'] = array(
+            'title' => "tripal_library",
+            'value' => "error. Some required modules are just being installed. Please try again.",
+            'severity' => REQUIREMENT_ERROR,
+         );
+      }
+   }
+   return $requirements;
+}

+ 1648 - 0
tripal_library/tripal_library.module

@@ -0,0 +1,1648 @@
+<?php
+
+//
+// Copyright 2009 Clemson University
+//
+
+/*******************************************************************************
+ * Display help and module information
+ * @param path which path of the site we're displaying help
+ * @param arg array that holds the current path as would be returned from arg()
+ * function
+ * @return help text for the path
+ */
+function tripal_library_help($path, $arg) {
+   $output = '';
+   switch ($path) {
+      case "admin/help#tripal_library":
+         $output = '<p>'.
+         t("Displays links to nodes created on this date").
+                   '</p>';
+         break;
+   }
+   return $output;
+}
+
+/*******************************************************************************
+ * Provide information to drupal about the node types that we're creating
+ * in this module
+ */
+function tripal_library_node_info() {
+   $nodes = array();
+   $nodes['chado_library'] = array(
+      'name' => t('Library'),
+      'module' => 'chado_library',
+      'description' => t('A library from the chado database'),
+      'has_title' => FALSE,
+      'title_label' => t('Library'),
+      'has_body' => FALSE,
+      'body_label' => t('Library Description'),
+      'locked' => TRUE
+   );
+   return $nodes;
+}
+
+/*******************************************************************************
+ * Set the permission types that the chado module uses.  Essentially we
+ * want permissionis that protect creation, editing and deleting of chado
+ * data objects
+ */
+function tripal_library_perm(){
+   return array(
+      'access chado_library content',
+      'create chado_library content',
+      'delete chado_library content',
+      'edit chado_library content',
+   );
+}
+/************************************************************************
+ *  Set the permission types that the module uses.
+ */
+function chado_library_access($op, $node, $account) {
+   if ($op == 'create') {
+      return user_access('create chado_library content', $account);
+   }
+
+   if ($op == 'update') {
+      if (user_access('edit chado_library content', $account)) {
+         return TRUE;
+      }
+   }
+   if ($op == 'delete') {
+      if (user_access('delete chado_library content', $account)) {
+         return TRUE;
+      }
+   }
+   if ($op == 'view') {
+      if (user_access('access chado_library content', $account)) {
+         return TRUE;
+      }
+   }
+   return FALSE;
+}
+/*******************************************************************************
+ * Menu items are automatically added for the new node types created
+ * by this module to the 'Create Content' Navigation menu item.  This function
+ * adds more menu items needed for this module.
+ */
+function tripal_library_menu() {
+   $items = array();
+   // The administative settings menu
+   $items['admin/tripal/tripal_library'] = array(
+      'title' => 'Libraries',
+      'description' => 'Manage integration of Chado libraries including associated features.',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_library_admin'),
+      'access arguments' => array('access administration pages'),
+      'type' => MENU_NORMAL_ITEM,
+   );
+   // Synchronizing libraries from Chado to Drupal
+   $items['chado_sync_libraries'] = array(
+      'title' => t('Sync Data'),
+      'page callback' => 'tripal_library_sync_libraries',
+      'access arguments' => array('access administration pages'),
+      'type' => MENU_CALLBACK
+   );
+   // Displaying libraries
+   $items['libraries'] = array(
+      'menu_name' => ('primary-links'), //Enable the 'Library' primary link
+      'title' => t('DNA Libraries'),
+      'page callback' => 'tripal_library_show_libraries',
+      'access arguments' => array('access chado_library content'),
+      'type' => MENU_NORMAL_ITEM
+   );
+
+   $items['node/%/libraries'] = array(
+     'title' => t('Libraries'),
+     'page callback' => 'get_tripal_library_organism_libraries',
+     'page arguments' => array(1),
+     'access callback' => 'tripal_library_node_has_menu',
+     'access arguments' => array('access chado_library content',1),
+     'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM
+   );
+
+   return $items;
+}
+/*******************************************************************************
+ * Dynamic addition/removal of menu item
+ */
+function tripal_library_node_has_menu($type,$vid){
+   // check to see if this node is an organism node
+   $sql = 'SELECT organism_id FROM {chado_organism} WHERE vid = %d';
+   $result = db_query($sql, $vid);
+
+   // menu status
+   $box_status =variable_get("tripal_library-box-libraries","menu_off");
+
+   // if this node is not an organism or a feature node then return false
+   // we don't want the menu item to be shown, otherwise get the normal perms
+   if($org_id = db_fetch_object($result)){
+      if(strcmp($box_status,"menu_on")==0){
+         return user_access($type);
+      }
+   } else {
+      return FALSE;
+   }
+}
+
+/*******************************************************************************
+ * Administrative settings form
+ */
+function tripal_library_admin () {
+   $form = array();
+
+   // before proceeding check to see if we have any
+   // currently processing jobs. If so, we don't want
+   // to give the opportunity to sync libraries
+   $active_jobs = FALSE;
+   if(tripal_get_module_active_jobs('tripal_library')){
+      $active_jobs = TRUE;
+   }
+
+   // add the field set for syncing libraries
+   if(!$active_jobs){
+      get_tripal_library_admin_form_sync_set ($form);
+      get_tripal_library_admin_form_reindex_set($form);
+      get_tripal_library_admin_form_taxonomy_set($form);
+      get_tripal_library_admin_form_cleanup_set($form);
+      get_tripal_library_admin_form_menu_set($form);
+   } else {
+      $form['notice'] = array(
+		   '#type' => 'fieldset',
+		   '#title' => t('Library Management Temporarily Unavailable')
+      );
+      $form['notice']['message'] = array(
+          '#value' => t('Currently, library management jobs are waiting or are running. . Managemment features have been hidden until these jobs complete.  Please check back later once these jobs have finished.  You can view the status of pending jobs in the Tripal jobs page.'),
+      );
+   }
+
+   return system_settings_form($form);
+}
+
+/*******************************************************************************
+ * HOOK: Implementation of hook_nodeapi()
+ * Display library information for associated features or organisms
+ * This function also provides contents for indexing
+ */
+function tripal_library_nodeapi(&$node, $op, $teaser, $page) {
+
+   switch ($op) {
+      // Note that this function only adds library view to an organism/feature
+      // node. The view of a library node is controled by the theme *.tpl file
+      case 'view':
+         // Set the node types for showing library information
+         $types_to_show = array('chado_organism', 'chado_feature');
+
+         // Abort if this node is not one of the types we should show.
+         if (!in_array($node->type, $types_to_show, TRUE)) {
+            break;
+         }
+
+         // Add library to the content item if it's not a teaser
+         if (!$teaser) {
+            // add the library to the organism/feature search indexing
+            if($node->build_mode == NODE_BUILD_SEARCH_INDEX){
+               $node->content['tripal_library_index_version'] = array(
+						'#value' => theme('tripal_library_search_index',$node),
+						'#weight' => 4,
+               );
+            } else if ($node->build_mode == NODE_BUILD_SEARCH_RESULT) {
+               $node->content['tripal_library_index_version'] = array(
+						'#value' => theme('tripal_library_search_result',$node),
+						'#weight' => 4,
+               );
+            } else {
+               // Show library if the organism/feature is not at teaser view
+               $node->content['tripal_library_node_addition'] = array(
+						'#value' => theme('tripal_library_node_libraries', $node),
+						'#weight' => 4
+               );
+            }
+         }
+   }
+}
+
+/************************************************************************
+ *  We need to let drupal know about our theme functions and their arguments.
+ *  We create theme functions to allow users of the module to customize the
+ *  look and feel of the output generated in this module
+ */
+function tripal_library_theme () {
+   return array(
+   	  'tripal_library_library_table' => array (
+         'arguments' => array('libraries'),
+   ),
+      'tripal_library_search_index' => array (
+         'arguments' => array('node'),
+   ),
+      'tripal_library_search_result' => array (
+         'arguments' => array('node'),
+   ),
+      'tripal_library_node_libraries' => array (
+         'arguments' => array('node'),
+   )
+   );
+}
+
+/************************************************************************
+ * This function is an extension of the chado_feature_view and
+ * chado_organism_view by providing the markup for the feature/organism object
+ * to show on a search result page.
+ */
+function theme_tripal_library_search_result ($node) {
+   if ($node->type == 'chado_organism') {
+      $content = "";
+      // get the libraries for the organism
+      $previous_db = db_set_active('chado');
+      $sql = "SELECT * FROM {library} L ".
+       	     "WHERE L.Organism_id = $node->organism_id";
+      $libraries = array();
+      $results = db_query($sql);
+      while($library = db_fetch_object($results)){
+         // get the description
+         $sql = "SELECT * FROM {libraryprop} LP ".
+           	    "  INNER JOIN CVTerm CVT ON CVT.cvterm_id = LP.type_id ".
+                "WHERE LP.library_id = $library->library_id ".
+                "  AND CVT.name = 'library_description'";
+         $desc = db_fetch_object(db_query($sql));
+         $library->description = $desc->value;
+         $libraries[] = $library;
+      }
+      db_set_active($previous_db);
+      if(count($libraries) > 0){
+         foreach ($libraries as $library){
+            $content .= "Library: $library->name. ";
+            $content .= "$library->description";
+         };
+      }
+      // Provide library names to show in a feature page
+   } else if ($node->type == 'chado_feature') {
+      $content = "";
+      $organism_id = $node->feature->organism_id;
+      $previous_db = db_set_active('chado');
+      $sql = "SELECT * FROM {library} L ".
+             "  INNER JOIN Library_feature LF ON L.library_id = LF.library_id ".
+       	  	 "WHERE LF.feature_id = " . $node->feature->feature_id;
+      $libraries = array();
+      $results = db_query($sql);
+      while($library = db_fetch_object($results)){
+         $libraries[] = $library;
+      }
+      db_set_active($previous_db);
+      if(count($libraries) > 0){
+         $lib_additions = array();
+         foreach ($libraries as $library){
+            $content .= "Library: ".$library->name;
+         };
+      }
+   }
+   return $content;
+
+
+}
+
+/************************************************************************
+ * This function is an extension of the chado_feature_view and
+ * chado_organism_view by providing the markup for the library object
+ * THAT WILL BE INDEXED.
+ */
+function theme_tripal_library_search_index ($node) {
+
+   if ($node->type == 'chado_organism') {
+      $content = "";
+      // get the libraries for the organism
+      $previous_db = db_set_active('chado');
+      $sql = "SELECT * FROM {library} L ".
+       	     "WHERE L.Organism_id = $node->organism_id";
+      $libraries = array();
+      $results = db_query($sql);
+      while($library = db_fetch_object($results)){
+         // get the description
+         $sql = "SELECT * FROM {libraryprop} LP ".
+           	    "  INNER JOIN CVTerm CVT ON CVT.cvterm_id = LP.type_id ".
+                "WHERE LP.library_id = $library->library_id ".
+                "  AND CVT.name = 'library_description'";
+         $desc = db_fetch_object(db_query($sql));
+         $library->description = $desc->value;
+         $libraries[] = $library;
+      }
+      db_set_active($previous_db);
+      if(count($libraries) > 0){
+         foreach ($libraries as $library){
+            $content .= "$library->name ";
+            $content .= "$library->description";
+         };
+      }
+      // Provide library names to show in a feature page
+   } else if ($node->type == 'chado_feature') {
+      $content = "";
+      $organism_id = $node->feature->organism_id;
+      $previous_db = db_set_active('chado');
+      $sql = "SELECT * FROM {library} L ".
+             "  INNER JOIN Library_feature LF ON L.library_id = LF.library_id ".
+       	  	 "WHERE LF.feature_id = " . $node->feature->feature_id;
+      $libraries = array();
+      $results = db_query($sql);
+      while($library = db_fetch_object($results)){
+         $libraries[] = $library;
+      }
+      db_set_active($previous_db);
+      if(count($libraries) > 0){
+         $lib_additions = array();
+         foreach ($libraries as $library){
+            $content .= $library->name;
+         };
+      }
+   }
+   return $content;
+}
+
+/*******************************************************************************
+ * This function shows library information on an organism/feature node
+ */
+function theme_tripal_library_node_libraries($node) {
+   $content = "";
+
+   // Show library information in a expandable box for a organism page.
+   // Make sure we have $node->organism_id. In the case of creating a new
+   // organism, the organism_id is not created until we save. This will cause
+   // an error when users preview the creation without a $node->organism_id
+   if ($node->type == 'chado_organism' && $node->organism_id) {
+      $box_status = variable_get("tripal_library-box-libraries","menu_off");
+      
+      if(strcmp($box_status,"menu_off")==0){
+         return get_tripal_library_organism_libraries($node->nid);
+      }
+   }
+   // Provide library names to show in a feature page.
+   // Make sure we have $node->feature->feature_id or there will be an error
+   // when a feature is previewed at its creation
+   else if ($node->type == 'chado_feature' && $node->feature->feature_id) {
+      $organism_id = $node->feature->organism_id;
+      $previous_db = db_set_active('chado');
+      $sql = "SELECT * FROM {library} L ".
+             " INNER JOIN Library_feature LF ON L.library_id = LF.library_id ".
+       	  	 "WHERE LF.feature_id = " . $node->feature->feature_id;
+      $libraries = array();
+      $results = db_query($sql);
+      while($library = db_fetch_object($results)){
+         $libraries[] = $library;
+      }
+      db_set_active($previous_db);
+      if(count($libraries) > 0){
+         $lib_additions = array();
+         foreach ($libraries as $library){
+            $sql = "SELECT nid FROM {chado_library} WHERE library_id = %d";
+            $lib_nid = db_result(db_query($sql, $library->library_id));
+            if ($lib_nid) {
+               $lib_url = url("node/$lib_nid");
+            }
+            $lib_additions[$lib_url] = $library->name;
+         };
+         $node->lib_additions = $lib_additions;
+      }
+   }
+   return $content;
+}
+/************************************************************************
+ *
+ */
+function get_tripal_library_organism_libraries($nid) {
+      $content = "";
+
+      // if this content is intended to be a menu item the 
+      // we need to know so we can format the content slightly different
+      $box_status =variable_get("tripal_library-box-libraries","menu_off");
+
+      // get the organism id for this node
+      $sql = "SELECT organism_id FROM {chado_organism} WHERE nid = %d";
+      $organism_id = db_result(db_query($sql, $nid));
+
+      // get the libraries for the organism
+      $previous_db = db_set_active('chado');
+      $sql = "SELECT L.library_id, L.organism_id, L.name, L.uniquename, ".
+             "   L.type_id, CVT.name as cvname, CVT.definition ".
+             "FROM {library} L ".
+             "  INNER JOIN CVTerm CVT ON CVT.cvterm_id = L.type_id ".
+       	  	 "WHERE L.Organism_id = $organism_id";
+      $libraries = array();
+      $results = db_query($sql);
+      while($library = db_fetch_object($results)){
+         // get the description
+         $sql = "SELECT * FROM {libraryprop} LP ".
+           	    "  INNER JOIN CVTerm CVT ON CVT.cvterm_id = LP.type_id ".
+                "WHERE LP.library_id = $library->library_id ".
+                "  AND CVT.name = 'library_description'";
+         $desc = db_fetch_object(db_query($sql));
+         $library->description = $desc->value;
+         $libraries[] = $library;
+      }
+      db_set_active($previous_db);
+      
+      if(strcmp($box_status,"menu_off")==0){
+         $content .= "<div id=\"tripal_library_box\" class=\"tripal_library-info-box\">";
+         $content .= "<br><div class=\"tripal_expandableBox\">".
+       			  	 	"<h3>Libraries associated with this organism</h3>".
+                 	 	"</div>";
+         $content .= "<div class=\"tripal_expandableBoxContent\">";
+      } else {
+   	  $content .= "<h3>Libraries associated with this organism</h3>";
+      }
+      $content .= "<table class=\"organism-libraries\">";
+      if (count($libraries) > 0) {
+         $content .= "  <tr>";
+         $content .= "    <th class=\"dbfieldname\">Name</th>";
+         $content .= "    <th class=\"dbfieldname\">Description</th>";
+         $content .= "    <th class=\"dbfieldname\">Type</th>";
+         $content .= "  </tr>";
+         foreach ($libraries as $library){
+            $content .= "<tr>";
+            $sql = "SELECT nid FROM {chado_library} WHERE library_id = %d";
+            $lib_nid = db_result(db_query($sql, $library->library_id));
+            $lib_url = url("node/$lib_nid");
+            if ($lib_nid) {
+               $content .= "  <td><a href=\"$lib_url\">$library->name</a></td>";
+            } else {
+               $content .= "  <td>$library->name</td>";
+            }
+            $content .= "  <td>$library->description</td>";
+            if ($library->cvname == 'cdna_library') {
+               $display_lib = 'cDNA';
+            } else if ($library->cvname == 'bac_library') {
+               $display_lib = 'BAC';
+            } else {
+               $display_lib = $library->cvname;
+            }
+            $content .= "  <td>$display_lib</td>";
+            $content .= "</tr>";
+         }
+      } else {
+       	$content .= '<tr><td>There are no libraries available for this organism</td></tr>';
+      }
+      $content .= "</table>";
+      if(user_access('access administrative pages')){
+         $link = url("tripal_toggle_box_menu/tripal_library/libraries/$nid");
+      	if(strcmp($box_status,"menu_off")==0){
+           $content .= "<br><a href=\"$link\">Show on menu</a>";
+         } else {
+           $content .= "<br><a href=\"$link\">Remove from menu</a>";
+        }
+      }
+      if(strcmp($box_status,"menu_off")==0){
+        $content .= "</div></div>";
+      }
+
+   return $content;
+}
+
+/************************************************************************
+ *
+ */
+function get_tripal_library_admin_form_menu_set(&$form){
+   $form['menu'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Set Menu')
+   );
+
+   
+   $types = array(
+      'tripal_organism' => t('Organism Page'),
+      'tripal_feature' => t('Feature Page'),
+   );
+
+   $defaults = variable_get('tripal_lib_menu_node_types','');
+
+   $form['menu']['tripal_lib_menu_node_types'] = array(
+      '#title' => 'Page Types',
+      '#type'  => 'checkboxes',
+      '#description' => t("Libraries can be associated with other data types ".
+         "such as organisms, features, analyses, etc.  The library module ".
+         "will add to the respective pages a box or menu item with a ".
+         "list of libraries associated with the data type.  This list ".
+         "will appear in a box on the page by default.  To place this ".
+         "list as a menu item rather than a box, check the appropriate boxes ".
+         "above"),
+      '#options' => $types,
+      '#default_value' => $defaults,
+      '#weight' => 1,
+   );
+}
+/************************************************************************
+ *
+ */
+function get_tripal_library_admin_form_cleanup_set(&$form) {
+   $form['cleanup'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Clean Up')
+   );
+   $form['cleanup']['description'] = array(
+       '#type' => 'item',
+       '#value' => t("With Drupal and chado residing in different databases ".
+          "it is possible that nodes in Drupal and libraries in Chado become ".
+          "\"orphaned\".  This can occur if an library node in Drupal is ".
+          "deleted but the corresponding chado library is not and/or vice ".
+          "versa. Click the button below to resolve these discrepancies."),
+       '#weight' => 1,
+   );
+   $form['cleanup']['button'] = array(
+      '#type' => 'submit',
+      '#value' => t('Clean up orphaned libraries'),
+      '#weight' => 2,
+   );
+}
+/************************************************************************
+ *
+ */
+function get_tripal_library_admin_form_taxonomy_set(&$form) {
+   $form['taxonify'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Assign Drupal Taxonomy to Library Features')
+   );
+
+   // get the list of libraries
+   $sql = "SELECT * FROM {Library} ORDER BY uniquename";
+   $previous_db = db_set_active('chado');  // use chado database
+   $lib_rset = db_query($sql);
+   db_set_active($previous_db);  // now use drupal database
+
+   // iterate through all of the libraries
+   $lib_boxes = array();
+   while($library = db_fetch_object($lib_rset)){
+      $lib_boxes[$library->library_id] = "$library->name";
+   }
+
+   $form['taxonify']['description'] = array(
+       '#type' => 'item',
+       '#value' => t("Drupal allows for assignment of \"taxonomy\" or catagorical terms to " .
+                     "nodes. These terms allow for advanced filtering during searching. This option allows ".
+                     "for setting taxonomy only for features that belong to the selected libraries below.  All other features will be unaffected.  To set taxonomy for all features in the site see the Feature Administration page."),
+		 '#weight' => 1,
+   );
+
+   $form['taxonify']['tx-libraries'] = array (
+     '#title'       => t('Libraries'),
+     '#type'        => t('checkboxes'),
+     '#description' => t("Check the libraries whose features you want to reset taxonomy.  Note: this list contains all libraries, even those that may not be synced."),
+     '#required'    => FALSE,
+     '#prefix'      => '<div id="lib_boxes">',
+     '#suffix'      => '</div>',
+     '#options'     => $lib_boxes,
+     '#weight'      => 2
+   );
+   $form['taxonify']['tx-button'] = array(
+      '#type' => 'submit',
+      '#value' => t('Set Feature Taxonomy'),
+      '#weight'      => 3
+   );
+}
+/************************************************************************
+ *
+ */
+function get_tripal_library_admin_form_reindex_set(&$form) {
+   // define the fieldsets
+   $form['reindex'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Reindex Library Features')
+   );
+
+   // get the list of libraries
+   $sql = "SELECT * FROM {Library} ORDER BY uniquename";
+   $previous_db = db_set_active('chado');  // use chado database
+   $lib_rset = db_query($sql);
+   db_set_active($previous_db);  // now use drupal database
+
+   // iterate through all of the libraries
+   $lib_boxes = array();
+   while($library = db_fetch_object($lib_rset)){
+      $lib_boxes[$library->library_id] = "$library->name";
+   }
+   $form['reindex']['description'] = array(
+       '#type' => 'item',
+       '#value' => t("This option allows for reindexing of only those features that belong to the selected libraries below. All other features will be unaffected.  To reindex all features in the site see the Feature Administration page."),
+		 '#weight' => 1,
+   );
+
+   $form['reindex']['re-libraries'] = array (
+     '#title'       => t('Libraries'),
+     '#type'        => t('checkboxes'),
+     '#description' => t("Check the libraries whoee features you want to reindex. Note: this list contains all libraries, even those that may not be synced."),
+     '#required'    => FALSE,
+     '#prefix'      => '<div id="lib_boxes">',
+     '#suffix'      => '</div>',
+     '#options'     => $lib_boxes,
+     '#weight' => 2,
+   );
+   $form['reindex']['re-button'] = array(
+      '#type' => 'submit',
+      '#value' => t('Reindex Features'),
+      '#weight' => 3,
+   );
+}
+/************************************************************************
+ *
+ */
+function get_tripal_library_admin_form_sync_set (&$form) {
+   // define the fieldsets
+   $form['sync'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Sync Libraries')
+   );
+
+
+   // get the list of libraries
+   $sql = "SELECT * FROM {Library} ORDER BY uniquename";
+   $previous_db = db_set_active('chado');  // use chado database
+   $lib_rset = db_query($sql);
+   db_set_active($previous_db);  // now use drupal database
+
+   // if we've added any libraries to the list that can be synced
+   // then we want to build the form components to allow the user
+   // to select one or all of them.  Otherwise, just present
+   // a message stating that all libraries are currently synced.
+   $lib_boxes = array();
+   $added = 0;
+   while($library = db_fetch_object($lib_rset)){
+      // check to see if the library is already present as a node in drupal.
+      // if so, then skip it.
+      $sql = "SELECT * FROM {chado_library} WHERE library_id = %d";
+      if(!db_fetch_object(db_query($sql,$library->library_id))){
+         $lib_boxes[$library->library_id] = "$library->name";
+         $added++;
+      }
+   }
+
+   // if we have libraries we need to add to the checkbox then
+   // build that form element
+   if($added > 0){
+      $lib_boxes['all'] = "All Libraries";
+
+      $form['reindex']['description'] = array(
+       '#type' => 'item',
+       '#value' => t("This option allows for the creation of Drupal content for libraries in chado. Only the selected libraries will be synced."),
+		 '#weight' => 1,
+      );
+
+
+      $form['sync']['libraries'] = array (
+        '#title'       => t('Available Libraries'),
+        '#type'        => t('checkboxes'),
+        '#description' => t("Check the libraries you want to sync.  Drupal content will be created for each of the libraries listed above.  Select 'All Libraries' to sync all of them."),
+        '#required'    => FALSE,
+        '#prefix'      => '<div id="lib_boxes">',
+        '#suffix'      => '</div>',
+        '#options'     => $lib_boxes,
+		  '#weight' => 2,
+      );
+      $form['sync']['button'] = array(
+         '#type' => 'submit',
+         '#value' => t('Sync Libraries'),
+		   '#weight' => 3,
+      );
+   }
+   // we don't have any libraries to select from
+   else {
+      $form['sync']['value'] = array(
+         '#value' => t('All libraries in Chado are currently synced with Drupal.')
+      );
+   }
+}
+/************************************************************************
+ *
+ */
+function tripal_library_admin_validate($form, &$form_state) {
+   global $user;  // we need access to the user info
+   $job_args = array();
+
+   // Submit the Sync Job if selected
+   if ($form_state['values']['op'] == t('Sync Libraries')) {
+
+      // check to see if the user wants to sync chado and drupal.  If
+      // so then we need to register a job to do so with tripal
+      $libraries = $form_state['values']['libraries'];
+      $do_all = FALSE;
+      $to_sync = array();
+
+      foreach ($libraries as $library_id){
+         if(preg_match("/^all$/i",$library_id)){
+            $do_all = TRUE;
+         }
+         if($library_id and preg_match("/^\d+$/i",$library_id)){
+            // get the library info
+            $sql = "SELECT * FROM {Library} WHERE library_id = %d";
+            $previous_db = db_set_active('chado');  // use chado database
+            $library = db_fetch_object(db_query($sql,$library_id));
+            db_set_active($previous_db);  // now use drupal database
+            $to_sync[$library_id] = $library->name;
+         }
+      }
+
+      // submit the job to the tripal job manager
+      if($do_all){
+         tripal_add_job('Sync all libraries','tripal_library','tripal_library_sync_libraries',$job_args,$user->uid);
+      }
+      else{
+         foreach($to_sync as $library_id => $name){
+            $job_args[0] = $library_id;
+            tripal_add_job("Sync library: $name",'tripal_library','tripal_library_sync_libraries',$job_args,$user->uid);
+         }
+      }
+   }
+
+   // -------------------------------------
+   // Submit the Reindex Job if selected
+   if ($form_state['values']['op'] == t('Reindex Features')) {
+      $libraries = $form_state['values']['re-libraries'];
+      foreach ($libraries as $library_id){
+         if($library_id and preg_match("/^\d+$/i",$library_id)){
+            // get the library info
+            $sql = "SELECT * FROM {Library} WHERE library_id = %d";
+            $previous_db = db_set_active('chado');  // use chado database
+            $library = db_fetch_object(db_query($sql,$library_id));
+            db_set_active($previous_db);  // now use drupal database
+            $job_args[0] = $library_id;
+            tripal_add_job("Reindex features for library: $library->name",'tripal_library',
+             'tripal_library_reindex_features',$job_args,$user->uid);
+         }
+      }
+   }
+
+   // -------------------------------------
+   // Submit the Taxonomy Job if selected
+   if ($form_state['values']['op'] == t('Set Feature Taxonomy')) {
+      $libraries = $form_state['values']['tx-libraries'];
+      foreach ($libraries as $library_id){
+         if($library_id and preg_match("/^\d+$/i",$library_id)){
+            // get the library info
+            $sql = "SELECT * FROM {Library} WHERE library_id = %d";
+            $previous_db = db_set_active('chado');  // use chado database
+            $library = db_fetch_object(db_query($sql,$library_id));
+            db_set_active($previous_db);  // now use drupal database
+            $job_args[0] = $library_id;
+            tripal_add_job("Set taxonomy for features in library: $library->name",'tripal_library',
+             'tripal_library_taxonify_features',$job_args,$user->uid);
+         }
+      }
+   }
+   // -------------------------------------
+   // Submit the Cleanup Job if selected
+   if ($form_state['values']['op'] == t('Clean up orphaned libraries')) {
+      tripal_add_job('Cleanup orphaned libraries','tripal_library',
+         'tripal_library_cleanup',$job_args,$user->uid);
+   }
+}
+/*******************************************************************************
+ *
+ */
+function tripal_library_show_libraries (){
+   // Show libraries stored in Drupal's {chado_library} table
+   $sql = "SELECT COUNT(library_id) FROM {chado_library}";
+   $no_libs = db_result(db_query ($sql));
+   if($no_libs != 0) {
+      $libraries = get_chado_libraries ();
+      if($no_libs != count($libraries)) {
+         drupal_set_message("Synchronization needed.");
+      }
+      return theme('tripal_library_library_table', $libraries);
+   } else {
+      return t("No library exists. Please contact administrators to ".
+               "synchronize libraries.");
+   }
+}
+
+/*******************************************************************************
+ *
+ */
+function tripal_library_cron (){
+
+}
+/*******************************************************************************
+ *
+ *                  CHADO_LIBRARY NODE FUNCTIONS
+ *
+ *  The following function proves access control for users trying to
+ *  perform actions on data managed by this module
+ */
+function tripal_library_library_access($op, $node, $account){
+   if ($op == 'create') {
+      return user_access('create chado_library content', $account);
+   }
+
+   if ($op == 'update') {
+      if (user_access('edit any chado_library content', $account) ||
+      (user_access('edit own chado_library content', $account) &&
+      ($account->uid == $node->uid))){
+         return TRUE;
+      }
+   }
+
+   if ($op == 'delete') {
+      if (user_access('delete any chado_library content', $account) ||
+      (user_access('delete own chado_library content', $account) &&
+      ($account->uid == $node->uid))) {
+         return TRUE;
+      }
+   }
+}
+/*******************************************************************************
+ *  validates submission of form when adding or updating a library node
+ */
+function chado_library_validate($node){
+   $lib = 0;
+   // check to make sure the unique name on the library is unique
+   // before we try to insert into chado.
+   if($node->library_id){
+      $sql = "SELECT * FROM ".
+             "{Library} WHERE ".
+             "uniquename = '%s' ".
+             "AND NOT library_id = %d";
+      $previous_db = db_set_active('chado');
+      $lib = db_fetch_object(db_query($sql, $node->uniquename,
+      $node->library_id));
+      db_set_active($previous_db);
+   } else {
+      $sql = "SELECT * FROM ".
+             "{Library} ".
+             "WHERE uniquename = '%s'";
+      $previous_db = db_set_active('chado');
+      $lib = db_fetch_object(db_query($sql, $node->uniquename));
+      db_set_active($previous_db);
+   }
+   if($lib){
+      form_set_error('uniquename',t('The unique library name already exists. '.
+                                    'Please choose another'));
+   }
+}
+
+/*******************************************************************************
+ *  When a new chado_library node is created we also need to add information
+ *  to our chado_library table.  This function is called on insert of a new node
+ *  of type 'chado_library' and inserts the necessary information.
+ */
+function chado_library_insert($node){
+   // If this library already exists then don't create it in chado
+   // e.g. when tripal_library_sync_libraries call this function
+   $l_sql= "SELECT library_id ".
+           "FROM {Library} ".
+           "WHERE organism_id = %d ".
+           "AND uniquename = '%s' ".
+           "AND type_id = %d";
+   $previous_db = db_set_active('chado');
+   $library = db_fetch_object(db_query($l_sql, $node->organism_id,
+   $node->uniquename, $node->type_id));
+   $libid = $node->library_id;
+   
+   // Create the chado library entry only if it doesn't exist
+   if (!$library) {
+      $sql = "INSERT INTO {library} (organism_id, name, uniquename, type_id)".
+             "VALUES(%d,'%s','%s', ".
+             "  (SELECT cvterm_id ".
+             "   FROM {CVTerm} CVT ".
+             "   INNER JOIN CV ON CVT.cv_id = CV.cv_id ".
+             "   WHERE CV.name = 'tripal' and CVT.name = '%s'))";
+      db_query($sql,$node->organism_id,$node->title,$node->uniquename,
+      $node->library_type);
+
+      // get the library id for this library
+      $sql = "SELECT library_id ".
+             "FROM {library} ".
+             "WHERE uniquename = '%s'";
+      $lib = db_fetch_object(db_query($sql, $node->uniquename));
+      $libid = $lib->library_id;
+   }
+
+   // Now use drupal database
+   db_set_active($previous_db);
+
+   // Next add the node to the drupal table
+   $sql = "INSERT INTO {chado_library} (nid, vid, library_id) ".
+          "VALUES (%d, %d, %d)";
+   db_query($sql, $node->nid, $node->vid, $libid);
+
+   // Finally add the remaining properties if the library doesn't exist in Chado
+   if (!$library) {
+      tripal_library_add_properties($node,$libid);
+   }
+}
+/*******************************************************************************
+ * Update nodes
+ */
+function chado_library_update($node){
+   if($node->revision){
+      // TODO -- decide what to do about revisions
+   } else {
+      // Get the library_id for this node:
+      $sql = "SELECT library_id ".
+             "FROM {chado_library} ".
+             "WHERE vid = %d";
+      $lib = db_fetch_object(db_query($sql, $node->vid));
+
+      // Update the chado library table
+      $sql = "UPDATE {library} ".
+             "  SET name = '%s', uniquename = '%s', organism_id = %d, ".
+             "    type_id = (SELECT cvterm_id ".
+             "               FROM {CVTerm} CVT ".
+             "               INNER JOIN CV ON CVT.cv_id = CV.cv_id ".
+             "               WHERE CV.name = 'local' and CVT.name = '%s') ".
+             "WHERE library_id = %d ";
+      $previous_db = db_set_active('chado');  // use chado database
+      db_query($sql, $node->title, $node->uniquename, $node->organism_id,
+      $node->library_type, $lib->library_id);
+      db_set_active($previous_db);  // now use drupal database
+      tripal_library_add_properties($node,$lib->library_id);
+      tripal_library_add_taxonomy($node,$lib->library_id);
+   }
+}
+
+/*******************************************************************************
+ * Add properties to the specified library.
+ */
+function tripal_library_add_properties ($node,$library_id){
+   // Use chado database
+   $previous_db = db_set_active('chado');
+
+   // Now remove any properties for this library and add the new properties
+   // provided by the this posting.
+   $sql = "DELETE FROM {libraryprop} ".
+          "WHERE library_id = %d";
+   db_query($sql,$library_id);
+
+   // Now add each property one at a time
+   $sql = "INSERT INTO {libraryprop} (library_id, type_id, value) ".
+          "VALUES (%d,".
+          "        (SELECT cvterm_id ".
+          "         FROM {CVTerm} CVT ".
+          "           INNER JOIN CV ON CVT.cv_id = CV.cv_id ".
+          "         WHERE CV.name = 'tripal' and CVT.name = '%s'), ".
+          "        '%s')";
+
+   if($node->library_description){
+      db_query($sql,$library_id,'library_description',
+      $node->library_description);
+   }
+
+   // now use drupal database
+   db_set_active($previous_db);
+}
+/*******************************************************************************
+ * Add the library as a taxonomy term for associating with library_features
+ */
+function tripal_library_add_taxonomy ($node,$library_id){
+
+   //include the file containing the required functions.  We only have to
+   // do this because Drupal 6 fails to do this globally for us and
+   // the drupal_execute function below won't work
+   module_load_include('inc', 'taxonomy', 'taxonomy.admin');
+
+   /*   // get the vocabulary id
+    $vocabularies = taxonomy_get_vocabularies();
+    $vid = NULL;
+    foreach($vocabularies as $vocab){
+    if($vocab->name == 'DNA Libraries'){
+    $vid = $vocab->vid;
+    }
+    }
+
+    if(!$vid){  */
+   // add the vocabulary
+   $vocab_form['values']['name'] = 'DNA Libraries';
+   $vocab_form['values']['description'] = 'Allows for associating/searching of library features by library name';
+   $vocab_form['values']['help'] = '';
+   $vocab_form['values']['module'] = 'taxonomy';
+   drupal_execute('taxonomy_form_vocabulary',$vocab_form);
+   return;
+   //   }
+
+   // make sure this term doesn't already exist.  If it doesn't then add it
+   if($vid){
+      $tree = taxonomy_get_tree($vid);
+      $found = 0;
+      foreach ($tree as $term) {
+         if($term->name == $node->title){
+            $found = 1;
+         }
+      }
+
+      // add the term to the vocabulary
+      if(!$found){
+         $form_state = array();
+         $form_state['values']['name'] = $node->title;
+         $form_state['values']['description'] = $library_id;
+         drupal_execute('taxonomy_form_term',$form_state,$vid);
+      }
+   }
+}
+
+/*******************************************************************************
+ *  When editing or creating a new node of type 'chado_library' we need
+ *  a form.  This function creates the form that will be used for this.
+ */
+function chado_library_form ($node){
+   $type = node_get_types('type',$node);
+   $form = array();
+
+   // keep track of the library id if we have.  If we do have one then
+   // this is an update as opposed to an insert.
+   $form['library_id'] = array(
+      '#type' => 'value',
+      '#value' => $node->library_id,
+   );
+
+   $form['title']= array(
+      '#type'          => 'textfield',
+      '#title'         => t('Library Title'),
+      '#description'   => t('Please enter the title for this library. '.
+                            'This appears at the top of the library page.'),
+      '#required'      => TRUE,
+      '#default_value' => $node->title,
+      '#weight'        => 1
+   );
+
+   $form['uniquename']= array(
+      '#type'          => 'textfield',
+      '#title'         => t('Unique Library Name'),
+      '#description'   => t('Please enter a unique name for this library'),
+      '#required'      => TRUE,
+      '#default_value' => $node->uniquename,
+      '#weight'        => 2
+   );
+
+   // These library types should not be hard coded, but for now the are...
+   $library_types = array();
+   $library_types[''] = '';
+   $library_types['cdna_library'] = 'cDNA Library';
+   $library_types['bac_library'] = 'BAC Library';
+   $library_types['fosmid_library'] = 'FOSMID Library';
+   $library_types['cosmid_library'] = 'COSMID Library';
+   $library_types['yac_library'] = 'YAC Library';
+     
+   
+   $form['library_type'] = array (
+      '#title'       => t('Library Type'),
+      '#type'        => t('select'),
+      '#description' => t("Choose the library type."),
+      '#required'    => TRUE,
+      '#default_value' => $node->library_type,
+      '#options'     => $library_types,
+      '#weight'      => 3
+   );
+
+   // get the list of organisms
+   $sql = "SELECT * FROM {Organism}";
+   $previous_db = db_set_active('chado');  // use chado database
+   $org_rset = db_query($sql);
+   db_set_active($previous_db);  // now use drupal database
+
+   $organisms = array();
+   $organisms[''] = '';
+   while($organism = db_fetch_object($org_rset)){
+      $organisms[$organism->organism_id] =
+      "$organism->genus $organism->species ($organism->common_name)";
+   }
+
+   $form['organism_id'] = array (
+     '#title'       => t('Organism'),
+     '#type'        => t('select'),
+     '#description' => t("Choose the organism with which this library is ".
+                         "associated."),
+     '#required'    => TRUE,
+     '#default_value' => $node->organism_id,
+     '#options'     => $organisms,
+     '#weight'      => 4,
+   );
+
+   $form['library_description']= array(
+      '#type'          => 'textarea',
+      '#title'         => t('Library Description'),
+      '#description'   => t('A brief description of the library'),
+      '#required'      => TRUE,
+      '#default_value' => $node->library_description,
+      '#weight'        => 5
+   );
+
+   //Save the number of EST so it will show up in preview
+   $form['sequence_num'] = array(
+      '#type' => 'value',
+      '#value' => $node->sequence_num,
+   );
+   return $form;
+}
+/************************************************************************
+ *
+ */
+function tripal_library_sync_libraries ($library_id = NULL, $job_id = NULL){
+
+   global $user;
+   $page_content = '';
+
+   // get the list of libraries and create new nodes
+   if(!$library_id){
+      $sql = "SELECT * FROM {Library} L";
+      $previous_db = db_set_active('chado');  // use chado database
+      $results = db_query($sql);
+      db_set_active($previous_db);  // now use drupal database
+   } else {
+      $sql = "SELECT * FROM {Library} L WHERE library_id = %d";
+      $previous_db = db_set_active('chado');  // use chado database
+      $results = db_query($sql,$library_id);
+      db_set_active($previous_db);  // now use drupal database
+   }
+
+   // We'll use the following SQL statement for checking if the library
+   // already exists as a drupal node.
+   $sql = "SELECT * FROM {chado_library} ".
+          "WHERE library_id = %d";
+
+   while($library = db_fetch_object($results)){
+      // check if this library already exists in the drupal database. if it
+      // does then skip this library and go to the next one.
+      if(!db_fetch_object(db_query($sql,$library->library_id))){
+
+         $new_node = new stdClass();
+         $new_node->type = 'chado_library';
+         $new_node->uid = $user->uid;
+         $new_node->title = "$library->name";
+         $new_node->library_id = $library->library_id;
+         $new_node->organism_id = $library->organism_id;
+         $new_node->uniquename = $library->uniquename;
+         $new_node->type_id = $library->type_id;
+
+         node_validate($new_node);
+         if(!form_get_errors()){
+            $node = node_submit($new_node);
+            node_save($node);
+            if($node->nid){
+               $page_content .= "Added $library->name<br>";
+            }
+         }
+      } else {
+         $page_content .= "Skipped $library->name<br>";
+      }
+   }
+   return $page_content;
+}
+
+/************************************************************************
+ *  When a node is requested by the user this function is called to allow us
+ *  to add auxiliary data to the node object.
+ */
+function chado_library_load($node){
+   $sql = 'SELECT library_id FROM {chado_library} WHERE vid = %d';
+   $map = db_fetch_object(db_query($sql, $node->vid));
+   $additions->library_id = $map->library_id;
+   $previous_db = db_set_active('chado');  // use chado database
+
+   // get information about this library
+   $sql = "SELECT L.organism_id, L.uniquename, CVT.name as type_name ".
+          "FROM {Library} L ".
+          "INNER JOIN CVTerm CVT ON CVT.cvterm_id = L.type_id ".
+          "WHERE library_id = %d";
+   $library = db_fetch_object(db_query($sql, $map->library_id));
+   $additions->uniquename = $library->uniquename;
+   $additions->library_type = $library->type_name;
+   $additions->organism_id = $library->organism_id;
+
+   $sql = "SELECT genus, species, common_name ".
+          "FROM {organism} O ".
+          "INNER JOIN library L ".
+          "ON L.organism_id = O.organism_id ".
+          "WHERE L.library_id = %d";
+   $organism = db_fetch_object(db_query($sql,$map->library_id));
+   $additions->genus = $organism->genus;
+   $additions->species = $organism->species;
+   $additions->common_name = $organism->common_name;
+
+   $sql = "SELECT LP.value ".
+          "FROM {libraryProp} LP ".
+          "WHERE LP.library_id = %d ";
+   $desc = db_fetch_object(db_query($sql, $map->library_id))->value;
+   if ($desc) {
+      $additions->library_description = $desc;
+   } else {
+      $additions->library_description = "NA";
+   }
+
+   // get the feature counts.  This is dependent on a materialized view
+   // installed with the library module
+   if ($map->library_id) {
+      $sql = "SELECT num_features FROM {library_feature_count} ".
+      		 "WHERE Library_id = $map->library_id";
+      $additions->num_features = db_fetch_object(db_query($sql, $map->library_id))->num_features;
+   }
+
+   db_set_active($previous_db);  // now use drupal database
+   return $additions;
+
+}
+/*******************************************************************************
+ *  This function customizes the view of the chado_library node.  It allows
+ *  us to generate the markup. This function is required for node [Preview]
+ */
+function chado_library_view ($node, $teaser = FALSE, $page = FALSE) {
+   // use drupal's default node view:
+   if (!$teaser) {
+
+      $node = node_prepare($node, $teaser);
+
+      // If Hook_view() is called by Hook_form(), we'll only have orgnism_id
+      // but not genus/species/common_name. We need to get those from chado
+      // database so they will show up in preview
+      if(!$node->genus) {
+         $previous_db = db_set_active('chado');
+         $sql = "SELECT * FROM {organism} WHERE organism_id = %d";
+         $data = db_fetch_object(db_query($sql, $node->organism_id));
+         $node->genus = $data->genus;
+         $node->species = $data->species;
+         $node->common_name = $data->common_name;
+         db_set_active($previous_db);
+      }
+   }
+   return $node;
+}
+
+/************************************************************************
+ **  This function creates the html markup for the library table.
+ **  It can be overridden in the theme for the site by adding a php
+ **  method in the template.php file named
+ **  <theme_name>_tripal_library_library_table(&$libraries)
+ */
+
+function theme_tripal_library_library_table (&$libraries) {
+
+   // cycle through the libraries and build the libraries page
+   $output = "<div id=\"libraries\">";
+   $output .= '<table>';
+   $output .= "<tr>";
+   $output .= "<th>Name</th>";
+   $output .= "<th>Type</th>";
+   $output .= "<th>Organism</th>";
+   $output .= "<th>Description</th>";
+   $output .= "</tr>";
+
+   foreach($libraries as $library){
+      $lib_url = url("node/$library->node_id");
+      $output .= "<tr>";
+      $output .= "<td>".
+                 "  <a href=\"$lib_url\">$library->name</a>".
+                 "</td>";
+
+      if(strcasecmp($library->type_name, 'bac_library') == 0){
+         $output .= "<td>BAC</td>";
+      }
+      elseif(strcasecmp($library->type_name, 'cdna_library') == 0){
+         $output .= "<td>cDNA</td>";
+      }
+      else{
+         $output .= "<td>$library->type_name</td>";
+      }
+      $output .= "<td nowrap>".
+                 " $library->common_name".
+                 "</td>";
+      $description = $library->library_description;
+      $output .= "<td>$description</td>";
+
+      $output .= "</tr>";
+   }
+   $output .= "</table>";
+   $output .= "</div>";
+
+   return $output;
+}
+
+/************************************************************************
+ *
+ */
+function tripal_library_feature_set_taxonomy($library_id = NULL){
+
+   //TO DO : return usable error if vocabs don't exist
+   // get the list of vocabularies and find our two vocabularies of interest
+   $vocabularies = taxonomy_get_vocabularies();
+   $vid = NULL;
+   foreach($vocabularies as $vocab){
+      if($vocab->name == 'Library'){
+         $vid = $vocab->vid;
+      }
+   }
+   if(!$vid){
+      return;
+   }
+
+   // We'll use the following SQL statement for getting the node info
+   if($library_id){
+      print "Finding features for library with ID: $library_id\n";
+      $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
+             "FROM {library_feature} LF ".
+             "INNER JOIN Library L ON LF.library_id = L.library_id ".
+             "WHERE L.library_id = $library_id ".
+             "ORDER BY LF.feature_id";
+      $previous_db = db_set_active('chado');  // use chado database
+      $features = db_query($sql);
+      db_set_active($previous_db);  // now use drupal database
+   } else {
+      print "Finding features for all libraries\n";
+      $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
+             "FROM {library_feature} LF ".
+             "INNER JOIN Library L ON LF.library_id = L.library_id ".
+             "ORDER BY LF.feature_id";
+      $previous_db = db_set_active('chado');  // use chado database
+      $features = db_query($sql);
+      db_set_active($previous_db);  // now use drupal database
+   }
+
+   $node_sql = "SELECT * FROM {chado_feature} CF ".
+               "  INNER JOIN {node} N ON CF.nid = N.nid ".
+               "WHERE feature_id = %d";
+
+   // iterate through the features and add the taxonomy
+   while($feature = db_fetch_object($features)){
+      $node = db_fetch_object(db_query($node_sql,$feature->feature_id));
+      $tags["$vid"] = $feature->libname;
+      $terms['tags'] = $tags;
+      taxonomy_node_save($node,$terms);
+      print "Updated $feature->feature_id as $feature->libname\n";
+   }
+}
+/*******************************************************************************
+ *
+ */
+function tripal_library_reindex_features ($library_id = NULL, $job_id = NULL){
+   $i = 0;
+
+   // if the caller provided a library_id then get all of the features
+   // associated with the library. Otherwise get all sequences assoicated
+   // with all libraries.
+   if($library_id){
+      $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
+             " FROM {library_feature} LF ".
+             "  INNER JOIN Library L ON LF.library_id = L.library_id ".
+             "WHERE L.library_id = $library_id ".
+             "ORDER BY LF.feature_id";
+      $previous_db = db_set_active('chado');  // use chado database
+      $results = db_query($sql);
+      db_set_active($previous_db);  // now use drupal database
+   }
+   else {
+      $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
+             " FROM {library_feature} LF ".
+             "  INNER JOIN Library L ON LF.library_id = L.library_id ".
+             "ORDER BY LF.feature_id";
+      $previous_db = db_set_active('chado');  // use chado database
+      $results = db_query($sql);
+      db_set_active($previous_db);  // now use drupal database
+   }
+
+   // load into ids array
+   $count = 0;
+   $ids = array();
+   while($id = db_fetch_object($results)){
+      $ids[$count] = $id->feature_id;
+      $count++;
+   }
+
+   $interval = intval($count * 0.01);
+   foreach($ids as $feature_id){
+      // update the job status every 1% features
+      if($job_id and $i % interval == 0){
+         tripal_job_set_progress($job_id,intval(($i/$count)*100));
+      }
+      tripal_feature_sync_feature ($feature_id);
+      $i++;
+   }
+}
+/*******************************************************************************
+ *
+ */
+function tripal_library_taxonify_features ($library_id = NULL, $job_id = NULL){
+   $i = 0;
+
+   // if the caller provided a library_id then get all of the features
+   // associated with the library. Otherwise get all sequences assoicated
+   // with all libraries.
+   if($library_id){
+      $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
+             " FROM {library_feature} LF ".
+             "  INNER JOIN Library L ON LF.library_id = L.library_id ".
+             "WHERE L.library_id = $library_id ".
+             "ORDER BY LF.feature_id";
+      $previous_db = db_set_active('chado');  // use chado database
+      $results = db_query($sql);
+      db_set_active($previous_db);  // now use drupal database
+   }
+   else {
+      $sql = "SELECT LF.feature_id, L.library_id, L.name as libname ".
+             " FROM {library_feature} LF ".
+             "  INNER JOIN Library L ON LF.library_id = L.library_id ".
+             "ORDER BY LF.feature_id";
+      $previous_db = db_set_active('chado');  // use chado database
+      $results = db_query($sql);
+      db_set_active($previous_db);  // now use drupal database
+   }
+
+   // load into ids array
+   $count = 0;
+   $ids = array();
+   while($id = db_fetch_object($results)){
+      $ids[$count] = $id->feature_id;
+      $count++;
+   }
+
+   // make sure our vocabularies are set before proceeding
+   tripal_feature_set_vocabulary();
+
+   // use this SQL for getting the nodes
+   $nsql =  "SELECT * FROM {chado_feature} CF ".
+            "  INNER JOIN {node} N ON N.nid = CF.nid ".
+            "WHERE feature_id = %d";
+
+   // iterate through the features and set the taxonomy
+   $interval = intval($count * 0.01);
+   foreach($ids as $feature_id){
+      // update the job status every 1% features
+      if($job_id and $i % interval == 0){
+         tripal_job_set_progress($job_id,intval(($i/$count)*100));
+      }
+      $node = db_fetch_object(db_query($nsql,$feature_id));
+      tripal_feature_set_taxonomy($node,$feature_id);
+      $i++;
+   }
+}
+/*******************************************************************************
+ * Delete data from drupal and chado databases when a node is deleted
+ */
+function chado_library_delete(&$node){
+   // Before removing, get library_id so we can remove it from chado database
+   // later
+   $sql_drupal = "SELECT library_id ".
+                 "FROM {chado_library} ".
+                 "WHERE nid = %d AND vid = %d";
+   $library_id = db_result(db_query($sql_drupal, $node->nid, $node->vid));
+
+   // Remove data from {chado_library}, {node} and {node_revisions} tables of
+   // drupal database
+   $sql_del = "DELETE FROM {chado_library} ".
+              "WHERE nid = %d ".
+              "AND vid = %d";
+   db_query($sql_del, $node->nid, $node->vid);
+   $sql_del = "DELETE FROM {node} ".
+              "WHERE nid = %d ".
+              "AND vid = %d";
+   db_query($sql_del, $node->nid, $node->vid);
+   $sql_del = "DELETE FROM {node_revisions} ".
+              "WHERE nid = %d ".
+              "AND vid = %d";
+   db_query($sql_del, $node->nid, $node->vid);
+
+   // Remove data from library and libraryprop tables of chado database as well
+   $previous_db = db_set_active('chado');
+   db_query("DELETE FROM {library} WHERE library_id = %d", $library_id);
+   db_query("DELETE FROM {libraryprop} WHERE library_id = %d", $library_id);
+   db_set_active($previous_db);
+}
+
+/************************************************************************
+ * Display block with libraries
+ * @param op    - parameter to define the phase being called for the block
+ * @param delta - id of the block to return (ignored when op is list)
+ * @param edit  - when op is save, contains the submitted form data
+ */
+function tripal_library_block($op = 'list', $delta = '0', $edit = array()){
+   switch($op){
+      case 'list':
+         $blocks[0]['info'] = t('Libraries');
+         return $blocks;
+
+      case 'view':
+         if(user_access('access chado_library content')){
+            // Show libraries stored in Drupal's {chado_library} table
+            $sql = "SELECT COUNT(library_id) FROM {chado_library}";
+            $no_libs = db_result(db_query ($sql));
+            if($no_libs != 0) {
+               $libraries = get_chado_libraries();
+               foreach($libraries as $library){
+                  // get the node id for this organism
+                  $items[] = l($library->name, 'node/' . $library->node_id);
+               }
+            } else {
+               $items[] = t("No library exists.");
+            }
+            $block['subject'] = t('Libraries');
+            //We theme our array of links as an unordered list
+            $block['content'] = theme('item_list', $items);
+         }
+         return $block;
+   }
+}
+
+/*******************************************************************************
+ * This function uses library_id's of all drupal library nodes as input and
+ * pull the library information (name, uniquename, type, genus, species,
+ * common_name, description) from chado database. The return type is an object
+ * array that stores sorted $library objects
+ */
+function get_chado_libraries() {
+   $sql_drupal = "SELECT COUNT (library_id) FROM {chado_library}";
+   $no_libs = db_result(db_query($sql_drupal));
+   if ($no_libs != 0) {
+      // Get library_id's from drupal
+      $sql = "SELECT library_id, nid FROM {chado_library}";
+      $result = db_query($sql);
+      $previous_db = db_set_active('chado');
+      // Get library info from chado's library, organism, and cvterm tables
+      $sql_info = "SELECT L.name, uniquename, genus, species, common_name, ".
+                  "  CVT.name as type_name ".
+                  "FROM {Library} L ".
+                  "INNER JOIN Organism O ON L.organism_id = O.organism_id ".
+                  "INNER JOIN CVTerm CVT ON L.type_id = CVT.cvterm_id ".
+                  "WHERE library_id=%d";
+      // Get library description from libraryprop if there is any
+      $sql_desc = "SELECT value ".
+                  "FROM {Libraryprop} LP ".
+                  "INNER JOIN CVTerm CVT ON LP.type_id = CVT.cvterm_id ".
+                  "WHERE library_id = %d AND CVT.name = 'library_description'";
+      $libraries = array();
+      while ($data = db_fetch_object($result)) {
+         $library = db_fetch_object(db_query($sql_info, $data->library_id));
+         $library->node_id = $data->nid;
+         $desc = db_fetch_object(db_query($sql_desc, $data->library_id))->value;
+         if ($desc) {
+            $library->library_description = $desc;
+         } else {
+            $library->library_description = "NA";
+         }
+         // Use uniquename as the key so we can sort by uniquename later
+         $key = strtolower($library->uniquename);
+         $libraries [$key] = $library;
+      }
+      db_set_active($previous_db);
+
+      //Sort libraries by uniquename
+      ksort($libraries, SORT_STRING);
+      return $libraries;
+   }
+}
+/************************************************************************
+ *
+ */
+function tripal_library_cleanup($dummy = NULL, $job_id = NULL) {
+
+   // build the SQL statments needed to check if nodes point to valid analyses
+   $dsql = "SELECT * FROM {node} WHERE type = 'chado_library' order by nid";
+   $nsql = "SELECT * FROM {node} WHERE nid = %d";
+   $csql = "SELECT * FROM {chado_library} where nid = %d ";
+   $cosql= "SELECT * FROM {chado_library}";
+   $tsql = "SELECT * FROM {library} L WHERE library_id = %d";
+
+   // load into nodes array
+   $results = db_query($dsql);
+   $count = 0;
+   $nodes = array();
+   while($node = db_fetch_object($results)){
+      $nodes[$count] = $node;
+      $count++;
+   }
+
+   // load the chado_analyses into an array
+   $results = db_query($cosql);
+   $cnodes = array();
+   while($node = db_fetch_object($results)){
+      $cnodes[$count] = $node;
+      $count++;
+   }
+   $interval = intval($count * 0.01);
+
+   // iterate through all of the chado_library nodes and delete those that aren't valid
+   foreach($nodes as $nid){
+
+      // update the job status every 1% analyses
+      if($job_id and $i % $interval == 0){
+         tripal_job_set_progress($job_id,intval(($i/$count)*100));
+      }
+
+      // first check to see if the node has a corresponding entry
+      // in the chado_library table. If not then delete the node.
+      $library = db_fetch_object(db_query($csql,$nid->nid));
+      if(!$library){
+         node_delete($nid->nid);
+         $message = "Missing in chado_library table.... DELETING: $nid->nid\n";
+         watchdog('tripal_library',$message,array(),WATCHDOG_WARNING);
+         continue;
+      }
+      $i++;
+   }
+
+   // iterate through all of the chado_library nodes and delete those  that aren't valid
+   foreach($cnodes as $nid){
+      // update the job status every 1% analyses
+      if($job_id and $i % $interval == 0){
+         tripal_job_set_progress($job_id,intval(($i/$count)*100));
+      }
+      $node = db_fetch_object(db_query($nsql,$nid->nid));
+      if(!$node){
+         db_query("DELETE FROM {chado_library} WHERE nid = $nid->nid");        
+         $message = "chado_library missing node.... DELETING: $nid->nid\n";
+         watchdog('tripal_library',$message,array(),WATCHDOG_WARNING);
+      }
+
+      $i++;
+   }
+   return '';
+}