OBOImporter.inc 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078
  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 an exhaustive search of EBI to find it if we don't alread have it in
  716. // chado.
  717. if ($namespace and !$short_name) {
  718. $sql = "SELECT dbname FROM {db2cv_mview} WHERE cvname = :cvname";
  719. $short_name = chado_query($sql, [':cvname' => $namespace])->fetchField();
  720. if (!$short_name) {
  721. $short_name = $this->findEBIOntologyPrefix($namespace);
  722. }
  723. }
  724. // If we can't find the namespace or the short_name then bust.
  725. if (!$namespace and !$short_name) {
  726. throw new ErrorException('Cannot determine the namespace or ontology prefix from this OBO file. It is missing both the "default-namespace" and "ontology" headers.');
  727. }
  728. // Set the defaults.
  729. $this->default_namespace = $namespace;
  730. $this->default_db = $short_name;
  731. $this->addDB($this->default_db);
  732. $this->addCV($this->default_namespace);
  733. }
  734. /**
  735. * This function searches EBI to find the ontology details for this OBO.
  736. *
  737. * @param $ontology
  738. * The ontology name from the OBO headers.
  739. *
  740. * @throws Exception
  741. */
  742. private function findEBIOntologyNamespace($ontology) {
  743. // Check if the EBI ontology search has this ontology:
  744. try {
  745. $results = $this->oboEbiLookup($ontology, 'ontology');
  746. if (array_key_exists('default-namespace', $results['config']['annotations'])) {
  747. $namespace = $results['config']['annotations']['default-namespace'];
  748. if (is_array($namespace)) {
  749. $namespace = $namespace[0];
  750. }
  751. }
  752. elseif (array_key_exists('namespace', $results['config'])) {
  753. $namespace = $results['config']['namespace'];
  754. }
  755. // If we can't find the namespace at EBI, then just default to using the
  756. // same namespace as the DB short name.
  757. else {
  758. $namespace = $this->default_db;
  759. }
  760. return $namespace;
  761. }
  762. catch (Exception $e) {
  763. watchdog_exception('Cannot find the namespace for this ontology.', $e);
  764. throw $e;
  765. }
  766. }
  767. /**
  768. * Finds the ontology prefix (DB short name) using EBI.
  769. *
  770. * @param $namespace
  771. * The namespace for ontology.
  772. */
  773. private function findEBIOntologyPrefix($namespace) {
  774. $options = array();
  775. $page = 1;
  776. $size = 25;
  777. $full_url = 'https://www.ebi.ac.uk/ols/api/ontologies?page=' . $page. '&size=' . $size;
  778. while ($response = drupal_http_request($full_url, $options)) {
  779. $response = drupal_json_decode($response->data);
  780. $page++;
  781. $full_url = 'https://www.ebi.ac.uk/ols/api/ontologies?page=' . $page. '&size=' . $size;
  782. }
  783. }
  784. /**
  785. * A helper function to get details about a foreign term.
  786. *
  787. * A foreign term is one that does not belong to the ontology.
  788. *
  789. * @param $t
  790. * A term array that contains these keys at a minimum: id, name,
  791. * definition, subset, namespace, is_obsolete.
  792. */
  793. private function findEBITerm($id) {
  794. // Get the short name and accession for the term.
  795. $pair = explode(":", $id, 2);
  796. $short_name = $pair[0];
  797. $accession_num = $pair[1];
  798. // Check for the ID of the term in EBI.
  799. $oterm = NULL;
  800. $results = $this->oboEbiLookup($id, 'term');
  801. if (isset($results['label'])) {
  802. $oterm = $results;
  803. }
  804. // If we did not get a name for the term from a direct term
  805. // lookup then let's try a query.
  806. if (!isset($results['label'])) {
  807. $results = $this->oboEbiLookup($id, 'query');
  808. if (array_key_exists('docs', $results)) {
  809. if (!empty($results['response']['docs'])) {
  810. if (count($results['response']['docs']) > 1) {
  811. foreach ($results['response']['docs'] as $doc) {
  812. if ($doc['obo_id'] == $t['id']) {
  813. $external = TRUE;
  814. $oterm = $doc;
  815. }
  816. }
  817. }
  818. else {
  819. $external = true;
  820. $oterm = $results['response']['docs'][0];
  821. }
  822. }
  823. }
  824. }
  825. // If the accession could not be found in EBI.
  826. if ($results['response']['numFound'] == 0 && !isset($results['label'])) {
  827. // The first search doesn't work, so let's try a broader one.
  828. $results = $this->oboEbiLookup($t['id'], 'query-non-local');
  829. if (!empty($results)) {
  830. if (array_key_exists('docs', $results)) {
  831. if (!empty($results['docs'])) {
  832. $accession = $t['id'];
  833. $accession_underscore = str_replace(":", "_", $accession);
  834. foreach ($results['response']['docs'] as $item) {
  835. if ($item['label'] != $accession && $item['label'] != $accession_underscore) {
  836. // Found the first place a label is other than the accession
  837. // is used, so take that info and then end the loop.
  838. $external = TRUE;
  839. $oterm = $item;
  840. break;
  841. }
  842. }
  843. }
  844. }
  845. }
  846. }
  847. // If we found a term then return it.
  848. if ($oterm) {
  849. // Make an OBO stanza array as if this term were in the OBO file and
  850. // return it.
  851. $stanza = [];
  852. $stanza['id'][] = $oterm['label'];
  853. $stanza['name'][] = $oterm['label'];
  854. $stanza['def'][] = $oterm['def'];
  855. $stanza['namespace'][] = $oterm['ontology_name'];
  856. $stanza['is_obsolete'][] = $oterm['is_obsolete'];
  857. $stanza['subset'][] = $oterm['subset'];
  858. $stanza['db_name'][] = $short_name;
  859. return $stanza;
  860. }
  861. return FALSE;
  862. }
  863. /**
  864. * Inserts a new cvterm using the OBO stanza array provided.
  865. *
  866. * The stanza passed to this function should always come from the term cache,
  867. * not directly from the OBO file because the cached terms have been
  868. * updated to include all necessary values. This function also removes
  869. * all properties assocaited with the term so that those can be added
  870. * fresh.
  871. *
  872. * @param $stanza
  873. * An OBO stanza array as returned by getCachedTermStanza().
  874. * @param $is_relationship
  875. * Set to TRUE if this term is a relationship term.
  876. * @param $update_if_exists
  877. * Set to TRUE to update the term if it exists.
  878. *
  879. * @return
  880. * The cvterm ID.
  881. */
  882. private function saveTerm($stanza, $is_relationship = FALSE) {
  883. // Get the term ID.
  884. $id = $stanza['id'][0];
  885. // First check if we've already used this term.
  886. if ($this->used_terms[$id]) {
  887. return $this->used_terms[$id];
  888. }
  889. // Get the term properties.
  890. $id = $stanza['id'][0];
  891. $name = $stanza['name'][0];
  892. $cvname = $stanza['namespace'][0];
  893. $dbname = $stanza['db_name'][0];
  894. $namespace = $stanza['namespace'][0];
  895. // Does this term ID have both a short name and accession? If so, then
  896. // separate out these components, otherwise we will use the id as both
  897. // the id and accession.
  898. $accession = '';
  899. $matches = [];
  900. if (preg_match('/^(.+?):(.*)$/', $id, $matches)) {
  901. $accession = $matches[2];
  902. }
  903. else {
  904. $accession = $id;
  905. }
  906. // Get the definition if there is on.
  907. $definition = '';
  908. if (array_key_exists('definition', $stanza)) {
  909. $definition = preg_replace('/^\"(.*)\"/', '\1', $stanza['def'][0]);
  910. }
  911. // Set the flag if this term is obsolete.
  912. $is_obsolete = 0;
  913. if (array_key_exists('is_obsolete', $stanza)) {
  914. $is_obsolete = $stanza['is_obsolete'][0] == TRUE ? 1 : 0;
  915. }
  916. // Is this term borrowed from another ontology? We can find out by checking
  917. // if the namespace belongs to the list of known namespaces provided by this
  918. // OBO. If not, then it's borrowed.
  919. $is_borrowed = FALSE;
  920. if (!array_key_exists($namespace, $this->obo_namespaces)) {
  921. $is_borrowed = TRUE;
  922. }
  923. // The cvterm ChadoRecord object.
  924. $cvterm = NULL;
  925. // Get the CV and DB objects.
  926. $cv = $this->all_cvs[$cvname];
  927. $db = $this->all_dbs[$dbname];
  928. // If this is set to TRUE then we should insert the term.
  929. $do_cvterm_insert = FALSE;
  930. // We need to locate terms using their dbxref. This is because term names
  931. // can sometimes change, so we don't want to look up the term by it's name.
  932. // the unique ID which is in the accession will never change.
  933. $dbxref = new ChadoRecord('dbxref');
  934. $dbxref->setValues([
  935. 'db_id' => $db->db_id,
  936. 'accession' => $accession
  937. ]);
  938. if ($dbxref->find()) {
  939. // Now see if there is a cvterm for this dbxref. A dbxref can only be
  940. // used one time. If so, then update the term, but only if this term
  941. // belongs to namespace created by this OBO. We don't want to update
  942. // terms from other OBOs that may be borrowed by this one.
  943. $cvterm = new ChadoRecord('cvterm');
  944. $cvterm->setValues(['dbxref_id' => $dbxref->getID()]);
  945. if ($cvterm->find()) {
  946. if (!$is_borrowed) {
  947. $cvterm->setValue('name', $name);
  948. $cvterm->setValue('definition', $definition);
  949. $cvterm->setValue('is_obsolete', $is_obsolete);
  950. $cvterm->update();
  951. }
  952. }
  953. else {
  954. $do_cvterm_insert = TRUE;
  955. }
  956. }
  957. else {
  958. // The dbxref doesn't exist, so let's add it.
  959. $dbxref->insert();
  960. $do_cvterm_insert = TRUE;
  961. }
  962. if ($do_cvterm_insert) {
  963. // Before inserting the term let's check to see if it already exists. The
  964. // cvterm table has two unique constraints, one on the dbxref and another
  965. // on the name, cv_id and is_obsolete columns. If for some reason the
  966. // term exists but is assocaited with a different dbxref we'll have
  967. // a problem. Because the is_obsolete may be set this time, but the
  968. // term may not have it set from a previous load we will check for the
  969. // presence of the term without the is_obsolete.
  970. $cvterm = new ChadoRecord('cvterm');
  971. $cvterm->setValues([
  972. 'cv_id' => $cv->cv_id,
  973. 'name' => $name,
  974. ]);
  975. if ($cvterm->find()) {
  976. // We found the term so do an update and change the dbxref_id.
  977. if (!$is_borrowed) {
  978. // This is a borrowed term so just update the dbxref_id.
  979. $cvterm->setValue('dbxref_id', $dbxref->getID());
  980. $cvterm->update();
  981. }
  982. else {
  983. $cvterm->setValue('definition', $definition);
  984. $cvterm->setValue('dbxref_id', $dbxref->getID());
  985. $cvterm->setValue('is_obsolete', $is_obsolete);
  986. $cvterm->update();
  987. }
  988. }
  989. else {
  990. // The term doesnt exist, so let's just do our insert.
  991. $cvterm->setValues([
  992. 'cv_id' => $cv->cv_id,
  993. 'name' => $name,
  994. 'definition' => $definition,
  995. 'dbxref_id' => $dbxref->getID(),
  996. 'is_relationshiptype' => $is_relationship,
  997. 'is_obsolete' => $is_obsolete,
  998. ]);
  999. $cvterm->insert();
  1000. }
  1001. }
  1002. // Save the cvterm_id for this term so we don't look it up again.
  1003. $cvterm_id = $cvterm->getID();
  1004. $this->used_terms[$id] = $cvterm_id;
  1005. // Return the cvterm_id.
  1006. return $cvterm_id;
  1007. }
  1008. /**
  1009. * Uses the provided term array to add/update information to Chado about the
  1010. * term including the term, dbxref, synonyms, properties, and relationships.
  1011. *
  1012. * @param $term
  1013. * An array representing the cvterm.
  1014. * @is_relationship
  1015. * Set to 1 if this term is a relationship term
  1016. *
  1017. * @ingroup tripal_obo_loader
  1018. */
  1019. private function processTerm($stanza, $is_relationship = 0) {
  1020. //
  1021. // First things first--save the term.
  1022. //
  1023. $cvterm_id = $this->saveTerm($stanza, FALSE);
  1024. // If this term is borrowed from another ontology, then we do not want
  1025. // to do any further processing. We only want to process terms that
  1026. // belong to this one.
  1027. $namespace = $stanza['namespace'][0];
  1028. if (!array_key_exists($namespace, $this->obo_namespaces)) {
  1029. return;
  1030. }
  1031. // If this term belongs to this OBO (not borrowed from another OBO) then
  1032. // remove any relationships, properties, xrefs, and synonyms that this
  1033. // term alreadyn has so that they can be re-added.
  1034. $sql = "
  1035. DELETE FROM {cvterm_relationship}
  1036. WHERE subject_id = :cvterm_id
  1037. ";
  1038. chado_query($sql, array(':cvterm_id' => $cvterm_id));
  1039. $sql = "
  1040. DELETE FROM {cvtermprop}
  1041. WHERE cvterm_id = :cvterm_id
  1042. ";
  1043. chado_query($sql, array(':cvterm_id' => $cvterm_id));
  1044. $sql = "
  1045. DELETE FROM {cvterm_dbxref}
  1046. WHERE cvterm_id = :cvterm_id
  1047. ";
  1048. chado_query($sql, array(':cvterm_id' => $cvterm_id));
  1049. $sql = "
  1050. DELETE FROM {cvtermsynonym} CVTSYN
  1051. WHERE cvterm_id = :cvterm_id
  1052. ";
  1053. chado_query($sql, array(':cvterm_id' => $cvterm_id));
  1054. // We should never have the problem where we don't have a cvterm_id. The
  1055. // saveTerm() function should always return on. But if for some unkonwn
  1056. // reason we don't have one then fail.
  1057. if (!$cvterm_id) {
  1058. throw new Exception(t('Missing cvterm after saving term: !term',
  1059. ['!term' => print_r($stanza, TRUE)]));
  1060. }
  1061. //
  1062. // Handle: alt_id
  1063. //
  1064. if (array_key_exists('alt_id', $stanza)) {
  1065. foreach ($stanza['alt_id'] as $alt_id) {
  1066. $this->addAltID($cvterm_id, $alt_id);
  1067. }
  1068. }
  1069. //
  1070. // Handle: synonym
  1071. //
  1072. if (array_key_exists('synonym', $stanza)) {
  1073. foreach ($stanza['synonym'] as $synonym) {
  1074. $this->addSynonym($cvterm_id, $synonym);
  1075. }
  1076. }
  1077. //
  1078. // Handle: exact_synonym
  1079. //
  1080. if (array_key_exists('exact_synonym', $stanza)) {
  1081. foreach ($stanza['exact_synonym'] as $synonym) {
  1082. $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 EXACT $2', $synonym);
  1083. $this->addSynonym($cvterm_id, $fixed);
  1084. }
  1085. }
  1086. //
  1087. // Handle: narrow_synonym
  1088. //
  1089. if (array_key_exists('narrow_synonym', $stanza)) {
  1090. foreach ($stanza['narrow_synonym'] as $synonym) {
  1091. $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 NARROW $2', $synonym);
  1092. $this->addSynonym($cvterm_id, $fixed);
  1093. }
  1094. }
  1095. //
  1096. // Handle: broad_synonym
  1097. //
  1098. if (array_key_exists('broad_synonym', $stanza)) {
  1099. foreach ($stanza['broad_synonym'] as $synonym) {
  1100. $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 BROAD $2', $synonym);
  1101. $this->addSynonym($cvterm_id, $fixed);
  1102. }
  1103. }
  1104. //
  1105. // Handle: comment
  1106. //
  1107. if (array_key_exists('comment', $stanza)) {
  1108. $comments = $stanza['comment'];
  1109. foreach ($comments as $rank => $comment) {
  1110. $this->addComment($cvterm_id, $comment, $rank);
  1111. }
  1112. }
  1113. //
  1114. // Handle: xref
  1115. //
  1116. if (array_key_exists('xref', $stanza)) {
  1117. foreach ($stanza['xref'] as $xref) {
  1118. $this->addXref($cvterm_id, $xref);
  1119. }
  1120. }
  1121. //
  1122. // Handle: xref_analog
  1123. //
  1124. if (array_key_exists('xref_analog', $stanza)) {
  1125. foreach ($stanza['xref_analog'] as $xref) {
  1126. $this->addXref($cvterm_id, $xref);
  1127. }
  1128. }
  1129. //
  1130. // Handle: xref_unk
  1131. //
  1132. if (array_key_exists('xref_unk', $stanza)) {
  1133. foreach ($stanza['xref_unk'] as $xref) {
  1134. $this->addXref($cvterm_id, $xref);
  1135. }
  1136. }
  1137. //
  1138. // Handle: subset
  1139. //
  1140. if (array_key_exists('subset', $stanza)) {
  1141. foreach ($stanza['subset'] as $subset) {
  1142. $this->addSubset($cvterm_id, $subset);
  1143. }
  1144. }
  1145. //
  1146. // Handle: is_a
  1147. //
  1148. if (array_key_exists('is_a', $stanza)) {
  1149. foreach ($stanza['is_a'] as $is_a) {
  1150. $this->addRelationship($cvterm_id, 'is_a', $is_a);
  1151. }
  1152. }
  1153. //
  1154. // Handle: relationship
  1155. //
  1156. if (array_key_exists('relationship', $stanza)) {
  1157. foreach ($stanza['relationship'] as $value) {
  1158. $rel = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
  1159. $object = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
  1160. $this->addRelationship($cvterm_id, $rel, $object);
  1161. }
  1162. }
  1163. /**
  1164. * The following properties are currently unsupported:
  1165. *
  1166. * - intersection_of
  1167. * - union_of
  1168. * - disjoint_from
  1169. * - replaced_by
  1170. * - consider
  1171. * - use_term
  1172. * - builtin
  1173. * - is_anonymous
  1174. *
  1175. */
  1176. }
  1177. /**
  1178. * Adds a cvterm relationship
  1179. *
  1180. * @param $cvterm_id
  1181. * A cvterm_id of the term to which the relationship will be added.
  1182. * @param $rel_id
  1183. * The relationship term ID
  1184. * @param $obj_id
  1185. * The relationship object term ID.
  1186. *
  1187. * @ingroup tripal_obo_loader
  1188. */
  1189. private function addRelationship($cvterm_id, $rel_id, $obj_id) {
  1190. // Get the cached terms for both the relationship and the object. They
  1191. // shold be there, but just in case something went wrong, we'll throw
  1192. // an exception if we can't find them.
  1193. $rel_stanza = $this->getCachedTermStanza($rel_id);
  1194. if (!$rel_stanza) {
  1195. throw new Exception(t('Cannot find term, "!name", in the term cache.', ['!name' => $rel_id]));
  1196. }
  1197. $rel_cvterm_id = $this->saveTerm($rel_stanza, TRUE);
  1198. // Make sure the object term exists in the cache.
  1199. $obj_stanza = $this->getCachedTermStanza($obj_id);
  1200. if (!$obj_stanza) {
  1201. throw new Exception(t('Cannot find term "!name" in the term cache.', ['!name' => $obj_id]));
  1202. }
  1203. $obj_cvterm_id = $this->saveTerm($obj_stanza);
  1204. // Add the cvterm_relationship.
  1205. $cvterm_relationship = new ChadoRecord('cvterm_relationship');
  1206. $cvterm_relationship->setValues([
  1207. 'type_id' => $rel_cvterm_id,
  1208. 'subject_id' => $cvterm_id,
  1209. 'object_id' => $obj_cvterm_id
  1210. ]);
  1211. $cvterm_relationship->insert();
  1212. return TRUE;
  1213. }
  1214. /**
  1215. * Retrieves the term array from the temp loading table for a given term id.
  1216. *
  1217. * @param id
  1218. * The id of the term to retrieve
  1219. *
  1220. * @ingroup tripal_obo_loader
  1221. */
  1222. private function getCachedTermStanza($id) {
  1223. if ($this->cache_type == 'table') {
  1224. $values = array('id' => $id);
  1225. $result = chado_select_record('tripal_obo_temp', array('stanza'), $values);
  1226. if (count($result) == 0) {
  1227. return FALSE;
  1228. }
  1229. return unserialize(base64_decode($result['stanza']));
  1230. }
  1231. if (array_key_exists($id, $this->termStanzaCache['ids'])) {
  1232. return $this->termStanzaCache['ids'][$id];
  1233. }
  1234. else {
  1235. return FALSE;
  1236. }
  1237. }
  1238. /**
  1239. * Adds a term stanza from the OBO file to the cache for easier lookup.
  1240. *
  1241. * @param $stanza
  1242. * The stanza from the OBO file for the term.
  1243. * @throws Exception
  1244. */
  1245. private function addCacheTermStanza($stanza, $type) {
  1246. // Make sure we have defaults.
  1247. if (!$this->default_namespace) {
  1248. throw new Exception('Cannot cache terms without a default CV.' . print_r($stanza, TRUE));
  1249. }
  1250. if (!$this->default_db) {
  1251. throw new Exception('Cannot cache terms without a default DB.' . print_r($stanza, TRUE));
  1252. }
  1253. $id = $stanza['id'][0];
  1254. // First check if this term is already in the cache, if so then skip it.
  1255. if ($this->getCachedTermStanza($id)) {
  1256. return;
  1257. }
  1258. // Does this term have a database short name prefix in the ID (accession)?
  1259. // If not then we'll add the default CV as the namespace. If it does and
  1260. // the short name is not the default for this vocabulary then we'll look
  1261. // it up.
  1262. $matches = [];
  1263. if (preg_match('/^(.+):(.+)$/', $id, $matches)) {
  1264. $short_name = $matches[1];
  1265. $accession = $matches[2];
  1266. // If the DB short name and the default DB short name don't match then
  1267. // let's do a lookup on EBI to get the term details.
  1268. if ($short_name != $this->default_db) {
  1269. if ($this->ebi_warned == FALSE) {
  1270. $this->logMessage(
  1271. "A term that belongs to another ontology is used within this " .
  1272. "vocabulary. Therefore a lookup will be performed with the EBI Ontology " .
  1273. "Lookup Service to retrieve the information for this term. " .
  1274. "Please note, that vocabularies with many non-local terms " .
  1275. "require remote lookups and these lookups can dramatically " .
  1276. "decrease loading time. " ,
  1277. ['!vocab' => $this->default_namespace], TRIPAL_WARNING);
  1278. $this->ebi_warned = TRUE;
  1279. // This ontology may havem ultiple remote terms and that takes a while
  1280. // to load so lets change the progress interval down to give
  1281. // updates more often.
  1282. $this->setInterval(1);
  1283. }
  1284. // If we found a term then let's create a new stanza as if it existed
  1285. // in the original OBO file but with all the necessary details.
  1286. $oterm = $this->findEBITerm($id);
  1287. if ($oterm) {
  1288. $stanza = $oterm;
  1289. }
  1290. else {
  1291. throw new Exception(t('Cannot find the term defined in the ontology or via an EBI OLS lookup: !term',
  1292. ['!term' => $id]));
  1293. }
  1294. }
  1295. // If the term belongs to this OBO then let's set the 'db_name'.
  1296. else {
  1297. if (!array_key_exists('namespace', $stanza)) {
  1298. $stanza['namespace'][] = $this->default_namespace;
  1299. }
  1300. $stanza['db_name'][] = $short_name;
  1301. }
  1302. }
  1303. // If there is no DB short name prefix for the id.
  1304. else {
  1305. if (!array_key_exists('namespace', $stanza)) {
  1306. $stanza['namespace'][] = $this->default_namespace;
  1307. }
  1308. $stanza['db_name'][] = $this->default_db;
  1309. }
  1310. if ($this->cache_type == 'table') {
  1311. // Add the term to the temp table.
  1312. $values = [
  1313. 'id' => $id,
  1314. 'stanza' => base64_encode(serialize($stanza)),
  1315. 'type' => $type,
  1316. ];
  1317. $success = chado_insert_record('tripal_obo_temp', $values);
  1318. if (!$success) {
  1319. throw new Exception("Cannot insert stanza into temporary table.");
  1320. }
  1321. return;
  1322. }
  1323. $this->termStanzaCache['ids'][$id] = $stanza;
  1324. $this->termStanzaCache['count'][$type]++;
  1325. $this->termStanzaCache['types'][$type][] = $id;
  1326. }
  1327. /**
  1328. * Returns the size of a given term type from the cache.
  1329. * @param $type
  1330. * The term type: Typedef, Term, etc.
  1331. */
  1332. private function getCacheSize($type) {
  1333. if ($this->cache_type == 'table') {
  1334. $sql = "
  1335. SELECT count(*) as num_terms
  1336. FROM {tripal_obo_temp}
  1337. WHERE type = :type
  1338. ";
  1339. $result = chado_query($sql, [':type' => $type])->fetchObject();
  1340. return $result->num_terms;
  1341. }
  1342. return $this->termStanzaCache['count'][$type];
  1343. }
  1344. /**
  1345. * Retrieves all term IDs for a given type.
  1346. *
  1347. * If the cache is using the tripal_obo_temp table then it
  1348. * returns an iterable Database handle.
  1349. */
  1350. private function getCachedTermStanzas($type) {
  1351. if ($this->cache_type == 'table') {
  1352. $sql = "SELECT id FROM {tripal_obo_temp} WHERE type = 'Typedef' ";
  1353. $typedefs = chado_query($sql);
  1354. return $typdefs;
  1355. }
  1356. return $this->termStanzaCache['types'][$type];
  1357. }
  1358. /**
  1359. * Clear's the term cache.
  1360. */
  1361. private function clearTermStanzaCache() {
  1362. if ($this->cache_type == 'table') {
  1363. $sql = "DELETE FROM {tripal_obo_temp}";
  1364. chado_query($sql);
  1365. return;
  1366. }
  1367. $this->termStanzaCache = [
  1368. 'ids' => [],
  1369. 'count' => [
  1370. 'Typedef' => 0,
  1371. 'Term' => 0,
  1372. 'Instance' => 0,
  1373. ],
  1374. 'types' => [
  1375. 'Typedef' => [],
  1376. 'Term' => [],
  1377. 'Instance' => [],
  1378. ],
  1379. ];
  1380. }
  1381. /**
  1382. * Adds the synonyms to a term
  1383. *
  1384. * @param $cvterm_id
  1385. * The cvterm_id of the term to which the synonym will be added.
  1386. * @param $synonym
  1387. * The value of the 'synonym' line of the term stanza.
  1388. *
  1389. * @ingroup tripal_obo_loader
  1390. */
  1391. private function addSynonym($cvterm_id, $synonym) {
  1392. $def = $synonym;
  1393. $syn_type = '';
  1394. // Separate out the synonym definition and type (e.g. EXACT).
  1395. $matches = [];
  1396. if (preg_match('/^\s*"(.*)"\s+(.*?)\s+.*$/', $synonym, $matches)) {
  1397. $def = $matches[1];
  1398. $syn_type = $matches[2];
  1399. }
  1400. // Get the syn type cvterm.
  1401. if (!$syn_type) {
  1402. $syn_type = 'exact';
  1403. }
  1404. $syn_type = $this->syn_types[$syn_type];
  1405. // Now save the new synonym.
  1406. $cvtermsynonym = new ChadoRecord('cvtermsynonym');
  1407. $cvtermsynonym->setValues([
  1408. 'cvterm_id' => $cvterm_id,
  1409. 'synonym' => $def,
  1410. 'type_id' => $syn_type->cvterm_id
  1411. ]);
  1412. $cvtermsynonym->insert();
  1413. }
  1414. /**
  1415. * Parse the OBO file and populate the templ loading table
  1416. *
  1417. * @param $file
  1418. * The path on the file system where the ontology can be found
  1419. * @param $header
  1420. * An array passed by reference that will be populated with the header
  1421. * information from the OBO file
  1422. *
  1423. * @ingroup tripal_obo_loader
  1424. */
  1425. private function parse($obo_file, &$header) {
  1426. // Set to 1 if we are in the top header lines of the file.
  1427. $in_header = TRUE;
  1428. // Holds the full stanza for the term.
  1429. $stanza = array();
  1430. // Holds the default database for the term.
  1431. $db_short_name = '';
  1432. $line_num = 0;
  1433. $num_read = 0;
  1434. // The type of term: Typedef or Term (inside the [] brackets]
  1435. $type = '';
  1436. $filesize = filesize($obo_file);
  1437. $this->setTotalItems($filesize);
  1438. $this->setItemsHandled(0);
  1439. $this->setInterval(5);
  1440. // iterate through the lines in the OBO file and parse the stanzas
  1441. $fh = fopen($obo_file, 'r');
  1442. while ($line = fgets($fh)) {
  1443. $line_num++;
  1444. $size = drupal_strlen($line);
  1445. $num_read += $size;
  1446. $line = trim($line);
  1447. $this->setItemsHandled($num_read);
  1448. // remove newlines
  1449. $line = rtrim($line);
  1450. // remove any special characters that may be hiding
  1451. $line = preg_replace('/[^(\x20-\x7F)]*/', '', $line);
  1452. // skip empty lines
  1453. if (strcmp($line, '') == 0) {
  1454. continue;
  1455. }
  1456. // Remove comments from end of lines.
  1457. $line = preg_replace('/^(.*?)\!.*$/', '\1', $line);
  1458. // At the first stanza we're out of header.
  1459. if (preg_match('/^\s*\[/', $line)) {
  1460. // After parsing the header we need to get information about this OBO.
  1461. if ($in_header == TRUE) {
  1462. $this->setDefaults($header);
  1463. $in_header = FALSE;
  1464. }
  1465. // Store the stanza we just finished reading.
  1466. if (sizeof($stanza) > 0) {
  1467. // If this term has a namespace then we want to keep track of it.
  1468. if (array_key_exists('namespace', $stanza)) {
  1469. $namespace = $stanza['namespace'][0];
  1470. $cv = $this->all_cvs[$namespace];
  1471. $this->obo_namespaces[$namespace] = $cv->cv_id;
  1472. }
  1473. $this->addCacheTermStanza($stanza, $type);
  1474. }
  1475. // Get the stanza type: Term, Typedef or Instance
  1476. $type = preg_replace('/^\s*\[\s*(.+?)\s*\]\s*$/', '\1', $line);
  1477. // start fresh with a new array
  1478. $stanza = array();
  1479. continue;
  1480. }
  1481. // break apart the line into the tag and value but ignore any escaped colons
  1482. preg_replace("/\\:/", "|-|-|", $line); // temporarily replace escaped colons
  1483. $pair = explode(":", $line, 2);
  1484. $tag = $pair[0];
  1485. $value = ltrim(rtrim($pair[1]));// remove surrounding spaces
  1486. // if this is the ID line then get the database short name from the ID.
  1487. $matches = array();
  1488. if ($tag == 'id' and preg_match('/^(.+?):.*$/', $value, $matches)) {
  1489. $db_short_name = $matches[1];
  1490. }
  1491. $tag = preg_replace("/\|-\|-\|/", "\:", $tag); // return the escaped colon
  1492. $value = preg_replace("/\|-\|-\|/", "\:", $value);
  1493. if ($in_header) {
  1494. if (!array_key_exists($tag, $header)) {
  1495. $header[$tag] = array();
  1496. }
  1497. $header[$tag][] = $value;
  1498. }
  1499. else {
  1500. if (!array_key_exists($tag, $stanza)) {
  1501. $stanza[$tag] = array();
  1502. }
  1503. $stanza[$tag][] = $value;
  1504. }
  1505. }
  1506. // now add the last term in the file
  1507. if (sizeof($stanza) > 0) {
  1508. // If this term has a namespace then we want to keep track of it.
  1509. if (array_key_exists('namespace', $stanza)) {
  1510. $namespace = $stanza['namespace'][0];
  1511. $cv = $this->all_cvs[$namespace];
  1512. $this->obo_namespaces[$namespace] = $cv->cv_id;
  1513. }
  1514. $this->addCacheTermStanza($stanza, $type);
  1515. $this->setItemsHandled($num_read);
  1516. }
  1517. $message = t('Found the following namespaces: !namespaces.',
  1518. ['!namespaces' => implode(', ', array_keys($this->obo_namespaces))]);
  1519. $this->logMessage($message);
  1520. }
  1521. /**
  1522. * Iterates through all of the cached terms and caches any relationships
  1523. */
  1524. private function cacheRelationships() {
  1525. // Now that we have all of the terms parsed and loaded into the cache,
  1526. // lets run through them one more time cache any terms in relationships
  1527. // as well.
  1528. $terms = $this->getCachedTermStanzas('Term');
  1529. $count = $this->getCacheSize('Term');
  1530. $this->setTotalItems($count);
  1531. $this->setItemsHandled(0);
  1532. $this->setInterval(25);
  1533. // Iterate through the terms.
  1534. $i = 1;
  1535. foreach ($terms as $t) {
  1536. // TODO: it would be better if we had a term iterator so that we
  1537. // don't have to distinguish here between the table vs memory cache type.
  1538. if ($this->cache_type == 'table') {
  1539. $stanza = unserialize(base64_decode($t->stanza));
  1540. }
  1541. else {
  1542. $stanza = $this->termStanzaCache['ids'][$t];
  1543. }
  1544. // Check if this stanza has an is_a relationship that needs lookup.
  1545. if (array_key_exists('is_a', $stanza)) {
  1546. foreach ($stanza['is_a'] as $object_term) {
  1547. $rstanza = [];
  1548. $rstanza['id'][] = $object_term;
  1549. $this->addCacheTermStanza($stanza, 'Term');
  1550. }
  1551. }
  1552. // Check if this stanza has any additional relationships for lookup.
  1553. if (array_key_exists('relationship', $stanza)) {
  1554. foreach ($stanza['relationship'] as $value) {
  1555. // Get the relationship term and the object term
  1556. $rel_term = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
  1557. $object_term = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
  1558. $rstanza = [];
  1559. $rstanza['id'][] = $rel_term;
  1560. $this->addCacheTermStanza($stanza, 'Typedef');
  1561. $rstanza = [];
  1562. $rstanza['id'][] = $object_term;
  1563. $this->addCacheTermStanza($stanza, 'Term');
  1564. }
  1565. }
  1566. }
  1567. $this->setItemsHandled($i++);
  1568. // Last of all, we need to add the "is_a" relationship It's part of the
  1569. // OBO specification as a built-in relationship but not all vocabularies
  1570. // include that term.
  1571. if (!$this->getCachedTermStanza('is_a')) {
  1572. $stanza = [];
  1573. $stanza['id'][] = 'is_a';
  1574. $stanza['name'][] = 'is_a';
  1575. $stanza['namespace'][] = $this->default_namespace;
  1576. $stanza['db_name'][] = $this->default_db;
  1577. $this->addCacheTermStanza($stanza, 'Typedef');
  1578. }
  1579. }
  1580. /**
  1581. * Adds a new namespace to the database by performing an EBI Lookup.
  1582. *
  1583. * @param $namespace
  1584. */
  1585. private function addNamespace($namespace) {
  1586. // The controlled vocabulary is not in the cv table and needs to be added.
  1587. $ontology_info = $this->oboEbiLookup($namespace, 'ontology');
  1588. if (!empty($ontology_info['config'])){
  1589. // CV Name.
  1590. if (array_key_exists('namespace', $ontology_info['config'])) {
  1591. $cv_info = $ontology_info['config']['namespace'];
  1592. }
  1593. elseif (array_key_exists('default-namespace', $ontology_info['config']['annotations'])) {
  1594. $cv_info = $ontology_info['config']['annotations']['default-namespace'];
  1595. }
  1596. //CV Description.
  1597. if (array_key_exists('description', $ontology_info['config'])) {
  1598. $description = $ontology_info['config']['description'];
  1599. }
  1600. else {
  1601. $description = '';
  1602. }
  1603. $cv_returned = chado_insert_cv($cv_info, $description);
  1604. if($cv_returned) {
  1605. $this->all_cvs[$cv_returned->name] = $cv_returned;
  1606. $namespace = $cv_returned->name;
  1607. // Now add the db entry.
  1608. $values = array(
  1609. 'name' => $ontology_info['config']['preferredPrefix'],
  1610. 'description' => $ontology_info['config']['description'],
  1611. 'url' => $ontology_info['config']['versionIri'],
  1612. );
  1613. $db_returned = chado_insert_db($values);
  1614. if ($db_returned) {
  1615. $short_name = $db_returned->name;
  1616. }
  1617. return TRUE;
  1618. }
  1619. }
  1620. return FALSE;
  1621. }
  1622. /**
  1623. * Adds a property to the cvterm indicating it belongs to a subset.
  1624. * @param $cvterm_id
  1625. * The cvterm_id of the term to which the subset will be added.
  1626. * @param $subset
  1627. * The name of the subset.
  1628. */
  1629. private function addSubset($cvterm_id, $subset) {
  1630. $cvtermprop = new ChadoRecord('cvtermprop');
  1631. $cvtermprop->setValues([
  1632. 'cvterm_id' => $cvterm_id,
  1633. 'type_id' => $this->used_terms['NCIT:C25693'],
  1634. 'value' => $subset
  1635. ]);
  1636. $cvtermprop->insert();
  1637. return TRUE;
  1638. }
  1639. /**
  1640. * Adds a database to Chado if it doesn't exist.
  1641. *
  1642. * @param $dbname
  1643. * The name of the database to add.
  1644. *
  1645. * @return
  1646. * A Chado database object.
  1647. */
  1648. private function addDB($dbname) {
  1649. // Add the database if it doesn't exist.
  1650. $db = NULL;
  1651. if (array_key_exists($dbname, $this->all_dbs)) {
  1652. $db = $this->all_dbs[$dbname];
  1653. }
  1654. else {
  1655. $db = new ChadoRecord('db');
  1656. $db->setValues(['name' => $dbname]);
  1657. $db->insert();
  1658. $db = (object) $db->getValues();
  1659. $this->all_dbs[$dbname] = $db;
  1660. }
  1661. return $db;
  1662. }
  1663. /**
  1664. * Adds a vocabulary to Chado if it doesn't exist.
  1665. *
  1666. * @param $cvname
  1667. * The name of the vocabulary to add.
  1668. *
  1669. * @return
  1670. * A Chado cv object.
  1671. */
  1672. private function addCV($cvname) {
  1673. // TODO: we need to get the description and title from EBI for these
  1674. // ontology so that we can put something in the proper fields when
  1675. // adding a new CV or DB.
  1676. // Add the CV record if it doesn't exist.
  1677. $cv = new ChadoRecord('cv');
  1678. $cv->setValues(['name' => $cvname]);
  1679. if (!$cv->find()) {
  1680. $cv->insert();
  1681. }
  1682. $this->all_cvs[$cvname] = (object) $cv->getValues();
  1683. $this->obo_namespaces[$cvname] = $cv->getID();
  1684. }
  1685. /**
  1686. * Adds an alternative ID
  1687. *
  1688. * @param $cvterm_id
  1689. * The cvterm_id of the term to which the synonym will be added.
  1690. * @param $alt_id
  1691. * The cross refernce. It should be of the form from the OBO specification
  1692. *
  1693. * @ingroup tripal_obo_loader
  1694. */
  1695. private function addAltID($cvterm_id, $alt_id) {
  1696. $dbname = '';
  1697. $accession = '';
  1698. $matches = [];
  1699. if (preg_match('/^(.+?):(.*)$/', $alt_id, $matches)) {
  1700. $dbname = $matches[1];
  1701. $accession = $matches[2];
  1702. }
  1703. if (!$accession) {
  1704. throw new Exception("Cannot add an Alt ID without an accession: '$alt_id'");
  1705. }
  1706. // Add the database if it doesn't exist.
  1707. $db = $this->addDB($dbname);
  1708. $db_id = $db->db_id;
  1709. // Now add the dbxref if it doesn't alredy exist
  1710. $dbxref = new ChadoRecord('dbxref');
  1711. $dbxref->setValues([
  1712. 'db_id' => $db_id,
  1713. 'accession' => $accession
  1714. ]);
  1715. if (!$dbxref->find()) {
  1716. $dbxref->insert();
  1717. }
  1718. // Now add the cvterm_dbxref record.
  1719. $cvterm_dbxref = new ChadoRecord('cvterm_dbxref');
  1720. $cvterm_dbxref->setValues([
  1721. 'cvterm_id' => $cvterm_id,
  1722. 'dbxref_id' => $dbxref->getID(),
  1723. ]);
  1724. $cvterm_dbxref->insert();
  1725. }
  1726. /**
  1727. * Adds a database reference to a cvterm
  1728. *
  1729. * @param $cvterm_id
  1730. * The cvterm_id of the term to which the synonym will be added.
  1731. * @param xref
  1732. * The cross refernce. It should be of the form from the OBO specification
  1733. *
  1734. * @ingroup tripal_obo_loader
  1735. */
  1736. private function addXref($cvterm_id, $xref) {
  1737. $dbname = preg_replace('/^(.+?):.*$/', '$1', $xref);
  1738. $accession = preg_replace('/^.+?:\s*(.*?)(\{.+$|\[.+$|\s.+$|\".+$|$)/', '$1', $xref);
  1739. $description = preg_replace('/^.+?\"(.+?)\".*?$/', '$1', $xref);
  1740. $dbxrefs = preg_replace('/^.+?\[(.+?)\].*?$/', '$1', $xref);
  1741. if (!$accession) {
  1742. throw new Exception("Cannot add an xref without an accession: '$xref'");
  1743. }
  1744. // If the xref is a database link then skip those for now.
  1745. if (strcmp($dbname, 'http') == 0) {
  1746. return;
  1747. }
  1748. // Add the database if it doesn't exist.
  1749. $db = $this->addDB($dbname);
  1750. $db_id = $db->db_id;
  1751. // Now add the dbxref if it doesn't alredy exist
  1752. $dbxref = new ChadoRecord('dbxref');
  1753. $dbxref->setValues([
  1754. 'db_id' => $db_id,
  1755. 'accession' => $accession
  1756. ]);
  1757. if (!$dbxref->find()) {
  1758. $dbxref->insert();
  1759. }
  1760. // Now add the cvterm_dbxref record.
  1761. $cvterm_dbxref = new ChadoRecord('cvterm_dbxref');
  1762. $cvterm_dbxref->setValues([
  1763. 'cvterm_id' => $cvterm_id,
  1764. 'dbxref_id' => $dbxref->getID(),
  1765. ]);
  1766. $cvterm_dbxref->insert();
  1767. }
  1768. /**
  1769. * Adds a comment to a cvterm.
  1770. *
  1771. * @param $cvterm_id
  1772. * A cvterm_id of the term to which properties will be added
  1773. * @param $comment
  1774. * The comment to add to the cvterm.
  1775. * @param rank
  1776. * The rank of the comment
  1777. *
  1778. * @ingroup tripal_obo_loader
  1779. */
  1780. private function addComment($cvterm_id, $comment, $rank) {
  1781. // Get the comment type id.
  1782. $comment_type_id = $this->used_terms['rdfs:comment'];
  1783. // Add the comment as a property of the cvterm.
  1784. $cvtermprop = new ChadoRecord('cvtermprop');
  1785. $cvtermprop->setValues([
  1786. 'cvterm_id' => $cvterm_id,
  1787. 'type_id' => $comment_type_id,
  1788. 'value' => $comment,
  1789. 'rank' => $rank,
  1790. ]);
  1791. $cvtermprop->insert();
  1792. }
  1793. /**
  1794. * API call to Ontology Lookup Service provided by
  1795. * https://www.ebi.ac.uk/ols/docs/api#resources-terms
  1796. *
  1797. * @param accession
  1798. * Accession term for query
  1799. * @param type_of_search
  1800. * Either ontology, term, query, or query-non-local
  1801. *
  1802. * @ingroup tripal_obo_loader
  1803. */
  1804. private function oboEbiLookup($accession, $type_of_search) {
  1805. //Grab just the ontology from the $accession.
  1806. $parts = explode(':', $accession);
  1807. $ontology = strtolower($parts[0]);
  1808. $ontology = preg_replace('/\s+/', '', $ontology);
  1809. if ($type_of_search == 'ontology') {
  1810. $options = array();
  1811. $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontology;
  1812. $response = drupal_http_request($full_url, $options);
  1813. if(!empty($response)){
  1814. $response = drupal_json_decode($response->data);
  1815. }
  1816. }
  1817. elseif ($type_of_search == 'term') {
  1818. //The IRI of the terms, this value must be double URL encoded
  1819. $iri = urlencode(urlencode("http://purl.obolibrary.org/obo/" . str_replace(':' , '_', $accession)));
  1820. $options = array();
  1821. $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontology . '/' . 'terms/' . $iri;
  1822. $response = drupal_http_request($full_url, $options);
  1823. if(!empty($response)){
  1824. $response = drupal_json_decode($response->data);
  1825. }
  1826. }
  1827. elseif($type_of_search == 'query') {
  1828. $options = array();
  1829. $full_url = 'http://www.ebi.ac.uk/ols/api/search?q=' . $accession . '&queryFields=obo_id&local=true';
  1830. $response = drupal_http_request($full_url, $options);
  1831. if(!empty($response)){
  1832. $response = drupal_json_decode($response->data);
  1833. }
  1834. }
  1835. elseif($type_of_search == 'query-non-local') {
  1836. $options = array();
  1837. $full_url = 'http://www.ebi.ac.uk/ols/api/search?q=' . $accession . '&queryFields=obo_id';
  1838. $response = drupal_http_request($full_url, $options);
  1839. if(!empty($response)){
  1840. $response = drupal_json_decode($response->data);
  1841. }
  1842. }
  1843. return $response;
  1844. }
  1845. }
  1846. /**
  1847. * Ajax callback for the OBOImporter::form() function.
  1848. */
  1849. function tripal_cv_obo_form_ajax_callback($form, $form_state) {
  1850. return $form['obo_existing'];
  1851. }