tripal_cv.api.inc 40 KB

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