tripal_cv.api.inc 33 KB

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