tripal_cv.api.inc 39 KB

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