OBOImporter.inc 74 KB

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