OBOImporter.inc 81 KB

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