tripal_chado.cv.api.inc 52 KB

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