tripal_cv.api.inc 38 KB

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