tripal_chado.cv.api.inc 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  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_chado_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 variable
  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_chado_api
  44. */
  45. function tripal_get_cv($identifiers, $options = array()) {
  46. // Set Defaults
  47. if (!isset($options['include_fk'])) {
  48. // Tells chado_generate_var not to follow any foreign keys
  49. $options['include_fk'] = array();
  50. }
  51. // Error Checking of parameters
  52. if (!is_array($identifiers)) {
  53. tripal_report_error(
  54. 'tripal_chado_api',
  55. TRIPAL_ERROR,
  56. "tripal_get_cv: The identifier passed in is expected to be an array with the key
  57. matching a column name in the cv table (ie: cv_id or name). You passed in %identifier.",
  58. array(
  59. '%identifier'=> print_r($identifiers, TRUE)
  60. )
  61. );
  62. }
  63. elseif (empty($identifiers)) {
  64. tripal_report_error(
  65. 'tripal_chado_api',
  66. TRIPAL_ERROR,
  67. "tripal_get_cv: You did not pass in anything to identify the cv you want. The identifier
  68. is expected to be an array with the key matching a column name in the cv table
  69. (ie: cv_id or name). You passed in %identifier.",
  70. array(
  71. '%identifier'=> print_r($identifiers, TRUE)
  72. )
  73. );
  74. }
  75. // Try to get the cv
  76. $cv = chado_generate_var(
  77. 'cv',
  78. $identifiers,
  79. $options
  80. );
  81. // Ensure the cv is singular. If it's an array then it is not singular
  82. if (is_array($cv)) {
  83. tripal_report_error(
  84. 'tripal_chado_api',
  85. TRIPAL_ERROR,
  86. "tripal_get_cv: The identifiers you passed in were not unique. You passed in %identifier.",
  87. array(
  88. '%identifier'=> print_r($identifiers, TRUE)
  89. )
  90. );
  91. }
  92. // Report an error if $cv is FALSE since then chado_generate_var has failed
  93. elseif ($cv === FALSE) {
  94. tripal_report_error(
  95. 'tripal_chado_api',
  96. TRIPAL_ERROR,
  97. "tripal_get_cv: chado_generate_var() failed to return a cv based on the identifiers
  98. you passed in. You should check that your identifiers are correct, as well as, look
  99. for a chado_generate_var error for additional clues. You passed in %identifier.",
  100. array(
  101. '%identifier'=> print_r($identifiers, TRUE)
  102. )
  103. );
  104. }
  105. // Else, as far we know, everything is fine so give them their cv :)
  106. else {
  107. return $cv;
  108. }
  109. }
  110. /**
  111. * Create an options array to be used in a form element which provides a
  112. * list of all chado cvs
  113. *
  114. * @return
  115. * An array(cv_id => name) for each cv in the chado cv table
  116. *
  117. * @ingroup tripal_chado_api
  118. */
  119. function tripal_get_cv_select_options() {
  120. $results = chado_select_record('cv', array('cv_id', 'name'), array(), array('order_by' => array('name' => 'ASC')));
  121. $options = array();
  122. $options[] = 'Select a Vocabulary';
  123. foreach ($results as $r) {
  124. $options[$r->cv_id] = $r->name;
  125. }
  126. return $options;
  127. }
  128. /**
  129. * Retrieves a chado controlled vocabulary term variable
  130. *
  131. * @param $identifier
  132. * An array apropriate for use with the chado_generate_var for uniquely
  133. * identifying a cvterm record. Alternativley, there are also some specially
  134. * handled keys. They are:
  135. * - id: an ID for the term of the for [dbname]:[accession], where [dbname]
  136. * is the short name of the vocabulary and accession is the unique ID.
  137. * - cv_id: an integer indicating the cv_id or an array with 'name' => the
  138. * name of the cv.
  139. * - synonym: an array with 'name' => the name of the synonym of the cvterm
  140. * you want returned; 'cv_id' => the cv_id of the synonym; 'cv_name' =>
  141. * the name of the cv of the synonym
  142. * - property: An array/object describing the property to select records
  143. * for. It should at least have either a type_name (if unique across cvs)
  144. * or type_id. Other supported keys include: cv_id/cv_name (of the type),
  145. * value and rank
  146. * @param $options
  147. * An array of options. Supported keys include:
  148. * - Any keys supported by chado_generate_var(). See that function
  149. * definition for additional details.
  150. *
  151. * NOTE: the $identifier parameter can really be any array similar to $values
  152. * passed into chado_select_record(). It should fully specify the cvterm
  153. * record to be returned.
  154. *
  155. * @return
  156. * If unique values were passed in as an identifier then an object describing
  157. * the cvterm will be returned (will be a chado variable from
  158. * chado_generate_var()). Otherwise, FALSE will be returned.
  159. *
  160. * @ingroup tripal_cv_api
  161. */
  162. function tripal_get_cvterm($identifiers, $options = array()) {
  163. // Set Defaults
  164. if (!isset($options['include_fk'])) {
  165. // Tells chado_generate_var to only get the cv
  166. $options['include_fk'] = array('cv_id' => TRUE);
  167. }
  168. // Error Checking of parameters
  169. if (!is_array($identifiers)) {
  170. tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
  171. "tripal_get_cvterm: The identifier passed in is expected to be an array with the key
  172. matching a column name in the cvterm table (ie: cvterm_id or name). You passed in %identifier.",
  173. array('%identifier'=> print_r($identifiers, TRUE))
  174. );
  175. }
  176. elseif (empty($identifiers)) {
  177. tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
  178. "tripal_get_cvterm: You did not pass in anything to identify the cvterm you want. The identifier
  179. is expected to be an array with the key matching a column name in the cvterm table
  180. (ie: cvterm_id or name). You passed in %identifier.",
  181. array('%identifier'=> print_r($identifiers, TRUE))
  182. );
  183. }
  184. // If synonym was passed in, then process this first before calling chado_generate_var()
  185. if (isset($identifiers['synonym'])) {
  186. $synonym = $identifiers['synonym']['name'];
  187. $values = array('synonym' => $synonym);
  188. if (isset($identifiers['synonym']['cv_id'])) {
  189. $values['cvterm_id'] = array('cv_id' => $identifiers['synonym']['cv_id']);
  190. }
  191. if (isset($identifiers['synonym']['cv_name'])) {
  192. $values['cvterm_id'] = array('cv_id' => array('name' => $identifiers['synonym']['cv_name']));
  193. }
  194. $options = array(
  195. 'case_insensitive_columns' => array('name')
  196. );
  197. $result = chado_select_record('cvtermsynonym', array('cvterm_id'), $values, $options);
  198. // if the synonym doens't exist or more than one record is returned then return false
  199. if (count($result) == 0) {
  200. return FALSE;
  201. }
  202. if (count($result) > 1) {
  203. return FALSE;
  204. }
  205. $identifiers = array('cvterm_id' => $result[0]->cvterm_id);
  206. }
  207. // If one of the identifiers is property then use chado_get_record_with_property()
  208. if (isset($identifiers['property'])) {
  209. $property = $identifiers['property'];
  210. unset($identifiers['property']);
  211. $cvterm = chado_get_record_with_property(
  212. array('table' => 'cvterm', 'base_records' => $identifiers),
  213. array('type_name' => $property),
  214. $options
  215. );
  216. }
  217. if (isset($identifiers['id'])) {
  218. list($db_name, $accession) = preg_split('/:/', $identifiers['id']);
  219. $cvterm = chado_generate_var('cvterm',array(
  220. 'dbxref_id' => array(
  221. 'db_id' => array(
  222. 'name' => $db_name,
  223. ),
  224. 'accession' => $accession,
  225. )
  226. ));
  227. }
  228. // Else we have a simple case and we can just use chado_generate_var to get the cvterm
  229. else {
  230. // Try to get the cvterm
  231. $cvterm = chado_generate_var('cvterm', $identifiers, $options);
  232. }
  233. // Ensure the cvterm is singular. If it's an array then it is not singular
  234. if (is_array($cvterm)) {
  235. tripal_report_error(
  236. 'tripal_cv_api',
  237. TRIPAL_ERROR,
  238. "tripal_get_cvterm: The identifiers you passed in were not unique. You passed in %identifier.",
  239. array(
  240. '%identifier'=> print_r($identifiers, TRUE)
  241. )
  242. );
  243. }
  244. // Report an error if $cvterm is FALSE since then chado_generate_var has failed
  245. elseif ($cvterm === FALSE) {
  246. tripal_report_error(
  247. 'tripal_cv_api',
  248. TRIPAL_ERROR,
  249. "tripal_get_cvterm: chado_generate_var() failed to return a cvterm based on the identifiers
  250. you passed in. You should check that your identifiers are correct, as well as, look
  251. for a chado_generate_var error for additional clues. You passed in %identifier.",
  252. array(
  253. '%identifier'=> print_r($identifiers, TRUE)
  254. )
  255. );
  256. }
  257. // Else, as far we know, everything is fine so give them their cvterm :)
  258. else {
  259. return $cvterm;
  260. }
  261. }
  262. /**
  263. * Create an options array to be used in a form element
  264. * which provides a list of all chado cvterms
  265. *
  266. * @param $cv_id
  267. * The chado cv_id; only cvterms with the supplied cv_id will be returned
  268. * @param $rel_type
  269. * Set to TRUE if the terms returned should only be relationship types in
  270. * the vocabulary. This is useful for creating drop-downs of terms
  271. * used for relationship linker tables.
  272. *
  273. * @return
  274. * An associative array with the cvterm_id's as keys. The first
  275. * element in the array has a key of '0' and a value of 'Select a Type'
  276. *
  277. * @ingroup tripal_chado_api
  278. */
  279. function tripal_get_cvterm_select_options($cv_id, $rel_type = FALSE) {
  280. $columns = array('cvterm_id', 'name');
  281. $values = array('cv_id' => $cv_id);
  282. if ($rel_type) {
  283. $values['is_relationshiptype'] = 1;
  284. }
  285. $s_options = array('order_by' => array('name' => 'ASC'));
  286. $cvterms = chado_select_record('cvterm', $columns, $values, $s_options);
  287. $options = array();
  288. $options[0] = 'Select a Type';
  289. foreach ($cvterms as $cvterm) {
  290. $options[$cvterm->cvterm_id] = $cvterm->name;
  291. }
  292. return $options;
  293. }
  294. /**
  295. * Updates the cvtermpath table of Chado for the specified CV.
  296. *
  297. * @param $cv_id
  298. * The chado cv_id;
  299. * @param $job_id
  300. * This function is intended to be used with the Tripal Jobs API.
  301. * When this function is called as a job the $job_id is automatically
  302. * passed to this function.
  303. * @return
  304. * TRUE on success FALSE on failure
  305. *
  306. * @ingroup tripal_chado_api
  307. */
  308. function tripal_update_cvtermpath($cv_id, $job_id = NULL) {
  309. // TODO: need better error checking in this function
  310. // first get the controlled vocabulary name:
  311. $sql = "SELECT * FROM {cv} WHERE cv_id = :cv_id";
  312. $cv = chado_query($sql, array(':cv_id' => $cv_id))->fetchObject();
  313. print "\nUpdating cvtermpath for $cv->name...\n";
  314. $previous = chado_set_active('chado');
  315. try {
  316. $sql = "SELECT * FROM fill_cvtermpath(:name)";
  317. db_query($sql, array(':name' => $cv->name));
  318. chado_set_active($previous);
  319. }
  320. catch (Exception $e) {
  321. chado_set_active($previous);
  322. $error = $e->getMessage();
  323. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not fill cvtermpath table: @error", array('@error' => $error));
  324. return FALSE;
  325. }
  326. return TRUE;
  327. }
  328. /**
  329. * Adds a controlled vocabular to the CV table of Chado.
  330. *
  331. * @param $name
  332. * The name of the controlled vocabulary. These are typically all lower case
  333. * with no special characters other than an undrescore (for spaces).
  334. * @param $comment
  335. * A description or definition of the vocabulary.
  336. *
  337. * @return
  338. * An object populated with fields from the newly added database.
  339. *
  340. * @ingroup tripal_chado_api
  341. */
  342. function tripal_insert_cv($name, $definition) {
  343. // insert/update values
  344. $ins_values = array(
  345. 'name' => $name,
  346. 'definition' => $definition
  347. );
  348. // see if the CV default exists already in the database
  349. $sel_values = array('name' => $name);
  350. $results = chado_select_record('cv', array('*'), $sel_values);
  351. // if it does not exists then add it
  352. if (count($results) == 0) {
  353. $success = chado_insert_record('cv', $ins_values);
  354. if (!$success) {
  355. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to create the CV record", NULL);
  356. return FALSE;
  357. }
  358. $results = chado_select_record('cv', array('*'), $sel_values);
  359. }
  360. // if it already exists then do an update
  361. else {
  362. $success = chado_update_record('cv', $sel_values, $ins_values);
  363. if (!$success) {
  364. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the CV record", NULL);
  365. return FALSE;
  366. }
  367. $results = chado_select_record('cv', array('*'), $sel_values);
  368. }
  369. // return the cv object
  370. return $results[0];
  371. }
  372. /**
  373. * Add's a controlled vocabulary term to Chado.
  374. *
  375. * This function will add a cvterm record (and a dbxref record if appropriate
  376. * values are provided). If the parent vocabulary does not exist then
  377. * that also is added to the cv table. If the cvterm is a relationship term
  378. * then the 'is_relationship' value should be set. All
  379. * terms must also have a corresponding database. This is specified in the
  380. * term's ID just before the colon (e.g. GO:003824). If the database does not
  381. * exist in the DB table then it will be added automatically. The accession
  382. * (the value just after the colon in the term's ID) will be added to the
  383. * dbxref table. If the CVterm already exists and $update is set (default)
  384. * then the cvterm is updated. If the CVTerm already exists and $update is
  385. * not set, then no changes are made and the CVTerm object is returned.
  386. *
  387. * @param $term
  388. * An associative array with the following keys:
  389. * - id: the term accession. must be of the form <DB>:<ACCESSION>, where
  390. * <DB> is the name of the database to which the cvterm belongs and the
  391. * <ACCESSION> is the term's accession number in the database.
  392. * - name: the name of the term. usually meant to be human-readable.
  393. * - is_obsolete: is present and set to 1 if the term is defunct
  394. * - definition: the definition of the term
  395. * - cv_name: The CV name to which the term belongs. If this arugment is
  396. * null or not provided then the function tries to find a record in the
  397. * CV table with the same name provided in the $term[namespace]. If
  398. * this field is provided then it overrides what the value in
  399. * $term[namespace]
  400. * - is_relationship: If this term is a relationship term then this value
  401. * should be 1.
  402. * - db_name: In some cases the database name will not be part of the
  403. * $term['id'] and it needs to be explicitly set. Use this argument
  404. * only if the database name cannot be specififed in the term ID
  405. * (e.g. <DB>:<ACCESSION>).
  406. * @param $options
  407. * An associative array with the following keys:
  408. * - update_existing: By default this is TRUE. If the term exists it is
  409. * automatically updated.
  410. * - force_db_change: Sometimes a term may need to switch from one
  411. * database to another. If the term already exists, but associated
  412. * with another term the insert (or update, rather) will fail. Set
  413. * this variable to TRUE to force the change to occur.
  414. *
  415. * @return
  416. * A cvterm object
  417. *
  418. * @ingroup tripal_chado_api
  419. */
  420. function tripal_insert_cvterm($term, $options = array()) {
  421. // get the term properties
  422. $id = (isset($term['id'])) ? $term['id'] : '';
  423. $name = '';
  424. $cvname = '';
  425. $definition = '';
  426. $is_obsolete = 0;
  427. $accession = '';
  428. // Set Defaults
  429. if (isset($term['cv_name'])) {
  430. $cvname = $term['cv_name'];
  431. }
  432. else {
  433. $cvname = 'local';
  434. }
  435. // Namespace is deprecated but must be supported for backwards
  436. // compatability
  437. if (array_key_exists('namespace', $term)) {
  438. $cvname = $term['namespace'];
  439. }
  440. if (isset($term['is_relationship'])) {
  441. $is_relationship = $term['is_relationship'];
  442. }
  443. else {
  444. $is_relationship = 0;
  445. }
  446. if (isset($term['db_name'])) {
  447. $dbname = $term['db_name'];
  448. }
  449. else {
  450. $dbname = 'local';
  451. }
  452. if (isset($options['update_existing'])) {
  453. $update = $options['update_existing'];
  454. }
  455. else {
  456. $update = 1;
  457. }
  458. if (array_key_exists('name', $term)) {
  459. $name = $term['name'];
  460. }
  461. else {
  462. $name = $id;
  463. }
  464. if (array_key_exists('definition', $term)) {
  465. $definition = preg_replace('/^\"(.*)\"/', '\1', $term['definition']);
  466. }
  467. else {
  468. $definition = '';
  469. }
  470. if (array_key_exists('is_obsolete', $term)) {
  471. $is_obsolete = $term['is_obsolete'];
  472. if (strcmp($is_obsolete, 'true') == 0) {
  473. $is_obsolete = 1;
  474. }
  475. }
  476. if (!$name and !$id) {
  477. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Cannot find cvterm without 'id' or 'name'", NULL);
  478. return 0;
  479. }
  480. if (!$id) {
  481. $id = $name;
  482. }
  483. // Get the accession and the database from the cvterm id.
  484. if ($dbname) {
  485. $accession = $id;
  486. }
  487. if (preg_match('/^.+?:.*$/', $id)) {
  488. $accession = preg_replace('/^.+?:(.*)$/', '\1', $id);
  489. $dbname = preg_replace('/^(.+?):.*$/', '\1', $id);
  490. }
  491. // Check that we have a database name, give a different message if it's a
  492. // relationship.
  493. if ($is_relationship and !$dbname) {
  494. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  495. "A database name is not provided for this relationship term: $id", NULL);
  496. return 0;
  497. }
  498. if (!$is_relationship and !$dbname) {
  499. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  500. "A database identifier is missing from the term: $id", NULL);
  501. return 0;
  502. }
  503. // Make sure the CV name exists
  504. $cv = tripal_get_cv(array('name' => $cvname));
  505. if (!$cv) {
  506. $cv = tripal_insert_cv($cvname, '');
  507. }
  508. if (!$cv) {
  509. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  510. "Cannot find namespace '$cvname' when adding/updating $id", NULL);
  511. return 0;
  512. }
  513. // This SQL statement will be used a lot to find a cvterm so just set it
  514. // here for easy reference below. Because CV terms can change their names
  515. // but accessions don't change, the following SQL finds cvterms based on
  516. // their accession rather than the name.
  517. $cvtermsql = "
  518. SELECT CVT.name, CVT.cvterm_id, CV.cv_id, CV.name as cvname,
  519. DB.name as dbname, DB.db_id, DBX.accession
  520. FROM {cvterm} CVT
  521. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  522. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  523. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  524. WHERE DBX.accession = :accession and DB.name = :name
  525. ";
  526. // Add the database. The function will just return the DB object if the
  527. // database already exists.
  528. $db = tripal_get_db(array('name' => $dbname));
  529. if (!$db) {
  530. $db = tripal_insert_db(array('name' => $dbname));
  531. }
  532. if (!$db) {
  533. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Cannot find database '$dbname' in Chado.", NULL);
  534. return 0;
  535. }
  536. // The cvterm table has two unique dependencies. We need to check both.
  537. // first check the (name, cv_id, is_obsolete) constraint.
  538. $values = array(
  539. 'name' => $name,
  540. 'is_obsolete' => $is_obsolete,
  541. 'cv_id' => array(
  542. 'name' => $cvname,
  543. ),
  544. );
  545. $result = chado_select_record('cvterm', array('*'), $values);
  546. if (count($result) == 1) {
  547. $cvterm = $result[0];
  548. // Get the dbxref record.
  549. $values = array('dbxref_id' => $cvterm->dbxref_id);
  550. $result = chado_select_record('dbxref', array('*'), $values);
  551. $dbxref = $result[0];
  552. if (!$dbxref) {
  553. tripal_report_error('tripal_cv', TRIPAL_ERROR,
  554. 'Unable to access the dbxref record for the :term cvterm. Term Record: !record',
  555. array(':term' => $name, '!record' => print_r($cvterm, TRUE))
  556. );
  557. return FALSE;
  558. }
  559. // Get the db.
  560. $values = array('db_id' => $dbxref->db_id);
  561. $result = chado_select_record('db', array('*'), $values);
  562. $db_check = $result[0];
  563. // If the database from the existing record doesn't match the one that
  564. // has been provided then we have a problem. The term already exists
  565. // but we don't want to just switch the term, the callee must force it.
  566. if ($db_check->name != $db->name) {
  567. if (array_key_exists('force_db_change', $options) and
  568. $options['force_db_change'] != TRUE) {
  569. tripal_report_error('tripal_cv', TRIPAL_ERROR,
  570. 'The term already exists, but associated with a different database record: \'!db\'. It cannot be added: !record',
  571. array(':term' => $name, '!db' => $db_check->name, '!record' => print_r($cvterm, TRUE))
  572. );
  573. return FALSE;
  574. }
  575. // Look to see if the correct dbxref record already exists for this
  576. // database.
  577. $values = array(
  578. 'db_id' => $db->db_id,
  579. 'accession' => $accession,
  580. );
  581. $result = chado_select_record('dbxref', array('*'), $values);
  582. // If we already have a good dbxref then we want to update our cvterm
  583. // to use this dbxref.
  584. if (count($result) > 0) {
  585. $dbxref = $result[0];
  586. $match = array('cvterm_id' => $cvterm->cvterm_id);
  587. $values = array('dbxref_id' => $dbxref->dbxref_id);
  588. $success = chado_update_record('cvterm', $match, $values);
  589. if (!$success) {
  590. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to correct the dbxref id for the cvterm " .
  591. "'$name' (id: $accession), for database $dbname", NULL);
  592. return 0;
  593. }
  594. }
  595. // If we don't have the dbxref then we want to delete our cvterm and let
  596. // the code below recreate it with the correct info.
  597. else {
  598. $match = array('cvterm_id' => $cvterm->cvterm_id);
  599. chado_delete_record('cvterm', $match);
  600. }
  601. }
  602. // Check that the accession matches. Sometimes an OBO can define a term
  603. // multiple times but with different accessions. If this is the case we
  604. // can't do an insert or it will violate the constraint in the cvterm table.
  605. // So we'll need to add the record to the cvterm_dbxref table instead.
  606. if ($dbxref->accession != $accession) {
  607. // Get/add the dbxref for his term.
  608. $dbxref_new = tripal_insert_dbxref(array(
  609. 'db_id' => $db->db_id,
  610. 'accession' => $accession
  611. ));
  612. if (!$dbxref_new) {
  613. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  614. "$name (id: $accession), for database $dbname", NULL);
  615. return 0;
  616. }
  617. // Check to see if the cvterm_dbxref record already exists.
  618. $values = array(
  619. 'cvterm_id' => $cvterm->cvterm_id,
  620. 'dbxref_id' => $dbxref_new->dbxref_id,
  621. 'is_for_definition' => 1,
  622. );
  623. $result = chado_select_record('cvterm_dbxref', array('*'), $values);
  624. // if the cvterm_dbxref record does not exists then add it
  625. if (count($result)==0) {
  626. $options = array(
  627. 'return_record' => FALSE,
  628. );
  629. $success = chado_insert_record('cvterm_dbxref', $values, $options);
  630. if (!$success) {
  631. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the cvterm_dbxref record for a " .
  632. "duplicated cvterm: $name (id: $accession), for database $dbname", NULL);
  633. return 0;
  634. }
  635. }
  636. // get the original cvterm with the same name and return that.
  637. $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
  638. $cvterm = $result->fetchObject();
  639. return $cvterm;
  640. }
  641. // Continue on, we've fixed the record if the db_id did not match.
  642. // We can now perform and updated if we need to.
  643. }
  644. // get the CVterm record
  645. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  646. $cvterm = $result->fetchObject();
  647. if (!$cvterm) {
  648. // Check to see if the dbxref exists if not, add it.
  649. $dbxref = tripal_insert_dbxref(array(
  650. 'db_id' => $db->db_id,
  651. 'accession' => $accession
  652. ));
  653. if (!$dbxref) {
  654. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  655. "$name (id: $accession), for database $dbname", NULL);
  656. return 0;
  657. }
  658. // Check to see if the dbxref already has an entry in the cvterm table.
  659. $values = array('dbxref_id' => $dbxref->dbxref_id);
  660. $check = chado_select_record('cvterm', array('cvterm_id'), $values);
  661. if (count($check) == 0) {
  662. // now add the cvterm
  663. $ins_values = array(
  664. 'cv_id' => $cv->cv_id,
  665. 'name' => $name,
  666. 'definition' => $definition,
  667. 'dbxref_id' => $dbxref->dbxref_id,
  668. 'is_obsolete' => $is_obsolete,
  669. 'is_relationshiptype' => $is_relationship,
  670. );
  671. $success = chado_insert_record('cvterm', $ins_values);
  672. if (!$success) {
  673. if (!$is_relationship) {
  674. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to insert the term: $name ($dbname)", NULL);
  675. return 0;
  676. }
  677. else {
  678. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)", NULL);
  679. return 0;
  680. }
  681. }
  682. }
  683. // This dbxref already exists in the cvterm table.
  684. else {
  685. tripal_report_error('tripal_chado', TRIPAL_WARNING, "The dbxref already exists for another cvterm record: $name (cv: " . $cvname . " db: $dbname)", NULL);
  686. return 0;
  687. }
  688. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  689. $cvterm = $result->fetchObject();
  690. }
  691. // Update the cvterm.
  692. elseif ($update) {
  693. // First, basic update of the term.
  694. $match = array('cvterm_id' => $cvterm->cvterm_id);
  695. $upd_values = array(
  696. 'name' => $name,
  697. 'definition' => $definition,
  698. 'is_obsolete' => $is_obsolete,
  699. 'is_relationshiptype' => $is_relationship,
  700. );
  701. $success = chado_update_record('cvterm', $match, $upd_values);
  702. if (!$success) {
  703. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the term: $name", NULL);
  704. return 0;
  705. }
  706. // Second, check that the dbxref has not changed and if it has then update it.
  707. $checksql = "
  708. SELECT cvterm_id
  709. FROM {cvterm} CVT
  710. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  711. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  712. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  713. WHERE DBX.accession = :accession and DB.name = :dbname and CVT.name = :term and CV.name = :cvname
  714. ";
  715. $check = chado_query($checksql, array(':accession' => $dbxref->accession, ':dbname' => $dbname, ':term' => $name, ':cvname' => $cvname))->fetchObject();
  716. if (!$check) {
  717. // check to see if the dbxref exists if not, add it.
  718. $dbxref = tripal_insert_dbxref(array(
  719. 'db_id' => $db->db_id,
  720. 'accession' => $accession
  721. ));
  722. if (!$dbxref) {
  723. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  724. "$name (id: $accession), for database $dbname", NULL);
  725. return 0;
  726. }
  727. $match = array('cvterm_id' => $cvterm->cvterm_id);
  728. $upd_values = array(
  729. 'dbxref_id' => $dbxref->dbxref_id,
  730. );
  731. $success = chado_update_record('cvterm', $match, $upd_values);
  732. if (!$success) {
  733. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the term $name with new accession $db:$accession", NULL);
  734. return 0;
  735. }
  736. }
  737. // Finally grab the updated details.
  738. $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
  739. $cvterm = $result->fetchObject();
  740. }
  741. else {
  742. // do nothing, we have the cvterm but we don't want to update
  743. }
  744. // return the cvterm
  745. return $cvterm;
  746. }
  747. /**
  748. * This function allows other modules to programatically
  749. * submit an ontology for loading into Chado.
  750. *
  751. * This function will add a job to the Jobs subsystem for parsing the ontology.
  752. * You can either pass a known OBO ID to the function or the URL
  753. * or full path the the ontology file. If a URL or file name is
  754. * passed then the $obo_name argument must also be provided. If
  755. * this is the first time the ontology has been provided to Tripal
  756. * then it will be added to the database and will be assigned a
  757. * unique OBO ID.
  758. *
  759. * @param $obo_id
  760. * If the ontology is already loaded into the Tripal tables then
  761. * use this argument to specify the unique ID for the ontology
  762. * that will be loaded
  763. * @param $obo_name
  764. * If the OBO has not been added before then use this argument
  765. * to specify the human readable name of the ontology.
  766. * @param $obo_url
  767. * If the OBO to be loaded is located on a remote server then
  768. * use this argument to provide the URL.
  769. * @param $obo_file
  770. * If the OBO is housed on the local file system of the server then
  771. * use this argument to specify the full path.
  772. *
  773. * @return
  774. * returns the job_id of the submitted job or FALSE if the job was not added
  775. *
  776. * @ingroup tripal_chado_api
  777. */
  778. function tripal_submit_obo_job($obo) {
  779. global $user;
  780. // Set Defaults
  781. $obo['obo_id'] = (isset($obo['obo_id'])) ? $obo['obo_id'] : NULL;
  782. $obo['name'] = (isset($obo['name'])) ? $obo['name'] : NULL;
  783. $obo['url'] = (isset($obo['url'])) ? $obo['url'] : NULL;
  784. $obo['file'] = (isset($obo['file'])) ? $obo['file'] : NULL;
  785. $includes = array(
  786. module_load_include('inc', 'tripal_chado', 'includes/loaders/tripal_chado.obo_loader'),
  787. );
  788. if ($obo['obo_id']) {
  789. $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = :obo_id";
  790. $result = db_query($sql, array(':obo_id' => $obo['obo_id']))->fetchObject();
  791. $args = array($result->obo_id);
  792. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  793. "tripal_chado_load_obo_v1_2_id", $args, $user->uid, 10, $includes);
  794. }
  795. else {
  796. if ($obo['url']) {
  797. $args = array($obo['name'], $obo['url']);
  798. return tripal_add_job("Load OBO " . $obo['name'], 'tripal_chado',
  799. "tripal_chado_load_obo_v1_2_url", $args, $user->uid, 10, $includes);
  800. }
  801. elseif ($obo['file']) {
  802. $args = array($obo['name'], $obo['file']);
  803. return tripal_add_job("Load OBO " . $obo['name'], 'tripal_chado',
  804. "tripal_chado_load_obo_v1_2_file", $args, $user->uid, 10, $includes);
  805. }
  806. }
  807. return FALSE;
  808. }
  809. /**
  810. * Add the OBO to the tripal_cv_obo table in the Drupal database.
  811. *
  812. * If the OBO name already exists in the table then the path is updated.
  813. *
  814. * @param $name
  815. * The human readable name of this ontology
  816. * @param $path
  817. * The file path or URL of the ontology
  818. *
  819. * @return
  820. * Returns the ontology ID
  821. *
  822. * @ingroup tripal_chado_api
  823. */
  824. function tripal_insert_obo($name, $path) {
  825. // make sure an OBO with the same name doesn't already exist
  826. $obo_id = db_select('tripal_cv_obo', 'tco')
  827. ->fields('tco', array('obo_id'))
  828. ->condition('name', $name)
  829. ->execute()
  830. ->fetchField();
  831. if ($obo_id) {
  832. db_update('tripal_cv_obo')
  833. ->fields(array(
  834. 'path' => $path,
  835. ))
  836. ->condition('name', $name)
  837. ->execute();
  838. return $obo_id;
  839. }
  840. else {
  841. $obo_id = db_insert('tripal_cv_obo')
  842. ->fields(array(
  843. 'name' => $name,
  844. 'path' => $path,
  845. ))
  846. ->execute();
  847. return $obo_id;
  848. }
  849. }
  850. /**
  851. * Retrieves an OBO record.
  852. *
  853. * @param $values
  854. * An associate array with the following allowed keys: obo_id, name
  855. *
  856. * @return
  857. * An instance of an OBO record object.
  858. */
  859. function tripal_get_obo($values) {
  860. $query = db_select('tripal_cv_obo', 'tco')
  861. ->fields('tco');
  862. if (array_key_exists('name', $values)) {
  863. $query->condition('tco.name', $values['name']);
  864. }
  865. if (array_key_exists('obo_id', $values)) {
  866. $query->condition('tco.obo_id', $values['obo_id']);
  867. }
  868. return $query->execute()->fetchObject();
  869. }
  870. /**
  871. * This function is intended to be used in autocomplete forms
  872. * for searching for CV terms that begin with the provided string
  873. *
  874. * @param $cv_id
  875. * The CV ID in which to search for the term
  876. * @param $string
  877. * The string to search for
  878. *
  879. * @return
  880. * A json array of terms that begin with the provided string
  881. *
  882. * @ingroup tripal_chado_api
  883. */
  884. function tripal_autocomplete_cvterm($cv_id, $string = '') {
  885. if ($cv_id) {
  886. $sql = "
  887. SELECT CVT.cvterm_id, CVT.name
  888. FROM {cvterm} CVT
  889. WHERE CVT.cv_id = :cv_id and lower(CVT.name) like lower(:name)
  890. UNION
  891. SELECT CVT2.cvterm_id, CVTS.synonym as name
  892. FROM {cvterm} CVT2
  893. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  894. WHERE CVT2.cv_id = :cv_id and lower(CVTS.synonym) like lower(:name)
  895. ORDER by name
  896. LIMIT 25 OFFSET 0
  897. ";
  898. $results = chado_query($sql, array(':cv_id' => $cv_id, ':name' => $string . '%'));
  899. $items = array();
  900. foreach ($results as $term) {
  901. $items[$term->name] = $term->name;
  902. }
  903. }
  904. // If a CV wasn't provided then search all of them, and include the cv
  905. // in the results.
  906. else {
  907. $sql = "
  908. SELECT CVT.cvterm_id, CVT.name, CV.name as cvname, CVT.cv_id
  909. FROM {cvterm} CVT
  910. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  911. WHERE lower(CVT.name) like lower(:name)
  912. UNION
  913. SELECT CVT2.cvterm_id, CVTS.synonym as name, CV2.name as cvname, CVT2.cv_id
  914. FROM {cvterm} CVT2
  915. INNER JOIN {cv} CV2 on CVT2.cv_id = CV2.cv_id
  916. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  917. WHERE lower(CVTS.synonym) like lower(:name)
  918. ORDER by name
  919. LIMIT 25 OFFSET 0
  920. ";
  921. $results = chado_query($sql, array(':name' => $string . '%'));
  922. $items = array();
  923. foreach ($results as $term) {
  924. $items[$term->name] = $term->name;
  925. }
  926. }
  927. drupal_json_output($items);
  928. }
  929. /**
  930. * Add a record to a cvterm linking table (ie: feature_cvterm)
  931. *
  932. * @param $basetable
  933. * The base table to which the cvterm should be linked/associated. Thus to associate a
  934. * cvterm to a feature the basetable=feature and cvterm_id is added to the feature_cvterm table.
  935. * @param $record_id
  936. * The primary key of the basetable to associate the cvterm with. This should be in integer.
  937. * @param $cvterm
  938. * An associative array describing the cvterm. Valid keys include:
  939. * - name: the name for the cvterm,
  940. * - cv_name: the name of the cv the cvterm belongs to.
  941. * - cv_id: the primary key of the cv the cvterm belongs to.
  942. * @param $options
  943. * An associative array of options. Valid keys include:
  944. * - insert_cvterm: Insert the cvterm if it doesn't already exist. FALSE is the default
  945. *
  946. * @ingroup tripal_chado_api
  947. */
  948. function tripal_associate_cvterm($basetable, $record_id, $cvterm, $options = array()) {
  949. $linking_table = $basetable . '_cvterm';
  950. $foreignkey_name = $basetable . '_id';
  951. // Default Values
  952. $options['insert_cvterm'] = (isset($options['insert_cvterm'])) ? $options['insert_cvterm'] : FALSE;
  953. // If the cvterm_id is not set then find the cvterm record using the name and cv_id
  954. if (!isset($cvterm['cvterm_id'])) {
  955. $values = array(
  956. 'name' => $cvterm['name'],
  957. );
  958. if (isset($cvterm['cv_id'])) {
  959. $values['cv_id'] = $cvterm['cv_id'];
  960. }
  961. elseif (isset($cvterm['cv_name'])) {
  962. $values['cv_id'] = array(
  963. 'name' => $cvterm['cv_name']
  964. );
  965. }
  966. else {
  967. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  968. "tripal_associate_cvterm: The cvterm needs to have either the cv_name or cv_id
  969. supplied. You were trying to associate a cvterm with the %base %record_id
  970. and supplied the cvterm values: %cvterm.",
  971. array('%base' => $basetable, '%record_id' => $record_id, '%cvterm' => print_r($cvterm,TRUE))
  972. );
  973. return FALSE;
  974. }
  975. // Get the cvterm. If it doesn't exist then add it if the option
  976. // 'insert_cvterm' is set.
  977. $select = chado_select_record('cvterm', array('*'), $values);
  978. if ($select) {
  979. $cvterm['cvterm_id'] = $select[0]->cvterm_id;
  980. }
  981. elseif ($options['insert_cvterm']) {
  982. // Insert the cvterm
  983. $insert = tripal_insert_cvterm($values);
  984. if (isset($insert->cvterm_id)) {
  985. $cvterm['cvterm_id'] = $insert->cvterm_id;
  986. }
  987. else {
  988. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  989. "tripal_associate_cvterm: Unable to insert the cvterm using the cvterm values: %cvterm.",
  990. array('%cvterm' => print_r($cvterm,TRUE))
  991. );
  992. return FALSE;
  993. }
  994. }
  995. else {
  996. tripal_report_error('tripal_api', TRIPAL_WARNING,
  997. "tripal_associate_cvterm: The cvterm doesn't already exist. You supplied the cvterm values: %cvterm.",
  998. array('%cvterm' => print_r($cvterm,TRUE))
  999. );
  1000. return FALSE;
  1001. }
  1002. }
  1003. // Now add the link between the record & cvterm
  1004. if ($cvterm['cvterm_id'] > 0) {
  1005. $values = array(
  1006. 'cvterm_id' => $cvterm['cvterm_id'],
  1007. $foreignkey_name => $record_id,
  1008. 'pub_id' => 1,
  1009. );
  1010. // Check if the cvterm is already associated. If so, don't re-add it.
  1011. $result = chado_select_record($linking_table, array('*'), $values);
  1012. if (!$result) {
  1013. $success = chado_insert_record($linking_table, $values);
  1014. if (!$success) {
  1015. tripal_report_error('tripal_api', TRIPAL_WARNING,
  1016. "Failed to insert the %base record %term",
  1017. array('%base' => $linking_table, '%term' => $cvterm['name'])
  1018. );
  1019. return FALSE;
  1020. }
  1021. $result = chado_select_record($linking_table, array('*'), $values);
  1022. }
  1023. if (isset($result[0])) {
  1024. return $result[0];
  1025. }
  1026. else {
  1027. return FALSE;
  1028. }
  1029. }
  1030. return FALSE;
  1031. }
  1032. /**
  1033. * This function sets the default vocabulary for a given table and field.
  1034. *
  1035. * @param $table
  1036. * The name of the table that contains a field with a foreign key
  1037. * relationship to the cvterm table
  1038. * @param $field
  1039. * The table field name that has the foreign key relationship to the
  1040. * cvterm table for which the default vocabulary will be set
  1041. * @param $cv_name
  1042. * The name of the vocabulary
  1043. *
  1044. * @return
  1045. * TRUE if set, FALSE if an error occured
  1046. */
  1047. function tripal_set_default_cv($table, $field, $cv_name, $cv_id = FALSE) {
  1048. // Get the CV object
  1049. if ($cv_id) {
  1050. $cv = tripal_get_cv(array('cv_id' => $cv_id));
  1051. }
  1052. else {
  1053. $cv = tripal_get_cv(array('name' => $cv_name));
  1054. }
  1055. if ($cv) {
  1056. // first delete any entries for this table and field
  1057. $num_deleted = db_delete('tripal_cv_defaults')
  1058. ->condition('table_name', $table)
  1059. ->condition('field_name', $field)
  1060. ->execute();
  1061. // now add the default value
  1062. $cv_default_id = db_insert('tripal_cv_defaults')
  1063. ->fields(array(
  1064. 'table_name' => $table,
  1065. 'field_name' => $field,
  1066. 'cv_id' => $cv->cv_id,
  1067. ))
  1068. ->execute();
  1069. if (!$cv_default_id) {
  1070. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  1071. "Cannot set default vocabulary for %table.%field. Check the error logs.",
  1072. array('%table' => $table, '%field' => $field));
  1073. return FALSE;
  1074. }
  1075. }
  1076. else {
  1077. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  1078. "Cannot set default vocabulary for %table.%field. The vocabulary name, '%cvname', doesn't exist.",
  1079. array('%table' => $table, '%field' => $field, '%cvname' => $cv_name));
  1080. return FALSE;
  1081. }
  1082. }