tripal_cv.api.inc 33 KB

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