tripal_chado.cv.api.inc 55 KB

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