tripal_cv.api.inc 37 KB

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