tripal_chado.cv.api.inc 54 KB

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