tripal_chado.cv.api.inc 52 KB

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