tripal_chado.cv.api.inc 40 KB

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