瀏覽代碼

Nightly checking

spficklin 11 年之前
父節點
當前提交
34bfc95115

+ 11 - 10
tripal_core/api/tripal_core_chado.api.inc

@@ -97,13 +97,11 @@ require_once "tripal_core.schema_v1.11.api.inc";
 function tripal_core_chado_insert($table, $values, $options = array()) {
 
   if (!is_array($values)) {
-    watchdog('tripal_core', 'Cannot pass non array as values for inserting.', array(),
-      WATCHDOG_ERROR);
+    watchdog('tripal_core', 'Cannot pass non array as values for inserting.', array(), WATCHDOG_ERROR);
     return FALSE;
   }
   if (count($values)==0) {
-    watchdog('tripal_core', 'Cannot pass an empty array as values for inserting.', array(),
-      WATCHDOG_ERROR);
+    watchdog('tripal_core', 'Cannot pass an empty array as values for inserting.', array(), WATCHDOG_ERROR);
     return FALSE;
   }
 
@@ -2426,15 +2424,19 @@ function tripal_core_chado_schema_exists() {
   // @coder-ignore: acting on pg_catalog schema rather then drupal schema therefore, table prefixing does not apply
   $sql = "
     SELECT nspname
-    FROM pg_catalog.pg_namespace
-    WHERE nspname = 'chado'
+    FROM pg_namespace
+    WHERE
+      has_schema_privilege(nspname, 'USAGE') AND
+      nspname = 'chado'
   ";
   $results = db_query($sql);
   $name = $results->fetchObject();
   if ($name) {
+    variable_set('chado_schema_exists', FALSE);
     return TRUE;
   }
   else {
+    variable_set('chado_schema_exists', TRUE);
     return FALSE;
   }
 }
@@ -2464,8 +2466,7 @@ function tripal_core_schema_exists($schema) {
   $name = $results->fetchObject();
   if (strcmp($name->nspname, $schema) != 0) {
     return FALSE;
-  }
-
+  }  
   return TRUE;
 }
 
@@ -2795,7 +2796,7 @@ function tripal_core_is_chado_installed() {
     return TRUE;
   }
 
-  // check to make sure the chado schema exists
+  // check to make sure the chado schema exists          
   return tripal_core_chado_schema_exists();
 }
 
@@ -2856,7 +2857,7 @@ function tripal_db_set_active($dbname  = 'default') {
   global $databases, $active_db;
 
   $chado_exists = variable_get('chado_schema_exists', FALSE);
-  if ($chado_exists) {
+  if ($dbname ) {
     if ($dbname == 'chado') {
       db_query('set search_path to chado');
       return 'default';

+ 1 - 2
tripal_core/api/tripal_core_custom_tables.api.inc

@@ -126,8 +126,7 @@ function tripal_core_create_custom_table($table, $schema, $skip_creation = 1) {
     catch (Exception $e) {
       tripal_db_set_active($previous_db);  // now use drupal database
       $error = $e->getMessage();
-      watchdog('tripal_core', "Error adding custom table: @message",
-        array('@message' => $error), WATCHDOG_ERROR);
+      watchdog('tripal_core', "Error adding custom table: @message", array('@message' => $error), WATCHDOG_ERROR);
       drupal_set_message("Could not add custom table. $error.", "error");
       return FALSE;
     }    

+ 72 - 47
tripal_core/api/tripal_core_mviews.api.inc

@@ -35,31 +35,11 @@
  *   currently not used
  * @param $comment
  *   A string containing a description of the materialized view
- * @param $mv_schema
- *   If using the newer Schema API array to define the materialized view then
- *   this variable should contain the array or a string representation of the 
- *   array.
- * 
+ *
  * @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) {
-    // if the schema is provided as a string then convert it to an array
-    if (!is_array($mv_schema)) {
-      eval("\$schema_arr = $mv_schema;");
-    }
-    // if the schema is provided as an array then create a string
-    // copy of it for storage in the mview 
-    else {
-      $schema_arr = $mv_schema;
-      $mv_schema = var_export($schema_arr, 1);
-    }
-    $mv_table = $schema_arr['table'];
-  }
+function tripal_add_legacy_mview($name, $modulename, $mv_table, $mv_specs, $indexed,
+  $query, $special_index, $comment = NULL) {
 
   // Create a new record
   $record = new stdClass();
@@ -71,7 +51,6 @@ function tripal_add_mview($name, $modulename, $mv_table, $mv_specs, $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
@@ -93,30 +72,76 @@ function tripal_add_mview($name, $modulename, $mv_table, $mv_specs, $indexed,
         $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_core_create_custom_table ($mv_table, $schema_arr, 0)) {
-        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)));
-      }
+  // 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');
+  }
+}
+/**
+ * Add a materialized view to the chado database to help speed data access. This
+ * 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.
+ *
+ * @param $name
+ *   The name of the materialized view.
+ * @param $modulename
+ *   The name of the module submitting the materialized view (e.g. 'tripal_library')
+ * @param $mv_schema
+ *   If using the newer Schema API array to define the materialized view then
+ *   this variable should contain the array or a string representation of the 
+ *   array.
+ * @param $query
+ *   The SQL query that loads the materialized view with data
+ * @param $comment
+ *   A string containing a description of the materialized view 
+ *   
+ * @ingroup tripal_mviews_api
+ */
+function tripal_add_mview($name, $modulename, $schema_arr, $query, $comment = NULL) {
+  
+  $mv_table = $schema_arr['table'];
+  
+  if (!$mv_table) {
+     watchdog('tripal_core', 'Must have a table name when creating an mview.', array(), WATCHDOG_ERROR);
+     return NULL;
+  }
+
+  // Create a new record
+  $record = new stdClass();
+  $record->name = $name;
+  $record->modulename = $modulename;
+  $record->mv_table = $mv_table;
+  $record->query = $query;
+  $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
+    if (chado_table_exists($mv_table)) {
+      $sql = 'DROP TABLE {' . $mv_table . '}';
+      chado_query($sql);
+    }   
+    // create the table
+    if (!tripal_core_create_custom_table ($mv_table, $schema_arr, 0)) {
+      drupal_set_message(t("Could not create the materialized view. Check Drupal error report logs."), 'error');
     }
     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');
-      }
+      drupal_set_message(t("View '%name' created", array('%name' => $name)));
     }
   }
 }
@@ -319,8 +344,8 @@ function tripal_mviews_action($op, $mview_id, $redirect = FALSE) {
     // 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);
+      $sql = "DROP TABLE {" . $mview->mv_table . "}";
+      chado_query($sql);
     }
     tripal_db_set_active($previous_db);  // now use drupal database
   }

+ 11 - 11
tripal_core/includes/mviews.inc

@@ -25,14 +25,14 @@ function tripal_mview_report($mview_id) {
 
   // create a table with each row containig stats for
   // an individual job in the results set.
-  $output  = "<p>" . l("Return to table of materialized views", "admin/tripal/mviews/") . "</p>";
+  $output  = "<p>" . l("Return to table of materialized views", "admin/tripal/schema/mviews/") . "</p>";
   $output .= "<p>Details for <b>$mview->name</b>:</p>";
   
   // 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");
+  $update_url = url("admin/tripal/schema/mviews/action/update/$mview->mview_id");
+  $delete_url = url("admin/tripal/schema/mviews/action/delete/$mview->mview_id");
+  $edit_url = url("admin/tripal/schema/mviews/edit/$mview->mview_id");
   $rows[] = array('Actions', "<a href='$update_url'>Populate</a>, <a href='$edit_url'>Edit</a>,  <a href='$delete_url'>Delete</a>");
   
   if ($mview->last_update > 0) {    
@@ -102,20 +102,20 @@ function tripal_mviews_report() {
     }
 
     $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"),
+      l(t('View'), "admin/tripal/schema/mviews/report/$mview->mview_id") . " | " .
+      l(t('Edit'), "admin/tripal/schema/mviews/edit/$mview->mview_id") . " | " .
+      l(t('Populate'), "admin/tripal/schema/mviews/action/update/$mview->mview_id"),
       $mview->name,
       $update,
       $mview->status,
       $mview->comment,
-      l(t('Delete'), "admin/tripal/mviews/action/delete/$mview->mview_id"),
+      l(t('Delete'), "admin/tripal/schema/mviews/action/delete/$mview->mview_id"),
     );
   }
 
   $rows[] = array(
     'data' => array(
-      array('data' => l(t('Create a new materialized view.'), "admin/tripal/mviews/new"),
+      array('data' => l(t('Create a new materialized view.'), "admin/tripal/schema/mviews/new"),
         'colspan' => 6),
     )
   );
@@ -275,7 +275,7 @@ function tripal_mviews_form($form, &$form_state = NULL, $mview_id = NULL) {
   
   $form['return_link'] = array(
     '#type' => 'item',
-    '#description' => l("Return to table of materialized views", "admin/tripal/mviews/"),
+    '#description' => l("Return to table of materialized views", "admin/tripal/schema/mviews/"),
   );
   
 
@@ -391,7 +391,7 @@ function tripal_mviews_form($form, &$form_state = NULL, $mview_id = NULL) {
     '#weight'       => 9,
     '#executes_submit_callback' => TRUE,
   );
-  $form['#redirect'] = 'admin/tripal/mviews';
+  $form['#redirect'] = 'admin/tripal/schema/mviews';
 
   return $form;
 }

+ 4 - 4
tripal_core/tripal_core.module

@@ -65,7 +65,7 @@ function tripal_core_init() {
 
   // 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()) {
+  if (tripal_core_is_chado_installed()) {    
 
     // make sure the current version of chado is set
     tripal_core_set_chado_version();
@@ -242,7 +242,7 @@ function tripal_core_menu() {
     'title' => 'Materialized View',
     'description' => 'Materialized views are used to improve speed of large or complex queries. These are database views as compared to Drupal views.',
     'page callback' => 'tripal_mview_report',
-    'page arguments' => array(4),
+    'page arguments' => array(5),
     'access arguments' => array('access administration pages'),
     'type' => MENU_NORMAL_ITEM,
   );
@@ -257,7 +257,7 @@ function tripal_core_menu() {
   $items['admin/tripal/schema/mviews/edit/%'] = array(
     'title' => 'Edit Materialized View',
     'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_mviews_form', 4),
+    'page arguments' => array('tripal_mviews_form', 5),
     'access arguments' => array('access administration pages'),
     'type' => MENU_NORMAL_ITEM,
   );
@@ -265,7 +265,7 @@ function tripal_core_menu() {
     'title' => 'Create Materialized View',
     'description' => 'Materialized views are used to improve speed of large or complex queries.',
     'page callback' => 'tripal_mviews_action',
-    'page arguments' => array(4, 5, "1"),
+    'page arguments' => array(5, 6, "1"),
     'access arguments' => array('access administration pages'),
     'type' => MENU_CALLBACK,
   );

+ 87 - 51
tripal_cv/tripal_cv.install

@@ -5,6 +5,23 @@
  * Contains functions executed only on install/uninstall of this module
  */
 
+/**
+ * Implementation of hook_requirements().
+ */
+function tripal_cv_requirements($phase) {
+  $requirements = array();
+  if ($phase == 'install') {
+    // make sure chado is installed
+    if (!tripal_core_is_chado_installed()) {
+      $requirements ['tripal_cv'] = array(
+        'title' => "tripal_cv",
+        'value' => "ERROR: Chado most be installed before this module can be enabled",
+        'severity' => REQUIREMENT_ERROR,
+      );
+    }
+  }
+  return $requirements;
+}
 /**
  * Implementation of hook_install().
  *
@@ -14,45 +31,21 @@ function tripal_cv_install() {
 
   // create the module's data directory
   tripal_create_moddir('tripal_cv');
-
-  // 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} CV on CV.cv_id = CVT.cv_id
-     WHERE CVTR.object_id not in
-       (SELECT subject_id FROM {cvterm_relationship}) ',
-    // special index
-    ''
-  );
-
+    
+  // add the cv_root_mview 
+  tripal_cv_add_cv_root_mview();
+  
   // create the tables that correlate OBO files/references with a chado 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) {
+  if ($mview = tripal_mviews_get_mview_id('cv_root_mview')) {
     tripal_mviews_action('delete', $mview);
   }
 }
@@ -63,14 +56,25 @@ function tripal_cv_uninstall() {
  * @ingroup tripal_cv
  */
 function tripal_cv_schema() {
+  
   $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),
+      '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'),
+      'tripal_cv_obo_idx1' => array('obo_id'),
     ),
     'primary key' => array('obo_id'),
   );
@@ -78,6 +82,56 @@ function tripal_cv_schema() {
   return $schema;
 }
 
+/**
+ * 
+ * @ingroup tripal_cv
+ */
+function tripal_cv_add_cv_root_mview() {
+  $mv_name = 'cv_root_mview';
+  $comment = 'A list of the root terms for all controlled vocabularies. This is needed for viewing CV trees';
+  $schema = array(
+    'table' => $mv_name,
+    'description' => $comment,
+    'fields' => array(
+      'name' => array(
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+      ),
+      'cvterm_id' => array(
+        'type' => 'int',
+        'not null' => TRUE,
+      ),
+      'cv_id' => array(
+        'type' => 'int',
+        'not null' => TRUE, 
+      ),
+      'cv_name' => array(
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+      ),
+    ),
+    'indexes' => array(
+      'cv_root_mview_indx1' => array('cvterm_id'),
+      'cv_root_mview_indx2' => array('cv_id'),
+    ),
+  );
+  
+  $sql = "
+    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 CV on CV.cv_id = CVT.cv_id
+    WHERE CVTR.object_id not in
+      (SELECT subject_id FROM cvterm_relationship)
+  ";
+  
+  // Create the MView
+  tripal_add_mview($mv_name, 'tripal_cv', $schema, $sql, $comment);
+}
+
+
 /**
  * Add's defaults to the tripal_cv_obo table
  *
@@ -99,21 +153,3 @@ function tripal_cv_add_obo_defaults() {
     db_query("INSERT INTO {tripal_cv_obo} (name,path) VALUES (:name, :path)", array(':name' => $o[0], ':path' => $o[1]));
   }
 }
-
-/**
- * Implementation of hook_requirements(). 
- */
-function tripal_cv_requirements($phase) {
-  $requirements = array();
-  if ($phase == 'install') {
-    // make sure chado is installed
-    if (!tripal_core_is_chado_installed()) {
-      $requirements ['tripal_cv'] = array(
-            'title' => "tripal_cv",
-            'value' => "ERROR: Chado most be installed before this module can be enabled",
-            'severity' => REQUIREMENT_ERROR,
-      );
-    }
-  }
-  return $requirements;
-}

+ 18 - 17
tripal_db/tripal_db.install

@@ -5,6 +5,24 @@
  * Contains functions related to the installation of this module
  */
 
+/**
+ * Implementation of hook_requirements().
+ */
+function tripal_db_requirements($phase) {
+  $requirements = array();
+  if ($phase == 'install') {
+    // make sure chado is installed
+    if (!tripal_core_is_chado_installed()) {
+      $requirements ['tripal_db'] = array(
+          'title' => "tripal_db",
+          'value' => "ERROR: Chado most be installed before this module can be enabled",
+          'severity' => REQUIREMENT_ERROR,
+      );
+    }
+  }
+  return $requirements;
+}
+
 /**
  * Implementation of hook_install().
  *
@@ -26,20 +44,3 @@ function tripal_db_uninstall() {
 
 }
 
-/**
- * Implementation of hook_requirements(). 
- */
-function tripal_db_requirements($phase) {
-  $requirements = array();
-  if ($phase == 'install') {
-    // make sure chado is installed
-    if (!tripal_core_is_chado_installed()) {
-      $requirements ['tripal_db'] = array(
-            'title' => "tripal_db",
-            'value' => "ERROR: Chado most be installed before this module can be enabled",
-            'severity' => REQUIREMENT_ERROR,
-      );
-    }
-  }
-  return $requirements;
-}

+ 38 - 39
tripal_feature/api/tripal_feature.api.inc

@@ -515,8 +515,8 @@ function tripal_feature_get_formatted_sequence($feature_id, $feature_name,
         watchdog('tripal_feature', "init: not able to prepare SQL statement '%name'", 
           array('%name' => 'feature_by_subject'), 'WATCHDOG ERROR');
       }    
-      $sql = "EXECUTE feature_rel_get_object(%d,'%s')";
-      $features = chado_query($sql, $feature_id, $relationship); 
+      $sql = "EXECUTE feature_rel_get_object(:feature_id, :relationship)";
+      $features = chado_query($sql, array(':feature_id' => $feature_id, ':relationship' => $relationship)); 
     }
     if ($rel_part == "object") {
       $psql = '
@@ -537,11 +537,11 @@ function tripal_feature_get_formatted_sequence($feature_id, $feature_name,
         watchdog('tripal_feature', "init: not able to prepare SQL statement '%name'", 
           array('%name' => 'feature_by_object'), 'WATCHDOG ERROR');
       }
-      $sql = "EXECUTE feature_rel_get_subject(%d,'%s')";
-      $features = chado_query($sql, $feature_id, $relationship);     
+      $sql = "EXECUTE feature_rel_get_subject(:feature_id, :relationship)";
+      $features = chado_query($sql, array(':feature_id' => $feature_id, ':relationship' => $relationship));     
     }
     $sequences = '';
-    while ($feature = db_fetch_object($features)) {  
+    while ($feature = $features->fetchObject()) {  
 
       // recurse and get the sequences for these in the relationship
       if ($rel_part == "subject") {
@@ -625,11 +625,11 @@ function tripal_feature_get_formatted_sequence($feature_id, $feature_name,
           END as downstream,  
           OF.residues                                                     
         FROM {featureloc} FL 
-          INNER JOIN {feature} SF on FL.feature_id = SF.feature_id
-          INNER JOIN {cvterm} SCVT on SF.type_id = SCVT.cvterm_id
-          INNER JOIN {feature} OF on FL.srcfeature_id = OF.feature_id                
-          INNER JOIN {cvterm} OCVT on OF.type_id = OCVT.cvterm_id
-          INNER JOIN {organism} OO on OF.organism_id = OO.organism_id
+          INNER JOIN {feature} SF   on FL.feature_id    = SF.feature_id
+          INNER JOIN {cvterm}  SCVT on SF.type_id       = SCVT.cvterm_id
+          INNER JOIN {feature} OF   on FL.srcfeature_id = OF.feature_id                
+          INNER JOIN {cvterm}  OCVT on OF.type_id       = OCVT.cvterm_id
+          INNER JOIN {organism} OO  on OF.organism_id   = OO.organism_id
         WHERE SF.feature_id = $3 and NOT (OF.residues = \'\' or OF.residues IS NULL)) as tbl1
     ';              
     $status = tripal_core_chado_prepare('sequence_by_parent', $psql, array('int', 'int', 'int'));
@@ -677,10 +677,10 @@ function tripal_feature_get_formatted_sequence($feature_id, $feature_name,
   if ($derive_from_parent) {                  
     
     // execute the query to get the sequence from the parent
-    $sql = "EXECUTE sequence_by_parent (%d, %d, %d)";
-    $parents = chado_query($sql, $upstream, $downstream, $feature_id);
+    $sql = "EXECUTE sequence_by_parent (:upstream, :downstream, :feature_id)";
+    $parents = chado_query($sql, array(':uptream' => $upstream, ':downstream' => $downstream, ':feature_id' => $feature_id));
 
-    while ($parent = db_fetch_object($parents)) {  
+    while ($parent = $parents->fetchObject()) {  
       $seq = '';  // initialize the sequence for each parent
 
       // if we are to aggregate then we will ignore the feature returned
@@ -688,16 +688,17 @@ function tripal_feature_get_formatted_sequence($feature_id, $feature_name,
       if ($aggregate) {
         
         // now get the sub features that are located on the parent.
-        $sql = "EXECUTE sub_features (%d, %d)";
-        $children = chado_query($sql, $feature_id, $parent->srcfeature_id);
-        $sql = "EXECUTE count_sub_features (%d, %d)";
-        $num_children = db_fetch_object(chado_query($sql, $feature_id, $parent->srcfeature_id));
+        $sql = "EXECUTE sub_features (:feature_id, :srcfeature_id)";
+        $children = chado_query($sql, array(':feature_id' => $feature_id, ':srcfeature_id' => $parent->srcfeature_id));
+        $sql = "EXECUTE count_sub_features (:feature_id, :srcfeature_id)";
+        $sub_features = chado_query($sql, array(':feature_id' => $feature_id, ':srcfeature_id' => $parent->srcfeature_id));
+        $num_children = $sub_features->fetchObject();
                
         // iterate through the sub features and concat their sequences. They
         // should already be in order.
         $types = array();
         $i = 0;
-        while ($child = db_fetch_object($children)) {
+        while ($child = $children->fetchObject()) {
           // if the callee has specified that only certain sub features should be
           // included then continue if this child is not one of those allowed
           // subfeatures
@@ -710,7 +711,7 @@ function tripal_feature_get_formatted_sequence($feature_id, $feature_name,
             $types[] = $child->type_name;
           }
           
-          $sql = "EXECUTE sequence_by_parent (%d, %d, %d)";
+          $sql = "EXECUTE sequence_by_parent (:upstream, %d, :feature_id)";
 
           // if the first sub feature we need to include the upstream bases. first check if 
           // the feature is in the foward direction or the reverse.
@@ -718,13 +719,13 @@ function tripal_feature_get_formatted_sequence($feature_id, $feature_name,
             // -------------------------- ref
             //    ....---->  ---->        
             //     up    1       2         
-            $q = chado_query($sql, $upstream, 0, $child->feature_id);
+            $q = chado_query($sql, array(':upstream' => $upstream, ':downstream' => 0, ':feature_id' => $child->feature_id));
           }
           elseif ($i == 0 and $parent->strand < 0) { // reverse direction
             // -------------------------- ref
             //    ....<----  <----
             //    down  1       2
-            $q = chado_query($sql, 0, $downstream, $child->feature_id);
+            $q = chado_query($sql, array(':upstream' => 0, ':downstream' => $downstream, ':feature_id' => $child->feature_id));
           }
                     
           // Next, if the last sub feature we need to include the downstream bases. first check if
@@ -733,22 +734,22 @@ function tripal_feature_get_formatted_sequence($feature_id, $feature_name,
             // -------------------------- ref
             //        ---->  ---->....
             //          1       2 down
-            $q = chado_query($sql, 0, $downstream, $child->feature_id);
+            $q = chado_query($sql, array(':upstream' => 0, ':downstream' => $downstream, ':feature_id' => $child->feature_id));
           }
           elseif ($i == $num_children->num_children - 1 and $parent->strand < 0) { // reverse direction
             // -------------------------- ref
             //        <----  <----....
             //          1       2  up
-            $q = chado_query($sql, $upstream, 0, $child->feature_id);
+            $q = chado_query($sql, array(':upstream' => $upstream, ':downstream' => 0, ':feature_id' => $child->feature_id));
           }
           
           // for internal sub features we don't want upstream or downstream bases
           else {         
             $sql = "EXECUTE sequence_by_parent (%d, %d, %d)";
-            $q = chado_query($sql, 0, 0, $child->feature_id);
+            $q = chado_query($sql, array(':upstream' => 0, ':downstream' => 0, ':feature_id' => $child->feature_id));
           }
           
-          while ($subseq = db_fetch_object($q)) {
+          while ($subseq = $q->fetchObject()) {
             // concatenate the sequences of all the sub features            
             if ($subseq->srcfeature_id == $parent->srcfeature_id) {
               $seq .= $subseq->residues;   
@@ -809,8 +810,8 @@ function tripal_feature_get_formatted_sequence($feature_id, $feature_name,
   // if we are not getting the sequence from the parent sequence then
   // use what comes through from the feature record
   else {
-    $sql = "SELECT * FROM {feature} F WHERE feature_id = %d";
-    $values = db_fetch_object(chado_query($sql, $feature_id));
+    $sql = "SELECT * FROM {feature} F WHERE feature_id = :feature_id"; 
+    $values = chado_query($sql, array(':feature_id' => $feature_id))->fetchObject();
     $residues = $values->residues;
     if ($output_format == 'fasta_html') {
        $residues = wordwrap($residues, $num_bases_per_line, "<br>", TRUE);  
@@ -942,10 +943,9 @@ function tripal_feature_get_feature_relationships($feature) {
        // same landmark feature.
        $rel->child_featurelocs = array();     
        foreach ($cfeaturelocs as $featureloc) {
-          $res = chado_query("EXECUTE sel_featureloc_preprocess_relationships (%d, %d)", 
-            $relationship->subject_id->feature_id, 
-            $featureloc->srcfeature_id->feature_id);        
-          while ($loc = db_fetch_object($res)) {
+          $res = chado_query("EXECUTE sel_featureloc_preprocess_relationships (:relationship, :featureloc)", 
+            array(':relationship' => $relationship->subject_id->feature_id, ':featureloc' => $featureloc->srcfeature_id->feature_id));        
+          while ($loc = $res->fetchObject()) {
              // add in the node id of the src feature if it exists and save this location
              $loc->nid = $featureloc->srcfeature_id->nid;
              $rel->child_featurelocs[] = $loc;
@@ -958,8 +958,8 @@ function tripal_feature_get_feature_relationships($feature) {
        $child_type = $relationship->subject_id->type_id->name;
        
        // get the node id of the subject
-       $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = %d";
-       $n = db_fetch_object(db_query($sql, $relationship->subject_id->feature_id));
+       $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
+       $n = db_query($sql, array('feature_id' => $relationship->subject_id->feature_id))->fetchObject();
        if ($n) {
           $rel->record->nid = $n->nid;
        }
@@ -981,10 +981,9 @@ function tripal_feature_get_feature_relationships($feature) {
        // get locations where this feature overlaps with the parent
        $rel->parent_featurelocs = array();     
        foreach ($cfeaturelocs as $featureloc) {
-          $res = chado_query("EXECUTE sel_featureloc_preprocess_relationships (%d, %d)", 
-            $relationship->object_id->feature_id, 
-            $featureloc->srcfeature_id->feature_id);
-          while ($loc = db_fetch_object($res)) {
+          $res = chado_query("EXECUTE sel_featureloc_preprocess_relationships (:feature_id, :srcfeature_id)", 
+            array('feature_id' => $relationship->object_id->feature_id, ':srcfeature_id' => $featureloc->srcfeature_id->feature_id));
+          while ($loc = $res->fetchObject()) {
              // add in the node id of the src feature if it exists and save this location
              $loc->nid = $featureloc->srcfeature_id->nid;
              $rel->parent_featurelocs[] = $loc;
@@ -995,8 +994,8 @@ function tripal_feature_get_feature_relationships($feature) {
        $parent_type = $relationship->object_id->type_id->name;
        
        // get the node id of the subject
-       $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = %d";
-       $n = db_fetch_object(db_query($sql, $relationship->object_id->feature_id));
+       $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
+       $n = db_query($sql, array(':feature_id' => $relationship->object_id->feature_id))->fetchObject();
        if ($n) {
           $rel->record->nid = $n->nid;
        }

+ 11 - 11
tripal_feature/includes/fasta_loader.inc

@@ -36,7 +36,7 @@ function tripal_feature_fasta_load_form( ) {
   $org_rset = chado_query($sql);
   $organisms = array();
   $organisms[''] = '';
-  while ($organism = db_fetch_object($org_rset)) {
+  while ($organism = $org_rset->fetchObject()) {
     $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
   }
   $form['organism_id'] = array(
@@ -63,7 +63,7 @@ function tripal_feature_fasta_load_form( ) {
   $lib_rset = chado_query($sql);
   $libraries = array();
   $libraries[''] = '';
-  while ($library = db_fetch_object($lib_rset)) {
+  while ($library = $lib_rset->fetchObject()) {
     $libraries[$library->library_id] = "$library->name ($library->type)";
   }
   //   $form['library_id'] = array (
@@ -132,7 +132,7 @@ function tripal_feature_fasta_load_form( ) {
   $org_rset = chado_query($sql);
   $analyses = array();
   $analyses[''] = '';
-  while ($analysis = db_fetch_object($org_rset)) {
+  while ($analysis = $org_rset->fetchObject()) {
     $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
   }
   $form['analysis']['analysis_id'] = array(
@@ -202,7 +202,7 @@ function tripal_feature_fasta_load_form( ) {
   $db_rset = chado_query($sql);
   $dbs = array();
   $dbs[''] = '';
-  while ($db = db_fetch_object($db_rset)) {
+  while ($db = $db_rset->fetchObject()) {
     $dbs[$db->db_id] = "$db->name";
   }
   $form['advanced']['db']['db_id'] = array(
@@ -350,13 +350,13 @@ function tripal_feature_fasta_load_form_validate($form, &$form_state) {
                FROM {cvterm} CVT
                   INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
                   LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
-               WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
-  $cvterm = db_fetch_object(chado_query($cvtermsql, 'sequence', $type, $type));
+               WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)";
+  $cvterm = chado_query($cvtermsql, array(':cvname' => 'sequence', ':name' => $type, ':synonym' => $type))->fetchObject();
   if (!$cvterm) {
     form_set_error('type', t("The Sequence Ontology (SO) term selected for the sequence type is not available in the database. Please check spelling or select another."));
   }
   if ($rel_type) {
-    $cvterm = db_fetch_object(chado_query($cvtermsql, 'sequence', $parent_type, $parent_type));
+    $cvterm = chado_query($cvtermsql, array(':cvname' => 'sequence', ':name' => $parent_type, ':synonym' => $parent_type))->fetchObject();
     if (!$cvterm) {
       form_set_error('parent_type', t("The Sequence Ontology (SO) term selected for the parent relationship is not available in the database. Please check spelling or select another."));
     }
@@ -444,21 +444,21 @@ function tripal_feature_load_fasta($dfile, $organism_id, $type,
                FROM {cvterm} CVT
                   INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
                   LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
-               WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
-  $cvterm = db_fetch_object(chado_query($cvtermsql, 'sequence', $type, $type));     
+               WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)";
+  $cvterm = chado_query($cvtermsql, array(':cvname' => 'sequence', ':name' => $type, ':synonym' => $type))->fetchObject();     
   if (!$cvterm) {
     watchdog("T_fasta_loader", "Cannot find the term type: '%type'", array('%type' => $type), WATCHDOG_ERROR);
     return 0;
   }
   if ($parent_type) {
-    $parentcvterm = db_fetch_object(chado_query($cvtermsql, 'sequence', $parent_type, $parent_type));
+    $parentcvterm = chado_query($cvtermsql, array(':cvname' => 'sequence', ':name' => $parent_type, ':synonym' => $parent_type))->fetchObject();
     if (!$parentcvterm) {
       watchdog("T_fasta_loader", "Cannot find the paretne term type: '%type'", array('%type' => $parentcvterm), WATCHDOG_ERROR);
       return 0;
     }
   }
   if ($rel_type) {
-    $relcvterm = db_fetch_object(chado_query($cvtermsql, 'relationship', $rel_type, $rel_type));
+    $relcvterm = chado_query($cvtermsql, array(':cvname' => 'relationship', ':name' => $rel_type, ':synonym' => $rel_type))->fetchObject();
     if (!$relcvterm) {
       watchdog("T_fasta_loader", "Cannot find the relationship term type: '%type'", array('%type' => $relcvterm), WATCHDOG_ERROR);
       return 0;

+ 26 - 21
tripal_feature/includes/gff_loader.inc

@@ -33,7 +33,7 @@ function tripal_feature_gff3_load_form() {
   $org_rset = chado_query($sql);
   $organisms = array();
   $organisms[''] = '';
-  while ($organism = db_fetch_object($org_rset)) {
+  while ($organism = $org_rset->fetchObject()) {
     $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
   }
   $form['organism_id'] = array(
@@ -49,7 +49,7 @@ function tripal_feature_gff3_load_form() {
   $org_rset = chado_query($sql);
   $analyses = array();
   $analyses[''] = '';
-  while ($analysis = db_fetch_object($org_rset)) {
+  while ($analysis = $org_rset->fetchObject()) {
     $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
   }
   $form['analysis_id'] = array(
@@ -372,8 +372,8 @@ function tripal_feature_load_gff3($gff_file, $organism_id, $analysis_id,
 
   // get the controlled vocaubulary that we'll be using.  The
   // default is the 'sequence' ontology
-  $sql = "SELECT * FROM {cv} WHERE name = '%s'";
-  $cv = db_fetch_object(chado_query($sql, 'sequence'));
+  $sql = "SELECT * FROM {cv} WHERE name = :cvname";
+  $cv = chado_query($sql, array(':cvname' => 'sequence'))->fetchObject();
   if (!$cv) {   
     watchdog('T_gff3_loader', "Cannot find the 'sequence' ontology", 
       array(), WATCHDOG_ERROR);
@@ -381,8 +381,8 @@ function tripal_feature_load_gff3($gff_file, $organism_id, $analysis_id,
   }
 
   // get the organism for which this GFF3 file belongs
-  $sql = "SELECT * FROM {organism} WHERE organism_id = %d";
-  $organism = db_fetch_object(chado_query($sql, $organism_id));
+  $sql = "SELECT * FROM {organism} WHERE organism_id = :organism_id";
+  $organism = chado_query($sql, array(':organism_id' => $organism_id))->fetchObject();
 
   $interval = intval($filesize * 0.0001);
   if ($interval == 0) {
@@ -448,8 +448,9 @@ function tripal_feature_load_gff3($gff_file, $organism_id, $analysis_id,
       $rstart = $region_matches[2];
       $rend = $region_matches[3];
       if ($landmark_type) {
-        $result = chado_query("EXECUTE sel_cvterm_idnasy (%d, '%s', '%s')", $cv->cv_id, $landmark_type, $landmark_type);
-        $cvterm = db_fetch_object($result);
+        $result = chado_query("EXECUTE sel_cvterm_idnasy (:cv_id, :name, :synonym)", 
+          array(':cv_id' => $cv->cv_id, ':name' => $landmark_type, ':synonym' => $landmark_type));
+        $cvterm = $result->fetchObject();
         if (!$cvterm) {
           watchdog('T_gff3_loader', 'cannot find feature type \'%landmark_type\' on line %line_num of the GFF file', 
             array('%landmark_type' => $landmark_type, '%line_num' => $line_num), WATCHDOG_ERROR);
@@ -513,9 +514,10 @@ function tripal_feature_load_gff3($gff_file, $organism_id, $analysis_id,
       $phase = '';
     }
   
-    $result = chado_query("EXECUTE sel_cvterm_idnasy (%d, '%s', '%s')", $cv->cv_id, $type, $type);
+    $result = chado_query("EXECUTE sel_cvterm_idnasy (:cv_id, :name, :synonym)", 
+      array(':cv_id' => $cv->cv_id, ':name' => $type, ':synonym' => $type));
 
-    $cvterm = db_fetch_object($result);
+    $cvterm = $result->fetchObject();
     if (!$cvterm) {
       watchdog('T_gff3_loader', 'cannot find feature term \'%type\' on line %line_num of the GFF file', 
         array('%type' => $type, '%line_num' => $line_num), WATCHDOG_ERROR);
@@ -847,10 +849,10 @@ function tripal_feature_load_gff3($gff_file, $organism_id, $analysis_id,
     
     // build and prepare the SQL for selecting the children relationship
     $sql = "SELECT DISTINCT FR.feature_relationship_id, FL.fmin, FR.rank
-            FROM {feature_relationship} FR              
+            FROM {feature_relationship} FR
               INNER JOIN {featureloc} FL on FL.feature_id = FR.subject_id";
     if (!$connection) {
-      $sql .= "WHERE FR.object_id = %d " .
+      $sql .= "WHERE FR.object_id = :feature_id " .
               "ORDER BY FL.fmin ASC ";
     }
     else {
@@ -869,19 +871,19 @@ function tripal_feature_load_gff3($gff_file, $organism_id, $analysis_id,
     // on the fmin.  The start rank is 1.  This allows features with other
     // relationships to be '0' (the default), and doesn't interfer with the
     // ordering defined here.        
-    while ($parent = db_fetch_object($parents)) {
+    while ($parent = $parents->fetchObject()) {
       
       // get the children
       if ($connection) {      
-        $result = chado_query('EXECUTE sel_gffchildren (%d)', $parent->feature_id);
+        $result = chado_query('EXECUTE sel_gffchildren (:feature_id)', array(':feature_id' => $parent->feature_id));
       }
       else {
-        $result = chado_query($sql, $parent->feature_id);
+        $result = chado_query($sql, array(':feature_id' => $parent->feature_id));
       }
       
       // build an array of the children
       $children = array();
-      while ($child = db_fetch_object($result)) {
+      while ($child = $result->fetchObject()) {
          $children[] = $child;  
       }
       
@@ -1032,8 +1034,10 @@ function tripal_feature_load_gff3_parents($feature, $cvterm, $parents, $organism
     $parent_type = $result[0]->type_name;
 
     // try to find the parent
-    $parentcvterm = db_fetch_object(chado_query("EXECUTE sel_cvterm_cvname_cvtname_synonym ('%s', '%s', '%s')", 'sequence', $parent_type, $parent_type));
-    $relcvterm = db_fetch_object(chado_query("EXECUTE sel_cvterm_cvname_cvtname_synonym ('%s', '%s', '%s')", 'relationship', $rel_type, $rel_type));
+    $parentcvterm = chado_query("EXECUTE sel_cvterm_cvname_cvtname_synonym (:cvname, :name, :synonym)", 
+      array(':cvname' => 'sequence', ':name' => $parent_type, ':synonym' => $parent_type))->fetchObject();
+    $relcvterm = chado_query("EXECUTE sel_cvterm_cvname_cvtname_synonym (:cvname, :name, :synonym)", 
+      array(':cvname' => 'relationship', ':name' => $rel_type, ':synonymn' => $rel_type))->fetchObject();
     $values = array(
         'organism_id' => $organism_id,
         'uniquename' => $parent,
@@ -1373,7 +1377,8 @@ function tripal_feature_load_gff3_alias($feature, $aliases) {
         } 
       }    
       // insert the null pub 
-      $result = db_fetch_object(chado_query("EXECUTE ins_pub_uniquename_typeid ('%s', '%s')", 'null', 'null'));
+      $result = chado_query("EXECUTE ins_pub_uniquename_typeid (:uname, :type_id)", 
+        array(':uname' => 'null', ':type_id' => 'null'))->fetchObject();
       if (!$result) {
         watchdog("T_gff3_loader", "Cannot add null publication needed for setup of alias", array(), WATCHDOG_WARNING);
         return 0;
@@ -1856,7 +1861,7 @@ function tripal_feature_load_gff3_fasta($fh, $interval, &$num_read, &$intv_read,
         }
         // if we have a feature then add the residues
         else {    
-          $feature = db_fetch_object($result);    
+          $feature = $result->fetchObject();    
           $values = array('residues' => $residues);
           $match = array('feature_id' => $feature->feature_id);
           $options = array('statement_name' => 'upd_feature_re');
@@ -1880,7 +1885,7 @@ function tripal_feature_load_gff3_fasta($fh, $interval, &$num_read, &$intv_read,
   }
   // if we have a feature then add the residues
   else {        
-    $feature = db_fetch_object($result);    
+    $feature = $result->fetchObject();    
     $values = array('residues' => $residues);
     $match = array('feature_id' => $feature->feature_id);
     $options = array('statement_name' => 'upd_feature_re');

+ 29 - 29
tripal_feature/includes/seq_extract.inc

@@ -171,7 +171,7 @@ function tripal_feature_seq_extract_form(&$form_state = NULL) {
   $results = chado_query($sql);
   $genus = array();
   $genus[] = '';
-  while ($organism = db_fetch_object($results)) {
+  while ($organism = $results->fetchObject()) {
     $genus[$organism->genus] = $organism->genus;  
   }
   
@@ -196,11 +196,11 @@ function tripal_feature_seq_extract_form(&$form_state = NULL) {
     $sql = "
       SELECT DISTINCT species 
       FROM {organism} 
-      WHERE genus = '%s'
+      WHERE genus = :genus
       ORDER BY species
     ";
-    $results = chado_query($sql, $dgenus);
-    while ($organism = db_fetch_object($results)) {
+    $results = chado_query($sql, array(':genus' => $dgenus));
+    while ($organism = $results->fetchObject()) {
       $species[$organism->species] = $organism->species;  
     }
   }  
@@ -227,17 +227,17 @@ function tripal_feature_seq_extract_form(&$form_state = NULL) {
       FROM {analysis_organism} AO 
         INNER JOIN {analysis} A ON A.analysis_id = AO.analysis_id
         INNER JOIN {organism} O ON O.organism_id = AO.organism_id
-      WHERE O.genus = '%s'
+      WHERE O.genus = :genus
     ";
     $args = array();
-    $args[] = $dgenus;
+    $args[':genus'] = $dgenus;
     if ($dspecies) {
-      $sql .= " AND O.species = '%s' ";
-      $args[] = $dspecies;
+      $sql .= " AND O.species = :species ";
+      $args[':species'] = $dspecies;
     }
     $sql .=" ORDER BY A.name ";
     $results = chado_query($sql, $args);  
-    while ($analysis = db_fetch_object($results)) {
+    while ($analysis = $results->fetchObject()) {
       $analyses[$analysis->name] = $analysis->name;  
     }
   }
@@ -256,18 +256,18 @@ function tripal_feature_seq_extract_form(&$form_state = NULL) {
     $sql = "
       SELECT DISTINCT OFC.cvterm_id, OFC.feature_type
       FROM {organism_feature_count} OFC 
-      WHERE OFC.genus = '%s'
+      WHERE OFC.genus = :genus
     ";
     $args = array();
-    $args[] = $dgenus;
+    $args['genus'] = $dgenus;
     if ($dspecies) {
-      $sql .= " AND OFC.species = '%s'";
-      $args[] = $dspecies;
+      $sql .= " AND OFC.species = :species";
+      $args['species'] = $dspecies;
     }
     $sql .= " ORDER BY OFC.feature_type ";
     $results = chado_query($sql, $args);
     
-    while ($type = db_fetch_object($results)) {
+    while ($type = $results->fetchObject()) {
       $ftype[$type->feature_type] = $type->feature_type;  
     }
   }
@@ -481,45 +481,45 @@ function tripal_feature_seq_extract_get_features($org_commonname, $genus, $speci
   }         
   $sql .= "WHERE (1=1) ";
   if ($org_commonname) {
-    $sql .= "AND O.common_name = '%s' ";
-    $vars[] = $org_commonname;
+    $sql .= "AND O.common_name = :common_name ";
+    $vars[':common_name'] = $org_commonname;
   }
   if ($genus) {
-    $sql .= "AND O.genus = '%s' ";
-    $vars[] = $genus;
+    $sql .= "AND O.genus = :genus ";
+    $vars[':genus'] = $genus;
   }
   if ($species) {
-    $sql .= "AND O.species = '%s' ";
-    $vars[] = $species;
+    $sql .= "AND O.species = :species ";
+    $vars[':species'] = $species;
   }
   if ($type) {
-    $sql .= "AND CVT.name = '%s' ";
-    $vars[] = $type; 
+    $sql .= "AND CVT.name = ':cvtname ";
+    $vars[':cvtname'] = $type; 
   }
   if ($feature_name) {
     if (is_array($feature_name)) {
       $sql .= "AND F.name IN (";
       foreach ($feature_name as $i => $fname) {
-        $sql .= "'%s', ";
-        $vars[] = $fname;
+        $sql .= ":fname$i, ";
+        $vars[":fname$i"] = $fname;
       } 
       // remove the trailing comma and close the paren
       $sql = substr($sql, 0, -2) . ")";
     }
     else {
-      $sql .= "AND F.name = '%s'";
-      $vars[] = $feature_name;
+      $sql .= "AND F.name = :fname";
+      $vars[':fname'] = $feature_name;
     }
   }
   if ($analysis_name) {
-    $sql .= "AND A.name = '%s'";
-    $vars[] = $analysis_name;
+    $sql .= "AND A.name = :aname";
+    $vars[':aname'] = $analysis_name;
   }
   $num_bases_per_line = 50;
   $num_seqs = 0;
   $q = chado_query($sql, $vars);
   
-  while ($feature = db_fetch_object($q)) {
+  while ($feature = $q->fetchObject()) {
     
     $feature_id = $feature->feature_id;
     

+ 0 - 357
tripal_feature/includes/tripal_feature-db_references.inc

@@ -1,357 +0,0 @@
-<?php
-
-/**
- * @file
- * @todo Add file header description
- */
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_add_ALL_dbreferences_page($node) {
-  $output = '';
-
-  $output .= tripal_feature_implement_add_chado_properties_progress('db_references') . '<br />';
-  $output .= '<b>All Database References should strictly pertain to THE CURRENT Individual</b><br />';
-  $output .= '<br /><b>Current Database References</b><br />';
-  $output .= list_dbreferences_for_node($node->db_references);
-  $output .= '<br /><br />';
-  $output .= drupal_get_form('tripal_feature_add_ONE_dbreference_form', $node);
-  $output .= '<br />';
-  $output .= drupal_get_form('tripal_feature_implement_add_chado_properties_navigate', 'db_references', $node->nid);
-  return $output;
-}
-
-/**
- * Implements Hook_form()
- * Handles adding of Database References to features
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_add_ONE_dbreference_form($form_state, $node) {
-
-  $form['nid'] = array(
-    '#type' => 'hidden',
-    '#value' => $node->nid
-  );
-
-  $form['feature_id'] = array(
-    '#type' => 'hidden',
-    '#value' => $node->feature->feature_id,
-  );
-
-  $form['add_dbreference'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Add Database References') . '<span class="form-optional" title="This field is optional">(optional)</span>',
-  );
-
-  $form['add_dbreference']['accession'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Accession'),
-    '#required' => TRUE,
-  );
-
-  $form['add_dbreference']['description'] = array(
-    '#type' => 'textarea',
-    '#title' => t('Description of Reference') . '<span class="form-optional" title="This field is optional">+</span>',
-    '#description' => t('Optionally enter a description about the database accession.'),
-  );
-
-  $db_options = tripal_db_get_db_options();
-  $db_options[0] = 'Select a Database';
-  ksort($db_options);
-  $form['add_dbreference']['db_id'] = array(
-    '#type' => 'select',
-    '#title' => t('Database'),
-    '#options' => $db_options,
-    '#required' => TRUE,
-  );
-
-  $form['add_dbreference']['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Add Database Reference')
-  );
-
-  return $form;
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_add_ONE_dbreference_form_validate($form, &$form_state) {
-
-  $db_id = $form_state['values']['db_id'];
-  $accession = $form_state['values']['accession'];
-  $description = $form_state['values']['description'];
-  $feature_id = $form_state['values']['feature_id'];
-  $nid = $form_state['values']['nid'];
-
-  // Check database is valid db_id in chado
-  $tmp_obj = db_fetch_object(chado_query("SELECT count(*) as count FROM {db} WHERE db_id=%d", $db_id));
-  if ($tmp_obj->count != 1) {
-    form_set_error('database', 'The database you selected is not valid. Please choose another one.');
-  }
-
-  // Check Accession is unique for database
-  $sql = "SELECT count(*) as count FROM {dbxref} WHERE accession='%s' and db_id = %d";
-  $tmp_obj = db_fetch_object(chado_query($sql, $accession, $db_id));
-
-  if ($tmp_obj->count > 0) {
-    form_set_error('accession', 'This accession has already been assigned to another feature in the selected database.');
-  }
-
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_add_ONE_dbreference_form_submit($form, &$form_state) {
-
-  $db_id = $form_state['values']['db_id'];
-  $accession = $form_state['values']['accession'];
-  $description = $form_state['values']['description'];
-  $feature_id = $form_state['values']['feature_id'];
-  $nid = $form_state['values']['nid'];
-
-  // create dbxref
-  $isql =  "INSERT INTO {dbxref} (db_id, accession, description) VALUES (%d, '%s', '%s')";
-  chado_query($isql, $db_id, $accession, $description);
-
-  //create feature_dbxref
-  $dbxref = tripal_db_get_dbxref( array('db_id' => array('type' => 'INT', 'value' => $form_state['values']['db_id']),
-                     'accession' => array('type' => 'STRING', 'exact' => TRUE, 'value' => $form_state['values']['accession']) ) );
-
-  if (!empty($dbxref->dbxref_id)) {
-      $isql = "INSERT INTO {feature_dbxref} (feature_id, dbxref_id) VALUES (%d, %d)";
-      chado_query($isql, $feature_id, $dbxref->dbxref_id);
-      drupal_set_message(t('Successfully Added Database Reference'));
-      drupal_goto('node/' . $nid);
-  }
-  else {
-    drupal_set_message(t('Database reference NOT successfully created...'), 'error');
-  } //end of if dbxref was created successfully
-
-}
-
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_edit_ALL_dbreferences_page($node) {
-  $output = '';
-
-  $output .= drupal_get_form('tripal_feature_edit_ALL_db_references_form', $node);
-  $output .= '<br />';
-  $output .= drupal_get_form('tripal_feature_add_ONE_dbreference_form', $node);
-  $output .= '<br />';
-  $output .= drupal_get_form('tripal_feature_implement_back_to_feature_button', $node->nid);
-
-  return $output;
-}
-
-/**
- * Implements Hook_form()
- * Handles adding of DB References to Features
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_edit_ALL_db_references_form($form_state, $node) {
-  $form = array();
-
-  $form['nid'] = array(
-    '#type' => 'hidden',
-    '#value' => $node->nid
-  );
-
-  $i=0;
-
-  $feature = $node->feature;
-  $references = tripal_feature_load_references($feature->feature_id);
-
-  // pre populate the database options
-  $db_options = tripal_db_get_db_options();
-  $db_options[0] = 'Select a Database';
-  ksort($db_options);
-
-  if (sizeof($references) != 0) {
-    foreach ($references as $ref) {
-      $i++;
-      $form["num-$i"] = array(
-        '#type' => 'fieldset',
-        '#title' => t("Database Reference") . " $i"
-      );
-
-      $form["num-$i"]["accession-$i"] = array(
-        '#type' => 'textfield',
-        '#title' => t('Accession'),
-        '#size' => 30,
-        '#required' => TRUE,
-        '#default_value' => $ref->accession
-      );
-
-      $form["num-$i"]["db_id-$i"] = array(
-        '#type' => 'select',
-        '#title' => t('Database'),
-        '#options' => $db_options,
-        '#required' => TRUE,
-        '#default_value' => $ref->db_id
-      );
-
-
-      $form["num-$i"]["dbxref_id-$i"] = array(
-        '#type' => 'hidden',
-        '#value' => $ref->dbxref_id
-      );
-
-      $form["num-$i"]["delete-$i"] = array(
-        '#type' => 'submit',
-        '#value' => t("Delete"),
-        '#name' => "delete-$i",
-      );
-
-      }
-
-      $form['num_db_references'] = array(
-        '#type' => 'hidden',
-        '#value' => $i
-      );
-
-      $form["submit-edits"] = array(
-        '#type' => 'submit',
-        '#value' => t('Update All References')
-      );
-  } //end of foreach db ref
-  return $form;
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_edit_ALL_db_references_form_submit($form, &$form_state) {
-
-  $num_refs = $form_state['values']['num_db_references'];
-  $action = $form_state['clicked_button']['#value'];
-  $button = $form_state['clicked_button']['#name'];
-  $nid = $form_state['values']['nid'];
-
-  if (strcmp($action, 'Update All References')==0) {
-    for ($i=1; $i<=$num_refs; $i++) {
-    $dbxref_id = $form_state['values']["dbxref_id-$i"];
-    $db_id = $form_state['values']["db_id-$i"];
-    $accession = $form_state['values']["accession-$i"];
-      tripal_feature_update_db_reference($dbxref_id, $db_id, $accession);
-    }
-    drupal_set_message(t("Updated all Database References"));
-    drupal_goto('node/' . $nid);
-  }
-  elseif (strcmp($action, 'Delete')==0) {
-    if (preg_match('/delete-(\d+)/', $button, $matches) ) {
-      $i = $matches[1];
-      $dbxref_id = $form_state['values']["dbxref_id-$i"];
-      tripal_feature_delete_db_reference($dbxref_id);
-      drupal_set_message(t("Deleted Database Reference"));
-      drupal_goto('node/' . $nid);
-    }
-    else {
-      drupal_set_message(t("Could not remove database reference:"), 'error');
-    }
-    }
-  else {
-    drupal_set_message(t("Unrecognized Button Pressed"), 'error');
-  }
-
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_update_db_reference($dbxref_id, $db_id, $accession) {
-
-  $sql =  "UPDATE {dbxref} SET db_id=%d, accession='%s' WHERE dbxref_id=%d";
-  chado_query($sql, $db_id, $accession, $dbxref_id);
-
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_delete_db_reference($dbxref_id) {
-
-  chado_query(
-    "DELETE FROM {dbxref} WHERE dbxref_id=%d",
-    $dbxref_id
-  );
-
-  chado_query(
-    "DELETE FROM {feature_dbxref} WHERE dbxref_id=%d",
-    $dbxref_id
-  );
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function theme_tripal_feature_edit_ALL_db_references_form($form) {
-  $output = '';
-
-  $output .= '<br /><fieldset>';
-  $output .= '<legend>Edit Existing Database References<span class="form-optional" title="This field is optional">(optional)</span></legend>';
-  $output .= '<p>Below is a list of already existing database references, one per line. When entering a database reference, the accession ' .
-             'is a unique identifier for this feature in the specified database.</p>';
-  $output .= '<table>';
-  $output .= '<tr><th>#</th><th>Database</th><th>Accession</th><th></th></tr>';
-
-  for ($i=1; $i<=$form['num_db_references']['#value']; $i++) {
-    $output .= '<tr><td>' . drupal_render($form["num-$i"]) . '</td><td>'
-             . drupal_render($form["database-$i"]) . '</td><td>'
-         . drupal_render($form["accession-$i"]) . '</td><td>'
-         . drupal_render($form["submit-$i"]) . '</td></tr>';
-  }
-
-  $output .= '</table><br />';
-  $output .= drupal_render($form);
-  $output .= '</fieldset>';
-
-  return $output;
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function list_dbreferences_for_node($db_references) {
-
-  if (!empty($db_references) ) {
-    $output = '<table>';
-    $output .= '<tr><th>Database</th><th>Accession</th></tr>';
-
-    foreach ($db_references as $db) {
-        $output .= '<tr><td>' . $db->db_name . '</td><td>' . $db->accession . '</td></tr>';
-    } // end of foreach db reference
-
-    $output .= '</table>';
-
-  }
-  else {
-    $output = 'No Database References Added to the Current Feature';
-  }
-
-  return $output;
-}

+ 13 - 9
tripal_feature/includes/tripal_feature-delete.inc

@@ -10,7 +10,7 @@ function tripal_feature_delete_form() {
   $org_rset = chado_query($sql);
   $organisms = array();
   $organisms[''] = '';
-  while ($organism = db_fetch_object($org_rset)) {
+  while ($organism = $org_rset->fetchObject()) {
     $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
   }
   $form['desc'] = array(
@@ -50,7 +50,7 @@ function tripal_feature_delete_form() {
   $org_rset = chado_query($sql);
   $analyses = array();
   $analyses[''] = '';
-  while ($analysis = db_fetch_object($org_rset)) {
+  while ($analysis = $org_rset->fetchObject()) {
     $analyses[$analysis->analysis_id] = "$analysis->name ($analysis->program $analysis->programversion, $analysis->sourcename)";
   }
   //  TODO: ADD THIS BACK IN LATER
@@ -82,14 +82,18 @@ function tripal_feature_delete_form_validate($form, &$form_state) {
 
   // check to make sure the types exists
   if ($seq_type) {
-    $cvtermsql = "SELECT CVT.cvterm_id
-                  FROM {cvterm} CVT
-                     INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
-                     LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
-                  WHERE cv.name = '%s' and (CVT.name = '%s' or CVTS.synonym = '%s')";
-    $cvterm = db_fetch_object(chado_query($cvtermsql, 'sequence', $seq_type, $seq_type));
+    $cvtermsql = "
+      SELECT CVT.cvterm_id
+      FROM {cvterm} CVT
+        INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
+        LEFT JOIN {cvtermsynonym} CVTS on CVTS.cvterm_id = CVT.cvterm_id
+      WHERE cv.name = :cvname and (CVT.name = :name or CVTS.synonym = :synonym)
+    ";
+    $cvterm = chado_query($cvtermsql, 
+      array(':cvname' => 'sequence', ':name' => $seq_type, ':synonym' => $seq_type))->fetchObject();
     if (!$cvterm) {
-      form_set_error('seq_type', t("The Sequence Ontology (SO) term selected for the sequence type is not available in the database. Please check spelling or select another."));
+      form_set_error('seq_type', t("The Sequence Ontology (SO) term selected for the " .
+      "sequence type is not available in the database. Please check spelling or select another."));
     }
   }
 }

+ 0 - 327
tripal_feature/includes/tripal_feature-properties.inc

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

+ 0 - 553
tripal_feature/includes/tripal_feature-relationships.inc

@@ -1,553 +0,0 @@
-<?php
-/**
- * @file
- * @todo Add file header description
- */
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_add_ALL_relationships_page($node) {
-  $output = '';
-
-  $output .= tripal_feature_implement_add_chado_properties_progress('relationships') . '<br />';
-  $output .= '<b>All Relationships should include the CURRENT Individual (' . $node->uniquename . ')</b><br />';
-  $output .= '<br /><b>Current Relationships</b><br />';
-  $output .= list_relationships_for_node($node->uniquename, $node->subject_relationships, $node->object_relationships);
-  $output .= '<br /><br />';
-  $output .= drupal_get_form('tripal_feature_add_ONE_relationship_form', $node);
-  $output .= '<br />';
-  $output .= drupal_get_form('tripal_feature_implement_add_chado_properties_navigate', 'relationships', $node->nid);
-  return $output;
-}
-
-/**
- * Implements Hook_form()
- * Handles adding of Relationships to Features
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_add_ONE_relationship_form($form_state, $node) {
-
-  $feature_id = $node->feature_id;
-  $organism_id = $node->organism->organism_id;
-  $_SESSION['organism'] = $organism_id; //needed for autocomplete enter feature to work
-
-  $form['rel_nid'] = array(
-    '#type' => 'hidden',
-    '#value' => $node->nid
-  );
-
-  $form['add_relationships'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Add Relationships') . '<span class="form-optional" title="This field is optional">(optional)</span>',
-  );
-
-  $form['add_relationships']['description'] = array(
-    '#type' => 'item',
-    '#value' => t('Relationships are specified as follows: (Subject) (Type of Relationship) (Object). For example, X part_of Y, where X & Y are genomic features.')
-  );
-
-  $form['add_relationships']['subject_id'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Subject'),
-    '#description' => 'The Uniquename, Name, Database Reference or Synonym of a Feature can be used here',
-  );
-
-  $cv = tripal_cv_get_cv_by_name('relationship');
-  $type_options = tripal_cv_get_cvterm_options($cv->cv_id);
-  $type_options[0] = 'Select a Type';
-  ksort($type_options);
-  $form['add_relationships']['type_id'] = array(
-    '#type' => 'select',
-    '#title' => t('Type of Relationship'),
-    '#options' => $type_options
-
-  );
-
-  $form['add_relationships']['object_id'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Object'),
-    '#description' => 'The Uniquename, Name, Database Reference or Synonym of a Feature can be used here',
-  );
-
-  $form['add_relationships']['r_description'] = array(
-    '#type' => 'textarea',
-    '#title' => t('Notes on the relationship') . '<span class="form-optional" title="This field is optional">+</span>',
-    '#description' => t('Should not include Genotypes and Phenotypes'),
-  );
-
-  $form['add_relationships']['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Add a Relationship')
-  );
-
-  $form['add_relationships']['r_feature_id'] = array(
-    '#type' => 'value',
-    '#value' => $feature_id,
-    '#required' => TRUE
-
-  );
-
-  $form['add_relationships']['r_feature_uniquename'] = array(
-    '#type' => 'value',
-    '#value' => $node->uniquename,
-    '#required' => TRUE
-  );
-
-  return $form;
-
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_add_ONE_relationship_form_validate($form, &$form_state) {
-
-  //Require Validation if adding
-  if ($form_state['clicked_button']['#value'] == t('Add a Relationship') ) {
-
-    // check valid feature selected for subject
-    $criteria = array('unknown' => array('value' => $form_state['values']['subject_id'],
-                                          'columns' => array('name', 'uniquename', 'accession', 'synonym') ));
-    $subject_results = get_chado_stocks($criteria, 'ANY', $_SESSION['organism']);
-    if (sizeof($subject_results) > 1) {
-      $links= array();
-      for ($i=0; $i<sizeof($subject_results); $i++) {
-      $links[] = l($i+1, "node/" . $subject_results[$i]->nid); }
-      $message = t("Too many features match '%object'! Please refine your input to match
-        ONLY ONE feature. <br />To aid in this process, here are the features that
-        match your initial input: %features",
-        array('%object' => $form_state['values']['subject_id'],
-          '%features' => join(', ', $links)
-        )
-      );
-      form_set_error('subject_id', $message);
-    }
-    elseif (sizeof($subject_results) < 1) {
-      form_set_error('subject_id', t("There are no features matching your input. Please check your input for typos and/or lookup the feature <a href='!url'>here</a>", array('!url' => url('features'))));
-    }
-    elseif (sizeof($subject_results) == 1) {
-      $form_state['values']['subject_id'] = $subject_results[0]->stock_id;
-    }
-
-    // check valid stock selected for object
-    $criteria = array('unknown' => array('value' => $form_state['values']['object_id'],
-                                          'columns' => array('name', 'uniquename', 'accession', 'synonym') ));
-    $object_results = get_chado_stocks($criteria, 'ANY', $_SESSION['organism']);
-    if (sizeof($object_results) > 1) {
-      $links= array();
-      for ($i=0; $i<sizeof($object_results); $i++) {
-      $links[] = l($i+1, "node/" . $object_results[$i]->nid); }
-      $message = t("Too many features match '%object'! Please refine your input to match
-        ONLY ONE stock. <br />To aid in this process, here are the stocks that match
-        your initial input: %features",
-        array('%object' => $form_state['values']['object_id'],
-        '%features' => join(', ', $links)
-        )
-      );
-      form_set_error('object_id', $message);
-    }
-    elseif (sizeof($object_results) < 1) {
-      form_set_error('object_id', t("There are no features matching your input. Please check your input for typos and/or lookup the feature <a href='!url'>here</a>", array('!url' => url('features'))));
-    }
-    elseif (sizeof($object_results) == 1) {
-      $form_state['values']['object_id'] = $object_results[0]->stock_id;
-    }
-
-    // check valid type selected
-    if ($form_state['values']['type_id'] == 0) {
-      form_set_error('type_id', 'Please select a type of relationship.');
-    }
-    else {
-      $tmp_obj = db_fetch_object(chado_query("SELECT count(*) as count FROM {cvterm} WHERE cvterm_id=%d", $form_state['values']['type_id']));
-
-      if ($tmp_obj->count != 1) {
-        form_set_error('type_id', 'The type you selected is not valid. Please choose another one.');
-      }
-    }
-
-    // check either subject or object is the current stock
-    if ( $subject_results[0]->nid != $form_state['values']['rel_nid'] ) {
-      if ( $object_results[0]->nid != $form_state['values']['rel_nid'] ) {
-        form_set_error('subject_id', 'Either Subject or Object must be the current stock (' . $form_state['values']['r_stock_uniquename'] . ').');
-      }
-    }
-  } //end of require validation if adding relationship
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_add_ONE_relationship_form_submit($form, &$form_state) {
-
-  if ($form_state['values']['subject_id'] > 0) {
-    chado_query(
-      "INSERT INTO {stock_relationship} (subject_id, type_id, object_id, value) VALUES (%d, %d, %d, '%s')",
-      $form_state['values']['subject_id'],
-      $form_state['values']['type_id'],
-      $form_state['values']['object_id'],
-      $form_state['values']['r_description']
-    );
-
-    drupal_set_message(t('Successfully Added Relationship.'));
-  } //end of insert relationship
-
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_edit_ALL_relationships_page($node) {
-  $output = '';
-
-  $output .= drupal_get_form('tripal_feature_edit_ALL_relationships_form', $node);
-  $output .= '<br />';
-  $output .= drupal_get_form('tripal_feature_add_ONE_relationship_form', $node);
-  $output .= '<br />';
-  $output .= drupal_get_form('tripal_feature_implement_back_to_feature_button', $node->nid);
-
-  return $output;
-}
-
-/**
- * Implements Hook_form()
- * Handles adding of Properties & Synonyms to Stocks
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_edit_ALL_relationships_form($form_state, $node) {
-  $form = array();
-
-  $form['nid'] = array(
-    '#type' => 'hidden',
-    '#value' => $node->nid
-  );
-
-  $form['r_feature_uniquename'] = array(
-    '#type' => 'hidden',
-    '#value' => $node->uniquename
-  );
-
-  $i=0;
-
-  $feature = $node->feature;
-  $orelationships = tripal_feature_load_relationships($feature->feature_id, 'as_object');
-  $srelationships = tripal_feature_load_relationships($feature->feature_id, 'as_subject');
-  $relationships = array_merge($orelationships, $srelationships);
-
-  if (sizeof($relationships) != 0) {
-    foreach ($relationships as $r) {
-
-      $i++;
-      $form["num-$i"] = array(
-        '#type' => 'fieldset',
-        '#title' => t("Relationship %i", array('%i' => $i)),
-      );
-
-      $form["num-$i"]["id-$i"] = array(
-        '#type' => 'hidden',
-        '#value' => $r->stock_relationship_id
-      );
-
-      //Enter relationship specific fields
-      if ( !empty($r->subject_id) ) {
-        $default = $r->subject_uniquename;
-        $description = l($r->subject_name, 'node/' . $r->subject_nid);
-      }
-      else {
-        $default = $node->uniquename;
-        $description = "Current Feature";
-      }
-      $description .= " (" . $r->subject_type . ")";
-      $form["num-$i"]["subject_id-$i"] = array(
-        '#type' => 'textfield',
-        //'#title' => t('Subject'),
-        '#required'   => TRUE,
-        '#size' => 30,
-        '#default_value' => $default,
-        '#description' => t('%description', array('%description' => $description)),
-      );
-
-      $cv = tripal_cv_get_cv_by_name('relationship');
-      $type_options = tripal_cv_get_cvterm_options($cv->cv_id);
-      ksort($type_options);
-      $form["num-$i"]["type_id-$i"] = array(
-        '#type' => 'select',
-        //'#title' => t('Type of Relationship'),
-        '#options' => $type_options,
-        '#required' => TRUE,
-        '#default_value' => $r->relationship_type_id
-      );
-
-      if (!empty($r->object_id) ) {
-        $default = $r->object_uniquename;
-        $description = l($r->object_name, 'node/' . $r->object_nid);
-      }
-      else {
-        $default = $node->uniquename;
-        $description = 'Current Feature';
-      }
-      $description .= " (" . $r->object_type . ")";
-      $form["num-$i"]["object_id-$i"] = array(
-        '#type' => 'textfield',
-        //'#title' => t('Object'),
-        '#required'   => TRUE,
-        '#size' => 30,
-        '#default_value' => $default,
-        '#description' => $description
-      );
-
-      $form["num-$i"]["delete-$i"] = array(
-        '#type' => 'submit',
-        '#value' => t("Delete"),
-        '#name' => "delete-$i",
-      );
-
-    } //end of foreach relationship
-    $form['num_relationships'] = array(
-      '#type' => 'hidden',
-      '#value' => $i
-    );
-
-    $form["submit-edits"] = array(
-      '#type' => 'submit',
-      '#value' => t('Update All Relationships')
-    );
-  }
-  else {
-    $form["info"] = array(
-      '#type' => 'markup',
-      '#value' => t('No relationships currently exist for this feature.')
-    );
-  }
-
-  return $form;
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_edit_ALL_relationships_form_validate($form, &$form_state) {
-
-  // Only Require if Updating Relationships
-  if ($form_state['clicked_button']['#value'] == t('Update All Relationships') ) {
-
-    for ($i=1; $i<=$form_state['values']['num_relationships']; $i++) {
-
-      // check valid stock selected for subject
-      $criteria = array('unknown' => array('value' => $form_state['values']["subject_id-$i"],
-                                          'columns' => array('name', 'uniquename', 'accession', 'synonym') ));
-      $subject_results = get_chado_stocks($criteria, 'ANY', $_SESSION['organism']);
-      if (sizeof($subject_results) > 1) {
-        $links= array();
-        for ($j=0; $j<sizeof($subject_results); $j++) {
-        $links[] = l($j+1, "node/" . $subject_results[$j]->nid); }
-        $message = t("Too many features match '%subject'!  Please refine your input to
-          match ONLY ONE feature. <br /> To aid in this process, here are the features that
-          match your initial input: %features",
-          array('%subject' => $form_state['values']["subject_id-$i"],
-            '%features' => join(', ', $links)
-          )
-        );
-        form_set_error("subject_id-$i", $message);
-      }
-      elseif (sizeof($subject_results) < 1) {
-        form_set_error("subject_id-$i", t("There are no features matching your input. Please check your input for typos and/or lookup the <a href='!url'>here</a>", array('!url' => url('features'))));
-      }
-      elseif (sizeof($subject_results) == 1) {
-        $form_state['values']["subject_id-$i"] = $subject_results[0]->stock_id;
-      }
-
-      // check valid stock selected for object
-      $criteria = array('unknown' => array('value' => $form_state['values']["object_id-$i"],
-                                          'columns' => array('name', 'uniquename', 'accession', 'synonym') ));
-      $object_results = get_chado_stocks($criteria, 'ANY' , $_SESSION['organism']);
-      if (sizeof($object_results) > 1) {
-        $links= array();
-        for ($j=0; $j<sizeof($object_results); $j++) {
-        $links[] = l($j+1, "node/" . $object_results[$j]->nid); }
-        $message = "Too many stocks match '" . $form_state['values']["object_id-$i"] . "'! "
-                 . "Please refine your input to match ONLY ONE stock. <br />"
-                 . "To aid in this process, here are the stocks that match your initial input: "
-                 . join(', ', $links);
-        form_set_error("object_id-$i", $message);
-      }
-      elseif (sizeof($object_results) < 1) {
-        form_set_error("object_id-$i", t("There are no features matching your input. Please check your input for typos and/or lookup the <a href='!url'>here</a>", array('!url' => url('features'))));
-      }
-      elseif (sizeof($object_results) == 1) {
-        $form_state['values']["object_id-$i"] = $object_results[0]->stock_id;
-      }
-
-      // check valid type selected
-      if ($form_state['values']["type_id-$i"] == 0) {
-        form_set_error('type_id', 'Please select a type of relationship.');
-      }
-      else {
-        $tmp_obj = db_fetch_object(chado_query("SELECT count(*) as count FROM {cvterm} WHERE cvterm_id=%d" , $form_state['values']["type_id-$i"]));
-
-        if ($tmp_obj->count != 1) {
-          form_set_error("type_id-$i", 'The type you selected is not valid. Please choose another one.');
-        }
-      }
-
-      // check either subject or object is the current stock
-      if ( $subject_results[0]->nid != $form_state['values']['nid'] ) {
-        if ( $object_results[0]->nid != $form_state['values']['nid'] ) {
-          form_set_error("subject_id-$i", 'Either Subject or Object must be the current stock (' . $form_state['values']['r_stock_uniquename'] . ').');
-        }
-      }
-
-    } // end of for each relationship
-  } //end of if updating relationships
-
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_edit_ALL_relationships_form_submit($form, &$form_state) {
-
-  if ($form_state['clicked_button']['#value'] == t('Update Relationships') ) {
-    //Update all
-    for ($i=1; $i<=$form_state['values']['num_relationships']; $i++) {
-
-      //process stock textfields
-      tripal_feature_update_relationship(
-        $form_state['values']["id-$i"],
-        $form_state['values']["subject_id-$i"],
-        $form_state['values']["type_id-$i"],
-        $form_state['values']["object_id-$i"]
-      );
-    }
-    drupal_set_message(t("Updated all Relationships"));
-    drupal_goto('node/' . $form_state['values']['nid']);
-
-  }
-  elseif ( preg_match('/Delete #(\d+)/', $form_state['clicked_button']['#value'], $matches) ) {
-
-    $i = $matches[1];
-    tripal_feature_delete_relationship($form_state['values']["id-$i"]);
-    drupal_set_message(t("Deleted Relationship"));
-
-  }
-  elseif ($form_state['clicked_button']['#value'] == t('Back to Stock') ) {
-    drupal_goto('node/' . $form_state['values']['nid']);
-  }
-  else {
-    drupal_set_message(t("Unrecognized Button Pressed"), 'error');
-  }
-
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_update_relationship($stock_relationship_id, $subject_id, $cvterm_id, $object_id) {
-
-  $previous_db = db_set_active('chado');
-  db_query(
-    "UPDATE {stock_relationship} SET subject_id=%d, type_id=%d, object_id=%d WHERE stock_relationship_id=%d",
-    $subject_id,
-    $cvterm_id,
-    $object_id,
-    $stock_relationship_id
-  );
-  db_set_active($previous_db);
-
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_delete_relationship($stock_relationship_id) {
-
-  $previous_db = db_set_active('chado');
-  db_query(
-    "DELETE FROM {stock_relationship} WHERE stock_relationship_id=%d",
-    $stock_relationship_id
-  );
-  db_set_active($previous_db);
-
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function theme_tripal_feature_edit_ALL_relationships_form($form) {
-  $output = '';
-
-  $output .= '<br /><fieldset>';
-  $output .= '<legend>Edit Already Existing Relationships<span class="form-optional" title="This field is optional">(optional)</span></legend>';
-  $output .= '<p>Each relationship for this stock is listed below, one per line. The textboxes indicating ' .
-             'the subject and object of the relationship can contain the uniquename, name, database ' .
-             'reference or synonym of a stock of the same organism.</p>';
-  $output .= '<table>';
-  $output .= '<tr><th>#</th><th>Subject</th><th>Type</th><th>Object</th><th></th></tr>';
-
-  for ($i=1; $i <= $form['num_relationships']['#value']; $i++) {
-    $output .= '<tr><td>' . drupal_render($form["num-$i"]) . '</td>' .
-              '<td>' . drupal_render($form["subject_id-$i"]) . '</td>' .
-              '<td>' . drupal_render($form["type_id-$i"]) . '</td>' .
-                '<td>' . drupal_render($form["object_id-$i"]) . '</td>' .
-              '<td>' . drupal_render($form["submit-$i"]) . '</td></tr>';
-  }
-
-  $output .= '</table><br />';
-  $output .= drupal_render($form);
-  $output .= '</fieldset>';
-
-  return $output;
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_list_relationships_for_node($feature_name, $subject_relationships, $object_relationships) {
-
-  if (!empty($subject_relationships) OR !empty($object_relationships) ) {
-    $output = '<table>';
-    $output .= '<tr><th>Subject</th><th>Relationship Type</th><th>Object</th></tr>';
-
-    if (!empty($subject_relationships) ) {
-      foreach ($subject_relationships as $s) {
-        $output .= '<tr><td>' . $s->subject_name . '</td><td>' . $s->relationship_type . '</td><td>' . $feature_name . '</td></tr>';
-      }
-    }
-
-    if (!empty($object_relationships) ) {
-      foreach ($object_relationships as $o) {
-        $output .= '<tr><td>' . $feature_name . '</td><td>' . $o->relationship_type . '</td><td>' . $o->object_name . '</td></tr>';
-      } // end of foreach property
-    }
-
-    $output .= '</table>';
-  }
-  else {
-    $output = 'No Relationships For the Current Feature';
-  }
-
-  return $output;
-
-}

+ 0 - 233
tripal_feature/includes/tripal_feature-secondary_tables.inc

@@ -1,233 +0,0 @@
-<?php
-/**
- * @file
- * @todo Add file header description
- */
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_implement_back_to_feature_button($form_state, $nid) {
-  $form = array();
-
-  $form['nid'] = array(
-    '#type' => 'hidden',
-    '#value' => $nid
-  );
-
-  $form["submit-back"] = array(
-    '#type' => 'submit',
-    '#value' => t('Back to Stock')
-  );
-
-  return $form;
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_implement_back_to_feature_button_submit($form, $form_state) {
-  drupal_goto('node/' . $form_state['values']['nid']);
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_implement_add_chado_properties_progress($current) {
-
-    $value = '<div class="form_progress"><div class="form_progress-text">';
-
-    if ($current == 'main') {
-    $value .= '<span id="form-step-current">Create Basic Feature</span>'; }
-    else { $value .= '<span id="form-step">Create Basic Stock</span>'; }
-
-    $value .= '<span id="form-segway">  >>  </span>';
-
-    if ($current == 'properties') {
-    $value .= '<span id="form-step-current">Add Synonyms & Properties</span>'; }
-    else { $value .= '<span id="form-step">Add Synonyms & Properties</span>'; }
-
-    $value .= '<span id="form-segway">  >>  </span>';
-
-    if ($current == 'db_references') {
-    $value .= '<span id="form-step-current">Add Database References</span>'; }
-    else { $value .= '<span id="form-step">Add Database References</span>'; }
-
-    $value .= '<span id="form-segway">  >>  </span>';
-
-    if ($current == 'relationships') {
-    $value .= '<span id="form-step-current">Add Relationships</span>'; }
-    else { $value .= '<span id="form-step">Add Relationships</span>'; }
-
-    $value .= '</div></div>';
-
-    return $value;
-
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_implement_add_chado_properties_navigate($form_state, $step, $nid) {
-  $form = array();
-
-  $form['current_step'] = array(
-    '#type' => 'hidden',
-    '#value' => $step
-  );
-
-  // Use this field to set all the steps and the path to each form
-  // where each step is of the form name;path and each step is separated by ::
-  $steps =array(
-    'properties' => 'node/%node/properties',
-    'db_references' => 'node/%node/db_references',
-    'relationships' => 'node/%node/relationships'
-  );
-  $steps_value = array();
-  foreach ($steps as $k => $v) {
-  $steps_value[] = $k . ';' . $v; }
-  $form['steps'] = array(
-    '#type' => 'hidden',
-    '#value' => implode('::', $steps_value)
-  );
-
-  $form['first_step'] = array(
-    '#type' => 'hidden',
-    '#value' => 'properties'
-  );
-
-  $form['last_step'] = array(
-    '#type' => 'hidden',
-    '#value' => 'relationships'
-  );
-
-  $form['nid'] = array(
-    '#type' => 'hidden',
-    '#value' => $nid
-  );
-
-  if ($step != $form['first_step']['#value']) {
-    $form['submit-prev'] = array(
-      '#type' => 'submit',
-      '#value' => t('Previous Step')
-    );
-  }
-
-  if ($step != $form['last_step']['#value']) {
-    $form['submit-next'] = array(
-      '#type' => 'submit',
-      '#value' => t('Next Step')
-    );
-  }
-
-  if ($step == $form['last_step']['#value']) {
-    $form['submit-finish'] = array(
-      '#type' => 'submit',
-      '#value' => t('Finish')
-    );
-  }
-
-  return $form;
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_implement_add_chado_properties_navigate_submit($form, $form_state) {
-
-  $raw_steps = preg_split('/::/', $form_state['values']['steps']);
-
-  $steps = array();
-  $current_index = 'EMPTY';
-  $i=0;
-
-  foreach ($raw_steps as $raw_step) {
-    $step = preg_split('/;/', $raw_step);
-    $steps[$i] = $step;
-
-    if ($step[0] == $form_state['values']['current_step']) {
-      $current_index = $i;
-    }
-
-    $i++;
-  }
-  $num_steps = $i;
-
-  if (strcmp($current_index, 'EMPTY') == 0) {
-    // No Matching Step
-    drupal_set_message(t('Could not determine next step - %currentstep, please contact the administrator', array('%currentstep' => $form_state['values']['current_step'])), 'error');
-  }
-  elseif ($current_index == 0) {
-    $next_goto = $steps[$current_index+1][1];
-  }
-  elseif ($current_index == ($num_steps-1)) {
-    $prev_goto = $steps[$current_index-1][1];
-    $next_goto = 'node/%node';
-  }
-  else {
-    $prev_goto = $steps[$current_index-1][1];
-    $next_goto = $steps[$current_index+1][1];
-  }
-
-  if ($form_state['clicked_button']['#value'] == t('Previous Step') ) {
-    //replace %node
-    $prev_goto = preg_replace('/%node/', $form_state['values']['nid'], $prev_goto);
-    $_REQUEST['destination'] = $prev_goto;
-  }
-  elseif ($form_state['clicked_button']['#value'] == t('Next Step') ) {
-    $next_goto = preg_replace('/%node/', $form_state['values']['nid'], $next_goto);
-    $_REQUEST['destination'] = $next_goto;
-  }
-  elseif ($form_state['clicked_button']['#value'] == t('Finish') ) {
-    $next_goto = preg_replace('/%node/', $form_state['values']['nid'], $next_goto);
-    $_REQUEST['destination'] = $next_goto;
-  }
-
-}
-
-/**
- * Implements Hook_form()
- * Handles setting the is_obsolete property of stocks
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_is_obsolete_form($node, $stock_id) {
-
-  $form['make_obsolete'] = array(
-    '#type' => 'submit',
-    '#value' => t('Mark Stock as Obsolete')
-  );
-
-  $form['make_obsolete_stock_id'] = array(
-    '#type' => 'value',
-    '#value' => $stock_id,
-    '#required' => TRUE
-  );
-
-  return $form;
-}
-
-/**
- *
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_is_obsolete_form_submit($form, &$form_state) {
-
-  chado_query(
-    "UPDATE {stock} SET is_obsolete='t' WHERE stock_id=%d",
-    $form_state['values']['make_obsolete_stock_id']
-  );
-
-}
-

+ 29 - 21
tripal_feature/includes/tripal_feature.admin.inc

@@ -420,14 +420,16 @@ function tripal_features_set_taxonomy($max_sync = 0, $job_id = NULL) {
 
   // iterate through all drupal feature nodes and set the taxonomy
   $results = db_query("SELECT * FROM {chado_feature}");
-  $nsql =  "SELECT * FROM {node} " .
-          "WHERE nid = %d";
+  $nsql =  "
+    SELECT * FROM {node} 
+    WHERE nid = :nid
+  ";
   $i = 0;
 
   // load into ids array
   $count = 0;
   $chado_features = array();
-  while ($chado_feature = db_fetch_object($results)) {
+  while ($chado_feature = $results->fetchObject()) {
     $chado_features[$count] = $chado_feature;
     $count++;
   }
@@ -441,7 +443,7 @@ function tripal_features_set_taxonomy($max_sync = 0, $job_id = NULL) {
     tripal_job_set_progress($job_id, intval(($i/$count)*100));
   }
   print "$i of $count: ";
-  $node = db_fetch_object(db_query($nsql, $chado_feature->nid));
+  $node = db_query($nsql, array(':nid' => $chado_feature->nid))->fetchObject();
   tripal_feature_set_taxonomy($node, $chado_feature->feature_id);
 
   $i++;
@@ -500,12 +502,14 @@ function tripal_feature_set_taxonomy($node, $feature_id) {
   }
 
   // get the cvterm and the organism for this feature
-  $sql = "SELECT CVT.name AS cvname, O.genus, O.species " .
-        "FROM {CVTerm} CVT " .
-        "  INNER JOIN {Feature} F on F.type_id = CVT.cvterm_id " .
-        "  INNER JOIN {Organism} O ON F.organism_id = O.organism_id " .
-        "WHERE F.feature_id = $feature_id";
-  $feature = db_fetch_object(chado_query($sql));
+  $sql = "
+    SELECT CVT.name AS cvname, O.genus, O.species 
+    FROM {CVTerm} CVT 
+      INNER JOIN {Feature} F on F.type_id = CVT.cvterm_id 
+      INNER JOIN {Organism} O ON F.organism_id = O.organism_id 
+    WHERE F.feature_id = :feature_id 
+  ";
+  $feature = chado_query($sql, array(':feature_id' => $feature_id))->fetchObject();
 
   // Set the feature type for this feature
   if ($do_ft && $ft_vid) {
@@ -518,11 +522,13 @@ function tripal_feature_set_taxonomy($node, $feature_id) {
 
   // get the library that this feature may belong to and add it as taxonomy
   if ($do_lb && $lb_vid) {
-    $sql = "SELECT L.name " .
-           "FROM {Library} L " .
-           "  INNER JOIN {Library_feature} LF ON LF.library_id = L.library_id " .
-           "WHERE LF.feature_id = %d ";
-    $library = db_fetch_object(chado_query($sql, $feature_id));
+    $sql = "
+      SELECT L.name 
+      FROM {Library} L 
+        INNER JOIN {Library_feature} LF ON LF.library_id = L.library_id 
+      WHERE LF.feature_id = :feature_id 
+    ";
+    $library = chado_query($sql, array(':feature_id' => $feature_id))->fetchObject();
     $tags["$lb_vid"] = "$library->name";
   }
 
@@ -534,13 +540,15 @@ function tripal_feature_set_taxonomy($node, $feature_id) {
   // get the analysis that this feature may belong to and add it as taxonomy
   // We'll add each one individually since there may be more than one analysis
   if ($do_an && $an_vid) {
-    $sql = "SELECT A.name " .
-           "FROM {Analysis} A " .
-           "  INNER JOIN {Analysisfeature} AF ON AF.analysis_id = A.analysis_id " .
-           "WHERE AF.feature_id = $feature_id ";
-    $results = chado_query($sql);
+    $sql = "
+      SELECT A.name 
+      FROM {Analysis} A 
+        INNER JOIN {analysisfeature} AF ON AF.analysis_id = A.analysis_id 
+      WHERE AF.feature_id = :feature_id 
+    ";
+    $results = chado_query($sql, array(':feature_id' => $feature_id));
     $analysis_terms = array();
-    while ($analysis=db_fetch_object($results)) {
+    while ($analysis = $results->fetchObject()) {
       $tags2["$an_vid"] = "$analysis->name";
       $terms['tags'] = $tags2;
       taxonomy_node_save($node, $terms);

+ 44 - 42
tripal_feature/includes/tripal_feature.sync_features.inc

@@ -164,7 +164,7 @@ function tripal_feature_set_urls($na = NULL, $job = NULL) {
   // get the list of features that have been synced
   $sql = "SELECT * FROM {chado_feature}";
   $nodes = db_query($sql);  
-  while ($node = db_fetch_object($nodes)) {
+  while ($node = $nodes->fetchObject()) {
    
     // get the URL alias
     $src = "node/$node->nid";
@@ -183,7 +183,7 @@ function tripal_feature_set_urls($na = NULL, $job = NULL) {
     }
     
     // remove any previous alias and then add the new one
-    $success = db_query("EXECUTE del_url_alias_by_src('%s')", $src);    
+    $success = db_query("EXECUTE del_url_alias_by_src(:src)", array(':src' => $src));    
     if (!$success) {
       db_query('DEALLOCATE "del_url_alias_by_src"');
       db_query('DEALLOCATE "ins_url_alias_nisrds"');
@@ -191,7 +191,7 @@ function tripal_feature_set_urls($na = NULL, $job = NULL) {
       watchdog('trp-seturl', "Failed Removing URL Alias: %src", array('%src' => $src), WATCHDOG_ERROR);
       return;
     }
-    $success = db_query("EXECUTE ins_url_alias_nisrds('%s', '%s')", $src, $dst);
+    $success = db_query("EXECUTE ins_url_alias_nisrds(:src, :dst)", array(':src' => $src, ':dst' => $dst));
     if (!$success) {
       db_query('DEALLOCATE "del_url_alias_by_src"');
       db_query('DEALLOCATE "ins_url_alias_nisrds"');
@@ -315,6 +315,7 @@ function tripal_feature_sync_features($max_sync = 0, $organism_id = NULL,
 
   print "Looking for features of type: $allowed_types\n";
 
+  # TODO: fix the hard-coding of variables in this SQL statement
   $so_terms = split(' ', $allowed_types);
   $where_cvt = "";
   foreach ($so_terms as $term) {
@@ -341,12 +342,13 @@ function tripal_feature_sync_features($max_sync = 0, $organism_id = NULL,
   $where_org = drupal_substr($where_org, 0, drupal_strlen($where_org)-3);  # strip trailing 'OR'
 
   // use this SQL statement to get the features that we're going to upload
-  $sql = "SELECT feature_id " .
-        "FROM {FEATURE} F " .
-        "  INNER JOIN {Cvterm} CVT ON F.type_id = CVT.cvterm_id " .
-        "  INNER JOIN {CV} on CV.cv_id = CVT.cv_id " .
-        "WHERE ($where_cvt) AND ($where_org) AND CV.name = 'sequence' " .
-        "ORDER BY feature_id";
+  $sql = "
+    SELECT feature_id 
+    FROM {FEATURE} F 
+      INNER JOIN {Cvterm} CVT ON F.type_id = CVT.cvterm_id 
+      INNER JOIN {CV} on CV.cv_id = CVT.cv_id 
+    WHERE ($where_cvt) AND ($where_org) AND CV.name = 'sequence' 
+    ORDER BY feature_id";
 
   // get the list of features
   $results = chado_query($sql);
@@ -354,7 +356,7 @@ function tripal_feature_sync_features($max_sync = 0, $organism_id = NULL,
   // load into ids array
   $count = 0;
   $ids = array();
-  while ($id = db_fetch_object($results)) {
+  while ($id = $results->fetchObject()) {
     $ids[$count] = $id->feature_id;
     $count++;
   }
@@ -365,7 +367,7 @@ function tripal_feature_sync_features($max_sync = 0, $organism_id = NULL,
   // pre-create the SQL statement that will be used to check
   // if a feature has already been synced.  We skip features
   // that have been synced
-  $sql = "SELECT * FROM {chado_feature} WHERE feature_id = %d";
+  $sql = "SELECT * FROM {chado_feature} WHERE feature_id = :feature_id";
 
   // Iterate through features that need to be synced
   $interval = intval($count * 0.01);
@@ -384,7 +386,7 @@ function tripal_feature_sync_features($max_sync = 0, $organism_id = NULL,
     if ($max_sync and $i == $max_sync) {
       return '';
     }
-    if (!db_fetch_object(db_query($sql, $feature_id))) {
+    if (!db_query($sql, array(':feature_id' => $feature_id))->fetchObject()) {
 
       # parsing all the features can cause memory overruns
       # we are not sure why PHP does not clean up the memory as it goes
@@ -422,24 +424,28 @@ function tripal_feature_sync_feature($feature_id) {
   }
 
   // get information about this feature
-  $fsql = "SELECT F.feature_id, F.name, F.uniquename,O.genus, " .
-         "    O.species,CVT.name as cvname,F.residues,F.organism_id " .
-         "FROM {FEATURE} F " .
-         "  INNER JOIN {Cvterm} CVT ON F.type_id = CVT.cvterm_id " .
-         "  INNER JOIN {Organism} O ON F.organism_id = O.organism_ID " .
-         "WHERE F.feature_id = %d";
-  $feature = db_fetch_object(chado_query($fsql, $feature_id));
+  $fsql = "
+    SELECT F.feature_id, F.name, F.uniquename,O.genus, 
+      O.species,CVT.name as cvname,F.residues,F.organism_id 
+    FROM {FEATURE} F 
+      INNER JOIN {Cvterm} CVT ON F.type_id = CVT.cvterm_id 
+      INNER JOIN {Organism} O ON F.organism_id = O.organism_ID 
+    WHERE F.feature_id = :feature_id
+  ";
+  $feature = chado_query($fsql, array(':feature_id' => $feature_id))->fetchObject();
 
   // get the synonyms for this feature
-  $synsql = "SELECT S.name " .
-            "FROM {feature_synonym} FS " .
-            "  INNER JOIN {synonym} S on FS.synonym_id = S.synonym_id " .
-            "WHERE FS.feature_id = %d";
-  $synonyms = chado_query($synsql, $feature_id);
+  $synsql = "
+    SELECT S.name 
+    FROM {feature_synonym} FS 
+      INNER JOIN {synonym} S on FS.synonym_id = S.synonym_id 
+    WHERE FS.feature_id = :feature_id
+  ";
+  $synonyms = chado_query($synsql, array(':feature_id' => $feature_id));
 
   // now add these synonyms to the feature object as a single string
   $synstring = '';
-  while ($synonym = db_fetch_object($synonyms)) {
+  while ($synonym = $synonyms->fetchObject()) {
     $synstring .= "$synonym->name\n";
   }
   $feature->synonyms = $synstring;
@@ -448,14 +454,12 @@ function tripal_feature_sync_feature($feature_id) {
   // but without a corresponding entry in the chado_feature table if so then we want to
   // clean up that node.  (If a node is found we don't know if it belongs to our feature or
   // not since features can have the same name/title.)
-  $tsql =  "SELECT * FROM {node} N " .
-           "WHERE title = '%s'";
-  $cnsql = "SELECT * FROM {chado_feature} " .
-           "WHERE nid = %d";
-  $nodes = db_query($tsql, $feature->name);
+  $tsql =  "SELECT * FROM {node} N WHERE title = :title";
+  $cnsql = "SELECT * FROM {chado_feature} WHERE nid = :nid";
+  $nodes = db_query($tsql, array(':title' => $feature->name));
   // cycle through all nodes that may have this title
-  while ($node = db_fetch_object($nodes)) {
-    $feature_nid = db_fetch_object(db_query($cnsql, $node->nid));
+  while ($node = $nodes->fetchObject()) {
+    $feature_nid = db_query($cnsql, array(':nid' => $node->nid))->fetchObject();
     if (!$feature_nid) {
       drupal_set_message(t("%feature_id: A node is present but the chado_feature entry is missing... correcting", array('%feature_id' => $feature_id)));
       node_delete($node->nid);
@@ -464,21 +468,19 @@ function tripal_feature_sync_feature($feature_id) {
 
   // check if this feature already exists in the chado_feature table.
   // if we have a chado feature, we want to check to see if we have a node
-  $cfsql = "SELECT * FROM {chado_feature} " .
-           "WHERE feature_id = %d";
+  $cfsql = "SELECT * FROM {chado_feature} WHERE feature_id = :feature_id";
   // @coder-ignore: don't need to use db_rewrite_sql() since need all nodes regardless of access control
-  $nsql =  "SELECT * FROM {node} N " .
-           "WHERE nid = %d";
-  $chado_feature = db_fetch_object(db_query($cfsql, $feature->feature_id));
+  $nsql =  "SELECT * FROM {node} N WHERE nid = :nid";
+  $chado_feature = db_query($cfsql, array(':feature_id' => $feature->feature_id))->fetchObject();
   if ($chado_feature) {
     drupal_set_message(t("%feature_id: A chado_feature entry exists", array('%feature_id' => $feature_id)));
-    $node = db_fetch_object(db_query($nsql, $chado_feature->nid));
+    $node = db_query($nsql, array(':nid' => $chado_feature->nid))->fetchObject();
     if (!$node) {
       // if we have a chado_feature but not a node then we have a problem and
       // need to cleanup
       drupal_set_message(t("%feature_id: The node is missing, but has a chado_feature entry... correcting", array('%feature_id' => $feature_id)));
-      $df_sql = "DELETE FROM {chado_feature} WHERE feature_id = %d";
-      db_query($df_sql, $feature_id);
+      $df_sql = "DELETE FROM {chado_feature} WHERE feature_id = :feature_id";
+      db_query($df_sql, array(':feature_id' => $feature_id));
     }
     else {
       drupal_set_message(t("%feature_id: A corresponding node exists", array('%feature_id' => $feature_id)));
@@ -497,8 +499,8 @@ function tripal_feature_sync_feature($feature_id) {
   // will call the hook_submit function which
   if ($create_node) {
     // get the organism for this feature
-    $sql = "SELECT * FROM {organism} WHERE organism_id = %d";
-    $organism = db_fetch_object(chado_query($sql, $feature->organism_id));
+    $sql = "SELECT * FROM {organism} WHERE organism_id = :organism_id";
+    $organism = chado_query($sql, array(':organism_id' => $feature->organism_id))->fetchObject();
 
     drupal_set_message(t("%feature_id: Creating node $feature->name", array('%feature_id' => $feature_id)));
     $new_node = new stdClass();

+ 118 - 106
tripal_feature/tripal_feature.install

@@ -4,6 +4,24 @@
  * @todo Add file header description
  */
 
+/**
+ * Implementation of hook_requirements().
+ */
+function tripal_feature_requirements($phase) {
+  $requirements = array();
+  if ($phase == 'install') {
+    // make sure chado is installed
+    if (!tripal_core_is_chado_installed()) {
+      $requirements ['tripal_feature'] = array(
+          'title' => "tripal_feature",
+          'value' => "ERROR: Chado most be installed before this module can be enabled",
+          'severity' => REQUIREMENT_ERROR,
+      );
+    }
+  }
+  return $requirements;
+}
+
 /**
  * Implementation of hook_install().
  *
@@ -15,136 +33,130 @@ function tripal_feature_install() {
 
   // add the materialized view
   tripal_feature_add_organism_count_mview();
-
-}
-/**
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_add_organism_count_mview() {
-  $view_name = 'organism_feature_count';
-
-  // Drop the MView table if it exists
-  $mview_id = tripal_mviews_get_mview_id($view_name);
-  if ($mview_id) {
-    tripal_mviews_action("delete", $mview_id);
-  }
-
-  // Create the MView
-  tripal_add_mview(
-    // view name
-    $view_name,
-    // tripal module name
-    'tripal_feature',
-    // table name
-    $view_name,
-    // table schema definition
-    'organism_id integer, genus character varying(255), ' .
-    '  species character varying(255), ' .
-    '  common_name character varying(255), ' .
-    '  num_features integer, cvterm_id integer, ' .
-    '  feature_type character varying(255)',
-    // columns for indexing
-    'organism_id,cvterm_id,feature_type',
-    // SQL statement to populate the view
-    'SELECT O.organism_id, O.genus, O.species, O.common_name,
-        count(F.feature_id) as num_features,
-        CVT.cvterm_id, CVT.name as feature_type
-     FROM Organism O
-        INNER JOIN Feature F           ON O.Organism_id = F.organism_id
-        INNER JOIN Cvterm CVT          ON F.type_id = CVT.cvterm_id
-     GROUP BY O.Organism_id, O.genus, O.species, O.common_name,
-        CVT.cvterm_id, CVT.name',
-    // special index
-    ''
-  );
-
+  
   // add a job to the job queue so this view gets updated automatically next
   // time the job facility is run
-  $mview_id = tripal_mviews_get_mview_id($view_name);
-  if ($mview_id) {
+  if ($mview_id = tripal_mviews_get_mview_id('organism_feature_count')) {
     tripal_mviews_action('update', $mview_id);
   }
 }
-/**
- * Implementation of hook_schema().
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_schema() {
-  $schema = tripal_feature_get_schemas();
-  return $schema;
-}
+
 /**
  * Implementation of hook_uninstall().
  *
  * @ingroup tripal_feature
  */
 function tripal_feature_uninstall() {
-
   // Drop the MView table if it exists
-  $mview_id = tripal_mviews_get_mview_id('organism_feature_count');
-  if ($mview_id) {
+  if ($mview_id = tripal_mviews_get_mview_id('organism_feature_count')) {
     tripal_mviews_action("delete", $mview_id);
   }
-
-  // Get the list of nodes to remove
-  $sql_feature_id = "SELECT nid, vid " .
-               "FROM {node} " .
-               "WHERE type='chado_feature'";
-  $result = db_query($sql_feature_id);
-  while ($node = db_fetch_object($result)) {
-    node_delete($node->nid);
-  }
 }
-
+ 
 /**
- * This function simply defines all tables needed for the module to work
- * correctly.  By putting the table definitions in a separate function we
- * can easily provide the entire list for hook_install or individual
- * tables for an update.
+ * Implementation of hook_schema().
  *
  * @ingroup tripal_feature
  */
-function tripal_feature_get_schemas($table = NULL) {
-  $schema = array();
-
-
-  if (!$table or strcmp($table, 'chado_feature')==0) {
-    $schema['chado_feature'] = array(
-      'fields' => array(
-        'vid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
-        'nid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
-        'feature_id' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
-        'sync_date' => array('type' => 'int', 'not null' => FALSE, 'description' => 'UNIX integer sync date/time'),
-      ),
-      'indexes' => array(
-        'feature_id' => array('feature_id')
+function tripal_feature_schema() {
+  
+  $schema['chado_feature'] = array(
+    'fields' => array(
+      'vid' => array(
+        'type' => 'int', 
+        'unsigned' => TRUE, 
+        'not null' => TRUE, 
+        'default' => 0
+       ),
+      'nid' => array(
+        'type' => 'int', 
+        'unsigned' => TRUE, 
+        'not null' => TRUE, 
+        'default' => 0
+       ),
+      'feature_id' => array(
+        'type' => 'int', 
+        'not null' => TRUE, 
+        'default' => 0
       ),
-      'unique keys' => array(
-        'nid_vid' => array('nid', 'vid'),
-        'vid' => array('vid')
+      'sync_date' => array(
+        'type' => 'int', 
+        'not null' => FALSE, 
+        'description' => 'UNIX integer sync date/time'
       ),
-      'primary key' => array('nid'),
-    );
-  }
+    ),
+    'indexes' => array(
+      'chado_feature_idx1' => array('feature_id')
+    ),
+    'unique keys' => array(
+      'chado_feature_uq1' => array('nid', 'vid'),
+      'chado_feature_uq2' => array('vid')
+    ),
+    'primary key' => array('nid'),
+  );
+  
   return $schema;
 };
 
 /**
- * Implementation of hook_requirements(). 
+ *
+ * @ingroup tripal_feature
  */
-function tripal_feature_requirements($phase) {
-  $requirements = array();
-  if ($phase == 'install') {
-    // make sure chado is installed
-    if (!tripal_core_is_chado_installed()) {
-      $requirements ['tripal_feature'] = array(
-            'title' => "tripal_feature",
-            'value' => "ERROR: Chado most be installed before this module can be enabled",
-            'severity' => REQUIREMENT_ERROR,
-      );
-    }
-  }
-  return $requirements;
+function tripal_feature_add_organism_count_mview() {
+  $view_name = 'organism_feature_count';
+  $comment = 'Stores the type and number of features per organism';
+
+  $schema = array(
+    'description' => $comment,
+    'table' => $view_name,
+    'fields' => array(
+      'organism_id' => array(
+        'type' => 'int',
+        'not null' => TRUE,
+      ),
+      'genus' => array(
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+      ),
+      'species' => array(
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+      ),
+      'common_name' => array(
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => FALSE,
+      ),
+      'num_features' => array(
+        'type' => 'int',
+        'not null' => TRUE,
+      ),
+      'feature_type' => array(
+        'type' => 'varchar',
+        'length' => '255',
+        'not null' => TRUE,
+      ),
+    ),      
+    'indexes' => array(
+      'organism_feature_count_idx1' => array('organism_id'),
+      'organism_feature_count_idx2' => array('cvterm_id'),
+      'organism_feature_count_idx3' => array('feature_type'),
+    ),
+  );
+
+  $sql = "
+    SELECT
+        O.organism_id, O.genus, O.species, O.common_name,
+        count(F.feature_id) as num_features,
+        CVT.cvterm_id, CVT.name as feature_type
+     FROM organism O
+        INNER JOIN feature F  ON O.Organism_id = F.organism_id
+        INNER JOIN cvterm CVT ON F.type_id     = CVT.cvterm_id
+     GROUP BY
+        O.Organism_id, O.genus, O.species, O.common_name, CVT.cvterm_id, CVT.name
+  ";
+
+  tripal_add_mview($view_name, 'tripal_feature', $schema, $sql, $comment);
 }

+ 303 - 284
tripal_feature/tripal_feature.module

@@ -13,20 +13,13 @@
  * @}
  */
 
+require_once "api/tripal_feature.api.inc";
 require_once "includes/tripal_feature.admin.inc";
 require_once "includes/tripal_feature.sync_features.inc";
 require_once "includes/fasta_loader.inc";
 require_once "includes/gff_loader.inc";
 require_once "includes/seq_extract.inc";
-
-require_once "api/tripal_feature.api.inc";
-
 require_once "includes/tripal_feature-delete.inc";
-//require_once "includes/tripal_feature-secondary_tables.inc";
-//require_once "includes/tripal_feature-properties.inc";
-//require_once "includes/tripal_feature-relationships.inc";
-//require_once "includes/tripal_feature-db_references.inc";
-
 
 /**
  *
@@ -524,14 +517,19 @@ function chado_feature_insert($node) {
 
   // make sure the entry for this feature doesn't already exist in the chado_feature table
   // if it doesn't exist then we want to add it.
-  $node_check_sql = "SELECT * FROM {chado_feature} " .
-                    "WHERE feature_id = '%s'";
-  $node_check = db_fetch_object(db_query($node_check_sql, $feature[0]->feature_id));
+  $node_check_sql = "
+    SELECT * FROM {chado_feature} 
+    WHERE feature_id = :feature_id
+  ";
+  $node_check = db_query($node_check_sql, array(':feature_id' => $feature[0]->feature_id))->fetchObject();
   if (!$node_check) {
     // next add the item to the drupal table
-    $sql = "INSERT INTO {chado_feature} (nid, vid, feature_id, sync_date) " .
-           "VALUES (%d, %d, %d, " . REQUEST_TIME . ")";
-      db_query($sql, $node->nid, $node->vid, $feature[0]->feature_id);
+    $sql = "
+      INSERT INTO {chado_feature} (nid, vid, feature_id, sync_date) 
+      VALUES (:nid, :vid, :feature_id, :time)
+    ";
+    db_query($sql, array(':nid' => $node->nid, ':vid' => $node->vid, 
+      ':feature_id' => $feature[0]->feature_id, ':time' => REQUEST_TIME));
   }
 }
 
@@ -610,24 +608,18 @@ function chado_feature_delete($node) {
   }
 
   // remove the drupal content
-  $sql_del = "DELETE FROM {chado_feature} " .
-             "WHERE nid = %d " .
-             "AND vid = %d";
-  db_query($sql_del, $node->nid, $node->vid);
-  $sql_del = "DELETE FROM {node} " .
-             "WHERE nid = %d " .
-             "AND vid = %d";
-  db_query($sql_del, $node->nid, $node->vid);
-  $sql_del = "DELETE FROM {node_revision} " .
-             "WHERE nid = %d " .
-             "AND vid = %d";
-  db_query($sql_del, $node->nid, $node->vid);
+  $sql_del = "DELETE FROM {chado_feature} WHERE nid = :nid AND vid = :vid";
+  db_query($sql_del, array(':nid' => $node->nid, ':vid' => $node->vid));
+  $sql_del = "DELETE FROM {node} WHERE nid = :nid AND vid = :vid";
+  db_query($sql_del, array(':nid' => $node->nid, ':vid' => $node->vid));
+  $sql_del = "DELETE FROM {node_revision} WHERE nid = :nid AND vid = :vid";
+  db_query($sql_del, array(':nid' => $node->nid, ':vid' => $node->vid));
 
 
   // Remove data from feature tables of chado database.  This will
   // cause a cascade delete and remove all data in referencing tables
   // for this feature
-  chado_query("DELETE FROM {feature} WHERE feature_id = %d", $feature_id);
+  chado_query("DELETE FROM {feature} WHERE feature_id = :feature_id", array(':feature_id' => $feature_id));
 
   drupal_set_message(t("The feature and all associated data were removed from") .
   "chado");
@@ -648,8 +640,8 @@ function chado_feature_add_synonyms($synonyms, $feature_id) {
 
 
   // remove any old synonyms
-  $feature_syn_dsql = "DELETE FROM {feature_synonym} WHERE feature_id = %d";
-  if (!chado_query($feature_syn_dsql, $feature_id)) {
+  $feature_syn_dsql = "DELETE FROM {feature_synonym} WHERE feature_id = :feature_id";
+  if (!chado_query($feature_syn_dsql, array(':feature_id' => $feature_id))) {
     $error .= "Could not remove synonyms from feature. ";
   }
 
@@ -666,29 +658,32 @@ function chado_feature_add_synonyms($synonyms, $feature_id) {
     // check to see if we have this accession number already in the database
     // if so then don't add it again. it messes up drupal if the insert fails.
     // It is possible for the accession number to be present and not the feature
-    $synonym_sql = "SELECT synonym_id FROM {synonym} " .
-                   "WHERE name = '%s'";
-    $synonym = db_fetch_object(chado_query($synonym_sql, $syn));
+    $synonym_sql = "SELECT synonym_id FROM {synonym} WHERE name = :name";
+    $synonym = chado_query($synonym_sql, array(':name' => $syn))->fetchObject();
     if (!$synonym) {
-      $synonym_isql = "INSERT INTO {synonym} (name,synonym_sgml,type_id) " .
-                      "VALUES ('%s','%s', " .
-                      "   (SELECT cvterm_id " .
-                      "    FROM {CVTerm} CVT " .
-                      "    INNER JOIN CV ON CVT.cv_id = CV.cv_id " .
-                      "    WHERE CV.name = 'feature_property' and CVT.name = 'synonym'))";
-      if (!chado_query($synonym_isql, $syn, $syn)) {
+      $synonym_isql = "
+        INSERT INTO {synonym} (name, synonym_sgml, type_id) 
+      	VALUES (:name, :synonym_sgml, 
+          (SELECT cvterm_id 
+           FROM {CVTerm} CVT 
+             INNER JOIN CV ON CVT.cv_id = CV.cv_id 
+           WHERE CV.name = 'feature_property' and CVT.name = 'synonym')
+          )
+      ";
+      if (!chado_query($synonym_isql, array(':name' => $syn, ':synonym_sgml' => $syn))) {
         $error .= "Could not add synonym. ";
       }
       // now get the synonym we just added
-      $synonym_sql = "SELECT synonym_id FROM {synonym} " .
-                     "WHERE name = '%s'";
-      $synonym = db_fetch_object(chado_query($synonym_sql, $syn));
+      $synonym_sql = "SELECT synonym_id FROM {synonym} WHERE name = :name";
+      $synonym = chado_query($synonym_sql, array(':name' => $syn))->fetchObject();
     }
 
     // now add in our new sysnonym
-    $feature_syn_isql = "INSERT INTO {feature_synonym} (synonym_id,feature_id,pub_id) " .
-                        "VALUES (%d,%d,1)";
-    if (!chado_query($feature_syn_isql, $synonym->synonym_id, $feature_id)) {
+    $feature_syn_isql = "
+      INSERT INTO {feature_synonym} (synonym_id,feature_id,pub_id) 
+      VALUES (:synonym_id, :feature_id, :pub_id)";
+    $args = array(':synonym_id' => $synonym->synonym_id, ':feature_id' => $feature_id, ':pub_id'=> 1);
+    if (!chado_query($feature_syn_isql, $args)) {
       $error .= "Could not add synonyms to feature. ";
     }
   }
@@ -707,13 +702,17 @@ function chado_feature_add_gbaccession($accession, $feature_id) {
   // use chado database
 
   // remove any old accession from genbank dbEST
-  $fdbxref_dsql = "DELETE FROM {feature_dbxref} " .
-                 "WHERE feature_id = %d and dbxref_id IN " .
-                 "   (SELECT DBX.dbxref_id FROM {dbxref} DBX " .
-                 "    INNER JOIN DB  ON DB.db_id = DBX.db_id " .
-                 "    INNER JOIN feature_dbxref FDBX ON DBX.dbxref_id = FDBX.dbxref_id " .
-                 "    WHERE DB.name = 'DB:Genbank' and FDBX.feature_id = %d)";
-  if (!chado_query($fdbxref_dsql, $feature_id, $feature_id)) {
+  $fdbxref_dsql = "
+    DELETE FROM {feature_dbxref} 
+    WHERE feature_id = :feature_id and dbxref_id IN 
+      (SELECT DBX.dbxref_id 
+       FROM {dbxref} DBX 
+         INNER JOIN DB  ON DB.db_id = DBX.db_id 
+         INNER JOIN feature_dbxref FDBX ON DBX.dbxref_id = FDBX.dbxref_id 
+       WHERE DB.name = 'DB:Genbank' and FDBX.feature_id = :feature_id
+      )
+  ";
+  if (!chado_query($fdbxref_dsql, array(':feature_id' => $feature_id))) {
     $error .= "Could not remove accession from feature. ";
   }
 
@@ -722,34 +721,29 @@ function chado_feature_add_gbaccession($accession, $feature_id) {
     return;
   }
   // get the db_id
-  $db_sql = "SELECT db_id FROM {DB} " .
-            "WHERE name = 'DB:Genbank_est'";
-  $db = db_fetch_object(chado_query($db_sql));
+  $db_sql = "SELECT db_id FROM {DB} WHERE name = 'DB:Genbank_est'";
+  $db = chado_query($db_sql)->fetchObject();
 
   // check to see if we have this accession number already in the database
   // if so then don't add it again. it messes up drupal if the insert fails.
   // It is possible for the accession number to be present and not the feature
-  $dbxref_sql = "SELECT dbxref_id FROM {dbxref} " .
-                "WHERE db_id = %d and accession = '%s'";
-  $dbxref = db_fetch_object(chado_query($dbxref_sql, $db->db_id, $accession));
+  $dbxref_sql = "SELECT dbxref_id FROM {dbxref} WHERE db_id = :db_id and accession = :accession";
+  $dbxref = chado_query($dbxref_sql, array(':db_id' => $db->db_id, ':accession' => $accession))->fetchObject();
   if (!$dbxref) {
     // add the accession number
-    $dbxref_isql = "INSERT INTO {dbxref} (db_id,accession) " .
-                   "  VALUES (%d, '%s') ";
-    if (!chado_query($dbxref_isql, $db->db_id, $accession)) {
+    $dbxref_isql = "INSERT INTO {dbxref} (db_id, accession) VALUES (:db_id, :accession) ";
+    if (!chado_query($dbxref_isql, array(':db_id' => $db->db_id, ':accession' => $accession))) {
       $error .= 'Could not add accession as a database reference ';
     }
     // get the dbxref_id for the just added accession number
-    $dbxref_sql = "SELECT dbxref_id FROM {dbxref} " .
-                  "WHERE db_id = %d and accession = '%s'";
-    $dbxref = db_fetch_object(chado_query($dbxref_sql, $db->db_id, $accession));
+    $dbxref_sql = "SELECT dbxref_id FROM {dbxref} WHERE db_id = :db_id and accession = :accession";
+    $dbxref = chado_query($dbxref_sql, array(':db_id' => $db->db_id, ':accession' => $accession))->fetchObject();
   }
 
 
   // associate the accession number with the feature
-  $feature_dbxref_isql = "INSERT INTO {feature_dbxref} (feature_id,dbxref_id) " .
-                         "  VALUES (%d, %d) ";
-  if (!chado_query($feature_dbxref_isql, $feature_id, $dbxref->dbxref_id)) {
+  $feature_dbxref_isql = "INSERT INTO {feature_dbxref} (feature_id, dbxref_id) VALUES (:feature_id, :dbxref_id) ";
+  if (!chado_query($feature_dbxref_isql, array(':feature_id' => $feature_id, ':dbxref_id' => $dbxref->dbxref_id))) {
     $error .= 'Could not add feature database reference. ';
   }
 
@@ -864,7 +858,7 @@ function chado_feature_form($node, $param) {
   $org_rset = chado_query($sql);
   $organisms = array();
   $organisms[''] = '';
-  while ($organism = db_fetch_object($org_rset)) {
+  while ($organism = $org_rset->fetchObject()) {
     $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
   }
   $form['organism_id'] = array(
@@ -934,12 +928,19 @@ function chado_feature_validate($node) {
   // the organism doesn't already have this uniquename. We don't want to give
   // two sequences the same uniquename
   if ($node->feature_id) {
-    $sql = "SELECT *
-            FROM {Feature} F
-              INNER JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
-            WHERE uniquename = '%s'
-             AND organism_id = %d AND CVT.name = '%s' AND NOT feature_id = %d";
-    $result = db_fetch_object(chado_query($sql, $node->uniquename, $node->organism_id, $node->feature_type, $node->feature_id));
+    $sql = "
+      SELECT *
+      FROM {feature} F
+        INNER JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
+      WHERE 
+        F.uniquename     = :uname AND 
+        F.organism_id    = :orgnism_id AND 
+        CVT.name         = :cvtname AND 
+        NOT f.feature_id = :feature_id
+    ";
+    $args = array(':uname' => $node->uniquename, ':organism_id' => $node->organism_id, 
+      ':cvtname' => $node->feature_type, ':feature_id' => $node->feature_id);
+    $result = chado_query($sql, $args)->fetchObject();
     if ($result) {
       form_set_error('uniquename', t("Feature update cannot proceed. The feature name '$node->uniquename' is not unique for this organism. Please provide a unique name for this feature."));
     }
@@ -948,12 +949,17 @@ function chado_feature_validate($node) {
   // if this is an insert then we just need to make sure this name doesn't
   // already exist for this organism if it does then we need to throw an error
   else {
-    $sql = "SELECT *
-            FROM {Feature} F
-              INNER JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
-            WHERE uniquename = '%s'
-             AND organism_id = %d AND CVT.name = '%s'";
-    $result = db_fetch_object(chado_query($sql, $node->uniquename, $node->organism_id, $node->feature_type));
+    $sql = "
+      SELECT *
+      FROM {feature} F
+        INNER JOIN {cvterm} CVT ON F.type_id = CVT.cvterm_id
+      WHERE 
+        F.uniquename  = :name AND 
+        F.organism_id = :organism_id AND 
+        CVT.name      = :cvtname
+    ";
+    $args = array(':name' => $node->uniquename, ':organism_id' => $node->organism_id, ':cvtname' => $node->feature_type);
+    $result = chado_query($sql, $args)->fetchObject();
     if ($result) {
       form_set_error('uniquename', t("Feature insert cannot proceed. The feature name '$node->uniquename' already exists for this organism. Please provide a unique name for this feature."));
     }
@@ -1011,8 +1017,8 @@ function chado_feature_load($node) {
  */
 function tripal_feature_load_organism($organism_id) {
   // add organism details
-  $sql = "SELECT * FROM {organism} WHERE organism_id = %d";
-  $organism = db_fetch_object(chado_query($sql, $organism_id));
+  $sql = "SELECT * FROM {organism} WHERE organism_id = :organism_id";
+  $organism = chado_query($sql, array(':organism_id' => $organism_id))->fetchObject();
   return $organism;
 }
 /**
@@ -1022,16 +1028,17 @@ function tripal_feature_load_organism($organism_id) {
  */
 function tripal_feature_load_synonyms($feature_id) {
 
-  $sql = "SELECT S.name " .
-        "FROM {Feature_Synonym} FS " .
-        "  INNER JOIN {Synonym} S " .
-        "    ON FS.synonym_id = S.Synonym_id " .
-        "WHERE FS.feature_id = %d " .
-        "ORDER BY S.name ";
-  $results = chado_query($sql, $feature_id);
+  $sql = "
+    SELECT S.name 
+    FROM {feature_synonym} FS 
+      INNER JOIN {synonym} S  ON FS.synonym_id = S.Synonym_id 
+    WHERE FS.feature_id = :feature_id
+    ORDER BY S.name 
+   ";
+  $results = chado_query($sql, array(':feature_id' => $feature_id));
   $synonyms = array();
   $i=0;
-  while ($synonym = db_fetch_object($results)) {
+  while ($synonym = $results->fetchObject()) {
     $synonyms[$i++] = $synonym;
   }
   return $synonyms;
@@ -1043,20 +1050,24 @@ function tripal_feature_load_synonyms($feature_id) {
  */
 function tripal_feature_load_properties($feature_id) {
 
-  $sql = "SELECT CVT.name as cvname, FS.type_id, FS.value, FS.rank,
-           CVT.definition, CVT.is_obsolete,
-           DBX.dbxref_id,DBX.accession,DB.name as dbname,
-           DB.urlprefix, DB.description as db_description, DB.url
-         FROM {featureprop} FS
-           INNER JOIN {cvterm} CVT ON FS.type_id = CVT.cvterm_id
-           INNER JOIN {dbxref} DBX ON CVT.dbxref_id = DBX.dbxref_id
-           INNER JOIN {db} DB      ON DB.db_id = DBX.db_id
-         WHERE FS.feature_id = %d
-         ORDER BY FS.rank ASC";
-  $results = chado_query($sql, $feature_id);
+  $sql = "
+    SELECT 
+      CVT.name as cvname, CVT.definition, CVT.is_obsolete, 
+      FS.type_id, FS.value, FS.rank,      
+      DBX.dbxref_id,DBX.accession,DB.name as dbname,
+      DB.urlprefix, DB.description as db_description, DB.url
+    FROM {featureprop} FS
+      INNER JOIN {cvterm} CVT ON FS.type_id    = CVT.cvterm_id
+      INNER JOIN {dbxref} DBX ON CVT.dbxref_id = DBX.dbxref_id
+      INNER JOIN {db} DB      ON DB.db_id      = DBX.db_id
+    WHERE 
+      FS.feature_id = :feature_id
+    ORDER BY FS.rank ASC
+  ";
+  $results = chado_query($sql, array(':feature_id' => $feature_id));
   $i=0;
   $properties = array();
-  while ($property = db_fetch_object($results)) {
+  while ($property = $results->fetchObject()) {
     $properties[$i++] = $property;
   }
   return $properties;
@@ -1068,18 +1079,23 @@ function tripal_feature_load_properties($feature_id) {
  */
 function tripal_feature_load_references($feature_id) {
 
-  $sql = "SELECT F.uniquename,F.Feature_id,DBX.accession,DB.description as dbdesc, " .
-        "   DB.db_id, DB.name as db_name, DB.urlprefix,DBX.dbxref_id " .
-        "FROM {feature} F " .
-        "  INNER JOIN {feature_dbxref} FDBX on F.feature_id = FDBX.feature_id " .
-        "  INNER JOIN {dbxref} DBX on DBX.dbxref_id = FDBX.dbxref_id " .
-        "  INNER JOIN {db} on DB.db_id = DBX.db_id " .
-        "WHERE F.feature_id = %d " .
-        "ORDER BY DB.name ";
-  $results = chado_query($sql, $feature_id);
+  $sql = "
+    SELECT 
+       F.uniquename, F.Feature_id,
+       DB.description as dbdesc, DB.db_id, DB.name as db_name, DB.urlprefix,
+       DBX.accession, DBX.dbxref_id 
+    FROM {feature} F 
+      INNER JOIN {feature_dbxref} FDBX ON F.feature_id  = FDBX.feature_id 
+      INNER JOIN {dbxref} DBX          ON DBX.dbxref_id = FDBX.dbxref_id 
+      INNER JOIN {db}                  ON DB.db_id      = DBX.db_id 
+    WHERE 
+      F.feature_id = :feature_id
+    ORDER BY DB.name 
+  ";
+  $results = chado_query($sql, array(':feature_id' => $feature_id));
   $references = array();
   $i=0;
-  while ($accession = db_fetch_object($results)) {
+  while ($accession = $results->fetchObject()) {
     $references[$i++] = $accession;
   }
   return $references;
@@ -1091,40 +1107,38 @@ function tripal_feature_load_references($feature_id) {
  */
 function tripal_feature_load_featurelocs($feature_id, $side = 'as_parent', $aggregate = 1) {
 
-  $sql = "SELECT
-           F.name, F.feature_id, F.uniquename,
-           FS.name as src_name,
-           FS.feature_id as src_feature_id,
-           FS.uniquename as src_uniquename,
-           CVT.name as cvname, CVT.cvterm_id,
-           CVTS.name as src_cvname, CVTS.cvterm_id as src_cvterm_id,
-           FL.fmin, FL.fmax, FL.is_fmin_partial, FL.is_fmax_partial,FL.strand,
-           FL.phase
-         FROM {featureloc} FL
-            INNER JOIN {feature} F on FL.feature_id = F.feature_id
-            INNER JOIN {feature} FS on FS.feature_id = FL.srcfeature_id
-            INNER JOIN {cvterm} CVT on F.type_id = CVT.cvterm_id
-            INNER JOIN {cvterm} CVTS on FS.type_id = CVTS.cvterm_id
-         ";
+  $sql = "
+    SELECT
+       F.name, F.feature_id, F.uniquename,
+       FS.name as src_name, FS.feature_id as src_feature_id, FS.uniquename as src_uniquename,
+       CVT.name as cvname, CVT.cvterm_id,
+       CVTS.name as src_cvname, CVTS.cvterm_id as src_cvterm_id,
+       FL.fmin, FL.fmax, FL.is_fmin_partial, FL.is_fmax_partial,FL.strand, FL.phase
+     FROM {featureloc} FL
+       INNER JOIN {feature} F   ON FL.feature_id = F.feature_id
+       INNER JOIN {feature} FS  ON FS.feature_id = FL.srcfeature_id
+       INNER JOIN {cvterm} CVT  ON F.type_id     = CVT.cvterm_id
+       INNER JOIN {cvterm} CVTS ON FS.type_id    = CVTS.cvterm_id
+   ";
   if (strcmp($side, 'as_parent')==0) {
-    $sql .= "WHERE FL.srcfeature_id = %d ";
+    $sql .= "WHERE FL.srcfeature_id = :feature_id ";
   }
   if (strcmp($side, 'as_child')==0) {
-    $sql .= "WHERE FL.feature_id = %d ";
+    $sql .= "WHERE FL.feature_id = :feature_id ";
   }
-
-  $flresults = chado_query($sql, $feature_id);
+  
+  $flresults = chado_query($sql, array(':feature_id' => $feature_id));
 
   // copy the results into an array
   $i=0;
   $featurelocs = array();
-  while ($loc = db_fetch_object($flresults)) {
+  while ($loc = $flresults->fetchObject()) {
     // if a drupal node exists for this feature then add the nid to the
     // results object
-    $sql = 'SELECT nid FROM {chado_feature} WHERE feature_id = %d';
+    $sql = 'SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id';
 
-    $ffeature = db_fetch_object(db_query($sql, $loc->feature_id));
-    $sfeature = db_fetch_object(db_query($sql, $loc->src_feature_id));
+    $ffeature = db_query($sql, array(':feature_id' => $loc->feature_id))->fetchObject();
+    $sfeature = db_query($sql, array(':feature_id' => $loc->src_feature_id))->fetchObject();
     $loc->fnid = $ffeature->nid;
     $loc->snid = $sfeature->nid;
     // add the result to the array
@@ -1164,50 +1178,44 @@ function tripal_feature_sort_locations($a, $b) {
 function tripal_feature_load_relationships($feature_id, $side = 'as_subject') {
   // get the relationships for this feature.  The query below is used for both
   // querying the object and subject relationships
-  $sql = "SELECT
-           FS.name as subject_name,
-           FS.uniquename as subject_uniquename,
-           CVTS.name as subject_type,
-           CVTS.cvterm_id as subject_type_id,
-           FR.subject_id,
-           FR.type_id as relationship_type_id,
-           CVT.name as rel_type,
-           FO.name as object_name,
-           FO.uniquename as object_uniquename,
-           CVTO.name as object_type,
-           CVTO.cvterm_id as object_type_id,
-           FR.object_id,
-           FR.rank
-         FROM {feature_relationship} FR
-           INNER JOIN {cvterm} CVT ON FR.type_id = CVT.cvterm_id
-           INNER JOIN {feature} FS ON FS.feature_id = FR.subject_id
-           INNER JOIN {feature} FO ON FO.feature_id = FR.object_id
-           INNER JOIN {cvterm} CVTO ON FO.type_id = CVTO.cvterm_id
-           INNER JOIN {cvterm} CVTS ON FS.type_id = CVTS.cvterm_id
+  $sql = "
+    SELECT
+      FS.name as subject_name, FS.uniquename as subject_uniquename,
+      CVTS.name as subject_type, CVTS.cvterm_id as subject_type_id,
+      FR.subject_id, FR.type_id as relationship_type_id, FR.object_id, FR.rank,
+      CVT.name as rel_type,
+      FO.name as object_name, FO.uniquename as object_uniquename,
+      CVTO.name as object_type, CVTO.cvterm_id as object_type_id      
+    FROM {feature_relationship} FR
+     INNER JOIN {cvterm} CVT  ON FR.type_id    = CVT.cvterm_id
+     INNER JOIN {feature} FS  ON FS.feature_id = FR.subject_id
+     INNER JOIN {feature} FO  ON FO.feature_id = FR.object_id
+     INNER JOIN {cvterm} CVTO ON FO.type_id    = CVTO.cvterm_id
+     INNER JOIN {cvterm} CVTS ON FS.type_id    = CVTS.cvterm_id
   ";
   if (strcmp($side, 'as_object')==0) {
-    $sql .= " WHERE FR.object_id = %d";
+    $sql .= " WHERE FR.object_id = :feature_id";
   }
   if (strcmp($side, 'as_subject')==0) {
-    $sql .= " WHERE FR.subject_id = %d";
+    $sql .= " WHERE FR.subject_id = :feature_id";
   }
   $sql .= " ORDER BY FR.rank";
 
   // get the relationships
-  $results = chado_query($sql, $feature_id);
+  $results = chado_query($sql, array(':feature_id' => $feature_id));
 
 
   // iterate through the relationships, put these in an array and add
   // in the Drupal node id if one exists
   $i=0;
-  $nodesql = "SELECT nid FROM {chado_feature} WHERE feature_id = %d";
+  $nodesql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
   $relationships = array();
-  while ($rel = db_fetch_object($results)) {
-    $node = db_fetch_object(db_query($nodesql, $rel->subject_id));
+  while ($rel = $results->fetchObject()) {
+    $node = db_query($nodesql, array(':feature_id' => $rel->subject_id))->fetchObject();
     if ($node) {
       $rel->subject_nid = $node->nid;
     }
-    $node = db_fetch_object(db_query($nodesql, $rel->object_id));
+    $node = db_query($nodesql, array(':feature_id' => $rel->object_id))->fetchObject();
     if ($node) {
       $rel->object_nid = $node->nid;
     }
@@ -1289,9 +1297,11 @@ function tripal_feature_load_featureloc_sequences($feature_id, $featurelocs) {
   // where this feature is found.   We want to get the sequence for each
   // location and then annotate it with the parts found from the relationships
   // locations determiend above.
-  $sql = "SELECT substring(residues from %d for %d) as residues " .
-         "FROM {feature} " .
-         "WHERE feature_id = %d";
+  $sql = "
+    SELECT substring(residues from :start for :size) as residues 
+    FROM {feature} 
+    WHERE feature_id = :feature_id
+  ";
   $floc_sequences = array();
   foreach ($featurelocs as $featureloc) {
 
@@ -1340,7 +1350,8 @@ function tripal_feature_load_featureloc_sequences($feature_id, $featurelocs) {
 
       $floc_sequences[$src]['src'] = $src;
       $floc_sequences[$src]['type'] = $featureloc->feature_id->type_id->name;
-      $sequence = db_fetch_object(chado_query($sql, $featureloc->fmin + 1, ($featureloc->fmax - $featureloc->fmin), $featureloc->srcfeature_id->feature_id));
+      $args = array(':start' => $featureloc->fmin + 1, ':size' => ($featureloc->fmax - $featureloc->fmin), ':feature_id' => $featureloc->srcfeature_id->feature_id);
+      $sequence = chado_query($sql, $args)->fetchObject();
       $residues = $sequence->residues;
       if ($featureloc->strand < 0) {
          $residues = tripal_feature_reverse_complement($residues);
@@ -1383,43 +1394,46 @@ function tripal_feature_get_matched_alignments($feature) {
   // not want to include these, so we have to filter on the SO terms:
   // match, or %_match
   //
-   $sql = "SELECT  " .
-          "   FL1.featureloc_id    as left_featureloc_id, " .
-          "   FL1.srcfeature_id    as left_srcfeature_id, " .
-          "   FL1.feature_id       as left_feature_id, " .
-          "   FL1.fmin             as left_fmin, " .
-          "   FL1.is_fmin_partial  as left_is_fmin_partial, " .
-          "   FL1.fmax             as left_fmax, " .
-          "   FL1.is_fmax_partial  as left_is_fmax_partial, " .
-          "   FL1.strand           as left_strand,  " .
-          "   FL1.phase            as left_phase, " .
-          "   FL1.locgroup         as left_locgroup, " .
-          "   FL1.rank             as left_rank, " .
-          "   FL2.featureloc_id    as right_featureloc_id, " .
-          "   FL2.srcfeature_id    as right_srcfeature_id, " .
-          "   FL2.feature_id       as right_feature_id, " .
-          "   FL2.fmin             as right_fmin, " .
-          "   FL2.is_fmin_partial  as right_is_fmin_partial, " .
-          "   FL2.fmax             as right_fmax, " .
-          "   FL2.is_fmax_partial  as right_is_fmax_partial, " .
-          "   FL2.strand           as right_strand,  " .
-          "   FL2.phase            as right_phase, " .
-          "   FL2.locgroup         as right_locgroup, " .
-          "   FL2.rank             as right_rank " .
-          "FROM {feature} F1 " .
-          "  INNER JOIN {featureloc} FL1 on FL1.srcfeature_id = F1.feature_id " .
-          "  INNER JOIN {feature} F2 on FL1.feature_id = F2.feature_id " .
-          "  INNER JOIN {featureloc} FL2 on FL2.feature_id = F2.feature_id " .
-          "  INNER JOIN {cvterm} CVT2 on F2.type_id = CVT2.cvterm_id " .
-          "WHERE F1.feature_id = %d " .
-          "  AND (CVT2.name = 'match' or CVT2.name like '%_match') " .
-          "ORDER BY FL1.fmin";
-
-   $results = chado_query($sql, $feature->feature_id);
+   $sql = "
+     SELECT  
+       FL1.featureloc_id    as left_featureloc_id, 
+       FL1.srcfeature_id    as left_srcfeature_id, 
+       FL1.feature_id       as left_feature_id, 
+       FL1.fmin             as left_fmin, 
+       FL1.is_fmin_partial  as left_is_fmin_partial, 
+       FL1.fmax             as left_fmax, 
+       FL1.is_fmax_partial  as left_is_fmax_partial, 
+       FL1.strand           as left_strand,  
+       FL1.phase            as left_phase, 
+       FL1.locgroup         as left_locgroup, 
+       FL1.rank             as left_rank, 
+       FL2.featureloc_id    as right_featureloc_id, 
+       FL2.srcfeature_id    as right_srcfeature_id, 
+       FL2.feature_id       as right_feature_id, 
+       FL2.fmin             as right_fmin, 
+       FL2.is_fmin_partial  as right_is_fmin_partial, 
+       FL2.fmax             as right_fmax, 
+       FL2.is_fmax_partial  as right_is_fmax_partial, 
+       FL2.strand           as right_strand,  
+       FL2.phase            as right_phase, 
+       FL2.locgroup         as right_locgroup, 
+       FL2.rank             as right_rank 
+     FROM {feature} F1 
+       INNER JOIN {featureloc} FL1 on FL1.srcfeature_id = F1.feature_id 
+       INNER JOIN {feature} F2 on FL1.feature_id = F2.feature_id 
+       INNER JOIN {featureloc} FL2 on FL2.feature_id = F2.feature_id 
+       INNER JOIN {cvterm} CVT2 on F2.type_id = CVT2.cvterm_id 
+     WHERE 
+       F1.feature_id = :feature_id  AND 
+       (CVT2.name = 'match' or CVT2.name like '%_match') 
+     ORDER BY FL1.fmin
+   ";
+
+   $results = chado_query($sql, array(':feature_id' => $feature->feature_id));
 
    // iterate through the results and add them to our featurelocs array
    $featurelocs = array();
-   while ($fl = db_fetch_object($results)) {
+   while ($fl = $results->fetchObject()) {
      // ignore featurelocs where the left and right srcfeature is the same
      if (strcmp($fl->left_srcfeature_id, $fl->right_srcfeature_id) == 0) {
        continue;
@@ -1441,8 +1455,6 @@ function tripal_feature_load_organism_feature_counts($organism) {
   if (strcmp($show_counts, 'show_feature_summary')!=0) {
     return array('enabled' => FALSE );
   }
-
-
   $args = array();
   $names = array();
   $order = array();
@@ -1456,6 +1468,7 @@ function tripal_feature_load_organism_feature_counts($organism) {
   if ($temp) {
     $is_custom = 1;
     $temp = explode("\n", $temp);
+    $i = 0;
     foreach ($temp as $key => $value) {
       // separate the key value pairs
       $temp2 = explode("=", $value);
@@ -1465,12 +1478,13 @@ function tripal_feature_load_organism_feature_counts($organism) {
       // if a new name is provided then use that otherwise just
       // use the feature type
       if (count($temp2) == 2) {
-        $names[] = rtrim($temp2[1]);
+        $names[":name$i"] = rtrim($temp2[1]);
       }
       else {
-        $names[] = $feature_type;
+        $names[":name$i"] = $feature_type;
       }
-      $where .= "OFC.feature_type = '%s' OR \n";
+      $where .= " OFC.feature_type = :name$i OR ";
+      $i++;
     }
     if ($where) {
       $where = drupal_substr($where, 0, -5);  # remove OR from the end
@@ -1484,15 +1498,15 @@ function tripal_feature_load_organism_feature_counts($organism) {
     SELECT OFC.num_features,OFC.feature_type,CVT.definition
     FROM {organism_feature_count} OFC
       INNER JOIN {cvterm} CVT on OFC.cvterm_id = CVT.cvterm_id
-    WHERE $where organism_id = %d
+    WHERE $where organism_id = :organism_id
     ORDER BY num_features desc
   ";
-  $args[] = $organism->organism_id;
+  $args[':organism_id'] = $organism->organism_id;
   $org_features = chado_query($sql, $args);
 
   // iterate through the types
   $types = array();
-  while ($type = db_fetch_object($org_features)) {
+  while ($type = $org_features->fetchObject()) {
     $types[$type->feature_type] = $type;
     // if we don't have an order this means we didn't go through the loop
     // above to set the names, so do that now
@@ -1550,11 +1564,11 @@ function tripal_feature_load_organism_feature_browser($organism) {
   $pager = theme('pager');
 
   // add the node ids and types
-  $nsql = "SELECT nid FROM {chado_feature} WHERE feature_id = %d";
-  $tsql = "SELECT name FROM {cvterm} WHERE cvterm_id = %d";
+  $nsql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
+  $tsql = "SELECT name FROM {cvterm} WHERE cvterm_id = :cvterm_id";
   foreach ($features as $feature) {
-    $node = db_fetch_object(db_query($nsql, $feature->feature_id));
-    $type = db_fetch_object(chado_query($tsql, $feature->type_id));
+    $node = db_query($nsql, array(':feature_id' => $feature->feature_id))->fetchObject();
+    $type = chado_query($tsql, array(':cvterm_id' => $feature->type_id))->fetchObject();
     $feature->nid = $node->nid;
     $feature->type_name = $type->name;
   }
@@ -1583,39 +1597,46 @@ function tripal_feature_load_library_feature_browser($library) {
   $allowed_types = preg_replace("/[\s\n\r]+/", " ", $allowed_types);
   $so_terms = split(' ', $allowed_types);
   $where_cvt = "";
+  $args = array();
+  $i = 0;
   foreach ($so_terms as $term) {
-    $where_cvt .= "CVT.name = '$term' OR ";
+    $where_cvt .= "CVT.name = :cvtname$i OR ";
+    $args[':cvtname$i'] = $term;
+    $i++;
   }
   $where_cvt = drupal_substr($where_cvt, 0, drupal_strlen($where_cvt)-3);  # strip trailing 'OR'
 
   // get the features for this library
-  $sql  = "SELECT F.name,F.feature_id,F.uniquename,CVT.name as cvname " .
-         "FROM {feature} F " .
-            "  INNER JOIN {cvterm} CVT on F.type_id = CVT.cvterm_id " .
-            "  INNER JOIN {library_feature} LF on F.feature_id = LF.feature_id " .
-            "  INNER JOIN {library} L on LF.library_id = L.library_id " .
-          "WHERE LF.library_id = %d and ($where_cvt) " .
-          "ORDER BY feature_id ASC";
-
+  $sql  = "
+    SELECT F.name, F.feature_id, F.uniquename, CVT.name as cvname 
+    FROM {feature} F 
+      INNER JOIN {cvterm} CVT         ON F.type_id = CVT.cvterm_id 
+      INNER JOIN {library_feature} LF ON F.feature_id = LF.feature_id 
+      INNER JOIN {library} L          ON LF.library_id = L.library_id 
+    WHERE LF.library_id = :library_id and ($where_cvt) 
+    ORDER BY feature_id ASC
+  ";
+  $args[':library_id'] = $library->libary_id;
+  
   // the counting SQL
-  $csql  = "SELECT count(*) " .
-          "FROM {feature} F" .
-            "  INNER JOIN {cvterm} CVT on F.type_id = CVT.cvterm_id " .
-            "  INNER JOIN {library_feature} LF on F.feature_id = LF.feature_id " .
-            "  INNER JOIN {library} L on LF.library_id = L.library_id " .
-          "WHERE LF.library_id = %d and ($where_cvt) " .
-          "GROUP BY L.library_id ";
-
-  $org_features = chado_pager_query($sql, 10, 0, $csql, $library->library_id);
+  $csql  = "
+    SELECT count(*) 
+    FROM {feature} F
+      INNER JOIN {cvterm} CVT on F.type_id = CVT.cvterm_id 
+      INNER JOIN {library_feature} LF on F.feature_id = LF.feature_id 
+      INNER JOIN {library} L on LF.library_id = L.library_id 
+    WHERE LF.library_id = :library_id and ($where_cvt) 
+      GROUP BY L.library_id ";
+
+  $org_features = chado_pager_query($sql, 10, 0, $csql, $args);
   $pager = theme('pager');
 
   // prepare the query that will lookup node ids
-  $sql = "SELECT nid FROM {chado_feature} " .
-         "WHERE feature_id = %d";
+  $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
   $i=0;
   $features = array();
-  while ($feature = db_fetch_object($org_features)) {
-    $node = db_fetch_object(db_query($sql, $feature->feature_id));
+  while ($feature = $org_features->fetchObject()) {
+    $node = db_query($sql, array(':feature_id' => $feature->feature_id))->fetchObject();
     $feature->nid = $node->nid;
     $features[$i++] = $feature;
   }
@@ -1643,39 +1664,47 @@ function tripal_feature_load_analysis_feature_browser($analysis) {
   $allowed_types = preg_replace("/[\s\n\r]+/", " ", $allowed_types);
   $so_terms = split(' ', $allowed_types);
   $where_cvt = "";
+  $i = 0;
+  $args = array();
   foreach ($so_terms as $term) {
-    $where_cvt .= "CVT.name = '$term' OR ";
+    $where_cvt .= "CVT.name = :aname$i OR ";
+    $args[":aname$i"] = $term;
+    $i++;
   }
   $where_cvt = drupal_substr($where_cvt, 0, drupal_strlen($where_cvt)-3);  # strip trailing 'OR'
 
   // get the features for this library
-  $sql  = "SELECT F.name,F.feature_id,F.uniquename,CVT.name as cvname " .
-         "FROM {feature} F " .
-            "  INNER JOIN {cvterm} CVT on F.type_id = CVT.cvterm_id " .
-            "  INNER JOIN {analysisfeature} AF on F.feature_id = AF.feature_id " .
-            "  INNER JOIN {analysis} A on AF.analysis_id = A.analysis_id " .
-          "WHERE A.analysis_id = %d and ($where_cvt) " .
-          "ORDER BY feature_id ASC";
+  $sql  = "
+    SELECT F.name,F.feature_id,F.uniquename,CVT.name as cvname 
+    FROM {feature} F 
+      INNER JOIN {cvterm} CVT on F.type_id = CVT.cvterm_id 
+      INNER JOIN {analysisfeature} AF on F.feature_id = AF.feature_id 
+      INNER JOIN {analysis} A on AF.analysis_id = A.analysis_id 
+    WHERE A.analysis_id = :analysis_id and ($where_cvt) 
+    ORDER BY feature_id ASC
+  ";
+  $args[':analysis_id'] = $analysis->analysis_id;
 
   // the counting SQL
-  $csql  = "SELECT count(*) " .
-          "FROM {feature} F" .
-            "  INNER JOIN {cvterm} CVT on F.type_id = CVT.cvterm_id " .
-            "  INNER JOIN {analysisfeature} AF on F.feature_id = AF.feature_id " .
-            "  INNER JOIN {analysis} A on AF.analysis_id = A.analysis_id " .
-          "WHERE A.analysis_id = %d and ($where_cvt) " .
-          "GROUP BY A.analysis_id ";
-
-  $org_features = chado_pager_query($sql, 10, 0, $csql, $analysis->analysis_id);
+  $csql  = "
+    SELECT count(*) 
+    FROM {feature} F
+      INNER JOIN {cvterm} CVT on F.type_id = CVT.cvterm_id 
+      INNER JOIN {analysisfeature} AF on F.feature_id = AF.feature_id 
+      INNER JOIN {analysis} A on AF.analysis_id = A.analysis_id 
+    WHERE A.analysis_id = %d and ($where_cvt) 
+    GROUP BY A.analysis_id 
+  ";
+
+  $org_features = chado_pager_query($sql, 10, 0, $csql, $args);
   $pager = theme('pager');
 
   // prepare the query that will lookup node ids
-  $sql = "SELECT nid FROM {chado_feature} " .
-         "WHERE feature_id = %d";
+  $sql = "SELECT nid FROM {chado_feature} WHERE feature_id = :feature_id";
   $i=0;
   $features = array();
-  while ($feature = db_fetch_object($org_features)) {
-    $node = db_fetch_object(db_query($sql, $feature->feature_id));
+  while ($feature = $org_features->fetchObject()) {
+    $node = db_query($sql, array(':feature_id' => $feature->feature_id))->fetchObject();
     $feature->nid = $node->nid;
     $features[$i++] = $feature;
   }
@@ -1837,33 +1866,13 @@ function tripal_feature_node_insert($node) {
   switch ($node->type) {
     case 'chado_feature':
       if (!$node->feature_id) {
-        $sql = "SELECT * FROM {chado_feature} WHERE nid = %d";
-        $chado_feature = db_fetch_object(db_query($sql, $node->nid));
+        $sql = "SELECT * FROM {chado_feature} WHERE nid = :nid";
+        $chado_feature = db_query($sql, array(':nid' => $node->nid))->fetchObject();
         $node->feature_id = $chado_feature->feature_id;
       }
       
       // remove any previous alias
-      db_query("DELETE FROM {url_alias} WHERE src = '%s'", "node/$node->nid");
-      
-      // set the URL for this feature page
-      $url_alias = tripal_feature_get_feature_url($node);
-      path_set_alias("node/$node->nid", $url_alias);
-      break;
-  }
-}
-/**
- *
- * @ingroup tripal_feature
- */
-function tripal_feature_node_update($node) {
-  
-  // set the URL path after inserting.  We do it here because we do not 
-  // know the feature_id in the presave  
-  switch ($node->type) {
-    case 'chado_feature':
-      
-      // remove any previous alias
-      db_query("DELETE FROM {url_alias} WHERE src = '%s'", "node/$node->nid");
+      db_query("DELETE FROM {url_alias} WHERE src = :src", array(':src' => "node/$node->nid"));
       
       // set the URL for this feature page
       $url_alias = tripal_feature_get_feature_url($node);
@@ -1871,6 +1880,7 @@ function tripal_feature_node_update($node) {
       break;
   }
 }
+
 /**
  *
  * @ingroup tripal_feature
@@ -1890,7 +1900,16 @@ function tripal_feature_node_update($node) {
           '#value' => theme('tripal_organism_feature_browser', $node),
         );
       }
-    break;
+      break;
+    case 'chado_feature':
+      
+      // remove any previous alias
+      db_query("DELETE FROM {url_alias} WHERE src = :src", array(':src' => "node/$node->nid"));
+      
+      // set the URL for this feature page
+      $url_alias = tripal_feature_get_feature_url($node);
+      path_set_alias("node/$node->nid", $url_alias);
+      break;
   }
 }
 
@@ -2311,13 +2330,13 @@ function tripal_feature_match_features_page($id) {
       LEFT JOIN {synonym} S on S.synonym_id = FS.synonym_id
       INNER JOIN public.chado_feature CF on CF.feature_id = F.feature_id
     WHERE
-      F.uniquename = '%s' or
-      F.name = '%s' or
-      S.name = '%s'
+      F.uniquename = :uname or
+      F.name = :fname' or
+      S.name = :sname
     GROUP BY F.name, F.uniquename, F.feature_id, O.genus, O.species,
       O.organism_id, CVT.cvterm_id, CVT.name, CF.nid
   ";
-  $results = chado_query($sql, $id, $id, $id);
+  $results = chado_query($sql, array(':uname' => $id, ':fname' => $id, ':sname' => $id));
 
   $num_matches = 0;
 
@@ -2325,7 +2344,7 @@ function tripal_feature_match_features_page($id) {
   $header = array('Uniquename', 'Name', 'Type', 'Species', 'Synonyms');
   $rows = array();
   $curr_match;
-  while ($match = db_fetch_object($results)) {
+  while ($match = $results->fetchObject()) {
     $curr_match = $match;
     $synonyms = $match->synonyms;
     $synonyms = preg_replace('/[\"\{\}]/', '', $synonyms);