OBOImporter.inc 71 KB

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