OBOImporter.inc 73 KB

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