Bläddra i källkod

Merged in 6.x-0.4-dev after tripal_core was amde compliant to drupal coding standards

Lacey Sanderson 12 år sedan
förälder
incheckning
fabedccb75
89 ändrade filer med 7707 tillägg och 7970 borttagningar
  1. 276 248
      tripal_core/chado_install.php
  2. 285 272
      tripal_core/jobs.php
  3. 673 616
      tripal_core/mviews.php
  4. 608 570
      tripal_core/tripal_core.api.inc
  5. 21 0
      tripal_core/tripal_core.coder_ignores.txt
  6. 31 29
      tripal_core/tripal_core.drush.inc
  7. 197 175
      tripal_core/tripal_core.install
  8. 213 193
      tripal_core/tripal_core.module
  9. 183 185
      tripal_core/tripal_core.schema.api.inc
  10. 16 12
      tripal_core/tripal_core_job_view.tpl.php
  11. 41 44
      tripal_core/tripal_launch_jobs.php
  12. 48 43
      tripal_core/tripal_launch_jobs_multi.php
  13. 111 99
      tripal_cv/charts.php
  14. 843 792
      tripal_cv/obo_loader.php
  15. 371 341
      tripal_cv/trees.php
  16. 306 300
      tripal_cv/tripal_cv.api.inc
  17. 11 0
      tripal_cv/tripal_cv.coder_ignores.txt
  18. 124 124
      tripal_cv/tripal_cv.install
  19. 481 472
      tripal_cv/tripal_cv.module
  20. 20 20
      tripal_cv/tripal_cv.views.inc
  21. 0 45
      tripal_cv/views/README
  22. 67 67
      tripal_cv/views/cv.views.inc
  23. 122 121
      tripal_cv/views/cvterm.views.inc
  24. 0 84
      tripal_cv/views/template.node_join.views.inc
  25. 0 211
      tripal_cv/views/template.table_defn.views.inc
  26. 92 84
      tripal_db/tripal_db.api.inc
  27. 7 2
      tripal_db/tripal_db.install
  28. 80 75
      tripal_db/tripal_db.module
  29. 6 6
      tripal_db/tripal_db.views.inc
  30. 0 45
      tripal_db/views/README
  31. 21 20
      tripal_db/views/db.views.inc
  32. 5 4
      tripal_db/views/dbxref.views.inc
  33. 0 84
      tripal_db/views/template.node_join.views.inc
  34. 0 211
      tripal_db/views/template.table_defn.views.inc
  35. 21 21
      tripal_stock/tripal_stock.views.inc
  36. 73 43
      tripal_views/tripal_views.api.inc
  37. 20 0
      tripal_views/tripal_views.coder_ignores.txt
  38. 266 252
      tripal_views/tripal_views.install
  39. 76 63
      tripal_views/tripal_views.module
  40. 484 474
      tripal_views/tripal_views.views.inc
  41. 11 1
      tripal_views/tripal_views_data_export_download_form.tpl.php
  42. 56 48
      tripal_views/tripal_views_form_elements.inc
  43. 358 342
      tripal_views/tripal_views_integration.inc
  44. 9 0
      tripal_views/tripal_views_integration_fields_form.tpl.php
  45. 0 45
      tripal_views/views/README
  46. 23 15
      tripal_views/views/handlers/chado_views_handler_field.inc
  47. 38 30
      tripal_views/views/handlers/chado_views_handler_field_aggregate.inc
  48. 23 15
      tripal_views/views/handlers/chado_views_handler_field_boolean.inc
  49. 23 15
      tripal_views/views/handlers/chado_views_handler_field_counter.inc
  50. 23 15
      tripal_views/views/handlers/chado_views_handler_field_custom.inc
  51. 23 15
      tripal_views/views/handlers/chado_views_handler_field_date.inc
  52. 23 15
      tripal_views/views/handlers/chado_views_handler_field_markup.inc
  53. 23 15
      tripal_views/views/handlers/chado_views_handler_field_math.inc
  54. 23 15
      tripal_views/views/handlers/chado_views_handler_field_numeric.inc
  55. 30 20
      tripal_views/views/handlers/chado_views_handler_filter_boolean_operator.inc
  56. 29 20
      tripal_views/views/handlers/chado_views_handler_filter_boolean_operator_string.inc
  57. 30 20
      tripal_views/views/handlers/chado_views_handler_filter_date.inc
  58. 30 20
      tripal_views/views/handlers/chado_views_handler_filter_equality.inc
  59. 30 20
      tripal_views/views/handlers/chado_views_handler_filter_float.inc
  60. 30 20
      tripal_views/views/handlers/chado_views_handler_filter_numeric.inc
  61. 30 20
      tripal_views/views/handlers/chado_views_handler_filter_string.inc
  62. 20 11
      tripal_views/views/handlers/chado_views_handler_sort.inc
  63. 20 11
      tripal_views/views/handlers/chado_views_handler_sort_date.inc
  64. 20 11
      tripal_views/views/handlers/chado_views_handler_sort_formula.inc
  65. 20 11
      tripal_views/views/handlers/chado_views_handler_sort_menu_hierarchy.inc
  66. 20 11
      tripal_views/views/handlers/chado_views_handler_sort_random.inc
  67. 27 20
      tripal_views/views/handlers/chado_wrapper_functions.inc
  68. 17 15
      tripal_views/views/handlers/views_handler_field_chado_count.inc
  69. 41 38
      tripal_views/views/handlers/views_handler_field_chado_rel_by_type.inc
  70. 3 2
      tripal_views/views/handlers/views_handler_field_chado_tf_boolean.inc
  71. 19 20
      tripal_views/views/handlers/views_handler_field_cvterm_name.inc
  72. 39 34
      tripal_views/views/handlers/views_handler_field_dbxref_accession_link.inc
  73. 17 14
      tripal_views/views/handlers/views_handler_field_node_optional.inc
  74. 2 1
      tripal_views/views/handlers/views_handler_field_readable_date.inc
  75. 8 8
      tripal_views/views/handlers/views_handler_field_type_name.inc
  76. 16 14
      tripal_views/views/handlers/views_handler_filter_chado_boolean.inc
  77. 81 68
      tripal_views/views/handlers/views_handler_filter_chado_select_cvterm_name.inc
  78. 37 29
      tripal_views/views/handlers/views_handler_filter_chado_select_string.inc
  79. 70 74
      tripal_views/views/handlers/views_handler_filter_file_upload.inc
  80. 21 15
      tripal_views/views/handlers/views_handler_filter_no_results.inc
  81. 59 49
      tripal_views/views/handlers/views_handler_join_chado_aggregator.inc
  82. 27 20
      tripal_views/views/handlers/views_handler_join_chado_through_linking.inc
  83. 0 84
      tripal_views/views/template.node_join.views.inc
  84. 0 211
      tripal_views/views/template.table_defn.views.inc
  85. 1 1
      tripal_views/views_data_export/plugins/tripal_views_plugin_style_export_fasta.inc
  86. 24 12
      tripal_views/views_data_export/theme/tripal_views_data_export.theme.inc
  87. 30 13
      tripal_views/views_data_export/theme/views-data-export-fasta-body.tpl.php
  88. 2 0
      tripal_views/views_data_export/theme/views-data-export-fasta-footer.tpl.php
  89. 2 0
      tripal_views/views_data_export/theme/views-data-export-fasta-header.tpl.php

+ 276 - 248
tripal_core/chado_install.php

@@ -1,278 +1,306 @@
 <?php
 
 /**
-*
-*
-* @ingroup tripal_core
-*/
-function tripal_core_chado_v1_11_load_form (){
-   $form['description'] = array(
-       '#type' => 'item',
-       '#value' => t("Click the submit button below to install Chado into the Drupal database. <br><font color=\"red\">WARNING:</font> use this only for a new chado installation or reinstall completely.  This will erase any data currently in the chado database.  If you are 
-using chado in a database external to the Drupal database with a 'chado' entry in the 'settings.php' \$db_url argument then this option will intall chado but it will not be usable.  The external database specified in the settings.php file takes precedence."),
-       '#weight' => 1,
-   );
-   $form['button'] = array(
-      '#type' => 'submit',
-      '#value' => t('Install Chado'),
-      '#weight' => 2,
-   );
-   return $form;
-}
+ * @file
+ * Functions to install chado schema through Drupal
+ */
 
 /**
-*
-* @ingroup tripal_core
-*/
-function tripal_core_chado_v1_11_load_form_submit ($form, &$form_state){
-   global $user;
+ * Load Chado Schema 1.11 Form
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_chado_v1_11_load_form() {
+
+  $form['description'] = array(
+    '#type' => 'item',
+    '#value' => t("Click the submit button below to install Chado into the Drupal "
+      ."database. <br /><font color=\"red\">WARNING:</font> use this only for a new "
+      ."chado installation or reinstall completely.  This will erase any data currently "
+      ."in the chado database.  If you are using chado in a database external to the "
+      ."Drupal database with a 'chado' entry in the 'settings.php' \$db_url argument "
+      ."then this option will intall chado but it will not be usable.  The external "
+      ."database specified in the settings.php file takes precedence."),
+    '#weight' => 1,
+  );
 
-   $args = array();
-   tripal_add_job("Install Chado",'tripal_core',
-      'tripal_core_install_chado',$args,$user->uid);
+  $form['button'] = array(
+    '#type' => 'submit',
+    '#value' => t('Install Chado'),
+    '#weight' => 2,
+  );
 
-   return '';
+  return $form;
 }
+
 /**
-*
-*
-* @ingroup tripal_core
-*/
-function tripal_core_install_chado ($dummy = NULL, $job = NULL){
-   $schema_file = drupal_get_path('module', 'tripal_core').'/default_schema.sql';
-   $init_file = drupal_get_path('module', 'tripal_core').'/initialize.sql';
-   if(tripal_core_reset_chado_schema()){
-      tripal_core_install_sql($schema_file);
-      tripal_core_install_sql($init_file);      
-   } else {
-      print "ERROR: cannot install chado.  Please check database permissions\n";
-      exit;
-   }
+ * Submit Load Chado Schema 1.11 Form
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_chado_v1_11_load_form_submit($form, &$form_state) {
+  global $user;
+
+  $args = array();
+  tripal_add_job("Install Chado", 'tripal_core',
+    'tripal_core_install_chado', $args, $user->uid);
+
 }
+
 /**
-*
-*
-* @ingroup tripal_core
-*/
-function tripal_core_reset_chado_schema (){
-   global $active_db;
+ * Install Chado Schema
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_install_chado() {
+  $schema_file = drupal_get_path('module', 'tripal_core') . '/default_schema.sql';
+  $init_file = drupal_get_path('module', 'tripal_core') . '/initialize.sql';
 
-   // iterate through the lines of the schema file and rebuild the SQL
-   if(tripal_core_schema_exists('chado')){
-      print "Dropping existing 'chado' schema\n";
-      pg_query($active_db,"drop schema chado cascade");
-   }
-   if(tripal_core_schema_exists('genetic_code')){
-      print "Dropping existing 'genetic_code' schema\n";
-      pg_query($active_db,"drop schema genetic_code cascade");
-   }
-   if(tripal_core_schema_exists('so')){
-      print "Dropping existing 'so' schema\n";
-      pg_query($active_db,"drop schema so cascade");
-   }
-   if(tripal_core_schema_exists('frange')){
-      print "Dropping existing 'frange' schema\n";
-      pg_query($active_db,"drop schema frange cascade");
-   }
-   // create the new chado schema
-   print "Creating 'chado' schema\n";
-   pg_query($active_db,"create schema chado");
-   if(tripal_core_schema_exists('chado')){
-      pg_query($active_db,"create language plpgsql");
-      return 1;
-   }
-   return 0;
+  if (tripal_core_reset_chado_schema()) {
+    tripal_core_install_sql($schema_file);
+    tripal_core_install_sql($init_file);
+  }
+  else {
+    print "ERROR: cannot install chado.  Please check database permissions\n";
+    exit;
+  }
 }
+
 /**
-*
-*
-* @ingroup tripal_core
-*/
+ * Reset the Chado Schema
+ * This drops the current chado and chado-related schema and re-creates it
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_reset_chado_schema() {
+  global $active_db;
+
+  // drop current chado and chado-related schema
+  if (tripal_core_schema_exists('chado')) {
+    print "Dropping existing 'chado' schema\n";
+    pg_query($active_db, "drop schema chado cascade");
+  }
+  if (tripal_core_schema_exists('genetic_code')) {
+    print "Dropping existing 'genetic_code' schema\n";
+    pg_query($active_db, "drop schema genetic_code cascade");
+  }
+  if (tripal_core_schema_exists('so')) {
+    print "Dropping existing 'so' schema\n";
+    pg_query($active_db, "drop schema so cascade");
+  }
+  if (tripal_core_schema_exists('frange')) {
+    print "Dropping existing 'frange' schema\n";
+    pg_query($active_db, "drop schema frange cascade");
+  }
+
+  // create the new chado schema
+  print "Creating 'chado' schema\n";
+  pg_query($active_db, "create schema chado");
+  if (tripal_core_schema_exists('chado')) {
+    pg_query($active_db, "create language plpgsql");
+    return TRUE;
+  }
 
-function tripal_core_schema_exists($schema){
-   // check that the chado schema now exists
-   $sql = "SELECT nspname
-           FROM pg_namespace
-           WHERE has_schema_privilege(nspname, 'USAGE') and nspname = '%s'
-           ORDER BY nspname";
-   $name = db_fetch_object(db_query($sql,$schema));
-   if(strcmp($name->nspname,$schema)!=0){
-      return 0;
-   }
-   return 1;
+  return FALSE;
 }
+
 /**
-*
-*
-* @ingroup tripal_core
-*/
-function tripal_core_install_sql ($sql_file){
-   global $active_db;
+ * Check that a given schema exists
+ *
+ * @param $schema
+ *   The name of the schema to check the existence of
+ *
+ * @return
+ *   TRUE/FALSE depending upon whether or not the schema exists
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_schema_exists($schema) {
 
-   pg_query($active_db,"set search_path to chado,public");
+  // check that the chado schema now exists
+  $sql = "SELECT nspname
+         FROM pg_namespace
+         WHERE has_schema_privilege(nspname, 'USAGE') and nspname = '%s'
+         ORDER BY nspname";
+  $name = db_fetch_object(db_query($sql, $schema));
+  if (strcmp($name->nspname, $schema) != 0) {
+    return FALSE;
+  }
 
-   print "Loading $sql_file...\n";
-   $lines = file($sql_file,FILE_SKIP_EMPTY_LINES);
-   if(!$lines){
-      return 'Cannot open $schema_file';
-   }
+  return TRUE;
+}
 
-   $stack = array();
-   $in_string = 0;
+/**
+ * Execute the provided SQL
+ *
+ * @param $sql_file
+ *   Contains SQL statements to be executed
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_install_sql($sql_file) {
+  global $active_db;
 
-   $query = '';
-   $i = 0;
-   foreach ($lines as $line_num => $line) {
-      $i++;
-      $type = '';
+  pg_query($active_db, "set search_path to chado,public");
+  print "Loading $sql_file...\n";
+  $lines = file($sql_file, FILE_SKIP_EMPTY_LINES);
 
-      // find and remove comments except when inside of strings
-      if(preg_match('/--/',$line) and !$in_string and !preg_match("/'.*?--.*?'/",$line)){
-         $line = preg_replace('/--.*$/','',$line);  // remove comments
-      }
-      if(preg_match('/\/\*.*?\*\//',$line)){
-         $line = preg_replace('/\/\*.*?\*\//','',$line);  // remove comments
-      }
-      // skip empty lines
-      if(preg_match('/^\s*$/',$line) or strcmp($line,'')==0){
-         continue;
-      }
+  if (!$lines) {
+    return 'Cannot open $schema_file';
+  }
 
-      // Find SQL for new objects
-      if(preg_match('/^\s*CREATE\s+TABLE/i',$line) and !$in_string){
-         $stack[] = 'table';
-         $line = preg_replace("/public./","chado.",$line);
-      }
-      if(preg_match('/^\s*ALTER\s+TABLE/i',$line) and !$in_string){
-         $stack[] = 'alter table';
-         $line = preg_replace("/public./","chado.",$line);
-      }
-      if(preg_match('/^\s*SET/i',$line) and !$in_string){
-         $stack[] = 'set';
-      }
-      if(preg_match('/^\s*CREATE\s+SCHEMA/i',$line) and !$in_string){
-         $stack[] = 'schema';
-      }
-      if(preg_match('/^\s*CREATE\s+SEQUENCE/i',$line) and !$in_string){
-         $stack[] = 'sequence';
-         $line = preg_replace("/public./","chado.",$line);
-      }
-      if(preg_match('/^\s*CREATE\s+(?:OR\s+REPLACE\s+)*VIEW/i',$line) and !$in_string){
-         $stack[] = 'view';
-         $line = preg_replace("/public./","chado.",$line);
-      }
-      if(preg_match('/^\s*COMMENT/i',$line) and !$in_string and sizeof($stack)==0){
-         $stack[] = 'comment';  
-         $line = preg_replace("/public./","chado.",$line);
-      }
-      if(preg_match('/^\s*CREATE\s+(?:OR\s+REPLACE\s+)*FUNCTION/i',$line) and !$in_string){
-         $stack[] = 'function';
-         $line = preg_replace("/public./","chado.",$line);
-      }
-      if(preg_match('/^\s*CREATE\s+INDEX/i',$line) and !$in_string){
-         $stack[] = 'index';
-      }
-      if(preg_match('/^\s*INSERT\s+INTO/i',$line) and !$in_string){
-         $stack[] = 'insert';
-         $line = preg_replace("/public./","chado.",$line);
-      }
-      if(preg_match('/^\s*CREATE\s+TYPE/i',$line) and !$in_string){
-         $stack[] = 'type';
-      }
-      if(preg_match('/^\s*GRANT/i',$line) and !$in_string){
-         $stack[] = 'grant';
-      }
-      if(preg_match('/^\s*CREATE\s+AGGREGATE/i',$line) and !$in_string){
-         $stack[] = 'aggregate';
-      }
+  $stack = array();
+  $in_string = 0;
+  $query = '';
+  $i = 0;
+  foreach ($lines as $line_num => $line) {
+    $i++;
+    $type = '';
+    // find and remove comments except when inside of strings
+    if (preg_match('/--/', $line) and !$in_string and !preg_match("/'.*?--.*?'/", $line)) {
+      $line = preg_replace('/--.*$/', '', $line);  // remove comments
+    }
+    if (preg_match('/\/\*.*?\*\//', $line)) {
+      $line = preg_replace('/\/\*.*?\*\//', '', $line);  // remove comments
+    }
+    // skip empty lines
+    if (preg_match('/^\s*$/', $line) or strcmp($line, '')==0) {
+      continue;
+    }
+    // Find SQL for new objects
+    if (preg_match('/^\s*CREATE\s+TABLE/i', $line) and !$in_string) {
+      $stack[] = 'table';
+      $line = preg_replace("/public./", "chado.", $line);
+    }
+    if (preg_match('/^\s*ALTER\s+TABLE/i', $line) and !$in_string) {
+      $stack[] = 'alter table';
+      $line = preg_replace("/public./", "chado.", $line);
+    }
+    if (preg_match('/^\s*SET/i', $line) and !$in_string) {
+      $stack[] = 'set';
+    }
+    if (preg_match('/^\s*CREATE\s+SCHEMA/i', $line) and !$in_string) {
+      $stack[] = 'schema';
+    }
+    if (preg_match('/^\s*CREATE\s+SEQUENCE/i', $line) and !$in_string) {
+      $stack[] = 'sequence';
+      $line = preg_replace("/public./", "chado.", $line);
+    }
+    if (preg_match('/^\s*CREATE\s+(?:OR\s+REPLACE\s+)*VIEW/i', $line) and !$in_string) {
+      $stack[] = 'view';
+      $line = preg_replace("/public./", "chado.", $line);
+    }
+    if (preg_match('/^\s*COMMENT/i', $line) and !$in_string and sizeof($stack)==0) {
+      $stack[] = 'comment';
+      $line = preg_replace("/public./", "chado.", $line);
+    }
+    if (preg_match('/^\s*CREATE\s+(?:OR\s+REPLACE\s+)*FUNCTION/i', $line) and !$in_string) {
+      $stack[] = 'function';
+      $line = preg_replace("/public./", "chado.", $line);
+    }
+    if (preg_match('/^\s*CREATE\s+INDEX/i', $line) and !$in_string) {
+      $stack[] = 'index';
+    }
+    if (preg_match('/^\s*INSERT\s+INTO/i', $line) and !$in_string) {
+      $stack[] = 'insert';
+      $line = preg_replace("/public./", "chado.", $line);
+    }
+    if (preg_match('/^\s*CREATE\s+TYPE/i', $line) and !$in_string) {
+      $stack[] = 'type';
+    }
+    if (preg_match('/^\s*GRANT/i', $line) and !$in_string) {
+      $stack[] = 'grant';
+    }
+    if (preg_match('/^\s*CREATE\s+AGGREGATE/i', $line) and !$in_string) {
+      $stack[] = 'aggregate';
+    }
 
-      // determine if we are in a string that spans a line
-      $matches = preg_match_all("/[']/i",$line,$temp);
-      $in_string = $in_string - ($matches % 2);
-      $in_string = abs($in_string);
+    // determine if we are in a string that spans a line
+    $matches = preg_match_all("/[']/i", $line, $temp);
+    $in_string = $in_string - ($matches % 2);
+    $in_string = abs($in_string);
 
-      // if we've reached the end of an object the pop the stack 
-      if(strcmp($stack[sizeof($stack)-1],'table') == 0 and preg_match('/\);\s*$/',$line)){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'alter table') == 0 and preg_match('/;\s*$/',$line) and !$in_string){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'set') == 0 and preg_match('/;\s*$/',$line) and !$in_string){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'schema') == 0 and preg_match('/;\s*$/',$line) and !$in_string){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'sequence') == 0 and preg_match('/;\s*$/',$line) and !$in_string){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'view') == 0 and preg_match('/;\s*$/',$line) and !$in_string){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'comment') == 0 and preg_match('/;\s*$/',$line) and !$in_string){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'function') == 0 and preg_match("/LANGUAGE.*?;\s+$/i",$line)){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'index') == 0 and preg_match('/;\s*$/',$line) and !$in_string){
-         $type = array_pop($stack);
+    // if we've reached the end of an object the pop the stack
+    if (strcmp($stack[sizeof($stack)-1], 'table') == 0 and preg_match('/\);\s*$/', $line)) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'alter table') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'set') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'schema') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'sequence') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'view') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'comment') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'function') == 0 and preg_match("/LANGUAGE.*?;\s+$/i", $line)) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'index') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'insert') == 0 and preg_match('/\);\s*$/', $line)) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'type') == 0 and preg_match('/\);\s*$/', $line)) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'grant') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
+      $type = array_pop($stack);
+    }
+    if (strcmp($stack[sizeof($stack)-1], 'aggregate') == 0 and preg_match('/\);\s*$/', $line)) {
+      $type = array_pop($stack);
+    }
+    // if we're in a recognized SQL statement then let's keep track of lines
+    if ($type or sizeof($stack) > 0) {
+      $query .= "$line";
+    }
+    else {
+      print "UNHANDLED $i, $in_string: $line";
+      return tripal_core_chado_install_done();
+    }
+    if (preg_match_all("/\n/", $query, $temp) > 100) {
+      print "SQL query is too long.  Terminating:\n$query\n";
+      return tripal_core_chado_install_done();
+    }
+    if ($type and sizeof($stack) == 0) {
+      print "Adding $type: line $i\n";
+      // rewrite the set serach_path to make 'public' be 'chado'
+      if (strcmp($type, 'set')==0) {
+        $query = preg_replace("/public/m", "chado", $query);
       }
-      if(strcmp($stack[sizeof($stack)-1],'insert') == 0 and preg_match('/\);\s*$/',$line)){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'type') == 0 and preg_match('/\);\s*$/',$line)){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'grant') == 0 and preg_match('/;\s*$/',$line) and !$in_string){
-         $type = array_pop($stack);
-      }
-      if(strcmp($stack[sizeof($stack)-1],'aggregate') == 0 and preg_match('/\);\s*$/',$line)){
-         $type = array_pop($stack);
-      }
-
-
-      // if we're in a recognized SQL statement then let's keep track of lines
-      if($type or sizeof($stack) > 0){
-         $query .= "$line";
-      } else {
-         print "UNHANDLED $i, $in_string: $line";
-         return tripal_core_chado_install_done();
+      $result = pg_query($active_db, $query);
+      if (!$result) {
+        $error  = pg_last_error();
+        print "Installation failed:\nSQL $i, $in_string: $query\n$error\n";
+        pg_query($active_db, "set search_path to public,chado");
+        return tripal_core_chado_install_done();
       }
+      $query = '';
+    }
+  }
+  print "Installation Complete!\n";
+  tripal_core_chado_install_done();
+}
 
-      if(preg_match_all("/\n/",$query,$temp) > 100){
-         print "SQL query is too long.  Terminating:\n$query\n";
-         return tripal_core_chado_install_done();
-      }
+/**
+ * Finish the Chado Schema Installation
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_chado_install_done() {
 
-      if($type and sizeof($stack) == 0){
-         print "Adding $type: line $i\n";
-         // rewrite the set serach_path to make 'public' be 'chado'
-         if(strcmp($type,'set')==0){
-            $query = preg_replace("/public/m","chado",$query);
-         }
-         $result = pg_query($active_db, $query);
-         if(!$result){
-            $error  = pg_last_error();
-            print "Installation failed:\nSQL $i, $in_string: $query\n$error\n";
-            pg_query($active_db,"set search_path to public,chado");  
-            return tripal_core_chado_install_done();
-         }
-         $query = '';
-      }    
-   }
+  // return the search path to normal
+  global $active_db;
+  pg_query($active_db, "set search_path to public,chado");
 
-   print "Installation Complete!\n";
-   tripal_core_chado_install_done(); 
-}
-/**
-*
-*
-* @ingroup tripal_core
-*/
-function tripal_core_chado_install_done (){
-   // return the search path to normal
-   global $active_db;
-   pg_query($active_db,"set search_path to public,chado");  
-}
+}

+ 285 - 272
tripal_core/jobs.php

@@ -1,27 +1,30 @@
 <?php
 
-/** 
+/**
+ * @file
+ * Contains functions related to the Tripal Jobs API
+ *
  * @defgroup tripal_jobs_api Core Module Jobs API
  * @{
- * Tripal offers a job management subsystem for managing tasks that may require an extended period of time for 
- * completion.  Drupal uses a UNIX-based cron job to handle tasks such as  checking  the  availability of updates, 
- * indexing new nodes for searching, etc.   Drupal's cron uses the web interface for launching these tasks, however, 
- * Tripal provides several administrative tasks that may time out and not complete due to limitations of the web 
- * server.  Examples including syncing of a large number of features between chado and Drupal.  To circumvent this, 
- * as well as provide more fine-grained control and monitoring, Tripal uses a jobs management sub-system built into 
- * the Tripal Core module.   It is anticipated that this functionality will be used for managing analysis jobs provided by 
- * future tools, with eventual support for distributed computing.   
- *
- * The  Tripal jobs management system allows administrators to submit tasks to be performed which can then  be 
- * launched through a UNIX command-line PHP script or cron job.  This command-line script can be added to a cron 
- * entry along-side the Drupal cron entry for automatic, regular launching of Tripal jobs.  The order of execution of 
- * waiting jobs is determined first by priority and second by the order the jobs were entered.  
+ * Tripal offers a job management subsystem for managing tasks that may require an extended period of time for
+ * completion.  Drupal uses a UNIX-based cron job to handle tasks such as  checking  the  availability of updates,
+ * indexing new nodes for searching, etc.   Drupal's cron uses the web interface for launching these tasks, however,
+ * Tripal provides several administrative tasks that may time out and not complete due to limitations of the web
+ * server.  Examples including syncing of a large number of features between chado and Drupal.  To circumvent this,
+ * as well as provide more fine-grained control and monitoring, Tripal uses a jobs management sub-system built into
+ * the Tripal Core module.   It is anticipated that this functionality will be used for managing analysis jobs provided by
+ * future tools, with eventual support for distributed computing.
+ *
+ * The  Tripal jobs management system allows administrators to submit tasks to be performed which can then  be
+ * launched through a UNIX command-line PHP script or cron job.  This command-line script can be added to a cron
+ * entry along-side the Drupal cron entry for automatic, regular launching of Tripal jobs.  The order of execution of
+ * waiting jobs is determined first by priority and second by the order the jobs were entered.
  *
  * The API functions described below provide a programmatic interface for adding, checking and viewing jobs.
  * @}
  * @ingroup tripal_api
  */
- 
+
 /**
  * Adds a job to the Tripal Jbo queue
  *
@@ -36,7 +39,7 @@
  * @param $uid
  *    The uid of the user adding the job
  * @param $priority
- *    The priority at which to run the job where the highest priority is 10 and the lowest priority 
+ *    The priority at which to run the job where the highest priority is 10 and the lowest priority
  *    is 1. The default priority is 10.
  *
  * @return
@@ -44,30 +47,30 @@
  *
  * @ingroup tripal_jobs_api
  */
-function tripal_add_job ($job_name,$modulename,$callback,$arguments,$uid,$priority = 10){
-
-   # convert the arguments into a string for storage in the database
-   $args = implode("::",$arguments);
-
-   $record = new stdClass();
-   $record->job_name = $job_name;
-   $record->modulename = $modulename;
-   $record->callback = $callback;
-   $record->status = 'Waiting';
-   $record->submit_date = time();
-   $record->uid = $uid;
-   $record->priority = $priority;  # the lower the number the higher the priority
-   if($args){
-      $record->arguments = $args;
-   }
-   if(drupal_write_record('tripal_jobs',$record)){
-      $jobs_url = url("admin/tripal/tripal_jobs");
-      drupal_set_message(t("Job '$job_name' submitted.  Check the <a href='$jobs_url'>jobs page</a> for status"));
-   } else {
-      drupal_set_message("Failed to add job $job_name.");
-   }
-
-   return $record->job_id;
+function tripal_add_job($job_name, $modulename, $callback, $arguments, $uid, $priority = 10) {
+
+  // convert the arguments into a string for storage in the database
+  $args = implode("::", $arguments);
+  $record = new stdClass();
+  $record->job_name = $job_name;
+  $record->modulename = $modulename;
+  $record->callback = $callback;
+  $record->status = 'Waiting';
+  $record->submit_date = time();
+  $record->uid = $uid;
+  $record->priority = $priority;  # the lower the number the higher the priority
+  if ($args) {
+    $record->arguments = $args;
+  }
+  if (drupal_write_record('tripal_jobs', $record)) {
+    $jobs_url = url("admin/tripal/tripal_jobs");
+    drupal_set_message(t("Job '%job_name' submitted.  Check the %jobs_link for status", array('%job_name' => $job_name, '%jobs_link' => l($jobs_url, 'jobs page'))));
+  }
+  else {
+    drupal_set_message(t("Failed to add job %job_name.", array('%job_name' => $job_name)), 'error');
+  }
+
+  return $record->job_id;
 }
 
 /**
@@ -83,17 +86,18 @@ function tripal_add_job ($job_name,$modulename,$callback,$arguments,$uid,$priori
  *
  * @ingroup tripal_core
  */
-function tripal_job_set_progress($job_id,$percentage){
+function tripal_job_set_progress($job_id, $percentage) {
 
-   if(preg_match("/^(\d+|100)$/",$percentage)){
-      $record = new stdClass();
-      $record->job_id = $job_id; 
-      $record->progress = $percentage;
-	  if(drupal_write_record('tripal_jobs',$record,'job_id')){
-	     return 1;
-	  }
-   }
-   return 0;
+  if (preg_match("/^(\d+|100)$/", $percentage)) {
+    $record = new stdClass();
+    $record->job_id = $job_id;
+    $record->progress = $percentage;
+    if (drupal_write_record('tripal_jobs', $record, 'job_id')) {
+      return TRUE;
+    }
+  }
+
+  return FALSE;
 }
 
 /**
@@ -107,12 +111,12 @@ function tripal_job_set_progress($job_id,$percentage){
  *
  * @ingroup tripal_jobs_api
  */
-function tripal_get_module_active_jobs ($modulename){
-   $sql =  "SELECT * FROM {tripal_jobs} TJ ".
+function tripal_get_module_active_jobs($modulename) {
+  $sql =  "SELECT * FROM {tripal_jobs} TJ ".
            "WHERE TJ.end_time IS NULL and TJ.modulename = '%s' ";
-  return db_fetch_object(db_query($sql,$modulename));
-
+  return db_fetch_object(db_query($sql, $modulename));
 }
+
 /**
  * Returns the Tripal Job Report
  *
@@ -121,70 +125,69 @@ function tripal_get_module_active_jobs ($modulename){
  *
  * @ingroup tripal_core
  */
-function tripal_jobs_report () {
-   //$jobs = db_query("SELECT * FROM {tripal_jobs} ORDER BY job_id DESC");
-   $jobs = pager_query(
-      "SELECT TJ.job_id,TJ.uid,TJ.job_name,TJ.modulename,TJ.progress,
-              TJ.status as job_status, TJ,submit_date,TJ.start_time,
-              TJ.end_time,TJ.priority,U.name as username
-       FROM {tripal_jobs} TJ 
-         INNER JOIN {users} U on TJ.uid = U.uid 
-       ORDER BY job_id DESC", 10,0,"SELECT count(*) FROM {tripal_jobs}");
-	
-   // create a table with each row containig stats for 
-   // an individual job in the results set.
-   $output .= "Waiting jobs are executed first by priority level (the lower the ".
-              "number the higher the priority) and second by the order they ".
-              "were entered";
-   $output .= "<table class=\"tripal-table tripal-table-horz\">". 
-              "  <tr>".
-              "    <th>Job ID</th>".
-              "    <th>User</th>".
-              "    <th>Job Name</th>".
-              "    <th nowrap>Dates</th>".             
-			     "    <th>Priority</th>".
-			     "    <th>Progress</th>".
-              "    <th>Status</th>".
-              "    <th>Actions</th>".
-              "  </tr>";
-   $i = 0;
-   while($job = db_fetch_object($jobs)){
-      $class = 'tripal-table-odd-row';
-      if($i % 2 == 0 ){
-         $class = 'tripal-table-even-row';
-      }
-      $submit = tripal_jobs_get_submit_date($job);
-      $start = tripal_jobs_get_start_time($job);
-      $end = tripal_jobs_get_end_time($job);
-
-      $cancel_link = '';
-      if($job->start_time == 0 and $job->end_time == 0){
-         $cancel_link = "<a href=\"".url("admin/tripal/tripal_jobs/cancel/".$job->job_id)."\">Cancel</a><br>";
-      }
-      $rerun_link = "<a href=\"".url("admin/tripal/tripal_jobs/rerun/".$job->job_id)."\">Re-run</a><br>";
-      $view_link ="<a href=\"".url("admin/tripal/tripal_jobs/view/".$job->job_id)."\">View</a>";
-      $output .= "  <tr class=\"$class\">";
-      $output .= "    <td>$job->job_id</td>".
-                 "    <td>$job->username</td>".
-                 "    <td>$job->job_name</td>".
-                 "    <td nowrap>Submit Date: $submit".
-                 "    <br>Start Time: $start".
-                 "    <br>End Time: $end</td>".
-                 "    <td>$job->priority</td>".
-				     "    <td>$job->progress%</td>".
-                 "    <td>$job->job_status</td>".
-                 "    <td>$cancel_link $rerun_link $view_link</td>".
-                 "  </tr>";
-      $i++;
-   }
-   $output .= "</table>";
-	$output .= theme_pager();
-   return $output;
+function tripal_jobs_report() {
+
+  //$jobs = db_query("SELECT * FROM {tripal_jobs} ORDER BY job_id DESC");
+  $jobs = pager_query(
+    "SELECT TJ.job_id,TJ.uid,TJ.job_name,TJ.modulename,TJ.progress,
+            TJ.status as job_status, TJ,submit_date,TJ.start_time,
+            TJ.end_time,TJ.priority,U.name as username
+     FROM {tripal_jobs} TJ
+       INNER JOIN {users} U on TJ.uid = U.uid
+     ORDER BY job_id DESC", 10, 0, "SELECT count(*) FROM {tripal_jobs}");
+  // create a table with each row containig stats for
+  // an individual job in the results set.
+  $output .= "Waiting jobs are executed first by priority level (the lower the ".
+            "number the higher the priority) and second by the order they ".
+            "were entered";
+  $output .= "<table class=\"tripal-table tripal-table-horz\">".
+            "  <tr>".
+            "    <th>Job ID</th>".
+            "    <th>User</th>".
+            "    <th>Job Name</th>".
+            "    <th nowrap>Dates</th>".
+         "    <th>Priority</th>".
+         "    <th>Progress</th>".
+            "    <th>Status</th>".
+            "    <th>Actions</th>".
+            "  </tr>";
+  $i = 0;
+  while ($job = db_fetch_object($jobs)) {
+    $class = 'tripal-table-odd-row';
+    if ($i % 2 == 0 ) {
+      $class = 'tripal-table-even-row';
+    }
+    $submit = tripal_jobs_get_submit_date($job);
+    $start = tripal_jobs_get_start_time($job);
+    $end = tripal_jobs_get_end_time($job);
+    $cancel_link = '';
+    if ($job->start_time == 0 and $job->end_time == 0) {
+      $cancel_link = "<a href=\"" . url("admin/tripal/tripal_jobs/cancel/" . $job->job_id) . "\">Cancel</a><br />";
+    }
+    $rerun_link = "<a href=\"" . url("admin/tripal/tripal_jobs/rerun/" . $job->job_id) . "\">Re-run</a><br />";
+    $view_link ="<a href=\"" . url("admin/tripal/tripal_jobs/view/" . $job->job_id) . "\">View</a>";
+    $output .= "  <tr class=\"$class\">";
+    $output .= "    <td>$job->job_id</td>".
+               "    <td>$job->username</td>".
+               "    <td>$job->job_name</td>".
+               "    <td nowrap>Submit Date: $submit".
+               "    <br />Start Time: $start".
+               "    <br />End Time: $end</td>".
+               "    <td>$job->priority</td>".
+           "    <td>$job->progress%</td>".
+               "    <td>$job->job_status</td>".
+               "    <td>$cancel_link $rerun_link $view_link</td>".
+               "  </tr>";
+    $i++;
+  }
+  $output .= "</table>";
+  $output .= theme_pager();
+  return $output;
 }
 
 /**
  * Returns the start time for a given job
- * 
+ *
  * @param $job
  *   An object describing the job
  *
@@ -193,22 +196,25 @@ function tripal_jobs_report () {
  *
  * @ingroup tripal_jobs_api
  */
-function tripal_jobs_get_start_time($job){
-   if($job->start_time > 0){
-      $start = format_date($job->start_time);
-   } else {
-      if(strcmp($job->job_status,'Cancelled')==0){
-         $start = 'Cancelled';
-      } else {
-         $start = 'Not Yet Started';
-      }
-   }
-   return $start;
+function tripal_jobs_get_start_time($job) {
+
+  if ($job->start_time > 0) {
+    $start = format_date($job->start_time);
+  }
+  else {
+    if (strcmp($job->job_status, 'Cancelled')==0) {
+      $start = 'Cancelled';
+    }
+    else {
+      $start = 'Not Yet Started';
+    }
+  }
+  return $start;
 }
 
 /**
  * Returns the end time for a given job
- * 
+ *
  * @param $job
  *   An object describing the job
  *
@@ -217,13 +223,16 @@ function tripal_jobs_get_start_time($job){
  *
  * @ingroup tripal_jobs_api
  */
-function tripal_jobs_get_end_time($job){
-   if($job->end_time > 0){
-      $end = format_date($job->end_time);
-   } else {
-      $end = '';
-   }
-   return $end;
+function tripal_jobs_get_end_time($job) {
+
+  if ($job->end_time > 0) {
+    $end = format_date($job->end_time);
+  }
+  else {
+    $end = '';
+  }
+
+  return $end;
 }
 
 /**
@@ -237,8 +246,8 @@ function tripal_jobs_get_end_time($job){
  *
  * @ingroup tripal_jobs_api
  */
-function tripal_jobs_get_submit_date($job){
-   return format_date($job->submit_date);
+function tripal_jobs_get_submit_date($job) {
+  return format_date($job->submit_date);
 }
 
 /**
@@ -249,85 +258,86 @@ function tripal_jobs_get_submit_date($job){
  *
  * @ingroup tripal_jobs_api
  */
-function tripal_jobs_launch ($do_parallel = 0){
-   
-   // first check if any jobs are currently running
-   // if they are, don't continue, we don't want to have
-   // more than one job script running at a time
-   if(!$do_parallel and tripal_jobs_check_running()){
-      return;
-   }
-   
-   // get all jobs that have not started and order them such that
-   // they are processed in a FIFO manner. 
-   $sql =  "SELECT * FROM {tripal_jobs} TJ ".
-           "WHERE TJ.start_time IS NULL and TJ.end_time IS NULL ".
-           "ORDER BY priority ASC,job_id ASC";
-   $job_res = db_query($sql);
-   while($job = db_fetch_object($job_res)){
-
-		// set the start time for this job
-		$record = new stdClass();
-		$record->job_id = $job->job_id;
-		$record->start_time = time();
-		$record->status = 'Running';
-		$record->pid = getmypid();
-		drupal_write_record('tripal_jobs',$record,'job_id');
-
-		// call the function provided in the callback column.
-		// Add the job_id as the last item in the list of arguments. All
-		// callback functions should support this argument.
-		$callback = $job->callback;
-		$args = split("::",$job->arguments);
-		$args[] = $job->job_id;
-		print "Calling: $callback(" . implode(", ",$args) . ")\n";   
-		call_user_func_array($callback,$args);
-		
-		// set the end time for this job
-		$record->end_time = time();
-		$record->status = 'Completed';
-		$record->progress = '100';
-		drupal_write_record('tripal_jobs',$record,'job_id');
-		
-		// send an email to the user advising that the job has finished
-   }
+function tripal_jobs_launch($do_parallel = 0) {
+
+  // first check if any jobs are currently running
+  // if they are, don't continue, we don't want to have
+  // more than one job script running at a time
+  if (!$do_parallel and tripal_jobs_check_running()) {
+    return;
+  }
+
+  // get all jobs that have not started and order them such that
+  // they are processed in a FIFO manner.
+  $sql =  "SELECT * FROM {tripal_jobs} TJ ".
+         "WHERE TJ.start_time IS NULL and TJ.end_time IS NULL ".
+         "ORDER BY priority ASC,job_id ASC";
+  $job_res = db_query($sql);
+  while ($job = db_fetch_object($job_res)) {
+    // set the start time for this job
+    $record = new stdClass();
+    $record->job_id = $job->job_id;
+    $record->start_time = time();
+    $record->status = 'Running';
+    $record->pid = getmypid();
+    drupal_write_record('tripal_jobs', $record, 'job_id');
+
+    // call the function provided in the callback column.
+    // Add the job_id as the last item in the list of arguments. All
+    // callback functions should support this argument.
+    $callback = $job->callback;
+    $args = split("::", $job->arguments);
+    $args[] = $job->job_id;
+    print "Calling: $callback(" . implode(", ", $args) . ")\n";
+    call_user_func_array($callback, $args);
+    // set the end time for this job
+    $record->end_time = time();
+    $record->status = 'Completed';
+    $record->progress = '100';
+    drupal_write_record('tripal_jobs', $record, 'job_id');
+
+    // send an email to the user advising that the job has finished
+  }
 }
 
 /**
  * Returns a list of running tripal jobs
  *
  * @return
- *    and array of objects where each object describes a running job or false if no jobs are running
+ *    and array of objects where each object describes a running job or FALSE if no jobs are running
  *
  * @ingroup tripal_jobs_api
  */
-function tripal_jobs_check_running () {
-   // iterate through each job that has not ended
-   // and see if it is still running. If it is not
-   // running but does not have an end_time then
-   // set the end time and set the status to 'Error'
-   $sql =  "SELECT * FROM {tripal_jobs} TJ ".
-           "WHERE TJ.end_time IS NULL and NOT TJ.start_time IS NULL ";
-   $jobs = db_query($sql);
-   while($job = db_fetch_object($jobs)){
-      $status = `ps --pid=$job->pid --no-header`;
-      if($job->pid && $status) {
-         // the job is still running so let it go
-		   // we return 1 to indicate that a job is running
-		   print "Job is still running (pid $job->pid)\n";
-		   return 1;
-      } else {
-	      // the job is not running so terminate it
-	      $record = new stdClass();
-         $record->job_id = $job->job_id;
-	      $record->end_time = time();
-         $record->status = 'Error';
-	      $record->error_msg = 'Job has terminated unexpectedly.';
-         drupal_write_record('tripal_jobs',$record,'job_id');
-	   }
-   }
-   // return 1 to indicate that no jobs are currently running.
-   return 0;
+function tripal_jobs_check_running() {
+
+  // iterate through each job that has not ended
+  // and see if it is still running. If it is not
+  // running but does not have an end_time then
+  // set the end time and set the status to 'Error'
+  $sql =  "SELECT * FROM {tripal_jobs} TJ ".
+         "WHERE TJ.end_time IS NULL and NOT TJ.start_time IS NULL ";
+  $jobs = db_query($sql);
+  while ($job = db_fetch_object($jobs)) {
+    $status = `ps --pid=$job->pid --no-header`;
+    if ($job->pid && $status) {
+      // the job is still running so let it go
+      // we return 1 to indicate that a job is running
+      print "Job is still running (pid $job->pid)\n";
+      return TRUE;
+    }
+    else {
+      // the job is not running so terminate it
+      $record = new stdClass();
+      $record->job_id = $job->job_id;
+      $record->end_time = time();
+      $record->status = 'Error';
+      $record->error_msg = 'Job has terminated unexpectedly.';
+      drupal_write_record('tripal_jobs', $record, 'job_id');
+    }
+  }
+
+  // return 1 to indicate that no jobs are currently running.
+  return FALSE;
 }
 
 /**
@@ -335,13 +345,13 @@ function tripal_jobs_check_running () {
  *
  * @param $job_id
  *   The job_id of the job to display
- * 
+ *
  * @return
  *   The HTML describing the indicated job
  * @ingroup tripal_core
  */
-function tripal_jobs_view ($job_id){
-   return theme('tripal_core_job_view',$job_id);
+function tripal_jobs_view($job_id) {
+  return theme('tripal_core_job_view', $job_id);
 }
 
 /**
@@ -352,64 +362,66 @@ function tripal_jobs_view ($job_id){
  *
  * @ingroup tripal_core
  */
-function tripal_core_preprocess_tripal_core_job_view (&$variables){
-   // get the job record
-   $job_id = $variables['job_id'];
-   $sql = 
-      "SELECT TJ.job_id,TJ.uid,TJ.job_name,TJ.modulename,TJ.progress,
-              TJ.status as job_status, TJ,submit_date,TJ.start_time,
-              TJ.end_time,TJ.priority,U.name as username,TJ.arguments,
-              TJ.callback,TJ.error_msg,TJ.pid
-       FROM {tripal_jobs} TJ 
-         INNER JOIN users U on TJ.uid = U.uid 
-       WHERE TJ.job_id = %d";
-   $job = db_fetch_object(db_query($sql,$job_id));
-
-   // we do not know what the arguments are for and we want to provide a 
-   // meaningful description to the end-user. So we use a callback function
-   // deinfed in the module that created the job to describe in an array
-   // the arguments provided.  If the callback fails then just use the 
-   // arguments as they are
-   $args = preg_split("/::/",$job->arguments);
-   $arg_hook = $job->modulename."_job_describe_args";
-   if(is_callable($arg_hook)){
-      $new_args = call_user_func_array($arg_hook,array($job->callback,$args));
-      if(is_array($new_args) and count($new_args)){
-         $job->arguments = $new_args;
-      } else {
-         $job->arguments = $args;
-      }
-   } else {
+function tripal_core_preprocess_tripal_core_job_view(&$variables) {
+
+  // get the job record
+  $job_id = $variables['job_id'];
+  $sql =
+    "SELECT TJ.job_id,TJ.uid,TJ.job_name,TJ.modulename,TJ.progress,
+            TJ.status as job_status, TJ,submit_date,TJ.start_time,
+            TJ.end_time,TJ.priority,U.name as username,TJ.arguments,
+            TJ.callback,TJ.error_msg,TJ.pid
+     FROM {tripal_jobs} TJ
+       INNER JOIN users U on TJ.uid = U.uid
+     WHERE TJ.job_id = %d";
+  $job = db_fetch_object(db_query($sql, $job_id));
+
+  // we do not know what the arguments are for and we want to provide a
+  // meaningful description to the end-user. So we use a callback function
+  // deinfed in the module that created the job to describe in an array
+  // the arguments provided.  If the callback fails then just use the
+  // arguments as they are
+  $args = preg_split("/::/", $job->arguments);
+  $arg_hook = $job->modulename . "_job_describe_args";
+  if (is_callable($arg_hook)) {
+    $new_args = call_user_func_array($arg_hook, array($job->callback, $args));
+    if (is_array($new_args) and count($new_args)) {
+      $job->arguments = $new_args;
+    }
+    else {
       $job->arguments = $args;
-   }
+    }
+  }
+  else {
+    $job->arguments = $args;
+  }
 
-   // make our start and end times more legible
-   $job->submit_date = tripal_jobs_get_submit_date($job);
-   $job->start_time = tripal_jobs_get_start_time($job);
-   $job->end_time = tripal_jobs_get_end_time($job);
+  // make our start and end times more legible
+  $job->submit_date = tripal_jobs_get_submit_date($job);
+  $job->start_time = tripal_jobs_get_start_time($job);
+  $job->end_time = tripal_jobs_get_end_time($job);
 
-   // add the job to the variables that get exported to the template
-   $variables['job'] = $job;
+  // add the job to the variables that get exported to the template
+  $variables['job'] = $job;
 }
+
 /**
  * Set a job to be re-ran (ie: add it back into the job queue)
- * 
+ *
  * @param $job_id
  *   The job_id of the job to be re-ran
- * 
+ *
  * @ingroup tripal_jobs_api
  */
-function tripal_jobs_rerun ($job_id){
-   global $user;
-
-   $sql = "select * from {tripal_jobs} where job_id = %d";
-   $job = db_fetch_object(db_query($sql,$job_id));
+function tripal_jobs_rerun($job_id) {
+  global $user;
 
-   $args = explode("::",$job->arguments);
-   tripal_add_job ($job->job_name,$job->modulename,$job->callback,$args,$user->uid,
-      $job->priority);
-
-   drupal_goto("admin/tripal/tripal_jobs");
+  $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = %d";
+  $job = db_fetch_object(db_query($sql, $job_id));
+  $args = explode("::", $job->arguments);
+  tripal_add_job($job->job_name, $job->modulename, $job->callback, $args, $user->uid,
+    $job->priority);
+  drupal_goto("admin/tripal/tripal_jobs");
 }
 
 /**
@@ -420,21 +432,22 @@ function tripal_jobs_rerun ($job_id){
  *
  * @ingroup tripal_jobs_api
  */
-function tripal_jobs_cancel ($job_id){
-   $sql = "select * from {tripal_jobs} where job_id = %d";
-   $job = db_fetch_object(db_query($sql,$job_id));
+function tripal_jobs_cancel($job_id) {
+  $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = %d";
+  $job = db_fetch_object(db_query($sql, $job_id));
 
-   // set the end time for this job
-   if($job->start_time == 0){
-      $record = new stdClass();
-      $record->job_id = $job->job_id;
-	   $record->end_time = time();
-	   $record->status = 'Cancelled';
-	   $record->progress = '0';
-	   drupal_write_record('tripal_jobs',$record,'job_id');
-      drupal_set_message("Job #$job_id cancelled");
-   } else {
-      drupal_set_message("Job #$job_id cannot be cancelled. It is in progress or has finished.");
-   }
-   drupal_goto("admin/tripal/tripal_jobs");
-}
+  // set the end time for this job
+  if ($job->start_time == 0) {
+    $record = new stdClass();
+    $record->job_id = $job->job_id;
+    $record->end_time = time();
+    $record->status = 'Cancelled';
+    $record->progress = '0';
+    drupal_write_record('tripal_jobs', $record, 'job_id');
+    drupal_set_message(t("Job #%job_id cancelled", array('%job_id' => $job_id)));
+  }
+  else {
+    drupal_set_message(t("Job %job_id cannot be cancelled. It is in progress or has finished.", array('%job_id' => $job_id)));
+  }
+  drupal_goto("admin/tripal/tripal_jobs");
+}

+ 673 - 616
tripal_core/mviews.php

@@ -1,35 +1,38 @@
 <?php
 
-/** 
+/**
+ * @file
+ * Contains functions for the Materialized Views API
+
  * @defgroup tripal_mviews_api Core Module Materalized Views API
  * @{
  * Provides an application programming interface (API) to manage materialized views in Chado.
  * The Perl-based chado comes with an interface for managing materialzed views.  This
- * API provides an alternative Drupal-based method.  
+ * API provides an alternative Drupal-based method.
  * @}
  * @ingroup tripal_api
  */
 
 /**
  * Add a materialized view to the chado database to help speed data access. This
- * function supports the older style where postgres column specifications 
+ * function supports the older style where postgres column specifications
  * are provided using the $mv_table, $mv_specs and $indexed variables. It also
  * supports the newer preferred method where the materialized view is described
- * using the Drupal Schema API array.  
+ * using the Drupal Schema API array.
  *
- * @param $name 
+ * @param $name
  *   The name of the materialized view.
- * @param $modulename 
+ * @param $modulename
  *   The name of the module submitting the materialized view (e.g. 'tripal_library')
- * @param $mv_table 
+ * @param $mv_table
  *   The name of the table to add to chado. This is the table that can be queried.
- * @param $mv_specs 
- *   The table definition 
- * @param $indexed 
+ * @param $mv_specs
+ *   The table definition
+ * @param $indexed
  *   The columns that are to be indexed
- * @param $query 
+ * @param $query
  *   The SQL query that loads the materialized view with data
- * @param $special_index  
+ * @param $special_index
  *   currently not used
  * @param $comment
  *   A string containing a description of the materialized view
@@ -39,96 +42,101 @@
  *
  * @ingroup tripal_mviews_api
  */
-function tripal_add_mview ($name, $modulename, $mv_table, $mv_specs, $indexed,
-   $query, $special_index, $comment=NULL, $mv_schema=NULL)
-{
-   // get the table name from the schema array
-   $schema_arr = array();
-   if($mv_schema){
-      // get the schema from the mv_specs and use it to add the custom table
-      eval("\$schema_arr = $mv_schema;");
-      $mv_table = $schema_arr['table'];
-   }
-
-   $record = new stdClass();
-   $record->name = $name;
-   $record->modulename = $modulename;
-   $record->mv_table = $mv_table;
-   $record->mv_specs = $mv_specs;
-   $record->indexed = $indexed;
-   $record->query = $query;
-   $record->special_index = $special_index;
-   $record->comment = $comment;
-   $record->mv_schema = $mv_schema;
-
-   // add the record to the tripal_mviews table and if successful
-   // create the new materialized view in the chado schema
-   if(drupal_write_record('tripal_mviews',$record)){
-
-      // drop the table from chado if it exists
-      $previous_db = tripal_db_set_active('chado');  // use chado database
-      if (db_table_exists($mv_table)) {
-         $sql = "DROP TABLE $mv_table";
-         db_query($sql);
-      }
-      tripal_db_set_active($previous_db);  // now use drupal database
-      
-      // now construct the indexes
+function tripal_add_mview($name, $modulename, $mv_table, $mv_specs, $indexed,
+  $query, $special_index, $comment = NULL, $mv_schema = NULL) {
+
+  // get the table name from the schema array
+  $schema_arr = array();
+  if ($mv_schema) {
+    // get the schema from the mv_specs and use it to add the custom table
+    eval("\$schema_arr = $mv_schema;");
+    $mv_table = $schema_arr['table'];
+  }
+
+  // Create a new record
+  $record = new stdClass();
+  $record->name = $name;
+  $record->modulename = $modulename;
+  $record->mv_table = $mv_table;
+  $record->mv_specs = $mv_specs;
+  $record->indexed = $indexed;
+  $record->query = $query;
+  $record->special_index = $special_index;
+  $record->comment = $comment;
+  $record->mv_schema = $mv_schema;
+
+  // add the record to the tripal_mviews table and if successful
+  // create the new materialized view in the chado schema
+  if (drupal_write_record('tripal_mviews', $record)) {
+
+    // drop the table from chado if it exists
+    $previous_db = tripal_db_set_active('chado');  // use chado database
+    if (db_table_exists($mv_table)) {
+      $sql = "DROP TABLE $mv_table";
+      db_query($sql);
+    }
+    tripal_db_set_active($previous_db);  // now use drupal database
+
+    // now construct the indexes
+    $index = '';
+    if ($indexed) {
+      // add to the array of values
+      $vals = preg_split("/[\n,]+/", $indexed);
       $index = '';
-      if($indexed){
-        // add to the array of values
-        $vals = preg_split("/[\n,]+/",$indexed);
-        $index = '';
-        foreach ($vals as $field){
-           $field = trim($field);
-           $index .= "CREATE INDEX idx_${mv_table}_${field} ON $mv_table ($field);";
-        }
+      foreach ($vals as $field) {
+        $field = trim($field);
+        $index .= "CREATE INDEX idx_${mv_table}_${field} ON $mv_table ($field);";
       }
+    }
 
-      // create the table differently depending on if it the traditional method
-      // or the Drupal Schema API method
-      if($mv_schema){
-         if(!tripal_create_chado_table ($ret,$mv_table,$schema_arr)){
-            drupal_set_message("Could not create the materialized view. Check Drupal error report logs.");
-         } else {
-            drupal_set_message(t("View '$name' created"));
-         }
-      } else {
-         // add the table to the database
-         $sql = "CREATE TABLE {$mv_table} ($mv_specs); $index"; 
-         $previous_db = tripal_db_set_active('chado');  // use chado database
-         $results = db_query($sql);
-         tripal_db_set_active($previous_db);  // now use drupal database
-         if($results){
-            drupal_set_message(t("View '$name' created"));
-         } else {
-            drupal_set_message(t("Failed to create the materialized view table: '$mv_table'"));
-         }
+    // create the table differently depending on if it the traditional method
+    // or the Drupal Schema API method
+    if ($mv_schema) {
+      if (!tripal_create_chado_table ($ret, $mv_table, $schema_arr)) {
+        drupal_set_message(t("Could not create the materialized view. Check Drupal error report logs."), 'error');
+      }
+      else {
+        drupal_set_message(t("View '%name' created", array('%name' => $name)));
+      }
+    }
+    else {
+      // add the table to the database
+      $sql = "CREATE TABLE {$mv_table} ($mv_specs); $index";
+      $previous_db = tripal_db_set_active('chado');  // use chado database
+      $results = db_query($sql);
+      tripal_db_set_active($previous_db);  // now use drupal database
+      if ($results) {
+        drupal_set_message(t("View '%name' created", array('%name' => $name)));
+      }
+      else {
+        drupal_set_message(t("Failed to create the materialized view table: '%mv_table'", array('%mv_table' => $mv_table)), 'error');
       }
-   }
+    }
+  }
 }
+
 /**
  * Edits a materialized view to the chado database to help speed data access.This
- * function supports the older style where postgres column specifications 
+ * function supports the older style where postgres column specifications
  * are provided using the $mv_table, $mv_specs and $indexed variables. It also
  * supports the newer preferred method where the materialized view is described
- * using the Drupal Schema API array.  
+ * using the Drupal Schema API array.
  *
- * @param $mview_id 
+ * @param $mview_id
  *   The mview_id of the materialized view to edit
- * @param $name 
+ * @param $name
  *   The name of the materialized view.
- * @param $modulename 
+ * @param $modulename
  *   The name of the module submitting the materialized view (e.g. 'tripal_library')
- * @param $mv_table 
+ * @param $mv_table
  *   The name of the table to add to chado. This is the table that can be queried.
- * @param $mv_specs 
- *   The table definition 
- * @param $indexed 
+ * @param $mv_specs
+ *   The table definition
+ * @param $indexed
  *   The columns that are to be indexed
- * @param $query 
+ * @param $query
  *   The SQL query that loads the materialized view with data
- * @param $special_index  
+ * @param $special_index
  *   currently not used
  * @param $comment
  *   A string containing a description of the materialized view
@@ -138,86 +146,90 @@ function tripal_add_mview ($name, $modulename, $mv_table, $mv_specs, $indexed,
  *
  * @ingroup tripal_mviews_api
  */
-function tripal_edit_mview ($mview_id,$name,$modulename,$mv_table,$mv_specs,
-   $indexed,$query,$special_index,$comment=NULL,$mv_schema=NULL)
-{
-
-   // get the table name from the schema array
-   $schema_arr = array();
-   if($mv_schema){
-      // get the schema from the mv_specs and use it to add the custom table
-      eval("\$schema_arr = $mv_schema;");
-      $mv_table = $schema_arr['table'];
-   }
-
-   $record = new stdClass();
-   $record->mview_id = $mview_id;
-   $record->name = $name;
-   $record->modulename = $modulename;
-   $record->mv_schema = $mv_schema;
-   $record->mv_table = $mv_table;
-   $record->mv_specs = $mv_specs;
-   $record->indexed = $indexed;
-   $record->query = $query;
-   $record->special_index = $special_index;
-   $record->last_update = 0;
-   $record->status = '';
-   $record->comment = $comment;
-
-   // drop the table from chado if it exists
-   $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = $mview_id ";
-   $mview = db_fetch_object(db_query($sql));
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   if (db_table_exists($mview->mv_table)) {
-      $sql = "DROP TABLE $mview->mv_table";
-      db_query($sql);
-   }
-   tripal_db_set_active($previous_db);  // now use drupal database
+function tripal_edit_mview($mview_id, $name, $modulename, $mv_table, $mv_specs,
+  $indexed, $query, $special_index, $comment = NULL, $mv_schema = NULL) {
 
-   // update the record to the tripal_mviews table and if successful
-   // create the new materialized view in the chado schema
-   if(drupal_write_record('tripal_mviews',$record,'mview_id')){
+  // get the table name from the schema array
+  $schema_arr = array();
+  if ($mv_schema) {
+    // get the schema from the mv_specs and use it to add the custom table
+    eval("\$schema_arr = $mv_schema;");
+    $mv_table = $schema_arr['table'];
+  }
 
-      // drop the table from chado if it exists
-      $previous_db = tripal_db_set_active('chado');  // use chado database
-      if (db_table_exists($mv_table)) {
-         $sql = "DROP TABLE $mv_table";
-         db_query($sql);
+  // Create a new record
+  $record = new stdClass();
+  $record->mview_id = $mview_id;
+  $record->name = $name;
+  $record->modulename = $modulename;
+  $record->mv_schema = $mv_schema;
+  $record->mv_table = $mv_table;
+  $record->mv_specs = $mv_specs;
+  $record->indexed = $indexed;
+  $record->query = $query;
+  $record->special_index = $special_index;
+  $record->last_update = 0;
+  $record->status = '';
+  $record->comment = $comment;
+
+  // drop the table from chado if it exists
+  $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d";
+  $mview = db_fetch_object(db_query($sql, $mview_id));
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  if (db_table_exists($mview->mv_table)) {
+    $sql = "DROP TABLE %s";
+    db_query($sql, $mview->mv_table);
+  }
+  tripal_db_set_active($previous_db);  // now use drupal database
+
+  // update the record to the tripal_mviews table and if successful
+  // create the new materialized view in the chado schema
+  if (drupal_write_record('tripal_mviews', $record, 'mview_id')) {
+    // drop the table from chado if it exists
+    $previous_db = tripal_db_set_active('chado');  // use chado database
+    if (db_table_exists($mv_table)) {
+      $sql = "DROP TABLE %s";
+      db_query($sql, $mv_table);
+    }
+    tripal_db_set_active($previous_db);  // now use drupal database
+
+    // now construct the indexes
+    $index = '';
+    if ($indexed) {
+      // add to the array of values
+      $vals = preg_split("/[\n,]+/", $indexed);
+      $index = '';
+      foreach ($vals as $field) {
+        $field = trim($field);
+        $index .= "CREATE INDEX idx_${mv_table}_${field} ON $mv_table ($field);";
       }
+    }
+
+    // re-create the table differently depending on if it the traditional method
+    // or the Drupal Schema API method
+    if ($mv_schema) {
+      if (!tripal_create_chado_table ($ret, $mv_table, $schema_arr)) {
+        drupal_set_message(t("Could not create the materialized view. Check Drupal error report logs."));
+      }
+      else {
+        drupal_set_message(t("View '%name' created", array('%name' => $name)));
+      }
+    }
+    else {
+      $sql = "CREATE TABLE {$mv_table} ($mv_specs); $index";
+      $previous_db = tripal_db_set_active('chado');  // use chado database
+      $results = db_query($sql);
       tripal_db_set_active($previous_db);  // now use drupal database
-      
-      // now construct the indexes
-      $index = '';
-      if($indexed){
-        // add to the array of values
-        $vals = preg_split("/[\n,]+/",$indexed);
-        $index = '';
-        foreach ($vals as $field){
-           $field = trim($field);
-           $index .= "CREATE INDEX idx_${mv_table}_${field} ON $mv_table ($field);";
-        }
+      if ($results) {
+        drupal_set_message(t("View '%name' edited and saved.  All results cleared. Please re-populate the view.", array('%name' => $name)));
       }
-      // re-create the table differently depending on if it the traditional method
-      // or the Drupal Schema API method
-      if($mv_schema){         
-         if(!tripal_create_chado_table ($ret,$mv_table,$schema_arr)){
-            drupal_set_message("Could not create the materialized view. Check Drupal error report logs.");
-         } else {
-            drupal_set_message(t("View '$name' created"));
-         }
-      } else {
-         $sql = "CREATE TABLE {$mv_table} ($mv_specs); $index"; 
-         $previous_db = tripal_db_set_active('chado');  // use chado database
-         $results = db_query($sql);
-         tripal_db_set_active($previous_db);  // now use drupal database
-         if($results){
-            drupal_set_message(t("View '$name' edited and saved.  All results cleared. Please re-populate the view."));
-         } else {
-            drupal_set_message(t("Failed to create the materialized view table: '$mv_table'"));
-         }
+      else {
+        drupal_set_message(t("Failed to create the materialized view table: '%mv_table'", array('%mv_table' => $mv_table)), 'error');
       }
-   }
+    }
+  }
 }
+
 /**
  * Retrieve the materialized view_id given the name
  *
@@ -229,475 +241,520 @@ function tripal_edit_mview ($mview_id,$name,$modulename,$mv_table,$mv_specs,
  *
  * @ingroup tripal_mviews_api
  */
-function tripal_mviews_get_mview_id ($view_name){
-
-   $sql = "SELECT * FROM {tripal_mviews} ".
-          "WHERE name = '%s'";
-   if(db_table_exists('tripal_mviews')){
-      $mview = db_fetch_object(db_query($sql,$view_name));
-	   if($mview){
-	      return $mview->mview_id;
-	   }
-   }
-   return 0;
+function tripal_mviews_get_mview_id($view_name) {
+  $sql = "SELECT * FROM {tripal_mviews} ".
+        "WHERE name = '%s'";
+  if (db_table_exists('tripal_mviews')) {
+    $mview = db_fetch_object(db_query($sql, $view_name));
+    if ($mview) {
+      return $mview->mview_id;
+    }
+  }
+
+  return FALSE;
 }
+
 /**
-*
-*
-* @ingroup tripal_core
-*/
-function tripal_mviews_action ($op,$mview_id,$redirect=0){
-   global $user;
-   $args = array("$mview_id");
-   
-   if(!$mview_id){
-      return '';
-   }
-
-   // get this mview details
-   $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = $mview_id ";
-   $mview = db_fetch_object(db_query($sql));
-   
-   // add a job or perform the action based on the given operation
-   if($op == 'update'){
-      tripal_add_job("Populate materialized view '$mview->name'",'tripal_core',
-         'tripal_update_mview',$args,$user->uid);
-	}
-   if($op == 'delete'){
-	   // remove the mview from the tripal_mviews table
-	   $sql = "DELETE FROM {tripal_mviews} ".
-             "WHERE mview_id = $mview_id";
+ * Does the specified action for the specified Materialized View
+ *
+ * @param $op
+ *   The action to be taken. One of update or delete
+ * @param $mview_id
+ *   The unique ID of the materialized view for the action to be performed on
+ * @param $redirect
+ *   TRUE/FALSE depending on whether you want to redirect the user to admin/tripal/mviews
+ *
+ * @ingroup tripal_core
+ */
+function tripal_mviews_action($op, $mview_id, $redirect = FALSE) {
+  global $user;
+
+  $args = array("$mview_id");
+  if (!$mview_id) {
+    return '';
+  }
+
+  // get this mview details
+  $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d";
+  $mview = db_fetch_object(db_query($sql, $mview_id));
+
+  // add a job or perform the action based on the given operation
+  if ($op == 'update') {
+    tripal_add_job("Populate materialized view '$mview->name'", 'tripal_core',
+       'tripal_update_mview', $args, $user->uid);
+  }
+  if ($op == 'delete') {
+    // remove the mview from the tripal_mviews table
+    $sql = "DELETE FROM {tripal_mviews} ".
+           "WHERE mview_id = $mview_id";
+    db_query($sql);
+    // drop the table from chado if it exists
+    $previous_db = tripal_db_set_active('chado');  // use chado database
+    if (db_table_exists($mview->mv_table)) {
+      $sql = "DROP TABLE $mview->mv_table";
       db_query($sql);
-		
-	   // drop the table from chado if it exists
-      $previous_db = tripal_db_set_active('chado');  // use chado database
-      if (db_table_exists($mview->mv_table)) {
-         $sql = "DROP TABLE $mview->mv_table";
-         db_query($sql);
-      }
-      tripal_db_set_active($previous_db);  // now use drupal database
-   }
-   if($redirect){
-      drupal_goto("admin/tripal/mviews");
-   }
+    }
+    tripal_db_set_active($previous_db);  // now use drupal database
+  }
+
+  // Redirect the user
+  if ($redirect) {
+    drupal_goto("admin/tripal/mviews");
+  }
 }
+
 /**
-* Update a Materialized View
-*
-* @param $mview_id
-*   The unique identifier for the materialized view to be updated
-*
-* @return
-*   True if successful, false otherwise
-*
-* @ingroup tripal_mviews_api
-*/
-function tripal_update_mview ($mview_id){
-   $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d ";
-   $mview = db_fetch_object(db_query($sql,$mview_id));
-   if($mview){
-      $previous_db = tripal_db_set_active('chado');  // use chado database
-	   $results = db_query("DELETE FROM {$mview->mv_table}");
-      $results = db_query("INSERT INTO {$mview->mv_table} ($mview->query)");
-      tripal_db_set_active($previous_db);  // now use drupal database
-      if($results){
-         $sql = "SELECT count(*) as cnt FROM {$mview->mv_table}";
-         $count = db_fetch_object(db_query($sql));
-	      $record = new stdClass();
-         $record->mview_id = $mview_id;
-         $record->last_update = time();
-         $record->status = "Populated with " . number_format($count->cnt) . " rows";
-		   drupal_write_record('tripal_mviews',$record,'mview_id');
-		   return 1;
-      } else {
-         # print and save the error message
-	      $record = new stdClass();
-         $record->mview_id = $mview_id;
-         $record->status = "ERROR populating. See Drupal's recent log entries for details.";
-         print $record->status . "\n";
-		   drupal_write_record('tripal_mviews',$record,'mview_id');
-	      return 0;
-	  }
-   }
+ * Update a Materialized View
+ *
+ * @param $mview_id
+ *   The unique identifier for the materialized view to be updated
+ *
+ * @return
+ *   True if successful, FALSE otherwise
+ *
+ * @ingroup tripal_mviews_api
+ */
+function tripal_update_mview($mview_id) {
+  $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d ";
+  $mview = db_fetch_object(db_query($sql, $mview_id));
+  if ($mview) {
+    $previous_db = tripal_db_set_active('chado');  // use chado database
+    $results = db_query("DELETE FROM {%s}", $mview->mv_table);
+    $results = db_query("INSERT INTO {%s} ($mview->query)", $mview->mv_table);
+    tripal_db_set_active($previous_db);  // now use drupal database
+    if ($results) {
+      $sql = "SELECT count(*) as cnt FROM {%s}";
+      $count = db_fetch_object(db_query($sql, $mview->mv_table));
+      $record = new stdClass();
+      $record->mview_id = $mview_id;
+      $record->last_update = time();
+      $record->status = "Populated with " . number_format($count->cnt) . " rows";
+      drupal_write_record('tripal_mviews', $record, 'mview_id');
+      return TRUE;
+    }
+    else {
+      // print and save the error message
+      $record = new stdClass();
+      $record->mview_id = $mview_id;
+      $record->status = "ERROR populating. See Drupal's recent log entries for details.";
+      print $record->status . "\n";
+      drupal_write_record('tripal_mviews', $record, 'mview_id');
+      return FALSE;
+    }
+  }
 }
+
 /**
-*
-*
-* @ingroup tripal_mviews_api
-*/
-function tripal_mview_report ($mview_id) {
-   // get this mview details
-   $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = $mview_id ";
-   $mview = db_fetch_object(db_query($sql));
-
-   // create a table with each row containig stats for
-   // an individual job in the results set.
-
-   $return_url = url("admin/tripal/mviews/");
-
-   $output .= "<p><a href=\"$return_url\">Return to table of materialized views.</a></p>";
-   $output .= "<br />";
-   $output .= "<p>Details for <b>$mview->name</b>:</p>";
-   $output .= "<br />";
-   $output .= "<table class=\"border-table\">";
-   if($mview->name){
-      $output .= "  <tr>".
-      "    <th>View Name</th>".
-      "    <td>$mview->name</td>".
-      "  </tr>";
-   }   
-   if($mview->modulename){
-      $output .= "  <tr>".
-      "    <th>Module Name</th>".
-      "    <td>$mview->modulename</td>".
-      "  </tr>";
-   }
-   if($mview->mv_table){
-      $output .= "  <tr>".
-      "    <th>Table Name</th>".
-      "    <td>$mview->mv_table</td>".
-      "  </tr>";
-   }   
-   if($mview->mv_specs){
-      $output .= "  <tr>".
-      "    <th>Table Field Definitions</th>".
-      "    <td>$mview->mv_specs</td>".
-      "  </tr>";
-   }   
-   if($mview->query){
-      $output .= "  <tr>".
-      "    <th>Query</th>".
-      "    <td><pre>$mview->query</pre></td>".
-      "  </tr>";
-   }   
-   if($mview->indexed){
-      $output .= "  <tr>".
-      "    <th>Indexed Fields</th>".
-      "    <td>$mview->indexed</td>".
-      "  </tr>";
-   }   
-   if($mview->special_index){
-      $output .= "  <tr>".
-      "    <th>Special Indexed Fields</th>".
-      "    <td>$mview->speical_index</td>".
-      "  </tr>";
-   }   
-   if($mview->last_update > 0){
-      $update = format_date($mview->last_update);
-   } else {
-      $update = 'Not yet populated';
-   }
-   $output .= "  <tr>".
-      "    <th>Last Update</th>".
-      "    <td>$update</td>".
-      "  </tr>";
-
-   // build the URLs using the url function so we can handle installations where
-   // clean URLs are or are not used
-   $update_url = url("admin/tripal/mviews/action/update/$mview->mview_id");
-   $delete_url = url("admin/tripal/mviews/action/delete/$mview->mview_id");
-   $edit_url = url("admin/tripal/mviews/edit/$mview->mview_id");
-
-   $output .= "<tr><th>Actions</th>".
-              "<td> <a href='$update_url'>Populate</a>, ".
-              "     <a href='$edit_url'>Edit</a>, ".
-              "     <a href='$delete_url'>Delete</a></td></tr>";
-
-   $output .= "</table>";
-
-   return $output;
+ * A template function which returns markup to display details for the current materialized view
+ *
+ * @param $mview_id
+ *  The unique ID of the materialized view to render
+ *
+ * @ingroup tripal_mviews_api
+ */
+function tripal_mview_report($mview_id) {
+
+  // get this mview details
+  $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d";
+  $mview = db_fetch_object(db_query($sql, $mview_id));
+
+  // create a table with each row containig stats for
+  // an individual job in the results set.
+  $return_url = url("admin/tripal/mviews/");
+  $output .= "<p><a href=\"$return_url\">Return to table of materialized views.</a></p>";
+  $output .= "<br />";
+  $output .= "<p>Details for <b>$mview->name</b>:</p>";
+  $output .= "<br />";
+  $output .= "<table class=\"border-table\">";
+  if ($mview->name) {
+    $output .= "  <tr>".
+    "    <th>View Name</th>".
+    "    <td>$mview->name</td>".
+    "  </tr>";
+  }
+  if ($mview->modulename) {
+    $output .= "  <tr>".
+    "    <th>Module Name</th>".
+    "    <td>$mview->modulename</td>".
+    "  </tr>";
+  }
+  if ($mview->mv_table) {
+    $output .= "  <tr>".
+    "    <th>Table Name</th>".
+    "    <td>$mview->mv_table</td>".
+    "  </tr>";
+  }
+  if ($mview->mv_specs) {
+    $output .= "  <tr>".
+    "    <th>Table Field Definitions</th>".
+    "    <td>$mview->mv_specs</td>".
+    "  </tr>";
+  }
+  if ($mview->query) {
+    $output .= "  <tr>".
+    "    <th>Query</th>".
+    "    <td><pre>$mview->query</pre></td>".
+    "  </tr>";
+  }
+  if ($mview->indexed) {
+    $output .= "  <tr>".
+    "    <th>Indexed Fields</th>".
+    "    <td>$mview->indexed</td>".
+    "  </tr>";
+  }
+  if ($mview->special_index) {
+    $output .= "  <tr>".
+    "    <th>Special Indexed Fields</th>".
+    "    <td>$mview->speical_index</td>".
+    "  </tr>";
+  }
+  if ($mview->last_update > 0) {
+    $update = format_date($mview->last_update);
+  }
+  else {
+    $update = 'Not yet populated';
+  }
+  $output .= "  <tr>".
+    "    <th>Last Update</th>".
+    "    <td>$update</td>".
+    "  </tr>";
+
+  // build the URLs using the url function so we can handle installations where
+  // clean URLs are or are not used
+  $update_url = url("admin/tripal/mviews/action/update/$mview->mview_id");
+  $delete_url = url("admin/tripal/mviews/action/delete/$mview->mview_id");
+  $edit_url = url("admin/tripal/mviews/edit/$mview->mview_id");
+  $output .= "<tr><th>Actions</th>".
+            "<td> <a href='$update_url'>Populate</a>, ".
+            "     <a href='$edit_url'>Edit</a>, ".
+            "     <a href='$delete_url'>Delete</a></td></tr>";
+  $output .= "</table>";
+
+  return $output;
 }
+
 /**
-*
-*
-* @ingroup tripal_mviews_api
-*/
-function tripal_mviews_report () {
-
-   $header = array('','MView Name','Last Update','Status','Description','');
-   $rows = array();
-
-   $mviews = db_query("SELECT * FROM {tripal_mviews} ORDER BY name");  
-   while($mview = db_fetch_object($mviews)){
-      if($mview->last_update > 0){
-         $update = format_date($mview->last_update);
-      } else {
-         $update = 'Not yet populated';
-      }
-      $rows[] = array(
-         l('View',"admin/tripal/mviews/report/$mview->mview_id") ." | ".
-         l('Edit',"admin/tripal/mviews/edit/$mview->mview_id") ." | ".
-         l('Populate',"admin/tripal/mviews/action/update/$mview->mview_id"),
-         $mview->name,
-         $update,
-         $mview->status,
-         $mview->comment,
-         l('Delete',"admin/tripal/mviews/action/delete/$mview->mview_id"),
-      );
-   }
-   $rows[] = array(
-      'data' => array( 
-         array('data' => l('Create a new materialized view.',"admin/tripal/mviews/new"), 
-               'colspan' => 6),
-         )
-   );
-   $page = theme('table', $header, $rows);
-
-   return $page;
+ * A template function to render a listing of all Materialized Views
+ *
+ * @ingroup tripal_mviews_api
+ */
+function tripal_mviews_report() {
+  $header = array('', 'MView Name', 'Last Update', 'Status', 'Description', '');
+  $rows = array();
+  $mviews = db_query("SELECT * FROM {tripal_mviews} ORDER BY name");
+
+  while ($mview = db_fetch_object($mviews)) {
+    if ($mview->last_update > 0) {
+      $update = format_date($mview->last_update);
+    }
+    else {
+      $update = 'Not yet populated';
+    }
+
+    $rows[] = array(
+      l(t('View'), "admin/tripal/mviews/report/$mview->mview_id") ." | ".
+      l(t('Edit'), "admin/tripal/mviews/edit/$mview->mview_id") ." | ".
+      l(t('Populate'), "admin/tripal/mviews/action/update/$mview->mview_id"),
+      $mview->name,
+      $update,
+      $mview->status,
+      $mview->comment,
+      l(t('Delete'), "admin/tripal/mviews/action/delete/$mview->mview_id"),
+    );
+  }
+
+  $rows[] = array(
+    'data' => array(
+      array('data' => l(t('Create a new materialized view.'), "admin/tripal/mviews/new"),
+        'colspan' => 6),
+    )
+  );
+
+  $page = theme('table', $header, $rows);
+  return $page;
 }
+
 /**
-*
-*
-* @ingroup tripal_core
-*/
-function tripal_mviews_form(&$form_state = NULL,$mview_id = NULL){
-
-   if(!$mview_id){
-      $action = 'Add';
-   } else {
-      $action = 'Edit';
-   }
-
-   // get this requested view
-   if(strcmp($action,'Edit')==0){
-      $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d ";
-      $mview = db_fetch_object(db_query($sql,$mview_id));
-      
-      # set the default values.  If there is a value set in the 
-      # form_state then let's use that, otherwise, we'll pull 
-      # the values from the database 
-      $default_name = $form_state['values']['name'];
-      $default_mv_table = $form_state['values']['mv_table'];
-      $default_mv_specs = $form_state['values']['mv_specs'];
-      $default_indexed = $form_state['values']['indexed'];
-      $default_mvquery = $form_state['values']['mvquery'];
-      $default_special_index = $form_state['values']['special_index'];
-      $default_comment = $form_state['values']['cpmment'];
-      if(!$default_name){
-         $default_name = $mview->name;
-      }
-      if(!$default_mv_table){
-         $default_mv_table = $mview->mv_table;
-      }
-      if(!$default_mv_specs){
-         $default_mv_specs = $mview->mv_specs;
-      }
-      if(!$default_indexed){
-         $default_indexed = $mview->indexed;
-      }
-      if(!$default_mvquery){
-         $default_mvquery = $mview->query;
-      }
-      if(!$default_special_index){
-         $default_special_index = $mview->special_index;
-      }
-      if(!$default_comment){
-         $default_comment = $mview->comment;
-      }      
-      if(!$default_schema){
-         $default_schema = $mview->mv_schema;
-      }
-      // the mv_table column of the tripal_mviews table always has the table 
-      // name even if it is a custom table. However, for the sake of the form,
-      // we do not want this to show up as the mv_table is needed for the 
-      // traditional style input.  We'll blank it out if we have a custom 
-      // table and it will get reset in the submit function using the 
-      // 'table' value from the schema array
-      if($default_schema){
-         $default_mv_table = '';
-      }
-      
-      // set which fieldset is collapsed 
-      $schema_collapsed = 0;      
-      $traditional_collapsed = 1;
-      if(!$default_schema){
-         $schema_collapsed = 1;      
-         $traditional_collapsed = 0;
-      }
-   }
-   // Build the form
-   $form['action'] = array(
-      '#type' => 'value',
-      '#value' => $action
-   );
-   $form['mview_id'] = array(
-      '#type' => 'value',
-      '#value' => $mview_id
-   );
-   $form['name']= array(
-      '#type'          => 'textfield',
-      '#title'         => t('View Name'),
-      '#description'   => t('Please enter the name for this materialized view.'),
-      '#required'      => TRUE,
-      '#default_value' => $default_name,
-   );
-   $form['comment']= array(
-      '#type'          => 'textarea',
-      '#title'         => t('MView Description'),
-      '#description'   => t('Optional.  Please provide a description of the purpose for this materialized vieww.'),
-      '#required'      => FALSE,
-      '#default_value' => $default_comment,
-   );
-
-   // add a fieldset for the Drupal Schema API
-   $form['schema'] = array(
-     '#type' => 'fieldset',
-     '#title' => 'Drupal Schema API Setup',
-     '#description' => t('Use the Drupal Schema API array to describe a table. The benefit is that it '.
-                         'can be fully integrated with Tripal Views.  Tripal supports an extended '.
-                         'array format to allow for descriptoin of foreign key relationships.'),
-     '#collapsible' => 1,
-     '#collapsed' => $schema_collapsed ,
-   );
-   $form['schema']['schema']= array(
-      '#type'          => 'textarea',
-      '#title'         => t('Schema Array'),
-      '#description'   => t('Please enter the Drupal Schema API compatible array that defines the table.'),
-      '#required'      => FALSE,
-      '#default_value' => $default_schema,
-      '#rows'          => 25,
-   ); 
-   // add a fieldset for the Original Table Description fields
-   $form['traditional'] = array(
-     '#type' => 'fieldset',
-     '#title' => 'Traditional MViews Setup',
-     '#description' => t('Traidtionally with Tripal MViews were created by specifying PostgreSQL style '.
-                         'column types.  This method can be used but is deprecated in favor of the '.
-                         'newer Drupal schema API method provided above.'),
-     '#collapsible' => 1,
-     '#collapsed' => $traditional_collapsed,
-   ); 
-   $form['traditional']['mv_table']= array(
-      '#type'          => 'textfield',
-      '#title'         => t('Table Name'),
-      '#description'   => t('Please enter the table name that this view will generate in the database.  You can use the schema and table name for querying the view'),
-      '#required'      => FALSE,
-      '#default_value' => $default_mv_table,
-   );
-   $form['traditional']['mv_specs']= array(
-      '#type'          => 'textarea',
-      '#title'         => t('Table Definition'),
-      '#description'   => t('Please enter the field definitions for this view. Each field should be separated by a comma or enter each field definition on each line.'),
-      '#required'      => FALSE,
-      '#default_value' => $default_mv_specs,
-   );
-   $form['traditional']['indexed']= array(
-      '#type'          => 'textarea',
-      '#title'         => t('Indexed Fields'),
-      '#description'   => t('Please enter the field names (as provided in the table definition above) that will be indexed for this view.  Separate by a comma or enter each field on a new line.'),
-      '#required'      => FALSE,
-      '#default_value' => $default_indexed,
-   );
-/**
-   $form['traditional']['special_index']= array(
-      '#type'          => 'textarea',
-      '#title'         => t('View Name'),
-      '#description'   => t('Please enter the name for this materialized view.'),
-      '#required'      => TRUE,
-      '#default_value' => $default_special_index,
-   );
-*/
-   $form['mvquery']= array(
-      '#type'          => 'textarea',
-      '#title'         => t('Query'),
-      '#description'   => t('Please enter the SQL statement used to populate the table.'),
-      '#required'      => TRUE,
-      '#default_value' => $default_mvquery,
-      '#rows'          => 25,
-   );
-   if($action == 'Edit'){
-      $value = 'Save';
-   }
-   if($action == 'Add'){
-      $value = 'Add';
-   }
-   $form['submit'] = array (
-     '#type'         => 'submit',
-     '#value'        => t($value),
-     '#weight'       => 9,
-     '#executes_submit_callback' => TRUE,
-   );
-
-   $form['#redirect'] = 'admin/tripal/mviews';
-   return $form;
+ * A Form to Create/Edit a Materialized View
+ *
+ * @param $form_state
+ *   The current state of the form (Form API)
+ * @param $mview_id
+ *   The unique ID of the Materialized View to Edit or NULL if creating a new materialized view
+ *
+ * @return
+ *   A form array (Form API)
+ *
+ * @ingroup tripal_core
+ */
+function tripal_mviews_form(&$form_state = NULL, $mview_id = NULL) {
+
+  if (!$mview_id) {
+    $action = 'Add';
+  }
+  else {
+    $action = 'Edit';
+  }
+
+  // get this requested view
+  if (strcmp($action, 'Edit')==0) {
+    $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d ";
+    $mview = db_fetch_object(db_query($sql, $mview_id));
+
+    // set the default values.  If there is a value set in the
+    // form_state then let's use that, otherwise, we'll pull
+    // the values from the database
+    $default_name = $form_state['values']['name'];
+    $default_mv_table = $form_state['values']['mv_table'];
+    $default_mv_specs = $form_state['values']['mv_specs'];
+    $default_indexed = $form_state['values']['indexed'];
+    $default_mvquery = $form_state['values']['mvquery'];
+    $default_special_index = $form_state['values']['special_index'];
+    $default_comment = $form_state['values']['cpmment'];
+
+    if (!$default_name) {
+      $default_name = $mview->name;
+    }
+    if (!$default_mv_table) {
+      $default_mv_table = $mview->mv_table;
+    }
+    if (!$default_mv_specs) {
+      $default_mv_specs = $mview->mv_specs;
+    }
+    if (!$default_indexed) {
+      $default_indexed = $mview->indexed;
+    }
+    if (!$default_mvquery) {
+      $default_mvquery = $mview->query;
+    }
+    if (!$default_special_index) {
+      $default_special_index = $mview->special_index;
+    }
+    if (!$default_comment) {
+      $default_comment = $mview->comment;
+    }
+    if (!$default_schema) {
+      $default_schema = $mview->mv_schema;
+    }
+
+    // the mv_table column of the tripal_mviews table always has the table
+    // name even if it is a custom table. However, for the sake of the form,
+    // we do not want this to show up as the mv_table is needed for the
+    // traditional style input.  We'll blank it out if we have a custom
+    // table and it will get reset in the submit function using the
+    // 'table' value from the schema array
+    if ($default_schema) {
+      $default_mv_table = '';
+    }
+    // set which fieldset is collapsed
+    $schema_collapsed = 0;
+    $traditional_collapsed = 1;
+    if (!$default_schema) {
+      $schema_collapsed = 1;
+      $traditional_collapsed = 0;
+    }
+  }
+
+  // Build the form
+  $form['action'] = array(
+    '#type' => 'value',
+    '#value' => $action
+  );
+
+  $form['mview_id'] = array(
+    '#type' => 'value',
+    '#value' => $mview_id
+  );
+
+  $form['name']= array(
+    '#type'          => 'textfield',
+    '#title'         => t('View Name'),
+    '#description'   => t('Please enter the name for this materialized view.'),
+    '#required'      => TRUE,
+    '#default_value' => $default_name,
+  );
+
+  $form['comment']= array(
+    '#type'          => 'textarea',
+    '#title'         => t('MView Description'),
+    '#description'   => t('Optional.  Please provide a description of the purpose for this materialized vieww.'),
+    '#required'      => FALSE,
+    '#default_value' => $default_comment,
+  );
+
+  // add a fieldset for the Drupal Schema API
+  $form['schema'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Drupal Schema API Setup',
+    '#description' => t('Use the Drupal Schema API array to describe a table. The benefit is that it '.
+                       'can be fully integrated with Tripal Views.  Tripal supports an extended '.
+                       'array format to allow for descriptoin of foreign key relationships.'),
+    '#collapsible' => 1,
+    '#collapsed' => $schema_collapsed ,
+  );
+
+  $form['schema']['schema']= array(
+    '#type'          => 'textarea',
+    '#title'         => t('Schema Array'),
+    '#description'   => t('Please enter the Drupal Schema API compatible array that defines the table.'),
+    '#required'      => FALSE,
+    '#default_value' => $default_schema,
+    '#rows'          => 25,
+  );
+
+  // add a fieldset for the Original Table Description fields
+  $form['traditional'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Traditional MViews Setup',
+    '#description' => t('Traidtionally with Tripal MViews were created by specifying PostgreSQL style '.
+                       'column types.  This method can be used but is deprecated in favor of the '.
+                       'newer Drupal schema API method provided above.'),
+    '#collapsible' => 1,
+    '#collapsed' => $traditional_collapsed,
+  );
+
+  $form['traditional']['mv_table']= array(
+    '#type'          => 'textfield',
+    '#title'         => t('Table Name'),
+    '#description'   => t('Please enter the table name that this view will generate in the database.  You can use the schema and table name for querying the view'),
+    '#required'      => FALSE,
+    '#default_value' => $default_mv_table,
+  );
+
+  $form['traditional']['mv_specs']= array(
+    '#type'          => 'textarea',
+    '#title'         => t('Table Definition'),
+    '#description'   => t('Please enter the field definitions for this view. Each field should be separated by a comma or enter each field definition on each line.'),
+    '#required'      => FALSE,
+    '#default_value' => $default_mv_specs,
+  );
+
+  $form['traditional']['indexed']= array(
+    '#type'          => 'textarea',
+    '#title'         => t('Indexed Fields'),
+    '#description'   => t('Please enter the field names (as provided in the table definition above) that will be indexed for this view.  Separate by a comma or enter each field on a new line.'),
+    '#required'      => FALSE,
+    '#default_value' => $default_indexed,
+  );
+
+  /**
+  $form['traditional']['special_index']= array(
+    '#type'          => 'textarea',
+    '#title'         => t('View Name'),
+    '#description'   => t('Please enter the name for this materialized view.'),
+    '#required'      => TRUE,
+    '#default_value' => $default_special_index,
+  );
+  */
+
+  $form['mvquery']= array(
+    '#type'          => 'textarea',
+    '#title'         => t('Query'),
+    '#description'   => t('Please enter the SQL statement used to populate the table.'),
+    '#required'      => TRUE,
+    '#default_value' => $default_mvquery,
+    '#rows'          => 25,
+  );
+
+  if ($action == 'Edit') {
+    $value = 'Save';
+  }
+  if ($action == 'Add') {
+    $value = 'Add';
+  }
+  $form['submit'] = array(
+    '#type'         => 'submit',
+    '#value'        => t($value),
+    '#weight'       => 9,
+    '#executes_submit_callback' => TRUE,
+  );
+  $form['#redirect'] = 'admin/tripal/mviews';
+
+  return $form;
 }
+
 /**
-*
-*
-* @ingroup tripal_core
-*/
-function tripal_mviews_form_validate($form, &$form_state){
-   $action = $form_state['values']['action'];
-   $mview_id = $form_state['values']['mview_id'];
-   $name = $form_state['values']['name'];
-   $mv_table = $form_state['values']['mv_table'];
-   $mv_specs = $form_state['values']['mv_specs'];
-   $indexed = $form_state['values']['indexed'];
-   $query = $form_state['values']['mvquery'];
-   $special_index = $form_state['values']['special_index'];
-   $comment = $form_state['values']['comment'];
-   $schema = $form_state['values']['schema'];
-   
-   if($schema and ($mv_table or $mv_specs or $indexed or $special_index)){
-       form_set_error($form_state['values']['schema'], 
-          t('You can create an MView using the Drupal Schema API method or the '.
-            'traditional method but not both.'));
-   }
-   if(!$schema){
-      if(!$mv_specs){
-         form_set_error($form_state['values']['mv_specs'], 
-            t('The Table Definition field is required.'));
-      }
-      if(!$mv_table){
-         form_set_error($form_state['values']['mv_table'], 
-            t('The Table Name field is required.'));
-      }
-   }
-   
-   // make sure the array is valid
-   if($schema){
-      $success = eval("\$schema_array = $schema;");
-      if ($success === FALSE){
-         $error = error_get_last();
-         form_set_error($form_state['values']['schema'], 
-            t("The schema array is improperly formatted. Parse Error : " . $error["message"]));
-      }
-      if(!array_key_exists('table',$schema_array)){
-         form_set_error($form_state['values']['schema'], 
-            t("The schema array must have key named 'table'"));
-      } 
-      // TODO: add in more validation checks of the array to help the user
-   }
+ * Validate the Create/Edit Materialized View Form
+ * Implements hook_form_validate().
+ *
+ * @ingroup tripal_core
+ */
+function tripal_mviews_form_validate($form, &$form_state) {
+  $action = $form_state['values']['action'];
+  $mview_id = $form_state['values']['mview_id'];
+  $name = $form_state['values']['name'];
+  $mv_table = $form_state['values']['mv_table'];
+  $mv_specs = $form_state['values']['mv_specs'];
+  $indexed = $form_state['values']['indexed'];
+  $query = $form_state['values']['mvquery'];
+  $special_index = $form_state['values']['special_index'];
+  $comment = $form_state['values']['comment'];
+  $schema = $form_state['values']['schema'];
+
+  if ($schema and ($mv_table or $mv_specs or $indexed or $special_index)) {
+    form_set_error($form_state['values']['schema'],
+      t('You can create an MView using the Drupal Schema API method or the '.
+        'traditional method but not both.'));
+  }
+  if (!$schema) {
+    if (!$mv_specs) {
+      form_set_error($form_state['values']['mv_specs'],
+        t('The Table Definition field is required.'));
+    }
+    if (!$mv_table) {
+      form_set_error($form_state['values']['mv_table'],
+        t('The Table Name field is required.'));
+    }
+  }
+
+  // make sure the array is valid
+  if ($schema) {
+    $success = eval("\$schema_array = $schema;");
+    if ($success === FALSE) {
+      $error = error_get_last();
+      form_set_error($form_state['values']['schema'],
+        t("The schema array is improperly formatted. Parse Error : " . $error["message"]));
+    }
+    if (!array_key_exists('table', $schema_array)) {
+      form_set_error($form_state['values']['schema'],
+        t("The schema array must have key named 'table'"));
+    }
+
+    // TODO: add in more validation checks of the array to help the user
+  }
 }
+
 /**
-*
-*
-* @ingroup tripal_core
-*/
-function tripal_mviews_form_submit($form, &$form_state){
-   $ret = array();
-   
-   $action = $form_state['values']['action'];
-   $mview_id = $form_state['values']['mview_id'];
-   $name = $form_state['values']['name'];
-   $mv_table = $form_state['values']['mv_table'];
-   $mv_specs = $form_state['values']['mv_specs'];
-   $indexed = $form_state['values']['indexed'];
-   $query = $form_state['values']['mvquery'];
-   $special_index = $form_state['values']['special_index'];
-   $comment = $form_state['values']['comment'];
-   $schema = $form_state['values']['schema'];
-
-   if(strcmp($action,'Edit')==0){
-      tripal_edit_mview($mview_id,$name, 'tripal_core',$mv_table, $mv_specs,
-         $indexed,$query,$special_index,$comment,$schema);
-   }
-   else if(strcmp($action,'Add')==0){
-      tripal_add_mview ($name, 'tripal_core',$mv_table, $mv_specs,
-         $indexed,$query,$special_index,$comment,$schema);
-   }
-   else {
-        drupal_set_message("No action performed.");
-   }
-   return '';
-}
+ * Submit the Create/Edit Materialized View Form
+ * Implements hook_form_submit().
+ *
+ * @ingroup tripal_core
+ */
+function tripal_mviews_form_submit($form, &$form_state) {
+
+  $ret = array();
+  $action = $form_state['values']['action'];
+  $mview_id = $form_state['values']['mview_id'];
+  $name = $form_state['values']['name'];
+  $mv_table = $form_state['values']['mv_table'];
+  $mv_specs = $form_state['values']['mv_specs'];
+  $indexed = $form_state['values']['indexed'];
+  $query = $form_state['values']['mvquery'];
+  $special_index = $form_state['values']['special_index'];
+  $comment = $form_state['values']['comment'];
+  $schema = $form_state['values']['schema'];
+
+  if (strcmp($action, 'Edit') == 0) {
+    tripal_edit_mview($mview_id, $name, 'tripal_core', $mv_table, $mv_specs,
+      $indexed, $query, $special_index, $comment, $schema);
+  }
+  elseif (strcmp($action, 'Add') == 0) {
+    tripal_add_mview($name, 'tripal_core', $mv_table, $mv_specs,
+      $indexed, $query, $special_index, $comment, $schema);
+  }
+  else {
+    drupal_set_message(t("No action performed."));
+  }
+
+  return '';
+}

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 608 - 570
tripal_core/tripal_core.api.inc


+ 21 - 0
tripal_core/tripal_core.coder_ignores.txt

@@ -0,0 +1,21 @@
+; The file should be formatted this way :
+; file:line:warning-type
+; where warning-type is one of security, style, sql, i18n, comment, etc.
+
+; This select statement is acting upon the pg_catalog schema rather then the Drupal
+; schema and thus the curly brackets ({}) are not needed.
+tripal_core.schema.api.inc:54:sql
+tripal_core.schema.api.inc:59:sql
+tripal_core.api.inc:1953:sql
+
+; This query selects from a non-drupal schema where the database prefixes are not
+; applied and thus the curcly brackets ({}) are not needed
+tripal_core.api.inc:971:sql
+
+; Only module designers can create the criteria evaluated by drupal_eval since it
+; is designed in a hook. Since module designers can already write php code to act on 
+; the database and the criteria is never subject to user input, this is not a security 
+; risk.
+tripal_core.api.inc:906:security
+tripal_core.api.inc:941:security
+tripal_core.api.inc:992:security

+ 31 - 29
tripal_core/tripal_core.drush.inc

@@ -1,5 +1,10 @@
 <?php
 
+/**
+ * @file
+ * Contains function relating to drush-integration of this module.
+ */
+
 /**
  * Describes each drush command implemented by the module
  *
@@ -71,50 +76,46 @@ function tripal_core_drush_command() {
 
 /**
  * Executes jobs in the Tripal Jobs Queue
- * 
+ *
  * NOTE: The following code is executed when drush 'trpjob-run' or 'drush tripal-launch-jobs' is called
  */
-function drush_tripal_core_tripal_launch_jobs () {
-  $parallel = drush_get_option('parallel');   
-  
-  if($parallel){
+function drush_tripal_core_tripal_launch_jobs() {
+  $parallel = drush_get_option('parallel');
+  if ($parallel) {
     print "Tripal Job Launcher (in parallel)\n";
     print "-------------------\n";
     tripal_jobs_launch($parallel);
-  } else {
+  }
+  else {
     print "Tripal Job Launcher\n";
     print "-------------------\n";
-    tripal_jobs_launch();  
+    tripal_jobs_launch();
   }
 }
 
 /**
  * Prints details about the current running job
- * 
+ *
  * NOTE: The following code is executed when 'drush trpjob-curr' or 'drush tripal-current-job' is called
  */
-function drush_tripal_core_tripal_current_job () {
-  
+function drush_tripal_core_tripal_current_job() {
   $sql =  "SELECT * FROM {tripal_jobs} TJ ".
             "WHERE TJ.end_time IS NULL and NOT TJ.start_time IS NULL ";
   $jobs = db_query($sql);
   while ($job = db_fetch_object($jobs)) {
     $job_pid = $job->pid;
-
-    $output = "Name: ".$job->job_name."\n"
-             ."Submitted: ".date(DATE_RFC822,$job->submit_date)."\n"
-             ."Started: ".date(DATE_RFC822,$job->start_time)."\n"
-             ."Module: ".$job->modulename."\n"
-             ."Callback: ".$job->callback."\n"
-             ."Process ID: ".$job->pid."\n"
-             ."Progress: ".$job->progress."%\n";
+    $output = "Name: " . $job->job_name . "\n"
+             ."Submitted: " . date(DATE_RFC822, $job->submit_date) . "\n"
+             ."Started: " . date(DATE_RFC822, $job->start_time) . "\n"
+             ."Module: " . $job->modulename . "\n"
+             ."Callback: " . $job->callback . "\n"
+             ."Process ID: " . $job->pid . "\n"
+             ."Progress: " . $job->progress . "%\n";
     drush_print($output);
   }
-  
   if (!$job_pid) {
     drush_print('There are currently no running jobs.');
   }
-    
   //log to the command line with an OK status
   drush_log('Running tripal-current-job', 'ok');
 }
@@ -128,11 +129,11 @@ function drush_tripal_core_tripal_current_job () {
  *   The name of the table storing the materialized view (tripal_mview.mv_table)
  *
  * Note: Either $mview_id OR $table_name is required
- */ 
-function drush_tripal_core_tripal_update_mview () {
+ */
+function drush_tripal_core_tripal_update_mview() {
   $mview_id = drush_get_option('mview_id');
   $table_name = drush_get_option('table_name');
-  
+
   // Either table_name or mview is required
   if (!$mview_id) {
     if ($table_name) {
@@ -143,17 +144,18 @@ function drush_tripal_core_tripal_update_mview () {
         drush_set_error('No Materialized View associated with that table_name.');
       }
       $mview_id=$r->mview_id;
-    } else {
+    }
+    else {
       drush_set_error('Either mview_id OR table_name are required.');
     }
   }
-  
-  drush_print('Updating the Materialized View with ID='.$mview_id);  
+
+  drush_print('Updating the Materialized View with ID=' . $mview_id);
   $status = tripal_update_mview($mview_id);
   if ($status) {
     drush_log('Materialized View Updated', 'ok');
-  } else {
+  }
+  else {
     drush_set_error('Update failed.');
   }
-  
-}
+}

+ 197 - 175
tripal_core/tripal_core.install

@@ -1,195 +1,217 @@
 <?php
 
-/************************************************************************
-*  Implementation of hook_install();
-* 
-* @ingroup tripal_core
-*/
-function tripal_core_install(){
-
-   // make the data directory for this module
-   $data_dir = file_directory_path() . "/tripal";
-   if(!file_check_directory($data_dir,FILE_CREATE_DIRECTORY)){
-      $message = "Cannot create directory $data_dir. This module may not ".
-                 "behave correctly without this directory.  Please  create ".
-                 "the directory manually or fix the problem and reinstall.";
-      drupal_set_message($message,'error');      
-      watchdog('tripal_core',$message,array(),WATCHDOG_ERROR);
-   }
+/**
+ * @file
+ * Contains functions used to install/uninstall tripal_core.
+ */
+
+/**
+ * Implementation of hook_install().
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_install() {
+
+  // make the data directory for this module
+  $data_dir = file_directory_path() . "/tripal";
+  if (!file_check_directory($data_dir, FILE_CREATE_DIRECTORY)) {
+    $message = "Cannot create directory $data_dir. This module may not ".
+               "behave correctly without this directory.  Please  create ".
+               "the directory manually or fix the problem and reinstall.";
+    drupal_set_message(check_plain($message), 'error');
+    watchdog('tripal_core', $message, array(), WATCHDOG_ERROR);
+  }
 
   // create the tables that manage materialized views and jobs
   drupal_install_schema('tripal_core');
 
 }
+
 /**
-*  Update for Drupal 6.x, Tripal 0.4
-*  This update adjusts the materialized view by adding a 'cvterm_id' column
-*
-* @ingroup tripal_feature
-*/
-function tripal_core_update_6000(){
-   // add additional columsn to the tripal_mviews table
-   db_add_field($ret, 'tripal_mviews', 'status', array('type' => 'text', 'size' => 'normal', 'not null' => FALSE));
-   db_add_field($ret, 'tripal_mviews', 'comment', array('type' => 'text', 'size' => 'normal', 'not null' => FALSE));
-   db_add_field($ret, 'tripal_mviews', 'mv_schema', array('type' => 'text', 'size' => 'normal', 'not null' => FALSE));
-   db_change_field($ret, 'tripal_mviews', 'mv_table','mv_table',array('type' => 'varchar','length' => 128, 'not null' => FALSE));
-   db_change_field($ret, 'tripal_mviews', 'mv_specs','mv_specs',array('type' => 'text', 'size' => 'normal', 'not null' => FALSE));
-   db_change_field($ret, 'tripal_mviews', 'indexed','indexed',array('type' => 'text', 'size' => 'normal', 'not null' => FALSE));
-
-   
-   // create the custom tables table
-   $ret = array();
-   $schema = tripal_core_custom_tables_schema();
-   db_create_table($ret,'tripal_custom_tables',$schema['tripal_custom_tables']);
-   
-   $ret = array(
-      '#finished' => 1,
-   );
-
-   return $ret;
+ *  Update for Drupal 6.x, Tripal 0.4
+ *  This update
+ *   - adjusts the materialized view by adding status, comment and mv_schema columns
+ *   - changes the specs of mv_table, mv_specs and indexed
+ *   - creates the tripal_custom_tables table
+ *
+ * @ingroup tripal_feature
+ */
+function tripal_core_update_6000() {
+  // add additional columsn to the tripal_mviews table
+  db_add_field($ret, 'tripal_mviews', 'status', array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE));
+  db_add_field($ret, 'tripal_mviews', 'comment', array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE));
+  db_add_field($ret, 'tripal_mviews', 'mv_schema', array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE));
+  db_change_field($ret, 'tripal_mviews', 'mv_table', 'mv_table', array('type' => 'varchar', 'length' => 128, 'not NULL' => FALSE));
+  db_change_field($ret, 'tripal_mviews', 'mv_specs', 'mv_specs', array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE));
+  db_change_field($ret, 'tripal_mviews', 'indexed', 'indexed', array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE));
+
+  // create the custom tables table
+  $ret = array();
+  $schema = tripal_core_custom_tables_schema();
+  db_create_table($ret, 'tripal_custom_tables', $schema['tripal_custom_tables']);
+
+  $ret = array(
+    '#finished' => 1,
+  );
+
+  return $ret;
 }
 
-/************************************************************************
-* Implementation of hook_schema().
-*
-* @ingroup tripal_core
-*/
+/**
+ * Implementation of hook_schema().
+ *
+ * @ingroup tripal_core
+ */
 function tripal_core_schema() {
-   $schema = tripal_core_get_schemas();
-   
-   // if this module is already installed and enabled, then we want to provide
-   // the schemas for all of the custom tables.  This will allow Views to 
-   // see the schemas.  We check if the module is installed because during 
-   // installation we don't want to make these custom tables available as we don't
-   // want them created in the Drupal database.  The custom tables go in the 
-   // Chado database.
-   $sql = 'SELECT * FROM {tripal_custom_tables}';
-   $q = db_query($sql);
-   while($custom = db_fetch_object($q)){
-      $schema[$custom->table_name] = unserialize($custom->schema);
-   }
-   return $schema;
+  $schema = tripal_core_get_schemas();
+
+  // if this module is already installed and enabled, then we want to provide
+  // the schemas for all of the custom tables.  This will allow Views to
+  // see the schemas.  We check if the module is installed because during
+  // installation we don't want to make these custom tables available as we don't
+  // want them created in the Drupal database.  The custom tables go in the
+  // Chado database.
+  $sql = 'SELECT * FROM {tripal_custom_tables}';
+  $q = db_query($sql);
+  while ($custom = db_fetch_object($q)) {
+    $schema[$custom->table_name] = unserialize($custom->schema);
+  }
+
+  return $schema;
 }
-/************************************************************************
-* Implementation of hook_uninstall()
-*
-* @ingroup tripal_core
-*/
-function tripal_core_uninstall(){
-   drupal_uninstall_schema('tripal_core');
+
+/**
+ * Implementation of hook_uninstall().
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_uninstall() {
+  drupal_uninstall_schema('tripal_core');
 }
 
-/************************************************************************
-* This function simply defines all tables needed for the module to work
-* correctly.  By putting the table definitions in a separate function we
-* can easily provide the entire list for hook_install or individual
-* tables for an update.
-*
-* @ingroup tripal_core
-*/
-function tripal_core_get_schemas (){  
-   $schema = array();
-
-   // get all the various schema parts and join them together
-   $temp = tripal_core_jobs_schema();
-   foreach ($temp as $table => $arr){ 
-      $schema[$table] = $arr; 
-   }
-   $temp = tripal_core_mviews_schema();
-   foreach ($temp as $table => $arr){ 
-      $schema[$table] = $arr; 
-   }
-   $temp = tripal_core_custom_tables_schema();
-   foreach ($temp as $table => $arr){ 
-      $schema[$table] = $arr; 
-   }
-	return $schema;
+/**
+ * This function simply defines all tables needed for the module to work
+ * correctly.  By putting the table definitions in a separate function we
+ * can easily provide the entire list for hook_install or individual
+ * tables for an update.
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_get_schemas() {
+  $schema = array();
+
+  // get all the various schema parts and join them together
+  $temp = tripal_core_jobs_schema();
+  foreach ($temp as $table => $arr) {
+    $schema[$table] = $arr;
+  }
+  $temp = tripal_core_mviews_schema();
+  foreach ($temp as $table => $arr) {
+    $schema[$table] = $arr;
+  }
+  $temp = tripal_core_custom_tables_schema();
+  foreach ($temp as $table => $arr) {
+    $schema[$table] = $arr;
+  }
+
+  return $schema;
 }
-/************************************************************************
-* 
-*
-* @ingroup tripal_core
-*/
-function tripal_core_mviews_schema(){
-   $schema = array();
-   $schema['tripal_mviews'] = array(
-      'fields' => array(
-         'mview_id'      => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
-         'name'          => array('type' => 'varchar','length' => 255, 'not null' => TRUE),
-         'modulename'    => array('type' => 'varchar','length' => 50, 'not null' => TRUE, 'description' => 'The module name that provides the callback for this job'),
-         'mv_table'      => array('type' => 'varchar','length' => 128, 'not null' => FALSE),
-         'mv_specs'      => array('type' => 'text', 'size' => 'normal', 'not null' => FALSE),
-         'mv_schema'     => array('type' => 'text', 'size' => 'normal', 'not null' => FALSE),
-         'indexed'       => array('type' => 'text', 'size' => 'normal', 'not null' => FALSE),
-         'query'         => array('type' => 'text', 'size' => 'normal', 'not null' => TRUE),
-         'special_index' => array('type' => 'text', 'size' => 'normal', 'not null' => FALSE),
-         'last_update'   => array('type' => 'int', 'not null' => FALSE, 'description' => 'UNIX integer time'),
-         'status'        => array('type' => 'text', 'size' => 'normal', 'not null' => FALSE),
-         'comment'       => array('type' => 'text', 'size' => 'normal', 'not null' => FALSE),
-      ),
-      'indexes' => array(
-         'mview_id' => array('mview_id')
-      ),
-      'unique keys' => array(
-         'mv_table' => array('mv_table'),
-         'mv_name' => array('name'),
-      ),
-      'primary key' => array('mview_id'),
+
+/**
+ * Describes the Tripal Materialized View (tripal_mviews) table
+ * This table keeps track of all materialized views created by Tripal and stored in chado
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_mviews_schema() {
+  $schema = array();
+
+  $schema['tripal_mviews'] = array(
+    'fields' => array(
+      'mview_id'      => array('type' => 'serial', 'unsigned' => TRUE, 'not NULL' => TRUE),
+      'name'          => array('type' => 'varchar', 'length' => 255, 'not NULL' => TRUE),
+      'modulename'    => array('type' => 'varchar', 'length' => 50, 'not NULL' => TRUE, 'description' => 'The module name that provides the callback for this job'),
+      'mv_table'      => array('type' => 'varchar', 'length' => 128, 'not NULL' => FALSE),
+      'mv_specs'      => array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE),
+      'mv_schema'     => array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE),
+      'indexed'       => array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE),
+      'query'         => array('type' => 'text', 'size' => 'normal', 'not NULL' => TRUE),
+      'special_index' => array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE),
+      'last_update'   => array('type' => 'int', 'not NULL' => FALSE, 'description' => 'UNIX integer time'),
+      'status'        => array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE),
+      'comment'       => array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE),
+    ),
+    'indexes' => array(
+      'mview_id' => array('mview_id')
+    ),
+    'unique keys' => array(
+      'mv_table' => array('mv_table'),
+      'mv_name' => array('name'),
+    ),
+    'primary key' => array('mview_id'),
   );
+
   return $schema;
 }
-/************************************************************************
-* 
-*
-* @ingroup tripal_core
-*/
-function tripal_core_jobs_schema(){
-   $schema = array();
-   $schema['tripal_jobs'] = array(
-      'fields' => array(
-         'job_id' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
-         'uid' => array ('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'description' => 'The Drupal userid of the submitee'),
-         'job_name' => array('type' => 'varchar','length' => 255, 'not null' => TRUE),
-         'modulename' => array('type' => 'varchar','length' => 50, 'not null' => TRUE, 'description' => 'The module name that provides the callback for this job'),
-         'callback' => array('type' => 'varchar','length' => 255, 'not null' => TRUE),
-         'arguments' => array('type' => 'text', 'size' => 'normal', 'not null' => FALSE),
-         'progress' => array('type' => 'int', 'unsigned' => TRUE, 'default' => 0, 'not null' => FALSE, 'description' => 'a value from 0 to 100 indicating percent complete'),
-         'status' => array('type' => 'varchar','length' => 50, 'not null' => TRUE),
-         'submit_date' => array ('type' => 'int', 'not null' => TRUE, 'description' => 'UNIX integer submit time'),
-         'start_time' => array ('type' => 'int', 'not null' => FALSE, 'description' => 'UNIX integer start time'),
-         'end_time' => array ('type' => 'int', 'not null' => FALSE, 'description' => 'UNIX integer end time'),
-         'error_msg' => array('type' => 'text','size' => 'normal', 'not null' => FALSE),
-         'pid' => array ('type' => 'int', 'unsigned' => TRUE, 'not null' => FALSE, 'description' => 'The process id for the job'),
-         'priority' => array ('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => '0', 'description' => 'The job priority'),
-         'mlock' => array ('type' => 'int', 'unsigned' => TRUE, 'not null' => FALSE, 'description' => 'If set to 1 then all jobs for the module are held until this one finishes'),
-         'lock' => array ('type' => 'int', 'unsigned' => TRUE, 'not null' => FALSE, 'description' => 'If set to 1 then all jobs are held until this one finishes'),
-      ),
-      'indexes' => array(
-         'job_id' => array('job_id'),
-         'job_name' => array('job_name')
-      ),
-      'primary key' => array('job_id'),
-   );
-   return $schema;
+
+/**
+ * Describes the Tripal Jobs (tripal_jobs) table
+ * This table keeps track of all tripal jobs including their current status and is used
+ * by tripal_launch_jobs to determine which jobs need to be run
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_jobs_schema() {
+  $schema = array();
+  $schema['tripal_jobs'] = array(
+    'fields' => array(
+      'job_id' => array('type' => 'serial', 'unsigned' => TRUE, 'not NULL' => TRUE),
+      'uid' => array('type' => 'int', 'unsigned' => TRUE, 'not NULL' => TRUE, 'description' => 'The Drupal userid of the submitee'),
+      'job_name' => array('type' => 'varchar', 'length' => 255, 'not NULL' => TRUE),
+      'modulename' => array('type' => 'varchar', 'length' => 50, 'not NULL' => TRUE, 'description' => 'The module name that provides the callback for this job'),
+      'callback' => array('type' => 'varchar', 'length' => 255, 'not NULL' => TRUE),
+      'arguments' => array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE),
+      'progress' => array('type' => 'int', 'unsigned' => TRUE, 'default' => 0, 'not NULL' => FALSE, 'description' => 'a value from 0 to 100 indicating percent complete'),
+      'status' => array('type' => 'varchar', 'length' => 50, 'not NULL' => TRUE),
+      'submit_date' => array('type' => 'int', 'not NULL' => TRUE, 'description' => 'UNIX integer submit time'),
+      'start_time' => array('type' => 'int', 'not NULL' => FALSE, 'description' => 'UNIX integer start time'),
+      'end_time' => array('type' => 'int', 'not NULL' => FALSE, 'description' => 'UNIX integer end time'),
+      'error_msg' => array('type' => 'text', 'size' => 'normal', 'not NULL' => FALSE),
+      'pid' => array('type' => 'int', 'unsigned' => TRUE, 'not NULL' => FALSE, 'description' => 'The process id for the job'),
+      'priority' => array('type' => 'int', 'unsigned' => TRUE, 'not NULL' => TRUE, 'default' => '0', 'description' => 'The job priority'),
+      'mlock' => array('type' => 'int', 'unsigned' => TRUE, 'not NULL' => FALSE, 'description' => 'If set to 1 then all jobs for the module are held until this one finishes'),
+      'lock' => array('type' => 'int', 'unsigned' => TRUE, 'not NULL' => FALSE, 'description' => 'If set to 1 then all jobs are held until this one finishes'),
+    ),
+    'indexes' => array(
+      'job_id' => array('job_id'),
+      'job_name' => array('job_name')
+    ),
+    'primary key' => array('job_id'),
+  );
+
+  return $schema;
 }
-/************************************************************************
-* 
-*
-* @ingroup tripal_core
-*/
-function tripal_core_custom_tables_schema(){
-   $schema = array();
-   $schema['tripal_custom_tables'] = array(
-      'fields' => array(
-         'table_id' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
-         'table_name' => array ('type' => 'varchar', 'length' => 255, 'not null' => TRUE),
-         'schema' => array('type' => 'text','not null' => TRUE),
-      ),
-      'indexes' => array(
-         'table_id' => array('table_id'),
-      ),
-      'primary key' => array('table_id'),
-   );
-   return $schema;
+
+/**
+ * Describes the Tripal Custom Tables (tripal_custom_tables) table
+ * This keeps track of tables created by Tripal and stored in chado that may or may not
+ * also be materialized views.
+ *
+ * @ingroup tripal_core
+ */
+function tripal_core_custom_tables_schema() {
+  $schema = array();
+  $schema['tripal_custom_tables'] = array(
+    'fields' => array(
+      'table_id' => array('type' => 'serial', 'unsigned' => TRUE, 'not NULL' => TRUE),
+      'table_name' => array('type' => 'varchar', 'length' => 255, 'not NULL' => TRUE),
+      'schema' => array('type' => 'text', 'not NULL' => TRUE),
+    ),
+    'indexes' => array(
+      'table_id' => array('table_id'),
+    ),
+    'primary key' => array('table_id'),
+  );
+
+  return $schema;
 }
-?>

+ 213 - 193
tripal_core/tripal_core.module

@@ -5,178 +5,176 @@ require_once "mviews.php";
 require_once "chado_install.php";
 require_once "tripal_core.api.inc";
 
-
 /**
  * @defgroup tripal_modules Tripal Modules
  * @{
  * All documented functions for the various Tripal Modules
  * @}
- */
-
-/**
+ *
  * @defgroup tripal_core Core Tripal Module
  * @ingroup tripal_modules
  */
- 
+
 /**
- *
+ * Implements hook_init().
+ * Used to set the search_path, create default content and set default variables.
  *
  * @ingroup tripal_core
  */
-function tripal_core_init(){
-   // the two lines below are necessary to ensure that the search_path
-   // variable is always set.  In the case where a view needs to query the
-   // chado schema when it is local to the Drupal database.  Otherwise the
-   // search_path isn't set.  When tripal_db_set_active is called it
-   // automatically sets the serach path if chado is local to the
-   // Drupal database
-   $previous = tripal_db_set_active('chado');
-   tripal_db_set_active($previous);
+function tripal_core_init() {
+
+  // the two lines below are necessary to ensure that the search_path
+  // variable is always set.  In the case where a view needs to query the
+  // chado schema when it is local to the Drupal database.  Otherwise the
+  // search_path isn't set.  When tripal_db_set_active is called it
+  // automatically sets the serach path if chado is local to the
+  // Drupal database
+  $previous = tripal_db_set_active('chado');
+  tripal_db_set_active($previous);
 
-   // create the 'tripal' controlled volcabulary in chado but only if it doesn't already exist, and
-   // only if the chado database is present.
-   if(tripal_core_is_chado_installed()){
-      $previous_db = tripal_db_set_active('chado');  // use chado database
-      if(!db_fetch_object(db_query("SELECT * FROM {cv} WHERE name = 'tripal'"))){
-         $results = db_query("INSERT INTO {cv} (name,definition) ".
-    	                     "VALUES ('tripal','Terms used by Tripal for modules to manage data such as that stored in property tables like featureprop, analysisprop, etc')");
-      }
-      if(!db_fetch_object(db_query("SELECT * FROM {db} WHERE name = 'tripal'"))){
-         $results = db_query("INSERT INTO {db} (name,description) ".
-	                        "VALUES ('tripal','Used as a database placeholder for tripal defined objects such as tripal cvterms')");
-      }
-      tripal_db_set_active($previous_db);  // now use drupal database
-   }
+  // create the 'tripal' controlled volcabulary in chado but only if it doesn't already exist, and
+  // only if the chado database is present.
+  if (tripal_core_is_chado_installed()) {
+    $previous_db = tripal_db_set_active('chado');  // use chado database
+    if (!db_fetch_object(db_query("SELECT * FROM {cv} WHERE name = 'tripal'"))) {
+      $results = db_query("INSERT INTO {cv} (name,definition) ".
+                         "VALUES ('tripal', 'Terms used by Tripal for modules to manage data such as that stored in property tables like featureprop, analysisprop, etc')");
+    }
+    if (!db_fetch_object(db_query("SELECT * FROM {db} WHERE name = 'tripal'"))) {
+      $results = db_query("INSERT INTO {db} (name,description) ".
+                        "VALUES ('tripal', 'Used as a database placeholder for tripal defined objects such as tripal cvterms')");
+    }
+    tripal_db_set_active($previous_db);  // now use drupal database
+  }
 
-   // add some variables for all javasript to use for building URLs
-   global $base_url;
-   $theme_dir = drupal_get_path('theme', 'tripal');
-   $clean_urls  = variable_get('clean_url', 0);
-   drupal_add_js("
-      var baseurl = '$base_url';
+  // add some variables for all javasript to use for building URLs
+  global $base_url;
+  $theme_dir = drupal_get_path('theme', 'tripal');
+  $clean_urls  = variable_get('clean_url', 0);
+  drupal_add_js(
+    "var baseurl = '$base_url';
       var themedir = '$theme_dir';
-      var isClean = $clean_urls;",'inline');
+      var isClean = $clean_urls;",
+    'inline');
 
-   // make sure the date time settings are the way Tripal will insert them
-   // otherwise PostgreSQL version that may have a different datestyle setting
-   // will fail when inserting or updating a date column in a table.
-   db_query("SET DATESTYLE TO '%s'",'MDY');
+  // make sure the date time settings are the way Tripal will insert them
+  // otherwise PostgreSQL version that may have a different datestyle setting
+  // will fail when inserting or updating a date column in a table.
+  db_query("SET DATESTYLE TO '%s'", 'MDY');
 }
 
-
-
 /**
- *
+ * Implements hook_menu().
+ * Defines all menu items needed by Tripal Core
  *
  * @ingroup tripal_core
  */
 function tripal_core_menu() {
-   $items = array();
-   
-   // Triapl setting groups
-   $items['admin/tripal'] = array(
-      'title' => 'Tripal Management',
-      'description' => "Manage the behavior or Tripal and its various modules.",
-      'position' => 'right',
-      'weight' => -5,
-      'page callback' => 'system_admin_menu_block_page',
-      'access arguments' => array('administer site configuration'),
-      'file' => 'system.admin.inc',
-      'file path' => drupal_get_path('module', 'system'),
-   );
-   $items['tripal_toggle_box_menu/%/%/%'] = array(
-     'title' => t('Toggle Box'),
-     'page callback' => 'tripal_toggle_box_menu',
-     'page arguments' => array(1,2,3),
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_CALLBACK | MENU_LINKS_TO_PARENT
-   );
-   $items['admin/tripal/chado_1_11_install'] = array(
-     'title' => 'Install Chado v1.11',
-     'description' => 'Installs Chado version 1.11 inside the current Drupal database',
-     'page callback' => 'drupal_get_form',
-     'page arguments' => array('tripal_core_chado_v1_11_load_form'),
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_NORMAL_ITEM,
-   );
+  $items = array();
+
+  // Triapl setting groups
+  $items['admin/tripal'] = array(
+    'title' => 'Tripal Management',
+    'description' => "Manage the behavior or Tripal and its various modules.",
+    'position' => 'right',
+    'weight' => -5,
+    'page callback' => 'system_admin_menu_block_page',
+    'access arguments' => array('administer site configuration'),
+    'file' => 'system.admin.inc',
+    'file path' => drupal_get_path('module', 'system'),
+  );
+  $items['tripal_toggle_box_menu/%/%/%'] = array(
+    'title' => 'Toggle Box',
+    'page callback' => 'tripal_toggle_box_menu',
+    'page arguments' => array(1, 2, 3),
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_CALLBACK | MENU_LINKS_TO_PARENT
+  );
+  $items['admin/tripal/chado_1_11_install'] = array(
+    'title' => 'Install Chado v1.11',
+    'description' => 'Installs Chado version 1.11 inside the current Drupal database',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_core_chado_v1_11_load_form'),
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+
+  // Jobs Management
+  $items['admin/tripal/tripal_jobs'] = array(
+    'title' => 'Jobs',
+    'description' => 'Jobs managed by Tripal',
+    'page callback' => 'tripal_jobs_report',
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+  $items['admin/tripal/tripal_jobs/cancel/%'] = array(
+    'title' => 'Jobs',
+    'description' => 'Cancel a pending job',
+    'page callback' => 'tripal_jobs_cancel',
+    'page arguments' => array(4),
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['admin/tripal/tripal_jobs/rerun/%'] = array(
+    'title' => 'Jobs',
+    'description' => 'Re-run an existing job.',
+    'page callback' => 'tripal_jobs_rerun',
+    'page arguments' => array(4),
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['admin/tripal/tripal_jobs/view/%'] = array(
+    'title' => 'Jobs Details',
+    'description' => 'View job details.',
+    'page callback' => 'tripal_jobs_view',
+    'page arguments' => array(4),
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_CALLBACK,
+  );
+
+  // Materialized Views
+  $items['admin/tripal/mviews'] = array(
+    'title' => 'MViews',
+    'description' => 'Materialized views are used to improve speed of large or complex queries.',
+    'page callback' => 'tripal_mviews_report',
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+  $items['admin/tripal/mviews/report/%'] = array(
+    'title' => 'Materialized View',
+    'description' => 'Materialized views are used to improve speed of large or complex queries.',
+    'page callback' => 'tripal_mview_report',
+    'page arguments' => array(4),
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+  $items['admin/tripal/mviews/new'] = array(
+    'title' => 'Create MView',
+    'description' => 'Materialized views are used to improve speed of large or complex queries.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_mviews_form'),
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_CALLBACK,
+  );
+  $items['admin/tripal/mviews/edit/%'] = array(
+    'title' => 'Edit MView',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_mviews_form', 4),
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+  $items['admin/tripal/mviews/action/%/%'] = array(
+    'title' => 'Create MView',
+    'description' => 'Materialized views are used to improve speed of large or complex queries.',
+    'page callback' => 'tripal_mviews_action',
+    'page arguments' => array(4, 5, "1"),
+    'access arguments' => array('access administration pages'),
+    'type' => MENU_CALLBACK,
+  );
 
-   // Jobs Management
-   $items['admin/tripal/tripal_jobs'] = array(
-     'title' => 'Jobs',
-     'description' => 'Jobs managed by Tripal',
-     'page callback' => 'tripal_jobs_report',
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_NORMAL_ITEM,
-   );
-   $items['admin/tripal/tripal_jobs/cancel/%'] = array(
-     'title' => 'Jobs',
-     'description' => 'Cancel a pending job',
-     'page callback' => 'tripal_jobs_cancel',
-     'page arguments' => array(4),
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_CALLBACK,
-   );
-   $items['admin/tripal/tripal_jobs/rerun/%'] = array(
-     'title' => 'Jobs',
-     'description' => 'Re-run an existing job.',
-     'page callback' => 'tripal_jobs_rerun',
-     'page arguments' => array(4),
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_CALLBACK,
-   );
-   $items['admin/tripal/tripal_jobs/view/%'] = array(
-     'title' => 'Jobs Details',
-     'description' => 'View job details.',
-     'page callback' => 'tripal_jobs_view',
-     'page arguments' => array(4),
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_CALLBACK,
-   );
- 
-   
-   // Materialized Views 
-   $items['admin/tripal/mviews'] = array(
-     'title' => 'MViews',
-     'description' => 'Materialized views are used to improve speed of large or complex queries.',
-     'page callback' => 'tripal_mviews_report',
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_NORMAL_ITEM,
-   );
-   $items['admin/tripal/mviews/report/%'] = array(
-     'title' => 'Materialized View',
-     'description' => 'Materialized views are used to improve speed of large or complex queries.',
-     'page callback' => 'tripal_mview_report',
-     'page arguments' => array(4),
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_NORMAL_ITEM,
-   );
-   $items['admin/tripal/mviews/new'] = array(
-     'title' => 'Create MView',
-     'description' => 'Materialized views are used to improve speed of large or complex queries.',
-     'page callback' => 'drupal_get_form',
-     'page arguments' => array('tripal_mviews_form'),
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_CALLBACK,
-   );
-   $items['admin/tripal/mviews/edit/%'] = array(
-     'title' => 'Edit MView',
-     'page callback' => 'drupal_get_form',
-     'page arguments' => array('tripal_mviews_form',4),
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_NORMAL_ITEM,
-   );
-   $items['admin/tripal/mviews/action/%/%'] = array(
-     'title' => 'Create MView',
-     'description' => 'Materialized views are used to improve speed of large or complex queries.',
-     'page callback' => 'tripal_mviews_action',
-     'page arguments' => array(4,5,"1"),
-     'access arguments' => array('access administration pages'),
-     'type' => MENU_CALLBACK,
-   );
   return $items;
 }
 
-
 /**
  *  Set the permission types that the chado module uses.  Essentially we
  *  want permissionis that protect creation, editing and deleting of chado
@@ -184,75 +182,97 @@ function tripal_core_menu() {
  *
  * @ingroup tripal_core
  */
-function tripal_core_perm(){
-   return array(
-   );
+function tripal_core_perm() {
+  return array();
 }
+
 /**
- *
- *
- * @param $dbname
- *   The name of the database to switch to as indicated in settings.php
- *   Should be either default or chado
+ * Check whether chado is installed (either in the same or a different database)
  *
  * @return
- *   The name of the previously set database
+ *   TRUE/FALSE depending upon whether chado is installed.
  *
  * @ingroup tripal_chado_api
  */
-function tripal_core_is_chado_installed(){
-   global $db_url, $db_type;
+function tripal_core_is_chado_installed() {
+  global $db_url, $db_type;
 
-   // first check if chado is in the db_url of the
-   // settings.php file
-   if(is_array($db_url)){
-      if(isset($db_url['chado'])){
-         return true;
-      }
-   }
-   // check to make sure the chado schema exists
-   $sql = "select nspname from pg_catalog.pg_namespace where nspname = 'chado'";
-   if(db_fetch_object(db_query($sql))){
-      return true;
-   }
-   return false;
+  // first check if chado is in the db_url of the
+  // settings.php file
+  if (is_array($db_url)) {
+    if (isset($db_url['chado'])) {
+      return TRUE;
+    }
+  }
+
+  // check to make sure the chado schema exists
+  return tripal_core_chado_schema_exists();
 }
 
 
 /**
+ * Implements hook_theme().
+ * Registers template files/functions used by this module.
  *
  * @ingroup tripal_core
  */
-function tripal_core_theme () {
-   return array(
-      'tripal_core_job_view' => array (
-         'arguments' => array('job_id'=> null),
-         'template' => 'tripal_core_job_view',
-      ),
-   );
+function tripal_core_theme() {
+  return array(
+    'tripal_core_job_view' => array(
+       'arguments' => array('job_id' => NULL),
+       'template' => 'tripal_core_job_view',
+    ),
+  );
 }
+
 /**
+ * Implements hook_job_describe_args().
+ * Describes the arguements for the tripal_update_mview job to allow for greater
+ * readability in the jobs details pages.
+ *
+ * @param $callback
+ *   The callback of the current tripal job (this is the function that will be executed
+ *   when tripal_launch_jobs.php is run.
+ * @param $args
+ *   An array of arguments passed in when the job was registered.
+ *
+ * @return
+ *   A more readable $args array
  *
  * @ingroup tripal_core
  */
-function tripal_core_job_describe_args($callback,$args){
-   $new_args = array();
-   if($callback == 'tripal_update_mview'){
-      // get this mview details
-      $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d ";
-      $mview = db_fetch_object(db_query($sql,$args[0]));
-      $new_args['View Name'] = $mview->name;
-   }
-   return $new_args;
+function tripal_core_job_describe_args($callback, $args) {
+  $new_args = array();
+  if ($callback == 'tripal_update_mview') {
+    // get this mview details
+    $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d ";
+    $mview = db_fetch_object(db_query($sql, $args[0]));
+    $new_args['View Name'] = $mview->name;
+  }
+
+  return $new_args;
 }
 
-// this is just a wrapper for backwards compatibility with a naming mistake.
-// it can go away in the future as it only is useful for jobs created by v0.3b
-function tripal_core_load_gff3($gff_file, $organism_id,$analysis_id,$add_only =0,
-   $update = 0, $refresh = 0, $remove = 0, $job = NULL)
-{
-   tripal_feature_load_gff3($gff_file, $organism_id,$analysis_id,$add_only,
-      $update, $refresh, $remove, $job);
+/**
+ * this is just a wrapper for backwards compatibility with a naming mistake.
+ * it can go away in the future as it only is useful for jobs created by v0.3b
+ *
+ * @todo remove this function
+ */
+function tripal_core_load_gff3($gff_file, $organism_id, $analysis_id, $add_only = 0,
+  $update = 0, $refresh = 0, $remove = 0, $job = NULL) {
+
+  tripal_feature_load_gff3($gff_file, $organism_id, $analysis_id, $add_only,
+    $update, $refresh, $remove, $job);
 }
- 
 
+/**
+ * Implements hook_coder_ignore().
+ * Defines the path to the file (tripal_core.coder_ignores.txt) where ignore rules for coder are stored
+ */
+function tripal_core_coder_ignore() {
+  return array(
+    'path' => drupal_get_path('module', 'tripal_core'),
+    'line prefix' => drupal_get_path('module', 'tripal_core'),
+  );
+}

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 183 - 185
tripal_core/tripal_core.schema.api.inc


+ 16 - 12
tripal_core/tripal_core_job_view.tpl.php

@@ -1,21 +1,27 @@
 <?php
+
+/**
+ * @file
+ * This is a template file to show how the details of an individual job should be displayed
+ */
+
 $job = $variables['job'];
 
 $cancel_link = '';
 $return_link = url("admin/tripal/tripal_jobs/");
-if($job->start_time == 0 and $job->end_time == 0){
-   $cancel_link = url("admin/tripal/tripal_jobs/cancel/".$job->job_id);
+if ($job->start_time == 0 and $job->end_time == 0) {
+  $cancel_link = url("admin/tripal/tripal_jobs/cancel/" . $job->job_id);
 }
-$rerun_link = url("admin/tripal/tripal_jobs/rerun/".$job->job_id);
- 
+$rerun_link = url("admin/tripal/tripal_jobs/rerun/" . $job->job_id);
+
 ?>
 
 <div id="tripal_core-job_view-box" class="tripal_core-info-box tripal-info-box">
   <div class="tripal_core-info-box-title tripal-info-box-title">Details for Job <?php print $job->job_id?></div>
   <div class="tripal_core-info-box-desc tripal-info-box-desc"></div>
-   <a href="<?php print $return_link?>">Return to jobs list</a> | 
-   <a href="<?php print $rerun_link?>">Re-run this job</a> | 
-   <a href="<?php print $cancel_link?>">Cancel this Job</a><br>
+   <a href="<?php print $return_link?>">Return to jobs list</a> |
+   <a href="<?php print $rerun_link?>">Re-run this job</a> |
+   <a href="<?php print $cancel_link?>">Cancel this Job</a><br />
    <table id="tripal_core-job_view-table" class="tripal_core-table tripal-table tripal-table-vert">
       <tr class="tripal_core-table-odd-row tripal-table-even-row tripal-table-first-row">
          <th>Job Description</th>
@@ -33,9 +39,9 @@ $rerun_link = url("admin/tripal/tripal_jobs/rerun/".$job->job_id);
          <th>Arguments</th>
          <td>
            <table>
-           <?php foreach($job->arguments as $key => $value){
-              print "<tr><td>$key</td><td>$value</td></tr>";
-           } ?>
+          <?php foreach ($job->arguments as $key => $value) {
+            print "<tr><td>$key</td><td>$value</td></tr>";
+          } ?>
            </table>
          </td>
       </tr>
@@ -77,5 +83,3 @@ $rerun_link = url("admin/tripal/tripal_jobs/rerun/".$job->job_id);
       </tr>
    </table>
 </div>
-
-

+ 41 - 44
tripal_core/tripal_launch_jobs.php

@@ -1,57 +1,54 @@
 <?php
-//
-// Copyright 2009 Clemson University
-//
 
-/* 
-
-This script must be run at the base directory level of the drupal installation 
-in order to pick up all necessary dependencies 
-
-*/
+/**
+ * @file
+ * This script will launch any waiting tripal jobs in succession.
+ *
+ * This script must be run at the base directory level of the drupal installation
+ * in order to pick up all necessary dependencies
+ */
 
-  $stdout = fopen('php://stdout', 'w');
+$stdout = fopen('php://stdout', 'w');
 
-  // we require one command-line argument
-  if(sizeof($argv) < 2){
-     print_usage($stdout);
-     exit;
-  }
+// we require one command-line argument
+if (sizeof($argv) < 2) {
+  print_usage($stdout);
+  exit;
+}
 
-  $drupal_base_url = parse_url('http://www.example.com');
-  $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
+$drupal_base_url = parse_url('http://www.example.com');
+$_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
 //  $_SERVER['PHP_SELF'] = $drupal_base_url['path'].'/index.php';
-  $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
-  $_SERVER['REMOTE_ADDR'] = NULL;
-  $_SERVER['REQUEST_METHOD'] = NULL;
-
-  require_once 'includes/bootstrap.inc';
-  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
-
-  fwrite($stdout, "Tripal Job Launcher\n");
-  fwrite($stdout, "-------------------\n");
+$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
+$_SERVER['REMOTE_ADDR'] = NULL;
+$_SERVER['REQUEST_METHOD'] = NULL;
+
+require_once 'includes/bootstrap.inc';
+drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
+
+fwrite($stdout, "Tripal Job Launcher\n");
+fwrite($stdout, "-------------------\n");
+
+// check to make sure the username is valid
+$username = $argv[1];
+$do_parallel = $argv[2];
+if (!db_fetch_object(db_query("SELECT * FROM {users} WHERE name = '%s'", $username))) {
+  fwrite($stdout, "'$username' is not a valid Drupal username. exiting...\n");
+  exit;
+}
 
-  // check to make sure the username is valid
-  $username = $argv[1];
-  $do_parallel = $argv[2];
-  if(!db_fetch_object(db_query("SELECT * FROM {users} WHERE name = '$username'"))){
-     fwrite($stdout, "'$username' is not a valid Drupal username. exiting...\n");
-     exit;
-  }
-  global $user;
-  $user = user_load(array('name' => $username));
+global $user;
+$user = user_load(array('name' => $username));
 
-  tripal_jobs_launch($do_parallel);
+tripal_jobs_launch($do_parallel);
 
 /**
- *
+ * Print out the usage instructions if they are not followed correctly
  *
  * @ingroup tripal_core
  */
-function print_usage ($stdout){
-  fwrite($stdout,"Usage:\n");
-  fwrite($stdout,"  php ./sites/all/modules/tripal_core/tripal_launch_jobs <username> \n\n");
-  fwrite($stdout,"    where <username> is a Drupal user name\n\n");
-}
-
-?>
+function print_usage($stdout) {
+  fwrite($stdout, "Usage:\n");
+  fwrite($stdout, "  php ./sites/all/modules/tripal_core/tripal_launch_jobs <username> \n\n");
+  fwrite($stdout, "    where <username> is a Drupal user name\n\n");
+}

+ 48 - 43
tripal_core/tripal_launch_jobs_multi.php

@@ -1,22 +1,25 @@
 <?php
 
-/* This script can be used to launch jobs on a multi-site Drupal installation*/
+/**
+ * @file
+ * This script can be used to launch jobs on a multi-site Drupal installation
+ */
 
 include_once './includes/bootstrap.inc';
 
-fwrite(STDOUT,"Running Tripal Job Launcher\n");
+fwrite(STDOUT, "Running Tripal Job Launcher\n");
 
-/***********
-* SETTINGS
-**********/
+/**
+ * SETTINGS
+ */
 
 //the location of the 'sites' directory relative to this script.
-$sitesDir = 'sites';
+$sites_dir = 'sites';
 $debug=0;
-/***********
-* END SETTINGS
-**********/
 
+/**
+ * END SETTINGS
+ */
 
 //error_reporting(E_ALL);
 
@@ -26,25 +29,26 @@ include ("Console/Getopt.php");
 $cg = new Console_Getopt();
 
 /* define list of allowed options - p = h:sitename, u:username  */
-$allowedShortOptions = "h:u:";
+$allowed_short_options = "h:u:";
 
 // read the command line
 $args = $cg->readPHPArgv();
 
 // get the options
-$ret = $cg->getopt($args, $allowedShortOptions);
+$ret = $cg->getopt($args, $allowed_short_options);
 
 // check for errors and die with an error message if there was a problem
 if (PEAR::isError($ret)) {
-    die ("Error in command line: " . $ret->getMessage() . "\n");
+    die("Error in command line: " . $ret->getMessage() . "\n");
 }
 
-ini_set('include_path',ini_get('include_path'). PATH_SEPARATOR . './scripts');
+ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . './scripts');
 
-/* This doesn't work in every case: getopt function is not always available
-$options = getopt("h:r:");
-var_dump($options);
-*/
+/*
+ * This doesn't work in every case: getopt function is not always available
+  $options = getopt("h:r:");
+  var_dump($options);
+ */
 
 $hostname = "";
 $username = "";
@@ -62,45 +66,46 @@ if (sizeof($opts) > 0) {
                 $username = $opt[1];
                 break;
             default:
-                fwrite(STDOUT,'Usage: \n');
-                fwrite(STDOUT,'- h hostname\n');
-                fwrite(STDOUT." -u username\n");
+                fwrite(STDOUT, 'Usage: \n');
+                fwrite(STDOUT, '- h hostname\n');
+                fwrite(STDOUT, " -u username\n");
                 break;
 
         }
     }
-}else{
-  fwrite(STDOUT,"Usage: \n");
-  fwrite(STDOUT," -h hostname\n");
-  fwrite(STDOUT," -u username\n"); 
-  
+}
+else {
+  fwrite(STDOUT, "Usage: \n");
+  fwrite(STDOUT, " -h hostname\n");
+  fwrite(STDOUT, " -u username\n");
+
 }
 
 runjob($hostname, $username);
 
 /**
- *
+ * Runs tripal_launch_jobs() as the specified user
  *
  * @ingroup tripal_core
  */
 function runjob($sitename, $username) {
+  global $user;
 
-    $_SERVER['SCRIPT_NAME'] = '/sites/all/modules/tripal_jobs/tripal_launch_jobs_multi.php';
-    $_SERVER['SCRIPT_FILENAME'] = '/sites/all/modules/tripal_jobs/tripal_launch_jobs_multi.php';
-    $_SERVER['HTTP_HOST'] = $sitename;
-    $_SERVER['REMOTE_ADDR'] = 'localhost';
-    $_SERVER['REQUEST_METHOD'] = 'GET';
-
-    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
-        
-    if(!db_fetch_object(db_query("SELECT * FROM {users} WHERE name = '$username'"))){
-     fwrite(STDOUT, "'$username' is not a valid Drupal username. exiting...\n");
-     exit;
-    }
-    global $user;
-    $user = $username;
-    $user = user_load(array('name' => $username));
+  $_SERVER['SCRIPT_NAME'] = '/sites/all/modules/tripal_jobs/tripal_launch_jobs_multi.php';
+  $_SERVER['SCRIPT_FILENAME'] = '/sites/all/modules/tripal_jobs/tripal_launch_jobs_multi.php';
+  $_SERVER['HTTP_HOST'] = $sitename;
+  $_SERVER['REMOTE_ADDR'] = 'localhost';
+  $_SERVER['REQUEST_METHOD'] = 'GET';
+
+  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
+
+  if (!db_fetch_object(db_query("SELECT * FROM {users} WHERE name = '%s'", $username))) {
+    fwrite(STDOUT, "'$username' is not a valid Drupal username. exiting...\n");
+    exit;
+  }
+
+  $user = $username;
+  $user = user_load(array('name' => $username));
 
-    tripal_jobs_launch();
+  tripal_jobs_launch();
 }
-?>

+ 111 - 99
tripal_cv/charts.php

@@ -1,11 +1,15 @@
 <?php
 
+/**
+ * @file
+ * Tripal API for generating a Google Chart of count data
+ */
 
 /**
  * Generates JSON used for generating a Google chart of count data associated
  * with a controlled vocabulary.  An example would be features assigned to
- * Gene Ontology terms. 
- * 
+ * Gene Ontology terms.
+ *
  * To generate a chart, the progammer must first create a materialized view that
  * will generate count data for a given controlled vocabulary.  For example, the Tripal
  * Analysis GO creates a materialized view for counting Gene Ontology assignments
@@ -18,23 +22,23 @@
  *  tripal_[module_name]_cv_chart_[unique id]
  *
  * where [module_name] is the name of the tripal module (e.g. tripal_analyisis_go)
- * and [unique id] is some unique identifier that the contolling module 
+ * and [unique id] is some unique identifier that the contolling module
  * recognizes. This string is the $chart_id variable passed as the first argument
- * to the function.  For example, the Tripal GO Analysis module generates 
+ * to the function.  For example, the Tripal GO Analysis module generates
  * chart ids of the form:
- * 
+ *
  *  tripal_analysis_go_cv_chart_10_2_bp
- * 
+ *
  * In this case the module that will manage this chart is identified as 'tripal_analysis_go' and within
  * the [unique id] portion contains the
- * organism_id (e.g. 10), analysis_id (e.g. 2) and chart type (bp = biological process). 
+ * organism_id (e.g. 10), analysis_id (e.g. 2) and chart type (bp = biological process).
  *
  * Second, the programmer must then define a hook in the controlling module for setting
  * some options used to build the chart.  The hook has the form:  hook_cv_chart($chart_id).
  * This hook should accept the full $chart_id as the single parameter.  For the Tripal
- * Analysis GO module the hook is named:  tripal_analysis_go_cv_chart.  
+ * Analysis GO module the hook is named:  tripal_analysis_go_cv_chart.
  *
- * The array returned by this hook must have the following fields:  
+ * The array returned by this hook must have the following fields:
  *  - count_mview
  *      the name of the materialized view that contains the count data
  *      this materialized view must have at least two columns, one with the cvterm_id
@@ -53,37 +57,37 @@
  *  - type
  *      the type of chart to create (see Google Charts documenation). Leave
  *      blank for a pie chart.
- *  - size 
- *      the dimensions of the chart in pixels (see Google Charts documenations 
+ *  - size
+ *      the dimensions of the chart in pixels (see Google Charts documenations
  *      for exact size limitations).
  *
  * Example from the tripal_analysis_go module:
  * @code
- *  function tripal_analysis_go_cv_chart($chart_id){
- *  
+ *  function tripal_analysis_go_cv_chart($chart_id) {
+ *
  *    // The CV module will create the JSON array necessary for buillding a
  *    // pie chart using jgChart and Google Charts.  We have to pass to it
- *    // a table that contains count information, tell it which column 
+ *    // a table that contains count information, tell it which column
  *    // contains the cvterm_id and provide a filter for getting the
  *    // results we want from the table.
  *    $organism_id = preg_replace("/^tripal_analysis_go_cv_chart_(\d+)-(\d+)_(bp|cc|mf)$/","$1",$chart_id);
  *    $analysis_id = preg_replace("/^tripal_analysis_go_cv_chart_(\d+)-(\d+)_(bp|cc|mf)$/","$2",$chart_id);
  *    $type        = preg_replace("/^tripal_analysis_go_cv_chart_(\d+)-(\d+)_(bp|cc|mf)$/","$3",$chart_id);
- *  
+ *
  *    $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  
- *   
- *    if(strcmp($type,'mf')==0){
+ *    tripal_db_set_active($previous_db);  // now use drupal database
+ *
+ *    if (strcmp($type,'mf')==0) {
  *       $class = 'molecular_function';
  *       $title = "Number of Molecular Function Terms From $analysis->name Analysis";
  *    }
- *    if(strcmp($type,'cc')==0){
+ *    if (strcmp($type,'cc')==0) {
  *       $class = 'cellular_component';
  *       $title = "Number of Cellular Component Terms From $analysis->name Analysis";
  *    }
- *    if(strcmp($type,'bp')==0){
+ *    if (strcmp($type,'bp')==0) {
  *       $class = 'biological_process';
  *       $title = "Number of Biological Process Terms From $analysis->name Analysis";
  *    }
@@ -92,14 +96,14 @@
  *       cvterm_id_column => 'cvterm_id',
  *       count_column     => 'feature_count',
  *       filter           => "
- *          CNT.organism_id = $organism_id AND 
- *          CNT.analysis_id = $analysis_id AND 
- *          CNT.cvterm_id IN ( 
- *            SELECT CVTR.subject_id 
- *            FROM {CVTerm_relationship} CVTR 
+ *          CNT.organism_id = $organism_id AND
+ *          CNT.analysis_id = $analysis_id AND
+ *          CNT.cvterm_id IN (
+ *            SELECT CVTR.subject_id
+ *            FROM {CVTerm_relationship} CVTR
  *              INNER JOIN CVTerm CVT on CVTR.object_id = CVT.cvterm_id
  *              INNER JOIN CV on CVT.cv_id = CV.cv_id
- *            WHERE CVT.name = '$class' AND  
+ *            WHERE CVT.name = '$class' AND
  *                   CV.name = '$class'
  *          )
  *       ",
@@ -123,19 +127,26 @@
  *
  * @ingroup tripal_cv
  */
-function tripal_cv_chart($chart_id){
-  // parse out the tripal module name from the chart_id to find out 
+function tripal_cv_chart($chart_id) {
+  // parse out the tripal module name from the chart_id to find out
   // which Tripal "hook" to call:
-  $tripal_mod = preg_replace("/^(tripal_.+?)_cv_chart_(.+)$/","$1",$chart_id);
+  $tripal_mod = preg_replace("/^(tripal_.+?)_cv_chart_(.+)$/", "$1", $chart_id);
   $callback = $tripal_mod . "_cv_chart";
 
   // now call the function in the module responsible for the chart to fill out
   // an options array needed by the tripal_cv_count_chart call below.
-  $opt = call_user_func_array($callback,array($chart_id));
+  $opt = call_user_func_array($callback, array($chart_id));
 
   // build the JSON array to return to the javascript caller
-  $json_arr = tripal_cv_count_chart($opt[count_mview],$opt[cvterm_id_column],
-     $opt[count_column],$opt[filter],$opt[title], $opt[type],$opt[size]);
+  $json_arr = tripal_cv_count_chart(
+    $opt['count_mview'],
+    $opt['cvterm_id_column'],
+    $opt['count_column'],
+    $opt['filter'],
+    $opt['title'],
+    $opt['type'],
+    $opt['size']
+  );
   $json_arr[] = $chart_id;  // add the chart_id back into the json array
 
   return drupal_json($json_arr);
@@ -154,7 +165,7 @@ function tripal_cv_chart($chart_id){
   *   two columns, one with the cvterm_id for each term, and a second
   *   column with the count (i.e. features assigned the term).
   * @param $fk_column
-  *   This is the name of the column in the $cnt_table that holds the 
+  *   This is the name of the column in the $cnt_table that holds the
   *   cvterm_id for each term.
   * @param $cnt_column
   *   The name of the column in the $cnt_table containing the counts
@@ -170,80 +181,81 @@ function tripal_cv_chart($chart_id){
   *   The size in pixels of the chart to be rendered. Default is 300x75. The
   *   size of the chart is constrained by Google charts.  See the Google
   *   chart documentation for exact limitations.
-  *  
-  * @return 
+  *
+  * @return
   *   An array that has the settings needed for Google Charts to creat the chart.
   *
   * @ingroup tripal_cv
   */
 function tripal_cv_count_chart($cnt_table, $fk_column,
-   $cnt_column, $filter = null, $title = '', $type = 'p3', $size='300x75') {
+  $cnt_column, $filter = NULL, $title = '', $type = 'p3', $size='300x75') {
+
+  if (!$type) {
+    $type = 'p3';
+  }
+
+  if (!$size) {
+    $size = '300x75';
+  }
+
+  if (!$filter) {
+    $filter = '(1=1)';
+  }
 
-   if(!$type){
-      $type = 'p3';
-   }
+  $is_pie = 0;
+  if (strcmp($type, 'p') == 0 or strcmp($type, 'p3') == 0) {
+    $is_pie = 1;
+  }
+  $sql = "
+    SELECT CVT.name, CVT.cvterm_id, CNT.$cnt_column as num_items
+    FROM {$cnt_table} CNT
+     INNER JOIN {cvterm} CVT on CNT.$fk_column = CVT.cvterm_id
+    WHERE $filter
+  ";
 
-   if(!$size){
-     $size = '300x75';
-   }
+  $features = array();
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $results = db_query($sql);
+  tripal_db_set_active($previous_db);  // now use drupal database
+  $data = array();
+  $axis = array();
+  $legend = array();
+  $total = 0;
+  $max = 0;
+  $i = 1;
+  while ($term = db_fetch_object($results)) {
 
-   if(!$filter){
-      $filter = '(1=1)'; 
-   }
+    if ($is_pie) {
+      $axis[] = "$term->name (" . number_format($term->num_items) . ")";
+      $data[] = array($term->num_items, 0, 0);
+    }
+    else {
+      $axis[] = "$term->name (" . number_format($term->num_items) . ")";
+      $data[] = array($term->num_items);
+      //$legend[] = "$term->name (" . number_format($term->num_items) . ")";
+    }
+    if ($term->num_items > $max) {
+      $max = $term->num_items;
+    }
+    $total += $term->num_items;
+    $i++;
+  }
+  // convert numerical values into percentages
+  foreach ($data as &$set) {
+    $set[0] = ($set[0] / $total) * 100;
+  }
+  $opt[] = array(
+    data => $data,
+    axis_labels => $axis,
+    legend => $legend,
+    size => $size,
+    type => $type,
 
-   $isPie = 0;
-   if(strcmp($type,'p')==0 or strcmp($type,'p3')==0){
-      $isPie = 1;
-   }
-   $sql = "
-      SELECT CVT.name, CVT.cvterm_id, CNT.$cnt_column as num_items
-      FROM {$cnt_table} CNT 
-       INNER JOIN {cvterm} CVT on CNT.$fk_column = CVT.cvterm_id 
-      WHERE $filter
-   ";    
+    bar_width     => 10,
+    bar_spacing   => 0,
+    title         => $title
+  );
+  //   $opt[] = $sql;
 
-   $features = array();
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $results = db_query($sql);
-   tripal_db_set_active($previous_db);  // now use drupal database
-   $data = array();
-   $axis = array();
-   $legend = array();
-   $total = 0;
-   $max = 0;
-   $i = 1;
-   while($term = db_fetch_object($results)){
-      
-      if($isPie){
-         $axis[] = "$term->name (".number_format($term->num_items).")";
-         $data[] = array($term->num_items,0,0);
-      } else {
-         $axis[] = "$term->name (".number_format($term->num_items).")";
-         $data[] = array($term->num_items);
-    //     $legend[] = "$term->name (".number_format($term->num_items).")";
-      }
-      if($term->num_items > $max){
-         $max = $term->num_items;
-      }
-      $total += $term->num_items;
-      $i++;
-   }
-   // convert numerical values into percentages
-   foreach($data as &$set){
-      $set[0] = ($set[0] / $total) * 100;
-   }
-   $opt[] = array(
-      data => $data,
-      axis_labels => $axis, 
-      legend => $legend,
-      size => $size, 
-      type => $type,
- 
-      bar_width     => 10, 
-      bar_spacing   => 0, 
-      title         => $title
-   );
-//   $opt[] = $sql;
-   
-   return $opt;
+  return $opt;
 }

+ 843 - 792
tripal_cv/obo_loader.php

@@ -1,866 +1,917 @@
 <?php
 
-/** 
+/**
+ * @file
+ * Tripal Ontology Loader
+ *
  * @defgroup tripal_obo_loader Tripal Ontology Loader
  * @ingroup tripal_cv
  */
- 
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_load_obo_v1_2_id($obo_id,$jobid = NULL){
-
-   // get the OBO reference
-   $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = %d";
-   $obo = db_fetch_object(db_query($sql,$obo_id));
-
-   // if the reference is for a remote URL then run the URL processing function
-   if(preg_match("/^http:\/\//",$obo->path) or preg_match("/^ftp:\/\//",$obo->path)){
-      tripal_cv_load_obo_v1_2_url($obo->name,$obo->path,$jobid,0);
-   } 
-   // if the reference is for a local file then run the file processing function
-   else {
-      // check to see if the file is located local to Drupal
-      $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo->path; 
-      if(file_exists($dfile)){
-         tripal_cv_load_obo_v1_2_file($obo->name,$dfile,$jobid,0);
-      } 
-      // if not local to Drupal, the file must be someplace else, just use
-      // the full path provided
-      else{
-         if(file_exists($obo->path)){
-            tripal_cv_load_obo_v1_2_file($obo->name,$obo->path,$jobid,0);
-         } else {
-            print "ERROR: counld not find OBO file: '$obo->path'\n";
-         }
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_load_obo_v1_2_id($obo_id, $jobid = NULL) {
+
+  // get the OBO reference
+  $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = %d";
+  $obo = db_fetch_object(db_query($sql, $obo_id));
+
+  // if the reference is for a remote URL then run the URL processing function
+  if (preg_match("/^http:\/\//", $obo->path) or preg_match("/^ftp:\/\//", $obo->path)) {
+    tripal_cv_load_obo_v1_2_url($obo->name, $obo->path, $jobid, 0);
+  }
+  // if the reference is for a local file then run the file processing function
+  else {
+    // check to see if the file is located local to Drupal
+    $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo->path;
+    if (file_exists($dfile)) {
+      tripal_cv_load_obo_v1_2_file($obo->name, $dfile , $jobid, 0);
+    }
+    // if not local to Drupal, the file must be someplace else, just use
+    // the full path provided
+    else {
+      if (file_exists($obo->path)) {
+        tripal_cv_load_obo_v1_2_file($obo->name, $obo->path, $jobid, 0);
       }
-   }  
+      else {
+        print "ERROR: counld not find OBO file: '$obo->path'\n";
+      }
+    }
+  }
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_load_obo_v1_2_file($obo_name,$file,$jobid = NULL,$is_new = 1){
-   $newcvs = array();
-
-   tripal_cv_load_obo_v1_2($file,$jobid,$newcvs);
-   if($is_new){
-      tripal_cv_load_obo_add_ref($obo_name,$file);
-   }
-   // update the cvtermpath table 
-   tripal_cv_load_update_cvtermpath($newcvs,$jobid);
-   print "Ontology Sucessfully loaded!\n";  
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_load_obo_v1_2_file($obo_name, $file, $jobid = NULL, $is_new = TRUE) {
+  $newcvs = array();
+
+  tripal_cv_load_obo_v1_2($file, $jobid, $newcvs);
+  if ($is_new) {
+    tripal_cv_load_obo_add_ref($obo_name, $file);
+  }
+
+  // update the cvtermpath table
+  tripal_cv_load_update_cvtermpath($newcvs, $jobid);
+  print "Ontology Sucessfully loaded!\n";
+
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_load_obo_v1_2_url($obo_name,$url,$jobid = NULL,$is_new = 1){
-
-   $newcvs = array();
-
-   // first download the OBO
-   $temp = tempnam(sys_get_temp_dir(),'obo_');
-   print "Downloading URL $url, saving to $temp\n";
-   $url_fh = fopen($url,"r");
-   $obo_fh = fopen($temp,"w");
-   if(!$url_fh){
-      tripal_cv_obo_quiterror("Unable to download the remote OBO file at $url. Could a firewall be blocking outgoing connections? ".
-            " if you are unable to download the file you may manually downlod the OBO file and use the web interface to ".
-            " specify the location of the file on your server.");
-      
-   }
-   while(!feof($url_fh)){
-      fwrite($obo_fh,fread($url_fh,255),255);
-   }
-   fclose($url_fh);
-   fclose($obo_fh);
-
-   // second, parse the OBO
-   tripal_cv_load_obo_v1_2($temp,$jobid,$newcvs);
-
-   // now remove the temp file
-   unlink($temp);
-
-   if($is_new){
-      tripal_cv_load_obo_add_ref($obo_name,$url);
-   }
-
-   // update the cvtermpath table 
-   tripal_cv_load_update_cvtermpath($newcvs,$jobid);
-
-   print "Ontology Sucessfully loaded!\n";
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_load_obo_v1_2_url($obo_name, $url, $jobid = NULL, $is_new = TRUE) {
+
+  $newcvs = array();
+
+  // first download the OBO
+  $temp = tempnam(sys_get_temp_dir(), 'obo_');
+  print "Downloading URL $url, saving to $temp\n";
+  $url_fh = fopen($url, "r");
+  $obo_fh = fopen($temp, "w");
+  if (!$url_fh) {
+    tripal_cv_obo_quiterror("Unable to download the remote OBO file at $url. Could a firewall be blocking outgoing connections? ".
+          " if you are unable to download the file you may manually downlod the OBO file and use the web interface to ".
+          " specify the location of the file on your server.");
+
+  }
+  while (!feof($url_fh)) {
+    fwrite($obo_fh, fread($url_fh, 255), 255);
+  }
+  fclose($url_fh);
+  fclose($obo_fh);
+
+  // second, parse the OBO
+  tripal_cv_load_obo_v1_2($temp, $jobid, $newcvs);
+
+  // now remove the temp file
+  unlink($temp);
+
+  if ($is_new) {
+    tripal_cv_load_obo_add_ref($obo_name, $url);
+  }
+
+  // update the cvtermpath table
+  tripal_cv_load_update_cvtermpath($newcvs, $jobid);
+
+  print "Ontology Sucessfully loaded!\n";
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_load_update_cvtermpath($newcvs,$jobid){
-
-   print "\nUpdating cvtermpath table.  This may take a while...\n";
-   foreach($newcvs as $namespace => $cvid){
-      tripal_cv_update_cvtermpath($cvid, $jobid);
-   }
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_load_update_cvtermpath($newcvs, $jobid) {
+
+  print "\nUpdating cvtermpath table.  This may take a while...\n";
+  foreach ($newcvs as $namespace => $cvid) {
+    tripal_cv_update_cvtermpath($cvid, $jobid);
+  }
 }
+
 /**
-*
-*/
-function tripal_cv_load_obo_add_ref($name,$path){
-   $isql = "INSERT INTO tripal_cv_obo (name,path) VALUES ('%s','%s')";
-   db_query($isql,$name,$path);
+ *
+ */
+function tripal_cv_load_obo_add_ref($name, $path) {
+  $isql = "INSERT INTO {tripal_cv_obo} (name,path) VALUES ('%s','%s')";
+  db_query($isql, $name, $path);
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_load_obo_v1_2($file,$jobid = NULL,&$newcvs) {
-
-   global $previous_db;
-
-   $header = array();
-   $obo = array();
-   
-   print "Opening File $file\n";
-
-   // set the search path
-   $previous_db = tripal_db_set_active('chado');
-
-   // make sure we have an 'internal' and a '_global' database
-   if(!tripal_cv_obo_add_db('internal')){
-      tripal_cv_obo_quiterror("Cannot add 'internal' database");
-   }
-   if(!tripal_cv_obo_add_db('_global')){
-      tripal_cv_obo_quiterror("Cannot add '_global' database");
-   }
-
-   // parse the obo file
-   tripal_cv_obo_parse($file,$obo,$header);
-
-   // add the CV for this ontology to the database
-   $defaultcv = tripal_cv_obo_add_cv($header['default-namespace'][0],'');
-   if(!$defaultcv){
-      tripal_cv_obo_quiterror('Cannot add namespace ' . $header['default-namespace'][0]);
-   }  
-   $newcvs[$header['default-namespace'][0]] = $defaultcv->cv_id;
-
-   // add any typedefs to the vocabulary first
-   $typedefs = $obo['Typedef'];
-   foreach($typedefs as $typedef){
-      tripal_cv_obo_process_term($typedef,$defaultcv,$obo,1,$newcvs);  
-   }
-
-   // next add terms to the vocabulary
-   $terms = $obo['Term'];
-   if(!tripal_cv_obo_process_terms($terms,$defaultcv,$obo,$jobid,$newcvs)){
-      tripal_cv_obo_quiterror('Cannot add terms from this ontology');
-   }
-   return tripal_cv_obo_loader_done();
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_load_obo_v1_2($file, $jobid = NULL, &$newcvs) {
+  global $_tripal_cv_previous_db;
+
+  $header = array();
+  $obo = array();
+
+  print "Opening File $file\n";
+
+  // set the search path
+  $_tripal_cv_previous_db = tripal_db_set_active('chado');
+
+  // make sure we have an 'internal' and a '_global' database
+  if (!tripal_cv_obo_add_db('internal')) {
+    tripal_cv_obo_quiterror("Cannot add 'internal' database");
+  }
+  if (!tripal_cv_obo_add_db('_global')) {
+    tripal_cv_obo_quiterror("Cannot add '_global' database");
+  }
+
+  // parse the obo file
+  tripal_cv_obo_parse($file, $obo, $header);
+
+  // add the CV for this ontology to the database
+  $defaultcv = tripal_cv_obo_add_cv($header['default-namespace'][0], '');
+  if (!$defaultcv) {
+    tripal_cv_obo_quiterror('Cannot add namespace ' . $header['default-namespace'][0]);
+  }
+  $newcvs[$header['default-namespace'][0]] = $defaultcv->cv_id;
+
+  // add any typedefs to the vocabulary first
+  $typedefs = $obo['Typedef'];
+  foreach ($typedefs as $typedef) {
+    tripal_cv_obo_process_term($typedef, $defaultcv, $obo, 1, $newcvs);
+  }
+
+  // next add terms to the vocabulary
+  $terms = $obo['Term'];
+  if (!tripal_cv_obo_process_terms($terms, $defaultcv, $obo, $jobid, $newcvs)) {
+    tripal_cv_obo_quiterror('Cannot add terms from this ontology');
+  }
+
+  return tripal_cv_obo_loader_done();
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_quiterror ($message){
-   print "ERROR: $message\n";
-   db_query("set search_path to public");  
-   exit;
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_quiterror($message) {
+
+  print "ERROR: $message\n";
+  db_query("set search_path to public");
+  exit;
+
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_loader_done (){
-   // return the search path to normal
-   tripal_db_set_active($previous_db);
-   db_query("set search_path to public");  
-   return '';
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_loader_done() {
+
+  // return the search path to normal
+  tripal_db_set_active($_tripal_cv_previous_db);
+  db_query("set search_path to public");
+
+  return '';
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_process_terms($terms,$defaultcv,$obo,$jobid=null,&$newcvs){
-
-   $i = 0;
-   $count = sizeof($terms);
-   $interval = intval($count * 0.01);
-   if($interval > 1){
-      $interval = 1;
-   }
-
-   foreach ($terms as $term){
-
-      // update the job status every 1% terms
-      if($jobid and $i % $interval == 0){
-         tripal_job_set_progress($jobid,intval(($i/$count)*50)); // we mulitply by 50 because parsing and loacing cvterms
-                                                                 // is only the first half.  The other half is updating
-      }                                                          // the cvtermpath table.
-
-      if(!tripal_cv_obo_process_term($term,$defaultcv,$obo,0,$newcvs)){
-         tripal_cv_obo_quiterror("Failed to process terms from the ontology");
-      }
-      $i++;
-   }
-   return 1;
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_process_terms($terms, $defaultcv, $obo, $jobid = NULL, &$newcvs) {
+
+  $i = 0;
+  $count = sizeof($terms);
+  $interval = intval($count * 0.01);
+  if ($interval > 1) {
+    $interval = 1;
+  }
+
+  foreach ($terms as $term) {
+
+    // update the job status every 1% terms
+    if ($jobid and $i % $interval == 0) {
+      tripal_job_set_progress($jobid, intval(($i / $count) * 50)); // we mulitply by 50 because parsing and loacing cvterms
+                                                                   // is only the first half.  The other half is updating
+    }                                                              // the cvtermpath table.
+
+    if (!tripal_cv_obo_process_term($term, $defaultcv, $obo, 0, $newcvs)) {
+      tripal_cv_obo_quiterror("Failed to process terms from the ontology");
+    }
+
+    $i++;
+  }
+  return 1;
 }
 
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_process_term($term,$defaultcv,$obo,$is_relationship=0,&$newcvs){
-
-   // add the cvterm
-   $cvterm = tripal_cv_obo_add_cvterm($term,$defaultcv,$is_relationship,1);     
-   if(!$cvterm){ 
-      tripal_cv_obo_quiterror("Cannot add the term " . $term['id'][0]);
-   }
-   if($term['namespace'][0]){
-      $newcvs[$term['namespace'][0]] = $cvterm->cv_id;
-   }
-
-   // now handle other properites
-   if(isset($term['is_anonymous'])){
-     //print "WARNING: unhandled tag: is_anonymous\n";
-   }
-   if(isset($term['alt_id'])){
-      foreach($term['alt_id'] as $alt_id){
-         if(!tripal_cv_obo_add_cvterm_dbxref($cvterm,$alt_id)){
-            tripal_cv_obo_quiterror("Cannot add alternate id $alt_id");
-         }
-      }
-   }
-   if(isset($term['subset'])){
-     //print "WARNING: unhandled tag: subset\n";
-   }
-   // add synonyms for this cvterm
-   if(isset($term['synonym'])){
-      if(!tripal_cv_obo_add_synonyms($term,$cvterm)){
-         tripal_cv_obo_quiterror("Cannot add synonyms");
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_process_term($term, $defaultcv, $obo, $is_relationship = 0, &$newcvs) {
+
+  // add the cvterm
+  $cvterm = tripal_cv_obo_add_cvterm($term, $defaultcv, $is_relationship, 1);
+  if (!$cvterm) {
+    tripal_cv_obo_quiterror("Cannot add the term " . $term['id'][0]);
+  }
+  if ($term['namespace'][0]) {
+    $newcvs[$term['namespace'][0]] = $cvterm->cv_id;
+  }
+
+  // now handle other properites
+  if (isset($term['is_anonymous'])) {
+    //print "WARNING: unhandled tag: is_anonymous\n";
+  }
+  if (isset($term['alt_id'])) {
+    foreach ($term['alt_id'] as $alt_id) {
+      if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $alt_id)) {
+        tripal_cv_obo_quiterror("Cannot add alternate id $alt_id");
       }
-   }
-   // reformat the deprecated 'exact_synonym, narrow_synonym, and broad_synonym'
-   // types to be of the v1.2 standard
-   if(isset($term['exact_synonym']) or isset($term['narrow_synonym']) or isset($term['broad_synonym'])){
-      if(isset($term['exact_synonym'])){
-         foreach ($term['exact_synonym'] as $synonym){
-
-            $new = preg_replace('/^\s*(\".+?\")(.*?)$/','$1 EXACT $2',$synonym);
-            $term['synonym'][] = $new;
-         }
+    }
+  }
+  if (isset($term['subset'])) {
+    //print "WARNING: unhandled tag: subset\n";
+  }
+  // add synonyms for this cvterm
+  if (isset($term['synonym'])) {
+    if (!tripal_cv_obo_add_synonyms($term, $cvterm)) {
+      tripal_cv_obo_quiterror("Cannot add synonyms");
+    }
+  }
+
+  // reformat the deprecated 'exact_synonym, narrow_synonym, and broad_synonym'
+  // types to be of the v1.2 standard
+  if (isset($term['exact_synonym']) or isset($term['narrow_synonym']) or isset($term['broad_synonym'])) {
+    if (isset($term['exact_synonym'])) {
+      foreach ($term['exact_synonym'] as $synonym) {
+        $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 EXACT $2', $synonym);
+        $term['synonym'][] = $new;
       }
-      if(isset($term['narrow_synonym'])){
-         foreach ($term['narrow_synonym'] as $synonym){
-            $new = preg_replace('/^\s*(\".+?\")(.*?)$/','$1 NARROW $2',$synonym);
-            $term['synonym'][] = $new;
-         }
+    }
+    if (isset($term['narrow_synonym'])) {
+      foreach ($term['narrow_synonym'] as $synonym) {
+        $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 NARROW $2', $synonym);
+        $term['synonym'][] = $new;
       }
-      if(isset($term['broad_synonym'])){
-         foreach ($term['broad_synonym'] as $synonym){
-            $new = preg_replace('/^\s*(\".+?\")(.*?)$/','$1 BROAD $2',$synonym);
-            $term['synonym'][] = $new;
-         }
-      } 
-
-      if(!tripal_cv_obo_add_synonyms($term,$cvterm)){
-         tripal_cv_obo_quiterror("Cannot add/update synonyms");
+    }
+    if (isset($term['broad_synonym'])) {
+      foreach ($term['broad_synonym'] as $synonym) {
+        $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 BROAD $2', $synonym);
+        $term['synonym'][] = $new;
       }
-   }
-   // add the comment to the cvtermprop table
-   if(isset($term['comment'])){
-      $comments = $term['comment'];
-      $j = 0;
-      foreach($comments as $comment){
-         if(!tripal_cv_obo_add_cvterm_prop($cvterm,'comment',$comment,$j)){
-            tripal_cv_obo_quiterror("Cannot add/update cvterm property");
-         }
-         $j++;
+    }
+
+    if (!tripal_cv_obo_add_synonyms($term, $cvterm)) {
+      tripal_cv_obo_quiterror("Cannot add/update synonyms");
+    }
+  }
+  // add the comment to the cvtermprop table
+  if (isset($term['comment'])) {
+    $comments = $term['comment'];
+    $j = 0;
+    foreach ($comments as $comment) {
+      if (!tripal_cv_obo_add_cvterm_prop($cvterm, 'comment', $comment, $j)) {
+        tripal_cv_obo_quiterror("Cannot add/update cvterm property");
       }
-   }    
-   // add any other external dbxrefs
-   if(isset($term['xref'])){
-      foreach($term['xref'] as $xref){
-         if(!tripal_cv_obo_add_cvterm_dbxref($cvterm,$xref)){
-            tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
-         }
+      $j++;
+    }
+  }
+  // add any other external dbxrefs
+  if (isset($term['xref'])) {
+    foreach ($term['xref'] as $xref) {
+      if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref)) {
+        tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
       }
-   }
-   if(isset($term['xref_analog'])){
-      foreach($term['xref_analog'] as $xref){
-         if(!tripal_cv_obo_add_cvterm_dbxref($cvterm,$xref)){
-            tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
-         }
+    }
+  }
+  if (isset($term['xref_analog'])) {
+    foreach ($term['xref_analog'] as $xref) {
+      if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref)) {
+        tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
       }
-   }
-   if(isset($term['xref_unk'])){
-      foreach($term['xref_unk'] as $xref){
-         if(!tripal_cv_obo_add_cvterm_dbxref($cvterm,$xref)){
-            tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
-         }
+    }
+  }
+  if (isset($term['xref_unk'])) {
+    foreach ($term['xref_unk'] as $xref) {
+      if (!tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref)) {
+        tripal_cv_obo_quiterror("Cannot add/update cvterm database reference (dbxref).");
       }
-   }
-
-   // add is_a relationships for this cvterm
-   if(isset($term['is_a'])){
-      foreach($term['is_a'] as $is_a){
-         if(!tripal_cv_obo_add_relationship($cvterm,$defaultcv,$obo,'is_a',$is_a,$is_relationship)){
-            tripal_cv_obo_quiterror("Cannot add relationship is_a: $is_a");
-         }
+    }
+  }
+
+  // add is_a relationships for this cvterm
+  if (isset($term['is_a'])) {
+    foreach ($term['is_a'] as $is_a) {
+      if (!tripal_cv_obo_add_relationship($cvterm, $defaultcv, $obo, 'is_a', $is_a, $is_relationship)) {
+        tripal_cv_obo_quiterror("Cannot add relationship is_a: $is_a");
       }
-   } 
-   if(isset($term['intersection_of'])){
-     //print "WARNING: unhandled tag: intersection_of\n";
-   }
-   if(isset($term['union_of'])){
-     //print "WARNING: unhandled tag: union_on\n";
-   }
-   if(isset($term['disjoint_from'])){
-     //print "WARNING: unhandled tag: disjoint_from\n";
-   }
-   if(isset($term['relationship'])){
-      foreach($term['relationship'] as $value){
-         $rel = preg_replace('/^(.+?)\s.+?$/','\1',$value);
-         $object = preg_replace('/^.+?\s(.+?)$/','\1',$value);
-         if(!tripal_cv_obo_add_relationship($cvterm,$defaultcv,$obo,$rel,$object,$is_relationship)){
-            tripal_cv_obo_quiterror("Cannot add relationship $rel: $object");
-         }
+    }
+  }
+  if (isset($term['intersection_of'])) {
+    //print "WARNING: unhandled tag: intersection_of\n";
+  }
+  if (isset($term['union_of'])) {
+    //print "WARNING: unhandled tag: union_on\n";
+  }
+  if (isset($term['disjoint_from'])) {
+    //print "WARNING: unhandled tag: disjoint_from\n";
+  }
+  if (isset($term['relationship'])) {
+    foreach ($term['relationship'] as $value) {
+      $rel = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
+      $object = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
+      if (!tripal_cv_obo_add_relationship($cvterm, $defaultcv, $obo, $rel, $object, $is_relationship)) {
+        tripal_cv_obo_quiterror("Cannot add relationship $rel: $object");
       }
-   }
-   if(isset($term['replaced_by'])){
-     //print "WARNING: unhandled tag: replaced_by\n";
-   }
-   if(isset($term['consider'])){
-     //print "WARNING: unhandled tag: consider\n";
-   }
-   if(isset($term['use_term'])){
-     //print "WARNING: unhandled tag: user_term\n";
-   }
-   if(isset($term['builtin'])){
-     //print "WARNING: unhandled tag: builtin\n";
-   }
-   return 1;
+    }
+  }
+  if (isset($term['replaced_by'])) {
+   //print "WARNING: unhandled tag: replaced_by\n";
+  }
+  if (isset($term['consider'])) {
+    //print "WARNING: unhandled tag: consider\n";
+  }
+  if (isset($term['use_term'])) {
+    //print "WARNING: unhandled tag: user_term\n";
+  }
+  if (isset($term['builtin'])) {
+    //print "WARNING: unhandled tag: builtin\n";
+  }
+  return 1;
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_add_db($dbname){
-
-   $db_sql = "SELECT * FROM {db} WHERE name ='%s'";
-   $db = db_fetch_object(db_query($db_sql,$dbname));
-   if(!$db){
-      if(!db_query("INSERT INTO {db} (name) VALUES ('%s')",$dbname)){
-         tripal_cv_obo_quiterror("Cannot create '$dbname' db in Chado.");
-      }      
-     $db = db_fetch_object(db_query($db_sql,$dbname));
-   }
-   return $db;
+ * Add a database record
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_add_db($dbname) {
+
+  $db_sql = "SELECT * FROM {db} WHERE name ='%s'";
+  $db = db_fetch_object(db_query($db_sql, $dbname));
+  if (!$db) {
+    if (!db_query("INSERT INTO {db} (name) VALUES ('%s')", $dbname)) {
+      tripal_cv_obo_quiterror("Cannot create '$dbname' db in Chado.");
+    }
+    $db = db_fetch_object(db_query($db_sql, $dbname));
+  }
+
+  return $db;
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_add_cv($name,$comment){
-
- // see if the CV (default-namespace) exists already in the database
-   $vocab = $name;
-   $remark = $comment;
-   $cv_sql = "SELECT * FROM {cv} WHERE name = '%s'";
-   $cv = db_fetch_object(db_query($cv_sql,$vocab));
-
-   // if the CV exists then update it, otherwise insert
-   if(!$cv){
-      $sql = "INSERT INTO {cv} (name,definition) VALUES ('%s','%s')";
-      if(!db_query($sql,$vocab,$remark)){
-         tripal_cv_obo_quiterror("Failed to create the CV record");
-      }
-      $cv = db_fetch_object(db_query($cv_sql,$vocab));
-   } else {
-      $sql = "UPDATE {cv} SET definition = '%s' WHERE name ='%s'";
-      if(!db_query($sql,$remark,$vocab)){
-         tripal_cv_obo_quiterror("Failed to update the CV record");
-      }
-      $cv = db_fetch_object(db_query($cv_sql,$vocab));
-   }
-   return $cv;
+ * Add a controlled vocab record
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_add_cv($name, $comment) {
+
+  // see if the CV (default-namespace) exists already in the database
+  $vocab = $name;
+  $remark = $comment;
+  $cv_sql = "SELECT * FROM {cv} WHERE name = '%s'";
+  $cv = db_fetch_object(db_query($cv_sql, $vocab));
+
+  // if the CV exists then update it, otherwise insert
+  if (!$cv) {
+    $sql = "INSERT INTO {cv} (name,definition) VALUES ('%s','%s')";
+    if (!db_query($sql, $vocab, $remark)) {
+      tripal_cv_obo_quiterror("Failed to create the CV record");
+    }
+    $cv = db_fetch_object(db_query($cv_sql, $vocab));
+  }
+  else {
+    $sql = "UPDATE {cv} SET definition = '%s' WHERE name ='%s'";
+    if (!db_query($sql, $remark, $vocab)) {
+      tripal_cv_obo_quiterror("Failed to update the CV record");
+    }
+    $cv = db_fetch_object(db_query($cv_sql, $vocab));
+  }
+
+  return $cv;
 }
 
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_add_relationship($cvterm,$defaultcv,$obo,$rel,$objname,$object_is_relationship=0){
-
-   // make sure the relationship cvterm exists
-   $term = array(
-      'name' => array($rel),
-      'id' => array($rel),
-      'definition' => array(''),
-      'is_obsolete' => array(0),
-   );
-   $relcvterm = tripal_cv_obo_add_cvterm($term,$defaultcv,1,0);
-   if(!$relcvterm){
-      tripal_cv_obo_quiterror("Cannot find or insert the relationship term: $rel\n");
-   }
-
-   // get the object term
-   $objterm = tripal_cv_obo_get_term($obo,$objname);
-   if(!$objterm) { 
-      tripal_cv_obo_quiterror("Could not find object term $objname\n"); 
-   }
-   $objcvterm = tripal_cv_obo_add_cvterm($objterm,$defaultcv,$object_is_relationship,1);
-   if(!$objcvterm){ 
-      tripal_cv_obo_quiterror("Cannot add/find cvterm");
-   }
-
-   // check to see if the cvterm_relationship already exists, if not add it
-   $cvrsql = "SELECT * FROM {cvterm_relationship} WHERE type_id = %d and subject_id = %d and object_id = %d";
-   if(!db_fetch_object(db_query($cvrsql,$relcvterm->cvterm_id,$cvterm->cvterm_id,$objcvterm->cvterm_id))){
-      $sql = "INSERT INTO {cvterm_relationship} ".
-             "(type_id,subject_id,object_id) VALUES (%d,%d,%d)";
-      if(!db_query($sql,$relcvterm->cvterm_id,$cvterm->cvterm_id,$objcvterm->cvterm_id)){
-         tripal_cv_obo_quiterror("Cannot add term relationship: '$cvterm->name' $rel '$objcvterm->name'");
-      }
-   }
-
-   return 1;
+ * Add a cvterm relationship
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_add_relationship($cvterm, $defaultcv, $obo, $rel, $objname, $object_is_relationship = 0) {
+
+  // make sure the relationship cvterm exists
+  $term = array(
+    'name' => array($rel),
+    'id' => array($rel),
+    'definition' => array(''),
+    'is_obsolete' => array(0),
+  );
+  $relcvterm = tripal_cv_obo_add_cvterm($term, $defaultcv, 1, 0);
+  if (!$relcvterm) {
+    tripal_cv_obo_quiterror("Cannot find or insert the relationship term: $rel\n");
+  }
+
+  // get the object term
+  $objterm = tripal_cv_obo_get_term($obo, $objname);
+  if (!$objterm) {
+    tripal_cv_obo_quiterror("Could not find object term $objname\n");
+  }
+  $objcvterm = tripal_cv_obo_add_cvterm($objterm, $defaultcv, $object_is_relationship, 1);
+  if (!$objcvterm) {
+    tripal_cv_obo_quiterror("Cannot add/find cvterm");
+  }
+
+  // check to see if the cvterm_relationship already exists, if not add it
+  $cvrsql = "SELECT * FROM {cvterm_relationship} WHERE type_id = %d and subject_id = %d and object_id = %d";
+  if (!db_fetch_object(db_query($cvrsql, $relcvterm->cvterm_id, $cvterm->cvterm_id, $objcvterm->cvterm_id))) {
+    $sql = "INSERT INTO {cvterm_relationship} ".
+           "(type_id,subject_id,object_id) VALUES (%d,%d,%d)";
+    if (!db_query($sql, $relcvterm->cvterm_id, $cvterm->cvterm_id, $objcvterm->cvterm_id)) {
+      tripal_cv_obo_quiterror("Cannot add term relationship: '$cvterm->name' $rel '$objcvterm->name'");
+    }
+  }
+
+  return TRUE;
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_get_term($obo,$id){
-   foreach ($obo as $type){
-      foreach ($type as $term){
-         $accession = $term['id'][0];
-         if(strcmp($accession,$id)==0){
-            return $term;
-         }
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_get_term($obo, $id) {
+  foreach ($obo as $type) {
+    foreach ($type as $term) {
+      $accession = $term['id'][0];
+      if (strcmp($accession, $id)==0) {
+        return $term;
       }
-   }
-   return;
+    }
+  }
+
+  return FALSE;
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_add_synonyms($term,$cvterm){
-
-   // make sure we have a 'synonym_type' vocabulary
-   $sql = "SELECT * FROM {cv} WHERE name='synonym_type'";
-   $syncv = db_fetch_object(db_query($sql));
-   if(!$syncv){
-      $sql = "INSERT INTO {cv} (name,definition) VALUES ('synonym_type','')";
-      if(!db_query($sql)){
-         tripal_cv_obo_quiterror("Failed to add the synonyms type vocabulary");
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_add_synonyms($term, $cvterm) {
+
+  // make sure we have a 'synonym_type' vocabulary
+  $sql = "SELECT * FROM {cv} WHERE name='synonym_type'";
+  $syncv = db_fetch_object(db_query($sql));
+  if (!$syncv) {
+    $sql = "INSERT INTO {cv} (name,definition) VALUES ('synonym_type','')";
+    if (!db_query($sql)) {
+      tripal_cv_obo_quiterror("Failed to add the synonyms type vocabulary");
+    }
+    $syncv = db_fetch_object(db_query($sql));
+  }
+
+  // now add the synonyms
+  if (isset($term['synonym'])) {
+    foreach ($term['synonym'] as $synonym) {
+      // separate out the synonym definition and the synonym type
+      $def = preg_replace('/^\s*"(.*)"\s*.*$/', '\1', $synonym);
+      $type = drupal_strtolower(preg_replace('/^.*"\s+(.*?)\s+.*$/', '\1', $synonym));
+
+      // make sure the synonym type exists in the 'synonym_type' vocabulary
+      $cvtsql = "
+        SELECT *
+        FROM {cvterm} CVT
+           INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
+        WHERE CVT.name = '%s' and CV.name = '%s'
+      ";
+      $syntype = db_fetch_object(db_query($cvtsql, $type, 'synonym_type'));
+      if (!$syntype) {
+        // build a 'term' object so we can add the missing term
+        $term = array(
+           'name' => array($type),
+           'id' => array("internal:$type"),
+           'definition' => array(''),
+           'is_obsolete' => array(0),
+        );
+        $syntype = tripal_cv_obo_add_cvterm($term, $syncv, 0, 1);
+        if (!$syntype) {
+          tripal_cv_obo_quiterror("Cannot add synonym type: internal:$type");
+        }
       }
-      $syncv = db_fetch_object(db_query($sql));
-   }
-
-   // now add the synonyms
-   if(isset($term['synonym'])){
-      foreach($term['synonym'] as $synonym){
-         // separate out the synonym definition and the synonym type
-         $def = preg_replace('/^\s*"(.*)"\s*.*$/','\1',$synonym);
-         $type = strtolower(preg_replace('/^.*"\s+(.*?)\s+.*$/','\1',$synonym)); 
-
-         // make sure the synonym type exists in the 'synonym_type' vocabulary
-         $cvtsql = "
-            SELECT * 
-            FROM {cvterm} CVT
-               INNER JOIN {cv} CV ON CVT.cv_id = CV.cv_id
-            WHERE CVT.name = '%s' and CV.name = '%s'
-         ";
-         $syntype = db_fetch_object(db_query($cvtsql,$type,'synonym_type'));
-         if(!$syntype){
-            // build a 'term' object so we can add the missing term
-            $term = array(
-               'name' => array($type),
-               'id' => array("internal:$type"),
-               'definition' => array(''),
-               'is_obsolete' => array(0),
-            );
-            $syntype = tripal_cv_obo_add_cvterm($term,$syncv,0,1);
-            if(!$syntype){
-               tripal_cv_obo_quiterror("Cannot add synonym type: internal:$type");
-            }
-         }       
-
-         // make sure the synonym doesn't already exists
-         $sql = "
-            SELECT * 
-            FROM {cvtermsynonym} 
-            WHERE cvterm_id = %d and synonym = '%s'
-         ";
-         $syn = db_fetch_object(db_query($sql,$cvterm->cvterm_id,$def));
-         if(!$syn){
-            $sql = "INSERT INTO {cvtermsynonym} (cvterm_id,synonym,type_id)
-                    VALUES(%d,'%s',%d)";
-            if(!db_query($sql,$cvterm->cvterm_id,$def,$syntype->cvterm_id)){
-               tripal_cv_obo_quiterror("Failed to insert the synonym for term: $name ($def)");
-            }
-         } 
-
-         // now add the dbxrefs for the synonym if we have a comma in the middle
-         // of a description then this will cause problems when splitting os lets
-         // just change it so it won't mess up our splitting and then set it back
-         // later.
-//         $synonym = preg_replace('/(".*?),\s(.*?")/','$1,_$2',$synonym);
-//         $dbxrefs = preg_split("/, /",preg_replace('/^.*\[(.*?)\]$/','\1',$synonym));
-//         foreach($dbxrefs as $dbxref){
-//            $dbxref = preg_replace('/,_/',", ",$dbxref);
-//            if($dbxref){
-//               tripal_cv_obo_add_cvterm_dbxref($syn,$dbxref);
-//            }
-//         }
-      } 
-   }
-   return 1;
+
+      // make sure the synonym doesn't already exists
+      $sql = "
+        SELECT *
+        FROM {cvtermsynonym}
+        WHERE cvterm_id = %d and synonym = '%s'
+      ";
+      $syn = db_fetch_object(db_query($sql, $cvterm->cvterm_id, $def));
+      if (!$syn) {
+        $sql = "INSERT INTO {cvtermsynonym} (cvterm_id,synonym,type_id)
+                VALUES(%d,'%s',%d)";
+        if (!db_query($sql, $cvterm->cvterm_id, $def, $syntype->cvterm_id)) {
+          tripal_cv_obo_quiterror("Failed to insert the synonym for term: $name ($def)");
+        }
+      }
+
+      // now add the dbxrefs for the synonym if we have a comma in the middle
+      // of a description then this will cause problems when splitting os lets
+      // just change it so it won't mess up our splitting and then set it back
+      // later.
+      /**
+      $synonym = preg_replace('/(".*?),\s(.*?")/','$1,_$2',$synonym);
+      $dbxrefs = preg_split("/, /",preg_replace('/^.*\[(.*?)\]$/','\1',$synonym));
+      foreach ($dbxrefs as $dbxref) {
+       $dbxref = preg_replace('/,_/',", ",$dbxref);
+        if ($dbxref) {
+          tripal_cv_obo_add_cvterm_dbxref($syn,$dbxref);
+        }
+      }
+      */
+    }
+  }
+
+  return TRUE;
 }
 
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_parse($obo_file,&$obo,&$header){
-   $i = 0;
-   $in_header = 1;
-   $stanza = array();
-
-   // iterate through the lines in the OBO file and parse the stanzas
-   $fh = fopen($obo_file,'r');
-   while($line = fgets($fh)) {
-      $i++;
-
-      // remove newlines
-      $line = rtrim($line);  
-
-      // remove any special characters that may be hiding
-      $line = preg_replace('/[^(\x20-\x7F)]*/','', $line);
-
-      // skip empty lines
-      if(strcmp($line,'')==0) { continue; }
-
-      //remove comments from end of lines
-      $line = preg_replace('/^(.*?)\!.*$/','\1',$line);  // TODO: if the explamation is escaped
-
-      if(preg_match('/^\s*\[/',$line)){  // at the first stanza we're out of header
-         $in_header = 0;
-         // load the stanza we just finished reading
-         if(sizeof($stanza) > 0){
-            if(!isset($obo[$type])){
-               $obo[$type] = array();
-            }
-            if(!isset($obo[$type][$stanza['id'][0]])){
-               $obo[$type][$stanza['id'][0]] = $stanza;
-            } else {
-               array_merge($obo[$type][$stanza['id'][0]],$stanza);
-            }
-         } 
-         // get the stanza type:  Term, Typedef or Instance
-         $type = preg_replace('/^\s*\[\s*(.+?)\s*\]\s*$/','\1',$line);
-
-         // start fresh with a new array
-         $stanza = array();
-         continue;
+ * Actually parse the OBO file
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_parse($obo_file, &$obo, &$header) {
+  $i = 0;
+  $in_header = 1;
+  $stanza = array();
+
+  // iterate through the lines in the OBO file and parse the stanzas
+  $fh = fopen($obo_file, 'r');
+  while ($line = fgets($fh)) {
+    $i++;
+
+    // remove newlines
+    $line = rtrim($line);
+
+    // remove any special characters that may be hiding
+    $line = preg_replace('/[^(\x20-\x7F)]*/', '', $line);
+
+    // skip empty lines
+    if (strcmp($line, '') == 0) {
+      continue;
+    }
+
+    //remove comments from end of lines
+    $line = preg_replace('/^(.*?)\!.*$/', '\1', $line);  // TODO: if the explamation is escaped
+
+    if (preg_match('/^\s*\[/', $line)) {  // at the first stanza we're out of header
+      $in_header = 0;
+      // load the stanza we just finished reading
+      if (sizeof($stanza) > 0) {
+        if (!isset($obo[$type])) {
+          $obo[$type] = array();
+        }
+        if (!isset($obo[$type][$stanza['id'][0]])) {
+          $obo[$type][$stanza['id'][0]] = $stanza;
+        }
+        else {
+          array_merge($obo[$type][$stanza['id'][0]], $stanza);
+        }
       }
-      // break apart the line into the tag and value but ignore any escaped colons
-      preg_replace("/\\:/","|-|-|",$line); // temporarily replace escaped colons
-      $pair = explode(":",$line,2);
-      $tag = $pair[0];
-      $value = ltrim(rtrim($pair[1]));// remove surrounding spaces
-      $tag = preg_replace("/\|-\|-\|/","\:",$tag); // return the escaped colon
-      $value = preg_replace("/\|-\|-\|/","\:",$value);
-      if($in_header){
-         if(!isset($header[$tag])){
-            $header[$tag] = array();
-         }
-         $header[$tag][] = $value;
-      } else {
-         if(!isset($stanza[$tag])){
-            $stanza[$tag] = array();
-         }  
-         $stanza[$tag][] = $value;
-      }          
-   }
-   // now add the last term in the file
-   if(sizeof($stanza) > 0){
-      if(!isset($obo[$type])){
-         $obo[$type] = array();
+      // get the stanza type:  Term, Typedef or Instance
+      $type = preg_replace('/^\s*\[\s*(.+?)\s*\]\s*$/', '\1', $line);
+
+      // start fresh with a new array
+      $stanza = array();
+      continue;
+    }
+    // break apart the line into the tag and value but ignore any escaped colons
+    preg_replace("/\\:/", "|-|-|", $line); // temporarily replace escaped colons
+    $pair = explode(":", $line, 2);
+    $tag = $pair[0];
+    $value = ltrim(rtrim($pair[1]));// remove surrounding spaces
+    $tag = preg_replace("/\|-\|-\|/", "\:", $tag); // return the escaped colon
+    $value = preg_replace("/\|-\|-\|/", "\:", $value);
+    if ($in_header) {
+      if (!isset($header[$tag])) {
+        $header[$tag] = array();
       }
-      if(!isset($obo[$type][$stanza['id'][0]])){
-         $obo[$type][$stanza['id'][0]] = $stanza;
-      } else {
-         array_merge($obo[$type][$stanza['id'][0]],$stanza);
+      $header[$tag][] = $value;
+    }
+    else {
+      if (!isset($stanza[$tag])) {
+        $stanza[$tag] = array();
       }
-   }
+      $stanza[$tag][] = $value;
+    }
+  }
+  // now add the last term in the file
+  if (sizeof($stanza) > 0) {
+    if (!isset($obo[$type])) {
+      $obo[$type] = array();
+    }
+    if (!isset($obo[$type][$stanza['id'][0]])) {
+      $obo[$type][$stanza['id'][0]] = $stanza;
+    }
+    else {
+      array_merge($obo[$type][$stanza['id'][0]], $stanza);
+    }
+  }
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_add_cvterm_dbxref($cvterm,$xref){
-
-   $dbname = preg_replace('/^(.+?):.*$/','$1',$xref);
-   $accession = preg_replace('/^.+?:\s*(.*?)(\{.+$|\[.+$|\s.+$|\".+$|$)/','$1',$xref);
-   $description = preg_replace('/^.+?\"(.+?)\".*?$/','$1',$xref);
-   $dbxrefs = preg_replace('/^.+?\[(.+?)\].*?$/','$1',$xref);
-
-   if(!$accession){
-      tripal_cv_obo_quiterror();
-      watchdog('tripal_cv',"Cannot add a dbxref without an accession: '$xref'"
-         ,NULL,WATCHDOG_WARNING);
-      return 0;
-   }
-
-   // if the xref is a database link, handle that specially
-   if(strcmp($dbname,'http')==0){
-      $accession = $xref;
-      $dbname = 'URL';
-   }
-
-   // check to see if the database exists
-   $db = tripal_cv_obo_add_db($dbname);
-   if(!$db){
-      tripal_cv_obo_quiterror("Cannot find database '$dbname' in Chado.");
-   }
-
-   // now add the dbxref
-   $dbxref = tripal_cv_obo_add_dbxref($db->db_id,$accession,'',$description);
-   if(!$dbxref){ 
-      tripal_cv_obo_quiterror("Cannot find or add the database reference (dbxref)");
-   }
-
-   // finally add the cvterm_dbxref but first check to make sure it exists
-   $sql = "SELECT * from {cvterm_dbxref} WHERE cvterm_id = %d and dbxref_id = %d";
-   if(!db_fetch_object(db_query($sql,$cvterm->cvterm_id,$dbxref->dbxref_id))){            
-      $sql = "INSERT INTO {cvterm_dbxref} (cvterm_id,dbxref_id)".
-             "VALUES (%d,%d)";
-      if(!db_query($sql,$cvterm->cvterm_id,$dbxref->dbxref_id)){
-         tripal_cv_obo_quiterror("Cannot add cvterm_dbxref: $xref");
-      }
-   }
-   return 1;
+ * Add database reference to cvterm
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_add_cvterm_dbxref($cvterm, $xref) {
+
+  $dbname = preg_replace('/^(.+?):.*$/', '$1', $xref);
+  $accession = preg_replace('/^.+?:\s*(.*?)(\{.+$|\[.+$|\s.+$|\".+$|$)/', '$1', $xref);
+  $description = preg_replace('/^.+?\"(.+?)\".*?$/', '$1', $xref);
+  $dbxrefs = preg_replace('/^.+?\[(.+?)\].*?$/', '$1', $xref);
+
+  if (!$accession) {
+    tripal_cv_obo_quiterror();
+    watchdog('tripal_cv', "Cannot add a dbxref without an accession: '$xref'", NULL, WATCHDOG_WARNING);
+    return FALSE;
+  }
+
+  // if the xref is a database link, handle that specially
+  if (strcmp($dbname, 'http') == 0) {
+    $accession = $xref;
+    $dbname = 'URL';
+  }
+
+  // check to see if the database exists
+  $db = tripal_cv_obo_add_db($dbname);
+  if (!$db) {
+    tripal_cv_obo_quiterror("Cannot find database '$dbname' in Chado.");
+  }
+
+  // now add the dbxref
+  $dbxref = tripal_cv_obo_add_dbxref($db->db_id, $accession, '', $description);
+  if (!$dbxref) {
+    tripal_cv_obo_quiterror("Cannot find or add the database reference (dbxref)");
+  }
+
+  // finally add the cvterm_dbxref but first check to make sure it exists
+  $sql = "SELECT * from {cvterm_dbxref} WHERE cvterm_id = %d and dbxref_id = %d";
+  if (!db_fetch_object(db_query($sql, $cvterm->cvterm_id, $dbxref->dbxref_id))) {
+    $sql = "INSERT INTO {cvterm_dbxref} (cvterm_id,dbxref_id)".
+           "VALUES (%d,%d)";
+    if (!db_query($sql, $cvterm->cvterm_id, $dbxref->dbxref_id)) {
+      tripal_cv_obo_quiterror("Cannot add cvterm_dbxref: $xref");
+    }
+  }
+
+  return TRUE;
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_add_cvterm_prop($cvterm,$property,$value,$rank){
-
-   // make sure the 'cvterm_property_type' CV exists
-   $cv = tripal_cv_obo_add_cv('cvterm_property_type','');
-   if(!$cv){ 
-      tripal_cv_obo_quiterror("Cannot add/find cvterm_property_type cvterm");
-   }
-
-   // get the property type cvterm.  If it doesn't exist then we want to add it
-   $sql = "
-        SELECT * 
-        FROM {cvterm} CVT INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
-        WHERE CVT.name = '%s' and CV.name = '%s'
-   ";
-   $cvproptype = db_fetch_object(db_query($sql,$property,'cvterm_property_type'));
-   if(!$cvproptype){
-      $term = array(
-         'name' => array($property),
-         'id' => array("internal:$property"),
-         'definition' => array(''),
-         'is_obsolete' => array(0),
-      );
-      $cvproptype = tripal_cv_obo_add_cvterm($term,$cv,0,0);
-      if(!$cvproptype){  
-         tripal_cv_obo_quiterror("Cannot add cvterm property: internal:$property");
-      }
-   }
-
-
-   // remove any properties that currently exist for this term.  We'll reset them
-   if($rank == 0){
-      $sql = "DELETE FROM {cvtermprop} WHERE cvterm_id = %d";
-      db_query($sql,$cvterm->cvterm_id);
-   }
-
-   // now add the property
-   $sql = "INSERT INTO {cvtermprop} (cvterm_id,type_id,value,rank) ".
-          "VALUES (%d, %d, '%s',%d)";
-   if(!db_query($sql,$cvterm->cvterm_id,$cvproptype->cvterm_id,$value,$rank)){
-      tripal_cv_obo_quiterror("Could not add property $property for term\n");
-   }
-   return 1;
+ * Add property to CVterm
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_add_cvterm_prop($cvterm, $property, $value, $rank) {
+
+  // make sure the 'cvterm_property_type' CV exists
+  $cv = tripal_cv_obo_add_cv('cvterm_property_type', '');
+  if (!$cv) {
+    tripal_cv_obo_quiterror("Cannot add/find cvterm_property_type cvterm");
+  }
+
+  // get the property type cvterm.  If it doesn't exist then we want to add it
+  $sql = "
+      SELECT *
+      FROM {cvterm} CVT INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
+      WHERE CVT.name = '%s' and CV.name = '%s'
+  ";
+  $cvproptype = db_fetch_object(db_query($sql, $property, 'cvterm_property_type'));
+  if (!$cvproptype) {
+    $term = array(
+      'name' => array($property),
+      'id' => array("internal:$property"),
+      'definition' => array(''),
+      'is_obsolete' => array(0),
+    );
+    $cvproptype = tripal_cv_obo_add_cvterm($term, $cv, 0, 0);
+    if (!$cvproptype) {
+      tripal_cv_obo_quiterror("Cannot add cvterm property: internal:$property");
+    }
+  }
+
+
+  // remove any properties that currently exist for this term.  We'll reset them
+  if ($rank == 0) {
+    $sql = "DELETE FROM {cvtermprop} WHERE cvterm_id = %d";
+    db_query($sql, $cvterm->cvterm_id);
+  }
+
+  // now add the property
+  $sql = "INSERT INTO {cvtermprop} (cvterm_id,type_id,value,rank) ".
+        "VALUES (%d, %d, '%s',%d)";
+  if (!db_query($sql, $cvterm->cvterm_id, $cvproptype->cvterm_id, $value, $rank)) {
+    tripal_cv_obo_quiterror("Could not add property $property for term\n");
+  }
+
+  return TRUE;
+
 }
+
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_add_cvterm($term,$defaultcv,$is_relationship = 0,$update = 1){
-
-   // get the term properties
-   $id = $term['id'][0];
-   $name = $term['name'][0];
-   $cvname = $term['namespace'][0];
-   $definition = preg_replace('/^\"(.*)\"/','\1',$term['def'][0]);
-   $is_obsolete = 0;
-   if(isset($term['is_obsolete'][0]) and  strcmp($term['is_obsolete'][0],'true')==0){
-     $is_obsolete = 1;
-   }
-   if(!$cvname){
-      $cvname = $defaultcv->name;
-   }
-   // make sure the CV name exists
-   $cv = tripal_cv_obo_add_cv($cvname,'');
-   if(!$cv){
-      tripal_cv_obo_quiterror("Cannot find namespace '$cvname' when adding/updating $id");
-   }
-
-   // this SQL statement will be used a lot to find a cvterm so just set it
-   // here for easy reference below.
-   $cvtermsql = "SELECT CVT.name, CVT.cvterm_id, DB.name as dbname, DB.db_id 
-                  FROM {cvterm} CVT
-                    INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
-                    INNER JOIN {db} DB on DBX.db_id = DB.db_id
-                    INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
-                  WHERE CVT.name = '%s' and DB.name = '%s'";  
-
-   // get the accession and the database from the cvterm
-   if(preg_match('/^.+?:.*$/',$id)){
-      $accession = preg_replace('/^.+?:(.*)$/','\1',$id);
-      $dbname = preg_replace('/^(.+?):.*$/','\1',$id);
-   } 
-   if($is_relationship and !$dbname){
-      $accession = $id;
-      // because this is a relationship cvterm first check to see if it 
-      // exists in the relationship ontology. If it does then return the cvterm.
-      //  If not then set the dbname to _global and we'll add it or find it there
-      $cvterm = db_fetch_object(db_query($cvtermsql,$name,'OBO_REL'));
-      if($cvterm){
-         return $cvterm;
-      } else {
-         // next check if this term is in the _global ontology.  If it is then
-         // return it no matter what the original CV
-         $dbname = '_global';
-
-         $cvterm = db_fetch_object(db_query($cvtermsql,$name,$dbname));
-         if($cvterm){
-            return $cvterm;
-         }
-      }
-   }
-   if(!$is_relationship and !$dbname){
-      tripal_cv_obo_quiterror("A database identifier is missing from the term: $id");
-   }
-
-   // check to see if the database exists. 
-   $db = tripal_cv_obo_add_db($dbname);
-   if(!$db){
-      tripal_cv_obo_quiterror("Cannot find database '$dbname' in Chado.");
-   }
-
-
-   // if the cvterm doesn't exist then add it otherwise just update it
-   $cvterm = db_fetch_object(db_query($cvtermsql,$name,$dbname));
-   if(!$cvterm){
-      // check to see if the dbxref exists if not, add it
-      $dbxref =  tripal_cv_obo_add_dbxref($db->db_id,$accession);
-      if(!$dbxref){
-         tripal_cv_obo_quiterror("Failed to find or insert the dbxref record for cvterm, $name (id: $accession), for database $dbname");
+ *
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_add_cvterm($term, $defaultcv, $is_relationship = 0, $update = 1) {
+
+  // get the term properties
+  $id = $term['id'][0];
+  $name = $term['name'][0];
+  $cvname = $term['namespace'][0];
+  $definition = preg_replace('/^\"(.*)\"/', '\1', $term['def'][0]);
+  $is_obsolete = 0;
+  if (isset($term['is_obsolete'][0]) and  strcmp($term['is_obsolete'][0], 'true') == 0) {
+    $is_obsolete = 1;
+  }
+  if (!$cvname) {
+    $cvname = $defaultcv->name;
+  }
+
+  // make sure the CV name exists
+  $cv = tripal_cv_obo_add_cv($cvname, '');
+  if (!$cv) {
+    tripal_cv_obo_quiterror("Cannot find namespace '$cvname' when adding/updating $id");
+  }
+
+  // this SQL statement will be used a lot to find a cvterm so just set it
+  // here for easy reference below.
+  $cvtermsql = "SELECT CVT.name, CVT.cvterm_id, DB.name as dbname, DB.db_id
+                FROM {cvterm} CVT
+                  INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
+                  INNER JOIN {db} DB on DBX.db_id = DB.db_id
+                  INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
+                WHERE CVT.name = '%s' and DB.name = '%s'";
+
+  // get the accession and the database from the cvterm
+  if (preg_match('/^.+?:.*$/', $id)) {
+    $accession = preg_replace('/^.+?:(.*)$/', '\1', $id);
+    $dbname = preg_replace('/^(.+?):.*$/', '\1', $id);
+  }
+  if ($is_relationship and !$dbname) {
+    $accession = $id;
+    // because this is a relationship cvterm first check to see if it
+    // exists in the relationship ontology. If it does then return the cvterm.
+    //  If not then set the dbname to _global and we'll add it or find it there
+    $cvterm = db_fetch_object(db_query($cvtermsql, $name, 'OBO_REL'));
+    if ($cvterm) {
+      return $cvterm;
+    }
+    else {
+      // next check if this term is in the _global ontology.  If it is then
+      // return it no matter what the original CV
+      $dbname = '_global';
+
+      $cvterm = db_fetch_object(db_query($cvtermsql, $name, $dbname));
+      if ($cvterm) {
+        return $cvterm;
       }
-
-      // check to see if the dbxref already has an entry in the cvterm table
-      $sql = "SELECT * FROM {cvterm} WHERE dbxref_id = %d";
-      $check = db_fetch_object(db_query($sql,$dbxref->dbxref_id));
-
-      if(!$check){
-         // now add the cvterm
-         $sql = "
-            INSERT INTO {cvterm} (cv_id, name, definition, dbxref_id, 
-               is_obsolete, is_relationshiptype) 
-            VALUES (%d,'%s','%s',%d,%d,%d)
-         ";
-         if(!db_query($sql,$cv->cv_id,$name,$definition,
-             $dbxref->dbxref_id,$is_obsolete,$is_relationship)){
-            if(!$is_relationship){
-               tripal_cv_obo_quiterror("Failed to insert the term: $name ($dbname)");
-            } else {
-               tripal_cv_obo_quiterror("Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)");
-            }
-         }  
-         if(!$is_relationship){
-            print "Added CV term: $name ($dbname)\n";
-         } else {
-            print "Added relationship CV term: $name ($dbname)\n";
-         }
+    }
+  }
+  if (!$is_relationship and !$dbname) {
+    tripal_cv_obo_quiterror("A database identifier is missing from the term: $id");
+  }
+
+  // check to see if the database exists.
+  $db = tripal_cv_obo_add_db($dbname);
+  if (!$db) {
+    tripal_cv_obo_quiterror("Cannot find database '$dbname' in Chado.");
+  }
+
+
+  // if the cvterm doesn't exist then add it otherwise just update it
+  $cvterm = db_fetch_object(db_query($cvtermsql, $name, $dbname));
+  if (!$cvterm) {
+    // check to see if the dbxref exists if not, add it
+    $dbxref =  tripal_cv_obo_add_dbxref($db->db_id, $accession);
+    if (!$dbxref) {
+      tripal_cv_obo_quiterror("Failed to find or insert the dbxref record for cvterm, $name (id: $accession), for database $dbname");
+    }
+
+    // check to see if the dbxref already has an entry in the cvterm table
+    $sql = "SELECT * FROM {cvterm} WHERE dbxref_id = %d";
+    $check = db_fetch_object(db_query($sql, $dbxref->dbxref_id));
+
+    if (!$check) {
+      // now add the cvterm
+      $sql = "
+          INSERT INTO {cvterm} (cv_id, name, definition, dbxref_id,
+             is_obsolete, is_relationshiptype)
+          VALUES (%d,'%s','%s',%d,%d,%d)
+      ";
+      if (!db_query($sql, $cv->cv_id, $name, $definition,
+        $dbxref->dbxref_id, $is_obsolete, $is_relationship)) {
+        if (!$is_relationship) {
+          tripal_cv_obo_quiterror("Failed to insert the term: $name ($dbname)");
+        }
+        else {
+          tripal_cv_obo_quiterror("Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)");
+        }
       }
-      elseif($check and strcmp($check->name,$name)!=0){
-         // this dbxref_id alrady exists in the database but the name is 
-         // different.  We will trust that the OBO is correct and that there
-         // has been a name change for this dbxref, so we'll update
-         $sql = "
-            UPDATE {cvterm} SET name = '%s', definition = '%s',
-               is_obsolete = %d, is_relationshiptype = %d 
-            WHERE dbxref_id = %d
-         ";
-         if(!db_query($sql,$name,$definition,$is_obsolete,$is_relationship,$dbxref->dbxref_id)){
-            if(!$is_relationship){
-               tripal_cv_obo_quiterror("Failed to update the term: $name ($dbname)");
-            } else {
-               tripal_cv_obo_quiterror("Failed to update the relationship term: $name (cv: " . $cvname . " db: $dbname)");
-            }
-         } 
-         if(!$is_relationship){
-            print "Updated CV term: $name ($dbname)\n";
-         } else {
-            print "Updated relationship CV term: $name ($dbname)\n";
-         }
+      if (!$is_relationship) {
+        print "Added CV term: $name ($dbname)\n";
       }
-      elseif($check and strcmp($check->name,$name)==0){
-         // this entry already exists. We're good, so do nothing
+      else {
+        print "Added relationship CV term: $name ($dbname)\n";
       }
-      $cvterm = db_fetch_object(db_query($cvtermsql,$name,$dbname));
-   }
-   elseif($update) { // update the cvterm
+    }
+    elseif ($check and strcmp($check->name, $name)!=0) {
+      // this dbxref_id alrady exists in the database but the name is
+      // different.  We will trust that the OBO is correct and that there
+      // has been a name change for this dbxref, so we'll update
       $sql = "
-         UPDATE {cvterm} SET name='%s', definition='%s',
-            is_obsolete = %d, is_relationshiptype = %d
-         WHERE cvterm_id = %d
+          UPDATE {cvterm} SET name = '%s', definition = '%s',
+             is_obsolete = %d, is_relationshiptype = %d
+          WHERE dbxref_id = %d
       ";
-      if(!db_query($sql,$term['name'][0],$definition,
-          $is_obsolete,$is_relationship,$cvterm->cvterm_id)){
-         tripal_cv_obo_quiterror("Failed to update the term: $name");
-      }  
-      $cvterm = db_fetch_object(db_query($cvtermsql,$name,$dbname));         
-      if(!$is_relationship){
-         print "Updated CV term: $name ($dbname)\n";
-      } else {
-         print "Updated relationship CV term: $name ($dbname)\n";
+      if (!db_query($sql, $name, $definition, $is_obsolete, $is_relationship, $dbxref->dbxref_id)) {
+        if (!$is_relationship) {
+          tripal_cv_obo_quiterror("Failed to update the term: $name ($dbname)");
+        }
+        else {
+          tripal_cv_obo_quiterror("Failed to update the relationship term: $name (cv: " . $cvname . " db: $dbname)");
+        }
+      }
+      if (!$is_relationship) {
+        print "Updated CV term: $name ($dbname)\n";
       }
-   }
-   // return the cvterm
-   return $cvterm;
+      else {
+        print "Updated relationship CV term: $name ($dbname)\n";
+      }
+    }
+    elseif ($check and strcmp($check->name, $name)==0) {
+      // this entry already exists. We're good, so do nothing
+    }
+    $cvterm = db_fetch_object(db_query($cvtermsql, $name, $dbname));
+  }
+  elseif ($update) { // update the cvterm
+    $sql = "
+       UPDATE {cvterm} SET name='%s', definition='%s',
+          is_obsolete = %d, is_relationshiptype = %d
+       WHERE cvterm_id = %d
+    ";
+    if (!db_query($sql, $term['name'][0], $definition,
+      $is_obsolete, $is_relationship, $cvterm->cvterm_id)) {
+      tripal_cv_obo_quiterror("Failed to update the term: $name");
+    }
+    $cvterm = db_fetch_object(db_query($cvtermsql, $name, $dbname));
+    if (!$is_relationship) {
+      print "Updated CV term: $name ($dbname)\n";
+    }
+    else {
+      print "Updated relationship CV term: $name ($dbname)\n";
+    }
+  }
+
+  // return the cvterm
+  return $cvterm;
 }
 
 /**
-*
-* @ingroup tripal_obo_loader
-*/
-function tripal_cv_obo_add_dbxref($db_id,$accession,$version='',$description=''){
-
-   // check to see if the dbxref exists if not, add it
-   $dbxsql = "SELECT dbxref_id FROM {dbxref} WHERE db_id = %d and accession = '%s'";
-   $dbxref = db_fetch_object(db_query($dbxsql,$db_id,$accession));
-   if(!$dbxref){
-      $sql = "
-         INSERT INTO {dbxref} (db_id, accession, version, description)
-         VALUES (%d,'%s','%s','%s')
-      ";
-      if(!db_query($sql,$db_id,$accession,$version,$description)){
-         tripal_cv_obo_quiterror("Failed to insert the dbxref record $accession");
-      }
-      print "Added Dbxref accession: $accession\n";
-      $dbxref = db_fetch_object(db_query($dbxsql,$db_id,$accession));
-   }
-   return $dbxref;
+ * Add Database Reference
+ * @ingroup tripal_obo_loader
+ */
+function tripal_cv_obo_add_dbxref($db_id, $accession, $version='', $description='') {
+
+  // check to see if the dbxref exists if not, add it
+  $dbxsql = "SELECT dbxref_id FROM {dbxref} WHERE db_id = %d and accession = '%s'";
+  $dbxref = db_fetch_object(db_query($dbxsql, $db_id, $accession));
+  if (!$dbxref) {
+    $sql = "
+       INSERT INTO {dbxref} (db_id, accession, version, description)
+       VALUES (%d,'%s','%s','%s')
+    ";
+    if (!db_query($sql, $db_id, $accession, $version, $description)) {
+      tripal_cv_obo_quiterror("Failed to insert the dbxref record $accession");
+    }
+    print "Added Dbxref accession: $accession\n";
+    $dbxref = db_fetch_object(db_query($dbxsql, $db_id, $accession));
+  }
+  return $dbxref;
 
 }
 

+ 371 - 341
tripal_cv/trees.php

@@ -1,22 +1,29 @@
 <?php
 
 /**
-*
-* @ingroup tripal_cv
-*/
+ * @file
+ * @todo Stephen describe this file
+ */
+
+/**
+ * Renders the cv_list form
+ *
+ * @ingroup tripal_cv
+ */
 function tripal_cv_show_browser() {
-  
-   $content = drupal_get_form('tripal_cv_list_form');
-   $content .= "
-      <div id=\"cv_browser\"></div>
-   ";
-   return $content;
+
+  $content = drupal_get_form('tripal_cv_list_form');
+  $content .= "
+    <div id=\"cv_browser\"></div>
+  ";
+
+  return $content;
 }
 
 
 /**
  * Generates JSON used for generating an exapandable tree of terms from
- * a controlled vocabulary that has associated counts. 
+ * a controlled vocabulary that has associated counts.
  *
  * The progammer must first create a materialized view that
  * will generate count data for a given controlled vocabulary.  For example, the Tripal
@@ -30,24 +37,24 @@ function tripal_cv_show_browser() {
  *  tripal_[module_name]_cv_tree_[unique id]
  *
  * where [module_name] is the name of the tripal module (e.g. tripal_analyisis_go)
- * and [unique id] is some unique identifier that the contolling module 
+ * and [unique id] is some unique identifier that the contolling module
  * recognizes. This string is the $tree_id variable passed as the first argument
- * to the function.  For example, the Tripal GO Analysis module generates 
+ * to the function.  For example, the Tripal GO Analysis module generates
  * tree ids of the form:
- * 
+ *
  *  tripal_analysis_go_cv_tree_10_2_bp
- * 
+ *
  * In this case the module that will manage this tree is identified as 'tripal_analysis_go' and within
  * the [unique id] portion contains the
- * organism_id (e.g. 10), analysis_id (e.g. 2) and tree type (bp = biological process). 
+ * organism_id (e.g. 10), analysis_id (e.g. 2) and tree type (bp = biological process).
  *
  * Second, the programmer must then define a hook in the controlling module for setting
  * some options used to build the chart.  The hook has the form:  hook_cv_tree($tree_id).
  * This hook should accept the full $tree_id as the single parameter.  For the Tripal
- * Analysis GO module the hook is named:  tripal_analysis_go_cv_tree.  
+ * Analysis GO module the hook is named:  tripal_analysis_go_cv_tree.
  *
- * The array returned by this hook must have the following fields: 
- *  - cv_id 
+ * The array returned by this hook must have the following fields:
+ *  - cv_id
  *      the cv_id for the controlled vocabulary
  *  - count_mview
  *      the name of the materialized view that contains the count data
@@ -68,22 +75,22 @@ function tripal_cv_show_browser() {
  *
  * Example from the tripal_analysis_go module:
  * @code
- *  function tripal_analysis_go_cv_tree($tree_id){
- * 
+ *  function tripal_analysis_go_cv_tree($tree_id) {
+ *
  *   $organism_id = preg_replace("/^tripal_analysis_go_cv_tree_(\d+)-(\d+)_(bp|cc|mf)$/","$1",$tree_id);
  *   $analysis_id = preg_replace("/^tripal_analysis_go_cv_tree_(\d+)-(\d+)_(bp|cc|mf)$/","$2",$tree_id);
  *   $type        = preg_replace("/^tripal_analysis_go_cv_tree_(\d+)-(\d+)_(bp|cc|mf)$/","$3",$tree_id);
- * 
- *   if(strcmp($type,'mf')==0){
+ *
+ *   if(strcmp($type,'mf')==0) {
  *      $class = 'molecular_function';
  *   }
- *   if(strcmp($type,'cc')==0){
+ *   if(strcmp($type,'cc')==0) {
  *      $class = 'cellular_component';
  *   }
- *   if(strcmp($type,'bp')==0){
+ *   if(strcmp($type,'bp')==0) {
  *      $class = 'biological_process';
  *   }
- * 
+ *
  *   $options = array(
  *      cv_id            => tripal_cv_get_cv_id($class),
  *      count_mview      => 'go_count_analysis',
@@ -108,350 +115,373 @@ function tripal_cv_show_browser() {
  *
  * @ingroup tripal_cv
  */
-function tripal_cv_tree($tree_id){
-  // parse out the tripal module name from the chart_id to find out 
+function tripal_cv_tree($tree_id) {
+  // parse out the tripal module name from the chart_id to find out
   // which Tripal "hook" to call:
-  $tripal_mod = preg_replace("/^(tripal_.+?)_cv_tree_(.+)$/","$1",$tree_id);
-  if($tripal_mod){
-     $callback = $tripal_mod . "_cv_tree";
+  $tripal_mod = preg_replace("/^(tripal_.+?)_cv_tree_(.+)$/", "$1", $tree_id);
+  if ($tripal_mod) {
+    $callback = $tripal_mod . "_cv_tree";
 
-     // now call the function in the module responsible for the tree.  This 
-     // should call the tripal_cv_init_cv with the proper parameters set for
-     // getting the cv_id of the vocabulary to use
-     $opt = call_user_func_array($callback,array($tree_id));
+    // now call the function in the module responsible for the tree.  This
+    // should call the tripal_cv_init_cv with the proper parameters set for
+    // getting the cv_id of the vocabulary to use
+    $opt = call_user_func_array($callback, array($tree_id));
 
-     // we only need to return the cv_id for this function call.
-     $json_array[] = $opt[cv_id];
+    // we only need to return the cv_id for this function call.
+    $json_array[] = $opt['cv_id'];
   }
+
   $json_array[] = $tree_id;
   return drupal_json($json_array);
 }
 
 
 /**
-*
-* @ingroup tripal_cv
-*/
+ *
+ * @ingroup tripal_cv
+ */
 function tripal_cv_update_tree() {
-   $content = array();
-   $ontology = 'sequence';
-
-   # get the id of the term to look up
-   $cv = check_plain($_REQUEST['cv']);
-   $term = check_plain($_REQUEST['term']);
-   $tree_id = check_plain($_REQUEST['tree_id']);
-
-   # get the options needed for this tree from the tripal module that 
-   # wants to create the tree
-   $tripal_mod = preg_replace("/^(tripal_.+?)_cv_tree_(.+)$/","$1",$tree_id);
-   if($tripal_mod){
-      $callback = $tripal_mod . "_cv_tree";
-      $opt = call_user_func_array($callback,array($tree_id));
-   }
-
-   # get the CV root terms
-   if(strcmp($term,'root')==0){
-      if(!$cv){
-        $cv = $opt[cv_id];
-      }
-      $content = tripal_cv_init_tree($cv,$opt[count_mview],
-         $opt[cvterm_id_column],$opt[count_column],$opt[filter],$opt[label]);
-   } 
-   # get the children terms
-   else {
-      $content = tripal_cv_get_term_children($term,$opt[count_mview],
-         $opt[cvterm_id_column],$opt[count_column],$opt[filter],$opt[label]);
-   }
-   drupal_json($content);
+  $content = array();
+  $ontology = 'sequence';
+
+  // get the id of the term to look up
+  $cv = check_plain($_REQUEST['cv']);
+  $term = check_plain($_REQUEST['term']);
+  $tree_id = check_plain($_REQUEST['tree_id']);
+
+  // get the options needed for this tree from the tripal module that
+  // wants to create the tree
+  $tripal_mod = preg_replace("/^(tripal_.+?)_cv_tree_(.+)$/", "$1", $tree_id);
+  if ($tripal_mod) {
+    $callback = $tripal_mod . "_cv_tree";
+    $opt = call_user_func_array($callback, array($tree_id));
+  }
+
+  // get the CV root terms
+  if (strcmp($term, 'root')==0) {
+    if (!$cv) {
+      $cv = $opt['cv_id'];
+    }
+    $content = tripal_cv_init_tree($cv, $opt['count_mview'],
+      $opt['cvterm_id_column'], $opt['count_column'], $opt['filter'], $opt['label']);
+
+  // get the children terms
+  }
+  else {
+    $content = tripal_cv_get_term_children($term, $opt['count_mview'],
+      $opt['cvterm_id_column'], $opt['count_column'], $opt['filter'], $opt['label']);
+  }
+
+  drupal_json($content);
 }
+
 /**
-* Generates JSON needed for jsTree Root-level Branches
-*
-* This function returns the JSON array for the jsTree 
-*    jQuery code that builds a tree for browsing the ontology.  This function
-*    should be called to generate the root level branches of the tree.
-*
-* @ingroup tripal_cv
-*/
-function tripal_cv_init_tree($cv_id,$cnt_table = null, $fk_column = null,
-   $cnt_column = null, $filter = null, $label = null) {
-
-   // get the list of root terms for the provided CV
-   $sql = "
-      SELECT *
-      FROM {cv_root_mview} CRM
-      WHERE cv_id = %d
-   ";
-   $previous_db = tripal_db_set_active('chado');
-   $results = db_query($sql,$cv_id);
-   tripal_db_set_active($previous_db); 
-
-   // prepare the SQL statement that will allow us to pull out count 
-   // information for each term in the tree.
-   if($cnt_table){
-      if(!$filter){
-         $filter = '(1=1)'; 
+ * Generates JSON needed for jsTree Root-level Branches
+ *
+ * This function returns the JSON array for the jsTree
+ *    jQuery code that builds a tree for browsing the ontology.  This function
+ *    should be called to generate the root level branches of the tree.
+ *
+ * @ingroup tripal_cv
+ */
+function tripal_cv_init_tree($cv_id, $cnt_table = NULL, $fk_column = NULL,
+  $cnt_column = NULL, $filter = NULL, $label = NULL) {
+
+  // get the list of root terms for the provided CV
+  $sql = "
+    SELECT *
+    FROM {cv_root_mview} CRM
+    WHERE cv_id = %d
+  ";
+  $previous_db = tripal_db_set_active('chado');
+  $results = db_query($sql, $cv_id);
+  tripal_db_set_active($previous_db);
+
+  // prepare the SQL statement that will allow us to pull out count
+  // information for each term in the tree.
+  if ($cnt_table) {
+    if (!$filter) {
+      $filter = '(1=1)';
+    }
+    $cnt_sql = "
+       SELECT CVT.name, CVT.cvterm_id, CNT.$cnt_column as num_items
+       FROM {$cnt_table} CNT
+        INNER JOIN cvterm CVT on CNT.$fk_column = CVT.cvterm_id
+       WHERE $filter AND CVT.cvterm_id = %d
+       ORDER BY $cnt_column desc
+    ";
+  }
+
+  while ($term = db_fetch_object($results)) {
+    $name = $term->name;
+    $count = 0;
+    if ($cnt_table) {
+      $previous_db = tripal_db_set_active('chado');
+      $cnt_results = db_query($cnt_sql, $term->cvterm_id);
+      tripal_db_set_active($previous_db);
+      while ($cnt = db_fetch_object($cnt_results)) {
+        $count += $cnt->cnt;
       }
-      $cnt_sql = "
-         SELECT CVT.name, CVT.cvterm_id, CNT.$cnt_column as num_items
-         FROM {$cnt_table} CNT 
-          INNER JOIN cvterm CVT on CNT.$fk_column = CVT.cvterm_id 
-         WHERE $filter AND CVT.cvterm_id = %d
-         ORDER BY $cnt_column desc
-      ";
-   }
- 
-   while ($term = db_fetch_object($results)) {
-      $name = $term->name;
-      $count = 0;
-      if($cnt_table){
-         $previous_db = tripal_db_set_active('chado');
-         $cnt_results = db_query($cnt_sql,$term->cvterm_id);
-         tripal_db_set_active($previous_db); 
-         while($cnt = db_fetch_object($cnt_results)){
-            $count += $cnt->cnt;
-         }
-         if($count > 0){
-            $name .= " ($count $label(s))";
-         }
-      } 
-      $content[] = array(
-           'attributes' => array (
-           'id' => $term->cvterm_id,
-        ),
-        state => 'closed',
-        data => $name,
-        children => array (),
-      );
-   }
+      if ($count > 0) {
+        $name .= " ($count $label(s))";
+      }
+    }
+    $content[] = array(
+      'attributes' => array(
+        'id' => $term->cvterm_id,
+      ),
+      'state' => 'closed',
+      'data' => $name,
+      'children' => array(),
+    );
+  }
 
-   return $content;
+  return $content;
 
 }
+
 /**
-*  Generates SON needed for jsTree -expanding a term to view children
-*
-*  This function returns the JSON array for the jsTree 
-*    jQuery code when expanding a term to view it's children.
-*
-* @ingroup tripal_cv_api
-*/
-function tripal_cv_get_term_children($cvterm_id,$cnt_table = null, 
-   $fk_column = null,$cnt_column = null, $filter = null, $label = null) {
-   # get the children for the term provided
-   $sql = "
-      SELECT CVTR.cvterm_relationship_id,CVTR.subject_id,
-         CVT1.name as subject_name, CVT3.name as type_name, CVTR.type_id, 
-         CVT2.name as object_name,CVTR.object_id 
-      FROM {cvterm_relationship} CVTR
-         INNER JOIN CVTerm CVT1 on CVTR.subject_id = CVT1.cvterm_id
-         INNER JOIN CVTerm CVT2 on CVTR.object_id = CVT2.cvterm_id
-         INNER JOIN CVTerm CVT3 on CVTR.type_id = CVT3.cvterm_id
-         INNER JOIN CV on CV.cv_id = CVT1.cv_id
-      WHERE CVTR.object_id = %d
-      ORDER BY CVT1.name
-   ";
-   $previous_db = tripal_db_set_active('chado');
-   $results = db_query($sql,$cvterm_id);
-   tripal_db_set_active($previous_db);
-
-
-   // prepare the SQL statement that will allow us to pull out count 
-   // information for each term in the tree.
-   if($cnt_table){
-      if(!$filter){
-         $filter = '(1=1)'; 
+ *  Generates SON needed for jsTree -expanding a term to view children
+ *
+ *  This function returns the JSON array for the jsTree
+ *    jQuery code when expanding a term to view it's children.
+ *
+ * @ingroup tripal_cv_api
+ */
+function tripal_cv_get_term_children($cvterm_id, $cnt_table = NULL,
+  $fk_column = NULL, $cnt_column = NULL, $filter = NULL, $label = NULL) {
+
+  // get the children for the term provided
+  $sql = "
+    SELECT CVTR.cvterm_relationship_id,CVTR.subject_id,
+       CVT1.name as subject_name, CVT3.name as type_name, CVTR.type_id,
+       CVT2.name as object_name,CVTR.object_id
+    FROM {cvterm_relationship} CVTR
+       INNER JOIN CVTerm CVT1 on CVTR.subject_id = CVT1.cvterm_id
+       INNER JOIN CVTerm CVT2 on CVTR.object_id = CVT2.cvterm_id
+       INNER JOIN CVTerm CVT3 on CVTR.type_id = CVT3.cvterm_id
+       INNER JOIN CV on CV.cv_id = CVT1.cv_id
+    WHERE CVTR.object_id = %d
+    ORDER BY CVT1.name
+  ";
+  $previous_db = tripal_db_set_active('chado');
+  $results = db_query($sql, $cvterm_id);
+  tripal_db_set_active($previous_db);
+
+
+  // prepare the SQL statement that will allow us to pull out count
+  // information for each term in the tree.
+  if ($cnt_table) {
+    if (!$filter) {
+      $filter = '(1=1)';
+    }
+    $cnt_sql = "
+       SELECT CVT.name, CVT.cvterm_id, CNT.$cnt_column as num_items
+       FROM {$cnt_table} CNT
+        INNER JOIN cvterm CVT on CNT.$fk_column = CVT.cvterm_id
+       WHERE $filter AND CVT.cvterm_id = %d
+       ORDER BY $cnt_column desc
+    ";
+  }
+
+  // populate the JSON content array
+  while ($term = db_fetch_object($results)) {
+    // count the number of items per term if requested
+    $name = $term->subject_name;
+    $count = 0;
+    if ($cnt_table) {
+      $previous_db = tripal_db_set_active('chado');
+      $cnt_results = db_query($cnt_sql, $term->subject_id);
+      tripal_db_set_active($previous_db);
+      while ($cnt = db_fetch_object($cnt_results)) {
+        $count += $cnt->num_items;
+      }
+      if ($count > 0) {
+        $name .= " (" . number_format($count) . " $label)";
+
+        // check if we have any children if so then set the value
+        $previous_db = tripal_db_set_active('chado');
+        $children = db_fetch_object(db_query($sql, $term->subject_id));
+        tripal_db_set_active($previous_db);
+        $state = 'leaf';
+        if ($children) {
+          $state = 'closed';
+        }
+        $content[] = array(
+          'attributes' => array(
+            'id' => $term->subject_id,
+          ),
+          'state' => $state,
+          'data' => $name,
+          'children' => array(),
+        );
       }
-      $cnt_sql = "
-         SELECT CVT.name, CVT.cvterm_id, CNT.$cnt_column as num_items
-         FROM {$cnt_table} CNT 
-          INNER JOIN cvterm CVT on CNT.$fk_column = CVT.cvterm_id 
-         WHERE $filter AND CVT.cvterm_id = %d
-         ORDER BY $cnt_column desc
-      ";
-   }
-   // populate the JSON content array
-   while ($term = db_fetch_object($results)) {
-      // count the number of items per term if requested
-      $name = $term->subject_name;
-      $count = 0;
-      if($cnt_table){
-         $previous_db = tripal_db_set_active('chado');
-         $cnt_results = db_query($cnt_sql,$term->subject_id);
-         tripal_db_set_active($previous_db); 
-         while($cnt = db_fetch_object($cnt_results)){
-            $count += $cnt->num_items;
-         }
-         if($count > 0){
-            $name .= " (".number_format($count)." $label)";
-            // check if we have any children if so then set the value
-            $previous_db = tripal_db_set_active('chado');
-            $children = db_fetch_object(db_query($sql,$term->subject_id));
-            tripal_db_set_active($previous_db);
-            $state = 'leaf';
-            if($children){
-               $state = 'closed';
-            }
-            $content[] = array(
-               'attributes' => array (
-                  'id' => $term->subject_id,
-               ),
-               state => $state,
-               data => $name,
-               children => array(),
-            );
-         }
-      } else {
-         // check if we have any children if so then set the value
-         $previous_db = tripal_db_set_active('chado');
-         $children = db_fetch_object(db_query($sql,$term->subject_id));
-         tripal_db_set_active($previous_db);
-         $state = 'leaf';
-         if($children){
-            $state = 'closed';
-         }
-         $content[] = array(
-            'attributes' => array (
-               'id' => $term->subject_id,
-            ),
-            state => $state,
-            data => $name,
-            children => array(),
-         );
+    }
+    else {
+      // check if we have any children if so then set the value
+      $previous_db = tripal_db_set_active('chado');
+      $children = db_fetch_object(db_query($sql, $term->subject_id));
+      tripal_db_set_active($previous_db);
+      $state = 'leaf';
+      if ($children) {
+        $state = 'closed';
       }
-   }
-   $content[] = $cnt_sql;
-   return $content;
+      $content[] = array(
+        'attributes' => array(
+           'id' => $term->subject_id,
+        ),
+        'state' => $state,
+        'data' => $name,
+        'children' => array(),
+      );
+    }
+  }
+  $content[] = $cnt_sql;
+
+  return $content;
 }
+
 /**
-* 
-* @ingroup tripal_cv
-*/
+ * @todo Stephen: describe what this function does
+ * @ingroup tripal_cv
+ */
 function tripal_cv_init_browser($cv_id) {
 
-   $content = "
-        <div id=\"tripal_cv_cvterm_info_box\">
-           <a href=\"#\" onclick=\"$('#tripal_cv_cvterm_info_box').hide()\" style=\"float: right\">Close [X]</a>
-           <h3>Term Information</h3>
-           <div id=\"tripal_cv_cvterm_info\"></div>
-        </div>
-        <div id=\"tripal_ajaxLoading\" style=\"display:none\">
-           <div id=\"loadingText\">Loading...</div>
-           <img src=\"$url\">
-        </div> 
-         <h3>Tree Browser</h3>
-        <div id=\"browser\"</div></div>
-   ";
-
-   drupal_json(array('update' => "$content"));
+  $content = "
+    <div id=\"tripal_cv_cvterm_info_box\">
+      <a href=\"#\" onclick=\"$('#tripal_cv_cvterm_info_box').hide()\" style=\"float: right\">Close [X]</a>
+      <h3>Term Information</h3>
+      <div id=\"tripal_cv_cvterm_info\"></div>
+    </div>
+    <div id=\"tripal_ajaxLoading\" style=\"display:none\">
+      <div id=\"loadingText\">Loading...</div>
+      <img src=\"$url\">
+    </div>
+    <h3>Tree Browser</h3>
+    <div id=\"browser\"</div>
+    </div>
+  ";
+
+  drupal_json(array('update' => "$content"));
+
 }
+
 /**
-*
-* @ingroup tripal_cv
-*/
-function tripal_cv_cvterm_info($cvterm_id){
-
-   # get the id of the term to look up
-   $cv = check_plain($_REQUEST['cv']);
-   $tree_id = check_plain($_REQUEST['tree_id']);
-
-   // first get any additional information to add to the cvterm
-   if(strcmp($tree_id,'undefined')!=0){
-      $tripal_mod = preg_replace("/^(tripal_.+?)_cv_tree_(.+)$/","$1",$tree_id);
-      if($tripal_mod){
-         $callback = $tripal_mod . "_cvterm_add";
-         $opt = call_user_func_array($callback,array($cvterm_id,$tree_id));
-      }
-   }
-
-   $sql = "
-      SELECT CVT.name as cvtermname, CVT.definition, CV.name as cvname,
-         DBX.accession,DB.urlprefix,DB.db_id,DB.name as dbname
-      FROM {CVTerm} CVT
-        INNER JOIN CV on CVT.cv_id = CV.cv_id
-        INNER JOIN dbxref DBX on CVT.dbxref_id = DBX.dbxref_id
-        INNER JOIN DB on DBX.db_id = DB.db_id
-      WHERE CVT.cvterm_id = %d
-   ";
-   $previous_db = tripal_db_set_active('chado');
-   $cvterm = db_fetch_object(db_query($sql,$cvterm_id));
-   tripal_db_set_active($previous_db);
-   $sql = "
-      SELECT CVTS.synonym, CVT.name as cvname
-      FROM {cvtermsynonym} CVTS
-        INNER JOIN cvterm CVT on CVTS.type_id = CVT.cvterm_id
-      WHERE CVTS.cvterm_id = %d
-    
-   ";
-   $previous_db = tripal_db_set_active('chado');
-   $results = db_query($sql,$cvterm_id);
-   tripal_db_set_active($previous_db);
-   while($synonym = db_fetch_object($results)){
-      $synonym_rows .= "<b>$synonym->cvname:</b>  $synonym->synonym<br>";
-   }
-   $accession = $cvterm->accession;
-   if($cvterm->urlprefix){
-      $accession = "<a href=\"$cvterm->urlprefix$cvterm->accession\">$cvterm->accession</a>";
-   }
-   $content = "
-      <div id=\"cvterm\">
-      <table>
-        <tr><th>Term</th><td>$cvterm->cvtermname</td></tr>
-        <tr><th>Accession</th><td>$accession</td></tr>
-        <tr><th>Ontology</th><td>$cvterm->cvname</td></tr>
-        <tr><th>Definition</th><td>$cvterm->definition</td></tr>
-        <tr><th>Synonyms</th><td>$synonym_rows</td></tr>
-        <tr><th>Internal ID</th><td>$cvterm_id</td></tr> 
-   ";
-
-   // now add in any additional options from a hook
-   if($opt){
-      foreach ($opt as $key=>$value){
-         $content .= "<tr><th>$key</th><td>$value</td>";
-      }
-   }
-
-   // close out the information table
-   $content .= "
-      </table>
-      </div>
-   ";
-   drupal_json(array('update' => $content));
+ * Describe a cvterm (Rendered)
+ *
+ * @ingroup tripal_cv
+ */
+function tripal_cv_cvterm_info($cvterm_id) {
+
+  // get the id of the term to look up
+  $cv = check_plain($_REQUEST['cv']);
+  $tree_id = check_plain($_REQUEST['tree_id']);
+
+  // first get any additional information to add to the cvterm
+  if (strcmp($tree_id, 'undefined') != 0) {
+    $tripal_mod = preg_replace("/^(tripal_.+?)_cv_tree_(.+)$/", "$1", $tree_id);
+    if ($tripal_mod) {
+      $callback = $tripal_mod . "_cvterm_add";
+      $opt = call_user_func_array($callback, array($cvterm_id, $tree_id));
+    }
+  }
+
+  $sql = "
+    SELECT CVT.name as cvtermname, CVT.definition, CV.name as cvname,
+       DBX.accession,DB.urlprefix,DB.db_id,DB.name as dbname
+    FROM {CVTerm} CVT
+      INNER JOIN CV on CVT.cv_id = CV.cv_id
+      INNER JOIN dbxref DBX on CVT.dbxref_id = DBX.dbxref_id
+      INNER JOIN DB on DBX.db_id = DB.db_id
+    WHERE CVT.cvterm_id = %d
+  ";
+  $previous_db = tripal_db_set_active('chado');
+  $cvterm = db_fetch_object(db_query($sql, $cvterm_id));
+  tripal_db_set_active($previous_db);
+
+  $sql = "
+    SELECT CVTS.synonym, CVT.name as cvname
+    FROM {cvtermsynonym} CVTS
+      INNER JOIN cvterm CVT on CVTS.type_id = CVT.cvterm_id
+    WHERE CVTS.cvterm_id = %d
+
+  ";
+  $previous_db = tripal_db_set_active('chado');
+  $results = db_query($sql, $cvterm_id);
+  tripal_db_set_active($previous_db);
+  while ($synonym = db_fetch_object($results)) {
+    $synonym_rows .= "<b>$synonym->cvname:</b>  $synonym->synonym<br />";
+  }
+
+  $accession = $cvterm->accession;
+  if ($cvterm->urlprefix) {
+    $accession = "<a href=\"$cvterm->urlprefix$cvterm->accession\">$cvterm->accession</a>";
+  }
+
+  $content = "
+    <div id=\"cvterm\">
+    <table>
+      <tr><th>Term</th><td>$cvterm->cvtermname</td></tr>
+      <tr><th>Accession</th><td>$accession</td></tr>
+      <tr><th>Ontology</th><td>$cvterm->cvname</td></tr>
+      <tr><th>Definition</th><td>$cvterm->definition</td></tr>
+      <tr><th>Synonyms</th><td>$synonym_rows</td></tr>
+      <tr><th>Internal ID</th><td>$cvterm_id</td></tr>
+  ";
+
+  // now add in any additional options from a hook
+  if ($opt) {
+    foreach ($opt as $key => $value) {
+      $content .= "<tr><th>$key</th><td>$value</td>";
+    }
+  }
+
+  // close out the information table
+  $content .= "
+    </table>
+    </div>
+  ";
+  drupal_json(array('update' => $content));
 }
+
 /**
-*
-* @ingroup tripal_cv
-*/
+ * Form listing CVs
+ *
+ * @ingroup tripal_cv
+ */
 function tripal_cv_list_form($form_state) {
 
-   // get a list of db from chado for user to choose
-    $sql = "
-      SELECT DISTINCT CV.name,CV.cv_id
-      FROM {cvterm_relationship} CVTR
-         INNER JOIN cvterm CVT on CVTR.object_id = CVT.cvterm_id
-         INNER JOIN CV on CV.cv_id = CVT.cv_id
-   ";
-   $previous_db = tripal_db_set_active('chado');  // use chado database
-   $results = db_query ($sql);
-   tripal_db_set_active($previous_db);
-   $blastdbs = array();
-   $cvs[''] = '';
-   while ($cv = db_fetch_object($results)){
-      $cvs[$cv->cv_id] = $cv->name;
-   }
-
-   $form['db_options'] = array(
-      '#type' => 'value',
-      '#value' => $cvs
-   );        
-   $form['cv_list'] = array(
-      '#title' => t('CVs with relationships'),
-      '#type' => 'select',
-      '#description' => t('Choose the controlled vocabulary to browse'),
-      '#options' => $form['db_options']['#value'],
-      '#attributes' => array(
-         'onChange' => "return tripal_cv_init_browser(this)",
-      )
-   );
-   return $form;
+  // get a list of db from chado for user to choose
+  $sql = "
+    SELECT DISTINCT CV.name,CV.cv_id
+    FROM {cvterm_relationship} CVTR
+       INNER JOIN cvterm CVT on CVTR.object_id = CVT.cvterm_id
+       INNER JOIN CV on CV.cv_id = CVT.cv_id
+  ";
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  $results = db_query($sql);
+  tripal_db_set_active($previous_db);
+
+  $blastdbs = array();
+  $cvs[''] = '';
+  while ($cv = db_fetch_object($results)) {
+    $cvs[$cv->cv_id] = $cv->name;
+  }
+
+  $form['db_options'] = array(
+    '#type' => 'value',
+    '#value' => $cvs
+  );
+
+  $form['cv_list'] = array(
+    '#title' => t('CVs with relationships'),
+    '#type' => 'select',
+    '#description' => t('Choose the controlled vocabulary to browse'),
+    '#options' => $form['db_options']['#value'],
+    '#attributes' => array(
+      'onChange' => "return tripal_cv_init_browser(this)",
+    )
+  );
+
+  return $form;
 }

+ 306 - 300
tripal_cv/tripal_cv.api.inc

@@ -1,15 +1,18 @@
 <?php
 
 /**
+ * @file
+ * Controlled Vocabulary API
+ *
  * @defgroup tripal_cv_api CV Module API
  * @ingroup tripal_api
  * @ingroup tripal_cv
  * This module provides a set of functions to simplify working with
  * controlled vocabularies.  Most of the API functions deal with retrieving
- * terms or their parent vocabularies.  
- * 
+ * terms or their parent vocabularies.
+ *
  * However, the API also supports
- * generation of trees for browsing a vocabulary as well as generation of 
+ * generation of trees for browsing a vocabulary as well as generation of
  * pie graphs for display of hierarchical counts of terms.  Version 0.3b of
  * Tripal provides a feature browser and a feature summary chart uses
  * the API functions provided here.  But in general charts and trees can be
@@ -27,7 +30,7 @@
  *   Chado controlled vocabulary object
  *
  * The controlled vocabulary is selected using tripal_core_chado select and as such the
- * $select_values array parameter meant to uniquely identify the controlled vocab to be 
+ * $select_values array parameter meant to uniquely identify the controlled vocab to be
  * returned follows the same form as when using tripal_core_chado_select directly.
  *
  * Example Usage:
@@ -39,55 +42,57 @@
  * @endcode
  *  The above code selects the feature_property cv and returns the following object:
  * @code
-    $cv_object = stdClass Object ( 
+    $cv_object = stdClass Object (
       [cv_id] => 13
       [name] => feature_property
-      [definition] => 
-    ); 
+      [definition] =>
+    );
  * @endcode
  *
  * @ingroup tripal_cv_api
  */
-function tripal_cv_get_cv ($select_values) {
+function tripal_cv_get_cv($select_values) {
 
   $columns = array(
-    'cv_id', 
-    'name', 
-    'definition', 
+    'cv_id',
+    'name',
+    'definition',
   );
   $results = tripal_core_chado_select('cv', $columns, $select_values);
   if (sizeof($results) == 1) {
     return $results[0];
-  } elseif (empty($results)) {
-    watchdog('tripal_cv', 
+  }
+  elseif (empty($results)) {
+    watchdog('tripal_cv',
       'tripal_cv_get_cv: No cv matches criteria values:%values',
       array('%values' => print_r($select_values, TRUE)),
       WATCHDOG_WARNING
     );
     return FALSE;
-  } else {
-    watchdog('tripal_cv', 
+  }
+  else {
+    watchdog('tripal_cv',
       'tripal_cv_get_cv: 2+ cvs match criteria values:%values',
       array('%values' => print_r($select_values, TRUE)),
       WATCHDOG_WARNING
     );
   }
-  
+
 }
 
 // Purpose: To retrieve a chado cv object
-// @param $where_options 
+// @param $where_options
 //   @code
 //        array(
-//													<column_name> => array(
-//														'type' => <type of column: INT/STRING>,
-//														'value' => <the vlaue you want to filter on>,
-//														'exact' => <if TRUE use =; if FALSE use ~>,
-//													)
-//				)
+//                          <column_name> => array(
+//                            'type' => <type of column: INT/STRING>,
+//                            'value' => <the vlaue you want to filter on>,
+//                            'exact' => <if TRUE use =; if FALSE use ~>,
+//                          )
+//        )
 // @endcode
 //
-// @return 
+// @return
 //   Chado cv object with all fields from the chado cv table
 //
 // @ingroup tripal_cv_api
@@ -99,24 +104,25 @@ function tripal_cv_get_cv ($select_values) {
  *
  * @param $name
  *  The name of the cv to be returned
- * @return 
+ * @return
  *   The cv object for the specified CV name
  *
- * @ingroup tripal_cv_api 
+ * @ingroup tripal_cv_api
  */
-function tripal_cv_get_cv_by_name ($name) {
-	$previous_db = tripal_db_set_active('chado');	
-   $r = db_fetch_object(db_query("SELECT * FROM cv WHERE name = '%s'",$name));
-   tripal_db_set_active($previous_db);
+function tripal_cv_get_cv_by_name($name) {
 
-  return $r;
+  $previous_db = tripal_db_set_active('chado');
+  $r = tripal_core_chado_select('cv', array('*'), array('name' => $name));
+  tripal_db_set_active($previous_db);
+
+  return $r[0];
 }
 
 /**
  * Retrieve the cv object for the specified CV id
  *
  * NOTE: This function is deprecated.
- * @see tripal_core_chado_generate_vars
+ * @see tripal_core_chado_generate_vars()
  *
  * @param $cv_id
  *   The unique identifier for the cv retrieve
@@ -126,10 +132,11 @@ function tripal_cv_get_cv_by_name ($name) {
  *
  * @ingroup tripal_cv_api
  */
-function tripal_cv_get_cv_by_id ($cv_id) {
-	$previous_db = tripal_db_set_active('chado');	
-   $r = db_fetch_object(db_query("SELECT * FROM cv WHERE cv_id = %d",$cv_id));
-   tripal_db_set_active($previous_db);
+function tripal_cv_get_cv_by_id($cv_id) {
+
+  $previous_db = tripal_db_set_active('chado');
+  $r = tripal_core_chado_select('cv', array('*'), array('cv_id' => $cv_id));
+  tripal_db_set_active($previous_db);
 
   return $r;
 }
@@ -137,21 +144,17 @@ function tripal_cv_get_cv_by_id ($cv_id) {
 /**
  * Create an options array to be used in a form element which provides a list of all chado cvs
  *
- * @return 
+ * @return
  *   An array(cv_id => name) for each cv in the chado cv table
  *
  * @ingroup tripal_cv_api
  */
 function tripal_cv_get_cv_options() {
 
-  $previous_db = tripal_db_set_active('chado');
-  $result = db_query(
-    "SELECT cv_id, name FROM cv"
-  );
-  tripal_db_set_active($previous_db);
+  $results = tripal_core_chado_select('cv', array('cv_id', 'name'), array());
 
   $options = array();
-  while ( $r = db_fetch_object($result) ) {
+  foreach ($results as $r) {
     $options[$r->cv_id] = $r->name;
   }
 
@@ -169,41 +172,41 @@ function tripal_cv_get_cv_options() {
  * @param $cv_name
  *   the name of the CV
  *
- * @return 
+ * @return
  *   cvterm object
  *
  * @ingroup tripal_cv_api
  */
-function tripal_cv_get_cvterm_by_name ($name, $cv_id=0,$cv_name='tripal') {
+function tripal_cv_get_cvterm_by_name($name, $cv_id = 0, $cv_name = 'tripal') {
 
   if ($cv_id) {
     $values = array(
        'name' => $name,
        'cv_id' => $cv_id,
     );
-    $r = tripal_core_chado_select('cvterm',array('*'),$values);
-  } 
-  elseif($cv_name){
+    $r = tripal_core_chado_select('cvterm', array('*'), $values);
+  }
+  elseif ($cv_name) {
     $values = array(
-       'name' => $name,
-       'cv_id' => array(
-          'name' => $cv_name,
-       ),
+      'name' => $name,
+      'cv_id' => array(
+        'name' => $cv_name,
+      ),
     );
-    $r = tripal_core_chado_select('cvterm',array('*'),$values);
+    $r = tripal_core_chado_select('cvterm', array('*'), $values);
   }
   else {
     $values = array(
-       'name' => $name,
+      'name' => $name,
     );
-    $r = tripal_core_chado_select('cvterm',array('*'),$values);
+    $r = tripal_core_chado_select('cvterm', array('*'), $values);
   }
-  
-  if(!$r){
-     return FALSE;
+
+  if (!$r) {
+    return FALSE;
   }
-  if(count($r) > 0){
-     return FALSE;
+  if (count($r) > 0) {
+    return FALSE;
   }
   return $r[0];
 }
@@ -211,32 +214,27 @@ function tripal_cv_get_cvterm_by_name ($name, $cv_id=0,$cv_name='tripal') {
 /**
  * Create an options array to be used in a form element
  *   which provides a list of all chado cvterms
- * 
- * @param $cv_id 
+ *
+ * @param $cv_id
  *   The chado cv_id;
  *   only cvterms with the supplied cv_id will be returned
- * @return 
- *   An array(cvterm_id => name) 
+ * @return
+ *   An array(cvterm_id => name)
  *   for each cvterm in the chado cvterm table where cv_id=that supplied
  *
  * @ingroup tripal_cv_api
  */
 function tripal_cv_get_cvterm_options($cv_id = 0) {
 
-  $previous_db = tripal_db_set_active('chado');
   if ($cv_id > 0) {
-  	$result = db_query(
-    	"SELECT cvterm_id, name FROM cvterm WHERE cv_id=%d", $cv_id
-  	);
-  } else {
-  	$result = db_query(
-    	"SELECT cvterm_id, name FROM cvterm"
-  	);
+    $results = tripal_core_chado_select('cvterm', array('cvterm_id', 'name'), array('cv_id' => $cv_id));
+  }
+  else {
+    $results = tripal_core_chado_select('cvterm', array('cvterm_id', 'name'), array());
   }
-  tripal_db_set_active($previous_db);
 
   $options = array();
-  while ( $r = db_fetch_object($result) ) {
+  foreach ($results as $r) {
     $options[$r->cvterm_id] = $r->name;
   }
 
@@ -252,7 +250,7 @@ function tripal_cv_get_cvterm_options($cv_id = 0) {
  * @return
  *    Array describing the cvterm table
  *
- * @ingroup tripal_schema_api 
+ * @ingroup tripal_schema_api
  */
 function tripal_cv_chado_cvterm_schema() {
   $description = array();
@@ -263,251 +261,259 @@ function tripal_cv_chado_cvterm_schema() {
           'cv_id' => 'cv_id',
         ),
   );
-      
+
   $description['foreign keys']['dbxref'] = array(
         'table' => 'dbxref',
         'columns' => array(
           'dbxref_id' => 'dbxref_id',
         ),
-  ); 
+  );
 
   return $description;
 }
 
 /**
-* Adds a controlled vocabular to the CV table of Chado.
-*
-* @param $name
-*   The name of the controlled vocabulary. These are typically all lower case
-*   with no special characters other than an undrescore (for spaces).
-* @param $comment
-*   A description or definition of the vocabulary.
-*
-* @return
-*   An object populated with fields from the newly added database.
-*
-* @ingroup tripal_cv_api
-*/
-function tripal_cv_add_cv($name,$comment){
-
- // see if the CV (default-namespace) exists already in the database
-   $vocab = $name;
-   $remark = $comment;
-   $cv_sql = "SELECT * FROM {cv} WHERE name = '%s'";
-   $cv = db_fetch_object(db_query($cv_sql,$vocab));
-
-   // if the CV exists then update it, otherwise insert
-   if(!$cv){
-      $sql = "INSERT INTO {cv} (name,definition) VALUES ('%s','%s')";
-      if(!db_query($sql,$vocab,$remark)){
-         watchdog('tripal_cv', "Failed to create the CV record",NULL,WATCHDOG_WARNING);
-         return 0;
-      }
-      $cv = db_fetch_object(db_query($cv_sql,$vocab));
-   } else {
-      $sql = "UPDATE {cv} SET definition = '%s' WHERE name ='%s'";
-      if(!db_query($sql,$remark,$vocab)){
-         watchdog('tripal_cv', "Failed to update the CV record",NULL,WATCHDOG_WARNING);
-         return 0;
-      }
-      $cv = db_fetch_object(db_query($cv_sql,$vocab));
-   }
-   return $cv;
+ * Adds a controlled vocabular to the CV table of Chado.
+ *
+ * @param $name
+ *   The name of the controlled vocabulary. These are typically all lower case
+ *   with no special characters other than an undrescore (for spaces).
+ * @param $comment
+ *   A description or definition of the vocabulary.
+ *
+ * @return
+ *   An object populated with fields from the newly added database.
+ *
+ * @ingroup tripal_cv_api
+ */
+function tripal_cv_add_cv($name, $comment) {
+
+  // see if the CV (default-namespace) exists already in the database
+  $vocab = $name;
+  $remark = $comment;
+  $cv_sql = "SELECT * FROM {cv} WHERE name = '%s'";
+  $cv = db_fetch_object(db_query($cv_sql, $vocab));
+
+  // if the CV exists then update it, otherwise insert
+  if (!$cv) {
+    $sql = "INSERT INTO {cv} (name,definition) VALUES ('%s','%s')";
+    if (!db_query($sql, $vocab, $remark)) {
+      watchdog('tripal_cv', "Failed to create the CV record", NULL, WATCHDOG_WARNING);
+      return FALSE;
+    }
+    $cv = db_fetch_object(db_query($cv_sql, $vocab));
+  }
+  else {
+    $sql = "UPDATE {cv} SET definition = '%s' WHERE name ='%s'";
+    if (!db_query($sql, $remark, $vocab)) {
+      watchdog('tripal_cv', "Failed to update the CV record", NULL, WATCHDOG_WARNING);
+      return FALSE;
+    }
+    $cv = db_fetch_object(db_query($cv_sql, $vocab));
+  }
+
+  return $cv;
 }
+
 /**
-*  Add's a CV term to the cvterm table.  If the parent CV does not exist then
-*  that too is added to the CV table.  If the cvterm is a relationship term
-*  then the $is_relationship argument should be set.  The function will try
-*  to first find the relationship in the relationship ontology for updating and
-*  if it can't be found will add the relationship to the __global CV.  All terms
-*  must also have a corresponding database.  This is specified in the term's
-*  ID just before the colon (e.g. GO:003824).  If the database does not exist
-*  in the DB table then it will be added automatically.  The accession (the 
-*  value just after the colon in the term's ID) will be added to the dbxref 
-*  table.  If the CVterm already exists and $update is set (default) then the
-*  cvterm is updated.  If the CVTerm already exists and $update is not set, then
-*  no changes are made and the CVTerm object is returned.
-*
-* @param $term
-*   An associative array with the following keys: 'id', 'name' and 'namespace',
-*   'is_obsolete', and 'def'.  Where 'id' is the term accession, 'name' is the 
-*   term name, 'namespace' is the CV name for the term, 'def' is the term 
-*   definition and 'is_obsolete' is present and set to 1 if the term is defunct.
-*   The 'id' must be of the form <DB>:<ACCESSION>, where <DB> is the name of
-*   the database to which the cvterm belongs and the <ACCESSION> is the 
-*   term's accession number in the database.
-* @param $defaultcv
-*   Optional. The CV name to which the term 
-*   belongs.  If this arugment is null or not provided then the function tries
-*   to find a record in the CV table with the same name provided in the 
-*   $term[namespace].  If this field is provided then it overrides what the 
-*   value in $term[namespace] 
-* @param $is_relationship
-*   If this term is a relationship term then this value should be 1.
-* @param $update
-*   By default this is set to 1.  If the term exists it is automatically updated.
-* @param $dbname
-*   In some cases the database name will not be part of the $term['id'] and it
-*   needs to be explicitly set.  Use this argument only if the database name
-*   cannot be specififed in the term ID (e.g. <DB>:<ACCESSION>).
-*
-* @return
-*   A CVTerm object  
-*
-* @ingroup tripal_cv_api
-*/
-function tripal_cv_add_cvterm($term,$defaultcv='',$is_relationship = 0,$update = 1,$dbname=NULL){
-
-   // get the term properties
-   $id = $term['id'];
-   $name = $term['name'];
-   $cvname = $term['namespace'];
-   $definition = preg_replace('/^\"(.*)\"/','\1',$term['def']);
-   $is_obsolete = 0;
-   if(isset($term['is_obsolete']) and  strcmp($term['is_obsolete'],'true')==0){
-     $is_obsolete = 1;
-   }
-   if(!$name and !$id){
-      watchdog('tripal_cv', "Cannot find cvterm without 'id' or 'name'",NULL,WATCHDOG_WARNING);
-      return 0;
-   }
-   if(!$id){
-      $id = $name;
-   }
-   if(!$name){
-      $name = $id;
-   }
-   if(!$cvname){
-      $cvname = $defaultcv;
-   }
-   // make sure the CV name exists
-   $cv = tripal_cv_add_cv($cvname,'');
-   if(!$cv){
-      watchdog('tripal_cv', "Cannot find namespace '$cvname' when adding/updating $id",NULL,WATCHDOG_WARNING);
-      return 0;
-   }
-
-   // this SQL statement will be used a lot to find a cvterm so just set it
-   // here for easy reference below.  Because CV terms can change their names
-   // but accessions don't change, the following SQL finds cvterms based on
-   // their accession rather than the name
-   $cvtermsql = "SELECT CVT.name, CVT.cvterm_id, DB.name as dbname, DB.db_id 
-                  FROM {cvterm} CVT
-                    INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
-                    INNER JOIN {db} DB on DBX.db_id = DB.db_id
-                    INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
-                  WHERE DBX.accession = '%s' and DB.name = '%s'";  
-
-   // get the accession and the database from the cvterm
-   if($dbname){
-      $accession = $id;
-   }
-   elseif(preg_match('/^.+?:.*$/',$id)){
-      $accession = preg_replace('/^.+?:(.*)$/','\1',$id);
-      $dbname = preg_replace('/^(.+?):.*$/','\1',$id);
-   } 
-   if($is_relationship and !$dbname){
-      $accession = $id;
-      // because this is a relationship cvterm first check to see if it 
-      // exists in the relationship ontology. If it does then return the cvterm.
-      //  If not then set the dbname to _global and we'll add it or find it there
-      $cvterm = db_fetch_object(db_query($cvtermsql,$accession,'OBO_REL'));
-      if($cvterm){
-         return $cvterm;
-      } else {
-         // next check if this term is in the _global ontology.  If it is then
-         // return it no matter what the original CV
-         $dbname = '_global';
-
-         $cvterm = db_fetch_object(db_query($cvtermsql,$accesion,$dbname));
-         if($cvterm){
-            return $cvterm;
-         }
+ *  Add's a CV term to the cvterm table.  If the parent CV does not exist then
+ *  that too is added to the CV table.  If the cvterm is a relationship term
+ *  then the $is_relationship argument should be set.  The function will try
+ *  to first find the relationship in the relationship ontology for updating and
+ *  if it can't be found will add the relationship to the __global CV.  All terms
+ *  must also have a corresponding database.  This is specified in the term's
+ *  ID just before the colon (e.g. GO:003824).  If the database does not exist
+ *  in the DB table then it will be added automatically.  The accession (the
+ *  value just after the colon in the term's ID) will be added to the dbxref
+ *  table.  If the CVterm already exists and $update is set (default) then the
+ *  cvterm is updated.  If the CVTerm already exists and $update is not set, then
+ *  no changes are made and the CVTerm object is returned.
+ *
+ * @param $term
+ *   An associative array with the following keys: 'id', 'name' and 'namespace',
+ *   'is_obsolete', and 'def'.  Where 'id' is the term accession, 'name' is the
+ *   term name, 'namespace' is the CV name for the term, 'def' is the term
+ *   definition and 'is_obsolete' is present and set to 1 if the term is defunct.
+ *   The 'id' must be of the form <DB>:<ACCESSION>, where <DB> is the name of
+ *   the database to which the cvterm belongs and the <ACCESSION> is the
+ *   term's accession number in the database.
+ * @param $defaultcv
+ *   Optional. The CV name to which the term
+ *   belongs.  If this arugment is null or not provided then the function tries
+ *   to find a record in the CV table with the same name provided in the
+ *   $term[namespace].  If this field is provided then it overrides what the
+ *   value in $term[namespace]
+ * @param $is_relationship
+ *   If this term is a relationship term then this value should be 1.
+ * @param $update
+ *   By default this is set to 1.  If the term exists it is automatically updated.
+ * @param $dbname
+ *   In some cases the database name will not be part of the $term['id'] and it
+ *   needs to be explicitly set.  Use this argument only if the database name
+ *   cannot be specififed in the term ID (e.g. <DB>:<ACCESSION>).
+ *
+ * @return
+ *   A CVTerm object
+ *
+ * @ingroup tripal_cv_api
+ */
+function tripal_cv_add_cvterm($term, $defaultcv='', $is_relationship = 0, $update = 1, $dbname=NULL) {
+
+  // get the term properties
+  $id = $term['id'];
+  $name = $term['name'];
+  $cvname = $term['namespace'];
+  $definition = preg_replace('/^\"(.*)\"/', '\1', $term['def']);
+  $is_obsolete = 0;
+  if (isset($term['is_obsolete']) and  strcmp($term['is_obsolete'], 'true') == 0) {
+    $is_obsolete = 1;
+  }
+  if (!$name and !$id) {
+    watchdog('tripal_cv', "Cannot find cvterm without 'id' or 'name'", NULL, WATCHDOG_WARNING);
+    return 0;
+  }
+  if (!$id) {
+    $id = $name;
+  }
+  if (!$name) {
+    $name = $id;
+  }
+  if (!$cvname) {
+    $cvname = $defaultcv;
+  }
+  // make sure the CV name exists
+  $cv = tripal_cv_add_cv($cvname, '');
+  if (!$cv) {
+    watchdog('tripal_cv', "Cannot find namespace '$cvname' when adding/updating $id", NULL, WATCHDOG_WARNING);
+    return 0;
+  }
+
+  // this SQL statement will be used a lot to find a cvterm so just set it
+  // here for easy reference below.  Because CV terms can change their names
+  // but accessions don't change, the following SQL finds cvterms based on
+  // their accession rather than the name
+  $cvtermsql = "SELECT CVT.name, CVT.cvterm_id, DB.name as dbname, DB.db_id
+                FROM {cvterm} CVT
+                  INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
+                  INNER JOIN {db} DB on DBX.db_id = DB.db_id
+                  INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
+                WHERE DBX.accession = '%s' and DB.name = '%s'";
+
+  // get the accession and the database from the cvterm
+  if ($dbname) {
+    $accession = $id;
+  }
+  elseif (preg_match('/^.+?:.*$/', $id)) {
+    $accession = preg_replace('/^.+?:(.*)$/', '\1', $id);
+    $dbname = preg_replace('/^(.+?):.*$/', '\1', $id);
+  }
+  if ($is_relationship and !$dbname) {
+    $accession = $id;
+    // because this is a relationship cvterm first check to see if it
+    // exists in the relationship ontology. If it does then return the cvterm.
+    //  If not then set the dbname to _global and we'll add it or find it there
+    $cvterm = db_fetch_object(db_query($cvtermsql, $accession, 'OBO_REL'));
+    if ($cvterm) {
+      return $cvterm;
+    }
+    else {
+      // next check if this term is in the _global ontology.  If it is then
+      // return it no matter what the original CV
+      $dbname = '_global';
+
+      $cvterm = db_fetch_object(db_query($cvtermsql, $accesion, $dbname));
+      if ($cvterm) {
+        return $cvterm;
       }
-   }
-   if(!$is_relationship and !$dbname){
-      watchdog('tripal_cv', "A database identifier is missing from the term: $id",NULL,WATCHDOG_WARNING);
-      return 0;
-   }
+    }
+  }
+  if (!$is_relationship and !$dbname) {
+    watchdog('tripal_cv', "A database identifier is missing from the term: $id", NULL, WATCHDOG_WARNING);
+    return 0;
+  }
 
-   // add the database. The function will just return the DB object if the
-   // database already exists. 
-   $db = tripal_db_add_db($dbname);
-   if(!$db){
-      watchdog('tripal_cv', "Cannot find database '$dbname' in Chado.",NULL,WATCHDOG_WARNING);
-      return 0;
-   }
+  // add the database. The function will just return the DB object if the
+  // database already exists.
+  $db = tripal_db_add_db($dbname);
+  if (!$db) {
+    watchdog('tripal_cv', "Cannot find database '$dbname' in Chado.", NULL, WATCHDOG_WARNING);
+    return 0;
+  }
 
 
-   // if the cvterm doesn't exist then add it otherwise just update it
-   $cvterm = db_fetch_object(db_query($cvtermsql,$accession,$dbname));
-   if(!$cvterm){
-      // check to see if the dbxref exists if not, add it
-      $dbxref =  tripal_db_add_dbxref($db->db_id,$accession);
-      if(!$dbxref){
-         watchdog('tripal_cv', "Failed to find or insert the dbxref record for cvterm, $name (id: $accession), for database $dbname",NULL,WATCHDOG_WARNING);
-         return 0;
-      }
+  // if the cvterm doesn't exist then add it otherwise just update it
+  $cvterm = db_fetch_object(db_query($cvtermsql, $accession, $dbname));
+  if (!$cvterm) {
+    // check to see if the dbxref exists if not, add it
+    $dbxref =  tripal_db_add_dbxref($db->db_id, $accession);
+    if (!$dbxref) {
+      watchdog('tripal_cv', "Failed to find or insert the dbxref record for cvterm, $name (id: $accession), for database $dbname", NULL, WATCHDOG_WARNING);
+      return 0;
+    }
 
-      // check to see if the dbxref already has an entry in the cvterm table
-      $sql = "SELECT * FROM {cvterm} WHERE dbxref_id = %d";
-      $check = db_fetch_object(db_query($sql,$dbxref->dbxref_id));
-      if(!$check){
-         // now add the cvterm
-         $sql = "
-            INSERT INTO {cvterm} (cv_id, name, definition, dbxref_id, 
-               is_obsolete, is_relationshiptype) 
-            VALUES (%d,'%s','%s',%d,%d,%d)
-         ";
-         if(!db_query($sql,$cv->cv_id,$name,$definition,
-             $dbxref->dbxref_id,$is_obsolete,$is_relationship)){
-            if(!$is_relationship){
-               watchdog('tripal_cv', "Failed to insert the term: $name ($dbname)",NULL,WATCHDOG_WARNING);
-               return 0;
-            } else {
-               watchdog('tripal_cv', "Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)",NULL,WATCHDOG_WARNING);
-               return 0;
-            }
-         }  
-      }
-      // if the dbxref already exists check to make sure it exists for the correct databaes name
-      // if it does then we're good and we don't need to do anything
-      elseif($check and strcmp($check->name,$name)==0){
-         // this entry already exists. We're good, so do nothing
-      }
-      // if the dbxref exists but does not map to the same database name
-      elseif($check and strcmp($check->name,$name)!=0){
-         watchdog('tripal_cv', "The dbxref already exists in the cvterm table. DBXREF ID: $dbxref->dbxref_id, ACCESSION: $accession. DB:  '".$dbxref->db_name ."'. term '$name'. The requested db was '$dbname'",NULL,WATCHDOG_WARNING);
-         return 0;
-      }
-      $cvterm = db_fetch_object(db_query($cvtermsql,$name,$dbname));
-      if(!$is_relationship){
-         print "Added CV term: $name ($dbname)\n";
-      } else {
-         print "Added relationship CV term: $name ($dbname)\n";
-      }
-   }
-   elseif($update) { // update the cvterm
+    // check to see if the dbxref already has an entry in the cvterm table
+    $sql = "SELECT * FROM {cvterm} WHERE dbxref_id = %d";
+    $check = db_fetch_object(db_query($sql, $dbxref->dbxref_id));
+    if (!$check) {
+      // now add the cvterm
       $sql = "
-         UPDATE {cvterm} SET name='%s', definition='%s',
-            is_obsolete = %d, is_relationshiptype = %d
-         WHERE cvterm_id = %d
+        INSERT INTO {cvterm} (cv_id, name, definition, dbxref_id,
+           is_obsolete, is_relationshiptype)
+        VALUES (%d,'%s','%s',%d,%d,%d)
       ";
-      if(!db_query($sql,$term['name'],$definition,
-          $is_obsolete,$is_relationship,$cvterm->cvterm_id)){
-         watchdog('tripal_cv', "Failed to update the term: $name",NULL,WATCHDOG_WARNING);
-         return 0;
-
-      }  
-      $cvterm = db_fetch_object(db_query($cvtermsql,$name,$dbname));         
-      if(!$is_relationship){
-         print "Updated CV term: $name ($dbname)\n";
-      } else {
-         print "Updated relationship CV term: $name ($dbname)\n";
+      if (!db_query($sql, $cv->cv_id, $name, $definition, $dbxref->dbxref_id, $is_obsolete, $is_relationship)) {
+        if (!$is_relationship) {
+          watchdog('tripal_cv', "Failed to insert the term: $name ($dbname)", NULL, WATCHDOG_WARNING);
+          return 0;
+        }
+        else {
+          watchdog('tripal_cv', "Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)", NULL, WATCHDOG_WARNING);
+          return 0;
+        }
       }
-   }
-   // return the cvterm
-   return $cvterm;
+    }
+    // if the dbxref already exists check to make sure it exists for the correct databaes name
+    // if it does then we're good and we don't need to do anything
+    elseif ($check and strcmp($check->name, $name) == 0) {
+      // this entry already exists. We're good, so do nothing
+    }
+    // if the dbxref exists but does not map to the same database name
+    elseif ($check and strcmp($check->name, $name) != 0) {
+      watchdog(
+        'tripal_cv',
+        "The dbxref already exists in the cvterm table. DBXREF ID: $dbxref->dbxref_id, ACCESSION: $accession. DB:  '" . $dbxref->db_name . "'. term '$name'. The requested db was '$dbname'",
+        NULL,
+        WATCHDOG_WARNING);
+      return FALSE;
+    }
+    $cvterm = db_fetch_object(db_query($cvtermsql, $name, $dbname));
+    if (!$is_relationship) {
+      print "Added CV term: $name ($dbname)\n";
+    }
+    else {
+      print "Added relationship CV term: $name ($dbname)\n";
+    }
+  }
+  elseif ($update) { // update the cvterm
+    $sql = "
+       UPDATE {cvterm} SET name='%s', definition='%s',
+          is_obsolete = %d, is_relationshiptype = %d
+       WHERE cvterm_id = %d
+    ";
+    if (!db_query($sql, $term['name'], $definition, $is_obsolete, $is_relationship, $cvterm->cvterm_id)) {
+      watchdog('tripal_cv', "Failed to update the term: $name", NULL, WATCHDOG_WARNING);
+      return FALSE;
+    }
+    $cvterm = db_fetch_object(db_query($cvtermsql, $name, $dbname));
+    if (!$is_relationship) {
+      print "Updated CV term: $name ($dbname)\n";
+    }
+    else {
+      print "Updated relationship CV term: $name ($dbname)\n";
+    }
+  }
+  // return the cvterm
+  return $cvterm;
 }
 
 

+ 11 - 0
tripal_cv/tripal_cv.coder_ignores.txt

@@ -0,0 +1,11 @@
+; The file should be formatted this way :
+; file:line:warning-type
+; where warning-type is one of security, style, sql, i18n, comment, etc.
+
+; This query selects from a non-drupal schema where the database prefixes are not
+; applied and thus the curcly brackets ({}) are not needed
+tripal_cv.module:1059:sql
+
+; Need to use POST since this is part of a JS callback
+tripal_cv.module:407:security
+tripal_cv.module:813:security

+ 124 - 124
tripal_cv/tripal_cv.install

@@ -1,150 +1,150 @@
 <?php
 
 /**
-*  Implementation of hook_install();
-*
-* @ingroup tripal_cv
-*/
-function tripal_cv_install(){
-
-   // create the module's data directory
-   tripal_create_moddir('tripal_cv');
-
-   // Add the materialized view needed to keep track of the 
-   // 
-   $previous_db = tripal_db_set_active('chado');
-   if (db_table_exists('cv_root_mview')) {
-      $sql = "DROP TABLE cv_root_mview";
-      db_query($sql);
-   }
-   tripal_db_set_active($previous_db);
-
-   // Create the MView
-   tripal_add_mview(
-      // view name
-      'cv_root_mview',
-      // module name  
-      'tripal_cv',
-      // table name
-      'cv_root_mview',
-      // table schema
-      'name character varying(1024), cvterm_id integer, cv_id integer, 
-       cv_name character varying(255)',
-      // indexed columns
-      'cvterm_id, cv_id',
-      // SQL statement that populates the view
-      'SELECT DISTINCT CVT.name,CVT.cvterm_id, CV.cv_id, CV.name
-       FROM {cvterm_relationship} CVTR
-         INNER JOIN cvterm CVT on CVTR.object_id = CVT.cvterm_id
-         INNER JOIN CV on CV.cv_id = CVT.cv_id
-       WHERE CVTR.object_id not in
-         (SELECT subject_id FROM {cvterm_relationship}) ',
-      // special index
-      ''
-   );
-
-   // create the tables that correlate OBO files/references with a chado CV
-   drupal_install_schema('tripal_cv');
-   tripal_cv_add_obo_defaults();
-}
+ * @file
+ * Contains functions executed only on install/uninstall of this module
+ */
+
 /**
-*  This update adds the new tripal_obo table.  This is an upgrade from
-*  Tripal version 0.2
-*
-* @ingroup tripal_cv
-*/
-
-function tripal_cv_update_6000(){
-   drupal_install_schema('tripal_cv');
-   tripal_cv_add_obo_defaults();
-   $ret = array(
-      '#finished' => 1,
-   );
-   
-   return $ret;
+ * Implementation of hook_install().
+ *
+ * @ingroup tripal_cv
+ */
+function tripal_cv_install() {
+
+  // create the module's data directory
+  tripal_create_moddir('tripal_cv');
+
+  // Add the materialized view needed to keep track of the
+  //
+  $previous_db = tripal_db_set_active('chado');
+  if (db_table_exists('cv_root_mview')) {
+    $sql = "DROP TABLE cv_root_mview";
+    db_query($sql);
+  }
+  tripal_db_set_active($previous_db);
+
+  // Create the MView
+  tripal_add_mview(
+    // view name
+    'cv_root_mview',
+    // module name
+    'tripal_cv',
+    // table name
+    'cv_root_mview',
+    // table schema
+    'name character varying(1024), cvterm_id integer, cv_id integer,
+     cv_name character varying(255)',
+    // indexed columns
+    'cvterm_id, cv_id',
+    // SQL statement that populates the view
+    'SELECT DISTINCT CVT.name,CVT.cvterm_id, CV.cv_id, CV.name
+     FROM {cvterm_relationship} CVTR
+       INNER JOIN cvterm CVT on CVTR.object_id = CVT.cvterm_id
+       INNER JOIN CV on CV.cv_id = CVT.cv_id
+     WHERE CVTR.object_id not in
+       (SELECT subject_id FROM {cvterm_relationship}) ',
+    // special index
+    ''
+  );
+
+  // create the tables that correlate OBO files/references with a chado CV
+  drupal_install_schema('tripal_cv');
+  tripal_cv_add_obo_defaults();
 }
+
 /**
-* Implementation of hook_uninstall()
-*
-* @ingroup tripal_cv
-*/
-function tripal_cv_uninstall(){
-
-	// remove the materialized view
-   $mview = tripal_mviews_get_mview_id('cv_root_mview');
-   if($mview){
-	   tripal_mviews_action('delete',$mview);
-	}
-
-   drupal_uninstall_schema('tripal_cv');
+ *  This update adds the new tripal_obo table.  This is an upgrade from
+ *  Tripal version 0.2
+ *
+ * @ingroup tripal_cv
+ */
+
+function tripal_cv_update_6000() {
+  drupal_install_schema('tripal_cv');
+  tripal_cv_add_obo_defaults();
+  $ret = array(
+    '#finished' => 1,
+  );
+
+  return $ret;
 }
 
 /**
- * Implementation of hook_requirements(). Make sure 'Tripal Core' is enabled
- * before installation
+ * Implementation of hook_uninstall().
  *
  * @ingroup tripal_cv
  */
-function tripal_cv_requirements($phase) {
-   $requirements = array();
-   if ($phase == 'install') {
-      if (!function_exists('tripal_create_moddir')) {
-         $requirements ['tripal_cv'] = array(
-            'title' => "tripal_cv",
-            'value' => "Required modules must be installed first before Tripal CV module can be installed",
-            'severity' => REQUIREMENT_ERROR,
-         );
-      }
-   }
-   return $requirements;
+function tripal_cv_uninstall() {
+
+  // remove the materialized view
+  $mview = tripal_mviews_get_mview_id('cv_root_mview');
+  if ($mview) {
+    tripal_mviews_action('delete', $mview);
+  }
+
+  drupal_uninstall_schema('tripal_cv');
 }
+
 /**
-* Implementation of hook_schema().
-*
-* @ingroup tripal_cv
-*/
+ * Implementation of hook_schema().
+ *
+ * @ingroup tripal_cv
+ */
 function tripal_cv_schema() {
-   $schema = tripal_cv_get_schemas();
-   return $schema;
+  $schema = tripal_cv_get_schemas();
+  return $schema;
 }
+
 /**
-* This function simply defines all tables needed for the module to work
-* correctly.  By putting the table definitions in a separate function we 
-* can easily provide the entire list for hook_install or individual
-* tables for an update.
-*
-* @ingroup tripal_cv
-*/
-function tripal_cv_get_schemas (){  
+ * This function simply defines all tables needed for the module to work
+ * correctly.  By putting the table definitions in a separate function we
+ * can easily provide the entire list for hook_install or individual
+ * tables for an update.
+ *
+ * @ingroup tripal_cv
+ */
+function tripal_cv_get_schemas() {
   $schema = array();
 
   $schema['tripal_cv_obo'] = array(
-      'fields' => array(
-         'obo_id' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
-         'name'  => array('type' => 'varchar','length' => 255),
-         'path'   => array('type' => 'varchar','length' => 1024),
-      ),
-      'indexes' => array(
-         'obo_id' => array('obo_id'),
-       ),
-      'primary key' => array('obo_id'),
+    'fields' => array(
+      'obo_id' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
+      'name'  => array('type' => 'varchar', 'length' => 255),
+      'path'   => array('type' => 'varchar', 'length' => 1024),
+    ),
+    'indexes' => array(
+      'obo_id' => array('obo_id'),
+    ),
+    'primary key' => array('obo_id'),
   );
+
   return $schema;
 }
+
 /**
-* Add's defaults to the tripal_cv_obo table
-*
-* @ingroup tripal_cv
-*/
-function tripal_cv_add_obo_defaults(){
-   // insert commonly used ontologies into the tables
-   $isql = "INSERT INTO tripal_cv_obo (name,path) VALUES ('%s','%s')";
-   db_query($isql,'Chado Feature Properties',drupal_get_path('module','tripal_cv').'/feature_property.obo');
-   db_query($isql,'Relationship Ontology','http://www.obofoundry.org/ro/ro.obo');
-   db_query($isql,'Sequence Ontology','http://song.cvs.sourceforge.net/*checkout*/song/ontology/so.obo');
-   db_query($isql,'Gene Ontology','http://www.geneontology.org/ontology/gene_ontology.obo');
-   db_query($isql,'Cell Ontology','http://obo.cvs.sourceforge.net/obo/obo/ontology/anatomy/cell_type/cell.obo?rev=HEAD');
-   db_query($isql,'Plant Structure Ontology','http://palea.cgrb.oregonstate.edu/viewsvn/Poc/trunk/ontology/OBO_format/po_anatomy.obo?view=co');  
-   db_query($isql,'Plant Growth and Development Stages Ontology','http://palea.cgrb.oregonstate.edu/viewsvn/Poc/trunk/ontology/OBO_format/po_temporal.obo?view=co');
+ * Add's defaults to the tripal_cv_obo table
+ *
+ * @ingroup tripal_cv
+ */
+function tripal_cv_add_obo_defaults() {
+
+  // insert commonly used ontologies into the tables
+  $ontologies = array(
+    array('Chado Feature Properties', drupal_get_path('module', 'tripal_cv') . '/feature_property.obo'),
+    array('Relationship Ontology', 'http://www.obofoundry.org/ro/ro.obo'),
+    array('Sequence Ontology', 'http://song.cvs.sourceforge.net/*checkout*/song/ontology/so.obo'),
+    array('Gene Ontology', 'http://www.geneontology.org/ontology/gene_ontology.obo'),
+    array('Cell Ontology', 'http://obo.cvs.sourceforge.net/obo/obo/ontology/anatomy/cell_type/cell.obo?rev=HEAD'),
+    array('Plant Structure Ontology', 'http://palea.cgrb.oregonstate.edu/viewsvn/Poc/trunk/ontology/OBO_format/po_anatomy.obo?view=co'),
+    array('Plant Growth and Development Stages Ontology', 'http://palea.cgrb.oregonstate.edu/viewsvn/Poc/trunk/ontology/OBO_format/po_temporal.obo?view=co')
+  );
+  foreach ($ontologies as $o) {
+    db_query(
+      "INSERT INTO {tripal_cv_obo} (name,path) VALUES ('%s','%s')",
+      $o[0],
+      $o[1]
+    );
+  }
 
 }

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 481 - 472
tripal_cv/tripal_cv.module


+ 20 - 20
tripal_cv/tripal_cv.views.inc

@@ -6,7 +6,7 @@
  *  chado/tripal db tables. Supplementary functions can be found in
  *  ./views/
  *
- *  Documentation on views integration can be found at 
+ *  Documentation on views integration can be found at
  *  http://views2.logrus.com/doc/html/index.html.
  */
 
@@ -17,7 +17,7 @@
  */
 
 require_once('views/cvterm.views.inc');
-require_once('views/cv.views.inc'); 
+require_once('views/cv.views.inc');
 /**
  * Implements hook_views_data()
  *
@@ -26,7 +26,7 @@ require_once('views/cv.views.inc');
  * @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 
+ *   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)
  *
@@ -34,23 +34,23 @@ require_once('views/cv.views.inc');
  */
 function tripal_cv_views_data() {
   $data = array();
-  
+
   //Function is contained in includes/cvterm.views.inc
   //Returns the data array for the chado cvterm table
   $data = array_merge($data, retrieve_cvterm_views_data());
-  
+
   //Function is contained in includes/cv.views.inc
   //Returns the data array for the chado cv table
   $data = array_merge($data, retrieve_cv_views_data());
-  
+
   return $data;
 }
- 
+
 /**
  * Implements hook_views_handlers()
  *
  * Purpose: Register all custom handlers with views
- *   where a handler describes either "the type of field", 
+ *   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
@@ -58,25 +58,25 @@ function tripal_cv_views_data() {
  * @ingroup tripal_cv_views
  */
 function tripal_cv_views_handlers() {
- return array(
-   'info' => array(
-     'path' => drupal_get_path('module', 'tripal_cv') . '/views/handlers',
-   ),
-   'handlers' => array(
-     'views_handler_field_tf_boolean' => array(
+  return array(
+    'info' => array(
+      'path' => drupal_get_path('module', 'tripal_cv') . '/views/handlers',
+    ),
+    'handlers' => array(
+      'views_handler_field_tf_boolean' => array(
        'parent' => 'views_handler_field',
-     ),
-   ),
- );
+      ),
+    ),
+  );
 }
 
 /**
  *
  * @ingroup tripal_cv_views
  */
-function tripal_cv_views_default_views () {
+function tripal_cv_views_default_views() {
   $views = array();
-  
+
   // Main default view
   // List all cvterms based on cv
   $view = new view;
@@ -366,6 +366,6 @@ function tripal_cv_views_default_views () {
     'name' => 'navigation',
   ));
   $views[$view->name] = $view;
-  
+
   return $views;
 }

+ 0 - 45
tripal_cv/views/README

@@ -1,45 +0,0 @@
-
-This directory contains all additional views code needed to integrate this module with views2.
-
-FILE/FOLDER DESCRIPTIONS
----------------------------
-<chado table name>.views.inc:
-	contains a single function retrieve_<chado table name>_views_data()
-	which describes that table to views. This function is called by
-	tripal_cv_views_data() in ../tripal_cv.views.inc.
-	For more information on the form of this data array look up the
-	views2 documentation for hook_views_data() 
-	-http://views2.logrus.com/doc/html/index.html
-	
-handlers/
-	Each file contained within this folder defines a views handler. Only custom
-	handlers are included in this folder and each must be described in 
-	hook_views_handlers() in ../tripal_cv.views.inc.
-	A views handler does one of the following:
-		1) describe the type of a field and how it should be displayed
-		2) describe a method to sort this field
-		3) describe a method to filter this field
-
-
-STANDARDS TO FOLLOW
----------------------------
-
-1. All table definition files should be named tablename.views.inc
-2. All handlers should be in a handlers sub-directory and follow the naming convention of
-   views handlers (ie: views_handler_field/filter/sort_handlername.inc )
-
-Views Table Definitions:
-- Please use the template files provided whenever you are describing a new table to views.
-   For any table in chado simply copy template.table_defn.views.inc to tablename.views.inc and 
-   follow the instructions listed at the top of the template file.
-- ONLY ONE TABLE DEFINITION PER FILE
-- To join a chado table to it's drupal node simply copy template.node_join.views.inc to 
-   basetablename.views.inc and replace all XXX with basetablename.
-   
-   NOTE: Creating the table definition file is not enough. You also need to call the 
-         retrieve_XXX_views_data() function from ../tripal_cv.views.inc:tripal_cv_views_data()
-         by adding the following line:
-            $data = array_merge($data, retrieve_XXX_views_data());
-         to the function and including the file directly above the function (blow the function 
-         header by adding:
-            require_once('views/XXX.views.inc');

+ 67 - 67
tripal_cv/views/cv.views.inc

@@ -1,9 +1,9 @@
 <?php
 
 /**
- * Prupose: this function returns a portion of the data array 
+ * Prupose: this function returns a portion of the data array
  *   which describes the cv table, it's fields and any joins between it and other tables
- * @see tripal_cv_views_data() --in tripal_cv.views.inc
+ * @see tripal_cv_views_data()
  *
  * TABLE: cv
  * @code
@@ -19,75 +19,75 @@
  * @ingroup tripal_cv_views
  */
 function retrieve_cv_views_data() {
-  $data = array();
+$data = array();
 
-  // Basic table definition
-  $data['cv']['table'] = array(
-    'field' => 'cv_id',
-    'title' => 'Chado CV (Controlled Vocabulary)',
-    'group' => 'Chado CV',
-    'help' => 'Controlled vocabularies existing in the Chado Database',
-    'database' => 'chado'
-  );
+// Basic table definition
+$data['cv']['table'] = array(
+'field' => 'cv_id',
+'title' => 'Chado CV (Controlled Vocabulary)',
+'group' => 'Chado CV',
+'help' => 'Controlled vocabularies existing in the Chado Database',
+'database' => 'chado'
+);
 
-  // Define relationships between this table and others
-  $data['cv']['table']['join'] = array(
-     'cvterm' => array(
-       'left_field' => 'cv_id',
-       'field' => 'cv_id',
-     ),
-  );
+// Define relationships between this table and others
+$data['cv']['table']['join'] = array(
+'cvterm' => array(
+'left_field' => 'cv_id',
+'field' => 'cv_id',
+),
+);
 
-  // Table Field Definitions----------------------
-  // Field: cv_id (primary key)
-  $data['cv']['cv_id'] = array(
-    'title' => t('CV ID'),
-    'help' => t('The primary key of the controlled vocabulary.'),
-    'field' => array(
-      'handler' => 'views_handler_field_numeric',
-      'click sortable' => TRUE,
-     ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_numeric',
-    ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-  ); 
-  
-  //Field: name (varchar -255)
-  $data['cv']['name'] = array(
-    'title' => 'Vocabulary Name',
-    'field' => array(
-       'handler' => 'views_handler_field',
-       'click sortable' => TRUE,
-     ),
-     'sort' => array(
-       'handler' => 'views_handler_sort',
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_chado_select_string',
-     ),
-     'argument' => array(
-       'handler' => 'views_handler_argument_string',
-     ),
-  );
+// Table Field Definitions----------------------
+// Field: cv_id (primary key)
+$data['cv']['cv_id'] = array(
+'title' => t('CV ID'),
+'help' => t('The primary key of the controlled vocabulary.'),
+'field' => array(
+'handler' => 'views_handler_field_numeric',
+'click sortable' => TRUE,
+),
+'filter' => array(
+'handler' => 'views_handler_filter_numeric',
+),
+'sort' => array(
+'handler' => 'views_handler_sort',
+),
+);
 
-  //Field: definition (text)
-  $data['cv']['definition'] = array(
-    'title' => 'Vocabulary Definition',
-    'field' => array(
-       'handler' => 'views_handler_field',
-       'click sortable' => TRUE,
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_string',
-     ),
-     'argument' => array(
-       'handler' => 'views_handler_argument_string',
-     ),
-  );
+//Field: name (varchar -255)
+$data['cv']['name'] = array(
+'title' => 'Vocabulary Name',
+'field' => array(
+'handler' => 'views_handler_field',
+'click sortable' => TRUE,
+),
+'sort' => array(
+'handler' => 'views_handler_sort',
+),
+'filter' => array(
+'handler' => 'views_handler_filter_chado_select_string',
+),
+'argument' => array(
+'handler' => 'views_handler_argument_string',
+),
+);
 
-  return $data;
+//Field: definition (text)
+$data['cv']['definition'] = array(
+'title' => 'Vocabulary Definition',
+'field' => array(
+'handler' => 'views_handler_field',
+'click sortable' => TRUE,
+),
+'filter' => array(
+'handler' => 'views_handler_filter_string',
+),
+'argument' => array(
+'handler' => 'views_handler_argument_string',
+),
+);
+
+return $data;
 
 }

+ 122 - 121
tripal_cv/views/cvterm.views.inc

@@ -1,9 +1,10 @@
 <?php
 
 /**
- * Purpose: this function returns the portion of the data array 
+ * @file
+ * Purpose: this function returns the portion of the data array
  *   which describes the cv table, it's fields and any joins between it and other tables
- * @see tripal_cv_views_data() --in tripal_cv.views.inc
+ * @see tripal_cv_views_data()
  *
  * BASE TABLE: cvterm
  * @code
@@ -27,129 +28,129 @@
  */
 function retrieve_cvterm_views_data() {
 
-  // Basic table definition
-  $data['cvterm']['table']['group'] = 'Chado CV Terms';
-  $data['cvterm']['table']['base'] = array(
-    'field' => 'cvterm_id',
-    'title' => 'Chado CV Terms (Controlled Vocabulary)',
-    'help' => 'Controlled Vocabularies (CVs) are the main way Chado controls content.',
-    'database' => 'chado'
-  );
+// Basic table definition
+$data['cvterm']['table']['group'] = 'Chado CV Terms';
+$data['cvterm']['table']['base'] = array(
+'field' => 'cvterm_id',
+'title' => 'Chado CV Terms (Controlled Vocabulary)',
+'help' => 'Controlled Vocabularies (CVs) are the main way Chado controls content.',
+'database' => 'chado'
+);
 
-  // Define relationships between this table and others
-   $data['cvterm']['table']['join'] = array(
-     'feature' => array(
-       'left_field' => 'type_id',
-       'field' => 'cvterm_id',
-     ),
-     'library' => array(
-       'left_field' => 'type_id',
-       'field' => 'cvterm_id',
-     ),
-     'stock' => array(
-       'left_field' => 'type_id',
-       'field' => 'cvterm_id',
-     ),
-     'nd_reagent' => array(
-       'left_field' => 'type_id',
-       'field' => 'cvterm_id',
-     ),
-   );
+// Define relationships between this table and others
+$data['cvterm']['table']['join'] = array(
+'feature' => array(
+'left_field' => 'type_id',
+'field' => 'cvterm_id',
+),
+'library' => array(
+'left_field' => 'type_id',
+'field' => 'cvterm_id',
+),
+'stock' => array(
+'left_field' => 'type_id',
+'field' => 'cvterm_id',
+),
+'nd_reagent' => array(
+'left_field' => 'type_id',
+'field' => 'cvterm_id',
+),
+);
 
- // Table Field Definitions----------------------
- // Field: cvterm_id (primary key)
- $data['cvterm']['cvterm_id'] = array(
-   'title' => t('CV Term ID'),
-   'help' => t('The primary kep of controlled vocabulary terms.'),
-   'field' => array(
-     'handler' => 'views_handler_field_numeric',
-     'click sortable' => TRUE,
-    ),
-   'filter' => array(
-     'handler' => 'views_handler_filter_numeric',
-   ),
-   'sort' => array(
-     'handler' => 'views_handler_sort',
-   ),
- );
- 
- //Field: cv_id (foreign key: cv)
- //  join between cv table and this one in cv.views.inc
- 
- // Field: Name (varchar 1024)
-  $data['cvterm']['name'] = array(
-     'title' => 'Name',
-     'help' => 'The term name',
-     'field' => array(
-     'handler' => 'views_handler_field',
-       'click sortable' => TRUE,
-     ),
-     'sort' => array(
-       'handler' => 'views_handler_sort',
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_string',
-     ),
-     'argument' => array(
-       'handler' => 'views_handler_argument_string',
-     ),
-   );
+// Table Field Definitions----------------------
+// Field: cvterm_id (primary key)
+$data['cvterm']['cvterm_id'] = array(
+'title' => t('CV Term ID'),
+'help' => t('The primary kep of controlled vocabulary terms.'),
+'field' => array(
+'handler' => 'views_handler_field_numeric',
+'click sortable' => TRUE,
+),
+'filter' => array(
+'handler' => 'views_handler_filter_numeric',
+),
+'sort' => array(
+'handler' => 'views_handler_sort',
+),
+);
 
-   // Field: Definition (text)
-   $data['cvterm']['definition'] = array(
-     'title' => 'Definition',
-     'help' => 'A definition of this term',
-     'field' => array(
-       'handler' => 'views_handler_field',
-       'click sortable' => TRUE,
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_string',
-     ),
-     'argument' => array(
-       'handler' => 'views_handler_argument_string',
-     ),
-   );
+//Field: cv_id (foreign key: cv)
+//  join between cv table and this one in cv.views.inc
 
-   // Field: dbxref_id (foreign key: dbxref)
-   //  join between dbxref table and this one in tripal_db/views/dbxref.views.inc
-   
-   // Field: is_obsolete (integer: 1/0)
-   $data['cvterm']['is_obsolete'] = array(
-     'title' => 'Is Obsolete',
-     'help' => 'Whether this term is obsolete or not.',
-     'field' => array(
-       'handler' => 'views_handler_field_boolean',
-       'click sortable' => TRUE,
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_string',
-       'label' => t('Is Obsolete?'),
-       'type' => 'yes-no',
-     ),
-     'sort' => array(
-       'handler' => 'views_handler_sort',
-     ),
-   );
+// Field: Name (varchar 1024)
+$data['cvterm']['name'] = array(
+'title' => 'Name',
+'help' => 'The term name',
+'field' => array(
+'handler' => 'views_handler_field',
+'click sortable' => TRUE,
+),
+'sort' => array(
+'handler' => 'views_handler_sort',
+),
+'filter' => array(
+'handler' => 'views_handler_filter_string',
+),
+'argument' => array(
+'handler' => 'views_handler_argument_string',
+),
+);
 
-   // Field: is_relationshiptype (integer: 1/0)
-   $data['cvterm']['is_relationshiptype'] = array(
-     'title' => 'Is Relationship',
-     'help' => 'Whether this term describes a relationship or not.',
-     'field' => array(
-       'handler' => 'views_handler_field_boolean',
-       'click sortable' => TRUE,
-     ),
-     'filter' => array(
-       'handler' => 'views_handler_filter_chado_boolean',
-       'label' => t('Is Relationship Type?'),
-       'type' => 'yes-no',
-     ),
-     'sort' => array(
-       'handler' => 'views_handler_sort',
-     ),
-    );
-  
-  return $data;
+// Field: Definition (text)
+$data['cvterm']['definition'] = array(
+'title' => 'Definition',
+'help' => 'A definition of this term',
+'field' => array(
+'handler' => 'views_handler_field',
+'click sortable' => TRUE,
+),
+'filter' => array(
+'handler' => 'views_handler_filter_string',
+),
+'argument' => array(
+'handler' => 'views_handler_argument_string',
+),
+);
+
+// Field: dbxref_id (foreign key: dbxref)
+//  join between dbxref table and this one in tripal_db/views/dbxref.views.inc
+
+// Field: is_obsolete (integer: 1/0)
+$data['cvterm']['is_obsolete'] = array(
+'title' => 'Is Obsolete',
+'help' => 'Whether this term is obsolete or not.',
+'field' => array(
+'handler' => 'views_handler_field_boolean',
+'click sortable' => TRUE,
+),
+'filter' => array(
+'handler' => 'views_handler_filter_string',
+'label' => t('Is Obsolete?'),
+'type' => 'yes-no',
+),
+'sort' => array(
+'handler' => 'views_handler_sort',
+),
+);
+
+// Field: is_relationshiptype (integer: 1/0)
+$data['cvterm']['is_relationshiptype'] = array(
+'title' => 'Is Relationship',
+'help' => 'Whether this term describes a relationship or not.',
+'field' => array(
+'handler' => 'views_handler_field_boolean',
+'click sortable' => TRUE,
+),
+'filter' => array(
+'handler' => 'views_handler_filter_chado_boolean',
+'label' => t('Is Relationship Type?'),
+'type' => 'yes-no',
+),
+'sort' => array(
+'handler' => 'views_handler_sort',
+),
+);
+
+return $data;
 
 }

+ 0 - 84
tripal_cv/views/template.node_join.views.inc

@@ -1,84 +0,0 @@
-<?php
-
-/*************************************************************************
- * @file: THIS IS A TEMPLATE AND SHOULD NOT BE INCLUDED IN THE MODULE CODE
- *
- *  - simply replace all XXX with the original chado table you want to join to it's drupal nodes.
- *    (ie: If you want to join features to their drupal nodes then XXX=feature)
- * 
- *  NOTE: Creating the table definition file is not enough. You also need to call the 
- *        retrieve_XXX_views_data() function from ../tripal_cv.views.inc:tripal_cv_views_data()
- *        by adding the following line:
- *           $data = array_merge($data, retrieve_XXX_views_data());
- *        to the function and including the file directly above the function (blow the function 
- *        header by adding:
- *           require_once('views/XXX.views.inc');
- *
- *  REMOVE THIS COMMENT IN THE COPY!
- */ 
- 
-/**
- *  @file
- *  This file defines the data array for a given chado table. This array
- *  is merged into a larger array containing definitions of all tables associated
- *  with this module in:
- *  @see tripal_cv.views.inc --in tripal_cv_views_data()
- *
- *  Note: All chado tables are joined to their drupal nodes through the chado_XXX linking table. 
- *        This file simply defines this linking table and joins the three tables together.
- *        No modification of XXX.views.inc is needed.
- *
- *  Documentation on views integration can be found at 
- *  http://views2.logrus.com/doc/html/index.html.
- */
- 
-/**
- * Purpose: this function returns the portion of the data array 
- *   which describes the chado_XXX drupal table, it's fields and any joins between it 
- *   and other tables
- * @see tripal_cv_views_data() --in tripal_cv.views.inc
- *
- * The main need for description of this table to views is to join chado data with drupal nodes
- *
- */
-function retrieve_chado_XXX_views_data () {
-	global $db_url;
-  $data = array();
-  
-  // if the chado database is not local to the drupal database
-  // then we need to set the database name.  This should always
-  // be 'chado'.
-  if(is_array($db_url) and array_key_exists('chado',$db_url)){
-     // return empty data array b/c if chado is external then no join to the nodetable can be made
-     return $data;
-  }
-
-  //Basic table definition-----------------------------------
-  $data['chado_XXX']['table'] = array(
-    'field' => 'nid',
-  );
-  
-  //Relationship Definitions---------------------------------
-  // Note: No joins need to be made from $data['XXX']['table']
-  
-  // Join the chado_XXX table to XXX
-  $data['chado_XXX']['table']['join']['XXX'] = array(
-  	'left_field' => 'XXX_id',
-  	'field' => 'XXX_id',
-  );
-  
-  // Join the node table to chado_XXX
-  $data['node']['table']['join']['chado_XXX'] = array(
-  	'left_field' => 'nid',
-  	'field' => 'nid',
-  );
-  
-  // Join the node table to XXX
-  $data['node']['table']['join']['XXX'] = array(
-  	'left_table' => 'chado_XXX',
-  	'left_field' => 'nid',
-  	'field' => 'nid',
-  );  
-
-	return $data;
-}

+ 0 - 211
tripal_cv/views/template.table_defn.views.inc

@@ -1,211 +0,0 @@
-<?php
-
-/*************************************************************************
- * @file: THIS IS A TEMPLATE AND SHOULD NOT BE INCLUDED IN THE MODULE CODE
- *
- *   - Every instance of XXX should be replaced with the name of your table
- *   - If this is a base table (you want a view where every row is a row from this table)
- *     then change $data['XXX']['table'] to $data['XXX']['table']['base'] 
- *     and $data['XXX']['table']['database'] to $data['XXX']['table']['base']['database']
- *   - Relationships between this table and others: YYY is the table you are trying to join to this
- *     one. You want to join a table to this one if this table contains a foreign key to the other
- *     table. If the join between this table and another is through a linking table
- *     (ie: library-XXX/YYY => library_feature-XY => feature-XXX/YYY) then make the join in both
- *     directions (ie: in the file XXX.views.inc and the file YYY.views.inc
- *   - Create a field definition for each field in this table using the example fields already
- *     listed. Match the type of the database field to the field definition listed below.
- *     (ie: for a text/varchar field from the database use plain_text_field below)
- * 
- *  NOTE: Creating the table definition file is not enough. You also need to call the 
- *        retrieve_XXX_views_data() function from ../tripal_cv.views.inc:tripal_cv_views_data()
- *        by adding the following line:
- *           $data = array_merge($data, retrieve_XXX_views_data());
- *        to the function and including the file directly above the function (blow the function 
- *        header by adding:
- *           require_once('views/XXX.views.inc');
- *
- *  REMOVE THIS COMMENT IN THE COPY!
- */ 
- 
-/**
- *  @file
- *  This file defines the data array for a given chado table. This array
- *  is merged into a larger array containing definitions of all tables associated
- *  with this module in:
- *  @see tripal_cv.views.inc --in tripal_cv_views_data()
- *
- *  Documentation on views integration can be found at 
- *  http://views2.logrus.com/doc/html/index.html.
- */
-
-/*************************************************************************
- * Purpose: this function returns the portion of the data array 
- *   which describes the XXX table, it's fields and any joins between it and other tables
- * @see tripal_cv_views_data() --in tripal_cv.views.inc
- *
- * Table: XXX
- * @code
- * XXX-Copy/Paste Table SQL code here-XXX
- * @endcode
- */
- function retrieve_XXX_views_data() {
-  global $db_url;
-  $data = array();
-
-  // if the chado database is not local to the drupal database
-  // then we need to set the database name.  This should always
-  // be 'chado'.
-  if(is_array($db_url) and array_key_exists('chado',$db_url)){
-    $database = 'chado';
-  }
-   
-  //Basic table definition-----------------------------------
-  $data['XXX']['table']['group'] = t('Chado XXX');
-  
-  $data['XXX']['table'] = array(
-    'field' => 'primary_id',
-    'title' => t('Chado XXX'),
-    'help' => t('Enter some user-friendly description of this tables purpose to the user.'),
-  );
-  if($database){
-     $data['XXX']['table']['database'] = $database;
-  }
-
-  
-  //Relationship Definitions---------------------------------
-  //Join: YYY => XXX
-  // Notice that this relationship tells the primary table to show it's fields to the
-  // table referencing it by a foreign key and thus the relationship is from
-  // primary table to table referenceing it (ie: cvterm => feature)
-  $data['XXX']['table']['join']['YYY'] = array(
-    'left_field' => 'foreign key in YYY table',
-    'field' => 'primary key in XXX table',
-  );  
-  
-  //Join: XXX => XY => YYY
-  // This relationship should be described in both directions
-  // in the appropriate files (ie: for feature => library 
-  // describe in both feature.views.inc and library.views.inc)
-  $data['XXX']['table']['join']['XY'] = array(
-    'left_field' => 'matching XXX key in the XY table',
-    'field' => 'primary key in XXX table',
-  );  
-  $data['XXX']['table']['join']['YYY'] = array(
-    'left_table' => 'XY',
-    'left_field' => 'matching XXX key in the XY table',
-    'field' => 'primary key in XXX table',
-  );
-  $data['XY']['table']['join']['YYY'] = array(
-    'left_field' => 'primary key in YYY table',
-    'field' => 'matching YYY key in the XY table',
-  );
-   
-  //Table Field Definitions----------------------------------
-      
-  //Field: XXX_id (primary key)
-  $data['XXX']['field_name'] = array(
-    'title' => t('XXX Primary Key'),
-    'help' => t('A unique index for every XXX.'),
-    'field' => array(
-      'handler' => 'views_handler_field_numeric',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_numeric',
-    ),
-  );
-
-  /*.......................................................
-   * Beginning of Example Field definitions
-   * Remove this section when done
-   */
-
-  //Field: plain_text_field (chado datatype)   
-  $data['XXX']['plain_text_field'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_string',
-    ),
-    'argument' => array(
-      'handler' => 'views_handler_argument_string',
-    ),
-  );
-
-  //Field: numeric_field (chado datatype)   
-  $data['XXX']['numeric_field'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_numeric',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_numeric',
-    ),
-  );
-
-  //Field: boolean_field (chado datatype)   
-  $data['XXX']['boolean_field'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_boolean',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_boolean_operator',
-    ),
-  );
-
-  //Field: unix_timestamp (chado datatype)   
-  $data['XXX']['unix_timestamp'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_date',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort_date',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_date',
-    ),
-  );
-
-  //Field: human_readable_date (chado datatype)   
-  $data['XXX']['human_readable_date'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_readble_date',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort_date',
-    ),
-  );
-   
-   /*
-    * End of Example Field definitions
-    */
-    
-  return $data;
-}

+ 92 - 84
tripal_db/tripal_db.api.inc

@@ -1,10 +1,12 @@
 <?php
 
 /**
+ * @file
+ * Provides an application programming interface (API) to manage references to external databases
+ *
  * @defgroup tripal_db_api DB Module API
  * @ingroup tripal_api
  * @ingroup tripal_db
- * Provides an application programming interface (API) to manage references to external databases
  */
 
 /**
@@ -17,7 +19,7 @@
  *   Chado database object
  *
  * The database is selected using tripal_core_chado select and as such the
- * $select_values array parameter meant to uniquely identify the database to be 
+ * $select_values array parameter meant to uniquely identify the database to be
  * returned follows the same form as when using tripal_core_chado_select directly.
  *
  * Example Usage:
@@ -29,22 +31,22 @@
  * @endcode
  *  The above code selects the SOFP db and returns the following object:
  * @code
-    $db_object = stdClass Object ( 
+    $db_object = stdClass Object (
       [db_id] => 49
       [name] => SOFP
-      [description] => 
-      [urlprefix] => 
-      [url] =>     
-    ); 
+      [description] =>
+      [urlprefix] =>
+      [url] =>
+    );
  * @endcode
  *
  * @ingroup tripal_db_api
  */
-function tripal_db_get_db ($select_values) {
+function tripal_db_get_db($select_values) {
 
   $columns = array(
-    'db_id', 
-    'name', 
+    'db_id',
+    'name',
     'description',
     'urlprefix',
     'url'
@@ -52,21 +54,23 @@ function tripal_db_get_db ($select_values) {
   $results = tripal_core_chado_select('db', $columns, $select_values);
   if (sizeof($results) == 1) {
     return $results[0];
-  } elseif (empty($results)) {
-    watchdog('tripal_cdb', 
+  }
+  elseif (empty($results)) {
+    watchdog('tripal_cdb',
       'tripal_db_get_db: No db matches criteria values:%values',
       array('%values' => print_r($select_values, TRUE)),
       WATCHDOG_WARNING
     );
     return FALSE;
-  } else {
-    watchdog('tripal_db', 
+  }
+  else {
+    watchdog('tripal_db',
       'tripal_db_get_db: 2+ dbs match criteria values:%values',
       array('%values' => print_r($select_values, TRUE)),
       WATCHDOG_WARNING
     );
   }
-  
+
 }
 
 /**
@@ -74,16 +78,16 @@ function tripal_db_get_db ($select_values) {
  *
  * @param $db_id
  *   db.db_id
- * @return 
+ * @return
  *   Chado db object with all fields from the chado db table
  *
  * @ingroup tripal_db_api
  */
-function tripal_db_get_db_by_db_id ($db_id) {
+function tripal_db_get_db_by_db_id($db_id) {
 
-	$previous_db = tripal_db_set_active('chado');
+  $previous_db = tripal_db_set_active('chado');
   $r = db_fetch_object(db_query(
-    "SELECT * FROM db WHERE db_id=%d", $db_id
+    "SELECT * FROM {db} WHERE db_id=%d", $db_id
   ));
   tripal_db_set_active($previous_db);
 
@@ -95,16 +99,16 @@ function tripal_db_get_db_by_db_id ($db_id) {
  *
  * @param $name
  *   db.name
- * @return 
+ * @return
  *   chado db object with all fields from the chado db table
  *
  * @ingroup tripal_db_api
  */
-function tripal_db_get_db_by_name ($name) {
+function tripal_db_get_db_by_name($name) {
 
-	$previous_db = tripal_db_set_active('chado');
+  $previous_db = tripal_db_set_active('chado');
   $r = db_fetch_object(db_query(
-    "SELECT * FROM db WHERE name='%s'", $name
+    "SELECT * FROM {db} WHERE name='%s'", $name
   ));
   tripal_db_set_active($previous_db);
 
@@ -114,12 +118,12 @@ function tripal_db_get_db_by_name ($name) {
 // Purpose: To retrieve a chado db object
 //
 // @params where_options: array(
-//													<column_name> => array(
-//														'type' => <type of column: INT/**STRING>,
-//														'value' => <the vlaue you want to filter on>,
-//														'exact' => <if TRUE use =; if FALSE use ~>,
-//													)
-//				)
+//                          <column_name> => array(
+//                            'type' => <type of column: INT/**STRING>,
+//                            'value' => <the vlaue you want to filter on>,
+//                            'exact' => <if TRUE use =; if FALSE use ~>,
+//                          )
+//        )
 // @return chado db object with all fields from the chado db table
 //
 //function tripal_db_get_db ($where_options) {
@@ -128,7 +132,7 @@ function tripal_db_get_db_by_name ($name) {
  * Purpose: Create an options array to be used in a form element
  *   which provides a list of all chado dbs
  *
- * @return 
+ * @return
  *   An array(db_id => name) for each db in the chado db table
  *
  * @ingroup tripal_db_api
@@ -137,7 +141,7 @@ function tripal_db_get_db_options() {
 
   $previous_db = tripal_db_set_active('chado');
   $result = db_query(
-    "SELECT db_id, name FROM db"
+    "SELECT db_id, name FROM {db}"
   );
   tripal_db_set_active($previous_db);
 
@@ -153,12 +157,12 @@ function tripal_db_get_db_options() {
 // Purpose: To retrieve a chado dbxref object
 //
 // @param where_options: array(
-//													<column_name> => array(
-//														'type' => <type of column: INT/**STRING>,
-//														'value' => <the vlaue you want to filter on>,
-//														'exact' => <if TRUE use =; if FALSE use ~>,
-//													)
-//				)
+//                          <column_name> => array(
+//                            'type' => <type of column: INT/**STRING>,
+//                            'value' => <the vlaue you want to filter on>,
+//                            'exact' => <if TRUE use =; if FALSE use ~>,
+//                          )
+//        )
 // @return chado dbxref object with all fields from the chado dbxref table
 //
 //function tripal_db_get_dbxref ($where_options) {
@@ -173,7 +177,7 @@ function tripal_db_get_db_options() {
  *   Chado database reference object
  *
  * The database reference is selected using tripal_core_chado select and as such the
- * $select_values array parameter meant to uniquely identify the database reference to be 
+ * $select_values array parameter meant to uniquely identify the database reference to be
  * returned follows the same form as when using tripal_core_chado_select directly.
  *
  * Example Usage:
@@ -188,27 +192,27 @@ function tripal_db_get_db_options() {
  * @endcode
  *  The above code selects the synonym database reference and returns the following object:
  * @code
-    $dbxref_object = stdClass Object ( 
+    $dbxref_object = stdClass Object (
       [dbxref_id] => 2581
       [accession] => synonym
-      [description] => 
-      [version] => 
+      [description] =>
+      [version] =>
       [db_db_id] => 49
       [db_name] => SOFP
-      [db_description] => 
-      [db_urlprefix] => 
-      [db_url] =>     
-    ); 
+      [db_description] =>
+      [db_urlprefix] =>
+      [db_url] =>
+    );
  * @endcode
  *
  * @ingroup tripal_db_api
  */
-function tripal_db_get_dbxref ($select_values) {
+function tripal_db_get_dbxref($select_values) {
 
   $columns = array(
     'dbxref_id',
-    'db_id', 
-    'accession', 
+    'db_id',
+    'accession',
     'description',
     'version'
   );
@@ -218,15 +222,17 @@ function tripal_db_get_dbxref ($select_values) {
     unset($dbxref->db_id);
 
     return $dbxref;
-  } elseif (empty($results)) {
-    watchdog('tripal_db', 
+  }
+  elseif (empty($results)) {
+    watchdog('tripal_db',
       'tripal_db_get_dbxref: No dbxref matches criteria values:%values',
       array('%values' => print_r($select_values, TRUE)),
       WATCHDOG_WARNING
     );
     return FALSE;
-  } else {
-    watchdog('tripal_db', 
+  }
+  else {
+    watchdog('tripal_db',
       'tripal_db_get_dbxref: 2+ dbxrefs match criteria values:%values',
       array('%values' => print_r($select_values, TRUE)),
       WATCHDOG_WARNING
@@ -242,29 +248,30 @@ function tripal_db_get_dbxref ($select_values) {
  *   dbxref.accession
  * @param $db_id
  *   dbxref.db_id
- * @return 
+ * @return
  *   chado dbxref object with all fields from the chado dbxref table
  *
  * @ingroup tripal_db_api
  */
-function tripal_db_get_dbxref_by_accession ($accession, $db_id=0) {
+function tripal_db_get_dbxref_by_accession($accession, $db_id=0) {
 
   if (!empty($db_id)) {
-	  $previous_db = tripal_db_set_active('chado');
+    $previous_db = tripal_db_set_active('chado');
     $r = db_fetch_object(db_query(
-      "SELECT * FROM dbxref WHERE accession='%s' AND db_id=%d",
+      "SELECT * FROM {dbxref} WHERE accession='%s' AND db_id=%d",
       $accession, $db_id
     ));
     tripal_db_set_active($previous_db);
-  } else {
-	  $previous_db = tripal_db_set_active('chado');
+  }
+  else {
+    $previous_db = tripal_db_set_active('chado');
     $r = db_fetch_object(db_query(
-      "SELECT * FROM dbxref WHERE accession='%s'",
+      "SELECT * FROM {dbxref} WHERE accession='%s'",
       $accession
     ));
-    tripal_db_set_active($previous_db);  
+    tripal_db_set_active($previous_db);
   }
-  
+
   return $r;
 }
 
@@ -286,7 +293,7 @@ function tripal_db_chado_dbxref_schema() {
         'columns' => array(
           'db_id' => 'db_id',
         ),
-  ); 
+  );
 
   return $description;
 }
@@ -304,7 +311,7 @@ function tripal_db_chado_dbxref_schema() {
 *   Optional. The URL that is to be used as a prefix when constructing a link to
 *   a database term
 * @param $update
-*   Optional. Set this to '1' to force an update of the database if it 
+*   Optional. Set this to '1' to force an update of the database if it
 *   already exists. The default is to not update. If the database exists
 *   then nothing is added.
 *
@@ -313,7 +320,7 @@ function tripal_db_chado_dbxref_schema() {
 *
 * @ingroup tripal_db_api
 */
-function tripal_db_add_db($dbname,$description='',$url='',$urlprefix='',$update=0){
+function tripal_db_add_db($dbname, $description='', $url='', $urlprefix='', $update=0) {
 
 
    $values = array(
@@ -322,24 +329,25 @@ function tripal_db_add_db($dbname,$description='',$url='',$urlprefix='',$update=
       'url' => $url,
       'urlprefix' => $urlprefix
    );
-      
+
    $db_sql = "SELECT * FROM {db} WHERE name ='%s'";
-   $db = db_fetch_object(db_query($db_sql,$dbname));
-   if(!$db){
-      if(!tripal_core_chado_insert('db',$values)){
-         watchdog('tripal_db', "Cannot create db '$dbname'.",NULL,WATCHDOG_WARNING);
+   $db = db_fetch_object(db_query($db_sql, $dbname));
+   if (!$db) {
+      if (!tripal_core_chado_insert('db', $values)) {
+         watchdog('tripal_db', "Cannot create db '$dbname'.", NULL, WATCHDOG_WARNING);
          return 0;
-      }      
-      $db = tripal_core_chado_select('db',array('*'),$values);
-   } 
-   elseif($update) {
+      }
+      $db = tripal_core_chado_select('db', array('*'), $values);
+   }
+   elseif ($update) {
       $match = array('db_id' => $db->db_id);
-      if(!tripal_core_chado_update('db',$match,$values)){
-         watchdog('tripal_db', "Cannot update db '$dbname'.",NULL,WATCHDOG_WARNING);
+      if (!tripal_core_chado_update('db', $match, $values)) {
+         watchdog('tripal_db', "Cannot update db '$dbname'.", NULL, WATCHDOG_WARNING);
          return 0;
-      }      
-      $db = tripal_core_chado_select('db',array('*'),$values);
-   } else {
+      }
+      $db = tripal_core_chado_select('db', array('*'), $values);
+   }
+   else {
       return $db;
    }
 }
@@ -347,7 +355,7 @@ function tripal_db_add_db($dbname,$description='',$url='',$urlprefix='',$update=
 *
 * @ingroup tripal_db_api
 */
-function tripal_db_add_dbxref($db_id,$accession,$version='',$description=''){
+function tripal_db_add_dbxref($db_id, $accession, $version='', $description='') {
 
    // check to see if the dbxref exists if not, add it
    $dbxsql = "
@@ -357,18 +365,18 @@ function tripal_db_add_dbxref($db_id,$accession,$version='',$description=''){
          INNER JOIN db DB on DB.db_id = DBX.db_id
       WHERE DBX.db_id = %d and DBX.accession = '%s'
    ";
-   $dbxref = db_fetch_object(db_query($dbxsql,$db_id,$accession));
-   if(!$dbxref){
+   $dbxref = db_fetch_object(db_query($dbxsql, $db_id, $accession));
+   if (!$dbxref) {
       $sql = "
          INSERT INTO {dbxref} (db_id, accession, version, description)
          VALUES (%d,'%s','%s','%s')
       ";
-      if(!db_query($sql,$db_id,$accession,$version,$description)){
-         watchdog('tripal_cv', "Failed to insert the dbxref record $accession",NULL,WATCHDOG_WARNING);
+      if (!db_query($sql, $db_id, $accession, $version, $description)) {
+         watchdog('tripal_cv', "Failed to insert the dbxref record $accession", NULL, WATCHDOG_WARNING);
          return 0;
       }
       print "Added Dbxref accession: $accession\n";
-      $dbxref = db_fetch_object(db_query($dbxsql,$db_id,$accession));
+      $dbxref = db_fetch_object(db_query($dbxsql, $db_id, $accession));
    }
    return $dbxref;
 

+ 7 - 2
tripal_db/tripal_db.install

@@ -1,11 +1,16 @@
 <?php
 
+/**
+ * @file
+ * Contains functions related to the installation of this module
+ */
+
 /**
 *  Implementation of hook_install();
 *
 * @ingroup tripal_db
 */
-function tripal_db_install(){
+function tripal_db_install() {
 
    // create the module's data directory
    tripal_create_moddir('tripal_db');
@@ -17,7 +22,7 @@ function tripal_db_install(){
 *
 * @ingroup tripal_db
 */
-function tripal_db_uninstall(){
+function tripal_db_uninstall() {
 
 }
 

+ 80 - 75
tripal_db/tripal_db.module

@@ -6,16 +6,16 @@ require_once "tripal_db.api.inc";
  * @defgroup tripal_db DB Module
  * @ingroup tripal_modules
  */
- 
+
 /**
 *
 * @ingroup tripal_db
 */
-function tripal_db_init(){
+function tripal_db_init() {
 
    // add the tripal_db JS and CSS
-   drupal_add_css(drupal_get_path('theme', 'tripal').'/css/tripal_db.css');
-   drupal_add_js(drupal_get_path('theme', 'tripal').'/js/tripal_db.js');
+   drupal_add_css(drupal_get_path('theme', 'tripal') . '/css/tripal_db.css');
+   drupal_add_js(drupal_get_path('theme', 'tripal') . '/js/tripal_db.js');
 }
 /**
 *
@@ -39,7 +39,7 @@ function tripal_db_menu() {
      'access arguments' => array('administer site configuration'),
      'type' => MENU_NORMAL_ITEM,
    );
-   
+
    $items['admin/tripal/tripal_db/add_db'] = array(
      'title' => 'Add a Database',
      'page callback' => 'drupal_get_form',
@@ -64,7 +64,7 @@ function tripal_db_menu() {
 *
 * @ingroup tripal_db
 */
-function tripal_db_perm(){
+function tripal_db_perm() {
    return array(
       'access chado_db content',
       'create chado_db content',
@@ -82,7 +82,7 @@ function tripal_db_perm(){
  * @ingroup tripal_db
  */
 function tripal_db_views_api() {
-	return array('api' => 2.0);
+  return array('api' => 2.0);
 }
 
 /**
@@ -97,42 +97,42 @@ function tripal_db_module_description_page() {
 
   $text = '<h3>Tripal External Database Administrative Tools Quick Links</h3>';
     $text .= '<ul>';
-      $text .= '<li>'.l('Add External DB', 'admin/tripal/tripal_db/add_db').'</li>';
-      $text .= '<li>'.l('Update/Delete External DBs', 'admin/tripal/tripal_db/edit_db').'</li>';
-      $text .= '<li>'.l('Database References Listing', 'admin/tripal/tripal_db/list_dbxrefs').'</li>';
+      $text .= '<li>' . l('Add External DB', 'admin/tripal/tripal_db/add_db') . '</li>';
+      $text .= '<li>' . l('Update/Delete External DBs', 'admin/tripal/tripal_db/edit_db') . '</li>';
+      $text .= '<li>' . l('Database References Listing', 'admin/tripal/tripal_db/list_dbxrefs') . '</li>';
     $text .= '</ul>';
-    
+
   $text .= '<h3>Module Description:</h3>';
   $text .= '<p>The Tripal DB Module provides functionality for linking the data in your Tripal Website with other biological websites out there. Essentially you register an enternal database with your website and then associate any of your data (usually sequence features) with that external database by providing the accession for your data in the other database. If the other database is online and you provided a URL prefix when you registered the external database with your site then there will be a link on the details page for your data that takes the user to the same record in the external database.</p>';
 
   $text .= '<h3>Setup Instructions:</h3>';
   $text .= '<ol>';
-  $text .= '<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, 
+  $text .= '<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>';
   $text .= '<li><b>Register any external databases</b> with data pertinent to your site.</li>';
   $text .= '<li><b>Create Database References</b>: Then as you load in your data, create database references linking your data to the external database.</li>';
   $text .= '</ol>';
-  
-  
+
+
   $text .= '<h3>Features of this Module:</h3>';
   $text .= '<ul>';
   $text .= '<li><b>Add/Register External Databases</b>:';
   $text .= 'By entering the name and any additional details into the <a href="tripal_db/add_db">add database form</a> you register an external database with your website. This allows you to specify that a sequence feature or other data is also stored in an external database. This is escpecially useful if the external database may contain additional details not stored in yours. If the external database is online you can even provide a URL prefix which will automatically link any data in your website to theirs via a web link.</li>';
-  
+
   $text .= '<li><b>Update/Delete External Databases</b>';
   $text .= 'To edit the details of an external database record or to delete an already existing external database, go to the <a href="tripal_db/edit_db">Update/Delete DBs form</a>. This will allow you to change details or enter new details.</li>';
 
   $text .= '<li><b>List all External Database References</b>';
   $text .= 'If you have views installed, there will be a link to a default listing of all database references currently in your database. This listing can be accessed <a href="tripal_db/list_dbxrefs">here</a>. It requires the Drupal Module Views version 2 to be installed (<a href="http://drupal.org/project/views">Drupal Views</a>)</li>';
-  $text .= '</ul>';  
-  
+  $text .= '</ul>';
+
   return $text;
 }
 
@@ -141,9 +141,9 @@ function tripal_db_module_description_page() {
 *
 * @ingroup tripal_db
 */
-function tripal_db_admin_page(){
+function tripal_db_admin_page() {
    $add_url = url("admin/tripal/tripal_db/add_db");
-   $output = "<a href=\"$add_url\">Add a new external database</a>"; 
+   $output = "<a href=\"$add_url\">Add a new external database</a>";
    $output .= drupal_get_form('tripal_db_select_form');
    $output .= '<div id="db-edit-div">Please select a database above to view or edit</div>';
    return $output;
@@ -153,21 +153,21 @@ function tripal_db_admin_page(){
 *
 * @ingroup tripal_db
 */
-function tripal_db_select_form(){
+function tripal_db_select_form() {
 
-	$previous_db = tripal_db_set_active('chado');  // use chado database
-	// get a list of db from chado for user to choose
-	$sql = "SELECT * FROM {db} WHERE NOT name = 'tripal' ORDER BY name ";
-	$results = db_query ($sql);
-	tripal_db_set_active($previous_db); // use drupal database
+  $previous_db = tripal_db_set_active('chado');  // use chado database
+  // get a list of db from chado for user to choose
+  $sql = "SELECT * FROM {db} WHERE NOT name = 'tripal' ORDER BY name ";
+  $results = db_query($sql);
+  tripal_db_set_active($previous_db); // use drupal database
 
-	$dbs = array();
+  $dbs = array();
    $dbs[] = '';
-	while ($db = db_fetch_object($results)){
-		$dbs[$db->db_id] = $db->name;
-	}
+  while ($db = db_fetch_object($results)) {
+    $dbs[$db->db_id] = $db->name;
+  }
 
-	$form['dbid'] = array(
+  $form['dbid'] = array(
       '#title' => t('External Database Name'),
       '#type' => 'select',
       '#options' => $dbs,
@@ -178,7 +178,7 @@ function tripal_db_select_form(){
          'event' => 'change',
          'method' => 'replace',
       ),
-	);
+  );
 
    return $form;
 }
@@ -186,47 +186,48 @@ function tripal_db_select_form(){
 *
 * @ingroup tripal_db
 */
-function tripal_ajax_db_edit (){ 
+function tripal_ajax_db_edit() {
    // get the database id, build the form and then return the JSON object
    $dbid = $_POST['dbid'];
-   $form = drupal_get_form('tripal_db_form',$dbid);
+   $form = drupal_get_form('tripal_db_form', $dbid);
    drupal_json(array('status' => TRUE, 'data' => $form));
 }
 /**
 *
 * @ingroup tripal_db
 */
-function tripal_db_form(&$form_state = NULL,$dbid = NULL){
+function tripal_db_form(&$form_state = NULL, $dbid = NULL) {
 
    // get this requested database
-   if($dbid){
-      $sql = "SELECT * FROM {db} WHERE db_id = $dbid ";
+   if ($dbid) {
+      $sql = "SELECT * FROM {db} WHERE db_id = %d ";
       $previous_db = tripal_db_set_active('chado');
-      $db = db_fetch_object(db_query($sql));
+      $db = db_fetch_object(db_query($sql, $dbid));
       tripal_db_set_active($previous_db);
 
 
-      # set the default values.  If there is a value set in the 
-      # form_state then let's use that, otherwise, we'll pull 
-      # the values from the database 
+      // set the default values.  If there is a value set in the
+      // form_state then let's use that, otherwise, we'll pull
+      // the values from the database
       $default_db = $form_state['values']['name'];
       $default_desc = $form_state['values']['description'];
       $default_url = $form_state['values']['url'];
       $default_urlprefix = $form_state['values']['urlprefix'];
-      if(!$default_db){
+      if (!$default_db) {
          $default_db = $db->name;
       }
-      if(!$default_desc){
+      if (!$default_desc) {
          $default_desc = $db->description;
       }
-      if(!$default_url){
+      if (!$default_url) {
          $default_url = $db->url;
       }
-      if(!$default_urlprefix){
+      if (!$default_urlprefix) {
          $default_urlprefix = $db->urlprefix;
       }
       $action = 'Update';
-   } else {
+   }
+   else {
       $action = 'Add';
    }
 
@@ -267,21 +268,22 @@ function tripal_db_form(&$form_state = NULL,$dbid = NULL){
    );
 
 
-   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,
@@ -297,7 +299,7 @@ function tripal_db_form(&$form_state = NULL,$dbid = NULL){
 *
 * @ingroup tripal_db
 */
-function tripal_db_form_submit($form, &$form_state){
+function tripal_db_form_submit($form, &$form_state) {
 
    $name =  $form_state['values']['name'];
    $desc =  $form_state['values']['description'];
@@ -306,10 +308,10 @@ function tripal_db_form_submit($form, &$form_state){
    $dbid =  $form_state['values']['dbid'];
    $op   =  $form_state['values']['op'];
 
-   if($dbid){ 
-      if(strcmp($op,'Update')==0){
+   if ($dbid) {
+      if (strcmp($op, 'Update')==0) {
          $sql = "
-            UPDATE {db} SET 
+            UPDATE {db} SET
               name = '%s',
               description = '%s',
               url = '%s',
@@ -317,45 +319,48 @@ function tripal_db_form_submit($form, &$form_state){
             WHERE db_id = %d
          ";
          $previous_db = tripal_db_set_active('chado');
-         $db = db_query($sql,$name,$desc,$url,$urlp,$dbid);
+         $db = db_query($sql, $name, $desc, $url, $urlp, $dbid);
          tripal_db_set_active($previous_db);
-         if($db){
+         if ($db) {
            drupal_set_message("External database updated");
-         } else {
+         }
+         else {
            drupal_set_message("Failed to update external database.");
          }
-      } 
-      if(strcmp($op,'Delete')==0){
+      }
+      if (strcmp($op, 'Delete')==0) {
          $sql = "
             DELETE FROM {db}
             WHERE db_id = %d
          ";
          $previous_db = tripal_db_set_active('chado');
-         $db = db_query($sql,$dbid);
+         $db = db_query($sql, $dbid);
          tripal_db_set_active($previous_db);
-         if($db){
+         if ($db) {
            drupal_set_message("External database deleted");
-         } else {
+         }
+         else {
            drupal_set_message("Failed to delete external database.");
          }
       }
-   } 
-   else { 
+   }
+   else {
       $sql = "
          INSERT INTO {db}
           (name,description,url,urlprefix)
-         VALUES 
+         VALUES
           ('%s','%s','%s','%s')
       ";
       $previous_db = tripal_db_set_active('chado');
-      $db = db_query($sql,$name,$desc,$url,$urlp);
+      $db = db_query($sql, $name, $desc, $url, $urlp);
       tripal_db_set_active($previous_db);
-      if($db){
+      if ($db) {
         drupal_set_message("External database added");
-      } else {
+      }
+      else {
         drupal_set_message("Failed to add external database.");
       }
-   } 
+   }
 
    return '';
 }

+ 6 - 6
tripal_db/tripal_db.views.inc

@@ -6,7 +6,7 @@
  *  chado/tripal db tables. Supplementary functions can be found in
  *  ./views/
  *
- *  Documentation on views integration can be found at 
+ *  Documentation on views integration can be found at
  *  http://views2.logrus.com/doc/html/index.html.
  */
 
@@ -17,13 +17,13 @@
  */
 
 require_once('views/dbxref.views.inc');
-require_once('views/db.views.inc'); 
+require_once('views/db.views.inc');
 /**
  * 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 
+ *   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)
  *
@@ -42,9 +42,9 @@ function tripal_db_views_data()  {
  *
  * @ingroup tripal_db_views
  */
-function tripal_db_views_default_views () {
+function tripal_db_views_default_views() {
   $views = array();
-  
+
   // Main default view
   // List all cvterms based on cv
   $view = new view;
@@ -306,6 +306,6 @@ function tripal_db_views_default_views () {
     'name' => 'navigation',
   ));
   $views[$view->name] = $view;
-  
+
   return $views;
 }

+ 0 - 45
tripal_db/views/README

@@ -1,45 +0,0 @@
-
-This directory contains all additional views code needed to integrate this module with views2.
-
-FILE/FOLDER DESCRIPTIONS
----------------------------
-<chado table name>.views.inc:
-	contains a single function retrieve_<chado table name>_views_data()
-	which describes that table to views. This function is called by
-	tripal_db_views_data() in ../tripal_db.views.inc.
-	For more information on the form of this data array look up the
-	views2 documentation for hook_views_data() 
-	-http://views2.logrus.com/doc/html/index.html
-	
-handlers/
-	Each file contained within this folder defines a views handler. Only custom
-	handlers are included in this folder and each must be described in 
-	hook_views_handlers() in ../tripal_db.views.inc.
-	A views handler does one of the following:
-		1) describe the type of a field and how it should be displayed
-		2) describe a method to sort this field
-		3) describe a method to filter this field
-
-
-STANDARDS TO FOLLOW
----------------------------
-
-1. All table definition files should be named tablename.views.inc
-2. All handlers should be in a handlers sub-directory and follow the naming convention of
-   views handlers (ie: views_handler_field/filter/sort_handlername.inc )
-
-Views Table Definitions:
-- Please use the template files provided whenever you are describing a new table to views.
-   For any table in chado simply copy template.table_defn.views.inc to tablename.views.inc and 
-   follow the instructions listed at the top of the template file.
-- ONLY ONE TABLE DEFINITION PER FILE
-- To join a chado table to it's drupal node simply copy template.node_join.views.inc to 
-   basetablename.views.inc and replace all XXX with basetablename.
-   
-   NOTE: Creating the table definition file is not enough. You also need to call the 
-         retrieve_XXX_views_data() function from ../tripal_db.views.inc:tripal_db_views_data()
-         by adding the following line:
-            $data = array_merge($data, retrieve_XXX_views_data());
-         to the function and including the file directly above the function (blow the function 
-         header by adding:
-            require_once('views/XXX.views.inc');

+ 21 - 20
tripal_db/views/db.views.inc

@@ -1,7 +1,8 @@
 <?php
 
   /**
- * Purpose: this function returns the portion of the data array 
+ * @file
+ * Purpose: this function returns the portion of the data array
  *   which describes the cv table, it's fields and any joins between it and other tables
  * @see tripal_cv_views_data() --in tripal_cv.views.inc
  *
@@ -21,7 +22,7 @@
  * @ingroup tripal_db_views
  */
 function retrieve_db_views_data() {
-  
+
   // Basic table definition
   $data['db']['table'] = array(
     'field' => 'db_id',
@@ -30,7 +31,7 @@ function retrieve_db_views_data() {
     'help' => 'Database Records existing in the Chado Database',
     'database' => 'chado'
   );
-  
+
   // Define relationships between this table and others
   $data['db']['table']['join'] = array(
     'dbxref' => array(
@@ -38,22 +39,22 @@ function retrieve_db_views_data() {
       'field' => 'db_id',
     ),
     'stock' => array(
-    	'left_table' => 'dbxref',
-    	'left_field' => 'db_id',
-    	'field' => 'db_id',
+      'left_table' => 'dbxref',
+      'left_field' => 'db_id',
+      'field' => 'db_id',
     ),
     'cvterm' => array(
-    	'left_table' => 'dbxref',
-    	'left_field' => 'db_id',
-    	'field' => 'db_id',
+      'left_table' => 'dbxref',
+      'left_field' => 'db_id',
+      'field' => 'db_id',
     ),
     'feature' => array(
-    	'left_table' => 'dbxref',
-    	'left_field' => 'db_id',
-    	'field' => 'db_id',
+      'left_table' => 'dbxref',
+      'left_field' => 'db_id',
+      'field' => 'db_id',
     ),
   );
-  
+
   // Table Field Definitions----------------------
   // Field: db_id (primary key)
   $data['db']['db_id'] = array(
@@ -70,7 +71,7 @@ function retrieve_db_views_data() {
       'handler' => 'views_handler_sort',
     ),
   );
-  
+
   // Field: name (varchar 255)
   $data['db']['name'] = array(
     'title' => 'Name',
@@ -88,7 +89,7 @@ function retrieve_db_views_data() {
       'handler' => 'views_handler_argument_string',
     ),
   );
-  
+
   // Field: description (varchar 255)
   $data['db']['description'] = array(
     'title' => 'Description',
@@ -106,7 +107,7 @@ function retrieve_db_views_data() {
       'handler' => 'views_handler_argument_string',
     ),
   );
-  
+
   // Field: urlprefix (varchar 255)
   $data['db']['urlprefix'] = array(
     'title' => 'URL Prefix',
@@ -125,7 +126,7 @@ function retrieve_db_views_data() {
       'handler' => 'views_handler_argument_string',
     ),
   );
-  
+
   // Field: url (varchar 255)
   $data['db']['url'] = array(
     'title' => 'URL',
@@ -144,7 +145,7 @@ function retrieve_db_views_data() {
       'handler' => 'views_handler_argument_string',
     ),
   );
-  
+
   return $data;
-  
-}
+
+}

+ 5 - 4
tripal_db/views/dbxref.views.inc

@@ -1,7 +1,8 @@
 <?php
 
 /**
- * Purpose: this function returns the portion of the data array 
+ * @file
+ * Purpose: this function returns the portion of the data array
  *   which describes the db table, it's fields and any joins between it and other tables
  * @see tripal_db_views_data() --in tripal_db.views.inc
  *
@@ -45,7 +46,7 @@ function retrieve_dbxref_views_data() {
     'stock' => array(
       'left_field' => 'dbxref_id',
       'field' => 'dbxref_id',
-    ),  
+    ),
   );
 
   // Table Field Definitions----------------------
@@ -64,7 +65,7 @@ function retrieve_dbxref_views_data() {
       'handler' => 'views_handler_sort',
     ),
   );
-   
+
   //Field: cv_id (foreign key: cv)
   //  join between cv table and this one in cv.views.inc
 
@@ -146,4 +147,4 @@ function retrieve_dbxref_views_data() {
 
   return $data;
 
-}
+}

+ 0 - 84
tripal_db/views/template.node_join.views.inc

@@ -1,84 +0,0 @@
-<?php
-
-/*************************************************************************
- * @file: THIS IS A TEMPLATE AND SHOULD NOT BE INCLUDED IN THE MODULE CODE
- *
- *  - simply replace all XXX with the original chado table you want to join to it's drupal nodes.
- *    (ie: If you want to join features to their drupal nodes then XXX=feature)
- * 
- *  NOTE: Creating the table definition file is not enough. You also need to call the 
- *        retrieve_XXX_views_data() function from ../tripal_db.views.inc:tripal_db_views_data()
- *        by adding the following line:
- *           $data = array_merge($data, retrieve_XXX_views_data());
- *        to the function and including the file directly above the function (blow the function 
- *        header by adding:
- *           require_once('views/XXX.views.inc');
- *
- *  REMOVE THIS COMMENT IN THE COPY!
- */ 
- 
-/**
- *  @file
- *  This file defines the data array for a given chado table. This array
- *  is merged into a larger array containing definitions of all tables associated
- *  with this module in:
- *  @see tripal_db.views.inc --in tripal_db_views_data()
- *
- *  Note: All chado tables are joined to their drupal nodes through the chado_XXX linking table. 
- *        This file simply defines this linking table and joins the three tables together.
- *        No modification of XXX.views.inc is needed.
- *
- *  Documentation on views integration can be found at 
- *  http://views2.logrus.com/doc/html/index.html.
- */
- 
-/**
- * Purpose: this function returns the portion of the data array 
- *   which describes the chado_XXX drupal table, it's fields and any joins between it 
- *   and other tables
- * @see tripal_db_views_data() --in tripal_db.views.inc
- *
- * The main need for description of this table to views is to join chado data with drupal nodes
- *
- */
-function retrieve_chado_XXX_views_data () {
-	global $db_url;
-  $data = array();
-  
-  // if the chado database is not local to the drupal database
-  // then we need to set the database name.  This should always
-  // be 'chado'.
-  if(is_array($db_url) and array_key_exists('chado',$db_url)){
-     // return empty data array b/c if chado is external then no join to the nodetable can be made
-     return $data;
-  }
-
-  //Basic table definition-----------------------------------
-  $data['chado_XXX']['table'] = array(
-    'field' => 'nid',
-  );
-  
-  //Relationship Definitions---------------------------------
-  // Note: No joins need to be made from $data['XXX']['table']
-  
-  // Join the chado_XXX table to XXX
-  $data['chado_XXX']['table']['join']['XXX'] = array(
-  	'left_field' => 'XXX_id',
-  	'field' => 'XXX_id',
-  );
-  
-  // Join the node table to chado_XXX
-  $data['node']['table']['join']['chado_XXX'] = array(
-  	'left_field' => 'nid',
-  	'field' => 'nid',
-  );
-  
-  // Join the node table to XXX
-  $data['node']['table']['join']['XXX'] = array(
-  	'left_table' => 'chado_XXX',
-  	'left_field' => 'nid',
-  	'field' => 'nid',
-  );  
-
-	return $data;
-}

+ 0 - 211
tripal_db/views/template.table_defn.views.inc

@@ -1,211 +0,0 @@
-<?php
-
-/*************************************************************************
- * @file: THIS IS A TEMPLATE AND SHOULD NOT BE INCLUDED IN THE MODULE CODE
- *
- *   - Every instance of XXX should be replaced with the name of your table
- *   - If this is a base table (you want a view where every row is a row from this table)
- *     then change $data['XXX']['table'] to $data['XXX']['table']['base'] 
- *     and $data['XXX']['table']['database'] to $data['XXX']['table']['base']['database']
- *   - Relationships between this table and others: YYY is the table you are trying to join to this
- *     one. You want to join a table to this one if this table contains a foreign key to the other
- *     table. If the join between this table and another is through a linking table
- *     (ie: library-XXX/YYY => library_feature-XY => feature-XXX/YYY) then make the join in both
- *     directions (ie: in the file XXX.views.inc and the file YYY.views.inc
- *   - Create a field definition for each field in this table using the example fields already
- *     listed. Match the type of the database field to the field definition listed below.
- *     (ie: for a text/varchar field from the database use plain_text_field below)
- * 
- *  NOTE: Creating the table definition file is not enough. You also need to call the 
- *        retrieve_XXX_views_data() function from ../tripal_db.views.inc:tripal_db_views_data()
- *        by adding the following line:
- *           $data = array_merge($data, retrieve_XXX_views_data());
- *        to the function and including the file directly above the function (blow the function 
- *        header by adding:
- *           require_once('views/XXX.views.inc');
- *
- *  REMOVE THIS COMMENT IN THE COPY!
- */ 
- 
-/**
- *  @file
- *  This file defines the data array for a given chado table. This array
- *  is merged into a larger array containing definitions of all tables associated
- *  with this module in:
- *  @see tripal_db.views.inc --in tripal_db_views_data()
- *
- *  Documentation on views integration can be found at 
- *  http://views2.logrus.com/doc/html/index.html.
- */
-
-/*************************************************************************
- * Purpose: this function returns the portion of the data array 
- *   which describes the XXX table, it's fields and any joins between it and other tables
- * @see tripal_db_views_data() --in tripal_db.views.inc
- *
- * Table: XXX
- * @code
- * XXX-Copy/Paste Table SQL code here-XXX
- * @endcode
- */
- function retrieve_XXX_views_data() {
-  global $db_url;
-  $data = array();
-
-  // if the chado database is not local to the drupal database
-  // then we need to set the database name.  This should always
-  // be 'chado'.
-  if(is_array($db_url) and array_key_exists('chado',$db_url)){
-    $database = 'chado';
-  }
-   
-  //Basic table definition-----------------------------------
-  $data['XXX']['table']['group'] = t('Chado XXX');
-  
-  $data['XXX']['table'] = array(
-    'field' => 'primary_id',
-    'title' => t('Chado XXX'),
-    'help' => t('Enter some user-friendly description of this tables purpose to the user.'),
-  );
-  if($database){
-     $data['XXX']['table']['database'] = $database;
-  }
-
-  
-  //Relationship Definitions---------------------------------
-  //Join: YYY => XXX
-  // Notice that this relationship tells the primary table to show it's fields to the
-  // table referencing it by a foreign key and thus the relationship is from
-  // primary table to table referenceing it (ie: cvterm => feature)
-  $data['XXX']['table']['join']['YYY'] = array(
-    'left_field' => 'foreign key in YYY table',
-    'field' => 'primary key in XXX table',
-  );  
-  
-  //Join: XXX => XY => YYY
-  // This relationship should be described in both directions
-  // in the appropriate files (ie: for feature => library 
-  // describe in both feature.views.inc and library.views.inc)
-  $data['XXX']['table']['join']['XY'] = array(
-    'left_field' => 'matching XXX key in the XY table',
-    'field' => 'primary key in XXX table',
-  );  
-  $data['XXX']['table']['join']['YYY'] = array(
-    'left_table' => 'XY',
-    'left_field' => 'matching XXX key in the XY table',
-    'field' => 'primary key in XXX table',
-  );
-  $data['XY']['table']['join']['YYY'] = array(
-    'left_field' => 'primary key in YYY table',
-    'field' => 'matching YYY key in the XY table',
-  );
-   
-  //Table Field Definitions----------------------------------
-      
-  //Field: XXX_id (primary key)
-  $data['XXX']['field_name'] = array(
-    'title' => t('XXX Primary Key'),
-    'help' => t('A unique index for every XXX.'),
-    'field' => array(
-      'handler' => 'views_handler_field_numeric',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_numeric',
-    ),
-  );
-
-  /*.......................................................
-   * Beginning of Example Field definitions
-   * Remove this section when done
-   */
-
-  //Field: plain_text_field (chado datatype)   
-  $data['XXX']['plain_text_field'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_string',
-    ),
-    'argument' => array(
-      'handler' => 'views_handler_argument_string',
-    ),
-  );
-
-  //Field: numeric_field (chado datatype)   
-  $data['XXX']['numeric_field'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_numeric',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_numeric',
-    ),
-  );
-
-  //Field: boolean_field (chado datatype)   
-  $data['XXX']['boolean_field'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_boolean',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_boolean_operator',
-    ),
-  );
-
-  //Field: unix_timestamp (chado datatype)   
-  $data['XXX']['unix_timestamp'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_date',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort_date',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_date',
-    ),
-  );
-
-  //Field: human_readable_date (chado datatype)   
-  $data['XXX']['human_readable_date'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_readble_date',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort_date',
-    ),
-  );
-   
-   /*
-    * End of Example Field definitions
-    */
-    
-  return $data;
-}

+ 21 - 21
tripal_stock/tripal_stock.views.inc

@@ -6,7 +6,7 @@
  *  chado/tripal stock tables. Supplementary functions can be found in
  *  ./views/
  *
- *  Documentation on views integration can be found at 
+ *  Documentation on views integration can be found at
  *  http://views2.logrus.com/doc/html/index.html.
  */
 
@@ -16,28 +16,28 @@
  * @ingroup tripal_stock
  */
 
-require_once('views/stock.views.inc');
-require_once('views/chado_stock.views.inc');
-require_once('views/misc_tables.views.inc'); 
 /**
  * Implements hook_views_data(): Describe chado/tripal tables & fields to views
  *
  * @return array
  *   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 
+ *   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_stock_views
  */
+require_once('views/stock.views.inc');
+require_once('views/chado_stock.views.inc');
+require_once('views/misc_tables.views.inc');
 function tripal_stock_views_data()  {
   $data = array();
 
   $data = array_merge($data, retrieve_stock_views_data());
   $data = array_merge($data, retrieve_chado_stock_views_data());
   $data = array_merge($data, retrieve_stock_misc_tables_views_data());
-  
+
   return $data;
 }
 
@@ -45,7 +45,7 @@ function tripal_stock_views_data()  {
  * Implements hook_views_handlers()
  *
  * Purpose: Register all custom handlers with views
- *   where a handler describes either "the type of field", 
+ *   where a handler describes either "the type of field",
  *   "how a field should be filtered", "how a field should be sorted"
  *
  * @return array
@@ -119,7 +119,7 @@ function tripal_stock_views_data_alter(&$data) {
       ),
     );
   }
-  
+
 }
 
 /**
@@ -136,18 +136,18 @@ function tripal_stock_views_data_alter(&$data) {
  */
 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);
-		
+
 		// 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)) {
-		
+
 			//-----Properties------------------------------------------
 			$field_names = array_keys($view->field);
 			//if any property fields are in the current view
@@ -159,14 +159,14 @@ function tripal_stock_views_pre_render	(&$view) {
 				$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;
 				}
 			}
-		
+
 			//-----Relationships----------------------------------------
 			//if any relationship fields are in the current view
 			$relationship_field_names = preg_grep('/relationships/', $field_names);
@@ -182,7 +182,7 @@ function tripal_stock_views_pre_render	(&$view) {
 				$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);
@@ -196,7 +196,7 @@ function tripal_stock_views_pre_render	(&$view) {
 					}
 				}
 			}
-		
+
 			//-----DB References--------------------------------------------
 			//if any dbxref fields are in the current view
 			$dbxref_field_names = preg_grep('/dbxref/',$field_names);
@@ -210,14 +210,14 @@ function tripal_stock_views_pre_render	(&$view) {
 				$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;
 				}
 			}
-			
+
 		} //if there are stocks
 	} //if we're dealing with a stock view
 }
@@ -228,7 +228,7 @@ function tripal_stock_views_pre_render	(&$view) {
  */
 function tripal_stock_views_default_views() {
   $views = array();
-  
+
   $view = new view;
   $view->name = 'all_stocks';
   $view->description = 'This view lists all stocks by default. There are exposed filters available but no arguments are used.';
@@ -581,7 +581,7 @@ function tripal_stock_views_default_views() {
     'weight' => 0,
     'name' => 'navigation',
   ));
-  $views[$view->name] = $view;  
-  
+  $views[$view->name] = $view;
+
   return $views;
 }

+ 73 - 43
tripal_views/tripal_views.api.inc

@@ -1,5 +1,10 @@
 <?php
 
+/**
+ * @file
+ * API functions for Tripal Views Integration
+ */
+
 /**
  * Retrieve the views integration setup with the lightest priority for a given table
  *
@@ -7,19 +12,20 @@
  * and -10 is of highest priority.
  *
  * @param $table_name
- *   The name of the table to retrieve the setup ID for. This can be either a materialized 
+ *   The name of the table to retrieve the setup ID for. This can be either a materialized
  *   view or a chado table
  *
  * @return
  *   On success, the setup_id to use for integration of this table; otherwise FALSE
  */
-function tripal_views_get_lightest_priority_setup ($table_name) {
+function tripal_views_get_lightest_priority_setup($table_name) {
 
   $sql = "SELECT setup_id FROM {tripal_views} WHERE table_name='%s' ORDER BY priority ASC";
   $setup = db_fetch_object(db_query($sql, $table_name));
   if ($setup) {
-    return $setup->setup_id;  
-  } else {
+    return $setup->setup_id;
+  }
+  else {
     return FALSE;
   }
 }
@@ -27,13 +33,16 @@ function tripal_views_get_lightest_priority_setup ($table_name) {
 /**
  * Checks if you are dealing with the lightest priority setup for a given table
  */
-function tripal_views_is_lightest_priority_setup ($setup_id, $table_name) {
-  $lightest_priority_setup_id = tripal_views_get_lightest_priority_setup ($table_name);
+function tripal_views_is_lightest_priority_setup($setup_id, $table_name) {
+
+  $lightest_priority_setup_id = tripal_views_get_lightest_priority_setup($table_name);
   if ($lightest_priority_setup_id == $setup_id) {
     return TRUE;
-  } else {
+  }
+  else {
     return FALSE;
   }
+
 }
 
 /**
@@ -79,7 +88,7 @@ function tripal_views_is_lightest_priority_setup ($setup_id, $table_name) {
  */
 function tripal_views_integration_add_entry($defn_array) {
   $no_errors = TRUE;
-  
+
   // First insert into tripal_views
   $view_record = array(
     'table_name' => $defn_array['table'],
@@ -88,29 +97,29 @@ function tripal_views_integration_add_entry($defn_array) {
     'priority' => $defn_array['priority'],
   );
   if ($defn_array['type'] == 'mview') {
-      $mview = db_fetch_object(db_query("SELECT mview_id FROM tripal_mviews WHERE mv_table='%s'",$defn_array['table']));
+      $mview = db_fetch_object(db_query("SELECT mview_id FROM {tripal_mviews} WHERE mv_table='%s'", $defn_array['table']));
       $view_record['mview_id'] = $mview->mview_id;
       if (!$mview->mview_id) {
         return FALSE;
       }
   }
-  $status = drupal_write_record('tripal_views',$view_record);
-  
+  $status = drupal_write_record('tripal_views', $view_record);
+
   if ($status) {
-    
+
     // Insert Field Definitions
     foreach ($defn_array['fields'] as $field) {
       $field_record = array(
-      	'setup_id' => $view_record['setup_id'],
+        'setup_id' => $view_record['setup_id'],
         'column_name' => $field['name'],
         'name' => $field['title'],
         'description' => $field['description'],
         'type' => $field['type'],
       );
-      $status = drupal_write_record('tripal_views_field',$field_record);
-      
+      $status = drupal_write_record('tripal_views_field', $field_record);
+
       if ($status) {
-      
+
         // Insert Handler Definitions
         foreach ($field['handlers'] as $handler_type => $handler) {
           $handler_record = array(
@@ -120,16 +129,18 @@ function tripal_views_integration_add_entry($defn_array) {
             'handler_name' => $handler['name'],
             'arguments' => serialize($handler)
           );
-          $status = drupal_write_record('tripal_views_handlers',$handler_record);
+          $status = drupal_write_record('tripal_views_handlers', $handler_record);
           if (!$status) {
-            drupal_set_message('Unable to integrate '.$handler_type.' handler: '.$handler['name'], 'error');
+            drupal_set_message(t('Unable to integrate %handler_type handler: %handler_name', array('%handler_type' => $handler_type, '%handler_name' => $handler['name'])), 'error');
             $no_errors = FALSE;
           }
         }
-        
+
         // Insert Joins
-        if (!is_array($field['joins'])) { $field['joins'] = array(); }
-        foreach($field['joins'] as $join) {
+        if (!is_array($field['joins'])) {
+          $field['joins'] = array();
+        }
+        foreach ($field['joins'] as $join) {
           $join_record = array(
             'setup_id' => $view_record['setup_id'],
             'base_table' => $defn_array['table'],
@@ -139,29 +150,43 @@ function tripal_views_integration_add_entry($defn_array) {
           );
 
           if (!empty($join['handler'])) {
-          	$join_record['handler'] = $join['handler'];
-          } else {
-          	$join_record['handler'] = 'views_join';
+            $join_record['handler'] = $join['handler'];
+          }
+          else {
+            $join_record['handler'] = 'views_join';
           }
 
-          $status = drupal_write_record('tripal_views_join',$join_record);
+          $status = drupal_write_record('tripal_views_join', $join_record);
           if (!$status) {
-            drupal_set_message('Unable to join '.$join['table'].'.'.$join['field'].' with '.$defn_array['table'].'.'.$field['name'], 'error');
+            drupal_set_message(
+              t(
+                'Unable to join %left_table.%left_field with %table.%field',
+                array(
+                  '%left_table' => $join['table'],
+                  '%left_field' => $join['field'],
+                  '%table' => $defn_array['table'],
+                  '%field' => $field['name']
+                )
+              ),
+              'error'
+            );
             $no_errors = FALSE;
           }
         }
-        
-      } else {
-        drupal_set_message('Unable to integrate field: '.$field['name'],'error');
+
+      }
+      else {
+        drupal_set_message(t('Unable to integrate field: %field_name', array('%field_name' => $field['name'])), 'error');
         $no_errors = FALSE;
       }
     }
-    
-  } else {
-    drupal_set_message('Unable to set default views integration','error');
+
+  }
+  else {
+    drupal_set_message(t('Unable to set default views integration'), 'error');
     $no_errors = FALSE;
   }
-  
+
   return $no_errors;
 }
 
@@ -176,16 +201,21 @@ function tripal_views_integration_add_entry($defn_array) {
  * @return
  *   TRUE on Success; FALSE otherwise
  */
-function tripal_views_integration_remove_entry_by_table_name ($table_name, $priority) {
+function tripal_views_integration_remove_entry_by_table_name($table_name, $priority) {
 
-  $views = db_fetch_object(db_query("SELECT * FROM {tripal_views} WHERE table_name='%s' AND priority=%d",$table_name,$priority));
+  $views = db_fetch_object(db_query(
+    "SELECT * FROM {tripal_views} WHERE table_name='%s' AND priority=%d",
+    $table_name,
+    $priority
+  ));
   if ($views->setup_id) {
     tripal_views_integration_remove_entry_by_setup_id($views->setup_id);
-    return TRUE;  
-  } else {
+    return TRUE;
+  }
+  else {
     return FALSE;
   }
-  
+
 }
 
 /**
@@ -194,11 +224,11 @@ function tripal_views_integration_remove_entry_by_table_name ($table_name, $prio
  * @param $setup_id
  *   The setup ID of the views integration entry to remove
  */
-function tripal_views_integration_remove_entry_by_setup_id ($setup_id) {
+function tripal_views_integration_remove_entry_by_setup_id($setup_id) {
 
-    db_query('DELETE FROM {tripal_views} WHERE setup_id=%d',$setup_id);
-    db_query('DELETE FROM {tripal_views_field} WHERE setup_id=%d',$setup_id);
-    db_query('DELETE FROM {tripal_views_handlers} WHERE setup_id=%d',$setup_id);
-    db_query('DELETE FROM {tripal_views_join} WHERE setup_id=%d',$setup_id);
+    db_query('DELETE FROM {tripal_views} WHERE setup_id=%d', $setup_id);
+    db_query('DELETE FROM {tripal_views_field} WHERE setup_id=%d', $setup_id);
+    db_query('DELETE FROM {tripal_views_handlers} WHERE setup_id=%d', $setup_id);
+    db_query('DELETE FROM {tripal_views_join} WHERE setup_id=%d', $setup_id);
 
 }

+ 20 - 0
tripal_views/tripal_views.coder_ignores.txt

@@ -0,0 +1,20 @@
+; The file should be formatted this way :
+; file:line:warning-type
+; where warning-type is one of security, style, sql, i18n, comment, etc.
+
+; All <?php should be closed with a ?> in theme template files
+tripal_views_integration_fields_form.tpl.php:48:style
+tripal_views_data_export_download_form.tpl.php:8:style
+
+; All variables are set through the code and thus don't need to be filtered
+tripal_views_integration.inc:734:security
+
+; SQL queries the chado database which does not use the drupal prefixing functionality
+; therefore, curly brackets ({}) are not appropriate.
+views/handlers/views_handler_filter_chado_select_cvterm_name.inc:53:sql
+views/handlers/views_handler_filter_chado_select_cvterm_name.inc:61:sql
+views/handlers/views_handler_field_dbxref_accession_link.inc:31:sql
+
+; SQL queries the pg_tables table to check if a table exists in chado; drupal
+; prefixing is not appropriate
+views/handlers/views_handler_field_chado_rel_by_type.inc:22:sql

+ 266 - 252
tripal_views/tripal_views.install

@@ -1,279 +1,293 @@
 <?php
 
-/************************************************************************
-*  Implementation of hook_install();
-* 
-* @ingroup tripal_views
-*/
-function tripal_views_install(){
+/**
+ * @file
+ * Functions related to installing/uninstalling this module
+ */
 
-   // create the module's data directory
-   tripal_create_moddir('tripal_views');
+/**
+ * Implementation of hook_install().
+ *
+ * @ingroup tripal_views
+ */
+function tripal_views_install() {
+
+  // create the module's data directory
+  tripal_create_moddir('tripal_views');
 
   // create the tables that manage materialized views and jobs
   drupal_install_schema('tripal_views');
 
 }
 
-/************************************************************************
-* Implementation of hook_schema().
-*
-* @ingroup tripal_views
-*/
+/**
+ * Implementation of hook_schema().
+ *
+ * @ingroup tripal_views
+ */
 function tripal_views_schema() {
-   $schema = tripal_views_get_schemas();
-   return $schema;
+  $schema = tripal_views_get_schemas();
+  return $schema;
 }
-/************************************************************************
-* Implementation of hook_uninstall()
-*
-* @ingroup tripal_views
-*/
-function tripal_views_uninstall(){
-   drupal_uninstall_schema('tripal_views');
+/**
+ * Implementation of hook_uninstall().
+ *
+ * @ingroup tripal_views
+ */
+function tripal_views_uninstall() {
+  drupal_uninstall_schema('tripal_views');
 }
 
-/************************************************************************
-* This function simply defines all tables needed for the module to work
-* correctly.  By putting the table definitions in a separate function we
-* can easily provide the entire list for hook_install or individual
-* tables for an update.
-*
-* @ingroup tripal_views
-*/
-function tripal_views_get_schemas (){  
-   $schema = array();
+/**
+ * This function simply defines all tables needed for the module to work
+ * correctly.  By putting the table definitions in a separate function we
+ * can easily provide the entire list for hook_install or individual
+ * tables for an update.
+ *
+ * @ingroup tripal_views
+ */
+function tripal_views_get_schemas() {
+  $schema = array();
 
-   $temp = tripal_views_views_schema();
-   foreach ($temp as $table => $arr){ 
-      $schema[$table] = $arr; 
-   } 
+  $temp = tripal_views_views_schema();
+  foreach ($temp as $table => $arr) {
+    $schema[$table] = $arr;
+  }
 
-	return $schema;
+  return $schema;
 }
 
-/** 
- *
+/**
+ * Tripal Views Update for 6.x-0.4
+ *   - Add priority field to tripal_views
+ *   - Add handler field to tripal_views_join
+ *   - Add tripal_views_field table to keep track of fields for views integration
  */
-function tripal_views_update_6040 () {
-	$ret = array();
-	
-	// Add Priority to tripal_views
+function tripal_views_update_6040() {
+  $ret = array();
+
+  // Add Priority to tripal_views
   db_add_field($ret, 'tripal_views', 'priority', array('type' => 'int'));
-  db_add_unique_key($ret,'tripal_views', 'priority', array('table_name','priority'));
-	db_add_index($ret,'tripal_views', 'priority', array('table_name','priority'));
-	
-	// Add handler to tripal_views_join
-	db_add_field($ret, 'tripal_views_join', 'handler', array('type' => 'varchar','length' => '255','not null' => TRUE,'default' => ''));
+  db_add_unique_key($ret, 'tripal_views', 'priority', array('table_name', 'priority'));
+  db_add_index($ret, 'tripal_views', 'priority', array('table_name', 'priority'));
+
+  // Add handler to tripal_views_join
+  db_add_field($ret, 'tripal_views_join', 'handler', array('type' => 'varchar', 'length' => '255', 'not null' => TRUE, 'default' => ''));
+
+  // Add tripal_views_field to keep track of fields for views integration
+  $schema = tripal_views_views_schema();
+  db_create_table(&$ret, 'tripal_views_field', $schema['tripal_views_field']);
 
-	// Add tripal_views_field to keep track of fields for views integration
-	$schema = tripal_views_views_schema();
-	db_create_table(&$ret, 'tripal_views_field', $schema['tripal_views_field']);
-	
   return $ret;
 }
 
-/************************************************************************
-* 
-*
-* @ingroup tripal_views
-*/
-function tripal_views_views_schema(){
-   $schema = array();
-	$schema['tripal_views'] = array(
-		'description' => 'contains the setupes, their materialized view id and base table name that was used.',
-		'fields' => array(
-			'setup_id' => array(
-				'description' => 'the id of the setup',
-				'type' => 'serial',
-				'unsigned' => TRUE,
-				'not null' => TRUE,
-			),
-			'mview_id' => array(
-				'description' => 'the materialized view used for this setup',
-				'type' => 'int',
-				'unsigned' => TRUE,
-			),
-			'table_name' => array(
-				'description' => 'the base table name to be used when using this setup. Use this field when not using a materialized view',
-				'type' => 'varchar',
-				'length' => 255,
-				'not null' => TRUE,
-				'default' => '',
-			),
-			'priority' => array(
-				'description' => 'when there are 2+ entries for the same table, the entry with the lightest (drupal-style) priority is used.',
-				'type' => 'int',
-			),
-			'name' => array(
-				'description' => 'Human readable name of this setup',
-				'type' => 'varchar',
-				'length' => 255,
-				'not null' => TRUE,
-				'default' => '',
-			),
-			'comment' => array(
-				'description' => 'add notes about this views setup',
-				'type' => 'text',
-				'size' => 'normal',
-				'not null' => FALSE,
-				'default' => '',
-			),
-		),
-		'unique_keys' => array(
-			'setup_id' => array('setup_id'),
-			'priority' => array('table_name','priority'),
-		),
-		'indexes' => array(
-			'priority' => array('table_name','priority'),
-		),
-		'primary key' => array('setup_id'),
-	);
+/**
+ * Describe the Tripal Views Schema
+ *
+ * Tables include:
+ *   - tripal_views: main table for views integration setups
+ *   - tripal_views_field: keeps track of all fields related to a given views integration setup
+ *   - tripal_views_join: keeps track of joins between the current views integration setup
+ *       and other tables.
+ *   - tripal_views_handlers: keeps track of which handlers to use for a given field
+ *
+ * @ingroup tripal_views
+ */
+function tripal_views_views_schema() {
+  $schema = array();
+  $schema['tripal_views'] = array(
+    'description' => 'contains the setupes, their materialized view id and base table name that was used.',
+    'fields' => array(
+      'setup_id' => array(
+        'description' => 'the id of the setup',
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'mview_id' => array(
+        'description' => 'the materialized view used for this setup',
+        'type' => 'int',
+        'unsigned' => TRUE,
+      ),
+      'table_name' => array(
+        'description' => 'the base table name to be used when using this setup. Use this field when not using a materialized view',
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'priority' => array(
+        'description' => 'when there are 2+ entries for the same table, the entry with the lightest (drupal-style) priority is used.',
+        'type' => 'int',
+      ),
+      'name' => array(
+        'description' => 'Human readable name of this setup',
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'comment' => array(
+        'description' => 'add notes about this views setup',
+        'type' => 'text',
+        'size' => 'normal',
+        'not null' => FALSE,
+        'default' => '',
+      ),
+    ),
+    'unique_keys' => array(
+      'setup_id' => array('setup_id'),
+      'priority' => array('table_name', 'priority'),
+    ),
+    'indexes' => array(
+      'priority' => array('table_name', 'priority'),
+    ),
+    'primary key' => array('setup_id'),
+  );
+
+  $schema['tripal_views_field'] = array(
+    'description' => 'keep track of fields available for a given table',
+    'fields' => array(
+      'setup_id' => array(
+        'description' => 'the id of the setup',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'column_name' => array(
+        'description' => 'the name of the field in the database',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+      ),
+      'name' => array(
+        'description' => 'the human-readable name of the field',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+      ),
+      'description' => array(
+        'description' => 'A short description of the field -seen under the field in the views UI',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+      ),
+      'type' => array(
+        'description' => 'the database type of this field (ie: int, varchar)',
+        'type' => 'varchar',
+        'length' => '50',
+        'not null' => TRUE,
+      ),
+    ),
+    'primary key' => array('setup_id', 'column_name')
+  );
 
-	$schema['tripal_views_field'] = array(
-		'description' => 'keep track of fields available for a given table',
-		'fields' => array(
-			'setup_id' => array(
-				'description' => 'the id of the setup',
-				'type' => 'int',
-				'unsigned' => TRUE,
-				'not null' => TRUE,
-			),
-			'column_name' => array(
-				'description' => 'the name of the field in the database',
-				'type' => 'varchar',
-				'length' => '255',
-				'not null' => TRUE,
-			),
-			'name' => array(
-				'description' => 'the human-readable name of the field',
-				'type' => 'varchar',
-				'length' => '255',
-				'not null' => TRUE,
-			),
-			'description' => array(
-				'description' => 'A short description of the field -seen under the field in the views UI',
-				'type' => 'varchar',
-				'length' => '255',
-				'not null' => TRUE,
-			),
-			'type' => array(
-				'description' => 'the database type of this field (ie: int, varchar)',
-				'type' => 'varchar',
-				'length' => '50',
-				'not null' => TRUE,
-			),
-		),
-		'primary key' => array('setup_id','column_name')
-	);
-	
-	$schema['tripal_views_join'] = array(
-		'description' => 'coordinate the joining of tables',
-		'fields' => array(
-		  'view_join_id' => array(
-				'description' => 'the id of the join',
-				'type' => 'serial',
-				'unsigned' => TRUE,
-				'not null' => TRUE,
-		  ),
-			'setup_id' => array(
-				'description' => 'setup id from tripal_views table',
-				'type' => 'int',
-				'unsigned' => TRUE,
-				'not null'=> TRUE,
-			),
-			'base_table' => array(
-			   'description' => 'the name of the base table',
-				'type' => 'varchar',
-				'length' => '255',
-				'not null' => TRUE,
-				'default' => '',
-	      ),
-			'base_field' => array(
-				'description' => 'the name of the base table column that will be joined',
-				'type' => 'varchar',
-				'length' => '255',
-				'not null' => TRUE,
-				'default' => '',
-			),
-			'left_table' => array(
-				'description' => 'the table on which to perform a left join',
-				'type' => 'varchar',
-				'length' => '255',
-				'not null' => TRUE,
-				'default' => '',
-			),
-			'left_field' => array(
-				'description' => 'the column on which to perform a left join',
-				'type' => 'varchar',
-				'length' => '255',
-				'not null' => TRUE,
-				'default' => '',
-	      ),
-	      'handler' => array(
-					'description' => 'the name of the handler',
-					'type' => 'varchar',
-					'length' => '255',
-					'not null' => TRUE,
-					'default' => '',
-	      ),
-		),
-		'unique_keys' => array(
-			'setup_id' => array('view_join_id'),
-		),
-		'primary key' => array('view_join_id'),
-	);
+  $schema['tripal_views_join'] = array(
+    'description' => 'coordinate the joining of tables',
+    'fields' => array(
+      'view_join_id' => array(
+        'description' => 'the id of the join',
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'setup_id' => array(
+        'description' => 'setup id from tripal_views table',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'base_table' => array(
+         'description' => 'the name of the base table',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+        'default' => '',
+        ),
+      'base_field' => array(
+        'description' => 'the name of the base table column that will be joined',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'left_table' => array(
+        'description' => 'the table on which to perform a left join',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'left_field' => array(
+        'description' => 'the column on which to perform a left join',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+        'default' => '',
+        ),
+        'handler' => array(
+          'description' => 'the name of the handler',
+          'type' => 'varchar',
+          'length' => '255',
+          'not null' => TRUE,
+          'default' => '',
+        ),
+    ),
+    'unique_keys' => array(
+      'setup_id' => array('view_join_id'),
+    ),
+    'primary key' => array('view_join_id'),
+  );
 
-	$schema['tripal_views_handlers'] = array(
-		'description' => 'in formation for views: column and views handler name',
-		'fields' => array(
-			'handler_id' => array(
-				'description' => 'the id of the handler',
-				'type' => 'serial',
-			   'unsigned' => TRUE,
-			   'not null' => TRUE,
-	      ),
-			'setup_id' => array(
-				'description' => 'setup id from the tripal_views table',
-				'type' => 'int',
-				'unsigned' => TRUE,
-				'not null'=> TRUE,
-			),
-			'column_name' => array(
-				'description' => '',
-				'type' => 'varchar',
-				'length' => '255',
-				'not null' => TRUE,
-				'default' => '',
-			),
-			'handler_type' => array(
-				'description' => 'identifies the type of hander (e.g. field, filter, sort, argument, relationship, etc.)',
-				'type' => 'varchar',
-				'length' => '50',
-				'not null' => TRUE,
-				'default' => '',
-			),
-			'handler_name' => array(
-				'description' => 'the name of the handler',
-				'type' => 'varchar',
-				'length' => '255',
-				'not null' => TRUE,
-				'default' => '',
-			),
-			'arguments' => array(
-				'description' => 'arguments that may get passed to the handler',
-				'type' => 'text',
-				'size' => 'normal',
-				'not null' => FALSE,
-				'default' => '',
-			),
-		),
-		'unique_keys' => array(
-		   'setup_id' => array('handler_id'),
-	   ),
-		'primary key' => array('handler_id'),
-	);
+  $schema['tripal_views_handlers'] = array(
+    'description' => 'in formation for views: column and views handler name',
+    'fields' => array(
+      'handler_id' => array(
+        'description' => 'the id of the handler',
+        'type' => 'serial',
+         'unsigned' => TRUE,
+         'not null' => TRUE,
+        ),
+      'setup_id' => array(
+        'description' => 'setup id from the tripal_views table',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'column_name' => array(
+        'description' => '',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'handler_type' => array(
+        'description' => 'identifies the type of hander (e.g. field, filter, sort, argument, relationship, etc.)',
+        'type' => 'varchar',
+        'length' => '50',
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'handler_name' => array(
+        'description' => 'the name of the handler',
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'arguments' => array(
+        'description' => 'arguments that may get passed to the handler',
+        'type' => 'text',
+        'size' => 'normal',
+        'not null' => FALSE,
+        'default' => '',
+      ),
+    ),
+    'unique_keys' => array(
+       'setup_id' => array('handler_id'),
+    ),
+    'primary key' => array('handler_id'),
+  );
 
-   return $schema;
+  return $schema;
 }
-?>

+ 76 - 63
tripal_views/tripal_views.module

@@ -12,63 +12,64 @@ require_once "tripal_views_form_elements.inc";
  * @ingroup tripal_views
  */
 function tripal_views_menu() {
-   $items = array();
-   
-   $items['admin/tripal/views'] = array(
-     'title' => t('Views Integration'),
-     'description' => 'Integration with Drupal Views',
-     'page callback' => 'tripal_views_description_page',
-     'access arguments' => array('administer site configuration'),
-     'type' => MENU_NORMAL_ITEM,
-   );
+  $items = array();
 
- 	$items['admin/tripal/views/integration'] = array(
-     'title' => t('Integrated Tables'),
-     'description' => t('Provide a list of all integrated tables and allows for adding new tables or editing already integrated tables.'),
-     'page callback' => 'tripal_views_integration_setup_list',
-     'access arguments' => array('manage tripal_views_integration'),
-     'type' => MENU_NORMAL_ITEM,
- 	);
+  $items['admin/tripal/views'] = array(
+    'title' => 'Views Integration',
+    'description' => 'Integration with Drupal Views',
+    'page callback' => 'tripal_views_description_page',
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
+  );
 
+  $items['admin/tripal/views/integration'] = array(
+    'title' => 'Integrated Tables',
+    'description' => 'Provide a list of all integrated tables and allows for adding new tables or editing already integrated tables.',
+    'page callback' => 'tripal_views_integration_setup_list',
+    'access arguments' => array('manage tripal_views_integration'),
+    'type' => MENU_NORMAL_ITEM,
+  );
 
-	$items['admin/tripal/views/integration/new'] = array(
-     'title' => 'Integrate Views',
-     'page callback' => 'drupal_get_form',
-     'page arguments' => array('tripal_views_integration_form'),
-     'access arguments' => array('manage tripal_views_integration'), //TODO: figure out the proper permissions arguments
-     'type' => MENU_CALLBACK,
-	);
-	
-	$items['admin/tripal/views/integration/edit/%'] = array(
-     'title' => 'Edit Views Integration',
-     'page callback' => 'drupal_get_form',
-     'page arguments' => array('tripal_views_integration_form',5),
-     'access arguments' => array('manage tripal_views_integration'), //TODO: figure out the proper permissions arguments
-     'type' => MENU_CALLBACK,
-	);
+  $items['admin/tripal/views/integration/new'] = array(
+    'title' => 'Integrate Views',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_views_integration_form'),
+    'access arguments' => array('manage tripal_views_integration'), //TODO: figure out the proper permissions arguments
+    'type' => MENU_CALLBACK,
+  );
 
-	$items['admin/tripal/views/integration/delete/%'] = array(
-     'title' => 'Delete Views Integration',
-     'page callback' => 'tripal_views_integration_delete',
-     'page arguments' => array(5),
-     'access arguments' => array('manage tripal_views_integration'), //TODO: figure out the proper permissions arguments
-     'type' => MENU_CALLBACK,
-	);
+  $items['admin/tripal/views/integration/edit/%'] = array(
+    'title' => 'Edit Views Integration',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('tripal_views_integration_form', 5),
+    'access arguments' => array('manage tripal_views_integration'), //TODO: figure out the proper permissions arguments
+    'type' => MENU_CALLBACK,
+  );
 
-   return $items;
+  $items['admin/tripal/views/integration/delete/%'] = array(
+    'title' => 'Delete Views Integration',
+    'page callback' => 'tripal_views_integration_delete',
+    'page arguments' => array(5),
+    'access arguments' => array('manage tripal_views_integration'), //TODO: figure out the proper permissions arguments
+    'type' => MENU_CALLBACK,
+  );
+
+  return $items;
 }
+
 /**
  * Implements hook_views_api()
- * 
- * Purpose: Set the permission types that the chado module uses.  
+ *
+ * Purpose: Set the permission types that the chado module uses.
  *
  * @ingroup tripal_views
  */
-function tripal_views_perm(){
-   return array(
-      'manage tripal_views_integration',
-   );
+function tripal_views_perm() {
+  return array(
+    'manage tripal_views_integration',
+  );
 }
+
 /**
  * Implements hook_views_api()
  *
@@ -79,30 +80,42 @@ function tripal_views_perm(){
  * @ingroup tripal_views
  */
 function tripal_views_views_api() {
-   return array(
-      'api' => 2.0,
-   );
+  return array(
+    'api' => 2.0,
+  );
 }
+
 /**
  * Implements hook_theme()
  *
- * Purpose: this hook provides details about themable objects added by 
+ * Purpose: this hook provides details about themable objects added by
  *   this module
  *
  * @ingroup tripal_views
  */
-function tripal_views_theme () {
-   return array(
-	   'tripal_views_integration_form' => array(
-         'arguments' => array('form' => NULL),
-         'template'  => 'tripal_views_integration_fields_form',
-	   ),
-	   'tripal_views_data_export_download_form' => array(
-         'arguments' => array('form' => NULL),
-         'template'  => 'tripal_views_data_export_download_form',
-	   ),
-      'file_upload_combo' => array(
-        'arguments' => array('element' => NULL)
-      ),
-   );
+function tripal_views_theme() {
+  return array(
+    'tripal_views_integration_form' => array(
+      'arguments' => array('form' => NULL),
+      'template'  => 'tripal_views_integration_fields_form',
+    ),
+    'tripal_views_data_export_download_form' => array(
+      'arguments' => array('form' => NULL),
+      'template'  => 'tripal_views_data_export_download_form',
+    ),
+    'file_upload_combo' => array(
+      'arguments' => array('element' => NULL)
+    ),
+  );
+}
+
+/**
+ * Implements hook_coder_ignore().
+ * Defines the path to the file (tripal_views.coder_ignores.txt) where ignore rules for coder are stored
+ */
+function tripal_views_coder_ignore() {
+  return array(
+    'path' => drupal_get_path('module', 'tripal_views'),
+    'line prefix' => drupal_get_path('module', 'tripal_views'),
+  );
 }

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 484 - 474
tripal_views/tripal_views.views.inc


+ 11 - 1
tripal_views/tripal_views_data_export_download_form.tpl.php

@@ -1,2 +1,12 @@
-<?php print drupal_render($form); ?>
+<?php
 
+/**
+ * @file
+ * Render the views data export form on views pages
+ * Allows you to select a download type without using Feed icons
+ */
+print drupal_render($form);
+
+?>
+
+<!-- END -->

+ 56 - 48
tripal_views/tripal_views_form_elements.inc

@@ -1,72 +1,80 @@
 <?php
 
+/**
+ * @file
+ * Form elements used for tripal views
+ */
+
 /**
  * Register form elements
  */
 function tripal_views_elements() {
 
-   $type['file_upload_combo'] = array(
-      '#input' => TRUE,
-      '#process' => array('expand_file_upload_combo'),
-      '#element_validate' => array('file_upload_combo_validate'),
-   );
-   return $type;
+  $type['file_upload_combo'] = array(
+    '#input' => TRUE,
+    '#process' => array('expand_file_upload_combo'),
+    '#element_validate' => array('file_upload_combo_validate'),
+  );
+
+  return $type;
 }
+
 /**
- * 
+ * Upload File and keep track of previously uploaded files
+ * Form element description
  */
-function expand_file_upload_combo ($element, $edit, $form_state, $complete_form) {
+function expand_file_upload_combo($element, $edit, $form_state, $complete_form) {
+
+  if (empty($element['#value'])) {
+    $element['#value'] = array(
+      'items' => '',
+      'items_file' => '',
+      'file_path' => '',
+    );
+  }
 
-	if (empty($element['#value'])) {
-    	$element['#value'] = array(
-         'items' => '',
-         'items_file' => '',
-         'file_path' => '',
-    	);
-  	}
-   //dpm($form_state);
+  $element['#tree'] = TRUE;
 
-	$element['#tree'] = TRUE;
+  $parents = $element['#parents'];
+  $parents[] = 'items';
+  $element['items'] = array(
+    '#type' => 'textarea',
+    '#default_value' => $element['#value']['items'],
+  );
+  $parents = $element['#parents'];
+  $parents[] = 'items_file';
+  $element['items_file'] = array(
+    '#type' => 'file',
+    '#title' =>  'File upload',
+    '#default_value' => $element['#value']['items_file'],
+  );
 
-	$parents = $element['#parents'];
-   $parents[] = 'items';
-   $element['items'] = array(
-      '#type' => 'textarea',
-		'#default_value' => $element['#value']['items'],
-   ); 
-	$parents = $element['#parents'];
-   $parents[] = 'items_file';
-   $element['items_file'] = array(
-      '#type' => 'file',
-      '#title' =>  'File upload',
-		'#default_value' => $element['#value']['items_file'],
-   ); 
+  $parents = $element['#parents'];
+  $parents[] = 'file_path';
+  $element['file_path'] = array(
+    '#type' => 'hidden',
+    '#default_value' => $element['#value']['file_path'],
+  );
 
-	$parents = $element['#parents'];
-   $parents[] = 'file_path';
-   $element['file_path'] = array(
-      '#type' => 'hidden',
-		'#default_value' => $element['#value']['file_path'],
-   );
-   return $element;
+  return $element;
 }
 
 /**
- * 
+ * Theme the file upload combo form element
  */
 function theme_file_upload_combo($element) {
-  	return theme('form_element', $element, '<div class="container-inline">'. $element['#children'] .'</div>');
+  return theme('form_element', $element, '<div class="container-inline">' . $element['#children'] . '</div>');
 }
 
 /**
- * 
+ * Validate all content passed into the file upload combo form element
  */
-function file_upload_combo_validate($element,&$form) {
-    $file = file_save_upload($element['#name'],array());
-    if($file) {
-       $form['values'][$element['#name']]['file_path'] = $file->filepath;
-       // we need to add our file path to the $_GET element as if it were
-       // submitted along with the rest of the form 
-       $_GET[$element['#name']]['file_path'] = $file->filepath;
-    }
+function file_upload_combo_validate($element, &$form) {
+  $file = file_save_upload($element['#name'], array());
+  if ($file) {
+    $form['values'][$element['#name']]['file_path'] = $file->filepath;
+    // we need to add our file path to the $_GET element as if it were
+    // submitted along with the rest of the form
+    $_GET[$element['#name']]['file_path'] = $file->filepath;
+  }
 }

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 358 - 342
tripal_views/tripal_views_integration.inc


+ 9 - 0
tripal_views/tripal_views_integration_fields_form.tpl.php

@@ -1,3 +1,10 @@
+<?php
+/**
+ * @file
+ * Template file for the views integration fields form.
+ */
+?>
+
 <style type="text/css">
 
 #tripal-views-integration-form  .fields-new-row, .field-headers {
@@ -44,3 +51,5 @@
 
 <?php print drupal_render($form); ?>
 
+<!-- END -->
+

+ 0 - 45
tripal_views/views/README

@@ -1,45 +0,0 @@
-
-This directory contains all additional views code needed to integrate this module with views2.
-
-FILE/FOLDER DESCRIPTIONS
----------------------------
-<chado table name>.views.inc:
-	contains a single function retrieve_<chado table name>_views_data()
-	which describes that table to views. This function is called by
-	tripal_core_views_data() in ../tripal_core.views.inc.
-	For more information on the form of this data array look up the
-	views2 documentation for hook_views_data() 
-	-http://views2.logrus.com/doc/html/index.html
-	
-handlers/
-	Each file contained within this folder defines a views handler. Only custom
-	handlers are included in this folder and each must be described in 
-	hook_views_handlers() in ../tripal_core.views.inc.
-	A views handler does one of the following:
-		1) describe the type of a field and how it should be displayed
-		2) describe a method to sort this field
-		3) describe a method to filter this field
-
-
-STANDARDS TO FOLLOW
----------------------------
-
-1. All table definition files should be named tablename.views.inc
-2. All handlers should be in a handlers sub-directory and follow the naming convention of
-   views handlers (ie: views_handler_field/filter/sort_handlername.inc )
-
-Views Table Definitions:
-- Please use the template files provided whenever you are describing a new table to views.
-   For any table in chado simply copy template.table_defn.views.inc to tablename.views.inc and 
-   follow the instructions listed at the top of the template file.
-- ONLY ONE TABLE DEFINITION PER FILE
-- To join a chado table to it's drupal node simply copy template.node_join.views.inc to 
-   basetablename.views.inc and replace all XXX with basetablename.
-   
-   NOTE: Creating the table definition file is not enough. You also need to call the 
-         retrieve_XXX_views_data() function from ../tripal_core.views.inc:tripal_core_views_data()
-         by adding the following line:
-            $data = array_merge($data, retrieve_XXX_views_data());
-         to the function and including the file directly above the function (blow the function 
-         header by adding:
-            require_once('views/XXX.views.inc');

+ 23 - 15
tripal_views/views/handlers/chado_views_handler_field.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_field.
+ *
+ * Handles fields which may be aggregated during the chado join process. This field
+ * will render an aggregated field as a pre_rendered list and will dynamically detect
+ * whether the field is aggregated or not.
+ */
 class chado_views_handler_field extends views_handler_field {
 
-  function init (&$view, $options) {
+  function init(&$view, $options) {
     include_once('chado_wrapper_functions.inc');
-    parent::init($view,$options);
+    parent::init($view, $options);
   }
-  
+
   /**
    * Defines the defaults for the options form
    */
@@ -18,13 +26,13 @@ class chado_views_handler_field extends views_handler_field {
 
     return $options;
   }
-  
+
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);
-    
+
     $form['type'] = array(
       '#type' => 'radios',
       '#title' => t('Display type'),
@@ -44,29 +52,29 @@ class chado_views_handler_field extends views_handler_field {
       '#dependency' => array('radio:options[type]' => array('separator')),
     );
   }
-  
+
   /**
    * Determines whether the current field is aggregated or not
    * Note: The parent::query() takes care of adding the field to the query, etc.
    */
-  function query () {
+  function query() {
     parent::query();
     $this->aggregated = chado_wrapper_is_aggregated_by_join($this);
   }
-  
+
   /**
    * Splits the aggregated values up for use in rendering
    */
-  function pre_render (&$values) {
-    
+  function pre_render(&$values) {
+
     // further check the results to see if this field is a postgresql array
     $this->aggregated = chado_wrapper_is_aggregated_by_result($this, $values);
-    
+
     // Split Aggregated Results
     chado_wrapper_split_array_agg_results($this, $values);
-    
+
   }
-  
+
   /**
    * Render the field.
    *
@@ -79,9 +87,9 @@ class chado_views_handler_field extends views_handler_field {
   function render($values) {
     return chado_wrapper_render_items($this, $values);
   }
-  
+
   function parent_render($val) {
     return parent::render($val);
   }
-  
+
 }

+ 38 - 30
tripal_views/views/handlers/chado_views_handler_field_aggregate.inc

@@ -1,22 +1,30 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_field.
+ *
+ * Handles fields which may be aggregated during the chado join process. This field
+ * will render an aggregated field as a pre_rendered list and will dynamically detect
+ * whether the field is aggregated or not.
+ */
 class chado_views_handler_field_aggregate extends chado_views_handler_field {
-  
+
   function init(&$view, $options) {
     parent::init($view, $options);
-    
+
     if (!isset($this->chado_table_description)) {
-      $this->chado_table_description = module_invoke_all('chado_'.$this->table.'_schema');
-      foreach($this->chado_table_description['foreign keys'] as $defn) {
+      $this->chado_table_description = module_invoke_all('chado_' . $this->table . '_schema');
+      foreach ($this->chado_table_description['foreign keys'] as $defn) {
         if ($defn['table'] != $this->view->base_table) {
-          $join_table = module_invoke_all('chado_'.$defn['table'].'_schema');
+          $join_table = module_invoke_all('chado_' . $defn['table'] . '_schema');
           foreach ($join_table['fields'] as $fname => $f) {
-            $this->chado_table_description['fields'][$defn['table'] .'_'. $fname] = $f;
+            $this->chado_table_description['fields'][$defn['table'] . '_' . $fname] = $f;
           }
         }
       }
     }
-    
+
   }
 
   /**
@@ -28,7 +36,7 @@ class chado_views_handler_field_aggregate extends chado_views_handler_field {
     $form['format'] = array(
       '#type' => 'fieldset',
       '#title' => 'Format Output',
-      '#description' => t('The following fields specify how a single result of this field will be 
+      '#description' => t('The following fields specify how a single result of this field will be
         displayed. When there are multiple results of this field due to aggregation, each result
         will be rendered according to the following rules and then all results will be joined
         together based on the "Display Type" indicated.')
@@ -36,59 +44,59 @@ class chado_views_handler_field_aggregate extends chado_views_handler_field {
 
     $this->tokens = array();
     $value = array();
-    foreach( array_keys($this->chado_table_description['fields']) as $field ) {
+    foreach ( array_keys($this->chado_table_description['fields']) as $field ) {
       $t = '[' . $this->options['id'] . '-' . $field . ']';
       $this->tokens[$t] = t($field);
       $value[] = $t . ' == ' . $field;
     }
-    
+
     $form['format']['format_string'] = array(
       '#type' => 'textfield',
       '#title' => t('Format String'),
       '#description' => 'Use any of the format tokens below to indicate what fields you want displayed.',
       '#default_value' => ($this->options['format']['format_string']) ? $this->options['format']['format_string'] : implode(', ', array_keys($this->tokens)),
     );
-    
+
     $form['format']['tokens'] = array(
       '#type' => 'item',
       '#title' => 'Format Tokens',
-      '#value' => implode("<br />",$value),
+      '#value' => implode("<br />", $value),
     );
-    
+
   }
-  
+
   function query() {
     parent::query();
-    
+
     $this->table_definition = $this->query->get_table_info($this->table);
   }
 
 
-  function pre_render (&$values) {
-    
+  function pre_render(&$values) {
+
     if ($this->aggregated) {
-      foreach($values as $k => $v) {
+      foreach ($values as $k => $v) {
         $values[$k]->{$this->field_alias} = $this->split_array_agg_results($v->{$this->field_alias});
-        
-        foreach($values[$k]->{$this->field_alias} as &$val) {
-          
+
+        foreach ($values[$k]->{$this->field_alias} as &$val) {
+
           // First, get the token values
-          $subparts = explode(',',$val);
+          $subparts = explode(',', $val);
           $token_values = array();
-          foreach($subparts as $ssk => $ssv) {
-            if(preg_match('/(.*)::(.*)/',$ssv,$matches)) {
-              $token_values[ '[all-'.$matches[1].']' ] = $matches[2];
+          foreach ($subparts as $ssk => $ssv) {
+            if (preg_match('/(.*)::(.*)/', $ssv, $matches)) {
+              $token_values[ '[all-' . $matches[1] . ']' ] = $matches[2];
             }
           }
-          
+
           // Now manually sub them in
-          $val = str_replace(array_keys($token_values),$token_values,$this->options['format']['format_string']);
-          
+          $val = str_replace(array_keys($token_values), $token_values, $this->options['format']['format_string']);
+
         }
       }
 
     }
-    
+
   }
-	
+
 }

+ 23 - 15
tripal_views/views/handlers/chado_views_handler_field_boolean.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_field_boolean.
+ *
+ * Handles fields which may be aggregated during the chado join process. This field
+ * will render an aggregated field as a pre_rendered list and will dynamically detect
+ * whether the field is aggregated or not.
+ */
 class chado_views_handler_field_boolean extends views_handler_field_boolean {
 
-  function init (&$view, $options) {
+  function init(&$view, $options) {
     include_once('chado_wrapper_functions.inc');
-    parent::init($view,$options);
+    parent::init($view, $options);
   }
-  
+
   /**
    * Defines the defaults for the options form
    */
@@ -18,13 +26,13 @@ class chado_views_handler_field_boolean extends views_handler_field_boolean {
 
     return $options;
   }
-  
+
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);
-    
+
     $form['type'] = array(
       '#type' => 'radios',
       '#title' => t('Display type'),
@@ -44,29 +52,29 @@ class chado_views_handler_field_boolean extends views_handler_field_boolean {
       '#dependency' => array('radio:options[type]' => array('separator')),
     );
   }
-  
+
   /**
    * Determines whether the current field is aggregated or not
    * Note: The parent::query() takes care of adding the field to the query, etc.
    */
-  function query () {
+  function query() {
     parent::query();
     $this->aggregated = chado_wrapper_is_aggregated_by_join($this);
   }
-  
+
   /**
    * Splits the aggregated values up for use in rendering
    */
-  function pre_render (&$values) {
-    
+  function pre_render(&$values) {
+
     // further check the results to see if this field is a postgresql array
     $this->aggregated = chado_wrapper_is_aggregated_by_result($this, $values);
-    
+
     // Split Aggregated Results
     chado_wrapper_split_array_agg_results($this, $values);
-    
+
   }
-  
+
   /**
    * Render the field.
    *
@@ -79,9 +87,9 @@ class chado_views_handler_field_boolean extends views_handler_field_boolean {
   function render($values) {
     return chado_wrapper_render_items($this, $values);
   }
-  
+
   function parent_render($val) {
     return parent::render($val);
   }
-  
+
 }

+ 23 - 15
tripal_views/views/handlers/chado_views_handler_field_counter.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_field_counter.
+ *
+ * Handles fields which may be aggregated during the chado join process. This field
+ * will render an aggregated field as a pre_rendered list and will dynamically detect
+ * whether the field is aggregated or not.
+ */
 class chado_views_handler_field_counter extends views_handler_field_counter {
 
-  function init (&$view, $options) {
+  function init =(&$view, $options) {
     include_once('chado_wrapper_functions.inc');
-    parent::init($view,$options);
+    parent::init($view, $options);
   }
-  
+
   /**
    * Defines the defaults for the options form
    */
@@ -18,13 +26,13 @@ class chado_views_handler_field_counter extends views_handler_field_counter {
 
     return $options;
   }
-  
+
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);
-    
+
     $form['type'] = array(
       '#type' => 'radios',
       '#title' => t('Display type'),
@@ -44,29 +52,29 @@ class chado_views_handler_field_counter extends views_handler_field_counter {
       '#dependency' => array('radio:options[type]' => array('separator')),
     );
   }
-  
+
   /**
    * Determines whether the current field is aggregated or not
    * Note: The parent::query() takes care of adding the field to the query, etc.
    */
-  function query () {
+  function query() {
     parent::query();
     $this->aggregated = chado_wrapper_is_aggregated_by_join($this);
   }
-  
+
   /**
    * Splits the aggregated values up for use in rendering
    */
-  function pre_render (&$values) {
-    
+  function pre_render(&$values) {
+
     // further check the results to see if this field is a postgresql array
     $this->aggregated = chado_wrapper_is_aggregated_by_result($this, $values);
-    
+
     // Split Aggregated Results
     chado_wrapper_split_array_agg_results($this, $values);
-    
+
   }
-  
+
   /**
    * Render the field.
    *
@@ -79,9 +87,9 @@ class chado_views_handler_field_counter extends views_handler_field_counter {
   function render($values) {
     return chado_wrapper_render_items($this, $values);
   }
-  
+
   function parent_render($val) {
     return parent::render($val);
   }
-  
+
 }

+ 23 - 15
tripal_views/views/handlers/chado_views_handler_field_custom.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_field_custom.
+ *
+ * Handles fields which may be aggregated during the chado join process. This field
+ * will render an aggregated field as a pre_rendered list and will dynamically detect
+ * whether the field is aggregated or not.
+ */
 class chado_views_handler_field_custom extends views_handler_field_custom {
 
-  function init (&$view, $options) {
+  function init(&$view, $options) {
     include_once('chado_wrapper_functions.inc');
-    parent::init($view,$options);
+    parent::init($view, $options);
   }
-  
+
   /**
    * Defines the defaults for the options form
    */
@@ -18,13 +26,13 @@ class chado_views_handler_field_custom extends views_handler_field_custom {
 
     return $options;
   }
-  
+
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);
-    
+
     $form['type'] = array(
       '#type' => 'radios',
       '#title' => t('Display type'),
@@ -44,29 +52,29 @@ class chado_views_handler_field_custom extends views_handler_field_custom {
       '#dependency' => array('radio:options[type]' => array('separator')),
     );
   }
-  
+
   /**
    * Determines whether the current field is aggregated or not
    * Note: The parent::query() takes care of adding the field to the query, etc.
    */
-  function query () {
+  function query() {
     parent::query();
     $this->aggregated = chado_wrapper_is_aggregated_by_join($this);
   }
-  
+
   /**
    * Splits the aggregated values up for use in rendering
    */
-  function pre_render (&$values) {
-    
+  function pre_render(&$values) {
+
     // further check the results to see if this field is a postgresql array
     $this->aggregated = chado_wrapper_is_aggregated_by_result($this, $values);
-    
+
     // Split Aggregated Results
     chado_wrapper_split_array_agg_results($this, $values);
-    
+
   }
-  
+
   /**
    * Render the field.
    *
@@ -79,9 +87,9 @@ class chado_views_handler_field_custom extends views_handler_field_custom {
   function render($values) {
     return chado_wrapper_render_items($this, $values);
   }
-  
+
   function parent_render($val) {
     return parent::render($val);
   }
-  
+
 }

+ 23 - 15
tripal_views/views/handlers/chado_views_handler_field_date.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_field_date.
+ *
+ * Handles fields which may be aggregated during the chado join process. This field
+ * will render an aggregated field as a pre_rendered list and will dynamically detect
+ * whether the field is aggregated or not.
+ */
 class chado_views_handler_field_date extends views_handler_field_date {
 
-  function init (&$view, $options) {
+  function init(&$view, $options) {
     include_once('chado_wrapper_functions.inc');
-    parent::init($view,$options);
+    parent::init($view, $options);
   }
-  
+
   /**
    * Defines the defaults for the options form
    */
@@ -18,13 +26,13 @@ class chado_views_handler_field_date extends views_handler_field_date {
 
     return $options;
   }
-  
+
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);
-    
+
     $form['type'] = array(
       '#type' => 'radios',
       '#title' => t('Display type'),
@@ -44,29 +52,29 @@ class chado_views_handler_field_date extends views_handler_field_date {
       '#dependency' => array('radio:options[type]' => array('separator')),
     );
   }
-  
+
   /**
    * Determines whether the current field is aggregated or not
    * Note: The parent::query() takes care of adding the field to the query, etc.
    */
-  function query () {
+  function query() {
     parent::query();
     $this->aggregated = chado_wrapper_is_aggregated_by_join($this);
   }
-  
+
   /**
    * Splits the aggregated values up for use in rendering
    */
-  function pre_render (&$values) {
-    
+  function pre_render(&$values) {
+
     // further check the results to see if this field is a postgresql array
     $this->aggregated = chado_wrapper_is_aggregated_by_result($this, $values);
-    
+
     // Split Aggregated Results
     chado_wrapper_split_array_agg_results($this, $values);
-    
+
   }
-  
+
   /**
    * Render the field.
    *
@@ -79,9 +87,9 @@ class chado_views_handler_field_date extends views_handler_field_date {
   function render($values) {
     return chado_wrapper_render_items($this, $values);
   }
-  
+
   function parent_render($val) {
     return parent::render($val);
   }
-  
+
 }

+ 23 - 15
tripal_views/views/handlers/chado_views_handler_field_markup.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_field_markup.
+ *
+ * Handles fields which may be aggregated during the chado join process. This field
+ * will render an aggregated field as a pre_rendered list and will dynamically detect
+ * whether the field is aggregated or not.
+ */
 class chado_views_handler_field_markup extends views_handler_field_markup {
 
-  function init (&$view, $options) {
+  function init(&$view, $options) {
     include_once('chado_wrapper_functions.inc');
-    parent::init($view,$options);
+    parent::init($view, $options);
   }
-  
+
   /**
    * Defines the defaults for the options form
    */
@@ -18,13 +26,13 @@ class chado_views_handler_field_markup extends views_handler_field_markup {
 
     return $options;
   }
-  
+
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);
-    
+
     $form['type'] = array(
       '#type' => 'radios',
       '#title' => t('Display type'),
@@ -44,29 +52,29 @@ class chado_views_handler_field_markup extends views_handler_field_markup {
       '#dependency' => array('radio:options[type]' => array('separator')),
     );
   }
-  
+
   /**
    * Determines whether the current field is aggregated or not
    * Note: The parent::query() takes care of adding the field to the query, etc.
    */
-  function query () {
+  function query() {
     parent::query();
     $this->aggregated = chado_wrapper_is_aggregated_by_join($this);
   }
-  
+
   /**
    * Splits the aggregated values up for use in rendering
    */
-  function pre_render (&$values) {
-    
+  function pre_render(&$values) {
+
     // further check the results to see if this field is a postgresql array
     $this->aggregated = chado_wrapper_is_aggregated_by_result($this, $values);
-    
+
     // Split Aggregated Results
     chado_wrapper_split_array_agg_results($this, $values);
-    
+
   }
-  
+
   /**
    * Render the field.
    *
@@ -79,9 +87,9 @@ class chado_views_handler_field_markup extends views_handler_field_markup {
   function render($values) {
     return chado_wrapper_render_items($this, $values);
   }
-  
+
   function parent_render($val) {
     return parent::render($val);
   }
-  
+
 }

+ 23 - 15
tripal_views/views/handlers/chado_views_handler_field_math.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_field_math.
+ *
+ * Handles fields which may be aggregated during the chado join process. This field
+ * will render an aggregated field as a pre_rendered list and will dynamically detect
+ * whether the field is aggregated or not.
+ */
 class chado_views_handler_field_math extends views_handler_field_math {
 
-  function init (&$view, $options) {
+  function init(&$view, $options) {
     include_once('chado_wrapper_functions.inc');
-    parent::init($view,$options);
+    parent::init($view, $options);
   }
-  
+
   /**
    * Defines the defaults for the options form
    */
@@ -18,13 +26,13 @@ class chado_views_handler_field_math extends views_handler_field_math {
 
     return $options;
   }
-  
+
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);
-    
+
     $form['type'] = array(
       '#type' => 'radios',
       '#title' => t('Display type'),
@@ -44,29 +52,29 @@ class chado_views_handler_field_math extends views_handler_field_math {
       '#dependency' => array('radio:options[type]' => array('separator')),
     );
   }
-  
+
   /**
    * Determines whether the current field is aggregated or not
    * Note: The parent::query() takes care of adding the field to the query, etc.
    */
-  function query () {
+  function query() {
     parent::query();
     $this->aggregated = chado_wrapper_is_aggregated_by_join($this);
   }
-  
+
   /**
    * Splits the aggregated values up for use in rendering
    */
-  function pre_render (&$values) {
-    
+  function pre_render(&$values) {
+
     // further check the results to see if this field is a postgresql array
     $this->aggregated = chado_wrapper_is_aggregated_by_result($this, $values);
-    
+
     // Split Aggregated Results
     chado_wrapper_split_array_agg_results($this, $values);
-    
+
   }
-  
+
   /**
    * Render the field.
    *
@@ -79,9 +87,9 @@ class chado_views_handler_field_math extends views_handler_field_math {
   function render($values) {
     return chado_wrapper_render_items($this, $values);
   }
-  
+
   function parent_render($val) {
     return parent::render($val);
   }
-  
+
 }

+ 23 - 15
tripal_views/views/handlers/chado_views_handler_field_numeric.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_field_numeric.
+ *
+ * Handles fields which may be aggregated during the chado join process. This field
+ * will render an aggregated field as a pre_rendered list and will dynamically detect
+ * whether the field is aggregated or not.
+ */
 class chado_views_handler_field_numeric extends views_handler_field_numeric {
 
-  function init (&$view, $options) {
+  function init(&$view, $options) {
     include_once('chado_wrapper_functions.inc');
-    parent::init($view,$options);
+    parent::init($view, $options);
   }
-  
+
   /**
    * Defines the defaults for the options form
    */
@@ -18,13 +26,13 @@ class chado_views_handler_field_numeric extends views_handler_field_numeric {
 
     return $options;
   }
-  
+
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
     parent::options_form($form, $form_state);
-    
+
     $form['type'] = array(
       '#type' => 'radios',
       '#title' => t('Display type'),
@@ -44,29 +52,29 @@ class chado_views_handler_field_numeric extends views_handler_field_numeric {
       '#dependency' => array('radio:options[type]' => array('separator')),
     );
   }
-  
+
   /**
    * Determines whether the current field is aggregated or not
    * Note: The parent::query() takes care of adding the field to the query, etc.
    */
-  function query () {
+  function query() {
     parent::query();
     $this->aggregated = chado_wrapper_is_aggregated_by_join($this);
   }
-  
+
   /**
    * Splits the aggregated values up for use in rendering
    */
-  function pre_render (&$values) {
-    
+  function pre_render(&$values) {
+
     // further check the results to see if this field is a postgresql array
     $this->aggregated = chado_wrapper_is_aggregated_by_result($this, $values);
-    
+
     // Split Aggregated Results
     chado_wrapper_split_array_agg_results($this, $values);
-    
+
   }
-  
+
   /**
    * Render the field.
    *
@@ -79,9 +87,9 @@ class chado_views_handler_field_numeric extends views_handler_field_numeric {
   function render($values) {
     return chado_wrapper_render_items($this, $values);
   }
-  
+
   function parent_render($val) {
     return parent::render($val);
   }
-  
+
 }

+ 30 - 20
tripal_views/views/handlers/chado_views_handler_filter_boolean_operator.inc

@@ -1,5 +1,13 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_filter_boolean_operator.
+ *
+ * Handles fields which may be aggregated during the chado join process. There are options
+ * to filter the base table based on an aggregated table or just filter the aggregated
+ * table (showing blank for that field if there are no records in the aggregated table).
+ */
 class chado_views_handler_filter_boolean_operator extends views_handler_filter_boolean_operator {
 
   /**
@@ -10,48 +18,50 @@ class chado_views_handler_filter_boolean_operator extends views_handler_filter_b
       '#type' => 'item',
       '#value' => '<b>If this filter applies to a table that is aggregated, additionally options may be ignored.</b>'
     );
-    
+
     parent::options_form($form, $form_state);
-    
+
     $form['agg'] = array(
       '#type' => 'fieldset',
       '#title' => 'Apply to fields that are aggregated'
     );
-    
+
     $form['agg']['records_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter base table records'),
-      '#description' => t('Filters '.$this->view->base_table.' to only those with the value in the aggregate array.'),
+      '#description' => t('Filters %base_table to only those with the value in the aggregate array.', array('%base_table' => $this->view->base_table)),
       '#default_value' => (isset($this->options['records_with'])) ? $this->options['records_with'] : TRUE,
     );
-    
+
     $form['agg']['aggregates_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter aggregates displayed'),
-      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of '.$this->view->base_table.' records.'),
-      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,    
+      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of %base_table records.', array('%base_table' => $this->view->base_table)),
+      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,
     );
-    
+
   }
-  
+
   /**
    * If the table to be filtered is not aggregated uses the parent::query()
    * However, if it is uses postgresql any() function to compare
    */
-  function query () {
+  function query() {
     $this->ensure_my_table();
-    
-    
+
+
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
 
     if (!$this->aggregated) {
       parent::query();
-    } else {
+    }
+    else {
 
       // Only base records with value in the aggregated field
       // This doesn't restrict the items in the aggregate field
@@ -63,13 +73,13 @@ class chado_views_handler_filter_boolean_operator extends views_handler_filter_b
       }
 
       // To restrict the items in the aggregate...
-      // Tell the join handler about the filter 
+      // Tell the join handler about the filter
       // so it can be done in the join query
       if ($this->options['agg']['aggregates_with']) {
-        $table['join']->filter[] = $field ." = '". $this->value."'";
-      }    
+        $table['join']->filter[] = $field . " = '" . $this->value . "'";
+      }
     }
-    
+
   }
-  
+
 }

+ 29 - 20
tripal_views/views/handlers/chado_views_handler_filter_boolean_operator_string.inc

@@ -1,5 +1,13 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_filter_boolean_operator_string.
+ *
+ * Handles fields which may be aggregated during the chado join process. There are options
+ * to filter the base table based on an aggregated table or just filter the aggregated
+ * table (showing blank for that field if there are no records in the aggregated table).
+ */
 class chado_views_handler_filter_boolean_operator_string extends views_handler_filter_boolean_operator_string {
 
   /**
@@ -10,48 +18,49 @@ class chado_views_handler_filter_boolean_operator_string extends views_handler_f
       '#type' => 'item',
       '#value' => '<b>If this filter applies to a table that is aggregated, additionally options may be ignored.</b>'
     );
-    
+
     parent::options_form($form, $form_state);
-    
+
     $form['agg'] = array(
       '#type' => 'fieldset',
       '#title' => 'Apply to fields that are aggregated'
     );
-    
+
     $form['agg']['records_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter base table records'),
-      '#description' => t('Filters '.$this->view->base_table.' to only those with the value in the aggregate array.'),
+      '#description' => t('Filters %table to only those with the value in the aggregate array.', array('%table' => $this->view->base_table)),
       '#default_value' => (isset($this->options['records_with'])) ? $this->options['records_with'] : TRUE,
     );
-    
+
     $form['agg']['aggregates_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter aggregates displayed'),
-      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of '.$this->view->base_table.' records.'),
-      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,    
+      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of %table records.', array('%table' => $this->view->base_table)),
+      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,
     );
-    
+
   }
-  
+
   /**
    * If the table to be filtered is not aggregated uses the parent::query()
    * However, if it is uses postgresql any() function to compare
    */
-  function query () {
+  function query() {
     $this->ensure_my_table();
-    
-    
+
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
 
     if (!$this->aggregated) {
       parent::query();
-    } else {
+    }
+    else {
 
       // Only base records with value in the aggregated field
       // This doesn't restrict the items in the aggregate field
@@ -63,13 +72,13 @@ class chado_views_handler_filter_boolean_operator_string extends views_handler_f
       }
 
       // To restrict the items in the aggregate...
-      // Tell the join handler about the filter 
+      // Tell the join handler about the filter
       // so it can be done in the join query
       if ($this->options['agg']['aggregates_with']) {
-        $table['join']->filter[] = $field ." = '". $this->value."'";
-      }    
+        $table['join']->filter[] = $field . " = '" . $this->value . "'";
+      }
     }
-    
+
   }
-  
+
 }

+ 30 - 20
tripal_views/views/handlers/chado_views_handler_filter_date.inc

@@ -1,5 +1,13 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_filter_date.
+ *
+ * Handles fields which may be aggregated during the chado join process. There are options
+ * to filter the base table based on an aggregated table or just filter the aggregated
+ * table (showing blank for that field if there are no records in the aggregated table).
+ */
 class chado_views_handler_filter_date extends views_handler_filter_date {
 
   /**
@@ -10,48 +18,50 @@ class chado_views_handler_filter_date extends views_handler_filter_date {
       '#type' => 'item',
       '#value' => '<b>If this filter applies to a table that is aggregated, additionally options may be ignored.</b>'
     );
-    
+
     parent::options_form($form, $form_state);
-    
+
     $form['agg'] = array(
       '#type' => 'fieldset',
       '#title' => 'Apply to fields that are aggregated'
     );
-    
+
     $form['agg']['records_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter base table records'),
-      '#description' => t('Filters '.$this->view->base_table.' to only those with the value in the aggregate array.'),
+      '#description' => t('Filters %base_table to only those with the value in the aggregate array.', array('%base_table' => $this->view->base_table)),
       '#default_value' => (isset($this->options['records_with'])) ? $this->options['records_with'] : TRUE,
     );
-    
+
     $form['agg']['aggregates_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter aggregates displayed'),
-      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of '.$this->view->base_table.' records.'),
-      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,    
+      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of %base_table records.', array('%base_table' => $this->view->base_table)),
+      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,
     );
-    
+
   }
-  
+
   /**
    * If the table to be filtered is not aggregated uses the parent::query()
    * However, if it is uses postgresql any() function to compare
    */
-  function query () {
+  function query() {
     $this->ensure_my_table();
-    
-    
+
+
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
 
     if (!$this->aggregated) {
       parent::query();
-    } else {
+    }
+    else {
 
       // Only base records with value in the aggregated field
       // This doesn't restrict the items in the aggregate field
@@ -63,13 +73,13 @@ class chado_views_handler_filter_date extends views_handler_filter_date {
       }
 
       // To restrict the items in the aggregate...
-      // Tell the join handler about the filter 
+      // Tell the join handler about the filter
       // so it can be done in the join query
       if ($this->options['agg']['aggregates_with']) {
-        $table['join']->filter[] = $field ." = '". $this->value."'";
-      }    
+        $table['join']->filter[] = $field . " = '" . $this->value . "'";
+      }
     }
-    
+
   }
-  
+
 }

+ 30 - 20
tripal_views/views/handlers/chado_views_handler_filter_equality.inc

@@ -1,5 +1,13 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_filter_equality.
+ *
+ * Handles fields which may be aggregated during the chado join process. There are options
+ * to filter the base table based on an aggregated table or just filter the aggregated
+ * table (showing blank for that field if there are no records in the aggregated table).
+ */
 class chado_views_handler_filter_equality extends views_handler_filter_equality {
 
   /**
@@ -10,48 +18,50 @@ class chado_views_handler_filter_equality extends views_handler_filter_equality
       '#type' => 'item',
       '#value' => '<b>If this filter applies to a table that is aggregated, additionally options may be ignored.</b>'
     );
-    
+
     parent::options_form($form, $form_state);
-    
+
     $form['agg'] = array(
       '#type' => 'fieldset',
       '#title' => 'Apply to fields that are aggregated'
     );
-    
+
     $form['agg']['records_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter base table records'),
-      '#description' => t('Filters '.$this->view->base_table.' to only those with the value in the aggregate array.'),
+      '#description' => t('Filters %base_table to only those with the value in the aggregate array.', array('%base_table' => $this->view->base_table)),
       '#default_value' => (isset($this->options['records_with'])) ? $this->options['records_with'] : TRUE,
     );
-    
+
     $form['agg']['aggregates_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter aggregates displayed'),
-      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of '.$this->view->base_table.' records.'),
-      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,    
+      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of %base_table records.', array('%base_table' => $this->view->base_table)),
+      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,
     );
-    
+
   }
-  
+
   /**
    * If the table to be filtered is not aggregated uses the parent::query()
    * However, if it is uses postgresql any() function to compare
    */
-  function query () {
+  function query() {
     $this->ensure_my_table();
-    
-    
+
+
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
 
     if (!$this->aggregated) {
       parent::query();
-    } else {
+    }
+    else {
 
       // Only base records with value in the aggregated field
       // This doesn't restrict the items in the aggregate field
@@ -63,13 +73,13 @@ class chado_views_handler_filter_equality extends views_handler_filter_equality
       }
 
       // To restrict the items in the aggregate...
-      // Tell the join handler about the filter 
+      // Tell the join handler about the filter
       // so it can be done in the join query
       if ($this->options['agg']['aggregates_with']) {
-        $table['join']->filter[] = $field ." = '". $this->value."'";
-      }    
+        $table['join']->filter[] = $field . " = '" . $this->value . "'";
+      }
     }
-    
+
   }
-  
+
 }

+ 30 - 20
tripal_views/views/handlers/chado_views_handler_filter_float.inc

@@ -1,5 +1,13 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_filter_float.
+ *
+ * Handles fields which may be aggregated during the chado join process. There are options
+ * to filter the base table based on an aggregated table or just filter the aggregated
+ * table (showing blank for that field if there are no records in the aggregated table).
+ */
 class chado_views_handler_filter_float extends views_handler_filter_float {
 
   /**
@@ -10,48 +18,50 @@ class chado_views_handler_filter_float extends views_handler_filter_float {
       '#type' => 'item',
       '#value' => '<b>If this filter applies to a table that is aggregated, additionally options may be ignored.</b>'
     );
-    
+
     parent::options_form($form, $form_state);
-    
+
     $form['agg'] = array(
       '#type' => 'fieldset',
       '#title' => 'Apply to fields that are aggregated'
     );
-    
+
     $form['agg']['records_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter base table records'),
-      '#description' => t('Filters '.$this->view->base_table.' to only those with the value in the aggregate array.'),
+      '#description' => t('Filters %base_table to only those with the value in the aggregate array.', array('%base_table' => $this->view->base_table)),
       '#default_value' => (isset($this->options['records_with'])) ? $this->options['records_with'] : TRUE,
     );
-    
+
     $form['agg']['aggregates_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter aggregates displayed'),
-      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of '.$this->view->base_table.' records.'),
-      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,    
+      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of %base_table records.', array('%base_table' => $this->view->base_table)),
+      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,
     );
-    
+
   }
-  
+
   /**
    * If the table to be filtered is not aggregated uses the parent::query()
    * However, if it is uses postgresql any() function to compare
    */
-  function query () {
+  function query() {
     $this->ensure_my_table();
-    
-    
+
+
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
 
     if (!$this->aggregated) {
       parent::query();
-    } else {
+    }
+    else {
 
       // Only base records with value in the aggregated field
       // This doesn't restrict the items in the aggregate field
@@ -63,13 +73,13 @@ class chado_views_handler_filter_float extends views_handler_filter_float {
       }
 
       // To restrict the items in the aggregate...
-      // Tell the join handler about the filter 
+      // Tell the join handler about the filter
       // so it can be done in the join query
       if ($this->options['agg']['aggregates_with']) {
-        $table['join']->filter[] = $field ." = '". $this->value."'";
-      }    
+        $table['join']->filter[] = $field . " = '" . $this->value . "'";
+      }
     }
-    
+
   }
-  
+
 }

+ 30 - 20
tripal_views/views/handlers/chado_views_handler_filter_numeric.inc

@@ -1,5 +1,13 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_filter_numeric.
+ *
+ * Handles fields which may be aggregated during the chado join process. There are options
+ * to filter the base table based on an aggregated table or just filter the aggregated
+ * table (showing blank for that field if there are no records in the aggregated table).
+ */
 class chado_views_handler_filter_numeric extends views_handler_filter_numeric {
 
   /**
@@ -10,48 +18,50 @@ class chado_views_handler_filter_numeric extends views_handler_filter_numeric {
       '#type' => 'item',
       '#value' => '<b>If this filter applies to a table that is aggregated, additionally options may be ignored.</b>'
     );
-    
+
     parent::options_form($form, $form_state);
-    
+
     $form['agg'] = array(
       '#type' => 'fieldset',
       '#title' => 'Apply to fields that are aggregated'
     );
-    
+
     $form['agg']['records_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter base table records'),
-      '#description' => t('Filters '.$this->view->base_table.' to only those with the value in the aggregate array.'),
+      '#description' => t('Filters %base_table to only those with the value in the aggregate array.', array('%base_table' => $this->view->base_table)),
       '#default_value' => (isset($this->options['records_with'])) ? $this->options['records_with'] : TRUE,
     );
-    
+
     $form['agg']['aggregates_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter aggregates displayed'),
-      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of '.$this->view->base_table.' records.'),
-      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,    
+      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of %base_table records.', array('%base_table' => $this->view->base_table)),
+      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,
     );
-    
+
   }
-  
+
   /**
    * If the table to be filtered is not aggregated uses the parent::query()
    * However, if it is uses postgresql any() function to compare
    */
-  function query () {
+  function query() {
     $this->ensure_my_table();
-    
-    
+
+
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
 
     if (!$this->aggregated) {
       parent::query();
-    } else {
+    }
+    else {
 
       // Only base records with value in the aggregated field
       // This doesn't restrict the items in the aggregate field
@@ -63,13 +73,13 @@ class chado_views_handler_filter_numeric extends views_handler_filter_numeric {
       }
 
       // To restrict the items in the aggregate...
-      // Tell the join handler about the filter 
+      // Tell the join handler about the filter
       // so it can be done in the join query
       if ($this->options['agg']['aggregates_with']) {
-        $table['join']->filter[] = $field ." = '". $this->value."'";
-      }    
+        $table['join']->filter[] = $field . " = '" . $this->value . "'";
+      }
     }
-    
+
   }
-  
+
 }

+ 30 - 20
tripal_views/views/handlers/chado_views_handler_filter_string.inc

@@ -1,5 +1,13 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_filter_string.
+ *
+ * Handles fields which may be aggregated during the chado join process. There are options
+ * to filter the base table based on an aggregated table or just filter the aggregated
+ * table (showing blank for that field if there are no records in the aggregated table).
+ */
 class chado_views_handler_filter_string extends views_handler_filter_string {
 
   /**
@@ -10,48 +18,50 @@ class chado_views_handler_filter_string extends views_handler_filter_string {
       '#type' => 'item',
       '#value' => '<b>If this filter applies to a table that is aggregated, additionally options may be ignored.</b>'
     );
-    
+
     parent::options_form($form, $form_state);
-    
+
     $form['agg'] = array(
       '#type' => 'fieldset',
       '#title' => 'Apply to fields that are aggregated'
     );
-    
+
     $form['agg']['records_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter base table records'),
-      '#description' => t('Filters '.$this->view->base_table.' to only those with the value in the aggregate array.'),
+      '#description' => t('Filters %base_table to only those with the value in the aggregate array.', array('%base_table' => $this->view->base_table)),
       '#default_value' => (isset($this->options['records_with'])) ? $this->options['records_with'] : TRUE,
     );
-    
+
     $form['agg']['aggregates_with'] = array(
       '#type' => 'checkbox',
       '#title' => t('Filter aggregates displayed'),
-      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of '.$this->view->base_table.' records.'),
-      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,    
+      '#description' => t('Filters the aggregates shown based on the value. Doesn\'t affect the number of %base_table records.', array('%base_table' => $this->view->base_table)),
+      '#default_value' => (isset($this->options['aggregates_with'])) ? $this->options['aggregates_with'] : TRUE,
     );
-    
+
   }
-  
+
   /**
    * If the table to be filtered is not aggregated uses the parent::query()
    * However, if it is uses postgresql any() function to compare
    */
-  function query () {
+  function query() {
     $this->ensure_my_table();
-    
-    
+
+
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
 
     if (!$this->aggregated) {
       parent::query();
-    } else {
+    }
+    else {
 
       // Only base records with value in the aggregated field
       // This doesn't restrict the items in the aggregate field
@@ -63,13 +73,13 @@ class chado_views_handler_filter_string extends views_handler_filter_string {
       }
 
       // To restrict the items in the aggregate...
-      // Tell the join handler about the filter 
+      // Tell the join handler about the filter
       // so it can be done in the join query
       if ($this->options['agg']['aggregates_with']) {
-        $table['join']->filter[] = $field ." = '". $this->value."'";
-      }    
+        $table['join']->filter[] = $field . " = '" . $this->value . "'";
+      }
     }
-    
+
   }
-  
+
 }

+ 20 - 11
tripal_views/views/handlers/chado_views_handler_sort.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_sort.
+ *
+ * Handles fields which may be aggregated during the chado join process. Sorting of
+ * aggregated fields required PostgreSQL 9.0 due to postgresql limitations. Sorting of
+ * non-aggregated fields works for all PostgreSQL versions.
+ */
 class chado_views_handler_sort extends views_handler_sort {
 
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
-    
+
     $form['msg'] = array(
       '#type' => 'item',
       '#value' => '<b>Sorting of aggregated fields only works for PostgreSQL 9.0+. This is due to lack of support at the database level. With lower postgreSQL versions, no sorting is applied.</b>'
@@ -14,21 +22,22 @@ class chado_views_handler_sort extends views_handler_sort {
 
     parent::options_form($form, $form_state);
   }
-  
+
   /**
    * Adds the sort to the query only if the field isn't aggregated
    * If the field is aggregated then the sort has to be applied at the join handler level
    */
-  function query () {
-    
+  function query() {
+
     // Determine if the current field is part of an aggregated table
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
-    
+
     // One day when the aggregated sort will work (ie: Postgresql 9.0+)
     // it will need to be applied in join handler
     // thus tell join handler about the sort
@@ -37,13 +46,13 @@ class chado_views_handler_sort extends views_handler_sort {
       'field' => $this->options['field'],
       'order' => $this->options['order']
     );
-    
-    
+
+
     // if not then add the sort
     if (!$this->aggregated) {
       parent::query();
     }
-    
+
   }
-  
+
 }

+ 20 - 11
tripal_views/views/handlers/chado_views_handler_sort_date.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_sort_date.
+ *
+ * Handles fields which may be aggregated during the chado join process. Sorting of
+ * aggregated fields required PostgreSQL 9.0 due to postgresql limitations. Sorting of
+ * non-aggregated fields works for all PostgreSQL versions.
+ */
 class chado_views_handler_sort extends views_handler_sort_date {
 
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
-    
+
     $form['msg'] = array(
       '#type' => 'item',
       '#value' => '<b>Sorting of aggregated fields only works for PostgreSQL 9.0+. This is due to lack of support at the database level. With lower postgreSQL versions, no sorting is applied.</b>'
@@ -14,21 +22,22 @@ class chado_views_handler_sort extends views_handler_sort_date {
 
     parent::options_form($form, $form_state);
   }
-  
+
   /**
    * Adds the sort to the query only if the field isn't aggregated
    * If the field is aggregated then the sort has to be applied at the join handler level
    */
-  function query () {
-    
+  function query() {
+
     // Determine if the current field is part of an aggregated table
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
-    
+
     // One day when the aggregated sort will work (ie: Postgresql 9.0+)
     // it will need to be applied in join handler
     // thus tell join handler about the sort
@@ -37,13 +46,13 @@ class chado_views_handler_sort extends views_handler_sort_date {
       'field' => $this->options['field'],
       'order' => $this->options['order']
     );
-    
-    
+
+
     // if not then add the sort
     if (!$this->aggregated) {
       parent::query();
     }
-    
+
   }
-  
+
 }

+ 20 - 11
tripal_views/views/handlers/chado_views_handler_sort_formula.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_sort_formula.
+ *
+ * Handles fields which may be aggregated during the chado join process. Sorting of
+ * aggregated fields required PostgreSQL 9.0 due to postgresql limitations. Sorting of
+ * non-aggregated fields works for all PostgreSQL versions.
+ */
 class chado_views_handler_sort extends views_handler_sort_formula {
 
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
-    
+
     $form['msg'] = array(
       '#type' => 'item',
       '#value' => '<b>Sorting of aggregated fields only works for PostgreSQL 9.0+. This is due to lack of support at the database level. With lower postgreSQL versions, no sorting is applied.</b>'
@@ -14,21 +22,22 @@ class chado_views_handler_sort extends views_handler_sort_formula {
 
     parent::options_form($form, $form_state);
   }
-  
+
   /**
    * Adds the sort to the query only if the field isn't aggregated
    * If the field is aggregated then the sort has to be applied at the join handler level
    */
-  function query () {
-    
+  function query() {
+
     // Determine if the current field is part of an aggregated table
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
-    
+
     // One day when the aggregated sort will work (ie: Postgresql 9.0+)
     // it will need to be applied in join handler
     // thus tell join handler about the sort
@@ -37,13 +46,13 @@ class chado_views_handler_sort extends views_handler_sort_formula {
       'field' => $this->options['field'],
       'order' => $this->options['order']
     );
-    
-    
+
+
     // if not then add the sort
     if (!$this->aggregated) {
       parent::query();
     }
-    
+
   }
-  
+
 }

+ 20 - 11
tripal_views/views/handlers/chado_views_handler_sort_menu_hierarchy.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_sort_menu_hierarchy.
+ *
+ * Handles fields which may be aggregated during the chado join process. Sorting of
+ * aggregated fields required PostgreSQL 9.0 due to postgresql limitations. Sorting of
+ * non-aggregated fields works for all PostgreSQL versions.
+ */
 class chado_views_handler_sort extends views_handler_sort_menu_hierarchy {
 
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
-    
+
     $form['msg'] = array(
       '#type' => 'item',
       '#value' => '<b>Sorting of aggregated fields only works for PostgreSQL 9.0+. This is due to lack of support at the database level. With lower postgreSQL versions, no sorting is applied.</b>'
@@ -14,21 +22,22 @@ class chado_views_handler_sort extends views_handler_sort_menu_hierarchy {
 
     parent::options_form($form, $form_state);
   }
-  
+
   /**
    * Adds the sort to the query only if the field isn't aggregated
    * If the field is aggregated then the sort has to be applied at the join handler level
    */
-  function query () {
-    
+  function query() {
+
     // Determine if the current field is part of an aggregated table
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
-    
+
     // One day when the aggregated sort will work (ie: Postgresql 9.0+)
     // it will need to be applied in join handler
     // thus tell join handler about the sort
@@ -37,13 +46,13 @@ class chado_views_handler_sort extends views_handler_sort_menu_hierarchy {
       'field' => $this->options['field'],
       'order' => $this->options['order']
     );
-    
-    
+
+
     // if not then add the sort
     if (!$this->aggregated) {
       parent::query();
     }
-    
+
   }
-  
+
 }

+ 20 - 11
tripal_views/views/handlers/chado_views_handler_sort_random.inc

@@ -1,12 +1,20 @@
 <?php
 
+/**
+ * @file
+ * A chado wrapper for the views_handler_sort_random.
+ *
+ * Handles fields which may be aggregated during the chado join process. Sorting of
+ * aggregated fields required PostgreSQL 9.0 due to postgresql limitations. Sorting of
+ * non-aggregated fields works for all PostgreSQL versions.
+ */
 class chado_views_handler_sort extends views_handler_sort_random {
 
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
-    
+
     $form['msg'] = array(
       '#type' => 'item',
       '#value' => '<b>Sorting of aggregated fields only works for PostgreSQL 9.0+. This is due to lack of support at the database level. With lower postgreSQL versions, no sorting is applied.</b>'
@@ -14,21 +22,22 @@ class chado_views_handler_sort extends views_handler_sort_random {
 
     parent::options_form($form, $form_state);
   }
-  
+
   /**
    * Adds the sort to the query only if the field isn't aggregated
    * If the field is aggregated then the sort has to be applied at the join handler level
    */
-  function query () {
-    
+  function query() {
+
     // Determine if the current field is part of an aggregated table
     $table = $this->query->get_table_info($this->table);
-    if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+    if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
       $this->aggregated = TRUE;
-    } else {
+    }
+    else {
       $this->aggregated = FALSE;
     }
-    
+
     // One day when the aggregated sort will work (ie: Postgresql 9.0+)
     // it will need to be applied in join handler
     // thus tell join handler about the sort
@@ -37,13 +46,13 @@ class chado_views_handler_sort extends views_handler_sort_random {
       'field' => $this->options['field'],
       'order' => $this->options['order']
     );
-    
-    
+
+
     // if not then add the sort
     if (!$this->aggregated) {
       parent::query();
     }
-    
+
   }
-  
+
 }

+ 27 - 20
tripal_views/views/handlers/chado_wrapper_functions.inc

@@ -1,5 +1,10 @@
 <?php
 
+/**
+ * @file
+ * A collection of functions used for the chado wrapper views handlers
+ */
+
 /**
  * Splits an SQL array of results in a single field
  * into a php array
@@ -12,16 +17,17 @@
 function chado_wrapper_split_array_agg_results($handler, &$values) {
 
   if ($handler->aggregated) {
-    foreach($values as $k => $v) {
-      
-      if(preg_match('/^{(.*)}$/',$v->{$handler->field_alias}, $matches)) {
+    foreach ($values as $k => $v) {
+
+      if (preg_match('/^{(.*)}$/', $v->{$handler->field_alias}, $matches)) {
         $values[$k]->{$handler->field_alias} = str_getcsv($matches[1]);
-      } else {
+      }
+      else {
         $values[$k]->{$handler->field_alias} = array();
       }
     }
   }
-  
+
   return $values;
 }
 
@@ -34,14 +40,14 @@ function chado_wrapper_split_array_agg_results($handler, &$values) {
  * @return
  *   TRUE/FALSE if or if not the field has the aggregated join handler
  */
-function chado_wrapper_is_aggregated_by_join ($handler) {
+function chado_wrapper_is_aggregated_by_join($handler) {
   $aggregated = FALSE;
-  
+
   $table = $handler->query->get_table_info($handler->table);
-  if (preg_match('/aggregator/',$table['join']->definition['handler'])) {
+  if (preg_match('/aggregator/', $table['join']->definition['handler'])) {
     $aggregated = TRUE;
   }
-  
+
   return $aggregated;
 }
 
@@ -56,24 +62,24 @@ function chado_wrapper_is_aggregated_by_join ($handler) {
  * @return
  *   TRUE/FALSE if or if not the field is aggregated
  */
-function chado_wrapper_is_aggregated_by_result ($handler, $values) {
+function chado_wrapper_is_aggregated_by_result($handler, $values) {
   $aggregated = FALSE;
-  
-  if (preg_match('/^{.*}$/',$values[0]->{$handler->field_alias})) {
+
+  if (preg_match('/^{.*}$/', $values[0]->{$handler->field_alias})) {
     $aggregated = TRUE;
   }
-  
+
   return $aggregated;
 }
 
 function chado_wrapper_render_items($handler, $values) {
 
-  // If it's aggregated (an array), then render each part 
+  // If it's aggregated (an array), then render each part
   // using the parent render functionality
   if ($handler->aggregated) {
-    
+
     $items = array();
-    
+
     $parts = $values->{$handler->field_alias};
     foreach ($parts as $p) {
       $v[ $handler->field_alias ] = $p;
@@ -81,17 +87,18 @@ function chado_wrapper_render_items($handler, $values) {
       $items[] = $handler->parent_render($val);
       unset($v, $val);
     }
-    
+
     if ($handler->options['type'] == 'separator') {
       return implode(check_plain($handler->options['separator']), $items);
     }
     else {
       return theme('item_list', $items, NULL, $handler->options['type']);
     }
-    
+
   // Otherwise it is not aggragated
   // Just render like the default handler would
-  } else {
+  }
+  else {
     return $handler->parent_render($values);
-  }      
+  }
 }

+ 17 - 15
tripal_views/views/handlers/views_handler_field_chado_count.inc

@@ -1,10 +1,11 @@
 <?php
- 
+
 /**
+ * @file
  * Purpose: Provide a field that counts the number of records in the current table
  *   are connected to the base table. For example, this field could be used to count
- *   the number of features connected to a given organism -base table=organism, 
- *   current table=feature: for each record in the organism view count feature records where 
+ *   the number of features connected to a given organism -base table=organism,
+ *   current table=feature: for each record in the organism view count feature records where
  *   feature.organism_id=organism_id of current organism record
  *
  * @ingroup views_field_handlers
@@ -14,50 +15,51 @@ class views_handler_field_chado_count extends views_handler_field {
 
   function init(&$view, $options) {
     parent::init($view, $options);
-    
+
     // the table to query is required
     // check that it was provided in the field definition and if not warn
     if ($this->definition['table_to_query']) {
       $this->aliases['current_table'] = $this->definition['table_to_query'];
-    } else {
-      drupal_set_message("The field definition ( in hook_views_data() ) needs to specify the 'table_to_query' in order for this fields to work. Field:".$this->field." in the ".$this->table." table definition", 'error');
     }
-    
+    else {
+      drupal_set_message(t("The field definition ( in hook_views_data() ) needs to specify the 'table_to_query' in order for this fields to work. Field:%field in the %table table definition"), array('%field' => $this->field, '%table' => $this->table), 'error');
+    }
+
     // set aliases
     $this->aliases['primary_id'] = $this->table . '_id';
     $this->aliases['foreign_key'] = $this->table . '_id';
   }
-  
+
   //Needed to ensure that the name of this field is not added to the query
   function query() {
     $this->add_additional_fields();
   }
-  
+
   function pre_render(&$values) {
     // Render nothing if the current table wasn't set in the field definition
-    if(!$this->aliases['current_table']) {
+    if (!$this->aliases['current_table']) {
       return '';
     }
 
     foreach ($values as $key => $record) {
       $primary_id = $record->{$this->aliases['primary_id']};
-      
+
       //Select count from database
       $sql = 'SELECT count(*) as count FROM %s WHERE %s=%d';
       $previous_db = tripal_db_set_active('chado');
       $result = db_fetch_object(db_query(
-        $sql, 
-        $this->aliases['current_table'], 
+        $sql,
+        $this->aliases['current_table'],
         $this->aliases['foreign_key'],
         $primary_id
       ));
       tripal_db_set_active($previous_db);
-      
+
       //Add to view results
       $this->view->result[$key]->{$this->field} = $result->count;
     }
   }
-  
+
   function render($values) {
     return $values->{$this->field};
   }

+ 41 - 38
tripal_views/views/handlers/views_handler_field_chado_rel_by_type.inc

@@ -1,7 +1,8 @@
 <?php
 
 /**
- * Field handler allowing all relationships of a specified type for a given chado entity to be displayed in 
+ * @file
+ * Field handler allowing all relationships of a specified type for a given chado entity to be displayed in
  * a single cell
  *
  * @ingroup views_field_handlers
@@ -12,18 +13,18 @@ class views_handler_field_chado_rel_by_type extends views_handler_field_prerende
 
     // 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    
+    //    FALSE => or just value is rendered  -only 1 porperty type is displayed
     $this->display_type = TRUE;
 
     $this->chado_type = $this->table;
-    
+
     // Check that this chado type has a <chado type>_relationship table
     $sql = "SELECT true as bool FROM pg_tables WHERE tablename='%s_relationship'";
     $previous_db = tripal_db_set_active('chado');
-    $exists = db_fetch_object(db_query($sql,$this->table));
+    $exists = db_fetch_object(db_query($sql, $this->table));
     tripal_db_set_active($previous_db);
     if (!$exists->bool) {
-      drupal_set_message('The Relationship by Type handler cannot be used with this table since the '.$this->table.'_relationship table doesn\'t exist', 'error');
+      drupal_set_message(t('The Relationship by Type handler cannot be used with this table since the %table_relationship table doesn\'t exist', array('%table' => $this->table)), 'error');
       $this->broken = TRUE;
     }
   }
@@ -31,7 +32,7 @@ class views_handler_field_chado_rel_by_type extends views_handler_field_prerende
   function option_definition() {
     $options = parent::option_definition();
     $options['rel_type_ids'] = array('default' => array());
-    $options['rel_display_options'] = array('default' => array('subject','type','object'));
+    $options['rel_display_options'] = array('default' => array('subject', 'type', 'object'));
     return $options;
   }
 
@@ -45,10 +46,11 @@ class views_handler_field_chado_rel_by_type extends views_handler_field_prerende
       $form = array(
         'broken' => array(
           '#type' => 'item',
-          '#value' => 'The Relationship by Type handler cannot be used with this table since the '.$this->table.'_relationship table doesn\'t exist',
+          '#value' => 'The Relationship by Type handler cannot be used with this table since the ' . $this->table . '_relationship table doesn\'t exist',
         ),
       );
-    } else {    
+    }
+    else {
       $form['rel_display_parts'] = array(
         '#type' => 'checkboxes',
         '#title' => t('Display Relationship Parts'),
@@ -63,29 +65,29 @@ class views_handler_field_chado_rel_by_type extends views_handler_field_prerende
         ),
         '#default_value' => array($this->options['rel_display_parts']['subject'], $this->options['rel_display_parts']['type'], $this->options['rel_display_parts']['object']),
       );
-      
+
       $form['rel_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 '.$this->chado_type.', '
-          .'if you selected "Current '.$this->chado_type.' is the Object" only Sarah is the maternal parent of Fred'
+          .'Fred is the paternal_parent of Max where Fred is the current ' . $this->chado_type . ', '
+          .'if you selected "Current ' . $this->chado_type . ' is the Object" only Sarah is the maternal parent of Fred'
           .' would be displayed.'),
         '#options' => array(
-          'subject' => 'Current '.$this->chado_type.' is the Subject',
-          'object' => 'Current '.$this->chado_type.' is the Object',
-          'all' => 'Current '.$this->chado_type.' is the Subject and/or Object',
+          'subject' => 'Current ' . $this->chado_type . ' is the Subject',
+          'object' => 'Current ' . $this->chado_type . ' is the Object',
+          'all' => 'Current ' . $this->chado_type . ' is the Subject and/or Object',
         ),
         '#default_value' => $this->options['rel_display_rels'],
       );
-      
+
       $options = array();
       $sql = 'SELECT rel.type_id, cvt.name FROM %s_relationship rel LEFT JOIN cvterm cvt ON cvt.cvterm_id=rel.type_id GROUP BY rel.type_id,cvt.name';
       $previous_db = tripal_db_set_active('chado');
-      $resource = db_query($sql,$this->table);
-      tripal_db_set_active($previous_db);      
+      $resource = db_query($sql, $this->table);
+      tripal_db_set_active($previous_db);
       while ($r = db_fetch_object($resource)) {
         $options[ $r->type_id ] = $r->name;
       }
@@ -104,36 +106,36 @@ class views_handler_field_chado_rel_by_type extends views_handler_field_prerende
   function query() {
     $this->add_additional_fields();
   }
-  
+
   function pre_render($values) {
     $this->aliases['relationships'] = $this->chado_type . '_relationships';
     $chado_id = $this->table . '_id';
     $chado_relationship_id = $this->table . '_relationship_id';
     $this->aliases[$chado_id] = $chado_id;
     $this->field_alias = $this->aliases[$chado_id];
-    
+
     //check if relationships added to results, if not then add
     if (empty( $this->view->result[0]->{$this->aliases['relationships']} )) {
-      
+
       // retrieve the chado_id for each record in the views current page
       $chado_ids = array();
       foreach ($this->view->result as $row_num => $row) {
         $chado_ids[$row_num] = $row->{$chado_id};
       }
-      
+
       // Add relationships to the view results
       $sql = "SELECT rel.*, cvterm.name as type_name, "
         ."subject.name as subject_name, object.name as object_name "
-        ."FROM ".$this->table."_relationship rel "
-        ."LEFT JOIN ".$this->table." subject ON rel.subject_id=subject.".$chado_id." "
-        ."LEFT JOIN ".$this->table." object ON rel.object_id=object.".$chado_id." "
+        ."FROM " . $this->table . "_relationship rel "
+        ."LEFT JOIN " . $this->table . " subject ON rel.subject_id=subject." . $chado_id . " "
+        ."LEFT JOIN " . $this->table . " object ON rel.object_id=object." . $chado_id . " "
         ."LEFT JOIN cvterm cvterm ON rel.type_id = cvterm.cvterm_id "
-        ."WHERE rel.subject_id IN (".implode(',',$chado_ids).") "
-        ."OR rel.object_id IN (".implode(',',$chado_ids).") ";
+        ."WHERE rel.subject_id IN (" . implode(',', $chado_ids) . ") "
+        ."OR rel.object_id IN (" . implode(',', $chado_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, $chado_ids)) {
           $key = array_search($r->subject_id, $chado_ids);
@@ -148,14 +150,14 @@ class views_handler_field_chado_rel_by_type extends views_handler_field_prerende
       }
 
     }
-    
+
     // add relationships to this field
     foreach ($this->view->result as $result) {
       if (!empty($result->{$this->aliases['relationships']})) {
         $relationships2keep = array_filter($this->options['rel_type_ids']);
-        
+
         // all relationships including the current chado guy
-        foreach ($result->{$this->aliases['relationships']} as $relationship) {      
+        foreach ($result->{$this->aliases['relationships']} as $relationship) {
           // perform filtering------
           //type
           if (!empty($this->options['rel_type_ids'])) {
@@ -163,18 +165,19 @@ class views_handler_field_chado_rel_by_type extends views_handler_field_prerende
               continue;
             }
           }
-          
+
           //"Display Relationships Where" criteria
           if (preg_match('/subject/', $this->options['rel_display_rels'])) {
             if ($relationship->{$chado_id} != $relationship->subject_id) {
               continue;
-            }      
-          } elseif (preg_match('/object/', $this->options['rel_display_rels'])) {
+            }
+          }
+          elseif (preg_match('/object/', $this->options['rel_display_rels'])) {
             if ($relationship->{$chado_id} != $relationship->object_id) {
               continue;
             }
           }
-          
+
           // Add relationship to the list of items to be rendered
           $this->items[$relationship->{$chado_id}][$relationship->{$chado_relationship_id}][$chado_id] = $relationship->{$chado_id};
           $this->items[$relationship->{$chado_id}][$relationship->{$chado_relationship_id}][$chado_relationship_id] = $relationship->{$chado_relationship_id};
@@ -186,13 +189,13 @@ class views_handler_field_chado_rel_by_type extends views_handler_field_prerende
           $this->items[$relationship->{$chado_id}][$relationship->{$chado_relationship_id}]['type_name'] = $relationship->type_name;
         }
       }
-    } 
-    
+    }
+
   }
 
   function render_item($count, $item) {
     $text = array();
-    
+
     // Render Parts
     if ($this->options['rel_display_parts']['subject']) {
       $text[] = $item['subject_name'];
@@ -203,7 +206,7 @@ class views_handler_field_chado_rel_by_type extends views_handler_field_prerende
     if ($this->options['rel_display_parts']['object']) {
       $text[] = $item['object_name'];
     }
-    
+
     return implode(' ', $text);
   }
 }

+ 3 - 2
tripal_views/views/handlers/views_handler_field_chado_tf_boolean.inc

@@ -1,6 +1,7 @@
 <?php
 
 /**
+ * @file
  * A handler to provide proper displays for booleans.
  *
  * Allows for display of true/false, yes/no, on/off.
@@ -28,11 +29,11 @@ class views_handler_field_chado_tf_boolean extends views_handler_field_boolean {
     }
 
     if (isset($this->formats[$this->options['type']])) {
-      return preg_match('/t/',$value) ? $this->formats[$this->options['type']][0] : $this->formats[$this->options['type']][1];
+      return preg_match('/t/', $value) ? $this->formats[$this->options['type']][0] : $this->formats[$this->options['type']][1];
     }
     else {
       return preg_match('/t/', $value) ? $this->formats['yes-no'][0] : $this->formats['yes-no'][1];
     }
   }
-  
+
 }

+ 19 - 20
tripal_views/views/handlers/views_handler_field_cvterm_name.inc

@@ -1,8 +1,7 @@
-<?php 
-// $Id$
+<?php
 
 /**
- *
+ * @file
  * @ingroup views_field_handlers
  * @ingroup tripal_core
  */
@@ -12,16 +11,16 @@ class views_handler_field_cvterm_name extends views_handler_field {
    * Add join to the cvterm table and cvterm.name field to the query
    */
   function query() {
-      
+
     // if this table isn't a base table
     // if it is this can be done by describing a join between base table and cvterm
-    if (!preg_match('/^'.$this->view->base_table.'$/', $this->table)) {
+    if (!preg_match('/^' . $this->view->base_table . '$/', $this->table)) {
 
       //Want to add join: LEFT JOIN cvterm nd_experimentprop_cvterm ON nd_experimentprop.type_id = nd_experimentprop_cvterm.cvterm_id
-      //===============================================================      
+      //===============================================================
 
       $this->query->ensure_table($this->table);
-      
+
       // add to table_queue--------------------------------------------
       $cvterm_join['table'] = 'cvterm';
       $cvterm_join['num'] = 1;
@@ -33,7 +32,7 @@ class views_handler_field_cvterm_name extends views_handler_field {
       $cvterm_join['join']->field = 'cvterm_id';
       $cvterm_join['join']->left_table = $this->table;
       $cvterm_join['join']->left_field = 'type_id';
-      
+
       $cvterm_join['join']->definition['table'] = 'cvterm';
       $cvterm_join['join']->definition['field'] = 'cvterm_id';
       $cvterm_join['join']->definition['left_table'] = $this->table;
@@ -42,26 +41,26 @@ class views_handler_field_cvterm_name extends views_handler_field {
       $this->query->table_queue[$cvterm_join['alias']] = $cvterm_join;
 
       // add to table--------------------------------------------------
-      $this->query->tables[$this->view->base_table][$this->table.'_cvterm'] = array(
+      $this->query->tables[$this->view->base_table][$this->table . '_cvterm'] = array(
         'count' => 1,
-        'alias' => $this->table.'_cvterm',
-      );    
+        'alias' => $this->table . '_cvterm',
+      );
 
       //Want to add field: nd_experimentprop_cvterm.name as nd_experimentprop_type
       //===============================================================
-      $field_alias = $this->table.'_cvterm_name';
-      $this->query->add_field($this->table.'_cvterm', 'name');
+      $field_alias = $this->table . '_cvterm_name';
+      $this->query->add_field($this->table . '_cvterm', 'name');
       $this->add_additional_fields();
-      $this->aliases['name'] = $field_alias;  
-      
+      $this->aliases['name'] = $field_alias;
+
     }
   }
-  
+
   /**
    * Ensure that the type/cvterm name is rendered
    */
- function render($values) { 
-   return $values->{$this->aliases['name']}; 
- }
-  
+  function render($values) {
+    return $values->{$this->aliases['name']};
+  }
+
 }

+ 39 - 34
tripal_views/views/handlers/views_handler_field_dbxref_accession_link.inc

@@ -1,42 +1,47 @@
 <?php
 
 /**
+ * @file
+ * Used for a custom field so that field can render the database reference link
  *
  * @ingroup views_field_handlers
  * @ingroup tripal_core
  */
 class views_handler_field_dbxref_accession_link extends views_handler_field {
- function construct() {
-   parent::construct();
-   $this->additional_fields['accession'] = 'accession';
-   $this->additional_fields['db_id'] = 'db_id';
-
- }
-
- function query() { 
-   $this->ensure_my_table();
-   $this->add_additional_fields(); 
- }
-
- function render($values) { 
-
-   $accession = $values->{$this->aliases['accession']}; 
-   $db_id = $values->{$this->aliases['db_id']};
-
-   if (!empty($db_id) AND !empty($accession)) {
-     $previous_db = tripal_db_set_active('chado');
-     $result = db_fetch_object(db_query('SELECT urlprefix FROM db WHERE db_id=%d', $db_id));
-     tripal_db_set_active($previous_db);   
-     $urlprefix = $result->urlprefix;
-
-     if (!empty($urlprefix)) {
-       $accession_link = $urlprefix . $accession;
-       return($accession_link); 
-     } else {
-       return $accession;
-     }
-   } else {
-     return $accession;
-   }
- } 
-} 
+  function construct() {
+    parent::construct();
+
+    $this->additional_fields['accession'] = 'accession';
+    $this->additional_fields['db_id'] = 'db_id';
+
+  }
+
+  function query() {
+    $this->ensure_my_table();
+    $this->add_additional_fields();
+  }
+
+  function render($values) {
+
+    $accession = $values->{$this->aliases['accession']};
+    $db_id = $values->{$this->aliases['db_id']};
+
+    if (!empty($db_id) AND !empty($accession)) {
+      $previous_db = tripal_db_set_active('chado');
+      $result = db_fetch_object(db_query('SELECT urlprefix FROM db WHERE db_id=%d', $db_id));
+      tripal_db_set_active($previous_db);
+      $urlprefix = $result->urlprefix;
+
+      if (!empty($urlprefix)) {
+        $accession_link = $urlprefix . $accession;
+        return $accession_link;
+      }
+      else {
+        return $accession;
+      }
+    }
+    else {
+      return $accession;
+    }
+  }
+}

+ 17 - 14
tripal_views/views/handlers/views_handler_field_node_optional.inc

@@ -1,6 +1,7 @@
 <?php
 
 /**
+ * @file
  * Field handler to provide simple renderer that allows linking to a node.
  *
  * @ingroup views_field_handlers
@@ -15,12 +16,12 @@ class views_handler_field_node_optional extends views_handler_field_node {
       $this->additional_fields['language'] = array('table' => 'node', 'field' => 'language');
     }
   }
-  
+
   /**
    * Add chado_* and *_node alias'd left joins to the table
    */
   function query() {
-    
+
     // Check what we have (ie: current table? node table? )
     $chado_table = 'chado_' . $this->table;
     foreach ($this->query->table_queue as $table_def) {
@@ -28,21 +29,21 @@ class views_handler_field_node_optional extends views_handler_field_node {
       if ($table_def['table'] == $this->table) {
         $this_table_alias = $table_def['alias'];
       }
-      
+
       // check is node joined to #this->table
       if ($table_def['table'] == $chado_table) {
         $node_table_alias = $table_def['alias'];
       }
     }
-    
+
     // First: Add the main field-----------------------------------------------
     if (!$this_table_alias) {
       $this_table_alias = $this->ensure_my_table();
     }
-    $field_alias = $this->query->add_field($this_table_alias, $this->real_field); 
+    $field_alias = $this->query->add_field($this_table_alias, $this->real_field);
     $this->aliases[ $this->real_field ] = $field_alias;
     $this->field_alias = $field_alias;
-    
+
     // Second: Add nid field and Joins if necessary----------------------------
     // Add node join if needed
     if (!$node_table_alias) {
@@ -50,18 +51,18 @@ class views_handler_field_node_optional extends views_handler_field_node {
       $def['field'] = $this->table . '_id';
       $def['left_table'] = $this_table_alias;
       $def['left_field'] = $this->table . '_id';
-      
+
       $join = new views_join();
       $join->definition = $def;
       $join->construct();
       $join->adjusted = TRUE;
-    
+
       $node_table_alias = $this->query->add_relationship($def['table'], $join, $def['table']);
     }
-    
+
     // Finally Add Field
-    $field_alias = $this->query->add_field($node_table_alias, 'nid'); 
-    $this->aliases['nid'] = $field_alias;   
+    $field_alias = $this->query->add_field($node_table_alias, 'nid');
+    $this->aliases['nid'] = $field_alias;
 
   }
 
@@ -71,7 +72,7 @@ class views_handler_field_node_optional extends views_handler_field_node {
    * Data should be made XSS safe prior to calling this function.
    */
   function render_link($data, $values) {
-    if (!empty($this->options['link_to_node']) && $data !== NULL && $data !== '') {  
+    if (!empty($this->options['link_to_node']) && $data !== NULL && $data !== '') {
       if (!empty($values->{$this->aliases['nid']})) {
         $this->options['alter']['make_link'] = TRUE;
         $this->options['alter']['path'] = "node/" . $values->{$this->aliases['nid']};
@@ -84,11 +85,13 @@ class views_handler_field_node_optional extends views_handler_field_node {
             unset($this->options['alter']['language']);
           }
         }
-      } else {
+      }
+      else {
         $this->options['alter']['make_link'] = FALSE;
-        $this->options['alter']['path'] = "";        
+        $this->options['alter']['path'] = "";
       }
     }
+
     return $data;
   }
 }

+ 2 - 1
tripal_views/views/handlers/views_handler_field_readable_date.inc

@@ -1,6 +1,7 @@
 <?php
 
 /**
+ * @file
  * A handler to provide proper displays for dates.
  *
  * @ingroup views_field_handlers
@@ -56,7 +57,7 @@ class views_handler_field_readable_date extends views_handler_field {
     if (in_array($format, array('custom', 'raw time ago', 'time ago', 'raw time span', 'time span'))) {
       $custom_format = $this->options['custom_date_format'];
     }
-    
+
     if (!$value) {
       return theme('views_nodate');
     }

+ 8 - 8
tripal_views/views/handlers/views_handler_field_type_name.inc

@@ -1,16 +1,16 @@
 <?php
 
 /**
- *
+ * @file
  * @ingroup views_field_handlers
  * @ingroup tripal_core
  */
 class views_handler_field_type_name extends views_handler_field {
- function construct() {
-   parent::construct();
- }
+  function construct() {
+    parent::construct();
+  }
 
- function render($values) { 
-   return $values->property_type_name;
- } 
-} 
+  function render($values) {
+    return $values->property_type_name;
+  }
+}

+ 16 - 14
tripal_views/views/handlers/views_handler_filter_chado_boolean.inc

@@ -1,6 +1,7 @@
 <?php
 
 /**
+ * @file
  * Purpose: This handler provides a TRUE/FALSE or YES/NO select for chado fields
  *  of type boolean (includes both 0/1 and t/f booleans)
  *
@@ -10,17 +11,14 @@
 class views_handler_filter_chado_boolean extends views_handler_filter_boolean_operator {
  /**
   * Checks if this field uses 0/1 or t/f
+  * @todo Implement LIMIT 1 functionality for tripal_core_chado_select().
   */
   function init(&$view, $options) {
     parent::init($view, $options);
-    
-    $sql = 'SELECT '.$this->field.' FROM '.$this->table.' LIMIT 1';
-    $previous_db = tripal_db_set_active('chado');
-    $result = db_fetch_object(db_query($sql));
-    tripal_db_set_active($previous_db);
-    
+
+    $results = tripal_core_chado_select($this->table, array($this->field), array());
     $this->boolean_type_tf = FALSE;
-    if (preg_match('/[tf]/', $result->{$this->field})) {
+    if (preg_match('/[tf]/', $results[0]->{$this->field})) {
       $this->boolean_type_tf = TRUE;
     }
 
@@ -46,8 +44,9 @@ class views_handler_filter_chado_boolean extends views_handler_filter_boolean_op
       // Provide a fallback if the above didn't set anything.
       if (!isset($this->value_options)) {
         $this->value_options = array('t' => t('True'), 'f' => t('False'));
-      }    
-    } else { //end of t/f boolean
+      }
+    }
+    else { //end of t/f boolean
       if (isset($this->definition['type'])) {
         if ($this->definition['type'] == 'yes-no') {
           $this->value_options = array(1 => t('Yes'), 0 => t('No'));
@@ -70,19 +69,22 @@ class views_handler_filter_chado_boolean extends views_handler_filter_boolean_op
     $where = "$this->table_alias.$this->real_field ";
 
     if ($this->boolean_type_tf) {
-      if (preg_match('/f/',$this->value)) {
+      if (preg_match('/f/', $this->value)) {
         $where .= "= 'f'";
-      } else {
+      }
+      else {
         $where .= "= 't'";
       }
-      $this->query->add_where($this->options['group'], $where);    
-    } else {
+      $this->query->add_where($this->options['group'], $where);
+    }
+    else {
       if (empty($this->value)) {
         $where .= '= 0';
         if ($this->accept_null) {
           $where = '(' . $where . " OR $this->table_alias.$this->real_field IS NULL)";
         }
-      } else {
+      }
+      else {
         $where .= '<> 0';
       }
       $this->query->add_where($this->options['group'], $where);

+ 81 - 68
tripal_views/views/handlers/views_handler_filter_chado_select_cvterm_name.inc

@@ -1,6 +1,7 @@
 <?php
 
 /**
+ * @file
  * Purpose: This Handler provides a select list for the type field
  *
  *  NOTE: This handler only works when applied to the type_id field in the base_table of
@@ -12,56 +13,63 @@
 class views_handler_filter_chado_select_cvterm_name extends views_handler_filter_string {
 
  /**
-	* Executed when the field is added
-	* Determine which cv to limit the cvterms to
-	*/
+  * Executed when the field is added
+  * Determine which cv to limit the cvterms to
+  */
   function init(&$view, $options) {
     parent::init($view, $options);
-  	
-  	if ($this->options['show_all']) {
-        $cv_id = variable_get('chado_'.$this->view->base_table.'_cv', null);
-        if ($cv_id) {
-          $results = tripal_core_chado_select('cvterm',array('cvterm_id','name'), array('cv_id'=>$cv_id));	
-          if (empty($results)) { $results = array(); }
-          foreach ($results as $c) {
-            $cvterms[$c->cvterm_id] = $c->name;
-          }    	
-        } else {
-          //get a list of cvs currently used
-          if ($this->view->base_table == 'cvterm') {
-            $sql = 'SELECT distinct(cv.cv_id) FROM '.$this->view->base_table
-              .' LEFT JOIN cv cv ON cv.cv_id=cvterm.cv_id';	
-          } else {
-            $sql = 'SELECT distinct(cv.cv_id) FROM '.$this->view->base_table
-              .' LEFT JOIN cvterm cvterm ON cvterm.cvterm_id='.$this->view->base_table.'.type_id '
-              .'LEFT JOIN cv cv ON cv.cv_id=cvterm.cv_id';
-          }
-          $previous_db = tripal_db_set_active('chado');
-          $resource = db_query($sql);
-          tripal_db_set_active($previous_db);
-          $cvterms = array();
-          while ( $r = db_fetch_object($resource) ) {
-            $results = tripal_core_chado_select('cvterm',array('cvterm_id','name'), array('cv_id'=>$r->cv_id));	
-            if (empty($results)) { $results = array(); }
-            foreach ($results as $c) {
-              $cvterms[$c->cvterm_id] = $c->name;
-            }
-          }
-        }// end of if variable not defined
-    
-    } else {
-        $sql = "SELECT cvterm_id, name FROM cvterm WHERE cvterm_id IN (SELECT distinct(type_id) FROM %s)";
+
+    if ($this->options['show_all']) {
+      $cv_id = variable_get('chado_' . $this->view->base_table . '_cv', NULL);
+      if ($cv_id) {
+        $results = tripal_core_chado_select('cvterm', array('cvterm_id', 'name'), array('cv_id' => $cv_id));
+        if (empty($results)) {
+          $results = array();
+        }
+        foreach ($results as $c) {
+          $cvterms[$c->cvterm_id] = $c->name;
+        }
+      }
+      else {
+        //get a list of cvs currently used
+        if ($this->view->base_table == 'cvterm') {
+          $sql = 'SELECT distinct(cv.cv_id) FROM ' . $this->view->base_table
+            .' LEFT JOIN cv cv ON cv.cv_id=cvterm.cv_id';
+        }
+        else {
+          $sql = 'SELECT distinct(cv.cv_id) FROM ' . $this->view->base_table
+            .' LEFT JOIN cvterm cvterm ON cvterm.cvterm_id=' . $this->view->base_table . '.type_id '
+            .'LEFT JOIN cv cv ON cv.cv_id=cvterm.cv_id';
+        }
         $previous_db = tripal_db_set_active('chado');
-        $resource = db_query($sql, $this->view->base_table);
+        $resource = db_query($sql);
         tripal_db_set_active($previous_db);
         $cvterms = array();
         while ( $r = db_fetch_object($resource) ) {
-          $cvterms[$r->cvterm_id] = $r->name;
-        }        
+          $results = tripal_core_chado_select('cvterm', array('cvterm_id', 'name'), array('cv_id' => $r->cv_id));
+          if (empty($results)) {
+            $results = array();
+          }
+          foreach ($results as $c) {
+            $cvterms[$c->cvterm_id] = $c->name;
+          }
+        }
+      }// end of if variable not defined
+
+    }
+    else {
+      $sql = "SELECT cvterm_id, name FROM cvterm WHERE cvterm_id IN (SELECT distinct(type_id) FROM %s)";
+      $previous_db = tripal_db_set_active('chado');
+      $resource = db_query($sql, $this->view->base_table);
+      tripal_db_set_active($previous_db);
+      $cvterms = array();
+      while ( $r = db_fetch_object($resource) ) {
+        $cvterms[$r->cvterm_id] = $r->name;
+      }
     }
     //sort cvterms by name (case insensitive)
     natcasesort($cvterms);
-    
+
     //add to this handler
     $this->cvterm_options = $cvterms;
   }
@@ -74,7 +82,7 @@ class views_handler_filter_chado_select_cvterm_name extends views_handler_filter
 
     $form['values_form_type'] = array(
       '#type' => 'radios',
-      '#title' => 'Filter Type',
+      '#title' => t('Filter Type'),
       '#options' => array(
         'textfield' => 'Text Field',
         'select' => 'Drop-Down Box',
@@ -95,90 +103,95 @@ class views_handler_filter_chado_select_cvterm_name extends views_handler_filter
       '#description' => t('Adds --Any-- to the available options.'),
       '#default_value' => (isset($this->options['optional'])) ? $this->options['optional'] : TRUE,
     );
-    
+
     $form['show_all'] = array(
       '#type' => 'checkbox',
-      '#title' => 'Show All Terms',
+      '#title' => t('Show All Terms'),
       '#description' => 'Otherwise only cvterms used in the base table will be used'
     );
   }
-  
+
  /**
   * Alters the query so that WHERE cvterm.cvterm_id=212 is used
   */
   function query() {
     $this->ensure_table;
-    
+
     if ($this->options['multiple']) {
       // Remove any if it's there
       unset($this->value['All']);
-      
+
       if (sizeof($this->value)) {
         $holders = array();
         foreach ($this->value as $v) {
-          if (preg_match('/^[\d\.]+$/',$v)) {
+          if (preg_match('/^[\d\.]+$/', $v)) {
             $holders[] = '%d';
-          } else {
+          }
+          else {
             $holders[] = "'%s'";
           }
         }
-        $where = "cvterm.cvterm_id IN (".implode(", ",$holders).")";
+        $where = "cvterm.cvterm_id IN (" . implode(", ", $holders) . ")";
       }
-    } else {
+    }
+    else {
       if (preg_match('/^\d+$/', $this->value)) {
         $where = 'cvterm.cvterm_id=%d';
-      } else {
+      }
+      else {
         $where = "cvterm.name" . $this->operator . "'%s'";
       }
     }
-    
+
     if ($where) {
       $this->query->add_where($this->options['group'], $where, $this->value);
     }
   }
-  
+
  /**
   * Defines the value field in both the views filter options form
   *   and the exposed form
   */
   function value_form(&$form, &$form_state) {
     parent::value_form($form, $form_state);
-    
+
     if (preg_match('/select/', $this->options['values_form_type'])) {
       // Get Options
       if ($this->options['optional']) {
-        $options['<select '.$this->table.'>'] = '--None--';
+        $options['<select ' . $this->table . '>'] = '--None--';
         $options['All'] = '--Any--';
       }
       $max_length = 40;
       foreach ($this->cvterm_options as $cvterm_id => $cvterm_name) {
-        if (strlen($cvterm_name) > $max_length) {
-          $options[$cvterm_id] = substr($cvterm_name,0,$max_length) . '...';
-        } else {
-          $options[$cvterm_id] = $cvterm_name;    
+        if (drupal_strlen($cvterm_name) > $max_length) {
+          $options[$cvterm_id] = drupal_substr($cvterm_name, 0, $max_length) . '...';
+        }
+        else {
+          $options[$cvterm_id] = $cvterm_name;
         }
       }
-      
+
       if (empty($options)) {
         $options[0] = '';
       }
-      
+
       //Select List
       $form['value'] = array(
           '#type' => 'select',
-          '#title' => $this->options['label'],
+          '#title' => t('%label', array('%label' => $this->options['label'])),
           '#options' => $options,
           '#default_value' => $this->value,
       );
-      
+
       if ($this->options['multiple']) {
         $form['value']['#multiple'] = TRUE;
       }
-    
-    } else {
+
+    }
+    else {
       $form['value'] = array(
         '#type' => 'textfield',
-        '#title' => $this->options['label'],
+        '#title' => t('%label', array('%label' => $this->options['label'])),
         '#default_value' => $this->value,
       );
     }
@@ -242,7 +255,7 @@ class views_handler_filter_chado_select_cvterm_name extends views_handler_filter
         'values' => 1,
       ),
     );
-    
+
     return $operators;
   }
 }

+ 37 - 29
tripal_views/views/handlers/views_handler_filter_chado_select_string.inc

@@ -1,6 +1,7 @@
 <?php
 
 /**
+ * @file
  * Purpose: This Handler provides a generic select list for any chado field that is a string
  *  The select list includes all distinct values for that field.
  *
@@ -14,14 +15,14 @@ class views_handler_filter_chado_select_string extends views_handler_filter_stri
 
     $form['values_form_type'] = array(
       '#type' => 'radios',
-      '#title' => 'Filter Type',
+      '#title' => t('Filter Type'),
       '#options' => array(
         'textfield' => 'Text Field',
         'select' => 'Drop-Down Box',
       ),
       '#default_value' => ($this->options['values_form_type']) ? $this->options['values_form_type'] : 'select',
     );
-    
+
     $form['multiple'] = array(
       '#type' => 'checkbox',
       '#title' => t('Select Multiple'),
@@ -35,7 +36,7 @@ class views_handler_filter_chado_select_string extends views_handler_filter_stri
       '#description' => t('Adds --Any-- to the available options.'),
       '#default_value' => (isset($this->options['optional'])) ? $this->options['optional'] : TRUE,
     );
- 
+
     $form['max_length'] = array(
       '#type' => 'textfield',
       '#title' => t('Max Width'),
@@ -43,23 +44,26 @@ class views_handler_filter_chado_select_string extends views_handler_filter_stri
       '#default_value' => (isset($this->options['max_length'])) ? $this->options['max_length'] : 40,
 
     );
-    
+
   }
-  
+
  /**
   * Defines the value field in both the views filter options form
   *   and the exposed form
   */
   function value_form(&$form, &$form_state) {
     parent::value_form($form, $form_state);
-    
+
     if (preg_match('/textfield/', $this->options['values_form_type'])) {
       $form['value'] = array(
         '#type' => 'textfield',
-        '#title' => $this->options['label'],
+        '#title' => t('%label', array('%label' => $this->options['label'])),
         '#default_value' => $this->value,
-      );    
-    } else {
+      );
+
+    }
+    else {
+
       // Get Options
       if ($this->options['optional']) {
         //$options['<select '.$this->table.'>'] = '--None--';
@@ -68,27 +72,28 @@ class views_handler_filter_chado_select_string extends views_handler_filter_stri
       $sql = "SELECT $this->field FROM $this->table ORDER BY $this->field ASC";
       $previous_db = tripal_db_set_active('chado');  // use chado database
       $results = db_query($sql);
-      tripal_db_set_active($previous_db);  // now use drupal database 
+      tripal_db_set_active($previous_db);  // now use drupal database
       $max_length = $this->options['max_length'];
-      if(!$max_length){
-         $max_length = 40;
+      if (!$max_length) {
+        $max_length = 40;
       }
-      while($r = db_fetch_object($results)){
-        if (strlen($r->{$this->field}) > $max_length) {
-          $options[$r->{$this->field}] = substr($r->{$this->field},0,$max_length) . '...';
-        } else {
-          $options[$r->{$this->field}] = $r->{$this->field};    
+      while ($r = db_fetch_object($results)) {
+        if (drupal_strlen($r->{$this->field}) > $max_length) {
+          $options[$r->{$this->field}] = drupal_substr($r->{$this->field}, 0, $max_length) . '...';
+        }
+        else {
+          $options[$r->{$this->field}] = $r->{$this->field};
         }
       }
-      
+
       //Select List
       $form['value'] = array(
           '#type' => 'select',
-          '#title' => $this->options['label'],
+          '#title' => t('%label', array('%label' => $this->options['label'])),
           '#options' => $options,
           '#default_value' => $this->value,
       );
-      
+
       if ($this->options['multiple']) {
         $form['value']['#multiple'] = TRUE;
       }
@@ -131,7 +136,7 @@ class views_handler_filter_chado_select_string extends views_handler_filter_stri
   *
   */
   function query() {
-  
+
     $this->ensure_my_table();
     $field = "$this->table_alias.$this->real_field";
     $upper = $this->case_transform();
@@ -139,25 +144,28 @@ class views_handler_filter_chado_select_string extends views_handler_filter_stri
     if ($this->options['multiple']) {
       // Remove any if it's there
       unset($this->value['All']);
-      
+
       if (sizeof($this->value)) {
         $holders = array();
         foreach ($this->value as $v) {
-          if (preg_match('/^[\d\.]+$/',$v)) {
+          if (preg_match('/^[\d\.]+$/', $v)) {
             $holders[] = '%d';
-          } else {
+          }
+          else {
             $holders[] = "'%s'";
           }
         }
-        $where = "$field IN (".implode(", ",$holders).")";
+        $where = "$field IN (" . implode(", ", $holders) . ")";
         $this->query->add_where($this->options['group'], $where, $this->value);
       }
-    } else {
-  
+    }
+    else {
+
       // Deal with All/Any as value
       if (preg_match('/All/', $this->value)) {
-        // Don't do anything    
-      } else {
+        // Don't do anything
+      }
+      else {
         $info = $this->operators();
         if (!empty($info[$this->operator]['method'])) {
           $this->{$info[$this->operator]['method']}($field, $upper);

+ 70 - 74
tripal_views/views/handlers/views_handler_filter_file_upload.inc

@@ -1,6 +1,7 @@
 <?php
 
 /**
+ * @file
  * Purpose: This Handler provides a file upload field by extending the
  * views_handler_filter object.
  *
@@ -8,45 +9,35 @@
  */
 class views_handler_filter_file_upload extends views_handler_filter {
 
-  function init(&$view,$options){
-     parent::init($view,$options);
-
-  }
-
-  function options_form(&$form, &$form_state) {
-    parent::options_form($form, $form_state);
-
-  }
-  
   /**
-  * Defines the value field in both the views filter options form
-  *   and the exposed form
-  */
+   * Defines the value field in both the views filter options form
+   *   and the exposed form
+   */
   function value_form(&$form, &$form_state) {
     parent::value_form($form, $form_state);
-    
+
     $this->value_form = array(
        '#type' => 'file_upload_combo',
-       '#title' => $this->options['expose']['label'],
+       '#title' => t('%label', array('%label' => $this->options['expose']['label'])),
        '#default_value' => $this->value,
        '#multiple' => FALSE,
-       '#description' => t('Provide search values for ' . $this->options['expose']['label'] . 
-         '. Please place each search item on a separate line or separated by commas.'),
+       '#description' => t('Provide search values for %label. Please place each search
+        item on a separate line or separated by commas.', array('%label' => $this->options['expose']['label'])),
     );
     $form['value'] = &$this->value_form;
   }
 
   /**
-  * Ensures the upload field gets rendered when the filter is exposed. It also
-  * changes the form type from a GET to a POST so that file uploads will work.
-  */
+   * Ensures the upload field gets rendered when the filter is exposed. It also
+   * changes the form type from a GET to a POST so that file uploads will work.
+   */
   function exposed_form(&$form, &$form_state) {
 
     // don't do anything if the form isn't exposed.
     if (empty($this->options['exposed'])) {
       return;
     }
-    // rebuild the form elements 
+    // rebuild the form elements
     $value = $this->options['expose']['identifier'];
     $this->value_form($form, $form_state);
 
@@ -64,69 +55,74 @@ class views_handler_filter_file_upload extends views_handler_filter {
     }
 
   }
-  /** 
+
+  /**
    *  Validates the input form
    */
   function exposed_validate(&$form, &$form_state) {
      //dpm($form_state);
   }
+
   /**
    *
    */
   function query() {
-     $this->ensure_my_table();
-     $field = "$this->table.$this->real_field";
-
-     // get the form element value
-     $value = $this->value[0];
-
-     // the form element value has sub values, so get those
-     $items =  $value['items'];
-     $file_path = $value['file_path'];
-
-     $holders = array();
-     $values = array();
-
-     // get the file upload content if one has been provided
-     if($file_path){
-        $fh = fopen($file_path,'r');
-        while($line = fgets($fh)){
-           $items = trim($line);
-
-           // remove extra spaces and new lines
-           $items = preg_replace("/\s+,/",",",$items);
-           $items = preg_replace("/\s+\n/","\n",$items);
-           $items = preg_replace("/,\n/","\n",$items);
-
-           // add the values from this line to the values[] array
-           $vals = preg_split("/[\n,]+/",$items);
-           $values = array_merge($values,$vals);
-        }
-     } 
-     // if a file upload has not been provided then use the value in the textarea
-     if($items){
+    $this->ensure_my_table();
+    $field = "$this->table.$this->real_field";
+
+    // get the form element value
+    $value = $this->value[0];
+
+    // the form element value has sub values, so get those
+    $items =  $value['items'];
+    $file_path = $value['file_path'];
+
+    $holders = array();
+    $values = array();
+
+    // get the file upload content if one has been provided
+    if ($file_path) {
+      $fh = fopen($file_path, 'r');
+      while ($line = fgets($fh)) {
+        $items = trim($line);
 
         // remove extra spaces and new lines
-        $items = preg_replace("/\s+,/",",",$items);
-        $items = preg_replace("/\s+\n/","\n",$items);
-        $items = preg_replace("/,\n/","\n",$items);
-
-        // in the event the user uploaded a file and provided items in the
-        // textbox then we need to merge these two lists
-        $vals = preg_split("/[\n,]+/",$items);
-        $values = array_merge($values,$vals);
-     }
-     // iterate through all of the values and generate the corresponding
-     // sprintf style holders
-     for($i = 0 ; $i < count($values); $i++){
-        $values[$i] = trim($values[$i]);
-        $holders[] = "'%s'";
-     }
-     // if we have any values supplied then update the where clause for
-     // the views query
-     if(count($holders) > 0){
-        $where = "$field IN (".implode(", ",$holders).")";
-        $this->query->add_where($this->options['group'], $where, $values);
-     }
+        $items = preg_replace("/\s+,/", ",", $items);
+        $items = preg_replace("/\s+\n/", "\n", $items);
+        $items = preg_replace("/,\n/", "\n", $items);
+
+        // add the values from this line to the values[] array
+        $vals = preg_split("/[\n,]+/", $items);
+        $values = array_merge($values, $vals);
+      }
+    }
+
+    // if a file upload has not been provided then use the value in the textarea
+    if ($items) {
+
+      // remove extra spaces and new lines
+      $items = preg_replace("/\s+,/", ",", $items);
+      $items = preg_replace("/\s+\n/", "\n", $items);
+      $items = preg_replace("/,\n/", "\n", $items);
+
+      // in the event the user uploaded a file and provided items in the
+      // textbox then we need to merge these two lists
+      $vals = preg_split("/[\n,]+/", $items);
+      $values = array_merge($values, $vals);
+    }
+
+    // iterate through all of the values and generate the corresponding
+    // sprintf style holders
+    for ($i = 0 ; $i < count($values); $i++) {
+      $values[$i] = trim($values[$i]);
+      $holders[] = "'%s'";
+    }
+
+    // if we have any values supplied then update the where clause for
+    // the views query
+    if (count($holders) > 0) {
+      $where = "$field IN (" . implode(", ", $holders) . ")";
+      $this->query->add_where($this->options['group'], $where, $values);
+    }
   }
 }

+ 21 - 15
tripal_views/views/handlers/views_handler_filter_no_results.inc

@@ -1,5 +1,11 @@
 <?php
 
+/**
+ * @file
+ * This filter ensures that when a page is first loaded, there are no results (ie: the
+ * query is not run). This imitates an advanced search form allowing users to fist
+ * enter other filter values and then retrieve results.
+ */
 class views_handler_filter_no_results extends views_handler_filter {
 
   /**
@@ -8,12 +14,12 @@ class views_handler_filter_no_results extends views_handler_filter {
   function can_expose() {
     return FALSE;
   }
-  
+
   /**
    * Defines the options form (form available to admin when they add a field to a view)
    */
   function options_form(&$form, &$form_state) {
-    
+
     $form['msg'] = array(
       '#type' => 'item',
       '#value' => t('This filter ensures that when the page is first loaded, there are no results '
@@ -22,56 +28,56 @@ class views_handler_filter_no_results extends views_handler_filter {
         .'large number of results if left unfiltered since it removes the long load time before '
         .'even allowing users the ability to filter down the results.')
     );
-    
+
     $form['apply_button'] = array(
       '#type' => 'textfield',
       '#title' => 'Apply Button Text',
       '#default_value' => isset($this->options['apply_button']) ? $this->options['apply_button'] : 'Search'
     );
-    
+
     $form['no_results_text'] = array(
       '#type' => 'textarea',
       '#title' => 'Header Text before Search',
       '#description' => 'This text will replace the no results text when the view is first loaded (before the user clicks Apply/Search)',
       '#default_value' => isset($this->options['no_results_text']) ? $this->options['no_results_text'] : ''
     );
-    
+
   }
-  
+
   function query() {
     global $base_url;
-    
+
     if (empty($this->view->exposed_input)) {
       $this->view->executed = TRUE;
-      
+
       $jquery_loaded = FALSE;
-      
+
       // If set, change the no_results text
       if (!empty($this->options['apply_button'])) {
         if (!$jquery_loaded) {
-          drupal_set_html_head('<script type="text/javascript" src="'.$base_url.'/misc/jquery.js"></script>');
+          drupal_set_html_head('<script type="text/javascript" src="' . $base_url . '/misc/jquery.js"></script>');
           $jquery_loaded = TRUE;
         }
         $javascript = '<script type="text/javascript">'."\n"
           ."$(document).ready(function(){\n"
-          ."  $('div.view-empty').html('".addslashes($this->options['no_results_text'])."');\n"
+          ."  $('div.view-empty').html('" . addslashes($this->options['no_results_text']) . "');\n"
           ."});\n"
           .'</script>'."\n";
         drupal_set_html_head($javascript);
       }
     }
-    
+
     // Set the Apply button text
     if (!empty($this->options['apply_button'])) {
       if (!$jquery_loaded) {
-        drupal_set_html_head('<script type="text/javascript" src="'.$base_url.'/misc/jquery.js"></script>');
+        drupal_set_html_head('<script type="text/javascript" src="' . $base_url . '/misc/jquery.js"></script>');
         $jquery_loaded = TRUE;
       }
       $javascript = '<script type="text/javascript">'."\n"
         ."$(document).ready(function(){\n"
-        ."  $('div.views-submit-button').html(".'"'."<input type='submit' id='edit-submit-all-analysis' value='".$this->options['apply_button']."' class='form-submit'>".'"'.");\n"
+        ."  $('div.views-submit-button').html(" . '"' . "<input type='submit' id='edit-submit-all-analysis' value='" . $this->options['apply_button'] . "' class='form-submit'>" . '"' . ");\n"
         ."});\n"
-        .'</script>'."\n";
+        .'</script>' . "\n";
       drupal_set_html_head($javascript);
     }
   }

+ 59 - 49
tripal_views/views/handlers/views_handler_join_chado_aggregator.inc

@@ -1,6 +1,7 @@
 <?php
 
 /**
+ * @file
  * Handler to allow joins between records via a linking table
  *
  * Example Usage:
@@ -21,7 +22,7 @@ class views_handler_join_chado_aggregator extends views_join {
   // the call to constructors upstream where appropriate.
   function construct($table = NULL, $left_table = NULL, $left_field = NULL, $field = NULL, $extra = array(), $type = 'LEFT', $added = NULL) {
     parent::construct($table, $left_table, $left_field, $field, $extra, $type);
-    
+
     // Determine the postgresql version
     $postgresql_version = pg_version();
     $this->postgresql_version = $postgresql_version['client'];
@@ -42,33 +43,33 @@ class views_handler_join_chado_aggregator extends views_join {
 
     // Create the table SQL (used in join) -------
     // query creating one-to-one table using array_agg
-    $table_desc = module_invoke_all('chado_'.$this->definition['table'].'_schema');
+    $table_desc = module_invoke_all('chado_' . $this->definition['table'] . '_schema');
     $select_fields[ $this->definition['table'] ] = $table_desc['fields'];
-    
+
     // Add joins to tables with a foreign key in this table
     // (ie: add join to cvterm if this table has a type_id
     $joins = array();
-    foreach($table_desc['foreign keys'] as $defn) {
+    foreach ($table_desc['foreign keys'] as $defn) {
       if ($defn['table'] != $this->left_table) {
-        foreach( $defn['columns'] as $left => $right) {
+        foreach ( $defn['columns'] as $left => $right) {
           $left = $this->definition['table'] .'.'. $left;
-          $right = $defn[table] .'.'. $right;
+          $right = $defn['table'] .'.'. $right;
           $joins[] = "LEFT JOIN $defn[table] $defn[table] ON $left=$right";
         }
-        
+
         // Fields to be selected from joined table
-        $join_table = module_invoke_all('chado_'.$defn['table'].'_schema');
+        $join_table = module_invoke_all('chado_' . $defn['table'] . '_schema');
         $select_fields[ $defn['table'] ] = $join_table['fields'];
-      } 
+      }
     }
-    
+
     // Determine Order BY's for aggregates
     $order_by = array();
     foreach ($this->sort as $s) {
-      $order_by[] = $s['table'].'.'.$s['field'].' '.$s['order'];
+      $order_by[] = $s['table'] . '.' . $s['field'] . ' ' . $s['order'];
     }
-    
-    
+
+
     // Fields to be selected
     foreach ($select_fields as $table => $table_fields) {
       foreach ($table_fields as $fname => $f) {
@@ -76,43 +77,46 @@ class views_handler_join_chado_aggregator extends views_join {
         if ($table != $this->definition['table']) {
           $alias = $table .'_';
         }
-        
+
         if ($fname != $this->definition['field']) {
           // Add sort to aggregate field if postgreSQL 9.0+
           if ($this->postgresql_9up && !empty($order_by)) {
-            $fields[] = 'array_agg('.$table.'.'.$fname.' ORDER BY '.implode(',',$order_by).') as '.$alias.$fname;
-          } else {
-            $fields[] = 'array_agg('.$table.'.'.$fname.') as '.$alias.$fname;
+            $fields[] = 'array_agg(' . $table . '.' . $fname . ' ORDER BY ' . implode(',', $order_by) . ') as ' . $alias . $fname;
+          }
+          else {
+            $fields[] = 'array_agg(' . $table . '.' . $fname . ') as ' . $alias . $fname;
           }
-          $composite_field_parts[] = "'".$alias.$fname."::' ||".$table.'.'.$fname;
-        } else {
+          $composite_field_parts[] = "'" . $alias . $fname . "::' ||" . $table . '.' . $fname;
+        }
+        else {
           $fields[] = $fname;
-          $composite_field_parts[] = "'".$alias.$fname."::' ||".$table.'.'.$fname;
+          $composite_field_parts[] = "'" . $alias . $fname . "::' ||" . $table . '.' . $fname;
         }
       }
     }
-    
-    // composite field 
+
+    // composite field
     // (combines all other fields before aggregating)
     // Add sort to aggregate field if postgreSQL 9.0+
     if ($this->postgresql_9up && !empty($order_by)) {
-      $composite_field = "array_agg('{'||".implode(" || ',' || ",$composite_field_parts)."||'}' ORDER BY ".implode(',',$order_by).") as all";
-    } else {
-      $composite_field = "array_agg('{'||".implode(" || ',' || ",$composite_field_parts)."||'}') as all";
+      $composite_field = "array_agg('{'||" . implode(" || ',' || ", $composite_field_parts) . "||'}' ORDER BY " . implode(',', $order_by) . ") as all";
+    }
+    else {
+      $composite_field = "array_agg('{'||" . implode(" || ',' || ", $composite_field_parts) . "||'}') as all";
     }
     $fields[] = $composite_field;
-    
+
     // SQL to use in the join
-    $sql = 'SELECT '.implode(', ',$fields)
-      .' FROM '.$this->definition['table']
-      .' '.implode(' ',$joins);
- 
+    $sql = 'SELECT ' . implode(', ', $fields)
+      .' FROM ' . $this->definition['table']
+      .' ' . implode(' ', $joins);
+
     if (!empty($this->filter)) {
-      $sql .= ' WHERE '.implode(', ', $this->filter);
+      $sql .= ' WHERE ' . implode(', ', $this->filter);
     }
-    
-    $sql .= ' GROUP BY '.$this->definition['field'];
-    
+
+    $sql .= ' GROUP BY ' . $this->definition['field'];
+
     // Create the join (full SQL) ----------------
     $output[] = $this->create_single_join(
       $query,
@@ -128,41 +132,47 @@ class views_handler_join_chado_aggregator extends views_join {
       ),
       'LEFT'
     );
-    
-    return implode("\n",$output);
+
+    return implode("\n", $output);
   }
-  
+
   /**
    * Creates SQL for a single join based on parameters
-   * Join will be: <type> JOIN (<query creating one-to-one table using array_agg>) <table alias> 
+   * Join will be: <type> JOIN (<query creating one-to-one table using array_agg>) <table alias>
    *                  ON <qualified left field>=<qualified right field>
    */
-  function create_single_join (&$query, $right_spec, $left_spec, $join_type) {
-    
+  function create_single_join(&$query, $right_spec, $left_spec, $join_type) {
+
     if ($right_spec['table']) {
       $right = $query->get_table_info($right_spec['table']);
-      if (!$right['alias']) { $right['alias'] = $right_spec['table']; }
+      if (!$right['alias']) {
+        $right['alias'] = $right_spec['table'];
+      }
       $right_field = "$right[alias].$right_spec[field]";
 
       if ($right_spec['is_drupal']) {
-        $right_table = '{'.$right_spec['table'].'}';
-      } else {
+        $right_table = '{' . $right_spec['table'] . '}';
+      }
+      else {
         $right_table = $right_spec['table'];
       }
-    }   
+    }
 
     if ($left_spec['table']) {
       $left = $query->get_table_info($left_spec['table']);
-      if (!$left['alias']) { $left['alias'] = $left_spec['table']; }
+      if (!$left['alias']) {
+        $left['alias'] = $left_spec['table'];
+      }
       $left_field = "$left[alias].$left_spec[field]";
-    } else {
+    }
+    else {
       // This can be used if left_field is a formula or something. It should be used only *very* rarely.
       $left_field = $this->left_spec['field'];
     }
-    
+
     $output = " $join_type JOIN ($right_spec[table_sql]) $right[alias] ON $left_field = $right_field";
-     
+
     return $output;
   }
- 
+
 }

+ 27 - 20
tripal_views/views/handlers/views_handler_join_chado_through_linking.inc

@@ -1,9 +1,10 @@
 <?php
 
-module_load_include('inc','views','includes/base');
-module_load_include('inc','views','includes/handlers');
+module_load_include('inc', 'views', 'includes/base');
+module_load_include('inc', 'views', 'includes/handlers');
 
 /**
+ * @file
  * Handler to allow joins between records via a linking table
  *
  * Example Usage:
@@ -20,10 +21,10 @@ module_load_include('inc','views','includes/handlers');
           'left_field' => 'feature_id',
           'field' => 'analysis_id',
           'handler' => 'views_handler_join_chado_through_linking'
-        ); 
+        );
  *   @endcode
  *
- * NOTE: If the right table is in the drupal schema rather then the chado schema 
+ * NOTE: If the right table is in the drupal schema rather then the chado schema
  *  (ie: node, chado_feature) then add the following to the above join description:
  *  @code
     'table_is_drupal' => TRUE
@@ -40,7 +41,7 @@ class views_handler_join_chado_through_linking extends views_join {
   function construct($table = NULL, $left_table = NULL, $left_field = NULL, $field = NULL, $extra = array(), $type = 'LEFT', $added = NULL) {
     parent::construct($table, $left_table, $left_field, $field, $extra, $type);
   }
-  
+
   /**
    * Creates SQL for both joins table => linking_table and linking_table => left_table
    * NOTE: Uses fields in definition as passed in from hook_views_data join definition
@@ -62,7 +63,7 @@ class views_handler_join_chado_through_linking extends views_join {
       ),
       'LEFT'
     );
-    
+
     $joins[] = $this->create_single_join(
       $query,
       array(
@@ -76,40 +77,46 @@ class views_handler_join_chado_through_linking extends views_join {
       ),
       'LEFT'
     );
-    
-    $output .= implode("\n",$joins);
+
+    $output .= implode("\n", $joins);
     return $output;
   }
-  
+
   /**
    * Creates SQL for a single join based on parameters
    */
-  function create_single_join (&$query, $right_spec, $left_spec, $join_type) {
-    
+  function create_single_join(&$query, $right_spec, $left_spec, $join_type) {
+
     if ($right_spec['table']) {
       $right = $query->get_table_info($right_spec['table']);
-      if (!$right['alias']) { $right['alias'] = $right_spec['table']; }
+      if (!$right['alias']) {
+        $right['alias'] = $right_spec['table'];
+      }
       $right_field = "$right[alias].$right_spec[field]";
 
       if ($right_spec['is_drupal']) {
-        $right_table = '{'.$right_spec['table'].'}';
-      } else {
+        $right_table = '{' . $right_spec['table'] . '}';
+      }
+      else {
         $right_table = $right_spec['table'];
       }
-    }   
+    }
 
     if ($left_spec['table']) {
       $left = $query->get_table_info($left_spec['table']);
-      if (!$left['alias']) { $left['alias'] = $left_spec['table']; }
+      if (!$left['alias']) {
+        $left['alias'] = $left_spec['table'];
+        }
       $left_field = "$left[alias].$left_spec[field]";
-    } else {
+    }
+    else {
       // This can be used if left_field is a formula or something. It should be used only *very* rarely.
       $left_field = $this->left_spec['field'];
     }
-    
+
     $output = " $join_type JOIN $right_table $right[alias] ON $left_field = $right_field";
-     
+
     return $output;
   }
- 
+
 }

+ 0 - 84
tripal_views/views/template.node_join.views.inc

@@ -1,84 +0,0 @@
-<?php
-
-/*************************************************************************
- * @file: THIS IS A TEMPLATE AND SHOULD NOT BE INCLUDED IN THE MODULE CODE
- *
- *  - simply replace all XXX with the original chado table you want to join to it's drupal nodes.
- *    (ie: If you want to join features to their drupal nodes then XXX=feature)
- * 
- *  NOTE: Creating the table definition file is not enough. You also need to call the 
- *        retrieve_XXX_views_data() function from ../tripal_core.views.inc:tripal_core_views_data()
- *        by adding the following line:
- *           $data = array_merge($data, retrieve_XXX_views_data());
- *        to the function and including the file directly above the function (blow the function 
- *        header by adding:
- *           require_once('views/XXX.views.inc');
- *
- *  REMOVE THIS COMMENT IN THE COPY!
- */ 
- 
-/**
- *  @file
- *  This file defines the data array for a given chado table. This array
- *  is merged into a larger array containing definitions of all tables associated
- *  with this module in:
- *  @see tripal_core.views.inc --in tripal_core_views_data()
- *
- *  Note: All chado tables are joined to their drupal nodes through the chado_XXX linking table. 
- *        This file simply defines this linking table and joins the three tables together.
- *        No modification of XXX.views.inc is needed.
- *
- *  Documentation on views integration can be found at 
- *  http://views2.logrus.com/doc/html/index.html.
- */
- 
-/**
- * Purpose: this function returns the portion of the data array 
- *   which describes the chado_XXX drupal table, it's fields and any joins between it 
- *   and other tables
- * @see tripal_core_views_data() --in tripal_core.views.inc
- *
- * The main need for description of this table to views is to join chado data with drupal nodes
- *
- */
-function retrieve_chado_XXX_views_data () {
-	global $db_url;
-  $data = array();
-  
-  // if the chado database is not local to the drupal database
-  // then we need to set the database name.  This should always
-  // be 'chado'.
-  if(is_array($db_url) and array_key_exists('chado',$db_url)){
-     // return empty data array b/c if chado is external then no join to the nodetable can be made
-     return $data;
-  }
-
-  //Basic table definition-----------------------------------
-  $data['chado_XXX']['table'] = array(
-    'field' => 'nid',
-  );
-  
-  //Relationship Definitions---------------------------------
-  // Note: No joins need to be made from $data['XXX']['table']
-  
-  // Join the chado_XXX table to XXX
-  $data['chado_XXX']['table']['join']['XXX'] = array(
-  	'left_field' => 'XXX_id',
-  	'field' => 'XXX_id',
-  );
-  
-  // Join the node table to chado_XXX
-  $data['node']['table']['join']['chado_XXX'] = array(
-  	'left_field' => 'nid',
-  	'field' => 'nid',
-  );
-  
-  // Join the node table to XXX
-  $data['node']['table']['join']['XXX'] = array(
-  	'left_table' => 'chado_XXX',
-  	'left_field' => 'nid',
-  	'field' => 'nid',
-  );  
-
-	return $data;
-}

+ 0 - 211
tripal_views/views/template.table_defn.views.inc

@@ -1,211 +0,0 @@
-<?php
-
-/*************************************************************************
- * @file: THIS IS A TEMPLATE AND SHOULD NOT BE INCLUDED IN THE MODULE CODE
- *
- *   - Every instance of XXX should be replaced with the name of your table
- *   - If this is a base table (you want a view where every row is a row from this table)
- *     then change $data['XXX']['table'] to $data['XXX']['table']['base'] 
- *     and $data['XXX']['table']['database'] to $data['XXX']['table']['base']['database']
- *   - Relationships between this table and others: YYY is the table you are trying to join to this
- *     one. You want to join a table to this one if this table contains a foreign key to the other
- *     table. If the join between this table and another is through a linking table
- *     (ie: library-XXX/YYY => library_feature-XY => feature-XXX/YYY) then make the join in both
- *     directions (ie: in the file XXX.views.inc and the file YYY.views.inc
- *   - Create a field definition for each field in this table using the example fields already
- *     listed. Match the type of the database field to the field definition listed below.
- *     (ie: for a text/varchar field from the database use plain_text_field below)
- * 
- *  NOTE: Creating the table definition file is not enough. You also need to call the 
- *        retrieve_XXX_views_data() function from ../tripal_core.views.inc:tripal_core_views_data()
- *        by adding the following line:
- *           $data = array_merge($data, retrieve_XXX_views_data());
- *        to the function and including the file directly above the function (blow the function 
- *        header by adding:
- *           require_once('views/XXX.views.inc');
- *
- *  REMOVE THIS COMMENT IN THE COPY!
- */ 
- 
-/**
- *  @file
- *  This file defines the data array for a given chado table. This array
- *  is merged into a larger array containing definitions of all tables associated
- *  with this module in:
- *  @see tripal_core.views.inc --in tripal_core_views_data()
- *
- *  Documentation on views integration can be found at 
- *  http://views2.logrus.com/doc/html/index.html.
- */
-
-/*************************************************************************
- * Purpose: this function returns the portion of the data array 
- *   which describes the XXX table, it's fields and any joins between it and other tables
- * @see tripal_core_views_data() --in tripal_core.views.inc
- *
- * Table: XXX
- * @code
- * XXX-Copy/Paste Table SQL code here-XXX
- * @endcode
- */
- function retrieve_XXX_views_data() {
-  global $db_url;
-  $data = array();
-
-  // if the chado database is not local to the drupal database
-  // then we need to set the database name.  This should always
-  // be 'chado'.
-  if(is_array($db_url) and array_key_exists('chado',$db_url)){
-    $database = 'chado';
-  }
-   
-  //Basic table definition-----------------------------------
-  $data['XXX']['table']['group'] = t('Chado XXX');
-  
-  $data['XXX']['table'] = array(
-    'field' => 'primary_id',
-    'title' => t('Chado XXX'),
-    'help' => t('Enter some user-friendly description of this tables purpose to the user.'),
-  );
-  if($database){
-     $data['XXX']['table']['database'] = $database;
-  }
-
-  
-  //Relationship Definitions---------------------------------
-  //Join: YYY => XXX
-  // Notice that this relationship tells the primary table to show it's fields to the
-  // table referencing it by a foreign key and thus the relationship is from
-  // primary table to table referenceing it (ie: cvterm => feature)
-  $data['XXX']['table']['join']['YYY'] = array(
-    'left_field' => 'foreign key in YYY table',
-    'field' => 'primary key in XXX table',
-  );  
-  
-  //Join: XXX => XY => YYY
-  // This relationship should be described in both directions
-  // in the appropriate files (ie: for feature => library 
-  // describe in both feature.views.inc and library.views.inc)
-  $data['XXX']['table']['join']['XY'] = array(
-    'left_field' => 'matching XXX key in the XY table',
-    'field' => 'primary key in XXX table',
-  );  
-  $data['XXX']['table']['join']['YYY'] = array(
-    'left_table' => 'XY',
-    'left_field' => 'matching XXX key in the XY table',
-    'field' => 'primary key in XXX table',
-  );
-  $data['XY']['table']['join']['YYY'] = array(
-    'left_field' => 'primary key in YYY table',
-    'field' => 'matching YYY key in the XY table',
-  );
-   
-  //Table Field Definitions----------------------------------
-      
-  //Field: XXX_id (primary key)
-  $data['XXX']['field_name'] = array(
-    'title' => t('XXX Primary Key'),
-    'help' => t('A unique index for every XXX.'),
-    'field' => array(
-      'handler' => 'views_handler_field_numeric',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_numeric',
-    ),
-  );
-
-  /*.......................................................
-   * Beginning of Example Field definitions
-   * Remove this section when done
-   */
-
-  //Field: plain_text_field (chado datatype)   
-  $data['XXX']['plain_text_field'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_string',
-    ),
-    'argument' => array(
-      'handler' => 'views_handler_argument_string',
-    ),
-  );
-
-  //Field: numeric_field (chado datatype)   
-  $data['XXX']['numeric_field'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_numeric',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_numeric',
-    ),
-  );
-
-  //Field: boolean_field (chado datatype)   
-  $data['XXX']['boolean_field'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_boolean',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_boolean_operator',
-    ),
-  );
-
-  //Field: unix_timestamp (chado datatype)   
-  $data['XXX']['unix_timestamp'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_date',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort_date',
-    ),
-    'filter' => array(
-      'handler' => 'views_handler_filter_date',
-    ),
-  );
-
-  //Field: human_readable_date (chado datatype)   
-  $data['XXX']['human_readable_date'] = array(
-    'title' => t('Human-Readable Name'),
-    'help' => t('Description of this field.'),
-    'field' => array(
-      'handler' => 'views_handler_field_readble_date',
-      'click sortable' => TRUE,
-     ),
-    'sort' => array(
-      'handler' => 'views_handler_sort_date',
-    ),
-  );
-   
-   /*
-    * End of Example Field definitions
-    */
-    
-  return $data;
-}

+ 1 - 1
tripal_views/views_data_export/plugins/tripal_views_plugin_style_export_fasta.inc

@@ -20,7 +20,7 @@ class tripal_views_plugin_style_export_fasta extends views_data_export_plugin_st
   function option_definition() {
     $options = parent::option_definition();
 
-  
+
     return $options;
   }
 

+ 24 - 12
tripal_views/views_data_export/theme/tripal_views_data_export.theme.inc

@@ -1,17 +1,29 @@
 <?php
 
+/**
+ * @file
+ * Contains template preprocessing functions
+ */
+
+/**
+ * Preprocess the variables for the FASTA views data export -body template
+ *   - replace the field tokens in the fasta record definition lines
+ *
+ * @param $vars
+ *   The variables available to the template
+ */
 function template_preprocess_views_data_export_fasta_body(&$vars) {
-   _views_data_export_header_shared_preprocess($vars);
-   _views_data_export_body_shared_preprocess($vars);
-   $defline_tpl = $vars['options']['defline_fields'];
+  _views_data_export_header_shared_preprocess($vars);
+  _views_data_export_body_shared_preprocess($vars);
+  $defline_tpl = $vars['options']['defline_fields'];
 
-   // iterate through the rows and replace the field tokens with values
-   // to generate the definition line
-   foreach ($vars['themed_rows'] as $i => $fields) {
-      $defline = $defline_tpl;
-      foreach ($fields as $key => $value) {
-         $defline = preg_replace("/\[$key\]/",$value,$defline);
-      }
-      $vars['themed_rows'][$i]['defline'] = $defline;
-   }
+  // iterate through the rows and replace the field tokens with values
+  // to generate the definition line
+  foreach ($vars['themed_rows'] as $i => $fields) {
+    $defline = $defline_tpl;
+    foreach ($fields as $key => $value) {
+      $defline = preg_replace("/\[$key\]/", $value, $defline);
+    }
+    $vars['themed_rows'][$i]['defline'] = $defline;
+  }
 }

+ 30 - 13
tripal_views/views_data_export/theme/views-data-export-fasta-body.tpl.php

@@ -1,19 +1,36 @@
 <?php
+
+/**
+ * @file
+ * Renders the body portion of a FASTA views data export
+ */
+
 //print_r($themed_rows);
+
+// print the first FASTA record header
+// this is needed due to the order of the fields
 print $defline;
-foreach ($themed_rows as $index => $fields){
-   $defline = array();
-   $residues = '';
-   foreach ($fields as $key => $value){
-     if(strcmp($key,'residues')==0){
-        $residues = wordwrap($value, 60, "\r\n", true);
-     } 
-     if(strcmp($key,'defline')==0){
-        $defline = $value;
-     }
-   }
-   print ">$defline\r\n";
-   print "$residues\r\n";
+
+// foreach row in the views table
+foreach ($themed_rows as $index => $fields) {
+  $defline = array();
+  $residues = '';
+  foreach ($fields as $key => $value) {
+
+    // wrap the sequence
+    if (strcmp($key, 'residues') == 0) {
+      $residues = wordwrap($value, 60, "\r\n", TRUE);
+    }
+
+    // set the FASTA header
+    if (strcmp($key, 'defline') == 0) {
+      $defline = $value;
+    }
+  }
+
+  // print the FASTA record
+  print ">$defline\r\n";
+  print "$residues\r\n";
 }
 
 

+ 2 - 0
tripal_views/views_data_export/theme/views-data-export-fasta-footer.tpl.php

@@ -1,5 +1,7 @@
 <?php
 
 /**
+ * @file
+ * Renders the footer of a FASTA views data export
  * FASTA files don't have a footer.
  */

+ 2 - 0
tripal_views/views_data_export/theme/views-data-export-fasta-header.tpl.php

@@ -1,5 +1,7 @@
 <?php
 
 /**
+ * @file
+ * Renders the header of a FASTA views data export
  * FASTA files don't have a header.
  */

Vissa filer visades inte eftersom för många filer har ändrats