tripal_cv.api.inc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. <?php
  2. /**
  3. * @file
  4. * This module provides a set of functions to simplify working with
  5. * controlled vocabularies.
  6. */
  7. /**
  8. * @defgroup tripal_cv_api Controlled Vocabulary API
  9. * @ingroup tripal_api
  10. * This module provides a set of functions to simplify working with
  11. * controlled vocabularies. Most of the API functions deal with retrieving
  12. * terms or their parent vocabularies.
  13. *
  14. * However, the API also supports
  15. * generation of trees for browsing a vocabulary as well as generation of
  16. * pie graphs for display of hierarchical counts of terms. Version 0.3b of
  17. * Tripal provides a feature browser and a feature summary chart uses
  18. * the API functions provided here. But in general charts and trees can be
  19. * created for any controlled vocabulary.
  20. *
  21. */
  22. /**
  23. * Retrieves a chado controlled vocabulary object
  24. *
  25. * @param $identifier
  26. * An array with the key stating what the identifier is. Supported keys (only on of the
  27. * following unique keys is required):
  28. * - cv_id: the chado cv.cv_id primary key
  29. * - name: the chado cv.name field (assume unique)
  30. * @param $options
  31. * An array of options. Supported keys include:
  32. * - Any keys supported by chado_generate_var(). See that function definition for
  33. * additional details.
  34. *
  35. * NOTE: the $identifier parameter can really be any array similar to $values passed into
  36. * chado_select_record(). It should fully specify the cv record to be returned.
  37. *
  38. * @return
  39. * If unique values were passed in as an identifier then an object describing the cv
  40. * will be returned (will be a chado variable from chado_generate_var()). Otherwise,
  41. * FALSE will be returned.
  42. *
  43. * @ingroup tripal_cv_api
  44. */
  45. function chado_get_cv($identifiers, $options = array()) {
  46. // Error Checking of parameters
  47. if (!is_array($identifiers)) {
  48. tripal_report_error(
  49. 'tripal_cv_api',
  50. TRIPAL_ERROR,
  51. "chado_get_cv: The identifier passed in is expected to be an array with the key
  52. matching a column name in the cv table (ie: cv_id or name). You passed in %identifier.",
  53. array(
  54. '%identifier'=> print_r($identifiers, TRUE)
  55. )
  56. );
  57. }
  58. elseif (empty($identifiers)) {
  59. tripal_report_error(
  60. 'tripal_cv_api',
  61. TRIPAL_ERROR,
  62. "chado_get_cv: You did not pass in anything to identify the cv you want. The identifier
  63. is expected to be an array with the key matching a column name in the cv table
  64. (ie: cv_id or name). You passed in %identifier.",
  65. array(
  66. '%identifier'=> print_r($identifiers, TRUE)
  67. )
  68. );
  69. }
  70. // Try to get the cv
  71. $cv = chado_generate_var(
  72. 'cv',
  73. $identifiers,
  74. $options
  75. );
  76. // Ensure the cv is singular. If it's an array then it is not singular
  77. if (is_array($cv)) {
  78. tripal_report_error(
  79. 'tripal_cv_api',
  80. TRIPAL_ERROR,
  81. "chado_get_cv: The identifiers you passed in were not unique. You passed in %identifier.",
  82. array(
  83. '%identifier'=> print_r($identifiers, TRUE)
  84. )
  85. );
  86. }
  87. // Report an error if $cv is FALSE since then chado_generate_var has failed
  88. elseif ($cv === FALSE) {
  89. tripal_report_error(
  90. 'tripal_cv_api',
  91. TRIPAL_ERROR,
  92. "chado_get_cv: chado_generate_var() failed to return a cv based on the identifiers
  93. you passed in. You should check that your identifiers are correct, as well as, look
  94. for a chado_generate_var error for additional clues. You passed in %identifier.",
  95. array(
  96. '%identifier'=> print_r($identifiers, TRUE)
  97. )
  98. );
  99. }
  100. // Else, as far we know, everything is fine so give them their cv :)
  101. else {
  102. return $cv;
  103. }
  104. }
  105. /**
  106. * Create an options array to be used in a form element which provides a
  107. * list of all chado cvs
  108. *
  109. * @return
  110. * An array(cv_id => name) for each cv in the chado cv table
  111. *
  112. * @ingroup tripal_cv_api
  113. */
  114. function cv_get_select_options() {
  115. $results = chado_select_record('cv', array('cv_id', 'name'), array());
  116. $options = array();
  117. foreach ($results as $r) {
  118. $options[$r->cv_id] = $r->name;
  119. }
  120. return $options;
  121. }
  122. /**
  123. * Retrieves a chado controlled vocabulary term object
  124. *
  125. * @param $identifier
  126. * An array for uniquely selecting a cvterm. It is compatible with chado_generate_var
  127. * and chado_select_record functions. To uniquely identify a cvterm, specify either
  128. * a 'cvterm_id' key or a 'cv_id' and 'name' keys. Additionally, to find a cvterm
  129. * using a synonym, use a 'synonym' key which is an array with the following keys:
  130. * 'name' (the name of the synonym) and either 'cv_id' (the cv_id of the synonym) or
  131. * 'cv_name' (the name of the cv of the synonym)
  132. * @param $options
  133. * An array of options. Supported keys include:
  134. * - Any keys supported by chado_generate_var(). See that function definition for
  135. * additional details.
  136. *
  137. * NOTE: the $identifier parameter can really be any array similar to $values passed into
  138. * chado_select_record(). It should fully specify the cvterm record to be returned.
  139. *
  140. * @return
  141. * If unique values were passed in as an identifier then an object describing the cvterm
  142. * will be returned (will be a chado variable from chado_generate_var()). Otherwise,
  143. * FALSE will be returned.
  144. *
  145. * @ingroup tripal_cv_api
  146. */
  147. function chado_get_cvterm($identifiers, $options = array()) {
  148. // Error Checking of parameters
  149. if (!is_array($identifiers)) {
  150. tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
  151. "chado_get_cvterm: The identifier passed in is expected to be an array with the key
  152. matching a column name in the cvterm table (ie: cvterm_id or name). You passed in %identifier.",
  153. array('%identifier'=> print_r($identifiers, TRUE))
  154. );
  155. }
  156. elseif (empty($identifiers)) {
  157. tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
  158. "chado_get_cvterm: You did not pass in anything to identify the cvterm you want. The identifier
  159. is expected to be an array with the key matching a column name in the cvterm table
  160. (ie: cvterm_id or name). You passed in %identifier.",
  161. array('%identifier'=> print_r($identifiers, TRUE))
  162. );
  163. }
  164. // If synonym was passed in, then process this first before calling chado_generate_var()
  165. if (array_key_exists('synonym', $identifiers)) {
  166. $sname = $identifiers['synonym']['name'];
  167. $values = array('synonym' => $sname);
  168. if (array_key_exists('cv_id', $identifiers['synonym'])) {
  169. $values['cvterm_id'] = array('cv_id' => $identifiers['synonym']['cv_id']);
  170. }
  171. if (array_key_exists('cv_name', $identifiers['synonym'])) {
  172. $values['cvterm_id'] = array('cv_id' => array('name' => $identifiers['synonym']['cv_name']));
  173. }
  174. $options = array('case_insensitive_columns' => array('name'));
  175. $synonym = chado_select_record('cvtermsynonym', array('cvterm_id'), $values, $options);
  176. // if the synonym doens't exist or more than one record is returned then return false
  177. if (count($synonym) == 0) {
  178. return FALSE;
  179. }
  180. if (count($synonym) > 1) {
  181. return FALSE;
  182. }
  183. $identifiers = array('cvterm_id' => $synonym[0]->cvterm_id);
  184. }
  185. // Try to get the cvterm
  186. $cvterm = chado_generate_var('cvterm', $identifiers, $options);
  187. // Ensure the cvterm is singular. If it's an array then it is not singular
  188. if (is_array($cvterm)) {
  189. tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
  190. "chado_get_cvterm: The identifiers you passed in were not unique. You passed in %identifier.",
  191. array('%identifier'=> print_r($identifiers, TRUE))
  192. );
  193. }
  194. // Report an error if $cvterm is FALSE since then chado_generate_var has failed
  195. elseif ($cvterm === FALSE) {
  196. tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
  197. "chado_get_cvterm: chado_generate_var() failed to return a cvterm based on the identifiers
  198. you passed in. You should check that your identifiers are correct, as well as, look
  199. for a chado_generate_var error for additional clues. You passed in %identifier.",
  200. array('%identifier'=> print_r($identifiers, TRUE))
  201. );
  202. }
  203. // Else, as far we know, everything is fine so give them their cvterm :)
  204. else {
  205. return $cvterm;
  206. }
  207. }
  208. /**
  209. * Create an options array to be used in a form element
  210. * which provides a list of all chado cvterms
  211. *
  212. * @param $cv_id
  213. * The chado cv_id;
  214. * only cvterms with the supplied cv_id will be returned
  215. * @return
  216. * An array(cvterm_id => name)
  217. * for each cvterm in the chado cvterm table where cv_id=that supplied
  218. *
  219. * @ingroup tripal_cv_api
  220. */
  221. function cvterm_get_select_options($cv_id = 0) {
  222. if ($cv_id > 0) {
  223. $results = chado_select_record('cvterm', array('cvterm_id', 'name'), array('cv_id' => $cv_id));
  224. }
  225. else {
  226. $results = chado_select_record('cvterm', array('cvterm_id', 'name'), array());
  227. }
  228. $options = array();
  229. foreach ($results as $r) {
  230. $options[$r->cvterm_id] = $r->name;
  231. }
  232. return $options;
  233. }
  234. /**
  235. * Updates the cvtermpath table of Chado for the specified CV.
  236. *
  237. * @param $cv_id
  238. * The chado cv_id;
  239. * @param $job_id
  240. * This function is intended to be used with the Tripal Jobs API.
  241. * When this function is called as a job the $job_id is automatically
  242. * passed to this function.
  243. * @return
  244. * TRUE on success FALSE on failure
  245. *
  246. * @ingroup tripal_cv_api
  247. */
  248. function chado_update_cvtermpath($cvid, $job_id = NULL) {
  249. // TODO: need better error checking in this function
  250. // first get the controlled vocabulary name:
  251. $sql = "SELECT * FROM {cv} WHERE cv_id = :cv_id";
  252. $cv = chado_query($sql, array(':cv_id' => $cvid))->fetchObject();
  253. print "\nUpdating cvtermpath for $cv->name...\n";
  254. $previous = chado_set_active('chado');
  255. try {
  256. $sql = "SELECT * FROM fill_cvtermpath(:name)";
  257. db_query($sql, array(':name' => $cv->name));
  258. chado_set_active($previous);
  259. }
  260. catch (Exception $e) {
  261. chado_set_active($previous);
  262. $error = $e->getMessage();
  263. tripal_report_error('tripal_cv', TRIPAL_ERROR, "Could not fill cvtermpath table: @error", array('@error' => $error));
  264. return FALSE;
  265. }
  266. return TRUE;
  267. }
  268. /**
  269. * Adds a controlled vocabular to the CV table of Chado.
  270. *
  271. * @param $name
  272. * The name of the controlled vocabulary. These are typically all lower case
  273. * with no special characters other than an undrescore (for spaces).
  274. * @param $comment
  275. * A description or definition of the vocabulary.
  276. *
  277. * @return
  278. * An object populated with fields from the newly added database.
  279. *
  280. * @ingroup tripal_cv_api
  281. */
  282. function chado_insert_cv($name, $definition) {
  283. // insert/update values
  284. $ins_values = array(
  285. 'name' => $name,
  286. 'definition' => $definition
  287. );
  288. // see if the CV (default-namespace) exists already in the database
  289. $sel_values = array('name' => $name);
  290. $sel_options = array('statement_name' => 'sel_cv_na');
  291. $results = chado_select_record('cv', array('*'), $sel_values, $sel_options);
  292. // if it does not exists then add it
  293. if (count($results) == 0) {
  294. $ins_options = array('statement_name' => 'ins_cv_nade');
  295. $success = chado_insert_record('cv', $ins_values, $ins_options);
  296. if (!$success) {
  297. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to create the CV record", NULL);
  298. return FALSE;
  299. }
  300. $results = chado_select_record('cv', array('*'), $sel_values, $sel_options);
  301. }
  302. // if it already exists then do an update
  303. else {
  304. $upd_options = array('statement_name' => 'upd_cv_nade');
  305. $success = chado_update_record('cv', $sel_values, $ins_values, $upd_options);
  306. if (!$success) {
  307. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to update the CV record", NULL);
  308. return FALSE;
  309. }
  310. $results = chado_select_record('cv', array('*'), $sel_values, $sel_options);
  311. }
  312. // return the cv object
  313. return $results[0];
  314. }
  315. /**
  316. * Add's a controlled vocabulary term to the cvterm table.
  317. *
  318. * If the parent CV does not exist then
  319. * that too is added to the CV table. If the cvterm is a relationship term
  320. * then the $is_relationship argument should be set. The function will try
  321. * to first find the relationship in the relationship ontology for updating and
  322. * if it can't be found will add the relationship to the __global CV. All terms
  323. * must also have a corresponding database. This is specified in the term's
  324. * ID just before the colon (e.g. GO:003824). If the database does not exist
  325. * in the DB table then it will be added automatically. The accession (the
  326. * value just after the colon in the term's ID) will be added to the dbxref
  327. * table. If the CVterm already exists and $update is set (default) then the
  328. * cvterm is updated. If the CVTerm already exists and $update is not set, then
  329. * no changes are made and the CVTerm object is returned.
  330. *
  331. * @param $term
  332. * An associative array with the following keys:
  333. * - id: the term accession. must be of the form <DB>:<ACCESSION>, where <DB> is the
  334. * name of the database to which the cvterm belongs and the <ACCESSION> is the
  335. * term's accession number in the database.
  336. * - name: the name of the term. usually meant to be human-readable.
  337. * - namespace: the CV name for the term. DEPRECATED. Please use cv_name instead.
  338. * - is_obsolete: is present and set to 1 if the term is defunct
  339. * - definition: the definition of the term
  340. * - cv_name: The CV name to which the term belongs. If this arugment is null or not
  341. * provided then the function tries to find a record in the CV table with the same
  342. * name provided in the $term[namespace]. If this field is provided then it
  343. * overrides what the value in $term[namespace]
  344. * - is_relationship: If this term is a relationship term then this value should be 1.
  345. * _ db_name: In some cases the database name will not be part of the $term['id'] and it
  346. * needs to be explicitly set. Use this argument only if the database name
  347. * cannot be specififed in the term ID (e.g. <DB>:<ACCESSION>).
  348. * @param $options
  349. * - update_existing: By default this is TRUE. If the term exists it is automatically updated.
  350. *
  351. * @return
  352. * A CVTerm object
  353. *
  354. * @ingroup tripal_cv_api
  355. */
  356. function chado_insert_cvterm($term, $options) {
  357. // Set Defaults
  358. if (isset($term['cv_name'])) {
  359. $defaultcv = $term['cv_name'];
  360. }
  361. else {
  362. $defaultcv = '_global';
  363. }
  364. if (isset($term['is_relationship'])) {
  365. $is_relationship = $term['is_relationship'];
  366. }
  367. else {
  368. $is_relationship = 0;
  369. }
  370. if (isset($term['db_name'])) {
  371. $dbname = $term['db_name'];
  372. }
  373. else {
  374. $dbname = 'internal';
  375. }
  376. if (isset($options['update_existing'])) {
  377. $update = $options['update_existing'];
  378. }
  379. else {
  380. $update = 1;
  381. }
  382. // get the term properties
  383. $id = $term['id'];
  384. $name = '';
  385. $cvname = '';
  386. $definition = '';
  387. $is_obsolete = 0;
  388. $accession = '';
  389. if (array_key_exists('name', $term)) {
  390. $name = $term['name'];
  391. }
  392. else {
  393. $name = $id;
  394. }
  395. if (array_key_exists('namespace', $term)) {
  396. $cvname = $term['namespace'];
  397. }
  398. else {
  399. $cvname = $defaultcv;
  400. }
  401. if (array_key_exists('definition', $term)) {
  402. $definition = preg_replace('/^\"(.*)\"/', '\1', $term['definition']);
  403. }
  404. else {
  405. $definition = '';
  406. }
  407. if (array_key_exists('is_obsolete', $term)) {
  408. $is_obsolete = $term['is_obsolete'];
  409. if (strcmp($is_obsolete, 'true') == 0) {
  410. $is_obsolete = 1;
  411. }
  412. }
  413. if (!$name and !$id) {
  414. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find cvterm without 'id' or 'name'", NULL);
  415. return 0;
  416. }
  417. if (!$id) {
  418. $id = $name;
  419. }
  420. // get the accession and the database from the cvterm id
  421. if ($dbname) {
  422. $accession = $id;
  423. }
  424. if (preg_match('/^.+?:.*$/', $id)) {
  425. $accession = preg_replace('/^.+?:(.*)$/', '\1', $id);
  426. $dbname = preg_replace('/^(.+?):.*$/', '\1', $id);
  427. }
  428. // check that we have a database name, give a different message if it's a relationship
  429. if ($is_relationship and !$dbname) {
  430. tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database name is not provided for this relationship term: $id", NULL);
  431. return 0;
  432. }
  433. if (!$is_relationship and !$dbname) {
  434. tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database identifier is missing from the term: $id", NULL);
  435. return 0;
  436. }
  437. // make sure the CV name exists
  438. $cv = tripal_cv_get_cv_by_name($cvname);
  439. if (!$cv) {
  440. $cv = tripal_cv_add_cv($cvname, '');
  441. }
  442. if (!$cv) {
  443. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find namespace '$cvname' when adding/updating $id", NULL);
  444. return 0;
  445. }
  446. // this SQL statement will be used a lot to find a cvterm so just set it
  447. // here for easy reference below. Because CV terms can change their names
  448. // but accessions don't change, the following SQL finds cvterms based on
  449. // their accession rather than the name
  450. $cvtermsql = "
  451. SELECT CVT.name, CVT.cvterm_id, CV.cv_id, CV.name as cvname,
  452. DB.name as dbname, DB.db_id, DBX.accession
  453. FROM {cvterm} CVT
  454. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  455. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  456. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  457. WHERE DBX.accession = :accession and DB.name = :name
  458. ";
  459. // add the database. The function will just return the DB object if the
  460. // database already exists.
  461. $db = tripal_db_get_db_by_name($dbname);
  462. if (!$db) {
  463. $db = tripal_db_add_db($dbname);
  464. }
  465. if (!$db) {
  466. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find database '$dbname' in Chado.", NULL);
  467. return 0;
  468. }
  469. // the cvterm table has two unique dependencies. We need to check both.
  470. // first check the (name, cv_id, is_obsolete) constraint
  471. $values = array(
  472. 'name' => $name,
  473. 'is_obsolete' => $is_obsolete,
  474. 'cv_id' => array(
  475. 'name' => $cvname,
  476. ),
  477. );
  478. $options = array('statement_name' => 'sel_cvterm_c1');
  479. $result = chado_select_record('cvterm', array('*'), $values, $options);
  480. // if the constraint is met then let's check it to see if
  481. // the database name matches the one we have been provided
  482. if (count($result) == 1) {
  483. $cvterm = $result[0];
  484. // get the dbxref record
  485. $values = array('dbxref_id' => $cvterm->dbxref_id);
  486. $options = array('statement_name' => 'sel_dbxref_id');
  487. $result = chado_select_record('dbxref', array('*'), $values, $options);
  488. $dbxref = $result[0];
  489. // get the db
  490. $values = array('db_id' => $dbxref->db_id);
  491. $options = array('statement_name' => 'sel_db_id');
  492. $result = chado_select_record('db', array('*'), $values, $options);
  493. $db_check = $result[0];
  494. // the database name for this existing term does not match that of the
  495. // one provided to this function. The CV name matches otherwise we
  496. // wouldn't have made it this far. So, let's swap the database for
  497. // this term
  498. if ($db_check->name != $db->name) {
  499. // look to see if the correct dbxref record already exists for this database
  500. $values = array(
  501. 'db_id' => $db->db_id,
  502. 'accession' => $accession,
  503. );
  504. $options = array('statement_name' => 'sel_dbxref_idac');
  505. $result = chado_select_record('dbxref', array('*'), $values, $options);
  506. // if we already have a good dbxref then we want to update our cvterm
  507. // to use this dbxref
  508. if (count($result) > 0) {
  509. $dbxref = $result[0];
  510. $match = array('cvterm_id' => $cvterm->cvterm_id);
  511. $values = array('dbxref_id' => $dbxref->dbxref_id);
  512. $options = array('statement_name' => 'upd_cvterm_db');
  513. $success = chado_update_record('cvterm', $match, $values, $options);
  514. if (!$success) {
  515. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to correct the dbxref id for the cvterm " .
  516. "'$name' (id: $accession), for database $dbname", NULL);
  517. return 0;
  518. }
  519. }
  520. // if we don't have the record then we want to delete our cvterm and let the code
  521. // below recreate it with the correct info
  522. else {
  523. $match = array('cvterm_id' => $cvterm->cvterm_id);
  524. $options = array('statement_name' => 'del_cvterm_cv');
  525. chado_delete_record('cvterm', $match, $options);
  526. }
  527. }
  528. // check that the accession matches. Sometimes an OBO can define the same term
  529. // multiple times but with different accessions. If this is the case we
  530. // can't do an insert or it will violate the constraint in the cvterm table.
  531. // so we'll need to add the record to the cvterm_dbxref table instead
  532. if ($dbxref->accession != $accession) {
  533. // get/add the dbxref fort his term
  534. $dbxref_new = tripal_db_add_dbxref($db->db_id, $accession);
  535. if (!$dbxref_new) {
  536. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  537. "$name (id: $accession), for database $dbname", NULL);
  538. return 0;
  539. }
  540. // check to see if the cvterm_dbxref record already exists
  541. $values = array(
  542. 'cvterm_id' => $cvterm->cvterm_id,
  543. 'dbxref_id' => $dbxref_new->dbxref_id,
  544. 'is_for_definition' => 1,
  545. );
  546. $options = array('statement_name' => 'sel_cvtermdbxref_cvdbis');
  547. $result = chado_select_record('cvterm_dbxref', array('*'), $values, $options);
  548. // if the cvterm_dbxref record does not exists then add it
  549. if (count($result)==0) {
  550. $options = array(
  551. 'statement_name' => 'ins_cvtermdbxref_cvdbis',
  552. 'return_record' => FALSE,
  553. );
  554. $success = chado_insert_record('cvterm_dbxref', $values, $options);
  555. if (!$success) {
  556. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the cvterm_dbxref record for a " .
  557. "duplicated cvterm: $name (id: $accession), for database $dbname", NULL);
  558. return 0;
  559. }
  560. }
  561. // get the original cvterm with the same name and return that.
  562. $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
  563. $cvterm = $result->fetchObject();
  564. return $cvterm;
  565. }
  566. // continue on, we've fixed the record if the db_id did not match,
  567. // we can now perform and updated if we need to.
  568. }
  569. // get the CVterm record
  570. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  571. $cvterm = $result->fetchObject();
  572. if (!$cvterm) {
  573. // check to see if the dbxref exists if not, add it
  574. $dbxref = tripal_db_add_dbxref($db->db_id, $accession);
  575. if (!$dbxref) {
  576. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  577. "$name (id: $accession), for database $dbname", NULL);
  578. return 0;
  579. }
  580. // check to see if the dbxref already has an entry in the cvterm table
  581. // this is the second constraint in the cvterm table
  582. $values = array('dbxref_id' => $dbxref->dbxref_id);
  583. $options = array('statement_name' => 'sel_cvterm_db');
  584. $check = chado_select_record('cvterm', array('cvterm_id'), $values, $options);
  585. if (count($check) == 0) {
  586. // now add the cvterm
  587. $ins_values = array(
  588. 'cv_id' => $cv->cv_id,
  589. 'name' => $name,
  590. 'definition' => $definition,
  591. 'dbxref_id' => $dbxref->dbxref_id,
  592. 'is_obsolete' => $is_obsolete,
  593. 'is_relationshiptype' => $is_relationship,
  594. );
  595. $ins_options = array('statement_name' => 'ins_cvterm_all');
  596. $success = chado_insert_record('cvterm', $ins_values, $ins_options);
  597. if (!$success) {
  598. if (!$is_relationship) {
  599. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the term: $name ($dbname)", NULL);
  600. return 0;
  601. }
  602. else {
  603. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)", NULL);
  604. return 0;
  605. }
  606. }
  607. }
  608. // this dbxref already exists in the cvterm table
  609. else {
  610. tripal_report_error('tripal_cv', TRIPAL_WARNING, "The dbxref already exists for another cvterm record: $name (cv: " . $cvname . " db: $dbname)", NULL);
  611. return 0;
  612. }
  613. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  614. $cvterm = $result->fetchObject();
  615. }
  616. // upate the cvterm
  617. elseif ($update) {
  618. $match = array('cvterm_id' => $cvterm->cvterm_id);
  619. $upd_values = array(
  620. 'name' => $name,
  621. 'definition' => $definition,
  622. 'is_obsolete' => $is_obsolete,
  623. 'is_relationshiptype' => $is_relationship,
  624. );
  625. $upd_options = array('statement_name' => 'upd_cvterm_nadeisis');
  626. $success = chado_update_record('cvterm', $match, $upd_values, $upd_options);
  627. if (!$success) {
  628. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to update the term: $name", NULL);
  629. return 0;
  630. }
  631. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  632. $cvterm = $result->fetchObject();
  633. }
  634. else {
  635. // do nothing, we have the cvterm but we don't want to update
  636. }
  637. // return the cvterm
  638. return $cvterm;
  639. }
  640. /**
  641. * This function allows other modules to programatically
  642. * submit an ontology for loading into Chado.
  643. *
  644. * This function will add a job to the Jobs subsystem for parsing the ontology.
  645. * You can either pass a known OBO ID to the function or the URL
  646. * or full path the the ontology file. If a URL or file name is
  647. * passed then the $obo_name argument must also be provided. If
  648. * this is the first time the ontology has been provided to Tripal
  649. * then it will be added to the database and will be assigned a
  650. * unique OBO ID.
  651. *
  652. * @param $obo_id
  653. * If the ontology is already loaded into the Tripal tables then
  654. * use this argument to specify the unique ID for the ontology
  655. * that will be loaded
  656. * @param $obo_name
  657. * If the OBO has not been added before then use this argument
  658. * to specify the human readable name of the ontology.
  659. * @param $obo_url
  660. * If the OBO to be loaded is located on a remote server then
  661. * use this argument to provide the URL.
  662. * @param $obo_file
  663. * If the OBO is housed on the local file system of the server then
  664. * use this argument to specify the full path.
  665. *
  666. * @return
  667. * returns the job_id of the submitted job or FALSE if the job was not added
  668. *
  669. * @ingroup tripal_cv_api
  670. */
  671. function tripal_submit_obo_job($obo) {
  672. global $user;
  673. // Set Defaults
  674. $obo['obo_id'] = (isset($obo['obo_id'])) ? $obo['obo_id'] : NULL;
  675. $obo['name'] = (isset($obo['name'])) ? $obo['name'] : NULL;
  676. $obo['url'] = (isset($obo['url'])) ? $obo['url'] : NULL;
  677. $obo['file'] = (isset($obo['file'])) ? $obo['file'] : NULL;
  678. if ($obo['obo_id']) {
  679. $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = :obo_id";
  680. $obo = db_query($sql, array(':obo_id' => $obo['obo_id']))->fetchObject();
  681. $args = array($obo['obo_id']);
  682. return tripal_add_job("Load OBO $obo->name", 'tripal_cv',
  683. "tripal_cv_load_obo_v1_2_id", $args, $user->uid);
  684. }
  685. else {
  686. if ($obo['url']) {
  687. $args = array($obo['name'], $obo['url']);
  688. return tripal_add_job("Load OBO $obo_name", 'tripal_cv',
  689. "tripal_cv_load_obo_v1_2_url", $args, $user->uid);
  690. }
  691. elseif ($obo['file']) {
  692. $args = array($obo['name'], $obo['file']);
  693. return tripal_add_job("Load OBO $obo_name", 'tripal_cv',
  694. "tripal_cv_load_obo_v1_2_file", $args, $user->uid);
  695. }
  696. }
  697. return FALSE;
  698. }
  699. /**
  700. * Add the obo to the tripal_cv_obo table in the Drupal database
  701. *
  702. * @param $name
  703. * The human readable name of this ontology
  704. * @param $path
  705. * The file path or URL of the ontology
  706. *
  707. * @return
  708. * Returns the ontology ID
  709. *
  710. * @ingroup tripal_cv_api
  711. */
  712. function tripal_insert_obo($name, $path) {
  713. $record = new stdClass;
  714. $record->name = $name;
  715. $record->path = $path;
  716. drupal_write_record('tripal_cv_obo', $record);
  717. return $record->obo_id;
  718. }
  719. /**
  720. * This function is intended to be used in autocomplete forms
  721. * for searching for CV terms that begin with the provided string
  722. *
  723. * @param $cv_id
  724. * The CV ID in which to search for the term
  725. * @param $string
  726. * The string to search for
  727. *
  728. * @return
  729. * A json array of terms that begin with the provided string
  730. *
  731. * @ingroup tripal_cv_api
  732. */
  733. function chado_cvterm_autocomplete($cv_id, $string = '') {
  734. $sql = "
  735. SELECT cvterm_id, name
  736. FROM {cvterm}
  737. WHERE cv_id = :cv_id and name like :name
  738. ORDER by name
  739. LIMIT 25 OFFSET 0
  740. ";
  741. $results = chado_query($sql, array(':cv_id' => $cv_id, ':name' => $string . '%'));
  742. $items = array();
  743. foreach ($results as $term) {
  744. $items[$term->name] = $term->name;
  745. }
  746. drupal_json_output($items);
  747. }
  748. /**
  749. * Add a record to a cvterm linking table (ie: feature_cvterm)
  750. *
  751. * @param $basetable
  752. * The base table to which the cvterm should be linked/associated. Thus to associate a
  753. * cvterm to a feature the basetable=feature and cvterm_id is added to the feature_cvterm table.
  754. * @param $record_id
  755. * The primary key of the basetable to associate the cvterm with. This should be in integer.
  756. * @param $cvterm
  757. * An associative array describing the cvterm. Valid keys include: 'name' => the
  758. * name for the cvterm, 'cv_name' => the name of the cv the cvterm belongs to;
  759. * 'cv_id' => the primary key of the cv the cvterm belongs to.
  760. * @param $options
  761. * An associative array of options. Valid keys include:
  762. * - insert_cvterm: Insert the cvterm if it doesn't already exist. FALSE is the default
  763. *
  764. * @ingroup tripal_db_api
  765. */
  766. function chado_associate_cvterm($basetable, $record_id, $cvterm) {
  767. $linking_table = $basetable . '_cvterm';
  768. $foreignkey_name = $basetable . '_id';
  769. // Default Values
  770. $options['insert_cvterm'] = (isset($options['insert_cvterm'])) ? $options['insert_cvterm'] : FALSE;
  771. // If the cvterm_id is set then we know it already exists
  772. // Otherwise, select to check
  773. if (!isset($cvterm['cvterm_id'])) {
  774. $values = array(
  775. 'name' => $cvterm['name'],
  776. );
  777. if (isset($cvterm['cv_id'])) {
  778. $values['cv_id'] = $cvterm['cv_id'];
  779. } elseif (isset($cvterm['cv_name'])) {
  780. $values['cv_id'] = array(
  781. 'name' => $cvterm['cv_name']
  782. );
  783. }
  784. else {
  785. tripal_report_error(
  786. 'tripal_cv_api',
  787. TRIPAL_WARNING,
  788. "chado_associate_cvterm: The cvterm needs to have either the cv_name or cv_id
  789. supplied. You were trying to associate a cvterm with the %base %record_id
  790. and supplied the cvterm values: %cvterm.",
  791. array('%base' => $basetable, '%record_id' => $record_id, '%cvterm' => print_r($cvterm,TRUE))
  792. );
  793. return FALSE;
  794. }
  795. $select = chado_select_record('cvterm',array('*'), $values);
  796. if ($select) {
  797. $cvterm['cvterm_id'] = $select[0]->cvterm_id;
  798. }
  799. elseif ($options['insert_cvterm']) {
  800. // Insert the cvterm
  801. $insert = chado_insert_cvterm($values);
  802. if (isset($insert->cvterm_id)) {
  803. $cvterm['cvterm_id'] = $insert->cvterm_id;
  804. }
  805. else {
  806. tripal_report_error(
  807. 'tripal_cv_api',
  808. TRIPAL_WARNING,
  809. "chado_associate_cvterm: Unable to insert the cvterm using the cvterm values: %cvterm.",
  810. array('%cvterm' => print_r($cvterm,TRUE))
  811. );
  812. return FALSE;
  813. }
  814. }
  815. else {
  816. tripal_report_error(
  817. 'tripal_api',
  818. TRIPAL_WARNING,
  819. "chado_associate_cvterm: The cvterm doesn't already exist. You supplied the cvterm values: %cvterm.",
  820. array('%cvterm' => print_r($cvterm,TRUE))
  821. );
  822. return FALSE;
  823. }
  824. }
  825. // Now add the link between the record & cvterm
  826. if ($cvterm['cvterm_id'] > 0) {
  827. $values = array(
  828. 'cvterm_id' => $cvterm['cvterm_id'],
  829. $foreignkey_name => $record_id,
  830. 'pub_id' => 1,
  831. );
  832. $result = chado_select_record($linking_table, array('*'), $values);
  833. // if it doesn't already exist then add it
  834. if (!$result) {
  835. $success = chado_insert_record($linking_table, $values);
  836. if (!$success) {
  837. tripal_report_error(
  838. 'tripal_api',
  839. TRIPAL_WARNING,
  840. "Failed to insert the %base record %term",
  841. array('%base' => $linking_table, '%term' => $cvterm['name'])
  842. );
  843. return FALSE;
  844. }
  845. $result = chado_select_record($linking_table, array('*'), $values);
  846. }
  847. if (isset($result[0])) {
  848. return $result[0];
  849. }
  850. else {
  851. return FALSE;
  852. }
  853. }
  854. return FALSE;
  855. }