tripal_chado.cv.api.inc 52 KB

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