tripal_chado.cv.api.inc 51 KB

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