tripal_chado.cv.api.inc 54 KB

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