tripal_chado.cv.api.inc 48 KB

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