OBOImporter.inc 67 KB

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