Browse Source

periodic checkin

Stephen Ficklin 6 years ago
parent
commit
e8ef524896

+ 4 - 4
tripal/api/tripal.DEPRECATED.api.inc

@@ -32,10 +32,10 @@
  */
 function tripal_get_job_end($job) {
   tripal_report_error('tripal_deprecated', TRIPAL_NOTICE,
-    "DEPRECATED: %function has been removed from the API the end date " .
+    "DEPRECATED: %old_function has been removed from the API the end date " .
     "is now accessible via the %property property. Please update your code.",
     array(
-      '%old_function' => 'tripal_jobs_get_end_time',
+      '%old_function' => 'tripal_get_job_end',
       '%property' => '\$job->end_time_string',
     )
   );
@@ -66,7 +66,7 @@ function tripal_get_job_end($job) {
 function tripal_get_job_start($job) {
 
   tripal_report_error('tripal_deprecated', TRIPAL_NOTICE,
-    "DEPRECATED: %function has been removed from the API the end date " .
+    "DEPRECATED: %old_function has been removed from the API the end date " .
     "is now accessible via the %property property. Please update your code.",
     array(
       '%old_function' => 'tripal_get_job_start',
@@ -104,7 +104,7 @@ function tripal_get_job_start($job) {
 function tripal_get_job_submit_date($job) {
 
   tripal_report_error('tripal_deprecated', TRIPAL_NOTICE,
-      "DEPRECATED: %function has been removed from the API the end date " .
+      "DEPRECATED: %old_function has been removed from the API the end date " .
       "is now accessible via the %property property. Please update your code.",
       array(
         '%old_function' => 'tripal_get_job_submit_date',

+ 0 - 2
tripal/api/tripal.notice.api.inc

@@ -63,8 +63,6 @@ define('TRIPAL_DEBUG',7);
  *   An array of options. Some available options include:
  *     - print: prints the error message to the terminal screen. Useful when
  *       display is the command-line
- *     - drupal_set_message: set to TRUE to call drupal_set_message with the 
- *       same error.
  *     - drupal_set_message:  set to TRUE then send the message to the
  *       drupal_set_message function.
  *     - watchdog:  set to FALSE to disable logging to Drupal's watchdog.

+ 138 - 251
tripal_chado/api/modules/tripal_chado.cv.api.inc

@@ -969,7 +969,7 @@ function chado_insert_cvterm($term, $options = array()) {
     $update = $options['update_existing'];
   }
   else {
-    $update = 1;
+    $update = TRUE;
   }
 
   if (array_key_exists('name', $term)) {
@@ -991,10 +991,14 @@ function chado_insert_cvterm($term, $options = array()) {
     if (strcmp($is_obsolete, 'true') == 0) {
       $is_obsolete = 1;
     }
+    else {
+      $is_obsolete = 0;
+    }
   }
   if (!$name and !$id) {
-    tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find cvterm without 'id' or 'name'", NULL);
-    return 0;
+    tripal_report_error('tripal_cv', TRIPAL_ERROR, 
+      "Please provide an 'id' or 'name' argument to the chado_insert_cvterm() function");
+    return FALSE;
   }
   if (!$id) {
     $id = $name;
@@ -1013,270 +1017,153 @@ function chado_insert_cvterm($term, $options = array()) {
   // Check that we have a database name, give a different message if it's a
   // relationship.
   if ($is_relationship and !$dbname) {
-    tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database name is not provided for this relationship term: $id", NULL);
-    return 0;
+    tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database name is not provided for this relationship term: !id", 
+      ['!id' => $id]);
+    return FALSE;
   }
   if (!$is_relationship and !$dbname) {
-    tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database identifier is missing from the term: $id", NULL);
-    return 0;
-  }
-
-  // Make sure the CV name exists.
-  $cv = chado_get_cv(array('name' => $cvname));
-  if (!$cv) {
-    $cv = chado_insert_cv($cvname, '');
-  }
-  if (!$cv) {
-    tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find namespace '$cvname' when adding/updating $id", NULL);
-    return 0;
-  }
-
-  // This SQL statement will be used a lot to find a cvterm so just set it
-  // here for easy reference below.  Because CV terms can change their names
-  // but accessions don't change, the following SQL finds cvterms based on
-  // their accession rather than the name.
-  $cvtermsql = "
-    SELECT CVT.name, CVT.cvterm_id, CV.cv_id, CV.name as cvname,
-      DB.name as dbname, DB.db_id, DBX.accession
-    FROM {cvterm} CVT
-      INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
-      INNER JOIN {db} DB on DBX.db_id = DB.db_id
-      INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
-    WHERE DBX.accession = :accession and DB.name = :name
-  ";
-
-  // Add the database. The function will just return the DB object if the
-  // database already exists.
-  $db = chado_get_db(array('name' => $dbname));
-  if (!$db) {
-    $db = chado_insert_db(array('name' => $dbname));
-  }
-  if (!$db) {
-    tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find database '$dbname' in Chado.", NULL);
-    return 0;
+    tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database identifier is missing from the term: !id", 
+      ['!id' => $id]);
+    return FALSE;
   }
 
-  // The cvterm table has two unique dependencies. We need to check both.
-  // first check the (name, cv_id, is_obsolete) constraint.
-  $values = array(
+  // Make sure the CV exists before we try to insert the cvterm. The cv table
+  // has a unique constraint on the name so we'll always get a 1 or 0 returned
+  // by the ->find function.
+  $cv = new ChadoRecord('cv');
+  $cv->setValues(['name' => $cvname]);
+  if (!$cv->find()) {
+    $cv->insert();
+  }
+  
+  // Make sure the DB exists before we try to insert the cvterm. The db table
+  // has a unique constraint on the name so we'll always get a 1 or 0 returned
+  // by the ->find function.
+  $db = new ChadoRecord('db');
+  $db->setValues(['name' => $dbname]);
+  if (!$db->find()) {
+    $db->insert();
+  }  
+
+  // The cvterm table has two unique dependencies:
+  //
+  // 1) name, cv_id, is_obsolete columns must be unique
+  // 2) the dbxref_id column must be unique.
+  // 
+  // First, we'll make sure the first is unique.
+  $cvterm = new ChadoRecord('cvterm');
+  $cvterm->setValues([
     'name' => $name,
     'is_obsolete' => $is_obsolete,
-    'cv_id' => array(
-      'name' => $cvname,
-    ),
-  );
-  $result = chado_select_record('cvterm', array('*'), $values);
-  if (count($result) == 1) {
-    $cvterm = $result[0];
-
-    // Get the dbxref record.
-    $values = array('dbxref_id' => $cvterm->dbxref_id);
-    $result = chado_select_record('dbxref', array('*'), $values);
-    $dbxref = $result[0];
-    if (!$dbxref) {
-      tripal_report_error('tripal_cv', TRIPAL_ERROR,
-          'Unable to access the dbxref record for the :term cvterm. Term Record: !record',
-          array(':term' => $name, '!record' => print_r($cvterm, TRUE))
-      );
-      return FALSE;
-    }
-
-    // Get the db.
-    $values = array('db_id' => $dbxref->db_id);
-    $result = chado_select_record('db', array('*'), $values);
-    $db_check = $result[0];
-
-    //     // The database name for this existing term does not match that of the
-    //     // one provided to this function.  The CV name matches otherwise we
-    //     // wouldn't have made it this far. So, let's swap the database for
-    //     // this term.
-    //     if ($db_check->name != $db->name) {
-
-    //       // Look to see if the correct dbxref record already exists for this
-    //       // database.
-    //       $values = array(
-    //         'db_id' => $db->db_id,
-    //         'accession' => $accession,
-    //       );
-    //       $result = chado_select_record('dbxref', array('*'), $values);
-
-    //       // If we already have a good dbxref then we want to update our cvterm
-    //       // to use this dbxref.
-    //       if (count($result) > 0) {
-    //         $dbxref = $result[0];
-    //         $match = array('cvterm_id' => $cvterm->cvterm_id);
-    //         $values = array('dbxref_id' => $dbxref->dbxref_id);
-    //         $success = chado_update_record('cvterm', $match, $values);
-    //         if (!$success) {
-    //           tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to correct the dbxref id for the cvterm " .
-    //             "'$name' (id: $accession), for database $dbname", NULL);
-    //           return 0;
-    //         }
-    //       }
-    //       // If we don't have the dbxref then we want to delete our cvterm and let
-    //       // the code below recreate it with the correct info.
-    //       else {
-    //         $match = array('cvterm_id' => $cvterm->cvterm_id);
-    //         chado_delete_record('cvterm', $match);
-    //       }
-    //     }
-
-    // Check that the accession matches.  Sometimes an OBO can define a term
-    // multiple times but with different accessions.  If this is the case we
-    // can't do an insert or it will violate the constraint in the cvterm table.
-    // So we'll need to add the record to the cvterm_dbxref table instead.
-    if ($dbxref->accession != $accession) {
-
-      // Get/add the dbxref for his term.
-      $dbxref_new = chado_insert_dbxref(array(
-        'db_id' => $db->db_id,
-        'accession' => $accession
-      ));
-      if (!$dbxref_new) {
-        tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
-            "$name (id: $accession), for database $dbname", NULL);
-        return 0;
+    'cv_id' => $cv->getID(),
+  ]);
+  
+  // If we found a match?
+  if ($cvterm->find()) {
+    
+    // Sometimes an OBO can define a term multiple times but with different 
+    // accessions.  If this is the case we can't do an insert or it will 
+    // violate the constraint in the cvterm table. So we'll need to add a 
+    // new dbxref and update.
+    
+    // Get the dbxref record for this cvterm so we can check if the 
+    // accession may have changed.
+    $dbxref = new ChadoRecord('dbxref');
+    $dbxref->setValues(['dbxref_id' => $cvterm->getValue('dbxref_id')]);
+    $dbxref->find();
+
+    // Check that the accession matches.  
+    $accession_change = FALSE;
+    $db_check = new ChadoRecord('db');
+    $db_check->setValues(['db_id' => $dbxref->getValue('db_id')]);
+    $db_check->find();
+    if ($dbxref->getValue('accession') != $accession or 
+        $db_check->getValue('db_id') != $db->getValue('db_id')) {
+      
+      // We need a new dbxref record.
+      $dbxref = new ChadoRecord('dbxref');
+      $dbxref->setValues([
+        'accession' => $accession,
+        'db_id' => $db->getID()
+      ]);
+      if (!$dbxref->find()) {
+        $dbxref_new->insert();
       }
-
-      // Check to see if the cvterm_dbxref record already exists.
-      $values = array(
-        'cvterm_id' => $cvterm->cvterm_id,
-        'dbxref_id' => $dbxref_new->dbxref_id,
-        'is_for_definition' => 1,
-      );
-      $result = chado_select_record('cvterm_dbxref', array('*'), $values);
-
-      // if the cvterm_dbxref record does not exists then add it
-      if (count($result)==0) {
-        $options = array(
-          'return_record' => FALSE,
-        );
-        $success = chado_insert_record('cvterm_dbxref', $values, $options);
-        if (!$success) {
-          tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the cvterm_dbxref record for a " .
-              "duplicated cvterm:  $name (id: $accession), for database $dbname", NULL);
-          return 0;
+      else {
+        // If the dbxref already exists, check constraint #2.  Check to see if
+        // the dbxref is already used by another term.
+        $cvterm_check = new ChadoRecord('cvterm');
+        $cvterm_check->setValues(['dbxref_id' => $dbxref->getID()]);
+        if ($cvterm_check->find()) {
+          tripal_report_error('tripal_cv', TRIPAL_WARNING, "The dbxref, is already " .
+            "used by another cvterm record: '!other_cvterm'.  It ".
+            "cannot be used for updating the existing term: '!term'",
+            ['!other_cvterm' => $cvterm_check->getValue('name'), '!term' => $cvterm->getValue('name')]);
+          return FALSE;
         }
       }
-      // Get the original cvterm with the same name and return that.
-      $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
-      $cvterm = $result->fetchObject();
-      return $cvterm;
+      
+      // Update the dbxref for this record. 
+      $cvterm->setValue('dbxref_id', $dbxref->getID());
+      $accession_change == TRUE;
+    }
+    
+    // If this is an update then make the changes now.
+    if ($update) {
+      $cvterm->setValue('definition', $definition);
+      $cvterm->setValue('dbxref_id', $dbxref->getID());
+      $cvterm->setValue('is_relationshiptype', $is_relationship);
+    }
+    
+    if ($accession_change or $update) {
+      $cvterm->update();
     }
-    // Continue on, we've fixed the record if the db_id did not match.
-    // We can now perform and updated if we need to.
   }
-
-  // Get the CVterm record.
-  $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
-  $cvterm = $result->fetchObject();
-  if (!$cvterm) {
-
-    // Check to see if the dbxref exists if not, add it.
-    $dbxref = chado_insert_dbxref(array(
-      'db_id' => $db->db_id,
+  // If the cvterm does not already exist, then we need to create it.
+  else {
+    
+    // Save our new dbxref record that the cvterm will use.
+    $dbxref = new ChadoRecord('dbxref');
+    $dbxref->setValues([
+      'db_id' => $db->getValue('db_id'),
       'accession' => $accession
-    ));
-    if (!$dbxref) {
-      tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
-          "$name (id: $accession), for database $dbname", NULL);
-      return 0;
-    }
-
-    // Check to see if the dbxref already has an entry in the cvterm table.
-    $values = array('dbxref_id' => $dbxref->dbxref_id);
-    $check = chado_select_record('cvterm', array('cvterm_id'), $values);
-    if (count($check) == 0) {
-      // now add the cvterm
-      $ins_values = array(
-        'cv_id'                => $cv->cv_id,
-        'name'                 => $name,
-        'definition'           => $definition,
-        'dbxref_id'            => $dbxref->dbxref_id,
-        'is_obsolete'          => $is_obsolete,
-        'is_relationshiptype'  => $is_relationship,
-      );
-      $success = chado_insert_record('cvterm', $ins_values);
-      if (!$success) {
-        if (!$is_relationship) {
-          tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the term: $name ($dbname)", NULL);
-          return 0;
-        }
-        else {
-          tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)", NULL);
-          return 0;
-        }
-      }
+    ]);
+    if (!$dbxref->find()) {
+      $dbxref->insert();
     }
-    // This dbxref already exists in the cvterm table.
     else {
-      tripal_report_error('tripal_cv', TRIPAL_WARNING, "The dbxref already exists for another cvterm record: $name (cv: " . $cvname . " db: $dbname)", NULL);
-      return 0;
-    }
-    $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
-    $cvterm = $result->fetchObject();
-  }
-  // Update the cvterm.
-  elseif ($update) {
-
-    // First, basic update of the term.
-    $match = array('cvterm_id' => $cvterm->cvterm_id);
-    $upd_values = array(
-      'name'                => $name,
-      'definition'          => $definition,
-      'is_obsolete'         => $is_obsolete,
-      'is_relationshiptype' => $is_relationship,
-    );
-    $success = chado_update_record('cvterm', $match, $upd_values);
-    if (!$success) {
-      tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to update the term: $name", NULL);
-      return 0;
-    }
-
-    // Second, check that the dbxref has not changed and if it has then update 
-    // it.
-    $checksql = "
-      SELECT cvterm_id
-      FROM {cvterm} CVT
-        INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
-        INNER JOIN {db} DB on DBX.db_id = DB.db_id
-        INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
-      WHERE DBX.accession = :accession and DB.name = :dbname and CVT.name = :term and CV.name = :cvname
-    ";
-    $check = chado_query($checksql, array(':accession' => $accession, ':dbname' => $dbname, ':term' => $name, ':cvname' => $cvname))->fetchObject();
-    if (!$check) {
-
-      // Check to see if the dbxref exists if not, add it.
-      $dbxref = chado_insert_dbxref(array(
-        'db_id' => $db->db_id,
-        'accession' => $accession
-      ));
-      if (!$dbxref) {
-        tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
-            "$name (id: $accession), for database $dbname", NULL);
-        return 0;
-      }
-
-      $match = array('cvterm_id' => $cvterm->cvterm_id);
-      $upd_values = array(
-        'dbxref_id' => $dbxref->dbxref_id,
-      );
-      $success = chado_update_record('cvterm', $match, $upd_values);
-      if (!$success) {
-        tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the term $name with new accession $db:$accession", NULL);
-        return 0;
+      // If the dbxref already exists, check constraint #2.  Check to see if 
+      // the dbxref is already used by another term.
+      $cvterm_check = new ChadoRecord('cvterm');
+      $cvterm_check->setValues(['dbxref_id' => $dbxref->getID()]);
+      if ($cvterm_check->find()) {
+        tripal_report_error('tripal_cv', TRIPAL_WARNING, "The dbxref, is already " . 
+          "used by another cvterm record: '!other_cvterm'.  It ".
+          "cannot be used for new term: '!term'",
+          ['!other_cvterm' => $cvterm_check->getValue('name'), '!term' => $cvterm->getValue('name')]);
+        return FALSE;
       }
     }
-
-    // Finally grab the updated details.
-    $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
-    $cvterm = $result->fetchObject();
-  }
-  else {
-    // Do nothing, we have the cvterm but we don't want to update.
-  }
-  // Return the cvterm.
-  return $cvterm;
+    
+    // Add the other values to our cvterm object and then insert!
+    $cvterm->setValue('definition', $definition);
+    $cvterm->setValue('dbxref_id', $dbxref->getID());
+    $cvterm->setValue('is_relationshiptype', $is_relationship);
+    $cvterm->insert();
+  }
+  
+  // For backwards compatibility retrieve the new/updated cvterm.
+  $cvtermsql = "
+    SELECT CVT.name, CVT.cvterm_id, CV.cv_id, CV.name as cvname,
+      DB.name as dbname, DB.db_id, DBX.accession
+    FROM {cvterm} CVT
+      INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
+      INNER JOIN {db} DB on DBX.db_id = DB.db_id
+      INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
+    WHERE DBX.accession = :accession and DB.name = :name
+  ";
+  $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
+  return $result->fetchObject();
 }
 
 

+ 239 - 192
tripal_chado/includes/TripalImporter/OBOImporter.inc

@@ -343,7 +343,7 @@ class OBOImporter extends TripalImporter {
       $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $uobo_file;
       if (!file_exists($dfile)) {
         if (!file_exists($uobo_file)) {
-          form_set_error('uobo_file', 'The specified path does not exist or cannot be read.');
+          form_set_error('uobo_file', t('The specified path, !path, does not exist or cannot be read.'), ['!path' => $dfile]);
         }
       }
       if (!$uobo_url and !$uobo_file) {
@@ -367,7 +367,7 @@ class OBOImporter extends TripalImporter {
       $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo_file;
       if (!file_exists($dfile)) {
         if (!file_exists($obo_file)) {
-          form_set_error('obo_file', 'The specified path does not exist or cannot be read.');
+          form_set_error('obo_file', t('The specified path, !path, does not exist or cannot be read.'), ['!path' => $dfile]);
         }
       }
       if (!$obo_url and !$obo_file) {
@@ -739,6 +739,156 @@ class OBOImporter extends TripalImporter {
     $this->setItemsHandled($i);
     return 1;
   }
+  
+  /**
+   * A helper function to get details about a foreign term.
+   * 
+   * A foreign term is one that does not belong to the ontology.
+   * 
+   * @param $t
+   *   A term array that contains these keys at a minimum: id, name,
+   *   definition, subset, namepace, is_obsolete.
+   * @param $default_db
+   *   The default database.
+   */
+  private function _resolveTerm(&$t, $default_db) {
+    
+    // We only check terms that have proper accessions (ie. short_name:accession)
+    if (strpos($t['id'], ':') === FALSE) {
+      return NULL;
+    }
+    
+    // Get the short name and accession for the term.
+    $pair = explode(":", $t['id'], 2);
+    $short_name = $pair[0];
+    $accession_num = $pair[1];
+    
+    // If the short name is the same as the deafult database then this
+    // term belongs in this ontology and should be defined in the file. We
+    // don't need to look it up.
+    if ($short_name == $default_db) {
+      return NULL;
+    }
+  
+    // Before running the oboEbiLookup check for it in the local chado and
+    // the tripal_obo_temp table.
+    $sql = "
+      SELECT *
+      FROM {tripal_obo_temp} tot
+      WHERE tot.id = :term_id
+    ";
+    $result = chado_query($sql, array(':term_id' => $t['id'] . '_lookup'))->fetchObject();
+    $oterm = unserialize(base64_decode($result->stanza));
+    if ($oterm['label']) {
+      $t['name'] = $oterm['label'];
+      $t['definition'] = $oterm['def'];
+      $t['namepace'] = $oterm['ontology_name'];
+      $t['is_obsolete'] = $oterm['is_obsolete'];
+      $t['subset'] =  $oterm['subset'];
+      $t['db_name'] = $oterm['ontology_prefix'];
+      return TRUE;
+    }
+      
+    // Is the term in the local chado?
+    $sql = "SELECT * FROM {db} db WHERE db.name = :short_name ";
+    $db = chado_query($sql, array(':short_name' => $short_name))->fetchObject();
+    if (!empty($db)){
+      // Find the accession.
+      $sql = "
+          SELECT *
+          FROM {dbxref} dbx
+          WHERE dbx.db_id = :db_id
+          AND accession = :accession_num ";
+      $dbxref = chado_query($sql, array(':db_id' => $db->db_id, ':accession_num' => $accession_num))->fetchObject();
+      if (!empty($dbxref)) {
+        $sql = "
+          SELECT CVT.*, CV.name as namespace
+          FROM {cvterm} CVT
+            INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
+          WHERE dbxref_id = :dbxref_id
+        ";
+        $cvterm = chado_query($sql, [':dbxref_id' => $dbxref->dbxref_id])->fetchObject();
+        $t['name'] = $cvterm->name;
+        $t['definition'] = $cvterm->definition;
+        $t['namepace'] = $cvterm->namespace;
+        $t['is_obsolete'] = $cvterm->is_obsolete;
+        $t['db_name'] = $db->name;
+        return TRUE;
+      }
+    }
+    
+    // Check for the ID of the term in EBI.
+    $oterm = NULL;
+    $results = $this->oboEbiLookup($t['id'], 'term');
+    if (isset($results['label'])) {
+      $oterm = $results;
+    }
+    
+    // If we did not get a name for the term from a direct term
+    // lookup then let's try a query.,
+    if (!isset($results['label'])) {
+      $results = $this->oboEbiLookup($t['id'], 'query');
+      if (array_key_exists('docs', $results)) {
+        if (!empty($results['response']['docs'])) {
+          if (count($results['response']['docs']) > 1) {
+            foreach ($results['response']['docs'] as $doc) {
+              if ($doc['obo_id'] == $t['id']) {
+                $external = TRUE;
+                $oterm = $doc;
+              }
+            }
+          }
+          else {
+            $external = true;
+            $oterm = $results['response']['docs'][0];
+          }
+        }
+      }
+    }
+    
+    // If the accession could not be found in EBI.
+    if ($results['response']['numFound'] == 0 && !isset($results['label'])) {
+      // The first search doesn't work, so let's try a broader one.
+      $results = $this->oboEbiLookup($t['id'], 'query-non-local');
+      if (!empty($results)) {
+        if (array_key_exists('docs', $results)) {
+          if (!empty($results['docs'])) {
+            $accession = $t['id'];
+            $accession_underscore = str_replace(":", "_", $accession);
+            foreach ($results['response']['docs'] as $item) {
+              if ($item['label'] != $accession && $item['label'] != $accession_underscore) {
+                // Found the first place a label is other than the accession 
+                // is used, so take that info and then end the loop.
+                $external = TRUE;
+                $oterm = $item;
+                break;
+              }
+            }
+          }
+        }
+      }
+    }
+    
+    if ($oterm) {
+      $t['name'] = $oterm['label'];
+      $t['definition'] = $oterm['def'];
+      $t['namepace'] = $oterm['ontology_name'];
+      $t['is_obsolete'] = $oterm['is_obsolete'];
+      $t['subset'] =  $oterm['subset'];
+      $t['db_name'] = $oterm['ontology_prefix'];
+      
+      // Write the term to the tripal_obo_temp table for future reference
+      $values = array(
+        'id' => $term_id . '_lookup',
+        'stanza' => base64_encode(serialize($oterm)),
+        'type' => 'lookup',
+      );
+      chado_insert_record('tripal_obo_temp', $values);
+      return TRUE;
+    }
+    // TODO: we couldn't find the term. What do we do!!!
+    return FALSE;
+  }
 
   /**
    * Uses the provided term array to add/update information to Chado about the
@@ -906,7 +1056,7 @@ class OBOImporter extends TripalImporter {
       } 
     }
     
-    $cvterm = tripal_insert_cvterm($t, array('update_existing' => TRUE));
+    $cvterm = chado_insert_cvterm($t, array('update_existing' => TRUE));
     if (!$cvterm) {
       throw new Exception("Cannot add the term " . $term['id'][0]);
     }
@@ -1074,204 +1224,101 @@ class OBOImporter extends TripalImporter {
    */
   private function addRelationship($cvterm, $defaultcv, $rel,
       $objname, $object_is_relationship = 0, $default_db = 'OBO_REL') {
+            
     $reference_term = FALSE;
     $in_obo = $this->getTerm($objname);
-    // If an accession was passed we need to see if we can find the actual label.
-    if (strpos($rel, ':') || strpos($objname, ':') && empty($in_obo['name'])) {
-
-      if (strpos($rel, ':')) {
-        $term_id = $rel;
-      }
-      elseif (strpos($objname, ':')) {
-        $term_id = $objname;
-      }
-      $reference_term = TRUE;
-      $pair = explode(":", $term_id, 2);
-      $ontology_id = $pair[0];
-      $accession_num = $pair[1];
-      $rel_name = '';
-
-      if (is_numeric($accession_num)) {
-        // Before running the oboEbiLookup check for it in the local chado and
-        // the tripal_obo_temp table.
-        // $term_with_quotes = '"' . $term_id . '"';
-        $sql = " 
-          SELECT * 
-          FROM {tripal_obo_temp} tot
-          WHERE tot.id = :term_id 
-          ";
-        $result = chado_query($sql, array(':term_id' => $term_id . '_lookup'))->fetchObject();
-        $oterm = unserialize(base64_decode($result->stanza));
-        if (empty($oterm['label'])){
-
-          // Is this ontology is in the local chado?
-          $sql = "SELECT * FROM {db} db WHERE db.name = :ontology_id ";
-          $db = chado_query($sql, array(':ontology_id' => $ontology_id, ))->fetchObject();
-
-          if (!empty($db)){
-            // Find the accession.
-            $sql = "
-              SELECT * 
-              FROM {dbxref} dbx 
-              WHERE dbx.db_id = :db_id 
-              AND accession = :accession_num ";
-            $v = chado_query($sql, array(':db_id' => $db->db_id, ':accession_num' => $accession_num))->fetchObject();
-            if (!empty($dbxref)) {
-              $sql = "SELECT * FROM {cvterm} WHERE dbxref_id = $dbxref->dbxref_id ";
-              $oterm = chado_query($sql)->fetchObject();
-              $rel_name = $oterm->name;
-            }
-          }
-          
-          if (empty($dbxref)){
-            $results = $this->oboEbiLookup($term_id, 'term');
-            if (isset($results['label'])) {
-              $rel_name = $results['label'];
-              $oterm = $results;
-            }
-            if (empty($rel_name)) {
-              $results = $this->oboEbiLookup($term_id, 'query');
-              if (array_key_exists('docs', $results['response'])) {
-                if (!empty($results['response']['docs'])) {
-                  if (count($results['response']['docs']) > 1) {
-                    foreach ($results['response']['docs'] as $doc) {
-                      if ($doc['obo_id'] == $term_id) {
-                        $rel_name = $doc['label'];
-                        $oterm = $doc;
-                      }
-                    }
-                  } else {
-                    $rel_name = $results['response']['docs'][0]['label'];
-                    $oterm = $results['response']['docs'][0];
-                  }
-                }
-              }
-            }
-            if (empty($rel_name)) {
-          // The first search doesn't work, so let's try a broader one.
-              $results = $this->oboEbiLookup($term_id, 'query-non-local');
-              if (!empty($results)) {
-                if (array_key_exists('docs', $results['response'])) {
-                  if (!empty($results['response']['docs'])) {
-                    foreach ($results['response']['docs'] as $item) {
-                      if ($item['obo_id'] == $term_id) {
-                    //Found the first place a label is other than the accession is used, so take
-                    // that info and then end the loop.
-                        $rel_name = $item['label'];
-                        $oterm = $item;
-                        break;
-                      }
-                    }
-                  }
-                }
-              }
-            }
-          }
-          // Write the term to the tripal_obo_temp table for future reference
-          $values = array(
-            'id' => $term_id . '_lookup',
-            'stanza' => base64_encode(serialize($oterm)),
-            'type' => 'lookup',
-          );
-          chado_insert_record('tripal_obo_temp', $values);
-        }
-      }
-    }    
-    // Make sure the relationship cvterm exists.
-    $term = array(
-      'name' => $rel,
-      'id' => "$default_db:$rel",
-      'definition' => '',
-      'is_obsolete' => 0,
-      'cv_name' => $defaultcv,
-      'is_relationship' => TRUE,
-      'db_name' => $default_db
-    );
-    $relcvterm = tripal_insert_cvterm($term, array('update_existing' => FALSE));
-
-    if (!$relcvterm) {
-      // If the relationship term couldn't be found in the default_db provided
-      // then do on more check to find it in the relationship ontology
-      $term = array(
-        'name' => $rel,
-        'id' => "OBO_REL:$rel",
-        'definition' => '',
-        'is_obsolete' => 0,
-        'cv_name' => $defaultcv,
-        'is_relationship' => TRUE,
-        'db_name' => 'OBO_REL'
-      );
-      $relcvterm = tripal_insert_cvterm($term, array('update_existing' => FALSE));
+    
+    // If the relationship term or the relationship object are defined using
+    // accession IDs then we need to break them apart and look them up to get
+    // the term name.
+    if (strpos($rel, ':') || strpos($objname, ':') && empty($in_obo['name'])) {  
+    
+      // Make sure the relationship cvterm exists.
+      $term = [];
+      $term['name'] = $rel;
+      $term['id'] = "$default_db:$rel";
+      $term['definition'] = '';
+      $term['is_obsolete'] = 0;
+      $term['cv_name'] = $defaultcv;
+      $term['is_relationship'] = TRUE;
+      $term['db_name'] = $default_db;
+      
+      $this->_resolveTerm($term, $default_db);
+      print_r($term);
+      
+      $relcvterm = chado_insert_cvterm($term, array('update_existing' => FALSE));
       if (!$relcvterm) {
-        throw new Exception("Cannot find the relationship term in the current ontology or in the relationship ontology: $rel\n");
-      }
-    }
-
-    // Get the object term.
-    if ($reference_term === TRUE && !empty($oterm)) {
-      $objterm = array();
-      $objterm['id'] = $oterm['obo_id'];
-      $objterm['name'] = $oterm['label'];
-      if (array_key_exists('def', $oterm)) {
-        $objterm['definition'] = $oterm['def'];
-      }
-      if (array_key_exists('subset', $oterm)) {
-        $objterm['subset'] = $oterm['subset'];
-      }
-      if (array_key_exists('namespace', $oterm)) {
-        $objterm['namespace'] = $oterm['ontology_name'];
-      }
-      if (array_key_exists('is_obsolete', $oterm)) {
-        $objterm['is_obsolete'] = $oterm['is_obsolete'];
-      }
-    }
-    else {
-      $oterm = $this->getTerm($objname);
-      if (!$oterm) {
-        throw new Exception("Could not find object term $objname\n");
-      }
-      $objterm = array();
-      $objterm['id'] = $oterm['id'][0];
-      $objterm['name'] = $oterm['name'][0];
-      if (array_key_exists('def', $oterm)) {
-        $objterm['definition'] = $oterm['def'][0];
+        // If the relationship term couldn't be found in the default_db provided
+        // then do one more check to find it in the relationship ontology
+        $term = array(
+          'name' => $rel,
+          'id' => "OBO_REL:$rel",
+          'definition' => '',
+          'is_obsolete' => 0,
+          'cv_name' => $defaultcv,
+          'is_relationship' => TRUE,
+          'db_name' => 'OBO_REL'
+        );        
+        $relcvterm = tripal_insert_cvterm($term, array('update_existing' => FALSE));
+        if (!$relcvterm) {
+          throw new Exception("Cannot find the relationship term in the current ontology or in the relationship ontology: $rel\n");
+        }
       }
-      if (array_key_exists('subset', $oterm)) {
-        $objterm['subset'] = $oterm['subset'][0];
+  
+      // Try to resolve the object term.
+      $objterm = ['id' => $objname];
+      $found = $this->_resolveTerm($objterm, $default_db);
+      
+      // If the $found var is NULL it means the term does not need resolving as
+      // it's local to this ontology. In that case we can pull it from the
+      // obo lookup table.
+      if ($found === NULL) {
+        $oterm = $this->getTerm($objname);
+        if (!$oterm) {
+          throw new Exception("Could not find object term $objname\n");
+        }
+        $objterm = array();
+        $objterm['id'] = $oterm['id'][0];
+        $objterm['name'] = $oterm['name'][0];
+        if (array_key_exists('def', $oterm)) {
+          $objterm['definition'] = $oterm['def'][0];
+        }
+        if (array_key_exists('subset', $oterm)) {
+          $objterm['subset'] = $oterm['subset'][0];
+        }
+        if (array_key_exists('namespace', $oterm)) {
+          $objterm['namespace'] = $oterm['namespace'][0];
+        }
+        if (array_key_exists('is_obsolete', $oterm)) {
+          $objterm['is_obsolete'] = $oterm['is_obsolete'][0];
+        }
+        $t['db_name'] = $oterm['ontology_prefix'];
       }
-      if (array_key_exists('namespace', $oterm)) {
-        $objterm['namespace'] = $oterm['namespace'][0];
+  
+      $objterm['is_relationship'] = $object_is_relationship;
+  
+      $objcvterm = chado_insert_cvterm($objterm, array('update_existing' => TRUE));
+      if (!$objcvterm) {
+        throw new Exception("Cannot add cvterm '" . $objterm['name'] . "' (" . $objterm['id'] . ").");
       }
-      if (array_key_exists('is_obsolete', $oterm)) {
-        $objterm['is_obsolete'] = $oterm['is_obsolete'][0];
+  
+      // check to see if the cvterm_relationship already exists, if not add it
+      $values = array(
+        'type_id'    => $relcvterm->cvterm_id,
+        'subject_id' => $cvterm->cvterm_id,
+        'object_id'  => $objcvterm->cvterm_id
+      );
+      $result = chado_select_record('cvterm_relationship', array('*'), $values);
+      if (count($result) == 0) {
+        $options = array('return_record' => FALSE);
+        $success = chado_insert_record('cvterm_relationship', $values, $options);
+        if (!$success) {
+          throw new Exception("Cannot add term relationship: '$cvterm->name' $rel '$objcvterm->name'");
+        }
       }
-    }
-
-    $objterm['cv_name' ] = $defaultcv;
-    $objterm['is_relationship'] = $object_is_relationship;
-    $objterm['db_name'] = $default_db;
 
-    $objcvterm = chado_insert_cvterm($objterm, array('update_existing' => TRUE));
-    if (!$objcvterm) {
-      throw new Exception("Cannot add cvterm '" . $objterm['name'] . "' (" . $objterm['id'] . ").");
-    }
-
-    // check to see if the cvterm_relationship already exists, if not add it
-    $values = array(
-      'type_id'    => $relcvterm->cvterm_id,
-      'subject_id' => $cvterm->cvterm_id,
-      'object_id'  => $objcvterm->cvterm_id
-    );
-    $result = chado_select_record('cvterm_relationship', array('*'), $values);
-    if (count($result) == 0) {
-      $options = array('return_record' => FALSE);
-      $success = chado_insert_record('cvterm_relationship', $values, $options);
-      if (!$success) {
-        throw new Exception("Cannot add term relationship: '$cvterm->name' $rel '$objcvterm->name'");
-      }
+      return TRUE;
     }
-
-    return TRUE;
   }
 
   /**

+ 2 - 0
tripal_chado/tripal_chado.module

@@ -36,6 +36,8 @@ require_once 'api/tripal_chado.schema_v1.11.api.inc';
 require_once 'api/tripal_chado.semweb.api.inc';
 require_once 'api/tripal_chado.migrate.api.inc';
 require_once 'api/tripal_chado.DEPRECATED.api.inc';
+require_once 'api/ChadoRecord.inc';
+
 
 // Chado module specific API functions
 require_once 'api/modules/tripal_chado.analysis.api.inc';