tripal_chado.cv.api.inc 54 KB

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