tripal_chado.cv.api.inc 52 KB

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