tripal_chado.cv.api.inc 38 KB

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