tripal_chado.cv.api.inc 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  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. $prev_db = chado_set_active('chado');
  379. $transaction = db_transaction();
  380. try {
  381. // Get the is_a term. The OBO importer adds this for evey vocabulary.
  382. $sql = "SELECT * FROM cvterm WHERE name = :is_a and cv_id = :cv_id";
  383. $args = [':is_a' => 'is_a', ':cv_id' => $cv_id];
  384. $cache['$is_a'] = chado_query($sql, $args)->fetchObject();
  385. // First cache all the relationships for this vocaublary so that we
  386. // don't have to do repetitive queries to Chado.
  387. print "Retrieving relationships...\n";
  388. $sql = "
  389. SELECT CVTR.subject_id, CVTR.type_id, CVTR.object_id, CVTS.name
  390. FROM {cvterm_relationship} CVTR
  391. INNER JOIN {cvterm} CVTO on CVTO.cvterm_id = CVTR.object_id
  392. INNER JOIN {cvterm} CVTS on CVTS.cvterm_id = CVTR.subject_id
  393. WHERE CVTO.cv_id = :cv_id
  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. chado_set_active($prev_db);
  439. throw $e;
  440. }
  441. }
  442. /**
  443. * Treats a term within the ontology as a root.
  444. *
  445. * In order to add all relationships between a term and it's descendents each
  446. * term gets it's turn as a "root". The first time this function is called
  447. * it should be called with the actual root's of the ontology. This function
  448. * will then recursively treat each child term within the tree as a root in
  449. * order to find all relationships.
  450. *
  451. * @param $cv_id
  452. * The vocaulary Id
  453. * @param $root_id
  454. * This root term's cvterm Id.
  455. * @param $root_name
  456. * The name of this root term.
  457. * @param $cache
  458. * The cache used for lookups.
  459. * @param $job
  460. * The TripalJob instance.
  461. * @param $num_handled
  462. * Used to keep track of the number of nodes that have been handled for
  463. * progress reporting.
  464. * @param $root_depth
  465. * The current depth in the tree of this term.
  466. */
  467. function _chado_update_cvtermpath_root($cv_id, $root_id, $root_name, &$cache,
  468. $job, &$num_handled, $root_depth = 0) {
  469. // Don't use a node as a root if we've already used it once before.
  470. if (in_array($root_id, $cache['roots_processed'])) {
  471. return;
  472. }
  473. // Mark this node as having been processed as a root node.
  474. $cache['roots_processed'][] = $root_id;
  475. // For the actual tree roots we need to add a relatioship to themselves.
  476. if ($root_depth == 0) {
  477. $is_a = $cache['$is_a'];
  478. $type_id = $is_a->cvterm_id;
  479. $depth = 1;
  480. _chado_update_cvtermpath_add_relationship($type_id, $root_id, $root_id, $cv_id, $depth);
  481. }
  482. // Get this term's children and recurse.
  483. $children = $cache['rels'][$root_id];
  484. // If there are no children do nothing.
  485. if (!$children) {
  486. return;
  487. }
  488. // Set the job progress.
  489. if ($job) {
  490. $job->setItemsHandled($num_handled);
  491. }
  492. $num_handled++;
  493. // The $path variable contains only the current path on the descent. This
  494. // is used for detecting loops in the graph. If we encounter a node a
  495. // second time while traversing a single path of the tree then we've hit
  496. // a loop.
  497. $path = [];
  498. // Process the children of this term.
  499. $cache['nodes_processed'] = [];
  500. _chado_update_cvtermpath_process_children($cv_id, $root_id, $root_id, $path, $cache, $next_depth);
  501. // Next make each child of this node a root and recurse again.
  502. foreach ($children as $child) {
  503. $child_id = $child[0];
  504. $child_type_id = $child[1];
  505. $child_name = $child[2];
  506. // Process this child as a root.
  507. $next_depth = $root_depth + 1;
  508. _chado_update_cvtermpath_root($cv_id, $child_id, $child_name, $cache,
  509. $job, $num_handled, $next_depth);
  510. }
  511. }
  512. /**
  513. * Handles a single node in the tree.
  514. *
  515. * This is a recursive function which calls itself as the tree is descended. It
  516. * performs a depth-first search of the tree.
  517. *
  518. * @param $cv_id
  519. * The vocaulary Id
  520. * @param $root_id
  521. * This root term's cvterm Id.
  522. * @param $cvterm_id
  523. * This term's cvterm Id.
  524. * @param $path
  525. * An array used for storing the current path down the tree. This is the
  526. * sequence of nodes visited to this point down a single branch.
  527. * @param $cache
  528. * The cache used for lookups.
  529. * @param $depth
  530. * The current depth in the tree.
  531. */
  532. function _chado_update_cvtermpath_process_children($cv_id, $root_id, $cvterm_id,
  533. $path, &$cache, $depth = 1) {
  534. $cache['nodes_processed'][$cvterm_id] = TRUE;
  535. // Have we visited this node before while on this path then we won't
  536. // descend further as this means we've hit a loop.
  537. if (in_array($cvterm_id, $path)) {
  538. return;
  539. }
  540. // Add this term to the path.
  541. $path[] = $cvterm_id;
  542. //print implode('-', $path) . "\n";
  543. // Get this term's children and recurse.
  544. $children = $cache['rels'][$cvterm_id];
  545. // If this term does not have children then return.
  546. if (!$children) {
  547. return;
  548. }
  549. // If the term has children then recurse on those.
  550. $next_depth = $depth + 1;
  551. foreach ($children as $child) {
  552. $child_id = $child[0];
  553. $child_type_id = $child[1];
  554. _chado_update_cvtermpath_add_relationship($child_type_id, $child_id, $root_id,
  555. $cv_id, $next_depth);
  556. // Don't descend for children we've already seen.
  557. if (array_key_exists($child_id, $cache['nodes_processed'])) {
  558. continue;
  559. }
  560. _chado_update_cvtermpath_process_children($cv_id, $root_id, $child_id, $path, $cache, $next_depth);
  561. }
  562. }
  563. /**
  564. * Inserts values into the cvtermpath table.
  565. *
  566. * After the entire tree below the current root term is traversed, this
  567. * function is called and inserts all of the relationships that were found
  568. * into the cvtermpath table.
  569. *
  570. * @param $visited
  571. * The array contaiing relationships for all visited nodes in the tree. These
  572. * elements will become the entries in the cvtermpath table.
  573. * @param $job
  574. * The TripalJob instance.
  575. */
  576. function _chado_update_cvtermpath_add_relationship($type_id, $cvterm_id,
  577. $root_id, $cv_id, $depth) {
  578. $cvtermpath = new ChadoRecord('cvtermpath');
  579. $cvtermpath->setValues([
  580. 'type_id' => $type_id,
  581. 'subject_id' => $cvterm_id,
  582. 'object_id' => $root_id,
  583. 'cv_id' => $cv_id,
  584. 'pathdistance' => $depth,
  585. ]);
  586. $cvtermpath->insert();
  587. }
  588. /**
  589. * Adds a controlled vocabulary to the CV table of Chado.
  590. *
  591. * @param $name
  592. * The name of the controlled vocabulary. These are typically all lower case
  593. * with no special characters other than an undrescore (for spaces).
  594. * @param $comment
  595. * A description or definition of the vocabulary.
  596. *
  597. * @return
  598. * An object populated with fields from the newly added database.
  599. *
  600. * @ingroup tripal_chado_cv_api
  601. */
  602. function chado_insert_cv($name, $definition) {
  603. // Insert/update values.
  604. $ins_values = array(
  605. 'name' => $name,
  606. 'definition' => $definition
  607. );
  608. // See if the CV default exists already in the database.
  609. $sel_values = array('name' => $name);
  610. $results = chado_select_record('cv', array('*'), $sel_values);
  611. // If it does not exists then add it.
  612. if (count($results) == 0) {
  613. $success = chado_insert_record('cv', $ins_values);
  614. if (!$success) {
  615. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to create the CV record", NULL);
  616. return FALSE;
  617. }
  618. $results = chado_select_record('cv', array('*'), $sel_values);
  619. }
  620. // If it already exists then do an update.
  621. else {
  622. $success = chado_update_record('cv', $sel_values, $ins_values);
  623. if (!$success) {
  624. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the CV record", NULL);
  625. return FALSE;
  626. }
  627. $results = chado_select_record('cv', array('*'), $sel_values);
  628. }
  629. // Return the cv object.
  630. return $results[0];
  631. }
  632. /**
  633. * Add's a controlled vocabulary term to Chado.
  634. *
  635. * This function will add a cvterm record (and a dbxref record if appropriate
  636. * values are provided). If the parent vocabulary does not exist then
  637. * that also is added to the cv table. If the cvterm is a relationship term
  638. * then the 'is_relationship' value should be set. All
  639. * terms must also have a corresponding database. This is specified in the
  640. * term's ID just before the colon (e.g. GO:003824). If the database does not
  641. * exist in the DB table then it will be added automatically. The accession
  642. * (the value just after the colon in the term's ID) will be added to the
  643. * dbxref table. If the CVterm already exists and $update is set (default)
  644. * then the cvterm is updated. If the CVTerm already exists and $update is
  645. * not set, then no changes are made and the CVTerm object is returned.
  646. *
  647. * @param $term
  648. * An associative array with the following keys:
  649. * - id: the term accession. must be of the form <DB>:<ACCESSION>, where
  650. * <DB> is the name of the database to which the cvterm belongs and the
  651. * <ACCESSION> is the term's accession number in the database.
  652. * - name: the name of the term. usually meant to be human-readable.
  653. * - is_obsolete: is present and set to 1 if the term is defunct.
  654. * - definition: the definition of the term.
  655. * - cv_name: The CV name to which the term belongs. If this arugment is
  656. * null or not provided then the function tries to find a record in the
  657. * CV table with the same name provided in the $term[namespace]. If
  658. * this field is provided then it overrides what the value in
  659. * $term[namespace].
  660. * - is_relationship: If this term is a relationship term then this value
  661. * should be 1.
  662. * - db_name: In some cases the database name will not be part of the
  663. * $term['id'] and it needs to be explicitly set. Use this argument
  664. * only if the database name cannot be specififed in the term ID
  665. * (e.g. <DB>:<ACCESSION>).
  666. * @param $options
  667. * An associative array with the following keys:
  668. * - update_existing: By default this is TRUE. If the term exists it is
  669. * automatically updated.
  670. *
  671. * @return
  672. * A cvterm object
  673. *
  674. * @ingroup tripal_chado_cv_api
  675. */
  676. function chado_insert_cvterm($term, $options = array()) {
  677. // Get the term properties.
  678. $id = (isset($term['id'])) ? $term['id'] : '';
  679. $name = '';
  680. $cvname = '';
  681. $definition = '';
  682. $is_obsolete = 0;
  683. $accession = '';
  684. // Set Defaults.
  685. if (isset($term['cv_name'])) {
  686. $cvname = $term['cv_name'];
  687. }
  688. else {
  689. $cvname = 'local';
  690. }
  691. // Namespace is deprecated but must be supported for backwards
  692. // compatability.
  693. if (array_key_exists('namespace', $term)) {
  694. $cvname = $term['namespace'];
  695. }
  696. if (isset($term['is_relationship'])) {
  697. $is_relationship = $term['is_relationship'];
  698. }
  699. else {
  700. $is_relationship = 0;
  701. }
  702. if (isset($term['db_name'])) {
  703. $dbname = $term['db_name'];
  704. }
  705. else {
  706. $dbname = 'internal';
  707. }
  708. if (isset($options['update_existing'])) {
  709. $update = $options['update_existing'];
  710. }
  711. else {
  712. $update = 1;
  713. }
  714. if (array_key_exists('name', $term)) {
  715. $name = $term['name'];
  716. }
  717. else {
  718. $name = $id;
  719. }
  720. if (array_key_exists('definition', $term)) {
  721. $definition = preg_replace('/^\"(.*)\"/', '\1', $term['definition']);
  722. }
  723. else {
  724. $definition = '';
  725. }
  726. if (array_key_exists('is_obsolete', $term)) {
  727. $is_obsolete = $term['is_obsolete'];
  728. if (strcmp($is_obsolete, 'true') == 0) {
  729. $is_obsolete = 1;
  730. }
  731. }
  732. if (!$name and !$id) {
  733. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find cvterm without 'id' or 'name'", NULL);
  734. return 0;
  735. }
  736. if (!$id) {
  737. $id = $name;
  738. }
  739. // Get the accession and the database from the cvterm id.
  740. if ($dbname) {
  741. $accession = $id;
  742. }
  743. if (preg_match('/^.+?:.*$/', $id)) {
  744. $accession = preg_replace('/^.+?:(.*)$/', '\1', $id);
  745. $dbname = preg_replace('/^(.+?):.*$/', '\1', $id);
  746. }
  747. // Check that we have a database name, give a different message if it's a
  748. // relationship.
  749. if ($is_relationship and !$dbname) {
  750. tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database name is not provided for this relationship term: $id", NULL);
  751. return 0;
  752. }
  753. if (!$is_relationship and !$dbname) {
  754. tripal_report_error('tripal_cv', TRIPAL_WARNING, "A database identifier is missing from the term: $id", NULL);
  755. return 0;
  756. }
  757. // Make sure the CV name exists.
  758. $cv = chado_get_cv(array('name' => $cvname));
  759. if (!$cv) {
  760. $cv = chado_insert_cv($cvname, '');
  761. }
  762. if (!$cv) {
  763. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find namespace '$cvname' when adding/updating $id", NULL);
  764. return 0;
  765. }
  766. // This SQL statement will be used a lot to find a cvterm so just set it
  767. // here for easy reference below. Because CV terms can change their names
  768. // but accessions don't change, the following SQL finds cvterms based on
  769. // their accession rather than the name.
  770. $cvtermsql = "
  771. SELECT CVT.name, CVT.cvterm_id, CV.cv_id, CV.name as cvname,
  772. DB.name as dbname, DB.db_id, DBX.accession
  773. FROM {cvterm} CVT
  774. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  775. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  776. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  777. WHERE DBX.accession = :accession and DB.name = :name
  778. ";
  779. // Add the database. The function will just return the DB object if the
  780. // database already exists.
  781. $db = chado_get_db(array('name' => $dbname));
  782. if (!$db) {
  783. $db = chado_insert_db(array('name' => $dbname));
  784. }
  785. if (!$db) {
  786. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Cannot find database '$dbname' in Chado.", NULL);
  787. return 0;
  788. }
  789. // The cvterm table has two unique dependencies. We need to check both.
  790. // first check the (name, cv_id, is_obsolete) constraint.
  791. $values = array(
  792. 'name' => $name,
  793. 'is_obsolete' => $is_obsolete,
  794. 'cv_id' => array(
  795. 'name' => $cvname,
  796. ),
  797. );
  798. $result = chado_select_record('cvterm', array('*'), $values);
  799. if (count($result) == 1) {
  800. $cvterm = $result[0];
  801. // Get the dbxref record.
  802. $values = array('dbxref_id' => $cvterm->dbxref_id);
  803. $result = chado_select_record('dbxref', array('*'), $values);
  804. $dbxref = $result[0];
  805. if (!$dbxref) {
  806. tripal_report_error('tripal_cv', TRIPAL_ERROR,
  807. 'Unable to access the dbxref record for the :term cvterm. Term Record: !record',
  808. array(':term' => $name, '!record' => print_r($cvterm, TRUE))
  809. );
  810. return FALSE;
  811. }
  812. // Get the db.
  813. $values = array('db_id' => $dbxref->db_id);
  814. $result = chado_select_record('db', array('*'), $values);
  815. $db_check = $result[0];
  816. // // The database name for this existing term does not match that of the
  817. // // one provided to this function. The CV name matches otherwise we
  818. // // wouldn't have made it this far. So, let's swap the database for
  819. // // this term.
  820. // if ($db_check->name != $db->name) {
  821. // // Look to see if the correct dbxref record already exists for this
  822. // // database.
  823. // $values = array(
  824. // 'db_id' => $db->db_id,
  825. // 'accession' => $accession,
  826. // );
  827. // $result = chado_select_record('dbxref', array('*'), $values);
  828. // // If we already have a good dbxref then we want to update our cvterm
  829. // // to use this dbxref.
  830. // if (count($result) > 0) {
  831. // $dbxref = $result[0];
  832. // $match = array('cvterm_id' => $cvterm->cvterm_id);
  833. // $values = array('dbxref_id' => $dbxref->dbxref_id);
  834. // $success = chado_update_record('cvterm', $match, $values);
  835. // if (!$success) {
  836. // tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to correct the dbxref id for the cvterm " .
  837. // "'$name' (id: $accession), for database $dbname", NULL);
  838. // return 0;
  839. // }
  840. // }
  841. // // If we don't have the dbxref then we want to delete our cvterm and let
  842. // // the code below recreate it with the correct info.
  843. // else {
  844. // $match = array('cvterm_id' => $cvterm->cvterm_id);
  845. // chado_delete_record('cvterm', $match);
  846. // }
  847. // }
  848. // Check that the accession matches. Sometimes an OBO can define a term
  849. // multiple times but with different accessions. If this is the case we
  850. // can't do an insert or it will violate the constraint in the cvterm table.
  851. // So we'll need to add the record to the cvterm_dbxref table instead.
  852. if ($dbxref->accession != $accession) {
  853. // Get/add the dbxref for his term.
  854. $dbxref_new = chado_insert_dbxref(array(
  855. 'db_id' => $db->db_id,
  856. 'accession' => $accession
  857. ));
  858. if (!$dbxref_new) {
  859. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  860. "$name (id: $accession), for database $dbname", NULL);
  861. return 0;
  862. }
  863. // Check to see if the cvterm_dbxref record already exists.
  864. $values = array(
  865. 'cvterm_id' => $cvterm->cvterm_id,
  866. 'dbxref_id' => $dbxref_new->dbxref_id,
  867. 'is_for_definition' => 1,
  868. );
  869. $result = chado_select_record('cvterm_dbxref', array('*'), $values);
  870. // if the cvterm_dbxref record does not exists then add it
  871. if (count($result)==0) {
  872. $options = array(
  873. 'return_record' => FALSE,
  874. );
  875. $success = chado_insert_record('cvterm_dbxref', $values, $options);
  876. if (!$success) {
  877. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the cvterm_dbxref record for a " .
  878. "duplicated cvterm: $name (id: $accession), for database $dbname", NULL);
  879. return 0;
  880. }
  881. }
  882. // Get the original cvterm with the same name and return that.
  883. $result = chado_query($cvtermsql, array(':accession' => $dbxref->accession, ':name' => $dbname));
  884. $cvterm = $result->fetchObject();
  885. return $cvterm;
  886. }
  887. // Continue on, we've fixed the record if the db_id did not match.
  888. // We can now perform and updated if we need to.
  889. }
  890. // Get the CVterm record.
  891. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  892. $cvterm = $result->fetchObject();
  893. if (!$cvterm) {
  894. // Check to see if the dbxref exists if not, add it.
  895. $dbxref = chado_insert_dbxref(array(
  896. 'db_id' => $db->db_id,
  897. 'accession' => $accession
  898. ));
  899. if (!$dbxref) {
  900. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  901. "$name (id: $accession), for database $dbname", NULL);
  902. return 0;
  903. }
  904. // Check to see if the dbxref already has an entry in the cvterm table.
  905. $values = array('dbxref_id' => $dbxref->dbxref_id);
  906. $check = chado_select_record('cvterm', array('cvterm_id'), $values);
  907. if (count($check) == 0) {
  908. // now add the cvterm
  909. $ins_values = array(
  910. 'cv_id' => $cv->cv_id,
  911. 'name' => $name,
  912. 'definition' => $definition,
  913. 'dbxref_id' => $dbxref->dbxref_id,
  914. 'is_obsolete' => $is_obsolete,
  915. 'is_relationshiptype' => $is_relationship,
  916. );
  917. $success = chado_insert_record('cvterm', $ins_values);
  918. if (!$success) {
  919. if (!$is_relationship) {
  920. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the term: $name ($dbname)", NULL);
  921. return 0;
  922. }
  923. else {
  924. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to insert the relationship term: $name (cv: " . $cvname . " db: $dbname)", NULL);
  925. return 0;
  926. }
  927. }
  928. }
  929. // This dbxref already exists in the cvterm table.
  930. else {
  931. tripal_report_error('tripal_cv', TRIPAL_WARNING, "The dbxref already exists for another cvterm record: $name (cv: " . $cvname . " db: $dbname)", NULL);
  932. return 0;
  933. }
  934. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  935. $cvterm = $result->fetchObject();
  936. }
  937. // Update the cvterm.
  938. elseif ($update) {
  939. // First, basic update of the term.
  940. $match = array('cvterm_id' => $cvterm->cvterm_id);
  941. $upd_values = array(
  942. 'name' => $name,
  943. 'definition' => $definition,
  944. 'is_obsolete' => $is_obsolete,
  945. 'is_relationshiptype' => $is_relationship,
  946. );
  947. $success = chado_update_record('cvterm', $match, $upd_values);
  948. if (!$success) {
  949. tripal_report_error('tripal_cv', TRIPAL_WARNING, "Failed to update the term: $name", NULL);
  950. return 0;
  951. }
  952. // Second, check that the dbxref has not changed and if it has then update
  953. // it.
  954. $checksql = "
  955. SELECT cvterm_id
  956. FROM {cvterm} CVT
  957. INNER JOIN {dbxref} DBX on CVT.dbxref_id = DBX.dbxref_id
  958. INNER JOIN {db} DB on DBX.db_id = DB.db_id
  959. INNER JOIN {cv} CV on CV.cv_id = CVT.cv_id
  960. WHERE DBX.accession = :accession and DB.name = :dbname and CVT.name = :term and CV.name = :cvname
  961. ";
  962. $check = chado_query($checksql, array(':accession' => $accession, ':dbname' => $dbname, ':term' => $name, ':cvname' => $cvname))->fetchObject();
  963. if (!$check) {
  964. // Check to see if the dbxref exists if not, add it.
  965. $dbxref = chado_insert_dbxref(array(
  966. 'db_id' => $db->db_id,
  967. 'accession' => $accession
  968. ));
  969. if (!$dbxref) {
  970. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to find or insert the dbxref record for cvterm, " .
  971. "$name (id: $accession), for database $dbname", NULL);
  972. return 0;
  973. }
  974. $match = array('cvterm_id' => $cvterm->cvterm_id);
  975. $upd_values = array(
  976. 'dbxref_id' => $dbxref->dbxref_id,
  977. );
  978. $success = chado_update_record('cvterm', $match, $upd_values);
  979. if (!$success) {
  980. tripal_report_error('tripal_chado', TRIPAL_WARNING, "Failed to update the term $name with new accession $db:$accession", NULL);
  981. return 0;
  982. }
  983. }
  984. // Finally grab the updated details.
  985. $result = chado_query($cvtermsql, array(':accession' => $accession, ':name' => $dbname));
  986. $cvterm = $result->fetchObject();
  987. }
  988. else {
  989. // Do nothing, we have the cvterm but we don't want to update.
  990. }
  991. // Return the cvterm.
  992. return $cvterm;
  993. }
  994. /**
  995. * TODO: deprecate this function
  996. *
  997. * Avoid using this function as it will be deprecated in future releases.
  998. *
  999. * This function allows other modules to programatically
  1000. * submit an ontology for loading into Chado.
  1001. *
  1002. * This function will add a job to the Jobs subsystem for parsing the ontology.
  1003. * You can either pass a known OBO ID to the function or the URL
  1004. * or full path the the ontology file. If a URL or file name is
  1005. * passed then the $obo_name argument must also be provided. If
  1006. * this is the first time the ontology has been provided to Tripal
  1007. * then it will be added to the database and will be assigned a
  1008. * unique OBO ID.
  1009. *
  1010. * @param $obo_id
  1011. * If the ontology is already loaded into the Tripal tables then
  1012. * use this argument to specify the unique ID for the ontology
  1013. * that will be loaded.
  1014. * @param $obo_name
  1015. * If the OBO has not been added before then use this argument
  1016. * to specify the human readable name of the ontology.
  1017. * @param $obo_url
  1018. * If the OBO to be loaded is located on a remote server then
  1019. * use this argument to provide the URL.
  1020. * @param $obo_file
  1021. * If the OBO is housed on the local file system of the server then
  1022. * use this argument to specify the full path.
  1023. *
  1024. * @return
  1025. * returns the job_id of the submitted job or FALSE if the job was not added
  1026. *
  1027. * @ingroup tripal_chado_cv_api
  1028. */
  1029. function chado_submit_obo_job($obo) {
  1030. global $user;
  1031. // Set Defaults
  1032. $obo['obo_id'] = (isset($obo['obo_id'])) ? $obo['obo_id'] : NULL;
  1033. $obo['name'] = (isset($obo['name'])) ? $obo['name'] : NULL;
  1034. $obo['url'] = (isset($obo['url'])) ? $obo['url'] : NULL;
  1035. $obo['file'] = (isset($obo['file'])) ? $obo['file'] : NULL;
  1036. $includes = array(
  1037. drupal_get_path('module', 'tripal_chado') . '/includes/tripal_chado.cv.inc',
  1038. );
  1039. if ($obo['obo_id']) {
  1040. $sql = "SELECT * FROM {tripal_cv_obo} WHERE obo_id = :obo_id";
  1041. $result = db_query($sql, array(':obo_id' => $obo['obo_id']))->fetchObject();
  1042. $args = array($result->obo_id);
  1043. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1044. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1045. }
  1046. else {
  1047. if ($obo['url']) {
  1048. $sql = "SELECT * FROM {tripal_cv_obo} WHERE path = :url";
  1049. $result = db_query($sql, array(':url' => $obo['url']))->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. elseif ($obo['file']) {
  1055. $sql = "SELECT * FROM {tripal_cv_obo} WHERE path = :file";
  1056. $result = db_query($sql, array(':url' => $obo['file']))->fetchObject();
  1057. $args = array($result->obo_id);
  1058. return tripal_add_job("Load OBO " . $result->name, 'tripal_chado',
  1059. "tripal_cv_load_obo", $args, $user->uid, 10, $includes);
  1060. }
  1061. }
  1062. return FALSE;
  1063. }
  1064. /**
  1065. * Add the OBO to the tripal_cv_obo table in the Drupal database.
  1066. *
  1067. * If the OBO name already exists in the table then the path is updated.
  1068. *
  1069. * @param $name
  1070. * The human readable name of this ontology.
  1071. * @param $path
  1072. * The file path or URL of the ontology.
  1073. *
  1074. * @return
  1075. * Returns the ontology ID.
  1076. *
  1077. * @ingroup tripal_chado_cv_api
  1078. */
  1079. function chado_insert_obo($name, $path) {
  1080. // Make sure an OBO with the same name doesn't already exist.
  1081. $obo_id = db_select('tripal_cv_obo', 'tco')
  1082. ->fields('tco', array('obo_id'))
  1083. ->condition('name', $name)
  1084. ->execute()
  1085. ->fetchField();
  1086. if ($obo_id) {
  1087. db_update('tripal_cv_obo')
  1088. ->fields(array(
  1089. 'path' => $path,
  1090. ))
  1091. ->condition('name', $name)
  1092. ->execute();
  1093. return $obo_id;
  1094. }
  1095. else {
  1096. $obo_id = db_insert('tripal_cv_obo')
  1097. ->fields(array(
  1098. 'name' => $name,
  1099. 'path' => $path,
  1100. ))
  1101. ->execute();
  1102. return $obo_id;
  1103. }
  1104. }
  1105. /**
  1106. * Retrieves an OBO record.
  1107. *
  1108. * @param $values
  1109. * An associate array with the following allowed keys: obo_id, name.
  1110. *
  1111. * @return
  1112. * An instance of an OBO record object.
  1113. *
  1114. * @ingroup tripal_chado_cv_api
  1115. */
  1116. function chado_get_obo($values) {
  1117. $query = db_select('tripal_cv_obo', 'tco')
  1118. ->fields('tco');
  1119. if (array_key_exists('name', $values)) {
  1120. $query->condition('tco.name', $values['name']);
  1121. }
  1122. if (array_key_exists('obo_id', $values)) {
  1123. $query->condition('tco.obo_id', $values['obo_id']);
  1124. }
  1125. return $query->execute()->fetchObject();
  1126. }
  1127. /**
  1128. * This function is intended to be used in autocomplete forms.
  1129. *
  1130. * This function searches for a matching controlled vobulary name.
  1131. *
  1132. * @param $string
  1133. * The string to search for.
  1134. *
  1135. * @return
  1136. * A json array of terms that begin with the provided string.
  1137. *
  1138. * @ingroup tripal_chado_cv_api
  1139. */
  1140. function chado_autocomplete_cv($string = '') {
  1141. $sql = "
  1142. SELECT CV.cv_id, CV.name
  1143. FROM {cv} CV
  1144. WHERE lower(CV.name) like lower(:name)
  1145. ORDER by CV.name
  1146. LIMIT 25 OFFSET 0
  1147. ";
  1148. $results = chado_query($sql, array(':name' => $string . '%'));
  1149. $items = array();
  1150. foreach ($results as $cv) {
  1151. $items[$cv->name] = $cv->name;
  1152. }
  1153. drupal_json_output($items);
  1154. }
  1155. /**
  1156. * This function is intended to be used in autocomplete forms
  1157. * for searching for CV terms that begin with the provided string.
  1158. *
  1159. * @param $cv_id
  1160. * The CV ID in which to search for the term.
  1161. * @param $string
  1162. * The string to search for.
  1163. *
  1164. * @return
  1165. * A json array of terms that begin with the provided string.
  1166. *
  1167. * @ingroup tripal_chado_cv_api
  1168. */
  1169. function chado_autocomplete_cvterm($cv_id, $string = '') {
  1170. if ($cv_id) {
  1171. $sql = "
  1172. SELECT CVT.cvterm_id, CVT.name
  1173. FROM {cvterm} CVT
  1174. WHERE CVT.cv_id = :cv_id and lower(CVT.name) like lower(:name)
  1175. UNION
  1176. SELECT CVT2.cvterm_id, CVTS.synonym as name
  1177. FROM {cvterm} CVT2
  1178. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  1179. WHERE CVT2.cv_id = :cv_id and lower(CVTS.synonym) like lower(:name)
  1180. ORDER by name
  1181. LIMIT 25 OFFSET 0
  1182. ";
  1183. $results = chado_query($sql, array(':cv_id' => $cv_id, ':name' => $string . '%'));
  1184. $items = array();
  1185. foreach ($results as $term) {
  1186. $items[$term->name] = $term->name;
  1187. }
  1188. }
  1189. // If a CV wasn't provided then search all of them, and include the cv
  1190. // in the results.
  1191. else {
  1192. $sql = "
  1193. SELECT CVT.cvterm_id, CVT.name, CV.name as cvname, CVT.cv_id
  1194. FROM {cvterm} CVT
  1195. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  1196. WHERE lower(CVT.name) like lower(:name)
  1197. UNION
  1198. SELECT CVT2.cvterm_id, CVTS.synonym as name, CV2.name as cvname, CVT2.cv_id
  1199. FROM {cvterm} CVT2
  1200. INNER JOIN {cv} CV2 on CVT2.cv_id = CV2.cv_id
  1201. INNER JOIN {cvtermsynonym} CVTS ON CVTS.cvterm_id = CVT2.cvterm_id
  1202. WHERE lower(CVTS.synonym) like lower(:name)
  1203. ORDER by name
  1204. LIMIT 25 OFFSET 0
  1205. ";
  1206. $results = chado_query($sql, array(':name' => $string . '%'));
  1207. $items = array();
  1208. foreach ($results as $term) {
  1209. $items[$term->name] = $term->name;
  1210. }
  1211. }
  1212. drupal_json_output($items);
  1213. }
  1214. /**
  1215. * Add a record to a cvterm linking table (ie: feature_cvterm).
  1216. *
  1217. * @param $basetable
  1218. * The base table to which the cvterm should be linked/associated. Thus to
  1219. * associate a cvterm to a feature the basetable=feature and cvterm_id is
  1220. * added to the feature_cvterm table.
  1221. * @param $record_id
  1222. * The primary key of the basetable to associate the cvterm with. This should
  1223. * be in integer.
  1224. * @param $cvterm
  1225. * An associative array describing the cvterm. Valid keys include:
  1226. * - name: the name for the cvterm,
  1227. * - cv_name: the name of the cv the cvterm belongs to.
  1228. * - cv_id: the primary key of the cv the cvterm belongs to.
  1229. * @param $options
  1230. * An associative array of options. Valid keys include:
  1231. * - insert_cvterm: Insert the cvterm if it doesn't already exist. FALSE is
  1232. * the default.
  1233. *
  1234. * @ingroup tripal_chado_cv_api
  1235. */
  1236. function chado_associate_cvterm($basetable, $record_id, $cvterm, $options = array()) {
  1237. $linking_table = $basetable . '_cvterm';
  1238. $foreignkey_name = $basetable . '_id';
  1239. // Default Values
  1240. $options['insert_cvterm'] = (isset($options['insert_cvterm'])) ? $options['insert_cvterm'] : FALSE;
  1241. // If the cvterm_id is not set then find the cvterm record using the name and
  1242. // cv_id.
  1243. if (!isset($cvterm['cvterm_id'])) {
  1244. $values = array(
  1245. 'name' => $cvterm['name'],
  1246. );
  1247. if (isset($cvterm['cv_id'])) {
  1248. $values['cv_id'] = $cvterm['cv_id'];
  1249. }
  1250. elseif (isset($cvterm['cv_name'])) {
  1251. $values['cv_id'] = array(
  1252. 'name' => $cvterm['cv_name']
  1253. );
  1254. }
  1255. else {
  1256. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  1257. "chado_associate_cvterm: The cvterm needs to have either the cv_name or cv_id
  1258. supplied. You were trying to associate a cvterm with the %base %record_id
  1259. and supplied the cvterm values: %cvterm.",
  1260. array('%base' => $basetable, '%record_id' => $record_id, '%cvterm' => print_r($cvterm,TRUE))
  1261. );
  1262. return FALSE;
  1263. }
  1264. // Get the cvterm. If it doesn't exist then add it if the option
  1265. // 'insert_cvterm' is set.
  1266. $select = chado_select_record('cvterm', array('*'), $values);
  1267. if ($select) {
  1268. $cvterm['cvterm_id'] = $select[0]->cvterm_id;
  1269. }
  1270. elseif ($options['insert_cvterm']) {
  1271. // Insert the cvterm
  1272. $insert = chado_insert_cvterm($values);
  1273. if (isset($insert->cvterm_id)) {
  1274. $cvterm['cvterm_id'] = $insert->cvterm_id;
  1275. }
  1276. else {
  1277. tripal_report_error('tripal_chado_api', TRIPAL_WARNING,
  1278. "chado_associate_cvterm: Unable to insert the cvterm using the cvterm values: %cvterm.",
  1279. array('%cvterm' => print_r($cvterm,TRUE))
  1280. );
  1281. return FALSE;
  1282. }
  1283. }
  1284. else {
  1285. tripal_report_error('tripal_api', TRIPAL_WARNING,
  1286. "chado_associate_cvterm: The cvterm doesn't already exist. You supplied the cvterm values: %cvterm.",
  1287. array('%cvterm' => print_r($cvterm,TRUE))
  1288. );
  1289. return FALSE;
  1290. }
  1291. }
  1292. // Now add the link between the record & cvterm.
  1293. if ($cvterm['cvterm_id'] > 0) {
  1294. $values = array(
  1295. 'cvterm_id' => $cvterm['cvterm_id'],
  1296. $foreignkey_name => $record_id,
  1297. 'pub_id' => 1,
  1298. );
  1299. // Check if the cvterm is already associated. If so, don't re-add it.
  1300. $result = chado_select_record($linking_table, array('*'), $values);
  1301. if (!$result) {
  1302. $success = chado_insert_record($linking_table, $values);
  1303. if (!$success) {
  1304. tripal_report_error('tripal_api', TRIPAL_WARNING,
  1305. "Failed to insert the %base record %term",
  1306. array('%base' => $linking_table, '%term' => $cvterm['name'])
  1307. );
  1308. return FALSE;
  1309. }
  1310. $result = chado_select_record($linking_table, array('*'), $values);
  1311. }
  1312. if (isset($result[0])) {
  1313. return $result[0];
  1314. }
  1315. else {
  1316. return FALSE;
  1317. }
  1318. }
  1319. return FALSE;
  1320. }