OBOImporter.inc 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509
  1. <?php
  2. class OBOImporter extends TripalImporter {
  3. // --------------------------------------------------------------------------
  4. // EDITABLE STATIC CONSTANTS
  5. //
  6. // The following constants SHOULD be set for each descendent class. They are
  7. // used by the static functions to provide information to Drupal about
  8. // the field and it's default widget and formatter.
  9. // --------------------------------------------------------------------------
  10. /**
  11. * The name of this loader. This name will be presented to the site
  12. * user.
  13. */
  14. public static $name = 'OBO Vocabulary Loader';
  15. /**
  16. * The machine name for this loader. This name will be used to construct
  17. * the URL for the loader.
  18. */
  19. public static $machine_name = 'chado_obo_loader';
  20. /**
  21. * A brief description for this loader. This description will be
  22. * presented to the site user.
  23. */
  24. public static $description = 'Import vocabularies and terms in OBO format.';
  25. /**
  26. * An array containing the extensions of allowed file types.
  27. */
  28. public static $file_types = ['obo'];
  29. /**
  30. * Provides information to the user about the file upload. Typically this
  31. * may include a description of the file types allowed.
  32. */
  33. public static $upload_description = 'Please provide the details for importing a new OBO file. The file must have a .obo extension.';
  34. /**
  35. * The title that should appear above the upload button.
  36. */
  37. public static $upload_title = 'New OBO File';
  38. /**
  39. * If the loader should require an analysis record. To maintain provenance
  40. * we should always indicate where the data we are uploading comes from.
  41. * The method that Tripal attempts to use for this by associating upload files
  42. * with an analysis record. The analysis record provides the details for
  43. * how the file was created or obtained. Set this to FALSE if the loader
  44. * should not require an analysis when loading. if $use_analysis is set to
  45. * true then the form values will have an 'analysis_id' key in the $form_state
  46. * array on submitted forms.
  47. */
  48. public static $use_analysis = FALSE;
  49. /**
  50. * If the $use_analysis value is set above then this value indicates if the
  51. * analysis should be required.
  52. */
  53. public static $require_analysis = TRUE;
  54. /**
  55. * Text that should appear on the button at the bottom of the importer
  56. * form.
  57. */
  58. public static $button_text = 'Import OBO File';
  59. /**
  60. * Indicates the methods that the file uploader will support.
  61. */
  62. public static $methods = [
  63. // Allow the user to upload a file to the server.
  64. 'file_upload' => FALSE,
  65. // Allow the user to provide the path on the Tripal server for the file.
  66. 'file_local' => FALSE,
  67. // Allow the user to provide a remote URL for the file.
  68. 'file_remote' => FALSE,
  69. ];
  70. /**
  71. * Be default, all loaders are automaticlly added to the Admin >
  72. * Tripal > Data Loaders menu. However, if this loader should be
  73. * made available via a different menu path, then set it here. If the
  74. * value is empty then the path will be the default.
  75. */
  76. public static $menu_path = 'admin/tripal/loaders/chado_vocabs/obo_loader';
  77. public static $file_required = FALSE;
  78. /**
  79. * Keep track of vocabularies that have been added.
  80. *
  81. * @var array
  82. */
  83. private $obo_namespaces = [];
  84. /**
  85. * Holds the list of all CVs on this site. By storing them here it saves
  86. * us query time later.
  87. */
  88. private $all_cvs = [];
  89. /**
  90. * Holds the list of all DBs on this site. By storing them here it saves
  91. * us query time later.
  92. *
  93. * @var array
  94. */
  95. private $all_dbs = [];
  96. /**
  97. * When adding synonyms we need to know the cvterm_ids of the synonym types.
  98. * This array holds those.
  99. *
  100. * @var array
  101. */
  102. private $syn_types = [
  103. 'exact' => NULL,
  104. 'broad' => NULL,
  105. 'narrow' => NULL,
  106. 'related' => NULL,
  107. ];
  108. // An alternative cache to the temp_obo table.
  109. private $termStanzaCache = [
  110. 'ids' => [],
  111. 'count' => [
  112. 'Typedef' => 0,
  113. 'Term' => 0,
  114. 'Instance' => 0,
  115. ],
  116. 'types' => [
  117. 'Typedef' => [],
  118. 'Term' => [],
  119. 'Instance' => [],
  120. ],
  121. ];
  122. /**
  123. * Indicates how terms are cached. Values can be 'memory' or 'table'. If
  124. * 'memory' then the $termStanzaCache variable is used. If 'table', then the
  125. * tripal_obo_temp table is used.
  126. *
  127. * @var string
  128. */
  129. private $cache_type = 'memory';
  130. /**
  131. * The default namespace for all terms that don't have a 'namespace' in their
  132. * term stanza.
  133. *
  134. * @var string
  135. */
  136. private $default_namespace = '';
  137. /**
  138. * The default database prefix for this ontology.
  139. *
  140. * @var string
  141. */
  142. private $default_db = '';
  143. /**
  144. * An array of used cvterm objects so that we don't have to lookup them
  145. * up repeatedly.
  146. */
  147. private $used_terms = [];
  148. /**
  149. * An array of base IRIs returned from the EBI OLS lookup service. We
  150. * don't want to continually query OLS for the same ontology base IRIs.
  151. */
  152. private $baseIRIs = [];
  153. /**
  154. * A flag to keep track if the user was warned about slowness when doing
  155. * EBI Lookups.
  156. *
  157. * @var string
  158. */
  159. private $ebi_warned = FALSE;
  160. /**
  161. * A flag that indicates if this ontology is just a subset of a much larger
  162. * one. Examples include the GO slims.
  163. *
  164. * @var string
  165. */
  166. private $is_subset = FALSE;
  167. /**
  168. * Sometimes an OBO can define two terms with the same name but different
  169. * IDs (e.g. GO:0001404 and GO:0007125). We need to find these and
  170. * deal with them. This array keeps track of term names as we see them for
  171. * easy lookup later.
  172. *
  173. * @var array
  174. */
  175. private $term_names = [];
  176. /**
  177. * @see TripalImporter::form()
  178. */
  179. public function form($form, &$form_state) {
  180. // get a list of db from chado for user to choose
  181. $sql = "SELECT * FROM {tripal_cv_obo} ORDER BY name";
  182. $results = db_query($sql);
  183. $obos = [];
  184. $obos[] = 'Select a Vocabulary';
  185. foreach ($results as $obo) {
  186. $obos[$obo->obo_id] = $obo->name;
  187. }
  188. $obo_id = '';
  189. if (array_key_exists('values', $form_state)) {
  190. $obo_id = array_key_exists('obo_id', $form_state['values']) ? $form_state['values']['obo_id'] : '';
  191. }
  192. $form['instructions']['info'] = [
  193. '#type' => 'item',
  194. '#markup' => t('This page allows you to load vocabularies and ontologies
  195. that are in OBO format. Once loaded, the terms from these
  196. vocabularies can be used to create content.
  197. You may use the form below to either reload a vocabulary that is already
  198. loaded (as when new updates to that vocabulary are available) or load a new
  199. vocabulary.'),
  200. ];
  201. $form['obo_existing'] = [
  202. '#type' => 'fieldset',
  203. '#title' => t('Use a Saved Ontology OBO Reference'),
  204. '#prefix' => '<span id="obo-existing-fieldset">',
  205. '#suffix' => '</span>',
  206. ];
  207. $form['obo_existing']['existing_instructions'] = [
  208. '#type' => 'item',
  209. '#markup' => t('The vocabularies listed in the select box below have been pre-populated
  210. upon installation of Tripal or have been previously loaded. Select one to edit
  211. its settings or submit for loading. You may reload any vocabulary that has
  212. already been loaded to retrieve any new updates.'),
  213. ];
  214. $form['obo_existing']['obo_id'] = [
  215. '#title' => t('Ontology OBO File Reference'),
  216. '#type' => 'select',
  217. '#options' => $obos,
  218. '#ajax' => [
  219. 'callback' => 'tripal_cv_obo_form_ajax_callback',
  220. 'wrapper' => 'obo-existing-fieldset',
  221. ],
  222. '#description' => t('Select a vocabulary to import.'),
  223. ];
  224. // If the user has selected an OBO ID then get the form elements for
  225. // updating.
  226. if ($obo_id) {
  227. $uobo_name = '';
  228. $uobo_url = '';
  229. $uobo_file = '';
  230. $vocab = db_select('tripal_cv_obo', 't')
  231. ->fields('t', ['name', 'path'])
  232. ->condition('obo_id', $obo_id)
  233. ->execute()
  234. ->fetchObject();
  235. $uobo_name = $vocab->name;
  236. if (preg_match('/^http/', $vocab->path)) {
  237. $uobo_url = $vocab->path;
  238. }
  239. else {
  240. $uobo_file = trim($vocab->path);
  241. $matches = [];
  242. if (preg_match('/\{(.*?)\}/', $uobo_file, $matches)) {
  243. $modpath = drupal_get_path('module', $matches[1]);
  244. $uobo_file = preg_replace('/\{.*?\}/', $modpath, $uobo_file);
  245. }
  246. }
  247. // We don't want the previous value to remain. We want the new default to
  248. // show up, so remove the input values
  249. unset($form_state['input']['uobo_name']);
  250. unset($form_state['input']['uobo_url']);
  251. unset($form_state['input']['uobo_file']);
  252. $form['obo_existing']['uobo_name'] = [
  253. '#type' => 'textfield',
  254. '#title' => t('Vocabulary Name'),
  255. '#description' => t('Please provide a name for this vocabulary. After upload, this name will appear in the drop down
  256. list above for use again later.'),
  257. '#default_value' => $uobo_name,
  258. ];
  259. $form['obo_existing']['uobo_url'] = [
  260. '#type' => 'textfield',
  261. '#title' => t('Remote URL'),
  262. '#description' => t('Please enter a URL for the online OBO file. The file will be downloaded and parsed.
  263. (e.g. http://www.obofoundry.org/ro/ro.obo)'),
  264. '#default_value' => $uobo_url,
  265. ];
  266. $form['obo_existing']['uobo_file'] = [
  267. '#type' => 'textfield',
  268. '#title' => t('Local File'),
  269. '#description' => t('Please enter the file system path for an OBO
  270. definition file. If entering a path relative to
  271. the Drupal installation you may use a relative path that excludes the
  272. Drupal installation directory (e.g. sites/default/files/xyz.obo). Note
  273. that Drupal relative paths have no preceding slash.
  274. Otherwise, please provide the full path on the filesystem. The path
  275. must be accessible to the web server on which this Drupal instance is running.'),
  276. '#default_value' => $uobo_file,
  277. ];
  278. $form['obo_existing']['update_obo_details'] = [
  279. '#type' => 'submit',
  280. '#value' => 'Update Ontology Details',
  281. '#name' => 'update_obo_details',
  282. ];
  283. }
  284. $form['obo_new'] = [
  285. '#type' => 'fieldset',
  286. '#title' => t('Add a New Ontology OBO Reference'),
  287. '#collapsible' => TRUE,
  288. '#collapsed' => TRUE,
  289. ];
  290. $form['obo_new']['path_instructions'] = [
  291. '#value' => t('Provide the name and path for the OBO file. If the vocabulary OBO file
  292. is stored local to the server provide a file name. If the vocabulary is stored remotely,
  293. provide a URL. Only provide a URL or a local file, not both.'),
  294. ];
  295. $form['obo_new']['obo_name'] = [
  296. '#type' => 'textfield',
  297. '#title' => t('New Vocabulary Name'),
  298. '#description' => t('Please provide a name for this vocabulary. After upload, this name will appear in the drop down
  299. list above for use again later. Additionally, if a default namespace is not provided in the OBO
  300. header this name will be used as the default_namespace.'),
  301. ];
  302. $form['obo_new']['obo_url'] = [
  303. '#type' => 'textfield',
  304. '#title' => t('Remote URL'),
  305. '#description' => t('Please enter a URL for the online OBO file. The file will be downloaded and parsed.
  306. (e.g. http://www.obofoundry.org/ro/ro.obo)'),
  307. ];
  308. $form['obo_new']['obo_file'] = [
  309. '#type' => 'textfield',
  310. '#title' => t('Local File'),
  311. '#description' => t('Please enter the file system path for an OBO
  312. definition file. If entering a path relative to
  313. the Drupal installation you may use a relative path that excludes the
  314. Drupal installation directory (e.g. sites/default/files/xyz.obo). Note
  315. that Drupal relative paths have no preceding slash.
  316. Otherwise, please provide the full path on the filesystem. The path
  317. must be accessible to the web server on which this Drupal instance is running.'),
  318. ];
  319. return $form;
  320. }
  321. /**
  322. * @see TripalImporter::formSubmit()
  323. */
  324. public function formSubmit($form, &$form_state) {
  325. $obo_id = $form_state['values']['obo_id'];
  326. $obo_name = trim($form_state['values']['obo_name']);
  327. $obo_url = trim($form_state['values']['obo_url']);
  328. $obo_file = trim($form_state['values']['obo_file']);
  329. $uobo_name = array_key_exists('uobo_name', $form_state['values']) ? trim($form_state['values']['uobo_name']) : '';
  330. $uobo_url = array_key_exists('uobo_url', $form_state['values']) ? trim($form_state['values']['uobo_url']) : '';
  331. $uobo_file = array_key_exists('uobo_file', $form_state['values']) ? trim($form_state['values']['uobo_file']) : '';
  332. // If the user requested to alter the details then do that.
  333. if ($form_state['clicked_button']['#name'] == 'update_obo_details') {
  334. $form_state['rebuild'] = TRUE;
  335. $success = db_update('tripal_cv_obo')
  336. ->fields([
  337. 'name' => $uobo_name,
  338. 'path' => $uobo_url ? $uobo_url : $uobo_file,
  339. ])
  340. ->condition('obo_id', $obo_id)
  341. ->execute();
  342. if ($success) {
  343. drupal_set_message(t("The vocabulary !vocab has been updated.", ['!vocab' => $uobo_name]));
  344. }
  345. else {
  346. drupal_set_message(t("The vocabulary !vocab could not be updated.", ['!vocab' => $uobo_name]), 'error');
  347. }
  348. }
  349. elseif (!empty($obo_name)) {
  350. $obo_id = db_insert('tripal_cv_obo')
  351. ->fields([
  352. 'name' => $obo_name,
  353. 'path' => $obo_url ? $obo_url : $obo_file,
  354. ])
  355. ->execute();
  356. // Add the obo_id to the form_state values.
  357. $form_state['values']['obo_id'] = $obo_id;
  358. if ($obo_id) {
  359. drupal_set_message(t("The vocabulary !vocab has been added.", ['!vocab' => $obo_name]));
  360. }
  361. else {
  362. $form_state['rebuild'] = TRUE;
  363. drupal_set_message(t("The vocabulary !vocab could not be added.", ['!vocab' => $obo_name]), 'error');
  364. }
  365. }
  366. }
  367. /**
  368. * @see TripalImporter::formValidate()
  369. */
  370. public function formValidate($form, &$form_state) {
  371. $obo_id = $form_state['values']['obo_id'];
  372. $obo_name = trim($form_state['values']['obo_name']);
  373. $obo_url = trim($form_state['values']['obo_url']);
  374. $obo_file = trim($form_state['values']['obo_file']);
  375. $uobo_name = array_key_exists('uobo_name', $form_state['values']) ? trim($form_state['values']['uobo_name']) : '';
  376. $uobo_url = array_key_exists('uobo_url', $form_state['values']) ? trim($form_state['values']['uobo_url']) : '';
  377. $uobo_file = array_key_exists('uobo_file', $form_state['values']) ? trim($form_state['values']['uobo_file']) : '';
  378. // Make sure if the name is changed it doesn't conflict with another OBO.
  379. if ($form_state['clicked_button']['#name'] == 'update_obo_details' or
  380. $form_state['clicked_button']['#name'] == 'update_load_obo') {
  381. // Get the current record
  382. $vocab = db_select('tripal_cv_obo', 't')
  383. ->fields('t', ['obo_id', 'name', 'path'])
  384. ->condition('name', $uobo_name)
  385. ->execute()
  386. ->fetchObject();
  387. if ($vocab and $vocab->obo_id != $obo_id) {
  388. form_set_error('uobo_name', 'The vocabulary name must be different from existing vocabularies');
  389. }
  390. // Make sure the file exists. First check if it is a relative path
  391. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $uobo_file;
  392. if (!file_exists($dfile)) {
  393. if (!file_exists($uobo_file)) {
  394. form_set_error('uobo_file', t('The specified path, !path, does not exist or cannot be read.'), ['!path' => $dfile]);
  395. }
  396. }
  397. if (!$uobo_url and !$uobo_file) {
  398. form_set_error('uobo_url', 'Please provide a URL or a path for the vocabulary.');
  399. }
  400. if ($uobo_url and $uobo_file) {
  401. form_set_error('uobo_url', 'Please provide only a URL or a path for the vocabulary, but not both.');
  402. }
  403. }
  404. if ($form_state['clicked_button']['#name'] == 'add_new_obo') {
  405. // Get the current record
  406. $vocab = db_select('tripal_cv_obo', 't')
  407. ->fields('t', ['obo_id', 'name', 'path'])
  408. ->condition('name', $obo_name)
  409. ->execute()
  410. ->fetchObject();
  411. if ($vocab) {
  412. form_set_error('obo_name', 'The vocabulary name must be different from existing vocabularies');
  413. }
  414. // Make sure the file exists. First check if it is a relative path
  415. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo_file;
  416. if (!file_exists($dfile)) {
  417. if (!file_exists($obo_file)) {
  418. form_set_error('obo_file', t('The specified path, !path, does not exist or cannot be read.'), ['!path' => $dfile]);
  419. }
  420. }
  421. if (!$obo_url and !$obo_file) {
  422. form_set_error('obo_url', 'Please provide a URL or a path for the vocabulary.');
  423. }
  424. if ($obo_url and $obo_file) {
  425. form_set_error('obo_url', 'Please provide only a URL or a path for the vocabulary, but not both.');
  426. }
  427. }
  428. }
  429. /**
  430. * @see TripalImporter::run()
  431. *
  432. * @param $details
  433. * The following arguments are supported:
  434. * - obo_id: (required) The ID of the ontology to be imported.
  435. */
  436. public function run() {
  437. $arguments = $this->arguments['run_args'];
  438. $obo_id = $arguments['obo_id'];
  439. // Make sure the $obo_id is valid
  440. $obo = db_select('tripal_cv_obo', 'tco')
  441. ->fields('tco')
  442. ->condition('obo_id', $obo_id)
  443. ->execute()
  444. ->fetchObject();
  445. if (!$obo) {
  446. throw new Exception("Invalid OBO ID provided: '$obo_id'.");
  447. }
  448. // Get the list of all CVs so we can save on lookups later
  449. $sql = "SELECT * FROM {cv} CV";
  450. $cvs = chado_query($sql);
  451. while ($cv = $cvs->fetchObject()) {
  452. $this->all_cvs[$cv->name] = $cv;
  453. }
  454. // Get the list of all DBs so we can save on lookups later
  455. $sql = "SELECT * FROM {db} DB";
  456. $dbs = chado_query($sql);
  457. while ($db = $dbs->fetchObject()) {
  458. $this->all_dbs[$db->name] = $db;
  459. }
  460. // Get the 'Subgroup' term that we will use for adding subsets.
  461. $term = chado_get_cvterm(['id' => 'NCIT:C25693']);
  462. $this->used_terms['NCIT:C25693'] = $term->cvterm_id;
  463. // Get the 'Comment' term that we will use for adding comments.
  464. $term = chado_get_cvterm(['id' => 'rdfs:comment']);
  465. $this->used_terms['rdfs:comment'] = $term->cvterm_id;
  466. // Make sure we have a 'synonym_type' vocabulary.
  467. $syn_cv = new ChadoRecord('cv');
  468. $syn_cv->setValues(['name' => 'synonym_type']);
  469. $syn_cv->save();
  470. $this->all_cvs['synonym_type'] = (object) $syn_cv->getValues();
  471. // Make sure we have a 'synonym_type' database.
  472. $syn_db = new ChadoRecord('db');
  473. $syn_db->setValues(['name' => 'synonym_type']);
  474. $syn_db->save();
  475. $this->all_dbs['synonym_type'] = (object) $syn_db->getValues();
  476. // Make sure the synonym types exists in the 'synonym_type' vocabulary.
  477. foreach (array_keys($this->syn_types) as $syn_type) {
  478. $syn_dbxref = new ChadoRecord('dbxref');
  479. $syn_dbxref->setValues([
  480. 'accession' => $syn_type,
  481. 'db_id' => $syn_db->getID(),
  482. ]);
  483. $syn_dbxref->save();
  484. $syn_term = new ChadoRecord('cvterm');
  485. $syn_term->setValues([
  486. 'name' => $syn_type,
  487. 'cv_id' => $syn_cv->getID(),
  488. ]);
  489. if (!$syn_term->find()) {
  490. $syn_term->setValues([
  491. 'name' => $syn_type,
  492. 'definition' => '',
  493. 'is_obsolete' => 0,
  494. 'cv_id' => $syn_cv->getID(),
  495. 'is_relationshiptype' => 0,
  496. 'dbxref_id' => $syn_dbxref->getID(),
  497. ]);
  498. $syn_term->insert();
  499. }
  500. $this->syn_types[$syn_type] = (object) $syn_term->getValues();
  501. }
  502. // Run the importer!
  503. $this->loadOBO_v1_2_id($obo);
  504. }
  505. /**
  506. * @see TripalImporter::postRun()
  507. *
  508. */
  509. public function postRun() {
  510. // Clear the cached terms
  511. cache_clear_all('tripal_chado:term:*', 'cache', TRUE);
  512. // Update the cv_root_mview materialized view.
  513. $this->logMessage("Updating the cv_root_mview materialized view...");
  514. $mview_id = tripal_get_mview_id('cv_root_mview');
  515. tripal_populate_mview($mview_id);
  516. $this->logMessage("Updating the db2cv_mview materialized view...");
  517. $mview_id = tripal_get_mview_id('db2cv_mview');
  518. tripal_populate_mview($mview_id);
  519. // Update the cvtermpath table for each newly added CV.
  520. $this->logMessage("Updating cvtermpath table. This may take a while...");
  521. foreach ($this->obo_namespaces as $namespace => $cv_id) {
  522. $this->logMessage("- Loading paths for vocabulary: @vocab", ['@vocab' => $namespace]);
  523. chado_update_cvtermpath($cv_id, $this->job);
  524. }
  525. }
  526. /**
  527. * A wrapper function for importing the user specified OBO file into Chado by
  528. * specifying the obo_id of the OBO. It requires that the file be in OBO v1.2
  529. * compatible format. This function is typically executed via the Tripal
  530. * jobs
  531. * management after a user submits a job via the Load Ontologies form.
  532. *
  533. * @param $obo_id
  534. * An obo_id from the tripal_cv_obo file that specifies which OBO file to
  535. * import
  536. *
  537. * @ingroup tripal_obo_loader
  538. */
  539. private function loadOBO_v1_2_id($obo) {
  540. // Convert the module name to the real path if present
  541. if (preg_match("/\{(.*?)\}/", $obo->path, $matches)) {
  542. $module = $matches[1];
  543. $path = drupal_realpath(drupal_get_path('module', $module));
  544. $obo->path = preg_replace("/\{.*?\}/", $path, $obo->path);
  545. }
  546. // if the reference is for a remote URL then run the URL processing function
  547. if (preg_match("/^https:\/\//", $obo->path) or
  548. preg_match("/^http:\/\//", $obo->path) or
  549. preg_match("/^ftp:\/\//", $obo->path)) {
  550. $this->loadOBO_v1_2_url($obo->name, $obo->path, 0);
  551. }
  552. // if the reference is for a local file then run the file processing function
  553. else {
  554. // check to see if the file is located local to Drupal
  555. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo->path;
  556. if (file_exists($dfile)) {
  557. $this->loadOBO_v1_2_file($obo->name, $dfile, 0);
  558. }
  559. // if not local to Drupal, the file must be someplace else, just use
  560. // the full path provided
  561. else {
  562. if (file_exists($obo->path)) {
  563. $this->loadOBO_v1_2_file($obo->name, $obo->path, 0);
  564. }
  565. else {
  566. print "ERROR: could not find OBO file: '$obo->path'\n";
  567. }
  568. }
  569. }
  570. }
  571. /**
  572. * A wrapper function for importing the user specified OBO file into Chado by
  573. * specifying the filename and path of the OBO. It requires that the file be
  574. * in OBO v1.2 compatible format. This function is typically executed via
  575. * the Tripal jobs management after a user submits a job via the Load
  576. * Ontologies form.
  577. *
  578. * @param $obo_name
  579. * The name of the OBO (typically the ontology or controlled vocabulary
  580. * name)
  581. * @param $file
  582. * The path on the file system where the ontology can be found
  583. * @param $is_new
  584. * Set to TRUE if this is a new ontology that does not yet exist in the
  585. * tripal_cv_obo table. If TRUE the OBO will be added to the table.
  586. *
  587. * @ingroup tripal_obo_loader
  588. */
  589. private function loadOBO_v1_2_file($obo_name, $file, $is_new = TRUE) {
  590. if ($is_new) {
  591. tripal_insert_obo($obo_name, $file);
  592. }
  593. $success = $this->loadOBO_v1_2($file, $obo_name);
  594. }
  595. /**
  596. * A wrapper function for importing the user specified OBO file into Chado by
  597. * specifying the remote URL of the OBO. It requires that the file be in OBO
  598. * v1.2 compatible format. This function is typically executed via the
  599. * Tripal jobs management after a user submits a job via the Load Ontologies
  600. * form.
  601. *
  602. * @param $obo_name
  603. * The name of the OBO (typically the ontology or controlled vocabulary
  604. * name)
  605. * @param $url
  606. * The remote URL of the OBO file.
  607. * @param $is_new
  608. * Set to TRUE if this is a new ontology that does not yet exist in the
  609. * tripal_cv_obo table. If TRUE the OBO will be added to the table.
  610. *
  611. * @ingroup tripal_obo_loader
  612. */
  613. private function loadOBO_v1_2_url($obo_name, $url, $is_new = TRUE) {
  614. // first download the OBO
  615. $temp = tempnam(sys_get_temp_dir(), 'obo_');
  616. print "Downloading URL $url, saving to $temp\n";
  617. $url_fh = fopen($url, "r");
  618. $obo_fh = fopen($temp, "w");
  619. if (!$url_fh) {
  620. throw new Exception("Unable to download the remote OBO file at $url. Could a firewall be blocking outgoing connections? " .
  621. " if you are unable to download the file you may manually download the OBO file and use the web interface to " .
  622. " specify the location of the file on your server.");
  623. }
  624. while (!feof($url_fh)) {
  625. fwrite($obo_fh, fread($url_fh, 255), 255);
  626. }
  627. fclose($url_fh);
  628. fclose($obo_fh);
  629. if ($is_new) {
  630. tripal_insert_obo($obo_name, $url);
  631. }
  632. // second, parse the OBO
  633. $this->loadOBO_v1_2($temp, $obo_name);
  634. // now remove the temp file
  635. unlink($temp);
  636. }
  637. /**
  638. * Imports a given OBO file into Chado. This function is usually called by
  639. * one of three wrapper functions: loadOBO_v1_2_id,
  640. * loadOBO_v1_2_file or tripal_cv_load_obo_v1_2_url. But, it can
  641. * be called directly if the full path to an OBO file is available on the
  642. * file system.
  643. *
  644. * @param $file
  645. * The full path to the OBO file on the file system
  646. *
  647. * @ingroup tripal_obo_loader
  648. */
  649. private function loadOBO_v1_2($file, $obo_name) {
  650. $header = [];
  651. $ret = [];
  652. // Empty the temp table.
  653. $this->clearTermStanzaCache();
  654. // Parse the obo file.
  655. $this->logMessage("Step 1: Preloading File $file...");
  656. $this->parse($file, $header);
  657. // Cache the relationships of terms.
  658. $this->logMessage("Step 2: Examining relationships...");
  659. $this->cacheRelationships();
  660. // Add any typedefs to the vocabulary first.
  661. $this->logMessage("Step 3: Loading type defs...");
  662. $this->processTypeDefs();
  663. // Next add terms to the vocabulary.
  664. $this->logMessage("Step 4: Loading terms...");
  665. $this->processTerms();
  666. // Empty the term cache.
  667. $this->logMessage("Step 5: Cleanup...");
  668. $this->clearTermStanzaCache();
  669. }
  670. /**
  671. * OBO files are divided into a typedefs terms section and vocabulary terms
  672. * section. This function loads the typedef terms from the OBO.
  673. *
  674. * @ingroup tripal_obo_loader
  675. */
  676. private function processTypeDefs() {
  677. $typedefs = $this->getCachedTermStanzas('Typedef');
  678. $count = $this->getCacheSize('Typedef');
  679. $this->setTotalItems($count);
  680. $this->setItemsHandled(0);
  681. $this->setInterval(5);
  682. $i = 1;
  683. foreach ($typedefs as $t) {
  684. // TODO: it would be better if we had a term iterator so that we
  685. // don't have to distinguish here between the table vs memory cache type.
  686. if ($this->cache_type == 'table') {
  687. $stanza = unserialize(base64_decode($t->stanza));
  688. }
  689. else {
  690. $stanza = $this->termStanzaCache['ids'][$t];
  691. }
  692. $this->setItemsHandled($i++);
  693. $this->processTerm($stanza, TRUE);
  694. }
  695. $this->setItemsHandled($i);
  696. return 1;
  697. }
  698. /**
  699. * This function loads all of the [Term] terms from the OBO.
  700. */
  701. private function processTerms() {
  702. $i = 0;
  703. $external = FALSE;
  704. $terms = $this->getCachedTermStanzas('Term');
  705. $count = $this->getCacheSize('Term');
  706. $this->setTotalItems($count);
  707. $this->setItemsHandled(0);
  708. $this->setInterval(1);
  709. // Iterate through the terms.
  710. foreach ($terms as $t) {
  711. // TODO: it would be better if we had a term iterator so that we
  712. // don't have to distinguish here between the table vs memory cache type.
  713. if ($this->cache_type == 'table') {
  714. $term = unserialize(base64_decode($t->stanza));
  715. }
  716. else {
  717. $term = $this->termStanzaCache['ids'][$t];
  718. }
  719. $this->setItemsHandled($i);
  720. // Add/update this term.
  721. $this->processTerm($term, FALSE);
  722. $i++;
  723. }
  724. $this->setItemsHandled($i);
  725. return 1;
  726. }
  727. /**
  728. * Sets the default CV and DB for this loader.
  729. *
  730. * Unfortunately, not all OBOs include both the 'ontology' and the
  731. * 'default-namespace' in their headers, so we have to do our best to
  732. * work out what these two should be.
  733. *
  734. */
  735. private function setDefaults($header) {
  736. $short_name = '';
  737. $namespace = '';
  738. // Get the 'ontology' and 'default-namespace' headers. Unfortunately,
  739. // not all OBO files contain these.
  740. if (array_key_exists('ontology', $header)) {
  741. $short_name = strtoupper($header['ontology'][0]);
  742. }
  743. if (array_key_exists('default-namespace', $header)) {
  744. $namespace = $header['default-namespace'][0];
  745. }
  746. // The OBO specification allows the 'ontology' header tag to be nested for
  747. // subsets (e.g. go/subsets/goslim_plant). We need to simplify that down
  748. // to the top-level item.
  749. $matches = [];
  750. if (preg_match('/^(.+?)\/.*/', $short_name, $matches)) {
  751. $short_name = $matches[1];
  752. $this->is_subset = TRUE;
  753. }
  754. // If we have the DB short name (or ontology header) but not the default
  755. // namespace then we may be able to find it via an EBI lookup.
  756. if (!$namespace and $short_name) {
  757. $namespace = $this->findEBIOntologyNamespace($short_name);
  758. }
  759. // If we have the namespace but not the short name then we have to
  760. // do a few tricks to try and find it.
  761. if ($namespace and !$short_name) {
  762. // First see if we've seen this ontology before and get it's currently
  763. // loaded database.
  764. $sql = "SELECT dbname FROM {db2cv_mview} WHERE cvname = :cvname";
  765. $short_name = chado_query($sql, [':cvname' => $namespace])->fetchField();
  766. if (!$short_name and array_key_exists('namespace-id-rule', $header)) {
  767. $matches = [];
  768. if (preg_match('/^.*\s(.+?):.+$/', $header['namespace-id-rule'][0], $matches)) {
  769. $short_name = $matches[1];
  770. }
  771. }
  772. // Try the EBI Lookup: still experimental.
  773. if (!$short_name) {
  774. //$short_name = $this->findEBIOntologyPrefix($namespace);
  775. }
  776. }
  777. // If we can't find the namespace or the short_name then bust.
  778. if (!$namespace and !$short_name) {
  779. throw new ErrorException('Cannot determine the namespace or ontology prefix from this OBO file. It is missing both the "default-namespace" and "ontology" headers.');
  780. }
  781. // Set the defaults.
  782. $this->default_namespace = $namespace;
  783. $this->default_db = $short_name;
  784. $this->addDB($this->default_db);
  785. $cv = $this->addCV($this->default_namespace);
  786. $this->obo_namespaces[$namespace] = $cv->cv_id;
  787. }
  788. /**
  789. * This function searches EBI to find the ontology details for this OBO.
  790. *
  791. * @param $ontology
  792. * The ontology name from the OBO headers.
  793. *
  794. * @throws Exception
  795. */
  796. private function findEBIOntologyNamespace($ontology) {
  797. // Check if the EBI ontology search has this ontology:
  798. try {
  799. $results = $this->oboEbiLookup($ontology, 'ontology');
  800. if (array_key_exists('default-namespace', $results['config']['annotations'])) {
  801. $namespace = $results['config']['annotations']['default-namespace'];
  802. if (is_array($namespace)) {
  803. $namespace = $namespace[0];
  804. }
  805. }
  806. elseif (array_key_exists('namespace', $results['config'])) {
  807. $namespace = $results['config']['namespace'];
  808. }
  809. // If we can't find the namespace at EBI, then just default to using the
  810. // same namespace as the DB short name.
  811. else {
  812. $namespace = $this->default_db;
  813. }
  814. return $namespace;
  815. } catch (Exception $e) {
  816. watchdog_exception('Cannot find the namespace for this ontology.', $e);
  817. throw $e;
  818. }
  819. }
  820. /**
  821. * Finds the ontology prefix (DB short name) using EBI.
  822. *
  823. * @param $namespace
  824. * The namespace for ontology.
  825. */
  826. private function findEBIOntologyPrefix($namespace) {
  827. // NOTE: this code is not yet completed.. It's not clear it will
  828. // actually work.
  829. $options = [];
  830. $page = 1;
  831. $size = 25;
  832. $full_url = 'https://www.ebi.ac.uk/ols/api/ontologies?page=' . $page . '&size=' . $size;
  833. while ($response = drupal_http_request($full_url, $options)) {
  834. $response = drupal_json_decode($response->data);
  835. foreach ($response['_embedded']['ontologies'] as $ontology) {
  836. $namespace = $ontology['config']['namespace'];
  837. }
  838. $page++;
  839. $full_url = 'https://www.ebi.ac.uk/ols/api/ontologies?page=' . $page . '&size=' . $size;
  840. }
  841. }
  842. /**
  843. * A helper function to get details about a foreign term.
  844. *
  845. * A foreign term is one that does not belong to the ontology.
  846. *
  847. * @param $t
  848. * A term array that contains these keys at a minimum: id, name,
  849. * definition, subset, namespace, is_obsolete.
  850. */
  851. private function findEBITerm($id) {
  852. // Warn the user if we're looking up terms in EBI as this will slow the
  853. // loader if there are many lookups.
  854. if ($this->ebi_warned == FALSE) {
  855. $this->logMessage(
  856. "A term that belongs to another ontology is used within this " .
  857. "vocabulary. Therefore a lookup will be performed with the EBI Ontology " .
  858. "Lookup Service to retrieve the information for this term. " .
  859. "Please note, that vocabularies with many non-local terms " .
  860. "require remote lookups and these lookups can dramatically " .
  861. "decrease loading time. ",
  862. ['!vocab' => $this->default_namespace], TRIPAL_WARNING);
  863. $this->ebi_warned = TRUE;
  864. // This ontology may have multiple remote terms and that takes a while
  865. // to load so lets change the progress interval down to give
  866. // updates more often.
  867. $this->setInterval(1);
  868. }
  869. $this->logMessage("Performing EBI OLS Lookup for: !id", ['!id' => $id]);
  870. // Get the short name and accession for the term.
  871. $pair = explode(":", $id, 2);
  872. $short_name = $pair[0];
  873. $accession = $pair[1];
  874. // First get the ontology so we can build an IRI for the term
  875. $base_iri = '';
  876. $ontologyID = '';
  877. if (array_key_exists($short_name, $this->baseIRIs)) {
  878. list($ontologyID, $base_iri) = $this->baseIRIs[$short_name];
  879. }
  880. else {
  881. $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $short_name;
  882. $response = drupal_http_request($full_url, []);
  883. if (!$response) {
  884. throw new Exception(t('Did not get a response from EBI OLS trying to lookup ontology: !ontology',
  885. ['!ontology' => $short_name]));
  886. }
  887. $ontology_results = drupal_json_decode($response->data);
  888. if ($ontology_results['error']) {
  889. $this->logMessage(t('Cannot find the ontology via an EBI OLS lookup: !short_name. \n' .
  890. 'We tried to access: !url' .
  891. 'EBI Reported: !message. ' .
  892. 'Consider finding the OBO file for this ontology and manually loading it first.',
  893. [
  894. '!message' => $ontology_results['message'],
  895. '!short_name' => $short_name,
  896. '!url' => $full_url,
  897. ]), TRIPAL_WARNING);
  898. }
  899. //What should happen with this stuff?
  900. $base_iri = $ontology_results['config']['baseUris'][0];
  901. $ontologyID = $ontology_results['ontologyId'];
  902. $this->baseIRIs[$short_name] = [$ontologyID, $base_iri];
  903. }
  904. // Next get the term.
  905. $iri = urlencode(urlencode($base_iri . $accession));
  906. $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontologyID . '/terms/' . $iri;
  907. $response = drupal_http_request($full_url, []);
  908. if (!$response) {
  909. throw new Exception(t('Did not get a response from EBI OLS trying to lookup term: !id',
  910. ['!id' => $id]));
  911. }
  912. $results = drupal_json_decode($response->data);
  913. if (!$results) {
  914. $this->logMessage('Error: no data with !url. The response was: !response', [
  915. '!url' => $full_url,
  916. '!response' => $response,
  917. ]);
  918. return FALSE;
  919. }
  920. // If EBI sent an error message then throw an error.
  921. if ($results['error']) {
  922. $this->logMessage('Cannot find the term via an EBI OLS lookup: !term. ' .
  923. 'We tried to access: !url' .
  924. 'EBI Reported: !message. Consider finding the OBO file for this ontology and manually loading it first.',
  925. [
  926. '!message' => $results['message'],
  927. '!term' => $id,
  928. '!url' => $full_url,
  929. ], TRIPAL_WARNING);
  930. return FALSE;
  931. }
  932. // TODO: what do we do if the term is not defined by this ontology?
  933. if ($results['is_defining_ontology'] != 1) {
  934. }
  935. // Make an OBO stanza array as if this term were in the OBO file and
  936. // return it.
  937. $this->logMessage("Found !term in EBI OLS.", ['!term' => $id]);
  938. $stanza = [];
  939. $stanza['id'][0] = $id;
  940. $stanza['name'][0] = $results['label'];
  941. $stanza['def'][0] = $results['def'];
  942. $stanza['namespace'][0] = $results['ontology_name'];
  943. $stanza['is_obsolete'][0] = $results['is_obsolete'] ? 'true' : '';
  944. $stanza['is_relationshiptype'][0] = '';
  945. $stanza['db_name'][0] = $short_name;
  946. $stanza['comment'][0] = 'Term obtained using the EBI Ontology Lookup Service.';
  947. if (array_key_exists('in_subset', $results)) {
  948. if (is_array($results['in_subset'])) {
  949. $stanza['subset'] = $results['in_subset'];
  950. }
  951. elseif ($results['in_subset']) {
  952. $stanza['subset'][0] = $results['in_subset'];
  953. }
  954. }
  955. // If this term has been replaced then get the new term.
  956. if (array_key_exists('term_replaced_by', $results) and isset($results['term_replaced_by'])) {
  957. $replaced_by = $results['term_replaced_by'];
  958. $replaced_by = preg_replace('/_/', ':', $replaced_by);
  959. $this->logMessage("The term, !term, is replaced by, !replaced",
  960. ['!term' => $id, '!replaced' => $replaced_by]);
  961. // Before we try to look for the replacement term, let's try to find it.
  962. // in our list of cached terms.
  963. if (array_key_exists($replaced_by, $this->termStanzaCache['ids'])) {
  964. $this->logMessage("Found term, !replaced in the term cache.",
  965. ['!term' => $id, '!replaced' => $replaced_by]);
  966. return $this->termStanzaCache['ids'][$id];
  967. }
  968. // Next look in the database.
  969. $rpair = explode(":", $replaced_by, 2);
  970. $found = $this->lookupTerm($rpair[0], $rpair[1]);
  971. if ($found) {
  972. $this->logMessage("Found term, !replaced in the local data store.",
  973. ['!term' => $id, '!replaced' => $replaced_by]);
  974. return $found;
  975. }
  976. // Look for this new term.
  977. $stanza = $this->findEBITerm($replaced_by);
  978. }
  979. return $stanza;
  980. }
  981. /**
  982. * Inserts a new cvterm using the OBO stanza array provided.
  983. *
  984. * The stanza passed to this function should always come from the term cache,
  985. * not directly from the OBO file because the cached terms have been
  986. * updated to include all necessary values. This function also removes
  987. * all properties associated with the term so that those can be added
  988. * fresh.
  989. *
  990. * @param $stanza
  991. * An OBO stanza array as returned by getCachedTermStanza().
  992. * @param $is_relationship
  993. * Set to TRUE if this term is a relationship term.
  994. * @param $update_if_exists
  995. * Set to TRUE to update the term if it exists.
  996. *
  997. * @return
  998. * The cvterm ID.
  999. */
  1000. private function saveTerm($stanza, $is_relationship = FALSE) {
  1001. // Get the term ID.
  1002. $id = $stanza['id'][0];
  1003. // First check if we've already used this term.
  1004. if (array_key_exists($id, $this->used_terms)) {
  1005. return $this->used_terms[$id];
  1006. }
  1007. // Get the term properties.
  1008. $id = $stanza['id'][0];
  1009. $name = $stanza['name'][0];
  1010. $cvname = $stanza['namespace'][0];
  1011. $dbname = $stanza['db_name'][0];
  1012. $namespace = $stanza['namespace'][0];
  1013. // Does this term ID have both a short name and accession? If so, then
  1014. // separate out these components, otherwise we will use the id as both
  1015. // the id and accession.
  1016. $accession = '';
  1017. $matches = [];
  1018. if (preg_match('/^(.+?):(.*)$/', $id, $matches)) {
  1019. $accession = $matches[2];
  1020. }
  1021. else {
  1022. $accession = $id;
  1023. }
  1024. // Get the definition if there is one.
  1025. $definition = '';
  1026. if (array_key_exists('def', $stanza)) {
  1027. $definition = preg_replace('/^\"(.*)\"/', '\1', $stanza['def'][0]);
  1028. }
  1029. // Set the flag if this term is obsolete.
  1030. $is_obsolete = 0;
  1031. if (array_key_exists('is_obsolete', $stanza)) {
  1032. $is_obsolete = $stanza['is_obsolete'][0] == 'true' ? 1 : 0;
  1033. }
  1034. // Set the flag if this is a relationship type.
  1035. $is_relationshiptype = 0;
  1036. if (array_key_exists('is_relationshiptype', $stanza)) {
  1037. $is_relationshiptype = $stanza['is_relationshiptype'][0] == 'true' ? 1 : 0;
  1038. }
  1039. // Is this term borrowed from another ontology?
  1040. $is_borrowed = $this->isTermBorrowed($stanza);
  1041. // Will hold the cvterm ChadoRecord object.
  1042. $cvterm = NULL;
  1043. // Get the CV and DB objects.
  1044. $cv = $this->all_cvs[$cvname];
  1045. $db = $this->all_dbs[$dbname];
  1046. // If this is set to TRUE then we should insert the term.
  1047. $do_cvterm_insert = TRUE;
  1048. // We need to locate terms using their dbxref. This is because term names
  1049. // can sometimes change, so we don't want to look up the term by it's name.
  1050. // the unique ID which is in the accession will never change.
  1051. $dbxref = new ChadoRecord('dbxref');
  1052. $dbxref->setValues([
  1053. 'db_id' => $db->db_id,
  1054. 'accession' => $accession,
  1055. ]);
  1056. if ($dbxref->find()) {
  1057. // Does this accession already have a cvterm it's associated with? Then
  1058. // we need to make we will update the name. Names change but accessions
  1059. // always refer to the same term.
  1060. $dbx_cvterm = new ChadoRecord('cvterm');
  1061. $dbx_cvterm->setValues(['dbxref_id' => $dbxref->getID()]);
  1062. if ($dbx_cvterm->find()) {
  1063. $do_cvterm_insert = FALSE;
  1064. $cvterm = $dbx_cvterm;
  1065. // We don't want to do any updates for borrowed terms. Just leave them
  1066. // as they are.
  1067. if (!$is_borrowed) {
  1068. // Let's make sure we don't have a conflict in term naming
  1069. // if we change the name of this term.
  1070. $this->fixTermMismatch($stanza, $dbxref, $cv, $name);
  1071. // Now update this cvterm record.
  1072. $cvterm->setValue('name', $name);
  1073. $cvterm->setValue('definition', $definition);
  1074. $cvterm->setValue('is_obsolete', $is_obsolete);
  1075. $cvterm->setValue('is_relationshiptype', $is_relationshiptype);
  1076. try {
  1077. $cvterm->update();
  1078. } catch (Exception $e) {
  1079. $this->logMessage('Could not update the term, "!term", with name, "!name" for vocabulary, "!vocab". ERROR: !error.',
  1080. [
  1081. '!term' => $id,
  1082. '!name' => $name,
  1083. '!vocab' => $cv->name,
  1084. '!error' => $e->getMessage(),
  1085. ],
  1086. TRIPAL_ERROR);
  1087. throw $e;
  1088. }
  1089. }
  1090. }
  1091. }
  1092. // The dbxref doesn't exist, so let's add it.
  1093. else {
  1094. $dbxref->insert();
  1095. }
  1096. // Add the cvterm if we didn't do an update.
  1097. if ($do_cvterm_insert) {
  1098. // Before updating the term let's check to see if it already exists
  1099. // and make corrections.
  1100. $cvterm = new ChadoRecord('cvterm');
  1101. $cvterm->setValue('cv_id', $cv->cv_id);
  1102. $cvterm->setValue('name', $name);
  1103. if ($cvterm->find()) {
  1104. $fixed = $this->fixTermMismatch($stanza, $dbxref, $cv, $name);
  1105. }
  1106. // The term doesn't exist, so let's just do our insert.
  1107. $cvterm->setValues([
  1108. 'cv_id' => $cv->cv_id,
  1109. 'name' => $name,
  1110. 'definition' => $definition,
  1111. 'dbxref_id' => $dbxref->getID(),
  1112. 'is_relationshiptype' => $is_relationshiptype,
  1113. 'is_obsolete' => $is_obsolete,
  1114. 'dbxref_id' => $dbxref->getValue('dbxref_id'),
  1115. ]);
  1116. // If the insert fails lets catch the error so we can
  1117. // give a more informative message.
  1118. try {
  1119. $cvterm->insert();
  1120. } catch (Exception $e) {
  1121. $this->logMessage('Could not insert the term, "!term", with name, "!name" for vocabulary, "!vocab". ERROR: !error.',
  1122. [
  1123. '!term' => $id,
  1124. '!name' => $name,
  1125. '!vocab' => $cv->name,
  1126. '!error' => $e->getMessage(),
  1127. ],
  1128. TRIPAL_ERROR);
  1129. throw $e;
  1130. }
  1131. }
  1132. // Save the cvterm_id for this term so we don't look it up again.
  1133. $cvterm_id = $cvterm->getID();
  1134. $this->used_terms[$id] = $cvterm_id;
  1135. // Return the cvterm_id.
  1136. return $cvterm_id;
  1137. }
  1138. /**
  1139. * Fixes mismatches between two terms with the same name.
  1140. *
  1141. * If it has been determined that a term's name has changed. Before we update
  1142. * or insert it we must check to make sure no other terms have that name. If
  1143. * they do we must make a correction.
  1144. *
  1145. * @param $dbxref
  1146. * The ChadoRecord object containing the dbxref record for the term
  1147. * to be inserted/updated.
  1148. * @param $cv
  1149. * The cvterm object.
  1150. * @param $name
  1151. * The name of the term that is a potential conflict.
  1152. *
  1153. * @return
  1154. * Returns TRUE if a conflict was found and corrected.
  1155. */
  1156. public function fixTermMismatch($stanza, $dbxref, $cv, $name) {
  1157. $id = $stanza['id'][0];
  1158. $name = $stanza['name'][0];
  1159. // First get the record for any potential conflicting term.
  1160. $sql = "
  1161. SELECT cvterm_id
  1162. FROM {cvterm}
  1163. WHERE name = :name and cv_id = :cv_id and dbxref_id != :dbxref_id
  1164. ";
  1165. $args = [
  1166. ':name' => $name,
  1167. ':cv_id' => $cv->cv_id,
  1168. ':dbxref_id' => $dbxref->getID(),
  1169. ];
  1170. $results = chado_query($sql, $args);
  1171. while ($conflict_id = $results->fetchField()) {
  1172. $check_cvterm = new ChadoRecord('cvterm', $conflict_id);
  1173. // If the dbxref of this matched term is the same as the current term
  1174. // then it is the same term and there is no conflict.
  1175. if ($dbxref->getID() == $check_cvterm->getValue('dbxref_id')) {
  1176. return FALSE;
  1177. }
  1178. // At this point, we have a cvterm with the same name and vocabulary
  1179. // but with a different dbxref. First let's get that other accession.
  1180. $check_dbxref = new ChadoRecord('dbxref', $check_cvterm->getValue('dbxref_id'));
  1181. $check_db = new ChadoRecord('db', $check_dbxref->getValue('db_id'));
  1182. $check_accession = $check_db->getValue('name') . ':' . $check_dbxref->getValue('accession');
  1183. // Case 1: The other term that currently has the same name is
  1184. // missing in the OBO file (i.e. no stanza). So, that means that this
  1185. // term probably got relegated to an alt_id on another term. We do
  1186. // not want to delete a term because it may be linked to other
  1187. // records. Instead, let's update its name to let folks know
  1188. // what happened to it and so we can get around the unique
  1189. // constraint. An example of this is the GO:0015881 and
  1190. // GO:1902598 terms where the latter became an alt_id of the
  1191. // first and no longer has its own entry.
  1192. $check_stanza = $this->getCachedTermStanza($check_accession);
  1193. if (!$check_stanza) {
  1194. $new_name = $check_cvterm->getValue('name') . ' (' . $check_accession . ')';
  1195. $check_cvterm->setValue('name', $new_name);
  1196. $check_cvterm->setValue('is_obsolete', '1');
  1197. $check_cvterm->update();
  1198. return TRUE;
  1199. }
  1200. // Case 2: The conflicting term is in the OBO file (ie. has a stanza) and
  1201. // is obsolete and this one is not. Fix it by adding an (obsolete) suffix
  1202. // to the name to avoid the conflict.
  1203. else {
  1204. if (array_key_exists('is_obsolete', $check_stanza) and ($check_stanza['is_obsolete'][0] == 'true') and (!array_key_exists('is_obsolete', $stanza) or ($stanza['is_obsolete'][0] != 'true'))) {
  1205. $new_name = $check_cvterm->getValue('name') . ' (obsolete)';
  1206. $check_cvterm->setValue('name', $new_name);
  1207. $check_cvterm->update();
  1208. return TRUE;
  1209. }
  1210. // Case 3: The conflicting term is in the OBO file (ie. has a stanza).
  1211. // That means that there has been some name swapping between
  1212. // terms. We need to temporarily rename the term so that
  1213. // we don't have a unique constraint violation when we update
  1214. // the new one. An example of this is where GO:000425 and
  1215. // GO:0030242 changed names and one was renamed to the previous
  1216. // name of the other.
  1217. else {
  1218. $new_name = $check_cvterm->getValue('name') . ' (' . $check_accession . ')';
  1219. $check_cvterm->setValue('name', $new_name);
  1220. $check_cvterm->update();
  1221. return TRUE;
  1222. }
  1223. }
  1224. }
  1225. // We have no conflict so it's save to update or insert.
  1226. return FALSE;
  1227. }
  1228. /**
  1229. * Uses the provided term array to add/update information to Chado about the
  1230. * term including the term, dbxref, synonyms, properties, and relationships.
  1231. *
  1232. * @param $term
  1233. * An array representing the cvterm.
  1234. *
  1235. * @is_relationship
  1236. * Set to 1 if this term is a relationship term
  1237. *
  1238. * @ingroup tripal_obo_loader
  1239. */
  1240. private function processTerm($stanza, $is_relationship = 0) {
  1241. //
  1242. // First things first--save the term.
  1243. //
  1244. // If the term does not exist it is inserted, if it does exist it just
  1245. // retrieves the cvterm_id.
  1246. //
  1247. $cvterm_id = $this->saveTerm($stanza, FALSE);
  1248. $id = $stanza['id'][0];
  1249. // If this term is borrowed from another ontology? If so then we will
  1250. // not update it.
  1251. if ($this->isTermBorrowed($stanza)) {
  1252. return;
  1253. }
  1254. // If this term belongs to this OBO (not borrowed from another OBO) then
  1255. // remove any relationships, properties, xrefs, and synonyms that this
  1256. // term already has so that they can be re-added.
  1257. $sql = "
  1258. DELETE FROM {cvterm_relationship}
  1259. WHERE subject_id = :cvterm_id
  1260. ";
  1261. chado_query($sql, [':cvterm_id' => $cvterm_id]);
  1262. // If this is an obsolete term then clear out the relationships where
  1263. // this term is the object.
  1264. if (in_array('is_obsolete', $stanza) and $stanza['is_obsolete'] == 'true') {
  1265. $sql = "
  1266. DELETE FROM {cvterm_relationship}
  1267. WHERE object_id = :cvterm_id
  1268. ";
  1269. chado_query($sql, [':cvterm_id' => $cvterm_id]);
  1270. }
  1271. $sql = "
  1272. DELETE FROM {cvtermprop}
  1273. WHERE cvterm_id = :cvterm_id
  1274. ";
  1275. chado_query($sql, [':cvterm_id' => $cvterm_id]);
  1276. $sql = "
  1277. DELETE FROM {cvterm_dbxref}
  1278. WHERE cvterm_id = :cvterm_id
  1279. ";
  1280. chado_query($sql, [':cvterm_id' => $cvterm_id]);
  1281. $sql = "
  1282. DELETE FROM {cvtermsynonym} CVTSYN
  1283. WHERE cvterm_id = :cvterm_id
  1284. ";
  1285. chado_query($sql, [':cvterm_id' => $cvterm_id]);
  1286. // We should never have the problem where we don't have a cvterm_id. The
  1287. // saveTerm() function should always return on. But if for some unknown
  1288. // reason we don't have one then fail.
  1289. if (!$cvterm_id) {
  1290. throw new Exception(t('Missing cvterm after saving term: !term',
  1291. ['!term' => print_r($stanza, TRUE)]));
  1292. }
  1293. //
  1294. // Handle: alt_id
  1295. //
  1296. if (array_key_exists('alt_id', $stanza)) {
  1297. foreach ($stanza['alt_id'] as $alt_id) {
  1298. $this->addAltID($id, $cvterm_id, $alt_id);
  1299. }
  1300. }
  1301. //
  1302. // Handle: synonym
  1303. //
  1304. if (array_key_exists('synonym', $stanza)) {
  1305. foreach ($stanza['synonym'] as $synonym) {
  1306. $this->addSynonym($id, $cvterm_id, $synonym);
  1307. }
  1308. }
  1309. //
  1310. // Handle: exact_synonym
  1311. //
  1312. if (array_key_exists('exact_synonym', $stanza)) {
  1313. foreach ($stanza['exact_synonym'] as $synonym) {
  1314. $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 EXACT $2', $synonym);
  1315. $this->addSynonym($id, $cvterm_id, $fixed);
  1316. }
  1317. }
  1318. //
  1319. // Handle: narrow_synonym
  1320. //
  1321. if (array_key_exists('narrow_synonym', $stanza)) {
  1322. foreach ($stanza['narrow_synonym'] as $synonym) {
  1323. $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 NARROW $2', $synonym);
  1324. $this->addSynonym($id, $cvterm_id, $fixed);
  1325. }
  1326. }
  1327. //
  1328. // Handle: broad_synonym
  1329. //
  1330. if (array_key_exists('broad_synonym', $stanza)) {
  1331. foreach ($stanza['broad_synonym'] as $synonym) {
  1332. $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 BROAD $2', $synonym);
  1333. $this->addSynonym($id, $cvterm_id, $fixed);
  1334. }
  1335. }
  1336. //
  1337. // Handle: comment
  1338. //
  1339. if (array_key_exists('comment', $stanza)) {
  1340. $comments = $stanza['comment'];
  1341. foreach ($comments as $rank => $comment) {
  1342. $this->addComment($id, $cvterm_id, $comment, $rank);
  1343. }
  1344. }
  1345. //
  1346. // Handle: xref
  1347. //
  1348. if (array_key_exists('xref', $stanza)) {
  1349. foreach ($stanza['xref'] as $xref) {
  1350. $this->addXref($id, $cvterm_id, $xref);
  1351. }
  1352. }
  1353. //
  1354. // Handle: xref_analog
  1355. //
  1356. if (array_key_exists('xref_analog', $stanza)) {
  1357. foreach ($stanza['xref_analog'] as $xref) {
  1358. $this->addXref($id, $cvterm_id, $xref);
  1359. }
  1360. }
  1361. //
  1362. // Handle: xref_unk
  1363. //
  1364. if (array_key_exists('xref_unk', $stanza)) {
  1365. foreach ($stanza['xref_unk'] as $xref) {
  1366. $this->addXref($id, $cvterm_id, $xref);
  1367. }
  1368. }
  1369. //
  1370. // Handle: subset
  1371. //
  1372. if (array_key_exists('subset', $stanza)) {
  1373. foreach ($stanza['subset'] as $subset) {
  1374. $this->addSubset($id, $cvterm_id, $subset);
  1375. }
  1376. }
  1377. //
  1378. // Handle: is_a
  1379. //
  1380. if (array_key_exists('is_a', $stanza)) {
  1381. foreach ($stanza['is_a'] as $is_a) {
  1382. $this->addRelationship($id, $cvterm_id, 'is_a', $is_a);
  1383. }
  1384. }
  1385. //
  1386. // Handle: relationship
  1387. //
  1388. if (array_key_exists('relationship', $stanza)) {
  1389. foreach ($stanza['relationship'] as $value) {
  1390. $rel = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
  1391. $object = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
  1392. $this->addRelationship($id, $cvterm_id, $rel, $object);
  1393. }
  1394. }
  1395. /**
  1396. * The following properties are currently unsupported:
  1397. *
  1398. * - intersection_of
  1399. * - union_of
  1400. * - disjoint_from
  1401. * - replaced_by
  1402. * - consider
  1403. * - use_term
  1404. * - builtin
  1405. * - is_anonymous
  1406. *
  1407. */
  1408. }
  1409. /**
  1410. * Adds a cvterm relationship
  1411. *
  1412. * @param $cvterm_id
  1413. * A cvterm_id of the term to which the relationship will be added.
  1414. * @param $rel_id
  1415. * The relationship term ID
  1416. * @param $obj_id
  1417. * The relationship object term ID.
  1418. *
  1419. * @ingroup tripal_obo_loader
  1420. */
  1421. private function addRelationship($id, $cvterm_id, $rel_id, $obj_id) {
  1422. // Get the cached terms for both the relationship and the object. They
  1423. // should be there, but just in case something went wrong, we'll throw
  1424. // an exception if we can't find them.
  1425. $rel_stanza = $this->getCachedTermStanza($rel_id);
  1426. if (!$rel_stanza) {
  1427. throw new Exception(t('Cannot add relationship: "!source !rel !object". ' .
  1428. 'The term, !rel, is not in the term cache.',
  1429. ['!source' => $id, '!rel' => $rel_id, '!name' => $obj_id]));
  1430. }
  1431. $rel_cvterm_id = $this->saveTerm($rel_stanza, TRUE);
  1432. // Make sure the object term exists in the cache.
  1433. $obj_stanza = $this->getCachedTermStanza($obj_id);
  1434. if (!$obj_stanza) {
  1435. throw new Exception(t('Cannot add relationship: "!source !rel !object". ' .
  1436. 'The term, !object, is not in the term cache.',
  1437. ['!source' => $id, '!rel' => $rel_id, '!object' => $obj_id]));
  1438. }
  1439. $obj_cvterm_id = $this->saveTerm($obj_stanza);
  1440. // Add the cvterm_relationship.
  1441. $cvterm_relationship = new ChadoRecord('cvterm_relationship');
  1442. $cvterm_relationship->setValues([
  1443. 'type_id' => $rel_cvterm_id,
  1444. 'subject_id' => $cvterm_id,
  1445. 'object_id' => $obj_cvterm_id,
  1446. ]);
  1447. // If the insert fails then catch the error and generate a more meaningful
  1448. // message that helps with debugging.
  1449. try {
  1450. $cvterm_relationship->insert();
  1451. } catch (Exception $e) {
  1452. throw new Exception(t('Cannot add relationship: "!source !rel !object". ' .
  1453. 'ERROR: !error.',
  1454. [
  1455. '!source' => $id,
  1456. '!rel' => $rel_id,
  1457. '!object' => $obj_id,
  1458. '!error' => $e->getMessage(),
  1459. ]));
  1460. }
  1461. }
  1462. /**
  1463. * Retrieves the term array from the temp loading table for a given term id.
  1464. *
  1465. * @param id
  1466. * The id of the term to retrieve
  1467. *
  1468. * @ingroup tripal_obo_loader
  1469. */
  1470. private function getCachedTermStanza($id) {
  1471. if ($this->cache_type == 'table') {
  1472. $values = ['id' => $id];
  1473. $result = chado_select_record('tripal_obo_temp', ['stanza'], $values);
  1474. if (count($result) == 0) {
  1475. return FALSE;
  1476. }
  1477. return unserialize(base64_decode($result['stanza']));
  1478. }
  1479. if (array_key_exists($id, $this->termStanzaCache['ids'])) {
  1480. return $this->termStanzaCache['ids'][$id];
  1481. }
  1482. else {
  1483. return FALSE;
  1484. }
  1485. }
  1486. /**
  1487. * Using the term's short-name and accession try to find it in Chado.
  1488. *
  1489. * @param $short_name
  1490. * The term's ontology prefix (database short name)
  1491. * @param $accession
  1492. * The term's accession.
  1493. *
  1494. * @return array|NULL
  1495. */
  1496. private function lookupTerm($short_name, $accession) {
  1497. // Does the database already exist?
  1498. if (!array_key_exists($short_name, $this->all_dbs)) {
  1499. return NULL;
  1500. }
  1501. $db = $this->all_dbs[$short_name];
  1502. // Check if the dbxref exists.
  1503. $dbxref = new ChadoRecord('dbxref');
  1504. $dbxref->setValues([
  1505. 'db_id' => $db->db_id,
  1506. 'accession' => $accession,
  1507. ]);
  1508. if (!$dbxref->find()) {
  1509. return NULL;
  1510. }
  1511. // If the dbxref exists then see if it has a corresponding cvterm.
  1512. $cvterm = new ChadoRecord('cvterm');
  1513. $cvterm->setValues(['dbxref_id' => $dbxref->getID()]);
  1514. if (!$cvterm->find()) {
  1515. return NULL;
  1516. }
  1517. // Get the CV for this term.
  1518. $cv = new ChadoRecord('cv');
  1519. $cv->setValues(['cv_id' => $cvterm->getValue('cv_id')]);
  1520. $cv->find();
  1521. // Create a new stanza using the values of this cvterm.
  1522. $stanza = [];
  1523. $stanza['id'][0] = $short_name . ':' . $accession;
  1524. $stanza['name'][0] = $cvterm->getValue('name');
  1525. $stanza['def'][0] = $cvterm->getValue('definition');
  1526. $stanza['namespace'][0] = $cv->getValue('name');
  1527. $stanza['is_obsolete'][0] = $cvterm->getValue('is_obsolete') == 1 ? 'true' : '';
  1528. $stanza['is_relationshiptype'][0] = '';
  1529. $stanza['db_name'][0] = $db->name;
  1530. $stanza['cv_name'][0] = $cv->getValue('name');
  1531. return $stanza;
  1532. }
  1533. /**
  1534. * Adds a term stanza from the OBO file to the cache for easier lookup.
  1535. *
  1536. * @param $stanza
  1537. * The stanza from the OBO file for the term.
  1538. *
  1539. * @throws Exception
  1540. */
  1541. private function cacheTermStanza($stanza, $type) {
  1542. // Make sure we have defaults.
  1543. if (!$this->default_namespace) {
  1544. throw new Exception('Cannot cache terms without a default CV.' . print_r($stanza, TRUE));
  1545. }
  1546. if (!$this->default_db) {
  1547. throw new Exception('Cannot cache terms without a default DB.' . print_r($stanza, TRUE));
  1548. }
  1549. $id = $stanza['id'][0];
  1550. // First check if this term is already in the cache, if so then skip it.
  1551. if ($this->getCachedTermStanza($id)) {
  1552. return;
  1553. }
  1554. // Does this term have a database short name prefix in the ID (accession)?
  1555. // If not then we'll add the default CV as the namespace. If it does and
  1556. // the short name is not the default for this vocabulary then we'll look
  1557. // it up.
  1558. $matches = [];
  1559. if (preg_match('/^(.+):(.+)$/', $id, $matches)) {
  1560. $short_name = $matches[1];
  1561. $accession = $matches[2];
  1562. // If the term is borrowed then let's try to deal with it.
  1563. if ($short_name != $this->default_db) {
  1564. // First try to lookup the term and replace the stanza with the updated
  1565. // details.
  1566. $found = $this->lookupTerm($short_name, $accession);
  1567. if ($found) {
  1568. $stanza = $found;
  1569. }
  1570. // If we can't find the term in the database then do an EBI lookup.
  1571. else {
  1572. $stanza = $this->findEBITerm($id);
  1573. if (!$stanza) {
  1574. return FALSE;
  1575. }
  1576. // Make sure the DBs and CVs exist and are added to our cache.
  1577. $this->addDB($stanza['db_name'][0]);
  1578. $this->addCV($stanza['namespace'][0]);
  1579. }
  1580. }
  1581. // If the term belongs to this OBO then let's set the 'db_name'.
  1582. else {
  1583. if (!array_key_exists('namespace', $stanza)) {
  1584. $stanza['namespace'][0] = $this->default_namespace;
  1585. }
  1586. $stanza['db_name'][0] = $short_name;
  1587. }
  1588. // Make sure the db for this term is added to Chado. If it already is
  1589. // then this function won't re-add it.
  1590. $this->addDB($short_name);
  1591. }
  1592. // If there is no DB short name prefix for the id.
  1593. else {
  1594. if (!array_key_exists('namespace', $stanza)) {
  1595. $stanza['namespace'][0] = $this->default_namespace;
  1596. }
  1597. $stanza['db_name'][0] = $this->default_db;
  1598. }
  1599. $stanza['is_relationshiptype'][0] = '';
  1600. if ($type == 'Typedef') {
  1601. $stanza['is_relationshiptype'][0] = 'true';
  1602. }
  1603. // The is_a field can have constructs like this: {is_inferred="true"}
  1604. // We need to remove those if they exist.
  1605. if (array_key_exists('is_a', $stanza)) {
  1606. foreach ($stanza['is_a'] as $index => $is_a) {
  1607. $stanza['is_a'][$index] = trim(preg_replace('/\{.+?\}/', '', $is_a));
  1608. }
  1609. }
  1610. if (array_key_exists('relationship', $stanza)) {
  1611. foreach ($stanza['relationship'] as $index => $relationship) {
  1612. $stanza['relationship'][$index] = trim(preg_replace('/\{.+?\}/', '', $relationship));
  1613. }
  1614. }
  1615. // Clean up any synonym definitions. We only handle the synonym in
  1616. // quotes and the type.
  1617. if (array_key_exists('synonym', $stanza)) {
  1618. foreach ($stanza['synonym'] as $index => $synonym) {
  1619. if (preg_match('/\"(.*?)\".*(EXACT|NARROW|BROAD|RELATED)/', $synonym, $matches)) {
  1620. $stanza['synonym'][$index] = '"' . $matches[1] . '" ' . $matches[2];
  1621. }
  1622. }
  1623. }
  1624. // Now before saving, remove any duplicates. Sometimes the OBOs have
  1625. // the same item duplicated in the stanza multiple times. This will
  1626. // result in duplicate constraint violations in the tables. We can either
  1627. // check on every insert if the record exists increasing loading time or
  1628. // remove duplicates here.
  1629. foreach ($stanza as $key => $values) {
  1630. $stanza[$key] = array_unique($values);
  1631. }
  1632. // If we should use the cache_type is to cache in the tripal_obo_temp
  1633. // table then handle that now.
  1634. if ($this->cache_type == 'table') {
  1635. // Add the term to the temp table.
  1636. $values = [
  1637. 'id' => $id,
  1638. 'stanza' => base64_encode(serialize($stanza)),
  1639. 'type' => $type,
  1640. ];
  1641. $success = chado_insert_record('tripal_obo_temp', $values);
  1642. if (!$success) {
  1643. throw new Exception("Cannot insert stanza into temporary table.");
  1644. }
  1645. return;
  1646. }
  1647. // Cache the term stanza
  1648. $this->termStanzaCache['ids'][$id] = $stanza;
  1649. $this->termStanzaCache['count'][$type]++;
  1650. $this->termStanzaCache['types'][$type][] = $id;
  1651. // Cache the term name so we don't have conflicts.
  1652. $name = $stanza['name'][0];
  1653. $this->term_names[$name] = 1;
  1654. }
  1655. /**
  1656. * Returns the size of a given term type from the cache.
  1657. *
  1658. * @param $type
  1659. * The term type: Typedef, Term, etc.
  1660. */
  1661. private function getCacheSize($type) {
  1662. if ($this->cache_type == 'table') {
  1663. $sql = "
  1664. SELECT count(*) as num_terms
  1665. FROM {tripal_obo_temp}
  1666. WHERE type = :type
  1667. ";
  1668. $result = chado_query($sql, [':type' => $type])->fetchObject();
  1669. return $result->num_terms;
  1670. }
  1671. return $this->termStanzaCache['count'][$type];
  1672. }
  1673. /**
  1674. * Retrieves all term IDs for a given type.
  1675. *
  1676. * If the cache is using the tripal_obo_temp table then it
  1677. * returns an iterable Database handle.
  1678. */
  1679. private function getCachedTermStanzas($type) {
  1680. if ($this->cache_type == 'table') {
  1681. $sql = "SELECT id FROM {tripal_obo_temp} WHERE type = 'Typedef' ";
  1682. $typedefs = chado_query($sql);
  1683. return $typedefs;
  1684. }
  1685. return $this->termStanzaCache['types'][$type];
  1686. }
  1687. /**
  1688. * Clear's the term cache.
  1689. */
  1690. private function clearTermStanzaCache() {
  1691. if ($this->cache_type == 'table') {
  1692. $sql = "DELETE FROM {tripal_obo_temp}";
  1693. chado_query($sql);
  1694. return;
  1695. }
  1696. $this->termStanzaCache = [
  1697. 'ids' => [],
  1698. 'count' => [
  1699. 'Typedef' => 0,
  1700. 'Term' => 0,
  1701. 'Instance' => 0,
  1702. ],
  1703. 'types' => [
  1704. 'Typedef' => [],
  1705. 'Term' => [],
  1706. 'Instance' => [],
  1707. ],
  1708. ];
  1709. }
  1710. /**
  1711. * Adds the synonyms to a term
  1712. *
  1713. * @param $cvterm_id
  1714. * The cvterm_id of the term to which the synonym will be added.
  1715. * @param $synonym
  1716. * The value of the 'synonym' line of the term stanza.
  1717. *
  1718. * @ingroup tripal_obo_loader
  1719. */
  1720. private function addSynonym($id, $cvterm_id, $synonym) {
  1721. $def = $synonym;
  1722. $syn_type = '';
  1723. // Separate out the synonym definition and type (e.g. EXACT).
  1724. $matches = [];
  1725. if (preg_match('/\"(.*?)\".*(EXACT|NARROW|BROAD|RELATED)/', $synonym, $matches)) {
  1726. $def = $matches[1];
  1727. $syn_type = strtolower($matches[2]);
  1728. }
  1729. // Get the syn type cvterm.
  1730. if (!$syn_type) {
  1731. $syn_type = 'exact';
  1732. }
  1733. $syn_type_term = $this->syn_types[$syn_type];
  1734. if (!$syn_type_term) {
  1735. throw new Exception(t('Cannot find synonym type: !type', ['!type' => $syn_type]));
  1736. }
  1737. // The synonym can only be 255 chars in the cvtermsynonym table.
  1738. // to prevent failing we have to truncate.
  1739. if (strlen($def) > 255) {
  1740. $def = substr($def, 0, 252) . "...";
  1741. }
  1742. // Now save the new synonym.
  1743. $cvtermsynonym = new ChadoRecord('cvtermsynonym');
  1744. $cvtermsynonym->setValues([
  1745. 'cvterm_id' => $cvterm_id,
  1746. 'synonym' => $def,
  1747. ]);
  1748. // If the insert fails then catch the error and generate a more meaningful
  1749. // message that helps with debugging.
  1750. try {
  1751. // The unique constraint for the cvterm_synonym table is with the
  1752. // cvterm_id and the synonym. It does not include the type_id.
  1753. // The CHEBI contains terms with the same synonym but with different
  1754. // types. For example:
  1755. // synonym: "2-chloro-N-(2-chloroethyl)-N-methylethanamine hydrochloride" EXACT IUPAC_NAME [IUPAC]
  1756. // synonym: "2-chloro-N-(2-chloroethyl)-N-methylethanamine hydrochloride" RELATED [ChemIDplus]
  1757. // In this case on the first one is added.
  1758. // @todo: This is a deficiency with Chado that should be corrected.
  1759. if (!$cvtermsynonym->find()) {
  1760. $cvtermsynonym->setValue('type_id', $syn_type_term->cvterm_id);
  1761. $cvtermsynonym->insert();
  1762. }
  1763. } catch (Exception $e) {
  1764. throw new Exception(t('Cannot add synonym, "!synonym" to term: !id. ' .
  1765. 'ERROR: !error.',
  1766. ['!synonym' => $def, '!id' => $id, '!error' => $e->getMessage()]));
  1767. }
  1768. }
  1769. /**
  1770. * Parse the OBO file and populate the templ loading table
  1771. *
  1772. * @param $file
  1773. * The path on the file system where the ontology can be found
  1774. * @param $header
  1775. * An array passed by reference that will be populated with the header
  1776. * information from the OBO file
  1777. *
  1778. * @ingroup tripal_obo_loader
  1779. */
  1780. private function parse($obo_file, &$header) {
  1781. // Set to 1 if we are in the top header lines of the file.
  1782. $in_header = TRUE;
  1783. // Holds the full stanza for the term.
  1784. $stanza = [];
  1785. // Holds the default database for the term.
  1786. $db_short_name = '';
  1787. $line_num = 0;
  1788. $num_read = 0;
  1789. // The type of term: Typedef or Term (inside the [] brackets]
  1790. $type = '';
  1791. $filesize = filesize($obo_file);
  1792. $this->setTotalItems($filesize);
  1793. $this->setItemsHandled(0);
  1794. $this->setInterval(5);
  1795. // iterate through the lines in the OBO file and parse the stanzas
  1796. $fh = fopen($obo_file, 'r');
  1797. while ($line = fgets($fh)) {
  1798. $line_num++;
  1799. $size = drupal_strlen($line);
  1800. $num_read += $size;
  1801. $line = trim($line);
  1802. $this->setItemsHandled($num_read);
  1803. // remove newlines
  1804. $line = rtrim($line);
  1805. // remove any special characters that may be hiding
  1806. $line = preg_replace('/[^(\x20-\x7F)]*/', '', $line);
  1807. // skip empty lines
  1808. if (strcmp($line, '') == 0) {
  1809. continue;
  1810. }
  1811. // Remove comments from end of lines.
  1812. $line = preg_replace('/^(.*?)\!.*$/', '\1', $line);
  1813. // At the first stanza we're out of header.
  1814. if (preg_match('/^\s*\[/', $line)) {
  1815. // After parsing the header we need to get information about this OBO.
  1816. if ($in_header == TRUE) {
  1817. $this->setDefaults($header);
  1818. $in_header = FALSE;
  1819. }
  1820. // Store the stanza we just finished reading.
  1821. if (sizeof($stanza) > 0) {
  1822. // If this term has a namespace then we want to keep track of it.
  1823. if (array_key_exists('namespace', $stanza)) {
  1824. $namespace = $stanza['namespace'][0];
  1825. $cv = $this->all_cvs[$namespace];
  1826. $this->obo_namespaces[$namespace] = $cv->cv_id;
  1827. }
  1828. // Before caching this stanza, check the term's name to
  1829. // make sure it doesn't conflict. If it does we'll just
  1830. // add the ID to the name to ensure it doesn't.
  1831. if (array_key_exists($stanza['name'][0], $this->term_names)) {
  1832. $new_name = $stanza['name'][0] . '(' . $stanza['id'][0] . ')';
  1833. $stanza['name'][0] = $stanza['name'][0];
  1834. }
  1835. $this->cacheTermStanza($stanza, $type);
  1836. }
  1837. // Get the stanza type: Term, Typedef or Instance
  1838. $type = preg_replace('/^\s*\[\s*(.+?)\s*\]\s*$/', '\1', $line);
  1839. // start fresh with a new array
  1840. $stanza = [];
  1841. continue;
  1842. }
  1843. // break apart the line into the tag and value but ignore any escaped colons
  1844. preg_replace("/\\:/", "|-|-|", $line); // temporarily replace escaped colons
  1845. $pair = explode(":", $line, 2);
  1846. $tag = $pair[0];
  1847. $value = ltrim(rtrim($pair[1]));// remove surrounding spaces
  1848. // if this is the ID line then get the database short name from the ID.
  1849. $matches = [];
  1850. if ($tag == 'id' and preg_match('/^(.+?):.*$/', $value, $matches)) {
  1851. $db_short_name = $matches[1];
  1852. }
  1853. $tag = preg_replace("/\|-\|-\|/", "\:", $tag); // return the escaped colon
  1854. $value = preg_replace("/\|-\|-\|/", "\:", $value);
  1855. if ($in_header) {
  1856. if (!array_key_exists($tag, $header)) {
  1857. $header[$tag] = [];
  1858. }
  1859. $header[$tag][] = $value;
  1860. }
  1861. else {
  1862. if (!array_key_exists($tag, $stanza)) {
  1863. $stanza[$tag] = [];
  1864. }
  1865. $stanza[$tag][] = $value;
  1866. }
  1867. }
  1868. // now add the last term in the file
  1869. if (sizeof($stanza) > 0) {
  1870. // If this term has a namespace then we want to keep track of it.
  1871. if (array_key_exists('namespace', $stanza)) {
  1872. $namespace = $stanza['namespace'][0];
  1873. $cv = $this->all_cvs[$namespace];
  1874. $this->obo_namespaces[$namespace] = $cv->cv_id;
  1875. }
  1876. $this->cacheTermStanza($stanza, $type);
  1877. $this->setItemsHandled($num_read);
  1878. }
  1879. // Make sure there are CV records for all namespaces.
  1880. $message = t('Found the following namespaces: !namespaces.',
  1881. ['!namespaces' => implode(', ', array_keys($this->obo_namespaces))]);
  1882. foreach ($this->obo_namespaces as $namespace => $cv_id) {
  1883. $this->addCV($namespace);
  1884. }
  1885. $this->logMessage($message);
  1886. }
  1887. /**
  1888. * Iterates through all of the cached terms and caches any relationships
  1889. */
  1890. private function cacheRelationships() {
  1891. // Now that we have all of the terms parsed and loaded into the cache,
  1892. // lets run through them one more time cache any terms in relationships
  1893. // as well.
  1894. $terms = $this->getCachedTermStanzas('Term');
  1895. $count = $this->getCacheSize('Term');
  1896. $this->setTotalItems($count);
  1897. $this->setItemsHandled(0);
  1898. $this->setInterval(25);
  1899. // Iterate through the terms.
  1900. $i = 1;
  1901. foreach ($terms as $t) {
  1902. // TODO: it would be better if we had a term iterator so that we
  1903. // don't have to distinguish here between the table vs memory cache type.
  1904. if ($this->cache_type == 'table') {
  1905. $stanza = unserialize(base64_decode($t->stanza));
  1906. }
  1907. else {
  1908. $stanza = $this->termStanzaCache['ids'][$t];
  1909. }
  1910. // Check if this stanza has an is_a relationship that needs lookup.
  1911. if (array_key_exists('is_a', $stanza)) {
  1912. foreach ($stanza['is_a'] as $object_term) {
  1913. $rstanza = [];
  1914. $rstanza['id'][] = $object_term;
  1915. $this->cacheTermStanza($rstanza, 'Term');
  1916. }
  1917. }
  1918. // Check if this stanza has any additional relationships for lookup.
  1919. if (array_key_exists('relationship', $stanza)) {
  1920. foreach ($stanza['relationship'] as $value) {
  1921. // Get the relationship term and the object term
  1922. $rel_term = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
  1923. $object_term = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
  1924. $rstanza = [];
  1925. $rstanza['id'][] = $rel_term;
  1926. $this->cacheTermStanza($rstanza, 'Typedef');
  1927. $rstanza = [];
  1928. $rstanza['id'][] = $object_term;
  1929. $this->cacheTermStanza($rstanza, 'Term');
  1930. }
  1931. }
  1932. }
  1933. $this->setItemsHandled($i++);
  1934. // Last of all, we need to add the "is_a" relationship It's part of the
  1935. // OBO specification as a built-in relationship but not all vocabularies
  1936. // include that term.
  1937. if (!$this->getCachedTermStanza('is_a')) {
  1938. $stanza = [];
  1939. $stanza['id'][0] = 'is_a';
  1940. $stanza['name'][0] = 'is_a';
  1941. $stanza['namespace'][0] = $this->default_namespace;
  1942. $stanza['db_name'][0] = $this->default_db;
  1943. $this->cacheTermStanza($stanza, 'Typedef');
  1944. }
  1945. }
  1946. /**
  1947. * Adds a property to the cvterm indicating it belongs to a subset.
  1948. *
  1949. * @param $cvterm_id
  1950. * The cvterm_id of the term to which the subset will be added.
  1951. * @param $subset
  1952. * The name of the subset.
  1953. */
  1954. private function addSubset($id, $cvterm_id, $subset) {
  1955. $cvtermprop = new ChadoRecord('cvtermprop');
  1956. $cvtermprop->setValues([
  1957. 'cvterm_id' => $cvterm_id,
  1958. 'type_id' => $this->used_terms['NCIT:C25693'],
  1959. 'value' => $subset,
  1960. ]);
  1961. // If the insert fails then catch the error and generate a more meaningful
  1962. // message that helps with debugging.
  1963. try {
  1964. $cvtermprop->insert();
  1965. } catch (Exception $e) {
  1966. throw new Exception(t('Cannot add subset, "!subset" to term: !id. ' .
  1967. 'ERROR: !error.',
  1968. ['!subset' => $subset, '!id' => $id, '!error' => $e->getMessage()]));
  1969. }
  1970. }
  1971. /**
  1972. * Adds a database to Chado if it doesn't exist.
  1973. *
  1974. * @param $dbname
  1975. * The name of the database to add.
  1976. *
  1977. * @return
  1978. * A Chado database object.
  1979. */
  1980. private function addDB($dbname) {
  1981. // Add the database if it doesn't exist.
  1982. $db = NULL;
  1983. if (array_key_exists($dbname, $this->all_dbs)) {
  1984. $db = $this->all_dbs[$dbname];
  1985. }
  1986. else {
  1987. // If it's not in the cache we can assume it doesn't exist and insert.
  1988. $db = new ChadoRecord('db');
  1989. $db->setValues(['name' => $dbname]);
  1990. $db->insert();
  1991. $db = (object) $db->getValues();
  1992. $this->all_dbs[$dbname] = $db;
  1993. }
  1994. return $db;
  1995. }
  1996. /**
  1997. * Adds a vocabulary to Chado if it doesn't exist.
  1998. *
  1999. * @param $cvname
  2000. * The name of the vocabulary to add.
  2001. *
  2002. * @return
  2003. * A Chado cv object.
  2004. */
  2005. private function addCV($cvname) {
  2006. // TODO: we need to get the description and title from EBI for these
  2007. // ontology so that we can put something in the proper fields when
  2008. // adding a new CV or DB.
  2009. // Add the CV record if it doesn't exist.
  2010. $cv = NULL;
  2011. if (array_key_exists($cvname, $this->all_cvs)) {
  2012. $cv = $this->all_cvs[$cvname];
  2013. }
  2014. else {
  2015. // If it's not in the cache we can assume it doesn't exist and insert.
  2016. $cv = new ChadoRecord('cv');
  2017. $cv->setValues(['name' => $cvname]);
  2018. $cv->insert();
  2019. $cv = (object) $cv->getValues();
  2020. $this->all_cvs[$cvname] = $cv;
  2021. $this->obo_namespaces[$cvname] = $cv->cv_id;
  2022. }
  2023. return $cv;
  2024. }
  2025. /**
  2026. * Indicates if the term belongs to this OBO or if it was borrowed
  2027. * .
  2028. *
  2029. * @param $stanza
  2030. */
  2031. private function isTermBorrowed($stanza) {
  2032. $namespace = $stanza['namespace'][0];
  2033. if (array_key_exists($namespace, $this->obo_namespaces)) {
  2034. return FALSE;
  2035. }
  2036. return TRUE;
  2037. }
  2038. /**
  2039. * Adds an alternative ID
  2040. *
  2041. * @param $cvterm_id
  2042. * The cvterm_id of the term to which the synonym will be added.
  2043. * @param $alt_id
  2044. * The cross reference. It should be of the form from the OBO specification
  2045. *
  2046. * @ingroup tripal_obo_loader
  2047. */
  2048. private function addAltID($id, $cvterm_id, $alt_id) {
  2049. $dbname = '';
  2050. $accession = '';
  2051. $matches = [];
  2052. if (preg_match('/^(.+?):(.*)$/', $alt_id, $matches)) {
  2053. $dbname = $matches[1];
  2054. $accession = $matches[2];
  2055. }
  2056. if (!$accession) {
  2057. throw new Exception("Cannot add an Alt ID without an accession: '$alt_id'");
  2058. }
  2059. // Add the database if it doesn't exist.
  2060. $db = $this->addDB($dbname);
  2061. $db_id = $db->db_id;
  2062. // Now add the dbxref if it doesn't already exist
  2063. $dbxref = new ChadoRecord('dbxref');
  2064. $dbxref->setValues([
  2065. 'db_id' => $db_id,
  2066. 'accession' => $accession,
  2067. ]);
  2068. if (!$dbxref->find()) {
  2069. $dbxref->insert();
  2070. }
  2071. // Now add the cvterm_dbxref record.
  2072. $cvterm_dbxref = new ChadoRecord('cvterm_dbxref');
  2073. $cvterm_dbxref->setValues([
  2074. 'cvterm_id' => $cvterm_id,
  2075. 'dbxref_id' => $dbxref->getID(),
  2076. ]);
  2077. if (!$cvterm_dbxref->find()) {
  2078. $cvterm_dbxref->insert();
  2079. }
  2080. }
  2081. /**
  2082. * Adds a database reference to a cvterm
  2083. *
  2084. * @param $cvterm_id
  2085. * The cvterm_id of the term to which the synonym will be added.
  2086. * @param xref
  2087. * The cross reference. It should be of the form from the OBO specification
  2088. *
  2089. * @ingroup tripal_obo_loader
  2090. */
  2091. private function addXref($id, $cvterm_id, $xref) {
  2092. $dbname = preg_replace('/^(.+?):.*$/', '$1', $xref);
  2093. $accession = preg_replace('/^.+?:\s*(.*?)(\{.+$|\[.+$|\s.+$|\".+$|$)/', '$1', $xref);
  2094. $description = preg_replace('/^.+?\"(.+?)\".*?$/', '$1', $xref);
  2095. $dbxrefs = preg_replace('/^.+?\[(.+?)\].*?$/', '$1', $xref);
  2096. if (!$accession) {
  2097. throw new Exception("Cannot add an xref without an accession: '$xref'");
  2098. }
  2099. // If the xref is a database link then skip those for now.
  2100. if (strcmp($dbname, 'http') == 0) {
  2101. return;
  2102. }
  2103. // Add the database if it doesn't exist.
  2104. $db = $this->addDB($dbname);
  2105. $db_id = $db->db_id;
  2106. // Now add the dbxref if it doesn't already exist
  2107. $dbxref = new ChadoRecord('dbxref');
  2108. $dbxref->setValues([
  2109. 'db_id' => $db_id,
  2110. 'accession' => $accession,
  2111. ]);
  2112. if (!$dbxref->find()) {
  2113. $dbxref->insert();
  2114. }
  2115. // Now add the cvterm_dbxref record.
  2116. $cvterm_dbxref = new ChadoRecord('cvterm_dbxref');
  2117. $cvterm_dbxref->setValues([
  2118. 'cvterm_id' => $cvterm_id,
  2119. 'dbxref_id' => $dbxref->getID(),
  2120. ]);
  2121. if (!$cvterm_dbxref->find()) {
  2122. $cvterm_dbxref->insert();
  2123. }
  2124. }
  2125. /**
  2126. * Adds a comment to a cvterm.
  2127. *
  2128. * @param $cvterm_id
  2129. * A cvterm_id of the term to which properties will be added
  2130. * @param $comment
  2131. * The comment to add to the cvterm.
  2132. * @param rank
  2133. * The rank of the comment
  2134. *
  2135. * @ingroup tripal_obo_loader
  2136. */
  2137. private function addComment($id, $cvterm_id, $comment, $rank) {
  2138. // Get the comment type id.
  2139. $comment_type_id = $this->used_terms['rdfs:comment'];
  2140. // Add the comment as a property of the cvterm.
  2141. $cvtermprop = new ChadoRecord('cvtermprop');
  2142. $cvtermprop->setValues([
  2143. 'cvterm_id' => $cvterm_id,
  2144. 'type_id' => $comment_type_id,
  2145. 'value' => $comment,
  2146. 'rank' => $rank,
  2147. ]);
  2148. // If the insert fails then catch the error and generate a more meaningful
  2149. // message that helps with debugging.
  2150. try {
  2151. $cvtermprop->insert();
  2152. } catch (Exception $e) {
  2153. throw new Exception(t('Cannot add comment, "!comment" to term: !id. ' .
  2154. 'ERROR: !error.',
  2155. ['!comment' => $comment, '!id' => $id, '!error' => $e->getMessage()]));
  2156. }
  2157. }
  2158. /**
  2159. * API call to Ontology Lookup Service provided by
  2160. * https://www.ebi.ac.uk/ols/docs/api#resources-terms
  2161. *
  2162. * @param accession
  2163. * Accession term for query
  2164. * @param type_of_search
  2165. * Either ontology, term, query, or query-non-local
  2166. *
  2167. * @ingroup tripal_obo_loader
  2168. */
  2169. private function oboEbiLookup($accession, $type_of_search) {
  2170. //Grab just the ontology from the $accession.
  2171. $parts = explode(':', $accession);
  2172. $ontology = strtolower($parts[0]);
  2173. $ontology = preg_replace('/\s+/', '', $ontology);
  2174. if ($type_of_search == 'ontology') {
  2175. $options = [];
  2176. $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontology;
  2177. $response = drupal_http_request($full_url, $options);
  2178. if (!empty($response)) {
  2179. $response = drupal_json_decode($response->data);
  2180. }
  2181. }
  2182. elseif ($type_of_search == 'term') {
  2183. //The IRI of the terms, this value must be double URL encoded
  2184. $iri = urlencode(urlencode("http://purl.obolibrary.org/obo/" . str_replace(':', '_', $accession)));
  2185. $options = [];
  2186. $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontology . '/' . 'terms/' . $iri;
  2187. $response = drupal_http_request($full_url, $options);
  2188. if (!empty($response)) {
  2189. $response = drupal_json_decode($response->data);
  2190. }
  2191. }
  2192. elseif ($type_of_search == 'query') {
  2193. $options = [];
  2194. $full_url = 'http://www.ebi.ac.uk/ols/api/search?q=' . $accession . '&queryFields=obo_id&local=true';
  2195. $response = drupal_http_request($full_url, $options);
  2196. if (!empty($response)) {
  2197. $response = drupal_json_decode($response->data);
  2198. }
  2199. }
  2200. elseif ($type_of_search == 'query-non-local') {
  2201. $options = [];
  2202. $full_url = 'http://www.ebi.ac.uk/ols/api/search?q=' . $accession . '&queryFields=obo_id';
  2203. $response = drupal_http_request($full_url, $options);
  2204. if (!empty($response)) {
  2205. $response = drupal_json_decode($response->data);
  2206. }
  2207. }
  2208. return $response;
  2209. }
  2210. }
  2211. /**
  2212. * Ajax callback for the OBOImporter::form() function.
  2213. */
  2214. function tripal_cv_obo_form_ajax_callback($form, $form_state) {
  2215. return $form['obo_existing'];
  2216. }