tripal_chado.cv.api.inc 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  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_chado_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_chado_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_chado_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_chado_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_chado_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_chado_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_chado_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. $options[] = 'Select a Vocabulary';
  123. foreach ($results as $r) {
  124. $options[$r->cv_id] = $r->name;
  125. }
  126. return $options;
  127. }
  128. /**
  129. * Retrieves a chado controlled vocabulary term variable
  130. *
  131. * @param $identifier
  132. * An array apropriate for use with the chado_generate_var for uniquely
  133. * identifying a cvterm record. Alternativley, there are also some specially
  134. * handled keys. They are:
  135. * - id: an ID for the term of the for [dbname]:[accession], where [dbname]
  136. * is the short name of the vocabulary and accession is the unique ID.
  137. * - cv_id: an integer indicating the cv_id or an array with 'name' => the
  138. * name of the cv.
  139. * - synonym: an array with 'name' => the name of the synonym of the cvterm
  140. * you want returned; 'cv_id' => the cv_id of the synonym; 'cv_name' =>
  141. * the name of the cv of the synonym
  142. * - property: An array/object describing the property to select records
  143. * for. It should at least have either a type_name (if unique across cvs)
  144. * or type_id. Other supported keys include: cv_id/cv_name (of the type),
  145. * value and rank
  146. * @param $options
  147. * An array of options. Supported keys include:
  148. * - Any keys supported by chado_generate_var(). See that function
  149. * definition for additional details.
  150. *
  151. * NOTE: the $identifier parameter can really be any array similar to $values
  152. * passed into chado_select_record(). It should fully specify the cvterm
  153. * record to be returned.
  154. *
  155. * @return
  156. * If unique values were passed in as an identifier then an object describing
  157. * the cvterm will be returned (will be a chado variable from
  158. * chado_generate_var()). Otherwise, FALSE will be returned.
  159. *
  160. * @ingroup tripal_cv_api
  161. */
  162. function tripal_get_cvterm($identifiers, $options = array()) {
  163. // Set Defaults
  164. if (!isset($options['include_fk'])) {
  165. // Tells chado_generate_var to only get the cv
  166. $options['include_fk'] = array('cv_id' => TRUE);
  167. }
  168. // Error Checking of parameters
  169. if (!is_array($identifiers)) {
  170. tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
  171. "tripal_get_cvterm: The identifier passed in is expected to be an array with the key
  172. matching a column name in the cvterm table (ie: cvterm_id or name). You passed in %identifier.",
  173. array('%identifier'=> print_r($identifiers, TRUE))
  174. );
  175. }
  176. elseif (empty($identifiers)) {
  177. tripal_report_error('tripal_cv_api', TRIPAL_ERROR,
  178. "tripal_get_cvterm: You did not pass in anything to identify the cvterm you want. The identifier
  179. is expected to be an array with the key matching a column name in the cvterm table
  180. (ie: cvterm_id or name). You passed in %identifier.",
  181. array('%identifier'=> print_r($identifiers, TRUE))
  182. );
  183. }
  184. // If synonym was passed in, then process this first before calling chado_generate_var()
  185. if (isset($identifiers['synonym'])) {
  186. $synonym = $identifiers['synonym']['name'];
  187. $values = array('synonym' => $synonym);
  188. if (isset($identifiers['synonym']['cv_id'])) {
  189. $values['cvterm_id'] = array('cv_id' => $identifiers['synonym']['cv_id']);
  190. }
  191. if (isset($identifiers['synonym']['cv_name'])) {
  192. $values['cvterm_id'] = array('cv_id' => array('name' => $identifiers['synonym']['cv_name']));
  193. }
  194. $options = array(
  195. 'case_insensitive_columns' => array('name')
  196. );
  197. $result = chado_select_record('cvtermsynonym', array('cvterm_id'), $values, $options);
  198. // if the synonym doens't exist or more than one record is returned then return false
  199. if (count($result) == 0) {
  200. return FALSE;
  201. }
  202. if (count($result) > 1) {
  203. return FALSE;
  204. }
  205. $identifiers = array('cvterm_id' => $result[0]->cvterm_id);
  206. }
  207. // If one of the identifiers is property then use chado_get_record_with_property()
  208. if (isset($identifiers['property'])) {
  209. $property = $identifiers['property'];
  210. unset($identifiers['property']);
  211. $cvterm = chado_get_record_with_property(
  212. array('table' => 'cvterm', 'base_records' => $identifiers),
  213. array('type_name' => $property),
  214. $options
  215. );
  216. }
  217. if (isset($identifiers['id'])) {
  218. list($db_name, $accession) = preg_split('/:/', $identifiers['id']);
  219. $cvterm = chado_generate_var('cvterm',array(
  220. 'dbxref_id' => array(
  221. 'db_id' => array(
  222. 'name' => $db_name,
  223. ),
  224. 'accession' => $accession,
  225. )
  226. ));
  227. }
  228. // Else we have a simple case and we can just use chado_generate_var to get the cvterm
  229. else {
  230. // Try to get the cvterm
  231. $cvterm = chado_generate_var('cvterm', $identifiers, $options);
  232. }
  233. // Ensure the cvterm is singular. If it's an array then it is not singular
  234. if (is_array($cvterm)) {
  235. tripal_report_error(
  236. 'tripal_cv_api',
  237. TRIPAL_ERROR,
  238. "tripal_get_cvterm: The identifiers you passed in were not unique. You passed in %identifier.",
  239. array(
  240. '%identifier'=> print_r($identifiers, TRUE)
  241. )
  242. );
  243. }
  244. // Report an error if $cvterm is FALSE since then chado_generate_var has failed
  245. elseif ($cvterm === FALSE) {
  246. tripal_report_error(
  247. 'tripal_cv_api',
  248. TRIPAL_ERROR,
  249. "tripal_get_cvterm: chado_generate_var() failed to return a cvterm based on the identifiers
  250. you passed in. You should check that your identifiers are correct, as well as, look
  251. for a chado_generate_var error for additional clues. You passed in %identifier.",
  252. array(
  253. '%identifier'=> print_r($identifiers, TRUE)
  254. )
  255. );
  256. }
  257. // Else, as far we know, everything is fine so give them their cvterm :)
  258. else {
  259. return $cvterm;
  260. }
  261. }
  262. /**
  263. * Create an options array to be used in a form element
  264. * which provides a list of all chado cvterms
  265. *
  266. * @param $cv_id
  267. * The chado cv_id; only cvterms with the supplied cv_id will be returned
  268. * @param $rel_type
  269. * Set to TRUE if the terms returned should only be relationship types in
  270. * the vocabulary. This is useful for creating drop-downs of terms
  271. * used for relationship linker tables.
  272. *
  273. * @return
  274. * An associative array with the cvterm_id's as keys. The first
  275. * element in the array has a key of '0' and a value of 'Select a Type'
  276. *
  277. * @ingroup tripal_chado_api
  278. */
  279. function tripal_get_cvterm_select_options($cv_id, $rel_type = FALSE) {
  280. $columns = array('cvterm_id', 'name');
  281. $values = array('cv_id' => $cv_id);
  282. if ($rel_type) {
  283. $values['is_relationshiptype'] = 1;
  284. }
  285. $s_options = array('order_by' => array('name' => 'ASC'));
  286. $cvterms = chado_select_record('cvterm', $columns, $values, $s_options);
  287. $options = array();
  288. $options[0] = 'Select a Type';
  289. foreach ($cvterms as $cvterm) {
  290. $options[$cvterm->cvterm_id] = $cvterm->name;
  291. }
  292. return $options;
  293. }
  294. /**
  295. * Updates the cvtermpath table of Chado for the specified CV.
  296. *
  297. * @param $cv_id
  298. * The chado cv_id;
  299. * @param $job_id
  300. * This function is intended to be used with the Tripal Jobs API.
  301. * When this function is called as a job the $job_id is automatically
  302. * passed to this function.
  303. * @return
  304. * TRUE on success FALSE on failure
  305. *
  306. * @ingroup tripal_chado_api
  307. */
  308. function tripal_update_cvtermpath_old($cv_id, $job_id = NULL) {
  309. // TODO: need better error checking in this function
  310. // first get the controlled vocabulary name:
  311. $sql = "SELECT * FROM {cv} WHERE cv_id = :cv_id";
  312. $cv = chado_query($sql, array(':cv_id' => $cv_id))->fetchObject();
  313. print "\nUpdating cvtermpath for $cv->name...\n";
  314. // We need to set the chado schema as active because some of the
  315. // functions call other functions which would not be in scope.
  316. $previous = chado_set_active('chado');
  317. try {
  318. $sql = "SELECT * FROM fill_cvtermpath(:name)";
  319. db_query($sql, array(':name' => $cv->name));
  320. chado_set_active($previous);
  321. }
  322. catch (Exception $e) {
  323. chado_set_active($previous);
  324. $error = $e->getMessage();
  325. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Could not fill cvtermpath table: @error", array('@error' => $error));
  326. return FALSE;
  327. }
  328. return TRUE;
  329. }
  330. /**
  331. * Duplicate of fill_cvtermpath() stored procedure in Chado.
  332. *
  333. * Identifies all of the root terms of the controlled vocabulary. These
  334. * root terms are then processed by calling the
  335. * tripal_update_cvtermpath_root_loop() function on each one.
  336. *
  337. * @param $cvid
  338. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  339. * @param $job_id
  340. */
  341. function tripal_update_cvtermpath($cv_id, $job_id = NULL){
  342. // TODO: there's a function to determine the current Chado instance.
  343. // we should use that.
  344. $prev_db = chado_set_active('chado');
  345. try {
  346. $result = db_query('
  347. SELECT DISTINCT t.*
  348. FROM cvterm t
  349. LEFT JOIN cvterm_relationship r ON (t.cvterm_id = r.subject_id)
  350. INNER JOIN cvterm_relationship r2 ON (t.cvterm_id = r2.object_id)
  351. WHERE t.cv_id = :cvid AND r.subject_id is null',
  352. array(':cvid' => $cv_id)
  353. );
  354. // Iterate through each root level term.
  355. $record = $result->fetchAll();
  356. $roots = array();
  357. foreach ($record as $item){
  358. tripal_update_cvtermpath_root_loop($item->cvterm_id, $item->cv_id, $roots);
  359. }
  360. }
  361. catch (Exception $e) {
  362. // If there's an exception we have to set the database back. So, do that
  363. // and then rethrow the error.
  364. chado_set_active($prev_db);
  365. throw $e;
  366. }
  367. chado_set_active($prev_db);
  368. }
  369. /**
  370. * Duplicate of _fill_cvtermpath4root() stored procedure in Chado.
  371. *
  372. * This function process a "branch" of the ontology. Initially, the
  373. * "root" starts at the top of the tree. But, as the cvtermpath is populated
  374. * the "root" becomes terms deeper in the tree.
  375. *
  376. * @param $rootid
  377. * The term ID from the cvterm table of Chado (i.e. cvterm.cvterm_id).
  378. * @param $cvid
  379. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  380. */
  381. function tripal_update_cvtermpath_root_loop($rootid, $cvid, &$roots) {
  382. // Get's the cvterm record for this "root".
  383. $ttype = db_select('cvterm', 'cv')
  384. ->fields('cv', array('cvterm_id'));
  385. $db_or = db_or();
  386. $db_or->condition('cv.name', "isa", '=');
  387. $db_or->condition('cv.name', "is_a", '=');
  388. $ttype->condition($db_or);
  389. $result = $ttype->execute()->fetchObject();
  390. $term_id = $rootid . '|' . $rootid . '|' . $cvid . '|' . $result->cvterm_id;
  391. // If the child_id matches any other id in the array then we've hit a loop.
  392. foreach ($roots as $element_id) {
  393. if ($element_id == $term_id) {
  394. return;
  395. }
  396. }
  397. // Then add that new entry to the $tree_path.
  398. $roots[] = $term_id;
  399. // Descends through the branch starting at this "root" term.
  400. $tree_path = array();
  401. $matched_rows = array();
  402. $possible_start_of_loop = array();
  403. $depth = 0;
  404. tripal_update_cvtermpath_loop($rootid, $rootid, $cvid, $result->cvterm_id, $depth,
  405. 0, $tree_path, FALSE, $matched_rows, $possible_start_of_loop, FALSE);
  406. // Get's the children terms of this "root" term and then recursively calls
  407. // this function making each child root.
  408. $cterm = db_query(
  409. 'SELECT *
  410. FROM cvterm_relationship
  411. WHERE object_id = :rootid
  412. ',
  413. array(':rootid' => $rootid)
  414. );
  415. while ($cterm_result = $cterm->fetchAssoc()) {
  416. tripal_update_cvtermpath_root_loop($cterm_result['subject_id'], $cvid, $roots);
  417. }
  418. }
  419. /**
  420. *
  421. * @param $origin
  422. * The root terms cvterm_id.
  423. * @param $child_id
  424. * The cvterm_id of the current child term. The child term is a descendent
  425. * of the origin.
  426. * @param $cv_id
  427. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  428. * @param $type_id
  429. * The relationship type between the origin term and the child.
  430. * @param $depth
  431. * The depth of the recursion.
  432. * @param $increment_of_depth.
  433. * An integer ??
  434. * @param $tree_path.
  435. * The array of every term between the current child and the origin. Each
  436. * element in the array is an associative array with the keys:
  437. * -build_id: an string identifier for the child that combines the origin,
  438. * child cvterm_id,cv_id, and the type_id.
  439. * -depth: the depth that a child was inserted into the cvtermpath table.
  440. * @param $possible_loop
  441. * A boolean flag.
  442. * @param $matched_row
  443. * An array of rows that are currently in the cvtermpath table that match the
  444. * build_id of the current term trying to be written to the table
  445. * @param $possible_start_of_ loop
  446. * The array of the possible loop item between the current child and the origin.
  447. * Each element in the array is an associative array with the keys:
  448. * - cvid : $cv_id
  449. * - subject_id:
  450. * - child_id : $child_id,
  451. * - type_id : $type_id,
  452. * - depth : $depth,
  453. * @param $no_loop_skip_test
  454. * A boolean used when the possible loop has been ruled out as a loop.
  455. * @return multitype:
  456. */
  457. function tripal_update_cvtermpath_loop(
  458. $origin,
  459. $child_id,
  460. $cv_id,
  461. $type_id,
  462. $depth,
  463. $increment_of_depth,
  464. $tree_path,
  465. $possible_loop,
  466. $matched_rows,
  467. $possible_start_of_loop,
  468. $no_loop_skip_test) {
  469. // We have not detected a loop, so it's safe to insert the term.
  470. $new_match_rows = array();
  471. if (!empty($possible_start_of_loop)) {
  472. // Go through each matched_row.
  473. if (count($matched_rows) === 1) {
  474. // Get the cvtermpath_id and then increment down one row.
  475. $cvtermpath_id = (int) $matched_rows[0]->cvtermpath_id;
  476. $cvtermpath_id = $cvtermpath_id + 1;
  477. chado_set_active('chado');
  478. $next_row = db_query(
  479. 'SELECT *
  480. FROM cvtermpath
  481. WHERE cvtermpath_id = :cvtermpath_id
  482. ',
  483. array(':cvtermpath_id' => $cvtermpath_id)
  484. );
  485. $next_row = $next_row->fetchObject();
  486. // If the next row matches the values passed we can't rule out a loop.
  487. if (($next_row->type_id === $type_id) &&
  488. ($next_row->subject_id === $child_id) &&
  489. ($next_row->object_id === $origin) &&
  490. ($next_row->cv_id === $cv_id)) {
  491. $new_match_rows[] = $next_row;
  492. }
  493. elseif (($next_row->type_id === $possible_start_of_loop['type_id']) &&
  494. ($next_row->subject_id === $possible_start_of_loop['subject_id']) &&
  495. ($next_row->object_id === $possible_start_of_loop['object_id']) &&
  496. ($next_row->cv_id === $possible_start_of_loop['cv_id'])) {
  497. // The next_row is equal to start of loop, so we've reached the end
  498. // and confirmed that this is a loop.
  499. $possible_loop == FALSE;
  500. $matched_rows = array();
  501. tripal_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  502. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  503. $new_match_rows, $possible_start_of_loop, $no_loop_skip_test);
  504. }
  505. }
  506. else {
  507. foreach ($matched_rows as $matched_row) {
  508. // Get the cvtermpath_id and then increment down one row.
  509. $cvtermpath_id = (int) $match_row->cvtermpath_id;
  510. // Get the cvtermpath_id and then increment down one row.
  511. $cvtermpath_id = $cvtermpath_id + 1;
  512. chado_set_active('chado');
  513. $next_row = db_query(
  514. 'SELECT *
  515. FROM cvtermpath
  516. WHERE cvtermpath_id = :cvtermpath_id
  517. ',
  518. array(':cvtermpath_id' => $cvtermpath_id)
  519. );
  520. $next_row = $next_row->fetchObject();
  521. // If the next row matches the values passed we can't rule out a loop.
  522. if (($next_row->type_id === $type_id) &&
  523. ($next_row->subject_id === $child_id) &&
  524. ($next_row->object_id === $origin) &&
  525. ($next_row->cv_id === $cv_id)) {
  526. $new_match_rows[] = $next_row;
  527. }
  528. elseif (($next_row->type_id === $possible_start_of_loop['type_id']) &&
  529. ($next_row->subject_id === $possible_start_of_loop['subject_id']) &&
  530. ($next_row->object_id === $possible_start_of_loop['object_id']) &&
  531. ($next_row->cv_id === $possible_start_of_loop['cv_id'])) {
  532. // The next_row is equal to start of loop, so we've reached the end
  533. // and confirmed that this is a loop.
  534. $possible_loop == FALSE;
  535. $matched_rows = array();
  536. tripal_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  537. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  538. $new_match_rows, $possible_start_of_loop, $no_loop_skip_test);
  539. }
  540. }
  541. }
  542. // If $match_rows is empty there is no loop.
  543. if (empty($new_match_rows)) {
  544. $possible_loop == FALSE;
  545. $matched_rows = array();
  546. unset($new_match_rows);
  547. $no_loop_skip_test = TRUE;
  548. // There is not loop so pass it back the possible_start_of_loop info
  549. // and a flag telling it to skip the loop check.
  550. tripal_update_cvtermpath_loop_increment($possible_start_of_loop->subject_id,
  551. $possible_start_of_loop->child_id, $possible_start_of_loop->cvid,
  552. $possible_start_of_loop->type_id, $possible_start_of_loop->depth,
  553. $increment_of_depth, $tree_path, $possible_loop, $matched_rows,
  554. $possible_start_of_loop, $no_loop_skip_test);
  555. }
  556. // If $match_rows is not empty we need to keep trying rows.
  557. else {
  558. tripal_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  559. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  560. $match_rows, $possible_start_of_loop, $no_loop_skip_test);
  561. }
  562. }
  563. elseif ($possible_loop === FALSE) {
  564. tripal_update_cvtermpath_loop_increment($origin, $child_id, $cv_id,
  565. $type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  566. $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
  567. }
  568. }
  569. /**
  570. *
  571. * @param $origin
  572. * The root terms cvterm_id.
  573. * @param $child_id
  574. * The cvterm_id of the current child term. The child term is a descendent
  575. * of the origin.
  576. * @param $cv_id
  577. * The controlled vocabulary ID from the cv table of Chado (i.e. cv.cv_id).
  578. * @param $type_id
  579. * The relationship type between the origin term and the child.
  580. * @param $depth
  581. * The depth of the recursion.
  582. * @param $increment_of_depth.
  583. * An integer ??
  584. * @param $tree_path.
  585. * The array of every term between the current child and the origin. Each
  586. * element in the array is an associative array with the keys:
  587. * -build_id: an string identifier for the child that combines the origin,
  588. * child cvterm_id,cv_id, and the type_id.
  589. * -depth: the depth that a child was inserted into the cvtermpath table.
  590. * @param $possible_loop
  591. * A boolean flag.
  592. * @param $matched_row
  593. * An array of rows that are currently in the cvtermpath table that match the
  594. * build_id of the current term trying to be written to the table
  595. * @param $possible_start_of_ loop
  596. * The array of the possible loop item between the current child and the origin.
  597. * Each element in the array is an associative array with the keys:
  598. * - cvid : $cv_id
  599. * - subject_id:
  600. * - child_id : $child_id,
  601. * - type_id : $type_id,
  602. * - depth : $depth,
  603. * @param $no_loop_skip_test
  604. * A boolean used when the possible loop has been ruled out as a loop.
  605. * @return multitype:
  606. */
  607. function tripal_update_cvtermpath_loop_increment(
  608. $origin,
  609. $child_id,
  610. $cv_id,
  611. $type_id,
  612. $depth,
  613. $increment_of_depth,
  614. $tree_path,
  615. $possible_loop,
  616. $matched_rows,
  617. &$possible_start_of_loop,
  618. $no_loop_skip_test) {
  619. // Check to see if a row with these values already exists.
  620. if ($possible_loop === FALSE && empty($possible_start_of_loop)) {
  621. chado_set_active('chado');
  622. $count = db_query(
  623. 'SELECT *
  624. FROM cvtermpath
  625. WHERE cv_id = :cvid
  626. AND object_id = :origin
  627. AND subject_id = :child_id
  628. AND pathdistance = :depth
  629. ',
  630. array(
  631. ':cvid' => $cv_id,
  632. ':origin' => $origin,
  633. ':child_id' => $child_id,
  634. ':depth' => $depth
  635. )
  636. );
  637. $count_total = $count->rowCount();
  638. if ($count_total > 0) {
  639. return $count;
  640. }
  641. // Build the ID.
  642. $term_id = $origin . '|' . $child_id . '|' . $cv_id . '|' . $type_id;
  643. if ($no_loop_skip_test === FALSE) {
  644. // Now check if the most recent entry already exists in the array.
  645. if ($increment_of_depth != 0) {
  646. // Search the $tree_path for the new $child_id in the build_id column.
  647. foreach ($tree_path as $parent) {
  648. // If this child is the same as a parent term that has already been
  649. // processed then we have a potential loop.
  650. if ($parent['build_id'] == $term_id) {
  651. // Tell the function this is a possible loop and to stop writing to the table.
  652. $possible_loop = TRUE;
  653. // Find all the results in the table that might be the start of the loop.
  654. $matching_rows = db_query(
  655. 'SELECT *
  656. FROM cvtermpath
  657. WHERE cv_id = :cvid
  658. AND object_id = :origin
  659. AND subject_id = :child_id
  660. AND type_id = :type_id
  661. ',
  662. array(
  663. ':cvid' => $cv_id,
  664. ':origin' => $origin,
  665. ':child_id' => $child_id,
  666. ':type_id' => $type_id
  667. )
  668. );
  669. $matched_rows = $matching_rows->fetchAll();
  670. $possible_start_of_loop = array(
  671. 'cvid' => $cv_id,
  672. 'subject_id' => $origin,
  673. 'child_id' => $child_id,
  674. 'type_id' => $type_id,
  675. 'depth' => $depth,
  676. );
  677. }
  678. }
  679. }
  680. $query = db_insert('cvtermpath')
  681. ->fields([
  682. 'object_id' => $origin,
  683. 'subject_id' => $child_id,
  684. 'cv_id' => $cv_id,
  685. 'type_id' => $type_id,
  686. 'pathdistance' => $depth,
  687. ]);
  688. $rows = $query->execute();
  689. // Then add that new entry to the $tree_path.
  690. $tree_path[$increment_of_depth] = [
  691. 'build_id' => $term_id,
  692. 'depth' => $depth
  693. ];
  694. }
  695. // Reset to FALSE and empty variable if passed in as TRUE.
  696. $no_loop_skip_test == FALSE;
  697. $possible_start_of_loop = array();
  698. // Get all of the relationships of this child term, and recursively
  699. // call the tripal_update_cvtermpath_loop() function to continue
  700. // descending down the tree.
  701. $query = db_select('cvterm_relationship', 'cvtr')
  702. ->fields('cvtr')
  703. ->condition('cvtr.object_id', $child_id, '=')
  704. ->execute();
  705. $cterm_relationships = $query->fetchAll();
  706. foreach ($cterm_relationships as $item) {
  707. $increment_of_depth++;
  708. tripal_update_cvtermpath_loop_increment($origin, $item->subject_id, $cv_id,
  709. $item->type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  710. $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
  711. }
  712. }
  713. elseif ($possible_loop === FALSE && !empty($possible_start_of_loop)) {
  714. // This means a loop has been identified and the recursive call can move
  715. // on to the next item and skip the rest of this run.
  716. return $possible_start_of_loop;
  717. }
  718. elseif ($possible_loop === TRUE) {
  719. // Get all of the relationships of this child term, and recursively
  720. // call the tripal_update_cvtermpath_loop() function to continue
  721. // descending down the tree.
  722. $query = db_select('cvterm_relationship', 'cvtr')
  723. ->fields('cvtr')
  724. ->condition('cvtr.object_id', $child_id, '=')
  725. ->execute();
  726. $cterm_relationships = $query->fetchAll();
  727. foreach ($cterm_relationships as $item) {
  728. $increment_of_depth++;
  729. tripal_update_cvtermpath_loop($origin, $item->subject_id, $cv_id,
  730. $item->type_id, $depth + 1, $increment_of_depth, $tree_path, $possible_loop,
  731. $matched_rows, $possible_start_of_loop, $no_loop_skip_test);
  732. }
  733. }
  734. }
  735. /**
  736. * Adds a controlled vocabular to the CV table of Chado.
  737. *
  738. * @param $name
  739. * The name of the controlled vocabulary. These are typically all lower case
  740. * with no special characters other than an undrescore (for spaces).
  741. * @param $comment
  742. * A description or definition of the vocabulary.
  743. *
  744. * @return
  745. * An object populated with fields from the newly added database.
  746. *
  747. * @ingroup tripal_chado_api
  748. */
  749. function tripal_insert_cv($name, $definition) {
  750. // insert/update values
  751. $ins_values = array(
  752. 'name' => $name,
  753. 'definition' => $definition
  754. );
  755. // see if the CV default exists already in the database
  756. $sel_values = array('name' => $name);
  757. $results = chado_select_record('cv', array('*'), $sel_values);
  758. // if it does not exists then add it
  759. if (count($results) == 0) {
  760. $success = chado_insert_record('cv', $ins_values);
  761. if (!$success) {
  762. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to create the CV record", NULL);
  763. return FALSE;
  764. }
  765. $results = chado_select_record('cv', array('*'), $sel_values);
  766. }
  767. // if it already exists then do an update
  768. else {
  769. $success = chado_update_record('cv', $sel_values, $ins_values);
  770. if (!$success) {
  771. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the CV record", NULL);
  772. return FALSE;
  773. }
  774. $results = chado_select_record('cv', array('*'), $sel_values);
  775. }
  776. // return the cv object
  777. return $results[0];
  778. }
  779. /**
  780. * Add's a controlled vocabulary term to Chado.
  781. *
  782. * This function will add a cvterm record (and a dbxref record if appropriate
  783. * values are provided). If the parent vocabulary does not exist then
  784. * that also is added to the cv table. If the cvterm is a relationship term
  785. * then the 'is_relationship' value should be set. All
  786. * terms must also have a corresponding database. This is specified in the
  787. * term's ID just before the colon (e.g. GO:003824). If the database does not
  788. * exist in the DB table then it will be added automatically. The accession
  789. * (the value just after the colon in the term's ID) will be added to the
  790. * dbxref table. If the CVterm already exists and $update is set (default)
  791. * then the cvterm is updated. If the CVTerm already exists and $update is
  792. * not set, then no changes are made and the CVTerm object is returned.
  793. *
  794. * @param $term
  795. * An associative array with the following keys:
  796. * - id: the term accession. must be of the form <DB>:<ACCESSION>, where
  797. * <DB> is the name of the database to which the cvterm belongs and the
  798. * <ACCESSION> is the term's accession number in the database.
  799. * - name: the name of the term. usually meant to be human-readable.
  800. * - is_obsolete: is present and set to 1 if the term is defunct
  801. * - definition: the definition of the term
  802. * - cv_name: The CV name to which the term belongs. If this arugment is
  803. * null or not provided then the function tries to find a record in the
  804. * CV table with the same name provided in the $term[namespace]. If
  805. * this field is provided then it overrides what the value in
  806. * $term[namespace]
  807. * - is_relationship: If this term is a relationship term then this value
  808. * should be 1.
  809. * - db_name: In some cases the database name will not be part of the
  810. * $term['id'] and it needs to be explicitly set. Use this argument
  811. * only if the database name cannot be specififed in the term ID
  812. * (e.g. <DB>:<ACCESSION>).
  813. * @param $options
  814. * An associative array with the following keys:
  815. * - update_existing: By default this is TRUE. If the term exists it is
  816. * automatically updated.
  817. *
  818. * @return
  819. * A cvterm object
  820. *
  821. * @ingroup tripal_chado_api
  822. */
  823. function tripal_insert_cvterm($term, $options = array()) {
  824. // get the term properties
  825. $id = (isset($term['id'])) ? $term['id'] : '';
  826. $name = '';
  827. $cvname = '';
  828. $definition = '';
  829. $is_obsolete = 0;
  830. $accession = '';
  831. // Set Defaults
  832. if (isset($term['cv_name'])) {
  833. $cvname = $term['cv_name'];
  834. }
  835. else {
  836. $cvname = 'local';
  837. }
  838. // Namespace is deprecated but must be supported for backwards
  839. // compatability
  840. if (array_key_exists('namespace', $term)) {
  841. $cvname = $term['namespace'];
  842. }
  843. if (isset($term['is_relationship'])) {
  844. $is_relationship = $term['is_relationship'];
  845. }
  846. else {
  847. $is_relationship = 0;
  848. }
  849. if (isset($term['db_name'])) {
  850. $dbname = $term['db_name'];
  851. }
  852. else {
  853. $dbname = 'internal';
  854. }
  855. if (isset($options['update_existing'])) {
  856. $update = $options['update_existing'];
  857. }
  858. else {
  859. $update = 1;
  860. }
  861. if (array_key_exists('name', $term)) {
  862. $name = $term['name'];
  863. }
  864. else {
  865. $name = $id;
  866. }
  867. if (array_key_exists('definition', $term)) {
  868. $definition = preg_replace('/^\"(.*)\"/', '\1', $term['definition']);
  869. }
  870. else {
  871. $definition = '';
  872. }
  873. if (array_key_exists('is_obsolete', $term)) {
  874. $is_obsolete = $term['is_obsolete'];
  875. if (strcmp($is_obsolete, 'true') == 0) {
  876. $is_obsolete = 1;
  877. }
  878. }
  879. if (!$name and !$id) {
  880. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find cvterm without 'id' or 'name'", NULL);
  881. return 0;
  882. }
  883. if (!$id) {
  884. $id = $name;
  885. }
  886. // Get the accession and the database from the cvterm id.
  887. if ($dbname) {
  888. $accession = $id;
  889. }
  890. if (preg_match('/^.+?:.*$/', $id)) {
  891. $accession = preg_replace('/^.+?:(.*)$/', '\1', $id);
  892. $dbname = preg_replace('/^(.+?):.*$/', '\1', $id);
  893. }
  894. // Check that we have a database name, give a different message if it's a
  895. // relationship.
  896. if ($is_relationship and !$dbname) {
  897. tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database name is not provided for this relationship term: $id", NULL);
  898. return 0;
  899. }
  900. if (!$is_relationship and !$dbname) {
  901. tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database identifier is missing from the term: $id", NULL);
  902. return 0;
  903. }
  904. // Make sure the CV name exists
  905. $cv = tripal_get_cv(array('name' => $cvname));
  906. if (!$cv) {
  907. $cv = tripal_insert_cv($cvname, '');
  908. }
  909. if (!$cv) {
  910. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find namespace '$cvname' when adding/updating $id", NULL);
  911. return 0;
  912. }
  913. // This SQL statement will be used a lot to find a cvterm so just set it
  914. // here for easy reference below. Because CV terms can change their names
  915. // but accessions don't change, the following SQL finds cvterms based on
  916. // their accession rather than the name.
  917. $cvtermsql = "
  918. SELECT CVT.name, CVT.cvterm_id, CV.cv_id, CV.name as cvname,
  919. DB.name as dbname, DB.db_id, DBX.accession
  920. FROM {cvterm} CVT
  921. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  922. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  923. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  924. WHERE DBX.accession = :accession and DB.name = :name
  925. ";
  926. // Add the database. The function will just return the DB object if the
  927. // database already exists.
  928. $db = tripal_get_db(array('name' => $dbname));
  929. if (!$db) {
  930. $db = tripal_insert_db(array('name' => $dbname));
  931. }
  932. if (!$db) {
  933. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find database '$dbname' in Chado.", NULL);
  934. return 0;
  935. }
  936. // The cvterm table has two unique dependencies. We need to check both.
  937. // first check the (name, cv_id, is_obsolete) constraint.
  938. $values = array(
  939. 'name' => $name,
  940. 'is_obsolete' => $is_obsolete,
  941. 'cv_id' => array(
  942. 'name' => $cvname,
  943. ),
  944. );
  945. $result = chado_select_record('cvterm', array('*'), $values);
  946. if (count($result) == 1) {
  947. $cvterm = $result[0];
  948. // Get the dbxref record.
  949. $values = array('dbxref_id' => $cvterm->dbxref_id);
  950. $result = chado_select_record('dbxref', array('*'), $values);
  951. $dbxref = $result[0];
  952. if (!$dbxref) {
  953. tripal_report_error('tripal_cv', TRIPAL_ERROR,
  954. 'Unable to access the dbxref record for the :term cvterm. Term Record: !record',
  955. array(':term' => $name, '!record' => print_r($cvterm, TRUE))
  956. );
  957. return FALSE;
  958. }
  959. // Get the db.
  960. $values = array('db_id' => $dbxref->db_id);
  961. $result = chado_select_record('db', array('*'), $values);
  962. $db_check = $result[0];
  963. // // The database name for this existing term does not match that of the
  964. // // one provided to this function. The CV name matches otherwise we
  965. // // wouldn't have made it this far. So, let's swap the database for
  966. // // this term.
  967. // if ($db_check->name != $db->name) {
  968. // // Look to see if the correct dbxref record already exists for this
  969. // // database.
  970. // $values = array(
  971. // 'db_id' => $db->db_id,
  972. // 'accession' => $accession,
  973. // );
  974. // $result = chado_select_record('dbxref', array('*'), $values);
  975. // // If we already have a good dbxref then we want to update our cvterm
  976. // // to use this dbxref.
  977. // if (count($result) > 0) {
  978. // $dbxref = $result[0];
  979. // $match = array('cvterm_id' => $cvterm->cvterm_id);
  980. // $values = array('dbxref_id' => $dbxref->dbxref_id);
  981. // $success = chado_update_record('cvterm', $match, $values);
  982. // if (!$success) {
  983. // tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to correct the dbxref id for the cvterm " .
  984. // "'$name' (id: $accession), for database $dbname", NULL);
  985. // return 0;
  986. // }
  987. // }
  988. // // If we don't have the dbxref then we want to delete our cvterm and let
  989. // // the code below recreate it with the correct info.
  990. // else {
  991. // $match = array('cvterm_id' => $cvterm->cvterm_id);
  992. // chado_delete_record('cvterm', $match);
  993. // }
  994. // }
  995. // Check that the accession matches. Sometimes an OBO can define a term
  996. // multiple times but with different accessions. If this is the case we
  997. // can't do an insert or it will violate the constraint in the cvterm table.
  998. // So we'll need to add the record to the cvterm_dbxref table instead.
  999. if ($dbxref->accession != $accession) {
  1000. // Get/add the dbxref for his term.
  1001. $dbxref_new = tripal_insert_dbxref(array(
  1002. 'db_id' => $db->db_id,
  1003. 'accession' => $accession
  1004. ));
  1005. if (!$dbxref_new) {
  1006. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  1007. "$name (id: $accession), for database $dbname", NULL);
  1008. return 0;
  1009. }
  1010. // Check to see if the cvterm_dbxref record already exists.
  1011. $values = array(
  1012. 'cvterm_id' => $cvterm->cvterm_id,
  1013. 'dbxref_id' => $dbxref_new->dbxref_id,
  1014. 'is_for_definition' => 1,
  1015. );
  1016. $result = chado_select_record('cvterm_dbxref', array('*'), $values);
  1017. // if the cvterm_dbxref record does not exists then add it
  1018. if (count($result)==0) {
  1019. $options = array(
  1020. 'return_record' => FALSE,
  1021. );
  1022. $success = chado_insert_record('cvterm_dbxref', $values, $options);
  1023. if (!$success) {
  1024. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the cvterm_dbxref record for a " .
  1025. "duplicated cvterm: $name (id: $accession), for database $dbname", NULL);
  1026. return 0;
  1027. }
  1028. }
  1029. // get the original cvterm with the same name and return that.
  1030. $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
  1031. $cvterm = $result->fetchObject();
  1032. return $cvterm;
  1033. }
  1034. // Continue on, we've fixed the record if the db_id did not match.
  1035. // We can now perform and updated if we need to.
  1036. }
  1037. // get the CVterm record
  1038. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  1039. $cvterm = $result->fetchObject();
  1040. if (!$cvterm) {
  1041. // Check to see if the dbxref exists if not, add it.
  1042. $dbxref = tripal_insert_dbxref(array(
  1043. 'db_id' => $db->db_id,
  1044. 'accession' => $accession
  1045. ));
  1046. if (!$dbxref) {
  1047. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  1048. "$name (id: $accession), for database $dbname", NULL);
  1049. return 0;
  1050. }
  1051. // Check to see if the dbxref already has an entry in the cvterm table.
  1052. $values = array('dbxref_id' => $dbxref->dbxref_id);
  1053. $check = chado_select_record('cvterm', array('cvterm_id'), $values);
  1054. if (count($check) == 0) {
  1055. // now add the cvterm
  1056. $ins_values = array(
  1057. 'cv_id' => $cv->cv_id,
  1058. 'name' => $name,
  1059. 'definition' => $definition,
  1060. 'dbxref_id' => $dbxref->dbxref_id,
  1061. 'is_obsolete' => $is_obsolete,
  1062. 'is_relationshiptype' => $is_relationship,
  1063. );
  1064. $success = chado_insert_record('cvterm', $ins_values);
  1065. if (!$success) {
  1066. if (!$is_relationship) {
  1067. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the term: $name ($dbname)", NULL);
  1068. return 0;
  1069. }
  1070. else {
  1071. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)", NULL);
  1072. return 0;
  1073. }
  1074. }
  1075. }
  1076. // This dbxref already exists in the cvterm table.
  1077. else {
  1078. tripal_report_error('tripal_cv', TRIPAL_WARNING, "The dbxref already exists for another cvterm record: $name (cv: " . $cvname . " db: $dbname)", NULL);
  1079. return 0;
  1080. }
  1081. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  1082. $cvterm = $result->fetchObject();
  1083. }
  1084. // Update the cvterm.
  1085. elseif ($update) {
  1086. // First, basic update of the term.
  1087. $match = array('cvterm_id' => $cvterm->cvterm_id);
  1088. $upd_values = array(
  1089. 'name' => $name,
  1090. 'definition' => $definition,
  1091. 'is_obsolete' => $is_obsolete,
  1092. 'is_relationshiptype' => $is_relationship,
  1093. );
  1094. $success = chado_update_record('cvterm', $match, $upd_values);
  1095. if (!$success) {
  1096. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to update the term: $name", NULL);
  1097. return 0;
  1098. }
  1099. // Second, check that the dbxref has not changed and if it has then update it.
  1100. $checksql = "
  1101. SELECT cvterm_id
  1102. FROM {cvterm} CVT
  1103. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  1104. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  1105. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  1106. WHERE DBX.accession = :accession and DB.name = :dbname and CVT.name = :term and CV.name = :cvname
  1107. ";
  1108. $check = chado_query($checksql, array(':accession' => $accession, ':dbname' => $dbname, ':term' => $name, ':cvname' => $cvname))->fetchObject();
  1109. if (!$check) {
  1110. // check to see if the dbxref exists if not, add it.
  1111. $dbxref = tripal_insert_dbxref(array(
  1112. 'db_id' => $db->db_id,
  1113. 'accession' => $accession
  1114. ));
  1115. if (!$dbxref) {
  1116. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  1117. "$name (id: $accession), for database $dbname", NULL);
  1118. return 0;
  1119. }
  1120. $match = array('cvterm_id' => $cvterm->cvterm_id);
  1121. $upd_values = array(
  1122. 'dbxref_id' => $dbxref->dbxref_id,
  1123. );
  1124. $success = chado_update_record('cvterm', $match, $upd_values);
  1125. if (!$success) {
  1126. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the term $name with new accession $db:$accession", NULL);
  1127. return 0;
  1128. }
  1129. }
  1130. // Finally grab the updated details.
  1131. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  1132. $cvterm = $result->fetchObject();
  1133. }
  1134. else {
  1135. // do nothing, we have the cvterm but we don't want to update
  1136. }
  1137. // return the cvterm
  1138. return $cvterm;
  1139. }
  1140. /**
  1141. * TODO: deprecate this function
  1142. *
  1143. * This function allows other modules to programatically
  1144. * submit an ontology for loading into Chado.
  1145. *
  1146. * This function will add a job to the Jobs subsystem for parsing the ontology.
  1147. * You can either pass a known OBO ID to the function or the URL
  1148. * or full path the the ontology file. If a URL or file name is
  1149. * passed then the $obo_name argument must also be provided. If
  1150. * this is the first time the ontology has been provided to Tripal
  1151. * then it will be added to the database and will be assigned a
  1152. * unique OBO ID.
  1153. *
  1154. * @param $obo_id
  1155. * If the ontology is already loaded into the Tripal tables then
  1156. * use this argument to specify the unique ID for the ontology
  1157. * that will be loaded
  1158. * @param $obo_name
  1159. * If the OBO has not been added before then use this argument
  1160. * to specify the human readable name of the ontology.
  1161. * @param $obo_url
  1162. * If the OBO to be loaded is located on a remote server then
  1163. * use this argument to provide the URL.
  1164. * @param $obo_file
  1165. * If the OBO is housed on the local file system of the server then
  1166. * use this argument to specify the full path.
  1167. *
  1168. * @return
  1169. * returns the job_id of the submitted job or FALSE if the job was not added
  1170. *
  1171. * @ingroup tripal_chado_api
  1172. */
  1173. function tripal_submit_obo_job($obo) {
  1174. global $user;
  1175. // Set Defaults
  1176. $obo['obo_id'] = (isset($obo['obo_id'])) ? $obo['obo_id'] : NULL;
  1177. $obo['name'] = (isset($obo['name'])) ? $obo['name'] : NULL;
  1178. $obo['url'] = (isset($obo['url'])) ? $obo['url'] : NULL;
  1179. $obo['file'] = (isset($obo['file'])) ? $obo['file'] : NULL;
  1180. $includes = array(
  1181. drupal_get_path('module', 'tripal_chado') . '/includes/tripal_chado.cv.inc',
  1182. );
  1183. if ($obo['obo_id']) {
  1184. $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = :obo_id";
  1185. $result = db_query($sql, array(':obo_id' => $obo['obo_id']))->fetchObject();
  1186. $args = array($result->obo_id);
  1187. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1188. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1189. }
  1190. else {
  1191. if ($obo['url']) {
  1192. $sql = "SELECT * FROM {tripal_cv_obo} WHERE path = :url";
  1193. $result = db_query($sql, array(':url' => $obo['url']))->fetchObject();
  1194. $args = array($result->obo_id);
  1195. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1196. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1197. }
  1198. elseif ($obo['file']) {
  1199. $sql = "SELECT * FROM {tripal_cv_obo} WHERE path = :file";
  1200. $result = db_query($sql, array(':url' => $obo['file']))->fetchObject();
  1201. $args = array($result->obo_id);
  1202. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1203. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1204. }
  1205. }
  1206. return FALSE;
  1207. }
  1208. /**
  1209. * Add the OBO to the tripal_cv_obo table in the Drupal database.
  1210. *
  1211. * If the OBO name already exists in the table then the path is updated.
  1212. *
  1213. * @param $name
  1214. * The human readable name of this ontology
  1215. * @param $path
  1216. * The file path or URL of the ontology
  1217. *
  1218. * @return
  1219. * Returns the ontology ID
  1220. *
  1221. * @ingroup tripal_chado_api
  1222. */
  1223. function tripal_insert_obo($name, $path) {
  1224. // make sure an OBO with the same name doesn't already exist
  1225. $obo_id = db_select('tripal_cv_obo', 'tco')
  1226. ->fields('tco', array('obo_id'))
  1227. ->condition('name', $name)
  1228. ->execute()
  1229. ->fetchField();
  1230. if ($obo_id) {
  1231. db_update('tripal_cv_obo')
  1232. ->fields(array(
  1233. 'path' => $path,
  1234. ))
  1235. ->condition('name', $name)
  1236. ->execute();
  1237. return $obo_id;
  1238. }
  1239. else {
  1240. $obo_id = db_insert('tripal_cv_obo')
  1241. ->fields(array(
  1242. 'name' => $name,
  1243. 'path' => $path,
  1244. ))
  1245. ->execute();
  1246. return $obo_id;
  1247. }
  1248. }
  1249. /**
  1250. * Retrieves an OBO record.
  1251. *
  1252. * @param $values
  1253. * An associate array with the following allowed keys: obo_id, name
  1254. *
  1255. * @return
  1256. * An instance of an OBO record object.
  1257. */
  1258. function tripal_get_obo($values) {
  1259. $query = db_select('tripal_cv_obo', 'tco')
  1260. ->fields('tco');
  1261. if (array_key_exists('name', $values)) {
  1262. $query->condition('tco.name', $values['name']);
  1263. }
  1264. if (array_key_exists('obo_id', $values)) {
  1265. $query->condition('tco.obo_id', $values['obo_id']);
  1266. }
  1267. return $query->execute()->fetchObject();
  1268. }
  1269. /**
  1270. * This function is intended to be used in autocomplete forms.
  1271. *
  1272. * This function searches for a matching controlled vobulary name.
  1273. *
  1274. * @param $string
  1275. * The string to search for
  1276. *
  1277. * @return
  1278. * A json array of terms that begin with the provided string
  1279. *
  1280. * @ingroup tripal_chado_api
  1281. */
  1282. function tripal_autocomplete_cv($string = '') {
  1283. $sql = "
  1284. SELECT CV.cv_id, CV.name
  1285. FROM {cv} CV
  1286. WHERE lower(CV.name) like lower(:name)
  1287. ORDER by CV.name
  1288. LIMIT 25 OFFSET 0
  1289. ";
  1290. $results = chado_query($sql, array(':name' => $string . '%'));
  1291. $items = array();
  1292. foreach ($results as $cv) {
  1293. $items[$cv->name] = $cv->name;
  1294. }
  1295. drupal_json_output($items);
  1296. }
  1297. /**
  1298. * This function is intended to be used in autocomplete forms
  1299. * for searching for CV terms that begin with the provided string
  1300. *
  1301. * @param $cv_id
  1302. * The CV ID in which to search for the term
  1303. * @param $string
  1304. * The string to search for
  1305. *
  1306. * @return
  1307. * A json array of terms that begin with the provided string
  1308. *
  1309. * @ingroup tripal_chado_api
  1310. */
  1311. function tripal_autocomplete_cvterm($cv_id, $string = '') {
  1312. if ($cv_id) {
  1313. $sql = "
  1314. SELECT CVT.cvterm_id, CVT.name
  1315. FROM {cvterm} CVT
  1316. WHERE CVT.cv_id = :cv_id and lower(CVT.name) like lower(:name)
  1317. UNION
  1318. SELECT CVT2.cvterm_id, CVTS.synonym as name
  1319. FROM {cvterm} CVT2
  1320. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  1321. WHERE CVT2.cv_id = :cv_id and lower(CVTS.synonym) like lower(:name)
  1322. ORDER by name
  1323. LIMIT 25 OFFSET 0
  1324. ";
  1325. $results = chado_query($sql, array(':cv_id' => $cv_id, ':name' => $string . '%'));
  1326. $items = array();
  1327. foreach ($results as $term) {
  1328. $items[$term->name] = $term->name;
  1329. }
  1330. }
  1331. // If a CV wasn't provided then search all of them, and include the cv
  1332. // in the results.
  1333. else {
  1334. $sql = "
  1335. SELECT CVT.cvterm_id, CVT.name, CV.name as cvname, CVT.cv_id
  1336. FROM {cvterm} CVT
  1337. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  1338. WHERE lower(CVT.name) like lower(:name)
  1339. UNION
  1340. SELECT CVT2.cvterm_id, CVTS.synonym as name, CV2.name as cvname, CVT2.cv_id
  1341. FROM {cvterm} CVT2
  1342. INNER JOIN {cv} CV2 on CVT2.cv_id = CV2.cv_id
  1343. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  1344. WHERE lower(CVTS.synonym) like lower(:name)
  1345. ORDER by name
  1346. LIMIT 25 OFFSET 0
  1347. ";
  1348. $results = chado_query($sql, array(':name' => $string . '%'));
  1349. $items = array();
  1350. foreach ($results as $term) {
  1351. $items[$term->name] = $term->name;
  1352. }
  1353. }
  1354. drupal_json_output($items);
  1355. }
  1356. /**
  1357. * Add a record to a cvterm linking table (ie: feature_cvterm)
  1358. *
  1359. * @param $basetable
  1360. * The base table to which the cvterm should be linked/associated. Thus to associate a
  1361. * cvterm to a feature the basetable=feature and cvterm_id is added to the feature_cvterm table.
  1362. * @param $record_id
  1363. * The primary key of the basetable to associate the cvterm with. This should be in integer.
  1364. * @param $cvterm
  1365. * An associative array describing the cvterm. Valid keys include:
  1366. * - name: the name for the cvterm,
  1367. * - cv_name: the name of the cv the cvterm belongs to.
  1368. * - cv_id: the primary key of the cv the cvterm belongs to.
  1369. * @param $options
  1370. * An associative array of options. Valid keys include:
  1371. * - insert_cvterm: Insert the cvterm if it doesn't already exist. FALSE is the default
  1372. *
  1373. * @ingroup tripal_chado_api
  1374. */
  1375. function tripal_associate_cvterm($basetable, $record_id, $cvterm, $options = array()) {
  1376. $linking_table = $basetable . '_cvterm';
  1377. $foreignkey_name = $basetable . '_id';
  1378. // Default Values
  1379. $options['insert_cvterm'] = (isset($options['insert_cvterm'])) ? $options['insert_cvterm'] : FALSE;
  1380. // If the cvterm_id is not set then find the cvterm record using the name and cv_id
  1381. if (!isset($cvterm['cvterm_id'])) {
  1382. $values = array(
  1383. 'name' => $cvterm['name'],
  1384. );
  1385. if (isset($cvterm['cv_id'])) {
  1386. $values['cv_id'] = $cvterm['cv_id'];
  1387. }
  1388. elseif (isset($cvterm['cv_name'])) {
  1389. $values['cv_id'] = array(
  1390. 'name' => $cvterm['cv_name']
  1391. );
  1392. }
  1393. else {
  1394. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  1395. "tripal_associate_cvterm: The cvterm needs to have either the cv_name or cv_id
  1396. supplied. You were trying to associate a cvterm with the %base %record_id
  1397. and supplied the cvterm values: %cvterm.",
  1398. array('%base' => $basetable, '%record_id' => $record_id, '%cvterm' => print_r($cvterm,TRUE))
  1399. );
  1400. return FALSE;
  1401. }
  1402. // Get the cvterm. If it doesn't exist then add it if the option
  1403. // 'insert_cvterm' is set.
  1404. $select = chado_select_record('cvterm', array('*'), $values);
  1405. if ($select) {
  1406. $cvterm['cvterm_id'] = $select[0]->cvterm_id;
  1407. }
  1408. elseif ($options['insert_cvterm']) {
  1409. // Insert the cvterm
  1410. $insert = tripal_insert_cvterm($values);
  1411. if (isset($insert->cvterm_id)) {
  1412. $cvterm['cvterm_id'] = $insert->cvterm_id;
  1413. }
  1414. else {
  1415. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  1416. "tripal_associate_cvterm: Unable to insert the cvterm using the cvterm values: %cvterm.",
  1417. array('%cvterm' => print_r($cvterm,TRUE))
  1418. );
  1419. return FALSE;
  1420. }
  1421. }
  1422. else {
  1423. tripal_report_error('tripal_api', TRIPAL_WARNING,
  1424. "tripal_associate_cvterm: The cvterm doesn't already exist. You supplied the cvterm values: %cvterm.",
  1425. array('%cvterm' => print_r($cvterm,TRUE))
  1426. );
  1427. return FALSE;
  1428. }
  1429. }
  1430. // Now add the link between the record & cvterm
  1431. if ($cvterm['cvterm_id'] > 0) {
  1432. $values = array(
  1433. 'cvterm_id' => $cvterm['cvterm_id'],
  1434. $foreignkey_name => $record_id,
  1435. 'pub_id' => 1,
  1436. );
  1437. // Check if the cvterm is already associated. If so, don't re-add it.
  1438. $result = chado_select_record($linking_table, array('*'), $values);
  1439. if (!$result) {
  1440. $success = chado_insert_record($linking_table, $values);
  1441. if (!$success) {
  1442. tripal_report_error('tripal_api', TRIPAL_WARNING,
  1443. "Failed to insert the %base record %term",
  1444. array('%base' => $linking_table, '%term' => $cvterm['name'])
  1445. );
  1446. return FALSE;
  1447. }
  1448. $result = chado_select_record($linking_table, array('*'), $values);
  1449. }
  1450. if (isset($result[0])) {
  1451. return $result[0];
  1452. }
  1453. else {
  1454. return FALSE;
  1455. }
  1456. }
  1457. return FALSE;
  1458. }
  1459. /**
  1460. * This function sets the default vocabulary for a given table and field.
  1461. *
  1462. * @param $table
  1463. * The name of the table that contains a field with a foreign key
  1464. * relationship to the cvterm table
  1465. * @param $field
  1466. * The table field name that has the foreign key relationship to the
  1467. * cvterm table for which the default vocabulary will be set
  1468. * @param $cv_name
  1469. * The name of the vocabulary
  1470. *
  1471. * @return
  1472. * TRUE if set, FALSE if an error occured
  1473. */
  1474. function tripal_set_default_cv($table, $field, $cv_name, $cv_id = FALSE) {
  1475. // Get the CV object
  1476. if ($cv_id) {
  1477. $cv = tripal_get_cv(array('cv_id' => $cv_id));
  1478. }
  1479. else {
  1480. $cv = tripal_get_cv(array('name' => $cv_name));
  1481. }
  1482. if ($cv) {
  1483. // first delete any entries for this table and field
  1484. $num_deleted = db_delete('tripal_cv_defaults')
  1485. ->condition('table_name', $table)
  1486. ->condition('field_name', $field)
  1487. ->execute();
  1488. // now add the default value
  1489. $cv_default_id = db_insert('tripal_cv_defaults')
  1490. ->fields(array(
  1491. 'table_name' => $table,
  1492. 'field_name' => $field,
  1493. 'cv_id' => $cv->cv_id,
  1494. ))
  1495. ->execute();
  1496. if (!$cv_default_id) {
  1497. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  1498. "Cannot set default vocabulary for %table.%field. Check the error logs.",
  1499. array('%table' => $table, '%field' => $field));
  1500. return FALSE;
  1501. }
  1502. }
  1503. else {
  1504. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  1505. "Cannot set default vocabulary for %table.%field. The vocabulary name, '%cvname', doesn't exist.",
  1506. array('%table' => $table, '%field' => $field, '%cvname' => $cv_name));
  1507. return FALSE;
  1508. }
  1509. }