123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565 |
- <?php
- class OBOImporter extends TripalImporter {
-
-
-
-
-
-
-
-
- public static $name = 'OBO Vocabulary Loader';
-
- public static $machine_name = 'chado_obo_loader';
-
- public static $description = 'Import vocabularies and terms in OBO format.';
-
- public static $file_types = ['obo'];
-
- public static $upload_description = 'Please provide the details for importing a new OBO file. The file must have a .obo extension.';
-
- public static $upload_title = 'New OBO File';
-
- public static $use_analysis = FALSE;
-
- public static $require_analysis = TRUE;
-
- public static $button_text = 'Import OBO File';
-
- public static $methods = [
-
- 'file_upload' => FALSE,
-
- 'file_local' => FALSE,
-
- 'file_remote' => FALSE,
- ];
-
- public static $menu_path = 'admin/tripal/loaders/chado_vocabs/obo_loader';
- public static $file_required = FALSE;
-
- private $obo_namespaces = [];
-
- private $all_cvs = [];
-
- private $all_dbs = [];
-
- private $syn_types = [
- 'exact' => NULL,
- 'broad' => NULL,
- 'narrow' => NULL,
- 'related' => NULL,
- ];
-
- private $termStanzaCache = [
- 'ids' => [],
- 'count' => [
- 'Typedef' => 0,
- 'Term' => 0,
- 'Instance' => 0,
- ],
- 'types' => [
- 'Typedef' => [],
- 'Term' => [],
- 'Instance' => [],
- ],
- ];
-
- private $cache_type = 'memory';
-
- private $default_namespace = '';
-
- private $idspaces = [];
-
- private $default_db = '';
-
- private $used_terms = [];
-
- private $baseIRIs = [];
-
- private $ebi_warned = FALSE;
-
- private $is_subset = FALSE;
-
- private $term_names = [];
-
- public function form($form, &$form_state) {
-
- $sql = "SELECT * FROM {tripal_cv_obo} ORDER BY name";
- $results = db_query($sql);
- $obos = [];
- $obos[] = 'Select a Vocabulary';
- foreach ($results as $obo) {
- $obos[$obo->obo_id] = $obo->name;
- }
- $obo_id = '';
- if (array_key_exists('values', $form_state)) {
- $obo_id = array_key_exists('obo_id', $form_state['values']) ? $form_state['values']['obo_id'] : '';
- }
- $form['instructions']['info'] = [
- '#type' => 'item',
- '#markup' => t('This page allows you to load vocabularies and ontologies
- that are in OBO format. Once loaded, the terms from these
- vocabularies can be used to create content.
- You may use the form below to either reload a vocabulary that is already
- loaded (as when new updates to that vocabulary are available) or load a new
- vocabulary.'),
- ];
- $form['obo_existing'] = [
- '#type' => 'fieldset',
- '#title' => t('Use a Saved Ontology OBO Reference'),
- '#prefix' => '<span id="obo-existing-fieldset">',
- '#suffix' => '</span>',
- ];
- $form['obo_existing']['existing_instructions'] = [
- '#type' => 'item',
- '#markup' => t('The vocabularies listed in the select box below have been pre-populated
- upon installation of Tripal or have been previously loaded. Select one to edit
- its settings or submit for loading. You may reload any vocabulary that has
- already been loaded to retrieve any new updates.'),
- ];
- $form['obo_existing']['obo_id'] = [
- '#title' => t('Ontology OBO File Reference'),
- '#type' => 'select',
- '#options' => $obos,
- '#ajax' => [
- 'callback' => 'tripal_cv_obo_form_ajax_callback',
- 'wrapper' => 'obo-existing-fieldset',
- ],
- '#description' => t('Select a vocabulary to import.'),
- ];
-
-
- if ($obo_id) {
- $uobo_name = '';
- $uobo_url = '';
- $uobo_file = '';
- $vocab = db_select('tripal_cv_obo', 't')
- ->fields('t', ['name', 'path'])
- ->condition('obo_id', $obo_id)
- ->execute()
- ->fetchObject();
- $uobo_name = $vocab->name;
- if (preg_match('/^http/', $vocab->path)) {
- $uobo_url = $vocab->path;
- }
- else {
- $uobo_file = trim($vocab->path);
- $matches = [];
- if (preg_match('/\{(.*?)\}/', $uobo_file, $matches)) {
- $modpath = drupal_get_path('module', $matches[1]);
- $uobo_file = preg_replace('/\{.*?\}/', $modpath, $uobo_file);
- }
- }
-
-
- unset($form_state['input']['uobo_name']);
- unset($form_state['input']['uobo_url']);
- unset($form_state['input']['uobo_file']);
- $form['obo_existing']['uobo_name'] = [
- '#type' => 'textfield',
- '#title' => t('Vocabulary Name'),
- '#description' => t('Please provide a name for this vocabulary. After upload, this name will appear in the drop down
- list above for use again later.'),
- '#default_value' => $uobo_name,
- ];
- $form['obo_existing']['uobo_url'] = [
- '#type' => 'textfield',
- '#title' => t('Remote URL'),
- '#description' => t('Please enter a URL for the online OBO file. The file will be downloaded and parsed.
- (e.g. https://raw.githubusercontent.com/oborel/obo-relations/master/ro.obo)'),
- '#default_value' => $uobo_url,
- ];
- $form['obo_existing']['uobo_file'] = [
- '#type' => 'textfield',
- '#title' => t('Local File'),
- '#description' => t('Please enter the file system path for an OBO
- definition file. If entering a path relative to
- the Drupal installation you may use a relative path that excludes the
- Drupal installation directory (e.g. sites/default/files/xyz.obo). Note
- that Drupal relative paths have no preceeding slash.
- Otherwise, please provide the full path on the filesystem. The path
- must be accessible to the web server on which this Drupal instance is running.'),
- '#default_value' => $uobo_file,
- ];
- $form['obo_existing']['update_obo_details'] = [
- '#type' => 'submit',
- '#value' => 'Update Ontology Details',
- '#name' => 'update_obo_details',
- ];
- }
- $form['obo_new'] = [
- '#type' => 'fieldset',
- '#title' => t('Add a New Ontology OBO Reference'),
- '#collapsible' => TRUE,
- '#collapsed' => TRUE,
- ];
- $form['obo_new']['path_instructions'] = [
- '#value' => t('Provide the name and path for the OBO file. If the vocabulary OBO file
- is stored local to the server provide a file name. If the vocabulary is stored remotely,
- provide a URL. Only provide a URL or a local file, not both.'),
- ];
- $form['obo_new']['obo_name'] = [
- '#type' => 'textfield',
- '#title' => t('New Vocabulary Name'),
- '#description' => t('Please provide a name for this vocabulary. After upload, this name will appear in the drop down
- list above for use again later. Additionally, if a default namespace is not provided in the OBO
- header this name will be used as the default_namespace.'),
- ];
- $form['obo_new']['obo_url'] = [
- '#type' => 'textfield',
- '#title' => t('Remote URL'),
- '#description' => t('Please enter a URL for the online OBO file. The file will be downloaded and parsed.
- (e.g. https://raw.githubusercontent.com/oborel/obo-relations/master/ro.obo)'),
- ];
- $form['obo_new']['obo_file'] = [
- '#type' => 'textfield',
- '#title' => t('Local File'),
- '#description' => t('Please enter the file system path for an OBO
- definition file. If entering a path relative to
- the Drupal installation you may use a relative path that excludes the
- Drupal installation directory (e.g. sites/default/files/xyz.obo). Note
- that Drupal relative paths have no preceeding slash.
- Otherwise, please provide the full path on the filesystem. The path
- must be accessible to the web server on which this Drupal instance is running.'),
- ];
- return $form;
- }
-
- public function formSubmit($form, &$form_state) {
- $obo_id = $form_state['values']['obo_id'];
- $obo_name = trim($form_state['values']['obo_name']);
- $obo_url = trim($form_state['values']['obo_url']);
- $obo_file = trim($form_state['values']['obo_file']);
- $uobo_name = array_key_exists('uobo_name', $form_state['values']) ? trim($form_state['values']['uobo_name']) : '';
- $uobo_url = array_key_exists('uobo_url', $form_state['values']) ? trim($form_state['values']['uobo_url']) : '';
- $uobo_file = array_key_exists('uobo_file', $form_state['values']) ? trim($form_state['values']['uobo_file']) : '';
-
- if ($form_state['clicked_button']['#name'] == 'update_obo_details') {
- $form_state['rebuild'] = TRUE;
- $success = db_update('tripal_cv_obo')
- ->fields([
- 'name' => $uobo_name,
- 'path' => $uobo_url ? $uobo_url : $uobo_file,
- ])
- ->condition('obo_id', $obo_id)
- ->execute();
- if ($success) {
- drupal_set_message(t("The vocabulary !vocab has been updated.", ['!vocab' => $uobo_name]));
- }
- else {
- drupal_set_message(t("The vocabulary !vocab could not be updated.", ['!vocab' => $uobo_name]), 'error');
- }
- }
- elseif (!empty($obo_name)) {
- $obo_id = db_insert('tripal_cv_obo')
- ->fields([
- 'name' => $obo_name,
- 'path' => $obo_url ? $obo_url : $obo_file,
- ])
- ->execute();
-
- $form_state['values']['obo_id'] = $obo_id;
- if ($obo_id) {
- drupal_set_message(t("The vocabulary !vocab has been added.", ['!vocab' => $obo_name]));
- }
- else {
- $form_state['rebuild'] = TRUE;
- drupal_set_message(t("The vocabulary !vocab could not be added.", ['!vocab' => $obo_name]), 'error');
- }
- }
- }
-
- public function formValidate($form, &$form_state) {
- $obo_id = $form_state['values']['obo_id'];
- $obo_name = trim($form_state['values']['obo_name']);
- $obo_url = trim($form_state['values']['obo_url']);
- $obo_file = trim($form_state['values']['obo_file']);
- $uobo_name = array_key_exists('uobo_name', $form_state['values']) ? trim($form_state['values']['uobo_name']) : '';
- $uobo_url = array_key_exists('uobo_url', $form_state['values']) ? trim($form_state['values']['uobo_url']) : '';
- $uobo_file = array_key_exists('uobo_file', $form_state['values']) ? trim($form_state['values']['uobo_file']) : '';
-
- if ($form_state['clicked_button']['#name'] == 'update_obo_details' or
- $form_state['clicked_button']['#name'] == 'update_load_obo') {
-
- $vocab = db_select('tripal_cv_obo', 't')
- ->fields('t', ['obo_id', 'name', 'path'])
- ->condition('name', $uobo_name)
- ->execute()
- ->fetchObject();
- if ($vocab and $vocab->obo_id != $obo_id) {
- form_set_error('uobo_name', 'The vocabulary name must be different from existing vocabularies');
- }
-
- $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $uobo_file;
- if (!file_exists($dfile)) {
- if (!file_exists($uobo_file)) {
- form_set_error('uobo_file', t('The specified path, !path, does not exist or cannot be read.'), ['!path' => $dfile]);
- }
- }
- if (!$uobo_url and !$uobo_file) {
- form_set_error('uobo_url', 'Please provide a URL or a path for the vocabulary.');
- }
- if ($uobo_url and $uobo_file) {
- form_set_error('uobo_url', 'Please provide only a URL or a path for the vocabulary, but not both.');
- }
- }
- if ($form_state['clicked_button']['#name'] == 'add_new_obo') {
-
- $vocab = db_select('tripal_cv_obo', 't')
- ->fields('t', ['obo_id', 'name', 'path'])
- ->condition('name', $obo_name)
- ->execute()
- ->fetchObject();
- if ($vocab) {
- form_set_error('obo_name', 'The vocabulary name must be different from existing vocabularies');
- }
-
- $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo_file;
- if (!file_exists($dfile)) {
- if (!file_exists($obo_file)) {
- form_set_error('obo_file', t('The specified path, !path, does not exist or cannot be read.'), ['!path' => $dfile]);
- }
- }
- if (!$obo_url and !$obo_file) {
- form_set_error('obo_url', 'Please provide a URL or a path for the vocabulary.');
- }
- if ($obo_url and $obo_file) {
- form_set_error('obo_url', 'Please provide only a URL or a path for the vocabulary, but not both.');
- }
- }
- }
-
- public function run() {
- $arguments = $this->arguments['run_args'];
- $obo_id = $arguments['obo_id'];
-
- $obo = db_select('tripal_cv_obo', 'tco')
- ->fields('tco')
- ->condition('obo_id', $obo_id)
- ->execute()
- ->fetchObject();
- if (!$obo) {
- throw new Exception("Invalid OBO ID provided: '$obo_id'.");
- }
-
- $sql = "SELECT * FROM {cv} CV";
- $cvs = chado_query($sql);
- while ($cv = $cvs->fetchObject()) {
- $this->all_cvs[$cv->name] = $cv;
- }
-
- $sql = "SELECT * FROM {db} DB";
- $dbs = chado_query($sql);
- while ($db = $dbs->fetchObject()) {
- $this->all_dbs[$db->name] = $db;
- }
-
- $term = chado_get_cvterm(['id' => 'NCIT:C25693']);
- $this->used_terms['NCIT:C25693'] = $term->cvterm_id;
-
- $term = chado_get_cvterm(['id' => 'rdfs:comment']);
- $this->used_terms['rdfs:comment'] = $term->cvterm_id;
-
- $syn_cv = new ChadoRecord('cv');
- $syn_cv->setValues(['name' => 'synonym_type']);
- $syn_cv->save();
- $this->all_cvs['synonym_type'] = (object) $syn_cv->getValues();
-
- $syn_db = new ChadoRecord('db');
- $syn_db->setValues(['name' => 'synonym_type']);
- $syn_db->save();
- $this->all_dbs['synonym_type'] = (object) $syn_db->getValues();
-
- foreach (array_keys($this->syn_types) as $syn_type) {
- $syn_dbxref = new ChadoRecord('dbxref');
- $syn_dbxref->setValues([
- 'accession' => $syn_type,
- 'db_id' => $syn_db->getID(),
- ]);
- $syn_dbxref->save();
- $syn_term = new ChadoRecord('cvterm');
- $syn_term->setValues([
- 'name' => $syn_type,
- 'cv_id' => $syn_cv->getID(),
- ]);
- if (!$syn_term->find()) {
- $syn_term->setValues([
- 'name' => $syn_type,
- 'definition' => '',
- 'is_obsolete' => 0,
- 'cv_id' => $syn_cv->getID(),
- 'is_relationshiptype' => 0,
- 'dbxref_id' => $syn_dbxref->getID(),
- ]);
- $syn_term->insert();
- }
- $this->syn_types[$syn_type] = (object) $syn_term->getValues();
- }
-
- $this->loadOBO_v1_2_id($obo);
- }
-
- public function postRun() {
-
- cache_clear_all('tripal_chado:term:*', 'cache', TRUE);
-
- $this->logMessage("Updating the cv_root_mview materialized view...");
- $mview_id = tripal_get_mview_id('cv_root_mview');
- tripal_populate_mview($mview_id);
- $this->logMessage("Updating the db2cv_mview materialized view...");
- $mview_id = tripal_get_mview_id('db2cv_mview');
- tripal_populate_mview($mview_id);
-
- $this->logMessage("Updating cvtermpath table. This may take a while...");
- foreach ($this->obo_namespaces as $namespace => $cv_id) {
- $this->logMessage("- Loading paths for vocabulary: @vocab", ['@vocab' => $namespace]);
- chado_update_cvtermpath($cv_id, $this->job);
- }
- }
-
- private function loadOBO_v1_2_id($obo) {
-
- if (preg_match("/\{(.*?)\}/", $obo->path, $matches)) {
- $module = $matches[1];
- $path = drupal_realpath(drupal_get_path('module', $module));
- $obo->path = preg_replace("/\{.*?\}/", $path, $obo->path);
- }
-
- if (preg_match("/^https:\/\//", $obo->path) or
- preg_match("/^http:\/\//", $obo->path) or
- preg_match("/^ftp:\/\//", $obo->path)) {
- $this->loadOBO_v1_2_url($obo->name, $obo->path, 0);
- }
-
- else {
-
- $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo->path;
- if (file_exists($dfile)) {
- $this->loadOBO_v1_2_file($obo->name, $dfile, 0);
- }
-
-
- else {
- if (file_exists($obo->path)) {
- $this->loadOBO_v1_2_file($obo->name, $obo->path, 0);
- }
- else {
- print "ERROR: could not find OBO file: '$obo->path'\n";
- }
- }
- }
- }
-
- private function loadOBO_v1_2_file($obo_name, $file, $is_new = TRUE) {
- if ($is_new) {
- tripal_insert_obo($obo_name, $file);
- }
- $success = $this->loadOBO_v1_2($file, $obo_name);
- }
-
- private function loadOBO_v1_2_url($obo_name, $url, $is_new = TRUE) {
-
- $temp = tempnam(sys_get_temp_dir(), 'obo_');
- print "Downloading URL $url, saving to $temp\n";
- $url_fh = fopen($url, "r");
- $obo_fh = fopen($temp, "w");
- if (!$url_fh) {
- throw new Exception("Unable to download the remote OBO file at $url. Could a firewall be blocking outgoing connections? " .
- " if you are unable to download the file you may manually download the OBO file and use the web interface to " .
- " specify the location of the file on your server.");
- }
- while (!feof($url_fh)) {
- fwrite($obo_fh, fread($url_fh, 255), 255);
- }
- fclose($url_fh);
- fclose($obo_fh);
- if ($is_new) {
- tripal_insert_obo($obo_name, $url);
- }
-
- $this->loadOBO_v1_2($temp, $obo_name);
-
- unlink($temp);
- }
-
- private function loadOBO_v1_2($file, $obo_name) {
- $header = [];
- $ret = [];
-
- $this->clearTermStanzaCache();
-
- $this->logMessage("Step 1: Preloading File $file...");
- $this->parse($file, $header);
-
- $this->logMessage("Step 2: Examining relationships...");
- $this->cacheRelationships();
-
- $this->logMessage("Step 3: Loading type defs...");
- $this->processTypeDefs();
-
- $this->logMessage("Step 4: Loading terms...");
- $this->processTerms();
-
- $this->logMessage("Step 5: Cleanup...");
- $this->clearTermStanzaCache();
- }
-
- private function processTypeDefs() {
- $typedefs = $this->getCachedTermStanzas('Typedef');
- $count = $this->getCacheSize('Typedef');
- $this->setTotalItems($count);
- $this->setItemsHandled(0);
- $this->setInterval(5);
- $i = 1;
- foreach ($typedefs as $t) {
-
-
- if ($this->cache_type == 'table') {
- $stanza = unserialize(base64_decode($t->stanza));
- }
- else {
- $stanza = $this->termStanzaCache['ids'][$t];
- }
- $this->setItemsHandled($i++);
- $this->processTerm($stanza, TRUE);
- }
- $this->setItemsHandled($i);
- return 1;
- }
-
- private function processTerms() {
- $i = 0;
- $external = FALSE;
- $terms = $this->getCachedTermStanzas('Term');
- $count = $this->getCacheSize('Term');
- $this->setTotalItems($count);
- $this->setItemsHandled(0);
- $this->setInterval(1);
-
- foreach ($terms as $t) {
-
-
- if ($this->cache_type == 'table') {
- $term = unserialize(base64_decode($t->stanza));
- }
- else {
- $term = $this->termStanzaCache['ids'][$t];
- }
- $this->setItemsHandled($i);
-
- $this->processTerm($term, FALSE);
- $i++;
- }
- $this->setItemsHandled($i);
- return 1;
- }
-
- private function setDefaults($header) {
- $short_name = '';
- $namespace = '';
- $idspaces = [];
-
-
- if (array_key_exists('ontology', $header)) {
- $short_name = strtoupper($header['ontology'][0]);
- }
- if (array_key_exists('default-namespace', $header)) {
- $namespace = $header['default-namespace'][0];
- }
- if (array_key_exists('idspace', $header)) {
- $matches = [];
- foreach ($header['idspace'] as $idspace) {
- if (preg_match('/^(.+?)\s+(.+?)\s+"(.+)"$/', $idspace, $matches)) {
- $idspaces[$matches[1]]['url'] = $matches[2];
- $idspaces[$matches[1]]['description'] = $matches[3];
- }
- elseif (preg_match('/^(.+?)\s+(.+?)$/', $idspace, $matches)) {
- $idspaces[$matches[1]]['url'] = $matches[2];
- $idspaces[$matches[1]]['description'] = '';
- }
- }
- }
-
-
-
- $matches = [];
- if (preg_match('/^(.+?)\/.*/', $short_name, $matches)) {
- $short_name = $matches[1];
- $this->is_subset = TRUE;
- }
-
-
- if (!$namespace and $short_name) {
- $namespace = $this->findEBIOntologyNamespace($short_name);
- }
-
-
- if ($namespace and !$short_name) {
-
-
- $sql = "SELECT dbname FROM {db2cv_mview} WHERE cvname = :cvname";
- $short_name = chado_query($sql, [':cvname' => $namespace])->fetchField();
- if (!$short_name and array_key_exists('namespace-id-rule', $header)) {
- $matches = [];
- if (preg_match('/^.*\s(.+?):.+$/', $header['namespace-id-rule'][0], $matches)) {
- $short_name = $matches[1];
- }
- }
-
- if (!$short_name) {
-
- }
- }
-
-
- if (!$namespace and array_key_exists('run_args', $this->arguments)
- and array_key_exists('obo_name', $this->arguments['run_args'])) {
- $namespace = $this->arguments['run_args']['obo_name'];
- }
- if (!$namespace and array_key_exists('run_args', $this->arguments)
- and array_key_exists('uobo_name', $this->arguments['run_args'])) {
- $namespace = $this->arguments['run_args']['uobo_name'];
- }
-
- if (!$namespace and !$short_name) {
- throw new ErrorException('Cannot determine the namespace or ontology prefix from this OBO file. It is missing both the "default-namespace" or a compatible "ontology" header.');
- }
-
- $this->default_namespace = $namespace;
- $this->default_db = $short_name;
- $this->addDB($this->default_db);
- $cv = $this->addCV($this->default_namespace);
- $this->obo_namespaces[$namespace] = $cv->cv_id;
- $this->idspaces = $idspaces;
-
- foreach ($idspaces as $shortname => $idspace) {
- $this->addDB($shortname, $idspace['url'], $idspace['description']);
- }
- }
-
- private function findEBIOntologyNamespace($ontology) {
-
- try {
- $results = $this->oboEbiLookup($ontology, 'ontology');
- if ($results and array_key_exists('config', $results) and array_key_exists('default-namespace', $results['config']['annotations'])) {
- $namespace = $results['config']['annotations']['default-namespace'];
- if (is_array($namespace)) {
- $namespace = $namespace[0];
- }
- }
- elseif ($results and array_key_exists('config', $results) and array_key_exists('namespace', $results['config'])) {
- $namespace = $results['config']['namespace'];
- }
-
-
- else {
- $namespace = $this->default_db;
- }
- return $namespace;
- } catch (Exception $e) {
- watchdog_exception('Cannot find the namespace for this ontology.', $e);
- throw $e;
- }
- }
-
- private function findEBIOntologyPrefix($namespace) {
-
-
- $options = [];
- $page = 1;
- $size = 25;
- $full_url = 'https://www.ebi.ac.uk/ols/api/ontologies?page=' . $page . '&size=' . $size;
- while ($response = drupal_http_request($full_url, $options)) {
- $response = drupal_json_decode($response->data);
- foreach ($response['_embedded']['ontologies'] as $ontology) {
- $namespace = $ontology['config']['namespace'];
- }
- $page++;
- $full_url = 'https://www.ebi.ac.uk/ols/api/ontologies?page=' . $page . '&size=' . $size;
- }
- }
-
- private function findEBITerm($id) {
-
-
- if ($this->ebi_warned == FALSE) {
- $this->logMessage(
- "A term that belongs to another ontology is used within this " .
- "vocabulary. Therefore a lookup will be performed with the EBI Ontology " .
- "Lookup Service to retrieve the information for this term. " .
- "Please note, that vocabularies with many non-local terms " .
- "require remote lookups and these lookups can dramatically " .
- "increase loading time. ",
- ['!vocab' => $this->default_namespace], TRIPAL_WARNING);
- $this->ebi_warned = TRUE;
-
-
-
- $this->setInterval(1);
- }
- $this->logMessage("Performing EBI OLS Lookup for: !id", ['!id' => $id]);
-
- $pair = explode(":", $id, 2);
- $short_name = $pair[0];
- $accession = $pair[1];
-
- $base_iri = '';
- $ontologyID = '';
- if (array_key_exists($short_name, $this->baseIRIs)) {
- list($ontologyID, $base_iri) = $this->baseIRIs[$short_name];
- }
- else {
- $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $short_name;
- $response = drupal_http_request($full_url, []);
- if (!$response) {
- throw new Exception(t('Did not get a response from EBI OLS trying to lookup ontology: !ontology',
- ['!ontology' => $short_name]));
- }
- $ontology_results = drupal_json_decode($response->data);
- if ($ontology_results['error']) {
- $this->logMessage(t('Cannot find the ontology via an EBI OLS lookup: !short_name. \n' .
- 'We tried to access: !url' .
- 'EBI Reported: !message. ' .
- 'Consider finding the OBO file for this ontology and manually loading it first.',
- [
- '!message' => $ontology_results['message'],
- '!short_name' => $short_name,
- '!url' => $full_url,
- ]), TRIPAL_WARNING);
- }
-
- $base_iri = $ontology_results['config']['baseUris'][0];
- $ontologyID = $ontology_results['ontologyId'];
- $this->baseIRIs[$short_name] = [$ontologyID, $base_iri];
- }
-
- $iri = urlencode(urlencode($base_iri . $accession));
- $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontologyID . '/terms/' . $iri;
- $response = drupal_http_request($full_url, []);
- if (!$response) {
- throw new Exception(t('Did not get a response from EBI OLS trying to lookup term: !id',
- ['!id' => $id]));
- }
- $results = drupal_json_decode($response->data);
- if (!$results) {
- $this->logMessage('Error: no data with !url. The response was: !response', [
- '!url' => $full_url,
- '!response' => $response,
- ]);
- return FALSE;
- }
-
- if ($results['error']) {
- $this->logMessage('Cannot find the term via an EBI OLS lookup: !term. ' .
- 'We tried to access: "!url" ' .
- 'EBI Reported: !message. Consider finding the OBO file for this ontology and manually loading it first.',
- [
- '!message' => $results['message'],
- '!term' => $id,
- '!url' => $full_url,
- ], TRIPAL_WARNING);
- return FALSE;
- }
-
- if ($results['is_defining_ontology'] != 1) {
- }
-
-
- $this->logMessage("Found !term in EBI OLS.", ['!term' => $id]);
- $stanza = [];
- $stanza['id'][0] = $id;
- $stanza['name'][0] = $results['label'];
- $stanza['def'][0] = $results['def'];
- $stanza['namespace'][0] = $results['ontology_name'];
- $stanza['is_obsolete'][0] = $results['is_obsolete'] ? 'true' : '';
- $stanza['is_relationshiptype'][0] = '';
- $stanza['db_name'][0] = $short_name;
- $stanza['comment'][0] = 'Term obtained using the EBI Ontology Lookup Service.';
- if (array_key_exists('in_subset', $results)) {
- if (is_array($results['in_subset'])) {
- $stanza['subset'] = $results['in_subset'];
- }
- elseif ($results['in_subset']) {
- $stanza['subset'][0] = $results['in_subset'];
- }
- }
-
- if (array_key_exists('term_replaced_by', $results) and isset($results['term_replaced_by'])) {
- $replaced_by = $results['term_replaced_by'];
- $replaced_by = preg_replace('/_/', ':', $replaced_by);
- $this->logMessage("The term, !term, is replaced by, !replaced",
- ['!term' => $id, '!replaced' => $replaced_by]);
-
-
- if (array_key_exists($replaced_by, $this->termStanzaCache['ids'])) {
- $this->logMessage("Found term, !replaced in the term cache.",
- ['!term' => $id, '!replaced' => $replaced_by]);
- return $this->termStanzaCache['ids'][$id];
- }
-
- $rpair = explode(":", $replaced_by, 2);
- $found = $this->lookupTerm($rpair[0], $rpair[1]);
- if ($found) {
- $this->logMessage("Found term, !replaced in the local data store.",
- ['!term' => $id, '!replaced' => $replaced_by]);
- return $found;
- }
-
- $stanza = $this->findEBITerm($replaced_by);
- }
- return $stanza;
- }
-
- private function saveTerm($stanza, $is_relationship = FALSE) {
-
- $id = $stanza['id'][0];
-
- if (array_key_exists($id, $this->used_terms)) {
- return $this->used_terms[$id];
- }
-
- $id = $stanza['id'][0];
- $name = $stanza['name'][0];
- $cvname = $stanza['namespace'][0];
- $dbname = $stanza['db_name'][0];
- $namespace = $stanza['namespace'][0];
-
-
-
- $accession = '';
- $matches = [];
- if (preg_match('/^(.+?):(.*)$/', $id, $matches)) {
- $accession = $matches[2];
- }
- else {
- $accession = $id;
- }
-
- $definition = '';
- if (array_key_exists('def', $stanza)) {
- $definition = preg_replace('/^\"(.*)\"/', '\1', $stanza['def'][0]);
- }
-
- $is_obsolete = 0;
- if (array_key_exists('is_obsolete', $stanza)) {
- $is_obsolete = $stanza['is_obsolete'][0] == 'true' ? 1 : 0;
- }
-
- $is_relationshiptype = 0;
- if (array_key_exists('is_relationshiptype', $stanza)) {
- $is_relationshiptype = $stanza['is_relationshiptype'][0] == 'true' ? 1 : 0;
- }
-
- $is_borrowed = $this->isTermBorrowed($stanza);
-
- $cvterm = NULL;
-
- $cv = $this->all_cvs[$cvname];
- $db = $this->all_dbs[$dbname];
-
- $do_cvterm_insert = TRUE;
-
-
-
- $dbxref = new ChadoRecord('dbxref');
- $dbxref->setValues([
- 'db_id' => $db->db_id,
- 'accession' => $accession,
- ]);
- if ($dbxref->find()) {
-
-
-
- $dbx_cvterm = new ChadoRecord('cvterm');
- $dbx_cvterm->setValues(['dbxref_id' => $dbxref->getID()]);
- if ($dbx_cvterm->find()) {
- $do_cvterm_insert = FALSE;
- $cvterm = $dbx_cvterm;
-
-
- if (!$is_borrowed) {
-
-
- $this->fixTermMismatch($stanza, $dbxref, $cv, $name);
-
- $cvterm->setValue('name', $name);
- $cvterm->setValue('definition', $definition);
- $cvterm->setValue('is_obsolete', $is_obsolete);
- $cvterm->setValue('is_relationshiptype', $is_relationshiptype);
- try {
- $cvterm->update();
- } catch (Exception $e) {
- $this->logMessage('Could not update the term, "!term", with name, "!name" for vocabulary, "!vocab". ERROR: !error.',
- [
- '!term' => $id,
- '!name' => $name,
- '!vocab' => $cv->name,
- '!error' => $e->getMessage(),
- ],
- TRIPAL_ERROR);
- throw $e;
- }
- }
- }
- }
-
- else {
- $dbxref->insert();
- }
-
- if ($do_cvterm_insert) {
-
-
- $cvterm = new ChadoRecord('cvterm');
- $cvterm->setValue('cv_id', $cv->cv_id);
- $cvterm->setValue('name', $name);
- if ($cvterm->find()) {
- $fixed = $this->fixTermMismatch($stanza, $dbxref, $cv, $name);
- }
-
- $cvterm->setValues([
- 'cv_id' => $cv->cv_id,
- 'name' => $name,
- 'definition' => $definition,
- 'dbxref_id' => $dbxref->getID(),
- 'is_relationshiptype' => $is_relationshiptype,
- 'is_obsolete' => $is_obsolete,
- 'dbxref_id' => $dbxref->getValue('dbxref_id'),
- ]);
-
-
- try {
- $cvterm->insert();
- } catch (Exception $e) {
- $this->logMessage('Could not insert the term, "!term", with name, "!name" for vocabulary, "!vocab". ERROR: !error.',
- [
- '!term' => $id,
- '!name' => $name,
- '!vocab' => $cv->name,
- '!error' => $e->getMessage(),
- ],
- TRIPAL_ERROR);
- throw $e;
- }
- }
-
- $cvterm_id = $cvterm->getID();
- $this->used_terms[$id] = $cvterm_id;
-
- return $cvterm_id;
- }
-
- public function fixTermMismatch($stanza, $dbxref, $cv, $name) {
- $id = $stanza['id'][0];
- $name = $stanza['name'][0];
-
- $sql = "
- SELECT cvterm_id
- FROM {cvterm}
- WHERE name = :name and cv_id = :cv_id and dbxref_id != :dbxref_id
- ";
- $args = [
- ':name' => $name,
- ':cv_id' => $cv->cv_id,
- ':dbxref_id' => $dbxref->getID(),
- ];
- $results = chado_query($sql, $args);
- while ($conflict_id = $results->fetchField()) {
- $check_cvterm = new ChadoRecord('cvterm', $conflict_id);
-
-
- if ($dbxref->getID() == $check_cvterm->getValue('dbxref_id')) {
- return FALSE;
- }
-
-
- $check_dbxref = new ChadoRecord('dbxref', $check_cvterm->getValue('dbxref_id'));
- $check_db = new ChadoRecord('db', $check_dbxref->getValue('db_id'));
- $check_accession = $check_db->getValue('name') . ':' . $check_dbxref->getValue('accession');
-
-
-
-
-
-
-
-
-
- $check_stanza = $this->getCachedTermStanza($check_accession);
- if (!$check_stanza) {
- $new_name = $check_cvterm->getValue('name') . ' (' . $check_accession . ')';
- $check_cvterm->setValue('name', $new_name);
- $check_cvterm->setValue('is_obsolete', '1');
- $check_cvterm->update();
- return TRUE;
- }
-
-
-
- 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'))) {
- $new_name = $check_cvterm->getValue('name') . ' (obsolete)';
- $check_cvterm->setValue('name', $new_name);
- $check_cvterm->update();
- return TRUE;
- }
-
-
-
-
-
-
-
- else {
- $new_name = $check_cvterm->getValue('name') . ' (' . $check_accession . ')';
- $check_cvterm->setValue('name', $new_name);
- $check_cvterm->update();
- return TRUE;
- }
- }
- }
-
- return FALSE;
- }
-
- private function processTerm($stanza, $is_relationship = 0) {
-
-
-
-
-
-
- $cvterm_id = $this->saveTerm($stanza, FALSE);
- $id = $stanza['id'][0];
-
-
- if ($this->isTermBorrowed($stanza)) {
- return;
- }
-
-
-
- $sql = "
- DELETE FROM {cvterm_relationship}
- WHERE subject_id = :cvterm_id
- ";
- chado_query($sql, [':cvterm_id' => $cvterm_id]);
-
-
- if (in_array('is_obsolete', $stanza) and $stanza['is_obsolete'] == 'true') {
- $sql = "
- DELETE FROM {cvterm_relationship}
- WHERE object_id = :cvterm_id
- ";
- chado_query($sql, [':cvterm_id' => $cvterm_id]);
- }
- $sql = "
- DELETE FROM {cvtermprop}
- WHERE cvterm_id = :cvterm_id
- ";
- chado_query($sql, [':cvterm_id' => $cvterm_id]);
- $sql = "
- DELETE FROM {cvterm_dbxref}
- WHERE cvterm_id = :cvterm_id
- ";
- chado_query($sql, [':cvterm_id' => $cvterm_id]);
- $sql = "
- DELETE FROM {cvtermsynonym} CVTSYN
- WHERE cvterm_id = :cvterm_id
- ";
- chado_query($sql, [':cvterm_id' => $cvterm_id]);
-
-
-
- if (!$cvterm_id) {
- throw new Exception(t('Missing cvterm after saving term: !term',
- ['!term' => print_r($stanza, TRUE)]));
- }
-
-
-
- if (array_key_exists('alt_id', $stanza)) {
- foreach ($stanza['alt_id'] as $alt_id) {
- $this->addAltID($id, $cvterm_id, $alt_id);
- }
- }
-
-
-
- if (array_key_exists('synonym', $stanza)) {
- foreach ($stanza['synonym'] as $synonym) {
- $this->addSynonym($id, $cvterm_id, $synonym);
- }
- }
-
-
-
- if (array_key_exists('exact_synonym', $stanza)) {
- foreach ($stanza['exact_synonym'] as $synonym) {
- $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 EXACT $2', $synonym);
- $this->addSynonym($id, $cvterm_id, $fixed);
- }
- }
-
-
-
- if (array_key_exists('narrow_synonym', $stanza)) {
- foreach ($stanza['narrow_synonym'] as $synonym) {
- $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 NARROW $2', $synonym);
- $this->addSynonym($id, $cvterm_id, $fixed);
- }
- }
-
-
-
- if (array_key_exists('broad_synonym', $stanza)) {
- foreach ($stanza['broad_synonym'] as $synonym) {
- $fixed = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 BROAD $2', $synonym);
- $this->addSynonym($id, $cvterm_id, $fixed);
- }
- }
-
-
-
- if (array_key_exists('comment', $stanza)) {
- $comments = $stanza['comment'];
- foreach ($comments as $rank => $comment) {
- $this->addComment($id, $cvterm_id, $comment, $rank);
- }
- }
-
-
-
- if (array_key_exists('xref', $stanza)) {
- foreach ($stanza['xref'] as $xref) {
- $this->addXref($id, $cvterm_id, $xref);
- }
- }
-
-
-
- if (array_key_exists('xref_analog', $stanza)) {
- foreach ($stanza['xref_analog'] as $xref) {
- $this->addXref($id, $cvterm_id, $xref);
- }
- }
-
-
-
- if (array_key_exists('xref_unk', $stanza)) {
- foreach ($stanza['xref_unk'] as $xref) {
- $this->addXref($id, $cvterm_id, $xref);
- }
- }
-
-
-
- if (array_key_exists('subset', $stanza)) {
- foreach ($stanza['subset'] as $subset) {
- $this->addSubset($id, $cvterm_id, $subset);
- }
- }
-
-
-
- if (array_key_exists('is_a', $stanza)) {
- foreach ($stanza['is_a'] as $is_a) {
- $this->addRelationship($id, $cvterm_id, 'is_a', $is_a);
- }
- }
-
-
-
- if (array_key_exists('relationship', $stanza)) {
- foreach ($stanza['relationship'] as $value) {
- $rel = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
- $object = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
- $this->addRelationship($id, $cvterm_id, $rel, $object);
- }
- }
-
- }
-
- private function addRelationship($id, $cvterm_id, $rel_id, $obj_id) {
-
-
-
- $rel_stanza = $this->getCachedTermStanza($rel_id);
- if (!$rel_stanza) {
- throw new Exception(t('Cannot add relationship: "!source !rel !object". ' .
- 'The term, !rel, is not in the term cache.',
- ['!source' => $id, '!rel' => $rel_id, '!name' => $obj_id]));
- }
- $rel_cvterm_id = $this->saveTerm($rel_stanza, TRUE);
-
- $obj_stanza = $this->getCachedTermStanza($obj_id);
- if (!$obj_stanza) {
- throw new Exception(t('Cannot add relationship: "!source !rel !object". ' .
- 'The term, !object, is not in the term cache.',
- ['!source' => $id, '!rel' => $rel_id, '!object' => $obj_id]));
- }
- $obj_cvterm_id = $this->saveTerm($obj_stanza);
-
- $cvterm_relationship = new ChadoRecord('cvterm_relationship');
- $cvterm_relationship->setValues([
- 'type_id' => $rel_cvterm_id,
- 'subject_id' => $cvterm_id,
- 'object_id' => $obj_cvterm_id,
- ]);
-
-
- try {
- $cvterm_relationship->insert();
- } catch (Exception $e) {
- throw new Exception(t('Cannot add relationship: "!source !rel !object". ' .
- 'ERROR: !error.',
- [
- '!source' => $id,
- '!rel' => $rel_id,
- '!object' => $obj_id,
- '!error' => $e->getMessage(),
- ]));
- }
- }
-
- private function getCachedTermStanza($id) {
- if ($this->cache_type == 'table') {
- $values = ['id' => $id];
- $result = chado_select_record('tripal_obo_temp', ['stanza'], $values);
- if (count($result) == 0) {
- return FALSE;
- }
- return unserialize(base64_decode($result['stanza']));
- }
- if (array_key_exists($id, $this->termStanzaCache['ids'])) {
- return $this->termStanzaCache['ids'][$id];
- }
- else {
- return FALSE;
- }
- }
-
- private function lookupTerm($short_name, $accession) {
-
- if (!array_key_exists($short_name, $this->all_dbs)) {
- return NULL;
- }
- $db = $this->all_dbs[$short_name];
-
- $dbxref = new ChadoRecord('dbxref');
- $dbxref->setValues([
- 'db_id' => $db->db_id,
- 'accession' => $accession,
- ]);
- if (!$dbxref->find()) {
- return NULL;
- }
-
- $cvterm = new ChadoRecord('cvterm');
- $cvterm->setValues(['dbxref_id' => $dbxref->getID()]);
- if (!$cvterm->find()) {
- return NULL;
- }
-
- $cv = new ChadoRecord('cv');
- $cv->setValues(['cv_id' => $cvterm->getValue('cv_id')]);
- $cv->find();
-
- $stanza = [];
- $stanza['id'][0] = $short_name . ':' . $accession;
- $stanza['name'][0] = $cvterm->getValue('name');
- $stanza['def'][0] = $cvterm->getValue('definition');
- $stanza['namespace'][0] = $cv->getValue('name');
- $stanza['is_obsolete'][0] = $cvterm->getValue('is_obsolete') == 1 ? 'true' : '';
- $stanza['is_relationshiptype'][0] = '';
- $stanza['db_name'][0] = $db->name;
- $stanza['cv_name'][0] = $cv->getValue('name');
- return $stanza;
- }
-
- private function cacheTermStanza($stanza, $type) {
-
- if (!$this->default_namespace) {
- throw new Exception('Cannot cache terms without a default CV.' . print_r($stanza, TRUE));
- }
- if (!$this->default_db) {
- throw new Exception('Cannot cache terms without a default DB.' . print_r($stanza, TRUE));
- }
- $id = $stanza['id'][0];
-
- if ($this->getCachedTermStanza($id)) {
- return;
- }
-
-
-
-
- $matches = [];
- if (preg_match('/^(.+):(.+)$/', $id, $matches)) {
- $short_name = $matches[1];
- $accession = $matches[2];
-
- $idspaces = array_keys($this->idspaces);
- if ($short_name != $this->default_db and !in_array($short_name, $idspaces)) {
-
-
- $found = $this->lookupTerm($short_name, $accession);
- if ($found) {
- $stanza = $found;
- }
-
- else {
- $stanza = $this->findEBITerm($id);
- if (!$stanza) {
- return FALSE;
- }
-
- $this->addDB($stanza['db_name'][0]);
- $this->addCV($stanza['namespace'][0]);
- }
- }
-
- else {
- if (!array_key_exists('namespace', $stanza)) {
- $stanza['namespace'][0] = $this->default_namespace;
- }
- $stanza['db_name'][0] = $short_name;
- }
-
-
- $this->addDB($short_name);
- }
-
- else {
- if (!array_key_exists('namespace', $stanza)) {
- $stanza['namespace'][0] = $this->default_namespace;
- }
- $stanza['db_name'][0] = $this->default_db;
- }
- $stanza['is_relationshiptype'][0] = '';
- if ($type == 'Typedef') {
- $stanza['is_relationshiptype'][0] = 'true';
- }
-
-
- if (array_key_exists('is_a', $stanza)) {
- foreach ($stanza['is_a'] as $index => $is_a) {
- $stanza['is_a'][$index] = trim(preg_replace('/\{.+?\}/', '', $is_a));
- }
- }
- if (array_key_exists('relationship', $stanza)) {
- foreach ($stanza['relationship'] as $index => $relationship) {
- $stanza['relationship'][$index] = trim(preg_replace('/\{.+?\}/', '', $relationship));
- }
- }
-
-
- if (array_key_exists('synonym', $stanza)) {
- foreach ($stanza['synonym'] as $index => $synonym) {
- if (preg_match('/\"(.*?)\".*(EXACT|NARROW|BROAD|RELATED)/', $synonym, $matches)) {
- $stanza['synonym'][$index] = '"' . $matches[1] . '" ' . $matches[2];
- }
- }
- }
-
-
-
-
-
- foreach ($stanza as $key => $values) {
- $stanza[$key] = array_unique($values);
- }
-
-
- if ($this->cache_type == 'table') {
-
- $values = [
- 'id' => $id,
- 'stanza' => base64_encode(serialize($stanza)),
- 'type' => $type,
- ];
- $success = chado_insert_record('tripal_obo_temp', $values);
- if (!$success) {
- throw new Exception("Cannot insert stanza into temporary table.");
- }
- return;
- }
-
- $this->termStanzaCache['ids'][$id] = $stanza;
- $this->termStanzaCache['count'][$type]++;
- $this->termStanzaCache['types'][$type][] = $id;
-
- $name = $stanza['name'][0];
- $this->term_names[$name] = 1;
- }
-
- private function getCacheSize($type) {
- if ($this->cache_type == 'table') {
- $sql = "
- SELECT count(*) as num_terms
- FROM {tripal_obo_temp}
- WHERE type = :type
- ";
- $result = chado_query($sql, [':type' => $type])->fetchObject();
- return $result->num_terms;
- }
- return $this->termStanzaCache['count'][$type];
- }
-
- private function getCachedTermStanzas($type) {
- if ($this->cache_type == 'table') {
- $sql = "SELECT id FROM {tripal_obo_temp} WHERE type = 'Typedef' ";
- $typedefs = chado_query($sql);
- return $typedefs;
- }
- return $this->termStanzaCache['types'][$type];
- }
-
- private function clearTermStanzaCache() {
- if ($this->cache_type == 'table') {
- $sql = "DELETE FROM {tripal_obo_temp}";
- chado_query($sql);
- return;
- }
- $this->termStanzaCache = [
- 'ids' => [],
- 'count' => [
- 'Typedef' => 0,
- 'Term' => 0,
- 'Instance' => 0,
- ],
- 'types' => [
- 'Typedef' => [],
- 'Term' => [],
- 'Instance' => [],
- ],
- ];
- }
-
- private function addSynonym($id, $cvterm_id, $synonym) {
- $def = $synonym;
- $syn_type = '';
-
- $matches = [];
- if (preg_match('/\"(.*?)\".*(EXACT|NARROW|BROAD|RELATED)/', $synonym, $matches)) {
- $def = $matches[1];
- $syn_type = strtolower($matches[2]);
- }
-
- if (!$syn_type) {
- $syn_type = 'exact';
- }
- $syn_type_term = $this->syn_types[$syn_type];
- if (!$syn_type_term) {
- throw new Exception(t('Cannot find synonym type: !type', ['!type' => $syn_type]));
- }
-
-
- if (strlen($def) > 255) {
- $def = substr($def, 0, 252) . "...";
- }
-
- $cvtermsynonym = new ChadoRecord('cvtermsynonym');
- $cvtermsynonym->setValues([
- 'cvterm_id' => $cvterm_id,
- 'synonym' => $def,
- ]);
-
-
- try {
-
-
-
-
-
-
-
-
- if (!$cvtermsynonym->find()) {
- $cvtermsynonym->setValue('type_id', $syn_type_term->cvterm_id);
- $cvtermsynonym->insert();
- }
- } catch (Exception $e) {
- throw new Exception(t('Cannot add synonym, "!synonym" to term: !id. ' .
- 'ERROR: !error.',
- ['!synonym' => $def, '!id' => $id, '!error' => $e->getMessage()]));
- }
- }
-
- private function parse($obo_file, &$header) {
-
- $in_header = TRUE;
-
- $stanza = [];
-
- $db_short_name = '';
- $line_num = 0;
- $num_read = 0;
-
- $type = '';
- $filesize = filesize($obo_file);
- $this->setTotalItems($filesize);
- $this->setItemsHandled(0);
- $this->setInterval(5);
-
- $fh = fopen($obo_file, 'r');
- while ($line = fgets($fh)) {
- $line_num++;
- $size = drupal_strlen($line);
- $num_read += $size;
- $line = trim($line);
- $this->setItemsHandled($num_read);
-
- $line = rtrim($line);
-
- $line = preg_replace('/[^(\x20-\x7F)]*/', '', $line);
-
- if (strcmp($line, '') == 0) {
- continue;
- }
-
- $line = preg_replace('/^(.*?)\!.*$/', '\1', $line);
-
- if (preg_match('/^\s*\[/', $line)) {
-
- if ($in_header == TRUE) {
- $this->setDefaults($header);
- $in_header = FALSE;
- }
-
- if (sizeof($stanza) > 0) {
-
- if (array_key_exists('namespace', $stanza)) {
-
-
- if ($this->default_namespace == 'EDAM') {
- $stanza['namespace'][0] = 'EDAM';
- }
- $namespace = $stanza['namespace'][0];
- $cv = $this->all_cvs[$namespace];
- $this->obo_namespaces[$namespace] = $cv->cv_id;
- }
-
-
-
- if (array_key_exists($stanza['name'][0], $this->term_names)) {
- $new_name = $stanza['name'][0] . '(' . $stanza['id'][0] . ')';
- $stanza['name'][0] = $new_name;
- }
- $this->cacheTermStanza($stanza, $type);
- }
-
- $type = preg_replace('/^\s*\[\s*(.+?)\s*\]\s*$/', '\1', $line);
-
- $stanza = [];
- continue;
- }
-
-
- $line = preg_replace('/EDAM_(\w+)/', '\1', $line);
-
- preg_replace("/\\:/", "|-|-|", $line);
- $pair = explode(":", $line, 2);
- $tag = $pair[0];
- $value = ltrim(rtrim($pair[1]));
-
- $matches = [];
- if ($tag == 'id' and preg_match('/^(.+?):.*$/', $value, $matches)) {
- $db_short_name = $matches[1];
- }
- $tag = preg_replace("/\|-\|-\|/", "\:", $tag);
- $value = preg_replace("/\|-\|-\|/", "\:", $value);
- if ($in_header) {
- if (!array_key_exists($tag, $header)) {
- $header[$tag] = [];
- }
- $header[$tag][] = $value;
- }
- else {
- if (!array_key_exists($tag, $stanza)) {
- $stanza[$tag] = [];
- }
- $stanza[$tag][] = $value;
- }
- }
-
- if (sizeof($stanza) > 0) {
-
- if (array_key_exists('namespace', $stanza)) {
- $namespace = $stanza['namespace'][0];
- $cv = $this->all_cvs[$namespace];
- $this->obo_namespaces[$namespace] = $cv->cv_id;
- }
- $this->cacheTermStanza($stanza, $type);
- $this->setItemsHandled($num_read);
- }
-
- $message = t('Found the following namespaces: !namespaces.',
- ['!namespaces' => implode(', ', array_keys($this->obo_namespaces))]);
- foreach ($this->obo_namespaces as $namespace => $cv_id) {
- $this->addCV($namespace);
- }
- $this->logMessage($message);
- }
-
- private function cacheRelationships() {
-
-
-
- $terms = $this->getCachedTermStanzas('Term');
- $count = $this->getCacheSize('Term');
- $this->setTotalItems($count);
- $this->setItemsHandled(0);
- $this->setInterval(25);
-
- $i = 1;
- foreach ($terms as $t) {
-
-
- if ($this->cache_type == 'table') {
- $stanza = unserialize(base64_decode($t->stanza));
- }
- else {
- $stanza = $this->termStanzaCache['ids'][$t];
- }
-
- if (array_key_exists('is_a', $stanza)) {
- foreach ($stanza['is_a'] as $object_term) {
- $rstanza = [];
- $rstanza['id'][] = $object_term;
- $this->cacheTermStanza($rstanza, 'Term');
- }
- }
-
- if (array_key_exists('relationship', $stanza)) {
- foreach ($stanza['relationship'] as $value) {
-
- $rel_term = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
- $object_term = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
- $rstanza = [];
- $rstanza['id'][] = $rel_term;
- $this->cacheTermStanza($rstanza, 'Typedef');
- $rstanza = [];
- $rstanza['id'][] = $object_term;
- $this->cacheTermStanza($rstanza, 'Term');
- }
- }
- }
- $this->setItemsHandled($i++);
-
-
-
- if (!$this->getCachedTermStanza('is_a')) {
- $stanza = [];
- $stanza['id'][0] = 'is_a';
- $stanza['name'][0] = 'is_a';
- $stanza['namespace'][0] = $this->default_namespace;
- $stanza['db_name'][0] = $this->default_db;
- $this->cacheTermStanza($stanza, 'Typedef');
- }
- }
-
- private function addSubset($id, $cvterm_id, $subset) {
- $cvtermprop = new ChadoRecord('cvtermprop');
- $cvtermprop->setValues([
- 'cvterm_id' => $cvterm_id,
- 'type_id' => $this->used_terms['NCIT:C25693'],
- 'value' => $subset,
- ]);
-
-
- try {
- $cvtermprop->insert();
- } catch (Exception $e) {
- throw new Exception(t('Cannot add subset, "!subset" to term: !id. ' .
- 'ERROR: !error.',
- ['!subset' => $subset, '!id' => $id, '!error' => $e->getMessage()]));
- }
- }
-
- private function addDB($dbname, $url = '', $description = '') {
-
- $db = NULL;
- if (array_key_exists($dbname, $this->all_dbs)) {
- $db = $this->all_dbs[$dbname];
- }
- else {
-
- $db = new ChadoRecord('db');
- $values = ['name' => $dbname];
- if ($url) {
- $values['url'] = $url;
- }
- if ($description) {
- $values['description'] = $description;
- }
- $db->setValues($values);
- $db->insert();
- $db = (object) $db->getValues();
- $this->all_dbs[$dbname] = $db;
- }
- return $db;
- }
-
- private function addCV($cvname) {
-
-
-
-
- $cv = NULL;
- if (array_key_exists($cvname, $this->all_cvs)) {
- $cv = $this->all_cvs[$cvname];
- }
- else {
-
- $cv = new ChadoRecord('cv');
- $cv->setValues(['name' => $cvname]);
- $cv->insert();
- $cv = (object) $cv->getValues();
- $this->all_cvs[$cvname] = $cv;
- $this->obo_namespaces[$cvname] = $cv->cv_id;
- }
- return $cv;
- }
-
- private function isTermBorrowed($stanza) {
- $namespace = $stanza['namespace'][0];
- if (array_key_exists($namespace, $this->obo_namespaces)) {
- return FALSE;
- }
- return TRUE;
- }
-
- private function addAltID($id, $cvterm_id, $alt_id) {
- $dbname = '';
- $accession = '';
- $matches = [];
- if (preg_match('/^(.+?):(.*)$/', $alt_id, $matches)) {
- $dbname = $matches[1];
- $accession = $matches[2];
- }
- if (!$accession) {
- $this->logMessage("Cannot add an Alt ID without an accession: '!alt_id'", ['!alt_id' => $alt_id]);
- return;
- }
-
- $db = $this->addDB($dbname);
- $db_id = $db->db_id;
-
- $dbxref = new ChadoRecord('dbxref');
- $dbxref->setValues([
- 'db_id' => $db_id,
- 'accession' => $accession,
- ]);
- if (!$dbxref->find()) {
- $dbxref->insert();
- }
-
- $cvterm_dbxref = new ChadoRecord('cvterm_dbxref');
- $cvterm_dbxref->setValues([
- 'cvterm_id' => $cvterm_id,
- 'dbxref_id' => $dbxref->getID(),
- ]);
- if (!$cvterm_dbxref->find()) {
- $cvterm_dbxref->insert();
- }
- }
-
- private function addXref($id, $cvterm_id, $xref) {
- $dbname = preg_replace('/^(.+?):.*$/', '$1', $xref);
- $accession = preg_replace('/^.+?:\s*(.*?)(\{.+$|\[.+$|\s.+$|\".+$|$)/', '$1', $xref);
- $description = preg_replace('/^.+?\"(.+?)\".*?$/', '$1', $xref);
- $dbxrefs = preg_replace('/^.+?\[(.+?)\].*?$/', '$1', $xref);
- if (!$accession) {
- throw new Exception("Cannot add an xref without an accession: '$xref'");
- }
-
- if (strcmp($dbname, 'http') == 0) {
- return;
- }
-
- $db = $this->addDB($dbname);
- $db_id = $db->db_id;
-
- $dbxref = new ChadoRecord('dbxref');
- $dbxref->setValues([
- 'db_id' => $db_id,
- 'accession' => $accession,
- ]);
- if (!$dbxref->find()) {
- $dbxref->insert();
- }
-
- $cvterm_dbxref = new ChadoRecord('cvterm_dbxref');
- $cvterm_dbxref->setValues([
- 'cvterm_id' => $cvterm_id,
- 'dbxref_id' => $dbxref->getID(),
- ]);
- if (!$cvterm_dbxref->find()) {
- $cvterm_dbxref->insert();
- }
- }
-
- private function addComment($id, $cvterm_id, $comment, $rank) {
-
- $comment_type_id = $this->used_terms['rdfs:comment'];
-
- $cvtermprop = new ChadoRecord('cvtermprop');
- $cvtermprop->setValues([
- 'cvterm_id' => $cvterm_id,
- 'type_id' => $comment_type_id,
- 'value' => $comment,
- 'rank' => $rank,
- ]);
-
-
- try {
- $cvtermprop->insert();
- } catch (Exception $e) {
- throw new Exception(t('Cannot add comment, "!comment" to term: !id. ' .
- 'ERROR: !error.',
- ['!comment' => $comment, '!id' => $id, '!error' => $e->getMessage()]));
- }
- }
-
- private function oboEbiLookup($accession, $type_of_search) {
-
- $parts = explode(':', $accession);
- $ontology = strtolower($parts[0]);
- $ontology = preg_replace('/\s+/', '', $ontology);
- if ($type_of_search == 'ontology') {
- $options = [];
- $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontology;
- $response = drupal_http_request($full_url, $options);
- if (!empty($response)) {
- $response = drupal_json_decode($response->data);
- }
- }
- elseif ($type_of_search == 'term') {
-
- $iri = urlencode(urlencode("http://purl.obolibrary.org/obo/" . str_replace(':', '_', $accession)));
- $options = [];
- $full_url = 'http://www.ebi.ac.uk/ols/api/ontologies/' . $ontology . '/' . 'terms/' . $iri;
- $response = drupal_http_request($full_url, $options);
- if (!empty($response)) {
- $response = drupal_json_decode($response->data);
- }
- }
- elseif ($type_of_search == 'query') {
- $options = [];
- $full_url = 'http://www.ebi.ac.uk/ols/api/search?q=' . $accession . '&queryFields=obo_id&local=true';
- $response = drupal_http_request($full_url, $options);
- if (!empty($response)) {
- $response = drupal_json_decode($response->data);
- }
- }
- elseif ($type_of_search == 'query-non-local') {
- $options = [];
- $full_url = 'http://www.ebi.ac.uk/ols/api/search?q=' . $accession . '&queryFields=obo_id';
- $response = drupal_http_request($full_url, $options);
- if (!empty($response)) {
- $response = drupal_json_decode($response->data);
- }
- }
- return $response;
- }
- }
- function tripal_cv_obo_form_ajax_callback($form, $form_state) {
- return $form['obo_existing'];
- }
|