Browse Source

Merge 6.x-0.4-dev brnach (and coding standards update) into this branch

laceysanderson 12 years ago
parent
commit
738d671b4a
68 changed files with 12146 additions and 4705 deletions
  1. 290 284
      tripal_analysis/tripal_analysis.admin.inc
  2. 23 18
      tripal_analysis/tripal_analysis.api.inc
  3. 58 55
      tripal_analysis/tripal_analysis.install
  4. 343 332
      tripal_analysis/tripal_analysis.module
  5. 2 2
      tripal_analysis/tripal_analysis.views.inc
  6. 567 0
      tripal_analysis/tripal_analysis.views.inc.orig
  7. 75 69
      tripal_analysis/tripal_analysis_privacy.inc
  8. 271 211
      tripal_bulk_loader/tripal_bulk_loader.admin.inc
  9. 2427 0
      tripal_bulk_loader/tripal_bulk_loader.admin.inc.orig
  10. 153 133
      tripal_bulk_loader/tripal_bulk_loader.constants.inc
  11. 86 81
      tripal_bulk_loader/tripal_bulk_loader.install
  12. 239 186
      tripal_bulk_loader/tripal_bulk_loader.loader.inc
  13. 733 0
      tripal_bulk_loader/tripal_bulk_loader.loader.inc.orig
  14. 174 172
      tripal_bulk_loader/tripal_bulk_loader.module
  15. 647 0
      tripal_bulk_loader/tripal_bulk_loader.module.orig
  16. 7 2
      tripal_contact/tripal_contact.api.inc
  17. 141 29
      tripal_core/tripal_core.api.inc
  18. 71 63
      tripal_feature/tripal_feature-db_references.inc
  19. 45 43
      tripal_feature/tripal_feature-delete.inc
  20. 75 67
      tripal_feature/tripal_feature-properties.inc
  21. 153 129
      tripal_feature/tripal_feature-relationships.inc
  22. 38 25
      tripal_feature/tripal_feature-secondary_tables.inc
  23. 189 180
      tripal_feature/tripal_feature.admin.inc
  24. 100 105
      tripal_feature/tripal_feature.api.inc
  25. 33 29
      tripal_feature/tripal_feature.install
  26. 227 219
      tripal_feature/tripal_feature.module
  27. 2 2
      tripal_feature/tripal_feature.views.inc
  28. 473 0
      tripal_feature/tripal_feature.views.inc.orig
  29. 13 8
      tripal_feature/views_handlers/views_handler_field_residues.inc
  30. 22 17
      tripal_genetic/tripal_genetic.api.inc
  31. 10 10
      tripal_genetic/tripal_genetic.module
  32. 29 25
      tripal_library/tripal_library.api.inc
  33. 22 18
      tripal_library/tripal_library.install
  34. 209 199
      tripal_library/tripal_library.module
  35. 2 2
      tripal_library/tripal_library.views.inc
  36. 425 0
      tripal_library/tripal_library.views.inc.orig
  37. 68 64
      tripal_natural_diversity/tripal_natural_diversity.api.inc
  38. 11 10
      tripal_natural_diversity/tripal_natural_diversity.module
  39. 3 3
      tripal_natural_diversity/tripal_natural_diversity.views.inc
  40. 105 0
      tripal_natural_diversity/tripal_natural_diversity.views.inc.orig
  41. 36 30
      tripal_organism/tripal_organism.api.inc
  42. 15 10
      tripal_organism/tripal_organism.install
  43. 230 222
      tripal_organism/tripal_organism.module
  44. 2 2
      tripal_organism/tripal_organism.views.inc
  45. 410 0
      tripal_organism/tripal_organism.views.inc.orig
  46. 4 4
      tripal_phenotype/tripal_phenotype.module
  47. 38 33
      tripal_project/tripal_project.admin.inc
  48. 33 34
      tripal_project/tripal_project.install
  49. 58 58
      tripal_project/tripal_project.module
  50. 47 48
      tripal_pub/tripal_pub.install
  51. 487 486
      tripal_pub/tripal_pub.module
  52. 20 15
      tripal_search/tripal_search.module
  53. 34 27
      tripal_stock/other_module_api_functions.inc
  54. 119 110
      tripal_stock/tripal_stock-administration.inc
  55. 77 67
      tripal_stock/tripal_stock-db_references.inc
  56. 111 97
      tripal_stock/tripal_stock-properties.inc
  57. 145 119
      tripal_stock/tripal_stock-relationships.inc
  58. 45 32
      tripal_stock/tripal_stock-secondary_tables.inc
  59. 103 91
      tripal_stock/tripal_stock.api.inc
  60. 37 37
      tripal_stock/tripal_stock.install
  61. 316 299
      tripal_stock/tripal_stock.module
  62. 86 86
      tripal_stock/tripal_stock.views.inc
  63. 173 0
      tripal_views/views/handlers/views_handler_field_chado_relationship_by_type.inc.orig
  64. 258 0
      tripal_views/views/handlers/views_handler_filter_stock_dbxref_id.inc.orig
  65. 5 5
      tripal_views/views/handlers/views_handler_filter_stock_relationship_id.inc
  66. 355 0
      tripal_views/views/handlers/views_handler_filter_stock_relationship_id.inc.orig
  67. 1 1
      tripal_views/views/handlers/views_handler_filter_stockprop_id.inc
  68. 340 0
      tripal_views/views/handlers/views_handler_filter_stockprop_id.inc.orig

+ 290 - 284
tripal_analysis/tripal_analysis.admin.inc

@@ -3,10 +3,15 @@
 // Copyright 2009 Clemson University
 //
 
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 /**
  * Purpose: Provide Guidance to new Tripal Admin
  *
- * @return 
+ * @return
  *   HTML Formatted text
  *
  * @ingroup tripal_analysis
@@ -15,9 +20,9 @@ function tripal_analysis_module_description_page() {
 
   $text .= '<h3>Tripal Analysis Administrative Tools Quick Links:</h3>';
   $text .= "<ul>
-             <li><a href=\"".url("admin/tripal/tripal_analysis/configuration") . "\">Analysis Configuration</a></li>
+             <li><a href=\"" . url("admin/tripal/tripal_analysis/configuration") . "\">Analysis Configuration</a></li>
            </ul>";
- 
+
 
   $text .= '<h3>Module Description:</h3>';
   $text .= '<p>The Tripal Analysis module provides a generic analysis content type that is intended to be
@@ -30,66 +35,66 @@ function tripal_analysis_module_description_page() {
   $text .= '<h3>Setup Instructions:</h3>';
   $text .= '<p>After installation of the analysis module or any specialized analysis module.  The following tasks should be performed
             <ol>
-              <li><p><b>Set Permissions</b>: Each analysis module supports the Drupal user permissions interface for 
-               controlling access to the content and functions. These permissions include viewing, 
+              <li><p><b>Set Permissions</b>: Each analysis module supports the Drupal user permissions interface for
+               controlling access to the content and functions. These permissions include viewing,
                creating, editing or administering of
-               analysis content. The default is that only the original site administrator has these 
-               permissions.  You can <a href="'.url('admin/user/roles').'">add roles</a> for classifying users, 
-               <a href="'.url('admin/user/user').'">assign users to roles</a> and
-               <a href="'.url('admin/user/permissions').'">assign permissions</a> for the analysis content to 
-               those roles.  For a simple setup, allow anonymous users access to view organism content and 
+               analysis content. The default is that only the original site administrator has these
+               permissions.  You can <a href="' . url('admin/user/roles') .  '">add roles</a> for classifying users,
+               <a href="' . url('admin/user/user') . '">assign users to roles</a> and
+               <a href="' . url('admin/user/permissions') . '">assign permissions</a> for the analysis content to
+               those roles.  For a simple setup, allow anonymous users access to view organism content and
                allow the site administrator all other permissions.</p></li>
 
 
-               <li><p><b>Create Analysis</b>:  An analysis should be <a href="'.url('node/add').'">created</a> before data is imported into
+               <li><p><b>Create Analysis</b>:  An analysis should be <a href="' . url('node/add') . '">created</a> before data is imported into
                chado.  The generic analysis type should only be used when a more specialized analysis module
-               (e.g. Tripal Analysis Blast module) does not already exists.  All data imported into 
-               Chado should be associated with an analysis.    
+               (e.g. Tripal Analysis Blast module) does not already exists.  All data imported into
+               Chado should be associated with an analysis.
 
                <li><p><b>Sync Analyses</b>:  If Chado has preloaded analyses then you can sync those.  This process is what
-               creates the pages for viewing an analysis on the site.  Analyses can be synced using the 
-               <a href="'.url('admin/tripal/tripal_analysis/configuration').'">Analysis Configuration page</a>. 
+               creates the pages for viewing an analysis on the site.  Analyses can be synced using the
+               <a href="' . url('admin/tripal/tripal_analysis/configuration') . '">Analysis Configuration page</a>.
                However, syncing an analyses will always create a generic analysis content type.  If you would like
                to use a specialized analysis module for visualization of data then do not sync the analysis but recreate it
                using the appropriate specialized analysis content type.</p></li>
- 
+
             </ol>
             </p>';
-  
-  
+
+
   $text .= '<h3>Features of this Module:</h3>';
   $text .= '<p>Aside from providing a generic content type the Tripal Analysis module also provides the following functionality
             <ul>
-            
-              <li><p><b>Basic Analysis Lookup View</b>: This module provides a basic <a href="'.url('analyses').'">analysis search 
+
+              <li><p><b>Basic Analysis Lookup View</b>: This module provides a basic <a href="' . url('analyses') . '">analysis search
               tool</a> for finding or listing analyses in Chado. It does not require indexing for Drupal searching but relies
-              on Drupal Views.  <a href="http://drupal.org/project/views">Drupal Views</a> must be installed. </p></li>              
+              on Drupal Views.  <a href="http://drupal.org/project/views">Drupal Views</a> must be installed. </p></li>
 
             </ul>
             </p>';
 
    $text .= '<h3>Page Customizations</h3>';
-   $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal. 
+   $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal.
              Below is a description of several methods.  These methods may be used in conjunction with one another to
-             provide fine-grained control. 
+             provide fine-grained control.
              <ul>
 
-             <li><p><b>Integration with Drupal Panels</b>:  <a href="http://drupal.org/project/views">Drupal Panels</a> 
-              allows for customization of a page layout if you don\'t want to do PHP/Javascript/CSS programming.  
-              Tripal comes with pre-set layouts for analysis pages.  However, 
+             <li><p><b>Integration with Drupal Panels</b>:  <a href="http://drupal.org/project/views">Drupal Panels</a>
+              allows for customization of a page layout if you don\'t want to do PHP/Javascript/CSS programming.
+              Tripal comes with pre-set layouts for analysis pages.  However,
               Panels become useful if you prefer a layout that is different from the pre-set layouts.  Chado content
-              is provided to Panels in the form of Drupal "blocks" which you can then place anywhere on a page using the 
+              is provided to Panels in the form of Drupal "blocks" which you can then place anywhere on a page using the
               Panel\'s GUI.</p></li>
 
-             <li><p><b>Drupal\'s Content Construction Kit (CCK)</b>: the 
+             <li><p><b>Drupal\'s Content Construction Kit (CCK)</b>: the
              <a href="http://drupal.org/project/cck">Content Construction Kit (CCK) </a> is a powerful way to add non-Chado content
              to any page without need to edit template files or knowing PHP.  You must first download and install CCK.
              With CCK, the site administartor can create a new field to appear on the page.  For example, currently,
-             the Chado publication module is not yet supported by Tripal.  Therefore, the site administrator can add a text 
+             the Chado publication module is not yet supported by Tripal.  Therefore, the site administrator can add a text
              field to the analysis pages.  This content is not stored in Chado, but will appear on the analysis page.  A field
              added by CCK will also appear in the form when editing a analysis to allow users to manually enter the appropriate
              text.  If the default pre-set layout and themeing for Tripal is used, it is better to create the CCK element,
-             indicate that it is not to be shown (using the CCK interface), then manually add the new content type 
+             indicate that it is not to be shown (using the CCK interface), then manually add the new content type
              where desired by editing the templates (as described below).  If using Panels, the CCK field can be added to the
              location desired using the Panels interface.</p></li>
 
@@ -97,18 +102,18 @@ function tripal_analysis_module_description_page() {
              themeing for Chado content.    The analysis module has a template file for analysis "nodes" (Tripal analysis pages).  This file
              is named "node-chado_analysis.tpl.php", and provides javascript, HTML and PHP code for display of the analysis
              pages.  Specialized analysis modules will have their own template files as well, such as "node-chado_analysis-blast.tpl.php" for the
-             Tripal Analysis Blast module.  You can edit the template file to control which types of information (or which analysis "blocks") are displayed 
-             for analysis. Be sure to 
+             Tripal Analysis Blast module.  You can edit the template file to control which types of information (or which analysis "blocks") are displayed
+             for analysis. Be sure to
              copy these template to your primary theme directory for editing. Do not edit them in the "theme_tripal" directory as
              future Tripal updates may overwrite your customizations. See the <a href="http://tripal.sourceforge.net/">Tripal website </a>
              for instructions on how to access variables and other Chado content within the template file.</p></li>
 
              <li><p><b>Analysis "Block" Templates</b>:  In the "theme_tripal" directory are subdirectories named after each tripal module (e.g. "tripal_feature", "tripal_library", etc.).
              Inside each directory is a set of templates that control distinct types of information for each content type.  For example,
-             there is a "base" template for displaying of data directly from the Chado feature table, and a "references" 
-             template for showing external site references for a feature (data from the feature_dbxref table). 
+             there is a "base" template for displaying of data directly from the Chado feature table, and a "references"
+             template for showing external site references for a feature (data from the feature_dbxref table).
               These templates are used both by Drupal blocks
-             for use in Drupal Panels (as described above) or for use in the default pre-set layout that the node template 
+             for use in Drupal Panels (as described above) or for use in the default pre-set layout that the node template
              provides (also desribed above).  Analyses block templates can exist in any of these directories.  For example, the Tripal Analysis Unigene
              module uses templates in the tripal_analysis_unigene, tripal_organism, and tripal_feature directories.  Content for a unigene is then
              cusotmizable within each of these contexts.
@@ -120,9 +125,9 @@ function tripal_analysis_module_description_page() {
 
              <li><p><b>Adding Links to the "Resources" Sidebar</b>: If you use the pre-set default Tripal layout for theming, you
              will see a "Resources" sidebar on each page.  The links that appear on the sidebar are automatically generated
-             using Javascript for all of the analysis "Blocks" that appear on the page. If you want to add additional links 
-             (e.g. a dynamic link to GBrowse for the analysis) and you want that link to appear in the 
-             "Resources" sidebar, simply edit the Drupal Node Template (as described above) and add the link to the 
+             using Javascript for all of the analysis "Blocks" that appear on the page. If you want to add additional links
+             (e.g. a dynamic link to GBrowse for the analysis) and you want that link to appear in the
+             "Resources" sidebar, simply edit the Drupal Node Template (as described above) and add the link to the
              section at the bottom of the template file where the resources section is found.</p></li>
 
              </ul>
@@ -140,66 +145,67 @@ function tripal_analysis_module_description_page() {
  * @ingroup tripal_analysis
  */
 function tripal_analysis_admin() {
-	// Create a new administrative form. We'll add main functions to the form
-	// first (Sync, Reindex, Clean, Taxonify). Thereafter, any sub-module that
-	// has a setting will be added.
-	$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_organism')){
-		$active_jobs = TRUE;
-	}
-
-	// add the field set for syncing libraries
-	if(!$active_jobs){
-		// add the field set for syncing analyses
-		get_tripal_analysis_admin_form_sync_set($form);
-//		get_tripal_analysis_admin_form_reindex_set($form);
-//		get_tripal_analysis_admin_form_taxonomy_set($form);
-		get_tripal_analysis_admin_form_cleanup_set($form);
-	} else {
-		$form['notice'] = array(
-		   '#type' => 'fieldset',
-		   '#title' => t('Analysis Management Temporarily Unavailable')
-		);
-		$form['notice']['message'] = array(
+  // Create a new administrative form. We'll add main functions to the form
+  // first (Sync, Reindex, Clean, Taxonify). Thereafter, any sub-module that
+  // has a setting will be added.
+  $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_organism')) {
+    $active_jobs = TRUE;
+  }
+
+  // add the field set for syncing libraries
+  if (!$active_jobs) {
+    // add the field set for syncing analyses
+    get_tripal_analysis_admin_form_sync_set($form);
+//    get_tripal_analysis_admin_form_reindex_set($form);
+//    get_tripal_analysis_admin_form_taxonomy_set($form);
+    get_tripal_analysis_admin_form_cleanup_set($form);
+  }
+  else {
+    $form['notice'] = array(
+       '#type' => 'fieldset',
+       '#title' => t('Analysis Management Temporarily Unavailable')
+    );
+    $form['notice']['message'] = array(
           '#value' => t('Currently, analysis 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.'),
-		);
-	}
-
-	// Add sub-module settings. Pull all sub-module information from
-	// {tripal_analysis} table
-	$sql = "SELECT modulename FROM {tripal_analysis}";
-	$result = db_query($sql);
-	$counter = 0;  //keep track of the number of sub-modules
-	while ($data = db_fetch_object($result)) {
-
-		// Check if the hook_get_settings() function is already defined.
-		$func = $data->modulename."_get_settings";
-		$functions = get_defined_functions();
-		$settings;
-		foreach($functions['user'] as $function) {
-			if ($function == $func) {
-				$settings = $func();
-			}
-		}
-		
-		// Add sub-module's specific settings to the administrative view
-		if ($settings) {
-			// Define a fieldset for the sub-module
-			$form["field$counter"] = array(
+    );
+  }
+
+  // Add sub-module settings. Pull all sub-module information from
+  // {tripal_analysis} table
+  $sql = "SELECT modulename FROM {tripal_analysis}";
+  $result = db_query($sql);
+  $counter = 0;  //keep track of the number of sub-modules
+  while ($data = db_fetch_object($result)) {
+
+    // Check if the hook_get_settings() function is already defined.
+    $func = $data->modulename . "_get_settings";
+    $functions = get_defined_functions();
+    $settings;
+    foreach ($functions['user'] as $function) {
+      if ($function == $func) {
+        $settings = $func();
+      }
+    }
+
+    // Add sub-module's specific settings to the administrative view
+    if ($settings) {
+      // Define a fieldset for the sub-module
+      $form["field$counter"] = array(
             '#type' => 'fieldset',
             '#title' => "$settings->title",
             '#collapsible' => TRUE
-			);
-			$form["field$counter"]["$settings->title"] = $settings->form;
-		}
-		$counter ++;
-	}
-	return system_settings_form($form);
+      );
+      $form["field$counter"]["$settings->title"] = $settings->form;
+    }
+    $counter ++;
+  }
+  return system_settings_form($form);
 }
 
 /**
@@ -207,32 +213,32 @@ function tripal_analysis_admin() {
  * @ingroup tripal_analysis
  */
 function get_tripal_analysis_admin_form_taxonomy_set(&$form) {
-	$form['taxonify'] = array(
+  $form['taxonify'] = array(
       '#type' => 'fieldset',
       '#title' => t('Assign Drupal Taxonomy to Analysis Features')
-	);
+  );
 
-	// get the list of analyses
-	$sql = "SELECT * FROM {Analysis} ORDER BY name";
-	$previous_db = tripal_db_set_active('chado');  // use chado database
-	$lib_rset = db_query($sql);
-	tripal_db_set_active($previous_db);  // now use drupal database
+  // get the list of analyses
+  $sql = "SELECT * FROM {Analysis} ORDER BY name";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $lib_rset = db_query($sql);
+  tripal_db_set_active($previous_db);  // now use drupal database
 
-	// iterate through all of the libraries
-	$lib_boxes = array();
-	while($analysis = db_fetch_object($lib_rset)){
-		$lib_boxes[$analysis->analysis_id] = "$analysis->name";
-	}
+  // iterate through all of the libraries
+  $lib_boxes = array();
+  while ($analysis = db_fetch_object($lib_rset)) {
+    $lib_boxes[$analysis->analysis_id] = "$analysis->name";
+  }
 
-	$form['taxonify']['description'] = array(
+  $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 analyses below.  All other features will be unaffected.  To set taxonomy for all features in the site see the Feature Administration page."),
-		 '#weight' => 1,
-	);
+     '#weight' => 1,
+  );
 
-	$form['taxonify']['tx-analyses'] = array (
+  $form['taxonify']['tx-analyses'] = array(
      '#title'       => t('Analyses'),
      '#type'        => t('checkboxes'),
      '#description' => t("Check the analyses whose features you want to reset taxonomy.  Note: this list contains all analyses, even those that may not be synced."),
@@ -241,42 +247,42 @@ function get_tripal_analysis_admin_form_taxonomy_set(&$form) {
      '#suffix'      => '</div>',
      '#options'     => $lib_boxes,
      '#weight'      => 2
-	);
-	$form['taxonify']['tx-button'] = array(
+  );
+  $form['taxonify']['tx-button'] = array(
       '#type' => 'submit',
       '#value' => t('Set Feature Taxonomy'),
       '#weight'      => 3
-	);
+  );
 }
-/** 
+/**
  *
  * @ingroup tripal_analysis
  */
 function get_tripal_analysis_admin_form_reindex_set(&$form) {
-	// define the fieldsets
-	$form['reindex'] = array(
+  // define the fieldsets
+  $form['reindex'] = array(
       '#type' => 'fieldset',
       '#title' => t('Reindex Analysis Features')
-	);
-
-	// get the list of libraries
-	$sql = "SELECT * FROM {Analysis} ORDER BY name";
-	$previous_db = tripal_db_set_active('chado');  // use chado database
-	$lib_rset = db_query($sql);
-	tripal_db_set_active($previous_db);  // now use drupal database
-
-	// iterate through all of the libraries
-	$lib_boxes = array();
-	while($analysis = db_fetch_object($lib_rset)){
-		$lib_boxes[$analysis->analysis_id] = "$analysis->name";
-	}
-	$form['reindex']['description'] = array(
+  );
+
+  // get the list of libraries
+  $sql = "SELECT * FROM {Analysis} ORDER BY name";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $lib_rset = db_query($sql);
+  tripal_db_set_active($previous_db);  // now use drupal database
+
+  // iterate through all of the libraries
+  $lib_boxes = array();
+  while ($analysis = db_fetch_object($lib_rset)) {
+    $lib_boxes[$analysis->analysis_id] = "$analysis->name";
+  }
+  $form['reindex']['description'] = array(
        '#type' => 'item',
        '#value' => t("This option allows for reindexing of only those features that belong to the selected analyses below. All other features will be unaffected.  To reindex all features in the site see the Feature Administration page."),
-		 '#weight' => 1,
-	);
+     '#weight' => 1,
+  );
 
-	$form['reindex']['re-analyses'] = array (
+  $form['reindex']['re-analyses'] = array(
      '#title'       => t('Libraries'),
      '#type'        => t('checkboxes'),
      '#description' => t("Check the analyses whoee features you want to reindex. Note: this list contains all analyses, even those that may not be synced."),
@@ -285,23 +291,23 @@ function get_tripal_analysis_admin_form_reindex_set(&$form) {
      '#suffix'      => '</div>',
      '#options'     => $lib_boxes,
      '#weight' => 2,
-	);
-	$form['reindex']['re-button'] = array(
+  );
+  $form['reindex']['re-button'] = array(
       '#type' => 'submit',
       '#value' => t('Reindex Features'),
       '#weight' => 3,
-	);
+  );
 }
-/** 
+/**
  *
  * @ingroup tripal_analysis
  */
 function get_tripal_analysis_admin_form_cleanup_set(&$form) {
-	$form['cleanup'] = array(
+  $form['cleanup'] = array(
       '#type' => 'fieldset',
       '#title' => t('Clean Up')
-	);
-	$form['cleanup']['description'] = array(
+  );
+  $form['cleanup']['description'] = array(
        '#type' => 'item',
        '#value' => t("With Drupal and chado residing in different databases ".
           "it is possible that nodes in Drupal and analyses in Chado become ".
@@ -309,62 +315,62 @@ function get_tripal_analysis_admin_form_cleanup_set(&$form) {
           "deleted but the corresponding chado analysis is not and/or vice ".
           "versa. Click the button below to resolve these discrepancies."),
        '#weight' => 1,
-	);
-	$form['cleanup']['button'] = array(
+  );
+  $form['cleanup']['button'] = array(
       '#type' => 'submit',
       '#value' => t('Clean up orphaned analyses'),
       '#weight' => 2,
-	);
+  );
 }
-/** 
+/**
  *
  * @ingroup tripal_analysis
  */
-function get_tripal_analysis_admin_form_sync_set (&$form) {
-	// define the fieldsets
-	$form['sync'] = array(
+function get_tripal_analysis_admin_form_sync_set(&$form) {
+  // define the fieldsets
+  $form['sync'] = array(
       '#type' => 'fieldset',
       '#title' => t('Sync Analyses')
-	);
-
-	// before proceeding check to see if we have any
-	// currently processing jobs. If so, we don't want
-	// to give the opportunity to sync analyses
-	$active_jobs = FALSE;
-	if(tripal_get_module_active_jobs('tripal_analysis')){
-		$active_jobs = TRUE;
-	}
-
-	if(!$active_jobs){
-			
-		// get the list of analyses
-		$sql = "SELECT * FROM {analysis} ORDER BY name";
-		$previous_db = tripal_db_set_active('chado');  // use chado database
-		$ana_rset = db_query($sql);
-		tripal_db_set_active($previous_db);  // now use drupal database
-			
-		// if we've added any analyses 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 analyses are currently synced.
-		$ana_boxes = array();
-		$added = 0;
-		while($analysis = db_fetch_object($ana_rset)){
-			// check to see if the analysis is already present as a node in drupal.
-			// if so, then skip it.
-			$sql = "SELECT * FROM {chado_analysis} WHERE analysis_id = %d";
-			if(!db_fetch_object(db_query($sql,$analysis->analysis_id))){
-				$ana_boxes[$analysis->analysis_id] = "$analysis->name";
-				$added++;
-			}
-		}
-
-		// if we have analyses we need to add to the checkbox then
-		// build that form element
-		if($added > 0){
-			$ana_boxes['all'] = "All analyses";
-
-			$form['sync']['analyses'] = 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 analyses
+  $active_jobs = FALSE;
+  if (tripal_get_module_active_jobs('tripal_analysis')) {
+    $active_jobs = TRUE;
+  }
+
+  if (!$active_jobs) {
+
+    // get the list of analyses
+    $sql = "SELECT * FROM {analysis} ORDER BY name";
+    $previous_db = tripal_db_set_active('chado');  // use chado database
+    $ana_rset = db_query($sql);
+    tripal_db_set_active($previous_db);  // now use drupal database
+
+    // if we've added any analyses 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 analyses are currently synced.
+    $ana_boxes = array();
+    $added = 0;
+    while ($analysis = db_fetch_object($ana_rset)) {
+      // check to see if the analysis is already present as a node in drupal.
+      // if so, then skip it.
+      $sql = "SELECT * FROM {chado_analysis} WHERE analysis_id = %d";
+      if (!db_fetch_object(db_query($sql, $analysis->analysis_id))) {
+        $ana_boxes[$analysis->analysis_id] = "$analysis->name";
+        $added++;
+      }
+    }
+
+    // if we have analyses we need to add to the checkbox then
+    // build that form element
+    if ($added > 0) {
+      $ana_boxes['all'] = "All analyses";
+
+      $form['sync']['analyses'] = array(
            '#title'       => t('Available analyses'),
            '#type'        => t('checkboxes'),
            '#description' => t("Check the analyses you want to sync.  Drupal ".
@@ -374,112 +380,112 @@ function get_tripal_analysis_admin_form_sync_set (&$form) {
            '#prefix'      => '<div id="ana_boxes">',
            '#suffix'      => '</div>',
            '#options'     => $ana_boxes,
-			);
-			$form['sync']['button'] = array(
+      );
+      $form['sync']['button'] = array(
             '#type' => 'submit',
             '#value' => t('Submit Sync Job')
-			);
-		}
-		// we don't have any analyses to select from
-		else {
-			$form['sync']['value'] = array(
+      );
+    }
+    // we don't have any analyses to select from
+    else {
+      $form['sync']['value'] = array(
             '#value' => t('All analyses in Chado are currently synced with Drupal.')
-			);
-		}
-	}
-	// we don't want to present a form since we have an active job running
-	else {
-		$form['sync']['value'] = array(
+      );
+    }
+  }
+  // we don't want to present a form since we have an active job running
+  else {
+    $form['sync']['value'] = array(
           '#value' => t('Currently, jobs exist related to chado analyses. Please check back later for analyses that can by synced once these jobs have finished.  You can view the status of pending jobs in the Tripal jobs page.')
-		);
-	}
+    );
+  }
 }
 /**
  *
  * @ingroup tripal_analysis
  */
 function tripal_analysis_admin_validate($form, &$form_state) {
-	global $user;  // we need access to the user info
-	$job_args = array();
-
-	if ($form_state['values']['op'] == t('Submit Sync Job')) {
-
-		// 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
-		$analyses = $form_state['values']['analyses'];
-		$do_all = FALSE;
-		$to_sync = array();
-
-		foreach ($analyses as $analysis_id){
-			if(preg_match("/^all$/i",$analysis_id)){
-				$do_all = TRUE;
-			}
-			if($analysis_id and preg_match("/^\d+$/i",$analysis_id)){
-				// get the list of analyses
-				$sql = "SELECT * FROM {analysis} WHERE analysis_id = %d";
-				$previous_db = tripal_db_set_active('chado');  // use chado database
-				$analysis = db_fetch_object(db_query($sql,$analysis_id));
-				tripal_db_set_active($previous_db);  // now use drupal database
-				$to_sync[$analysis_id] = $analysis->name;
-			}
-		}
-
-		// submit the job the tripal job manager
-		if($do_all){
-			tripal_add_job('Sync all analyses','tripal_analysis','tripal_analysis_sync_analyses',$job_args,$user->uid);
-		}
-		else{
-			foreach($to_sync as $analysis_id => $name){
-				$job_args[0] = $analysis_id;
-				tripal_add_job("Sync analysis: $name",'tripal_analysis','tripal_analysis_sync_analyses',$job_args,$user->uid);
-			}
-		}
-	}
-	// -------------------------------------
-	// Submit the Reindex Job if selected
-	if ($form_state['values']['op'] == t('Reindex Features')) {
-		global $user;  // we need access to the user info
-		$job_args = array();
-		$analyses = $form_state['values']['re-analyses'];
-		foreach ($analyses as $analysis_id){
-			if($analysis_id and preg_match("/^\d+$/i",$analysis_id)){
-				// get the analysis info
-				$sql = "SELECT * FROM {analysis} WHERE analysis_id = %d";
-				$previous_db = tripal_db_set_active('chado');  // use chado database
-				$analysis = db_fetch_object(db_query($sql,$analysis_id));
-				tripal_db_set_active($previous_db);  // now use drupal database
-				$job_args[0] = $analysis_id;
-				tripal_add_job("Reindex features for analysis: $analysis->name",'tripal_analysis',
-             'tripal_analysis_reindex_features',$job_args,$user->uid);
-			}
-		}
-	}
-
-	// -------------------------------------
-	// Submit the Taxonomy Job if selected
-	if ($form_state['values']['op'] == t('Set Feature Taxonomy')) {
-		global $user;  // we need access to the user info
-		$job_args = array();
-		$analyses = $form_state['values']['tx-analyses'];
-		foreach ($analyses as $analysis_id){
-			if($analysis_id and preg_match("/^\d+$/i",$analysis_id)){
-				// get the analysis info
-				$sql = "SELECT * FROM {analysis} WHERE analysis_id = %d";
-				$previous_db = tripal_db_set_active('chado');  // use chado database
-				$analysis = db_fetch_object(db_query($sql,$analysis_id));
-				tripal_db_set_active($previous_db);  // now use drupal database
-				$job_args[0] = $analysis_id;
-				tripal_add_job("Set taxonomy for features in analysis: $analysis->name",'tripal_analysis',
-             'tripal_analysis_taxonify_features',$job_args,$user->uid);
-			}
-		}
-	}
-
-	// -------------------------------------
-	// Submit the Cleanup Job if selected
-	if ($form_state['values']['op'] == t('Clean up orphaned analyses')) {
-		tripal_add_job('Cleanup orphaned analyses','tripal_analysis',
-         'tripal_analyses_cleanup',$job_args,$user->uid);
-	}
+  global $user;  // we need access to the user info
+  $job_args = array();
+
+  if ($form_state['values']['op'] == t('Submit Sync Job')) {
+
+    // 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
+    $analyses = $form_state['values']['analyses'];
+    $do_all = FALSE;
+    $to_sync = array();
+
+    foreach ($analyses as $analysis_id) {
+      if (preg_match("/^all$/i", $analysis_id)) {
+        $do_all = TRUE;
+      }
+      if ($analysis_id and preg_match("/^\d+$/i", $analysis_id)) {
+        // get the list of analyses
+        $sql = "SELECT * FROM {analysis} WHERE analysis_id = %d";
+        $previous_db = tripal_db_set_active('chado');  // use chado database
+        $analysis = db_fetch_object(db_query($sql, $analysis_id));
+        tripal_db_set_active($previous_db);  // now use drupal database
+        $to_sync[$analysis_id] = $analysis->name;
+      }
+    }
+
+    // submit the job the tripal job manager
+    if ($do_all) {
+      tripal_add_job('Sync all analyses', 'tripal_analysis', 'tripal_analysis_sync_analyses', $job_args, $user->uid);
+    }
+    else{
+      foreach ($to_sync as $analysis_id => $name) {
+        $job_args[0] = $analysis_id;
+        tripal_add_job("Sync analysis: $name", 'tripal_analysis', 'tripal_analysis_sync_analyses', $job_args, $user->uid);
+      }
+    }
+  }
+  // -------------------------------------
+  // Submit the Reindex Job if selected
+  if ($form_state['values']['op'] == t('Reindex Features')) {
+    global $user;  // we need access to the user info
+    $job_args = array();
+    $analyses = $form_state['values']['re-analyses'];
+    foreach ($analyses as $analysis_id) {
+      if ($analysis_id and preg_match("/^\d+$/i", $analysis_id)) {
+        // get the analysis info
+        $sql = "SELECT * FROM {analysis} WHERE analysis_id = %d";
+        $previous_db = tripal_db_set_active('chado');  // use chado database
+        $analysis = db_fetch_object(db_query($sql, $analysis_id));
+        tripal_db_set_active($previous_db);  // now use drupal database
+        $job_args[0] = $analysis_id;
+        tripal_add_job("Reindex features for analysis: $analysis->name", 'tripal_analysis',
+             'tripal_analysis_reindex_features', $job_args, $user->uid);
+      }
+    }
+  }
+
+  // -------------------------------------
+  // Submit the Taxonomy Job if selected
+  if ($form_state['values']['op'] == t('Set Feature Taxonomy')) {
+    global $user;  // we need access to the user info
+    $job_args = array();
+    $analyses = $form_state['values']['tx-analyses'];
+    foreach ($analyses as $analysis_id) {
+      if ($analysis_id and preg_match("/^\d+$/i", $analysis_id)) {
+        // get the analysis info
+        $sql = "SELECT * FROM {analysis} WHERE analysis_id = %d";
+        $previous_db = tripal_db_set_active('chado');  // use chado database
+        $analysis = db_fetch_object(db_query($sql, $analysis_id));
+        tripal_db_set_active($previous_db);  // now use drupal database
+        $job_args[0] = $analysis_id;
+        tripal_add_job("Set taxonomy for features in analysis: $analysis->name", 'tripal_analysis',
+             'tripal_analysis_taxonify_features', $job_args, $user->uid);
+      }
+    }
+  }
+
+  // -------------------------------------
+  // Submit the Cleanup Job if selected
+  if ($form_state['values']['op'] == t('Clean up orphaned analyses')) {
+    tripal_add_job('Cleanup orphaned analyses', 'tripal_analysis',
+         'tripal_analyses_cleanup', $job_args, $user->uid);
+  }
 }
 

+ 23 - 18
tripal_analysis/tripal_analysis.api.inc

@@ -1,5 +1,10 @@
 <?php
 
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 /**
  * @defgroup tripal_analysis_api Analysis Module API
  * @ingroup tripal_analysis
@@ -20,9 +25,9 @@
  */
 function tripal_analysis_chado_analysis_schema() {
   $description = array();
-  
+
   // Default table description in tripal_core.schema.api.inc: tripal_core_chado_analysis_schema()
-  
+
   $referring_tables = array(
       'analysisfeature',
       'analysisprop',
@@ -30,7 +35,7 @@ function tripal_analysis_chado_analysis_schema() {
       'quantification'
   );
   $description['referring_tables'] = $referring_tables;
-  
+
   return $description;
 }
 
@@ -60,7 +65,7 @@ function tripal_analysis_chado_analysisfeature_schema() {
           'analysis_id' => 'analysis_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -137,8 +142,8 @@ function tripal_analysis_chado_analysisprop_schema() {
  *
  * @ingroup tripal_analysis_api
  */
-function tripal_analysis_get_property($analysis_id,$property){
-   return tripal_core_get_property('analysis',$analysis_id,$property,'tripal');
+function tripal_analysis_get_property($analysis_id, $property) {
+   return tripal_core_get_property('analysis', $analysis_id, $property, 'tripal');
 }
 
 /**
@@ -158,8 +163,8 @@ function tripal_analysis_get_property($analysis_id,$property){
  *
  * @ingroup tripal_analysis_api
  */
-function tripal_analysis_insert_property($analysis_id,$property,$value,$update_if_present = 0){
-    return tripal_core_insert_property('analysis',$analysis_id,$property,'tripal',$value,$update_if_present);
+function tripal_analysis_insert_property($analysis_id, $property, $value, $update_if_present = 0) {
+    return tripal_core_insert_property('analysis', $analysis_id, $property, 'tripal', $value, $update_if_present);
 }
 
 /**
@@ -171,7 +176,7 @@ function tripal_analysis_insert_property($analysis_id,$property,$value,$update_i
  *   The cvterm name of the property to update
  * @param $value
  *   The value of the property to update
- * @param $insert_if_missing 
+ * @param $insert_if_missing
  *   A boolean indicated whether to insert the record if it's absent
  *
  * Note: The property will be identified using the unique combination of the $analysis_id and $property
@@ -182,8 +187,8 @@ function tripal_analysis_insert_property($analysis_id,$property,$value,$update_i
  *
  * @ingroup tripal_analysis_api
  */
-function tripal_analysis_update_property($analysis_id,$property,$value,$insert_if_missing = 0){
-   return tripal_core_update_property('analysis',$analysis_id,$property,'tripal',$value, $insert_if_missing);
+function tripal_analysis_update_property($analysis_id, $property, $value, $insert_if_missing = 0) {
+   return tripal_core_update_property('analysis', $analysis_id, $property, 'tripal', $value, $insert_if_missing);
 }
 
 /**
@@ -198,12 +203,12 @@ function tripal_analysis_update_property($analysis_id,$property,$value,$insert_i
  * and then it will be deleted
  *
  * @return
- *   True of success, False otherwise 
+ *   True of success, False otherwise
  *
  * @ingroup tripal_analysis_api
  */
-function tripal_analysis_delete_property($analysis_id,$property){
-   return tripal_core_delete_property('analysis',$analysis_id,$property,'tripal');
+function tripal_analysis_delete_property($analysis_id, $property) {
+   return tripal_core_delete_property('analysis', $analysis_id, $property, 'tripal');
 }
 /**
  * Retreives the node of a sync'ed analysis
@@ -212,15 +217,15 @@ function tripal_analysis_delete_property($analysis_id,$property){
  *   The analysis_id of the property to delete
  *
  * @return
- *   node of analysis on success, null otherwise 
+ *   node of analysis on success, null otherwise
  *
  * @ingroup tripal_analysis_api
  */
-function tripal_analysis_get_node($analysis_id){
-   $sql = "SELECT * 
+function tripal_analysis_get_node($analysis_id) {
+   $sql = "SELECT *
            FROM chado_analysis CA
               INNER JOIN node N on CA.nid = N.nid
            WHERE analysis_id = %d";
-   $node = db_fetch_object(db_query($sql,$analysis_id));
+   $node = db_fetch_object(db_query($sql, $analysis_id));
    return $node;
 }

+ 58 - 55
tripal_analysis/tripal_analysis.install

@@ -1,54 +1,57 @@
 <?php
-//$Id:
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /*******************************************************************************
  * Implementation of hook_install().
  */
 function tripal_analysis_install() {
 
-	// create the module's data directory
-	tripal_create_moddir('tripal_analysis');
+  // create the module's data directory
+  tripal_create_moddir('tripal_analysis');
+
+  // Use schema API to create database table.
+  drupal_install_schema('tripal_analysis');
 
-	// Use schema API to create database table.
-	drupal_install_schema('tripal_analysis');
-	
-	// Create analysisfeatureprop table in chado. This cannot be accomplished
-	// by calling drupal_install_schema because it's not in the drupal db. This
-	// table is used to store Blast xml and Interpro html/goterms
-	$previous_db = tripal_db_set_active('chado');
-	if (!db_table_exists('analysisfeatureprop')) {
-	   $sql = "CREATE TABLE {analysisfeatureprop} (".
-	          "  analysisfeatureprop_id SERIAL PRIMARY KEY, ".
-	          "  analysisfeature_id INTEGER NOT NULL REFERENCES analysisfeature(analysisfeature_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, ".
-	          "  type_id INTEGER NOT NULL REFERENCES cvterm(cvterm_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, ".
-	          "  value TEXT, ".
-	          "  rank INTEGER NOT NULL, ".
-	          "  CONSTRAINT analysisfeature_id_type_id_rank UNIQUE(analysisfeature_id, type_id, rank)".
-	          ")";
-	   db_query($sql);
-	}
-	tripal_db_set_active($previous_db);
+  // Create analysisfeatureprop table in chado. This cannot be accomplished
+  // by calling drupal_install_schema because it's not in the drupal db. This
+  // table is used to store Blast xml and Interpro html/goterms
+  $previous_db = tripal_db_set_active('chado');
+  if (!db_table_exists('analysisfeatureprop')) {
+     $sql = "CREATE TABLE {analysisfeatureprop} (".
+            "  analysisfeatureprop_id SERIAL PRIMARY KEY, ".
+            "  analysisfeature_id INTEGER NOT NULL REFERENCES analysisfeature(analysisfeature_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, ".
+            "  type_id INTEGER NOT NULL REFERENCES cvterm(cvterm_id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED, ".
+            "  value TEXT, ".
+            "  rank INTEGER NOT NULL, ".
+            "  CONSTRAINT analysisfeature_id_type_id_rank UNIQUE(analysisfeature_id, type_id, rank)".
+            ")";
+     db_query($sql);
+  }
+  tripal_db_set_active($previous_db);
 
-   tripal_cv_add_cvterm(array('name' => 'analysis_type','def' => 'The type of analysis was performed. This value is automatically set by each Tripal Analysis module and should be equal to the module name (e.g. tripal_analysis_blast, tripal_analysis_go).'),'tripal',0,1,'tripal');
-	tripal_cv_add_cvterm(array('name' => 'analysis_date','def' => 'The date that an analysis was performed.'),'tripal',0,1,'tripal');
-	tripal_cv_add_cvterm(array('name' => 'analysis_short_name','def' => 'A computer legible (no spaces '.
-      'or special characters) abbreviation for the analysis.'),'tripal',0,1,'tripal');
+   tripal_cv_add_cvterm(array('name' => 'analysis_type', 'def' => 'The type of analysis was performed. This value is automatically set by each Tripal Analysis module and should be equal to the module name (e.g. tripal_analysis_blast, tripal_analysis_go).'), 'tripal', 0, 1, 'tripal');
+  tripal_cv_add_cvterm(array('name' => 'analysis_date', 'def' => 'The date that an analysis was performed.'), 'tripal', 0, 1, 'tripal');
+  tripal_cv_add_cvterm(array('name' => 'analysis_short_name', 'def' => 'A computer legible (no spaces ' .
+      'or special characters) abbreviation for the analysis.'), 'tripal', 0, 1 , 'tripal');
 }
 
 /*******************************************************************************
  * Implementation of hook_uninstall().
  */
 function tripal_analysis_uninstall() {
-	// Use schema API to delete database table.
-	drupal_uninstall_schema('tripal_analysis');
-	// Remove analysis nodes from drupal.
-	$sql_ana_id = "SELECT nid, vid ".
+  // Use schema API to delete database table.
+  drupal_uninstall_schema('tripal_analysis');
+  // Remove analysis nodes from drupal.
+  $sql_ana_id = "SELECT nid, vid ".
                  "FROM {node} ".
                  "WHERE type like 'chado_analysi%'";
-	$result = db_query($sql_ana_id);
-	while ($ana = db_fetch_object($result)) {
-		node_delete($ana->nid);
-	}
+  $result = db_query($sql_ana_id);
+  while ($ana = db_fetch_object($result)) {
+    node_delete($ana->nid);
+  }
 }
 
 /*******************************************************************************
@@ -58,39 +61,39 @@ function tripal_analysis_uninstall() {
  * tripal_analysis_blast, that are registered with this module.
  */
 function tripal_analysis_schema() {
-	// chado_analysis table
-	$schema['chado_analysis'] = array(
+  // chado_analysis table
+  $schema['chado_analysis'] = 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
-	),
+  ),
          'analysis_id' => array(
             'type' => 'int',
             'not null' => TRUE,
             'default' => 0
-	)
-	),
+  )
+  ),
       'indexes' => array(
          'analysis_id' => array('analysis_id')
-	),
+  ),
       'unique keys' => array(
-         'nid_vid' => array('nid','vid'),
+         'nid_vid' => array('nid', 'vid'),
          'vid' => array('vid')
-	),
+  ),
       'primary key' => array('nid'),
-	);
+  );
 
-	// tripal_analysis table
-	$schema['tripal_analysis'] = array(
+  // tripal_analysis table
+  $schema['tripal_analysis'] = array(
       'description' => t('Table to store analysis sub-modules'),
       'fields' => array(
          'modulename' => array(
@@ -99,13 +102,13 @@ function tripal_analysis_schema() {
             'not null' => TRUE,
             'description' => t('The module name. Tripal Analysis will use the '.
                                'module name to call module_setting_form()')
-	)
-	),
+  )
+  ),
       'unique keys' => array(
          'modulename' => array('modulename')
-	)
-	);
-	return $schema;
+  )
+  );
+  return $schema;
 }
 
 /*******************************************************************************
@@ -129,12 +132,12 @@ function tripal_analysis_requirements($phase) {
 /*******************************************************************************
  * Provide update script for adding new cvterms
  */
-function tripal_analysis_update_6001(){
+function tripal_analysis_update_6001() {
    // we have some new cvterms to add
-   tripal_cv_add_cvterm(array('name' => 'based_on_analysis','def' => 'The analysis that this analysis was based on. For example, blast/kegg/interpro analyses are based on a unigene analysis. The unigene analysis_id should be stored in analysisprop as the rank using this cvterm. The name of said unigene analysis can be inserted as the value in analysisprop.'),'tripal',0,1,'tripal');
-   tripal_cv_add_cvterm(array('name' => 'additional_files', 'def' => 'Additional files for this analysis. Each file should be separated by a semi-colon and have this format: <file description>, <file path>;'),'tripal',0,1,'tripal');
+   tripal_cv_add_cvterm(array('name' => 'based_on_analysis', 'def' => 'The analysis that this analysis was based on. For example, blast/kegg/interpro analyses are based on a unigene analysis. The unigene analysis_id should be stored in analysisprop as the rank using this cvterm. The name of said unigene analysis can be inserted as the value in analysisprop.'), 'tripal', 0, 1, 'tripal');
+   tripal_cv_add_cvterm(array('name' => 'additional_files', 'def' => 'Additional files for this analysis. Each file should be separated by a semi-colon and have this format: <file description>, <file path>;'), 'tripal', 0, 1, 'tripal');
    $ret = array(
       '#finished' => 1,
-   );   
+   );
    return $ret;
 }

File diff suppressed because it is too large
+ 343 - 332
tripal_analysis/tripal_analysis.module


+ 2 - 2
tripal_analysis/tripal_analysis.views.inc

@@ -90,7 +90,7 @@ function tripal_analysis_views_views_handlers() {
  */
 function tripal_analysis_views_data_alter(&$data) {
 
-  if( !(is_array($db_url) and array_key_exists('chado',$db_url)) ){
+  if (!(is_array($db_url) and array_key_exists('chado', $db_url)) ) {
 
     // Add featuer relationship to node
     $data['node']['analysis_chado_nid'] = array(
@@ -116,7 +116,7 @@ function tripal_analysis_views_data_alter(&$data) {
  *
  * @ingroup tripal_analysis_views
  */
-function tripal_analysis_views_default_views () {
+function tripal_analysis_views_default_views() {
   $views = array();
 
   // Main default view

+ 567 - 0
tripal_analysis/tripal_analysis.views.inc.orig

@@ -0,0 +1,567 @@
+<?php
+
+/**
+ *  @file
+ *  This file contains the basic functions for views integration of
+ *  chado/tripal analysis tables. Supplementary functions can be found in
+ *  ./views/
+ *
+ *  Documentation on views integration can be found at
+ *  http://views2.logrus.com/doc/html/index.html.
+ */
+
+/**
+ * @defgroup tripal_analysis_views Analysis Views Integration
+ * @ingroup views
+ * @ingroup tripal_analysis
+ */
+
+<<<<<<< HEAD
+=======
+require('views/analysis.views.inc');
+require('views/chado_analysis.views.inc');
+require('views/misc_tables.views.inc');
+>>>>>>> 6.x-0.4-dev
+/**
+ * Implements hook_views_data()
+ *
+ * Purpose: Describe chado/tripal tables & fields to views
+ *
+ * @return: a data array which follows the structure outlined in the
+ *   views2 documentation for this hook. Essentially, it's an array of table
+ *   definitions keyed by chado/tripal table name. Each table definition
+ *   includes basic details about the table, fields in that table and
+ *   relationships between that table and others (joins)
+ *
+ * @ingroup tripal_analysis_views
+ */
+function tripal_analysis_views_data()  {
+  $data = array();
+
+  if (module_exists('tripal_views')) {
+		// Base Table: Analysis
+		$tablename = 'analysis';
+		if (!tripal_views_is_integrated($tablename, 10)) {
+			$table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, TRUE);
+			tripal_views_integration_add_entry($table_integration_array);
+		}
+
+
+    $tables = array(
+      'analysisfeature',
+      'analysisprop'
+    );
+    foreach ($tables as $tablename) {
+      if (!tripal_views_is_integrated($tablename, 10)) {
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename, FALSE);
+        tripal_views_integration_add_entry($table_integration_array);
+      }
+    }
+
+  }
+
+  return $data;
+}
+
+/**
+ * Implements hook_views_handlers()
+ *
+ * Purpose: Register all custom handlers with views
+ *   where a handler describes either "the type of field",
+ *   "how a field should be filtered", "how a field should be sorted"
+ *
+ * @return
+ *   An array of handler definitions
+ *
+ * @ingroup tripal_analysis_views
+ */
+function tripal_analysis_views_views_handlers() {
+  return array(
+    'info' => array(
+      'path' => drupal_get_path('module', 'tripal_analysis') . '/views/handlers',
+    ),
+    'handlers' => array(
+      'views_handler_field_computed_analysis_nid' => array(
+        'parent' => 'views_handler_field_numeric',
+      ),
+      'views_handler_field_readable_date' => array(
+        'parent' => 'views_handler_field',
+      ),
+    ),
+  );
+}
+
+/**
+ * Implementation of hook_views_data_alter().
+ */
+function tripal_analysis_views_data_alter(&$data) {
+
+  if (!(is_array($db_url) and array_key_exists('chado', $db_url)) ) {
+
+    // Add featuer relationship to node
+    $data['node']['analysis_chado_nid'] = array(
+      'group' => 'Analysis',
+      'title' => 'Analysis Node',
+      'help' => 'Links Chado analysis Fields/Data to the Nodes in the current View.',
+      'real field' => 'nid',
+      'relationship' => array(
+        'handler' => 'views_handler_relationship',
+        'title' => t('Node => Chado'),
+        'label' => t('Node => Chado'),
+        'real field' => 'nid',
+        'base' => 'chado_analysis',
+        'base field' => 'nid'
+      ),
+    );
+  }
+
+}
+
+/**
+ *
+ *
+ * @ingroup tripal_analysis_views
+ */
+function tripal_analysis_views_default_views() {
+  $views = array();
+
+  // Main default view
+  // List all cvterms based on cv
+  $view = new view;
+  $view->name = 'all_analysis';
+  $view->description = 'A listing of all analysis\'';
+  $view->tag = 'chado';
+  $view->view_php = '';
+  $view->base_table = 'analysis';
+  $view->is_cacheable = FALSE;
+  $view->api_version = 2;
+  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
+  $handler = $view->new_display('default', 'Defaults', 'default');
+  $handler->override_option('fields', array(
+    'name' => array(
+      'label' => 'Name',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 1,
+      'exclude' => 0,
+      'id' => 'name',
+      'table' => 'analysis',
+      'field' => 'name',
+      'relationship' => 'none',
+    ),
+    'algorithm' => array(
+      'label' => 'Algorithm',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'algorithm',
+      'table' => 'analysis',
+      'field' => 'algorithm',
+      'relationship' => 'none',
+    ),
+    'program' => array(
+      'label' => 'Program',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'program',
+      'table' => 'analysis',
+      'field' => 'program',
+      'relationship' => 'none',
+    ),
+    'programversion' => array(
+      'label' => 'Program Version',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'programversion',
+      'table' => 'analysis',
+      'field' => 'programversion',
+      'relationship' => 'none',
+    ),
+    'description' => array(
+      'label' => 'Description',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'description',
+      'table' => 'analysis',
+      'field' => 'description',
+      'relationship' => 'none',
+    ),
+    'sourcename' => array(
+      'label' => 'Source Name',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'sourcename',
+      'table' => 'analysis',
+      'field' => 'sourcename',
+      'relationship' => 'none',
+    ),
+    'sourceuri' => array(
+      'label' => 'Source URL',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'sourceuri',
+      'table' => 'analysis',
+      'field' => 'sourceuri',
+      'relationship' => 'none',
+    ),
+    'sourceversion' => array(
+      'label' => 'Source Version',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'sourceversion',
+      'table' => 'analysis',
+      'field' => 'sourceversion',
+      'relationship' => 'none',
+    ),
+    'num_features' => array(
+      'label' => 'Number of Features',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'num_features',
+      'table' => 'analysis',
+      'field' => 'num_features',
+      'relationship' => 'none',
+    ),
+    'timeexecuted' => array(
+      'label' => 'Time Executed',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'date_format' => 'large',
+      'custom_date_format' => '',
+      'exclude' => 0,
+      'id' => 'timeexecuted',
+      'table' => 'analysis',
+      'field' => 'timeexecuted',
+      'relationship' => 'none',
+    ),
+  ));
+  $handler->override_option('filters', array(
+    'program' => array(
+      'operator' => '=',
+      'value' => 'All',
+      'group' => '0',
+      'exposed' => TRUE,
+      'expose' => array(
+        'use_operator' => 0,
+        'operator' => 'program_op',
+        'identifier' => 'program',
+        'label' => 'Program',
+        'optional' => 1,
+        'remember' => 0,
+      ),
+      'case' => 0,
+      'id' => 'program',
+      'table' => 'analysis',
+      'field' => 'program',
+      'relationship' => 'none',
+    ),
+    'sourcename' => array(
+      'operator' => 'contains',
+      'value' => '',
+      'group' => '0',
+      'exposed' => TRUE,
+      'expose' => array(
+        'use_operator' => 0,
+        'operator' => 'sourcename_op',
+        'identifier' => 'sourcename',
+        'label' => 'Source Name Contains',
+        'optional' => 1,
+        'remember' => 0,
+      ),
+      'case' => 0,
+      'id' => 'sourcename',
+      'table' => 'analysis',
+      'field' => 'sourcename',
+      'relationship' => 'none',
+    ),
+  ));
+  $handler->override_option('access', array(
+    'type' => 'perm',
+    'perm' => 'access chado_analysis content',
+  ));
+  $handler->override_option('cache', array(
+    'type' => 'none',
+  ));
+  $handler->override_option('title', 'Analysis');
+  $handler->override_option('empty', 'No analysis match the supplied criteria.');
+  $handler->override_option('empty_format', '1');
+  $handler->override_option('items_per_page', 50);
+  $handler->override_option('use_pager', '1');
+  $handler->override_option('style_plugin', 'table');
+  $handler->override_option('style_options', array(
+    'grouping' => '',
+    'override' => 1,
+    'sticky' => 0,
+    'order' => 'asc',
+    'columns' => array(
+      'algorithm' => 'algorithm',
+      'description' => 'description',
+      'name' => 'name',
+      'num_features' => 'num_features',
+      'program' => 'program',
+      'programversion' => 'programversion',
+      'sourcename' => 'sourcename',
+      'sourceuri' => 'sourceuri',
+      'sourceversion' => 'sourceversion',
+      'timeexecuted' => 'timeexecuted',
+    ),
+    'info' => array(
+      'algorithm' => array(
+        'sortable' => 1,
+        'separator' => '',
+      ),
+      'description' => array(
+        'sortable' => 1,
+        'separator' => '',
+      ),
+      'name' => array(
+        'sortable' => 1,
+        'separator' => '',
+      ),
+      'num_features' => array(
+        'separator' => '',
+      ),
+      'program' => array(
+        'sortable' => 1,
+        'separator' => '',
+      ),
+      'programversion' => array(
+        'sortable' => 1,
+        'separator' => '',
+      ),
+      'sourcename' => array(
+        'sortable' => 1,
+        'separator' => '',
+      ),
+      'sourceuri' => array(
+        'sortable' => 1,
+        'separator' => '',
+      ),
+      'sourceversion' => array(
+        'sortable' => 1,
+        'separator' => '',
+      ),
+      'timeexecuted' => array(
+        'sortable' => 1,
+        'separator' => '',
+      ),
+    ),
+    'default' => 'timeexecuted',
+  ));
+  $handler = $view->new_display('page', 'Page', 'page_1');
+  $handler->override_option('path', 'analyses');
+  $handler->override_option('menu', array(
+    'type' => 'normal',
+    'title' => 'Analyses',
+    'description' => '',
+    'weight' => '0',
+    'name' => 'primary-links',
+  ));
+  $handler->override_option('tab_options', array(
+    'type' => 'none',
+    'title' => '',
+    'description' => '',
+    'weight' => 0,
+    'name' => 'navigation',
+  ));
+  $views[$view->name] = $view;
+
+  return $views;
+}

+ 75 - 69
tripal_analysis/tripal_analysis_privacy.inc

@@ -1,82 +1,88 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /*
  *  Perform permission check by analysis_id only if 'node_privacy_byrole' module is enabled
  */
-function tripal_analysis_check_permission ($analysis_id) {
-	if (module_exists('node_privacy_byrole')) {
-		global $user;
-		$roles = $user->roles;
-		$node_access = 0;
-		foreach ($roles AS $rid => $role) {
-			$p_sql = "SELECT grant_view FROM {node_access} NA INNER JOIN {chado_analysis} CA ON NA.nid = CA.nid WHERE analysis_id=%d AND gid = %d";
-			$access = db_result(db_query($p_sql,$analysis_id, $rid));
-			if ($access == 1) {
-				$node_access = 1;
-				break;
-			}
-		}
-		if ($node_access == 1 || $user->uid == 1) {
-			return TRUE;
-		} else {
-			return FALSE;
-		}
-	
-	// If 'node_privacy_byrole' module is not enabled, return TRUE;
-	} else {
-		return TRUE;
-	}
+function tripal_analysis_check_permission($analysis_id) {
+  if (module_exists('node_privacy_byrole')) {
+    global $user;
+    $roles = $user->roles;
+    $node_access = 0;
+    foreach ($roles AS $rid => $role) {
+      $p_sql = "SELECT grant_view FROM {node_access} NA INNER JOIN {chado_analysis} CA ON NA.nid = CA.nid WHERE analysis_id=%d AND gid = %d";
+      $access = db_result(db_query($p_sql, $analysis_id, $rid));
+      if ($access == 1) {
+        $node_access = 1;
+        break;
+      }
+    }
+    if ($node_access == 1 || $user->uid == 1) {
+      return TRUE;
+    }
+    else {
+      return FALSE;
+    }
+
+  // If 'node_privacy_byrole' module is not enabled, return TRUE;
+  }
+  else {
+    return TRUE;
+  }
 }
 
 /*
  * Set permissions for features associated with an analysis
  */
-function tripal_analysis_set_feature_permission ($analysis_id, $nid) {
-	
-	print "Updating feature permissions:\n";
-	
-	// Get features associated with the analysis
-	$sql = "SELECT feature_id FROM {analysisfeature} WHERE analysis_id = %d";
-	$previous_db = db_set_active('chado');
-	$features = db_query($sql, $analysis_id);
-	db_set_active($previous_db);
-	
-	// Convert feature_id into node_id
-	$feature_nids = array ();
-	$counter = 0;
-	$sql = "SELECT nid FROM {chado_feature} WHERE feature_id = %d";
-	while ($feature = db_fetch_object($features)) {
-		$feature_nids [$counter] = db_result(db_query($sql, $feature->feature_id));
-		$counter ++;
-	}
-	
-	//Convert analysis_id into node_id
-	$ana_nid = db_result(db_query("SELECT nid FROM {chado_analysis} WHERE analysis_id = $analysis_id"));
-	// Get available roles
-	$roles = array_keys(user_roles());
-	
-	$interval = intval(($counter + 1) * 0.01);
-	$idx_iterations = 1;
-	
-	// Update permission node by node
-	foreach ($feature_nids AS $fnid) {
-		if ($idx_iterations % $interval == 0) {
-			$percentage = (int) ($idx_iterations / ($counter + 1) * 100);
-			tripal_job_set_progress($job_id, $percentage);
-			print $percentage."% ";
-		}
+function tripal_analysis_set_feature_permission($analysis_id, $nid) {
+
+  print "Updating feature permissions:\n";
+
+  // Get features associated with the analysis
+  $sql = "SELECT feature_id FROM {analysisfeature} WHERE analysis_id = %d";
+  $previous_db = db_set_active('chado');
+  $features = db_query($sql, $analysis_id);
+  db_set_active($previous_db);
+
+  // Convert feature_id into node_id
+  $feature_nids = array();
+  $counter = 0;
+  $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = %d";
+  while ($feature = db_fetch_object($features)) {
+    $feature_nids [$counter] = db_result(db_query($sql, $feature->feature_id));
+    $counter ++;
+  }
 
-		db_query("DELETE FROM {node_privacy_byrole} WHERE nid = %d AND realm = 'node_privacy_byrole_role'", $fnid);
-		foreach($roles AS $rid) {
-			// Get permissions of this analysis for this role
-			$rsql = "SELECT * FROM {node_privacy_byrole} WHERE gid = %d AND nid = %d AND realm = 'node_privacy_byrole_role'";
-			$ana_perm = db_fetch_object(db_query($rsql, $rid, $ana_nid));
-			db_query("INSERT INTO {node_privacy_byrole} (nid, gid, realm, grant_view, grant_update, grant_delete)
+  //Convert analysis_id into node_id
+  $ana_nid = db_result(db_query("SELECT nid FROM {chado_analysis} WHERE analysis_id = %analysis_id", $analysis_id));
+  // Get available roles
+  $roles = array_keys(user_roles());
+
+  $interval = intval(($counter + 1) * 0.01);
+  $idx_iterations = 1;
+
+  // Update permission node by node
+  foreach ($feature_nids AS $fnid) {
+    if ($idx_iterations % $interval == 0) {
+      $percentage = (int) ($idx_iterations / ($counter + 1) * 100);
+      tripal_job_set_progress($job_id, $percentage);
+      print $percentage . "% ";
+    }
+
+    db_query("DELETE FROM {node_privacy_byrole} WHERE nid = %d AND realm = 'node_privacy_byrole_role'", $fnid);
+    foreach ($roles AS $rid) {
+      // Get permissions of this analysis for this role
+      $rsql = "SELECT * FROM {node_privacy_byrole} WHERE gid = %d AND nid = %d AND realm = 'node_privacy_byrole_role'";
+      $ana_perm = db_fetch_object(db_query($rsql, $rid, $ana_nid));
+      db_query("INSERT INTO {node_privacy_byrole} (nid, gid, realm, grant_view, grant_update, grant_delete)
                   VALUES (%d, %d, '%s', %d, %d, %d)", $fnid, $rid, 'node_privacy_byrole_role', $ana_perm->grant_view,
                   $ana_perm->grant_update, $ana_perm->grant_delete);
-		}
-		$node = node_load($fnid);
-		node_save($node);
-		$idx_iterations ++;
-	}	
-}
+    }
+    $node = node_load($fnid);
+    node_save($node);
+    $idx_iterations ++;
+  }
+}

File diff suppressed because it is too large
+ 271 - 211
tripal_bulk_loader/tripal_bulk_loader.admin.inc


+ 2427 - 0
tripal_bulk_loader/tripal_bulk_loader.admin.inc.orig

@@ -0,0 +1,2427 @@
+<?php
+
+/**
+ * @file
+ * Handles Create/Edit/Delete Template Admin Forms
+ */
+
+/**
+ * Provides a description page and quick links for the bulk loader
+ */
+<<<<<<< HEAD
+function tripal_bulk_loader_admin_template() {
+  $output = '';
+
+  $output .= '<br><h3>Quick Links:</h3>';
+  $output .= l('Create a new bulk loader template', 'admin/tripal/tripal_bulk_loader_template/create') . "<br>";
+  $output .= l('Edit a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/edit') . "<br>";
+  $output .= l('Delete a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/delete') . "<br>";
+  $output .= l('Export a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/export') . "<br>";
+  $output .= l('Import a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/import') . "<br>";
+=======
+function tripal_bulk_loader_admin_template () {
+	$output = '';
+
+	$output .= '<br><h3>Quick Links:</h3>';
+  $output .= l('Create a new bulk loader template', 'admin/tripal/tripal_bulk_loader_template/create')."<br>";
+  $output .= l('Edit a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/edit')."<br>";
+  $output .= l('Delete a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/delete')."<br>";
+  $output .= l('Export a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/export')."<br>";
+  $output .= l('Import a bulk loader template', 'admin/tripal/tripal_bulk_loader_template/import')."<br>";
+>>>>>>> 6.x-0.4-dev
+  $output .= '<br>';
+
+  $output .= '<h3>Module Description:</h3>';
+  $output .= '<p>This module provides the ability to create loading templates for any tab-delimited '
+    . 'data file allowing it to be loaded into chado. The Loading Templates are a direct mapping '
+    . 'between the columns in your file and the columns in chado tables. As such to use this tool '
+    . 'you need to be very familar with the chado schema -See '
+    . l('Chado -Getting Started', 'http://gmod.org/wiki/Chado_-_Getting_Started')
+    . '. The ability to add constants and specify foreign key contraints is also provided '
+    . 'in order for the loader to fill chado columns which may be required but are not specified '
+    . 'in your input file.</p>';
+  $output .= '<br>';
+
+  $output .= '<h3>Setup Instructions</h3>';
+  $output .= '<p>After intallation of the bulk loader module, the following tasks should be performed:</p>';
+  $output .= '<ol>';
+  $output .= '<li><b>Install Theme:</b> In order for Bulk Loading pages to be displayed correctly, '
+    .'the contents of the Tripal Bulk Loader theme directory ([drupal root]/sites/all/modules/tripal/tripal_bulk_loader/theme) '
+    .'should be moved to the base directory of the Tripal theme ([drupal root]/sites/all/themes/tripal). '
+    .'Finally the drupal cache should be cleared for the new theme to take effect -navigate to admin/settings/performance '
+    .'and click the Clear Cached Data button.</li>';
+  $output .= '</ol>';
+
+  return $output;
+}
+
+/**
+ * A Configuration form for this module
+ */
+function tripal_bulk_loader_configuration_form($form_state = NULL) {
+  $form = array();
+
+  $form['speed'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Possible Speed Improvements'),
+  );
+
+  $form['speed']['prepare'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Use Prepared Statements'),
+    '#description' => t('SQL Prepared Statements allow for SQL queries which will be run '
+      .'many times to be parsed, rewritten and planned only once rather then every time '
+      .'the query is run. In the case of the bulk loader, this ensures that planning only '
+      .'occurs once for each "record" in your bulk loading template.'),
+    '#default_value' => variable_get('tripal_bulk_loader_prepare', TRUE),
+  );
+
+  $form['submit1'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save')
+  );
+
+  return $form;
+}
+
+/**
+ * A Configuration form for this module (Submit)
+ */
+function tripal_bulk_loader_configuration_form_submit($form, $form_state) {
+
+  variable_set('tripal_bulk_loader_prepare', $form_state['values']['prepare']);
+}
+
+//////////////////////////////////////////////////////////////////////////////////////
+// Modify Template
+//////////////////////////////////////////////////////////////////////////////////////
+
+
+/**
+ * The main form reached at admin/tripal/tripal_bulk_loader/create and /edit
+ */
+function tripal_bulk_loader_modify_template_base_form($form_state = NULL, $mode) {
+  $form = array();
+
+   // get template id from path and rebuild form
+   if ($_GET['template_id']) {
+    if (preg_match('/^\d+$/', $_GET['template_id'])) {
+      $form_state['storage']['template_id'] = $_GET['template_id'];
+    }
+
+    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+    $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
+    $form_state['storage']['template'] = unserialize($result->template_array);
+    $form_state['storage']['template_name'] = $result->name;
+
+    $form_state['storage']['record2priority'] = array();
+    foreach ($form_state['storage']['template'] as $priority => $record_array) {
+      if (!is_array($record_array)) {
+      continue; }
+      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
+    }
+  }
+
+  $form['mode'] = array(
+    '#type' => 'hidden',
+    '#value' => $mode,
+  );
+
+  if ($form_state['storage']['template_id']) {
+    $form['template_name'] = array(
+        '#type' => 'item',
+        '#title' => 'Template',
+        '#value' => $form_state['storage']['template_name'],
+        '#weight' => 1,
+    );
+  }
+  else {
+    if (preg_match('/create/', $mode)) {
+     $form['new_template_name'] = array(
+        '#type' => 'textfield',
+        '#title' => 'Template Name',
+        '#weight' => 1,
+      );
+    }
+    elseif (preg_match('/edit/', $mode)) {
+      $sql = "SELECT * FROM {tripal_bulk_loader_template}";
+      $resource = db_query($sql);
+      $templates = array();
+      $templates[''] = 'Select a Template';
+      while ($r = db_fetch_object($resource)) {
+        $templates[$r->template_id] = $r->name;
+      }
+
+      $form['template_id'] = array(
+        '#title'         => t('Template'),
+        '#description'   => t('Please select the template you would like to edit.'),
+        '#type'          => 'select',
+        '#options'       => $templates,
+        '#default_value' => $form_state['storage']['template_id'],
+        '#weight'        => 0,
+        '#required'      => TRUE,
+        '#weight' => 1,
+      );
+    }
+  }
+
+  $form['records'] = array(
+<<<<<<< HEAD
+    '#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
+    '#title' => t('Current Records'),
+    '#collapsible' => TRUE,
+    '#weight' => 2,
+=======
+		'#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
+		'#title' => t('Current Records'),
+		'#collapsible' => TRUE,
+		'#weight' => 2,
+>>>>>>> 6.x-0.4-dev
+  );
+
+  $form['records']['description'] = array(
+    '#type' => 'item',
+    '#value' => 'Records will be inserted into the chado database in the order listed below. To '
+      .'change this order: <ul><li>Drag the rows into the correct order OR</li><li>Enter '
+      .'the numbers 1 and up in the Order textboxes to indicate the correct order.</li></ul>',
+  );
+
+  $form['records']['records-data'] = array(
+    '#tree' => TRUE,
+  );
+
+  $form['records']['no_records'] = array(
+    '#type' => 'hidden',
+    '#value' => TRUE,
+  );
+
+  $form['records']['submit-new_record'] = array(
+    '#type' => 'submit',
+    '#value' => 'New Record/Field',
+  );
+
+  $form['records']['submit-reorder'] = array(
+    '#type' => 'submit',
+    '#value' => 'Save Order',
+  );
+
+<<<<<<< HEAD
+  $form['fields'] = array(
+    '#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
+    '#title' => t('Current Fields'),
+    '#collapsible' => TRUE,
+    '#weight' => 3,
+  );
+=======
+	$form['fields'] = array(
+		'#type' => ($form_state['storage']['template_id'])? 'fieldset' : 'hidden',
+		'#title' => t('Current Fields'),
+		'#collapsible' => TRUE,
+		'#weight' => 3,
+	);
+>>>>>>> 6.x-0.4-dev
+
+  $form['fields']['fields-data'] = array(
+    '#tree' => TRUE,
+  );
+
+<<<<<<< HEAD
+  if ($form_state['storage']['template']) {
+=======
+	if ($form_state['storage']['template']) {
+>>>>>>> 6.x-0.4-dev
+
+    // List Current Fields -------------------------------------------------------------
+    $i=1;
+    foreach ($form_state['storage']['template'] as $priority => $table_array) {
+<<<<<<< HEAD
+      if (!is_array($table_array)) {
+      continue; }
+=======
+      if (!is_array($table_array)) { continue; }
+>>>>>>> 6.x-0.4-dev
+
+        $form['records']['no_records']['#value'] = FALSE;
+
+        $form['records']['records-data'][$priority] = array(
+          'title' => array(
+            '#type' => 'markup',
+            '#value' => $table_array['record_id'],
+          ),
+          'chado_table' => array(
+            '#type' => 'markup',
+            '#value' => $table_array['table'],
+          ),
+          'mode' => array(
+            '#type' => 'item',
+            '#value' => ($table_array['mode']) ? $table_array['mode'] : 'insert_unique',
+          ),
+          'new_priority' => array(
+            '#type' => 'select',
+            '#options' => range(1, sizeof($form_state['storage']['template'])),
+            '#default_value' => $priority,
+          ),
+          'old_priority' => array(
+            '#type' => 'hidden',
+            '#value' => $priority,
+          ),
+          'id'  => array(
+            '#type' => 'hidden',
+            '#value' => $priority,
+          ),
+          'submit-edit_record' => array(
+            '#type' => 'submit',
+            '#name' => (string)$priority,
+            '#value' => 'Edit Record',
+          ),
+          'submit-add_field' => array(
+            '#type' => 'submit',
+            '#name' => (string)$priority,
+            '#value' => 'Add Field',
+          ),
+          'submit-duplicate_record' => array(
+            '#type' => 'submit',
+            '#name' => (string)$priority,
+            '#value' => 'Duplicate Record'
+          ),
+        );
+
+        foreach ($table_array['fields'] as $field_index => $field) {
+
+          $form['fields']['fields-data'][$i] = array(
+            'record_id' => array(
+              '#type' => 'item',
+              '#value' => $table_array['record_id'],
+            ),
+            'priority_hidden' => array(
+              '#type' => 'hidden',
+              '#value' => $priority,
+            ),
+            'field_name' => array(
+              '#type' => 'item',
+              '#value' => $field['title'],
+            ),
+            'chado_table_name' => array(
+              '#type' => 'item',
+              '#value' => $table_array['table'],
+            ),
+            'chado_table_hidden' => array(
+              '#type' => 'hidden',
+              '#value' => $table_array['table'],
+            ),
+            'chado_field_name' => array(
+              '#type' => 'item',
+              '#value' => $field['field'],
+            ),
+            'sheet_name' => array(
+              '#type' => 'item',
+              '#value' => $field['spreadsheet sheet'],
+            ),
+            'column_num' => array(
+              '#type' => 'item',
+              '#value' => $field['spreadsheet column'],
+            ),
+            'constant_value' => array(
+              '#type' => 'item',
+              '#value' => $field['constant value'],
+            ),
+            'field_index' => array(
+              '#type' => 'hidden',
+              '#value' => $field_index
+            ),
+            'foreign_record_id' => array(
+              '#type' => 'item',
+              '#value' => $field['foreign key'],
+            ),
+            'edit_submit' => array(
+              '#type' => 'submit',
+              '#name' => (string)$i,
+              '#value' => "Edit Field",
+            ),
+            'delete_submit' => array(
+              '#type' => 'submit',
+              '#name' => (string)$i,
+              '#value' => "Delete Field",
+            ),
+          );
+
+          $i++;
+        }
+    }
+    $form['fields']['total_fields'] = array(
+      '#type' => 'item',
+      '#value' => $i,
+    );
+
+  }
+
+  if ($form['records']['no_records']['#value']) {
+    $form['records']['description'] = array(
+      '#type' => 'item',
+      '#value' => 'There are currently no records.',
+    );
+    unset($form['records']['submit-reorder']);
+
+    $form['fields']['description'] = array(
+      '#type' => 'item',
+      '#value' => 'There are currently no fields.',
+    );
+
+  }
+
+<<<<<<< HEAD
+  $mode_title = (preg_match('/create/', $mode)) ? 'Create Template' : 'Edit Template';
+  $value = ($form_state['storage']['template_id'])? 'Save Template' : $mode_title;
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => $value,
+    '#weight' => 4,
+  );
+  return $form;
+=======
+  $mode_title = (preg_match('/create/',$mode)) ? 'Create Template' : 'Edit Template';
+	$value = ($form_state['storage']['template_id'])? 'Save Template' : $mode_title;
+	$form['submit'] = array(
+		'#type' => 'submit',
+		'#value' => $value,
+		'#weight' => 4,
+	);
+
+	return $form;
+>>>>>>> 6.x-0.4-dev
+}
+
+/**
+ * Submit for tripal_bulk_loader_modify_template_base_form
+ */
+function tripal_bulk_loader_modify_template_base_form_submit($form, &$form_state) {
+
+  $form_state['rebuild'] = TRUE;
+  if ($form_state['storage']['template_id']) {
+    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+    $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
+    $form_state['storage']['template'] = unserialize($result->template_array);
+  }
+
+  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
+  switch ($op) {
+    // Initialize after template is chosen ----------------------------------------
+    case 'Edit Template':
+      $form_state['storage']['template_id'] = $form_state['values']['template_id'];
+
+      $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+      $result = db_fetch_object(db_query($sql, $form_state['storage']['template_id']));
+      $form_state['storage']['template'] = unserialize($result->template_array);
+      $form_state['storage']['template_name'] = $result->name;
+
+      $form_state['storage']['record2priority'] = array();
+      foreach ($form_state['storage']['template'] as $priority => $record_array) {
+        if (!is_array($record_array)) {
+         continue;
+         }
+        $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
+      }
+    break;
+
+    case 'Create Template':
+      $record = array(
+        'name' => $form_state['values']['new_template_name'],
+        'template_array' => array(),
+      );
+      drupal_write_record('tripal_bulk_loader_template', $record);
+      $form_state['storage']['template_id'] = $record['template_id'];
+      $form_state['storage']['template_name'] = $record['name'];
+      $form_state['storage']['template'] = array();
+    break;
+
+    // Save Reordered Records -----------------------------------------------------
+    case 'Save Order':
+      $new_template = $form_state['storage']['template'];
+      // unset old elements
+       $form_state['storage']['record2priority'] = array();
+      foreach ($new_template as $priority => $record_array) {
+<<<<<<< HEAD
+        if (preg_match('/\d+/', $priority)) {
+           unset($new_template[$priority]);
+         }
+=======
+        if (preg_match('/\d+/', $priority)) { unset($new_template[$priority]); }
+>>>>>>> 6.x-0.4-dev
+      }
+      //set elements in new order
+      foreach ($form_state['values']['records-data'] as $item) {
+        $new_template[$item['new_priority']] = $form_state['storage']['template'][$item['old_priority']];
+        $record_name = $new_template[$item['new_priority']]['record_id'];
+        $form_state['storage']['record2priority'][$record_name] = $item['new_priority'];
+      }
+      ksort($new_template);
+      $form_state['storage']['template'] = $new_template;
+    break;
+
+    case 'New Record/Field':
+      $query = array(
+<<<<<<< HEAD
+        'template_id' => $form_state['storage']['template_id'],
+=======
+        'template_id'=> $form_state['storage']['template_id'],
+>>>>>>> 6.x-0.4-dev
+        'record_id' => 'NEW',
+      );
+      drupal_goto('admin/tripal/tripal_bulk_loader_template/add_field', $query);
+    break;
+
+    case 'Edit Record':
+      $query = array(
+<<<<<<< HEAD
+        'template_id' => $form_state['storage']['template_id'],
+=======
+        'template_id'=> $form_state['storage']['template_id'],
+>>>>>>> 6.x-0.4-dev
+        'record_id' => $form_state['clicked_button']['#name'],
+      );
+      drupal_goto('admin/tripal/tripal_bulk_loader_template/edit_record', $query);
+    break;
+
+    case 'Add Field':
+      $query = array(
+<<<<<<< HEAD
+        'template_id' => $form_state['storage']['template_id'],
+=======
+        'template_id'=> $form_state['storage']['template_id'],
+>>>>>>> 6.x-0.4-dev
+        'record_id' => $form_state['clicked_button']['#name'],
+      );
+      drupal_goto('admin/tripal/tripal_bulk_loader_template/add_field', $query);
+    break;
+
+    case 'Duplicate Record':
+      // original record (one to be duplicated)
+      $orig_priority = $form_state['clicked_button']['#name'];
+      $record = $form_state['storage']['template'][ $orig_priority ];
+
+      // new record
+      $new_priority = sizeof($form_state['storage']['template']) + 1;
+      $record['record_id'] = $record['record_id'] . '_' . date('YzHi');
+      $form_state['storage']['template'][ $new_priority ] = $record;
+    break;
+
+    case 'Edit Field':
+      $field_data_index = $form_state['clicked_button']['#name'];
+      $query = array(
+<<<<<<< HEAD
+        'template_id' => $form_state['storage']['template_id'],
+=======
+        'template_id'=> $form_state['storage']['template_id'],
+>>>>>>> 6.x-0.4-dev
+        'record_id' => $form_state['values']['fields-data'][$field_data_index]['priority_hidden'],
+        'field_index' => $form_state['values']['fields-data'][$field_data_index]['field_index'],
+      );
+      drupal_goto('admin/tripal/tripal_bulk_loader_template/edit_field', $query);
+    break;
+
+    case 'Delete Field':
+      $field_data = $form_state['values']['fields-data'][$form_state['clicked_button']['#name']];
+      $priority = $field_data['priority_hidden'];
+      $field_key = $field_data['field_index'];
+      unset($form_state['storage']['template'][$priority]['fields'][$field_key]);
+      if (!$form_state['storage']['template'][$priority]['fields']) {
+        unset($form_state['storage']['record2priority'][$form_state['storage']['template'][$priority]['record_id']]);
+        unset($form_state['storage']['template'][$priority]);
+      }
+      drupal_set_message('Deleted Field from Template.');
+    break;
+  } //end of switch
+
+  // Save Template
+  $record = array(
+    'template_id' => $form_state['storage']['template_id'],
+    'template_array' => serialize($form_state['storage']['template'])
+  );
+  drupal_write_record('tripal_bulk_loader_template', $record, array('template_id'));
+  drupal_set_message('Template Saved.');
+
+}
+
+//////////////////////////////////////////////////////////////////////////////////////
+// Delete Template
+//////////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * Delete Template Form
+ * This form allows admin to delete already existing templates
+ */
+function tripal_bulk_loader_delete_template_base_form() {
+  $form = array();
+
+  $sql = "SELECT * FROM {tripal_bulk_loader_template}";
+  $resource = db_query($sql);
+  $templates = array();
+  $templates[''] = 'Select a Template';
+  while ($r = db_fetch_object($resource)) {
+    $templates[$r->template_id] = $r->name;
+  }
+  $form['template_name'] = array(
+      '#title'         => t('Template'),
+      '#description'   => t('Please select the template you would like to delete.'),
+      '#type'          => 'select',
+      '#options'       => $templates,
+      '#weight'        => 0,
+      '#required'      => TRUE,
+<<<<<<< HEAD
+  );
+
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => 'Delete Template',
+  );
+
+  return $form;
+=======
+	);
+
+	$form['submit'] = array(
+		'#type' => 'submit',
+		'#value' => 'Delete Template',
+	);
+
+	return $form;
+>>>>>>> 6.x-0.4-dev
+}
+
+/**
+ * Delete Template Form Submit
+ *
+ * @param $form
+ *   The form that was submitted
+ * @param $form_state
+ *   The values and storage that were submitted
+ */
+function tripal_bulk_loader_delete_template_base_form_submit($form, &$form_state) {
+  $sql = "DELETE FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+  db_query($sql, $form_state['values']['template_name']);
+}
+
+//////////////////////////////////////////////////////////////////////////////////////
+// Import/Export Template
+//////////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * Import/Export Template Form
+ *
+ * On export, simply selects the serialized array from the db for a given template
+ * and presents it to the user. On import, a serialized template array and a name is
+ * supplied and a template record is created.
+ *
+ * @todo Make array presented to the user more readable. (ie: unserialize and print to the screen)
+ *
+ * @param $form_state
+ *   The values and storage for the form
+ * @param $mode
+ *   Either 'import' or 'export' to indicate which function is being performed
+ * @return
+ *   A form array to be rendered by drupal_get_form
+ */
+function tripal_bulk_loader_import_export_template_form($form_state = NULL, $mode) {
+  $form = array();
+
+  $form['mode'] = array(
+    '#type' => 'hidden',
+    '#value' => $mode,
+  );
+
+  if (preg_match('/import/', $mode)) {
+   $form['new_template_name'] = array(
+      '#type' => 'textfield',
+      '#title' => 'Template Name',
+      '#weight' => 1,
+    );
+  }
+  elseif (preg_match('/export/', $mode)) {
+    $sql = "SELECT * FROM {tripal_bulk_loader_template}";
+    $resource = db_query($sql);
+    $templates = array();
+    $templates[''] = 'Select a Template';
+    while ($r = db_fetch_object($resource)) {
+      $templates[$r->template_id] = $r->name;
+    }
+
+    $form['template_id'] = array(
+      '#title'         => t('Template'),
+      '#description'   => t('Please select the template you would like to edit.'),
+      '#type'          => 'select',
+      '#options'       => $templates,
+      '#default_value' => $form_state['storage']['template_id'],
+      '#weight'        => 0,
+      '#required'      => TRUE,
+      '#weight' => 1,
+    );
+  }
+
+  $form['template_array'] = array(
+    '#type' => 'textarea',
+    '#title' => 'Template Array',
+    '#default_value' => $form_state['storage']['template_array'],
+    '#weight' => 2,
+  );
+
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => 'Submit',
+    '#weight' => 10,
+  );
+
+  return $form;
+}
+
+/**
+ * Import/Export Template Form Submit
+ *
+ * @param $form
+ *   The form that was submitted
+ * @param $form_state
+ *   The values and storage that were submitted
+ */
+function tripal_bulk_loader_import_export_template_form_submit($form, &$form_state) {
+  switch ($form_state['values']['mode']) {
+    case 'export':
+      $record = db_fetch_object(db_query("SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d", $form_state['values']['template_id']));
+      $form_state['storage']['template_array'] = $record->template_array;
+      $form_state['storage']['template_id'] = $form_state['values']['template_id'];
+    break;
+    case 'import':
+      $record = array(
+        'name' => $form_state['values']['new_template_name'],
+        'template_array' => $form_state['values']['template_array'],
+      );
+      drupal_write_record('tripal_bulk_loader_template', $record);
+      if ($record->template_id) {
+        drupal_set_message('Successfully imported Tripal Bulk Loader Template.');
+      }
+    break;
+  }
+}
+
+//////////////////////////////////////////////////////////////////////////////////////
+// Edit Record Form
+//////////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * Edit Record Form
+ *
+ * This form is meant to be called from a bulk loader form. The following should be set
+ * in the query section of the path:
+ *  - template_id=\d+: the template which the edited record is part of
+ *  - record_id=\d+: the priority or key in the template array of the record to be edited
+ *
+ * @param $form_state
+ *   Contains the values and storage for the form
+ * @return
+ *   A form array to be rendered by drupal_get_form
+ */
+<<<<<<< HEAD
+function tripal_bulk_loader_edit_template_record_form(&$form_state = NULL) {
+   $form['#cache'] = TRUE; // Make sure the form is cached.
+
+   // get template id from path
+   $template_id = ($_GET['template_id'] !== NULL) ? $_GET['template_id'] : $form_state['values']['template_id'];
+
+   // if there is no template supplied don't return rest of form
+   if (!$template_id) {
+     return $form;
+   }
+=======
+function tripal_bulk_loader_edit_template_record_form (&$form_state = NULL) {
+ 	$form['#cache'] = TRUE; // Make sure the form is cached.
+
+ 	// get template id from path
+ 	$template_id = ($_GET['template_id'] !== NULL) ? $_GET['template_id'] : $form_state['values']['template_id'];
+
+ 	// if there is no template supplied don't return rest of form
+ 	if (!$template_id) {
+ 	  return $form;
+ 	}
+>>>>>>> 6.x-0.4-dev
+
+  // Pre-process values/defaults ---------------------------
+
+   // If this is the first load of the form (no form state) we need to initialize some variables
+   if (!$form_state['storage']['template']) {
+    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+    $template = db_fetch_object(db_query($sql, $template_id));
+    $form_state['storage']['template_array'] = unserialize($template->template_array);
+    $form_state['storage']['template'] = $template;
+
+    $form_state['storage']['record2priority'] = array();
+    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
+      if (!is_array($record_array)) {
+         continue;
+       }
+      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
+    }
+
+    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
+  }
+  else {
+    $template = $form_state['storage']['template'];
+  }
+
+   // get the record_id from the path
+   if ($_GET['record_id'] !== NULL) {
+     $form_state['values']['field_group'] = $_GET['record_id'];
+     $form_state['storage']['original_priority'] = $_GET['record_id'];
+  }
+
+
+  // Tables and default table
+  $tables = tripal_core_get_chado_tables();
+  if ($form_state['values']['chado_table']) {
+    $table = $form_state['values']['chado_table'];
+<<<<<<< HEAD
+  }
+  else {
+=======
+  } else {
+>>>>>>> 6.x-0.4-dev
+    $table = $form_state['storage']['template_array'][$form_state['storage']['original_priority']]['table'];
+  }
+
+  //dpm($form_state, 'form state');
+
+<<<<<<< HEAD
+   // Form Proper -------------------------------------------
+=======
+ 	// Form Proper -------------------------------------------
+>>>>>>> 6.x-0.4-dev
+  $form['template_name'] = array(
+    '#type' => 'item',
+    '#title' => 'Template',
+    '#value' => $template->name,
+  );
+
+  $form['template_id'] = array(
+    '#type' => 'hidden',
+    '#value' => $template_id,
+  );
+
+  $form['edit_record'] = array(
+    '#type' => 'fieldset',
+  );
+
+  // check template array for records then add one more
+  if (!$form_state['storage']['record2priority']) {
+    $groups = array();
+  }
+  else {
+    $groups = array_flip($form_state['storage']['record2priority']);
+  }
+  $priority_default = $form_state['values']['field_group'];
+  $form['edit_record']['field_group']  = array(
+    '#type' => 'select',
+    '#title' => 'Record',
+    '#description' => 'By Changing the record here, you can move all the fields from the current record into the selected record.',
+    '#options' => $groups,
+    '#default_value' => $priority_default,
+    '#required' => TRUE,
+  );
+
+  $form['edit_record']['record_name'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Unique Record Name',
+    '#default_value' => $groups[$priority_default],
+  );
+
+  $form['edit_record']['chado_table'] = array(
+    '#type' => 'select',
+    '#title' => t('Chado Table'),
+    '#description' => 'This changes the chado table for all fields in this record.',
+    '#options' => $tables,
+    '#default_value' => $table,
+  );
+
+  $form['edit_record']['mode'] = array(
+    '#type' => 'radios',
+    '#title' => 'Action to take when Loading Record',
+    '#options' => array(
+      'select' => 'SELECT: Don\'t insert this record: it\'s used to define a foreign key in another record',
+      'insert' => 'INSERT: Insert the record',
+      'optional' => 'OPTIONAL: Record will only be inserted if all required data is filled in',
+      'insert_once' => 'INSERT ONCE: Record will be inserted once for the entire spreadsheet',
+      'insert_unique' => 'INSERT UNIQUE: Only insert record if there isn\'t a record with the same values',
+    ),
+    '#default_value' => 'insert_unique'
+  );
+
+  $form['edit_record']['submit-edit_record'] = array(
+      '#type' => 'submit',
+      '#value' => 'Edit Record'
+  );
+
+  $form['edit_record']['submit-cancel'] = array(
+      '#type' => 'submit',
+      '#value' => 'Cancel'
+  );
+
+  return $form;
+}
+
+
+/**
+ * Edit Record Form Submit
+ *
+ * @param $form
+ *   The form that was submitted
+ * @param $form_state
+ *   Contains the values and storage for the form
+ */
+function tripal_bulk_loader_edit_template_record_form_submit($form, &$form_state) {
+  //dpm($form_state, 'form state -start submit');
+
+  if (!$form_state['ahah_submission']) {
+    if ($form_state['values']['op'] ==  'Edit Record') {
+
+      $template = $form_state['storage']['template_array'];
+
+      // Edit Record
+      $record = $template[ $form_state['storage']['original_priority'] ];
+      $record['record_id'] = $form_state['values']['record_name'];
+      $record['mode'] = $form_state['values']['mode'];
+      $record['table'] = $form_state['values']['chado_table'];
+
+      if ($form_state['storage']['original_priority'] != $form_state['values']['field_group']) {
+        $record['fields'] = array_merge($record['fields'], $template[ $form_state['values']['field_group'] ]['fields']);
+        $template[ $form_state['values']['field_group'] ] = $record;
+        unset($template[ $form_state['storage']['original_priority'] ]);
+      }
+      else {
+        $template[ $form_state['storage']['original_priority'] ] = $record;
+      }
+
+      // Save Template
+      $form_state['storage']['template']->template_array = serialize($template);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message('Successfully Updated Template Record');
+        drupal_set_message('Template Saved.');
+
+<<<<<<< HEAD
+        $path = explode('?', $form_state['storage']['referring URL']);
+=======
+        $path = explode('?',$form_state['storage']['referring URL']);
+>>>>>>> 6.x-0.4-dev
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        drupal_goto($path[0], $query);
+      }
+      else {
+        drupal_set_message('Unable to Save Template!', 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+    }
+    elseif ($form_state['values']['op'] ==  'Cancel') {
+        $path = explode('?', $form_state['storage']['referring URL']);
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        //dpm('Redirecting to: '.$path[0].'?'.print_r($query,TRUE).' where the referring URL:'.$form_state['storage']['referring URL']);
+        drupal_goto($path[0], $query);
+    }
+  }
+
+}
+
+//////////////////////////////////////////////////////////////////////////////////////
+// Add/Edit Field Forms
+//////////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * Add Field Form
+ *
+ * This form is meant to be called from a bulk loader form. Blank Defaults are in place but you
+ * can use the following in the query of the path to set defaults for a given template:
+ *  - template_id=\d+: the template to add the field to
+ *  - record_id=\d+: the priority or key in the template array of the record to add the field to
+ *
+ * @param $form_state
+ *   Contains the values and storage for the form
+ * @return
+ *   A form array to be rendered by drupal_get_form
+ */
+function tripal_bulk_loader_add_template_field_form(&$form_state = NULL) {
+  $form = array();
+<<<<<<< HEAD
+   $form['#cache'] = TRUE; // Make sure the form is cached.
+
+   // get template id from path
+   $template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
+
+   // if there is no template supplied don't return rest of form
+   if (!$template_id) {
+     return $form;
+   }
+=======
+ 	$form['#cache'] = TRUE; // Make sure the form is cached.
+
+ 	// get template id from path
+ 	$template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
+
+ 	// if there is no template supplied don't return rest of form
+ 	if (!$template_id) {
+ 	  return $form;
+ 	}
+>>>>>>> 6.x-0.4-dev
+
+  // Pre-set Variables needed for form proper------------------------------------------
+
+   // If this is the first load of the form (no form state) we need to initialize some variables
+   if (!$form_state['storage']['template']) {
+    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+    $template = db_fetch_object(db_query($sql, $template_id));
+    $form_state['storage']['template_array'] = unserialize($template->template_array);
+    $form_state['storage']['template'] = $template;
+
+    $form_state['storage']['record2priority'] = array();
+    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
+      if (!is_array($record_array)) {
+        continue;
+      }
+      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
+    }
+
+    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
+  }
+  else {
+    $template = $form_state['storage']['template'];
+  }
+
+  $field_type = ($form_state['values']['field_type'])? $form_state['values']['field_type'] : 'table field';
+
+  // Tables and default table
+  $tables = tripal_core_get_chado_tables();
+  if ($form_state['values']) {
+    if (!preg_match('/^' . current($tables) . '$/', $form_state['values']['chado_table'])) {
+      $table = $form_state['values']['chado_table'];
+    }
+    elseif ($form_state['values']['record_name']) {
+      $record_name = $form_state['values']['record_name'];
+      $priority = $form_state['storage']['record2priority'][$record_name];
+      $table = $form_state['storage']['template_array'][$priority]['table'];
+    }
+    else {
+      $priority = $form_state['values']['field_group'];
+      $table = $form_state['storage']['template_array'][$priority]['table'];
+    }
+  }
+  if (!$table) {
+    $table = reset($tables);
+  }
+
+   // get the record_id from the path
+   if ($_GET['record_id'] !== NULL) {
+     $form_state['values']['field_group'] = $_GET['record_id'];
+    if (preg_match('/\d+/', $_GET['record_id'])) {
+      $priority = $form_state['values']['field_group'];
+      $table = $form_state['storage']['template_array'][$priority]['table'];
+    }
+  }
+
+  // Fields and foreign key mappings
+  $chado_fields = array();
+  $fk_options = array();
+  $fk_options['NULL'] = 'None';
+  $table_description = module_invoke_all('chado_' . $table . '_schema');
+  //dpm($table_description, 'table description for |'.$table.'|');
+  if ($field_type == 'foreign key') {
+    $foreign_field2table = array();
+    foreach ($table_description['foreign keys'] as $key_table => $key_array) {
+      foreach ($key_array['columns'] as $left_field => $right_field) {
+        $chado_fields[$left_field] = $left_field;
+        $foreign_field2table[$left_field] = $key_table;
+      }
+    }
+    reset($chado_fields);
+
+    // set default field
+    if (empty($chado_fields)) {
+      $field = NULL;
+    }
+    elseif ($chado_fields[$form_state['values']['chado_field']]) {
+      $field = $form_state['values']['chado_field'];
+    }
+    else {
+      $field = current($chado_fields);
+    }
+
+    // Foreign key options
+    $foreign_table = $foreign_field2table[$field];
+    if ($foreign_table) {
+      foreach ($form_state['storage']['record2priority'] as $record_name => $priority ) {
+        if (preg_match('/^' . $foreign_table . '$/', $form_state['storage']['template_array'][$priority]['table'])) {
+          $fk_options[$record_name] = $record_name;
+        }
+      }
+    }
+  }
+  else {
+    foreach ($table_description['fields'] as $field_name => $field_array) {
+        $chado_fields[$field_name] = $field_name;
+    }
+  }
+
+  $variables = array(
+    'form_state' => $form_state,
+    'tables' => $tables,
+    'default table' => $table,
+    'fields' => $chado_fields,
+    'default_field' => $field,
+    'priority' => $priority,
+    'record_name' => $record_name,
+    'table description' => $table_description,
+    'foreign key options' => $fk_options,
+    'foreign field=>table' => $foreign_field2table,
+    'foreign table' => $foreign_table,
+  );
+  //dpm($variables, 'variables');
+
+  // Start of Form Proper--------------------------------------------------------------
+  //dpm($form_state, 'Form State');
+
+  $form['template_name'] = array(
+    '#type' => 'item',
+    '#title' => 'Template',
+    '#value' => $template->name,
+  );
+
+  $form['template_id'] = array(
+    '#type' => 'hidden',
+    '#value' => $template_id,
+  );
+
+  $form['add_fields'] = array(
+    '#type' => 'fieldset',
+    '#prefix' => '<div id="tripal_bulk_loader_template-add_field">',
+    '#suffix' => '</div>',
+  );
+
+  $form['add_fields']['field_type'] = array(
+    '#type' => 'radios',
+    '#title' => t('Type of Field'),
+    '#options' => array(
+      'table field' => t('Spreadsheet: Fields which maps to a Spreadsheet Column'),
+      'constant' => t('Constant: Field which remains Constant throughout the Spreadsheet'),
+      'foreign key' => t('Foreign Key: Fields which map to a record in another table'),
+    ),
+    '#required' => TRUE,
+    '#default_value' => $field_type,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-add_field',
+      'effect' => 'fade'
+    ),
+  );
+
+  // check template array for records then add one more
+  if (!$form_state['storage']['record2priority']) {
+    $groups = array();
+  }
+  else {
+    $groups = array_flip($form_state['storage']['record2priority']);
+  }
+  $groups['NONE'] = 'Select a Record';
+  $groups['NEW'] = 'New Record';
+  $form['add_fields']['field_group']  = array(
+    '#type' => 'select',
+    '#title' => 'Record',
+    '#description' => 'This is used to group a set of fields together allowing '
+      .'multiple records to be inserted into the same table per line of the spreadsheet',
+    '#options' => $groups,
+    '#default_value' => (preg_match('/\w+.*/', $form_state['values']['field_group'])) ? $form_state['values']['field_group'] : 'NONE',
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-add_field',
+      'effect' => 'fade'
+    ),
+    '#required' => TRUE,
+  );
+
+  $form['add_fields']['record_name'] = array(
+    '#type' => (preg_match('/NEW/', $form_state['values']['field_group'])) ? 'textfield' : 'hidden',
+    '#title' => 'Unique Record Name',
+    '#prefix' => '<div id="tripal_bulk_loader_template-add_record">',
+    '#suffix' => '</div>',
+    '#default_value' => $form_state['values']['record_name'],
+  );
+
+  $form['add_fields']['field_title'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Human-readable Title for Field'),
+    '#default_value' => $form_state['values']['field_title'],
+  );
+
+  // Spreadsheet column
+  $form['add_fields']['columns'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Spreadsheet Column'),
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'table field')? FALSE : TRUE,
+  );
+
+  $form['add_fields']['columns']['sheet_name'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Worksheet'),
+    '#description' => t('Specify the name of the worksheet.'),
+    '#size' => 5,
+    '#default_value' => ($form_state['values']['sheet_name'])? $form_state['values']['sheet_name'] : 'Sheet1',
+  );
+
+  $form['add_fields']['columns']['column_number'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Column'),
+    '#description' => t('Specify the column in the spreadsheet that this field maps to where the first column is 1.'),
+    '#size' => 5,
+    '#default_value' => $form_state['values']['column_number'],
+  );
+
+  $form['add_fields']['columns']['column_exposed'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Allow Column to be set for each Bulk Loading Job'),
+    '#description' => t('Adds a textbox field to the Bulk Loader Page to allow users to set this value.'),
+    '#default_value' => ($form_state['values']['column_exposed']) ? $form_state['values']['column_exposed'] : $template_field['exposed'],
+  );
+
+  $form['add_fields']['columns']['column_exposed_desc'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Description for exposed field on bulk loading job'),
+    '#description' => t('This description should tell the user what column should be entered here.'),
+    '#default_value' => ($form_state['values']['column_exposed_desc']) ? $form_state['values']['column_exposed_desc'] : $template_field['exposed_description'],
+  );
+
+  // Global Value
+  $form['add_fields']['constant'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Constant'),
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'constant')? FALSE : TRUE,
+  );
+
+  $form['add_fields']['constant']['constant_value'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Constant Value'),
+    '#description' => t('Specify the value you wish this field to have regardless of spreadsheet data.'),
+    '#default_value' => $form_state['values']['constant_value']
+  );
+
+  $form['add_fields']['constant']['constant_exposed'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Allow Constant to be set for each Bulk Loading Job'),
+    '#description' => t('Adds a textbox field to the Create Bulk Loader Form to allow users to set this value.')
+  );
+
+  $form['add_fields']['constant']['constant_validate'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Ensure value is in table'),
+    '#description' => t('Checks the database when a bulk loading job is created to ensure the value entered already exists in the database.'),
+  );
+
+  // Foreign Key
+  $form['add_fields']['foreign_key'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Foreign Key',
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
+  );
+
+  $form['add_fields']['foreign_key']['foreign_record'] = array(
+    '#type' => 'select',
+    '#title' => 'Record to refer to',
+    '#descripion' => 'Select the record that this foreign key shouold refer to. The record needs to already exist and be of the correct table.',
+    '#options' => $fk_options,
+  );
+
+  // Chado Field
+  $form['add_fields']['chado'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Chado Field/Column Details'),
+    '#description' => t('Specify the Table/Field in chado that this field maps to.'),
+  );
+
+  $form['add_fields']['chado']['chado_table'] = array(
+    '#type' => 'select',
+    '#title' => t('Chado Table'),
+    '#options' => $tables,
+    '#default_value' => $table,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-add_field',
+      'effect' => 'fade'
+      ),
+  );
+
+  $form['add_fields']['chado']['chado_field'] = array(
+    '#type' => 'select',
+    '#title' => t('Chado Field/Column'),
+    '#options' => $chado_fields,
+    '#default_value' => $form_state['values']['chado_field'],
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/add_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-add_field',
+      'effect' => 'fade'
+    ),
+  );
+
+  $form['add_fields']['additional'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Additional Options',
+  );
+
+  $form['add_fields']['additional']['required'] = array(
+    '#type' => 'checkbox',
+    '#title' => 'Make this file required',
+  );
+
+  $form['add_fields']['additional']['regex_transform'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Transform Spreadsheet Value Rules',
+    '#collapsible' => TRUE,
+    '#collapsed' => (!$form_state['storage']['regex']['pattern']) ? TRUE : FALSE,
+  );
+
+  $form['add_fields']['additional']['regex_transform']['regex_description'] = array(
+    '#type' => 'item',
+    '#value' => 'A transformation rule allows you to transform the original value '
+      .'(usually from a user submitted spreadsheet) into the form you would like it stored '
+      .'in the chado database. Each rule consists of a match pattern (a php regular expression '
+      .'which determines which replacement patterns are applied and captures regions of the '
+      .'original value) and a replacement pattern (a string which may contain capture references '
+      .'that describes what the new value should be). Each rule is applied to the result of the '
+      .'previous rule.'
+  );
+
+  $form['add_fields']['additional']['regex_transform']['regex-data'] = array(
+    '#tree' => TRUE,
+  );
+  if (!$form_state['storage']['regex']['pattern']) {
+    $form_state['storage']['regex']['pattern'] = array();
+  }
+  foreach ($form_state['storage']['regex']['pattern'] as $index => $pattern) {
+    $data_element = array(
+      'pattern' => array(
+        '#type' => 'item',
+        '#value' => $pattern,
+      ),
+      'replace' => array(
+        '#type' => 'item',
+        '#value' => $form_state['storage']['regex']['replace'][$index],
+      ),
+      'old_index' => array(
+        '#type' => 'hidden',
+        '#value' => $index,
+      ),
+      'new_index' => array(
+        '#type' => 'select',
+        '#options' => range(0, sizeof($form_state['storage']['regex']['pattern'])-1),
+        '#default_value' => $index,
+      ),
+      'id' => array(
+        '#type' => 'hidden',
+        '#value' => $index,
+      ),
+      'submit-delete' => array(
+        '#type' => 'submit',
+        '#value' => 'Delete Transformation',
+        '#name' => $index,
+      ),
+    );
+    $form['add_fields']['additional']['regex_transform']['regex-data'][$index] = $data_element;
+  }
+
+  $form['add_fields']['additional']['regex_transform']['submit-reorder_regex'] = array(
+    '#type' => ($form_state['storage']['regex']['pattern']) ? 'submit' : 'hidden',
+    '#value' => 'Save Transformation Rule Order'
+  );
+
+  $form['add_fields']['additional']['regex_transform']['new_regex'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Add a new Transformation Rule',
+  );
+
+  $form['add_fields']['additional']['regex_transform']['new_regex']['pattern'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Match Pattern',
+    '#description' => 'You can use standard php regular expressions in this field to specify a '
+      .'pattern. Only if this pattern matches the value in the spreadsheet does the replacement '
+      .'pattern get applied to the value. To capture a section of your value for use in the '
+      .'replacement patten surround with round brackets. For example, <i>GI:(\d+)</i> will match '
+      .' NCBI gi numbers and will capture the numerical digits for use in the replacement pattern. '
+      .' To match and capture any value use <i>.*</i>',
+  );
+
+  $form['add_fields']['additional']['regex_transform']['new_regex']['replace'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Replacement Pattern',
+    '#description' => 'This pattern should contain the text you want to replace the match pattern '
+    .'mentioned above. It can include references of the form \n where n is the number of the '
+    .'capture in the match pattern. For example, \1 will be replaced with the text matched in your '
+    .'first set of round brackets.',
+  );
+
+  if ($field_type == 'table field') {
+    $tab = '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
+    $form['add_fields']['additional']['regex_transform']['new_regex']['replace']['#description'] .= '<p>'
+      .'The following references are also available for spreadsheet fields: <b><#column:<i>number</i>#></b>. '
+      .'This allows you to substitute other spreadsheet values into the current field. For example, '
+      .'if you had the following line:<br>'
+      . $tab . 'SNP' . $tab . '15-Jan-2011' . $tab . '1' . $tab . '54' . $tab . 'Contig34355'
+      .'<br> and your current field is for column #1 and you\'re inserting into the chado field '
+      .'feature.uniquename then you might want to add in the data to ensure your uniquename is '
+      .'unique. The Match Pattern is (.*) to select all the first column and the Replacement '
+      .'Pattern could be \1_<#column:2#> which would insert SNP_15-Jan-2011 into the database.</p>';
+  }
+
+  $form['add_fields']['additional']['regex_transform']['new_regex']['submit-add_transform'] = array(
+    '#type' => 'submit',
+    '#value' => 'Add Transformation',
+  );
+
+  $form['add_fields']['additional']['regex_transform']['test_regex'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Test Transformation Rules',
+  );
+
+  $form['add_fields']['additional']['regex_transform']['test_regex']['test_string'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Test Value',
+    '#description' => 'This should be a value that you expect the above transformation rules '
+      .'to be applied to.',
+    '#default_value' => $form_state['storage']['test_regex_test'],
+  );
+
+  $form['add_fields']['additional']['regex_transform']['test_regex']['test_result'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Test Result',
+    '#description' => 'This is the value that would be saved to the database after the above transformation '
+      .'riles were applied to the Test Value.',
+    '#default_value' => $form_state['storage']['test_regex_result'],
+  );
+
+  $form['add_fields']['additional']['regex_transform']['test_regex']['submit-test'] = array(
+    '#type' => 'submit',
+    '#value' => 'Test Transformation Rules'
+  );
+
+  $form['add_fields']['submit-add_field'] = array(
+      '#type' => 'submit',
+      '#value' => 'Add Field'
+  );
+
+  $form['add_fields']['submit-cancel'] = array(
+      '#type' => 'submit',
+      '#value' => 'Cancel'
+  );
+
+  return $form;
+}
+
+/**
+ * Add Field Submit
+ *
+ * @param $form
+ *   The form that was submitted
+ * @param $form_state
+ *   The values and storage for the form
+ */
+<<<<<<< HEAD
+function tripal_bulk_loader_add_template_field_form_submit($form, &$form_state) {
+=======
+function tripal_bulk_loader_add_template_field_form_submit ($form, &$form_state) {
+>>>>>>> 6.x-0.4-dev
+
+  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
+
+  if (!$form_state['ahah_submission']) {
+    if ($op ==  'Add Field') {
+
+      $template = $form_state['storage']['template_array'];
+
+       // If new record
+      if (preg_match('/NEW/', $form_state['values']['field_group'])) {
+        $record_name = $form_state['values']['record_name'];
+        $priority = sizeof($form_state['storage']['template_array']) + 1;
+        $record2priority[$record_name] = $priority;
+        $template[$priority]['table'] = $form_state['values']['chado_table'];
+        $template[$priority]['record_id'] = $record_name;
+
+<<<<<<< HEAD
+      }
+      else {
+=======
+      } else {
+>>>>>>> 6.x-0.4-dev
+        $priority = $form_state['values']['field_group'];
+        $record_name = $record2priority[$priority];
+      }
+
+      // Add field to template array
+      if ($form_state['values']['field_type'] == 'table field') {
+        $field = array(
+          'type' => 'table field',
+          'title' => $form_state['values']['field_title'],
+          'field' => $form_state['values']['chado_field'],
+          'required' => $form_state['values']['required'],
+          //'allowed values' => empty by default,
+          'spreadsheet sheet' => $form_state['values']['sheet_name'],
+          'spreadsheet column' => $form_state['values']['column_number'],
+          'exposed' => $form_state['values']['column_exposed'],
+          'exposed_description' => $form_state['values']['column_exposed_desc'],
+        );
+      }
+      elseif ($form_state['values']['field_type'] == 'constant') {
+        $field = array(
+          'type' => 'constant',
+          'title' => $form_state['values']['field_title'],
+          'field' => $form_state['values']['chado_field'],
+          'required' => $form_state['values']['required'],
+          //'allowed values' => empty by default,
+          'constant value' => $form_state['values']['constant_value'],
+          'exposed' => $form_state['values']['constant_exposed'],
+          'exposed_validate' => $form_state['values']['constant_validate'],
+        );
+<<<<<<< HEAD
+      }
+      elseif ($form_state['values']['field_type'] == 'foreign key') {
+=======
+      } elseif ($form_state['values']['field_type'] == 'foreign key') {
+>>>>>>> 6.x-0.4-dev
+        $field = array(
+          'type' => 'foreign key',
+          'title' => $form_state['values']['field_title'],
+          'field' => $form_state['values']['chado_field'],
+          'foreign key' => $form_state['values']['foreign_record'],
+          'required' => $form_state['values']['required'],
+        );
+      }
+
+      // Deal with any additional options
+      if ($form_state['storage']['regex']) {
+        $field['regex'] = $form_state['storage']['regex'];
+      }
+
+      // Save Template
+      $template[$priority]['fields'][] = $field;
+      $form_state['storage']['template']->template_array = serialize($template);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message('Successfully Added Field to Template');
+        drupal_set_message('Template Saved.');
+
+<<<<<<< HEAD
+        $path = explode('?', $form_state['storage']['referring URL']);
+=======
+        $path = explode('?',$form_state['storage']['referring URL']);
+>>>>>>> 6.x-0.4-dev
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        drupal_goto($path[0], $query);
+      }
+      else {
+        drupal_set_message('Unable to Save Template!', 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+    }
+    elseif ($op ==  'Cancel') {
+        $path = explode('?', $form_state['storage']['referring URL']);
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        drupal_goto($path[0], $query);
+<<<<<<< HEAD
+    }
+    elseif ($op == 'Add Transformation') {
+=======
+    } elseif ($op == 'Add Transformation') {
+>>>>>>> 6.x-0.4-dev
+
+      // Add transformation rule to original field
+      $form_state['storage']['regex']['pattern'][] = '/' . $form_state['values']['pattern'] . '/';
+      $form_state['storage']['regex']['replace'][] = $form_state['values']['replace'];
+      drupal_set_message('Successfully Added Transformation Rule');
+
+<<<<<<< HEAD
+    }
+    elseif ($op == 'Save Transformation Rule Order') {
+=======
+    } elseif ($op == 'Save Transformation Rule Order') {
+>>>>>>> 6.x-0.4-dev
+
+      // Generate new regex array
+      $new_regex = array();
+      $old_regex = $form_state['storage']['regex'];
+      foreach ($form_state['values']['regex-data'] as $key => $element) {
+        $new_regex['pattern'][ $element['new_index'] ] = $old_regex['pattern'][ $element['old_index'] ];
+        $new_regex['replace'][ $element['new_index'] ] = $old_regex['replace'][ $element['old_index'] ];
+      }
+
+      // sort new regex arrays
+      asort($new_regex['pattern']);
+      asort($new_regex['replace']);
+
+      $form_state['storage']['regex'] = $new_regex;
+<<<<<<< HEAD
+    }
+    elseif ($op == 'Delete Transformation') {
+=======
+    } elseif ($op == 'Delete Transformation') {
+>>>>>>> 6.x-0.4-dev
+
+      // Unset regex rule
+      $index = $form_state['clicked_button']['#name'];
+      unset($form_state['storage']['regex']['pattern'][$index]);
+      unset($form_state['storage']['regex']['replace'][$index]);
+
+<<<<<<< HEAD
+    }
+    elseif ($op == 'Test Transformation Rules') {
+=======
+    } elseif ($op == 'Test Transformation Rules') {
+>>>>>>> 6.x-0.4-dev
+
+      $patterns = $form_state['storage']['regex']['pattern'];
+      $replaces = $form_state['storage']['regex']['replace'];
+      $test_string = $form_state['values']['test_string'];
+      $form_state['storage']['test_regex_result'] = preg_replace($patterns, $replaces, $test_string);
+      $form_state['storage']['test_regex_test'] = $test_string;
+    }
+  }
+
+}
+
+/**
+ * Edit Field Form
+ *
+ * This form is meant to be called from a bulk loader form. The following should be set
+ * in the query section of the path:
+ *  - template_id=\d+: the template which the edited field is part of
+ *  - record_id=\d+: the priority or key in the template array of the record the field
+ *      is currently part of
+ *  - field_index=\d+: the key of the field in the fields array of the previously
+ *      specified record
+ *
+ * @param $form_state
+ *   Contains the values and storage for the form
+ * @return
+ *   A form array to be rendered by drupal_get_form
+ */
+function tripal_bulk_loader_edit_template_field_form(&$form_state = NULL) {
+  $form = array();
+<<<<<<< HEAD
+   $form['#cache'] = TRUE; // Make sure the form is cached.
+
+   // get template id from path
+   $template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
+
+   // if there is no template supplied don't return rest of form
+   if (!$template_id) {
+     return $form;
+   }
+=======
+ 	$form['#cache'] = TRUE; // Make sure the form is cached.
+
+ 	// get template id from path
+ 	$template_id = ($_GET['template_id']) ? $_GET['template_id'] : $form_state['values']['template_id'];
+
+ 	// if there is no template supplied don't return rest of form
+ 	if (!$template_id) {
+ 	  return $form;
+ 	}
+>>>>>>> 6.x-0.4-dev
+
+  // Pre-set Variables needed for form proper------------------------------------------
+
+   // If this is the first load of the form (no form state) we need to initialize some variables
+   if (!$form_state['storage']['template']) {
+    $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+    $template = db_fetch_object(db_query($sql, $template_id));
+    $form_state['storage']['template_array'] = unserialize($template->template_array);
+    $form_state['storage']['template'] = $template;
+
+    $form_state['storage']['record2priority'] = array();
+    foreach ($form_state['storage']['template_array'] as $priority => $record_array) {
+      if (!is_array($record_array)) {
+         continue;
+       }
+      $form_state['storage']['record2priority'][$record_array['record_id']] = $priority;
+    }
+
+    $form_state['storage']['referring URL'] = $_SERVER["HTTP_REFERER"];
+  }
+  else {
+    $template = $form_state['storage']['template'];
+  }
+
+  // get the field from the path
+  if (!($_GET['record_id']===NULL || $_GET['field_index']===NULL)) {
+    $priority = $_GET['record_id'];
+    $field_index = $_GET['field_index'];
+    $template_field = $form_state['storage']['template_array'][$priority]['fields'][$field_index];
+    $form_state['storage']['original_field'] = $template_field;
+    $form_state['storage']['original_field']['priority'] = $priority;
+    $form_state['storage']['original_field']['field_index'] = $field_index;
+  }
+
+  $field_type = ($form_state['values']['field_type'])? $form_state['values']['field_type'] : $template_field['type'];
+
+  // Tables and default table
+  $tables = tripal_core_get_chado_tables();
+  if ($form_state['values']) {
+    $table = $form_state['values']['chado_table'];
+<<<<<<< HEAD
+  }
+  else {
+    $table = $form_state['storage']['template_array'][$priority]['table'];
+  }
+=======
+  } else {
+    $table = $form_state['storage']['template_array'][$priority]['table'];
+  }
+>>>>>>> 6.x-0.4-dev
+
+
+  // Fields and foreign key mappings
+  $chado_fields = array();
+  $fk_options = array();
+  $fk_options['NULL'] = 'None';
+  $table_description = module_invoke_all('chado_' . $table . '_schema');
+  if ($field_type == 'foreign key') {
+    $foreign_field2table = array();
+    foreach ($table_description['foreign keys'] as $key_table => $key_array) {
+      foreach ($key_array['columns'] as $left_field => $right_field) {
+        $chado_fields[$left_field] = $left_field;
+        $foreign_field2table[$left_field] = $key_table;
+      }
+    }
+    reset($chado_fields);
+
+    // set default field
+    if (empty($chado_fields)) {
+      $field = NULL;
+    }
+    elseif ($chado_fields[$form_state['values']['chado_field']]) {
+      $field = $form_state['values']['chado_field'];
+    }
+    elseif ($template_field['field']) {
+      $field = $template_field['field'];
+    }
+    else {
+      $field = current($chado_fields);
+    }
+    //dpm($field, 'field');
+
+    // Foreign key options
+    $foreign_table = $foreign_field2table[$field];
+    if ($foreign_table) {
+      foreach ($form_state['storage']['record2priority'] as $record_name_ => $priority_ ) {
+        if (preg_match('/^' . $foreign_table . '$/', $form_state['storage']['template_array'][$priority_]['table'])) {
+          $fk_options[$record_name_] = $record_name_;
+        }
+      }
+    }
+  }
+  else {
+    foreach ($table_description['fields'] as $field_name => $field_array) {
+        $chado_fields[$field_name] = $field_name;
+    }
+  }
+
+//  dpm(array( 'tables' => $tables, 'default table' => $table, 'record name' => $record_name, 'priority' => $priority,
+//    'fields' => $chad_fields, 'default field' => $field, 'foreign field=>table' => $foreign_field2table,
+//    'table desc' => $table_description, 'foreign record options' => $fk_options, 'foreign table' => $foreign_table
+//    ), 'Variables');
+
+  // Start of Form Proper--------------------------------------------------------------
+
+  $form['template_name'] = array(
+    '#type' => 'item',
+    '#title' => 'Template',
+    '#value' => $template->name,
+  );
+
+  $form['template_id'] = array(
+    '#type' => 'hidden',
+    '#value' => $template_id,
+  );
+
+  $form['edit_fields'] = array(
+    '#type' => 'fieldset',
+    '#prefix' => '<div id="tripal_bulk_loader_template-edit_field">',
+    '#suffix' => '</div>',
+  );
+
+  $form['edit_fields']['field_type'] = array(
+    '#type' => 'radios',
+    '#title' => t('Type of Field'),
+    '#options' => array(
+      'table field' => t('Spreadsheet: Fields which maps to a Spreadsheet Column'),
+      'constant' => t('Constant: Field which remains Constant throughout the Spreadsheet'),
+      'foreign key' => t('Foreign Key: Fields which map to a record in another table'),
+    ),
+    '#required' => TRUE,
+    '#default_value' => $field_type,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-edit_field',
+      'effect' => 'fade'
+    ),
+  );
+
+  // check template array for records then edit one more
+  if (!$form_state['storage']['record2priority']) {
+    $groups = array();
+  }
+  else {
+    $groups = array_flip($form_state['storage']['record2priority']);
+  }
+  $groups['NONE'] = 'Select a Record';
+  $groups['NEW'] = 'New Record';
+  $form['edit_fields']['field_group']  = array(
+    '#type' => 'select',
+    '#title' => 'Record',
+    '#description' => 'This is used to group a set of fields together allowing '
+      .'multiple records to be inserted into the same table per line of the spreadsheet',
+    '#options' => $groups,
+    '#default_value' => (preg_match('/(\d+|\w+)/', $form_state['values']['field_group'])) ? $form_state['values']['field_group'] : $priority,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-edit_field',
+      'effect' => 'fade'
+    ),
+    '#required' => TRUE,
+  );
+
+  $form['edit_fields']['record_name'] = array(
+    '#type' => (preg_match('/NEW/', $form_state['values']['field_group'])) ? 'textfield' : 'hidden',
+    '#title' => 'Unique Record Name',
+    '#prefix' => '<div id="tripal_bulk_loader_template-edit_record">',
+    '#suffix' => '</div>',
+    '#default_value' => $form_state['values']['record_name'],
+  );
+
+  $form['edit_fields']['field_title'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Human-readable Title for Field'),
+    '#default_value' => ($form_state['values']['field_title']) ? $form_state['values']['field_title'] : $template_field['title'],
+  );
+
+  // Spreadsheet column
+  $form['edit_fields']['columns'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Spreadsheet Column'),
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'table field')? FALSE : TRUE,
+  );
+
+  $form['edit_fields']['columns']['sheet_name'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Worksheet'),
+    '#description' => t('Specify the name of the worksheet.'),
+    '#size' => 5,
+    '#default_value' => ($form_state['values']['sheet_name'])? $form_state['values']['sheet_name'] : $template_field['spreadsheet sheet'],
+  );
+
+  $form['edit_fields']['columns']['column_number'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Column'),
+    '#description' => t('Specify the column in the spreadsheet that this field maps to where the first column is 1.'),
+    '#size' => 5,
+    '#default_value' => ($form_state['values']['column_number']) ? $form_state['values']['column_number'] : $template_field['spreadsheet column'],
+  );
+
+  $form['edit_fields']['columns']['column_exposed'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Allow Column to be set for each Bulk Loading Job'),
+    '#description' => t('Adds a textbox field to the Bulk Loader Page to allow users to set this value.'),
+    '#default_value' => ($form_state['values']['column_exposed']) ? $form_state['values']['column_exposed'] : $template_field['exposed'],
+  );
+
+  $form['edit_fields']['columns']['column_exposed_desc'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Description for exposed field on bulk loading job'),
+    '#description' => t('This description should tell the user what column should be entered here.'),
+    '#default_value' => ($form_state['values']['column_exposed_desc']) ? $form_state['values']['column_exposed_desc'] : $template_field['exposed_description'],
+  );
+
+  // Global Value
+  $form['edit_fields']['constant'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Constant'),
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'constant')? FALSE : TRUE,
+  );
+
+  $form['edit_fields']['constant']['constant_value'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Constant Value'),
+    '#description' => t('Specify the value you wish this field to have regardless of spreadsheet data.'),
+    '#default_value' => ($form_state['values']['constant_value']) ? $form_state['values']['constant_value'] : $template_field['constant value'],
+  );
+
+  $form['edit_fields']['constant']['constant_exposed'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Allow Constant to be set for each Bulk Loading Job'),
+    '#description' => t('Adds a textbox field to the Create Bulk Loader Form to allow users to set this value.'),
+    '#default_value' => ($form_state['values']['constant_exposed']) ? $form_state['values']['constant_exposed'] : $template_field['exposed'],
+  );
+
+  $form['edit_fields']['constant']['constant_validate'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Ensure value is in table'),
+    '#description' => t('Checks the database when a bulk loading job is created to ensure the value entered already exists in the database.'),
+    '#default_value' => ($form_state['values']['constant_validate']) ? $form_state['values']['constant_validate'] : $template_field['exposed_validate'],
+  );
+
+  // Foreign Key
+  $form['edit_fields']['foreign_key'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Foreign Key',
+    '#collapsible' => TRUE,
+    '#collapsed' => ($field_type == 'foreign key')? FALSE : TRUE,
+  );
+
+  $form['edit_fields']['foreign_key']['foreign_record'] = array(
+    '#type' => 'select',
+    '#title' => 'Record to refer to',
+    '#descripion' => 'Select the record that this foreign key shouold refer to. The record needs to already exist and be of the correct table.',
+    '#options' => $fk_options,
+  );
+
+  // Chado Field
+  $form['edit_fields']['chado'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Chado Field/Column Details'),
+    '#description' => t('Specify the Table/Field in chado that this field maps to.'),
+  );
+
+  $form['edit_fields']['chado']['chado_table'] = array(
+    '#type' => 'select',
+    '#title' => t('Chado Table'),
+    '#options' => $tables,
+    '#default_value' => $table,
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-edit_field',
+      'effect' => 'fade'
+      ),
+  );
+
+  $form['edit_fields']['chado']['chado_field'] = array(
+    '#type' => 'select',
+    '#title' => t('Chado Field/Column'),
+    '#options' => $chado_fields,
+    '#default_value' => ($form_state['values']['chado_field']) ? $form_state['values']['chado_field'] : $template_field['field'],
+    '#ahah' => array(
+      'path' => 'admin/tripal/tripal_bulk_loader_template/edit_field_ahah',
+      'wrapper' => 'tripal_bulk_loader_template-edit_field',
+      'effect' => 'fade'
+    ),
+  );
+
+  $form['edit_fields']['additional'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Additional Options',
+  );
+
+  $form['edit_fields']['additional']['required'] = array(
+    '#type' => 'checkbox',
+    '#title' => 'Make this file required',
+    '#default_value' => $template_field['required'],
+  );
+
+  $form['edit_fields']['additional']['regex_transform'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Transform Spreadsheet Value Rules',
+    '#collapsible' => TRUE,
+    '#collapsed' => (!$template_field['regex']['pattern']) ? TRUE : FALSE,
+  );
+
+  $transformation_msg = '<p>A transformation rule allows you to transform the original value '
+      .'(usually from a user submitted spreadsheet) into the form you would like it stored '
+      .'in the chado database. Each rule consists of a match pattern (a php regular expression '
+      .'which determines which replacement patterns are applied and captures regions of the '
+      .'original value) and a replacement pattern (a string which may contain capture references '
+      .'that describes what the new value should be). Each rule is applied to the result of the '
+      .'previous rule.<p>';
+  $form['edit_fields']['additional']['regex_transform']['regex_description'] = array(
+    '#type' => 'item',
+    '#value' => $transformation_msg,
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['regex-data'] = array(
+    '#tree' => TRUE,
+  );
+  foreach ($template_field['regex']['pattern'] as $index => $pattern) {
+    $data_element = array(
+      'pattern' => array(
+        '#type' => 'item',
+        '#value' => $pattern,
+      ),
+      'replace' => array(
+        '#type' => 'item',
+        '#value' => $template_field['regex']['replace'][$index],
+      ),
+      'old_index' => array(
+        '#type' => 'hidden',
+        '#value' => $index,
+      ),
+      'new_index' => array(
+        '#type' => 'select',
+        '#options' => range(0, sizeof($template_field['regex']['pattern'])-1),
+        '#default_value' => $index,
+      ),
+      'id' => array(
+        '#type' => 'hidden',
+        '#value' => $index,
+      ),
+      'submit-delete' => array(
+        '#type' => 'submit',
+        '#value' => 'Delete Transformation',
+        '#name' => $index,
+      ),
+    );
+    $form['edit_fields']['additional']['regex_transform']['regex-data'][$index] = $data_element;
+  }
+
+  $form['edit_fields']['additional']['regex_transform']['submit-reorder_regex'] = array(
+    '#type' => 'submit',
+    '#value' => 'Save Transformation Rule Order'
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['new_regex'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Add a new Transformation Rule',
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['new_regex']['pattern'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Match Pattern',
+    '#description' => 'You can use standard <b>php regular expressions</b> in this field to specify a '
+      .'pattern. Only if this pattern matches the value in the spreadsheet does the replacement '
+      .'pattern get applied to the value. To capture a section of your value for use in the '
+      .'replacement patten surround with round brackets. For example, <i>GI:(\d+)</i> will match '
+      .' NCBI gi numbers and will capture the numerical digits for use in the replacement pattern. '
+      .' To match and capture any value use <i>.*</i>',
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['new_regex']['replace'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Replacement Pattern',
+    '#description' => '<p>This pattern should contain the text you want to replace the match pattern '
+    .'mentioned above. It can include references of the form <b>\n</b> where n is the number of the '
+    .'capture in the match pattern. For example, \1 will be replaced with the text matched in your '
+    .'first set of round brackets.</p>',
+  );
+
+  if ($field_type == 'table field') {
+    $tab = '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
+    $form['edit_fields']['additional']['regex_transform']['new_regex']['replace']['#description'] .= '<p>'
+      .'The following references are also available for spreadsheet fields: <b><#column:<i>number</i>#></b>. '
+      .'This allows you to substitute other spreadsheet values into the current field. For example, '
+      .'if you had the following line:<br>'
+      . $tab . 'SNP' . $tab . '15-Jan-2011' . $tab . '1' . $tab . '54' . $tab . 'Contig34355'
+      .'<br> and your current field is for column #1 and you\'re inserting into the chado field '
+      .'feature.uniquename then you might want to add in the data to ensure your uniquename is '
+      .'unique. The Match Pattern is (.*) to select all the first column and the Replacement '
+      .'Pattern could be \1_<#column:2#> which would insert SNP_15-Jan-2011 into the database.</p>';
+  }
+
+  $form['edit_fields']['additional']['regex_transform']['new_regex']['submit-add_transform'] = array(
+    '#type' => 'submit',
+    '#value' => 'Add Transformation',
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['test_regex'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Test Transformation Rules',
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['test_regex']['test_string'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Test Value',
+    '#description' => 'This should be a value that you expect the above transformation rules '
+      .'to be applied to.',
+    '#default_value' => $form_state['storage']['test_regex_test'],
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['test_regex']['test_result'] = array(
+    '#type' => 'textfield',
+    '#title' => 'Test Result',
+    '#description' => 'This is the value that would be saved to the database after the above transformation '
+      .'riles were applied to the Test Value.',
+    '#default_value' => $form_state['storage']['test_regex_result'],
+  );
+
+  $form['edit_fields']['additional']['regex_transform']['test_regex']['submit-test'] = array(
+    '#type' => 'submit',
+    '#value' => 'Test Transformation Rules'
+  );
+
+  $form['edit_fields']['submit-edit_field'] = array(
+      '#type' => 'submit',
+      '#value' => 'Edit Field'
+  );
+
+  $form['edit_fields']['submit-cancel'] = array(
+      '#type' => 'submit',
+      '#value' => 'Cancel'
+  );
+
+  return $form;
+}
+
+/**
+ * Edit Field Form Submit
+ *
+ * @param $form
+ *   The form that was submitted
+ * @param $form_state
+ *   The values and storage for the form
+ */
+function tripal_bulk_loader_edit_template_field_form_submit($form, &$form_state) {
+
+  $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
+  //dpm($op, 'Operation Submitted');
+
+  //Clear Test
+  $form_state['storage']['test_regex_result'] = NULL;
+  $form_state['storage']['test_regex_test'] = NULL;
+
+  if (!$form_state['ahah_submission']) {
+    if ($op ==  'Edit Field') {
+
+      // If new record
+      if (preg_match('/NEW/', $form_state['values']['field_group'])) {
+        // add new record
+        $record_name = $form_state['values']['record_name'];
+        $priority = sizeof($form_state['storage']['template_array']) + 1;
+        $old_priority = $form_state['storage']['original_field']['priority'];
+        $field_index = $form_state['storage']['original_field']['field_index'];
+        $form_state['storage']['record2priority'][$record_name] = $priority;
+        $form_state['storage']['template_array'][$priority]['table'] = $form_state['values']['chado_table'];
+        $form_state['storage']['template_array'][$priority]['record_id'] = $record_name;
+
+<<<<<<< HEAD
+      }
+      else {
+=======
+      } else {
+>>>>>>> 6.x-0.4-dev
+        $priority = $form_state['values']['field_group'];
+        $old_priority = $form_state['storage']['original_field']['priority'];
+        $field_index = $form_state['storage']['original_field']['field_index'];
+        $record_name = $form_state['storage']['record2priority'][$priority];
+      }
+
+      $field = $form_state['storage']['original_field'];
+      if ($form_state['values']['field_type'] == 'table field') {
+          $field['type'] = 'table field';
+          $field['title'] = $form_state['values']['field_title'];
+          $field['field'] = $form_state['values']['chado_field'];
+          $field['required'] = $form_state['values']['required'];
+          //$field['allowed values'] = empty by default;
+          $field['spreadsheet sheet'] = $form_state['values']['sheet_name'];
+          $field['spreadsheet column'] = $form_state['values']['column_number'];
+          $field['exposed'] = $form_state['values']['column_exposed'];
+          $field['exposed_description'] = $form_state['values']['column_exposed_desc'];
+      }
+      elseif ($form_state['values']['field_type'] == 'constant') {
+          $field['type'] = 'constant';
+          $field['title'] = $form_state['values']['field_title'];
+          $field['field'] = $form_state['values']['chado_field'];
+          $field['required'] = $form_state['values']['required'];
+          //$field['allowed values'] = empty by default;
+          $field['constant value'] = $form_state['values']['constant_value'];
+          $field['exposed_validate'] = $form_state['values']['constant_validate'];
+          $field['exposed'] = $form_state['values']['constant_exposed'];
+<<<<<<< HEAD
+      }
+      elseif ($form_state['values']['field_type'] == 'foreign key') {
+=======
+      } elseif ($form_state['values']['field_type'] == 'foreign key') {
+>>>>>>> 6.x-0.4-dev
+          $field['type'] = 'foreign key';
+          $field['title'] = $form_state['values']['field_title'];
+          $field['field'] = $form_state['values']['chado_field'];
+          $field['foreign key'] = $form_state['values']['foreign_record'];
+          $field['required'] = $form_state['values']['required'];
+      }
+
+      // Deal with any additional options
+
+      // if the record has changed...
+      $form_state['storage']['template_array'][$priority]['table'] = $form_state['values']['chado_table'];
+      if ($old_priority != $priority) {
+        $form_state['storage']['template_array'][$priority]['fields'][] = $field;
+        unset($form_state['storage']['template_array'][$old_priority]['fields'][$field_index]);
+
+        // if there are no fields left delete the old record
+        if (!$form_state['storage']['template_array'][$old_priority]['fields']) {
+          unset($form_state['storage']['template_array'][$old_priority]);
+        }
+      }
+      else {
+        $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $field;
+      }
+
+      // Save Template
+      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message('Successfully Updated Field');
+        drupal_set_message('Template Saved.');
+
+        $path = explode('?', $form_state['storage']['referring URL']);
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        drupal_goto($path[0], $query);
+<<<<<<< HEAD
+      }
+      else {
+=======
+      } else {
+>>>>>>> 6.x-0.4-dev
+        drupal_set_message('Unable to Save Template!', 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+
+<<<<<<< HEAD
+    }
+    elseif ($op ==  'Cancel') {
+
+        $path = explode('?', $form_state['storage']['referring URL']);
+=======
+    } elseif ($op ==  'Cancel') {
+
+        $path = explode('?',$form_state['storage']['referring URL']);
+>>>>>>> 6.x-0.4-dev
+        parse_str($path[1], $query);
+        $query['template_id'] = $form_state['storage']['template']->template_id;
+        drupal_goto($path[0], $query);
+
+    }
+    elseif ($op == 'Add Transformation') {
+
+      // Add transformation rule to original field
+      $form_state['storage']['original_field']['regex']['pattern'][] = '/' . $form_state['values']['pattern'] . '/';
+      $form_state['storage']['original_field']['regex']['replace'][] = $form_state['values']['replace'];
+
+      // Add original field back into template
+      $priority = $form_state['storage']['original_field']['priority'];
+      $field_index = $form_state['storage']['original_field']['field_index'];
+      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
+
+      // Save Template
+      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message('Successfully Added Transformation Rule');
+        drupal_set_message('Template Saved.');
+<<<<<<< HEAD
+      }
+      else {
+=======
+      } else {
+>>>>>>> 6.x-0.4-dev
+        drupal_set_message('Unable to Save Template!', 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+<<<<<<< HEAD
+    }
+    elseif ($op == 'Save Transformation Rule Order') {
+=======
+    } elseif ($op == 'Save Transformation Rule Order') {
+>>>>>>> 6.x-0.4-dev
+
+      // Generate new regex array
+      $new_regex = array();
+      $old_regex = $form_state['storage']['original_field']['regex'];
+      foreach ($form_state['values']['regex-data'] as $key => $element) {
+        $new_regex['pattern'][ $element['new_index'] ] = $old_regex['pattern'][ $element['old_index'] ];
+        $new_regex['replace'][ $element['new_index'] ] = $old_regex['replace'][ $element['old_index'] ];
+      }
+
+      // sort new regex arrays
+      asort($new_regex['pattern']);
+      asort($new_regex['replace']);
+
+      // Add back to original field
+      $form_state['storage']['original_field']['regex'] = $new_regex;
+      $priority = $form_state['storage']['original_field']['priority'];
+      $field_index = $form_state['storage']['original_field']['field_index'];
+      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
+
+      // Save Template
+      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message('Successfully Reordered Transformation Rules');
+        drupal_set_message('Template Saved.');
+<<<<<<< HEAD
+      }
+      else {
+=======
+      } else {
+>>>>>>> 6.x-0.4-dev
+        drupal_set_message('Unable to Save Template!', 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+<<<<<<< HEAD
+    }
+    elseif ($op == 'Delete Transformation') {
+=======
+    } elseif ($op == 'Delete Transformation') {
+>>>>>>> 6.x-0.4-dev
+
+      // Unset regex rule
+      $index = $form_state['clicked_button']['#name'];
+      unset($form_state['storage']['original_field']['regex']['pattern'][$index]);
+      unset($form_state['storage']['original_field']['regex']['replace'][$index]);
+
+      $priority = $form_state['storage']['original_field']['priority'];
+      $field_index = $form_state['storage']['original_field']['field_index'];
+      $form_state['storage']['template_array'][$priority]['fields'][$field_index] = $form_state['storage']['original_field'];
+
+      // Save Template
+      $form_state['storage']['template']->template_array = serialize($form_state['storage']['template_array']);
+      $success = drupal_write_record('tripal_bulk_loader_template', $form_state['storage']['template'], array('template_id'));
+
+      if ($success) {
+        drupal_set_message('Successfully Reordered Transformation Rules');
+        drupal_set_message('Template Saved.');
+<<<<<<< HEAD
+      }
+      else {
+=======
+      } else {
+>>>>>>> 6.x-0.4-dev
+        drupal_set_message('Unable to Save Template!', 'error');
+        watchdog('T_bulk_loader',
+          'Unable to save bulk loader template: %template',
+          array('%template' => print_r($form_state['storage']['template'], TRUE)),
+          WATCHDOG_ERROR
+        );
+      }
+
+<<<<<<< HEAD
+    }
+    elseif ($op == 'Test Transformation Rules') {
+=======
+    } elseif ($op == 'Test Transformation Rules') {
+>>>>>>> 6.x-0.4-dev
+
+      $patterns = $form_state['storage']['original_field']['regex']['pattern'];
+      $replaces = $form_state['storage']['original_field']['regex']['replace'];
+      $test_string = $form_state['values']['test_string'];
+      $form_state['storage']['test_regex_result'] = preg_replace($patterns, $replaces, $test_string);
+      $form_state['storage']['test_regex_test'] = $test_string;
+    }
+  }
+
+}
+
+//////////////////////////////////////////////////////////////////////////////////////
+// AHAH Callbacks
+//////////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * AHAH Function: Replace $form['add_fields'] in tripal_bulk_loader_add_template_field_form
+ *
+ * @return
+ *  JSON Data printed to the screen
+ */
+function tripal_bulk_loader_add_field_ahah() {
+
+  $form_state = array('storage' => NULL, 'submitted' => FALSE);
+  $form_build_id = $_POST['form_build_id'];
+  $form = form_get_cache($form_build_id, $form_state);
+  $args = $form['#parameters'];
+  $form_id = array_shift($args);
+  $form_state['post'] = $form['#post'] = $_POST;
+
+  // Enable the submit/validate handlers to determine whether AHAH-submittted.
+  $form_state['ahah_submission'] = TRUE;
+
+  $form['#programmed'] = $form['#redirect'] = FALSE;
+  drupal_process_form($form_id, $form, $form_state);
+  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
+
+  $form_element = $form['add_fields'];
+  // Remove the wrapper so we don't double it up.
+  //unset($form_element['#prefix'], $form_element['#suffix']);
+
+  $output = theme('status_messages');
+  $output .= drupal_render($form_element);
+
+  // Final rendering callback.
+  print drupal_json(array('status' => TRUE, 'data' => $output));
+  exit();
+
+}
+
+/**
+ * AHAH Function: Replace $form['edit_fields'] in tripal_bulk_loader_edit_template_field_form
+ *
+ * @return
+ *  JSON Data printed to the screen
+ */
+function tripal_bulk_loader_edit_field_ahah() {
+
+  $form_state = array('storage' => NULL, 'submitted' => FALSE);
+  $form_build_id = $_POST['form_build_id'];
+  $form = form_get_cache($form_build_id, $form_state);
+  $args = $form['#parameters'];
+  $form_id = array_shift($args);
+  $form_state['post'] = $form['#post'] = $_POST;
+
+  // Enable the submit/validate handlers to determine whether AHAH-submittted.
+  $form_state['ahah_submission'] = TRUE;
+
+  $form['#programmed'] = $form['#redirect'] = FALSE;
+  drupal_process_form($form_id, $form, $form_state);
+  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
+
+  $form_element = $form['edit_fields'];
+  // Remove the wrapper so we don't double it up.
+  unset($form_element['#prefix'], $form_element['#suffix']);
+
+  $output = theme('status_messages');
+  $output .= drupal_render($form_element);
+
+  // Final rendering callback.
+  print drupal_json(array('status' => TRUE, 'data' => $output));
+  exit();
+
+<<<<<<< HEAD
+}
+=======
+}
+>>>>>>> 6.x-0.4-dev

+ 153 - 133
tripal_bulk_loader/tripal_bulk_loader.constants.inc

@@ -1,4 +1,8 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
  * Inserts/Updates a tripal bulk loading job constant
@@ -22,18 +26,18 @@
  *   On success it returns the object (with primary key if inserted);
  *   on failure it returns FALSE
  */
-function tripal_bulk_loader_update_constant ($nid, $group_id, $table, $field, $record_id, $field_id, $value) {
-  
+function tripal_bulk_loader_update_constant($nid, $group_id, $table, $field, $record_id, $field_id, $value) {
+
   $record = array(
-    'nid'=>$nid, 
+    'nid' => $nid,
     'group_id' => $group_id,
-    'chado_table'=>$table, 
-    'chado_field'=>$field, 
-    'record_id'=>$record_id, 
-    'field_id'=>$field_id, 
-    'value'=>$value
+    'chado_table' => $table,
+    'chado_field' => $field,
+    'record_id' => $record_id,
+    'field_id' => $field_id,
+    'value' => $value
   );
-  
+
   // Check to see if already exists
   $exists = db_fetch_object(db_query(
     "SELECT constant_id FROM {tripal_bulk_loader_constants} WHERE nid=%d AND record_id=%d AND field_id=%d AND group_id=%d",
@@ -44,45 +48,51 @@ function tripal_bulk_loader_update_constant ($nid, $group_id, $table, $field, $r
   ));
   if ($exists->constant_id) {
     $record['constant_id'] = $exists->constant_id;
-    $status = drupal_write_record('tripal_bulk_loader_constants',$record,'constant_id');
+    $status = drupal_write_record('tripal_bulk_loader_constants', $record, 'constant_id');
     if ($status) {
       return $record;
-    } else {
+    }
+    else {
       return FALSE;
     }
-  } else {
+  }
+  else {
 
-    $status = drupal_write_record('tripal_bulk_loader_constants',$record);
+    $status = drupal_write_record('tripal_bulk_loader_constants', $record);
     if ($status) {
       return $record;
-    } else {
+    }
+    else {
       return FALSE;
     }
   }
 }
 
-function tripal_bulk_loader_has_exposed_fields ($node) {
+function tripal_bulk_loader_has_exposed_fields($node) {
 
   // exposed fields isn't set
   if (!isset($node->exposed_fields)) {
     return FALSE;
   }
-  
+
   // exposed fields has at least one element
   if (sizeof($node->exposed_fields) == 1) {
     // need to check if single element is an empty array
     $element = reset($node->exposed_fields);
     if ($element) {
       return TRUE;
-    } else {
+    }
+    else {
       return FALSE;
     }
-  } elseif (sizeof($node->exposed_fields) > 1) {
+  }
+  elseif (sizeof($node->exposed_fields) > 1) {
     return TRUE;
-  } else {
+  }
+  else {
     return FALSE;
   }
-  
+
   return FALSE;
 }
 
@@ -93,7 +103,7 @@ function tripal_bulk_loader_has_exposed_fields ($node) {
 /**
  * Set constants (exposed fields in template)
  *
- * @param $form_state 
+ * @param $form_state
  *   The current state of the form
  * @param $node
  *   The node to set constants for
@@ -101,23 +111,23 @@ function tripal_bulk_loader_has_exposed_fields ($node) {
  * @return
  *   A form array to be rendered by drupal_get_form()
  */
-function tripal_bulk_loader_set_constants_form ($form_state, $node) {
+function tripal_bulk_loader_set_constants_form($form_state, $node) {
   $form = array();
-  
+
   $form['nid'] = array(
     '#type' => 'hidden',
     '#value' => $node->nid
   );
-  
+
   if (!tripal_bulk_loader_has_exposed_fields($node)) {
     return $form;
   }
-  
+
   $form['exposed_array'] = array(
     '#type' => 'hidden',
     '#value' => serialize($node->exposed_fields),
   );
-  
+
   $form['exposed_fields'] = array(
     '#type' => 'fieldset',
     '#title' => t('Constant Values'),
@@ -137,16 +147,16 @@ function tripal_bulk_loader_set_constants_form ($form_state, $node) {
         .'in the template to be loaded x number of times where there are x sets of '
         .'constants (rows in the following table).')
     );
-    
+
     $form['exposed_fields']['existing'] = array(
       '#tree' => TRUE,
     );
-    
+
     foreach ($node->constants as $set) {
 
       foreach ($set as $record) {
         foreach ($record as $field) {
-          $index = $field['record_id'].'-'.$field['field_id'];
+          $index = $field['record_id'] . '-' . $field['field_id'];
           $group = $field['group_id'];
           $form['exposed_fields']['existing'][$group][$index] = array(
             '#type' => 'markup',
@@ -157,65 +167,65 @@ function tripal_bulk_loader_set_constants_form ($form_state, $node) {
 
       $form['exposed_fields']['existing'][$group]['delete'] = array(
         '#type' => 'markup',
-        '#value' => l('Edit', 'node/'. $node->nid . '/constants/'.$group.'/edit') .'<br />'.
-          l('Delete', 'node/'. $node->nid . '/constants/'.$group.'/delete'),
+        '#value' => l(t('Edit'), 'node/' . $node->nid . '/constants/' . $group . '/edit') . '<br />'  .
+          l(t('Delete'), 'node/' . $node->nid . '/constants/' . $group . '/delete'),
       );
-                  
+
     }
   }
-  
+
   $form['exposed_fields']['new'] = array(
     '#type' => 'fieldset',
     '#title' => t('New set of Constants'),
   );
-    
+
   $form['exposed_fields']['new']['explanation-2'] = array(
     '#type' => 'item',
     '#value' => t('The following fields are constants in the selected template that you need to set values for.')
   );
-  
+
   // Add textifelds for exposed fields of the current template
   $exposed_fields = FALSE;
   $indexes = array();
   if (tripal_bulk_loader_has_exposed_fields($node)) {
     foreach ($node->exposed_fields as $exposed_index) {
-      
+
       $record_id = $exposed_index['record_id'];
       $field_id = $exposed_index['field_id'];
       $field = $node->template->template_array[$record_id]['fields'][$field_id];
-      
+
       if ($field['exposed']) {
         $exposed_fields = TRUE;
         $indexes[$record_id][] = $field_id;
-        
-        switch($field['type']) {
+
+        switch ($field['type']) {
           case 'table field':
-            $form['exposed_fields']['new'][$record_id.'-'.$field_id] = array(
+            $form['exposed_fields']['new'][$record_id . '-' . $field_id] = array(
               '#type' => 'textfield',
-              '#title' => t($field['title']),
-              '#description' => t($field['exposed_description']),
+              '#title' => t('%title', array('%title' => $field['title'])),
+              '#description' => t('%exposed_description', array('%exposed_description' => $field['exposed_description'])),
               '#default_value' => (isset($node->constants[$record_id][$field_id]['value'])) ? $node->constants[$record_id][$field_id]['value'] : $field['constant value'],
             );
           break;
           case 'constant':
-            $form['exposed_fields']['new'][$record_id.'-'.$field_id] = array(
+            $form['exposed_fields']['new'][$record_id . '-' . $field_id] = array(
               '#type' => 'textfield',
-              '#title' => t($field['title']),
+              '#title' => t('%title', array('%title' => $field['title']) ),
               '#description' => t('Enter the case-sensitive value of this constant for your spreadsheet'),
               '#default_value' => (isset($node->constants[$record_id][$field_id]['value'])) ? $node->constants[$record_id][$field_id]['value'] : $field['constant value'],
             );
           break;
         }
-        
-        $form['exposed_fields']['new'][$record_id.'-'.$field_id.'-table'] = array(
+
+        $form['exposed_fields']['new'][$record_id . '-' . $field_id . '-table'] = array(
           '#type' => 'hidden',
           '#value' => $node->template->template_array[$record_id]['table'],
         );
-        $form['exposed_fields']['new'][$record_id.'-'.$field_id.'-field'] = array(
+        $form['exposed_fields']['new'][$record_id . '-' . $field_id . '-field'] = array(
           '#type' => 'hidden',
           '#value' => $field['field'],
         );
-        $form['exposed_fields']['new'][$record_id.'-'.$field_id.'-type'] = array(
+        $form['exposed_fields']['new'][$record_id . '-' . $field_id . '-type'] = array(
           '#type' => 'hidden',
           '#value' => $field['type'],
         );
@@ -227,25 +237,25 @@ function tripal_bulk_loader_set_constants_form ($form_state, $node) {
     '#type' => 'hidden',
     '#value' => serialize($node->template->template_array)
   );
-  
+
   $form['exposed_fields']['new']['indexes'] = array(
     '#type' => 'hidden',
     '#value' => serialize($indexes),
   );
-  
+
   if (!$exposed_fields) {
     $form['exposed_fields']['new']['explanation'] = array(
       '#type' => 'item',
       '#value' => t('There are no exposed fields for this template.')
-    );    
+    );
   }
-  
+
   $form['exposed_fields']['new']['submit-2'] = array(
     '#type' => 'submit',
     '#name' => 'add_constant',
     '#value' => t('Add Constant Set')
   );
-  
+
   return $form;
 }
 
@@ -253,89 +263,99 @@ function tripal_bulk_loader_set_constants_form ($form_state, $node) {
  * Validate that the values entered exist in the database
  * if indicated in hte template array
  */
-function tripal_bulk_loader_set_constants_form_validate ($form, $form_state) {
+function tripal_bulk_loader_set_constants_form_validate($form, $form_state) {
 
   $template = unserialize($form_state['values']['template']);
   $indexes = unserialize($form_state['values']['indexes']);
 
   $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
-  if (strcmp('Add Constant Set',$op) == 0) {
+  if (strcmp('Add Constant Set', $op) == 0) {
       foreach ($indexes as $record_id => $array) {
-        foreach($array as $field_id) {
+        foreach ($array as $field_id) {
           if ($template[$record_id]['fields'][$field_id]['exposed_validate']) {
             $result = db_fetch_object(db_query(
               "SELECT 1 as valid FROM %s WHERE %s='%s'",
               $template[$record_id]['table'],
               $template[$record_id]['fields'][$field_id]['field'],
-              $form_state['values'][$record_id.'-'.$field_id]
+              $form_state['values'][$record_id . '-' . $field_id]
             ));
-    
+
             if (!$result->valid) {
-              $msg = 'A '.$form['exposed_fields']['new'][$record_id.'-'.$field_id]['#title'].' of "'.$form['exposed_fields']['new'][$record_id.'-'.$field_id]['#value'].'" must already exist!';
-              form_set_error($record_id.'-'.$field_id, $msg);
-            } else {
-              drupal_set_message('Confirmed a '.$form['exposed_fields']['new'][$record_id.'-'.$field_id]['#title'].' of "'.$form['exposed_fields']['new'][$record_id.'-'.$field_id]['#value'].'" already exists.');
+              $msg = 'A ' . $form['exposed_fields']['new'][$record_id . '-' . $field_id]['#title'] . ' of "' . $form['exposed_fields']['new'][$record_id . '-' . $field_id]['#value'] . '" must already exist!';
+              form_set_error($record_id . '-' . $field_id, $msg);
+            }
+            else {
+              drupal_set_message(
+                t(
+                  'Confirmed a %title of "%value" already exists.',
+                  array(
+                    '%title' => $form['exposed_fields']['new'][$record_id . '-' . $field_id]['#title'],
+                    '%value' => $form['exposed_fields']['new'][$record_id . '-' . $field_id]['#value']
+                  )
+                )
+              );
             }
           }
         }
       }
   }
-  
+
 }
 
 /**
  * Insert/update the constants associated with this node
  */
-function tripal_bulk_loader_set_constants_form_submit ($form, $form_state) {
+function tripal_bulk_loader_set_constants_form_submit($form, $form_state) {
 
-	// Insert/Update constants
+  // Insert/Update constants
   $template = unserialize($form_state['values']['template']);
   $indexes = unserialize($form_state['values']['indexes']);
 
   $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
-  if (strcmp('Add Constant Set',$op) == 0) {
-      $max_group = db_fetch_object(db_query("SELECT max(group_id) as value FROM tripal_bulk_loader_constants WHERE nid=%d",$form_state['values']['nid']));
+  if (strcmp('Add Constant Set', $op) == 0) {
+      $max_group = db_fetch_object(db_query("SELECT max(group_id) as value FROM {tripal_bulk_loader_constants} WHERE nid=%d", $form_state['values']['nid']));
       foreach ($indexes as $record_id => $array) {
-        foreach($array as $field_id) {	
+        foreach ($array as $field_id) {
           tripal_bulk_loader_update_constant(
-            $form_state['values']['nid'], 
+            $form_state['values']['nid'],
             $max_group->value+1,
-            $form_state['values'][$record_id.'-'.$field_id.'-table'], 
-            $form_state['values'][$record_id.'-'.$field_id.'-field'],
+            $form_state['values'][$record_id . '-' . $field_id . '-table'],
+            $form_state['values'][$record_id . '-' . $field_id . '-field'],
             $record_id,
             $field_id,
-            $form_state['values'][$record_id.'-'.$field_id]
+            $form_state['values'][$record_id . '-' . $field_id]
           );
         }
       }
   }
-  
+
 }
 
-function theme_tripal_bulk_loader_set_constants_form ($form) {
+function theme_tripal_bulk_loader_set_constants_form($form) {
   $output = '';
-  
+
   $exposed_fields = unserialize($form['exposed_array']['#value']);
   // need to put in the context of a node so we can use the has_exposed_fields function
   if ($exposed_fields) {
     $node->exposed_fields = $exposed_fields;
-  } else {
+  }
+  else {
     $node->exposed_fields = array();
   }
-  
+
   // Add draggable table for constant sets
   if (tripal_bulk_loader_has_exposed_fields($node)) {
     $i=1;
     foreach (element_children($form['exposed_fields']['existing']) as $key) {
       $element = &$form['exposed_fields']['existing'][$key];
       $element['group']['#attributes']['class'] = 'weight-group';
-  
+
       $row = array();
       foreach ($exposed_fields as $exposed) {
         if ($i==1) {
           $header[] = $exposed['title'];
         }
-        $k = $exposed['record_id'].'-'.$exposed['field_id'];
+        $k = $exposed['record_id'] . '-' . $exposed['field_id'];
         $row[] = drupal_render($element[$k]);
       }
       $row[] = drupal_render($element['delete']);
@@ -349,7 +369,7 @@ function theme_tripal_bulk_loader_set_constants_form ($form) {
       '#value' => theme('table', $header, $rows, array('id' => 'mytable')) . '<br />'
     );
   }
-    
+
   $output .= drupal_render($form);
   return $output;
 }
@@ -361,7 +381,7 @@ function theme_tripal_bulk_loader_set_constants_form ($form) {
 /**
  * Edit a constant set (exposed fields in template)
  *
- * @param $form_state 
+ * @param $form_state
  *   The current state of the form
  * @param $node
  *   The node to set constants for
@@ -371,11 +391,11 @@ function theme_tripal_bulk_loader_set_constants_form ($form) {
  * @return
  *   A form array to be rendered by drupal_get_form()
  */
-function tripal_bulk_loader_edit_constant_set_form ($form_state, $node, $group_id) {
+function tripal_bulk_loader_edit_constant_set_form($form_state, $node, $group_id) {
   $form = array();
 
-  $form['#redirect'] = 'node/'.$node->nid;
-  
+  $form['#redirect'] = 'node/' . $node->nid;
+
   $form['nid'] = array(
     '#type' => 'hidden',
     '#value' => $node->nid,
@@ -386,18 +406,18 @@ function tripal_bulk_loader_edit_constant_set_form ($form_state, $node, $group_i
     '#value' => $group_id,
   );
 
-    
+
   $form['explanation'] = array(
     '#type' => 'item',
     '#value' => t('The following fields are constants in the selected template that you need to set values for.')
   );
-  
+
   // Add textifelds for exposed fields of the current template
   $exposed_fields = FALSE;
   $indexes = array();
   if (tripal_bulk_loader_has_exposed_fields($node)) {
     foreach ($node->exposed_fields as $exposed_index) {
-      
+
       $record_id = $exposed_index['record_id'];
       $field_id = $exposed_index['field_id'];
       $field = $node->template->template_array[$record_id]['fields'][$field_id];
@@ -405,35 +425,35 @@ function tripal_bulk_loader_edit_constant_set_form ($form_state, $node, $group_i
       if ($field['exposed']) {
         $exposed_fields = TRUE;
         $indexes[$record_id][] = $field_id;
-        
-        switch($field['type']) {
+
+        switch ($field['type']) {
           case 'table field':
-            $form[$record_id.'-'.$field_id] = array(
+            $form[$record_id . '-' . $field_id] = array(
               '#type' => 'textfield',
-              '#title' => t($field['title']),
-              '#description' => t($field['exposed_description']),
+              '#title' => t('%title', array('%title' => $field['title'])),
+              '#description' => t('%exposed_description', array('%exposed_description' => $field['exposed_description'])),
               '#default_value' => (isset($node->constants[$group_id][$record_id][$field_id]['value'])) ? $node->constants[$group_id][$record_id][$field_id]['value'] : $field['constant value'],
             );
           break;
           case 'constant':
-            $form[$record_id.'-'.$field_id] = array(
+            $form[$record_id . '-' . $field_id] = array(
               '#type' => 'textfield',
-              '#title' => t($field['title']),
+              '#title' => t('%title', array('%title' => $field['title'])),
               '#description' => t('Enter the case-sensitive value of this constant for your spreadsheet'),
               '#default_value' => (isset($node->constants[$group_id][$record_id][$field_id]['value'])) ? $node->constants[$group_id][$record_id][$field_id]['value'] : $field['constant value'],
             );
           break;
         }
-        
-        $form[$record_id.'-'.$field_id.'-table'] = array(
+
+        $form[$record_id . '-' . $field_id . '-table'] = array(
           '#type' => 'hidden',
           '#value' => $record['table'],
         );
-        $form[$record_id.'-'.$field_id.'-field'] = array(
+        $form[$record_id . '-' . $field_id . '-field'] = array(
           '#type' => 'hidden',
           '#value' => $field['field'],
         );
-        $form[$record_id.'-'.$field_id.'-type'] = array(
+        $form[$record_id . '-' . $field_id . '-type'] = array(
           '#type' => 'hidden',
           '#value' => $field['type'],
         );
@@ -445,60 +465,60 @@ function tripal_bulk_loader_edit_constant_set_form ($form_state, $node, $group_i
     '#type' => 'hidden',
     '#value' => serialize($node->template->template_array)
   );
-  
+
   $form['indexes'] = array(
     '#type' => 'hidden',
     '#value' => serialize($indexes),
   );
-  
+
   $form['save'] = array(
     '#type' => 'submit',
     '#value' => 'Save',
   );
-  
+
   $form['cancel'] = array(
     '#type' => 'submit',
     '#value' => 'Cancel',
   );
-    
+
   return $form;
 }
 
 /**
  * Edit constants in the current constant set
  */
-function tripal_bulk_loader_edit_constant_set_form_submit ($form, $form_state) {
-  
+function tripal_bulk_loader_edit_constant_set_form_submit($form, $form_state) {
+
   // Update constants
   $template = unserialize($form_state['values']['template']);
   $indexes = unserialize($form_state['values']['indexes']);
-  
+
   $op = $form_state['values'][ $form_state['clicked_button']['#name'] ];
-  if (strcmp('Save',$op) == 0) {
+  if (strcmp('Save', $op) == 0) {
 
     foreach ($indexes as $record_id => $array) {
-      foreach($array as $field_id) {	
+      foreach ($array as $field_id) {
         tripal_bulk_loader_update_constant(
-          $form_state['values']['nid'], 
+          $form_state['values']['nid'],
           $form_state['values']['group_id'],
-          $form_state['values'][$record_id.'-'.$field_id.'-table'], 
-          $form_state['values'][$record_id.'-'.$field_id.'-field'],
+          $form_state['values'][$record_id . '-' . $field_id . '-table'],
+          $form_state['values'][$record_id . '-' . $field_id . '-field'],
           $record_id,
           $field_id,
-          $form_state['values'][$record_id.'-'.$field_id]
+          $form_state['values'][$record_id . '-' . $field_id]
         );
       }
     }
     drupal_set_message('The constant set was successfully updated.');
-      
+
   }
-  
+
 }
 
 /**
  * Delete a constant set (exposed fields in template)
  *
- * @param $form_state 
+ * @param $form_state
  *   The current state of the form
  * @param $node
  *   The node to set constants for
@@ -508,41 +528,41 @@ function tripal_bulk_loader_edit_constant_set_form_submit ($form, $form_state) {
  * @return
  *   A form array to be rendered by drupal_get_form()
  */
-function tripal_bulk_loader_delete_constant_set_form ($form_state, $node, $group_id) {
+function tripal_bulk_loader_delete_constant_set_form($form_state, $node, $group_id) {
   $form = array();
 
-  $form['#redirect'] = 'node/'.$node->nid;
-	
-	$form['nid'] = array(
-		'#type' => 'value',
-		'#value' => $node->nid,
-	);
+  $form['#redirect'] = 'node/' . $node->nid;
+
+  $form['nid'] = array(
+    '#type' => 'value',
+    '#value' => $node->nid,
+  );
 
   $form['group_id'] = array(
     '#type' => 'hidden',
     '#value' => $group_id,
   );
-   
-	return confirm_form($form,
-    	t('Are you sure you want to delete this constant set?'),
-    	'node/'.$node->nid,
-    	t('This action cannot be undone.'),
-    	t('Delete'),
-    	t('Cancel')
+
+  return confirm_form($form,
+      t('Are you sure you want to delete this constant set?'),
+      'node/' . $node->nid,
+      t('This action cannot be undone.'),
+      t('Delete'),
+      t('Cancel')
   );
-  
+
 }
 
 /**
  * Delete the current constant set
  */
-function tripal_bulk_loader_delete_constant_set_form_submit ($form, $form_state) {
+function tripal_bulk_loader_delete_constant_set_form_submit($form, $form_state) {
 
   $group_id = $form_state['values']['group_id'];
   $nid = $form_state['values']['nid'];
   if ($nid && $form_state['values']['confirm']) {
-    db_query("DELETE FROM {tripal_bulk_loader_constants} WHERE nid=%d AND group_id=%d",$nid, $group_id);
+    db_query("DELETE FROM {tripal_bulk_loader_constants} WHERE nid=%d AND group_id=%d", $nid, $group_id);
     drupal_set_message('Constant set successfully deleted.');
   }
-        
-}
+
+}

+ 86 - 81
tripal_bulk_loader/tripal_bulk_loader.install

@@ -1,16 +1,21 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 
 /**
  * Implements hook_install
  */
-function tripal_bulk_loader_install(){
+function tripal_bulk_loader_install() {
    drupal_install_schema('tripal_bulk_loader');
 }
 
 /**
  * Implements hook_uninstall
  */
-function tripal_bulk_loader_uninstall(){
+function tripal_bulk_loader_uninstall() {
    drupal_uninstall_schema('tripal_bulk_loader');
 }
 
@@ -23,93 +28,93 @@ function tripal_bulk_loader_uninstall(){
  *  - tripal_bulk_loader_inserted: Keeps track of all records inserted for a given bulk loading job
  */
 function tripal_bulk_loader_schema() {
-	$schema = array();
-	$schema['tripal_bulk_loader'] = array(
+  $schema = array();
+  $schema['tripal_bulk_loader'] = array(
       'fields' => array(
          'nid' => array(
             'type' => 'int',
             'unsigned' => TRUE,
             'not null' => TRUE,
-			),
+      ),
          'loader_name' => array(
             'type' => 'varchar',
-			),
+      ),
          'template_id' => array(
             'type' => 'varchar',
-			),
-			'file' => array(
+      ),
+      'file' => array(
         'type' => 'varchar',
         'not null' => TRUE
-			),
-			'job_id' => array(
-			  'type' => 'int',
-			),
-			'job_status' => array(
-			  'type' => 'varchar',
-			),
-			'file_has_header' => array(
-				'type' => 'int',
-				'size' => 'tiny',
-				'not null' => TRUE,
+      ),
+      'job_id' => array(
+        'type' => 'int',
+      ),
+      'job_status' => array(
+        'type' => 'varchar',
+      ),
+      'file_has_header' => array(
+        'type' => 'int',
+        'size' => 'tiny',
+        'not null' => TRUE,
         'default' => 0,
-			),
-		),
-  		'primary key' => array('nid'),
-  		'unique keys' => array(
-    		'name' => array('loader_name')
-		),
-	);
-	$schema['tripal_bulk_loader_template'] = array(
+      ),
+    ),
+      'primary key' => array('nid'),
+      'unique keys' => array(
+        'name' => array('loader_name')
+    ),
+  );
+  $schema['tripal_bulk_loader_template'] = array(
       'fields' => array(
          'template_id' => array(
             'type' => 'serial',
             'unsigned' => TRUE,
             'not null' => TRUE,
-			),
-			'name' => array(
+      ),
+      'name' => array(
             'type' => 'varchar',
-			),
+      ),
          'template_array' => array(
             'type' => 'varchar',
-			)
-		),
-  		'primary key' => array('template_id'),
-		'unique keys' => array(
-    		'name' => array('name')
-		),
-	);
-	$schema['tripal_bulk_loader_inserted'] = array(
-	  'fields' => array(
-	    'tripal_bulk_loader_inserted_id' => array(
-	      'type' => 'serial',
-	      'not null' => TRUE
-	    ),
+      )
+    ),
+      'primary key' => array('template_id'),
+    'unique keys' => array(
+        'name' => array('name')
+    ),
+  );
+  $schema['tripal_bulk_loader_inserted'] = array(
+    'fields' => array(
+      'tripal_bulk_loader_inserted_id' => array(
+        'type' => 'serial',
+        'not null' => TRUE
+      ),
       'nid' => array(
         'type' => 'int',
         'unsigned' => TRUE,
         'not null' => TRUE,
-			),
-			'table_inserted_into' => array(
-			  'type' => 'varchar',
-			  'not null' => TRUE,
-			),
-			'table_primary_key' => array(
-			  'type' => 'varchar',
-			  'not null' => TRUE,
-			),
-			'ids_inserted' => array(
-			  'type' => 'text',
-			  'not null' => TRUE
-			),
-	  ),
-	  'primary key' => array('tripal_bulk_loader_inserted_id'),
-	);
-	$schema['tripal_bulk_loader_constants'] = array(
-	  'fields' => array(
-	    'constant_id' => array(
-	      'type' => 'serial',
-	      'not null' => TRUE
-	    ),
+      ),
+      'table_inserted_into' => array(
+        'type' => 'varchar',
+        'not null' => TRUE,
+      ),
+      'table_primary_key' => array(
+        'type' => 'varchar',
+        'not null' => TRUE,
+      ),
+      'ids_inserted' => array(
+        'type' => 'text',
+        'not null' => TRUE
+      ),
+    ),
+    'primary key' => array('tripal_bulk_loader_inserted_id'),
+  );
+  $schema['tripal_bulk_loader_constants'] = array(
+    'fields' => array(
+      'constant_id' => array(
+        'type' => 'serial',
+        'not null' => TRUE
+      ),
       'nid' => array(
         'type' => 'int',
         'unsigned' => TRUE,
@@ -140,41 +145,41 @@ function tripal_bulk_loader_schema() {
       'value' => array(
         'type' => 'text',
       ),
-	  ),
-	  'primary key' => array('constant_id'),
-	);
-	
-	return $schema;
+    ),
+    'primary key' => array('constant_id'),
+  );
+
+  return $schema;
 }
 
 /**
  * Update schema for version 6.x-0.3.1b-1.5
  * - Add the tripal_bulk_loader_constants table
  */
-function tripal_bulk_loader_update_6150 () {
+function tripal_bulk_loader_update_6150() {
 
   // Create tripal_bulk_loader_constants table
   $schema = tripal_bulk_loader_schema();
   $ret = array();
   db_create_table($ret, 'tripal_bulk_loader_constants', $schema['tripal_bulk_loader_constants']);
-  
+
   return $ret;
-  
+
 }
 
 /**
  * Update schema for version 6.x-0.3.1b-1.5
- * - Add the tripal_bulk_loader_constants.group_id column 
+ * - Add the tripal_bulk_loader_constants.group_id column
  *   to allow multiple sets of constants per job
  */
-function tripal_bulk_loader_update_6151 () {
+function tripal_bulk_loader_update_6151() {
   $ret = array();
-  
+
   $schema = tripal_bulk_loader_schema();
   db_add_field(
-    $ret, 
-    'tripal_bulk_loader_constants', 
-    'group_id', 
+    $ret,
+    'tripal_bulk_loader_constants',
+    'group_id',
     array(
         'type' => 'int',
         'unsigned' => TRUE,
@@ -183,5 +188,5 @@ function tripal_bulk_loader_update_6151 () {
       )
     );
 
-  return $ret;  
-}
+  return $ret;
+}

+ 239 - 186
tripal_bulk_loader/tripal_bulk_loader.loader.inc

@@ -1,29 +1,34 @@
 <?php
 
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 /**
  * Add Loader Job Form
  *
- * This form is meant to be included on the node page to allow users to submit/re-submit 
+ * This form is meant to be included on the node page to allow users to submit/re-submit
  * loading jobs
  */
-function tripal_bulk_loader_add_loader_job_form ($form_state, $node) {
+function tripal_bulk_loader_add_loader_job_form($form_state, $node) {
   $form = array();
-  
+
   $form['nid'] = array(
     '#type' => 'hidden',
     '#value' => $node->nid,
-  ); 
-  
+  );
+
   $form['file'] = array(
-  	'#type' => 'hidden',
-  	'#value' => $node->file
+    '#type' => 'hidden',
+    '#value' => $node->file
   );
-  
+
   $form['job_id'] = array(
     '#type' => 'hidden',
     '#value' => $node->job_id,
   );
-  
+
   $form['submit'] = array(
     '#type' => 'submit',
     '#value' => ($node->job_id) ? 'Re-Submit Job' : 'Submit Job',
@@ -33,60 +38,65 @@ function tripal_bulk_loader_add_loader_job_form ($form_state, $node) {
     '#type' => ($node->job_id)? 'submit' : 'hidden',
     '#value' => 'Cancel Job',
   );
-  
+
   $form['submit-revert'] = array(
     '#type' => ($node->job_id) ? 'submit' : 'hidden',
     '#value' => 'Revert',
-  );  
-  
+  );
+
   return $form;
 }
 
 /**
  * Add Loader Job Form (Submit)
  */
-function tripal_bulk_loader_add_loader_job_form_submit ($form, $form_state) {
+function tripal_bulk_loader_add_loader_job_form_submit($form, $form_state) {
   global $user;
-  
+
   if (preg_match('/Submit Job/', $form_state['values']['op'])) {
     //Submit Tripal Job
-		$job_args[1] = $form_state['values']['nid'];
-		if (is_readable($form_state['values']['file'])) {
-			$fname = basename($form_state['values']['file']);
-			$job_id = tripal_add_job("Bulk Loading Job: $fname",'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
-			
-			// add job_id to bulk_loader node
+    $job_args[1] = $form_state['values']['nid'];
+    if (is_readable($form_state['values']['file'])) {
+      $fname = basename($form_state['values']['file']);
+      $job_id = tripal_add_job("Bulk Loading Job: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
+
+      // add job_id to bulk_loader node
       $success = db_query("UPDATE {tripal_bulk_loader} SET job_id=%d WHERE nid=%d", $job_id, $form_state['values']['nid']);
-      
+
       // change status
-      db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Submitted to Queue', $form_state['values']['nid']);
-		} else {
-			drupal_set_message("Can not open ".$form_state['values']['file'].". Job not scheduled.");
-		}    
-  } elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
+      db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
+    }
+    else {
+      drupal_set_message(t("Can not open %file. Job not scheduled.", array('%file' => $form_state['values']['file'])));
+    }
+  }
+  elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
     tripal_jobs_rerun($form_state['values']['job_id']);
-    db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Submitted to Queue', $form_state['values']['nid']);
-  } elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
-    db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Job Cancelled', $form_state['values']['nid']);
+    db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
+  }
+  elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
+    db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Job Cancelled', $form_state['values']['nid']);
     tripal_jobs_cancel($form_state['values']['job_id']);
-  } elseif (preg_match('/Revert/', $form_state['values']['op'])) {
-  
+  }
+  elseif (preg_match('/Revert/', $form_state['values']['op'])) {
+
     // Remove the records from the database that were already inserted
     $resource = db_query('SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d ORDER BY tripal_bulk_loader_inserted_id DESC', $form_state['values']['nid']);
     while ($r = db_fetch_object($resource)) {
-      $ids = preg_split('/,/',$r->ids_inserted);
-      db_query('DELETE FROM %s WHERE %s IN (%s)',$r->table_inserted_into, $r->table_primary_key, $r->ids_inserted);
+      $ids = preg_split('/,/', $r->ids_inserted);
+      db_query('DELETE FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted);
       $result = db_fetch_object(db_query('SELECT true as present FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted));
       if (!$result->present) {
-        drupal_set_message('Successfully Removed data Inserted into the '.$r->table_inserted_into.' table.');
-        db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=%d',$r->tripal_bulk_loader_inserted_id);
-      } else {
-        drupal_set_message('Unable to remove data Inserted into the '.$r->table_inserted_into.' table!', 'error');
+        drupal_set_message(t('Successfully Removed data Inserted into the %tableto table.', array('%tableto' => $r->table_inserted_into)));
+        db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=%d', $r->tripal_bulk_loader_inserted_id);
+      }
+      else {
+        drupal_set_message(t('Unable to remove data Inserted into the %tableto table!', array('%tableto' => $r->table_inserted_into)), 'error');
       }
     }
-    
+
     // reset status
-    db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Reverted -Data Deleted', $form_state['values']['nid']);
+    db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Reverted -Data Deleted', $form_state['values']['nid']);
   }
 
 }
@@ -97,75 +107,80 @@ function tripal_bulk_loader_add_loader_job_form_submit ($form, $form_state) {
  * This is the function that's run by tripal_launch_jobs to bulk load chado data.
  *
  * @param $nid
- *   The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be 
+ *   The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be
  *   in the node (ie: template ID and file)
  *
  * Note: Instead of returning a value this function updates the tripal_bulk_loader.status.
  *   Errors are thrown through watchdog and can be viewed at admin/reports/dblog.
  */
 function tripal_bulk_loader_load_data($nid) {
-  
+
   // ensure no timeout
   set_time_limit(0);
-  
+
   // set the status of the job (in the node not the tripal jobs)
-  db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Loading...', $nid);
+  db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Loading...', $nid);
+
 
-  
   $node = node_load($nid);
-  print "Template: ".$node->template->name." (".$node->template_id.")\n";
+  print "Template: " . $node->template->name . " (" . $node->template_id . ")\n";
 
   $total_lines = trim(`wc --lines < $node->file`);
-  print "File: ".$node->file." (".$total_lines." lines)\n";
-  
+  print "File: " . $node->file . " (" . $total_lines . " lines)\n";
+
   // Prep Work ==================================================================================
   $loaded_without_errors = TRUE;
-  
+
   // Generate default values array
   $default_data = array();
   $field2column = array();
   $record2priority = array();
 
   foreach ($node->template->template_array as $priority => $record_array) {
-    if (!is_array($record_array)) { continue; }
+    if (!is_array($record_array)) {
+      continue;
+    }
 
     //watchdog('T_bulk_loader','1)'.$record_array['record_id']." => \n<pre>".print_r($record_array,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-    
+
     foreach ($record_array['fields'] as $field_index => $field_array) {
-      
+
       $default_data[$priority]['table'] = $record_array['table'];
       $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert_unique';
       $default_data[$priority]['record_id'] = $record_array['record_id'];
       $record2priority[$record_array['record_id']] = $priority;
       $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
-      
+
       $one = $default_data[$priority];
       if (isset($field_array['regex'])) {
         $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
       }
-      
+
       $two = $default_data[$priority];
-      
+
       if (preg_match('/table field/', $field_array['type'])) {
         $default_data[$priority]['values_array'][$field_array['field']] = '';
         $default_data[$priority]['need_further_processing'] = TRUE;
         $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
-        
-      } elseif (preg_match('/constant/', $field_array['type'])) {
+
+      }
+      elseif (preg_match('/constant/', $field_array['type'])) {
         $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
-        
-      } elseif (preg_match('/foreign key/', $field_array['type'])) {
+
+      }
+      elseif (preg_match('/foreign key/', $field_array['type'])) {
         $default_data[$priority]['values_array'][$field_array['field']] = array();
         $default_data[$priority]['values_array'][$field_array['field']]['foreign record'] = $field_array['foreign key'];
         $default_data[$priority]['need_further_processing'] = TRUE;
-        
-      } else {
-        print 'WARNING: Unsupported type: '. $field_array['type'] . ' for ' . $table . '.' . $field_array['field']."!\n";
-      }   
-      
+
+      }
+      else {
+        print 'WARNING: Unsupported type: ' . $field_array['type'] . ' for ' . $table . '.' . $field_array['field'] . "!\n";
+      }
+
       $three = $default_data[$priority];
       //watchdog('T_bulk_loader','A)'.$field_index.':<pre>Field Array =>'.print_r($field_array,TRUE)."Initial => \n".print_r($one, TRUE)."\nAfter Regex =>".print_r($two, TRUE)."Final =>\n".print_r($three,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-      
+
     } // end of foreach field
     //watchdog('T_bulk_loader','2)'.$record_array['record_id'].':<pre>'.print_r($default_data[$priority], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
   } //end of foreach record
@@ -180,203 +195,220 @@ function tripal_bulk_loader_load_data($nid) {
     // revert default data array for next set of constants
     $default_data = $original_default_data;
     $group_index++;
-    
+
     // Add constants
     if (!empty($set)) {
       print "Constants:\n";
       foreach ($set as $priority => $record) {
         foreach ($record as $field_id => $field) {
-        
-          print "\t- ".$field['chado_table'].'.'.$field['chado_field'].' = '.$field['value']."\n";
-          
+
+          print "\t- " . $field['chado_table'] . '.' . $field['chado_field'] . ' = ' . $field['value'] . "\n";
+
           if ($default_data[$priority]['table'] == $field['chado_table']) {
             if (isset($default_data[$priority]['values_array'][$field['chado_field']])) {
               if (isset($field2column[$priority][$field['chado_field']])) {
                 $field2column[$priority][$field['chado_field']] = $field['value'];
-              } else {
+              }
+              else {
                 $default_data[$priority]['values_array'][$field['chado_field']] = $field['value'];
               }
-            } else {
+            }
+            else {
               print "ERROR: Template has changed after constants were assigned!\n";
-              watchdog('T_bulk_loader','Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
+              watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
               exit(1);
             }
-          } else {
+          }
+          else {
             print "ERROR: Template has changed after constants were assigned!\n";
-            watchdog('T_bulk_loader','Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
+            watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
             exit(1);
           }
         }
       }
     }
-    
+
     //print "Default Data:".print_r($default_data,TRUE)."\n";
     //watchdog('T_bulk_loader','Default Data:<pre>'.print_r($default_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-    
+
     //print "\nDefault Values Array: ".print_r($default_data, TRUE)."\n";
     //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
-    
+
     // Parse File adding records as we go ========================================================
     $file_handle = fopen($node->file, 'r');
-    if (preg_match('/(t|true|1)/', $node->file_has_header)) { fgets($file_handle, 4096); }
+    if (preg_match('/(t|true|1)/', $node->file_has_header)) {
+      fgets($file_handle, 4096);
+    }
     $num_records = 0;
     $num_lines = 0;
     $num_errors = 0;
     $interval = intval($total_lines * 0.10);
-    if($interval == 0){ $interval = 1; }
+    if ($interval == 0) {
+       $interval = 1;
+     }
     while (!feof($file_handle)) {
-  
+
       // Clear variables
       // Was added to fix memory leak
       unset($line);                     unset($raw_line);
       unset($data);                     unset($data_keys);
       unset($priority);                 unset($sql);
-      unset($result);                   
-      
+      unset($result);
+
       $raw_line = fgets($file_handle, 4096);
       $raw_line = trim($raw_line);
-      if (empty($raw_line)) { continue; } // skips blank lines
+      if (empty($raw_line)) {
+        continue;
+      } // skips blank lines
       $line = explode("\t", $raw_line);
       $num_lines++;
-      
+
       // update the job status every 10% of lines processed for the current group
-      if($node->job_id and $num_lines % $interval == 0){
+      if ($node->job_id and $num_lines % $interval == 0) {
         // percentage of lines processed for the current group
         $group_progress = round(($num_lines/$total_lines)*100);
-        
+
         // percentage of lines processed for all groups
         // <previous group index> * 100 + <current group progress>
         // --------------------------------------------------------
         //               <total number of groups>
-        // For example, if you were in the third group of 3 constant sets 
+        // For example, if you were in the third group of 3 constant sets
         // and had a group percentage of 50% then the job progress would be
         // (2*100 + 50%) / 3 = 250%/3 = 83%
         $job_progress = round(((($group_index-1)*100)+$group_progress)/$total_num_groups);
-        
+
         /**
           print "\nProgress Update:\n"
             ."\t- ".$num_lines." lines have been processed for the current constant set.\n"
             ."\t- ".$group_progress."% of the lines in the file have been processed for the current constant set.\n"
             ."\t- ".$job_progress."% of the current job has been completed.\n";
         */
-         
-        tripal_job_set_progress($node->job_id,$job_progress);
-      }    
-  
+
+        tripal_job_set_progress($node->job_id, $job_progress);
+      }
+
       $data = $default_data;
-  
-      $data_keys = array_keys($data); 
+
+      $data_keys = array_keys($data);
       foreach ($data_keys as $priority) {
         $status = process_data_array_for_line($priority, $data, $default_data, $field2column, $record2priority, $line, $nid, $num_lines, $group_index);
-        if (!$status ) { $loaded_without_errors = FALSE; }
+        if (!$status ) {
+          $loaded_without_errors = FALSE;
+        }
       } // end of foreach table in default data array
-      
+
     } //end of foreach line of file
   } //end of foreach constant set
-    
+
   // check that data was inserted and update job_status
   $sql = 'SELECT count(*) as num_tables FROM {tripal_bulk_loader_inserted} WHERE nid=%d GROUP BY nid';
   $result = db_fetch_object(db_query($sql, $nid));
   if ($result->num_tables > 0) {
     $node->job_status = 'Data Inserted';
-    drupal_write_record('node',$node,'nid');
+    drupal_write_record('node', $node, 'nid');
   }
-  
+
   // set the status of the job (in the node not the tripal jobs)
-  if ($loaded_without_errors) { $status = 'Loading Completed Successfully'; } else { $status = 'Errors Encountered'; }
-  db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",$status, $nid);
+  if ($loaded_without_errors) {
+      $status = 'Loading Completed Successfully';
+    }
+    else {
+      $status = 'Errors Encountered';
+      }
+  db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", $status, $nid);
 
 }
 
 /**
- * 
+ *
  *
  */
-function process_data_array_for_line ($priority, &$data, &$default_data, $field2column, $record2priority, $line, $nid, $line_num, $group_index) {
+function process_data_array_for_line($priority, &$data, &$default_data, $field2column, $record2priority, $line, $nid, $line_num, $group_index) {
   $table_data = $data[$priority];
 
   $no_errors = TRUE;
 
   $table = $table_data['table'];
   $values = $table_data['values_array'];
-  
+
   //watchdog('T_bulk_loader','Original:<pre>'.print_r($table_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-  
+
   //print 'default values:'.print_r($values,TRUE)."\n";
   if ($table_data['need_further_processing']) {
-    $values = tripal_bulk_loader_add_spreadsheetdata_to_values ($values, $line, $field2column[$priority]);
+    $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column[$priority]);
     if (!$values) {
-      watchdog('T_bulk_loader','Line '.$line_num.' Spreadsheet Added:'.print_r($values, TRUE), array(), WATCHDOG_NOTICE);
+      watchdog('T_bulk_loader', 'Line ' . $line_num . ' Spreadsheet Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
     }
-    
+
     $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority);
     if (!$values) {
-      watchdog('T_bulk_loader','Line '.$line_num.' FK Added:<pre>'.print_r($values, TRUE).print_r($data[$priority],TRUE).'</pre>', array(), WATCHDOG_NOTICE);
+      watchdog('T_bulk_loader', 'Line ' . $line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
     }
   }
   $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $line);
   if (!$values) {
-    watchdog('T_bulk_loader','Line '.$line_num.' Regex:<pre>'.print_r($values, TRUE).print_r($table_data, TRUE).'</pre>'.'</pre>', array(), WATCHDOG_NOTICE);
+    watchdog('T_bulk_loader', 'Line ' . $line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
   }
 
   if (!$values) {
-    $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Aborted due to error in previous record. Values of current record:'.print_r($table_data['values_array'],TRUE);
-    watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING); 
-    print "ERROR: ".$msg."\n";
+    $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Aborted due to error in previous record. Values of current record:' . print_r($table_data['values_array'], TRUE);
+    watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
+    print "ERROR: " . $msg . "\n";
     $data[$priority]['error'] = TRUE;
     $no_errors = FALSE;
   }
-  
-  $table_desc = module_invoke_all('chado_'.$table.'_schema');
+
+  $table_desc = module_invoke_all('chado_' . $table . '_schema');
   if (preg_match('/optional/', $table_array['mode'])) {
     // Check all db required fields are set
     $fields = $table_desc['fields'];
-    foreach($fields as $field => $def){
+    foreach ($fields as $field => $def) {
       // a field is considered missing if it cannot be null and there is no default
       // value for it or it is of type 'serial'
-      if($def['not null'] == 1 and !array_key_exists($field,$insert_values) and !isset($def['default']) and strcmp($def['type'],serial)!=0){
-         $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Missing Database Required Value: '.$table.'.'.$field;
-         watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE); 
+      if ($def['not null'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial)!=0) {
+         $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
+         watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
          $data[$priority]['error'] = TRUE;
       }
     }
   } //end of if optional record
-  
+
   // Check required fields are present
   foreach ($table_data['required'] as $field => $required) {
     if ($required) {
       if (!isset($values[$field])) {
-        $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Missing Template Required Value: '.$table.'.'.$field;
-        watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE); 
-        $data[$priority]['error'] = TRUE;  
+        $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Template Required Value: ' . $table . '.' . $field;
+        watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
+        $data[$priority]['error'] = TRUE;
       }
     }
   }
-  
+
   // add new values array into the data array
   $data[$priority]['values_array'] = $values;
-  
+
   // check if it is already inserted
   if ($table_data['inserted']) {
     //watchdog('T_bulk_loader','Already Inserted:'.print_r($values,TRUE),array(),WATCHDOG_NOTICE);
     return $no_errors;
   }
-  
+
   // if there was an error already -> don't insert
   if ($data[$priority]['error']) {
     return $no_errors;
   }
-  
+
   $header = '';
   if (isset($values['feature_id'])) {
-    $header = $values['feature_id']['uniquename'] .' '. $table_data['record_id'];
-  } else {
-    $header = $values['uniquename'] .' '. $table_data['record_id'];
+    $header = $values['feature_id']['uniquename'] . ' ' . $table_data['record_id'];
+  }
+  else {
+    $header = $values['uniquename'] . ' ' . $table_data['record_id'];
   }
-  
+
   // if insert unique then check to ensure unique
-  if (preg_match('/insert_unique/',$table_data['mode'])) {
-    $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record'=>TRUE));
+  if (preg_match('/insert_unique/', $table_data['mode'])) {
+    $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
     //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
     if ($unique > 0) {
       //$default_data[$priority]['inserted'] = TRUE;
@@ -384,31 +416,39 @@ function process_data_array_for_line ($priority, &$data, &$default_data, $field2
       return $no_errors;
     }
   }
-  
-    
-  if (!preg_match('/select/',$table_data['mode'])) {
+
+
+  if (!preg_match('/select/', $table_data['mode'])) {
     //watchdog('T_bulk_loader',$header.': Inserting:'.print_r($values, TRUE), array(), WATCHDOG_NOTICE);
-    $options = array('statement_name' => $priority);
-    if ($line_num == 1 && $group_index == 1) {
-      $options['prepare'] = TRUE;
+    if (variable_get('tripal_bulk_loader_prepare',TRUE)) {
+      $options = array('statement_name' => $priority);
+      if ($line_num == 1 && $group_index == 1) {
+        $options['prepare'] = TRUE;
+      }
+    }
+    else {
+      $options = array();
     }
+
     $record = tripal_core_chado_insert($table, $values, $options);
+
     if (!$record) {
-      $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Unable to insert record into '.$table.' where values:'.print_r($values,TRUE);
-      watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR); 
-      print "ERROR: ".$msg."\n";  
+      $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Unable to insert record into ' . $table . ' where values:' . print_r($values, TRUE);
+      watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
+      print "ERROR: " . $msg . "\n";
       $data[$priority]['error'] = TRUE;
       $no_errors = FALSE;
-    } else {
+    }
+    else {
       //add changes back to values array
       $data[$priority]['values_array'] = $record;
       $values = $record;
-      
+
       // if mode=insert_once then ensure we only insert it once
-      if (preg_match('/insert_once/',$table_data['mode'])) {
+      if (preg_match('/insert_once/', $table_data['mode'])) {
         $default_data[$priority]['inserted'] = TRUE;
       }
-      
+
       // add to tripal_bulk_loader_inserted
       $insert_record = db_fetch_object(db_query(
         "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
@@ -420,7 +460,8 @@ function process_data_array_for_line ($priority, &$data, &$default_data, $field2
         drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
         //print 'Update: '.print_r($insert_record,TRUE)."\n";
         return $no_errors;
-      } else {
+      }
+      else {
         $insert_record = array(
           'nid' => $nid,
           'table_inserted_into' => $table,
@@ -431,15 +472,16 @@ function process_data_array_for_line ($priority, &$data, &$default_data, $field2
         $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
         return $no_errors;
       }//end of if insert record
-      
+
     } //end of if insert was successful
-  } else {
-    $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record'=>TRUE));
+  }
+  else {
+    $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
     if (!$exists) {
       // No record on select
-      $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') No Matching record in '.$table.' where values:'.print_r($values,TRUE);
-      watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING); 
-      $data[$priority]['error'] = TRUE;  
+      $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
+      watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
+      $data[$priority]['error'] = TRUE;
     }
   }
   return $no_errors;
@@ -454,24 +496,29 @@ function process_data_array_for_line ($priority, &$data, &$default_data, $field2
  *   An array of values for the current line
  * @param $field2column
  *   An array mapping values fields to line columns
- * @return 
+ * @return
  *   Supplemented values array
  */
-function tripal_bulk_loader_add_spreadsheetdata_to_values ($values, $line, $field2column) {
+function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
 
   foreach ($values as $field => $value) {
-    if (is_array($value)) { continue; }
-    
+    if (is_array($value)) {
+      continue;
+    }
+
     $column = $field2column[$field] - 1;
-    if ($column < 0) { continue; }
-    
-    if (preg_match('/\S+/',$line[$column])) {
+    if ($column < 0) {
+      continue;
+    }
+
+    if (preg_match('/\S+/', $line[$column])) {
       $values[$field] = $line[$column];
-    } else {
+    }
+    else {
       unset($values[$field]);
     }
   }
-  
+
   return $values;
 }
 
@@ -490,7 +537,7 @@ function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2pri
       $foreign_record = $value['foreign record'];
       $foreign_priority = $record2priority[$foreign_record];
       $foreign_values = $data[$foreign_priority]['values_array'];
-      
+
       // add to current values array
       $values[$field] = $foreign_values;
     }
@@ -507,42 +554,46 @@ function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2pri
  * @param $table_data
  *   The data array for the given table
  */
-function tripal_bulk_loader_regex_tranform_values ($values, $table_data, $line) {
+function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
+
+  if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) {
+    return $values;
+  }
 
-  if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) { return $values; }
-  
   //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
-  
+
   foreach ($table_data['regex_transform'] as $field => $regex_array) {
-    if (!is_array($regex_array['replace'])) { continue; }
-    
+    if (!is_array($regex_array['replace'])) {
+       continue;
+     }
+
     //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
     //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
     //print 'Was:'.$values[$field]."\n";
-    
+
     // Check for <#column:\d+#> notation
     // if present replace with that column in the current line
     foreach ($regex_array['replace'] as $key => $replace) {
       if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
         foreach ($matches[1] as $k => $column_num) {
-          $replace = preg_replace('/'.$matches[0][$k].'/', $line[$column_num-1], $replace);
+          $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
         }
         $regex_array['replace'][$key] = $replace;
       }
     }
-    
+
     // do the full replacement
     $old_value = $values[$field];
     $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
     $values[$field] = $new_value;
-    
+
     if ($values[$field] === '') {
-      unset($values[$field]); 
+      unset($values[$field]);
     }
     //print 'Now:'.$values[$field]."\n";
   }
-  
-  
+
+
 
   return $values;
 }
@@ -551,25 +602,27 @@ function tripal_bulk_loader_regex_tranform_values ($values, $table_data, $line)
  * Flattens an array up to two levels
  * Used for printing of arrays without taking up much space
  */
-function tripal_bulk_loader_flatten_array ($values) {
+function tripal_bulk_loader_flatten_array($values) {
   $flattened_values = array();
-  
+
   foreach ($values as $k => $v) {
     if (is_array($v)) {
       $vstr = array();
       foreach ($v as $vk => $vv) {
         if (strlen($vv) > 20) {
-          $vstr[] = $vk .'=>'. substr($vv, 0, 20) . '...';
-        } else {
-          $vstr[] = $vk .'=>'. $vv;
+          $vstr[] = $vk . '=>' . substr($vv, 0, 20) . '...';
+        }
+        else {
+          $vstr[] = $vk . '=>' . $vv;
         }
       }
-      $v = '{'. implode(',',$vstr) .'}';
-    } elseif (strlen($v) > 20) {
+      $v = '{' . implode(',', $vstr) . '}';
+    }
+    elseif (strlen($v) > 20) {
       $v = substr($v, 0, 20) . '...';
     }
-    $flattened_values[] = $k .'=>'. $v;
+    $flattened_values[] = $k . '=>' . $v;
   }
-  
-  return implode(', ',$flattened_values);
-}
+
+  return implode(', ', $flattened_values);
+}

+ 733 - 0
tripal_bulk_loader/tripal_bulk_loader.loader.inc.orig

@@ -0,0 +1,733 @@
+<?php
+
+/**
+ * @file
+ * @todo Add file header description
+ */
+
+/**
+ * Add Loader Job Form
+ *
+ * This form is meant to be included on the node page to allow users to submit/re-submit
+ * loading jobs
+ */
+function tripal_bulk_loader_add_loader_job_form($form_state, $node) {
+  $form = array();
+
+  $form['nid'] = array(
+    '#type' => 'hidden',
+    '#value' => $node->nid,
+  );
+
+  $form['file'] = array(
+    '#type' => 'hidden',
+    '#value' => $node->file
+  );
+
+  $form['job_id'] = array(
+    '#type' => 'hidden',
+    '#value' => $node->job_id,
+  );
+
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => ($node->job_id) ? 'Re-Submit Job' : 'Submit Job',
+  );
+
+  $form['submit-cancel'] = array(
+    '#type' => ($node->job_id)? 'submit' : 'hidden',
+    '#value' => 'Cancel Job',
+  );
+
+  $form['submit-revert'] = array(
+    '#type' => ($node->job_id) ? 'submit' : 'hidden',
+    '#value' => 'Revert',
+  );
+
+  return $form;
+}
+
+/**
+ * Add Loader Job Form (Submit)
+ */
+function tripal_bulk_loader_add_loader_job_form_submit($form, $form_state) {
+  global $user;
+
+  if (preg_match('/Submit Job/', $form_state['values']['op'])) {
+    //Submit Tripal Job
+<<<<<<< HEAD
+    $job_args[1] = $form_state['values']['nid'];
+    if (is_readable($form_state['values']['file'])) {
+      $fname = basename($form_state['values']['file']);
+      $job_id = tripal_add_job("Bulk Loading Job: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
+
+      // add job_id to bulk_loader node
+      $success = db_query("UPDATE {tripal_bulk_loader} SET job_id=%d WHERE nid=%d", $job_id, $form_state['values']['nid']);
+
+      // change status
+      db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
+    }
+    else {
+      drupal_set_message(t("Can not open %file. Job not scheduled.", array('%file' => $form_state['values']['file'])));
+    }
+  }
+  elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
+=======
+		$job_args[1] = $form_state['values']['nid'];
+		if (is_readable($form_state['values']['file'])) {
+			$fname = basename($form_state['values']['file']);
+			$job_id = tripal_add_job("Bulk Loading Job: $fname",'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
+
+			// add job_id to bulk_loader node
+      $success = db_query("UPDATE {tripal_bulk_loader} SET job_id=%d WHERE nid=%d", $job_id, $form_state['values']['nid']);
+
+      // change status
+      db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Submitted to Queue', $form_state['values']['nid']);
+		} else {
+			drupal_set_message("Can not open ".$form_state['values']['file'].". Job not scheduled.");
+		}
+  } elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
+>>>>>>> 6.x-0.4-dev
+    tripal_jobs_rerun($form_state['values']['job_id']);
+    db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
+  }
+  elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
+    db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Job Cancelled', $form_state['values']['nid']);
+    tripal_jobs_cancel($form_state['values']['job_id']);
+<<<<<<< HEAD
+  }
+  elseif (preg_match('/Revert/', $form_state['values']['op'])) {
+=======
+  } elseif (preg_match('/Revert/', $form_state['values']['op'])) {
+>>>>>>> 6.x-0.4-dev
+
+    // Remove the records from the database that were already inserted
+    $resource = db_query('SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d ORDER BY tripal_bulk_loader_inserted_id DESC', $form_state['values']['nid']);
+    while ($r = db_fetch_object($resource)) {
+      $ids = preg_split('/,/', $r->ids_inserted);
+      db_query('DELETE FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted);
+      $result = db_fetch_object(db_query('SELECT true as present FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted));
+      if (!$result->present) {
+        drupal_set_message(t('Successfully Removed data Inserted into the %tableto table.', array('%tableto' => $r->table_inserted_into)));
+        db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=%d', $r->tripal_bulk_loader_inserted_id);
+      }
+      else {
+        drupal_set_message(t('Unable to remove data Inserted into the %tableto table!', array('%tableto' => $r->table_inserted_into)), 'error');
+      }
+    }
+
+    // reset status
+    db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Reverted -Data Deleted', $form_state['values']['nid']);
+  }
+
+}
+
+/**
+ * Tripal Bulk Loader
+ *
+ * This is the function that's run by tripal_launch_jobs to bulk load chado data.
+ *
+ * @param $nid
+ *   The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be
+ *   in the node (ie: template ID and file)
+ *
+ * Note: Instead of returning a value this function updates the tripal_bulk_loader.status.
+ *   Errors are thrown through watchdog and can be viewed at admin/reports/dblog.
+ */
+function tripal_bulk_loader_load_data($nid) {
+
+  // ensure no timeout
+  set_time_limit(0);
+
+  // set the status of the job (in the node not the tripal jobs)
+  db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Loading...', $nid);
+
+
+<<<<<<< HEAD
+=======
+
+>>>>>>> 6.x-0.4-dev
+  $node = node_load($nid);
+  print "Template: " . $node->template->name . " (" . $node->template_id . ")\n";
+
+  $total_lines = trim(`wc --lines < $node->file`);
+<<<<<<< HEAD
+  print "File: " . $node->file . " (" . $total_lines . " lines)\n";
+=======
+  print "File: ".$node->file." (".$total_lines." lines)\n";
+>>>>>>> 6.x-0.4-dev
+
+  // Prep Work ==================================================================================
+  $loaded_without_errors = TRUE;
+
+  // Generate default values array
+  $default_data = array();
+  $field2column = array();
+  $record2priority = array();
+
+  foreach ($node->template->template_array as $priority => $record_array) {
+    if (!is_array($record_array)) {
+      continue;
+    }
+
+    //watchdog('T_bulk_loader','1)'.$record_array['record_id']." => \n<pre>".print_r($record_array,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
+
+    foreach ($record_array['fields'] as $field_index => $field_array) {
+
+      $default_data[$priority]['table'] = $record_array['table'];
+      $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert_unique';
+      $default_data[$priority]['record_id'] = $record_array['record_id'];
+      $record2priority[$record_array['record_id']] = $priority;
+      $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
+
+      $one = $default_data[$priority];
+      if (isset($field_array['regex'])) {
+        $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
+      }
+
+      $two = $default_data[$priority];
+
+      if (preg_match('/table field/', $field_array['type'])) {
+        $default_data[$priority]['values_array'][$field_array['field']] = '';
+        $default_data[$priority]['need_further_processing'] = TRUE;
+        $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
+
+<<<<<<< HEAD
+      }
+      elseif (preg_match('/constant/', $field_array['type'])) {
+        $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
+
+      }
+      elseif (preg_match('/foreign key/', $field_array['type'])) {
+=======
+      } elseif (preg_match('/constant/', $field_array['type'])) {
+        $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
+
+      } elseif (preg_match('/foreign key/', $field_array['type'])) {
+>>>>>>> 6.x-0.4-dev
+        $default_data[$priority]['values_array'][$field_array['field']] = array();
+        $default_data[$priority]['values_array'][$field_array['field']]['foreign record'] = $field_array['foreign key'];
+        $default_data[$priority]['need_further_processing'] = TRUE;
+
+<<<<<<< HEAD
+      }
+      else {
+        print 'WARNING: Unsupported type: ' . $field_array['type'] . ' for ' . $table . '.' . $field_array['field'] . "!\n";
+=======
+      } else {
+        print 'WARNING: Unsupported type: '. $field_array['type'] . ' for ' . $table . '.' . $field_array['field']."!\n";
+>>>>>>> 6.x-0.4-dev
+      }
+
+      $three = $default_data[$priority];
+      //watchdog('T_bulk_loader','A)'.$field_index.':<pre>Field Array =>'.print_r($field_array,TRUE)."Initial => \n".print_r($one, TRUE)."\nAfter Regex =>".print_r($two, TRUE)."Final =>\n".print_r($three,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
+
+    } // end of foreach field
+    //watchdog('T_bulk_loader','2)'.$record_array['record_id'].':<pre>'.print_r($default_data[$priority], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
+  } //end of foreach record
+
+  ///////////////////////////////////////////////
+  // For each set of constants
+  ///////////////////////////////////////////////
+  $original_default_data = $default_data;
+  $group_index = 0;
+  $total_num_groups = sizeof($node->constants);
+  foreach ($node->constants as $group_id => $set) {
+    // revert default data array for next set of constants
+    $default_data = $original_default_data;
+    $group_index++;
+
+    // Add constants
+    if (!empty($set)) {
+      print "Constants:\n";
+      foreach ($set as $priority => $record) {
+        foreach ($record as $field_id => $field) {
+
+<<<<<<< HEAD
+          print "\t- " . $field['chado_table'] . '.' . $field['chado_field'] . ' = ' . $field['value'] . "\n";
+=======
+          print "\t- ".$field['chado_table'].'.'.$field['chado_field'].' = '.$field['value']."\n";
+>>>>>>> 6.x-0.4-dev
+
+          if ($default_data[$priority]['table'] == $field['chado_table']) {
+            if (isset($default_data[$priority]['values_array'][$field['chado_field']])) {
+              if (isset($field2column[$priority][$field['chado_field']])) {
+                $field2column[$priority][$field['chado_field']] = $field['value'];
+              }
+              else {
+                $default_data[$priority]['values_array'][$field['chado_field']] = $field['value'];
+              }
+            }
+            else {
+              print "ERROR: Template has changed after constants were assigned!\n";
+              watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
+              exit(1);
+            }
+          }
+          else {
+            print "ERROR: Template has changed after constants were assigned!\n";
+            watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
+            exit(1);
+          }
+        }
+      }
+    }
+
+    //print "Default Data:".print_r($default_data,TRUE)."\n";
+    //watchdog('T_bulk_loader','Default Data:<pre>'.print_r($default_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
+
+    //print "\nDefault Values Array: ".print_r($default_data, TRUE)."\n";
+    //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
+
+    // Parse File adding records as we go ========================================================
+    $file_handle = fopen($node->file, 'r');
+    if (preg_match('/(t|true|1)/', $node->file_has_header)) {
+      fgets($file_handle, 4096);
+    }
+    $num_records = 0;
+    $num_lines = 0;
+    $num_errors = 0;
+    $interval = intval($total_lines * 0.10);
+    if ($interval == 0) {
+       $interval = 1;
+     }
+    while (!feof($file_handle)) {
+
+      // Clear variables
+      // Was added to fix memory leak
+      unset($line);                     unset($raw_line);
+      unset($data);                     unset($data_keys);
+      unset($priority);                 unset($sql);
+      unset($result);
+
+      $raw_line = fgets($file_handle, 4096);
+      $raw_line = trim($raw_line);
+      if (empty($raw_line)) {
+        continue;
+      } // skips blank lines
+      $line = explode("\t", $raw_line);
+      $num_lines++;
+
+      // update the job status every 10% of lines processed for the current group
+      if ($node->job_id and $num_lines % $interval == 0) {
+        // percentage of lines processed for the current group
+        $group_progress = round(($num_lines/$total_lines)*100);
+
+        // percentage of lines processed for all groups
+        // <previous group index> * 100 + <current group progress>
+        // --------------------------------------------------------
+        //               <total number of groups>
+        // For example, if you were in the third group of 3 constant sets
+        // and had a group percentage of 50% then the job progress would be
+        // (2*100 + 50%) / 3 = 250%/3 = 83%
+        $job_progress = round(((($group_index-1)*100)+$group_progress)/$total_num_groups);
+
+        /**
+          print "\nProgress Update:\n"
+            ."\t- ".$num_lines." lines have been processed for the current constant set.\n"
+            ."\t- ".$group_progress."% of the lines in the file have been processed for the current constant set.\n"
+            ."\t- ".$job_progress."% of the current job has been completed.\n";
+        */
+
+<<<<<<< HEAD
+        tripal_job_set_progress($node->job_id, $job_progress);
+=======
+        tripal_job_set_progress($node->job_id,$job_progress);
+>>>>>>> 6.x-0.4-dev
+      }
+
+      $data = $default_data;
+
+      $data_keys = array_keys($data);
+      foreach ($data_keys as $priority) {
+        $status = process_data_array_for_line($priority, $data, $default_data, $field2column, $record2priority, $line, $nid, $num_lines, $group_index);
+        if (!$status ) {
+          $loaded_without_errors = FALSE;
+        }
+      } // end of foreach table in default data array
+
+    } //end of foreach line of file
+  } //end of foreach constant set
+
+  // check that data was inserted and update job_status
+  $sql = 'SELECT count(*) as num_tables FROM {tripal_bulk_loader_inserted} WHERE nid=%d GROUP BY nid';
+  $result = db_fetch_object(db_query($sql, $nid));
+  if ($result->num_tables > 0) {
+    $node->job_status = 'Data Inserted';
+    drupal_write_record('node', $node, 'nid');
+  }
+
+  // set the status of the job (in the node not the tripal jobs)
+  if ($loaded_without_errors) {
+      $status = 'Loading Completed Successfully';
+    }
+    else {
+      $status = 'Errors Encountered';
+      }
+  db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", $status, $nid);
+
+}
+
+/**
+ *
+ *
+ */
+function process_data_array_for_line($priority, &$data, &$default_data, $field2column, $record2priority, $line, $nid, $line_num, $group_index) {
+  $table_data = $data[$priority];
+
+  $no_errors = TRUE;
+
+  $table = $table_data['table'];
+  $values = $table_data['values_array'];
+
+  //watchdog('T_bulk_loader','Original:<pre>'.print_r($table_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
+
+  //print 'default values:'.print_r($values,TRUE)."\n";
+  if ($table_data['need_further_processing']) {
+    $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column[$priority]);
+    if (!$values) {
+      watchdog('T_bulk_loader', 'Line ' . $line_num . ' Spreadsheet Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
+    }
+
+    $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority);
+    if (!$values) {
+      watchdog('T_bulk_loader', 'Line ' . $line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
+    }
+  }
+  $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $line);
+  if (!$values) {
+    watchdog('T_bulk_loader', 'Line ' . $line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
+  }
+
+  if (!$values) {
+<<<<<<< HEAD
+    $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Aborted due to error in previous record. Values of current record:' . print_r($table_data['values_array'], TRUE);
+    watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
+    print "ERROR: " . $msg . "\n";
+=======
+    $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Aborted due to error in previous record. Values of current record:'.print_r($table_data['values_array'],TRUE);
+    watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
+    print "ERROR: ".$msg."\n";
+>>>>>>> 6.x-0.4-dev
+    $data[$priority]['error'] = TRUE;
+    $no_errors = FALSE;
+  }
+
+<<<<<<< HEAD
+  $table_desc = module_invoke_all('chado_' . $table . '_schema');
+=======
+  $table_desc = module_invoke_all('chado_'.$table.'_schema');
+>>>>>>> 6.x-0.4-dev
+  if (preg_match('/optional/', $table_array['mode'])) {
+    // Check all db required fields are set
+    $fields = $table_desc['fields'];
+    foreach ($fields as $field => $def) {
+      // a field is considered missing if it cannot be null and there is no default
+      // value for it or it is of type 'serial'
+<<<<<<< HEAD
+      if ($def['not null'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial)!=0) {
+         $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
+=======
+      if($def['not null'] == 1 and !array_key_exists($field,$insert_values) and !isset($def['default']) and strcmp($def['type'],serial)!=0){
+         $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Missing Database Required Value: '.$table.'.'.$field;
+>>>>>>> 6.x-0.4-dev
+         watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
+         $data[$priority]['error'] = TRUE;
+      }
+    }
+  } //end of if optional record
+
+  // Check required fields are present
+  foreach ($table_data['required'] as $field => $required) {
+    if ($required) {
+      if (!isset($values[$field])) {
+<<<<<<< HEAD
+        $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Template Required Value: ' . $table . '.' . $field;
+=======
+        $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Missing Template Required Value: '.$table.'.'.$field;
+>>>>>>> 6.x-0.4-dev
+        watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
+        $data[$priority]['error'] = TRUE;
+      }
+    }
+  }
+
+  // add new values array into the data array
+  $data[$priority]['values_array'] = $values;
+
+  // check if it is already inserted
+  if ($table_data['inserted']) {
+    //watchdog('T_bulk_loader','Already Inserted:'.print_r($values,TRUE),array(),WATCHDOG_NOTICE);
+    return $no_errors;
+  }
+
+  // if there was an error already -> don't insert
+  if ($data[$priority]['error']) {
+    return $no_errors;
+  }
+
+  $header = '';
+  if (isset($values['feature_id'])) {
+    $header = $values['feature_id']['uniquename'] . ' ' . $table_data['record_id'];
+  }
+  else {
+    $header = $values['uniquename'] . ' ' . $table_data['record_id'];
+  }
+
+  // if insert unique then check to ensure unique
+  if (preg_match('/insert_unique/', $table_data['mode'])) {
+    $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
+    //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
+    if ($unique > 0) {
+      //$default_data[$priority]['inserted'] = TRUE;
+      //watchdog('T_bulk_loader', $header.': Not unique ('.$unique.'):'.print_r($values,'values')."\n".print_r($data,TRUE),array(),WATCHDOG_NOTICE);;
+      return $no_errors;
+    }
+  }
+
+
+<<<<<<< HEAD
+  if (!preg_match('/select/', $table_data['mode'])) {
+=======
+  if (!preg_match('/select/',$table_data['mode'])) {
+>>>>>>> 6.x-0.4-dev
+    //watchdog('T_bulk_loader',$header.': Inserting:'.print_r($values, TRUE), array(), WATCHDOG_NOTICE);
+    if (variable_get('tripal_bulk_loader_prepare',TRUE)) {
+      $options = array('statement_name' => $priority);
+      if ($line_num == 1 && $group_index == 1) {
+        $options['prepare'] = TRUE;
+      }
+    }
+    else {
+      $options = array();
+    }
+
+    $record = tripal_core_chado_insert($table, $values, $options);
+
+    if (!$record) {
+<<<<<<< HEAD
+      $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Unable to insert record into ' . $table . ' where values:' . print_r($values, TRUE);
+      watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
+      print "ERROR: " . $msg . "\n";
+=======
+      $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') Unable to insert record into '.$table.' where values:'.print_r($values,TRUE);
+      watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
+      print "ERROR: ".$msg."\n";
+>>>>>>> 6.x-0.4-dev
+      $data[$priority]['error'] = TRUE;
+      $no_errors = FALSE;
+    }
+    else {
+      //add changes back to values array
+      $data[$priority]['values_array'] = $record;
+      $values = $record;
+
+      // if mode=insert_once then ensure we only insert it once
+      if (preg_match('/insert_once/', $table_data['mode'])) {
+        $default_data[$priority]['inserted'] = TRUE;
+      }
+
+      // add to tripal_bulk_loader_inserted
+      $insert_record = db_fetch_object(db_query(
+        "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
+        $table,
+        $nid
+      ));
+      if ($insert_record) {
+        $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
+        drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
+        //print 'Update: '.print_r($insert_record,TRUE)."\n";
+        return $no_errors;
+      }
+      else {
+        $insert_record = array(
+          'nid' => $nid,
+          'table_inserted_into' => $table,
+          'table_primary_key' => $table_desc['primary key'][0],
+          'ids_inserted' => $values[ $table_desc['primary key'][0] ],
+        );
+        //print 'New: '.print_r($insert_record,TRUE)."\n";
+        $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
+        return $no_errors;
+      }//end of if insert record
+
+    } //end of if insert was successful
+  }
+  else {
+    $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
+    if (!$exists) {
+      // No record on select
+<<<<<<< HEAD
+      $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
+=======
+      $msg = 'Line '.$line_num.' '.$table_data['record_id'].' ('.$table_data['mode'].') No Matching record in '.$table.' where values:'.print_r($values,TRUE);
+>>>>>>> 6.x-0.4-dev
+      watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
+      $data[$priority]['error'] = TRUE;
+    }
+  }
+  return $no_errors;
+}
+
+/**
+ * This function adds the file data to the values array
+ *
+ * @param $values
+ *   The default values array -contains all constants
+ * @param $line
+ *   An array of values for the current line
+ * @param $field2column
+ *   An array mapping values fields to line columns
+ * @return
+ *   Supplemented values array
+ */
+function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
+
+  foreach ($values as $field => $value) {
+<<<<<<< HEAD
+    if (is_array($value)) {
+      continue;
+    }
+
+    $column = $field2column[$field] - 1;
+    if ($column < 0) {
+      continue;
+    }
+
+    if (preg_match('/\S+/', $line[$column])) {
+=======
+    if (is_array($value)) { continue; }
+
+    $column = $field2column[$field] - 1;
+    if ($column < 0) { continue; }
+
+    if (preg_match('/\S+/',$line[$column])) {
+>>>>>>> 6.x-0.4-dev
+      $values[$field] = $line[$column];
+    }
+    else {
+      unset($values[$field]);
+    }
+  }
+
+  return $values;
+}
+
+/**
+ * Handles foreign keys in the values array.
+ *
+ * Specifically, if the value for a field is an array then it is assumed that the array contains
+ * the name of the record whose values array should be substituted here. Thus the foreign
+ * record is looked up and the values array is substituted in.
+ *
+ */
+function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
+
+  foreach ($values as $field => $value) {
+    if (is_array($value)) {
+      $foreign_record = $value['foreign record'];
+      $foreign_priority = $record2priority[$foreign_record];
+      $foreign_values = $data[$foreign_priority]['values_array'];
+
+      // add to current values array
+      $values[$field] = $foreign_values;
+    }
+  }
+
+  return $values;
+}
+
+/**
+ * Uses a supplied regex to transform spreadsheet values
+ *
+ * @param $values
+ *   The select/insert values array for the given table
+ * @param $table_data
+ *   The data array for the given table
+ */
+function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
+
+  if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) {
+    return $values;
+  }
+
+<<<<<<< HEAD
+  //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
+
+  foreach ($table_data['regex_transform'] as $field => $regex_array) {
+    if (!is_array($regex_array['replace'])) {
+       continue;
+     }
+=======
+  if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) { return $values; }
+
+  //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
+
+  foreach ($table_data['regex_transform'] as $field => $regex_array) {
+    if (!is_array($regex_array['replace'])) { continue; }
+>>>>>>> 6.x-0.4-dev
+
+    //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
+    //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
+    //print 'Was:'.$values[$field]."\n";
+
+    // Check for <#column:\d+#> notation
+    // if present replace with that column in the current line
+    foreach ($regex_array['replace'] as $key => $replace) {
+      if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
+        foreach ($matches[1] as $k => $column_num) {
+          $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
+        }
+        $regex_array['replace'][$key] = $replace;
+      }
+    }
+
+    // do the full replacement
+    $old_value = $values[$field];
+    $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
+    $values[$field] = $new_value;
+
+    if ($values[$field] === '') {
+      unset($values[$field]);
+    }
+    //print 'Now:'.$values[$field]."\n";
+  }
+
+
+
+  return $values;
+}
+
+/**
+ * Flattens an array up to two levels
+ * Used for printing of arrays without taking up much space
+ */
+function tripal_bulk_loader_flatten_array($values) {
+  $flattened_values = array();
+
+  foreach ($values as $k => $v) {
+    if (is_array($v)) {
+      $vstr = array();
+      foreach ($v as $vk => $vv) {
+        if (strlen($vv) > 20) {
+          $vstr[] = $vk . '=>' . substr($vv, 0, 20) . '...';
+        }
+        else {
+          $vstr[] = $vk . '=>' . $vv;
+        }
+      }
+      $v = '{' . implode(',', $vstr) . '}';
+    }
+    elseif (strlen($v) > 20) {
+      $v = substr($v, 0, 20) . '...';
+    }
+    $flattened_values[] = $k . '=>' . $v;
+  }
+
+<<<<<<< HEAD
+  return implode(', ', $flattened_values);
+}
+=======
+  return implode(', ',$flattened_values);
+}
+>>>>>>> 6.x-0.4-dev

+ 174 - 172
tripal_bulk_loader/tripal_bulk_loader.module

@@ -7,10 +7,10 @@ include('tripal_bulk_loader.constants.inc');
  * Implements hook_init
  * Used to add stylesheets and javascript files to the header
  */
-function tripal_bulk_loader_init(){
-	// Add javascript and style sheet
-	drupal_add_css(drupal_get_path('theme', 'tripal').'/css/tripal_bulk_loader.css');
-	drupal_add_js(drupal_get_path('theme', 'tripal').'/js/tripal_bulk_loader.js');
+function tripal_bulk_loader_init() {
+  // Add javascript and style sheet
+  drupal_add_css(drupal_get_path('theme', 'tripal') . '/css/tripal_bulk_loader.css');
+  drupal_add_js(drupal_get_path('theme', 'tripal') . '/js/tripal_bulk_loader.js');
 }
 
 /**
@@ -30,39 +30,40 @@ function tripal_bulk_loader_menu() {
    $items['node/%node/constants/%/edit'] = array(
       'title' => 'Edit Constant Set',
       'description' => 'Edit a group of constants associated with the current bulk loader',
-    	'page callback' => 'drupal_get_form',
-    	'page arguments' => array('tripal_bulk_loader_edit_constant_set_form',1,3),
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_edit_constant_set_form', 1, 3),
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,   
-		  'file' => 'tripal_bulk_loader.constants.inc',
+      'type' => MENU_CALLBACK,
+      'file' => 'tripal_bulk_loader.constants.inc',
    );
    $items['node/%node/constants/%/delete'] = array(
       'title' => 'Delete Constant Set',
       'description' => 'Delete a group of constants associated with the current bulk loader',
-    	'page callback' => 'drupal_get_form',
-    	'page arguments' => array('tripal_bulk_loader_delete_constant_set_form',1,3),
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_delete_constant_set_form', 1, 3),
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,   
-		  'file' => 'tripal_bulk_loader.constants.inc',
+      'type' => MENU_CALLBACK,
+      'file' => 'tripal_bulk_loader.constants.inc',
    );
+
    // Admin page to create the template
    $items['admin/tripal/tripal_bulk_loader_template'] = array(
       'title' => 'Bulk Loader Template',
       'description' => 'Templates for loading tab-delimited data',
-    	'page callback' => 'tripal_bulk_loader_admin_template',
+      'page callback' => 'tripal_bulk_loader_admin_template',
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,   
-		  'file' => 'tripal_bulk_loader.admin.inc',
-	);
-	// Create/Edit Template -------
+      'type' => MENU_NORMAL_ITEM,
+      'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  // Create/Edit Template -------
   $items['admin/tripal/tripal_bulk_loader_template/create'] = array(
       'title' => 'Create Bulk Loader Template',
       'description' => 'Create loader template for loading tab-delimited data',
       'page callback' => 'drupal_get_form',
       'page arguments' => array('tripal_bulk_loader_modify_template_base_form', 'create'),
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,   
-		'file' => 'tripal_bulk_loader.admin.inc',
+      'type' => MENU_NORMAL_ITEM,
+    'file' => 'tripal_bulk_loader.admin.inc',
   );
   $items['admin/tripal/tripal_bulk_loader_template/edit'] = array(
       'title' => 'Edit Bulk Loader Template',
@@ -70,79 +71,79 @@ function tripal_bulk_loader_menu() {
       'page callback' => 'drupal_get_form',
       'page arguments' => array('tripal_bulk_loader_modify_template_base_form', 'edit'),
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,   
-		  'file' => 'tripal_bulk_loader.admin.inc',  
+      'type' => MENU_NORMAL_ITEM,
+      'file' => 'tripal_bulk_loader.admin.inc',
   );
-	$items['admin/tripal/tripal_bulk_loader_template/edit_record'] = array(
+  $items['admin/tripal/tripal_bulk_loader_template/edit_record'] = array(
       'title' => 'Edit Template Record',
       'description' => 'Edit a record in an existing tripal bulk loader template.',
       'page callback' => 'drupal_get_form',
       'page arguments' => array('tripal_bulk_loader_edit_template_record_form'),
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,   
-		'file' => 'tripal_bulk_loader.admin.inc',
-	);
-	$items['admin/tripal/tripal_bulk_loader_template/add_field'] = array(
+      'type' => MENU_CALLBACK,
+    'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/add_field'] = array(
       'title' => 'Add Template Field',
       'description' => 'Add a template field to an existing tripal bulk loader template.',
       'page callback' => 'drupal_get_form',
       'page arguments' => array('tripal_bulk_loader_add_template_field_form'),
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,   
-		'file' => 'tripal_bulk_loader.admin.inc',
-	);
-	$items['admin/tripal/tripal_bulk_loader_template/edit_field'] = array(
+      'type' => MENU_CALLBACK,
+    'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/edit_field'] = array(
       'title' => 'Edit Template Field',
       'description' => 'Edit an existing field from a tripal bulk loader template.',
       'page callback' => 'drupal_get_form',
       'page arguments' => array('tripal_bulk_loader_edit_template_field_form'),
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,   
-		'file' => 'tripal_bulk_loader.admin.inc',
-	);
-	// Delete Template -----
-	$items['admin/tripal/tripal_bulk_loader_template/delete'] = array(
+      'type' => MENU_CALLBACK,
+    'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  // Delete Template -----
+  $items['admin/tripal/tripal_bulk_loader_template/delete'] = array(
       'title' => 'Delete Bulk Loader Template',
       'description' => 'Delete bulk loader template',
       'page callback' => 'drupal_get_form',
       'page arguments' => array('tripal_bulk_loader_delete_template_base_form'),
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,   
-		'file' => 'tripal_bulk_loader.admin.inc',
-	);
-	// Import/Export ---------
+      'type' => MENU_NORMAL_ITEM,
+    'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  // Import/Export ---------
   $items['admin/tripal/tripal_bulk_loader_template/import'] = array(
       'title' => 'Import Bulk Loader Template',
       'description' => 'Import Loaders',
       'page callback' => 'drupal_get_form',
       'page arguments' => array('tripal_bulk_loader_import_export_template_form', 'import'),
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,   
-		  'file' => 'tripal_bulk_loader.admin.inc',  
-  );	
+      'type' => MENU_NORMAL_ITEM,
+      'file' => 'tripal_bulk_loader.admin.inc',
+  );
   $items['admin/tripal/tripal_bulk_loader_template/export'] = array(
       'title' => 'Export Bulk Loader Template',
       'description' => 'Export Loaders',
       'page callback' => 'drupal_get_form',
       'page arguments' => array('tripal_bulk_loader_import_export_template_form', 'export'),
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_NORMAL_ITEM,   
-		  'file' => 'tripal_bulk_loader.admin.inc',  
-  );	
-	// AHAH ---------
-	$items['admin/tripal/tripal_bulk_loader_template/add_field_ahah'] = array(
+      'type' => MENU_NORMAL_ITEM,
+      'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  // AHAH ---------
+  $items['admin/tripal/tripal_bulk_loader_template/add_field_ahah'] = array(
       'page callback' => 'tripal_bulk_loader_add_field_ahah',
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,   
-		  'file' => 'tripal_bulk_loader.admin.inc',	
-	);
-	$items['admin/tripal/tripal_bulk_loader_template/edit_field_ahah'] = array(
+      'type' => MENU_CALLBACK,
+      'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/edit_field_ahah'] = array(
       'page callback' => 'tripal_bulk_loader_edit_field_ahah',
       'access arguments' => array('administer site configuration'),
-      'type' => MENU_CALLBACK,   
-		  'file' => 'tripal_bulk_loader.admin.inc',	
-	);
-	
+      'type' => MENU_CALLBACK,
+      'file' => 'tripal_bulk_loader.admin.inc',
+  );
+
   return $items;
 }
 
@@ -156,12 +157,12 @@ function tripal_bulk_loader_theme() {
       'arguments' => array('form' => NULL),
     ),
     'tripal_bulk_loader_template' => array(
-    	'arguments'=> array('template_id' => NULL),
-    	'template' => 'tripal_bulk_loader_template'
+      'arguments' => array('template_id' => NULL),
+      'template' => 'tripal_bulk_loader_template'
     ),
     'tripal_bulk_loader_modify_template_base_form' => array(
-    	'arguments' => array('form' => NULL),
-    	'template' => 'tripal_bulk_loader_modify_template_base_form',
+      'arguments' => array('form' => NULL),
+      'template' => 'tripal_bulk_loader_modify_template_base_form',
     ),
     'tripal_bulk_loader_edit_template_field_form' => array(
       'arguments' => array('form' => NULL),
@@ -177,69 +178,69 @@ function tripal_bulk_loader_theme() {
 /**
  *  Implements hook_access
  */
-function tripal_bulk_loader_access($op, $node, $account){
-	if ($op == 'create') {
-		if(!user_access('create tripal_bulk_loader', $account)){
+function tripal_bulk_loader_access($op, $node, $account) {
+  if ($op == 'create') {
+    if (!user_access('create tripal_bulk_loader', $account)) {
          return FALSE;
       }
-	}
-	if ($op == 'update') {
-		if (!user_access('edit tripal_bulk_loader', $account)) {
-			return FALSE;
-		}
-	}
-	if ($op == 'delete') {
-		if (!user_access('delete tripal_bulk_loader', $account)) {
-			return FALSE;
-		}
-	}
-	if ($op == 'view') {
-		if (!user_access('access tripal_bulk_loader', $account)) {
-			return FALSE;
-		}
-	}
-	return NULL;
+  }
+  if ($op == 'update') {
+    if (!user_access('edit tripal_bulk_loader', $account)) {
+      return FALSE;
+    }
+  }
+  if ($op == 'delete') {
+    if (!user_access('delete tripal_bulk_loader', $account)) {
+      return FALSE;
+    }
+  }
+  if ($op == 'view') {
+    if (!user_access('access tripal_bulk_loader', $account)) {
+      return FALSE;
+    }
+  }
+  return NULL;
 }
 
 /**
  * Implements hook_perm
  */
-function tripal_bulk_loader_perm(){
-	return array(
+function tripal_bulk_loader_perm() {
+  return array(
       'access tripal_bulk_loader',
       'create tripal_bulk_loader',
       'delete tripal_bulk_loader',
       'edit tripal_bulk_loader',
-	);
+  );
 }
 
 /**
  * Creates a listing page for all bulk loading jobs
  */
-function tripal_bulk_loader_list () {
+function tripal_bulk_loader_list() {
   $num_results_per_page = 50;
   $output = '';
-  
-  $header = array('','Status','Loader','File');
+
+  $header = array('', 'Status', 'Loader', 'File');
   $rows = array();
-  
+
   $query = 'SELECT * FROM {tripal_bulk_loader} l '
     .'LEFT JOIN {node} n ON n.nid = l.nid '
     .'LEFT JOIN {tripal_bulk_loader_template} t ON t.template_id = cast(l.template_id as integer)';
   $resource = pager_query($query, $num_results_per_page, 0, NULL);
   while ($r = db_fetch_object($resource)) {
     $row = array(
-      l($r->title, 'node/'.$r->nid),
+      l($r->title, 'node/' . $r->nid),
       $r->job_status,
       $r->name,
       $r->file
     );
     $rows[] = $row;
   }
-  
+
   $output .= theme('table', $header, $rows);
   return $output;
-  
+
 }
 
 //////////////////////////////////////////////////////////////////////////////////////////////
@@ -250,52 +251,52 @@ function tripal_bulk_loader_list () {
  * Implements hook_node_info
  */
 function tripal_bulk_loader_node_info() {
-	$nodes = array();
-	$nodes['tripal_bulk_loader'] = array(
+  $nodes = array();
+  $nodes['tripal_bulk_loader'] = array(
       'name' => t('Bulk Loading Job'),
       'module' => 'tripal_bulk_loader',
       'description' => t('A bulk loader for inserting tab-delimited data into chado database'),
       'has_title' => TRUE,
       'has_body' => FALSE,
       'locked' => TRUE
-	);
-	return $nodes;
+  );
+  return $nodes;
 }
 
 /**
  * Implements node_form
  * Used to gather the extra details stored with a Bulk Loading Job Node
  */
-function tripal_bulk_loader_form ($node, $form_state){
+function tripal_bulk_loader_form($node, $form_state) {
   $form = array();
-  
+
   if (isset($form_state['values'])) {
     $node = $form_state['values'] + (array)$node;
     $node = (object) $node;
   }
-  
+
   $sql = "SELECT * FROM {tripal_bulk_loader_template}";
   $results = db_query($sql);
-  $templates = array ();
+  $templates = array();
   while ($template = db_fetch_object ($results)) {
     $templates [$template->template_id] = $template->name;
   }
-  
+
   if (!$templates) {
     $form['label'] = array(
     '#type' => 'item',
       '#description' => t("Loader template needs to be created before any bulk loader can be added. Go to 'Tripal Management > Bulk Loader Template' to create the template."),
       '#weight'        => -10,
     );
-    
+
     return $form;
   }
-  
+
   $form['loader'] = array(
     '#type' => 'fieldset',
     '#title' => t('Basic Details'),
   );
-  
+
   $form['loader']['loader_name'] = array(
     '#type'          => 'textfield',
     '#title'         => t('Loading Job Name'),
@@ -303,7 +304,7 @@ function tripal_bulk_loader_form ($node, $form_state){
     '#required'      => TRUE,
     '#default_value' => $node->loader_name
   );
-  
+
   $form['loader']['template_id'] = array(
     '#type' => 'select',
     '#title' => t('Template'),
@@ -313,7 +314,7 @@ function tripal_bulk_loader_form ($node, $form_state){
     '#required'      => TRUE,
     '#default_value' => $node->template_id,
   );
-  
+
   $form['loader']['file']= array(
     '#type'          => 'textfield',
     '#title'         => t('Data File'),
@@ -321,7 +322,7 @@ function tripal_bulk_loader_form ($node, $form_state){
     '#weight'        => -8,
     '#default_value' => $node->file
   );
-  
+
   $form['loader']['has_header'] = array(
     '#type' => 'radios',
     '#title' => t('File has a Header'),
@@ -329,7 +330,7 @@ function tripal_bulk_loader_form ($node, $form_state){
     '#weight' => -7,
     '#default_value' => $node->file_has_header,
   );
-  
+
   return $form;
 }
 
@@ -337,24 +338,24 @@ function tripal_bulk_loader_form ($node, $form_state){
 /**
  * Implements node_load
  */
-function tripal_bulk_loader_load($node){
-	$sql = "SELECT * FROM {tripal_bulk_loader} WHERE nid = %d";
-	$node = db_fetch_object(db_query($sql, $node->nid));
-
-	$node->title = 'Bulk Loading Job: '.$node->loader_name;
-	
-	// Add the loader template
-	$sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-	$results = db_fetch_object(db_query($sql, $node->template_id));
-	$template = unserialize($results->template_array);
-	$node->template = $results;
-	$node->template->template_array = $template;
+function tripal_bulk_loader_load($node) {
+  $sql = "SELECT * FROM {tripal_bulk_loader} WHERE nid = %d";
+  $node = db_fetch_object(db_query($sql, $node->nid));
+
+  $node->title = 'Bulk Loading Job: ' . $node->loader_name;
+
+  // Add the loader template
+  $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+  $results = db_fetch_object(db_query($sql, $node->template_id));
+  $template = unserialize($results->template_array);
+  $node->template = $results;
+  $node->template->template_array = $template;
 
   // Add inserted records
   $sql = 'SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d';
-  $resource = db_query($sql,$node->nid);
+  $resource = db_query($sql, $node->nid);
   while ($r = db_fetch_object($resource)) {
-    $r->num_inserted = sizeof(preg_split('/,/',$r->ids_inserted)); 
+    $r->num_inserted = sizeof(preg_split('/,/', $r->ids_inserted));
     $node->inserted_records->{$r->table_inserted_into} = $r;
   }
 
@@ -372,86 +373,87 @@ function tripal_bulk_loader_load($node){
         }
       }
     }
-    
+
     if (empty($node->exposed_fields)) {
       $node->exposed_fields[] = array();
     }
   }
 
-  
+
   // Add constants
   $sql = 'SELECT * FROM {tripal_bulk_loader_constants} WHERE nid=%d ORDER BY group_id, record_id, field_id';
-  $resource = db_query($sql,$node->nid);
+  $resource = db_query($sql, $node->nid);
   while ($r = db_fetch_object($resource)) {
     $node->constants[$r->group_id][$r->record_id][$r->field_id] = array(
       'constant_id' => $r->constant_id,
       'group_id' => $r->group_id,
-      'chado_table'=>$r->chado_table, 
-      'chado_field'=>$r->chado_field, 
-      'record_id'=>$r->record_id, 
-      'field_id'=>$r->field_id, 
-      'value'=>$r->value
+      'chado_table' => $r->chado_table,
+      'chado_field' => $r->chado_field,
+      'record_id' => $r->record_id,
+      'field_id' => $r->field_id,
+      'value' => $r->value
     );
   }
   if (!$node->constants) {
     $node->constants[] = array();
   }
-  
-	return $node;
+
+  return $node;
 }
 
 /**
  * Implements node_insert
  * Insert the data from the node form on Create content
  */
-function tripal_bulk_loader_insert ($node) {
-  
+function tripal_bulk_loader_insert($node) {
+
   // Insert into tripal_bulk_loader
   $sql = "INSERT INTO {tripal_bulk_loader} (nid, loader_name, template_id, file, file_has_header, job_status) VALUES (%d, '%s', %d, '%s', %d, '%s')";
   db_query($sql, $node->nid, $node->loader_name, $node->template_id, $node->file, $node->has_header, 'Initialized');
-	
-	// Update title
-	$node->title =$node->loader_name;
-	drupal_write_record('node',$node,'nid');
-	drupal_write_record('node_revision',$node,'nid');	
-  
+
+  // Update title
+  $node->title =$node->loader_name;
+  drupal_write_record('node', $node, 'nid');
+  drupal_write_record('node_revision', $node, 'nid');
+
   drupal_set_message('After reviewing the details, please Submit this Job (by clicking the "Submit Job" button below). No data will be loaded until the submitted job is reached in the queue.');
-  
+
 }
 
 /**
  * Implements node_delete
  * Deletes the data when the delete button on the node form is clicked
  */
-function tripal_bulk_loader_delete ($node) {
-	$sql = "DELETE FROM {tripal_bulk_loader} WHERE nid = %d";
-	db_query($sql, $node->nid);
+function tripal_bulk_loader_delete($node) {
+  $sql = "DELETE FROM {tripal_bulk_loader} WHERE nid = %d";
+  db_query($sql, $node->nid);
 }
 
 /**
  * Implements node_update
  * Updates the data submitted by the node form on edit
  */
-function tripal_bulk_loader_update ($node) {
-  
+function tripal_bulk_loader_update($node) {
+
   // Update tripal_bulk_loader
-	$sql = "UPDATE {tripal_bulk_loader} SET nid = %d, loader_name = '%s', template_id = %d, file = '%s', file_has_header = '%s' WHERE nid = %d";
-	db_query($sql, $node->nid, $node->loader_name, $node->template_id, $node->file, $node->has_header, $node->nid);
-	
-	// Add a job if the user want to load the data
-	global $user;
-	if($node->job) {
-		$job_args[0] =$node->loader_name;
-		$job_args[1] = $node->template_id;
-		$job_args[2] = $node->file;
-		if (is_readable($node->file)) {
-			$fname = preg_replace("/.*\/(.*)/", "$1", $node->file);
-			tripal_add_job("Bulk Load: $fname",'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
-		} else {
-			drupal_set_message("Can not open $node->file. Job not scheduled.");
-		}
-	}
-  
+  $sql = "UPDATE {tripal_bulk_loader} SET nid = %d, loader_name = '%s', template_id = %d, file = '%s', file_has_header = '%s' WHERE nid = %d";
+  db_query($sql, $node->nid, $node->loader_name, $node->template_id, $node->file, $node->has_header, $node->nid);
+
+  // Add a job if the user want to load the data
+  global $user;
+  if ($node->job) {
+    $job_args[0] =$node->loader_name;
+    $job_args[1] = $node->template_id;
+    $job_args[2] = $node->file;
+    if (is_readable($node->file)) {
+      $fname = preg_replace("/.*\/(.*)/", "$1", $node->file);
+      tripal_add_job("Bulk Load: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
+    }
+    else {
+      drupal_set_message(t("Can not open %file. Job not scheduled.", array('%file' => $node->file)));
+    }
+  }
+
 }
 
 ///////////////////////////////////////////////////////////
@@ -459,13 +461,13 @@ function tripal_bulk_loader_update ($node) {
 /**
  * Preprocessor function for the tripal_bulk_loader template
  */
-function tripal_bulk_loader_preprocess_tripal_bulk_loader_template (&$variables) {
+function tripal_bulk_loader_preprocess_tripal_bulk_loader_template(&$variables) {
+
+  $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+  $template = db_fetch_object(db_query($sql, $variables['template_id']));
+  $template->template_array = unserialize($template->template_array);
+  $variables['template'] = $template;
 
-	$sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
-	$template = db_fetch_object(db_query($sql, $variables['template_id']));
-	$template->template_array = unserialize($template->template_array);	
-	$variables['template'] = $template;
-	
 }
 
 /**
@@ -476,19 +478,19 @@ function tripal_bulk_loader_preprocess_tripal_bulk_loader_template (&$variables)
  *   The callback passed into tripal_add_job()
  * @param $args
  *   The arguements passed into tripal_add_job()
- * @return 
- *   An array where keys are the human readable headers describing each arguement 
+ * @return
+ *   An array where keys are the human readable headers describing each arguement
  *   and the value is the aguement passed in after formatting
  */
-function tripal_bulk_loader_job_describe_args($callback,$args){
+function tripal_bulk_loader_job_describe_args($callback, $args) {
 
   $new_args = array();
-  if($callback == 'tripal_bulk_loader_load_data'){
+  if ($callback == 'tripal_bulk_loader_load_data') {
     //1st arg is the nid for a bulk loader node
     $node = node_load($args[0]);
-    $new_args['Bulk Loading Job'] = l($node->title, 'node/'.$args[0]);
+    $new_args['Bulk Loading Job'] = l($node->title, 'node/' . $args[0]);
     return $new_args;
   }
-  
+
 }
 

+ 647 - 0
tripal_bulk_loader/tripal_bulk_loader.module.orig

@@ -0,0 +1,647 @@
+<?php
+
+include('tripal_bulk_loader.loader.inc');
+include('tripal_bulk_loader.constants.inc');
+
+/**
+ * Implements hook_init
+ * Used to add stylesheets and javascript files to the header
+ */
+function tripal_bulk_loader_init() {
+  // Add javascript and style sheet
+  drupal_add_css(drupal_get_path('theme', 'tripal') . '/css/tripal_bulk_loader.css');
+  drupal_add_js(drupal_get_path('theme', 'tripal') . '/js/tripal_bulk_loader.js');
+}
+
+/**
+ * Implements hook_menu
+ */
+function tripal_bulk_loader_menu() {
+  $items = array();
+   // Show all loaders
+   $items['tripal_bulk_loaders'] = array(
+     'title' => 'Tripal Bulk Loaders',
+     'description' => 'Tripal bulk loaders for loading tab-delimited file into chado database',
+     'page callback' => 'tripal_bulk_loader_list',
+     'access arguments' => array('access tripal_bulk_loader'),
+     'type' => MENU_NORMAL_ITEM,
+   );
+   // Bulk Loading Job Node
+   $items['node/%node/constants/%/edit'] = array(
+      'title' => 'Edit Constant Set',
+      'description' => 'Edit a group of constants associated with the current bulk loader',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_edit_constant_set_form', 1, 3),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_CALLBACK,
+<<<<<<< HEAD
+      'file' => 'tripal_bulk_loader.constants.inc',
+=======
+		  'file' => 'tripal_bulk_loader.constants.inc',
+>>>>>>> 6.x-0.4-dev
+   );
+   $items['node/%node/constants/%/delete'] = array(
+      'title' => 'Delete Constant Set',
+      'description' => 'Delete a group of constants associated with the current bulk loader',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_delete_constant_set_form', 1, 3),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_CALLBACK,
+<<<<<<< HEAD
+      'file' => 'tripal_bulk_loader.constants.inc',
+=======
+		  'file' => 'tripal_bulk_loader.constants.inc',
+>>>>>>> 6.x-0.4-dev
+   );
+
+   // Admin page to create the template
+   $items['admin/tripal/tripal_bulk_loader_template'] = array(
+      'title' => 'Bulk Loader Template',
+      'description' => 'Templates for loading tab-delimited data',
+      'page callback' => 'tripal_bulk_loader_admin_template',
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_NORMAL_ITEM,
+<<<<<<< HEAD
+      'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  // Create/Edit Template -------
+=======
+		  'file' => 'tripal_bulk_loader.admin.inc',
+	);
+   $items['admin/tripal/tripal_bulk_loader_template/configure'] = array(
+      'title' => 'Configuration',
+      'description' => 'Configure the Tripal Bulk Loader Module',
+    	'page callback' => 'drupal_get_form',
+    	'page arguments' => array('tripal_bulk_loader_configuration_form'),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_NORMAL_ITEM,
+		  'file' => 'tripal_bulk_loader.admin.inc',
+	);
+
+	// Create/Edit Template -------
+>>>>>>> 6.x-0.4-dev
+  $items['admin/tripal/tripal_bulk_loader_template/create'] = array(
+      'title' => 'Create Bulk Loader Template',
+      'description' => 'Create loader template for loading tab-delimited data',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_modify_template_base_form', 'create'),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_NORMAL_ITEM,
+<<<<<<< HEAD
+    'file' => 'tripal_bulk_loader.admin.inc',
+=======
+		'file' => 'tripal_bulk_loader.admin.inc',
+>>>>>>> 6.x-0.4-dev
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/edit'] = array(
+      'title' => 'Edit Bulk Loader Template',
+      'description' => 'Edit loader template for loading tab-delimited data',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_modify_template_base_form', 'edit'),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_NORMAL_ITEM,
+<<<<<<< HEAD
+      'file' => 'tripal_bulk_loader.admin.inc',
+=======
+		  'file' => 'tripal_bulk_loader.admin.inc',
+>>>>>>> 6.x-0.4-dev
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/edit_record'] = array(
+      'title' => 'Edit Template Record',
+      'description' => 'Edit a record in an existing tripal bulk loader template.',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_edit_template_record_form'),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_CALLBACK,
+<<<<<<< HEAD
+    'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/add_field'] = array(
+=======
+		'file' => 'tripal_bulk_loader.admin.inc',
+	);
+	$items['admin/tripal/tripal_bulk_loader_template/add_field'] = array(
+>>>>>>> 6.x-0.4-dev
+      'title' => 'Add Template Field',
+      'description' => 'Add a template field to an existing tripal bulk loader template.',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_add_template_field_form'),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_CALLBACK,
+<<<<<<< HEAD
+    'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/edit_field'] = array(
+=======
+		'file' => 'tripal_bulk_loader.admin.inc',
+	);
+	$items['admin/tripal/tripal_bulk_loader_template/edit_field'] = array(
+>>>>>>> 6.x-0.4-dev
+      'title' => 'Edit Template Field',
+      'description' => 'Edit an existing field from a tripal bulk loader template.',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_edit_template_field_form'),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_CALLBACK,
+<<<<<<< HEAD
+    'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  // Delete Template -----
+  $items['admin/tripal/tripal_bulk_loader_template/delete'] = array(
+=======
+		'file' => 'tripal_bulk_loader.admin.inc',
+	);
+	// Delete Template -----
+	$items['admin/tripal/tripal_bulk_loader_template/delete'] = array(
+>>>>>>> 6.x-0.4-dev
+      'title' => 'Delete Bulk Loader Template',
+      'description' => 'Delete bulk loader template',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_delete_template_base_form'),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_NORMAL_ITEM,
+<<<<<<< HEAD
+    'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  // Import/Export ---------
+=======
+		'file' => 'tripal_bulk_loader.admin.inc',
+	);
+	// Import/Export ---------
+>>>>>>> 6.x-0.4-dev
+  $items['admin/tripal/tripal_bulk_loader_template/import'] = array(
+      'title' => 'Import Bulk Loader Template',
+      'description' => 'Import Loaders',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_import_export_template_form', 'import'),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_NORMAL_ITEM,
+<<<<<<< HEAD
+      'file' => 'tripal_bulk_loader.admin.inc',
+=======
+		  'file' => 'tripal_bulk_loader.admin.inc',
+>>>>>>> 6.x-0.4-dev
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/export'] = array(
+      'title' => 'Export Bulk Loader Template',
+      'description' => 'Export Loaders',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('tripal_bulk_loader_import_export_template_form', 'export'),
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_NORMAL_ITEM,
+<<<<<<< HEAD
+      'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  // AHAH ---------
+  $items['admin/tripal/tripal_bulk_loader_template/add_field_ahah'] = array(
+      'page callback' => 'tripal_bulk_loader_add_field_ahah',
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_CALLBACK,
+      'file' => 'tripal_bulk_loader.admin.inc',
+  );
+  $items['admin/tripal/tripal_bulk_loader_template/edit_field_ahah'] = array(
+      'page callback' => 'tripal_bulk_loader_edit_field_ahah',
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_CALLBACK,
+      'file' => 'tripal_bulk_loader.admin.inc',
+  );
+=======
+		  'file' => 'tripal_bulk_loader.admin.inc',
+  );
+	// AHAH ---------
+	$items['admin/tripal/tripal_bulk_loader_template/add_field_ahah'] = array(
+      'page callback' => 'tripal_bulk_loader_add_field_ahah',
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_CALLBACK,
+		  'file' => 'tripal_bulk_loader.admin.inc',
+	);
+	$items['admin/tripal/tripal_bulk_loader_template/edit_field_ahah'] = array(
+      'page callback' => 'tripal_bulk_loader_edit_field_ahah',
+      'access arguments' => array('administer site configuration'),
+      'type' => MENU_CALLBACK,
+		  'file' => 'tripal_bulk_loader.admin.inc',
+	);
+>>>>>>> 6.x-0.4-dev
+
+  return $items;
+}
+
+
+/**
+ * Implements hook_theme
+ */
+function tripal_bulk_loader_theme() {
+  return array(
+    'tripal_bulk_loader_set_constants_form' => array(
+      'arguments' => array('form' => NULL),
+    ),
+    'tripal_bulk_loader_template' => array(
+      'arguments' => array('template_id' => NULL),
+      'template' => 'tripal_bulk_loader_template'
+    ),
+    'tripal_bulk_loader_modify_template_base_form' => array(
+      'arguments' => array('form' => NULL),
+      'template' => 'tripal_bulk_loader_modify_template_base_form',
+    ),
+    'tripal_bulk_loader_edit_template_field_form' => array(
+      'arguments' => array('form' => NULL),
+      'template' => 'tripal_bulk_loader_edit_template_field_form',
+    ),
+    'tripal_bulk_loader_add_template_field_form' => array(
+      'arguments' => array('form' => NULL),
+      'template' => 'tripal_bulk_loader_add_template_field_form',
+    ),
+  );
+}
+
+/**
+ *  Implements hook_access
+ */
+function tripal_bulk_loader_access($op, $node, $account) {
+  if ($op == 'create') {
+    if (!user_access('create tripal_bulk_loader', $account)) {
+         return FALSE;
+      }
+  }
+  if ($op == 'update') {
+    if (!user_access('edit tripal_bulk_loader', $account)) {
+      return FALSE;
+    }
+  }
+  if ($op == 'delete') {
+    if (!user_access('delete tripal_bulk_loader', $account)) {
+      return FALSE;
+    }
+  }
+  if ($op == 'view') {
+    if (!user_access('access tripal_bulk_loader', $account)) {
+      return FALSE;
+    }
+  }
+  return NULL;
+}
+
+/**
+ * Implements hook_perm
+ */
+function tripal_bulk_loader_perm() {
+  return array(
+      'access tripal_bulk_loader',
+      'create tripal_bulk_loader',
+      'delete tripal_bulk_loader',
+      'edit tripal_bulk_loader',
+  );
+}
+
+/**
+ * Creates a listing page for all bulk loading jobs
+ */
+function tripal_bulk_loader_list() {
+  $num_results_per_page = 50;
+  $output = '';
+
+<<<<<<< HEAD
+  $header = array('', 'Status', 'Loader', 'File');
+=======
+  $header = array('','Status','Loader','File');
+>>>>>>> 6.x-0.4-dev
+  $rows = array();
+
+  $query = 'SELECT * FROM {tripal_bulk_loader} l '
+    .'LEFT JOIN {node} n ON n.nid = l.nid '
+    .'LEFT JOIN {tripal_bulk_loader_template} t ON t.template_id = cast(l.template_id as integer)';
+  $resource = pager_query($query, $num_results_per_page, 0, NULL);
+  while ($r = db_fetch_object($resource)) {
+    $row = array(
+      l($r->title, 'node/' . $r->nid),
+      $r->job_status,
+      $r->name,
+      $r->file
+    );
+    $rows[] = $row;
+  }
+
+  $output .= theme('table', $header, $rows);
+  return $output;
+
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////////
+// Node Functions
+//////////////////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * Implements hook_node_info
+ */
+function tripal_bulk_loader_node_info() {
+  $nodes = array();
+  $nodes['tripal_bulk_loader'] = array(
+      'name' => t('Bulk Loading Job'),
+      'module' => 'tripal_bulk_loader',
+      'description' => t('A bulk loader for inserting tab-delimited data into chado database'),
+      'has_title' => TRUE,
+      'has_body' => FALSE,
+      'locked' => TRUE
+  );
+  return $nodes;
+}
+
+/**
+ * Implements node_form
+ * Used to gather the extra details stored with a Bulk Loading Job Node
+ */
+function tripal_bulk_loader_form($node, $form_state) {
+  $form = array();
+
+  if (isset($form_state['values'])) {
+    $node = $form_state['values'] + (array)$node;
+    $node = (object) $node;
+  }
+
+  $sql = "SELECT * FROM {tripal_bulk_loader_template}";
+  $results = db_query($sql);
+  $templates = array();
+  while ($template = db_fetch_object ($results)) {
+    $templates [$template->template_id] = $template->name;
+  }
+
+  if (!$templates) {
+    $form['label'] = array(
+    '#type' => 'item',
+      '#description' => t("Loader template needs to be created before any bulk loader can be added. Go to 'Tripal Management > Bulk Loader Template' to create the template."),
+      '#weight'        => -10,
+    );
+
+    return $form;
+  }
+
+  $form['loader'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Basic Details'),
+  );
+
+  $form['loader']['loader_name'] = array(
+    '#type'          => 'textfield',
+    '#title'         => t('Loading Job Name'),
+    '#weight'        => -10,
+    '#required'      => TRUE,
+    '#default_value' => $node->loader_name
+  );
+
+  $form['loader']['template_id'] = array(
+    '#type' => 'select',
+    '#title' => t('Template'),
+    '#description'   => t('Please specify a template for this loader'),
+    '#options'       => $templates,
+    '#weight'        => -9,
+    '#required'      => TRUE,
+    '#default_value' => $node->template_id,
+  );
+
+  $form['loader']['file']= array(
+    '#type'          => 'textfield',
+    '#title'         => t('Data File'),
+    '#description'   => t('Please specify the data file to be loaded.'),
+    '#weight'        => -8,
+    '#default_value' => $node->file
+  );
+
+  $form['loader']['has_header'] = array(
+    '#type' => 'radios',
+    '#title' => t('File has a Header'),
+    '#options' => array( 1 => 'Yes', 2 => 'No'),
+    '#weight' => -7,
+    '#default_value' => $node->file_has_header,
+  );
+
+  return $form;
+}
+
+
+/**
+ * Implements node_load
+ */
+function tripal_bulk_loader_load($node) {
+  $sql = "SELECT * FROM {tripal_bulk_loader} WHERE nid = %d";
+  $node = db_fetch_object(db_query($sql, $node->nid));
+
+<<<<<<< HEAD
+  $node->title = 'Bulk Loading Job: ' . $node->loader_name;
+
+  // Add the loader template
+  $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+  $results = db_fetch_object(db_query($sql, $node->template_id));
+  $template = unserialize($results->template_array);
+  $node->template = $results;
+  $node->template->template_array = $template;
+=======
+	$node->title = 'Bulk Loading Job: '.$node->loader_name;
+
+	// Add the loader template
+	$sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+	$results = db_fetch_object(db_query($sql, $node->template_id));
+	$template = unserialize($results->template_array);
+	$node->template = $results;
+	$node->template->template_array = $template;
+>>>>>>> 6.x-0.4-dev
+
+  // Add inserted records
+  $sql = 'SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d';
+  $resource = db_query($sql, $node->nid);
+  while ($r = db_fetch_object($resource)) {
+<<<<<<< HEAD
+    $r->num_inserted = sizeof(preg_split('/,/', $r->ids_inserted));
+=======
+    $r->num_inserted = sizeof(preg_split('/,/',$r->ids_inserted));
+>>>>>>> 6.x-0.4-dev
+    $node->inserted_records->{$r->table_inserted_into} = $r;
+  }
+
+  // Add exposed field list
+  $node->exposed_fields = array();
+  if ($template) {
+    foreach ($template as $record_id => $record) {
+      foreach ($record['fields'] as $field_id => $field) {
+        if ($field['exposed']) {
+          $node->exposed_fields[] = array(
+            'record_id' => $record_id,
+            'field_id' => $field_id,
+            'title' => $field['title'],
+          );
+        }
+      }
+    }
+
+    if (empty($node->exposed_fields)) {
+      $node->exposed_fields[] = array();
+    }
+  }
+
+
+  // Add constants
+  $sql = 'SELECT * FROM {tripal_bulk_loader_constants} WHERE nid=%d ORDER BY group_id, record_id, field_id';
+  $resource = db_query($sql, $node->nid);
+  while ($r = db_fetch_object($resource)) {
+    $node->constants[$r->group_id][$r->record_id][$r->field_id] = array(
+      'constant_id' => $r->constant_id,
+      'group_id' => $r->group_id,
+<<<<<<< HEAD
+      'chado_table' => $r->chado_table,
+      'chado_field' => $r->chado_field,
+      'record_id' => $r->record_id,
+      'field_id' => $r->field_id,
+      'value' => $r->value
+=======
+      'chado_table'=>$r->chado_table,
+      'chado_field'=>$r->chado_field,
+      'record_id'=>$r->record_id,
+      'field_id'=>$r->field_id,
+      'value'=>$r->value
+>>>>>>> 6.x-0.4-dev
+    );
+  }
+  if (!$node->constants) {
+    $node->constants[] = array();
+  }
+
+<<<<<<< HEAD
+  return $node;
+=======
+	return $node;
+>>>>>>> 6.x-0.4-dev
+}
+
+/**
+ * Implements node_insert
+ * Insert the data from the node form on Create content
+ */
+<<<<<<< HEAD
+function tripal_bulk_loader_insert($node) {
+=======
+function tripal_bulk_loader_insert ($node) {
+>>>>>>> 6.x-0.4-dev
+
+  // Insert into tripal_bulk_loader
+  $sql = "INSERT INTO {tripal_bulk_loader} (nid, loader_name, template_id, file, file_has_header, job_status) VALUES (%d, '%s', %d, '%s', %d, '%s')";
+  db_query($sql, $node->nid, $node->loader_name, $node->template_id, $node->file, $node->has_header, 'Initialized');
+
+<<<<<<< HEAD
+  // Update title
+  $node->title =$node->loader_name;
+  drupal_write_record('node', $node, 'nid');
+  drupal_write_record('node_revision', $node, 'nid');
+=======
+	// Update title
+	$node->title =$node->loader_name;
+	drupal_write_record('node',$node,'nid');
+	drupal_write_record('node_revision',$node,'nid');
+>>>>>>> 6.x-0.4-dev
+
+  drupal_set_message('After reviewing the details, please Submit this Job (by clicking the "Submit Job" button below). No data will be loaded until the submitted job is reached in the queue.');
+
+}
+
+/**
+ * Implements node_delete
+ * Deletes the data when the delete button on the node form is clicked
+ */
+function tripal_bulk_loader_delete($node) {
+  $sql = "DELETE FROM {tripal_bulk_loader} WHERE nid = %d";
+  db_query($sql, $node->nid);
+}
+
+/**
+ * Implements node_update
+ * Updates the data submitted by the node form on edit
+ */
+<<<<<<< HEAD
+function tripal_bulk_loader_update($node) {
+
+  // Update tripal_bulk_loader
+  $sql = "UPDATE {tripal_bulk_loader} SET nid = %d, loader_name = '%s', template_id = %d, file = '%s', file_has_header = '%s' WHERE nid = %d";
+  db_query($sql, $node->nid, $node->loader_name, $node->template_id, $node->file, $node->has_header, $node->nid);
+
+  // Add a job if the user want to load the data
+  global $user;
+  if ($node->job) {
+    $job_args[0] =$node->loader_name;
+    $job_args[1] = $node->template_id;
+    $job_args[2] = $node->file;
+    if (is_readable($node->file)) {
+      $fname = preg_replace("/.*\/(.*)/", "$1", $node->file);
+      tripal_add_job("Bulk Load: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
+    }
+    else {
+      drupal_set_message(t("Can not open %file. Job not scheduled.", array('%file' => $node->file)));
+    }
+  }
+=======
+function tripal_bulk_loader_update ($node) {
+
+  // Update tripal_bulk_loader
+	$sql = "UPDATE {tripal_bulk_loader} SET nid = %d, loader_name = '%s', template_id = %d, file = '%s', file_has_header = '%s' WHERE nid = %d";
+	db_query($sql, $node->nid, $node->loader_name, $node->template_id, $node->file, $node->has_header, $node->nid);
+
+	// Add a job if the user want to load the data
+	global $user;
+	if($node->job) {
+		$job_args[0] =$node->loader_name;
+		$job_args[1] = $node->template_id;
+		$job_args[2] = $node->file;
+		if (is_readable($node->file)) {
+			$fname = preg_replace("/.*\/(.*)/", "$1", $node->file);
+			tripal_add_job("Bulk Load: $fname",'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
+		} else {
+			drupal_set_message("Can not open $node->file. Job not scheduled.");
+		}
+	}
+>>>>>>> 6.x-0.4-dev
+
+}
+
+///////////////////////////////////////////////////////////
+
+/**
+ * Preprocessor function for the tripal_bulk_loader template
+ */
+function tripal_bulk_loader_preprocess_tripal_bulk_loader_template(&$variables) {
+
+  $sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+  $template = db_fetch_object(db_query($sql, $variables['template_id']));
+  $template->template_array = unserialize($template->template_array);
+  $variables['template'] = $template;
+
+<<<<<<< HEAD
+=======
+	$sql = "SELECT * FROM {tripal_bulk_loader_template} WHERE template_id=%d";
+	$template = db_fetch_object(db_query($sql, $variables['template_id']));
+	$template->template_array = unserialize($template->template_array);
+	$variables['template'] = $template;
+
+>>>>>>> 6.x-0.4-dev
+}
+
+/**
+ * Implements hook_job_describe_args()
+ * Specifically to make viewing past tripal jobs more readable for jobs registered by this module
+ *
+ * @params $callback
+ *   The callback passed into tripal_add_job()
+ * @param $args
+ *   The arguements passed into tripal_add_job()
+ * @return
+ *   An array where keys are the human readable headers describing each arguement
+ *   and the value is the aguement passed in after formatting
+ */
+function tripal_bulk_loader_job_describe_args($callback, $args) {
+
+  $new_args = array();
+  if ($callback == 'tripal_bulk_loader_load_data') {
+    //1st arg is the nid for a bulk loader node
+    $node = node_load($args[0]);
+    $new_args['Bulk Loading Job'] = l($node->title, 'node/' . $args[0]);
+    return $new_args;
+  }
+
+}
+

+ 7 - 2
tripal_contact/tripal_contact.api.inc

@@ -1,9 +1,14 @@
 <?php
 
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 /****************************************************************************
  * @section Chado Table Descriptions
  ****************************************************************************/
- 
+
  /**
  * Implements hook_chado_contact_schema()
  * Purpose: To add descriptions and foreign keys to default table description
@@ -50,6 +55,6 @@ function tripal_stock_chado_contact_relationship_schema() {
           'object_id' => 'contact_id',
         ),
   );
-  
+
   return $description;
 }

+ 141 - 29
tripal_core/tripal_core.api.inc

@@ -104,6 +104,21 @@ require_once "tripal_core.schema.api.inc";
  */
 function tripal_core_chado_insert($table, $values) {
   $insert_values = array();
+  $chado_db = tripal_db_persistent_chado();
+
+  // Determine plan of action
+  if ($options['statement_name']) {
+    $prepared = TRUE;
+    if ($options['prepare']) {
+      $build_sql = TRUE;
+    }
+    else {
+      $build_sql = FALSE;
+    }
+  }
+  else {
+    $build_sql = TRUE;
+  }
 
   // get the table description
   $table_desc = module_invoke_all('chado_' . $table . '_schema');
@@ -177,47 +192,101 @@ function tripal_core_chado_insert($table, $values) {
   }
 
   // Now build the insert SQL statement
-  $ifields = array();
-  $ivalues = array();
-  $itypes = array();
-  foreach ($insert_values as $field => $value) {
-    array_push($ifields, $field);
-    array_push($ivalues, $value);
-    if (strcmp($value, '__NULL__') == 0) {
-      array_push($itypes, "NULL");
+  $ifields = array(); //contains the names of the fields
+  $ivalues = array(); //contains the values of the fields
+  $itypes = array(); // contains %d/%s placeholders for the sql query
+  $iplaceholders = array(); // contains $1/$2 placeholders for the prepare query
+  $idatatypes = array(); //contains the data type of the fields (int, text, etc.)
+  $i = 1;
+  foreach ($insert_values as $field => $value){
+    $ifields[] = $field;
+    $ivalues[] = $value;
+    $iplaceholders[] = '$'.$i;
+    $i++;
+    if(strcmp($value,'__NULL__')==0){
+      $itypes[] = "NULL";
+      $idatatypes[] = "NULL";
     }
-    elseif (strcmp($fields[$field]['type'], 'serial') == 0 or
-      strcmp($fields[$field]['type'], 'int') == 0) {
-      array_push($itypes, "%d");
+    elseif(strcmp($fields[$field]['type'],'serial')==0 or
+      strcmp($fields[$field]['type'],'int')==0){
+      $itypes[] = "%d";
+      $idatatypes[] = 'int';
     }
     else {
-      array_push($itypes, "'%s'");
+      $itypes[] = "'%s'";
+      $idatatypes[] = 'text';
+    }
+  }
+
+  if ($build_sql) {
+    // prepare the statement
+    if ($prepared) {
+      $prepare_sql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (" . implode(", ", $iplaceholders) . ")";
+
+      $previous_db = tripal_db_set_active('chado');
+      $status = db_query($prepare_sql);
+      tripal_db_set_active($previous_db);
+
+      if (!$status) {
+        watchdog('tripal_core',"tripal_core_chado_insert: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), 'WATCHDOG ERROR');
+        return FALSE;
+       }
+    } else {
+      $sql = "INSERT INTO {$table} (" . implode(", ",$ifields) . ") VALUES (". implode(", ",$itypes) .")";
     }
   }
-  $sql = "INSERT INTO {$table} (" . implode(", ", $ifields) . ") VALUES (". implode(", ", $itypes) .")";
 
   // finally perform the insert.
-  $previous_db = tripal_db_set_active('chado');  // use chado database
-  $result = db_query($sql, $ivalues);
-  tripal_db_set_active($previous_db);  // now use drupal database
-  if ($result) {
-    // add primary keys to values before return
-    $primary_key = array();
-    if (!is_array($table_desc['primary key'])) {
-      $table_desc['primary key'] = array();
-      watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
+  if ($prepared) {
+
+    $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $itypes) . ")";
+
+    $previous_db = tripal_db_set_active('chado');
+    $result = db_query($sql, $ivalues);
+    tripal_db_set_active($previous_db);
+    if ($result) {
+      // add primary keys to values before return
+      $primary_key = array();
+      if (!is_array($table_desc['primary key'])) {
+        $table_desc['primary key'] = array();
+        watchdog('tripal_core',"tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
+      }
+      foreach ($table_desc['primary key'] as $field) {
+        $value = db_last_insert_id($table, $field);
+        $values[$field] = $value;
+      }
+      return $values;
     }
-    foreach ($table_desc['primary key'] as $field) {
-      $value = db_last_insert_id($table, $field);
-      $values[$field] = $value;
+    else {
+      watchdog('tripal_core',"tripal_core_chado_insert: not able to execute prepared statement '%name' with values: %values", array('%name' => $options['statement_name'], '%values' => print_r($values,1)), 'WATCHDOG ERROR');
+      return FALSE;
     }
-    return $values;
   }
   else {
-    watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
-    return FALSE;
+    $previous_db = tripal_db_set_active('chado');  // use chado database
+    $result = db_query($sql, $ivalues);
+    tripal_db_set_active($previous_db);  // now use drupal database
+    if ($result) {
+      // add primary keys to values before return
+      $primary_key = array();
+      if (!is_array($table_desc['primary key'])) {
+        $table_desc['primary key'] = array();
+        watchdog('tripal_core', "tripal_core_chado_insert: %table not defined in tripal schema api", array('%table' => $table), 'WATCHDOG WARNING');
+      }
+      foreach ($table_desc['primary key'] as $field) {
+        $value = db_last_insert_id($table, $field);
+        $values[$field] = $value;
+      }
+      return $values;
+    }
+    else {
+      watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert record into $table table: " . print_r($values, 1), array(), 'WATCHDOG_ERROR');
+      return FALSE;
+    }
   }
+
   return FALSE;
+
 }
 
 /**
@@ -1781,6 +1850,48 @@ function tripal_db_set_active($dbname) {
   }
 }
 
+
+/**
+ * Instantiate or Return a persistent chado connection
+ *
+ * NOTE: cannot use $active_db since a new connection is created each time
+ * db_set_active() is called
+ *
+ * @return
+ *   A postgresql connection object which can be used by pg_prepare, pg_execute, etc.
+ */
+function tripal_db_persistent_chado () {
+  global $db_url;
+
+  // get connection if it already exists
+  $connection = variable_get('tripal_perisistent_chado',NULL);
+
+  if ($connection) {
+    return $connection;
+
+  // Otherwise we need to set it
+  } else {
+    if (is_array($db_url) && isset($db_url['chado'])) {
+      $connection = db_connect($db_url['chado']);
+      variable_set('tripal_perisistent_chado', $connection);
+    } else {
+      $connection = db_connect($db_url);
+      variable_set('tripal_perisistent_chado', $connection);
+    }
+
+    return $connection;
+  }
+  return FALSE;
+}
+
+/**
+ * Release a persistent chado connection
+ */
+function tripal_db_release_persistent_chado () {
+  variable_del('tripal_perisistent_chado');
+}
+
+
 /**
  * Purpose: Get max rank for a given set of criteria
  *   This function was developed with the many property tables in chado in mind
@@ -1957,4 +2068,5 @@ function tripal_core_chado_schema_exists() {
   else {
     return FALSE;
   }
-}
+}
+

+ 71 - 63
tripal_feature/tripal_feature-db_references.inc

@@ -1,14 +1,19 @@
 <?php
 
 /**
- * 
+ * @file
+ * @todo Add file header description
+ */
+
+/**
+ *
  *
  * @ingroup tripal_feature
  */
 function tripal_feature_add_ALL_dbreferences_page($node) {
   $output = '';
 
-  $output .= tripal_feature_implement_add_chado_properties_progress('db_references').'<br>';
+  $output .= tripal_feature_implement_add_chado_properties_progress('db_references') . '<br>';
   $output .= '<b>All Database References should strictly pertain to THE CURRENT Individual</b><br>';
   $output .= '<br><b>Current Database References</b><br>';
   $output .= list_dbreferences_for_node($node->db_references);
@@ -87,23 +92,23 @@ function tripal_feature_add_ONE_dbreference_form_validate($form, &$form_state) {
 
    // Check database is valid db_id in chado
    $previous_db = tripal_db_set_active('chado');
-   $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM db WHERE db_id=%d",$db_id));
-   tripal_db_set_active($previous_db);    	
+   $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM {db} WHERE db_id=%d", $db_id));
+   tripal_db_set_active($previous_db);
    if ($tmp_obj->count != 1) {
-      form_set_error('database', 'The database you selected is not valid. Please choose another one.'); 
+      form_set_error('database', 'The database you selected is not valid. Please choose another one.');
    }
 
    // Check Accession is unique for database
    $previous_db = tripal_db_set_active('chado');
-   $sql = "SELECT count(*) as count FROM dbxref WHERE accession='%s' and db_id = %d";
-   $tmp_obj = db_fetch_object(db_query($sql,$accession,$db_id));
+   $sql = "SELECT count(*) as count FROM {dbxref} WHERE accession='%s' and db_id = %d";
+   $tmp_obj = db_fetch_object(db_query($sql, $accession, $db_id));
    tripal_db_set_active($previous_db);
 
    if ($tmp_obj->count > 0) {
-      form_set_error('accession', 'This accession has already been assigned to another feature in the selected database.'); 
+      form_set_error('accession', 'This accession has already been assigned to another feature in the selected database.');
    }
 
-} 
+}
 
 /**
  *
@@ -120,23 +125,24 @@ function tripal_feature_add_ONE_dbreference_form_submit($form, &$form_state) {
 
    // create dbxref
    $previous_db = tripal_db_set_active('chado');
-   $isql =  "INSERT INTO dbxref (db_id, accession, description) VALUES (%d, '%s', '%s')";
-   db_query($isql,$db_id,$accession,$description);
+   $isql =  "INSERT INTO {dbxref} (db_id, accession, description) VALUES (%d, '%s', '%s')";
+   db_query($isql, $db_id, $accession, $description);
    tripal_db_set_active($previous_db);
 
    //create feature_dbxref
-   $dbxref = tripal_db_get_dbxref( array('db_id'=>array('type'=>'INT','value'=>$form_state['values']['db_id']), 
- 											'accession'=>array('type'=>'STRING','exact'=>TRUE,'value'=>$form_state['values']['accession']) ) );
-
-	if (!empty($dbxref->dbxref_id)) {
-		$previous_db = tripal_db_set_active('chado');
-      $isql = "INSERT INTO feature_dbxref (feature_id, dbxref_id) VALUES (%d, %d)";
- 	   db_query($isql,$feature_id,$dbxref->dbxref_id);
-		tripal_db_set_active($previous_db);
-    	drupal_set_message('Successfully Added Database Reference');
-      drupal_goto('node/'.$nid);
-   } else {
- 	   drupal_set_message('Database reference NOT successfully created...','error');
+   $dbxref = tripal_db_get_dbxref( array('db_id' => array('type' => 'INT', 'value' => $form_state['values']['db_id']),
+                       'accession' => array('type' => 'STRING', 'exact' => TRUE, 'value' => $form_state['values']['accession']) ) );
+
+  if (!empty($dbxref->dbxref_id)) {
+    $previous_db = tripal_db_set_active('chado');
+      $isql = "INSERT INTO {feature_dbxref} (feature_id, dbxref_id) VALUES (%d, %d)";
+      db_query($isql, $feature_id, $dbxref->dbxref_id);
+    tripal_db_set_active($previous_db);
+      drupal_set_message('Successfully Added Database Reference');
+      drupal_goto('node/' . $nid);
+   }
+   else {
+      drupal_set_message('Database reference NOT successfully created...', 'error');
    } //end of if dbxref was created successfully
 
 }
@@ -159,12 +165,12 @@ function tripal_feature_edit_ALL_dbreferences_page($node) {
   return $output;
 }
 
-/**                                           
- * Implements Hook_form()                      
+/**
+ * Implements Hook_form()
  * Handles adding of DB References to Features
  *
  * @ingroup tripal_feature
- */                                        
+ */
 function tripal_feature_edit_ALL_db_references_form($form_state, $node) {
   $form = array();
 
@@ -176,7 +182,7 @@ function tripal_feature_edit_ALL_db_references_form($form_state, $node) {
   $i=0;
 
   $feature = $node->feature;
-  $references = tripal_feature_load_references ($feature->feature_id);
+  $references = tripal_feature_load_references($feature->feature_id);
 
   // pre populate the database options
   $db_options = tripal_db_get_db_options();
@@ -188,7 +194,7 @@ function tripal_feature_edit_ALL_db_references_form($form_state, $node) {
        $i++;
        $form["num-$i"] = array(
          '#type' => 'fieldset',
-         '#title' => t("Database Reference")." $i"
+         '#title' => t("Database Reference") . " $i"
        );
 
        $form["num-$i"]["accession-$i"] = array(
@@ -199,11 +205,11 @@ function tripal_feature_edit_ALL_db_references_form($form_state, $node) {
          '#default_value' => $ref->accession
        );
 
-       $form["num-$i"]["db_id-$i"] = array( 
-         '#type' => 'select', 
+       $form["num-$i"]["db_id-$i"] = array(
+         '#type' => 'select',
          '#title' => t('Database'),
          '#options' => $db_options,
-         '#required' => TRUE, 
+         '#required' => TRUE,
          '#default_value' => $ref->db_id
        );
 
@@ -246,29 +252,30 @@ function tripal_feature_edit_ALL_db_references_form_submit($form, &$form_state)
   $button = $form_state['clicked_button']['#name'];
   $nid = $form_state['values']['nid'];
 
-  if (strcmp($action,'Update All References')==0) {
+  if (strcmp($action, 'Update All References')==0) {
      for ($i=1; $i<=$num_refs; $i++) {
-		 $dbxref_id = $form_state['values']["dbxref_id-$i"]; 
-		 $db_id = $form_state['values']["db_id-$i"];
-		 $accession = $form_state['values']["accession-$i"];
-       tripal_feature_update_db_reference($dbxref_id,$db_id,$accession);
+     $dbxref_id = $form_state['values']["dbxref_id-$i"];
+     $db_id = $form_state['values']["db_id-$i"];
+     $accession = $form_state['values']["accession-$i"];
+       tripal_feature_update_db_reference($dbxref_id, $db_id, $accession);
      }
      drupal_set_message("Updated all Database References");
-     drupal_goto('node/'.$nid);
-  } 
-  elseif (strcmp($action,'Delete')==0){
-     if(preg_match('/delete-(\d+)/', $button, $matches) ) {
+     drupal_goto('node/' . $nid);
+  }
+  elseif (strcmp($action, 'Delete')==0) {
+     if (preg_match('/delete-(\d+)/', $button, $matches) ) {
         $i = $matches[1];
-	     $dbxref_id = $form_state['values']["dbxref_id-$i"]; 
+       $dbxref_id = $form_state['values']["dbxref_id-$i"];
         tripal_feature_delete_db_reference($dbxref_id);
         drupal_set_message("Deleted Database Reference");
-        drupal_goto('node/'.$nid);
-     } else {
-        drupal_set_message("Could not remove database reference: ",'error');
+        drupal_goto('node/' . $nid);
+     }
+     else {
+        drupal_set_message("Could not remove database reference: ", 'error');
      }
-  } 
+  }
   else {
-    drupal_set_message("Unrecognized Button Pressed",'error');
+    drupal_set_message("Unrecognized Button Pressed", 'error');
   }
 
 }
@@ -281,8 +288,8 @@ function tripal_feature_edit_ALL_db_references_form_submit($form, &$form_state)
 function tripal_feature_update_db_reference($dbxref_id, $db_id, $accession) {
 
   $previous_db = tripal_db_set_active('chado');
-  $sql =  "UPDATE dbxref SET db_id=%d, accession='%s' WHERE dbxref_id=%d";
-  db_query($sql,$db_id,$accession,$dbxref_id);
+  $sql =  "UPDATE {dbxref} SET db_id=%d, accession='%s' WHERE dbxref_id=%d";
+  db_query($sql, $db_id, $accession, $dbxref_id);
   tripal_db_set_active($previous_db);
 
 }
@@ -296,12 +303,12 @@ function tripal_feature_delete_db_reference($dbxref_id) {
 
   $previous_db = tripal_db_set_active('chado');
   db_query(
-    "DELETE FROM dbxref WHERE dbxref_id=%d",
+    "DELETE FROM {dbxref} WHERE dbxref_id=%d",
     $dbxref_id
   );
 
   db_query(
-    "DELETE FROM feature_dbxref WHERE dbxref_id=%d",
+    "DELETE FROM {feature_dbxref} WHERE dbxref_id=%d",
     $dbxref_id
   );
   tripal_db_set_active($previous_db);
@@ -313,21 +320,21 @@ function tripal_feature_delete_db_reference($dbxref_id) {
  *
  * @ingroup tripal_feature
  */
-function theme_tripal_feature_edit_ALL_db_references_form ($form) {
+function theme_tripal_feature_edit_ALL_db_references_form($form) {
   $output = '';
 
   $output .= '<br><fieldset>';
   $output .= '<legend>Edit Existing Database References<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Below is a list of already existing database references, one per line. When entering a database reference, the accession '
-  	     .'is a unique identifier for this feature in the specified database.</p>';
+         .'is a unique identifier for this feature in the specified database.</p>';
   $output .= '<table>';
   $output .= '<tr><th>#</th><th>Database</th><th>Accession</th><th></th></tr>';
 
   for ($i=1; $i<=$form['num_db_references']['#value']; $i++) {
-    $output .= '<tr><td>'.drupal_render($form["num-$i"]).'</td><td>'
-    	       .drupal_render($form["database-$i"]).'</td><td>'
-	       .drupal_render($form["accession-$i"]).'</td><td>'
-	       .drupal_render($form["submit-$i"]).'</td></tr>';
+    $output .= '<tr><td>' . drupal_render($form["num-$i"]) . '</td><td>'
+             . drupal_render($form["database-$i"]) . '</td><td>'
+         . drupal_render($form["accession-$i"]) . '</td><td>'
+         . drupal_render($form["submit-$i"]) . '</td></tr>';
   }
 
   $output .= '</table><br>';
@@ -338,7 +345,7 @@ function theme_tripal_feature_edit_ALL_db_references_form ($form) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_feature
  */
@@ -349,14 +356,15 @@ function list_dbreferences_for_node($db_references) {
     $output .= '<tr><th>Database</th><th>Accession</th></tr>';
 
     foreach ($db_references as $db) {
-        $output .= '<tr><td>'.$db->db_name.'</td><td>'.$db->accession.'</td></tr>';
-    } // end of foreach db reference 
+        $output .= '<tr><td>' . $db->db_name . '</td><td>' . $db->accession . '</td></tr>';
+    } // end of foreach db reference
 
-    $output .= '</table>'; 
+    $output .= '</table>';
 
-  } else {
+  }
+  else {
     $output = 'No Database References Added to the Current Feature';
-  }              
+  }
 
   return $output;
-}     
+}

+ 45 - 43
tripal_feature/tripal_feature-delete.inc

@@ -1,7 +1,10 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
-
-function tripal_feature_delete_form (){
+function tripal_feature_delete_form() {
    // get the list of organisms
    $sql = "SELECT * FROM {organism} ORDER BY genus, species";
    $previous_db = tripal_db_set_active('chado');  // use chado database
@@ -9,34 +12,34 @@ function tripal_feature_delete_form (){
    tripal_db_set_active($previous_db);  // now use drupal database
    $organisms = array();
    $organisms[''] = '';
-   while($organism = db_fetch_object($org_rset)){
+   while ($organism = db_fetch_object($org_rset)) {
       $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
    }
    $form['desc'] = array(
       '#type' => 'markup',
-      '#value' => t("Use one or more of the following fields to identify sets of features to be deleted."), 
+      '#value' => t("Use one or more of the following fields to identify sets of features to be deleted."),
    );
 
    $form['feature_names']= array(
       '#type' => 'textarea',
       '#title' => t('Feature Names'),
-      '#description' => t('Please provide a list of feature names or unique names, 
+      '#description' => t('Please provide a list of feature names or unique names,
          separated by spaces or by new lines to be delete. If you specify feature names then
          all other options below will be ignored (except the unique checkbox).'),
    );
-	$form['is_unique'] = array(
+  $form['is_unique'] = array(
       '#title' => t('Names are Unique Names'),
       '#type' => 'checkbox',
-      '#description' => t('Select this checbox if the names listed in the feature 
+      '#description' => t('Select this checbox if the names listed in the feature
         names box above are the unique name of the feature rather than the human readable names.'),
-	);
+  );
    $form['seq_type']= array(
       '#type' => 'textfield',
       '#title' => t('Sequence Type'),
       '#description' => t('Please enter the Sequence Ontology term that describes the features to be deleted. Use in conjunction with an organism or anaylysis.'),
    );
 
-   $form['organism_id'] = array (
+   $form['organism_id'] = array(
      '#title'       => t('Organism'),
      '#type'        => t('select'),
      '#description' => t("Choose the organism for which features will be deleted."),
@@ -51,7 +54,7 @@ function tripal_feature_delete_form (){
    tripal_db_set_active($previous_db);  // now use drupal database
    $analyses = array();
    $analyses[''] = '';
-   while($analysis = db_fetch_object($org_rset)){
+   while ($analysis = db_fetch_object($org_rset)) {
       $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
    }
 //  TODO: ADD THIS BACK IN LATER
@@ -70,32 +73,32 @@ function tripal_feature_delete_form (){
    return $form;
 }
 
-function tripal_feature_delete_form_validate ($form, &$form_state){
+function tripal_feature_delete_form_validate($form, &$form_state) {
    $organism_id   = $form_state['values']['organism_id'];
    $seq_type      = trim($form_state['values']['seq_type']);
    $analysis_id   = $form_state['values']['analysis_id'];
    $is_unique     = $form_state['values']['is_unique'];
    $feature_names = $form_state['values']['feature_names'];
 
-   if (!$organism_id and !$anaysis_id and !$seq_type and !$feature_names){
-      form_set_error('feature_names',t("Please select at least one option"));
+   if (!$organism_id and !$anaysis_id and !$seq_type and !$feature_names) {
+      form_set_error('feature_names', t("Please select at least one option"));
    }
 
    // check to make sure the types exists
-   if($seq_type){
+   if ($seq_type) {
       $cvtermsql = "SELECT CVT.cvterm_id
                     FROM {cvterm} CVT
                        INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
                        LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
                     WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
-      $cvterm = db_fetch_object(db_query($cvtermsql,'sequence',$seq_type,$seq_type));
-      if(!$cvterm){
-         form_set_error('seq_type',t("The Sequence Ontology (SO) term selected for the sequence type is not available in the database. Please check spelling or select another."));
+      $cvterm = db_fetch_object(db_query($cvtermsql, 'sequence', $seq_type, $seq_type));
+      if (!$cvterm) {
+         form_set_error('seq_type', t("The Sequence Ontology (SO) term selected for the sequence type is not available in the database. Please check spelling or select another."));
       }
    }
 }
 
-function tripal_feature_delete_form_submit ($form, &$form_state){
+function tripal_feature_delete_form_submit($form, &$form_state) {
    global $user;
 
    $organism_id   = $form_state['values']['organism_id'];
@@ -104,47 +107,47 @@ function tripal_feature_delete_form_submit ($form, &$form_state){
    $is_unique     = $form_state['values']['is_unique'];
    $feature_names = $form_state['values']['feature_names'];
 
-   $args = array($organism_id,$analysis_id,$seq_type,$is_unique,$feature_names);
+   $args = array($organism_id, $analysis_id, $seq_type, $is_unique, $feature_names);
 
-   tripal_add_job("Delete features",'tripal_feature',
-      'tripal_feature_delete_features',$args,$user->uid);
+   tripal_add_job("Delete features", 'tripal_feature',
+      'tripal_feature_delete_features', $args, $user->uid);
 }
 
 
-function tripal_feature_delete_features($organism_id,$analysis_id,$seq_type,
-   $is_unique,$feature_names,$job = NULL)
-{
+function tripal_feature_delete_features($organism_id, $analysis_id, $seq_type,
+   $is_unique, $feature_names, $job = NULL) {
 
    global $user;
-   $match = array();   
+   $match = array();
 
    // if feature names have been provided then handle that separately
-   if($feature_names){
-      $names = preg_split('/\s+/',$feature_names);
-      if(sizeof($names) == 1){
+   if ($feature_names) {
+      $names = preg_split('/\s+/', $feature_names);
+      if (sizeof($names) == 1) {
          $names = $names[0];
       }
-      if($is_unique){
+      if ($is_unique) {
          $match['uniquename'] = $names;
-      } else {
+      }
+      else {
          $match['name'] = $names;
       }
-      $num_deletes = tripal_core_chado_select('feature',array('count(*) as cnt'),$match);
-      print "Deleting ".$num_deletes[0]->cnt ." features\n"; 
-      tripal_core_chado_delete('feature',$match);
+      $num_deletes = tripal_core_chado_select('feature', array('count(*) as cnt'), $match);
+      print "Deleting " . $num_deletes[0]->cnt . " features\n";
+      tripal_core_chado_delete('feature', $match);
    }
 
    // if the user has provided an analysis_id then handle that separately
-   elseif($analysis_id){
+   elseif ($analysis_id) {
       tripal_feature_delete_by_analysis();
    }
    else {
 
 
-      if($organism_id){
+      if ($organism_id) {
          $match['organism_id'] = $organism_id;
       }
-      if($seq_type){
+      if ($seq_type) {
          $match['type_id'] = array(
             'name' => $seq_type,
             'cv_id' => array(
@@ -152,18 +155,17 @@ function tripal_feature_delete_features($organism_id,$analysis_id,$seq_type,
             ),
          );
       }
-      $num_deletes = tripal_core_chado_select('feature',array('count(*) as cnt'),$match);
-      print "Deleting ".$num_deletes[0]->cnt ." features\n"; 
-      tripal_core_chado_delete('feature',$match);
+      $num_deletes = tripal_core_chado_select('feature', array('count(*) as cnt'), $match);
+      print "Deleting " . $num_deletes[0]->cnt . " features\n";
+      tripal_core_chado_delete('feature', $match);
    }
 
    print "Removing orphaned feature pages\n";
-   tripal_features_cleanup(array(),$user->uid);
+   tripal_features_cleanup(array(), $user->uid);
 }
 
-function tripal_feature_delete_by_analysis($organism_id,$analysis_id,$seq_type,
-   $is_unique,$feature_names,$job = NULL)
-{
+function tripal_feature_delete_by_analysis($organism_id, $analysis_id, $seq_type,
+   $is_unique, $feature_names, $job = NULL) {
 
 }
 

+ 75 - 67
tripal_feature/tripal_feature-properties.inc

@@ -1,4 +1,8 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
  *
@@ -10,12 +14,12 @@ function tripal_feature_edit_ALL_properties_page($node) {
 
   // get the list of properties for this feature
   $values  = array('feature_id' => $node->feature->feature_id);
-  $options = array('order_by' => array('type_id' => 'ASC','rank'=>'ASC'));
-  $properties = tripal_core_generate_chado_var('featureprop',$values,$options);
-  $properties = tripal_core_expand_chado_vars($properties,'field','featureprop.value');
-  
+  $options = array('order_by' => array('type_id' => 'ASC', 'rank' => 'ASC'));
+  $properties = tripal_core_generate_chado_var('featureprop', $values, $options);
+  $properties = tripal_core_expand_chado_vars($properties, 'field', 'featureprop.value');
+
   $expand_add = (sizeof($properties)) ? FALSE : TRUE;
-  
+
   // add the appopriate form sections
   $output .= drupal_get_form('tripal_feature_add_ONE_property_form', $node, $expand_add);
   $output .= drupal_get_form('tripal_feature_edit_ALL_properties_form', $node, $properties);
@@ -25,7 +29,7 @@ function tripal_feature_edit_ALL_properties_page($node) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_feature
  */
@@ -38,35 +42,35 @@ function tripal_feature_add_ONE_property_form($form_state, $node, $expand) {
     '#title' => t('Add Property'),
     '#collapsible' => TRUE,
     '#collapsed' => ($expand) ? FALSE : TRUE,
-  ); 
+  );
 
   $form['prop_nid'] = array(
     '#type' => 'hidden',
     '#value' => $node->nid
   );
-  
+
   $form['add_properties']['feature_id'] = array(
     '#type' => 'value',
     '#value' => $feature_id,
     '#required' => TRUE
   );
-  
+
   // right now this defaults to the 'feature_property' CV
   // but in the future it should be more flexible
   $form['cv_name'] = array(
     '#type' => 'hidden',
     '#value' => 'feature_property'
   );
-	
+
   // get the list of property types
   $prop_type_options = array();
-  $columns = array('cvterm_id','name');
+  $columns = array('cvterm_id', 'name');
   $values = array(
     'cv_id' => array(
       'name' => $form['cv_name']['#value'],
     )
   );
-  $results = tripal_core_chado_select('cvterm',$columns,$values);
+  $results = tripal_core_chado_select('cvterm', $columns, $values);
   foreach ($results as $r) {
     $prop_type_options[$r->name] = $r->name;
   }
@@ -83,7 +87,7 @@ function tripal_feature_add_ONE_property_form($form_state, $node, $expand) {
   );
 
   $form['add_properties']['submit-add'] = array(
-    '#type' => 'submit',         
+    '#type' => 'submit',
     '#value' => t('Add Property')
   );
 
@@ -91,7 +95,7 @@ function tripal_feature_add_ONE_property_form($form_state, $node, $expand) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_feature
  */
@@ -99,35 +103,36 @@ function tripal_feature_add_ONE_property_form_validate($form, &$form_state) {
 
    // Only Require if Adding Property
    if ($form_state['clicked_button']['#value'] == t('Add Property') ) {
-   
+
       // Check that there is a feature
       if ( $form_state['values']['feature_id'] <= 0 ) {
          form_set_error('feature_id', 'There is no associated feature.');
       }
-		
+
       // Check that Selected a type
       if ( !$form_state['values']['property']) {
          form_set_error('property', 'Please select a type of property.');
-      } 
-   } 
+      }
+   }
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_add_ONE_property_form_submit($form, &$form_state) {	
+function tripal_feature_add_ONE_property_form_submit($form, &$form_state) {
    $feature_id = $form_state['values']['feature_id'];
    $property = $form_state['values']['property'];
-   $value = $form_state['values']['prop_value'];       
-   $cv_name = $form_state['values']['cv_name'];       
-       
-   $succes = tripal_feature_insert_property($feature_id,$property,$value,0,$cv_name);
-   if($succes){
-      drupal_set_message("Successfully Added Property: $property => $value");
-   } else {
-      drupal_set_message("Failed to Add Property: $property => $value");
+   $value = $form_state['values']['prop_value'];
+   $cv_name = $form_state['values']['cv_name'];
+
+   $succes = tripal_feature_insert_property($feature_id, $property, $value, 0, $cv_name);
+   if ($succes) {
+      drupal_set_message(t("Successfully Added Property: %property => %value", array('%property' => $property), array('%value' => $value)));
+   }
+   else {
+      drupal_set_message(t("Failed to Add Property: %property => %value", array('%property' => $property), array('%value' => $value)));
    }
 }
 
@@ -136,114 +141,114 @@ function tripal_feature_add_ONE_property_form_submit($form, &$form_state) {
  * Handles adding of Properties for features
  *
  * @ingroup tripal_feature
- */ 
+ */
 function tripal_feature_edit_ALL_properties_form($form_state, $node, $properties) {
   $form = array();
   $feature_id = $node->feature->feature_id;
-  
+
   $form['nid'] = array(
     '#type' => 'hidden',
     '#value' => $node->nid
   );
-  
+
   $form['add_properties']['feature_id'] = array(
     '#type' => 'value',
     '#value' => $feature_id,
     '#required' => TRUE
   );
-    
+
   // right now this defaults to the 'feature_property' CV
   // but in the future it should be more flexible
   $form['cv_name'] = array(
     '#type' => 'hidden',
     '#value' => 'feature_property'
   );
-  
+
   if (sizeof($properties)) {
-    
+
     // build the select box options for the property name
     $prop_type_options = array();
-    $columns = array('cvterm_id','name');
+    $columns = array('cvterm_id', 'name');
     $values = array(
        'cv_id' => array(
           'name' => $form['cv_name']['#value']
        )
     );
-    $results = tripal_core_chado_select('cvterm',$columns, $values);
+    $results = tripal_core_chado_select('cvterm', $columns, $values);
     foreach ($results as $r) {
       $prop_type_options[$r->name] = $r->name;
     }
-    
-    // iterate through all of the properties and create a set of form elements 
+
+    // iterate through all of the properties and create a set of form elements
     foreach ($properties as $i => $property) {
        $form["num-$i"] = array(
           '#type' => 'fieldset',
           '#value' => "Property $i"
-       );      
+       );
        $form["num-$i"]["id-$i"] = array(
           '#type' => 'hidden',
           '#value' => $property->featureprop_id
-       );      
-       $default = array_search($property->type, $prop_type_options);  
+       );
+       $default = array_search($property->type, $prop_type_options);
        $form["num-$i"]["type-$i"] = array(
           '#type' => 'select',
           '#options' => $prop_type_options,
           '#default_value' => $property->type_id->name
-       );     
+       );
        $form["num-$i"]["value-$i"] = array(
           '#type' => 'textfield',
           '#default_value' => $property->value
-       );      
+       );
        $form["num-$i"]["delete-$i"] = array(
           '#type' => 'submit',
           '#value' => t("Delete"),
          '#name' => "delete-$i",
        );
     } //end of foreach property
-  
+
     $form['num_properties'] = array(
       '#type' => 'hidden',
       '#value' => $i
     );
-  
+
     $form["submit-edits"] = array(
       '#type' => 'submit',
       '#value' => t('Update All Properties')
     );
   }
-  
+
   return $form;
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_feature
  */
 function tripal_feature_edit_ALL_properties_form_submit($form, &$form_state) {
 
-  $cv_name = $form_state['values']['cv_name'];  
+  $cv_name = $form_state['values']['cv_name'];
   $feature_id = $form_state['values']["feature_id"];
   $all_good = 1;
 
   // if the update button was clicked then do the update
   if ($form_state['clicked_button']['#value'] == t('Update All Properties') ) {
-     // iterate through each of the properties and set each one               
+     // iterate through each of the properties and set each one
      for ($i=1; $i<=$form_state['values']['num_properties']; $i++) {
        $featureprop_id = $form_state['values']["id-$i"];
        $property = $form_state['values']["type-$i"];
        $value = $form_state['values']["value-$i"];
-       $success = tripal_feature_update_property_by_id($featureprop_id,$property,$value,$cv_name);       
-       if(!$success){
-          drupal_set_message("Failed to Update Property: $property => $value");
+       $success = tripal_feature_update_property_by_id($featureprop_id, $property, $value, $cv_name);
+       if (!$success) {
+          drupal_set_message(t("Failed to Update Property: %property => %value", array('%property' => $property), array('%value' => $value)));
           $all_good = 0;
        }
      }
-     if($all_good){
+     if ($all_good) {
         drupal_set_message("Updated all Properties");
      }
-     drupal_goto('node/'.$form_state['values']['nid']);
-  } 
+     drupal_goto('node/' . $form_state['values']['nid']);
+  }
   // if the delete button was clicked then remove the property
   elseif (preg_match('/delete-(\d+)/', $form_state['clicked_button']['#name'], $matches) ) {
      $i = $matches[1];
@@ -251,33 +256,35 @@ function tripal_feature_edit_ALL_properties_form_submit($form, &$form_state) {
      $property = $form_state['values']["type-$i"];
      $value = $form_state['values']["value-$i"];
      $success = tripal_feature_delete_property_by_id($featureprop_id);
-     if($success){
+     if ($success) {
         drupal_set_message("Deleted Property");
-     } else {
+     }
+     else {
         drupal_set_message("Unable to Delete Property");
      }
-  } else {
-    drupal_set_message("Unrecognized Button Pressed",'error');
+  }
+  else {
+    drupal_set_message("Unrecognized Button Pressed", 'error');
   }
 }
 /**
- * 
+ *
  *
  * @ingroup tripal_feature
  */
-function theme_tripal_feature_edit_ALL_properties_form ($form) {
+function theme_tripal_feature_edit_ALL_properties_form($form) {
   $output = '';
-  
+
   $output .= '<br><fieldset>';
   $output .= '<legend>Edit Already Existing Properties<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Below is a list of already existing properties for this feature, one property per line. The type refers to the type of '
-  	     .'property and the value is the value for that property. </p>';
+         .'property and the value is the value for that property. </p>';
   $output .= '<table>';
   $output .= '<tr><th>#</th><th>Type</th><th>Value</th><th></th></tr>';
 
   for ($i=0; $i<=$form['num_properties']['#value']; $i++) {
     if (isset($form["num-$i"])) {
-      $output .= '<tr><td>'.($i+1).'</td><td>'.drupal_render($form["num-$i"]["type-$i"]).'</td><td>'.drupal_render($form["num-$i"]["value-$i"]).'</td><td>'.drupal_render($form["num-$i"]["delete-$i"]).'</td></tr>';
+      $output .= '<tr><td>' . ($i+1) . '</td><td>' . drupal_render($form["num-$i"]["type-$i"]) . '</td><td>' . drupal_render($form["num-$i"]["value-$i"]) . '</td><td>' . drupal_render($form["num-$i"]["delete-$i"]) . '</td></tr>';
       unset($form["num-$i"]);
     }
   }
@@ -290,7 +297,7 @@ function theme_tripal_feature_edit_ALL_properties_form ($form) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_feature
  */
@@ -303,13 +310,14 @@ function tripal_feature_list_properties_for_node($properties) {
 
     if (!empty($properties) ) {
       foreach ($properties as $p) {
-        $output .= '<tr><td>'.$p->type.'</td><td>'.$p->value.'</td></tr>';
+        $output .= '<tr><td>' . $p->type . '</td><td>' . $p->value . '</td></tr>';
       } // end of foreach property
     }
 
     $output .= '</table>';
 
-  } else {
+  }
+  else {
     $output = 'No properties exist for the current feature';
   }
 

+ 153 - 129
tripal_feature/tripal_feature-relationships.inc

@@ -1,5 +1,8 @@
 <?php
-
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
  *
@@ -9,8 +12,8 @@
 function tripal_feature_add_ALL_relationships_page($node) {
   $output = '';
 
-  $output .= tripal_feature_implement_add_chado_properties_progress('relationships').'<br>';
-  $output .= '<b>All Relationships should include the CURRENT Individual ('.$node->uniquename.')</b><br>';
+  $output .= tripal_feature_implement_add_chado_properties_progress('relationships') . '<br>';
+  $output .= '<b>All Relationships should include the CURRENT Individual (' . $node->uniquename . ')</b><br>';
   $output .= '<br><b>Current Relationships</b><br>';
   $output .= list_relationships_for_node($node->uniquename, $node->subject_relationships, $node->object_relationships);
   $output .= '<br><br>';
@@ -33,9 +36,9 @@ function tripal_feature_add_ONE_relationship_form($form_state, $node) {
   $_SESSION['organism'] = $organism_id; //needed for autocomplete enter feature to work
 
   $form['rel_nid'] = array(
-    '#type' => 'hidden', 
+    '#type' => 'hidden',
     '#value' => $node->nid
-  ); 
+  );
 
   $form['add_relationships'] = array(
     '#type' => 'fieldset',
@@ -88,7 +91,7 @@ function tripal_feature_add_ONE_relationship_form($form_state, $node) {
 
   );
 
-  $form['add_relationships']['r_feature_uniquename'] = array( 
+  $form['add_relationships']['r_feature_uniquename'] = array(
     '#type' => 'value',
     '#value' => $node->uniquename,
     '#required' => TRUE
@@ -109,49 +112,56 @@ function tripal_feature_add_ONE_relationship_form_validate($form, &$form_state)
   if ($form_state['clicked_button']['#value'] == t('Add a Relationship') ) {
 
     // check valid feature selected for subject
-    $criteria = array('unknown' => array('value'=> $form_state['values']['subject_id'], 
-      																		'columns'=>array('name','uniquename','accession','synonym') ));
-    $subject_results = get_chado_stocks($criteria,'ANY',$_SESSION['organism']);
+    $criteria = array('unknown' => array('value' => $form_state['values']['subject_id'],
+                                          'columns' => array('name', 'uniquename', 'accession', 'synonym') ));
+    $subject_results = get_chado_stocks($criteria, 'ANY', $_SESSION['organism']);
     if (sizeof($subject_results) > 1) {
       $links= array();
-      for ($i=0; $i<sizeof($subject_results); $i++) { $links[] = l($i+1, "node/".$subject_results[$i]->nid); }
-      $message = "Too many stocks match '".$form_state['values']['subject_id']."'! "
-      	       	 . " Please refine your input to match ONLY ONE stock. <br>"
-		 . "To aid in this process, here are the stocks that match your initial input: "
-		 .join(', ',$links);
+      for ($i=0; $i<sizeof($subject_results); $i++) {
+      $links[] = l($i+1, "node/" . $subject_results[$i]->nid); }
+      $message = "Too many stocks match '" . $form_state['values']['subject_id'] . "'! "
+                  . " Please refine your input to match ONLY ONE stock. <br>"
+     . "To aid in this process, here are the stocks that match your initial input: "
+     . join(', ', $links);
       form_set_error('subject_id', $message);
-    } elseif (sizeof($subject_results) < 1) {
-      form_set_error('subject_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock ".l('here', 'stocks'));
-    } elseif (sizeof($subject_results) == 1) {
+    }
+    elseif (sizeof($subject_results) < 1) {
+      form_set_error('subject_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+    }
+    elseif (sizeof($subject_results) == 1) {
       $form_state['values']['subject_id'] = $subject_results[0]->stock_id;
     }
 
     // check valid stock selected for object
-    $criteria = array('unknown' => array('value'=> $form_state['values']['object_id'], 
-      																		'columns'=>array('name','uniquename','accession','synonym') ));
-    $object_results = get_chado_stocks($criteria,'ANY',$_SESSION['organism']);
+    $criteria = array('unknown' => array('value' => $form_state['values']['object_id'],
+                                          'columns' => array('name', 'uniquename', 'accession', 'synonym') ));
+    $object_results = get_chado_stocks($criteria, 'ANY', $_SESSION['organism']);
     if (sizeof($object_results) > 1) {
       $links= array();
-      for ($i=0; $i<sizeof($object_results); $i++) { $links[] = l($i+1, "node/".$object_results[$i]->nid); } 
-      $message = "Too many stocks match '".$form_state['values']['object_id']."'! "
+      for ($i=0; $i<sizeof($object_results); $i++) {
+      $links[] = l($i+1, "node/" . $object_results[$i]->nid); }
+      $message = "Too many stocks match '" . $form_state['values']['object_id'] . "'! "
                  . "Please refine your input to match ONLY ONE stock. <br>"
                  . "To aid in this process, here are the stocks that match your initial input: "
-                 .join(', ',$links);
+                 . join(', ', $links);
       form_set_error('object_id', $message);
-    } elseif (sizeof($object_results) < 1) {
-      form_set_error('object_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock ".l('here', 'stocks'));                                                                         
-    } elseif (sizeof($object_results) == 1) {
+    }
+    elseif (sizeof($object_results) < 1) {
+      form_set_error('object_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+    }
+    elseif (sizeof($object_results) == 1) {
       $form_state['values']['object_id'] = $object_results[0]->stock_id;
     }
 
     // check valid type selected
     if ($form_state['values']['type_id'] == 0) {
       form_set_error('type_id', 'Please select a type of relationship.');
-    } else {
-    	$previous_db = tripal_db_set_active('chado');
-    	$tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM cvterm WHERE cvterm_id=%d",$form_state['values']['type_id']));
-    	tripal_db_set_active($previous_db);
-    	
+    }
+    else {
+      $previous_db = tripal_db_set_active('chado');
+      $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM {cvterm} WHERE cvterm_id=%d", $form_state['values']['type_id']));
+      tripal_db_set_active($previous_db);
+
       if ($tmp_obj->count != 1) {
         form_set_error('type_id', 'The type you selected is not valid. Please choose another one.');
       }
@@ -160,7 +170,7 @@ function tripal_feature_add_ONE_relationship_form_validate($form, &$form_state)
     // check either subject or object is the current stock
     if ( $subject_results[0]->nid != $form_state['values']['rel_nid'] ) {
       if ( $object_results[0]->nid != $form_state['values']['rel_nid'] ) {
-        form_set_error('subject_id', 'Either Subject or Object must be the current stock ('.$form_state['values']['r_stock_uniquename'].').');
+        form_set_error('subject_id', 'Either Subject or Object must be the current stock (' . $form_state['values']['r_stock_uniquename'] . ').');
       }
     }
   } //end of require validation if adding relationship
@@ -176,7 +186,7 @@ function tripal_feature_add_ONE_relationship_form_submit($form, &$form_state) {
   if ($form_state['values']['subject_id'] > 0) {
     $previous_db = db_set_active('chado');
     db_query(
-      "INSERT INTO stock_relationship (subject_id, type_id, object_id, value) VALUES (%d, %d, %d, '%s')",
+      "INSERT INTO {stock_relationship} (subject_id, type_id, object_id, value) VALUES (%d, %d, %d, '%s')",
       $form_state['values']['subject_id'],
       $form_state['values']['type_id'],
       $form_state['values']['object_id'],
@@ -189,14 +199,14 @@ function tripal_feature_add_ONE_relationship_form_submit($form, &$form_state) {
 
 }
 
-/** 
+/**
  *
  *
  * @ingroup tripal_feature
  */
 function tripal_feature_edit_ALL_relationships_page($node) {
   $output = '';
-	
+
   $output .= drupal_get_form('tripal_feature_edit_ALL_relationships_form', $node);
   $output .= '<br>';
   $output .= drupal_get_form('tripal_feature_add_ONE_relationship_form', $node);
@@ -205,13 +215,13 @@ function tripal_feature_edit_ALL_relationships_page($node) {
 
   return $output;
 }
-                                                      
-/**                                                 
- * Implements Hook_form()                             
- * Handles adding of Properties & Synonyms to Stocks  
+
+/**
+ * Implements Hook_form()
+ * Handles adding of Properties & Synonyms to Stocks
  *
  * @ingroup tripal_feature
- */                                                   
+ */
 function tripal_feature_edit_ALL_relationships_form($form_state, $node) {
   $form = array();
 
@@ -219,7 +229,7 @@ function tripal_feature_edit_ALL_relationships_form($form_state, $node) {
     '#type' => 'hidden',
     '#value' => $node->nid
   );
-  
+
   $form['r_feature_uniquename'] = array(
     '#type' => 'hidden',
     '#value' => $node->uniquename
@@ -228,9 +238,9 @@ function tripal_feature_edit_ALL_relationships_form($form_state, $node) {
   $i=0;
 
   $feature = $node->feature;
-  $orelationships = tripal_feature_load_relationships ($feature->feature_id,'as_object');
-  $srelationships = tripal_feature_load_relationships ($feature->feature_id,'as_subject');
-  $relationships = array_merge($orelationships,$srelationships);
+  $orelationships = tripal_feature_load_relationships($feature->feature_id, 'as_object');
+  $srelationships = tripal_feature_load_relationships($feature->feature_id, 'as_subject');
+  $relationships = array_merge($orelationships, $srelationships);
 
   if (sizeof($relationships) != 0) {
      foreach ($relationships as $r) {
@@ -238,7 +248,7 @@ function tripal_feature_edit_ALL_relationships_form($form_state, $node) {
        $i++;
        $form["num-$i"] = array(
          '#type' => 'fieldset',
-         '#title' => "Relationship $i",
+         '#title' => t("Relationship %i", array('%i' => $i)),
        );
 
        $form["num-$i"]["id-$i"] = array(
@@ -247,45 +257,47 @@ function tripal_feature_edit_ALL_relationships_form($form_state, $node) {
        );
 
        //Enter relationship specific fields
-       if ( !empty($r->subject_id) ) { 
+       if ( !empty($r->subject_id) ) {
          $default = $r->subject_uniquename;
-         $description = l($r->subject_name, 'node/'.$r->subject_nid); 
-       } else { 
-          $default = $node->uniquename; 
-          $description = "Current Feature"; 
+         $description = l($r->subject_name, 'node/' . $r->subject_nid);
        }
-       $description .= " (".$r->subject_type.")";
+       else {
+          $default = $node->uniquename;
+          $description = "Current Feature";
+       }
+       $description .= " (" . $r->subject_type . ")";
        $form["num-$i"]["subject_id-$i"] = array(
-         '#type' => 'textfield',      
-         //'#title' => t('Subject'), 
+         '#type' => 'textfield',
+         //'#title' => t('Subject'),
          '#required'   => TRUE,
          '#size' => 30,
          '#default_value' => $default,
-         '#description' => $description,
-       ); 
+         '#description' => t('%description', array('%description' => $description)),
+       );
 
        $cv = tripal_cv_get_cv_by_name('relationship');
        $type_options = tripal_cv_get_cvterm_options($cv->cv_id);
-       ksort($type_options);          
-       $form["num-$i"]["type_id-$i"] = array(  
-         '#type' => 'select',    
-         //'#title' => t('Type of Relationship'), 
+       ksort($type_options);
+       $form["num-$i"]["type_id-$i"] = array(
+         '#type' => 'select',
+         //'#title' => t('Type of Relationship'),
          '#options' => $type_options,
          '#required' => TRUE,
          '#default_value' => $r->relationship_type_id
        );
 
-       if (!empty($r->object_id) ) { 
+       if (!empty($r->object_id) ) {
          $default = $r->object_uniquename;
-         $description = l($r->object_name, 'node/'.$r->object_nid);
-       } else { 
-         $default = $node->uniquename; 
-         $description = 'Current Feature'; 
+         $description = l($r->object_name, 'node/' . $r->object_nid);
        }
-       $description .= " (".$r->object_type.")";
+       else {
+         $default = $node->uniquename;
+         $description = 'Current Feature';
+       }
+       $description .= " (" . $r->object_type . ")";
        $form["num-$i"]["object_id-$i"] = array(
-         '#type' => 'textfield',          
-         //'#title' => t('Object'),      
+         '#type' => 'textfield',
+         //'#title' => t('Object'),
          '#required'   => TRUE,
          '#size' => 30,
          '#default_value' => $default,
@@ -308,12 +320,13 @@ function tripal_feature_edit_ALL_relationships_form($form_state, $node) {
        '#type' => 'submit',
        '#value' => t('Update All Relationships')
      );
-  } else {
+  }
+  else {
      $form["info"] = array(
        '#type' => 'markup',
        '#value' => t('No relationships currently exist for this feature.')
      );
-  } 
+  }
 
 
 
@@ -331,52 +344,59 @@ function tripal_feature_edit_ALL_relationships_form_validate($form, &$form_state
   if ($form_state['clicked_button']['#value'] == t('Update All Relationships') ) {
 
     for ($i=1; $i<=$form_state['values']['num_relationships']; $i++) {
-      
+
       // check valid stock selected for subject
-      $criteria = array('unknown' => array('value'=>$form_state['values']["subject_id-$i"], 
-      																		'columns'=>array('name','uniquename','accession','synonym') ));
-      $subject_results = get_chado_stocks($criteria,'ANY',$_SESSION['organism']);
+      $criteria = array('unknown' => array('value' => $form_state['values']["subject_id-$i"],
+                                          'columns' => array('name', 'uniquename', 'accession', 'synonym') ));
+      $subject_results = get_chado_stocks($criteria, 'ANY', $_SESSION['organism']);
       if (sizeof($subject_results) > 1) {
         $links= array();
-        for ($j=0; $j<sizeof($subject_results); $j++) { $links[] = l($j+1, "node/".$subject_results[$j]->nid); }
-        $message = "Too many stocks match '".$form_state['values']["subject_id-$i"]."'! "
-                 . "Please refine your input to match ONLY ONE stock. <br>" 
+        for ($j=0; $j<sizeof($subject_results); $j++) {
+        $links[] = l($j+1, "node/" . $subject_results[$j]->nid); }
+        $message = "Too many stocks match '" . $form_state['values']["subject_id-$i"] . "'! "
+                 . "Please refine your input to match ONLY ONE stock. <br>"
                  . "To aid in this process, here are the stocks that match your initial input: "
-                 .join(', ',$links);
+                 . join(', ', $links);
         form_set_error("subject_id-$i", $message);
-      } elseif (sizeof($subject_results) < 1) { 
-        form_set_error("subject_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock ".l('here', 'stocks'));
-      } elseif (sizeof($subject_results) == 1) {
+      }
+      elseif (sizeof($subject_results) < 1) {
+        form_set_error("subject_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+      }
+      elseif (sizeof($subject_results) == 1) {
         $form_state['values']["subject_id-$i"] = $subject_results[0]->stock_id;
-      } 
+      }
 
       // check valid stock selected for object
-      $criteria = array('unknown' => array('value'=> $form_state['values']["object_id-$i"], 
-      																		'columns'=>array('name','uniquename','accession','synonym') ));
-      $object_results = get_chado_stocks($criteria,'ANY',$_SESSION['organism']);
+      $criteria = array('unknown' => array('value' => $form_state['values']["object_id-$i"],
+                                          'columns' => array('name', 'uniquename', 'accession', 'synonym') ));
+      $object_results = get_chado_stocks($criteria, 'ANY' , $_SESSION['organism']);
       if (sizeof($object_results) > 1) {
         $links= array();
-        for ($j=0; $j<sizeof($object_results); $j++) { $links[] = l($j+1, "node/".$object_results[$j]->nid); }
-        $message = "Too many stocks match '".$form_state['values']["object_id-$i"]."'! "
-                 . "Please refine your input to match ONLY ONE stock. <br>" 
+        for ($j=0; $j<sizeof($object_results); $j++) {
+        $links[] = l($j+1, "node/" . $object_results[$j]->nid); }
+        $message = "Too many stocks match '" . $form_state['values']["object_id-$i"] . "'! "
+                 . "Please refine your input to match ONLY ONE stock. <br>"
                  . "To aid in this process, here are the stocks that match your initial input: "
-                 .join(', ',$links);
+                 . join(', ', $links);
         form_set_error("object_id-$i", $message);
-      } elseif (sizeof($object_results) < 1) {
-        form_set_error("object_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock ".l('here', 'stocks'));
-      } elseif (sizeof($object_results) == 1) {
+      }
+      elseif (sizeof($object_results) < 1) {
+        form_set_error("object_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+      }
+      elseif (sizeof($object_results) == 1) {
         $form_state['values']["object_id-$i"] = $object_results[0]->stock_id;
-      } 
+      }
 
       // check valid type selected
       if ($form_state['values']["type_id-$i"] == 0) {
         form_set_error('type_id', 'Please select a type of relationship.');
-      } else {
-    		$previous_db = tripal_db_set_active('chado');
-    		$tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM cvterm WHERE cvterm_id=%d",$form_state['values']["type_id-$i"]));
-    		tripal_db_set_active($previous_db);
-    	
-      	if ($tmp_obj->count != 1) {
+      }
+      else {
+        $previous_db = tripal_db_set_active('chado');
+        $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM {cvterm} WHERE cvterm_id=%d" , $form_state['values']["type_id-$i"]));
+        tripal_db_set_active($previous_db);
+
+        if ($tmp_obj->count != 1) {
           form_set_error("type_id-$i", 'The type you selected is not valid. Please choose another one.');
         }
       }
@@ -384,7 +404,7 @@ function tripal_feature_edit_ALL_relationships_form_validate($form, &$form_state
       // check either subject or object is the current stock
       if ( $subject_results[0]->nid != $form_state['values']['nid'] ) {
         if ( $object_results[0]->nid != $form_state['values']['nid'] ) {
-          form_set_error("subject_id-$i", 'Either Subject or Object must be the current stock ('.$form_state['values']['r_stock_uniquename'].').');
+          form_set_error("subject_id-$i", 'Either Subject or Object must be the current stock (' . $form_state['values']['r_stock_uniquename'] . ').');
         }
       }
 
@@ -406,25 +426,28 @@ function tripal_feature_edit_ALL_relationships_form_submit($form, &$form_state)
 
        //process stock textfields
        tripal_feature_update_relationship(
-				$form_state['values']["id-$i"], 
-				$form_state['values']["subject_id-$i"],
-				$form_state['values']["type_id-$i"], 
-				$form_state['values']["object_id-$i"]
-			);
+        $form_state['values']["id-$i"],
+        $form_state['values']["subject_id-$i"],
+        $form_state['values']["type_id-$i"],
+        $form_state['values']["object_id-$i"]
+      );
      }
      drupal_set_message("Updated all Relationships");
-     drupal_goto('node/'.$form_state['values']['nid']);
+     drupal_goto('node/' . $form_state['values']['nid']);
 
-  } elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
+  }
+  elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
 
      $i = $matches[1];
      tripal_feature_delete_relationship($form_state['values']["id-$i"]);
      drupal_set_message("Deleted Relationship");
 
-  } elseif ($form_state['clicked_button']['#value'] == t('Back to Stock') ) {
-    drupal_goto('node/'.$form_state['values']['nid']);
-  } else {
-    drupal_set_message("Unrecognized Button Pressed",'error');
+  }
+  elseif ($form_state['clicked_button']['#value'] == t('Back to Stock') ) {
+    drupal_goto('node/' . $form_state['values']['nid']);
+  }
+  else {
+    drupal_set_message("Unrecognized Button Pressed", 'error');
   }
 
 }
@@ -434,13 +457,13 @@ function tripal_feature_edit_ALL_relationships_form_submit($form, &$form_state)
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_update_relationship ($stock_relationship_id, $subject_id, $cvterm_id, $object_id) {
+function tripal_feature_update_relationship($stock_relationship_id, $subject_id, $cvterm_id, $object_id) {
 
   $previous_db = db_set_active('chado');
   db_query(
-    "UPDATE stock_relationship SET subject_id=%d, type_id=%d, object_id=%d WHERE stock_relationship_id=%d",
+    "UPDATE {stock_relationship} SET subject_id=%d, type_id=%d, object_id=%d WHERE stock_relationship_id=%d",
     $subject_id,
-    $cvterm_id, 
+    $cvterm_id,
     $object_id,
     $stock_relationship_id
   );
@@ -453,11 +476,11 @@ function tripal_feature_update_relationship ($stock_relationship_id, $subject_id
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_delete_relationship ($stock_relationship_id) {
+function tripal_feature_delete_relationship($stock_relationship_id) {
 
   $previous_db = db_set_active('chado');
   db_query(
-    "DELETE FROM stock_relationship WHERE stock_relationship_id=%d",
+    "DELETE FROM {stock_relationship} WHERE stock_relationship_id=%d",
     $stock_relationship_id
   );
   db_set_active($previous_db);
@@ -469,23 +492,23 @@ function tripal_feature_delete_relationship ($stock_relationship_id) {
  *
  * @ingroup tripal_feature
  */
-function theme_tripal_feature_edit_ALL_relationships_form ($form) {
+function theme_tripal_feature_edit_ALL_relationships_form($form) {
   $output = '';
-  
+
   $output .= '<br><fieldset>';
   $output .= '<legend>Edit Already Existing Relationships<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Each relationship for this stock is listed below, one per line. The textboxes indicating '
-  	    .'the subject and object of the relationship can contain the uniquename, name, database '
-	    .'reference or synonym of a stock of the same organism.</p>';
+        .'the subject and object of the relationship can contain the uniquename, name, database '
+      .'reference or synonym of a stock of the same organism.</p>';
   $output .= '<table>';
   $output .= '<tr><th>#</th><th>Subject</th><th>Type</th><th>Object</th><th></th></tr>';
 
-  for ($i=1; $i<=$form['num_relationships']['#value']; $i++) {
-    $output .= '<tr><td>'.drupal_render($form["num-$i"]).'</td>'.
-      	      '<td>'.drupal_render($form["subject_id-$i"]).'</td>'.
-	            '<td>'.drupal_render($form["type_id-$i"]).'</td>'.
-     	         '<td>'.drupal_render($form["object_id-$i"]).'</td>'.
-	            '<td>'.drupal_render($form["submit-$i"]).'</td></tr>';
+  for ($i=1; $i <= $form['num_relationships']['#value']; $i++) {
+    $output .= '<tr><td>' . drupal_render($form["num-$i"]) . '</td>' .
+              '<td>' . drupal_render($form["subject_id-$i"]) . '</td>' .
+              '<td>' . drupal_render($form["type_id-$i"]) . '</td>' .
+                '<td>' . drupal_render($form["object_id-$i"]) . '</td>' .
+              '<td>' . drupal_render($form["submit-$i"]) . '</td></tr>';
   }
 
   $output .= '</table><br>';
@@ -508,19 +531,20 @@ function tripal_feature_list_relationships_for_node($feature_name, $subject_rela
 
     if (!empty($subject_relationships) ) {
       foreach ($subject_relationships as $s) {
-        $output .= '<tr><td>'.$s->subject_name.'</td><td>'.$s->relationship_type.'</td><td>'.$feature_name.'</td></tr>';
+        $output .= '<tr><td>' . $s->subject_name . '</td><td>' . $s->relationship_type . '</td><td>' . $feature_name . '</td></tr>';
       }
     }
 
     if (!empty($object_relationships) ) {
       foreach ($object_relationships as $o) {
-        $output .= '<tr><td>'.$feature_name.'</td><td>'.$o->relationship_type.'</td><td>'.$o->object_name.'</td></tr>';
+        $output .= '<tr><td>' . $feature_name . '</td><td>' . $o->relationship_type . '</td><td>' . $o->object_name . '</td></tr>';
       } // end of foreach property
     }
 
     $output .= '</table>';
-  } else {
-    $output = 'No Relationships For the Current Feature'; 
+  }
+  else {
+    $output = 'No Relationships For the Current Feature';
   }
 
   return $output;

+ 38 - 25
tripal_feature/tripal_feature-secondary_tables.inc

@@ -1,5 +1,8 @@
 <?php
-// $Id$
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
  *
@@ -14,9 +17,9 @@ function tripal_feature_implement_back_to_feature_button($form_state, $nid) {
     '#value' => $nid
   );
 
-  $form["submit-back"] = array( 
+  $form["submit-back"] = array(
     '#type' => 'submit',
-    '#value' => t('Back to Stock') 
+    '#value' => t('Back to Stock')
   );
 
   return $form;
@@ -28,7 +31,7 @@ function tripal_feature_implement_back_to_feature_button($form_state, $nid) {
  * @ingroup tripal_feature
  */
 function tripal_feature_implement_back_to_feature_button_submit($form, $form_state) {
-  drupal_goto('node/'.$form_state['values']['nid']);
+  drupal_goto('node/' . $form_state['values']['nid']);
 }
 
 /**
@@ -38,24 +41,28 @@ function tripal_feature_implement_back_to_feature_button_submit($form, $form_sta
  */
 function tripal_feature_implement_add_chado_properties_progress($current) {
 
-    $value = '<div class="form_progress"><div class="form_progress-text">'; 
+    $value = '<div class="form_progress"><div class="form_progress-text">';
 
-    if ($current == 'main') { $value .= '<span id="form-step-current">Create Basic Feature</span>'; } 
+    if ($current == 'main') {
+    $value .= '<span id="form-step-current">Create Basic Feature</span>'; }
     else { $value .= '<span id="form-step">Create Basic Stock</span>'; }
 
     $value .= '<span id="form-segway">  >>  </span>';
 
-    if ($current == 'properties') { $value .= '<span id="form-step-current">Add Synonyms & Properties</span>'; }
+    if ($current == 'properties') {
+    $value .= '<span id="form-step-current">Add Synonyms & Properties</span>'; }
     else { $value .= '<span id="form-step">Add Synonyms & Properties</span>'; }
 
-    $value .= '<span id="form-segway">  >>  </span>';                       
+    $value .= '<span id="form-segway">  >>  </span>';
 
-    if ($current == 'db_references') { $value .= '<span id="form-step-current">Add Database References</span>'; }
+    if ($current == 'db_references') {
+    $value .= '<span id="form-step-current">Add Database References</span>'; }
     else { $value .= '<span id="form-step">Add Database References</span>'; }
 
-    $value .= '<span id="form-segway">  >>  </span>';         
+    $value .= '<span id="form-segway">  >>  </span>';
 
-    if ($current == 'relationships') { $value .= '<span id="form-step-current">Add Relationships</span>'; }
+    if ($current == 'relationships') {
+    $value .= '<span id="form-step-current">Add Relationships</span>'; }
     else { $value .= '<span id="form-step">Add Relationships</span>'; }
 
     $value .= '</div></div>';
@@ -85,7 +92,8 @@ function tripal_feature_implement_add_chado_properties_navigate($form_state, $st
     'relationships' => 'node/%node/relationships'
   );
   $steps_value = array();
-  foreach ($steps as $k => $v) { $steps_value[] = $k.';'.$v; }
+  foreach ($steps as $k => $v) {
+  $steps_value[] = $k . ';' . $v; }
   $form['steps'] = array(
     '#type' => 'hidden',
     '#value' => implode('::', $steps_value)
@@ -114,7 +122,7 @@ function tripal_feature_implement_add_chado_properties_navigate($form_state, $st
   }
 
   if ($step != $form['last_step']['#value']) {
-    $form['submit-next'] = array( 
+    $form['submit-next'] = array(
       '#type' => 'submit',
       '#value' => t('Next Step')
     );
@@ -122,7 +130,7 @@ function tripal_feature_implement_add_chado_properties_navigate($form_state, $st
 
   if ($step == $form['last_step']['#value']) {
     $form['submit-finish'] = array(
-      '#type' => 'submit', 
+      '#type' => 'submit',
       '#value' => t('Finish')
     );
   }
@@ -137,7 +145,7 @@ function tripal_feature_implement_add_chado_properties_navigate($form_state, $st
  */
 function tripal_feature_implement_add_chado_properties_navigate_submit($form, $form_state) {
 
-  $raw_steps = preg_split('/::/', $form_state['values']['steps']); 
+  $raw_steps = preg_split('/::/', $form_state['values']['steps']);
 
   $steps = array();
   $current_index = 'EMPTY';
@@ -146,7 +154,7 @@ function tripal_feature_implement_add_chado_properties_navigate_submit($form, $f
   foreach ($raw_steps as $raw_step) {
     $step = preg_split('/;/', $raw_step);
     $steps[$i] = $step;
-    
+
     if ($step[0] == $form_state['values']['current_step']) {
       $current_index = $i;
     }
@@ -154,16 +162,19 @@ function tripal_feature_implement_add_chado_properties_navigate_submit($form, $f
     $i++;
   }
   $num_steps = $i;
-  
-  if (strcmp($current_index,'EMPTY') == 0) {
+
+  if (strcmp($current_index, 'EMPTY') == 0) {
     // No Matching Step
-    drupal_set_message('Could not determine next step -'.$form_state['values']['current_step'].', please contact the administrator', 'error');
-  } elseif ($current_index == 0) {
+    drupal_set_message(t('Could not determine next step - %currentstep, please contact the administrator', array('%currentstep' => $form_state['values']['current_step'])), 'error');
+  }
+  elseif ($current_index == 0) {
     $next_goto = $steps[$current_index+1][1];
-  } elseif ($current_index == ($num_steps-1)) {
+  }
+  elseif ($current_index == ($num_steps-1)) {
     $prev_goto = $steps[$current_index-1][1];
     $next_goto = 'node/%node';
-  } else {
+  }
+  else {
     $prev_goto = $steps[$current_index-1][1];
     $next_goto = $steps[$current_index+1][1];
   }
@@ -172,10 +183,12 @@ function tripal_feature_implement_add_chado_properties_navigate_submit($form, $f
     //replace %node
     $prev_goto = preg_replace('/%node/', $form_state['values']['nid'], $prev_goto);
     $_REQUEST['destination'] = $prev_goto;
-  } elseif ($form_state['clicked_button']['#value'] == t('Next Step') ) {
+  }
+  elseif ($form_state['clicked_button']['#value'] == t('Next Step') ) {
     $next_goto = preg_replace('/%node/', $form_state['values']['nid'], $next_goto);
     $_REQUEST['destination'] = $next_goto;
-  } elseif ($form_state['clicked_button']['#value'] == t('Finish') ) {
+  }
+  elseif ($form_state['clicked_button']['#value'] == t('Finish') ) {
     $next_goto = preg_replace('/%node/', $form_state['values']['nid'], $next_goto);
     $_REQUEST['destination'] = $next_goto;
   }
@@ -213,7 +226,7 @@ function tripal_feature_is_obsolete_form_submit($form, &$form_state) {
 
   $previous_db = db_set_active('chado');
   db_query(
-    "UPDATE stock SET is_obsolete='t' WHERE stock_id=%d",
+    "UPDATE {stock} SET is_obsolete='t' WHERE stock_id=%d",
     $form_state['values']['make_obsolete_stock_id']
   );
   db_set_active($previous_db);

+ 189 - 180
tripal_feature/tripal_feature.admin.inc

@@ -1,9 +1,14 @@
 <?php
 
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 /**
  * Purpose: Provide Guidance to new Tripal Admin
  *
- * @return 
+ * @return
  *   HTML Formatted text
  *
  * @ingroup tripal_feature
@@ -12,31 +17,31 @@ function tripal_feature_module_description_page() {
 
   $text .= '<h3>Tripal Feature Administrative Tools Quick Links:</h3>';
   $text .= "<ul>
-             <li><a href=\"".url("admin/tripal/tripal_feature/configuration") . "\">Feature Configuration</a></li>
-             <li><a href=\"".url("admin/tripal/tripal_feature/fasta_loader"). "\">Import a multi-FASTA file</a></li>
-             <li><a href=\"".url("admin/tripal/tripal_feature/gff3_load"). "\">Import a GFF3 file</a></li>
-             <li><a href=\"".url("admin/tripal/tripal_feature/sync") . "\">Sync Features</a></li>
-             <li><a href=\"".url("admin/tripal/tripal_feature/delete") . "\">Delete Features</a></li>
+             <li><a href=\"" . url("admin/tripal/tripal_feature/configuration") . "\">Feature Configuration</a></li>
+             <li><a href=\"" . url("admin/tripal/tripal_feature/fasta_loader") . "\">Import a multi-FASTA file</a></li>
+             <li><a href=\"" . url("admin/tripal/tripal_feature/gff3_load") . "\">Import a GFF3 file</a></li>
+             <li><a href=\"" . url("admin/tripal/tripal_feature/sync") . "\">Sync Features</a></li>
+             <li><a href=\"" . url("admin/tripal/tripal_feature/delete") . "\">Delete Features</a></li>
            </ul>";
-#             <li><a href=\"".url("admin/tripal/tripal_feature/aggregate"). "\">Feature Relationship Aggegators</a></li> 
+#             <li><a href=\"".url("admin/tripal/tripal_feature/aggregate"). "\">Feature Relationship Aggegators</a></li>
 
   $text .= '<h3>Module Description:</h3>';
   $text .= '<p>This module provides an interface for the Chado feature module which stores information
             related to genomic features.  This module provides support for bulk loading of data in
-            FASTA or GFF format, visualization of "feature" pages, editing and updating.  
+            FASTA or GFF format, visualization of "feature" pages, editing and updating.
             </p>';
 
   $text .= '<h3>Setup Instructions:</h3>';
   $text .= '<p>After installation of the feature module.  The following tasks should be performed
             <ol>
-              <li><p><b>Set Permissions</b>: The feature module supports the Drupal user permissions interface for 
-               controlling access to feature content and functions. These permissions include viewing, 
+              <li><p><b>Set Permissions</b>: The feature module supports the Drupal user permissions interface for
+               controlling access to feature content and functions. These permissions include viewing,
                creating, editing or administering of
-               feature content. The default is that only the original site administrator has these 
-               permissions.  You can <a href="'.url('admin/user/roles').'">add roles</a> for classifying users, 
-               <a href="'.url('admin/user/user').'">assign users to roles</a> and
-               <a href="'.url('admin/user/permissions').'">assign permissions</a> for the feature content to 
-               those roles.  For a simple setup, allow anonymous users access to view organism content and 
+               feature content. The default is that only the original site administrator has these
+               permissions.  You can <a href="' . url('admin/user/roles') . '">add roles</a> for classifying users,
+               <a href="' . url('admin/user/user') . '">assign users to roles</a> and
+               <a href="' . url('admin/user/permissions') . '">assign permissions</a> for the feature content to
+               those roles.  For a simple setup, allow anonymous users access to view organism content and
                allow the site administrator all other permissions.</p></li>
 
                <li><p><b>Themeing</b>:  Before content from Chado can be visualized the Tripal base theme must
@@ -46,8 +51,8 @@ function tripal_feature_module_description_page() {
 
                <li><p><b>Loading of Ontologies</b>:  If you
                used Tripal to create the Chado database, then you must load ontologies before proceeding.  Visit the
-               page to <a href="'.url('admin/tripal/tripal_cv/obo_loader').'">load ontologies</a> and load at 
-               least the following ontologies:  
+               page to <a href="' . url('admin/tripal/tripal_cv/obo_loader') . '">load ontologies</a> and load at
+               least the following ontologies:
                <ul>
                   <li>Chado Feature Properties</li>
                   <li>Relationship Ontology</li>
@@ -55,80 +60,80 @@ function tripal_feature_module_description_page() {
                   <li>Gene Ontology (if loading GO terms for features)</li>
                </ul></p></li>
 
-               <li><p><b>Create Organisms</b>:  Before adding feature data you must already have the 
-               organisms loaded in the database.  See the 
-               <a href="'.url('admin/tripal/tripal_organism').'">Tripal Organism Admin page</a> for 
+               <li><p><b>Create Organisms</b>:  Before adding feature data you must already have the
+               organisms loaded in the database.  See the
+               <a href="' . url('admin/tripal/tripal_organism') . '">Tripal Organism Admin page</a> for
                instructions for adding and Syncing organisms.</p></li>
 
                <li><p><b>Create Analysis</b>:  Tripal requires that feature data loaded using the Tripal loaders
                be associated with an analyis.  This provides a grouping for the feature data and can be used
                later to visualize data pipelines.  Before loading feature data through the FASTA or GFF loaders
-               you will need to <a href="'.url('node/add').'">create an analysis</a> for the data.</p></li>
+               you will need to <a href="' . url('node/add') . '">create an analysis</a> for the data.</p></li>
 
-               <li><p><b>Create Referring Database Entries</b>:  If you would like to associate your feature data with an 
-               external reference database, check to ensure that the <a href="'.url('admin/tripal/tripal_db/edit_db').'">
-               database record already exists</a>.  If not you should <a href="'.url('admin/tripal/tripal_db/add_db').'">add a new database record</a> before importing
+               <li><p><b>Create Referring Database Entries</b>:  If you would like to associate your feature data with an
+               external reference database, check to ensure that the <a href="' . url('admin/tripal/tripal_db/edit_db') . '">
+               database record already exists</a>.  If not you should <a href="' . url('admin/tripal/tripal_db/add_db') . '">add a new database record</a> before importing
                feature data.</p></li>
 
-               <li><p><b>Data Import</b>:  if you do not already have an existing Chado database with preloaded data 
+               <li><p><b>Data Import</b>:  if you do not already have an existing Chado database with preloaded data
                then you will want
-               to import data.  You can do so using the Chado perl scripts that come with the normal 
-               <a href="http://gmod.org/wiki/Chado">distribution of Chado</a> or you can use the <a href="'.url('admin/tripal/tripal_feature/fasta_loader').'">FASTA loader</a> and 
-               <a href="'.url('admin/tripal/tripal_feature/gff3_load').'">GFF loader</a> provided here.  If you
+               to import data.  You can do so using the Chado perl scripts that come with the normal
+               <a href="http://gmod.org/wiki/Chado">distribution of Chado</a> or you can use the <a href="' . url('admin/tripal/tripal_feature/fasta_loader') . '">FASTA loader</a> and
+               <a href="' . url('admin/tripal/tripal_feature/gff3_load') . '">GFF loader</a> provided here.  If you
                created the Chado database using Tripal then you\'ll most likely want to use the Tripal loaders.  If your data
-               is not condusive for loading with these loaders you may have to write your own loaders. 
+               is not condusive for loading with these loaders you may have to write your own loaders.
                </p></li>
 
                <li><p><b>Sync Features</b>:  After data is loaded you need to sync features.  This process is what
                creates the pages for viewing online.  Not all features need be synced.  For instance, if you
                have loaded whole genome sequence with fully defined gene models with several features to define
                a gene and its products (e.g. gene, mRNA, CDS, 5\'UTR, 3\'UTR, etc) you probably only want to create
-               pages for genes or genes and mRNA.  You probably do not want a page for a 5\'UTR.  
-               Using the <a href="'.url('admin/tripal/tripal_feature/configuration/sync').'">Feature Sync page</a> 
+               pages for genes or genes and mRNA.  You probably do not want a page for a 5\'UTR.
+               Using the <a href="' . url('admin/tripal/tripal_feature/configuration/sync') . '">Feature Sync page</a>
                you can sync (or create pages) for the desired feature types. </p></li>
 
-               <li><p><b>Set Feature URL</b>:  It is often convenient to have a simple URL for each feature page. 
+               <li><p><b>Set Feature URL</b>:  It is often convenient to have a simple URL for each feature page.
                For example, http://www.mygenomesite.org/[feature], where [feature] is a unique identifier for a feature page.
-               With this, people can easily include links to feature pages of interest. Use the 
-               <a href="'.url('admin/tripal/tripal_feature/configuration').'">Feature Configuration page</a> 
+               With this, people can easily include links to feature pages of interest. Use the
+               <a href="' . url('admin/tripal/tripal_feature/configuration') . '">Feature Configuration page</a>
                to specify whether to use the feature name, unique name or internal ID as the [feature] portion of the
                URL.  Select the one that will guarantee a unique identifier for feature pages.</p></li>
 
                <li><p><b>Indexing</b>:  Once all data has been loaded (including analysis data--e.g. blast, interpro, etc.)
-               you can index all feature pages for searching if you want to ues the Drupal default search mechanism. 
-               Use the <a href="'.url('admin/tripal/tripal_feature/configuration').'">Feature Configuration page</a> 
+               you can index all feature pages for searching if you want to ues the Drupal default search mechanism.
+               Use the <a href="' . url('admin/tripal/tripal_feature/configuration') . '">Feature Configuration page</a>
                to either Index (for the first time) or "Reindex" (after adding new data)
                the feature pages for searching.  Once the site is 100% indexed the pages will be searchable using Drupal\'s
-               full text searching.  You can find the percent indexed for the entire site by visiting the 
-               <a href="'.url('admin/settings/search').'">Search settings page</a>. Indexing
+               full text searching.  You can find the percent indexed for the entire site by visiting the
+               <a href="' . url('admin/settings/search') . '">Search settings page</a>. Indexing
                can take quite a while if you have a lot of data</p></li>
 
-               <li><p><b>Set Taxonomy</b>:  Drupal provides a mechanism for categorizing content to allow 
-               for advanced searching.  Drupal calls this "Taxonomy", but is essentially categorizing the pages.  
-               You can categorize feature pages by their type (e.g. gene, mRNA, contig, EST, etc.) and by the 
-               organism to which they belong.  This allows for filtering of search results by organism and feature type. 
-               Use the <a href="'.url('admin/tripal/tripal_feature/configuration').'">Feature Configuration page</a> to
+               <li><p><b>Set Taxonomy</b>:  Drupal provides a mechanism for categorizing content to allow
+               for advanced searching.  Drupal calls this "Taxonomy", but is essentially categorizing the pages.
+               You can categorize feature pages by their type (e.g. gene, mRNA, contig, EST, etc.) and by the
+               organism to which they belong.  This allows for filtering of search results by organism and feature type.
+               Use the <a href="' . url('admin/tripal/tripal_feature/configuration') . '">Feature Configuration page</a> to
                set the Taxonomy.</p></li>
             </ol>
             </p>';
-  
-  
+
+
   $text .= '<h3>Features of this Module:</h3>';
-  $text .= '<p>Aside from data loading and feature page setup (as described in the Setup section above), 
+  $text .= '<p>Aside from data loading and feature page setup (as described in the Setup section above),
             The Tripal feature module also provides the following functionality
             <ul>
-              <li><p><b>Feature Browser:</b>  The feature browser is a tabular list of features with links to their 
-               feature pages which appears on the organism 
+              <li><p><b>Feature Browser:</b>  The feature browser is a tabular list of features with links to their
+               feature pages which appears on the organism
                page.  It was created to provide a mechanism to allow site visitors to quickly
                accesss feature pages when they do not know what to search for.  For sites with large numbers of features, this
-               method for finding a specific pages is inadequate, but may still be included to aid new site 
-               visitors.    This browser can be toggled on or off using the 
-               <a href="'.url('admin/tripal/tripal_feature/configuration').'">Feature Configuration page</a></p></li>
- 
+               method for finding a specific pages is inadequate, but may still be included to aid new site
+               visitors.    This browser can be toggled on or off using the
+               <a href="' . url('admin/tripal/tripal_feature/configuration') . '">Feature Configuration page</a></p></li>
+
               <li><p><b>Feature Summary Report:</b>  The feature summary report is a pie chart that indicates the types and quantities
-              of feature types (Sequence Ontology terms) that are loaded in the database. It appears on the organism 
-              page.  The summary can be toggled on or off using the 
-              <a href="'.url('admin/tripal/tripal_feature/configuration').'">Feature Configuration page</a></p></li>             
+              of feature types (Sequence Ontology terms) that are loaded in the database. It appears on the organism
+              page.  The summary can be toggled on or off using the
+              <a href="' . url('admin/tripal/tripal_feature/configuration') . '">Feature Configuration page</a></p></li>
 
               <li><p><b>Integration with Drupal Views</b>: <a href="http://drupal.org/project/views">Drupal Views</a> is
               a powerful tool that allows the site administrator to create lists or basic searching forms of Chado content.
@@ -136,56 +141,56 @@ function tripal_feature_module_description_page() {
               and create custom lists without PHP programming or customization of Tripal source code.  Views can also
               be created to filter content that has not yet been synced with Druapl in order to protect access to non
               published data (only works if Chado was installed using Tripal).  You can see a list of available pre-existing
-              Views <a href="'.url('admin/build/views/').'">here</a>, as well as create your own. </p></li>
+              Views <a href="' . url('admin/build/views/') . '">here</a>, as well as create your own. </p></li>
 
-              <li><p><b>Basic Feature Lookup View</b>: This module provides a basic <a href="'.url('features').'">feature search 
+              <li><p><b>Basic Feature Lookup View</b>: This module provides a basic <a href="' . url('features') . '">feature search
               tool</a> for finding or listing features in Chado. It does not require indexing for Drupal searching but relies
-              on Drupal Views.  <a href="http://drupal.org/project/views">Drupal Views</a> must be installed. </p></li>              
+              on Drupal Views.  <a href="http://drupal.org/project/views">Drupal Views</a> must be installed. </p></li>
 
-              <li><p><b>Delete Features</b>: This module provides a <a href="'.url('admin/tripal/tripal_feature/delete').'">Delete Feature page</a>
+              <li><p><b>Delete Features</b>: This module provides a <a href="' . url('admin/tripal/tripal_feature/delete') . '">Delete Feature page</a>
               for bulk deltions of features. You may delete features using a list of feature names, or for a specific organism
-              or for a specific feature type.</p></li>              
+              or for a specific feature type.</p></li>
 
             </ul>
             </p>';
 
    $text .= '<h3>Page Customizations</h3>';
-   $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal. 
+   $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal.
              Below is a description of several methods.  These methods may be used in conjunction with one another to
-             provide fine-grained control. 
+             provide fine-grained control.
              <ul>
 
-             <li><p><b>Integration with Drupal Panels</b>:  <a href="http://drupal.org/project/views">Drupal Panels</a> 
-              allows for customization of a page layout if you don\'t want to do PHP/Javascript/CSS programming.  Tripal comes with pre-set layouts for feature pages.  However, 
+             <li><p><b>Integration with Drupal Panels</b>:  <a href="http://drupal.org/project/views">Drupal Panels</a>
+              allows for customization of a page layout if you don\'t want to do PHP/Javascript/CSS programming.  Tripal comes with pre-set layouts for feature pages.  However,
               Panels become useful if you prefer a layout that is different from the pre-set layouts.  Chado content
-              is provided to Panels in the form of Drupal "blocks" which you can then place anywhere on a page using the 
+              is provided to Panels in the form of Drupal "blocks" which you can then place anywhere on a page using the
               Panel\'s GUI.</p></li>
 
-             <li><p><b>Drupal\'s Content Construction Kit (CCK)</b>: the 
+             <li><p><b>Drupal\'s Content Construction Kit (CCK)</b>: the
              <a href="http://drupal.org/project/cck">Content Construction Kit (CCK) </a> is a powerful way to add non-Chado content
              to any page without need to edit template files or knowing PHP.  You must first download and install CCK.
              With CCK, the site administartor can create a new field to appear on the page.  For example, currently,
-             the Chado publication module is not yet supported by Tripal.  Therefore, the site administrator can add a text 
+             the Chado publication module is not yet supported by Tripal.  Therefore, the site administrator can add a text
              field to the feature pages.  This content is not stored in Chado, but will appear on the feature page.  A field
              added by CCK will also appear in the form when editing a feature to allow users to manually enter the appropriate
              text.  If the default pre-set layout and themeing for Tripal is used, it is better to create the CCK element,
-             indicate that it is not to be shown (using the CCK interface), then manually add the new content type 
+             indicate that it is not to be shown (using the CCK interface), then manually add the new content type
              where desired by editing the templates (as described below).  If using Panels, the CCK field can be added to the
              location desired using the Panels interface.</p></li>
 
              <li><p><b>Drupal Node Templates</b>:  The Tripal packages comes with a "theme_tripal" directory that contains the
              themeing for Chado content.    The feature module has a template file for feature "nodes" (Tripal feature pages).  This file
              is named "node-chado_feature.tpl.php", and provides javascript, HTML and PHP code for display of the feature
-             pages.  You can edit this file to control which types of information (or which feature "blocks") are displayed for features. Be sure to 
+             pages.  You can edit this file to control which types of information (or which feature "blocks") are displayed for features. Be sure to
              copy these template to your primary theme directory for editing. Do not edit them in the "theme_tripal" directory as
              future Tripal updates may overwrite your customizations. See the <a href="http://tripal.sourceforge.net/">Tripal website </a>
              for instructions on how to access variables and other Chado content within the template file.</p></li>
 
              <li><p><b>Feature "Block" Templates</b>:  In the "theme_tripal" directory is a subdirectory named "tripal_feature".
              Inside this directory is a set of templates that control distinct types of information for features.  For example,
-             there is a "base" template for displaying of data directly from the Chado feature table, and a "references" 
+             there is a "base" template for displaying of data directly from the Chado feature table, and a "references"
              template for showing external site references for a feature (data from the feature_dbxref table).  These templates are used both by Drupal blocks
-             for use in Drupal Panels (as described above) or for use in the default pre-set layout that the node template 
+             for use in Drupal Panels (as described above) or for use in the default pre-set layout that the node template
              provides (also desribed above).  You can customize this template as you desire.  Be sure to copy the
              template to your primary theme directory for editing. Do not edit them in the "theme_tripal" directory as
              future Tripal updates may overwrite your customizations.  See the <a href="http://tripal.sourceforge.net/">Tripal website </a>
@@ -194,9 +199,9 @@ function tripal_feature_module_description_page() {
 
              <li><p><b>Adding Links to the "Resources" Sidebar</b>: If you use the pre-set default Tripal layout for theming, you
              will see a "Resources" sidebar on each page.  The links that appear on the sidebar are automatically generated
-             using Javascript for all of the feature "Blocks" that appear on the page. If you want to add additional links 
-             (e.g. a dynamic link to GBrowse for the feature) and you want that link to appear in the 
-             "Resources" sidebar, simply edit the Drupal Node Template (as described above) and add the link to the 
+             using Javascript for all of the feature "Blocks" that appear on the page. If you want to add additional links
+             (e.g. a dynamic link to GBrowse for the feature) and you want that link to appear in the
+             "Resources" sidebar, simply edit the Drupal Node Template (as described above) and add the link to the
              section at the bottom of the template file where the resources section is found.</p></li>
 
              </ul>
@@ -210,16 +215,16 @@ function tripal_feature_module_description_page() {
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_admin () {
+function tripal_feature_admin() {
 
    // 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_feature')){
+   if (tripal_get_module_active_jobs('tripal_feature')) {
       $active_jobs = TRUE;
    }
-   if(!$active_jobs){
+   if (!$active_jobs) {
 
       get_tripal_feature_admin_form_url_set($form);
 
@@ -229,7 +234,7 @@ function tripal_feature_admin () {
          '#collapsible' => 1,
          '#collapsed' => 1 ,
       );
-      $allowedoptions1  = array (
+      $allowedoptions1  = array(
         'show_feature_browser' => "Show the feature browser on the organism page. The browser loads when page loads. This may be slow for large sites.",
         'hide_feature_browser' => "Hide the feature browser on the organism page. Disables the feature browser completely.",
       );
@@ -237,7 +242,7 @@ function tripal_feature_admin () {
 
       $form['browser']['browser_desc'] = array(
          '#type'        => 'markup',
-         '#value' => 'A feature browser can be added to an organism page to allow users to quickly '. 
+         '#value' => 'A feature browser can be added to an organism page to allow users to quickly '.
             'access a feature.  This will most likely not be the ideal mechanism for accessing feature '.
             'information, especially for large sites, but it will alow users exploring the site (such '.
             'as students) to better understand the data types available on the site.',
@@ -246,9 +251,9 @@ function tripal_feature_admin () {
       $form['browser']['feature_types'] = array(
          '#title'       => t('Feature Types'),
          '#type'        => 'textarea',
-         '#description' => t("Enter the Sequence Ontology (SO) terms for the feature types that ".
+         '#description' => t("Enter the Sequence Ontology (SO) terms for the feature types that " .
                              "will be shown in the feature browser."),
-         '#default_value' => variable_get('chado_browser_feature_types','gene contig'),
+         '#default_value' => variable_get('chado_browser_feature_types', 'gene contig'),
       );
 
 
@@ -256,9 +261,9 @@ function tripal_feature_admin () {
          '#title' => 'Feature Browser on Organism Page',
          '#type' => 'radios',
          '#options' => $allowedoptions1,
-         '#default_value'=>variable_get('tripal_feature_browse_setting', 'show_feature_browser'),
+         '#default_value' => variable_get('tripal_feature_browse_setting', 'show_feature_browser'),
       );
-      
+
       $form['browser']['browse_features_library'] = array(
          '#title' => 'Feature Browser on Library Page',
          '#type' => 'radios',
@@ -266,7 +271,7 @@ function tripal_feature_admin () {
           'show_feature_browser' => "Show the feature browse on the library page. The browser loads when page loads. This may be slow for large sites.",
           'hide_feature_browser' => "Hide the feature browser on the library page. Disables the feature browser completely.",
          ),
-         '#default_value'=>variable_get('tripal_library_feature_browse_setting', 'show_feature_browser'),
+         '#default_value' => variable_get('tripal_library_feature_browse_setting', 'show_feature_browser'),
       );
 
       $form['browser']['browse_features_analysis'] = array(
@@ -276,9 +281,9 @@ function tripal_feature_admin () {
           'show_feature_browser' => "Show the feature browse on the analysis page. The browser loads when page loads. This may be slow for large sites.",
           'hide_feature_browser' => "Hide the feature browser on the analysis page. Disables the feature browser completely.",
          ),
-         '#default_value'=>variable_get('tripal_analysis_feature_browse_setting', 'show_feature_browser'),
+         '#default_value' => variable_get('tripal_analysis_feature_browse_setting', 'show_feature_browser'),
       );
-      
+
       $form['browser']['set_browse_button'] = array(
          '#type' => 'submit',
          '#value' => t('Set Browser'),
@@ -305,7 +310,7 @@ function tripal_feature_admin () {
          '#title'       => t('Feature Types'),
          '#type'        => 'textarea',
          '#description' => t("Enter the Sequence Ontology (SO) terms for the allowed feature types when creating or editing features."),
-         '#default_value' => variable_get('chado_edit_feature_types','gene contig EST mRNA'),
+         '#default_value' => variable_get('chado_edit_feature_types', 'gene contig EST mRNA'),
       );
 
       $form['feature_edit']['set_feature_types'] = array(
@@ -328,7 +333,7 @@ function tripal_feature_admin () {
             'type and quantity of features available for the organism.',
          '#type' => 'radios',
          '#options' => $allowedoptions2,
-         '#default_value'=>variable_get('tripal_feature_summary_setting', 'show_feature_summary'),
+         '#default_value' => variable_get('tripal_feature_summary_setting', 'show_feature_summary'),
       );
       $form['summary']['feature_mapping'] = array(
          '#title' => 'Map feature types',
@@ -339,7 +344,7 @@ function tripal_feature_admin () {
             'SO term to be more human readable form, use an \'=\' sign after the SO term (e.g. \'polypeptide = Protein\')'),
          '#type' => 'textarea',
          '#rows' => 15,
-         '#default_value'=>variable_get('tripal_feature_summary_report_mapping', ''),
+         '#default_value' => variable_get('tripal_feature_summary_report_mapping', ''),
       );
       $form['summary']['set_summary_button'] = array(
          '#type' => 'submit',
@@ -350,7 +355,8 @@ function tripal_feature_admin () {
       get_tripal_feature_admin_form_taxonomy_set($form);
       get_tripal_feature_admin_form_reindex_set($form);
       get_tripal_feature_admin_form_cleanup_set($form);
-   } else {
+   }
+   else {
       $form['notice'] = array(
          '#type' => 'fieldset',
          '#title' => t('Feature Management Temporarily Unavailable')
@@ -375,51 +381,51 @@ function tripal_feature_admin_validate($form, &$form_state) {
    global $user;  // we need access to the user info
    $job_args = array();
 
-   variable_set('chado_browser_feature_types',$form_state['values']['feature_types']);
+   variable_set('chado_browser_feature_types', $form_state['values']['feature_types']);
 
    // if the user wants to sync up the chado features then
    // add the job to the management queue
-   switch ($form_state['values']['op']){
+   switch ($form_state['values']['op']) {
 
       case  t('Sync all Features') :
-         tripal_add_job('Sync all features','tripal_feature',
-            'tripal_feature_sync_features',$job_args,$user->uid);
+         tripal_add_job('Sync all features', 'tripal_feature',
+            'tripal_feature_sync_features', $job_args, $user->uid);
          break;
 
       case t('Set/Reset Taxonomy for all feature nodes') :
-         tripal_add_job('Set all feature taxonomy','tripal_feature',
-            'tripal_features_set_taxonomy',$job_args,$user->uid);
+         tripal_add_job('Set all feature taxonomy', 'tripal_feature',
+            'tripal_features_set_taxonomy', $job_args, $user->uid);
          break;
 
       case t('Reindex all feature nodes') :
-         tripal_add_job('Reindex all features','tripal_feature',
-            'tripal_features_reindex',$job_args,$user->uid);
+         tripal_add_job('Reindex all features', 'tripal_feature',
+            'tripal_features_reindex', $job_args, $user->uid);
          break;
 
       case t('Clean up orphaned features') :
-         tripal_add_job('Cleanup orphaned features','tripal_feature',
-            'tripal_features_cleanup',$job_args,$user->uid);
+         tripal_add_job('Cleanup orphaned features', 'tripal_feature',
+            'tripal_features_cleanup', $job_args, $user->uid);
          break;
 
       case t('Set Browser') :
-         variable_set('tripal_feature_browse_setting',$form_state['values']['browse_features']);
+         variable_set('tripal_feature_browse_setting', $form_state['values']['browse_features']);
          variable_set('tripal_library_feature_browse_setting', $form_state['values']['browse_features_library']);
          variable_set('tripal_analysis_feature_browse_setting', $form_state['values']['browse_features_analysis']);
          break;
 
       case t('Set Feature Types') :
-         variable_set('tripal_feature_type_setting',$form_state['values']['feature_edit_types']);
+         variable_set('tripal_feature_type_setting', $form_state['values']['feature_edit_types']);
          break;
 
       case t('Set Summary') :
-         variable_set('tripal_feature_summary_setting',$form_state['values']['feature_summary']);
-         variable_set('tripal_feature_summary_report_mapping',$form_state['values']['feature_mapping']);
+         variable_set('tripal_feature_summary_setting', $form_state['values']['feature_summary']);
+         variable_set('tripal_feature_summary_report_mapping', $form_state['values']['feature_mapping']);
          break;
 
       case t('Set Feature URLs') :
-         variable_set('chado_feature_url',$form_state['values']['feature_url']);
-         tripal_add_job('Set Feature URLs','tripal_feature',
-            'tripal_feature_set_urls',$job_args,$user->uid);
+         variable_set('chado_feature_url', $form_state['values']['feature_url']);
+         tripal_add_job('Set Feature URLs', 'tripal_feature',
+            'tripal_feature_set_urls', $job_args, $user->uid);
          break;
    }
 }
@@ -488,7 +494,7 @@ function get_tripal_feature_admin_form_reindex_set(&$form) {
  *
  * @ingroup tripal_feature
  */
-function get_tripal_feature_admin_form_taxonomy_set (&$form) {
+function get_tripal_feature_admin_form_taxonomy_set(&$form) {
 
 
    $form['taxonomy'] = array(
@@ -505,13 +511,13 @@ function get_tripal_feature_admin_form_taxonomy_set (&$form) {
           "filtering during searching."),
        '#weight' => 1,
    );
-   $tax_options = array (
+   $tax_options = array(
       'organism' => t('Organism name'),
       'feature_type'  => t('Feature Type (e.g. EST, mRNA, etc.)'),
       'analysis' => t('Analysis Name'),
       'library'  => t('Library Name'),
    );
-   $form['taxonomy']['tax_classes'] = array (
+   $form['taxonomy']['tax_classes'] = array(
      '#title'       => t('Available Taxonomic Classes'),
      '#type'        => t('checkboxes'),
      '#description' => t("Please select the class of terms to assign to ".
@@ -521,7 +527,7 @@ function get_tripal_feature_admin_form_taxonomy_set (&$form) {
      '#suffix'      => '</div>',
      '#options'     => $tax_options,
      '#weight'      => 2,
-     '#default_value' => variable_get('tax_classes',''),
+     '#default_value' => variable_get('tax_classes', ''),
    );
    $form['taxonomy']['button'] = array(
       '#type' => 'submit',
@@ -531,13 +537,13 @@ function get_tripal_feature_admin_form_taxonomy_set (&$form) {
 
 }
 
-function get_tripal_feature_admin_form_url_set (&$form) {
+function get_tripal_feature_admin_form_url_set(&$form) {
 
    $form['url'] = array(
       '#type' => 'fieldset',
       '#title' => t('Feature URL Path')
    );
-   $form['url']['desc'] = array (
+   $form['url']['desc'] = array(
       '#type'        => 'markup',
       '#value' => t('Each synced feature will have a unique URL which consists of '.
                           'the site domain followed by a unique identifer: for '.
@@ -557,19 +563,19 @@ function get_tripal_feature_admin_form_url_set (&$form) {
                           'It only need be unique among the synced dataset.'),
       '#required'    => FALSE,
       '#options'     => array('internal ID' => 'internal ID (Chado feature_id)',
-                              'feature unique name' => 'feature unique name', 
+                              'feature unique name' => 'feature unique name',
                               'feature name' => 'feature name'),
-      '#default_value' => variable_get('chado_feature_url','internal ID'),
+      '#default_value' => variable_get('chado_feature_url', 'internal ID'),
    );
 
-   $form['url']['chado_feature_accession_prefix'] = array (
+   $form['url']['chado_feature_accession_prefix'] = array(
       '#title'       => t('ID Prefix'),
       '#type'        => t('textfield'),
       '#description' => t("If you choose an Internal ID above you must also enter an ID prefix.".
                           "this prefix will be prepended to the internal ID number (e.g. ID38294). ".
                           "if you chose to use the feature name or unique name then this prfix is not used"),
       '#required'    => TRUE,
-      '#default_value' => variable_get('chado_feature_accession_prefix','ID'),
+      '#default_value' => variable_get('chado_feature_accession_prefix', 'ID'),
    );
 
    $form['url']['button'] = array(
@@ -583,9 +589,9 @@ function get_tripal_feature_admin_form_url_set (&$form) {
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_aggregator_page(){
+function tripal_feature_aggregator_page() {
    $add_url = url("admin/tripal/tripal_feature/aggregate/new");
-   $output = "<a href=\"$add_url\">Add a new aggregator</a>"; 
+   $output = "<a href=\"$add_url\">Add a new aggregator</a>";
    $output .= drupal_get_form('tripal_feature_aggregator_select_form');
    $output .= '<div id="db-edit-div">Please select an aggregator base type to view or edit</div>';
    return $output;
@@ -596,23 +602,23 @@ function tripal_feature_aggregator_page(){
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_aggregator_select_form(){
+function tripal_feature_aggregator_select_form() {
+
+  // get a list of base terms from chado for user to choose
+  $sql = "SELECT DISTINCT type_id FROM {tripal_feature_relagg} ORDER BY type_id ";
+  $results = db_query($sql);
 
-	// get a list of base terms from chado for user to choose
-	$sql = "SELECT DISTINCT type_id FROM {tripal_feature_relagg} ORDER BY type_id ";
-	$results = db_query ($sql);
-   
    $sql = "SELECT * FROM {cvterm} WHERE cvterm_id = %d";
    $previous_db = tripal_db_set_active('chado');
-	$types = array();
+  $types = array();
    $types[] = '';
-   while($base = db_fetch_object($results)){
-      $term = db_fetch_object(db_query($sql,$base->type_id));
-		$types[$base->type_id] = $term->name;
+   while ($base = db_fetch_object($results)) {
+      $term = db_fetch_object(db_query($sql, $base->type_id));
+    $types[$base->type_id] = $term->name;
    }
    tripal_db_set_active($previous_db);
 
-	$form['type_id'] = array(
+  $form['type_id'] = array(
       '#title' => t('Aggregator Base Type'),
       '#type' => 'select',
       '#options' => $types,
@@ -623,7 +629,7 @@ function tripal_feature_aggregator_select_form(){
          'event' => 'change',
          'method' => 'replace',
       ),
-	);
+  );
 
    return $form;
 }
@@ -633,28 +639,29 @@ function tripal_feature_aggregator_select_form(){
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_aggregator_form(&$form_state = NULL,$type_id = NULL){
+function tripal_feature_aggregator_form(&$form_state = NULL, $type_id = NULL) {
 
    // get this requested database
-   if($type_id){
+   if ($type_id) {
       $sql = "SELECT * FROM {tripal_feature_relagg} WHERE type_id = %d ";
       $tsql = "SELECT * FROM {cvterm} WHERE cvterm_id = %d ";
 
       // get the default list of terms
-      $results = db_query($sql,$type_id);
-      while($type = db_fetch_object($results)){
+      $results = db_query($sql, $type_id);
+      while ($type = db_fetch_object($results)) {
          $previous_db = tripal_db_set_active('chado');
-         $term = db_fetch_object(db_query($tsql,$type->rel_type_id));
+         $term = db_fetch_object(db_query($tsql, $type->rel_type_id));
          tripal_db_set_active($previous_db);
          $default_others .= $term->name . " ";
       }
-      $default_base = $base->name;     
+      $default_base = $base->name;
       $action = 'Update';
       $form['type_id'] = array(
          '#type' => 'hidden',
          '#value' => $type_id
       );
-   } else {
+   }
+   else {
       $action = 'Add';
       $form['base']= array(
          '#type'          => 'textfield',
@@ -674,22 +681,23 @@ function tripal_feature_aggregator_form(&$form_state = NULL,$type_id = NULL){
       '#required'      => TRUE,
       '#weight'        => 2
    );
- 
-   if(strcmp($action,'Update')==0){
-      $form['update'] = array (
+
+   if (strcmp($action, 'Update')==0) {
+      $form['update'] = array(
         '#type'         => 'submit',
         '#value'        => t('Update'),
         '#weight'       => 5,
         '#executes_submit_callback' => TRUE,
       );
-      $form['delete'] = array (
+      $form['delete'] = array(
         '#type'         => 'submit',
         '#value'        => t('Delete'),
         '#weight'       => 6,
         '#executes_submit_callback' => TRUE,
       );
-   } else {
-      $form['add'] = array (
+   }
+   else {
+      $form['add'] = array(
         '#type'         => 'submit',
         '#value'        => t('Add'),
         '#weight'       => 5,
@@ -707,49 +715,49 @@ function tripal_feature_aggregator_form(&$form_state = NULL,$type_id = NULL){
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_aggregator_form_validate($form, &$form_state){
+function tripal_feature_aggregator_form_validate($form, &$form_state) {
    $type_id  = $form_state['values']['type_id'];
    $base     = $form_state['values']['base'];
    $others   = $form_state['values']['others'];
    $op      =  $form_state['values']['op'];
 
    // split apart the feature types to be aggregated
-   $types = preg_split('/\s+/',$others);
+   $types = preg_split('/\s+/', $others);
 
    // the SQL for finding the term
    $tsql = "
-      SELECT * 
-      FROM {cvterm} CVT 
-         INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id 
+      SELECT *
+      FROM {cvterm} CVT
+         INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
       WHERE CVT.name = '%s' and CV.name = 'sequence'";
 
 
    // make sure the base type exists
-   if($base){
+   if ($base) {
       $previous_db = tripal_db_set_active('chado');
-      $term = db_fetch_object(db_query($tsql,$base));
+      $term = db_fetch_object(db_query($tsql, $base));
       tripal_db_set_active($previous_db);
-      if(!$term){
-         form_set_error('base',t('The specified base type is not a valid SO term'));
+      if (!$term) {
+         form_set_error('base', t('The specified base type is not a valid SO term'));
       }
 
       // make sure this type doesn't already in the table
       $sql = "SELECT * FROM {tripal_feature_relagg} WHERE type_id = %d ";
-      $agg = db_fetch_object(db_query($sql,$term->cvterm_id));
-      if($agg){
-         form_set_error('base',t('The specified base type is already used as a base type for another aggregator and cannot be readded.'));
-      }      
+      $agg = db_fetch_object(db_query($sql, $term->cvterm_id));
+      if ($agg) {
+         form_set_error('base', t('The specified base type is already used as a base type for another aggregator and cannot be readded.'));
+      }
    }
 
    // iterate through each type to be aggregated and make sure they are valid
-   foreach($types as $type){
+   foreach ($types as $type) {
       $previous_db = tripal_db_set_active('chado');
-      $term = db_fetch_object(db_query($tsql,$type));
+      $term = db_fetch_object(db_query($tsql, $type));
       tripal_db_set_active($previous_db);
-      if(!$term){
-         form_set_error('others',t('The specified type ') . $type . t(' is not a valid SO term'));
+      if (!$term) {
+         form_set_error('others', t('The specified type ') . $type . t(' is not a valid SO term'));
       }
-   }   
+   }
 }
 
 /**
@@ -757,7 +765,7 @@ function tripal_feature_aggregator_form_validate($form, &$form_state){
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_aggregator_form_submit($form, &$form_state){
+function tripal_feature_aggregator_form_submit($form, &$form_state) {
 
    $type_id  = $form_state['values']['type_id'];
    $base     = $form_state['values']['base'];
@@ -765,13 +773,13 @@ function tripal_feature_aggregator_form_submit($form, &$form_state){
    $op      =  $form_state['values']['op'];
 
    // split apart the feature types to be aggregated
-   $types = preg_split('/\s+/',$others);
+   $types = preg_split('/\s+/', $others);
 
    // the SQL for finding the term
    $tsql = "
-      SELECT * 
-      FROM {cvterm} CVT 
-         INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id 
+      SELECT *
+      FROM {cvterm} CVT
+         INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
       WHERE CVT.name = '%s' and CV.name = 'sequence'";
 
    // the SQL for deleting an aggregator
@@ -782,43 +790,44 @@ function tripal_feature_aggregator_form_submit($form, &$form_state){
 
    // if this is an insert then we have a base type name.  We
    // need to get the corresponding term id
-   if($base){
+   if ($base) {
       $previous_db = tripal_db_set_active('chado');
-      $term = db_fetch_object(db_query($tsql,$base));
+      $term = db_fetch_object(db_query($tsql, $base));
       tripal_db_set_active($previous_db);
       $type_id = $term->cvterm_id;
    }
 
-   if(strcmp($op,'Delete')==0){
-      $result = db_query($dsql,$type_id);
-      if($result){
+   if (strcmp($op, 'Delete')==0) {
+      $result = db_query($dsql, $type_id);
+      if ($result) {
         drupal_set_message("Aggregator deleted");
-      } else {
+      }
+      else {
         drupal_set_message("Failed to delete mailing list.");
       }
    }
    else {
       // for an update, first remove all the current aggregator settings
       // and we'll add them again
-      $result = db_query($dsql,$type_id);
+      $result = db_query($dsql, $type_id);
 
       // the SQL for inserting the aggregated types
       $isql = "
          INSERT INTO {tripal_feature_relagg}
           (type_id,rel_type_id)
-         VALUES 
+         VALUES
           (%d,%d)
       ";
 
       // iterate through each type to be aggregated and add an entry in the table
-      foreach($types as $type){
+      foreach ($types as $type) {
          $previous_db = tripal_db_set_active('chado');
-         $term = db_fetch_object(db_query($tsql,$type));
+         $term = db_fetch_object(db_query($tsql, $type));
          tripal_db_set_active($previous_db);
-         $result = db_query($isql,$type_id,$term->cvterm_id);
+         $result = db_query($isql, $type_id, $term->cvterm_id);
       }
       drupal_set_message("Aggregator added");
-   } 
+   }
    return '';
 }
 
@@ -827,9 +836,9 @@ function tripal_feature_aggregator_form_submit($form, &$form_state){
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_aggregator_ajax_edit (){ 
+function tripal_feature_aggregator_ajax_edit() {
    // get the database id, build the form and then return the JSON object
    $type_id = $_POST['type_id'];
-   $form = drupal_get_form('tripal_feature_aggregator_form',$type_id);
+   $form = drupal_get_form('tripal_feature_aggregator_form', $type_id);
    drupal_json(array('status' => TRUE, 'data' => $form));
 }

+ 100 - 105
tripal_feature/tripal_feature.api.inc

@@ -1,5 +1,9 @@
 <?php
- 
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 /**
  * Implements hook_chado_feature_schema()
  * Purpose: To add descriptions and foreign keys to default table description
@@ -21,21 +25,21 @@ function tripal_feature_chado_feature_schema() {
           'organism_id' => 'organism_id',
         ),
   );
-  
+
   $description['foreign keys']['dbxref'] = array(
         'table' => 'dbxref',
         'columns' => array(
           'dbxref_id' => 'dbxref_id',
         ),
   );
-  
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'type_id' => 'cvterm_id',
         ),
   );
-  
+
   $referring_tables = array('analysisfeature',
     'element',
     'feature_cvterm',
@@ -80,14 +84,14 @@ function tripal_feature_chado_featureprop_schema() {
           'feature_id' => 'feature_id',
         ),
   );
-  
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'type_id' => 'cvterm_id',
         ),
   );
-  
+
   $referring_tables = array('analysisfeature',
     'featureprop_pub',
   );
@@ -118,7 +122,7 @@ function tripal_feature_chado_featureloc_schema() {
           'srcfeature_id' => 'feature_id'
         ),
   );
-  
+
   $referring_tables = array('analysisfeature',
     'featureloc_pub',
   );
@@ -265,12 +269,12 @@ function tripal_feature_chado_feature_synonym_schema() {
  *    The feature ID for the analysis feature. This argument is optional but
  *    if specified it must also be accompanied with an analysis ID.
  * @param $analysisfeature_id
- *    The analysis feature ID for the analysis feature. This argument is 
- *    optional and can be used rather than specifying the $analysis_id and 
+ *    The analysis feature ID for the analysis feature. This argument is
+ *    optional and can be used rather than specifying the $analysis_id and
  *    $feature_id arguments.  If all three arguments are specified (e.g.
- *    an $analysis_id, $feature_id and $analysisfeature_id, then the 
+ *    an $analysis_id, $feature_id and $analysisfeature_id, then the
  *    $analysisfeature_id is used and the other two arguments are ignored.
- * @param $property 
+ * @param $property
  *    The cvterm name of the properties to retrieve
  * @param $cv_name
  *    Optional.  The name of the cv to which the property belongs.  By
@@ -281,28 +285,27 @@ function tripal_feature_chado_feature_synonym_schema() {
  *
  * @ingroup tripal_feature_api
  */
-function tripal_feature_analysis_get_property($analysis_id = NULL ,$feature_id = NUll, 
-   $analysisfeature_id = NULL, $property, $cv_name = 'tripal')
-{
-   
+function tripal_feature_analysis_get_property($analysis_id = NULL, $feature_id = NUll,
+   $analysisfeature_id = NULL, $property, $cv_name = 'tripal') {
+
    // check that the incoming arguments are correct
-   if(($analysis_id and !$feature_id) or
-       (!$analysis_id and $feature_id)){
-       watchdog('tripal_feature', 
-          'tripal_feature_analysis_get_property: Both an analysis ID and feature ID should be specified', 
-           array(), WATCHDOG_WARNING);       
+   if (($analysis_id and !$feature_id) or
+       (!$analysis_id and $feature_id)) {
+       watchdog('tripal_feature',
+          'tripal_feature_analysis_get_property: Both an analysis ID and feature ID should be specified',
+           array(), WATCHDOG_WARNING);
    }
 
    // get the analysisfeature_id if one is not provided
-   if(!$analysisfeature_id){
+   if (!$analysisfeature_id) {
       $columns = array('analysisfeature_id');
       $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
-      $result = tripal_core_chado_select('analysisfeature',$columns,$values);
+      $result = tripal_core_chado_select('analysisfeature', $columns, $values);
       $analysisfeature_id = $result[0]->analysisfeature_id;
    }
 
    // get the property.
-   return tripal_core_get_property('analysisfeature',$analysisfeature_id,$property,$cv_name);
+   return tripal_core_get_property('analysisfeature', $analysisfeature_id, $property, $cv_name);
 }
 
 /**
@@ -315,10 +318,10 @@ function tripal_feature_analysis_get_property($analysis_id = NULL ,$feature_id =
  *    The feature ID for the analysis feature. This argument is optional but
  *    if specified it must also be accompanied with an analysis ID.
  * @param $analysisfeature_id
- *    The analysis feature ID for the analysis feature. This argument is 
- *    optional and can be used rather than specifying the $analysis_id and 
+ *    The analysis feature ID for the analysis feature. This argument is
+ *    optional and can be used rather than specifying the $analysis_id and
  *    $feature_id arguments.  If all three arguments are specified (e.g.
- *    an $analysis_id, $feature_id and $analysisfeature_id, then the 
+ *    an $analysis_id, $feature_id and $analysisfeature_id, then the
  *    $analysisfeature_id is used and the other two arguments are ignored.
  * @param $property
  *   The cvterm name of the property to insert
@@ -336,35 +339,34 @@ function tripal_feature_analysis_get_property($analysis_id = NULL ,$feature_id =
  * @ingroup tripal_feature_api
  */
 function tripal_feature_analysis_insert_property($analysis_id = NULL, $feature_id = NUll,
-   $analysisfeature_id = NULL, $property, $value, $update_if_present = 0, 
-   $cv_name = 'tripal')
-{
-   
+   $analysisfeature_id = NULL, $property, $value, $update_if_present = 0,
+   $cv_name = 'tripal') {
+
    // check that the incoming arguments are correct
-   if(($analysis_id and !$feature_id) or
-       (!$analysis_id and $feature_id)){
-       watchdog('tripal_feature', 
-          'tripal_feature_analysis_insert_property: Both an analysis ID and feature ID should be specified', 
-           array(), WATCHDOG_WARNING);       
+   if (($analysis_id and !$feature_id) or
+       (!$analysis_id and $feature_id)) {
+       watchdog('tripal_feature',
+          'tripal_feature_analysis_insert_property: Both an analysis ID and feature ID should be specified',
+           array(), WATCHDOG_WARNING);
    }
 
    // get the analysisfeature_id if one is not provided
-   if(!$analysisfeature_id){
+   if (!$analysisfeature_id) {
       $columns = array('analysisfeature_id');
       $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
-      $result = tripal_core_chado_select('analysisfeature',$columns,$values);
+      $result = tripal_core_chado_select('analysisfeature', $columns, $values);
       $analysisfeature_id = $result[0]->analysisfeature_id;
    }
 
    // insert the property.
-   return tripal_core_insert_property('analysisfeature',$analysisfeature_id,
-      $property,$cv_name,$value,$update_if_present);
+   return tripal_core_insert_property('analysisfeature', $analysisfeature_id,
+      $property, $cv_name, $value, $update_if_present);
 }
 
 /**
  * Update an analysis feature property using the property name. Use this
  * when a property only exists once for a given analysis feature.  When more
- * than one value can exist for the same property use the 
+ * than one value can exist for the same property use the
  * tripal_feature_analysis_update_property_by_id() function.
  *
  * @param $analysis_id
@@ -374,16 +376,16 @@ function tripal_feature_analysis_insert_property($analysis_id = NULL, $feature_i
  *    The feature ID for the analysis feature. This argument is optional but
  *    if specified it must also be accompanied with an analysis ID.
  * @param $analysisfeature_id
- *    The analysis feature ID for the analysis feature. This argument is 
- *    optional and can be used rather than specifying the $analysis_id and 
+ *    The analysis feature ID for the analysis feature. This argument is
+ *    optional and can be used rather than specifying the $analysis_id and
  *    $feature_id arguments.  If all three arguments are specified (e.g.
- *    an $analysis_id, $feature_id and $analysisfeature_id, then the 
+ *    an $analysis_id, $feature_id and $analysisfeature_id, then the
  *    $analysisfeature_id is used and the other two arguments are ignored.
  * @param $property
  *   The cvterm name of the property to update
  * @param $value
  *   The value of the property to update
- * @param $insert_if_missing 
+ * @param $insert_if_missing
  *   A boolean indicated whether to insert the record if it's absent
  * @param $cv_name
  *    Optional.  The name of the cv to which the property belongs.  By
@@ -397,36 +399,35 @@ function tripal_feature_analysis_insert_property($analysis_id = NULL, $feature_i
  *
  * @ingroup tripal_feature_api
  */
-function tripal_feature_analysis_update_property($analysis_id = NULL, $feature_id = NUll, 
-   $analysisfeature_id = NULL, $property, $value, $insert_if_missing = 0, 
-   $cv_name = 'tripal')
-{
-  
+function tripal_feature_analysis_update_property($analysis_id = NULL, $feature_id = NUll,
+   $analysisfeature_id = NULL, $property, $value, $insert_if_missing = 0,
+   $cv_name = 'tripal') {
+
    // check that the incoming arguments are correct
-   if(($analysis_id and !$feature_id) or
-       (!$analysis_id and $feature_id)){
-       watchdog('tripal_feature', 
-          'tripal_feature_analysis_update_property: Both an analysis ID and feature ID should be specified', 
-           array(), WATCHDOG_WARNING);       
+   if (($analysis_id and !$feature_id) or
+       (!$analysis_id and $feature_id)) {
+       watchdog('tripal_feature',
+          'tripal_feature_analysis_update_property: Both an analysis ID and feature ID should be specified',
+           array(), WATCHDOG_WARNING);
    }
 
    // get the analysisfeature_id if one is not provided
-   if(!$analysisfeature_id){
+   if (!$analysisfeature_id) {
       $columns = array('analysisfeature_id');
       $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
-      $result = tripal_core_chado_select('analysisfeature',$columns,$values);
+      $result = tripal_core_chado_select('analysisfeature', $columns, $values);
       $analysisfeature_id = $result[0]->analysisfeature_id;
    }
 
    // update the property.
-   return tripal_core_update_property('analysisfeature',$analysisfeature_id,$property,$cv_name,$value, $insert_if_missing);
+   return tripal_core_update_property('analysisfeature', $analysisfeature_id, $property, $cv_name, $value, $insert_if_missing);
 }
 
 /**
  * Update a property for an analysis feature using the analysisfeatureprop_id.
  *
  * @param $analysisfeatureprop_id
- *    The analysis feature property ID for the analysis feature. 
+ *    The analysis feature property ID for the analysis feature.
  * @param $property
  *   The cvterm name of the property
  * @param $value
@@ -440,17 +441,17 @@ function tripal_feature_analysis_update_property($analysis_id = NULL, $feature_i
  *
  * @ingroup tripal_feature_api
  */
-function tripal_feature_analysis_update_property_by_id($analysisfeatureprop_id, 
-   $property, $value, $cv_name = 'tripal')
-{  
+function tripal_feature_analysis_update_property_by_id($analysisfeatureprop_id,
+   $property, $value, $cv_name = 'tripal') {
+
    // update the property.
    return tripal_core_update_property_by_id('analysisfeature',
-      $analysisfeatureprop_id,$property,$cv_name,$value);
+      $analysisfeatureprop_id, $property, $cv_name, $value);
 }
 /**
  * Delete an analysis feature property using the property name.  Use this
  * when a property only exists once for a given analysis feature.  When more
- * than one value can exist for the same property use the 
+ * than one value can exist for the same property use the
  * tripal_feature_analysis_delete_property_by_id() function.
  *
  * @param $analysis_id
@@ -460,10 +461,10 @@ function tripal_feature_analysis_update_property_by_id($analysisfeatureprop_id,
  *    The feature ID for the analysis feature. This argument is optional but
  *    if specified it must also be accompanied with an analysis ID.
  * @param $analysisfeature_id
- *    The analysis feature ID for the analysis feature. This argument is 
- *    optional and can be used rather than specifying the $analysis_id and 
+ *    The analysis feature ID for the analysis feature. This argument is
+ *    optional and can be used rather than specifying the $analysis_id and
  *    $feature_id arguments.  If all three arguments are specified (e.g.
- *    an $analysis_id, $feature_id and $analysisfeature_id, then the 
+ *    an $analysis_id, $feature_id and $analysisfeature_id, then the
  *    $analysisfeature_id is used and the other two arguments are ignored.
  * @param $property
  *    The cvterm name of the property to delete
@@ -475,47 +476,45 @@ function tripal_feature_analysis_update_property_by_id($analysisfeatureprop_id,
  * and then it will be deleted
  *
  * @return
- *   True of success, False otherwise 
+ *   True of success, False otherwise
  *
  * @ingroup tripal_feature_api
  */
-function tripal_feature_analysis_delete_property($analysis_id = NULL, $feature_id = NUll, 
-   $analysisfeature_id = NULL, $property, $cv_name = 'tripal')
-{
+function tripal_feature_analysis_delete_property($analysis_id = NULL, $feature_id = NUll,
+   $analysisfeature_id = NULL, $property, $cv_name = 'tripal') {
    // check that the incoming arguments are correct
-   if(($analysis_id and !$feature_id) or
-       (!$analysis_id and $feature_id)){
-       watchdog('tripal_feature', 
-          'tripal_feature_analysis_delete_property: Both an analysis ID and feature ID should be specified', 
-           array(), WATCHDOG_WARNING);       
+   if (($analysis_id and !$feature_id) or
+       (!$analysis_id and $feature_id)) {
+       watchdog('tripal_feature',
+          'tripal_feature_analysis_delete_property: Both an analysis ID and feature ID should be specified',
+           array(), WATCHDOG_WARNING);
    }
 
    // get the analysisfeature_id if one is not provided
-   if(!$analysisfeature_id){
+   if (!$analysisfeature_id) {
       $columns = array('analysisfeature_id');
       $values = array('analysis_id' => $analysis_id, 'feature_id' => $feature_id);
-      $result = tripal_core_chado_select('analysisfeature',$columns,$values);
+      $result = tripal_core_chado_select('analysisfeature', $columns, $values);
       $analysisfeature_id = $result[0]->analysisfeature_id;
    }
 
-   // get the property.   
-   return tripal_core_delete_property('analysisfeature',$analysisfeature_id,$property,$cv_name);
+   // get the property.
+   return tripal_core_delete_property('analysisfeature', $analysisfeature_id, $property, $cv_name);
 }
 /**
  * Delete a property using the analysisfeatureprop_id
  *
  * @param $analysisfeatureprop_id
- *    The analysis feature property ID for the analysis feature. 
+ *    The analysis feature property ID for the analysis feature.
  *
  * @return
- *   True of success, False otherwise 
+ *   True of success, False otherwise
  *
  * @ingroup tripal_feature_api
  */
-function tripal_feature_analysis_delete_property_by_id($analysisfeatureprop_id)
-{
-   // get the property.   
-   return tripal_core_delete_property_by_id('analysisfeature',$analysisfeatureprop_id);
+function tripal_feature_analysis_delete_property_by_id($analysisfeatureprop_id) {
+   // get the property.
+   return tripal_core_delete_property_by_id('analysisfeature', $analysisfeatureprop_id);
 }
 /**
  * Retrieve properties of a given type for a given feature
@@ -533,9 +532,8 @@ function tripal_feature_analysis_delete_property_by_id($analysisfeatureprop_id)
  *
  * @ingroup tripal_feature_api
  */
-function tripal_feature_get_property($feature_id,$property,$cv_name='tripal')
-{
-   return tripal_core_get_property('feature',$feature_id,$property,$cv_name);
+function tripal_feature_get_property($feature_id, $property, $cv_name='tripal') {
+   return tripal_core_get_property('feature', $feature_id, $property, $cv_name);
 }
 
 /**
@@ -559,8 +557,7 @@ function tripal_feature_get_property($feature_id,$property,$cv_name='tripal')
  * @ingroup tripal_feature_api
  */
 function tripal_feature_insert_property($feature_id, $property, $value,
-   $update_if_present = 0, $cv_name = 'tripal')
-{
+   $update_if_present = 0, $cv_name = 'tripal') {
     return tripal_core_insert_property('feature', $feature_id, $property,
        $cv_name, $value, $update_if_present);
 }
@@ -574,7 +571,7 @@ function tripal_feature_insert_property($feature_id, $property, $value,
  *   The cvterm name of the property to update
  * @param $value
  *   The value of the property to update
- * @param $insert_if_missing 
+ * @param $insert_if_missing
  *   A boolean indicated whether to insert the record if it's absent
  * @param $cv_name
  *   Optional.  The name of the cv to which the property belongs.  By
@@ -588,10 +585,9 @@ function tripal_feature_insert_property($feature_id, $property, $value,
  *
  * @ingroup tripal_feature_api
  */
-function tripal_feature_update_property($feature_id, $property, 
-  $value, $insert_if_missing = 0, $cv_name = 'tripal')
-{
-   return tripal_core_update_property('feature',$feature_id,$property,$cv_name,$value, $insert_if_missing);
+function tripal_feature_update_property($feature_id, $property,
+  $value, $insert_if_missing = 0, $cv_name = 'tripal') {
+   return tripal_core_update_property('feature', $feature_id, $property, $cv_name, $value, $insert_if_missing);
 }
 
 /**
@@ -612,10 +608,9 @@ function tripal_feature_update_property($feature_id, $property,
  *
  * @ingroup tripal_feature_api
  */
-function tripal_feature_update_property_by_id($featureprop_id, $property, 
-  $value, $cv_name = 'tripal')
-{
-   return tripal_core_update_property_by_id('feature',$featureprop_id,$property,$cv_name,$value);
+function tripal_feature_update_property_by_id($featureprop_id, $property,
+  $value, $cv_name = 'tripal') {
+   return tripal_core_update_property_by_id('feature', $featureprop_id, $property, $cv_name, $value);
 }
 
 /**
@@ -634,12 +629,12 @@ function tripal_feature_update_property_by_id($featureprop_id, $property,
  * and then it will be deleted
  *
  * @return
- *   True of success, False otherwise 
+ *   True of success, False otherwise
  *
  * @ingroup tripal_feature_api
  */
-function tripal_feature_delete_property($feature_id,$property,$cv_name='tripal'){
-   return tripal_core_delete_property('feature',$feature_id,$property,$cv_name);
+function tripal_feature_delete_property($feature_id, $property, $cv_name='tripal') {
+   return tripal_core_delete_property('feature', $feature_id, $property, $cv_name);
 }
 /**
  * Delete a given feature property using the featureprop_id
@@ -648,10 +643,10 @@ function tripal_feature_delete_property($feature_id,$property,$cv_name='tripal')
  *   The feature_id of the property to delete
  *
  * @return
- *   True of success, False otherwise 
+ *   True of success, False otherwise
  *
  * @ingroup tripal_feature_api
  */
-function tripal_feature_delete_property_by_id($featureprop_id){
-   return tripal_core_delete_property_by_id('feature',$featureprop_id);
+function tripal_feature_delete_property_by_id($featureprop_id) {
+   return tripal_core_delete_property_by_id('feature', $featureprop_id);
 }

+ 33 - 29
tripal_feature/tripal_feature.install

@@ -1,18 +1,22 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
 *  Implementation of hook_install();
 *
 * @ingroup tripal_feature
 */
-function tripal_feature_install(){
+function tripal_feature_install() {
    // create the module's data directory
    tripal_create_moddir('tripal_feature');
 
-   // create the tables that correlate drupal nodes with chado 
+   // create the tables that correlate drupal nodes with chado
    // features, organisms, etc....
    drupal_install_schema('tripal_feature');
-  
+
    // add the materialized view
    tripal_feature_add_organism_count_mview();
 
@@ -23,13 +27,13 @@ function tripal_feature_install(){
 *
 * @ingroup tripal_feature
 */
-function tripal_feature_update_6000(){
+function tripal_feature_update_6000() {
    // recreate the materialized view
    tripal_feature_add_organism_count_mview();
    $ret = array(
       '#finished' => 1,
    );
-   
+
    return $ret;
 }
 
@@ -37,25 +41,25 @@ function tripal_feature_update_6000(){
 *
 * @ingroup tripal_feature
 */
-function tripal_feature_update_6300(){
+function tripal_feature_update_6300() {
    // add the relationship aggregator table to the database
    $schema = tripal_feature_get_schemas('tripal_feature_relagg');
    $ret = array();
    db_create_table($ret, 'tripal_feature_relagg', $schema['tripal_feature_relagg']);
-   
+
    return $ret;
 }
 /**
 *
 * @ingroup tripal_feature
 */
-function tripal_feature_add_organism_count_mview(){
+function tripal_feature_add_organism_count_mview() {
    $view_name = 'organism_feature_count';
 
    // Drop the MView table if it exists
    $mview_id = tripal_mviews_get_mview_id($view_name);
-   if($mview_id){
-      tripal_mviews_action("delete",$mview_id);
+   if ($mview_id) {
+      tripal_mviews_action("delete", $mview_id);
    }
 
    // Create the MView
@@ -75,12 +79,12 @@ function tripal_feature_add_organism_count_mview(){
       // columns for indexing
       'organism_id,cvterm_id,feature_type',
       // SQL statement to populate the view
-      'SELECT O.organism_id, O.genus, O.species, O.common_name, 
-          count(F.feature_id) as num_features, 
-          CVT.cvterm_id, CVT.name as feature_type 
-       FROM {Organism} O 
-          INNER JOIN Feature F           ON O.Organism_id = F.organism_id 
-          INNER JOIN Cvterm CVT          ON F.type_id = CVT.cvterm_id 
+      'SELECT O.organism_id, O.genus, O.species, O.common_name,
+          count(F.feature_id) as num_features,
+          CVT.cvterm_id, CVT.name as feature_type
+       FROM {Organism} O
+          INNER JOIN Feature F           ON O.Organism_id = F.organism_id
+          INNER JOIN Cvterm CVT          ON F.type_id = CVT.cvterm_id
        GROUP BY O.Organism_id, O.genus, O.species, O.common_name,
           CVT.cvterm_id, CVT.name',
       // special index
@@ -90,8 +94,8 @@ function tripal_feature_add_organism_count_mview(){
    // add a job to the job queue so this view gets updated automatically next
    // time the job facility is run
    $mview_id = tripal_mviews_get_mview_id($view_name);
-   if($mview_id){
-      tripal_mviews_action('update',$mview_id);
+   if ($mview_id) {
+      tripal_mviews_action('update', $mview_id);
    }
 }
 /**
@@ -108,19 +112,19 @@ function tripal_feature_schema() {
 *
 * @ingroup tripal_feature
 */
-function tripal_feature_uninstall(){
+function tripal_feature_uninstall() {
 
    // Drop the MView table if it exists
    $mview_id = tripal_mviews_get_mview_id('organism_feature_count');
-   if($mview_id){
-      tripal_mviews_action("delete",$mview_id);
+   if ($mview_id) {
+      tripal_mviews_action("delete", $mview_id);
    }
 
    drupal_uninstall_schema('tripal_feature');
 
    // Get the list of nodes to remove
-   $sql_feature_id = "SELECT nid, vid ".
-                 "FROM {node} ".
+   $sql_feature_id = "SELECT nid, vid " .
+                 "FROM {node} " .
                  "WHERE type='chado_feature'";
    $result = db_query($sql_feature_id);
    while ($node = db_fetch_object($result)) {
@@ -130,35 +134,35 @@ function tripal_feature_uninstall(){
 
 /**
 * This function simply defines all tables needed for the module to work
-* correctly.  By putting the table definitions in a separate function we 
+* 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.
 *
 * @ingroup tripal_feature
 */
-function tripal_feature_get_schemas ($table = NULL){  
+function tripal_feature_get_schemas($table = NULL) {
   $schema = array();
 
 
-  if(!$table or strcmp($table,'chado_feature')==0){
+  if (!$table or strcmp($table, 'chado_feature')==0) {
      $schema['chado_feature'] = 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),
             'feature_id' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
-            'sync_date' => array ('type' => 'int', 'not null' => FALSE, 'description' => 'UNIX integer sync date/time'),
+            'sync_date' => array('type' => 'int', 'not null' => FALSE, 'description' => 'UNIX integer sync date/time'),
          ),
          'indexes' => array(
             'feature_id' => array('feature_id')
           ),
          'unique keys' => array(
-            'nid_vid' => array('nid','vid'),
+            'nid_vid' => array('nid', 'vid'),
             'vid' => array('vid')
          ),
          'primary key' => array('nid'),
      );
   }
-  if(!$table or strcmp($table,'tripal_feature_relagg')==0){
+  if (!$table or strcmp($table, 'tripal_feature_relagg')==0) {
      $schema['tripal_feature_relagg'] = array(
         'fields' => array(
            'type_id' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),

File diff suppressed because it is too large
+ 227 - 219
tripal_feature/tripal_feature.module


+ 2 - 2
tripal_feature/tripal_feature.views.inc

@@ -105,7 +105,7 @@ function tripal_feature_views_handlers() {
  */
 function tripal_feature_views_data_alter(&$data) {
 
-  if( !(is_array($db_url) and array_key_exists('chado',$db_url)) ){
+  if ( !(is_array($db_url) and array_key_exists('chado', $db_url)) ) {
 
     // Add featuer relationship to node
     $data['node']['feature_chado_nid'] = array(
@@ -130,7 +130,7 @@ function tripal_feature_views_data_alter(&$data) {
  *
  * @ingroup tripal_feature_views
  */
-function tripal_feature_views_default_views () {
+function tripal_feature_views_default_views() {
   $views = array();
 
   // Main default view

+ 473 - 0
tripal_feature/tripal_feature.views.inc.orig

@@ -0,0 +1,473 @@
+<?php
+
+/**
+ *  @file
+ *  This file contains the basic functions for views integration of
+ *  chado/tripal organism tables. Supplementary functions can be found in
+ *  ./views/
+ *
+ *  Documentation on views integration can be found at
+ *  http://views2.logrus.com/doc/html/index.html.
+ */
+
+/**
+ * @defgroup tripal_feature_views Feature Views Integration
+ * @ingroup views
+ * @ingroup tripal_feature
+ */
+
+/**
+ * Implements hook_views_data()
+ *
+ * Purpose: Describe chado/tripal tables & fields to views
+ *
+ * @return: a data array which follows the structure outlined in the
+ *   views2 documentation for this hook. Essentially, it's an array of table
+ *   definitions keyed by chado/tripal table name. Each table definition
+ *   includes basic details about the table, fields in that table and
+ *   relationships between that table and others (joins)
+ *
+ * @ingroup tripal_feature_views
+ */
+function tripal_feature_views_data()  {
+  $data = array();
+
+<<<<<<< HEAD
+  if (module_exists('tripal_views')) {
+    $tables = array(
+      'feature',
+    );
+    foreach ($tables as $tablename) {
+      if (!tripal_views_is_integrated($tablename, 10)) {
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        tripal_views_integration_add_entry($table_integration_array);
+      }
+    }
+
+    $tables = array(
+      'feature_cvterm',
+      'feature_cvterm_dbxref',
+      'feature_cvterm_pub',
+      'feature_cvtermprop',
+      'feature_dbxref',
+      'feature_pub',
+      'feature_pubprop',
+      'feature_relationship',
+      'feature_relationship_pub',
+      'feature_relationshipprop',
+      'feature_relationshipprop_pub',
+      'feature_synonym',
+      'featureloc',
+      'featureloc_pub',
+      'featureprop',
+      'featureprop_pub',
+      'featuremap',
+      'featuremap_pub',
+      'featurepos',
+      'featurerange'
+    );
+    foreach ($tables as $tablename) {
+      if (!tripal_views_is_integrated($tablename, 10)) {
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        tripal_views_integration_add_entry($table_integration_array);
+      }
+    }
+  }
+=======
+  $data = array_merge($data, retrieve_feature_views_data());
+  $data = array_merge($data, retrieve_chado_feature_views_data());
+  $data = array_merge($data, retrieve_feature_misc_tables_views_data());
+>>>>>>> 6.x-0.4-dev
+
+  return $data;
+}
+
+/**
+ * Implements hook_views_handlers()
+ *
+ * Purpose: Register all custom handlers with views
+ *   where a handler describes either "the type of field",
+ *   "how a field should be filtered", "how a field should be sorted"
+ *
+ * @return: An array of handler definitions
+ *
+ * @ingroup tripal_feature_views
+ */
+function tripal_feature_views_handlers() {
+ return array(
+   'info' => array(
+     'path' => drupal_get_path('module', 'tripal_feature') . '/views_handlers',
+   ),
+   'handlers' => array(
+     'views_handler_field_residues' => array(
+       'parent' => 'views_handler_field',
+     ),
+   ),
+ );
+}
+
+/**
+ * Implementation of hook_views_data_alter().
+ */
+function tripal_feature_views_data_alter(&$data) {
+
+  if ( !(is_array($db_url) and array_key_exists('chado', $db_url)) ) {
+
+    // Add featuer relationship to node
+    $data['node']['feature_chado_nid'] = array(
+      'group' => 'Feature',
+      'title' => 'Feature Node',
+      'help' => 'Links Chado Feature Fields/Data to the Nodes in the current View.',
+      'real field' => 'nid',
+      'relationship' => array(
+        'handler' => 'views_handler_relationship',
+        'title' => t('Node => Chado'),
+        'label' => t('Node => Chado'),
+        'real field' => 'nid',
+        'base' => 'chado_feature',
+        'base field' => 'nid'
+      ),
+    );
+  }
+
+}
+
+/**
+ *
+ * @ingroup tripal_feature_views
+ */
+function tripal_feature_views_default_views() {
+  $views = array();
+
+  // Main default view
+  // List all cvterms based on cv
+  $view = new view;
+  $view->name = 'all_features';
+  $view->description = 'A listing of all Sequence FEatures';
+  $view->tag = 'chado';
+  $view->view_php = '';
+  $view->base_table = 'feature';
+  $view->is_cacheable = FALSE;
+  $view->api_version = 2;
+  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
+  $handler = $view->new_display('default', 'Defaults', 'default');
+  $handler->override_option('fields', array(
+    'uniquename' => array(
+      'label' => 'Unique Name',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 1,
+      'exclude' => 0,
+      'id' => 'uniquename',
+      'table' => 'feature',
+      'field' => 'uniquename',
+      'relationship' => 'none',
+    ),
+    'name' => array(
+      'label' => 'Name',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 1,
+      'exclude' => 0,
+      'id' => 'name',
+      'table' => 'feature',
+      'field' => 'name',
+      'relationship' => 'none',
+    ),
+    'common_name' => array(
+      'label' => 'Organism',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 1,
+      'exclude' => 0,
+      'id' => 'common_name',
+      'table' => 'organism',
+      'field' => 'common_name',
+      'relationship' => 'none',
+    ),
+    'name_3' => array(
+      'label' => 'Type',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'name_3',
+      'table' => 'cvterm',
+      'field' => 'name',
+      'relationship' => 'none',
+    ),
+    'accession_link' => array(
+      'label' => 'External Reference',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'accession_link',
+      'table' => 'dbxref',
+      'field' => 'accession_link',
+      'relationship' => 'none',
+    ),
+    'name_1' => array(
+      'label' => 'Library',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 1,
+      'exclude' => 0,
+      'id' => 'name_1',
+      'table' => 'library',
+      'field' => 'name',
+      'relationship' => 'none',
+    ),
+    'name_2' => array(
+      'label' => 'Analysis',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 1,
+      'exclude' => 0,
+      'id' => 'name_2',
+      'table' => 'analysis',
+      'field' => 'name',
+      'relationship' => 'none',
+    ),
+  ));
+  $handler->override_option('filters', array(
+    'common_name' => array(
+      'operator' => '=',
+      'value' => '<select organism>',
+      'group' => '0',
+      'exposed' => TRUE,
+      'expose' => array(
+        'use_operator' => 0,
+        'operator' => 'common_name_op',
+        'identifier' => 'organism',
+        'label' => 'Organism',
+        'optional' => 1,
+        'remember' => 0,
+      ),
+      'case' => 1,
+      'id' => 'common_name',
+      'table' => 'organism',
+      'field' => 'common_name',
+      'relationship' => 'none',
+    ),
+    'name' => array(
+      'operator' => 'contains',
+      'value' => '',
+      'group' => '0',
+      'exposed' => TRUE,
+      'expose' => array(
+        'use_operator' => 0,
+        'operator' => 'name_op',
+        'identifier' => 'name',
+        'label' => 'Name Contains',
+        'optional' => 1,
+        'remember' => 0,
+      ),
+      'case' => 0,
+      'id' => 'name',
+      'table' => 'feature',
+      'field' => 'name',
+      'relationship' => 'none',
+    ),
+    'name_1' => array(
+      'operator' => 'contains',
+      'value' => '',
+      'group' => '0',
+      'exposed' => TRUE,
+      'expose' => array(
+        'use_operator' => 0,
+        'operator' => 'name_1_op',
+        'identifier' => 'library',
+        'label' => 'Library Name Contains',
+        'optional' => 1,
+        'remember' => 0,
+      ),
+      'case' => 0,
+      'id' => 'name_1',
+      'table' => 'library',
+      'field' => 'name',
+      'relationship' => 'none',
+    ),
+    'name_2' => array(
+      'operator' => 'contains',
+      'value' => '',
+      'group' => '0',
+      'exposed' => TRUE,
+      'expose' => array(
+        'use_operator' => 0,
+        'operator' => 'name_2_op',
+        'identifier' => 'analysis',
+        'label' => 'Analysis Name Contains',
+        'optional' => 1,
+        'remember' => 0,
+      ),
+      'case' => 0,
+      'id' => 'name_2',
+      'table' => 'analysis',
+      'field' => 'name',
+      'relationship' => 'none',
+    ),
+  ));
+  $handler->override_option('access', array(
+    'type' => 'perm',
+    'perm' => 'access chado_feature content',
+  ));
+  $handler->override_option('cache', array(
+    'type' => 'none',
+  ));
+  $handler->override_option('title', 'Sequence Features');
+  $handler->override_option('empty', 'There are no features matching that criteria. Please select a different organism above.');
+  $handler->override_option('empty_format', '1');
+  $handler->override_option('items_per_page', 50);
+  $handler->override_option('style_plugin', 'table');
+  $handler = $view->new_display('page', 'Page', 'page_1');
+  $handler->override_option('path', 'features');
+  $handler->override_option('menu', array(
+    'type' => 'normal',
+    'title' => 'Sequence Features',
+    'description' => '',
+    'weight' => '0',
+    'name' => 'primary-links',
+  ));
+  $handler->override_option('tab_options', array(
+    'type' => 'none',
+    'title' => '',
+    'description' => '',
+    'weight' => 0,
+    'name' => 'navigation',
+  ));
+  $views[$view->name] = $view;
+
+  return $views;
+}

+ 13 - 8
tripal_feature/views_handlers/views_handler_field_residues.inc

@@ -1,4 +1,9 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 /**
  * A handler to provide proper displays for sequence residues.
  *
@@ -7,19 +12,19 @@
  */
 class views_handler_field_residues extends views_handler_field {
 
-	function construct() {
-		parent::construct();
+  function construct() {
+    parent::construct();
       $this->additional_fields['residues'] = array('table' => 'feature', 'field' => 'residues');
-	}
+  }
 
-	function query() { 
-		$this->ensure_my_table();
-		$this->add_additional_fields(); 
-	}
+  function query() {
+    $this->ensure_my_table();
+    $this->add_additional_fields();
+  }
 
   function render($values) {
     // add a <br> every 100 bp
-    return ereg_replace("(.{100})","\\1<br>",$values->feature_residues);
+    return ereg_replace("(.{100})", "\\1<br>", $values->feature_residues);
 
   }
 }

+ 22 - 17
tripal_genetic/tripal_genetic.api.inc

@@ -1,9 +1,13 @@
-<?php 
+<?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
  *
  */
-function tripal_genetic_get_genotypes_by_feature_id ($feature_id) {
+function tripal_genetic_get_genotypes_by_feature_id($feature_id) {
 
   /**
   $sql = 'SELECT nd_experiment_id FROM nd_experiment_genotype WHERE genotype_id IN (SELECT genotype_id FROM feature_genotype WHERE feature_id=%d)';
@@ -13,24 +17,25 @@ function tripal_genetic_get_genotypes_by_feature_id ($feature_id) {
   while ($r = db_fetch_object($resource)) {
     $values['nd_experiment_id'][] = $r->nd_experiment_id;
   }
-  
+
   $object = tripal_core_generate_chado_var('nd_experiment',$values);
   $object = tripal_core_expand_chado_vars($object, 'table', 'nd_experiment_genotype');
   $object = tripal_core_expand_chado_vars($object, 'table', 'feature_genotype');
   $object = tripal_core_expand_chado_vars($object, 'table', 'nd_experiment_stock');
   */
 
-  $sql = 'SELECT genotype_id FROM genotype WHERE genotype_id IN (SELECT genotype_id FROM feature_genotype WHERE feature_id=%d)';
+  $sql = 'SELECT genotype_id FROM {genotype} WHERE genotype_id IN (SELECT genotype_id FROM {feature_genotype} WHERE feature_id=%d)';
   $resource = db_query($sql, $feature_id);
 
   $values['genotype_id'] = array();
   while ($r = db_fetch_object($resource)) {
     $values['genotype_id'][] = $r->genotype_id;
   }
-  
+
   if (!empty($values['genotype_id'])) {
-    $object = tripal_core_generate_chado_var('genotype',$values);  
-  } else {
+    $object = tripal_core_generate_chado_var('genotype', $values);
+  }
+  else {
     $object = array();
   }
   return $object;
@@ -47,9 +52,9 @@ function tripal_genetic_get_genotypes_by_feature_id ($feature_id) {
  *
  * @ingroup tripal_schema_api
  */
-function tripal_genetic_chado_genotype_schema () {
+function tripal_genetic_chado_genotype_schema() {
   $description = array();
- 
+
   $referring_tables = array('analysisfeature',
     'feature_genotype',
     'phendesc',
@@ -58,9 +63,9 @@ function tripal_genetic_chado_genotype_schema () {
     'stock_genotype',
   );
   $description['referring_tables'] = $referring_tables;
-  
+
   return $description;
-  
+
 }
 
 /**
@@ -73,7 +78,7 @@ function tripal_genetic_chado_genotype_schema () {
  *
  * @ingroup tripal_schema_api
  */
-function tripal_genetic_chado_feature_genotype_schema () {
+function tripal_genetic_chado_feature_genotype_schema() {
   $description = array();
 
   $description['foreign keys']['feature'] = array(
@@ -82,14 +87,14 @@ function tripal_genetic_chado_feature_genotype_schema () {
           'feature_id' => 'feature_id',
           'chromosome_id' => 'feature_id',
         ),
-  ); 
+  );
 
   $description['foreign keys']['genotype'] = array(
         'table' => 'genotype',
         'columns' => array(
           'genotype_id' => 'genotype_id',
         ),
-  );  
+  );
 
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
@@ -97,7 +102,7 @@ function tripal_genetic_chado_feature_genotype_schema () {
           'cvterm_id' => 'cvterm_id',
         ),
   );
-  
+
   return $description;
-  
-}
+
+}

+ 10 - 10
tripal_genetic/tripal_genetic.module

@@ -3,9 +3,9 @@
 /**
  *  @file
  * This file contains the basic functions needed for this drupal module.
- * The drupal tripal_genetic module maps directly to the chado X module. 
+ * The drupal tripal_genetic module maps directly to the chado X module.
  *
- * For documentation regarding the Chado X module: 
+ * For documentation regarding the Chado X module:
  * @see http://gmod.org/wiki/Chado_General_Module
  */
 
@@ -16,7 +16,7 @@ require('tripal_genetic.api.inc');
  * Purpose: Essentially this hook tells drupal that there is views support for
  *  for this module which then includes tripal_genetic.views.inc where all the
  *  views integration code is
- */ 
+ */
 function tripal_genetic_views_api() {
    return array(
       'api' => 2.0,
@@ -25,17 +25,17 @@ function tripal_genetic_views_api() {
 
 function tripal_genetic_theme() {
   return array(
-    'tripal_feature_genotypes' => array (
-       'arguments' => array('node'=> null),
+    'tripal_feature_genotypes' => array(
+       'arguments' => array('node' => NULL),
        'template' => 'tripal_feature_genotypes',
-    ),  
+    ),
   );
 }
 
 /**
  *
  */
-function tripal_genetic_nodeapi (&$node, $op, $teaser, $page) {
+function tripal_genetic_nodeapi(&$node, $op, $teaser, $page) {
   switch ($op) {
     case 'view':
       if ($node->type == 'chado_feature') {
@@ -51,7 +51,7 @@ function tripal_genetic_nodeapi (&$node, $op, $teaser, $page) {
 /**
  *
  */
-function tripal_genetic_preprocess_tripal_feature_genotypes(&$variables){
-    $feature = $variables['node']->feature;   
+function tripal_genetic_preprocess_tripal_feature_genotypes(&$variables) {
+    $feature = $variables['node']->feature;
     $variables['tripal_feature']['genotypes'] = tripal_genetic_get_genotypes_by_feature_id($feature->feature_id);
-}
+}

+ 29 - 25
tripal_library/tripal_library.api.inc

@@ -1,11 +1,15 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
  * @defgroup tripal_library_api Library Module API
  * @ingroup tripal_api
  * @ingroup tripal_library
  */
- 
+
 /**
  * Implements hook_chado_library_schema()
  * Purpose: To add descriptions and foreign keys to default table description
@@ -18,7 +22,7 @@
  */
 function tripal_library_chado_library_schema() {
   $description = array();
-  
+
   // Default table description in tripal_core.schema.api.inc: tripal_core_chado_feature_schema()
 
   $description['foreign keys']['organism'] = array(
@@ -26,24 +30,24 @@ function tripal_library_chado_library_schema() {
         'columns' => array(
           'organism_id' => 'organism_id',
         ),
-  );  
-  
+  );
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'type_id' => 'cvterm_id',
         ),
   );
-  
+
   $referring_tables = array(
       'library_cvterm',
       'library_feature',
       'library_pub',
       'library_synonym',
-      'libraryprop' 
+      'libraryprop'
   );
   $description['referring_tables'] = $referring_tables;
-  
+
   return $description;
 }
 
@@ -59,7 +63,7 @@ function tripal_library_chado_library_schema() {
  */
 function tripal_library_chado_library_feature_schema() {
   $description = array();
-  
+
   // Default table description in tripal_core.schema.api.inc: tripal_core_chado_library_feature_schema()
 
   $description['foreign keys']['library'] = array(
@@ -67,15 +71,15 @@ function tripal_library_chado_library_feature_schema() {
         'columns' => array(
           'library_id' => 'library_id',
         ),
-  );  
-  
+  );
+
   $description['foreign keys']['feature'] = array(
         'table' => 'feature',
         'columns' => array(
           'feature_id' => 'feature_id',
         ),
   );
-  
+
   return $description;
 }
 /**
@@ -90,7 +94,7 @@ function tripal_library_chado_library_feature_schema() {
  */
 function tripal_library_chado_libraryprop_schema() {
   $description = array();
-  
+
   // Default table description in tripal_core.schema.api.inc: tripal_core_chado_library_feature_schema()
 
   $description['foreign keys']['library'] = array(
@@ -98,15 +102,15 @@ function tripal_library_chado_libraryprop_schema() {
         'columns' => array(
           'library_id' => 'library_id',
         ),
-  );  
-  
+  );
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'type_id' => 'cvterm_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -123,8 +127,8 @@ function tripal_library_chado_libraryprop_schema() {
  *
  * @ingroup tripal_library_api
  */
-function tripal_library_get_property($library_id,$property){
-   return tripal_core_get_property('library',$library_id,$property,'tripal');
+function tripal_library_get_property($library_id, $property) {
+   return tripal_core_get_property('library', $library_id, $property, 'tripal');
 }
 
 /**
@@ -144,8 +148,8 @@ function tripal_library_get_property($library_id,$property){
  *
  * @ingroup tripal_library_api
  */
-function tripal_library_insert_property($library_id,$property,$value,$update_if_present = 0){
-   return tripal_core_insert_property('library',$library_id,$property,'tripal',$value,$update_if_present);
+function tripal_library_insert_property($library_id, $property, $value, $update_if_present = 0) {
+   return tripal_core_insert_property('library', $library_id, $property, 'tripal', $value, $update_if_present);
 }
 
 /**
@@ -157,7 +161,7 @@ function tripal_library_insert_property($library_id,$property,$value,$update_if_
  *   The cvterm name of the property to update
  * @param $value
  *   The value of the property to update
- * @param $insert_if_missing 
+ * @param $insert_if_missing
  *   A boolean indicated whether to insert the record if it's absent
  *
  * Note: The property will be identified using the unique combination of the $library_id and $property
@@ -168,8 +172,8 @@ function tripal_library_insert_property($library_id,$property,$value,$update_if_
  *
  * @ingroup tripal_library_api
  */
-function tripal_library_update_property($library_id,$property,$value,$insert_if_missing = 0){
-   return tripal_core_update_property('library',$library_id,$property,'tripal',$value, $insert_if_missing);
+function tripal_library_update_property($library_id, $property, $value, $insert_if_missing = 0) {
+   return tripal_core_update_property('library', $library_id, $property, 'tripal', $value, $insert_if_missing);
 }
 /**
  * Delete a given property
@@ -183,10 +187,10 @@ function tripal_library_update_property($library_id,$property,$value,$insert_if_
  * and then it will be deleted
  *
  * @return
- *   True of success, False otherwise 
+ *   True of success, False otherwise
  *
  * @ingroup tripal_library_api
  */
-function tripal_library_delete_property($library_id,$property){
-   return tripal_core_delete_property('library',$library_id,$property,'tripal');
+function tripal_library_delete_property($library_id, $property) {
+   return tripal_core_delete_property('library', $library_id, $property, 'tripal');
 }

+ 22 - 18
tripal_library/tripal_library.install

@@ -1,11 +1,15 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
 *  Implementation of hook_install();
 *
 * @ingroup tripal_library
 */
-function tripal_library_install(){
+function tripal_library_install() {
    // create the module's data directory
    tripal_create_moddir('tripal_library');
 
@@ -16,14 +20,14 @@ function tripal_library_install(){
    // 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_cv_add_cvterm(array('name' => 'library_description','def' => 'Description of a library'),'tripal',0,1,'tripal');
-   
+   tripal_cv_add_cvterm(array('name' => 'library_description', 'def' => 'Description of a library'), 'tripal', 0, 1, 'tripal');
+
    // Add CVTerms for the library types
-   tripal_cv_add_cvterm(array('name' => 'cdna_library','def' => 'cDNA Library'),'tripal',0,1,'tripal');
-   tripal_cv_add_cvterm(array('name' => 'bac_library','def' => 'BAC Library'),'tripal',0,1,'tripal');
-   tripal_cv_add_cvterm(array('name' => 'fosmid_library','def' => 'FOSMID Library'),'tripal',0,1,'tripal');
-   tripal_cv_add_cvterm(array('name' => 'cosmid_library','def' => 'COSMID Library'),'tripal',0,1,'tripal');
-   tripal_cv_add_cvterm(array('name' => 'yac_library','def' => 'YAC Library'),'tripal',0,1,'tripal');
+   tripal_cv_add_cvterm(array('name' => 'cdna_library', 'def' => 'cDNA Library'), 'tripal', 0, 1, 'tripal');
+   tripal_cv_add_cvterm(array('name' => 'bac_library', 'def' => 'BAC Library'), 'tripal', 0, 1, 'tripal');
+   tripal_cv_add_cvterm(array('name' => 'fosmid_library', 'def' => 'FOSMID Library'), 'tripal', 0, 1, 'tripal');
+   tripal_cv_add_cvterm(array('name' => 'cosmid_library', 'def' => 'COSMID Library'), 'tripal', 0, 1, 'tripal');
+   tripal_cv_add_cvterm(array('name' => 'yac_library', 'def' => 'YAC Library'), 'tripal', 0, 1, 'tripal');
 
    // Add the materialized view needed to count the features for the library
    // Drop the MView table if it exists
@@ -34,12 +38,12 @@ function tripal_library_install(){
    }
    tripal_db_set_active($previous_db);
    // Create the MView
-   tripal_add_mview('library_feature_count','tripal_library',
+   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 '.
+    '  num_features integer, feature_type character varying(255)',
+     'library_id',
+     'SELECT '.
       '   L.library_id, '.
       '   L.name, '.
       '    count(F.feature_id) as num_features, '.
@@ -49,7 +53,7 @@ function tripal_library_install(){
       '    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',
-	   ''
+     ''
    );
 
 }
@@ -69,7 +73,7 @@ function tripal_library_schema() {
  *
  * @ingroup tripal_library
  */
-function tripal_library_uninstall(){
+function tripal_library_uninstall() {
    drupal_uninstall_schema('tripal_library');
 
    // remove the materialized view
@@ -78,8 +82,8 @@ function tripal_library_uninstall(){
 
    if (db_table_exists('tripal_mviews')) {
       $mview = db_fetch_object(db_query($sql));
-      if($mview){
-         tripal_mviews_action('delete',$mview->mview_id);
+      if ($mview) {
+         tripal_mviews_action('delete', $mview->mview_id);
       }
    }
 
@@ -101,7 +105,7 @@ function tripal_library_uninstall(){
  *
  * @ingroup tripal_library
  */
-function tripal_library_get_schemas (){
+function tripal_library_get_schemas() {
   $schema = array();
   $schema['chado_library'] = array(
       'fields' => array(
@@ -127,7 +131,7 @@ function tripal_library_get_schemas (){
          'library_id' => array('library_id')
       ),
       'unique keys' => array(
-         'nid_vid' => array('nid','vid'),
+         'nid_vid' => array('nid', 'vid'),
          'vid' => array('vid')
       ),
       'primary key' => array('nid'),

File diff suppressed because it is too large
+ 209 - 199
tripal_library/tripal_library.module


+ 2 - 2
tripal_library/tripal_library.views.inc

@@ -86,7 +86,7 @@ function tripal_library_views_handlers() {
  */
 function tripal_library_views_data_alter(&$data) {
 
-  if( !(is_array($db_url) and array_key_exists('chado',$db_url)) ){
+  if ( !(is_array($db_url) and array_key_exists('chado', $db_url)) ) {
 
     // Add featuer relationship to node
     $data['node']['library_chado_nid'] = array(
@@ -112,7 +112,7 @@ function tripal_library_views_data_alter(&$data) {
  *
  * @ingroup tripal_library_views
  */
-function tripal_library_views_default_views () {
+function tripal_library_views_default_views() {
   $views = array();
 
   // Main default view

+ 425 - 0
tripal_library/tripal_library.views.inc.orig

@@ -0,0 +1,425 @@
+<?php
+
+/**
+ *  @file
+ *  This file contains the basic functions for views integration of
+ *  chado/tripal organism tables. Supplementary functions can be found in
+ *  ./views/
+ *
+ *  Documentation on views integration can be found at
+ *  http://views2.logrus.com/doc/html/index.html.
+ */
+
+/**
+ * @defgroup tripal_library_views Library Views Integration
+ * @ingroup views
+ * @ingroup tripal_library
+ */
+
+<<<<<<< HEAD
+=======
+require_once('views/library.views.inc');
+require_once('views/chado_library.views.inc');
+require_once('views/misc_tables.views.inc');
+>>>>>>> 6.x-0.4-dev
+/*************************************************************************
+ * Implements hook_views_data()
+ * Purpose: Describe chado/tripal tables & fields to views
+ * @return: a data array which follows the structure outlined in the
+ *   views2 documentation for this hook. Essentially, it's an array of table
+ *   definitions keyed by chado/tripal table name. Each table definition
+ *   includes basic details about the table, fields in that table and
+ *   relationships between that table and others (joins)
+ *
+ * @ingroup tripal_library_views
+ */
+function tripal_library_views_data()  {
+  $data = array();
+
+<<<<<<< HEAD
+  if (module_exists('tripal_views')) {
+    $tables = array(
+      'library'
+    );
+    foreach ($tables as $tablename) {
+      if (!tripal_views_is_integrated($tablename, 10)) {
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        tripal_views_integration_add_entry($table_integration_array);
+      }
+    }
+
+    $tables = array(
+      'library_cvterm',
+      'library_feature',
+      'library_pub',
+      'library_synonym',
+      'libraryprop'
+    );
+    foreach ($tables as $tablename) {
+      if (!tripal_views_is_integrated($tablename, 10)) {
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        tripal_views_integration_add_entry($table_integration_array);
+      }
+    }
+  }
+=======
+  $data = array_merge($data, retrieve_library_views_data());
+  $data = array_merge($data, retrieve_chado_library_views_data());
+  $data = array_merge($data, retrieve_library_misc_tables_views_data());
+>>>>>>> 6.x-0.4-dev
+
+  return $data;
+}
+
+/*************************************************************************
+ * Implements hook_views_handlers()
+ * Purpose: Register all custom handlers with views
+ *   where a handler describes either "the type of field",
+ *   "how a field should be filtered", "how a field should be sorted"
+ * @return: An array of handler definitions
+ *
+ * @ingroup tripal_library_views
+ */
+function tripal_library_views_handlers() {
+ return array(
+   'info' => array(
+     'path' => drupal_get_path('module', 'tripal_library') . '/views/handlers',
+   ),
+   'handlers' => array(
+     'views_handler_field_computed_library_nid' => array(
+       'parent' => 'views_handler_field_numeric',
+     ),
+   ),
+ );
+}
+
+/**
+ * Implementation of hook_views_data_alter().
+ */
+function tripal_library_views_data_alter(&$data) {
+
+  if ( !(is_array($db_url) and array_key_exists('chado', $db_url)) ) {
+
+    // Add featuer relationship to node
+    $data['node']['library_chado_nid'] = array(
+      'group' => 'Library',
+      'title' => 'Library Node',
+      'help' => 'Links Chado Library Fields/Data to the Nodes in the current View.',
+      'real field' => 'nid',
+      'relationship' => array(
+        'handler' => 'views_handler_relationship',
+        'title' => t('Node => Chado'),
+        'label' => t('Node => Chado'),
+        'real field' => 'nid',
+        'base' => 'chado_library',
+        'base field' => 'nid'
+      ),
+    );
+  }
+
+}
+
+/**
+ *
+ *
+ * @ingroup tripal_library_views
+ */
+function tripal_library_views_default_views() {
+  $views = array();
+
+  // Main default view
+  // List all cvterms based on cv
+  $view = new view;
+  $view->name = 'all_libraries';
+  $view->description = 'A listing of all libraries';
+  $view->tag = 'chado';
+  $view->view_php = '';
+  $view->base_table = 'library';
+  $view->is_cacheable = FALSE;
+  $view->api_version = 2;
+  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
+  $handler = $view->new_display('default', 'Defaults', 'default');
+  $handler->override_option('fields', array(
+    'uniquename' => array(
+      'label' => 'Unique Name',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 1,
+      'exclude' => 0,
+      'id' => 'uniquename',
+      'table' => 'library',
+      'field' => 'uniquename',
+      'relationship' => 'none',
+    ),
+    'name_1' => array(
+      'label' => 'Name',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 1,
+      'exclude' => 0,
+      'id' => 'name_1',
+      'table' => 'library',
+      'field' => 'name',
+      'relationship' => 'none',
+    ),
+    'common_name' => array(
+      'label' => 'Organism',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 1,
+      'exclude' => 0,
+      'id' => 'common_name',
+      'table' => 'organism',
+      'field' => 'common_name',
+      'relationship' => 'none',
+    ),
+    'name' => array(
+      'label' => 'Type',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'name',
+      'table' => 'cvterm',
+      'field' => 'name',
+      'relationship' => 'none',
+    ),
+    'is_obsolete' => array(
+      'label' => 'Is Obsolete?',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'type' => 'yes-no',
+      'not' => 0,
+      'exclude' => 0,
+      'id' => 'is_obsolete',
+      'table' => 'library',
+      'field' => 'is_obsolete',
+      'relationship' => 'none',
+    ),
+    'num_features' => array(
+      'label' => 'Number of Features',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'num_features',
+      'table' => 'library',
+      'field' => 'num_features',
+      'relationship' => 'none',
+    ),
+  ));
+  $handler->override_option('filters', array(
+    'common_name' => array(
+      'operator' => '=',
+      'value' => 'All',
+      'group' => '0',
+      'exposed' => TRUE,
+      'expose' => array(
+        'use_operator' => 0,
+        'operator' => 'common_name_op',
+        'identifier' => 'organism_common_name',
+        'label' => 'Organism',
+        'optional' => 1,
+        'remember' => 0,
+      ),
+      'case' => 1,
+      'id' => 'common_name',
+      'table' => 'organism',
+      'field' => 'common_name',
+      'relationship' => 'none',
+    ),
+  ));
+  $handler->override_option('access', array(
+    'type' => 'perm',
+    'perm' => 'access chado_library content',
+  ));
+  $handler->override_option('cache', array(
+    'type' => 'none',
+  ));
+  $handler->override_option('title', 'Libraries');
+  $handler->override_option('empty', 'There are no libraries matching the current criteria. If you think there should be, check that all chado libraries are sync\'d with your website.');
+  $handler->override_option('empty_format', '1');
+  $handler->override_option('use_pager', '1');
+  $handler->override_option('style_plugin', 'table');
+  $handler->override_option('style_options', array(
+    'grouping' => '',
+    'override' => 1,
+    'sticky' => 0,
+    'order' => 'asc',
+    'columns' => array(
+      'name' => 'name',
+      'timeaccessioned' => 'timeaccessioned',
+      'timelastmodified' => 'timelastmodified',
+      'is_obsolete' => 'is_obsolete',
+      'name_1' => 'name_1',
+      'uniquename' => 'uniquename',
+      'common_name' => 'common_name',
+      'num_libraries' => 'num_libraries',
+    ),
+    'info' => array(
+      'name' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+      'timeaccessioned' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+      'timelastmodified' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+      'is_obsolete' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+      'name_1' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+      'uniquename' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+      'common_name' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+      'num_libraries' => array(
+        'separator' => '',
+      ),
+    ),
+    'default' => '-1',
+  ));
+  $handler = $view->new_display('page', 'Page', 'page_1');
+  $handler->override_option('path', 'libraries');
+  $handler->override_option('menu', array(
+    'type' => 'normal',
+    'title' => 'Sequence Libraries',
+    'description' => '',
+    'weight' => '0',
+    'name' => 'primary-links',
+  ));
+  $handler->override_option('tab_options', array(
+    'type' => 'none',
+    'title' => '',
+    'description' => '',
+    'weight' => 0,
+    'name' => 'navigation',
+  ));
+  $views[$view->name] = $view;
+
+  return $views;
+}

+ 68 - 64
tripal_natural_diversity/tripal_natural_diversity.api.inc

@@ -1,8 +1,12 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
-function tripal_natural_diversity_chado_nd_experiment_schema () {
+function tripal_natural_diversity_chado_nd_experiment_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment',
     'fields' => array(
@@ -48,13 +52,13 @@ function tripal_natural_diversity_chado_nd_experiment_schema () {
       'nd_experimentprop'
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experiment_contact_schema () {
+function tripal_natural_diversity_chado_nd_experiment_contact_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment_contact',
     'fields' => array(
@@ -92,13 +96,13 @@ function tripal_natural_diversity_chado_nd_experiment_contact_schema () {
 
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experiment_dbxref_schema () {
+function tripal_natural_diversity_chado_nd_experiment_dbxref_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment_dbxref',
     'fields' => array(
@@ -136,13 +140,13 @@ function tripal_natural_diversity_chado_nd_experiment_dbxref_schema () {
 
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experiment_genotype_schema () {
+function tripal_natural_diversity_chado_nd_experiment_genotype_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment_genotype',
     'fields' => array(
@@ -180,13 +184,13 @@ function tripal_natural_diversity_chado_nd_experiment_genotype_schema () {
 
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experiment_phenotype_schema () {
+function tripal_natural_diversity_chado_nd_experiment_phenotype_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment_phenotype',
     'fields' => array(
@@ -224,13 +228,13 @@ function tripal_natural_diversity_chado_nd_experiment_phenotype_schema () {
 
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experiment_project_schema () {
+function tripal_natural_diversity_chado_nd_experiment_project_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment_project',
     'fields' => array(
@@ -268,13 +272,13 @@ function tripal_natural_diversity_chado_nd_experiment_project_schema () {
 
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experiment_protocol_schema () {
+function tripal_natural_diversity_chado_nd_experiment_protocol_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment_protocol',
     'fields' => array(
@@ -312,13 +316,13 @@ function tripal_natural_diversity_chado_nd_experiment_protocol_schema () {
 
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experiment_pub_schema () {
+function tripal_natural_diversity_chado_nd_experiment_pub_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment_pub',
     'fields' => array(
@@ -356,13 +360,13 @@ function tripal_natural_diversity_chado_nd_experiment_pub_schema () {
 
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experiment_stock_schema () {
+function tripal_natural_diversity_chado_nd_experiment_stock_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment_stock',
     'fields' => array(
@@ -411,13 +415,13 @@ function tripal_natural_diversity_chado_nd_experiment_stock_schema () {
       'nd_experiment_stockprop',
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experiment_stockprop_schema () {
+function tripal_natural_diversity_chado_nd_experiment_stockprop_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment_stockprop',
     'fields' => array(
@@ -462,13 +466,13 @@ function tripal_natural_diversity_chado_nd_experiment_stockprop_schema () {
     'referring_tables' => array(
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experiment_stock_dbxref_schema () {
+function tripal_natural_diversity_chado_nd_experiment_stock_dbxref_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experiment_stock_dbxref',
     'fields' => array(
@@ -506,13 +510,13 @@ function tripal_natural_diversity_chado_nd_experiment_stock_dbxref_schema () {
 
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_experimentprop_schema () {
+function tripal_natural_diversity_chado_nd_experimentprop_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_experimentprop',
     'fields' => array(
@@ -557,13 +561,13 @@ function tripal_natural_diversity_chado_nd_experimentprop_schema () {
     'referring_tables' => array(
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_geolocation_schema () {
+function tripal_natural_diversity_chado_nd_geolocation_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_reagent',
     'fields' => array(
@@ -595,13 +599,13 @@ function tripal_natural_diversity_chado_nd_geolocation_schema () {
       'nd_geolocationprop'
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_geolocationprop_schema () {
+function tripal_natural_diversity_chado_nd_geolocationprop_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_geolocationprop',
     'fields' => array(
@@ -646,13 +650,13 @@ function tripal_natural_diversity_chado_nd_geolocationprop_schema () {
     'referring_tables' => array(
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_protocol_schema () {
+function tripal_natural_diversity_chado_nd_protocol_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_protocol',
     'fields' => array(
@@ -671,23 +675,23 @@ function tripal_natural_diversity_chado_nd_protocol_schema () {
     'referring_tables' => array(
       'nd_experiment_protocol',
       'nd_protocol_reagent',
-      'nd_protocolprop'  
+      'nd_protocolprop'
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_protocol_reagent_schema () {
+function tripal_natural_diversity_chado_nd_protocol_reagent_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_protocol_reagent',
     'fields' => array(
       'nd_protocol_reagent_id' => array(
         'type' => 'serial',
         'not null' => 1,
-      ),    
+      ),
       'nd_protocol_id' => array(
         'type' => 'int',
         'not null' => 1,
@@ -702,7 +706,7 @@ function tripal_natural_diversity_chado_nd_protocol_reagent_schema () {
       ),
     ),
     'primary key' => array(
-      '0' => 'nd_protocol_reagent_id',   
+      '0' => 'nd_protocol_reagent_id',
     ),
     'foreign keys' => array(
       'nd_protocol' => array(
@@ -725,16 +729,16 @@ function tripal_natural_diversity_chado_nd_protocol_reagent_schema () {
       ),
     ),
     'referring_tables' => array(
-    
+
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_protocolprop_schema () {
+function tripal_natural_diversity_chado_nd_protocolprop_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_protocolprop',
     'fields' => array(
@@ -779,13 +783,13 @@ function tripal_natural_diversity_chado_nd_protocolprop_schema () {
     'referring_tables' => array(
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_reagent_schema () {
+function tripal_natural_diversity_chado_nd_reagent_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_reagent',
     'fields' => array(
@@ -819,13 +823,13 @@ function tripal_natural_diversity_chado_nd_reagent_schema () {
       ),
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_reagent_relationship_schema () {
+function tripal_natural_diversity_chado_nd_reagent_relationship_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_reagent_relationship',
     'fields' => array(
@@ -865,13 +869,13 @@ function tripal_natural_diversity_chado_nd_reagent_relationship_schema () {
       ),
     ),
   );
-  
+
   return $description;
 }
 
-function tripal_natural_diversity_chado_nd_reagentprop_schema () {
+function tripal_natural_diversity_chado_nd_reagentprop_schema() {
   $description = array();
-  
+
   $description = array(
     'table' => 'nd_reagentprop',
     'fields' => array(
@@ -916,6 +920,6 @@ function tripal_natural_diversity_chado_nd_reagentprop_schema () {
     'referring_tables' => array(
     ),
   );
-  
+
   return $description;
 }

+ 11 - 10
tripal_natural_diversity/tripal_natural_diversity.module

@@ -5,9 +5,9 @@ require_once('tripal_natural_diversity.api.inc');
 /**
  *  @file
  * This file contains the basic functions needed for this drupal module.
- * The drupal tripal_natural_diversity module maps directly to the chado X module. 
+ * The drupal tripal_natural_diversity module maps directly to the chado X module.
  *
- * For documentation regarding the Chado X module: 
+ * For documentation regarding the Chado X module:
  * @see http://gmod.org/wiki/Chado_General_Module
  */
 
@@ -16,7 +16,7 @@ require_once('tripal_natural_diversity.api.inc');
  * Purpose: Essentially this hook tells drupal that there is views support for
  *  for this module which then includes tripal_natural_diversity.views.inc where all the
  *  views integration code is
- */ 
+ */
 function tripal_natural_diversity_views_api() {
    return array(
       'api' => 2.0,
@@ -30,11 +30,11 @@ function tripal_natural_diversity_theme() {
   return array(
     'tripal_feature_genotype_experiments' => array(
       'arguments' => array('node' => NULL),
-      'template' => 'tripal_feature-genotype_experiments',      
+      'template' => 'tripal_feature-genotype_experiments',
     ),
     'tripal_stock_genotype_experiments' => array(
       'arguments' => array('node' => NULL),
-      'template' => 'tripal_feature-stock_experiments',      
+      'template' => 'tripal_feature-stock_experiments',
     ),
   );
 }
@@ -42,17 +42,18 @@ function tripal_natural_diversity_theme() {
 /**
  *
  */
-function tripal_natural_diversity_nodeapi (&$node, $op, $teaser, $page) {
+function tripal_natural_diversity_nodeapi(&$node, $op, $teaser, $page) {
   switch ($op) {
     case 'view':
       if ($node->type == 'chado_feature') {
         $node->content['tripal_feature_genotype_experiments'] = array(
            '#value' => theme('tripal_feature_genotype_experiments', $node),
-        );      
-      } elseif ($node->type == 'chado_stock') {
+        );
+      }
+      elseif ($node->type == 'chado_stock') {
         $node->content['tripal_stock_genotype_experiments'] = array(
            '#value' => theme('tripal_stock_genotype_experiments', $node),
-        );      
+        );
       }
   }
-}
+}

+ 3 - 3
tripal_natural_diversity/tripal_natural_diversity.views.inc

@@ -80,12 +80,12 @@ function tripal_natural_diversity_views_handlers() {
      'path' => drupal_get_path('module', 'tripal_natural_diversity') . '/views/handlers',
    ),
    'handlers' => array(
-		'views_handler_field_chado_relationship_all' => array(
+  'views_handler_field_chado_relationship_all' => array(
        'parent' => 'views_handler_field_prerender_list',
      ),
-		'views_handler_field_chado_relationship_by_type' => array(
+  'views_handler_field_chado_relationship_by_type' => array(
        'parent' => 'views_handler_field_prerender_list',
      ),
    ),
  );
-}
+}

+ 105 - 0
tripal_natural_diversity/tripal_natural_diversity.views.inc.orig

@@ -0,0 +1,105 @@
+<?php
+
+/**
+ *  @file
+ *  This file contains the basic functions for views integration of
+ *  chado/tripal_natural_diversity tables. Supplementary functions can be found in
+ *  ./views/
+ *
+ *  Documentation on views integration can be found at
+ *  http://views2.logrus.com/doc/html/index.html.
+ */
+
+/*************************************************************************
+ * Implements hook_views_data()
+ * Purpose: Describe chado/tripal tables & fields to views
+ *
+ * @return: a data array which follows the structure outlined in the
+ *   views2 documentation for this hook. Essentially, it's an array of table
+ *   definitions keyed by chado/tripal table name. Each table definition
+ *   includes basic details about the table, fields in that table and
+ *   relationships between that table and others (joins)
+ */
+function tripal_natural_diversity_views_data()  {
+  $data = array();
+
+<<<<<<< HEAD
+  if (module_exists('tripal_views')) {
+    $tables = array(
+      'nd_experiment',
+      'nd_geolocation',
+      'nd_protocol',
+      'nd_reagent'
+    );
+    foreach ($tables as $tablename) {
+      if (!tripal_views_is_integrated($tablename, 10)) {
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        tripal_views_integration_add_entry($table_integration_array);
+      }
+    }
+
+    $tables = array(
+      'nd_experiment_contact',
+      'nd_experiment_dbxref',
+      'nd_experiment_genotype',
+      'nd_experiment_phenotype',
+      'nd_experiment_project',
+      'nd_experiment_protocol',
+      'nd_experiment_pub',
+      'nd_experiment_stock',
+      'nd_experiment_stock_dbxref',
+      'nd_experiment_stockprop',
+      'nd_experimentprop',
+      'nd_geolocationprop',
+      'nd_protocol_reagent',
+      'nd_protocolprop',
+      'nd_reagent_relationship',
+      'nd_reagentprop'
+    );
+    foreach ($tables as $tablename) {
+      if (!tripal_views_is_integrated($tablename, 10)) {
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        tripal_views_integration_add_entry($table_integration_array);
+      }
+    }
+  }
+=======
+  //EXPERIMENT
+  $data = array_merge($data, retrieve_nd_experiment_views_data());
+  $data = array_merge($data, retrieve_nd_experimentprop_views_data());
+
+  // GEOLOCATION
+  $data = array_merge($data, retrieve_nd_geolocation_views_data());
+  $data = array_merge($data, retrieve_nd_geolocationprop_views_data());
+
+  // REAGENTS
+  $data = array_merge($data, retrieve_nd_reagent_views_data());
+  $data = array_merge($data, retrieve_nd_reagentprop_views_data());
+>>>>>>> 6.x-0.4-dev
+
+  return $data;
+}
+
+/*************************************************************************
+ * Implements hook_views_handlers()
+ * Purpose: Register all custom handlers with views
+ *   where a handler describes either "the type of field",
+ *   "how a field should be filtered", "how a field should be sorted"
+ *
+ * @return: An array of handler definitions
+ */
+function tripal_natural_diversity_views_handlers() {
+ return array(
+   'info' => array(
+     'path' => drupal_get_path('module', 'tripal_natural_diversity') . '/views/handlers',
+   ),
+   'handlers' => array(
+  'views_handler_field_chado_relationship_all' => array(
+       'parent' => 'views_handler_field_prerender_list',
+     ),
+  'views_handler_field_chado_relationship_by_type' => array(
+       'parent' => 'views_handler_field_prerender_list',
+     ),
+   ),
+ );
+}

+ 36 - 30
tripal_organism/tripal_organism.api.inc

@@ -1,10 +1,15 @@
 <?php
- 
-/*************************************************************************
+
+/**
+ * @file
+ * Provides an API to tripal organisms
+ */
+
+/**
  * Purpose: Create an options array to be used in a form element
  *   which provides a list of all chado organisms
  *
- * @return an array(organism_id => common_name) 
+ * @return an array(organism_id => common_name)
  *   for each organism in the chado organism table
  *
  * @ingroup tripal_organism_api
@@ -13,7 +18,7 @@ function tripal_organism_get_organism_options() {
 
   $previous_db = tripal_db_set_active('chado');
   $result = db_query(
-    "SELECT organism_id, common_name FROM organism"
+    "SELECT organism_id, common_name FROM {organism}"
   );
   tripal_db_set_active($previous_db);
 
@@ -26,41 +31,42 @@ function tripal_organism_get_organism_options() {
 
 }
 
-/*************************************************************************
+/**
  * Purpose: Return a given organism object using the nid
  *
  * @return organism object created by node load
  *
  * @ingroup tripal_organism_api
  */
-function tripal_organism_get_organism_by_nid ($nid) {
+function tripal_organism_get_organism_by_nid($nid) {
+
+  return node_load($nid);
 
-	return node_load($nid);
-	
 }
 
-/*************************************************************************
+/**
  * Purpose: Return a given organism object using the organism id
  *
  * @return organism object created by node load
  *
  * @ingroup tripal_organism_api
  */
-function tripal_organism_get_organism_by_organism_id ($organism_id) {
-
-	$sql = "SELECT nid FROM {chado_organism} WHERE organism_id=%d";
-	$r = db_fetch_object(db_query($sql, $organism_id));
-	if (!empty($r->nid)) {
-		return node_load($r->nid);
-	} else {
-		drupal_set_message("Function: tripal_organism_get_organism_by_organism_id() -no organism with that organism id sync'd with drupal", 'error');
-	}
-	
-	return 0;
-	
+function tripal_organism_get_organism_by_organism_id($organism_id) {
+
+  $sql = "SELECT nid FROM {chado_organism} WHERE organism_id=%d";
+  $r = db_fetch_object(db_query($sql, $organism_id));
+  if (!empty($r->nid)) {
+    return node_load($r->nid);
+  }
+  else {
+    drupal_set_message("Function: tripal_organism_get_organism_by_organism_id() -no organism with that organism id sync'd with drupal", 'error');
+  }
+
+  return 0;
+
 }
 
-/****************************************************************************
+/*****
  * @section Chado Table Descriptions
  * There should be a default table description for all chado tables included
  * in core.
@@ -79,7 +85,7 @@ function tripal_organism_get_organism_by_organism_id ($organism_id) {
  */
 function tripal_organism_chado_organism_schema() {
   $description = array();
-  
+
   $referring_tables = array(
     'biomaterial',
     'feature',
@@ -91,7 +97,7 @@ function tripal_organism_chado_organism_schema() {
     'wwwuser_organism'
   );
   $description['referring_tables'] = $referring_tables;
-  
+
   return $description;
 }
 
@@ -108,21 +114,21 @@ function tripal_organism_chado_organism_schema() {
  */
 function tripal_organism_chado_organismprop_schema() {
   $description = array();
-  
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'type_id' => 'cvterm_id',
         ),
   );
-  
+
   $description['foreign keys']['organism'] = array(
         'table' => 'organism',
         'columns' => array(
           'organism_id' => 'organism_id',
         ),
   );
-  
+
   return $description;
 }
 /**
@@ -142,11 +148,11 @@ function tripal_organism_get_synced() {
    $org_list = array();
 
    // iterate through the organisms and build an array of those that are synced
-   while($org = db_fetch_object($orgs)){
+   while ($org = db_fetch_object($orgs)) {
       $previous_db = tripal_db_set_active('chado');  // use chado database
-      $info = db_fetch_object(db_query($csql,$org->organism_id));
+      $info = db_fetch_object(db_query($csql, $org->organism_id));
       tripal_db_set_active($previous_db);  // now use drupal database
       $org_list[] = $info;
-   }  
+   }
    return $org_list;
 }

+ 15 - 10
tripal_organism/tripal_organism.install

@@ -1,22 +1,27 @@
 <?php
 
+/**
+ * @file
+ * Functions pertaining to the install/uninstall of this module
+ */
+
 /**
 *  Implementation of hook_install();
 *
 * @ingroup tripal_organism
 */
-function tripal_organism_install(){
+function tripal_organism_install() {
 
    // create the module's data directory
    tripal_create_moddir('tripal_organism');
 
-   // create the directory where image files will be stored.  We create this 
+   // create the directory where image files will be stored.  We create this
    // here otherwise it will get created when the first organism is synced.
-   // The user that performs the syncing will receive ownership of the 
+   // The user that performs the syncing will receive ownership of the
    // images directory which may not allow for write access by the web server
    // user.  So, we create it here
    $dest = file_directory_path() . "/tripal/tripal_organism/images";
-   file_check_directory($dest,FILE_CREATE_DIRECTORY);
+   file_check_directory($dest, FILE_CREATE_DIRECTORY);
 
    // create the tables that correlate drupal nodes with chado
    // features, organisms, etc....
@@ -31,7 +36,7 @@ function tripal_organism_install(){
 */
 function tripal_organism_schema() {
    $schema = tripal_organism_get_schemas();
-	return $schema;
+  return $schema;
 }
 
 /**
@@ -39,7 +44,7 @@ function tripal_organism_schema() {
 *
 * @ingroup tripal_organism
 */
-function tripal_organism_uninstall(){
+function tripal_organism_uninstall() {
    drupal_uninstall_schema('tripal_organism');
 
    // Get the list of nodes to remove
@@ -52,11 +57,11 @@ function tripal_organism_uninstall(){
    }
 
    // remove the materialized views
-   
+
    // Remove the custom view if exists
    if (db_table_exists('tripal_organism_views_common_name')) {
       $sql = "DROP TABLE {tripal_organism_views_common_name}";
-      db_query ($sql);
+      db_query($sql);
    }
 }
 
@@ -68,7 +73,7 @@ function tripal_organism_uninstall(){
 *
 * @ingroup tripal_organism
 */
-function tripal_organism_get_schemas (){
+function tripal_organism_get_schemas() {
   $schema = array();
 
   $schema['chado_organism'] = array(
@@ -95,7 +100,7 @@ function tripal_organism_get_schemas (){
          'organism_id' => array('organism_id')
       ),
       'unique keys' => array(
-         'nid_vid' => array('nid','vid'),
+         'nid_vid' => array('nid', 'vid'),
          'vid' => array('vid')
       ),
       'primary key' => array('nid'),

File diff suppressed because it is too large
+ 230 - 222
tripal_organism/tripal_organism.module


+ 2 - 2
tripal_organism/tripal_organism.views.inc

@@ -88,7 +88,7 @@ function tripal_organism_views_handlers() {
  */
 function tripal_organism_views_data_alter(&$data) {
 
-  if( !(is_array($db_url) and array_key_exists('chado',$db_url)) ){
+  if ( !(is_array($db_url) and array_key_exists('chado', $db_url)) ) {
 
     // Add featuer relationship to node
     $data['node']['organism_chado_nid'] = array(
@@ -113,7 +113,7 @@ function tripal_organism_views_data_alter(&$data) {
  *
  * @ingroup tripal_organism_views
  */
-function tripal_organism_views_default_views () {
+function tripal_organism_views_default_views() {
   $views = array();
 
   // Main default view

+ 410 - 0
tripal_organism/tripal_organism.views.inc.orig

@@ -0,0 +1,410 @@
+<?php
+
+/**
+ *  @file
+ *  This file contains the basic functions for views integration of
+ *  chado/tripal organism tables. Supplementary functions can be found in
+ *  ./views/
+ *
+ *  Documentation on views integration can be found at
+ *  http://views2.logrus.com/doc/html/index.html.
+ */
+
+/**
+ * @defgroup tripal_organism_views Organism Views Integration
+ * @ingroup views
+ * @ingroup tripal_organism
+ */
+
+<<<<<<< HEAD
+=======
+require_once('views/organism.views.inc');
+require_once('views/chado_organism.views.inc');
+>>>>>>> 6.x-0.4-dev
+/**
+ * Implements hook_views_data()
+ * Purpose: Describe chado/tripal tables & fields to views
+ * @return: a data array which follows the structure outlined in the
+ *   views2 documentation for this hook. Essentially, it's an array of table
+ *   definitions keyed by chado/tripal table name. Each table definition
+ *   includes basic details about the table, fields in that table and
+ *   relationships between that table and others (joins)
+ *
+ * @ingroup tripal_organism_views
+ */
+function tripal_organism_views_data()  {
+  $data = array();
+
+<<<<<<< HEAD
+  if (module_exists('tripal_views')) {
+    // Base Table
+    $tables = array(
+      'organism'
+    );
+    foreach ($tables as $tablename) {
+      if (!tripal_views_is_integrated($tablename, 10)) {
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,TRUE);
+        tripal_views_integration_add_entry($table_integration_array);
+      }
+    }
+
+    // Additional Tables
+    $tables = array(
+      'organismprop',
+      'organism_dbxref'
+    );
+    foreach ($tables as $tablename) {
+      if (!tripal_views_is_integrated($tablename, 10)) {
+        $table_integration_array = tripal_views_get_integration_array_for_chado_table($tablename,FALSE);
+        tripal_views_integration_add_entry($table_integration_array);
+      }
+    }
+  }
+=======
+  $data = array_merge($data, retrieve_organism_views_data());
+  $data = array_merge($data, retrieve_chado_organism_views_data());
+>>>>>>> 6.x-0.4-dev
+
+  return $data;
+}
+
+/**
+ * Implements hook_views_handlers()
+ * Purpose: Register all custom handlers with views
+ *   where a handler describes either "the type of field",
+ *   "how a field should be filtered", "how a field should be sorted"
+ * @return: An array of handler definitions
+ *
+ * @ingroup tripal_organism_views
+ */
+function tripal_organism_views_handlers() {
+ return array(
+   'info' => array(
+     'path' => drupal_get_path('module', 'tripal_organism') . '/views/handlers',
+   ),
+   'handlers' => array(
+     'views_handler_field_computed_organism_nid' => array(
+       'parent' => 'views_handler_field_numeric',
+     ),
+     'views_handler_filter_organism_common_name' => array(
+      'parent' => 'views_handler_filter_string',
+     ),
+   ),
+ );
+}
+
+/**
+ * Implementation of hook_views_data_alter().
+ */
+function tripal_organism_views_data_alter(&$data) {
+
+  if ( !(is_array($db_url) and array_key_exists('chado', $db_url)) ) {
+
+    // Add featuer relationship to node
+    $data['node']['organism_chado_nid'] = array(
+      'group' => 'Organism',
+      'title' => 'Organism Node',
+      'help' => 'Links Chado Organism Fields/Data to the Nodes in the current View.',
+      'real field' => 'nid',
+      'relationship' => array(
+        'handler' => 'views_handler_relationship',
+        'title' => t('Node => Chado'),
+        'label' => t('Node => Chado'),
+        'real field' => 'nid',
+        'base' => 'chado_organism',
+        'base field' => 'nid'
+      ),
+    );
+  }
+
+}
+
+/**
+ *
+ * @ingroup tripal_organism_views
+ */
+function tripal_organism_views_default_views() {
+  $views = array();
+
+  // Main default view
+  // List all cvterms based on cv
+  $view = new view;
+  $view->name = 'all_organisms';
+  $view->description = 'A listing of all organism in chado';
+  $view->tag = 'chado';
+  $view->view_php = '';
+  $view->base_table = 'organism';
+  $view->is_cacheable = FALSE;
+  $view->api_version = 2;
+  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
+  $handler = $view->new_display('default', 'Defaults', 'default');
+  $handler->override_option('fields', array(
+    'common_name' => array(
+      'label' => 'Common Name',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 1,
+      'exclude' => 0,
+      'id' => 'common_name',
+      'table' => 'organism',
+      'field' => 'common_name',
+      'relationship' => 'none',
+    ),
+    'abbreviation' => array(
+      'label' => 'Abbreviation',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'link_to_node' => 0,
+      'exclude' => 0,
+      'id' => 'abbreviation',
+      'table' => 'organism',
+      'field' => 'abbreviation',
+      'relationship' => 'none',
+    ),
+    'genus' => array(
+      'label' => 'Genus',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'genus',
+      'table' => 'organism',
+      'field' => 'genus',
+      'relationship' => 'none',
+    ),
+    'species' => array(
+      'label' => 'Species',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'species',
+      'table' => 'organism',
+      'field' => 'species',
+      'relationship' => 'none',
+    ),
+    'num_features' => array(
+      'label' => 'Number of Features',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'num_features',
+      'table' => 'organism',
+      'field' => 'num_features',
+      'relationship' => 'none',
+    ),
+    'num_stocks' => array(
+      'label' => 'Number of Stocks',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'num_stocks',
+      'table' => 'organism',
+      'field' => 'num_stocks',
+      'relationship' => 'none',
+    ),
+    'num_libraries' => array(
+      'label' => 'Number of Libraries',
+      'alter' => array(
+        'alter_text' => 0,
+        'text' => '',
+        'make_link' => 0,
+        'path' => '',
+        'link_class' => '',
+        'alt' => '',
+        'prefix' => '',
+        'suffix' => '',
+        'target' => '',
+        'help' => '',
+        'trim' => 0,
+        'max_length' => '',
+        'word_boundary' => 1,
+        'ellipsis' => 1,
+        'html' => 0,
+        'strip_tags' => 0,
+      ),
+      'empty' => '',
+      'hide_empty' => 0,
+      'empty_zero' => 0,
+      'exclude' => 0,
+      'id' => 'num_libraries',
+      'table' => 'organism',
+      'field' => 'num_libraries',
+      'relationship' => 'none',
+    ),
+  ));
+  $handler->override_option('access', array(
+    'type' => 'perm',
+    'perm' => 'access chado_organism content',
+  ));
+  $handler->override_option('cache', array(
+    'type' => 'none',
+  ));
+  $handler->override_option('title', 'Organisms');
+  $handler->override_option('empty', 'No organism currently in your chado database.');
+  $handler->override_option('empty_format', '1');
+  $handler->override_option('items_per_page', 0);
+  $handler->override_option('style_plugin', 'table');
+  $handler->override_option('style_options', array(
+    'grouping' => '',
+    'override' => 1,
+    'sticky' => 0,
+    'order' => 'asc',
+    'columns' => array(
+      'abbreviation' => 'abbreviation',
+      'common_name' => 'common_name',
+      'genus' => 'genus',
+      'species' => 'species',
+    ),
+    'info' => array(
+      'abbreviation' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+      'common_name' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+      'genus' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+      'species' => array(
+        'sortable' => 0,
+        'separator' => '',
+      ),
+    ),
+    'default' => '-1',
+  ));
+  $handler = $view->new_display('page', 'Page', 'page_1');
+  $handler->override_option('path', 'organisms');
+  $handler->override_option('menu', array(
+    'type' => 'normal',
+    'title' => 'Organisms',
+    'description' => '',
+    'weight' => '0',
+    'name' => 'primary-links',
+  ));
+  $handler->override_option('tab_options', array(
+    'type' => 'none',
+    'title' => '',
+    'description' => '',
+    'weight' => 0,
+    'name' => 'navigation',
+  ));
+  $views[$view->name] = $view;
+
+  return $views;
+}

+ 4 - 4
tripal_phenotype/tripal_phenotype.module

@@ -3,9 +3,9 @@
 /**
  *  @file
  * This file contains the basic functions needed for this drupal module.
- * The drupal tripal_phenotype module maps directly to the chado X module. 
+ * The drupal tripal_phenotype module maps directly to the chado X module.
  *
- * For documentation regarding the Chado X module: 
+ * For documentation regarding the Chado X module:
  * @see http://gmod.org/wiki/Chado_General_Module
  */
 
@@ -14,9 +14,9 @@
  * Purpose: Essentially this hook tells drupal that there is views support for
  *  for this module which then includes tripal_phenotype.views.inc where all the
  *  views integration code is
- */ 
+ */
 function tripal_phenotype_views_api() {
    return array(
       'api' => 2.0,
    );
-}
+}

+ 38 - 33
tripal_project/tripal_project.admin.inc

@@ -1,54 +1,58 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
-function tripal_project_administration_description_page () {
+function tripal_project_administration_description_page() {
  $output = '';
- 
- 
+
+
  return $output;
 }
 
-function tripal_project_configuration_page () {
+function tripal_project_configuration_page() {
   $output = '';
-  
+
   $output .= drupal_get_form('tripal_project_sync_projects_form');
-  
+
   return $output;
 }
 
-function tripal_project_sync_projects_form ($form_state = NULL) {
+function tripal_project_sync_projects_form($form_state = NULL) {
   $form = array();
-  
+
   $form['sync'] = array(
     '#type' => 'fieldset',
     '#title' => 'Sync Projects'
   );
-  
+
   $form['sync']['description'] = array(
     '#type' => 'item',
     '#value' => 'Many of the details for projects are stored in chado. Often other tripal '
       .'modules may create projects as a means of grouping data together. Sync\'ing projects '
       .'in chado created drupal pages (known as nodes) which display the data to priviledged users.'
   );
-  
+
   $form['sync']['submit'] = array(
     '#type' => 'submit',
     '#value' => 'Sync All Projects',
-    
+
   );
-  
+
   return $form;
 }
 
-function tripal_project_sync_projects_form_submit ($form, &$form_state) {
+function tripal_project_sync_projects_form_submit($form, &$form_state) {
   global $user;
-  
+
   //sync'ing is done by a tripal_job that is added here
-  $job_id = tripal_add_job('Sync Projects', 'tripal_project', 
-	'tripal_project_sync_all_projects', array(), $user->uid);
+  $job_id = tripal_add_job('Sync Projects', 'tripal_project',
+  'tripal_project_sync_all_projects', array(), $user->uid);
 
 }
 
-function tripal_project_sync_all_projects () {
+function tripal_project_sync_all_projects() {
 
   //retrieve all projects in drupal
   $resource = db_query('SELECT project_id FROM {chado_project}');
@@ -56,11 +60,11 @@ function tripal_project_sync_all_projects () {
   while ($r = db_fetch_object($resource)) {
     $drupal_projects[$r->project_id] = $r->project_id;
   }
-  
+
   // retrieve all projects in chado
   $chado_projects = array();
   $previous_db = tripal_db_set_active('chado');
-  $resource = db_query('SELECT project_id FROM project');
+  $resource = db_query('SELECT project_id FROM {project}');
   tripal_db_set_active($previous_db);
   while ($r = db_fetch_object($resource)) {
     // if not already in drupal add to list to be sync'd
@@ -68,12 +72,12 @@ function tripal_project_sync_all_projects () {
       $chado_projects[$r->project_id] = $r->project_id;
     }
   }
-  
-  print 'Number of Projects to Sync: '.sizeof($chado_projects)."\n";
-  
+
+  print 'Number of Projects to Sync: ' . sizeof($chado_projects) . "\n";
+
   foreach ($chado_projects as $project_id) {
-    $project = tripal_core_chado_select('project',array('name','description'),array('project_id'=>$project_id));
-    
+    $project = tripal_core_chado_select('project', array('name', 'description'), array('project_id' => $project_id));
+
     // create node
     $new_node = new stdClass();
     $new_node->type = 'chado_project';
@@ -83,18 +87,19 @@ function tripal_project_sync_all_projects () {
     $new_node->description = $project[0]->description;
     node_validate($new_node);
     $errors = form_get_errors();
-    if(!$errors){
+    if (!$errors) {
       $node = node_submit($new_node);
       node_save($node);
-      if($node->nid){
-         print "Added ".$project[0]->name." (Node ID:".$node->nid.")\n";
+      if ($node->nid) {
+         print "Added " . $project[0]->name . " (Node ID:" . $node->nid . ")\n";
       }
-    } else {
-      print "Failed to insert project: ".$project[0]->name."\n";
-      print "Errors: ".print_r($errors, TRUE)."\n";
     }
-    
+    else {
+      print "Failed to insert project: " . $project[0]->name . "\n";
+      print "Errors: " . print_r($errors, TRUE) . "\n";
+    }
+
   }
-  
-  
+
+
 }

+ 33 - 34
tripal_project/tripal_project.install

@@ -1,11 +1,10 @@
 <?php
-// $Id$
 
 /**
  * @file
  * This file contains all the functions which describe and implement drupal database tables
- * needed by this module. This module was developed by Chad N.A. Krilow and Lacey-Anne Sanderson, 
- * University of Saskatchewan. 
+ * needed by this module. This module was developed by Chad N.A. Krilow and Lacey-Anne Sanderson,
+ * University of Saskatchewan.
  *
  * The project manamgenet module allows you to sync data in a chado/Tripal instance with
  * multiple project/mysql instances as well as manage and create such project instances
@@ -15,14 +14,14 @@
  * Implementation of hook_install()
  */
 function tripal_project_install() {
-	drupal_install_schema('tripal_project');
+  drupal_install_schema('tripal_project');
 }
 
 /**
- * Implementation of hook_uninstall() 
+ * Implementation of hook_uninstall()
  */
 function tripal_project_uninstall() {
-	drupal_uninstall_schema('tripal_project');
+  drupal_uninstall_schema('tripal_project');
 }
 
 /**
@@ -30,37 +29,37 @@ function tripal_project_uninstall() {
  */
 function tripal_project_schema() {
 
-	//specification for 'tripal_project_instances'
-	$schema['chado_project'] = array(
-		
-		'fields' => array(
-      
-	    //a int field that cannot be null and acts as a unique identifier for all nid's
+  //specification for 'tripal_project_instances'
+  $schema['chado_project'] = array(
+
+    'fields' => array(
+
+      //a int field that cannot be null and acts as a unique identifier for all nid's
       'nid' => array(
-				'type' => 'int',
-				'unsigned' => TRUE,
-				'not null' => TRUE,
- 	 	  ),
-		
-	    //a int field that cannot be null and is vid 	  
-  		'vid' => array(
-   	   	'type' => 'int',
-   	   	'not null' => TRUE,
-  	  ),
-   	 	
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        ),
+
+      //a int field that cannot be null and is vid
+      'vid' => array(
+          'type' => 'int',
+          'not null' => TRUE,
+      ),
+
       //a intfield, not null and project_id is the unique_id of the project in chado
-    	 'project_id' => array(
-   	   	'type' => 'int',
-   	   	'unsigned' => TRUE,
-   	   	'not null' => TRUE,
-    	),
-    	 	
-  	  	
+       'project_id' => array(
+          'type' => 'int',
+          'unsigned' => TRUE,
+          'not null' => TRUE,
+      ),
+
+
     ),//end of shema
-  	
-  	'primary key' => array('nid','vid','project_id'),
-	
-	);
+
+    'primary key' => array('nid', 'vid', 'project_id'),
+
+  );
 
   return $schema;
 }

+ 58 - 58
tripal_project/tripal_project.module

@@ -5,9 +5,9 @@ require('tripal_project.admin.inc');
 /**
  *  @file
  * This file contains the basic functions needed for this drupal module.
- * The drupal tripal_project module maps directly to the chado general module. 
+ * The drupal tripal_project module maps directly to the chado general module.
  *
- * For documentation regarding the Chado General module: 
+ * For documentation regarding the Chado General module:
  * @see http://gmod.org/wiki/Chado_General_Module
  */
 
@@ -23,7 +23,7 @@ require('tripal_project.admin.inc');
  *  for this module which then includes tripal_project.views.inc where all the
  *  views integration code is
  *
- */ 
+ */
 function tripal_project_views_api() {
    return array(
       'api' => 2.0,
@@ -39,15 +39,15 @@ function tripal_project_menu() {
     'page callback' => 'tripal_project_administration_description_page',
     'access arguments' => array('administer site configuration'),
     'type' => MENU_NORMAL_ITEM
-  ); 
+  );
 
   $items[ 'admin/tripal/tripal_project/configuration' ]= array(
     'title' => t('Configuration'),
     'page callback' => 'tripal_project_configuration_page',
     'access arguments' => array('administer site configuration'),
     'type' => MENU_NORMAL_ITEM
-  ); 
-  
+  );
+
   return $items;
 }
 
@@ -62,7 +62,7 @@ function tripal_project_perm() {
 
   return array(
     'access chado_projects',
-    'create chado_projects', 
+    'create chado_projects',
     'edit own chado_projects'
   );
 }
@@ -76,10 +76,10 @@ function tripal_project_perm() {
  *    The operation that is to be performed
  *
  *  @parm $node
- *    The specific node that is to have the operation performed  
+ *    The specific node that is to have the operation performed
  *
  *  @parm $account
- *    The account of the user that is performing the operations  
+ *    The account of the user that is performing the operations
  *
  *  @return
  *    True if a operation was performed
@@ -88,29 +88,29 @@ function tripal_project_perm() {
 function chado_project_access($op, $node, $account) {
 
   if ($op == 'create') {
-  
+
     // Only users with permission to do so may create this node type.
-    if(!user_access('create chado_projects', $account)){
+    if (!user_access('create chado_projects', $account)) {
       return FALSE;
     }
   }
 
   // Users who create a node may edit or delete it later, assuming they have the necessary permissions.
   if ($op == 'update' || $op == 'delete') {
-  
-    if(!user_access('edit own chado_projects',$account)){
+
+    if (!user_access('edit own chado_projects', $account)) {
        return FALSE;
     }
-    if(user_access('edit own chado_projects',$account) &&
-       $account->uid != $node->uid){
+    if (user_access('edit own chado_projects', $account) &&
+       $account->uid != $node->uid) {
       return FALSE;
     }
   }
-  
+
   if ($op == 'view') {
-    if(!user_access('access chado_projects', $account)){
+    if (!user_access('access chado_projects', $account)) {
       return FALSE;
-    }  
+    }
   }
   return NULL;
 }
@@ -133,10 +133,10 @@ function tripal_project_node_info() {
       'name' => t('Project'),
       'module' => 'chado_project',
       'description' => t('A module for interfacing the GMOD chado database with Drupal, providing viewing of projects'),
-    	'has_title' => TRUE,
-    	'title_label' =>t('Project Name'),
-    	'had_body' => TRUE,
-    	'body_label' =>t('Full Description'),
+      'has_title' => TRUE,
+      'title_label' => t('Project Name'),
+      'had_body' => TRUE,
+      'body_label' => t('Full Description'),
     )
   );
 }
@@ -150,7 +150,7 @@ function tripal_project_node_info() {
 *    The initialized node
 *
 *  @parm $form_state
-*    The state of the form, that has the user entered information that is neccessary for adding 
+*    The state of the form, that has the user entered information that is neccessary for adding
 *    information to the project
 *
 *  @return $form
@@ -174,15 +174,15 @@ function chado_project_form(&$node, $form_state) {
     '#maxlength' => 255,
     '#title' => 'Short Description',
     '#default_value' => $node->project->description,
-  ); 
-  
+  );
+
   $form['body_filter']['body'] = array(
     '#type' => 'textarea',
     '#title' => check_plain($type->body_label),
     '#default_value' => $node->body,
   );
   $form['body_filter']['filter'] = filter_form($node->format);
-  
+
   // whether or not the project exists in chado
   $form['project_id'] = array(
     '#type' => 'value',
@@ -200,21 +200,21 @@ function chado_project_form(&$node, $form_state) {
 *
 */
 function chado_project_insert($node) {
-		
-	$values =  array(
+
+  $values =  array(
      'name' => $node->title,
      'description' => $node->description,
    );
-   
+
    if (!$node->project_id) {
      //inserts info into chado table.
-     $result = tripal_core_chado_insert('project',$values);
+     $result = tripal_core_chado_insert('project', $values);
      $node->project_id = $result['project_id'];
-  } 
-  
-	//inserts the row of vid,nid,project_id into the chado_project table
+  }
+
+  //inserts the row of vid,nid,project_id into the chado_project table
   db_query("INSERT INTO {chado_project} (vid, nid, project_id) VALUES (%d, %d, %d)", $node->vid, $node->nid, $node->project_id);
-  
+
 }
 
 /**
@@ -222,19 +222,19 @@ function chado_project_insert($node) {
 * Implementation of hook_delete().
 *
 * @param $node
-* The node which is to be deleted, only chado project and chado_project need to be dealt with 
+* The node which is to be deleted, only chado project and chado_project need to be dealt with
 * since the drupal node is deleted automagically
 *
 */
 function chado_project_delete($node) {
   // Notice that we're matching all revision, by using the node's nid.
-  
+
   // Find the project to delete
   $values =  array(
      'project_id' => $node->project->project_id,
    );
-  tripal_core_chado_delete('project',$values);
-  
+  tripal_core_chado_delete('project', $values);
+
   //deleteing in drupal chado_project table
   db_query('DELETE FROM {chado_project} WHERE nid = %d', $node->nid);
 
@@ -248,20 +248,20 @@ function chado_project_delete($node) {
 *  pertaining to the specific project
 *
 */
-function chado_project_update($node){
-	
-	// Find the project to update
-	$match= array(
-		'project_id'=>$node->project_id,
-	);
-	
-	// New values
-	$values =  array(
+function chado_project_update($node) {
+
+  // Find the project to update
+  $match= array(
+    'project_id' => $node->project_id,
+  );
+
+  // New values
+  $values =  array(
     'name' => $node->title,
     'description' => $node->description,
   );
 
-  $result = tripal_core_chado_update('project',$match,$values);
+  $result = tripal_core_chado_update('project', $match, $values);
 
 }
 
@@ -277,17 +277,17 @@ function chado_project_update($node){
 */
 function chado_project_load($node) {
 
-	//selecting the coresponding table information
-	$result = db_fetch_object(db_query('SELECT * FROM {chado_project} WHERE nid=%d AND vid=%d',$node->nid, $node->vid));
-	
-	//assigning the project-Id to a variable
-	$values = array(
-	  'project_id' => $result->project_id,
+  //selecting the coresponding table information
+  $result = db_fetch_object(db_query('SELECT * FROM {chado_project} WHERE nid=%d AND vid=%d', $node->nid, $node->vid));
+
+  //assigning the project-Id to a variable
+  $values = array(
+    'project_id' => $result->project_id,
   );
-	
-	//the current project set to the 'project' with the $values(project-Id)
-  $node->project = tripal_core_generate_chado_var('project',$values);
-  
+
+  //the current project set to the 'project' with the $values(project-Id)
+  $node->project = tripal_core_generate_chado_var('project', $values);
+
   return $node;
 
 }

+ 47 - 48
tripal_pub/tripal_pub.install

@@ -1,11 +1,10 @@
 <?php
-// $Id$
 
 /**
  * @file
  * This file contains all the functions which describe and implement drupal database tables
- * needed by this module. This module was developed by Chad N.A. Krilow and Lacey-Anne Sanderson, 
- * University of Saskatchewan. 
+ * needed by this module. This module was developed by Chad N.A. Krilow and Lacey-Anne Sanderson,
+ * University of Saskatchewan.
  *
  * The project manamgenet module allows you to sync data in a chado/Tripal instance with
  * multiple project/mysql instances as well as manage and create such project instances
@@ -17,23 +16,23 @@
  */
 function tripal_pub_install() {
 
-	drupal_install_schema('tripal_pub');
-	$dbxref = array('accession' => 'abstract', 'db_id'=>array('name'=>'tripal'));
-	$success = tripal_core_chado_insert('dbxref',$dbxref);
-	if ($success) {
-		tripal_core_chado_insert('cvterm',array('name'=>'abstract','cv_id'=>array('name'=>'tripal'), 'db
-xref_id'=>$dbxref));
-	}
+  drupal_install_schema('tripal_pub');
+  $dbxref = array('accession' => 'abstract', 'db_id' => array('name' => 'tripal'));
+  $success = tripal_core_chado_insert('dbxref', $dbxref);
+  if ($success) {
+    tripal_core_chado_insert('cvterm', array('name' => 'abstract', 'cv_id' => array('name' => 'tripal'), 'db
+xref_id' => $dbxref));
+  }
 }
 
 
 /**
- * Implementation of hook_uninstall() 
+ * Implementation of hook_uninstall()
  */
 function tripal_pub_uninstall() {
-	//Remove tables
-	drupal_uninstall_schema('tripal_pub');
-	
+  //Remove tables
+  drupal_uninstall_schema('tripal_pub');
+
 }
 
 
@@ -42,49 +41,49 @@ function tripal_pub_uninstall() {
  */
 function tripal_pub_schema() {
 //specification for 'tripal_pub_instances'
-	$schema['chado_pub'] = array(
-		
-		'fields' => array(
-      
-	    //a int field that cannot be null and acts as a unique identifier for all nid's
+  $schema['chado_pub'] = array(
+
+    'fields' => array(
+
+      //a int field that cannot be null and acts as a unique identifier for all nid's
       'nid' => array(
-				'type' => 'int',
-				'unsigned' => TRUE,
-				'not null' => TRUE,
- 	 	  ),
-		
-	    //a int field that cannot be null and is vid 	  
-  		'vid' => array(
-   	   	'type' => 'int',
-   	   	'not null' => TRUE,
-  	  ),
-   	 	
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        ),
+
+      //a int field that cannot be null and is vid
+      'vid' => array(
+          'type' => 'int',
+          'not null' => TRUE,
+      ),
+
       //a intfield, not null and project_id is the unique_id of the project in chado
-    	 'pub_id' => array(
-   	   	'type' => 'int',
-   	   	'unsigned' => TRUE,
-   	   	'not null' => TRUE,
-    	),	
-    	
-    	 //a intfield, not null and project_id is the unique_id of the project in chado
-    	 'pubmed_id' => array(
-   	   	'type' => 'int',
-   	   	'unsigned' => TRUE,
-   	   	'not null' => FALSE,
-    	),
-    	'author' => array(
+       'pub_id' => array(
+          'type' => 'int',
+          'unsigned' => TRUE,
+          'not null' => TRUE,
+      ),
+
+       //a intfield, not null and project_id is the unique_id of the project in chado
+       'pubmed_id' => array(
+          'type' => 'int',
+          'unsigned' => TRUE,
+          'not null' => FALSE,
+      ),
+      'author' => array(
         'type' => 'text',
         'size' => 'normal',
         'not null' => TRUE,
         'default' => '',
         'description' => 'The Author Name.',
       ),
-  	 ), 	
+     ),
      //end of shema
-  	
-  	'primary key' => array('nid'),
-	
-	);
+
+    'primary key' => array('nid'),
+
+  );
 
   return $schema;
 }

File diff suppressed because it is too large
+ 487 - 486
tripal_pub/tripal_pub.module


+ 20 - 15
tripal_search/tripal_search.module

@@ -1,13 +1,18 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
+
 //
 // Copyright 2009 Clemson University
 //
 /*******************************************************************************
  * Tripal Search initiation
  ******************************************************************************/
-function tripal_search_init(){
+function tripal_search_init() {
    // Add javascript
-   drupal_add_js(drupal_get_path('theme', 'tripal').
+   drupal_add_js(drupal_get_path('theme', 'tripal') .
                                   '/js/tripal_search.js');
 }
 /*******************************************************************************
@@ -35,11 +40,11 @@ function tripal_search_form_alter(&$form, $form_state, $form_id) {
   if ($form_id == 'search_form' && arg(2)) {
     // for pagination etc.
     $get = drupal_query_string_encode($_GET, array('q'));
-    if(preg_match("/node/",arg(1))){
+    if (preg_match("/node/", arg(1))) {
       $form['basic']['inline']['fasta'] = array('#type' => 'markup',
           '#value' => "<br><br><a id=\"tripal_search_link\" href=\"".
                       url('tripal_search/'. arg(1) .'/'. urlencode(search_get_keys()),
-                      array('query' => trim($get)?$get:NULL)).
+                      array('query' => trim($get)?$get:NULL)) .
                       "\">Download features (multi-FASTA format)</a><br><br>");
 
     }
@@ -58,8 +63,8 @@ function tripal_search_view() {
     return drupal_not_found();
   }
 
-  if (trim($keys)) {  	
-    $results = tripal_do_search($keys,$type);    //var_dump($pager_total['0']);
+  if (trim($keys)) {
+    $results = tripal_do_search($keys, $type);    //var_dump($pager_total['0']);
     return tripal_search_file($type, $keys, $results);
   }
 }
@@ -71,24 +76,24 @@ function tripal_search_file($type, $keys, $results) {
 
   drupal_set_header('Content-Type: text');
   drupal_set_header('Content-Disposition: attachment; filename="searchresults.fasta"');
-	
+
   foreach ($results as $result) {
     // Get feature id from drupal database
     $sqld = "SELECT * FROM {chado_feature} CF INNER JOIN {node} N on N.nid = CF.nid WHERE CF.nid = %d";
-    if($f_objd = db_fetch_object(db_query($sqld, $result->sid))){
+    if ($f_objd = db_fetch_object(db_query($sqld, $result->sid))) {
 
        // Get sequence from chado database
        $previous_db = tripal_db_set_active('chado');  // use chado database
        $sqlc = "SELECT * FROM {feature} WHERE feature_id = '%s'";
-       $f_objc = db_fetch_object(db_query($sqlc,$f_objd->feature_id));
+       $f_objc = db_fetch_object(db_query($sqlc, $f_objd->feature_id));
        tripal_db_set_active($previous_db);  // now use drupal database
        print tripal_feature_return_fasta($f_objc, $desc);
-    } 
+    }
   }
 }
 
 /*******************************************************************************
- *  This code is a duplicate of the do_search function but with the paging 
+ *  This code is a duplicate of the do_search function but with the paging
  *  call replaced by a simle db_query call.
  */
 function tripal_do_search($keywords, $type, $join1 = '', $where1 = '1 = 1', $arguments1 = array(), $columns2 = 'i.relevance AS score', $join2 = '', $arguments2 = array(), $sort_parameters = 'ORDER BY score DESC') {
@@ -117,7 +122,7 @@ function tripal_do_search($keywords, $type, $join1 = '', $where1 = '1 = 1', $arg
   }
 
   // Calculate maximum keyword relevance, to normalize it.
-  $select = "SELECT SUM(i.score * t.count) AS score FROM {search_index} i $join WHERE $conditions GROUP BY i.type, i.sid HAVING COUNT(*) >= %d ORDER BY score DESC";
+  $select = "SELECT SUM(i.score * t.count) AS score FROM {search_index} i " . $join . " WHERE $conditions GROUP BY i.type, i.sid HAVING COUNT(*) >= %d ORDER BY score DESC";
   $arguments = array_merge($arguments1, array($query[4]));
   $normalize = db_result(db_query_range($select, $arguments, 0, 1));
   if (!$normalize) {
@@ -126,13 +131,13 @@ function tripal_do_search($keywords, $type, $join1 = '', $where1 = '1 = 1', $arg
   $columns2 = str_replace('i.relevance', '('. (1.0 / $normalize) .' * SUM(i.score * t.count))', $columns2);
 
   // Build query to retrieve results.
-  $select = "SELECT i.type, i.sid, $columns2 FROM {search_index} i $join $join2 WHERE $conditions GROUP BY i.type, i.sid HAVING COUNT(*) >= %d";
+  $select = "SELECT i.type, i.sid, $columns2 FROM {search_index} i " . $join . " " . $join2 . " WHERE $conditions GROUP BY i.type, i.sid HAVING COUNT(*) >= %d";
   $count_select =  "SELECT COUNT(*) FROM ($select) n1";
   $arguments = array_merge($arguments2, $arguments1, array($query[4]));
- 
+
   // Do actual search query
 //  $result = pager_query("$select $sort_parameters", 10, 0, $count_select, $arguments);
-  $result = db_query("$select $sort_parameters",$arguments);
+  $result = db_query("$select $sort_parameters", $arguments);
   $results = array();
   while ($item = db_fetch_object($result)) {
     $results[] = $item;

+ 34 - 27
tripal_stock/other_module_api_functions.inc

@@ -1,4 +1,8 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 ///////////////////////////////////////////////////////////////////////////
 // Module: tripal_core
@@ -11,43 +15,46 @@
  * @params tablename: the name of the chado table you want to select the max rank from
  *    this table must contain a rank column of type integer
  * @params where_options: array(
- *													<column_name> => array(
- *														'type' => <type of column: INT/STRING>,
- *														'value' => <the value you want to filter on>,
- *														'exact' => <if TRUE use =; if FALSE use ~>,
- *													)
- *				)
+ *                          <column_name> => array(
+ *                            'type' => <type of column: INT/STRING>,
+ *                            'value' => <the value you want to filter on>,
+ *                            'exact' => <if TRUE use =; if FALSE use ~>,
+ *                          )
+ *        )
  *     where options should include the id and type for that table to correctly
  *     group a set of records together where the only difference are the value and rank
  * @return the maximum rank
  *
  */
-function get_max_chado_rank ($tablename, $where_options) {
+function get_max_chado_rank($tablename, $where_options) {
+
+  $where= array();
+  //generate the where clause from supplied options
+  // the key is the column name
+  foreach ($where_options as $key => $val_array) {
+    if (preg_match('/INT/', $val_array['type'])) {
+      $where[] = $key . "=" . $val_array['value'];
+    }
+     else {
+      if ($val_array['exact']) {
+      $operator='='; }
+      else { $operator='~'; }
+      $where[] = $key . $operator . "'" . $val_array['value'] . "'";
+    }
+  }
 
-	$where= array();
-	//generate the where clause from supplied options
-	// the key is the column name
-	foreach ($where_options as $key => $val_array) {
-		if (preg_match('/INT/', $val_array['type'])) {
-			$where[] = $key."=".$val_array['value'];
-		} else {
-			if ($val_array['exact']) { $operator='='; }
-			else { $operator='~'; }
-			$where[] = $key.$operator."'".$val_array['value']."'";
-		}
-	}
-	
   $previous_db = tripal_db_set_active('chado');
   $result = db_fetch_object(db_query(
     "SELECT max(rank) as max_rank, count(rank) as count FROM %s WHERE %s",
     $tablename,
-    implode(' AND ',$where)
+    implode(' AND ', $where)
   ));
   tripal_db_set_active($previous_db);
-	//drupal_set_message("Max Rank Query=SELECT max(rank) as max_rank, count(rank) as count FROM ".$tablename." WHERE ".implode(' AND ',$where));
-	if ($result->count > 0) {
-	  return $result->max_rank;
-	} else {
-		return -1;
-	}
+  //drupal_set_message("Max Rank Query=SELECT max(rank) as max_rank, count(rank) as count FROM ".$tablename." WHERE ".implode(' AND ',$where));
+  if ($result->count > 0) {
+    return $result->max_rank;
+  }
+  else {
+    return -1;
+  }
 }

+ 119 - 110
tripal_stock/tripal_stock-administration.inc

@@ -1,5 +1,8 @@
 <?php
-// $Id$
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
  * Purpose: Provide Guidance to new Tripal Admin
@@ -11,46 +14,46 @@
  */
 function tripal_stock_module_description_page() {
   $text = '';
-  
+
   $text = '<h3>Tripal Stock Administrative Tools Quick Links</h3>';
     $text .= '<ul>';
-      $text .= '<li>'.l('Configuration', 'admin/tripal/tripal_stock/configuration').'</li>';
-      $text .= '<li>'.l('Stock Listing', 'stocks').'</li>';
+      $text .= '<li>' . l('Configuration', 'admin/tripal/tripal_stock/configuration') . '</li>';
+      $text .= '<li>' . l('Stock Listing', 'stocks') . '</li>';
     $text .= '</ul>';
-    
+
   $text .= '<h3>Module Description:</h3>';
   //================================================================================
   $text .= '<p>The Tripal Stock Module provides functionality for adding, editing, deleting and accessing chado stocks. The stock module was designed to store information about stock collections in a laboratory. What is called a stock could also be called a strain or an accession. There is a lot in common between a Drosophila stock and a Saccharomyces strain and an Arabidopsis line. They all come from some taxon, have genotypes, physical locations in the lab, some conceivable relationship with a publication, some conceivable relationship with a sequence feature (such as a transgene), and could be described by some ontology term. For more information about the chado Stock Module <a href="http://gmod.org/wiki/Chado_Stock_Module">see the GMOD Wiki Page</a></p>';
-  
+
   $text .= '<h3>Setup Instructions:</h3>';
   //================================================================================
   $text .= '<ol>';
-  $text .= '<li><b>Set Ontologies</b>: Since at the time of this modules developement there is no accepted ontology for 
-            describing stocks, their properties and relationships, this module allows you to select the controlled 
-            vocabularies (CVs) in your Chado Database you would like to govern these data. To Set the Controlled Vocabularies for Stocks: 
-            First, ensure your Controlled Vocabulary is in Chado. This can be done by either loading an existing Ontology into Chado using 
-            the <a href="tripal_cv/ontology_loader">Tripal Ontology Loader</a> OR create your ontology from scratch by first 
+  $text .= '<li><b>Set Ontologies</b>: Since at the time of this modules developement there is no accepted ontology for
+            describing stocks, their properties and relationships, this module allows you to select the controlled
+            vocabularies (CVs) in your Chado Database you would like to govern these data. To Set the Controlled Vocabularies for Stocks:
+            First, ensure your Controlled Vocabulary is in Chado. This can be done by either loading an existing Ontology into Chado using
+            the <a href="tripal_cv/ontology_loader">Tripal Ontology Loader</a> OR create your ontology from scratch by first
             <a href="tripal_cv/add_cv">creating a controlled vocabulary</a> and then <a href="tripal_cv/add_cvterm">adding terms to it</a>.
-            Then go to the <a href="tripal_stock/configuration">Configuration Page for Stocks</a> and, in the "Set Stock Controlled Vocabularies" Fieldset, 
+            Then go to the <a href="tripal_stock/configuration">Configuration Page for Stocks</a> and, in the "Set Stock Controlled Vocabularies" Fieldset,
             select the Controlled Vocaulary name for Stock Types, Stock Properties and Stock Relationship Types.</li>';
       $text .= '<ol type="i">';
         $text .= '<li>Stock Types: When you are creating stocks, the type of each stock must be indicated. This might include "DNA extraction", "Individual Plant/Animal" or even "Progeny Population".</li>';
         $text .= '<li>Stock Properties: This module also allows you to assign properties to any stock. Each property has a type and a value where type is required an value is not. Therefore, if you want to say that a stock was grown at 23 degrees Celcius then the Type would be "temperature grown at" and the value would be 23 degrees Celcius. As such the Stock Properties controlled vocabulary might include "temperature grown at", "diet", "extraction date", "stock location", etc.</li>';
         $text .= '<li>Stock Relationship Types: You can also specify relationships between stocks. For example, a stock of type="DNA extraction" (Stock 1a) is related to the stock of type="Individual Plant/Animal" (Stock 1) that it was extracted from. Thus you might specify the relationship Stock 1 is the source material for Stock 1a where the relationship type is "is the source material for". As such Stock Relationship Types might include "is the source material for", "is maternal parent of", "is individual of population", etc.</li>';
       $text .= '</ol>';
-  
-  $text .= '<li><p><b>Set Permissions</b>: The stock module supports the Drupal user permissions interface for 
-               controlling access to stock content and functions. These permissions include viewing, 
+
+  $text .= '<li><p><b>Set Permissions</b>: The stock module supports the Drupal user permissions interface for
+               controlling access to stock content and functions. These permissions include viewing,
                creating, editing or administering of
-               stock content. The default is that only the original site administrator has these 
-               permissions.  You can <a href="'.url('admin/user/roles').'">add roles</a> for classifying users, 
-               <a href="'.url('admin/user/user').'">assign users to roles</a> and
-               <a href="'.url('admin/user/permissions').'">assign permissions</a> for the stock content to 
-               those roles.  For a simple setup, allow anonymous users access to view organism content and 
+               stock content. The default is that only the original site administrator has these
+               permissions.  You can <a href="' . url('admin/user/roles') . '">add roles</a> for classifying users,
+               <a href="' . url('admin/user/user') . '">assign users to roles</a> and
+               <a href="' . url('admin/user/permissions') . '">assign permissions</a> for the stock content to
+               those roles.  For a simple setup, allow anonymous users access to view organism content and
                allow the site administrator all other permissions.</p></li>';
-  
+
   $text .= '<li><b>Sync Stocks</b>: if you chado database already contains stocks, they need to be sync\'d with Drupal</b>. This creates Drupal Content including detail pages for each stock (known as nodes in Drupal). To sync\' Chado with Drupal simply go to the <a href="tripal_stock/configuration">Configuration Page for Stocks</a> and in the "Sync Stocks" Fieldset select the Organisms whose associated stocks you would like to sync. If this list doesn\'t contain an organism which you know is in Chado go to the Organism Configuration Page and make sure it is sync\'d with Drupal.</p>';
-  $text .= '</ol>';  
+  $text .= '</ol>';
   $text .= '<h3>Features of this Module:</h3>';
   //================================================================================
   $text .= '<ul>';
@@ -61,60 +64,60 @@ function tripal_stock_module_description_page() {
         $text .= '<li>Then you can Add External Database References. A Database Reference can be thought of as a synonym for the current stock where you want to specify a source for that synonym. The source would then be thought of as the database where a database can either be online and provide automatic linking out to the synonymous record or offline and simply be a text name of the source. To create a database reference with a given source you must first add the database to chado <a href="tripal_db/add_db">here</a>.</li>';
         $text .= '<li>Finally you can Add Relationships between Stocks. This allows you to specify, for example, the source material of a stock or one of it\'s parents. To create a relationship between your newly added stock and another stock, the other stock must first be created as this one was. Also, since the types of relationships is governed by a controlled vocabulary, just like with properties you have complete control over which relationships you want to allow. Once you click "Finish" you will be re-directed to the Details Page of the new Stock.</li>';
       $text .= '</ol></li>';
-      
+
   $text .= '<li><b>Details Page of a Stock:</b>';
   $text .= '<p>Each stock get\'s it\'s own page on this website. This page is meant to give an overall picture of the stock including listing the basic details, as well as, all properties, database references and relationships. To understand where it is -All page content in Drupal is known as a node and is given a unique identifier or nid. Thus every drupal page has a path of node/<nid>. You can get to the Details page for a given stock from either of the stock listings described below.</p>';
   $text .= '<p>If you want to customize the look of the stock Details page simply copy the PHP/HTML template node-chado_stock.tpl.php from theme_tripal to the base theme you are currently using. Then edit it as desired. There are plans to integrate this details page with Drupal Panels which will provide a much more user-friendly and no-programming-needed method to customize this page.</p>';
-  
+
   $text .= '<li><b>Adding/Updating/Deleting Stocks and their Properties, Database References and Relationships:</b>';
   $text .= '<p>The Stock Details Page also acts as a landing pad for updating/deleting stocks. To <b>update a stock</b>, go to the stocks details page and click on the Edit tab near the top of the page. This tab will only be visable if you have permission to edit chado stock content (See post installation steps above for information on setting user permissions). If you want to <b>delete a stock</b>, click the Edit tab and then near the bottom of the form, click the Delete button. This will delete the entire stock including it\'s properties, database references and any relationships including it.</p>';
   $text .= '<p>To <b>update/delete a given property of a stock</b>, click the "Edit Properties" Tab near the top of the stock details page. This form provides a listing of all existing properties for the given stock with form elements allowing you to change their value. After editing the properties you wanted to, simply click the "Update Properties" button to update all the properties for that stock. To delete a given property simply click the "Delete" Button beside the property you want to delete. You cannot undo this action! To <b>add a property to the given stock</b> simply fill out the "Add Property" form at the bottom of the "Edit Properties" Tab.</p>';
   $text .= '<p><b>Adding, updating and deleting Database References and Relationships</b> for a given stock is exactly the same as the method for properties. To edit Database References, click the "Edit DB References" tab and to add/edit/update stock relationships, click the "Edit Relationships" tab.</p></li>';
-  
+
   $text .= '<li><b><a href="../../stocks">Basic Listing of Stocks:</a></b>';
   $text .= '<p>This module also provides a basic listing of all stocks currently sync\'d with Drupal. To access this listing, there should be a Stocks Primary Menu item which links you to <a href="../../stocks">this page</a>. This page lists each stock on it\'s own row and provides a link to each stock by clicking on it\'s name. Currently there is no way to easily customize this listing.</p></li>';
-  
+
   $text .= '<li><b><a href="../build/views/">Flexible Listing of Stocks using Drupal Views:</a></b>';
   $text .= '<p>In order to access a more flexible listing of stocks you must first install the <a href="http://drupal.org/project/views">Drupal Views2 module</a>. You should then be able to access the default views <a href="../build/views/">here</a>. Essentially, Views is a module which allows you to create custom SQL queries completely through the web interface without knowing SQL. Furthermore, it also does some formatting of the results allowing you to display them as HTML lists, tables or grids. You can also expose filters to the user to let them customize the results they see and even implement various sorting.</p>';
   $text .= '<p>To use one of the Default Views simply click "Enable" and then "Edit" to change it to show exactly what you want. To view the current listing simply clikc "View Page" at the top of the Edit user interface. There are a number of good tutorials out there for Views2, any of which can be used to help you create your own custom listings of biological content. (Note: there aren\'t any tutorials specifically for tripal content but any tutorial for Views2 will show you how to use the views interface.</p></li>';
 
    $text .= '<h3>Page Customizations</h3>';
-   $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal. 
+   $text .= '<p>There are several ways to customize the look-and-feel for the way Chado data is presented through Tripal.
              Below is a description of several methods.  These methods may be used in conjunction with one another to
-             provide fine-grained control. 
+             provide fine-grained control.
              <ul>
 
-             <li><p><b>Integration with Drupal Panels</b>:  <a href="http://drupal.org/project/views">Drupal Panels</a> 
-              allows for customization of a page layout if you don\'t want to do PHP/Javascript/CSS programming.  Tripal comes with pre-set layouts for stock pages.  However, 
+             <li><p><b>Integration with Drupal Panels</b>:  <a href="http://drupal.org/project/views">Drupal Panels</a>
+              allows for customization of a page layout if you don\'t want to do PHP/Javascript/CSS programming.  Tripal comes with pre-set layouts for stock pages.  However,
               Panels become useful if you prefer a layout that is different from the pre-set layouts.  Chado content
-              is provided to Panels in the form of Drupal "blocks" which you can then place anywhere on a page using the 
+              is provided to Panels in the form of Drupal "blocks" which you can then place anywhere on a page using the
               Panel\'s GUI.</p></li>
 
-             <li><p><b>Drupal\'s Content Construction Kit (CCK)</b>: the 
+             <li><p><b>Drupal\'s Content Construction Kit (CCK)</b>: the
              <a href="http://drupal.org/project/cck">Content Construction Kit (CCK) </a> is a powerful way to add non-Chado content
              to any page without need to edit template files or knowing PHP.  You must first download and install CCK.
              With CCK, the site administartor can create a new field to appear on the page.  For example, currently,
-             the Chado publication module is not yet supported by Tripal.  Therefore, the site administrator can add a text 
+             the Chado publication module is not yet supported by Tripal.  Therefore, the site administrator can add a text
              field to the stock pages.  This content is not stored in Chado, but will appear on the stock page.  A field
              added by CCK will also appear in the form when editing a stock to allow users to manually enter the appropriate
              text.  If the default pre-set layout and themeing for Tripal is used, it is better to create the CCK element,
-             indicate that it is not to be shown (using the CCK interface), then manually add the new content type 
+             indicate that it is not to be shown (using the CCK interface), then manually add the new content type
              where desired by editing the templates (as described below).  If using Panels, the CCK field can be added to the
              location desired using the Panels interface.</p></li>
 
              <li><p><b>Drupal Node Templates</b>:  The Tripal packages comes with a "theme_tripal" directory that contains the
              themeing for Chado content.    The stock module has a template file for stock "nodes" (Tripal stock pages).  This file
              is named "node-chado_stock.tpl.php", and provides javascript, HTML and PHP code for display of the stock
-             pages.  You can edit this file to control which types of information (or which stock "blocks") are displayed for stocks. Be sure to 
+             pages.  You can edit this file to control which types of information (or which stock "blocks") are displayed for stocks. Be sure to
              copy these template to your primary theme directory for editing. Do not edit them in the "theme_tripal" directory as
              future Tripal updates may overwrite your customizations. See the <a href="http://tripal.sourceforge.net/">Tripal website </a>
              for instructions on how to access variables and other Chado content within the template file.</p></li>
 
              <li><p><b>Stock "Block" Templates</b>:  In the "theme_tripal" directory is a subdirectory named "tripal_stock".
              Inside this directory is a set of templates that control distinct types of information for stocks.  For example,
-             there is a "base" template for displaying of data directly from the Chado stock table, and a "references" 
+             there is a "base" template for displaying of data directly from the Chado stock table, and a "references"
              template for showing external site references for a stock (data from the stock_dbxref table).  These templates are used both by Drupal blocks
-             for use in Drupal Panels (as described above) or for use in the default pre-set layout that the node template 
+             for use in Drupal Panels (as described above) or for use in the default pre-set layout that the node template
              provides (also desribed above).  You can customize this template as you desire.  Be sure to copy the
              template to your primary theme directory for editing. Do not edit them in the "theme_tripal" directory as
              future Tripal updates may overwrite your customizations.  See the <a href="http://tripal.sourceforge.net/">Tripal website </a>
@@ -123,14 +126,14 @@ function tripal_stock_module_description_page() {
 
              <li><p><b>Adding Links to the "Resources" Sidebar</b>: If you use the pre-set default Tripal layout for theming, you
              will see a "Resources" sidebar on each page.  The links that appear on the sidebar are automatically generated
-             using Javascript for all of the stock "Blocks" that appear on the page. If you want to add additional links 
-             (e.g. a dynamic link to additional stock content) and you want that link to appear in the 
-             "Resources" sidebar, simply edit the Drupal Node Template (as described above) and add the link to the 
+             using Javascript for all of the stock "Blocks" that appear on the page. If you want to add additional links
+             (e.g. a dynamic link to additional stock content) and you want that link to appear in the
+             "Resources" sidebar, simply edit the Drupal Node Template (as described above) and add the link to the
              section at the bottom of the template file where the resources section is found.</p></li>
 
              </ul>
-             </p>';  
-  
+             </p>';
+
   return $text;
 }
 
@@ -149,11 +152,11 @@ function tripal_stock_admin() {
    // currently processing jobs. If so, we don't want
    // to give the opportunity to sync Stocks
    $active_jobs = FALSE;
-   if(tripal_get_module_active_jobs('tripal_stock')){
+   if (tripal_get_module_active_jobs('tripal_stock')) {
       $active_jobs = TRUE;
    }
-   if($active_jobs){
-   
+   if ($active_jobs) {
+
    $form['notice'] = array(
          '#type' => 'fieldset',
          '#title' => t('Stock Management Temporarily Unavailable')
@@ -167,24 +170,25 @@ function tripal_stock_admin() {
             "jobs page."),
       );
 
-   } else {
+   }
+   else {
 
    // SET Vocabularies -----------------------------------------------------------------------------------------
    $form['set_cv'] = array(
       '#type' => 'fieldset',
       '#title' => t('Set Stock Controlled Vocabularies'),
       '#weight' => -10
-   );   
-   
+   );
+
    $form['set_cv']['message'] = array(
          '#value' => t("This setting allows you to set which chado controlled vocabularies (cv)"
-	              ." are used. Cvs are used to control user input for the type of stock,"
-		      ." any properties they enter for a stock & the types of relationships"
-		      ." between stocks. Only cvs already loaded into chado can be selected here.")
+                ." are used. Cvs are used to control user input for the type of stock,"
+          ." any properties they enter for a stock & the types of relationships"
+          ." between stocks. Only cvs already loaded into chado can be selected here.")
    );
 
    $cv_options = tripal_cv_get_cv_options();
-   
+
    $form['set_cv']['stock_types_cv'] = array(
      '#type' => 'select',
      '#title' => t('Controlled Vocabulary governing Stock Types'),
@@ -270,10 +274,10 @@ function tripal_stock_admin_validate($form, &$form_state) {
       //for each organism selected submit job (handled by tripal_stock_sync_stock_set)
       //  which syncs all stocks with an organism_id equal to the selelcted organism
       foreach ( $organisms_2b_syncd as $organism_id ) {
-        if($organism_id != 0) {
+        if ($organism_id != 0) {
           $job_args[0] = $organism_id;
-          tripal_add_job("Sync Stocks from Organism $organism_id",'tripal_stock',
-            'tripal_stock_sync_stock_set',$job_args,$user->uid);
+          tripal_add_job("Sync Stocks from Organism $organism_id", 'tripal_stock',
+            'tripal_stock_sync_stock_set', $job_args, $user->uid);
         }
       }
     }
@@ -285,7 +289,7 @@ function tripal_stock_admin_validate($form, &$form_state) {
     }
 }
 
-/** 
+/**
  * Syncs all Stocks associated with an organism
  *
  * Note: Handling of multiple organisms is done in tripal_stock_admin_validate()
@@ -301,16 +305,17 @@ function tripal_stock_admin_validate($form, &$form_state) {
  * @ingroup tripal_stock
  */
  function tripal_stock_sync_stock_set($organism_id, $job_id) {
-	global $user;
+  global $user;
 
-	if(!$organism_id) {
-		print '0 Stocks to Sync -No Organisms Selected.\n';
-	} else {
+  if (!$organism_id) {
+    print '0 Stocks to Sync -No Organisms Selected.\n';
+  }
+  else {
 
-		// Get list of stocks to sync
-		$previous_db = tripal_db_set_active('chado');
+    // Get list of stocks to sync
+    $previous_db = tripal_db_set_active('chado');
     $result = db_query(
-       "SELECT stock_id, uniquename, type_id, organism_id FROM stock WHERE organism_id=%d",
+       "SELECT stock_id, uniquename, type_id, organism_id FROM {stock} WHERE organism_id=%d",
        $organism_id
     );
     tripal_db_set_active($previous_db);
@@ -322,67 +327,71 @@ function tripal_stock_admin_validate($form, &$form_state) {
       // $r is the current stock to be sync'd
       $stocks_attempted++;
 
-      print 'Processing '.$r->uniquename."... ";
+      print 'Processing ' . $r->uniquename . "... ";
 
       // check not already in drupal
       $in_drupal_query = db_query(
-      	"SELECT * FROM {chado_stock} WHERE stock_id=%d",
-	 			$r->stock_id
+        "SELECT * FROM {chado_stock} WHERE stock_id=%d",
+         $r->stock_id
       );
       if ( !db_fetch_object($in_drupal_query) ) {
 
         //create new chado_stock node
         $new_node = new stdClass();
-	 			$new_node->type = 'chado_stock';
+         $new_node->type = 'chado_stock';
         $new_node->uid = $user->uid;
-	 			$new_node->title = $r->uniquename;
-	 			$new_node->type_id = $r->type_id;
-	 			$new_node->organism_id = $r->organism_id;
-	 			$new_node->stock_id = $r->stock_id;
+         $new_node->title = $r->uniquename;
+         $new_node->type_id = $r->type_id;
+         $new_node->organism_id = $r->organism_id;
+         $new_node->stock_id = $r->stock_id;
         $new_node->chado_stock_exists = TRUE;
-        
-	 			//print 'New Node:';
-	 			//print_r($new_node);
-	 			
-	 			node_validate($new_node);
-	 			
-        if(!form_get_errors()){
-	    		//print 'Try to Create Node ';
-        	$node = node_submit($new_node);
+
+         //print 'New Node:';
+         //print_r($new_node);
+
+         node_validate($new_node);
+
+        if (!form_get_errors()) {
+          //print 'Try to Create Node ';
+          $node = node_submit($new_node);
           node_save($node);
-          if($node->nid){
-          	$stocks_created_count++;
-	 
-						//Add stock id to chado_stock table
-						/**
-	 					db_query(
-	   	  			"INSERT INTO chado_stock (stock_id, nid, vid) VALUES (%d, %d, %d)",
-	   	  			$r->stock_id,
-	   	  			$node->nid,
-	   	  			$node->vid
-	 					);
-	 					*/
+          if ($node->nid) {
+            $stocks_created_count++;
+
+            //Add stock id to chado_stock table
+            /**
+             db_query(
+               "INSERT INTO chado_stock (stock_id, nid, vid) VALUES (%d, %d, %d)",
+               $r->stock_id,
+               $node->nid,
+               $node->vid
+             );
+             */
           }
-        } else {
-        	print "Not completed due to errors:\nCreate Stock Form Errors: ";
-	 				print_r(form_get_errors());
         }
-	 			print "Nid=".$node->nid."\n";
-			} else {
-				print "Skipped $r->uniquename because it's already in drupal.\n";
+        else {
+          print "Not completed due to errors:\nCreate Stock Form Errors: ";
+           print_r(form_get_errors());
+        }
+         print "Nid=" . $node->nid . "\n";
+      }
+      else {
+        print "Skipped $r->uniquename because it's already in drupal.\n";
       } //end of if not already in drupal
     } //end of while still stocks to be sync'd
   } //end of if organism_id not supplied
-   
+
   if ($stocks_attempted == 0) {
-		print "No stocks retrieved for organism (".$organism_id.")\n";
-		return 1;
-	} else {
-		if ($stocks_created_count > 0) {
-			print "$stocks_created_count Stocks Successfully Created\n";
-			return 1;
-		} else {
-			return 0;
-		}
-	}
-}
+    print "No stocks retrieved for organism (" . $organism_id . ")\n";
+    return 1;
+  }
+  else {
+    if ($stocks_created_count > 0) {
+      print "$stocks_created_count Stocks Successfully Created\n";
+      return 1;
+    }
+    else {
+      return 0;
+    }
+  }
+}

+ 77 - 67
tripal_stock/tripal_stock-db_references.inc

@@ -1,5 +1,8 @@
 <?php
-
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
  * Display the ADD Database References to Stock Page
@@ -17,7 +20,7 @@
 function tripal_stock_add_ALL_dbreferences_page($node) {
   $output = '';
 
-  $output .= tripal_stock_add_chado_properties_progress('db_references').'<br>';
+  $output .= tripal_stock_add_chado_properties_progress('db_references') . '<br>';
   $output .= '<b>All Database References should strictly pertain to THE CURRENT Individual</b><br>';
   $output .= '<br>';
   $output .= theme('tripal_stock_references', $node);
@@ -112,29 +115,30 @@ function tripal_stock_add_ONE_dbreference_form_validate($form, &$form_state) {
 
     // Check database is valid db_id in chado
     if ( $form_state['values']['database'] > 0) {
-    	$previous_db = tripal_db_set_active('chado');
-    	$tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM db WHERE db_id=%d",$form_state['values']['database']));
-    	tripal_db_set_active($previous_db);
-    	
+      $previous_db = tripal_db_set_active('chado');
+      $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM {db} WHERE db_id=%d", $form_state['values']['database']));
+      tripal_db_set_active($previous_db);
+
       if ($tmp_obj->count != 1) {
-        form_set_error('database', 'The database you selected is not valid. Please choose another one.'); 
+        form_set_error('database', 'The database you selected is not valid. Please choose another one.');
       }
-    } else {
+    }
+    else {
       form_set_error('database', 'Please select a database');
     }
 
     // Check Accession is unique for database
     $previous_db = tripal_db_set_active('chado');
-    $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM dbxref WHERE accession='%s'",$form_state['values']['accession']));
+    $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM {dbxref} WHERE accession='%s'", $form_state['values']['accession']));
     tripal_db_set_active($previous_db);
-    	
+
     if ($tmp_obj->count > 0) {
-      form_set_error('accession', 'This accession has already been assigned to another stock.'); 
+      form_set_error('accession', 'This accession has already been assigned to another stock.');
     }
 
   } //end of if adding
 
-} 
+}
 
 /**
  * Implements hoook_form_submit(): Actually adds the db reference to the stock
@@ -149,17 +153,18 @@ function tripal_stock_add_ONE_dbreference_form_validate($form, &$form_state) {
 function tripal_stock_add_ONE_dbreference_form_submit($form, &$form_state) {
 
   // FIX: Sometimes on programatic submission of form (drupal_execute) values in the form state get lost
-  // 	  however, the post values always seem to be correct
-  if (empty($form_state['values']['db_stock_id'])) { $form_state['values']['db_stock_id'] = $form_state['clicked_button']['#post']['db_stock_id']; }
+  //     however, the post values always seem to be correct
+  if (empty($form_state['values']['db_stock_id'])) {
+  $form_state['values']['db_stock_id'] = $form_state['clicked_button']['#post']['db_stock_id']; }
 
   // Only Create if valid
   if ($form_state['values']['database'] > 0) {
-    
+
 
     // create dbxref
     $previous_db = tripal_db_set_active('chado');
     db_query(
-      "INSERT INTO dbxref (db_id, accession, description) VALUES (%d, '%s', '%s')",
+      "INSERT INTO {dbxref} (db_id, accession, description) VALUES (%d, '%s', '%s')",
       $form_state['values']['database'],
       $form_state['values']['accession'],
       $form_state['values']['db_description']
@@ -168,18 +173,19 @@ function tripal_stock_add_ONE_dbreference_form_submit($form, &$form_state) {
 
     //create stock_dbxref
     $dbxref = tripal_db_get_dbxref_by_accession($form_state['values']['accession'], $form_state['values']['database']);
-		if (!empty($dbxref->dbxref_id)) {
-			$previous_db = tripal_db_set_active('chado');
-    	db_query(
-      	"INSERT INTO stock_dbxref (stock_id, dbxref_id) VALUES (%d, %d)",
-      	$form_state['values']['db_stock_id'],
-      	$dbxref->dbxref_id
-    	);
-			tripal_db_set_active($previous_db);
-
-    	drupal_set_message('Successfully Added Database Reference');
-    } else {
-    	drupal_set_message('Database reference NOT successfully created...','error');
+    if (!empty($dbxref->dbxref_id)) {
+      $previous_db = tripal_db_set_active('chado');
+      db_query(
+        "INSERT INTO {stock_dbxref} (stock_id, dbxref_id) VALUES (%d, %d)",
+        $form_state['values']['db_stock_id'],
+        $dbxref->dbxref_id
+      );
+      tripal_db_set_active($previous_db);
+
+      drupal_set_message('Successfully Added Database Reference');
+    }
+    else {
+      drupal_set_message('Database reference NOT successfully created...', 'error');
     } //end of if dbxref was created successfully
   } //end of if valid db reference
 
@@ -197,7 +203,7 @@ function tripal_stock_add_ONE_dbreference_form_submit($form, &$form_state) {
  *   HTML formatted output
  *
  * @ingroup tripal_stock
- */                                            
+ */
 function tripal_stock_edit_ALL_dbreferences_page($node) {
   $output = '';
 
@@ -209,10 +215,10 @@ function tripal_stock_edit_ALL_dbreferences_page($node) {
 
   return $output;
 }
-                                               
-/**                                            
+
+/**
  * Implements Hook_form(): Handles adding of Database References to Stocks
- * 
+ *
  * Specifically this adds dbxrefs to a current stock using the stock_dbxref table
  *
  * @param $form_state
@@ -224,7 +230,7 @@ function tripal_stock_edit_ALL_dbreferences_page($node) {
  *   An array describing the form to be rendered
  *
  * @ingroup tripal_stock
- */                                        
+ */
 function tripal_stock_edit_ALL_db_references_form($form_state, $node) {
   $form = array();
 
@@ -237,17 +243,18 @@ function tripal_stock_edit_ALL_db_references_form($form_state, $node) {
   );
 
   $i=0;
-  if (!$node->stock->stock_dbxref) { 
-    $node->stock->stock_dbxref = array(); 
-  } elseif (!is_array($node->stock->stock_dbxref)) { 
-    $node->stock->stock_dbxref = array($node->stock->stock_dbxref); 
-  }  
+  if (!$node->stock->stock_dbxref) {
+    $node->stock->stock_dbxref = array();
+  }
+  elseif (!is_array($node->stock->stock_dbxref)) {
+    $node->stock->stock_dbxref = array($node->stock->stock_dbxref);
+  }
   if (sizeof($node->stock->stock_dbxref) != 0) {
   foreach ($node->stock->stock_dbxref as $ref) {
     $i++;
     $form["num-$i"] = array(
       '#type' => 'item',
-      '#value' => $i.'.'
+      '#value' => $i . '.'
     );
 
     $form["accession-$i"] = array(
@@ -261,10 +268,10 @@ function tripal_stock_edit_ALL_db_references_form($form_state, $node) {
     $db_options = tripal_db_get_db_options();
     $db_options[0] = 'Select a Database';
     ksort($db_options);
-    $form["database-$i"] = array( 
-      '#type' => 'select', 
+    $form["database-$i"] = array(
+      '#type' => 'select',
       //'#title' => t('Database'),
-      '#options' => $db_options, 
+      '#options' => $db_options,
       '#default_value' => $ref->dbxref_id->db_id->db_id
     );
 
@@ -311,22 +318,24 @@ function tripal_stock_edit_ALL_db_references_form_submit($form, &$form_state) {
      //Update all
      for ($i=1; $i<=$form_state['values']['num_db_references']; $i++) {
        tripal_stock_update_db_reference(
-					$form_state['values']["id-$i"], 
-					$form_state['values']["database-$i"], 
-					$form_state['values']["accession-$i"]
-			);
+          $form_state['values']["id-$i"],
+          $form_state['values']["database-$i"],
+          $form_state['values']["accession-$i"]
+      );
      }
      drupal_set_message("Updated all Database References");
-     drupal_goto('node/'.$form_state['values']['nid']);
+     drupal_goto('node/' . $form_state['values']['nid']);
 
-  } elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
+  }
+  elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
 
      $i = $matches[1];
      tripal_stock_delete_db_reference($form_state['values']["id-$i"]);
      drupal_set_message("Deleted Database Reference");
 
-  } else {
-    drupal_set_message("Unrecognized Button Pressed",'error');
+  }
+  else {
+    drupal_set_message("Unrecognized Button Pressed", 'error');
   }
 
 }
@@ -349,8 +358,8 @@ function tripal_stock_update_db_reference($dbxref_id, $database_id, $accession)
 
   $previous_db = tripal_db_set_active('chado');
   db_query(
-    "UPDATE dbxref SET db_id=%d, accession='%s' WHERE dbxref_id=%d",
-    $database_id, 
+    "UPDATE {dbxref} SET db_id=%d, accession='%s' WHERE dbxref_id=%d",
+    $database_id,
     $accession,
     $dbxref_id
   );
@@ -373,12 +382,12 @@ function tripal_stock_delete_db_reference($dbxref_id) {
 
   $previous_db = tripal_db_set_active('chado');
   db_query(
-    "DELETE FROM dbxref WHERE dbxref_id=%d",
+    "DELETE FROM {dbxref} WHERE dbxref_id=%d",
     $dbxref_id
   );
 
   db_query(
-    "DELETE FROM stock_dbxref WHERE dbxref_id=%d",
+    "DELETE FROM {stock_dbxref} WHERE dbxref_id=%d",
     $dbxref_id
   );
   tripal_db_set_active($previous_db);
@@ -391,26 +400,26 @@ function tripal_stock_delete_db_reference($dbxref_id) {
  * @param $form
  *   An array describing the form to be themed
  *
- * @return 
+ * @return
  *   An HTML rendering of the form
  *
  * @ingroup tripal_stock
  */
-function theme_tripal_stock_edit_ALL_db_references_form ($form) {
+function theme_tripal_stock_edit_ALL_db_references_form($form) {
   $output = '';
 
   $output .= '<br><fieldset>';
   $output .= '<legend>Edit Existing Database References<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Below is a list of already existing database references, one per line. When entering a database reference, the accession '
-  	     .'is a unique identifier for this stock in the specified database.</p>';
+         .'is a unique identifier for this stock in the specified database.</p>';
   $output .= '<table>';
   $output .= '<tr><th>#</th><th>Database</th><th>Accession</th><th></th></tr>';
 
   for ($i=1; $i<=$form['num_db_references']['#value']; $i++) {
-    $output .= '<tr><td>'.drupal_render($form["num-$i"]).'</td><td>'
-    	       .drupal_render($form["database-$i"]).'</td><td>'
-	       .drupal_render($form["accession-$i"]).'</td><td>'
-	       .drupal_render($form["submit-$i"]).'</td></tr>';
+    $output .= '<tr><td>' . drupal_render($form["num-$i"]) . '</td><td>'
+             . drupal_render($form["database-$i"]) . '</td><td>'
+         . drupal_render($form["accession-$i"]) . '</td><td>'
+         . drupal_render($form["submit-$i"]) . '</td></tr>';
   }
 
   $output .= '</table><br>';
@@ -441,14 +450,15 @@ function tripal_stock_list_dbreferences_for_node($db_references) {
     $output .= '<tr><th>Database</th><th>Accession</th></tr>';
 
     foreach ($db_references as $db) {
-        $output .= '<tr><td>'.$db->db_name.'</td><td>'.$db->accession.'</td></tr>';
-    } // end of foreach db reference 
+        $output .= '<tr><td>' . $db->db_name . '</td><td>' . $db->accession . '</td></tr>';
+    } // end of foreach db reference
 
-    $output .= '</table>'; 
+    $output .= '</table>';
 
-  } else {
+  }
+  else {
     $output = 'No Database References Added to the Current Stock';
-  }              
+  }
 
   return $output;
-}     
+}

+ 111 - 97
tripal_stock/tripal_stock-properties.inc

@@ -1,14 +1,18 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
 function tripal_stock_add_ALL_property_page($node) {
   $output = '';
 
-  $output .= tripal_stock_add_chado_properties_progress('properties').'<br>';
+  $output .= tripal_stock_add_chado_properties_progress('properties') . '<br>';
   $output .= '<b>All Properties should strictly pertain to THE CURRENT Individual</b><br>';
   $output .= '<br>';
   $output .= theme('tripal_stock_properties', $node);
@@ -20,7 +24,7 @@ function tripal_stock_add_ALL_property_page($node) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -31,17 +35,17 @@ function tripal_stock_add_ONE_property_form($form_state, $node) {
   $form['add_properties'] = array(
     '#type' => 'fieldset',
     '#title' => t('Add Property') . '<span class="form-optional" title="This field is optional"> (optional)</span>',
-  ); 
+  );
 
   $form['prop_nid'] = array(
     '#type' => 'hidden',
     '#value' => $node->nid
   );
 
-	$tmp_obj = tripal_cv_get_cvterm_by_name('synonym', variable_get('chado_stock_prop_types_cv', 'null'));
-	$synonym_id = $tmp_obj->cvterm_id;
-	
-  $prop_type_options = tripal_cv_get_cvterm_options( variable_get('chado_stock_prop_types_cv', 'null') ); 
+  $tmp_obj = tripal_cv_get_cvterm_by_name('synonym', variable_get('chado_stock_prop_types_cv', 'null'));
+  $synonym_id = $tmp_obj->cvterm_id;
+
+  $prop_type_options = tripal_cv_get_cvterm_options( variable_get('chado_stock_prop_types_cv', 'null') );
   $prop_type_options[0] = 'Select a Type';
   ksort($prop_type_options);
   $form['add_properties']['prop_type_id'] = array(
@@ -67,7 +71,7 @@ function tripal_stock_add_ONE_property_form($form_state, $node) {
   );
 
   $form['add_properties']['submit-add'] = array(
-    '#type' => 'submit',         
+    '#type' => 'submit',
     '#value' => t('Add Property')
   );
 
@@ -75,7 +79,7 @@ function tripal_stock_add_ONE_property_form($form_state, $node) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -84,18 +88,19 @@ function tripal_stock_add_ONE_property_form_validate($form, &$form_state) {
   // Only Require if Adding Property
   if ($form_state['clicked_button']['#value'] == t('Add Property') ) {
 
-		// Check that there is a stock
-		if ( $form_state['values']['prop_stock_id'] <= 0 ) {
-			form_set_error('prop_stock_id', 'There is no associated stock.');
-		}
-		
+    // Check that there is a stock
+    if ( $form_state['values']['prop_stock_id'] <= 0 ) {
+      form_set_error('prop_stock_id', 'There is no associated stock.');
+    }
+
     // Check that Selected a type
     if ( $form_state['values']['prop_type_id'] == 0) {
       form_set_error('prop_type_id', 'Please select a type of property.');
-    } else {
+    }
+    else {
       // Check that type is in chado
       $previous_db = tripal_db_set_active('chado');
-      $num_rows = db_fetch_object(db_query("SELECT count(*) as count FROM cvterm WHERE cvterm_id=%d", $form_state['values']['prop_type_id']));
+      $num_rows = db_fetch_object(db_query("SELECT count(*) as count FROM {cvterm} WHERE cvterm_id=%d", $form_state['values']['prop_type_id']));
       tripal_db_set_active($previous_db);
       if ( $num_rows->count != 1) {
         form_set_error('prop_type_id', "The type you selected is not valid. Please choose another one. (CODE:$num_rows)");
@@ -115,24 +120,26 @@ function tripal_stock_add_ONE_property_form_validate($form, &$form_state) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
 function tripal_stock_add_ONE_property_form_submit($form, &$form_state) {
-	
+
   // if there is a property add it (only won't be a property if clicked next step w/ no property)
   if ($form_state['values']['prop_type_id'] != 0) {
     //determine the rank for this property
-    $max_rank = get_max_chado_rank('stockprop', 
-    															array('stock_id'=>array('type'=>'INT','value'=>$form_state['values']['prop_stock_id']), 
-    																		'type_id'=>array('type'=>'INT','value'=> $form_state['values']['prop_type_id']) ));
-    if ($max_rank == -1) { $rank = 0; 
-    } else { $rank = $max_rank+1; }
-    
+    $max_rank = get_max_chado_rank('stockprop',
+                                  array('stock_id' => array('type' => 'INT', 'value' => $form_state['values']['prop_stock_id']),
+                                        'type_id' => array('type' => 'INT', 'value' => $form_state['values']['prop_type_id']) ));
+    if ($max_rank == -1) {
+    $rank = 0;
+    }
+    else { $rank = $max_rank+1; }
+
     $previous_db = tripal_db_set_active('chado');
     db_query(
-      "INSERT INTO stockprop (stock_id, type_id, value, rank) VALUES (%d, %d, '%s', %d)",
+      "INSERT INTO {stockprop} (stock_id, type_id, value, rank) VALUES (%d, %d, '%s', %d)",
       $form_state['values']['prop_stock_id'],
       $form_state['values']['prop_type_id'],
       $form_state['values']['prop_value'],
@@ -148,11 +155,11 @@ function tripal_stock_add_ONE_property_form_submit($form, &$form_state) {
       //use update node form so that both title and name get set
       $node = node_load($form_state['values']['prop_nid']);
       $node->title = $form_state['values']['prop_value'];
-      $node_form_state = array( 
+      $node_form_state = array(
         'values' => array(
-					'title' => $form_state['values']['prop_value'], 
-					'op' => 'Save'
-				) 
+          'title' => $form_state['values']['prop_value'],
+          'op' => 'Save'
+        )
       );
       module_load_include('inc', 'node', 'node.pages');
       drupal_execute('chado_stock_node_form', $node_form_state, $node);
@@ -163,7 +170,7 @@ function tripal_stock_add_ONE_property_form_submit($form, &$form_state) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -196,17 +203,18 @@ function tripal_stock_edit_ALL_properties_form($form_state, $node) {
   );
 
   $i=0;
-  if (!$node->stock->stockprop) { 
-    $node->stock->stockprop = array(); 
-  } elseif (!is_array($node->stock->stockprop)) { 
-    $node->stock->stockprop = array($node->stock->stockprop); 
+  if (!$node->stock->stockprop) {
+    $node->stock->stockprop = array();
+  }
+  elseif (!is_array($node->stock->stockprop)) {
+    $node->stock->stockprop = array($node->stock->stockprop);
   }
   if (sizeof($node->stock->stockprop) != 0) {
   foreach ($node->stock->stockprop as $property) {
     $i++;
     $form["num-$i"] = array(
       '#type' => 'item',
-      '#value' => $i.'.'
+      '#value' => $i . '.'
     );
 
     $form["id-$i"] = array(
@@ -250,7 +258,7 @@ function tripal_stock_edit_ALL_properties_form($form_state, $node) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -262,76 +270,81 @@ function tripal_stock_edit_ALL_properties_form_submit($form, &$form_state) {
        tripal_stock_update_property($form_state['values']["id-$i"], $form_state['values']["type-$i"], $form_state['values']["value-$i"], $form_state['values']["preferred-$i"], $form_state['values']["nid"]);
      }
      drupal_set_message("Updated all Properties");
-     drupal_goto('node/'.$form_state['values']['nid']);
-  } elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
+     drupal_goto('node/' . $form_state['values']['nid']);
+  }
+  elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
      $i = $matches[1];
      tripal_stock_delete_property($form_state['values']["id-$i"], $form_state['values']["type-$i"], $form_state['values']["value-$i"]);
      drupal_set_message("Deleted Property");
-  } else {
-    drupal_set_message("Unrecognized Button Pressed",'error');
   }
+  else {
+    drupal_set_message("Unrecognized Button Pressed", 'error');
+  }
+
 
-  
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
 function tripal_stock_update_property($stockprop_id, $cvterm_id, $value, $preferred, $nid) {
 
-	$previous_db = tripal_db_set_active('chado');
-	$old_obj = db_fetch_object(db_query("SELECT * FROM stockprop WHERE stockprop_id=%d",$stockprop_id));
-	tripal_db_set_active($previous_db);
-	
-	// if they changed the type need to check rank
-	//   (if there is another property of the same type then rank needs to be increased to prevent collisions)
-	if ($cvterm_id == $old_obj->type_id) {
-	  $previous_db = tripal_db_set_active('chado');
-  	db_query(
-    	"UPDATE stockprop SET type_id=%d, value='%s' WHERE stockprop_id=%d",
-    	$cvterm_id, 
-    	$value,
-    	$stockprop_id
-  	);
-  	tripal_db_set_active($previous_db);
-  } else {
+  $previous_db = tripal_db_set_active('chado');
+  $old_obj = db_fetch_object(db_query("SELECT * FROM {stockprop} WHERE stockprop_id=%d", $stockprop_id));
+  tripal_db_set_active($previous_db);
+
+  // if they changed the type need to check rank
+  //   (if there is another property of the same type then rank needs to be increased to prevent collisions)
+  if ($cvterm_id == $old_obj->type_id) {
+    $previous_db = tripal_db_set_active('chado');
+    db_query(
+      "UPDATE {stockprop} SET type_id=%d, value='%s' WHERE stockprop_id=%d",
+      $cvterm_id,
+      $value,
+      $stockprop_id
+    );
+    tripal_db_set_active($previous_db);
+  }
+  else {
       //determine the rank for this property
-    $max_rank = get_max_chado_rank('stockprop', 
-    															array('stock_id'=>array('type'=>'INT','value'=> $old_obj->stock_id), 
-    																		'type_id'=>array('type'=>'INT','value'=> $cvterm_id ) ));
-    if ($max_rank == -1) { $rank = 0; 
-    } else { $rank = $max_rank+1; }
-	  $previous_db = tripal_db_set_active('chado');
-  	db_query(
-    	"UPDATE stockprop SET type_id=%d, value='%s', rank=%d WHERE stockprop_id=%d",
-    	$cvterm_id, 
-    	$value,
-    	$rank,
-    	$stockprop_id
-  	);
-  	tripal_db_set_active($previous_db);  	
+    $max_rank = get_max_chado_rank('stockprop',
+                                  array('stock_id' => array('type' => 'INT', 'value' => $old_obj->stock_id),
+                                        'type_id' => array('type' => 'INT', 'value' => $cvterm_id ) ));
+    if ($max_rank == -1) {
+    $rank = 0;
+    }
+    else { $rank = $max_rank+1; }
+    $previous_db = tripal_db_set_active('chado');
+    db_query(
+      "UPDATE {stockprop} SET type_id=%d, value='%s', rank=%d WHERE stockprop_id=%d",
+      $cvterm_id,
+      $value,
+      $rank,
+      $stockprop_id
+    );
+    tripal_db_set_active($previous_db);
   }
 
   // Set Preferred Synonym
-  //use update node form so that both title and name get set                                                                                                                                                                       
+  //use update node form so that both title and name get set
   if ($preferred) {
-    $node = node_load($nid);                                                                                                                                                                            
-    $node->title = $value;                                                                                                                                                                              
-    $node_form_state = array(                                                                                                                                                                                                        
-      'values' => array(                                                                                                                                                                                                             
-        'title' => $value,                                                                                                                                               
-        'op' => 'Save'                                                                                                                                                                                
-      )                                                                                                                                                                                                            
-    );                                                                                                                                                                                                                               
-    module_load_include('inc', 'node', 'node.pages');                                                                                                                                                                                
-    drupal_execute('chado_stock_node_form', $node_form_state, $node);  
+    $node = node_load($nid);
+    $node->title = $value;
+    $node_form_state = array(
+      'values' => array(
+        'title' => $value,
+        'op' => 'Save'
+      )
+    );
+    module_load_include('inc', 'node', 'node.pages');
+    drupal_execute('chado_stock_node_form', $node_form_state, $node);
   }
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -339,7 +352,7 @@ function tripal_stock_delete_property($stockprop_id) {
 
   $previous_db = tripal_db_set_active('chado');
   db_query(
-    "DELETE FROM stockprop WHERE stockprop_id=%d",
+    "DELETE FROM {stockprop} WHERE stockprop_id=%d",
     $stockprop_id
   );
   tripal_db_set_active($previous_db);
@@ -347,24 +360,24 @@ function tripal_stock_delete_property($stockprop_id) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
-function theme_tripal_stock_edit_ALL_properties_form ($form) {
+function theme_tripal_stock_edit_ALL_properties_form($form) {
   $output = '';
 
   $output .= '<br><fieldset>';
   $output .= '<legend>Edit Already Existing Properties<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Below is a list of already existing properties for this stock, one property per line. The type refers to the type of '
-  	     .'property and the value is the value for that property. For example, if this stock has a seed coat colour of green then '
-	     .'the property type=sead coat colour and the value=green. When the type of property is synonym, there is an extra checkbox '
-	     .'allowing you to specify which is the <b>Preferred Synonym</b>. This will change the current name of the stock.</p>';
+         .'property and the value is the value for that property. For example, if this stock has a seed coat colour of green then '
+       .'the property type=sead coat colour and the value=green. When the type of property is synonym, there is an extra checkbox '
+       .'allowing you to specify which is the <b>Preferred Synonym</b>. This will change the current name of the stock.</p>';
   $output .= '<table>';
   $output .= '<tr><th>#</th><th>Type</th><th>Value</th><th></th></tr>';
 
   for ($i=1; $i<=$form['num_properties']['#value']; $i++) {
-    $output .= '<tr><td>'.drupal_render($form["num-$i"]).'</td><td>'.drupal_render($form["type-$i"]).'</td><td>'.drupal_render($form["value-$i"]).drupal_render($form["preferred-$i"]).'</td><td>'.drupal_render($form["submit-$i"]).'</td></tr>';
+    $output .= '<tr><td>' . drupal_render($form["num-$i"]) . '</td><td>' . drupal_render($form["type-$i"]) . '</td><td>' . drupal_render($form["value-$i"]) . drupal_render($form["preferred-$i"]) . '</td><td>' . drupal_render($form["submit-$i"]) . '</td></tr>';
   }
 
   $output .= '</table><br>';
@@ -375,7 +388,7 @@ function theme_tripal_stock_edit_ALL_properties_form ($form) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -387,21 +400,22 @@ function tripal_stock_list_properties_for_node($properties, $synonyms) {
 
     if (!empty($synonyms) ) {
       foreach ($synonyms as $s) {
-        $output .= '<tr><td>synonym</td><td>'.$s.'</td></tr>';
+        $output .= '<tr><td>synonym</td><td>' . $s . '</td></tr>';
       }
     }
 
     if (!empty($properties) ) {
       foreach ($properties as $p) {
-        $output .= '<tr><td>'.$p->type.'</td><td>'.$p->value.'</td></tr>';
+        $output .= '<tr><td>' . $p->type . '</td><td>' . $p->value . '</td></tr>';
       } // end of foreach property
     }
 
     $output .= '</table>';
 
-  } else {
+  }
+  else {
     $output = 'No Properties Added to the Current Stock';
   }
 
   return $output;
-}
+}

+ 145 - 119
tripal_stock/tripal_stock-relationships.inc

@@ -1,15 +1,19 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
 function tripal_stock_add_ALL_relationships_page($node) {
   $output = '';
 
-  $output .= tripal_stock_add_chado_properties_progress('relationships').'<br>';
-  $output .= '<b>All Relationships should include the CURRENT Individual ('.$node->stock->uniquename.')</b><br>';
+  $output .= tripal_stock_add_chado_properties_progress('relationships') . '<br>';
+  $output .= '<b>All Relationships should include the CURRENT Individual (' . $node->stock->uniquename . ')</b><br>';
   $output .= '<br>';
   $output .= theme('tripal_stock_relationships', $node);
   $output .= '<br><br>';
@@ -31,9 +35,9 @@ function tripal_stock_add_ONE_relationship_form($form_state, $node) {
   $_SESSION['organism'] = $organism_id; //needed for autocomplete enter stock to work
 
   $form['rel_nid'] = array(
-    '#type' => 'hidden', 
+    '#type' => 'hidden',
     '#value' => $node->nid
-  ); 
+  );
 
   $form['add_relationships'] = array(
     '#type' => 'fieldset',
@@ -85,7 +89,7 @@ function tripal_stock_add_ONE_relationship_form($form_state, $node) {
 
   );
 
-  $form['add_relationships']['r_stock_uniquename'] = array( 
+  $form['add_relationships']['r_stock_uniquename'] = array(
     '#type' => 'value',
     '#value' => $node->stock->uniquename,
     '#required' => TRUE
@@ -96,7 +100,7 @@ function tripal_stock_add_ONE_relationship_form($form_state, $node) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -108,15 +112,18 @@ function tripal_stock_add_ONE_relationship_form_validate($form, &$form_state) {
     $subject_results = tripal_stock_get_stock_by_name_identifier( $form_state['values']['subject_id'], $_SESSION['organism']);
     if (sizeof($subject_results) > 1) {
       $links= array();
-      for ($i=0; $i<sizeof($subject_results); $i++) { $links[] = l($i+1, "node/".$subject_results[$i]->nid); }
-      $message = "Too many stocks match '".$form_state['values']['subject_id']."'! "
-      	       	 . " Please refine your input to match ONLY ONE stock. <br>"
-		 . "To aid in this process, here are the stocks that match your initial input: "
-		 .join(', ',$links);
+      for ($i=0; $i<sizeof($subject_results); $i++) {
+      $links[] = l($i+1, "node/" . $subject_results[$i]->nid); }
+      $message = "Too many stocks match '" . $form_state['values']['subject_id'] . "'! "
+                  . " Please refine your input to match ONLY ONE stock. <br>"
+     . "To aid in this process, here are the stocks that match your initial input: "
+     . join(', ', $links);
       form_set_error('subject_id', $message);
-    } elseif (sizeof($subject_results) < 1) {
-      form_set_error('subject_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock ".l('here', 'stocks'));
-    } elseif (sizeof($subject_results) == 1) {
+    }
+    elseif (sizeof($subject_results) < 1) {
+      form_set_error('subject_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+    }
+    elseif (sizeof($subject_results) == 1) {
       $form_state['values']['subject_id'] = $subject_results[0]->stock->stock_id;
     }
 
@@ -124,26 +131,30 @@ function tripal_stock_add_ONE_relationship_form_validate($form, &$form_state) {
     $object_results = tripal_stock_get_stock_by_name_identifier( $form_state['values']['object_id'], $_SESSION['organism']);
     if (sizeof($object_results) > 1) {
       $links= array();
-      for ($i=0; $i<sizeof($object_results); $i++) { $links[] = l($i+1, "node/".$object_results[$i]->nid); } 
-      $message = "Too many stocks match '".$form_state['values']['object_id']."'! "
+      for ($i=0; $i<sizeof($object_results); $i++) {
+      $links[] = l($i+1, "node/" . $object_results[$i]->nid); }
+      $message = "Too many stocks match '" . $form_state['values']['object_id'] . "'! "
                  . "Please refine your input to match ONLY ONE stock. <br>"
                  . "To aid in this process, here are the stocks that match your initial input: "
-                 .join(', ',$links);
+                 . join(', ', $links);
       form_set_error('object_id', $message);
-    } elseif (sizeof($object_results) < 1) {
-      form_set_error('object_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock ".l('here', 'stocks'));                                                                         
-    } elseif (sizeof($object_results) == 1) {
+    }
+    elseif (sizeof($object_results) < 1) {
+      form_set_error('object_id', "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+    }
+    elseif (sizeof($object_results) == 1) {
       $form_state['values']['object_id'] = $object_results[0]->stock->stock_id;
     }
 
     // check valid type selected
     if ($form_state['values']['type_id'] == 0) {
       form_set_error('type_id', 'Please select a type of relationship.');
-    } else {
-    	$previous_db = tripal_db_set_active('chado');
-    	$tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM cvterm WHERE cvterm_id=%d",$form_state['values']['type_id']));
-    	tripal_db_set_active($previous_db);
-    	
+    }
+    else {
+      $previous_db = tripal_db_set_active('chado');
+      $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM {cvterm} WHERE cvterm_id=%d", $form_state['values']['type_id']));
+      tripal_db_set_active($previous_db);
+
       if ($tmp_obj->count != 1) {
         form_set_error('type_id', 'The type you selected is not valid. Please choose another one.');
       }
@@ -152,23 +163,23 @@ function tripal_stock_add_ONE_relationship_form_validate($form, &$form_state) {
     // check either subject or object is the current stock
     if ( $subject_results[0]->nid != $form_state['values']['rel_nid'] ) {
       if ( $object_results[0]->nid != $form_state['values']['rel_nid'] ) {
-        form_set_error('subject_id', 'Either Subject or Object must be the current stock ('.$form_state['values']['r_stock_uniquename'].').');
+        form_set_error('subject_id', 'Either Subject or Object must be the current stock (' . $form_state['values']['r_stock_uniquename'] . ').');
       }
     }
   } //end of require validation if adding relationship
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
 function tripal_stock_add_ONE_relationship_form_submit($form, &$form_state) {
-  
+
   if ($form_state['values']['subject_id'] > 0) {
     $previous_db = tripal_db_set_active('chado');
     db_query(
-      "INSERT INTO stock_relationship (subject_id, type_id, object_id, value) VALUES (%d, %d, %d, '%s')",
+      "INSERT INTO {stock_relationship} (subject_id, type_id, object_id, value) VALUES (%d, %d, %d, '%s')",
       $form_state['values']['subject_id'],
       $form_state['values']['type_id'],
       $form_state['values']['object_id'],
@@ -182,13 +193,13 @@ function tripal_stock_add_ONE_relationship_form_submit($form, &$form_state) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
 function tripal_stock_edit_ALL_relationships_page($node) {
   $output = '';
-	
+
   $output .= drupal_get_form('tripal_stock_edit_ALL_relationships_form', $node);
   $output .= '<br>';
   $output .= drupal_get_form('tripal_stock_add_ONE_relationship_form', $node);
@@ -197,25 +208,26 @@ function tripal_stock_edit_ALL_relationships_page($node) {
 
   return $output;
 }
-                                                      
-/**                                                   
- * Implements Hook_form()                             
+
+/**
+ * Implements Hook_form()
  *
  * @ingroup tripal_stock
- */                                                   
+ */
 function tripal_stock_edit_ALL_relationships_form($form_state, $node) {
   $form = array();
-  
+
   // All Stock Relationships
-  $node = tripal_core_expand_chado_vars($node, 'table', 'stock_relationship');    
-   
+  $node = tripal_core_expand_chado_vars($node, 'table', 'stock_relationship');
+
   // compile all relationships into one variable
   $relationships = array();
   if (is_array($node->stock->stock_relationship->subject_id)) {
     foreach ($node->stock->stock_relationship->subject_id as $r) {
       $relationships[$r->stock_relationship_id] = $r;
     }
-  } elseif (is_object($node->stock->stock_relationship->subject_id)) { 
+  }
+  elseif (is_object($node->stock->stock_relationship->subject_id)) {
     $relationships[$node->stock->stock_relationship->subject_id->stock_relationship_id] = $node->stock->stock_relationship->subject_id;
   }
 
@@ -223,15 +235,16 @@ function tripal_stock_edit_ALL_relationships_form($form_state, $node) {
     foreach ($node->stock->stock_relationship->object_id as $r) {
       $relationships[$r->stock_relationship_id] = $r;
     }
-  } elseif (is_object($node->stock->stock_relationship->object_id)) { 
+  }
+  elseif (is_object($node->stock->stock_relationship->object_id)) {
     $relationships[$node->stock->stock_relationship->object_id->stock_relationship_id] = $node->stock->stock_relationship->object_id;
   }
-    
+
   $form['nid'] = array(
     '#type' => 'hidden',
     '#value' => $node->nid
   );
-  
+
   $form['r_stock_uniquename'] = array(
     '#type' => 'hidden',
     '#value' => $node->stock->uniquename
@@ -244,7 +257,7 @@ function tripal_stock_edit_ALL_relationships_form($form_state, $node) {
     $i++;
     $form["num-$i"] = array(
       '#type' => 'item',
-      '#value' => $i.'.'
+      '#value' => $i . '.'
     );
 
     $form["id-$i"] = array(
@@ -253,36 +266,38 @@ function tripal_stock_edit_ALL_relationships_form($form_state, $node) {
     );
 
     //Enter relationship specific fields
-    if ( $node->stock->stock_id != $r->subject_id->stock_id ) { 
+    if ( $node->stock->stock_id != $r->subject_id->stock_id ) {
       $default = $r->subject_id->uniquename;
-      $description = l($r->subject_id->name, 'node/'.$r->subject_id->nid); 
-    } else { $default = $node->stock->uniquename; $description = 'Current Stock'; }
+      $description = l($r->subject_id->name, 'node/' . $r->subject_id->nid);
+    }
+    else { $default = $node->stock->uniquename; $description = 'Current Stock'; }
     $form["subject_id-$i"] = array(
-      '#type' => 'textfield',      
-      //'#title' => t('Subject'), 
+      '#type' => 'textfield',
+      //'#title' => t('Subject'),
       '#required'   => TRUE,
       '#size' => 30,
       '#default_value' => $default,
-      '#description' => $description,
-    ); 
+      '#description' => t('%description', array('%description' => $description)),
+    );
 
     $type_options = tripal_cv_get_cvterm_options( variable_get('chado_stock_relationship_cv', 'null') );
-    ksort($type_options);          
-    $form["type_id-$i"] = array(  
-      '#type' => 'select',    
-      //'#title' => t('Type of Relationship'), 
+    ksort($type_options);
+    $form["type_id-$i"] = array(
+      '#type' => 'select',
+      //'#title' => t('Type of Relationship'),
       '#options' => $type_options,
       '#required' => TRUE,
       '#default_value' => $r->type_id->cvterm_id
     );
 
-    if ( $node->stock->stock_id != $r->object_id->stock_id ) { 
+    if ( $node->stock->stock_id != $r->object_id->stock_id ) {
       $default = $r->object_id->uniquename;
-      $description = l($r->object_id->name, 'node/'.$r->object_id->nid);
-    } else { $default = $node->stock->uniquename; $description = 'Current Stock'; }
+      $description = l($r->object_id->name, 'node/' . $r->object_id->nid);
+    }
+    else { $default = $node->stock->uniquename; $description = 'Current Stock'; }
     $form["object_id-$i"] = array(
-      '#type' => 'textfield',          
-      //'#title' => t('Object'),      
+      '#type' => 'textfield',
+      //'#title' => t('Object'),
       '#required'   => TRUE,
       '#size' => 30,
       '#default_value' => $default,
@@ -310,7 +325,7 @@ function tripal_stock_edit_ALL_relationships_form($form_state, $node) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -320,48 +335,55 @@ function tripal_stock_edit_ALL_relationships_form_validate($form, &$form_state)
   if ($form_state['clicked_button']['#value'] == t('Update Relationships') ) {
 
     for ($i=1; $i<=$form_state['values']['num_relationships']; $i++) {
-      
+
       // check valid stock selected for subject
       $subject_results = tripal_stock_get_stock_by_name_identifier( $form_state['values']["subject_id-$i"], $_SESSION['organism']);
       if (sizeof($subject_results) > 1) {
         $links= array();
-        for ($j=0; $j<sizeof($subject_results); $j++) { $links[] = l($j+1, "node/".$subject_results[$j]->nid); }
-        $message = "Too many stocks match '".$form_state['values']["subject_id-$i"]."'! "
-                 . "Please refine your input to match ONLY ONE stock. <br>" 
+        for ($j=0; $j<sizeof($subject_results); $j++) {
+        $links[] = l($j+1, "node/" . $subject_results[$j]->nid); }
+        $message = "Too many stocks match '" . $form_state['values']["subject_id-$i"] . "'! "
+                 . "Please refine your input to match ONLY ONE stock. <br>"
                  . "To aid in this process, here are the stocks that match your initial input: "
-                 .join(', ',$links);
+                 . join(', ', $links);
         form_set_error("subject_id-$i", $message);
-      } elseif (sizeof($subject_results) < 1) { 
-        form_set_error("subject_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock ".l('here', 'stocks'));
-      } elseif (sizeof($subject_results) == 1) {
+      }
+      elseif (sizeof($subject_results) < 1) {
+        form_set_error("subject_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+      }
+      elseif (sizeof($subject_results) == 1) {
         $form_state['values']["subject_id-$i"] = $subject_results[0]->stock->stock_id;
-      } 
+      }
 
       // check valid stock selected for object
       $object_results = tripal_stock_get_stock_by_name_identifier( $form_state['values']["object_id-$i"], $_SESSION['organism']);
       if (sizeof($object_results) > 1) {
         $links= array();
-        for ($j=0; $j<sizeof($object_results); $j++) { $links[] = l($j+1, "node/".$object_results[$j]->nid); }
-        $message = "Too many stocks match '".$form_state['values']["object_id-$i"]."'! "
-                 . "Please refine your input to match ONLY ONE stock. <br>" 
+        for ($j=0; $j<sizeof($object_results); $j++) {
+        $links[] = l($j+1, "node/" . $object_results[$j]->nid); }
+        $message = "Too many stocks match '" . $form_state['values']["object_id-$i"] . "'! "
+                 . "Please refine your input to match ONLY ONE stock. <br>"
                  . "To aid in this process, here are the stocks that match your initial input: "
-                 .join(', ',$links);
+                 . join(', ', $links);
         form_set_error("object_id-$i", $message);
-      } elseif (sizeof($object_results) < 1) {
-        form_set_error("object_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock ".l('here', 'stocks'));
-      } elseif (sizeof($object_results) == 1) {
+      }
+      elseif (sizeof($object_results) < 1) {
+        form_set_error("object_id-$i", "There are no stocks matching your input. Please check your input for typos and/or lookup the stock " . l('here', 'stocks'));
+      }
+      elseif (sizeof($object_results) == 1) {
         $form_state['values']["object_id-$i"] = $object_results[0]->stock->stock_id;
-      } 
+      }
 
       // check valid type selected
       if ($form_state['values']["type_id-$i"] == 0) {
         form_set_error('type_id', 'Please select a type of relationship.');
-      } else {
-    		$previous_db = tripal_db_set_active('chado');
-    		$tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM cvterm WHERE cvterm_id=%d",$form_state['values']["type_id-$i"]));
-    		tripal_db_set_active($previous_db);
-    	
-      	if ($tmp_obj->count != 1) {
+      }
+      else {
+        $previous_db = tripal_db_set_active('chado');
+        $tmp_obj = db_fetch_object(db_query("SELECT count(*) as count FROM {cvterm} WHERE cvterm_id=%d", $form_state['values']["type_id-$i"]));
+        tripal_db_set_active($previous_db);
+
+        if ($tmp_obj->count != 1) {
           form_set_error("type_id-$i", 'The type you selected is not valid. Please choose another one.');
         }
       }
@@ -369,7 +391,7 @@ function tripal_stock_edit_ALL_relationships_form_validate($form, &$form_state)
       // check either subject or object is the current stock
       if ( $subject_results[0]->nid != $form_state['values']['nid'] ) {
         if ( $object_results[0]->nid != $form_state['values']['nid'] ) {
-          form_set_error("subject_id-$i", 'Either Subject or Object must be the current stock ('.$form_state['values']['r_stock_uniquename'].').');
+          form_set_error("subject_id-$i", 'Either Subject or Object must be the current stock (' . $form_state['values']['r_stock_uniquename'] . ').');
         }
       }
 
@@ -379,7 +401,7 @@ function tripal_stock_edit_ALL_relationships_form_validate($form, &$form_state)
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -391,41 +413,44 @@ function tripal_stock_edit_ALL_relationships_form_submit($form, &$form_state) {
 
        //process stock textfields
        tripal_stock_update_relationship(
-				$form_state['values']["id-$i"], 
-				$form_state['values']["subject_id-$i"],
-				$form_state['values']["type_id-$i"], 
-				$form_state['values']["object_id-$i"]
-			);
+        $form_state['values']["id-$i"],
+        $form_state['values']["subject_id-$i"],
+        $form_state['values']["type_id-$i"],
+        $form_state['values']["object_id-$i"]
+      );
      }
      drupal_set_message("Updated all Relationships");
-     drupal_goto('node/'.$form_state['values']['nid']);
+     drupal_goto('node/' . $form_state['values']['nid']);
 
-  } elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
+  }
+  elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
 
      $i = $matches[1];
      tripal_stock_delete_relationship($form_state['values']["id-$i"]);
      drupal_set_message("Deleted Relationship");
 
-  } elseif ($form_state['clicked_button']['#value'] == t('Back to Stock') ) {
-    drupal_goto('node/'.$form_state['values']['nid']);
-  } else {
-    drupal_set_message("Unrecognized Button Pressed",'error');
+  }
+  elseif ($form_state['clicked_button']['#value'] == t('Back to Stock') ) {
+    drupal_goto('node/' . $form_state['values']['nid']);
+  }
+  else {
+    drupal_set_message("Unrecognized Button Pressed", 'error');
   }
 
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
-function tripal_stock_update_relationship ($stock_relationship_id, $subject_id, $cvterm_id, $object_id) {
+function tripal_stock_update_relationship($stock_relationship_id, $subject_id, $cvterm_id, $object_id) {
 
   $previous_db = tripal_db_set_active('chado');
   db_query(
-    "UPDATE stock_relationship SET subject_id=%d, type_id=%d, object_id=%d WHERE stock_relationship_id=%d",
+    "UPDATE {stock_relationship} SET subject_id=%d, type_id=%d, object_id=%d WHERE stock_relationship_id=%d",
     $subject_id,
-    $cvterm_id, 
+    $cvterm_id,
     $object_id,
     $stock_relationship_id
   );
@@ -434,15 +459,15 @@ function tripal_stock_update_relationship ($stock_relationship_id, $subject_id,
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
-function tripal_stock_delete_relationship ($stock_relationship_id) {
+function tripal_stock_delete_relationship($stock_relationship_id) {
 
   $previous_db = tripal_db_set_active('chado');
   db_query(
-    "DELETE FROM stock_relationship WHERE stock_relationship_id=%d",
+    "DELETE FROM {stock_relationship} WHERE stock_relationship_id=%d",
     $stock_relationship_id
   );
   tripal_db_set_active($previous_db);
@@ -450,27 +475,27 @@ function tripal_stock_delete_relationship ($stock_relationship_id) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
-function theme_tripal_stock_edit_ALL_relationships_form ($form) {
+function theme_tripal_stock_edit_ALL_relationships_form($form) {
   $output = '';
-  
+
   $output .= '<br><fieldset>';
   $output .= '<legend>Edit Already Existing Relationships<span class="form-optional" title="This field is optional">(optional)</span></legend>';
   $output .= '<p>Each relationship for this stock is listed below, one per line. The textboxes indicating '
-  	    .'the subject and object of the relationship can contain the uniquename, name, database '
-	    .'reference or synonym of a stock of the same organism.</p>';
+        . 'the subject and object of the relationship can contain the uniquename, name, database '
+      . 'reference or synonym of a stock of the same organism.</p>';
   $output .= '<table>';
   $output .= '<tr><th>#</th><th>Subject</th><th>Type</th><th>Object</th><th></th></tr>';
 
   for ($i=1; $i<=$form['num_relationships']['#value']; $i++) {
-    $output .= '<tr><td>'.drupal_render($form["num-$i"]).'</td><td>'
-    	       .drupal_render($form["subject_id-$i"]).'</td><td>'
-	       .drupal_render($form["type_id-$i"]).'</td><td>'
-	       .drupal_render($form["object_id-$i"]).'</td><td>'
-	       .drupal_render($form["submit-$i"]).'</td></tr>';
+    $output .= '<tr><td>' . drupal_render($form["num-$i"]) . '</td><td>'
+             . drupal_render($form["subject_id-$i"]) . '</td><td>'
+         . drupal_render($form["type_id-$i"]) . '</td><td>'
+         . drupal_render($form["object_id-$i"]) . '</td><td>'
+         . drupal_render($form["submit-$i"]) . '</td></tr>';
   }
 
   $output .= '</table><br>';
@@ -494,21 +519,22 @@ function tripal_stock_list_relationships_for_node($stock_name, $subject_relation
 
     if (!empty($subject_relationships) ) {
       foreach ($subject_relationships as $s) {
-        $output .= '<tr><td>'.$s->subject_name.'</td><td>'.$s->relationship_type.'</td><td>'.$stock_name.'</td></tr>';
+        $output .= '<tr><td>' . $s->subject_name . '</td><td>' . $s->relationship_type . '</td><td>' . $stock_name . '</td></tr>';
       }
     }
 
     if (!empty($object_relationships) ) {
       foreach ($object_relationships as $o) {
-        $output .= '<tr><td>'.$stock_name.'</td><td>'.$o->relationship_type.'</td><td>'.$o->object_name.'</td></tr>';
+        $output .= '<tr><td>' . $stock_name . '</td><td>' . $o->relationship_type . '</td><td>' . $o->object_name . '</td></tr>';
       } // end of foreach property
     }
 
     $output .= '</table>';
-  } else {
-    $output = 'No Relationships Involving the Current Stock'; 
+  }
+  else {
+    $output = 'No Relationships Involving the Current Stock';
   }
 
   return $output;
 
-}
+}

+ 45 - 32
tripal_stock/tripal_stock-secondary_tables.inc

@@ -1,8 +1,11 @@
 <?php
-// $Id$
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -14,48 +17,52 @@ function tripal_stock_back_to_stock_button($form_state, $nid) {
     '#value' => $nid
   );
 
-  $form["submit-back"] = array( 
+  $form["submit-back"] = array(
     '#type' => 'submit',
-    '#value' => t('Back to Stock') 
+    '#value' => t('Back to Stock')
   );
 
   return $form;
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
 function tripal_stock_back_to_stock_button_submit($form, $form_state) {
-  drupal_goto('node/'.$form_state['values']['nid']);
+  drupal_goto('node/' . $form_state['values']['nid']);
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
 function tripal_stock_add_chado_properties_progress($current) {
 
-    $value = '<div class="form_progress"><div class="form_progress-text">'; 
+    $value = '<div class="form_progress"><div class="form_progress-text">';
 
-    if ($current == 'main') { $value .= '<span id="form-step-current">Create Basic Stock</span>'; } 
+    if ($current == 'main') {
+    $value .= '<span id="form-step-current">Create Basic Stock</span>'; }
     else { $value .= '<span id="form-step">Create Basic Stock</span>'; }
 
     $value .= '<span id="form-segway">  >>  </span>';
 
-    if ($current == 'properties') { $value .= '<span id="form-step-current">Add Synonyms & Properties</span>'; }
+    if ($current == 'properties') {
+    $value .= '<span id="form-step-current">Add Synonyms & Properties</span>'; }
     else { $value .= '<span id="form-step">Add Synonyms & Properties</span>'; }
 
-    $value .= '<span id="form-segway">  >>  </span>';                       
+    $value .= '<span id="form-segway">  >>  </span>';
 
-    if ($current == 'db_references') { $value .= '<span id="form-step-current">Add Database References</span>'; }
+    if ($current == 'db_references') {
+    $value .= '<span id="form-step-current">Add Database References</span>'; }
     else { $value .= '<span id="form-step">Add Database References</span>'; }
 
-    $value .= '<span id="form-segway">  >>  </span>';         
+    $value .= '<span id="form-segway">  >>  </span>';
 
-    if ($current == 'relationships') { $value .= '<span id="form-step-current">Add Relationships</span>'; }
+    if ($current == 'relationships') {
+    $value .= '<span id="form-step-current">Add Relationships</span>'; }
     else { $value .= '<span id="form-step">Add Relationships</span>'; }
 
     $value .= '</div></div>';
@@ -65,7 +72,7 @@ function tripal_stock_add_chado_properties_progress($current) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -85,7 +92,8 @@ function tripal_stock_add_chado_properties_navigate($form_state, $step, $nid) {
     'relationships' => 'node/%node/relationships'
   );
   $steps_value = array();
-  foreach ($steps as $k => $v) { $steps_value[] = $k.';'.$v; }
+  foreach ($steps as $k => $v) {
+  $steps_value[] = $k . ';' . $v; }
   $form['steps'] = array(
     '#type' => 'hidden',
     '#value' => implode('::', $steps_value)
@@ -114,7 +122,7 @@ function tripal_stock_add_chado_properties_navigate($form_state, $step, $nid) {
   }
 
   if ($step != $form['last_step']['#value']) {
-    $form['submit-next'] = array( 
+    $form['submit-next'] = array(
       '#type' => 'submit',
       '#value' => t('Next Step')
     );
@@ -122,7 +130,7 @@ function tripal_stock_add_chado_properties_navigate($form_state, $step, $nid) {
 
   if ($step == $form['last_step']['#value']) {
     $form['submit-finish'] = array(
-      '#type' => 'submit', 
+      '#type' => 'submit',
       '#value' => t('Finish')
     );
   }
@@ -131,13 +139,13 @@ function tripal_stock_add_chado_properties_navigate($form_state, $step, $nid) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
 function tripal_stock_add_chado_properties_navigate_submit($form, $form_state) {
 
-  $raw_steps = preg_split('/::/', $form_state['values']['steps']); 
+  $raw_steps = preg_split('/::/', $form_state['values']['steps']);
 
   $steps = array();
   $current_index = 'EMPTY';
@@ -146,7 +154,7 @@ function tripal_stock_add_chado_properties_navigate_submit($form, $form_state) {
   foreach ($raw_steps as $raw_step) {
     $step = preg_split('/;/', $raw_step);
     $steps[$i] = $step;
-    
+
     if ($step[0] == $form_state['values']['current_step']) {
       $current_index = $i;
     }
@@ -154,16 +162,19 @@ function tripal_stock_add_chado_properties_navigate_submit($form, $form_state) {
     $i++;
   }
   $num_steps = $i;
-  
-  if (strcmp($current_index,'EMPTY') == 0) {
+
+  if (strcmp($current_index, 'EMPTY') == 0) {
     // No Matching Step
-    drupal_set_message('Could not determine next step -'.$form_state['values']['current_step'].', please contact the administrator', 'error');
-  } elseif ($current_index == 0) {
+    drupal_set_message(t('Could not determine next step - %currentstep, please contact the administrator', array('%currentstep' => $form_state['values']['current_step'])), 'error');
+  }
+  elseif ($current_index == 0) {
     $next_goto = $steps[$current_index+1][1];
-  } elseif ($current_index == ($num_steps-1)) {
+  }
+  elseif ($current_index == ($num_steps-1)) {
     $prev_goto = $steps[$current_index-1][1];
     $next_goto = 'node/%node';
-  } else {
+  }
+  else {
     $prev_goto = $steps[$current_index-1][1];
     $next_goto = $steps[$current_index+1][1];
   }
@@ -172,10 +183,12 @@ function tripal_stock_add_chado_properties_navigate_submit($form, $form_state) {
     //replace %node
     $prev_goto = preg_replace('/%node/', $form_state['values']['nid'], $prev_goto);
     $_REQUEST['destination'] = $prev_goto;
-  } elseif ($form_state['clicked_button']['#value'] == t('Next Step') ) {
+  }
+  elseif ($form_state['clicked_button']['#value'] == t('Next Step') ) {
     $next_goto = preg_replace('/%node/', $form_state['values']['nid'], $next_goto);
     $_REQUEST['destination'] = $next_goto;
-  } elseif ($form_state['clicked_button']['#value'] == t('Finish') ) {
+  }
+  elseif ($form_state['clicked_button']['#value'] == t('Finish') ) {
     $next_goto = preg_replace('/%node/', $form_state['values']['nid'], $next_goto);
     $_REQUEST['destination'] = $next_goto;
   }
@@ -183,7 +196,7 @@ function tripal_stock_add_chado_properties_navigate_submit($form, $form_state) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -204,7 +217,7 @@ function tripal_stock_is_obsolete_form($node, $stock_id) {
 }
 
 /**
- * 
+ *
  *
  * @ingroup tripal_stock
  */
@@ -212,7 +225,7 @@ function tripal_stock_is_obsolete_form_submit($form, &$form_state) {
 
   $previous_db = tripal_db_set_active('chado');
   db_query(
-    "UPDATE stock SET is_obsolete='t' WHERE stock_id=%d",
+    "UPDATE {stock} SET is_obsolete='t' WHERE stock_id=%d",
     $form_state['values']['make_obsolete_stock_id']
   );
   tripal_db_set_active($previous_db);

+ 103 - 91
tripal_stock/tripal_stock.api.inc

@@ -1,11 +1,15 @@
 <?php
+/**
+ * @file
+ * @todo Add file header description
+ */
 
 /**
  * @defgroup tripal_stock_api Stock Module API
  * @ingroup tripal_api
  * @ingroup tripal_stock
  */
- 
+
 /**
  * Purpose: Return a given stock node using the nid
  *
@@ -17,53 +21,54 @@
  *
  * @ingroup tripal_stock_api
  */
-function tripal_stock_get_stock_by_nid ($nid) {
-	
-	return node_load($nid);
-	
+function tripal_stock_get_stock_by_nid($nid) {
+
+  return node_load($nid);
+
 }
 
 /**
  * Purpose: Return a given stock object using the stock id
  *
- * @return 
+ * @return
  *   Stock object created by node load
  *
  * @ingroup tripal_stock_api
  */
-function tripal_stock_get_stock_by_stock_id ($stock_id) {
+function tripal_stock_get_stock_by_stock_id($stock_id) {
 
   $sql = "SELECT nid FROM {chado_stock} WHERE stock_id=%d";
   $r = db_fetch_object(db_query($sql, $stock_id));
   if (!empty($r->nid)) {
     return node_load($r->nid);
-  } else {
+  }
+  else {
     watchdog('tripal_stock', 'tripal_stock_get_stock_by_stock_id(!stock_id): no stock with that stock_id is sync\'d with drupal', array('!stock_id' => $stock_id), WATCHDOG_WARNING);
-	}
+  }
+
+  return 0;
 
-	return 0;
-	
 }
 
 /**
  * Purpose: Returns all stocks currently sync'd with drupal
  *
- * @return 
+ * @return
  *   An array of node objects keyed by stock_id
  *
  * @ingroup tripal_stock_api
  */
 function tripal_stock_get_all_stocks() {
-	$sql = "SELECT stock_id, nid from {chado_stock}";
-	$resource = db_query($sql);
-	$stocks = array();
-	while ($r = db_fetch_object($resource)) {
-		$node = node_load($r->nid);
-		if ($node) {
+  $sql = "SELECT stock_id, nid from {chado_stock}";
+  $resource = db_query($sql);
+  $stocks = array();
+  while ($r = db_fetch_object($resource)) {
+    $node = node_load($r->nid);
+    if ($node) {
       $stocks[$r->stock_id] = $node;
     }
-	}
-	return $stocks;
+  }
+  return $stocks;
 }
 
 /**
@@ -72,7 +77,7 @@ function tripal_stock_get_all_stocks() {
  * @param $values
  *   An associative array containing the values for filtering the results.
  *
- * @return 
+ * @return
  *   An array of matching stock objects (produced using node_load)
  *   matching the given criteria
  *
@@ -96,20 +101,20 @@ function tripal_stock_get_all_stocks() {
  * @endcode
  * The above code selects a record from the chado stock table using three fields with values which
  * identify a stock or multiple stocks. Then the node for each stock identified is returned, if it
- * exists. The $values array is nested such that the organism is identified by way of the 
- * organism_id foreign key constraint by specifying the genus and species.  The cvterm is also 
+ * exists. The $values array is nested such that the organism is identified by way of the
+ * organism_id foreign key constraint by specifying the genus and species.  The cvterm is also
  * specified using its foreign key and the cv_id for the cvterm is nested as well.
  *
  * @ingroup tripal_stock_api
  */
 function tripal_stock_get_stocks($values) {
 
-  $stock_ids = tripal_core_chado_select('stock',array('stock_id'),$values);
+  $stock_ids = tripal_core_chado_select('stock', array('stock_id'), $values);
 
   // Change from stock_ids to nodes-----------------------------------
   $stock_ids = array_filter($stock_ids);
   $stock_ids = array_unique($stock_ids);
-  
+
   $stocks = array();
   foreach ($stock_ids as $stock_id) {
     $node = tripal_stock_get_stock_by_stock_id($stock_id->stock_id);
@@ -117,7 +122,7 @@ function tripal_stock_get_stocks($values) {
       $stocks[] = $node;
     }
   }
-  
+
   return $stocks;
 }
 
@@ -131,7 +136,7 @@ function tripal_stock_get_stocks($values) {
  * @param $stock_values
  *   An array of column_name => value where column_name is any column in the stock table
  *   and value is the value you want that column to be. This is used as a tripal_core_chado_select
- *   values array so nesting is allowed. 
+ *   values array so nesting is allowed.
  *
  * @return
  *   An array of stock node objects
@@ -167,14 +172,14 @@ function tripal_stock_get_stocks_by_stockprop($stockprop_values, $stock_values)
   if (!empty($stock_values)) {
     $stockprop_values['stock_id'] = $stock_values;
   }
-  
+
   //get stock_ids from stockprop table
-  $stock_ids = tripal_core_chado_select('stockprop',array('stock_id'),$stockprop_values);
+  $stock_ids = tripal_core_chado_select('stockprop', array('stock_id'), $stockprop_values);
 
   // Change from stock_ids to nodes-----------------------------------
   $stock_ids = array_filter($stock_ids);
   $stock_ids = array_unique($stock_ids);
-  
+
   $stocks = array();
   foreach ($stock_ids as $stock_id) {
     $node = tripal_stock_get_stock_by_stock_id($stock_id->stock_id);
@@ -182,13 +187,13 @@ function tripal_stock_get_stocks_by_stockprop($stockprop_values, $stock_values)
       $stocks[] = $node;
     }
   }
-  
+
   return $stocks;
 }
 
 /**
  * Purpose: Return all stocks with a given name identifier
- *  which might match stock.name, stock.uniquename, dbxref.accession, 
+ *  which might match stock.name, stock.uniquename, dbxref.accession,
  *  stockprop.value where stockprop.type='synonym'
  *
  * @param $name
@@ -203,13 +208,13 @@ function tripal_stock_get_stocks_by_stockprop($stockprop_values, $stock_values)
  */
 function tripal_stock_get_stock_by_name_identifier($name, $organism_id) {
   $stock_ids = array();
-  
+
   $options = array(
     'case_insensitive_columns' => array('name', 'uniquename', 'accession', 'value')
   );
-  
+
   // where name_identifier = stock.name-------------------------------
-  $current_stocks = tripal_core_chado_select('stock',array('stock_id'),
+  $current_stocks = tripal_core_chado_select('stock', array('stock_id'),
     array(
       'name' => $name,
       'organism_id' => $organism_id,
@@ -219,11 +224,12 @@ function tripal_stock_get_stock_by_name_identifier($name, $organism_id) {
     )
   );
   if (!empty($current_stocks)) {
-    foreach ($current_stocks as $c) { $stock_ids[] = $c->stock_id; }
+    foreach ($current_stocks as $c) {
+    $stock_ids[] = $c->stock_id; }
   }
 
   // where name_identifier = stock.uniquename-------------------------------
-  $current_stocks = tripal_core_chado_select('stock',array('stock_id'),
+  $current_stocks = tripal_core_chado_select('stock', array('stock_id'),
     array(
       'uniquename' => $name,
       'organism_id' => $organism_id,
@@ -233,12 +239,13 @@ function tripal_stock_get_stock_by_name_identifier($name, $organism_id) {
     )
   );
   if (!empty($current_stocks)) {
-    foreach ($current_stocks as $c) { $stock_ids[] = $c->stock_id; }
+    foreach ($current_stocks as $c) {
+    $stock_ids[] = $c->stock_id; }
   }
-  
+
   // where name_identifier = dbxref.accession-------------------------------
   // linked to stock through stock.dbxref
-  $current_stocks = tripal_core_chado_select('stock',array('stock_id'),
+  $current_stocks = tripal_core_chado_select('stock', array('stock_id'),
     array(
       'dbxref_id' => array(
         'accession' => $name,
@@ -250,11 +257,12 @@ function tripal_stock_get_stock_by_name_identifier($name, $organism_id) {
     )
   );
   if (!empty($current_stocks)) {
-    foreach ($current_stocks as $c) { $stock_ids[] = $c->stock_id; }  
+    foreach ($current_stocks as $c) {
+    $stock_ids[] = $c->stock_id; }
   }
-  
+
   // linked to stock through stock_dbxref?
-  $current_stocks = tripal_core_chado_select('stock_dbxref',array('stock_id'),
+  $current_stocks = tripal_core_chado_select('stock_dbxref', array('stock_id'),
     array(
       'dbxref_id' => array(
         'accession' => $name,
@@ -268,12 +276,14 @@ function tripal_stock_get_stock_by_name_identifier($name, $organism_id) {
     )
   );
   if (!empty($current_stocks)) {
-    foreach ($current_stocks as $c) { $stock_ids[] = $c->stock_id; }  
+    foreach ($current_stocks as $c) {
+      $stock_ids[] = $c->stock_id;
+    }
   }
-  
+
   // where name_identifier = stockprop.value-------------------------------
-  // where type='synonym' 
-  $current_stocks = tripal_core_chado_select('stockprop',array('stock_id'),
+  // where type='synonym'
+  $current_stocks = tripal_core_chado_select('stockprop', array('stock_id'),
     array(
       'stock_id' => array(
         'organism_id' => $organism_id,
@@ -289,13 +299,15 @@ function tripal_stock_get_stock_by_name_identifier($name, $organism_id) {
     )
   );
   if (!empty($current_stocks)) {
-    foreach ($current_stocks as $c) { $stock_ids[] = $c->stock_id; }
+    foreach ($current_stocks as $c) {
+      $stock_ids[] = $c->stock_id;
+    }
   }
-  
+
   // Change from stock_ids to nodes-----------------------------------
   $stock_ids = array_filter($stock_ids);
   $stock_ids = array_unique($stock_ids);
-  
+
   $stocks = array();
   foreach ($stock_ids as $stock_id) {
     $node = tripal_stock_get_stock_by_stock_id($stock_id);
@@ -303,10 +315,10 @@ function tripal_stock_get_stock_by_name_identifier($name, $organism_id) {
       $stocks[] = $node;
     }
   }
-  
+
   return $stocks;
 }
- 
+
 /**
  * Implements hook_chado_stock_schema()
  *
@@ -329,21 +341,21 @@ function tripal_stock_chado_stock_schema() {
           'organism_id' => 'organism_id',
         ),
   );
-      
+
   $description['foreign keys']['dbxref'] = array(
         'table' => 'dbxref',
         'columns' => array(
           'dbxref_id' => 'dbxref_id',
         ),
   );
-      
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'type_id' => 'cvterm_id',
         ),
   );
-     
+
   $referring_tables = array(
     'stock_cvterm',
     'stock_dbxref',
@@ -351,10 +363,10 @@ function tripal_stock_chado_stock_schema() {
     'stock_pub',
     'stock_relationship',
     'stockcollection_stock',
-    'stockprop'  
+    'stockprop'
   );
   $description['referring_tables'] = $referring_tables;
-  
+
   return $description;
 }
 
@@ -371,21 +383,21 @@ function tripal_stock_chado_stock_schema() {
  */
 function tripal_stock_chado_stockprop_schema() {
   $description = array();
-  
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'type_id' => 'cvterm_id',
         ),
   );
-  
+
   $description['foreign keys']['stock'] = array(
         'table' => 'stock',
         'columns' => array(
           'stock_id' => 'stock_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -402,21 +414,21 @@ function tripal_stock_chado_stockprop_schema() {
  */
 function tripal_stock_chado_stockprop_pub_schema() {
   $description = array();
-  
+
   $description['foreign keys']['pub'] = array(
         'table' => 'pub',
         'columns' => array(
           'pub_id' => 'pub_id',
         ),
   );
-  
+
   $description['foreign keys']['stockprop'] = array(
         'table' => 'stockprop',
         'columns' => array(
           'stockprop_id' => 'stockprop_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -433,14 +445,14 @@ function tripal_stock_chado_stockprop_pub_schema() {
  */
 function tripal_stock_chado_stock_cvterm_schema() {
   $description = array();
-  
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'cvterm_id' => 'cvterm_id',
         ),
   );
-  
+
   $description['foreign keys']['stock'] = array(
         'table' => 'stock',
         'columns' => array(
@@ -454,7 +466,7 @@ function tripal_stock_chado_stock_cvterm_schema() {
           'pub_id' => 'pub_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -471,21 +483,21 @@ function tripal_stock_chado_stock_cvterm_schema() {
  */
 function tripal_stock_chado_stock_dbxref_schema() {
   $description = array();
-  
+
   $description['foreign keys']['dbxref'] = array(
         'table' => 'dbxref',
         'columns' => array(
           'dbxref_id' => 'dbxref_id',
         ),
   );
-  
+
   $description['foreign keys']['stock'] = array(
         'table' => 'stock',
         'columns' => array(
           'stock_id' => 'stock_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -502,21 +514,21 @@ function tripal_stock_chado_stock_dbxref_schema() {
  */
 function tripal_stock_chado_stock_genotype_schema() {
   $description = array();
-  
+
   $description['foreign keys']['genotype'] = array(
         'table' => 'genotype',
         'columns' => array(
           'genotype_id' => 'genotype_id',
         ),
   );
-  
+
   $description['foreign keys']['stock'] = array(
         'table' => 'stock',
         'columns' => array(
           'stock_id' => 'stock_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -533,21 +545,21 @@ function tripal_stock_chado_stock_genotype_schema() {
  */
 function tripal_stock_chado_stock_pub_schema() {
   $description = array();
-  
+
   $description['foreign keys']['pub'] = array(
         'table' => 'pub',
         'columns' => array(
           'pub_id' => 'pub_id',
         ),
   );
-  
+
   $description['foreign keys']['stock'] = array(
         'table' => 'stock',
         'columns' => array(
           'stock_id' => 'stock_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -564,14 +576,14 @@ function tripal_stock_chado_stock_pub_schema() {
  */
 function tripal_stock_chado_stock_relationship_schema() {
   $description = array();
-  
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'type_id' => 'cvterm_id',
         ),
   );
-  
+
   $description['foreign keys']['stock'] = array(
         'table' => 'stock',
         'columns' => array(
@@ -579,7 +591,7 @@ function tripal_stock_chado_stock_relationship_schema() {
           'object_id' => 'stock_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -596,21 +608,21 @@ function tripal_stock_chado_stock_relationship_schema() {
  */
 function tripal_stock_chado_stock_relationship_pub_schema() {
   $description = array();
-  
+
   $description['foreign keys']['pub'] = array(
         'table' => 'pub',
         'columns' => array(
           'pub_id' => 'pub_id',
         ),
   );
-  
+
   $description['foreign keys']['stock_relationship'] = array(
         'table' => 'stock_relationship',
         'columns' => array(
           'stock_relationship_id' => 'stock_relationship_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -627,21 +639,21 @@ function tripal_stock_chado_stock_relationship_pub_schema() {
  */
 function tripal_stock_chado_stockcollection_schema() {
   $description = array();
-  
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'type_id' => 'cvterm_id',
         ),
   );
-  
+
   $description['foreign keys']['contact'] = array(
         'table' => 'contact',
         'columns' => array(
           'contact_id' => 'contact_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -658,21 +670,21 @@ function tripal_stock_chado_stockcollection_schema() {
  */
 function tripal_stock_chado_stockcollection_stock_schema() {
   $description = array();
-  
+
   $description['foreign keys']['stock'] = array(
         'table' => 'stock',
         'columns' => array(
           'stock_id' => 'stock_id',
         ),
   );
-  
+
   $description['foreign keys']['stockcollection'] = array(
         'table' => 'stockcollection',
         'columns' => array(
           'stockcollection_id' => 'stockcollection_id',
         ),
   );
-  
+
   return $description;
 }
 
@@ -689,20 +701,20 @@ function tripal_stock_chado_stockcollection_stock_schema() {
  */
 function tripal_stock_chado_stockcollectionprop_schema() {
   $description = array();
-  
+
   $description['foreign keys']['cvterm'] = array(
         'table' => 'cvterm',
         'columns' => array(
           'type_id' => 'cvterm_id',
         ),
   );
-  
+
   $description['foreign keys']['stockcollection'] = array(
         'table' => 'stockcollection',
         'columns' => array(
           'stockcollection_id' => 'stockcollection_id',
         ),
   );
-  
+
   return $description;
-}
+}

+ 37 - 37
tripal_stock/tripal_stock.install

@@ -1,5 +1,5 @@
 <?php
-// $Id$
+
 
 /**
  * Install the tripal stock module including it's content type
@@ -8,55 +8,55 @@
 
 /** Implementation of hook_install() */
 function tripal_stock_install() {
-	drupal_install_schema('tripal_stock');
+  drupal_install_schema('tripal_stock');
 }
 
 /** Implementation of hook_uninstall() */
 function tripal_stock_uninstall() {
-	drupal_uninstall_schema('tripal_stock');
+  drupal_uninstall_schema('tripal_stock');
 
-	// Get the list of nodes to remove
-	$sql_lib_id = "SELECT nid, vid ".
+  // Get the list of nodes to remove
+  $sql_lib_id = "SELECT nid, vid ".
                  "FROM {node} ".
                  "WHERE type='chado_stock'";
-	$result = db_query($sql_lib_id);
+  $result = db_query($sql_lib_id);
 
-	//delete all nodes
-	while ($node = db_fetch_object($result)) {
-	node_delete($node->nid);
-	}
+  //delete all nodes
+  while ($node = db_fetch_object($result)) {
+  node_delete($node->nid);
+  }
 
 }
 
 /** Implementation of hook_schema() */
 function tripal_stock_schema() {
-	$schema['chado_stock'] = array(
-		'fields' => array(
+  $schema['chado_stock'] = array(
+    'fields' => array(
       'vid' => array(
-				'type' => 'int',
-				'unsigned' => TRUE,
-				'not null' => TRUE,
- 	 	  ),
-  	  'nid' => array(
-   	   	'type' => 'int',
-   	   	'unsigned' => TRUE,
-   	   	'not null' => TRUE,
-  	  ),
-   	 	'stock_id' => array(
-   	   	'type' => 'int',
-   	   	'unsigned' => TRUE,
-   	   	'not null' => TRUE,
-    	),
-  	),
-  	'indexes' => array(
-    	'stock_id' => array('stock_id'),
-     	'nid' => array('nid'),
-  	),
-  	'unique' => array(
-    	'stock_id' => array('stock_id'),
-  	),
-  	'primary key' => array('vid'),
-	);
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        ),
+      'nid' => array(
+          'type' => 'int',
+          'unsigned' => TRUE,
+          'not null' => TRUE,
+      ),
+        'stock_id' => array(
+          'type' => 'int',
+          'unsigned' => TRUE,
+          'not null' => TRUE,
+      ),
+    ),
+    'indexes' => array(
+      'stock_id' => array('stock_id'),
+       'nid' => array('nid'),
+    ),
+    'unique' => array(
+      'stock_id' => array('stock_id'),
+    ),
+    'primary key' => array('vid'),
+  );
 
   return $schema;
-}
+}

+ 316 - 299
tripal_stock/tripal_stock.module

@@ -1,5 +1,4 @@
 <?php
-// $Id$
 
 /**
  * @file
@@ -11,13 +10,13 @@
  * @{
  * Provides functions for managing chado stocks including creating details pages for each stock
  *
- * The Tripal Stock Module provides functionality for adding, editing, deleting and accessing chado 
- * stocks. The stock module was designed to store information about stock collections in a 
- * laboratory. What is called a stock could also be called a strain or an accession. There is a lot 
- * in common between a Drosophila stock and a Saccharomyces strain and an Arabidopsis line. They all 
- * come from some taxon, have genotypes, physical locations in the lab, some conceivable 
- * relationship with a publication, some conceivable relationship with a sequence feature (such as a 
- * transgene), and could be described by some ontology term. For more information about the chado 
+ * The Tripal Stock Module provides functionality for adding, editing, deleting and accessing chado
+ * stocks. The stock module was designed to store information about stock collections in a
+ * laboratory. What is called a stock could also be called a strain or an accession. There is a lot
+ * in common between a Drosophila stock and a Saccharomyces strain and an Arabidopsis line. They all
+ * come from some taxon, have genotypes, physical locations in the lab, some conceivable
+ * relationship with a publication, some conceivable relationship with a sequence feature (such as a
+ * transgene), and could be described by some ontology term. For more information about the chado
  * Stock Module see the GMOD Wiki Page (http://gmod.org/wiki/Chado_Stock_Module)
  * @}
  * @ingroup tripal_modules
@@ -51,7 +50,7 @@ function tripal_stock_menu() {
     'access arguments' => array('administer site configuration'),
     'type' => MENU_NORMAL_ITEM
   );
-  
+
   $items['admin/tripal/tripal_stock/configuration'] = array(
     'title' => t('Configuration'),
     'description' => t('Settings for Chado Stocks'),
@@ -60,39 +59,39 @@ function tripal_stock_menu() {
     'access arguments' => array('administer site configuration'),
     'type' => MENU_NORMAL_ITEM
   );
-  
+
   //Displaying stocks----------------------------
   $items['stocks'] = array(
-  	'menu_name' => ('primary-links'),
+    'menu_name' => ('primary-links'),
     'title' => t('Stocks'),
     'page callback' => 'tripal_stock_show_stocks',
     'access arguments' => array('access chado_stock content'),
-    'type' => MENU_NORMAL_ITEM,  
+    'type' => MENU_NORMAL_ITEM,
   );
 
   // Adding Secondary Properties-----------------
-  $items['node/%cs_node/properties'] = array(       
-    'title' => t('Add Properties & Synonyms'),                         
+  $items['node/%cs_node/properties'] = array(
+    'title' => t('Add Properties & Synonyms'),
     'description' => t('Settings for Chado Stocks'),
-    'page callback' => 'tripal_stock_add_ALL_property_page',           
-    'page arguments' => array(1), 
+    'page callback' => 'tripal_stock_add_ALL_property_page',
+    'page arguments' => array(1),
     'access arguments' => array('create chado_stock content'),
     'type' => MENU_CALLBACK
-  ); 
+  );
 
-  $items['node/%cs_node/db_references'] = array(                        
-    'title' => t('Add Database References'),                   
-    'description' => t('Settings for Chado Stocks'),              
-    'page callback' => 'tripal_stock_add_ALL_dbreferences_page',                         
+  $items['node/%cs_node/db_references'] = array(
+    'title' => t('Add Database References'),
+    'description' => t('Settings for Chado Stocks'),
+    'page callback' => 'tripal_stock_add_ALL_dbreferences_page',
     'page arguments' => array(1),
     'access arguments' => array('create chado_stock content'),
     'type' => MENU_CALLBACK
-  ); 
+  );
 
-  $items['node/%cs_node/relationships'] = array(                      
-    'title' => t('Add Relationships'),                      
-    'description' => t('Settings for Chado Stocks'),               
-    'page callback' => 'tripal_stock_add_ALL_relationships_page',                          
+  $items['node/%cs_node/relationships'] = array(
+    'title' => t('Add Relationships'),
+    'description' => t('Settings for Chado Stocks'),
+    'page callback' => 'tripal_stock_add_ALL_relationships_page',
     'page arguments' => array(1),
     'access arguments' => array('create chado_stock content'),
     'type' => MENU_CALLBACK
@@ -111,7 +110,7 @@ function tripal_stock_menu() {
 
     $items['node/%cs_node/edit_relationships'] = array(
     'title' => t('Edit Relationships'),
-    'description' => t('Settings for Chado Stocks'), 
+    'description' => t('Settings for Chado Stocks'),
     'page callback' => 'tripal_stock_edit_ALL_relationships_page',
     'page arguments' => array(1),
     'access arguments' => array('edit chado_stock content'),
@@ -134,9 +133,9 @@ function tripal_stock_menu() {
 /**
  * Implements Menu wildcard_load hook
  *
- * Purpose: Allows the node ID of a chado stock to be dynamically 
+ * Purpose: Allows the node ID of a chado stock to be dynamically
  *   pulled from the path. The node is loaded from this node ID
- *   and supplied to the page as an arguement. This is an example 
+ *   and supplied to the page as an arguement. This is an example
  *   of dynamic argument replacement using wildcards in the path.
  *
  * @param $nid
@@ -194,7 +193,7 @@ function tripal_stock_perm() {
  */
 function chado_stock_access($op, $node, $account) {
    if ($op == 'create') {
-      if(!user_access('create chado_stock content', $account)){
+      if (!user_access('create chado_stock content', $account)) {
         return FALSE;
       }
    }
@@ -227,7 +226,7 @@ function chado_stock_access($op, $node, $account) {
  *   An array with fields important for views integration
  *
  * @ingroup tripal_stock
- */ 
+ */
 function tripal_stock_views_api() {
    return array(
       'api' => 2.0,
@@ -243,11 +242,11 @@ function tripal_stock_views_api() {
  * @ingroup tripal_stock
  */
 function tripal_stock_theme() {
-	return array(
-		'tripal_stock_stock_table' => array (
-			'arguments' => array('stocks'),
-		),
-		// Property edit forms--------------------------
+  return array(
+    'tripal_stock_stock_table' => array(
+      'arguments' => array('stocks'),
+    ),
+    // Property edit forms--------------------------
     'tripal_stock_edit_ALL_properties_form' => array(
       'arguments' => array('form'),
       'function' => 'theme_tripal_stock_edit_ALL_properties_form',
@@ -261,27 +260,27 @@ function tripal_stock_theme() {
       'function' => 'theme_tripal_stock_edit_ALL_relationships_form',
     ),
     // Block Templates------------------------------
-    'tripal_stock_base' => array (
-      'arguments' => array('node'=> null),
+    'tripal_stock_base' => array(
+      'arguments' => array('node' => NULL),
       'template' => 'tripal_stock_base',
     ),
-    'tripal_stock_properties' => array (
-      'arguments' => array('node'=> null),
+    'tripal_stock_properties' => array(
+      'arguments' => array('node' => NULL),
       'template' => 'tripal_stock_properties',
     ),
-    'tripal_stock_references' => array (
-      'arguments' => array('node'=> null),
+    'tripal_stock_references' => array(
+      'arguments' => array('node' => NULL),
       'template' => 'tripal_stock_references',
     ),
-    'tripal_stock_relationships' => array (
-      'arguments' => array('node'=> null),
+    'tripal_stock_relationships' => array(
+      'arguments' => array('node' => NULL),
       'template' => 'tripal_stock_relationships',
-    ),    
-    'tripal_stock_synonyms' => array (
-      'arguments' => array('node'=> null),
+    ),
+    'tripal_stock_synonyms' => array(
+      'arguments' => array('node' => NULL),
       'template' => 'tripal_stock_synonyms',
     ),
-	);
+  );
 }
 
 /**
@@ -296,17 +295,18 @@ function tripal_stock_theme() {
  *
  * @ingroup tripal_stock
  */
-function tripal_stock_show_stocks () {
-	$sql = "SELECT COUNT(stock_id) FROM {chado_stock}";
+function tripal_stock_show_stocks() {
+  $sql = "SELECT COUNT(stock_id) FROM {chado_stock}";
    $no_stocks = db_result(db_query($sql));
-   if($no_stocks != 0) {
+   if ($no_stocks != 0) {
       $stocks = tripal_stock_get_all_stocks();
-      if($no_stocks != count($stocks)) {
+      if ($no_stocks != count($stocks)) {
          drupal_set_message("Synchronization needed.");
       }
-      return theme('tripal_stock_stock_table',&$stocks);
-   } else {
-      return t("No Stocks exists. Please contact administrators to ".
+      return theme('tripal_stock_stock_table', &$stocks);
+   }
+   else {
+      return t("No Stocks exists. Please contact administrators to " .
                "synchronize stocks.");
    }
 }
@@ -322,11 +322,11 @@ function tripal_stock_show_stocks () {
  *
  * @ingroup tripal_stock
  */
-function theme_tripal_stock_stock_table (&$stocks) {
+function theme_tripal_stock_stock_table(&$stocks) {
 
-	// cycle through the stocks and build the stocks page
-	$output = "<div id=\"stocks\">";
-	$output .= '<table>';
+  // cycle through the stocks and build the stocks page
+  $output = "<div id=\"stocks\">";
+  $output .= '<table>';
   $output .= "<tr>";
   $output .= "<th>Name</th>";
   $output .= "<th>Type</th>";
@@ -334,16 +334,16 @@ function theme_tripal_stock_stock_table (&$stocks) {
   $output .= "<th>Description</th>";
   $output .= "</tr>";
 
-  foreach($stocks as $node){
-		$output .= "<tr>";
-		$output .= "<td>".l($node->stock->name, "node/".$node->nid)."</td>";
-		$output .= "<td>".$node->stock->type_id->name."</td>";
-		$output .= "<td nowrap>".$node->stock->organism_id->common_name."</td>";
-		$output .= "<td>".$node->stock->description."</td>";
-		$output .= "</tr>";
-	}
-	$output .= "</table>";
-	$output .= "</div>";
+  foreach ($stocks as $node) {
+    $output .= "<tr>";
+    $output .= "<td>" . l($node->stock->name, "node/" . $node->nid) . "</td>";
+    $output .= "<td>" . $node->stock->type_id->name . "</td>";
+    $output .= "<td nowrap>" . $node->stock->organism_id->common_name . "</td>";
+    $output .= "<td>" . $node->stock->description . "</td>";
+    $output .= "</tr>";
+  }
+  $output .= "</table>";
+  $output .= "</div>";
 
    return $output;
 }
@@ -386,9 +386,9 @@ function chado_stock_load($node) {
     "SELECT stock_id as stock_id FROM {chado_stock} WHERE vid=%d",
     $node->vid
   ));
-  
+
   // Get stock content and add to node
-  $stock = tripal_core_generate_chado_var('stock', array('stock_id'=>$map->stock_id));
+  $stock = tripal_core_generate_chado_var('stock', array('stock_id' => $map->stock_id));
   //
   // move expandable fields downwards
   $node->expandable_fields = $stock->expandable_fields;
@@ -398,7 +398,7 @@ function chado_stock_load($node) {
   $node->expandable_nodes = $stock->expandable_nodes;
   unset($stock->expandable_nodes);
   $node->stock = $stock;
-  
+
   return $node;
 }
 
@@ -407,12 +407,12 @@ function chado_stock_load($node) {
  * Implements hook_form(): Creates the main Add/Edit/Delete Form for chado stocks
  *
  * Parts to be added by this form
- *     name, 
- *     uniquename, 
- *     description, 
+ *     name,
+ *     uniquename,
+ *     description,
  *     type => select from cvterm with key cvterm_id,
  *     organism => select from available with key organism_id
- *     main_db_reference => accession, version, description, db_name(select from dropdown) 
+ *     main_db_reference => accession, version, description, db_name(select from dropdown)
  *
  * @param $node
  *   An empty node object on insert OR the current stock node object on update
@@ -448,13 +448,13 @@ function chado_stock_form($node, $form_state) {
   // Will then do default redirect (to new node) on submit
   $form['simulate_multipart'] = array(
     '#type' => 'textfield',
-    '#attributes'=>array('style'=>"display:none"),
+    '#attributes' => array('style' => "display:none"),
     '#default_value' => TRUE
   );
 
   if (!isset($node->stock->uniquename)) {
-    $form['progress'] = array( 
-      '#type' => 'item', 
+    $form['progress'] = array(
+      '#type' => 'item',
       '#value' => tripal_stock_add_chado_properties_progress('main')
     );
   }
@@ -468,14 +468,14 @@ function chado_stock_form($node, $form_state) {
     '#type' => 'textfield',
     '#title' => t('Name'),
     '#default_value' => $node->stock->name,
-    '#required'	     => TRUE
+    '#required'       => TRUE
   );
 
   $form['names']['uniquename'] = array(
     '#type' => 'textfield',
     '#title' => t('Unique Name'),
     '#default_value' => $node->stock->uniquename,
-    '#required'	     => TRUE
+    '#required'       => TRUE
   );
 
   $form['names']['stock_id'] = array(
@@ -485,29 +485,33 @@ function chado_stock_form($node, $form_state) {
 
   $form['details'] = array(
     '#type' => 'fieldset',
-    '#title' =>	t('Stock Details')
+    '#title' =>  t('Stock Details')
   );
 
-  $type_options = tripal_cv_get_cvterm_options( variable_get('chado_stock_types_cv', 'null') );
+  $type_options = tripal_cv_get_cvterm_options( variable_get('chado_stock_types_cv', 'NULL') );
   $type_options[0] = 'Select a Type';
-  if ($node->nid == '') { $type_default = 0; } else { $type_default = $node->stock->type_id->cvterm_id; }
+  if ($node->nid == '') {
+  $type_default = 0; }
+  else { $type_default = $node->stock->type_id->cvterm_id; }
   $form['details']['type_id'] = array(
     '#type' => 'select',
     '#title' => t('Type of Stock'),
     '#options' => $type_options,
     '#default_value' => $type_default,
-    '#required'	  => TRUE,
+    '#required'    => TRUE,
   );
 
   $stock_oganism_options = tripal_organism_get_organism_options();
   $stock_oganism_options[0] = 'Select An Organism';
-  if ($node->nid == '') { $organism_default = 0; } else {  $organism_default = $node->stock->organism_id->organism_id; }
+  if ($node->nid == '') {
+  $organism_default = 0; }
+  else {  $organism_default = $node->stock->organism_id->organism_id; }
   $form['details']['organism_id'] = array(
     '#type' => 'select',
     '#title' => t('Source Organism for stock'),
     '#default_value' => $organism_default,
     '#options' => $stock_oganism_options,
-    '#required'	  => TRUE
+    '#required'    => TRUE
   );
 
 
@@ -538,7 +542,9 @@ function chado_stock_form($node, $form_state) {
 
   $db_options = tripal_db_get_db_options();
   $db_options[0] = 'Select a Database';
-  if ($node->nid == '') { $db_default = 0; } else { $db_default = $node->stock->dbxref_id->db_id->db_id; }
+  if ($node->nid == '') {
+  $db_default = 0; }
+  else { $db_default = $node->stock->dbxref_id->db_id->db_id; }
   $form['database_reference']['database'] = array(
     '#type' => 'select',
     '#title' => t('Database'),
@@ -561,31 +567,33 @@ function chado_stock_form($node, $form_state) {
  */
 function chado_stock_validate($node, &$form) {
 
-	$int_in_chado_sql = "SELECT count(*) as count FROM %s WHERE %s=%d";
-	$string_in_chado_sql = "SELECT count(*) as count FROM %s WHERE %s='%s'";
-	
+  $int_in_chado_sql = "SELECT count(*) as count FROM %s WHERE %s=%d";
+  $string_in_chado_sql = "SELECT count(*) as count FROM %s WHERE %s='%s'";
+
   // Validate Uniquename only if add
   if (empty($node->stock_id)) {
-  	$previous_db = tripal_db_set_active('chado');
-  	$chado_row = db_fetch_object(db_query("SELECT * FROM stock WHERE uniquename='".$node->uniquename."'"));
-  	tripal_db_set_active($previous_db);
-  	if(!empty($chado_row->stock_id)) {
-  		$drupal_row = db_fetch_object(db_query("SELECT * FROM {chado_stock} WHERE stock_id=".$chado_row->stock_id));
-  		if (!empty($drupal_row->nid)) {
-  			$link = l('node/'.$drupal_row->nid, $node->uniquename);
-  			form_set_error('uniquename', "There is already a stock with that uniquename $link. Please enter another uniquename.");
-			} else {
-				form_set_error('uniquename', "There is already a stock with that uniquename (although it's not sync'd with drupal). Please enter another uniquename.");
-			}
-  	}
+    $previous_db = tripal_db_set_active('chado');
+    $chado_row = db_fetch_object(db_query("SELECT * FROM {stock} WHERE uniquename='" . $node->uniquename . "'"));
+    tripal_db_set_active($previous_db);
+    if (!empty($chado_row->stock_id)) {
+      $drupal_row = db_fetch_object(db_query("SELECT * FROM {chado_stock} WHERE stock_id=" . $chado_row->stock_id));
+      if (!empty($drupal_row->nid)) {
+        $link = l('node/' . $drupal_row->nid, $node->uniquename);
+        form_set_error('uniquename', "There is already a stock with that uniquename $link. Please enter another uniquename.");
+      }
+      else {
+        form_set_error('uniquename', "There is already a stock with that uniquename (although it's not sync'd with drupal). Please enter another uniquename.");
+      }
+    }
   }
 
 
   // Check Type of Stock is valid cvterm_id in chado ( $form['values']['details']['type_id'] )
   if ( $node->type_id == 0) {
     form_set_error('type_id', 'Please select a type of stock.');
-  } else {
-  	$previous_db = tripal_db_set_active('chado');
+  }
+  else {
+    $previous_db = tripal_db_set_active('chado');
     $num_rows = db_fetch_object(db_query($int_in_chado_sql, 'cvterm', 'cvterm_id', $node->type_id));
     tripal_db_set_active($previous_db);
     if ( $num_rows->count != 1) {
@@ -595,8 +603,9 @@ function chado_stock_validate($node, &$form) {
   // Check Source Organism is valid organism_id in chado ( $form['values']['details']['organism_id'] )
   if ( $node->organism_id == 0) {
     form_set_error('organism_id', 'Please select a source organism for this stock');
-  } else {
-  	$previous_db = tripal_db_set_active('chado');
+  }
+  else {
+    $previous_db = tripal_db_set_active('chado');
     $num_rows = db_fetch_object(db_query($int_in_chado_sql, 'organism', 'organism_id', $node->organism_id));
     tripal_db_set_active($previous_db);
     if ( $num_rows->count != 1 ) {
@@ -604,12 +613,13 @@ function chado_stock_validate($node, &$form) {
   }
 
   // Check if Accession also database
-  if ($node->accession != '') { 
+  if ($node->accession != '') {
     if ($node->database == 0) {
       // there is an accession but no database selected
       form_set_error('database', 'You need to enter both a database and an accession for that database in order to add a database reference.');
     }
-  } else {
+  }
+  else {
     if ($node->database > 0) {
       // there is a database selected but no accession
       form_set_error('accession', 'You need to enter both a database and an accession for that database in order to add a database reference.');
@@ -618,7 +628,7 @@ function chado_stock_validate($node, &$form) {
 
   // Check database is valid db_id in chado ( $form['values']['database_reference']['database'] )
   if ( $node->database > 0) {
-  	$previous_db = tripal_db_set_active('chado');
+    $previous_db = tripal_db_set_active('chado');
     $num_rows = db_fetch_object(db_query($int_in_chado_sql, 'db', 'db_id', $node->database));
     tripal_db_set_active($previous_db);
     if ($num_rows->count != 1) {
@@ -639,51 +649,52 @@ function chado_stock_validate($node, &$form) {
  * @ingroup tripal_stock
  */
 function chado_stock_insert($node) {
-  
+
   //If the chado stock exists
   // then don't create but simply link to node
   if ($node->chado_stock_exists) {
-  	if (!empty($node->stock_id)) {
-  		db_query(
-    		"INSERT INTO {chado_stock} (nid, vid, stock_id) "
-    		."VALUES (%d, %d, %d)",
-    		$node->nid,
-    		$node->vid,
-    		$node->stock_id
-  		);
-  	}
+    if (!empty($node->stock_id)) {
+      db_query(
+        "INSERT INTO {chado_stock} (nid, vid, stock_id) "
+        ."VALUES (%d, %d, %d)",
+        $node->nid,
+        $node->vid,
+        $node->stock_id
+      );
+    }
     return $node;
   }
-  
-	// create dbxref
+
+  // create dbxref
   if ( !empty($node->accession) ) {
-    if ( !empty($node->database) ) { 
+    if ( !empty($node->database) ) {
       $values = array(
-      	'db_id' => $node->database,
-      	'accession' => $node->accession,
+        'db_id' => $node->database,
+        'accession' => $node->accession,
       );
-      if (!tripal_core_chado_select('dbxref',array(dbxref_id), $values)) {
-      	$values['description'] = $node->db_description;
-      	$values['version'] = '1';
-      	$dbxref_status = tripal_core_chado_insert('dbxref', $values);
-      	if (!$dbxref_status) {
-      		drupal_set_message('Unable to add database reference to this stock.', 'warning');
-      		watchdog('tripal_stock', 
-      			'Insert Stock: Unable to create dbxref where values:%values', 
-      			array('%values' => print_r($values, TRUE)),
-      			WATCHDOG_WARNING
-      		);
-      	}
-      } else { $dbxref_status = 1; }
-  	}
+      if (!tripal_core_chado_select('dbxref', array(dbxref_id), $values)) {
+        $values['description'] = $node->db_description;
+        $values['version'] = '1';
+        $dbxref_status = tripal_core_chado_insert('dbxref', $values);
+        if (!$dbxref_status) {
+          drupal_set_message('Unable to add database reference to this stock.', 'warning');
+          watchdog('tripal_stock',
+            'Insert Stock: Unable to create dbxref where values:%values',
+            array('%values' => print_r($values, TRUE)),
+            WATCHDOG_WARNING
+          );
+        }
+      }
+      else { $dbxref_status = 1; }
+    }
   }
-  
+
   // create stock
-  if($dbxref_status) {
-		$values = array(
+  if ($dbxref_status) {
+    $values = array(
       'dbxref_id' => array(
-      	'db_id' => $node->database, 
-      	'accession' => $node->accession
+        'db_id' => $node->database,
+        'accession' => $node->accession
       ),
       'organism_id' => $node->organism_id,
       'name' => $node->title,
@@ -692,8 +703,9 @@ function chado_stock_insert($node) {
       'type_id' => $node->type_id
     );
     $stock_status = tripal_core_chado_insert('stock', $values);
-  } else {
-		$values = array(
+  }
+  else {
+    $values = array(
       'organism_id' => $node->organism_id,
       'name' => $node->title,
       'uniquename' => $node->uniquename,
@@ -705,39 +717,41 @@ function chado_stock_insert($node) {
 
   // create drupal chado_stock entry
   if ($stock_status) {
-	  $values = array(
-    	'organism_id' => $node->organism_id,
-    	'uniquename' => $node->uniquename,
-    	'type_id' => $node->type_id
-  	);
-  	$chado_stock = tripal_core_chado_select('stock', array('stock_id'), $values);
-  	if (!empty($chado_stock[0]->stock_id)) {
-  		db_query(
-    		"INSERT INTO {chado_stock} (nid, vid, stock_id) "
-    		."VALUES (%d, %d, %d)",
-    		$node->nid,
-    		$node->vid,
-    		$chado_stock[0]->stock_id
-  		);
-
- 	 		//Move on to next stage of Stock Creation based on next_stage_path field
-  		if ($node->simulate_multipart) {
-    		$next_stage_path = preg_replace('/%node/', $node->nid, $node->next_step_path);  
-    		$_REQUEST['destination'] = $next_stage_path;
-  		}
-  	} else {
-			drupal_set_message('Error during stock creation.', 'error');
-			watchdog('tripal_stock', 
-      	'Insert Stock: Unable to find newly created stock where values:%values', 
-      	array('%values' => print_r($values, TRUE)),
-      	WATCHDOG_ERROR
+    $values = array(
+      'organism_id' => $node->organism_id,
+      'uniquename' => $node->uniquename,
+      'type_id' => $node->type_id
+    );
+    $chado_stock = tripal_core_chado_select('stock', array('stock_id'), $values);
+    if (!empty($chado_stock[0]->stock_id)) {
+      db_query(
+        "INSERT INTO {chado_stock} (nid, vid, stock_id) "
+        ."VALUES (%d, %d, %d)",
+        $node->nid,
+        $node->vid,
+        $chado_stock[0]->stock_id
+      );
+
+        //Move on to next stage of Stock Creation based on next_stage_path field
+      if ($node->simulate_multipart) {
+        $next_stage_path = preg_replace('/%node/', $node->nid, $node->next_step_path);
+        $_REQUEST['destination'] = $next_stage_path;
+      }
+    }
+    else {
+      drupal_set_message('Error during stock creation.', 'error');
+      watchdog('tripal_stock',
+        'Insert Stock: Unable to find newly created stock where values:%values',
+        array('%values' => print_r($values, TRUE)),
+        WATCHDOG_ERROR
       );
       return FALSE;
-  	}
-  } else {
-  	drupal_set_message('Error during stock creation.', 'error');
-    watchdog('tripal_stock', 
-    	'Insert Stock: Unable to create stock where values:%values', 
+    }
+  }
+  else {
+    drupal_set_message('Error during stock creation.', 'error');
+    watchdog('tripal_stock',
+      'Insert Stock: Unable to create stock where values:%values',
       array('%values' => print_r($values, TRUE)),
       WATCHDOG_WARNING
     );
@@ -763,70 +777,73 @@ function chado_stock_update($node) {
 
   if ($node->revision) {
     chado_stock_insert($node);
-  } else {
-
-		//update dbxref
-		if ($node->database) {
-			if($node->accession) {
-				$dbxref_mode = '';
-				$stock = tripal_core_chado_select(
-					'stock', 
-					array('dbxref_id', 'type_id'), 
-					array('stock_id' => $node->stock_id)
-				);
-			
-				if ($stock[0]->dbxref_id) {
-					$values = array(
-						'db_id' => $node->database,
-						'accession' => $node->accession,
-						'description' => $node->db_description
-					);
-					$dbxref_status = tripal_core_chado_update(
-						'dbxref', 
-						array('dbxref_id' => $stock[0]->dbxref_id), 
-						$values
-					);
-					$dbxref_mode = 'Update';
-				} else {
-					if ($stock[0]->type_id) {
-						//create the dbxref
-						//used the type_id as a control to check we have a stock but not a dbxref
-						$values = array(
-							'db_id' => $node->database,
-							'accession' => $node->accession,
-							'description' => $node->db_description,
-							'version' => '1',
-						);						
-						$dbxref_status = tripal_core_chado_insert(
-							'dbxref',
-							$values
-						);
-						$dbxref_mode = 'Create';
-					} else {
-						drupal_set_message('Unable to find stock to Update', 'error');
-						watchdog(
-							'tripal_stock',
-							'Stock Update: Unable to find stock to update using values: %values',
-							array('%values', print_r($values, TRUE)),
-							WATCHDOG_ERROR
-						);
-						return FALSE;
-					}
-				}
-			}
-		}
-		
-		if (!$dbxref_status) {
-			watchdog(
-				'tripal_stock',
-				'Stock Update: Unable to %mode main stock dbxref with values: %values',
-				array('%values' => print_r($values,TRUE), '%mode' => $dbxref_mode),
-				WATCHDOG_WARNING
-			);
-		}
+  }
+  else {
+
+    //update dbxref
+    if ($node->database) {
+      if ($node->accession) {
+        $dbxref_mode = '';
+        $stock = tripal_core_chado_select(
+          'stock',
+          array('dbxref_id', 'type_id'),
+          array('stock_id' => $node->stock_id)
+        );
+
+        if ($stock[0]->dbxref_id) {
+          $values = array(
+            'db_id' => $node->database,
+            'accession' => $node->accession,
+            'description' => $node->db_description
+          );
+          $dbxref_status = tripal_core_chado_update(
+            'dbxref',
+            array('dbxref_id' => $stock[0]->dbxref_id),
+            $values
+          );
+          $dbxref_mode = 'Update';
+        }
+        else {
+          if ($stock[0]->type_id) {
+            //create the dbxref
+            //used the type_id as a control to check we have a stock but not a dbxref
+            $values = array(
+              'db_id' => $node->database,
+              'accession' => $node->accession,
+              'description' => $node->db_description,
+              'version' => '1',
+            );
+            $dbxref_status = tripal_core_chado_insert(
+              'dbxref',
+              $values
+            );
+            $dbxref_mode = 'Create';
+          }
+          else {
+            drupal_set_message('Unable to find stock to Update', 'error');
+            watchdog(
+              'tripal_stock',
+              'Stock Update: Unable to find stock to update using values: %values',
+              array('%values', print_r($values, TRUE)),
+              WATCHDOG_ERROR
+            );
+            return FALSE;
+          }
+        }
+      }
+    }
+
+    if (!$dbxref_status) {
+      watchdog(
+        'tripal_stock',
+        'Stock Update: Unable to %mode main stock dbxref with values: %values',
+        array('%values' => print_r($values, TRUE), '%mode' => $dbxref_mode),
+        WATCHDOG_WARNING
+      );
+    }
 
     //can't change stock id which is all thats stored in drupal thus only update chado
-		$update_values = array(
+    $update_values = array(
       'organism_id' => $node->organism_id,
       'name' => $node->title,
       'uniquename' => $node->uniquename,
@@ -834,25 +851,25 @@ function chado_stock_update($node) {
       'type_id' => $node->type_id,
     );
     if ($dbxref_status) {
-    	$update_values['dbxref_id'] = array(
-    		'db_id' => $node->database, 
-    		'accession' => $node->accession
-    	);
+      $update_values['dbxref_id'] = array(
+        'db_id' => $node->database,
+        'accession' => $node->accession
+      );
     }
     $status = tripal_core_chado_update(
-    	'stock',
-    	array('stock_id' => $node->stock_id), 
-    	$update_values
+      'stock',
+      array('stock_id' => $node->stock_id),
+      $update_values
     );
-    
+
     if (!$status) {
-    	drupal_set_message('Unable to update stock', 'error');
-    	watchdog(
-    		'tripal_stock',
-    		'Stock Update: Unable to update stock using match values: %mvalues and update values: %uvalues',
-				array('%mvalues' => print_r(array('stock_id' => $node->stock_id),TRUE), '%uvalues' => print_r($update_values,TRUE)),
-				WATCHDOG_ERROR
-    	);
+      drupal_set_message('Unable to update stock', 'error');
+      watchdog(
+        'tripal_stock',
+        'Stock Update: Unable to update stock using match values: %mvalues and update values: %uvalues',
+        array('%mvalues' => print_r(array('stock_id' => $node->stock_id), TRUE), '%uvalues' => print_r($update_values, TRUE)),
+        WATCHDOG_ERROR
+      );
     }
   }
 
@@ -876,11 +893,11 @@ function chado_stock_delete($node) {
   // Set stock in chado: is_obsolete = TRUE
   $previous_db = tripal_db_set_active('chado');
   db_query(
-    "DELETE FROM stock WHERE stock_id=%d",
+    "DELETE FROM {stock} WHERE stock_id=%d",
     $node->stock->stock_id
   );
   tripal_db_set_active($previous_db);
-  
+
   //remove drupal node and all revisions
   db_query(
     "DELETE FROM {chado_stock} WHERE nid=%d",
@@ -892,7 +909,7 @@ function chado_stock_delete($node) {
  * Purpose: Implement Blocks relating to stock content
  *
  * @param $op
- *   What kind of information to retrieve about the block or blocks. 
+ *   What kind of information to retrieve about the block or blocks.
  *   Possible values include list, configure, save, view.
  * @param $delta
  *   Which block to return (not applicable if $op is 'list').
@@ -900,66 +917,66 @@ function chado_stock_delete($node) {
  *   If $op is 'save', the submitted form data from the configuration form.
  *
  * @return
- *   One of the following depending on $op: An array of block descriptions (list), the configuration 
- *   form (configure), nothing (save), an array defining subject and content for the block indexed 
+ *   One of the following depending on $op: An array of block descriptions (list), the configuration
+ *   form (configure), nothing (save), an array defining subject and content for the block indexed
  *   by $delta (view)
  *
  * @ingroup tripal_stock
  */
-function tripal_stock_block ($op = 'list', $delta = 0, $edit=array()) {
-  switch($op) {
+function tripal_stock_block($op = 'list', $delta = 0, $edit=array()) {
+  switch ($op) {
     case 'list':
       $blocks['base']['info'] = t('Tripal Stock Details');
       $blocks['base']['cache'] = BLOCK_NO_CACHE;
 
       $blocks['properties']['info'] = t('Tripal Stock Properties');
       $blocks['properties']['cache'] = BLOCK_NO_CACHE;
-         
+
       $blocks['references']['info'] = t('Tripal Stock References');
       $blocks['references']['cache'] = BLOCK_NO_CACHE;
-         
+
       $blocks['relationships_as_object']['info'] = t('Tripal Stock Relationships');
       $blocks['relationships_as_object']['cache'] = BLOCK_NO_CACHE;
-         
+
       $blocks['synonyms']['info'] = t('Tripal Stock Synonyms');
       $blocks['synonyms']['cache'] = BLOCK_NO_CACHE;
-                  
+
       return $blocks;
 
- 		case 'view':
- 			if(user_access('access chado_stock content') and arg(0) == 'node' and is_numeric(arg(1))) {
-      	$nid = arg(1);
-      	$node = node_load($nid);
- 
+     case 'view':
+       if (user_access('access chado_stock content') and arg(0) == 'node' and is_numeric(arg(1))) {
+        $nid = arg(1);
+        $node = node_load($nid);
+
         $block = array();
-        switch($delta){
-					case 'base':
-						$block['subject'] = t('Stock Details');
-						$block['content'] = theme('tripal_stock_base',$node);
-						break;
-						
-					case 'properties':
-						$block['subject'] = t('Properties');
-						$block['content'] = theme('tripal_stock_properties',$node);
-						break;
-						
-					case 'references':
-						$block['subject'] = t('References');
-						$block['content'] = theme('tripal_stock_references',$node);
-						break;
-						
-					case 'relationships':
-						$block['subject'] = t('Relationships');
-						$block['content'] = theme('tripal_stock_relationships',$node);
-						break;
-						
-					case 'synonyms':
-						$block['subject'] = t('Synonyms');
-						$block['content'] = theme('tripal_stock_synonyms',$node);
-						break;
-						
+        switch ($delta) {
+          case 'base':
+            $block['subject'] = t('Stock Details');
+            $block['content'] = theme('tripal_stock_base', $node);
+            break;
+
+          case 'properties':
+            $block['subject'] = t('Properties');
+            $block['content'] = theme('tripal_stock_properties', $node);
+            break;
+
+          case 'references':
+            $block['subject'] = t('References');
+            $block['content'] = theme('tripal_stock_references', $node);
+            break;
+
+          case 'relationships':
+            $block['subject'] = t('Relationships');
+            $block['content'] = theme('tripal_stock_relationships', $node);
+            break;
+
+          case 'synonyms':
+            $block['subject'] = t('Synonyms');
+            $block['content'] = theme('tripal_stock_synonyms', $node);
+            break;
+
         }
-				return $block;
-			}
-	}
+        return $block;
+      }
+  }
 }

+ 86 - 86
tripal_stock/tripal_stock.views.inc

@@ -90,32 +90,32 @@ function tripal_stock_views_handlers() {
      'views_handler_field_stockprop_by_type' => array(
        'parent' => 'views_handler_field_prerender_list',
      ),
-		'views_handler_field_stockprop_all' => array(
+    'views_handler_field_stockprop_all' => array(
        'parent' => 'views_handler_field_prerender_list',
      ),
-		'views_handler_field_stockrel_by_type' => array(
+    'views_handler_field_stockrel_by_type' => array(
        'parent' => 'views_handler_field_prerender_list',
      ),
-		'views_handler_field_stockrel_all' => array(
+    'views_handler_field_stockrel_all' => array(
        'parent' => 'views_handler_field_prerender_list',
      ),
-		'views_handler_field_stock_dbxref_by_type' => array(
+    'views_handler_field_stock_dbxref_by_type' => array(
        'parent' => 'views_handler_field_prerender_list',
      ),
-		'views_handler_field_stock_dbxref_all' => array(
+    'views_handler_field_stock_dbxref_all' => array(
        'parent' => 'views_handler_field_prerender_list',
      ),
      'views_handler_filter_stockprop_id' => array(
-     	'parent' => 'views_handler_filter',
+       'parent' => 'views_handler_filter',
      ),
      'views_handler_filter_stock_dbxref_id' => array(
-     	'parent' => 'views_handler_filter',
+       'parent' => 'views_handler_filter',
      ),
      'views_handler_filter_stock_relationship_id' => array(
-     	'parent' => 'views_handler_filter',
+       'parent' => 'views_handler_filter',
      ),
      'views_handler_argument_stockprop_id' => array(
-     	'parent' => 'views_handler_argument_string',
+       'parent' => 'views_handler_argument_string',
      ),
    ),
  );
@@ -126,7 +126,7 @@ function tripal_stock_views_handlers() {
  */
 function tripal_stock_views_data_alter(&$data) {
 
-  if( !(is_array($db_url) and array_key_exists('chado',$db_url)) ){
+  if ( !(is_array($db_url) and array_key_exists('chado', $db_url)) ) {
 
     // Add featuer relationship to node
     $data['node']['stock_chado_nid'] = array(
@@ -159,92 +159,92 @@ function tripal_stock_views_data_alter(&$data) {
  *
  * @ingroup tripal_stock_views
  */
-function tripal_stock_views_pre_render	(&$view) {
-	if (preg_match('/stock/', $view->base_table)) {
+function tripal_stock_views_pre_render  (&$view) {
+  if (preg_match('/stock/', $view->base_table)) {
 
-		//-----Node IDs---------------------------------------------
-		// @see file: tripal_core.views.inc function: tripal_core_add_node_ids_to_view (&$view);
+    //-----Node IDs---------------------------------------------
+    // @see file: tripal_core.views.inc function: tripal_core_add_node_ids_to_view (&$view);
 
-		// retrieve the stock_id for each record in the views current page
-		$stock_ids = array();
-		foreach ($view->result as $row_num => $row) {
-			$stock_ids[$row_num] = $row->stock_id;
-		}
+    // retrieve the stock_id for each record in the views current page
+    $stock_ids = array();
+    foreach ($view->result as $row_num => $row) {
+      $stock_ids[$row_num] = $row->stock_id;
+    }
 
-		if (sizeof($stock_ids)) {
+    if (sizeof($stock_ids)) {
 
-			//-----Properties------------------------------------------
-			$field_names = array_keys($view->field);
-			//if any property fields are in the current view
-			$property_field_names = preg_grep('/properties/',$field_names);
-			if (!empty($property_field_names)) {
-				$sql = "SELECT stockprop.*, cvterm.name as type_name FROM stockprop "
-					."INNER JOIN cvterm cvterm ON stockprop.type_id=cvterm.cvterm_id "
-					."WHERE stockprop.stock_id IN (".implode(',',$stock_ids).")";
-				$previous_db = tripal_db_set_active('chado');
-				$resource = db_query($sql);
-			 tripal_db_set_active($previous_db);
+      //-----Properties------------------------------------------
+      $field_names = array_keys($view->field);
+      //if any property fields are in the current view
+      $property_field_names = preg_grep('/properties/', $field_names);
+      if (!empty($property_field_names)) {
+        $sql = "SELECT stockprop.*, cvterm.name as type_name FROM {stockprop} "
+          ."INNER JOIN cvterm cvterm ON stockprop.type_id=cvterm.cvterm_id "
+          ."WHERE stockprop.stock_id IN (" . implode(',', $stock_ids) . ")";
+        $previous_db = tripal_db_set_active('chado');
+        $resource = db_query($sql);
+       tripal_db_set_active($previous_db);
 
-				$view->result[$key]->properties = array();
-				while ($r = db_fetch_object($resource)) {
-					$key = array_search($r->stock_id, $stock_ids);
-					$view->result[$key]->properties[] = $r;
-				}
-			}
+        $view->result[$key]->properties = array();
+        while ($r = db_fetch_object($resource)) {
+          $key = array_search($r->stock_id, $stock_ids);
+          $view->result[$key]->properties[] = $r;
+        }
+      }
 
-			//-----Relationships----------------------------------------
-			//if any relationship fields are in the current view
-			$relationship_field_names = preg_grep('/relationships/', $field_names);
-			if (!empty($relationship_field_names)) {
-				$sql = "SELECT stock_relationship.*, cvterm.name as type_name, "
-					."subject_stock.name as subject_name, object_stock.name as object_name "
-					."FROM stock_relationship "
-					."LEFT JOIN stock subject_stock ON stock_relationship.subject_id=subject_stock.stock_id "
-					."LEFT JOIN stock object_stock ON stock_relationship.object_id=object_stock.stock_id "
-					."LEFT JOIN cvterm cvterm ON stock_relationship.type_id = cvterm.cvterm_id "
-					."WHERE stock_relationship.subject_id IN (".implode(',',$stock_ids).") "
-					."OR stock_relationship.object_id IN (".implode(',',$stock_ids).") ";
-				$previous_db = tripal_db_set_active('chado');
-				$resource = db_query($sql);
-			 tripal_db_set_active($previous_db);
+      //-----Relationships----------------------------------------
+      //if any relationship fields are in the current view
+      $relationship_field_names = preg_grep('/relationships/', $field_names);
+      if (!empty($relationship_field_names)) {
+        $sql = "SELECT stock_relationship.*, cvterm.name as type_name, "
+          ."subject_stock.name as subject_name, object_stock.name as object_name "
+          ."FROM stock_relationship "
+          ."LEFT JOIN stock subject_stock ON stock_relationship.subject_id=subject_stock.stock_id "
+          ."LEFT JOIN stock object_stock ON stock_relationship.object_id=object_stock.stock_id "
+          ."LEFT JOIN cvterm cvterm ON stock_relationship.type_id = cvterm.cvterm_id "
+          ."WHERE stock_relationship.subject_id IN (" . implode(',', $stock_ids) . ") "
+          ."OR stock_relationship.object_id IN (" . implode(',', $stock_ids) . ") ";
+        $previous_db = tripal_db_set_active('chado');
+        $resource = db_query($sql);
+       tripal_db_set_active($previous_db);
 
-				while ($r = db_fetch_object($resource)) {
-					if (in_array($r->subject_id, $stock_ids)) {
-						$key = array_search($r->subject_id, $stock_ids);
-						$r->stock_id = $r->subject_id;
-						$view->result[$key]->relationships[] = clone $r;
-					}
-					if (in_array($r->object_id, $stock_ids)) {
-						$key = array_search($r->object_id, $stock_ids);
-						$r->stock_id = $r->object_id;
-						$view->result[$key]->relationships[] = clone $r;
-					}
-				}
-			}
+        while ($r = db_fetch_object($resource)) {
+          if (in_array($r->subject_id, $stock_ids)) {
+            $key = array_search($r->subject_id, $stock_ids);
+            $r->stock_id = $r->subject_id;
+            $view->result[$key]->relationships[] = clone $r;
+          }
+          if (in_array($r->object_id, $stock_ids)) {
+            $key = array_search($r->object_id, $stock_ids);
+            $r->stock_id = $r->object_id;
+            $view->result[$key]->relationships[] = clone $r;
+          }
+        }
+      }
 
-			//-----DB References--------------------------------------------
-			//if any dbxref fields are in the current view
-			$dbxref_field_names = preg_grep('/dbxref/',$field_names);
-			if (!empty($dbxref_field_names)) {
-				$sql = "SELECT stock_dbxref.*, dbxref.db_id, db.name as db_name, db.urlprefix, "
-					."dbxref.accession, dbxref.version, dbxref.description "
-					."FROM stock_dbxref "
-					."LEFT JOIN dbxref dbxref ON stock_dbxref.dbxref_id=dbxref.dbxref_id "
-					."LEFT JOIN db db ON dbxref.db_id=db.db_id "
-					."WHERE stock_dbxref.stock_id IN (".implode(',',$stock_ids).")";
-				$previous_db = tripal_db_set_active('chado');
-				$resource = db_query($sql);
-			 tripal_db_set_active($previous_db);
+      //-----DB References--------------------------------------------
+      //if any dbxref fields are in the current view
+      $dbxref_field_names = preg_grep('/dbxref/', $field_names);
+      if (!empty($dbxref_field_names)) {
+        $sql = "SELECT stock_dbxref.*, dbxref.db_id, db.name as db_name, db.urlprefix, "
+          ."dbxref.accession, dbxref.version, dbxref.description "
+          ."FROM stock_dbxref "
+          ."LEFT JOIN dbxref dbxref ON stock_dbxref.dbxref_id=dbxref.dbxref_id "
+          ."LEFT JOIN db db ON dbxref.db_id=db.db_id "
+          ."WHERE stock_dbxref.stock_id IN (" . implode(',', $stock_ids) . ")";
+        $previous_db = tripal_db_set_active('chado');
+        $resource = db_query($sql);
+       tripal_db_set_active($previous_db);
 
-				$view->result[$key]->dbxref = array();
-				while ($r = db_fetch_object($resource)) {
-					$key = array_search($r->stock_id, $stock_ids);
-					$view->result[$key]->dbxref[] = $r;
-				}
-			}
+        $view->result[$key]->dbxref = array();
+        while ($r = db_fetch_object($resource)) {
+          $key = array_search($r->stock_id, $stock_ids);
+          $view->result[$key]->dbxref[] = $r;
+        }
+      }
 
-		} //if there are stocks
-	} //if we're dealing with a stock view
+    } //if there are stocks
+  } //if we're dealing with a stock view
 }
 
 /**

+ 173 - 0
tripal_views/views/handlers/views_handler_field_chado_relationship_by_type.inc.orig

@@ -0,0 +1,173 @@
+<?php
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_field_chado_relationship_by_type.inc
+=======
+/**
+ * @file
+ * @todo Add file header description
+ */
+>>>>>>> 6.x-0.4-dev:tripal_natural_diversity/views/handlers/views_handler_field_chado_relationship_by_type.inc
+
+/**
+ * @file
+ * Field handler for terms.
+ */
+class views_handler_field_chado_relationship_by_type extends views_handler_field_prerender_list {
+  function init(&$view, $options) {
+    parent::init($view, $options);
+
+    // Boolean to determine whether
+    //    TRUE =>  value (property type)      -more than one property type displayed
+    //    FALSE => or just value is rendered  -only 1 porperty type is displayed
+    $this->display_type = TRUE;
+
+  }
+
+  function option_definition() {
+    $options = parent::option_definition();
+    $options['stockrel_type_ids'] = array('default' => array());
+    $options['stockrel_display_options'] = array('default' => array('subject', 'type', 'object'));
+    return $options;
+  }
+
+  /**
+   * Provide "link to term" option.
+   */
+  function options_form(&$form, &$form_state) {
+    parent::options_form($form, $form_state);
+
+    $form['stockrel_display_parts'] = array(
+      '#type' => 'checkboxes',
+      '#title' => t('Display Relationship Parts'),
+      '#description' => t('Check each part of the relationship you want displayed where the part '
+        .'of a relationship are: \<Subject\> \<Relationship Type\> \<Object\>. '
+        .'For example, with the relationship Sarah is the maternal parent of Fred '
+        .'if you checked only Object then "Fred" would be displayed.'),
+      '#options' => array(
+        'subject' => 'Subject',
+        'type' => 'Relationship Type',
+        'object' => 'Object',
+      ),
+      '#default_value' => array($this->options['stockrel_display_parts']['subject'], $this->options['stockrel_display_parts']['type'], $this->options['stockrel_display_parts']['object']),
+    );
+
+    $form['stockrel_display_rels'] = array(
+      '#type' => 'radios',
+      '#title' => t('Display Relationships Where'),
+      '#description' => t('Only relationships where the selected criteria is met will be shown. '
+        .'The parts of a relationship are: \<Subject\> \<Relationship Type\> \<Object\>. '
+        .'For example, with the relationships Sarah is the maternal parent of Fred and '
+        .'Fred is the paternal_parent of Max where Fred is the current stock, '
+        .'if you selected "Current Stock is the Object" only Sarah is the maternal parent of Fred'
+        .' would be displayed.'),
+      '#options' => array(
+        'subject' => 'Current Stock is the Subject',
+        'object' => 'Current Stock is the Object',
+        'all' => 'Current Stock is the Subject and/or Object',
+      ),
+      '#default_value' => $this->options['stockrel_display_rels'],
+    );
+
+    $options = tripal_cv_get_cvterm_options( variable_get('chado_stock_relationship_cv', 'null') );
+    $form['stockrel_type_ids'] = array(
+      '#type' => 'checkboxes',
+      '#title' => t('Relationship Types'),
+      '#options' => $options,
+      '#default_value' => $this->options['stockrel_type_ids'],
+    );
+  }
+
+  /**
+   * Add this term to the query
+   */
+  function query() {
+    $this->add_additional_fields();
+  }
+
+  function pre_render($values) {
+    $this->aliases['relationships'] = 'relationships';
+    $this->aliases['stock_id'] = 'stock_id';
+    $this->field_alias = $this->aliases['stock_id'];
+
+    //for each stock in this view page
+    foreach ($values as $result) {
+      if (!empty($result->{$this->aliases['relationships']})) {
+
+        // all relationships including the current stock
+        $relationships = $result->{$this->aliases['relationships']};
+        foreach ($relationships as $relationship) {
+          // perform filtering------
+          //type
+          if (!empty($this->options['stockrel_type_ids'])) {
+            $relationships2keep = array_filter($this->options['stockrel_type_ids']);
+            if (!in_array($relationship->type_id, $relationships2keep)) {
+              continue;
+            }
+          }
+
+          //"Display Relationships Where" criteria
+          if (preg_match('/subject/', $this->options['stockrel_display_rels'])) {
+            if ($relationship->stock_id != $relationship->subject_id) {
+              continue;
+            }
+          }
+          elseif (preg_match('/object/', $this->options['stockrel_display_rels'])) {
+            if ($relationship->stock_id != $relationship->object_id) {
+              continue;
+            }
+          }
+
+          // Add relationship to the list of items to be rendered
+          $this->items[$relationship->stock_id][$relationship->stock_relationship_id]['stock_id'] = $relationship->stock_id;
+          $this->items[$relationship->stock_id][$relationship->stock_relationship_id]['stock_relationship_id'] = $relationship->stock_relationship_id;
+          $this->items[$relationship->stock_id][$relationship->stock_relationship_id]['subject_id'] = $relationship->subject_id;
+          $this->items[$relationship->stock_id][$relationship->stock_relationship_id]['subject_name'] = $relationship->subject_name;
+          $this->items[$relationship->stock_id][$relationship->stock_relationship_id]['object_id'] = $relationship->object_id;
+          $this->items[$relationship->stock_id][$relationship->stock_relationship_id]['object_name'] = $relationship->object_name;
+          $this->items[$relationship->stock_id][$relationship->stock_relationship_id]['type_id'] = $relationship->type_id;
+          $this->items[$relationship->stock_id][$relationship->stock_relationship_id]['type_name'] = $relationship->type_name;
+        }
+      }
+    }
+  }
+
+  function render_item($count, $item) {
+    $text = array();
+
+    // Render Parts
+    if ($this->options['stockrel_display_parts']['subject']) {
+      $text[] = $item['subject_name'];
+    }
+    if ($this->options['stockrel_display_parts']['type']) {
+      $text[] = $item['type_name'];
+    }
+    if ($this->options['stockrel_display_parts']['object']) {
+      $text[] = $item['object_name'];
+    }
+
+    return implode(' ', $text);
+  }
+
+  function document_self_tokens(&$tokens) {
+    $tokens['[' . $this->options['id'] . '-stock_id' . ']'] = t('The Stock ID.');
+    $tokens['[' . $this->options['id'] . '-stock_relationship_id' . ']'] = t('Relationship ID');
+    $tokens['[' . $this->options['id'] . '-subject_id' . ']'] = t('Subject ID');
+    $tokens['[' . $this->options['id'] . '-subject_name' . ']'] = t('Subject Name');
+    $tokens['[' . $this->options['id'] . '-object_id' . ']'] = t('Object ID');
+    $tokens['[' . $this->options['id'] . '-object_name' . ']'] = t('Object Name');
+    $tokens['[' . $this->options['id'] . '-type_id' . ']'] = t('Type ID');
+    $tokens['[' . $this->options['id'] . '-type_name' . ']'] = t('Type Name');
+  }
+
+  function add_self_tokens(&$tokens, $item) {
+    $tokens['[' . $this->options['id'] . '-stock_id' . ']'] = $item['stock_id'];
+    $tokens['[' . $this->options['id'] . '-stock_relationship_id' . ']'] = $item['stock_relationship_id'];
+    $tokens['[' . $this->options['id'] . '-subject_id' . ']'] = $item['subject_id'];
+    $tokens['[' . $this->options['id'] . '-subject_name' . ']'] = $item['subject_name'];
+    $tokens['[' . $this->options['id'] . '-object_id' . ']'] = $item['object_id'];
+    $tokens['[' . $this->options['id'] . '-object_name' . ']'] = $item['object_name'];
+    $tokens['[' . $this->options['id'] . '-type_id' . ']'] = $item['type_id'];
+    $tokens['[' . $this->options['id'] . '-type_name' . ']'] = $item['type_name'];
+
+  }
+}
+

+ 258 - 0
tripal_views/views/handlers/views_handler_filter_stock_dbxref_id.inc.orig

@@ -0,0 +1,258 @@
+<?php
+
+/**
+ * @file
+ * Allows stocks to be filtered by associated database reference accession
+ *
+ * @ingroup tripal_stock
+ * @ingroup views_filter_handlers
+ */
+class views_handler_filter_stock_dbxref_id extends views_handler_filter {
+
+  function init(&$view, $options) {
+    parent::init($view, $options);
+    $this->db = $this->options['db'];
+  }
+
+  function options_form(&$form, &$form_state) {
+    if ($this->can_expose()) {
+      $this->show_expose_button($form, $form_state);
+    }
+
+    $form['op_val_start'] = array('#value' => '<div class="clear-block">');
+
+    $this->types_form($form, $form_state);
+
+    $this->show_operator_form($form, $form_state);
+    $form['operator']['#prefix'] = '<div class="views-right-70">';
+    $this->show_value_form($form, $form_state);
+    $form['op_val_end'] = array('#value' => '</div>');
+
+    if ($this->can_expose()) {
+      $this->show_expose_form($form, $form_state);
+    }
+
+  }
+
+  function query() {
+    $this-> db = array_filter($this->db);
+
+    if (preg_match('/IS NOT NULL/', $this->options['operator'])) {
+      $new_where_sql = "stock.stock_id IN "
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stock_dbxref_id.inc
+      ."(SELECT stock_dbxref.stock_id FROM stock_dbxref, dbxref WHERE stock_dbxref.dbxref_id=dbxref.dbxref_id AND dbxref.db_id IN (" . implode(', ', $this->db) . "))";
+=======
+      . "(SELECT stock_dbxref.stock_id FROM stock_dbxref, dbxref WHERE stock_dbxref.dbxref_id=dbxref.dbxref_id AND dbxref.db_id IN (" . implode(', ', $this->db) . "))";
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stock_dbxref_id.inc
+      $this->query->add_where($this->options['group'], $new_where_sql);
+    }
+    elseif (preg_match('/IS NULL/', $this->options['operator'])) {
+      $new_where_sql = "stock.stock_id NOT IN "
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stock_dbxref_id.inc
+      ."(SELECT stock_dbxref.stock_id FROM stock_dbxref, dbxref WHERE stock_dbxref.dbxref_id=dbxref.dbxref_id AND dbxref.db_id IN (" . implode(', ', $this->db) . "))";
+=======
+      . "(SELECT stock_dbxref.stock_id FROM stock_dbxref, dbxref WHERE stock_dbxref.dbxref_id=dbxref.dbxref_id AND dbxref.db_id IN (" . implode(', ', $this->db) . "))";
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stock_dbxref_id.inc
+      $this->query->add_where($this->options['group'], $new_where_sql);
+    }
+    else {
+      if (!empty($this->value)) {
+        $new_where_sql = "stock.stock_id IN "
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stock_dbxref_id.inc
+          ."(SELECT stock_dbxref.stock_id FROM stock_dbxref, dbxref WHERE stock_dbxref.dbxref_id=dbxref.dbxref_id "
+          ."AND dbxref.db_id IN (" . implode(', ', $this->db) . ") AND dbxref.accession" . $this->operator . "'" . $this->value . "')";
+=======
+          . "(SELECT stock_dbxref.stock_id FROM stock_dbxref, dbxref WHERE stock_dbxref.dbxref_id=dbxref.dbxref_id "
+          . "AND dbxref.db_id IN (" . implode(', ', $this->db) . ") AND dbxref.accession" . $this->operator . "'" . $this->value . "')";
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stock_dbxref_id.inc
+        $this->query->add_where($this->options['group'], $new_where_sql);
+      }
+    }
+  }
+
+  /////////// Form Parts/////////////////////////
+  function types_form(&$form, &$form_state) {
+
+    $db_options = tripal_db_get_db_options();
+    ksort($db_options);
+    $form['db'] = array(
+      '#type' => 'checkboxes',
+      '#title' => t('Databases'),
+      '#options' => $db_options,
+      '#default_value' => $this->db,
+      '#prefix' => '<div class="views-left-30">',
+      '#suffix' => '</div>',
+    );
+
+  }
+
+  function value_form(&$form, &$form_state) {
+    parent::value_form($form, $form_state);
+
+    $form['value'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Accession'),
+      '#default_value' => $this->value,
+    );
+  }
+
+  function operator_options() {
+    return array(
+      '=' => t('Is equal to'),
+      '!=' => t('Is not equal to'),
+      '~' => t('Contains'),
+      '!~' => t('Does not contain'),
+      'IS NOT NULL' => t('Is Present (Not Empty)'),
+      'IS NULL' => t('Is Absent (Empty)'),
+    );
+  }
+
+ /**
+  * Render our chunk of the exposed filter form when selecting
+  */
+  function exposed_form(&$form, &$form_state) {
+    if (empty($this->options['exposed'])) {
+      return;
+    }
+
+    if (!empty($this->options['expose']['use_type']) && !empty($this->options['expose']['type'])) {
+      $type = $this->options['expose']['type'];
+      $form[$type] = array(
+        '#type' => 'select',
+        '#title' => t('Database References'),
+        '#options' => $this->type_options(),
+        '#default_value' => $this->type,
+      );
+
+      if (isset($form[$type]['#title'])) {
+        unset($form[$type]['#title']);
+      }
+    }
+
+    if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator'])) {
+      $operator = $this->options['expose']['operator'];
+      $this->operator_form($form, $form_state);
+      $form[$operator] = $form['operator'];
+
+      if (isset($form[$operator]['#title'])) {
+        unset($form[$operator]['#title']);
+      }
+
+      $this->exposed_translate($form[$operator], 'operator');
+
+      unset($form['operator']);
+    }
+
+    if (!empty($this->options['expose']['identifier'])) {
+      $value = $this->options['expose']['identifier'];
+      $this->value_form($form, $form_state);
+      $form[$value] = $form['value'];
+
+      if (isset($form[$value]['#title']) && !empty($form[$value]['#type']) && $form[$value]['#type'] != 'checkbox') {
+        unset($form[$value]['#title']);
+      }
+
+      $this->exposed_translate($form[$value], 'value');
+
+      if (!empty($form['#type']) && ($form['#type'] == 'checkboxes' || ($form['#type'] == 'select' && !empty($form['#multiple'])))) {
+        unset($form[$value]['#default_value']);
+      }
+
+      if (!empty($form['#type']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
+        $form[$value]['#default_value'] = 'All';
+      }
+
+      if ($value != 'value') {
+        unset($form['value']);
+      }
+    }
+  }
+
+  function expose_form_left(&$form, &$form_state) {
+    $form['expose']['label'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $this->options['expose']['label'],
+      '#title' => t('Label'),
+      '#size' => 40,
+    );
+
+    $form['expose']['identifier'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $this->options['expose']['identifier'],
+      '#title' => t('Filter identifier'),
+      '#size' => 40,
+      '#description' => t('This will appear in the URL after the ? to identify this filter. Cannot be blank.'),
+    );
+
+  }
+
+  function expose_form_right(&$form, &$form_state) {
+    if (!empty($form['type']['#type'])) {
+      $form['expose']['use_type'] = array(
+        '#type' => 'checkbox',
+        '#title' => t('Unlock Database Reference'),
+        '#description' => t('When checked, the Database Reference will be exposed to the user'),
+        '#default_value' => !empty($this->options['expose']['use_type']),
+      );
+      $form['expose']['type'] = array(
+        '#type' => 'textfield',
+        '#default_value' => $this->options['expose']['type'],
+        '#title' => t('Database Reference identifier'),
+        '#size' => 40,
+        '#description' => t('This will appear in the URL after the ? to identify this Database Reference.'),
+        '#process' => array('views_process_dependency'),
+        '#dependency' => array(
+          'edit-options-expose-use-type' => array(1)
+        ),
+      );
+    }
+    else {
+      $form['expose']['type'] = array(
+        '#type' => 'value',
+        '#value' => '',
+      );
+    }
+
+    $form['expose']['identifier'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $this->options['expose']['identifier'],
+      '#title' => t('Filter identifier'),
+      '#size' => 40,
+      '#description' => t('This will appear in the URL after the ? to identify this filter. Cannot be blank.'),
+    );
+
+    if (!empty($form['operator']['#type'])) {
+      $form['expose']['use_operator'] = array(
+        '#type' => 'checkbox',
+        '#title' => t('Unlock operator'),
+        '#description' => t('When checked, the operator will be exposed to the user'),
+        '#default_value' => !empty($this->options['expose']['use_operator']),
+      );
+      $form['expose']['operator'] = array(
+        '#type' => 'textfield',
+        '#default_value' => $this->options['expose']['operator'],
+        '#title' => t('Operator identifier'),
+        '#size' => 40,
+        '#description' => t('This will appear in the URL after the ? to identify this operator.'),
+        '#process' => array('views_process_dependency'),
+        '#dependency' => array(
+          'edit-options-expose-use-operator' => array(1)
+        ),
+      );
+    }
+    else {
+      $form['expose']['operator'] = array(
+        '#type' => 'value',
+        '#value' => '',
+      );
+    }
+
+    $form['expose']['optional'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Optional'),
+      '#description' => t('This exposed filter is optional and will have added options to allow it not to be set.'),
+      '#default_value' => $this->options['expose']['optional'],
+    );
+  }
+}
+

+ 5 - 5
tripal_views/views/handlers/views_handler_filter_stock_relationship_id.inc

@@ -139,11 +139,11 @@ class views_handler_filter_stock_relationship_id extends views_handler_filter {
   function value_form(&$form, &$form_state) {
     parent::value_form($form, $form_state);
 
-    if (!$this->options['label']) {
-      $label = 'Stock Name';
+    if ($this->options['label']) {
+      $label = $this->options['label'];
     }
     else {
-      $label = $this->options['label'];
+      $label = 'Stock Name';
     }
     $form['value'] = array(
       '#type' => 'textfield',
@@ -157,7 +157,7 @@ class views_handler_filter_stock_relationship_id extends views_handler_filter {
   function type_options() {
 
     $previous_db = tripal_db_set_active('chado');
-    $result = db_query("SELECT cvt.cvterm_id as type_id, cvt.name FROM cvterm cvt WHERE cvt.cvterm_id IN (SELECT type_id FROM stock_relationship)");
+    $result = db_query("SELECT cvt.cvterm_id as type_id, cvt.name FROM {cvterm} cvt WHERE cvt.cvterm_id IN (SELECT type_id FROM {stock_relationship})");
     tripal_db_set_active($previous_db);
 
     $types = array();
@@ -314,4 +314,4 @@ class views_handler_filter_stock_relationship_id extends views_handler_filter {
       '#default_value' => $this->options['expose']['optional'],
     );
   }
-}
+}

+ 355 - 0
tripal_views/views/handlers/views_handler_filter_stock_relationship_id.inc.orig

@@ -0,0 +1,355 @@
+<?php
+/**
+ * @file
+ * @todo Add file header description
+ */
+
+/**
+ * @file
+ * Filter stocks via stock_relationships
+ */
+class views_handler_filter_stock_relationship_id extends views_handler_filter {
+
+  function query() {
+    if ($this->value) {
+
+      // get variable position
+      if ($this->options['fixed_position'] == 'subject_id') {
+        $this->options['variable_position'] = 'object_id';
+      }
+      else {
+        $this->options['variable_position'] = 'subject_id';
+      }
+
+      // determine if just checking presence
+      if (preg_match('/NULL/', $this->operator)) {
+          $where = 'stock.stock_id IN ('
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stock_relationship_id.inc
+            .'SELECT ' . $this->options['variable_position'] . ' FROM stock_relationship '
+            .'WHERE ' . $this->options['fixed_position'] . ' ' . $this->operator . ' AND type_id = ' . $this->options['type']
+          .')';
+=======
+            . 'SELECT ' . $this->options['variable_position'] . ' FROM {stock_relationship} '
+            . 'WHERE ' . $this->options['fixed_position'] . ' ' . $this->operator . ' AND type_id = ' . $this->options['type']
+          . ')';
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stock_relationship_id.inc
+          $this->query->add_where($this->options['group'], $where);
+      }
+      else {
+
+        // determine whether regex was requested
+        if ($this->operator == '~') {
+          $search_options = array('regex_columns' => array('name', 'uniquename'));
+          $this->operator = '=';
+        }
+        elseif ($this->operator == '!~') {
+          $search_options = array('regex_columns' => array('name', 'uniquename'));
+          $this->operator = '!=';
+        }
+        else {
+          $search_options = array();
+        }
+
+        // get fixed stock id(s)
+        $fixed_stock = tripal_core_chado_select('stock', array('stock_id'), array('uniquename' => $this->value), $search_options);
+        $fixed_stock_ids = array();
+        if ($fixed_stock[0]->stock_id) {
+          $fixed_stock_ids[] = $fixed_stock[0]->stock_id;
+        }
+        else {
+          $fixed_stock = tripal_core_chado_select('stock', array('stock_id'), array('name' => $this->value), $search_options);
+          if (sizeof($fixed_stock) > 1) {
+            foreach ($fixed_stock as $s) {
+              $fixed_stock_ids[] = $s->stock_id;
+            }
+          }
+          elseif (sizeof($fixed_stock) == 1) {
+            $fixed_stock_ids[] = $fixed_stock[0]->stock_id;
+          }
+        }
+
+        // determine operator
+        if ($this->operator == '=' && sizeof($fixed_stock_ids) > 1) {
+          $this->operator = 'IN';
+        }
+        elseif ($this->operator == '!=' && sizeof($fixed_stock_ids) > 1) {
+          $this->operator = 'NOT IN';
+        }
+
+        //generate where
+        if (sizeof($fixed_stock_ids) == 1) {
+          $where = 'stock.stock_id IN ('
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stock_relationship_id.inc
+            .'SELECT ' . $this->options['variable_position'] . ' FROM stock_relationship '
+            .'WHERE ' . $this->options['fixed_position'] . ' ' . $this->operator . ' ' . $fixed_stock_ids[0] . ' AND type_id = ' . $this->options['type']
+          .')';
+=======
+            . 'SELECT ' . $this->options['variable_position'] . ' FROM {stock_relationship} '
+            . 'WHERE ' . $this->options['fixed_position'] . ' ' . $this->operator . ' ' . $fixed_stock_ids[0] . ' AND type_id = ' . $this->options['type']
+          . ')';
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stock_relationship_id.inc
+          $this->query->add_where($this->options['group'], $where);
+        }
+        elseif (sizeof($fixed_stock_ids) > 1) {
+          $where = 'stock.stock_id IN ('
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stock_relationship_id.inc
+            .'SELECT ' . $this->options['variable_position'] . ' FROM stock_relationship '
+            .'WHERE ' . $this->options['fixed_position'] . ' ' . $this->operator . ' (' . implode(', ', $fixed_stock_ids) . ') AND type_id = ' . $this->options['type']
+          .')';
+          $this->query->add_where($this->options['group'], $where);
+        }
+        else {
+          drupal_set_message(t('No stock with the name or uniquename %value was found -No filtering done.', array('%value' => $this->value)), 'error');
+=======
+            . 'SELECT ' . $this->options['variable_position'] . ' FROM {stock_relationship} '
+            . 'WHERE ' . $this->options['fixed_position'] . ' ' . $this->operator . ' (' . implode(', ', $fixed_stock_ids) . ') AND type_id = ' . $this->options['type']
+          . ')';
+          $this->query->add_where($this->options['group'], $where);
+        }
+        else {
+          drupal_set_message(t('No stock with the name or uniquename %value was found -No filtering done.',  array('%value' => $this->value ), 'error'));
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stock_relationship_id.inc
+        }
+      } //end of not just checking presence
+    }
+  }
+
+  function options_form(&$form, &$form_state) {
+
+    if ($this->can_expose()) {
+      $this->show_expose_button($form, $form_state);
+    }
+
+    $instructions = 'This filter allows you to enter a stock, the position of that stock in the '
+      .'relationship and relationship type and only stocks with a relationship of the type described '
+      .'will be shown. For example, if you want all stocks where Fred is_paternal_parent_of, then '
+      .'you would enter Fred as the value, select is_paternal_parent_of as the Relationship Type '
+      .'and subject as the Fixed Position.';
+    $form['instructions'] = array(
+      '#type' => 'item',
+      '#value' => t($instructions)
+    );
+
+    $form['op_val_start'] = array('#value' => '<div class="clear-block">');
+
+    // left side
+
+    $this->types_form($form, $form_state);
+    $form['type']['#prefix'] = '<div class="views-left-50">';
+    $form['type']['#suffix'] = '</div>';
+
+    $this->show_operator_form($form, $form_state);
+    $form['operator']['#prefix'] = '<div class="views-right-50">';
+    $form['operator']['#suffix'] = '</div>';
+
+    $this->show_value_form($form, $form_state);
+    $form['value']['#prefix'] = '<div class="views-right-50">';
+    $form['value']['#suffix'] = '</div>';
+
+    // right side
+
+
+    $this->fixed_position_form($form, $form_state);
+    $form['fixed_position']['#prefix'] = '<div class="views-right-50">';
+    $form['fixed_position']['#suffix'] = '</div>';
+
+
+    if ($this->can_expose()) {
+      $this->show_expose_form($form, $form_state);
+    }
+
+    $form['op_val_start'] = array('#value' => '</div>');
+
+  }
+
+  function value_form(&$form, &$form_state) {
+    parent::value_form($form, $form_state);
+
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stock_relationship_id.inc
+    if (!$this->options['label']) {
+      $label = 'Stock Name';
+    }
+    else {
+      $label = $this->options['label'];
+=======
+    if ($this->options['label']) {
+      $label = $this->options['label'];
+    }
+    else {
+      $label = 'Stock Name';
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stock_relationship_id.inc
+    }
+    $form['value'] = array(
+      '#type' => 'textfield',
+      '#title' => t('%label', array('%label' => $label)),
+      '#default_value' => $this->value,
+      '#size' => 40,
+    );
+
+  }
+
+  function type_options() {
+
+    $previous_db = tripal_db_set_active('chado');
+    $result = db_query("SELECT cvt.cvterm_id as type_id, cvt.name FROM {cvterm} cvt WHERE cvt.cvterm_id IN (SELECT type_id FROM {stock_relationship})");
+    tripal_db_set_active($previous_db);
+
+    $types = array();
+    while ($r = db_fetch_object($result)) {
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stock_relationship_id.inc
+      $types[$r->type_id] = $r->name;
+    }
+=======
+    $types[$r->type_id] = $r->name; }
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stock_relationship_id.inc
+
+    return $types;
+  }
+
+  function types_form(&$form, &$form_state) {
+
+    $form['type'] = array(
+      '#type' => count($options) < 10 ? 'radios' : 'select',
+      '#title' => t('Relationship Types'),
+      '#options' => $this->type_options(),
+      '#default_value' => $this->options['type'],
+    );
+
+  }
+
+  function fixed_position_form(&$form, &$form_state) {
+
+    $form['fixed_position'] = array(
+      '#type' => 'radios',
+      '#title' => 'Position of Stock to Filter on',
+      '#description' => t('Where a relationship consists of a subject type object, this field indicates '
+        .'what position in the relationship remains fixed (is the stock entered as the value).'),
+      '#options' => array(
+        'subject_id' => 'Subject',
+        'object_id' => 'Object'
+      ),
+      '#default_value' => ($this->options['fixed_position']) ? $this->options['fixed_position'] : 'subject_id',
+    );
+
+  }
+
+  function operator_options() {
+    return array(
+      '=' => t('Is equal to'),
+      '!=' => t('Is not equal to'),
+      '~' => t('Contains'),
+      '!~' => t('Does not contain'),
+      'IS NOT NULL' => t('Is Present (Not Empty)'),
+      'IS NULL' => t('Is Absent (Empty)'),
+    );
+  }
+
+ /**
+  * Render our chunk of the exposed filter form when selecting
+  */
+  function exposed_form(&$form, &$form_state) {
+    if (empty($this->options['exposed'])) {
+      return;
+    }
+
+    if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator'])) {
+      $operator = $this->options['expose']['operator'];
+      $this->operator_form($form, $form_state);
+      $form[$operator] = $form['operator'];
+
+      if (isset($form[$operator]['#title'])) {
+        unset($form[$operator]['#title']);
+      }
+
+      $this->exposed_translate($form[$operator], 'operator');
+
+      unset($form['operator']);
+    }
+
+    if (!empty($this->options['expose']['identifier'])) {
+      $value = $this->options['expose']['identifier'];
+      $this->value_form($form, $form_state);
+      $form[$value] = $form['value'];
+
+      if (isset($form[$value]['#title']) && !empty($form[$value]['#type']) && $form[$value]['#type'] != 'checkbox') {
+        unset($form[$value]['#title']);
+      }
+
+      $this->exposed_translate($form[$value], 'value');
+
+      if (!empty($form['#type']) && ($form['#type'] == 'checkboxes' || ($form['#type'] == 'select' && !empty($form['#multiple'])))) {
+        unset($form[$value]['#default_value']);
+      }
+
+      if (!empty($form['#type']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
+        $form[$value]['#default_value'] = 'All';
+      }
+
+      if ($value != 'value') {
+        unset($form['value']);
+      }
+    }
+  }
+
+  function expose_form_left(&$form, &$form_state) {
+    $form['expose']['label'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $this->options['expose']['label'],
+      '#title' => t('Label'),
+      '#size' => 40,
+    );
+
+    $form['expose']['identifier'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $this->options['expose']['identifier'],
+      '#title' => t('Filter identifier'),
+      '#size' => 40,
+      '#description' => t('This will appear in the URL after the ? to identify this filter. Cannot be blank.'),
+    );
+
+  }
+
+  function expose_form_right(&$form, &$form_state) {
+
+    $form['expose']['identifier'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $this->options['expose']['identifier'],
+      '#title' => t('Filter identifier'),
+      '#size' => 40,
+      '#description' => t('This will appear in the URL after the ? to identify this filter. Cannot be blank.'),
+    );
+
+    if (!empty($form['operator']['#type'])) {
+      $form['expose']['use_operator'] = array(
+        '#type' => 'checkbox',
+        '#title' => t('Unlock operator'),
+        '#description' => t('When checked, the operator will be exposed to the user'),
+        '#default_value' => !empty($this->options['expose']['use_operator']),
+      );
+      $form['expose']['operator'] = array(
+        '#type' => 'textfield',
+        '#default_value' => $this->options['expose']['operator'],
+        '#title' => t('Operator identifier'),
+        '#size' => 40,
+        '#description' => t('This will appear in the URL after the ? to identify this operator.'),
+        '#process' => array('views_process_dependency'),
+        '#dependency' => array(
+          'edit-options-expose-use-operator' => array(1)
+        ),
+      );
+    }
+    else {
+      $form['expose']['operator'] = array(
+        '#type' => 'value',
+        '#value' => '',
+      );
+    }
+
+    $form['expose']['optional'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Optional'),
+      '#description' => t('This exposed filter is optional and will have added options to allow it not to be set.'),
+      '#default_value' => $this->options['expose']['optional'],
+    );
+  }
+}

+ 1 - 1
tripal_views/views/handlers/views_handler_filter_stockprop_id.inc

@@ -75,7 +75,7 @@ class views_handler_filter_stockprop_id extends views_handler_filter {
 
   function types_form(&$form, &$form_state) {
     $previous_db = tripal_db_set_active('chado');
-    $result = db_query("SELECT cvt.cvterm_id as type_id, cvt.name FROM cvterm cvt WHERE cvt.cvterm_id IN (SELECT type_id FROM stockprop)");
+    $result = db_query("SELECT cvt.cvterm_id as type_id, cvt.name FROM {cvterm} cvt WHERE cvt.cvterm_id IN (SELECT type_id FROM {stockprop})");
     tripal_db_set_active($previous_db);
 
     $types = array();

+ 340 - 0
tripal_views/views/handlers/views_handler_filter_stockprop_id.inc.orig

@@ -0,0 +1,340 @@
+<?php
+
+/**
+ * @file
+ * Allows stocks to be filtered by proeprty values
+ *
+ * @ingroup tripal_stock
+ * @ingroup views_filter_handlers
+ */
+class views_handler_filter_stockprop_id extends views_handler_filter {
+
+  function init(&$view, $options) {
+    parent::init($view, $options);
+    $this->type = $this->options['type'];
+  }
+
+  function options_form(&$form, &$form_state) {
+    if ($this->can_expose()) {
+      $this->show_expose_button($form, $form_state);
+    }
+
+    $form['op_val_start'] = array('#value' => '<div class="clear-block">');
+
+    $this->types_form($form, $form_state);
+
+    $this->show_operator_form($form, $form_state);
+    $form['operator']['#prefix'] = '<div class="views-right-70">';
+    $this->show_value_form($form, $form_state);
+    $form['op_val_end'] = array('#value' => '</div>');
+
+    if ($this->can_expose()) {
+      $this->show_expose_form($form, $form_state);
+    }
+
+  }
+
+  function options_validate(&$form, &$form_state) {
+    parent::options_validate($form, $form_state);
+
+    if (preg_match('/NULL/', $form_state['values']['options']['operator'])) {
+      $value = $form_state['values']['options']['value'];
+      if (!empty($value)) {
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stockprop_id.inc
+        drupal_set_message(t('The Value (%value) will be IGNORED when the Operator is set to "Is Present" or Is Absent".', array('%value' => $value)), 'warning');
+=======
+        drupal_set_message(t('The Value %value will be IGNORED when the Operator is set to "Is Present" or Is Absent". ', array('%value' => $value), 'warning'));
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stockprop_id.inc
+      }
+    }
+    else {
+      $value = $form_state['values']['options']['value'];
+      if (empty($value)) {
+        form_error($form['value'], t('Value required. The value will be used in conjunction with the operator. For example, if the '
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stockprop_id.inc
+           .'operator="Is equal to" and the value="2010" then only properties with a value of 2010 and the type specified will be displayed.'));
+=======
+           . 'operator="Is equal to" and the value="2010" then only properties with a value of 2010 and the type specified will be displayed.'));
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stockprop_id.inc
+      }
+    }
+
+    if (empty($form_state['values']['options']['type'])) {
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stockprop_id.inc
+      drupal_set_message(t('No Property Type was choosen. As such, any property type whose value %op %value will be displayed.',
+        array('%op' => $form_state['values']['options']['operator'], '%value' => $form_state['values']['options']['value'])), 'warning');
+=======
+      drupal_set_message('No Property Type was choosen. As such, any property type whose value '
+                 . $form_state['values']['options']['operator'] . ' ' . $form_state['values']['options']['value'] . ' will be displayed', 'warning');
+    }
+  }
+
+  function query() {
+    if (preg_match('/IS NOT NULL/', $this->options['operator'])) {
+      $new_where_sql = "stock.stock_id IN (SELECT stockprop.stock_id FROM stockprop WHERE stockprop.type_id=" . $this->type . ")";
+      $this->query->add_where($this->options['group'], $new_where_sql);
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stockprop_id.inc
+    }
+    elseif (preg_match('/IS NULL/', $this->options['operator'])) {
+      $new_where_sql = "stock.stock_id NOT IN (SELECT stockprop.stock_id FROM stockprop WHERE stockprop.type_id=" . $this->type . ")";
+      $this->query->add_where($this->options['group'], $new_where_sql);
+    }
+    elseif ($this->value) {
+      $new_where_sql = "stock.stock_id IN (SELECT stockprop.stock_id FROM stockprop WHERE stockprop.type_id=" . $this->type . " AND stockprop.value" . $this->operator . "'" . $this->value . "')";
+      $this->query->add_where($this->options['group'], $new_where_sql);
+    }
+
+  }
+
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stockprop_id.inc
+  function query() {
+    if (preg_match('/IS NOT NULL/', $this->options['operator'])) {
+      $new_where_sql = "stock.stock_id IN (SELECT stockprop.stock_id FROM stockprop WHERE stockprop.type_id=" . $this->type . ")";
+      $this->query->add_where($this->options['group'], $new_where_sql);
+    }
+    elseif (preg_match('/IS NULL/', $this->options['operator'])) {
+      $new_where_sql = "stock.stock_id NOT IN (SELECT stockprop.stock_id FROM stockprop WHERE stockprop.type_id=" . $this->type . ")";
+      $this->query->add_where($this->options['group'], $new_where_sql);
+    }
+    elseif ($this->value) {
+      $new_where_sql = "stock.stock_id IN (SELECT stockprop.stock_id FROM stockprop WHERE stockprop.type_id=" . $this->type . " AND stockprop.value" . $this->operator . "'" . $this->value . "')";
+      $this->query->add_where($this->options['group'], $new_where_sql);
+    }
+
+  }
+
+=======
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stockprop_id.inc
+  function types_form(&$form, &$form_state) {
+    $previous_db = tripal_db_set_active('chado');
+    $result = db_query("SELECT cvt.cvterm_id as type_id, cvt.name FROM {cvterm} cvt WHERE cvt.cvterm_id IN (SELECT type_id FROM {stockprop})");
+    tripal_db_set_active($previous_db);
+
+    $types = array();
+    while ($r = db_fetch_object($result)) {
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stockprop_id.inc
+      $types[$r->type_id] = $r->name;
+    }
+=======
+    $types[$r->type_id] = $r->name; }
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stockprop_id.inc
+
+    $form['type'] = array(
+      '#type' => count($options) < 10 ? 'radios' : 'select',
+      '#title' => t('Property Types'),
+      '#options' => $types,
+      '#default_value' => $this->type,
+      '#prefix' => '<div class="views-left-30">',
+      '#suffix' => '</div>',
+    );
+
+  }
+
+  function value_form(&$form, &$form_state) {
+    parent::value_form($form, $form_state);
+
+    if ($this->options['expose']['display_type'] == 'select') {
+
+      // Get options
+      $previous_db = tripal_db_set_active('chado');
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stockprop_id.inc
+      $resource = db_query("SELECT value FROM stockprop WHERE type_id=" . $this->type . " ORDER BY value");
+      tripal_db_set_active($previous_db);
+=======
+      $resource = db_query("SELECT value FROM {stockprop} WHERE type_id=" . $this->type . " ORDER BY value");
+     tripal_db_set_active($previous_db);
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stockprop_id.inc
+      while ($r = db_fetch_object($resource)) {
+        $options[$r->value] = $r->value;
+      }
+      $form['value'] = array(
+        '#type' => 'select',
+<<<<<<< HEAD:tripal_views/views/handlers/views_handler_filter_stockprop_id.inc
+        '#title' => t('%label', array('%label' => $this->options['label'])),
+=======
+        '#title' => t('%label', array('%title' => $this->options['label'])),
+>>>>>>> 6.x-0.4-dev:tripal_stock/views/handlers/views_handler_filter_stockprop_id.inc
+        '#options' => $options,
+        '#default_value' => $this->value,
+      );
+    }
+    else {
+      $form['value'] = array(
+        '#type' => 'textfield',
+        '#title' => t('Value'),
+        '#default_value' => $this->value,
+      );
+    }
+  }
+
+  function operator_options() {
+    return array(
+      '=' => t('Is equal to'),
+      '!=' => t('Is not equal to'),
+      '~' => t('Contains'),
+      '!~' => t('Does not contain'),
+      'IS NOT NULL' => t('Is Present (Not Empty)'),
+      'IS NULL' => t('Is Absent (Empty)'),
+    );
+  }
+
+ /**
+  * Render our chunk of the exposed filter form when selecting
+  */
+  function exposed_form(&$form, &$form_state) {
+    if (empty($this->options['exposed'])) {
+      return;
+    }
+
+    if (!empty($this->options['expose']['use_type']) && !empty($this->options['expose']['type'])) {
+      $type = $this->options['expose']['type'];
+      $form[$type] = array(
+        '#type' => 'select',
+        '#title' => t('Property Types'),
+        '#options' => $this->type_options(),
+        '#default_value' => $this->type,
+      );
+
+      if (isset($form[$type]['#title'])) {
+        unset($form[$type]['#title']);
+      }
+    }
+
+    if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator'])) {
+      $operator = $this->options['expose']['operator'];
+      $this->operator_form($form, $form_state);
+      $form[$operator] = $form['operator'];
+
+      if (isset($form[$operator]['#title'])) {
+        unset($form[$operator]['#title']);
+      }
+
+      $this->exposed_translate($form[$operator], 'operator');
+
+      unset($form['operator']);
+    }
+
+    if (!empty($this->options['expose']['identifier'])) {
+      $value = $this->options['expose']['identifier'];
+      $this->value_form($form, $form_state);
+      $form[$value] = $form['value'];
+
+      if (isset($form[$value]['#title']) && !empty($form[$value]['#type']) && $form[$value]['#type'] != 'checkbox') {
+        unset($form[$value]['#title']);
+      }
+
+      $this->exposed_translate($form[$value], 'value');
+
+      if (!empty($form['#type']) && ($form['#type'] == 'checkboxes' || ($form['#type'] == 'select' && !empty($form['#multiple'])))) {
+        unset($form[$value]['#default_value']);
+      }
+
+      if (!empty($form['#type']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
+        $form[$value]['#default_value'] = 'All';
+      }
+
+      if ($value != 'value') {
+        unset($form['value']);
+      }
+    }
+  }
+
+  function expose_form_left(&$form, &$form_state) {
+    $form['expose']['label'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $this->options['expose']['label'],
+      '#title' => t('Label'),
+      '#size' => 40,
+    );
+
+    $form['expose']['identifier'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $this->options['expose']['identifier'],
+      '#title' => t('Filter identifier'),
+      '#size' => 40,
+      '#description' => t('This will appear in the URL after the ? to identify this filter. Cannot be blank.'),
+    );
+
+    $form['expose']['display_type'] = array(
+      '#type' => 'radios',
+      '#default_value' => $this->options['expose']['display_type'],
+      '#title' => t('Display Type'),
+      '#description' => t('This will change the form item type of the exposed value form. ie: it can be used to let the user select the property value from a select box rather than a textfield.'),
+      '#options' => array(
+        'textfield' => 'Text Field',
+        'select' => 'Drop Down',
+      ),
+    );
+  }
+
+  function expose_form_right(&$form, &$form_state) {
+    if (!empty($form['type']['#type'])) {
+      $form['expose']['use_type'] = array(
+        '#type' => 'checkbox',
+        '#title' => t('Unlock Property Type'),
+        '#description' => t('When checked, the property type will be exposed to the user'),
+        '#default_value' => !empty($this->options['expose']['use_type']),
+      );
+      $form['expose']['type'] = array(
+        '#type' => 'textfield',
+        '#default_value' => $this->options['expose']['type'],
+        '#title' => t('Property Type identifier'),
+        '#size' => 40,
+        '#description' => t('This will appear in the URL after the ? to identify this property type.'),
+        '#process' => array('views_process_dependency'),
+        '#dependency' => array(
+          'edit-options-expose-use-type' => array(1)
+        ),
+      );
+    }
+    else {
+      $form['expose']['type'] = array(
+        '#type' => 'value',
+        '#value' => '',
+      );
+    }
+
+    $form['expose']['identifier'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $this->options['expose']['identifier'],
+      '#title' => t('Filter identifier'),
+      '#size' => 40,
+      '#description' => t('This will appear in the URL after the ? to identify this filter. Cannot be blank.'),
+    );
+
+    if (!empty($form['operator']['#type'])) {
+      $form['expose']['use_operator'] = array(
+        '#type' => 'checkbox',
+        '#title' => t('Unlock operator'),
+        '#description' => t('When checked, the operator will be exposed to the user'),
+        '#default_value' => !empty($this->options['expose']['use_operator']),
+      );
+      $form['expose']['operator'] = array(
+        '#type' => 'textfield',
+        '#default_value' => $this->options['expose']['operator'],
+        '#title' => t('Operator identifier'),
+        '#size' => 40,
+        '#description' => t('This will appear in the URL after the ? to identify this operator.'),
+        '#process' => array('views_process_dependency'),
+        '#dependency' => array(
+          'edit-options-expose-use-operator' => array(1)
+        ),
+      );
+    }
+    else {
+      $form['expose']['operator'] = array(
+        '#type' => 'value',
+        '#value' => '',
+      );
+    }
+
+    $form['expose']['optional'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Optional'),
+      '#description' => t('This exposed filter is optional and will have added options to allow it not to be set.'),
+      '#default_value' => $this->options['expose']['optional'],
+    );
+  }
+
+
+}

Some files were not shown because too many files changed in this diff