tripal_chado.cv.api.inc 48 KB

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