tripal_chado.cv.api.inc 48 KB

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