OBOImporter.inc 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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 = 'Chado OBO 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. public static $file_required = FALSE;
  71. /**
  72. * Keep track of vocabularies that have been added.
  73. *
  74. * @var array
  75. */
  76. private $newcvs = array();
  77. /**
  78. * @see TripalImporter::form()
  79. */
  80. public function form($form, &$form_state) {
  81. // get a list of db from chado for user to choose
  82. $sql = "SELECT * FROM {tripal_cv_obo} ORDER BY name";
  83. $results = db_query($sql);
  84. $obos = array();
  85. $obos[] = 'Select a Vocabulary';
  86. foreach ($results as $obo) {
  87. $obos[$obo->obo_id] = $obo->name;
  88. }
  89. $obo_id = '';
  90. if (array_key_exists('values', $form_state)) {
  91. $obo_id = array_key_exists('obo_id', $form_state['values']) ? $form_state['values']['obo_id'] : '';
  92. }
  93. $form['instructions']['info'] = array(
  94. '#type' => 'item',
  95. '#markup' => t('This page allows you to load vocabularies and ontologies
  96. that are in OBO format. Once loaded, the terms from these
  97. vocabularies can be used to create content.
  98. You may use the form below to either reload a vocabulary that is already
  99. loaded (as when new updates to that vocabulary are available) or load a new
  100. vocabulary.'),
  101. );
  102. $form['obo_existing'] = array(
  103. '#type' => 'fieldset',
  104. '#title' => t('Use a Saved Ontology OBO Reference'),
  105. '#prefix' => '<span id="obo-existing-fieldset">',
  106. '#suffix' => '</span>'
  107. );
  108. $form['obo_existing']['existing_instructions']= array(
  109. '#type' => 'item',
  110. '#markup' => t('The vocabularies listed in the select box below have bene pre-populated
  111. upon installation of Tripal or have been previously loaded. Select one to edit
  112. its settings or submit for loading. You may reload any vocabulary that has
  113. already been loaded to retrieve any new updates.'),
  114. );
  115. $form['obo_existing']['obo_id'] = array(
  116. '#title' => t('Ontology OBO File Reference'),
  117. '#type' => 'select',
  118. '#options' => $obos,
  119. '#ajax' => array(
  120. 'callback' => 'tripal_cv_obo_form_ajax_callback',
  121. 'wrapper' => 'obo-existing-fieldset',
  122. ),
  123. '#description' => t('Select a vocabulary to import.')
  124. );
  125. // If the user has selected an OBO ID then get the form elements for
  126. // updating.
  127. if ($obo_id) {
  128. $uobo_name = '';
  129. $uobo_url = '';
  130. $uobo_file = '';
  131. $vocab = db_select('tripal_cv_obo', 't')
  132. ->fields('t', array('name', 'path'))
  133. ->condition('obo_id', $obo_id)
  134. ->execute()
  135. ->fetchObject();
  136. $uobo_name = $vocab->name;
  137. if (preg_match('/^http/', $vocab->path)) {
  138. $uobo_url = $vocab->path;
  139. }
  140. else {
  141. $uobo_file = trim($vocab->path);
  142. $matches = array();
  143. if (preg_match('/\{(.*?)\}/', $uobo_file, $matches)) {
  144. $modpath = drupal_get_path('module', $matches[1]);
  145. $uobo_file = preg_replace('/\{.*?\}/', $modpath, $uobo_file);
  146. }
  147. }
  148. // We don't want the previous value to remain. We want the new default to
  149. // show up, so remove the input values
  150. unset($form_state['input']['uobo_name']);
  151. unset($form_state['input']['uobo_url']);
  152. unset($form_state['input']['uobo_file']);
  153. $form['obo_existing']['uobo_name']= array(
  154. '#type' => 'textfield',
  155. '#title' => t('Vocabulary Name'),
  156. '#description' => t('Please provide a name for this vocabulary. After upload, this name will appear in the drop down
  157. list above for use again later.'),
  158. '#default_value' => $uobo_name,
  159. );
  160. $form['obo_existing']['uobo_url']= array(
  161. '#type' => 'textfield',
  162. '#title' => t('Remote URL'),
  163. '#description' => t('Please enter a URL for the online OBO file. The file will be downloaded and parsed.
  164. (e.g. http://www.obofoundry.org/ro/ro.obo)'),
  165. '#default_value' => $uobo_url,
  166. );
  167. $form['obo_existing']['uobo_file']= array(
  168. '#type' => 'textfield',
  169. '#title' => t('Local File'),
  170. '#description' => t('Please enter the file system path for an OBO
  171. definition file. If entering a path relative to
  172. the Drupal installation you may use a relative path that excludes the
  173. Drupal installation directory (e.g. sites/default/files/xyz.obo). Note
  174. that Drupal relative paths have no preceeding slash.
  175. Otherwise, please provide the full path on the filesystem. The path
  176. must be accessible to the web server on which this Drupal instance is running.'),
  177. '#default_value' => $uobo_file,
  178. );
  179. $form['obo_existing']['update_obo_details'] = array(
  180. '#type' => 'submit',
  181. '#value' => 'Update Ontology Details',
  182. '#name' => 'update_obo_details'
  183. );
  184. }
  185. $form['obo_new'] = array(
  186. '#type' => 'fieldset',
  187. '#title' => t('Add a New Ontology OBO Reference'),
  188. '#collapsible' => TRUE,
  189. '#collapsed' => TRUE,
  190. );
  191. $form['obo_new']['path_instructions']= array(
  192. '#value' => t('Provide the name and path for the OBO file. If the vocabulary OBO file
  193. is stored local to the server provide a file name. If the vocabulry is stored remotely,
  194. provide a URL. Only provide a URL or a local file, not both.'),
  195. );
  196. $form['obo_new']['obo_name']= array(
  197. '#type' => 'textfield',
  198. '#title' => t('New Vocabulary Name'),
  199. '#description' => t('Please provide a name for this vocabulary. After upload, this name will appear in the drop down
  200. list above for use again later.'),
  201. );
  202. $form['obo_new']['obo_url']= array(
  203. '#type' => 'textfield',
  204. '#title' => t('Remote URL'),
  205. '#description' => t('Please enter a URL for the online OBO file. The file will be downloaded and parsed.
  206. (e.g. http://www.obofoundry.org/ro/ro.obo)'),
  207. );
  208. $form['obo_new']['obo_file']= array(
  209. '#type' => 'textfield',
  210. '#title' => t('Local File'),
  211. '#description' => t('Please enter the file system path for an OBO
  212. definition file. If entering a path relative to
  213. the Drupal installation you may use a relative path that excludes the
  214. Drupal installation directory (e.g. sites/default/files/xyz.obo). Note
  215. that Drupal relative paths have no preceeding slash.
  216. Otherwise, please provide the full path on the filesystem. The path
  217. must be accessible to the web server on which this Drupal instance is running.'),
  218. );
  219. return $form;
  220. }
  221. /**
  222. * @see TripalImporter::formSubmit()
  223. */
  224. public function formSubmit($form, &$form_state) {
  225. $obo_id = $form_state['values']['obo_id'];
  226. $obo_name = trim($form_state['values']['obo_name']);
  227. $obo_url = trim($form_state['values']['obo_url']);
  228. $obo_file = trim($form_state['values']['obo_file']);
  229. $uobo_name = array_key_exists('uobo_name', $form_state['values']) ? trim($form_state['values']['uobo_name']) : '';
  230. $uobo_url = array_key_exists('uobo_url', $form_state['values']) ? trim($form_state['values']['uobo_url']) : '';
  231. $uobo_file = array_key_exists('uobo_file', $form_state['values']) ? trim($form_state['values']['uobo_file']) : '';
  232. // If the user requested to alter the details then do that.
  233. if ($form_state['clicked_button']['#name'] == 'update_obo_details') {
  234. $form_state['rebuild'] = TRUE;
  235. $success = db_update('tripal_cv_obo')
  236. ->fields(array(
  237. 'name' => $uobo_name,
  238. 'path' => $uobo_url ? $uobo_url : $uobo_file,
  239. ))
  240. ->condition('obo_id', $obo_id)
  241. ->execute();
  242. if ($success) {
  243. drupal_set_message(t("The vocabulary !vocab has been updated.", array('!vocab' => $uobo_name)));
  244. }
  245. else {
  246. drupal_set_message(t("The vocabulary !vocab could not be updated.", array('!vocab' => $uobo_name)), 'error');
  247. }
  248. }
  249. else if (!empty($obo_name)) {
  250. $obo_id = db_insert('tripal_cv_obo')
  251. ->fields(array(
  252. 'name' => $obo_name,
  253. 'path' => $obo_url ? $obo_url : $obo_file,
  254. ))
  255. ->execute();
  256. // Add the obo_id to the form_state vaules.
  257. $form_state['values']['obo_id'] = $obo_id;
  258. if ($obo_id) {
  259. drupal_set_message(t("The vocabulary !vocab has been added.", array('!vocab' => $obo_name)));
  260. }
  261. else {
  262. $form_state['rebuild'] = TRUE;
  263. drupal_set_message(t("The vocabulary !vocab could not be added.", array('!vocab' => $obo_name)), 'error');
  264. }
  265. }
  266. }
  267. /**
  268. * @see TripalImporter::formValidate()
  269. */
  270. public function formValidate($form, &$form_state) {
  271. $obo_id = $form_state['values']['obo_id'];
  272. $obo_name = trim($form_state['values']['obo_name']);
  273. $obo_url = trim($form_state['values']['obo_url']);
  274. $obo_file = trim($form_state['values']['obo_file']);
  275. $uobo_name = array_key_exists('uobo_name', $form_state['values']) ? trim($form_state['values']['uobo_name']) : '';
  276. $uobo_url = array_key_exists('uobo_url', $form_state['values']) ? trim($form_state['values']['uobo_url']) : '';
  277. $uobo_file = array_key_exists('uobo_file', $form_state['values']) ? trim($form_state['values']['uobo_file']) : '';
  278. // Make sure if the name is changed it doesn't conflict with another OBO.
  279. if ($form_state['clicked_button']['#name'] == 'update_obo_details' or
  280. $form_state['clicked_button']['#name'] == 'update_load_obo') {
  281. // Get the current record
  282. $vocab = db_select('tripal_cv_obo', 't')
  283. ->fields('t', array('obo_id', 'name', 'path'))
  284. ->condition('name', $uobo_name)
  285. ->execute()
  286. ->fetchObject();
  287. if ($vocab and $vocab->obo_id != $obo_id) {
  288. form_set_error('uobo_name', 'The vocabulary name must be different from existing vocabularies');
  289. }
  290. // Make sure the file exists. First check if it is a relative path
  291. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $uobo_file;
  292. if (!file_exists($dfile)) {
  293. if (!file_exists($uobo_file)) {
  294. form_set_error('uobo_file', 'The specified path does not exist or cannot be read.');
  295. }
  296. }
  297. if (!$uobo_url and !$uobo_file) {
  298. form_set_error('uobo_url', 'Please provide a URL or a path for the vocabulary.');
  299. }
  300. if ($uobo_url and $uobo_file) {
  301. form_set_error('uobo_url', 'Please provide only a URL or a path for the vocabulary, but not both.');
  302. }
  303. }
  304. if ($form_state['clicked_button']['#name'] == 'add_new_obo') {
  305. // Get the current record
  306. $vocab = db_select('tripal_cv_obo', 't')
  307. ->fields('t', array('obo_id', 'name', 'path'))
  308. ->condition('name', $obo_name)
  309. ->execute()
  310. ->fetchObject();
  311. if ($vocab) {
  312. form_set_error('obo_name', 'The vocabulary name must be different from existing vocabularies');
  313. }
  314. // Make sure the file exists. First check if it is a relative path
  315. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo_file;
  316. if (!file_exists($dfile)) {
  317. if (!file_exists($obo_file)) {
  318. form_set_error('obo_file', 'The specified path does not exist or cannot be read.');
  319. }
  320. }
  321. if (!$obo_url and !$obo_file) {
  322. form_set_error('obo_url', 'Please provide a URL or a path for the vocabulary.');
  323. }
  324. if ($obo_url and $obo_file) {
  325. form_set_error('obo_url', 'Please provide only a URL or a path for the vocabulary, but not both.');
  326. }
  327. }
  328. }
  329. /**
  330. * @see TripalImporter::run()
  331. *
  332. * @param $details
  333. * The following arguments are supported:
  334. * - obo_id: (required) The ID of the ontology to be imported.
  335. */
  336. public function run() {
  337. $arguments = $this->arguments['run_args'];
  338. $obo_id = $arguments['obo_id'];
  339. // Make sure the $obo_id is valid
  340. $obo = db_select('tripal_cv_obo', 'tco')
  341. ->fields('tco')
  342. ->condition('obo_id', $obo_id)
  343. ->execute()
  344. ->fetchObject();
  345. if (!$obo) {
  346. throw new Exception("Invalid OBO ID provided: '$obo_id'.");
  347. }
  348. $this->loadOBO_v1_2_id($obo);
  349. }
  350. /**
  351. * @see TripalImporter::postRun()
  352. *
  353. */
  354. public function postRun() {
  355. $this->load_cvtermpath($this->newcvs);
  356. }
  357. /**
  358. * A wrapper function for importing the user specified OBO file into Chado by
  359. * specifying the obo_id of the OBO. It requires that the file be in OBO v1.2
  360. * compatible format. This function is typically executed via the Tripal jobs
  361. * management after a user submits a job via the Load Onotloies form.
  362. *
  363. * @param $obo_id
  364. * An obo_id from the tripal_cv_obo file that specifies which OBO file to import
  365. * @ingroup tripal_obo_loader
  366. */
  367. private function loadOBO_v1_2_id($obo) {
  368. // Convert the module name to the real path if present
  369. if (preg_match("/\{(.*?)\}/", $obo->path, $matches)) {
  370. $module = $matches[1];
  371. $path = drupal_realpath(drupal_get_path('module', $module));
  372. $obo->path = preg_replace("/\{.*?\}/", $path, $obo->path);
  373. }
  374. // if the reference is for a remote URL then run the URL processing function
  375. if (preg_match("/^https:\/\//", $obo->path) or
  376. preg_match("/^http:\/\//", $obo->path) or
  377. preg_match("/^ftp:\/\//", $obo->path)) {
  378. $this->loadOBO_v1_2_url($obo->name, $obo->path, 0);
  379. }
  380. // if the reference is for a local file then run the file processing function
  381. else {
  382. // check to see if the file is located local to Drupal
  383. $dfile = $_SERVER['DOCUMENT_ROOT'] . base_path() . $obo->path;
  384. if (file_exists($dfile)) {
  385. $this->loadOBO_v1_2_file($obo->name, $dfile, 0);
  386. }
  387. // if not local to Drupal, the file must be someplace else, just use
  388. // the full path provided
  389. else {
  390. if (file_exists($obo->path)) {
  391. $this->loadOBO_v1_2_file($obo->name, $obo->path, 0);
  392. }
  393. else {
  394. print "ERROR: could not find OBO file: '$obo->path'\n";
  395. }
  396. }
  397. }
  398. }
  399. /**
  400. * A wrapper function for importing the user specified OBO file into Chado by
  401. * specifying the filename and path of the OBO. It requires that the file be in OBO v1.2
  402. * compatible format. This function is typically executed via the Tripal jobs
  403. * management after a user submits a job via the Load Onotloies form.
  404. *
  405. * @param $obo_name
  406. * The name of the OBO (typially the ontology or controlled vocabulary name)
  407. * @param $file
  408. * The path on the file system where the ontology can be found
  409. * @param $is_new
  410. * Set to TRUE if this is a new ontology that does not yet exist in the
  411. * tripal_cv_obo table. If TRUE the OBO will be added to the table.
  412. *
  413. * @ingroup tripal_obo_loader
  414. */
  415. private function loadOBO_v1_2_file($obo_name, $file, $is_new = TRUE) {
  416. if ($is_new) {
  417. tripal_insert_obo($obo_name, $file);
  418. }
  419. $success = $this->loadOBO_v1_2($file, $this->newcvs);
  420. }
  421. /**
  422. * A wrapper function for importing the user specified OBO file into Chado by
  423. * specifying the remote URL of the OBO. It requires that the file be in OBO v1.2
  424. * compatible format. This function is typically executed via the Tripal jobs
  425. * management after a user submits a job via the Load Onotloies form.
  426. *
  427. * @param $obo_name
  428. * The name of the OBO (typially the ontology or controlled vocabulary name)
  429. * @param $url
  430. * The remote URL of the OBO file.
  431. * @param $is_new
  432. * Set to TRUE if this is a new ontology that does not yet exist in the
  433. * tripal_cv_obo table. If TRUE the OBO will be added to the table.
  434. *
  435. * @ingroup tripal_obo_loader
  436. */
  437. private function loadOBO_v1_2_url($obo_name, $url, $is_new = TRUE) {
  438. $newcvs = array();
  439. // first download the OBO
  440. $temp = tempnam(sys_get_temp_dir(), 'obo_');
  441. print "Downloading URL $url, saving to $temp\n";
  442. $url_fh = fopen($url, "r");
  443. $obo_fh = fopen($temp, "w");
  444. if (!$url_fh) {
  445. throw new Exception("Unable to download the remote OBO file at $url. Could a firewall be blocking outgoing connections? " .
  446. " if you are unable to download the file you may manually downlod the OBO file and use the web interface to " .
  447. " specify the location of the file on your server.");
  448. }
  449. while (!feof($url_fh)) {
  450. fwrite($obo_fh, fread($url_fh, 255), 255);
  451. }
  452. fclose($url_fh);
  453. fclose($obo_fh);
  454. if ($is_new) {
  455. tripal_insert_obo($obo_name, $url);
  456. }
  457. // second, parse the OBO
  458. $this->loadOBO_v1_2($temp, $newcvs);
  459. // update the cvtermpath table
  460. $this->load_cvtermpath($newcvs);
  461. // now remove the temp file
  462. unlink($temp);
  463. }
  464. /**
  465. * A function for executing the cvtermpath function of Chado. This function
  466. * populates the cvtermpath table of Chado for quick lookup of term
  467. * relationships
  468. *
  469. * @param $newcvs
  470. * An associative array of controlled vocabularies to update. The key must be
  471. * the name of the vocabulary and the value the cv_id from the cv table of chado.
  472. *
  473. * @ingroup tripal_obo_loader
  474. */
  475. private function load_cvtermpath($newcvs) {
  476. print "\nUpdating cvtermpath table. This may take a while...\n";
  477. foreach ($newcvs as $namespace => $cvid) {
  478. tripal_update_cvtermpath($cvid);
  479. }
  480. }
  481. /**
  482. * Imports a given OBO file into Chado. This function is usually called by
  483. * one of three wrapper functions: loadOBO_v1_2_id,
  484. * loadOBO_v1_2_file or tirpal_cv_load_obo_v1_2_url. But, it can
  485. * be called directly if the full path to an OBO file is available on the
  486. * file system.
  487. *
  488. * @param $flie
  489. * The full path to the OBO file on the file system
  490. * @param $newcvs
  491. * An empty array passed by reference that upon return will contain the list
  492. * of newly added vocabularies. The key will contain the CV name and the
  493. * value the new cv_id
  494. *
  495. *
  496. * @ingroup tripal_obo_loader
  497. */
  498. private function loadOBO_v1_2($file, &$newcvs) {
  499. $header = array();
  500. $ret = array();
  501. // Empty the temp table.
  502. $sql = "DELETE FROM {tripal_obo_temp}";
  503. chado_query($sql);
  504. $this->logMessage("Step 1: Preloading File $file...");
  505. // parse the obo file
  506. $default_db = $this->parse($file, $header);
  507. // Add the CV for this ontology to the database. The v1.2 definition
  508. // specifies a 'default-namespace' to be used if a 'namespace' is not
  509. // present for each stanza. Some ontologies have adopted the v1.4 method
  510. // in their v1.2 files and not including it.
  511. if (array_key_exists('default-namespace', $header)) {
  512. $defaultcv = tripal_insert_cv($header['default-namespace'][0], '');
  513. if (!$defaultcv) {
  514. throw new Exception('Cannot add namespace ' . $header['default-namespace'][0]);
  515. }
  516. $newcvs[$header['default-namespace'][0]] = $defaultcv->cv_id;
  517. }
  518. // If the 'default-namespace' is missing.
  519. else {
  520. // Look to see if an 'ontology' key is present. It is part of the v1.4
  521. // specification so it shouldn't be in the file, but just in case
  522. if (array_key_exists('ontology', $header)) {
  523. $defaultcv = tripal_insert_cv(strtoupper($header['ontology'][0]), '');
  524. if (!$defaultcv) {
  525. throw new Exception('Cannot add namespace ' . strtoupper($header['ontology'][0]));
  526. }
  527. $newcvs[strtoupper(strtoupper($header['ontology'][0]))] = $defaultcv->cv_id;
  528. }
  529. else {
  530. throw new Exception("Could not find a namespace for this OBO file: $file");
  531. }
  532. $this->logMessage("This OBO is missing the 'default-namespace' header. It " .
  533. "is not possible to determine which vocabulary terms without a 'namespace' key " .
  534. "should go. Instead, those terms will be placed in the '!vocab' vocabulary.",
  535. array('!vocab' => $defaultcv->name), TRIPAL_WARNING);
  536. }!
  537. // Add any typedefs to the vocabulary first.
  538. $this->logMessage("Step 2: Loading type defs...");
  539. $this->loadTypeDefs($defaultcv, $newcvs, $default_db);
  540. // Next add terms to the vocabulary.
  541. $this->logMessage("Step 3: Loading terms...");
  542. if (!$this->processTerms($defaultcv, $newcvs, $default_db)) {
  543. throw new Exception('Cannot add terms from this ontology');
  544. }
  545. }
  546. /**
  547. * OBO files are divided into a typedefs terms section and vocabulary terms section.
  548. * This function loads the typedef terms from the OBO.
  549. *
  550. * @param $defaultcv
  551. * A database object containing a record from the cv table for the
  552. * default controlled vocabulary
  553. * @param $newcvs
  554. * An associative array of controlled vocabularies for this OBO. The key must be
  555. * the name of the vocabulary and the value the cv_id from the cv table of chado.
  556. * @param $default_db
  557. * The name of the default database.
  558. *
  559. * @ingroup tripal_obo_loader
  560. */
  561. private function loadTypeDefs($defaultcv, $newcvs, $default_db) {
  562. $sql = "SELECT * FROM {tripal_obo_temp} WHERE type = 'Typedef' ";
  563. $typedefs = chado_query($sql);
  564. $sql = "
  565. SELECT count(*) as num_terms
  566. FROM {tripal_obo_temp}
  567. WHERE type = 'Typedef'
  568. ";
  569. $result = chado_query($sql)->fetchObject();
  570. $count = $result->num_terms;
  571. $this->setTotalItems($count);
  572. $this->setItemsHandled(0);
  573. $i = 0;
  574. foreach ($typedefs as $typedef) {
  575. $this->setItemsHandled($i);
  576. $term = unserialize(base64_decode($typedef->stanza));
  577. $this->processTerm($term, $defaultcv->name, 1, $newcvs, $default_db);
  578. $i++;
  579. }
  580. $this->setItemsHandled($i);
  581. return 1;
  582. }
  583. /**
  584. * OBO files are divided into a typedefs section and a terms section.
  585. *
  586. * This function loads the typedef terms from the OBO.
  587. *
  588. * @param $defaultcv
  589. * A database object containing a record from the cv table for the
  590. * default controlled vocabulary
  591. * @param $newcvs
  592. * An associative array of controlled vocabularies for this OBO. The key must be
  593. * the name of the vocabulary and the value the cv_id from the cv table of chado.
  594. * @param $default_db
  595. * The name of the default database.
  596. */
  597. private function processTerms($defaultcv, &$newcvs, $default_db) {
  598. $i = 0;
  599. // Iterate through each term from the OBO file and add it.
  600. $sql = "
  601. SELECT * FROM {tripal_obo_temp}
  602. WHERE type = 'Term'
  603. ORDER BY id
  604. ";
  605. $terms = chado_query($sql);
  606. $sql = "
  607. SELECT count(*) as num_terms
  608. FROM {tripal_obo_temp}
  609. WHERE type = 'Term'
  610. ";
  611. $result = chado_query($sql)->fetchObject();
  612. $count = $result->num_terms;
  613. $this->setTotalItems($count);
  614. $this->setItemsHandled(0);
  615. // Iterate through the terms.
  616. foreach ($terms as $t) {
  617. $term = unserialize(base64_decode($t->stanza));
  618. $this->setItemsHandled($i);
  619. // Add/update this term.
  620. if (!$this->processTerm($term, $defaultcv->name, 0, $newcvs, $default_db)) {
  621. throw new Exception("Failed to process terms from the ontology");
  622. }
  623. $i++;
  624. }
  625. $this->setItemsHandled($i);
  626. return 1;
  627. }
  628. /**
  629. * Uses the provided term array to add/update information to Chado about the
  630. * term including the term, dbxref, synonyms, properties, and relationships.
  631. *
  632. * @param $term
  633. * An array representing the cvterm.
  634. * @param $defaultcv
  635. * The name of the default controlled vocabulary
  636. * @is_relationship
  637. * Set to 1 if this term is a relationship term
  638. * @default_db
  639. * The name of the default database.
  640. *
  641. * @ingroup tripal_obo_loader
  642. */
  643. private function processTerm($term, $defaultcv, $is_relationship = 0, &$newcvs, $default_db) {
  644. // make sure we have a namespace for this term
  645. if (!array_key_exists('namespace', $term) and !($defaultcv or $defaultcv == '')) {
  646. throw new Exception("Cannot add the term: no namespace defined. " . $term['id'][0]);
  647. }
  648. // construct the term array for sending to the tripal_chado_add_cvterm function
  649. // for adding a new cvterm
  650. $t = array();
  651. $t['id'] = $term['id'][0];
  652. $t['name'] = $term['name'][0];
  653. if (array_key_exists('def', $term)) {
  654. $t['definition'] = $term['def'][0];
  655. }
  656. if (array_key_exists('subset', $term)) {
  657. $t['subset'] = $term['subset'][0];
  658. }
  659. if (array_key_exists('namespace', $term)) {
  660. $t['namespace'] = $term['namespace'][0];
  661. }
  662. if (array_key_exists('is_obsolete', $term)) {
  663. $t['is_obsolete'] = $term['is_obsolete'][0];
  664. }
  665. $t['cv_name'] = $defaultcv;
  666. $t['is_relationship'] = $is_relationship;
  667. $t['db_name'] = $default_db;
  668. // add the cvterm
  669. $cvterm = tripal_insert_cvterm($t, array('update_existing' => TRUE));
  670. if (!$cvterm) {
  671. throw new Exception("Cannot add the term " . $term['id'][0]);
  672. }
  673. // Remove any relationships that this term already has (in case it was
  674. // updated) and we'll re-add them.
  675. $sql = "
  676. DELETE FROM {cvterm_relationship} CVTR
  677. WHERE CVTR.subject_id = :cvterm_id
  678. ";
  679. chado_query($sql, array(':cvterm_id' => $cvterm->cvterm_id));
  680. if (array_key_exists('namespace', $term)) {
  681. $newcvs[$term['namespace'][0]] = $cvterm->cv_id;
  682. }
  683. // now handle other properites
  684. if (array_key_exists('is_anonymous', $term)) {
  685. //print "WARNING: unhandled tag: is_anonymous\n";
  686. }
  687. if (array_key_exists('alt_id', $term)) {
  688. foreach ($term['alt_id'] as $alt_id) {
  689. if (!$this->addCvtermDbxref($cvterm, $alt_id)) {
  690. throw new Exception("Cannot add alternate id $alt_id");
  691. }
  692. }
  693. }
  694. if (array_key_exists('subset', $term)) {
  695. //print "WARNING: unhandled tag: subset\n";
  696. }
  697. // add synonyms for this cvterm
  698. if (array_key_exists('synonym', $term)) {
  699. if (!$this->addSynonym($term, $cvterm)) {
  700. throw new Exception("Cannot add synonyms");
  701. }
  702. }
  703. // reformat the deprecated 'exact_synonym, narrow_synonym, and broad_synonym'
  704. // types to be of the v1.2 standard
  705. if (array_key_exists('exact_synonym', $term) or array_key_exists('narrow_synonym', $term) or array_key_exists('broad_synonym', $term)) {
  706. if (array_key_exists('exact_synonym', $term)) {
  707. foreach ($term['exact_synonym'] as $synonym) {
  708. $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 EXACT $2', $synonym);
  709. $term['synonym'][] = $new;
  710. }
  711. }
  712. if (array_key_exists('narrow_synonym', $term)) {
  713. foreach ($term['narrow_synonym'] as $synonym) {
  714. $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 NARROW $2', $synonym);
  715. $term['synonym'][] = $new;
  716. }
  717. }
  718. if (array_key_exists('broad_synonym', $term)) {
  719. foreach ($term['broad_synonym'] as $synonym) {
  720. $new = preg_replace('/^\s*(\".+?\")(.*?)$/', '$1 BROAD $2', $synonym);
  721. $term['synonym'][] = $new;
  722. }
  723. }
  724. if (!$this->addSynonym($term, $cvterm)) {
  725. throw new Exception("Cannot add/update synonyms");
  726. }
  727. }
  728. // add the comment to the cvtermprop table
  729. if (array_key_exists('comment', $term)) {
  730. $comments = $term['comment'];
  731. $j = 0;
  732. foreach ($comments as $comment) {
  733. if (!$this->addCvtermProp($cvterm, 'comment', $comment, $j)) {
  734. throw new Exception("Cannot add/update cvterm property");
  735. }
  736. $j++;
  737. }
  738. }
  739. // add any other external dbxrefs
  740. if (array_key_exists('xref', $term)) {
  741. foreach ($term['xref'] as $xref) {
  742. if (!$this->addCvtermDbxref($cvterm, $xref)) {
  743. throw new Exception("Cannot add/update cvterm database reference (dbxref).");
  744. }
  745. }
  746. }
  747. if (array_key_exists('xref_analog', $term)) {
  748. foreach ($term['xref_analog'] as $xref) {
  749. if (!$this->addCvtermDbxref($cvterm, $xref)) {
  750. throw new Exception("Cannot add/update cvterm database reference (dbxref).");
  751. }
  752. }
  753. }
  754. if (array_key_exists('xref_unk', $term)) {
  755. foreach ($term['xref_unk'] as $xref) {
  756. if (!$this->addCvtermDbxref($cvterm, $xref)) {
  757. throw new Exception("Cannot add/update cvterm database reference (dbxref).");
  758. }
  759. }
  760. }
  761. // add is_a relationships for this cvterm
  762. if (array_key_exists('is_a', $term)) {
  763. foreach ($term['is_a'] as $is_a) {
  764. if (!$this->addRelationship($cvterm, $defaultcv, 'is_a', $is_a, $is_relationship, $default_db)) {
  765. throw new Exception("Cannot add relationship is_a: $is_a");
  766. }
  767. }
  768. }
  769. if (array_key_exists('intersection_of', $term)) {
  770. //print "WARNING: unhandled tag: intersection_of\n";
  771. }
  772. if (array_key_exists('union_of', $term)) {
  773. //print "WARNING: unhandled tag: union_on\n";
  774. }
  775. if (array_key_exists('disjoint_from', $term)) {
  776. //print "WARNING: unhandled tag: disjoint_from\n";
  777. }
  778. if (array_key_exists('relationship', $term)) {
  779. foreach ($term['relationship'] as $value) {
  780. $rel = preg_replace('/^(.+?)\s.+?$/', '\1', $value);
  781. $object = preg_replace('/^.+?\s(.+?)$/', '\1', $value);
  782. if (!$this->addRelationship($cvterm, $defaultcv, $rel, $object, $is_relationship, $default_db)) {
  783. throw new Exception("Cannot add relationship $rel: $object");
  784. }
  785. }
  786. }
  787. if (array_key_exists('replaced_by', $term)) {
  788. //print "WARNING: unhandled tag: replaced_by\n";
  789. }
  790. if (array_key_exists('consider', $term)) {
  791. //print "WARNING: unhandled tag: consider\n";
  792. }
  793. if (array_key_exists('use_term', $term)) {
  794. //print "WARNING: unhandled tag: user_term\n";
  795. }
  796. if (array_key_exists('builtin', $term)) {
  797. //print "WARNING: unhandled tag: builtin\n";
  798. }
  799. return 1;
  800. }
  801. /**
  802. * Adds a cvterm relationship
  803. *
  804. * @param $cvterm
  805. * A database object for the cvterm
  806. * @param $rel
  807. * The relationship name
  808. * @param $objname
  809. * The relationship term name
  810. * @param $defaultcv
  811. * A database object containing a record from the cv table for the
  812. * default controlled vocabulary
  813. * @object_is_relationship
  814. * Set to 1 if this term is a relationship term
  815. * @default_db
  816. * The name of the default database.
  817. *
  818. * @ingroup tripal_obo_loader
  819. */
  820. private function addRelationship($cvterm, $defaultcv, $rel,
  821. $objname, $object_is_relationship = 0, $default_db = 'OBO_REL') {
  822. // Make sure the relationship cvterm exists.
  823. $term = array(
  824. 'name' => $rel,
  825. 'id' => "$default_db:$rel",
  826. 'definition' => '',
  827. 'is_obsolete' => 0,
  828. 'cv_name' => $defaultcv,
  829. 'is_relationship' => TRUE,
  830. 'db_name' => $default_db
  831. );
  832. $relcvterm = tripal_insert_cvterm($term, array('update_existing' => FALSE));
  833. if (!$relcvterm) {
  834. // If the relationship term couldn't be found in the default_db provided
  835. // then do on more check to find it in the relationship ontology
  836. $term = array(
  837. 'name' => $rel,
  838. 'id' => "OBO_REL:$rel",
  839. 'definition' => '',
  840. 'is_obsolete' => 0,
  841. 'cv_name' => $defaultcv,
  842. 'is_relationship' => TRUE,
  843. 'db_name' => 'OBO_REL'
  844. );
  845. $relcvterm = tripal_insert_cvterm($term, array('update_existing' => FALSE));
  846. if (!$relcvterm) {
  847. throw new Exception("Cannot find the relationship term in the current ontology or in the relationship ontology: $rel\n");
  848. }
  849. }
  850. // Get the object term.
  851. $oterm = $this->getTerm($objname);
  852. if (!$oterm) {
  853. throw new Exception("Could not find object term $objname\n");
  854. }
  855. $objterm = array();
  856. $objterm['id'] = $oterm['id'][0];
  857. $objterm['name'] = $oterm['name'][0];
  858. if (array_key_exists('def', $oterm)) {
  859. $objterm['definition'] = $oterm['def'][0];
  860. }
  861. if (array_key_exists('subset', $oterm)) {
  862. $objterm['subset'] = $oterm['subset'][0];
  863. }
  864. if (array_key_exists('namespace', $oterm)) {
  865. $objterm['namespace'] = $oterm['namespace'][0];
  866. }
  867. if (array_key_exists('is_obsolete', $oterm)) {
  868. $objterm['is_obsolete'] = $oterm['is_obsolete'][0];
  869. }
  870. $objterm['cv_name' ] = $defaultcv;
  871. $objterm['is_relationship'] = $object_is_relationship;
  872. $objterm['db_name'] = $default_db;
  873. $objcvterm = tripal_insert_cvterm($objterm, array('update_existing' => TRUE));
  874. if (!$objcvterm) {
  875. throw new Exception("Cannot add cvterm " . $oterm['name'][0]);
  876. }
  877. // check to see if the cvterm_relationship already exists, if not add it
  878. $values = array(
  879. 'type_id' => $relcvterm->cvterm_id,
  880. 'subject_id' => $cvterm->cvterm_id,
  881. 'object_id' => $objcvterm->cvterm_id
  882. );
  883. $result = chado_select_record('cvterm_relationship', array('*'), $values);
  884. if (count($result) == 0) {
  885. $options = array('return_record' => FALSE);
  886. $success = chado_insert_record('cvterm_relationship', $values, $options);
  887. if (!$success) {
  888. throw new Exception("Cannot add term relationship: '$cvterm->name' $rel '$objcvterm->name'");
  889. }
  890. }
  891. return TRUE;
  892. }
  893. /**
  894. * Retreives the term array from the temp loading table for a given term id.
  895. *
  896. * @param id
  897. * The id of the term to retrieve
  898. *
  899. * @ingroup tripal_obo_loader
  900. */
  901. private function getTerm($id) {
  902. $values = array('id' => $id);
  903. $result = chado_select_record('tripal_obo_temp', array('stanza'), $values);
  904. if (count($result) == 0) {
  905. return FALSE;
  906. }
  907. return unserialize(base64_decode($result[0]->stanza));
  908. }
  909. /**
  910. * Adds the synonyms to a term
  911. *
  912. * @param term
  913. * An array representing the cvterm. It must have a 'synonym' key/value pair.
  914. * @param cvterm
  915. * The database object of the cvterm to which the synonym will be added.
  916. *
  917. * @ingroup tripal_obo_loader
  918. */
  919. private function addSynonym($term, $cvterm) {
  920. // make sure we have a 'synonym_type' vocabulary
  921. $syncv = tripal_insert_cv(
  922. 'synonym_type',
  923. 'A local vocabulary added for synonym types.'
  924. );
  925. // now add the synonyms
  926. if (array_key_exists('synonym', $term)) {
  927. foreach ($term['synonym'] as $synonym) {
  928. // separate out the synonym definition and the synonym type
  929. $def = preg_replace('/^\s*"(.*)"\s*.*$/', '\1', $synonym);
  930. // the scope will be 'EXACT', etc...
  931. $scope = drupal_strtolower(preg_replace('/^.*"\s+(.*?)\s+.*$/', '\1', $synonym));
  932. if (!$scope) { // if no scope then default to 'exact'
  933. $scope = 'exact';
  934. }
  935. // make sure the synonym type exists in the 'synonym_type' vocabulary
  936. $values = array(
  937. 'name' => $scope,
  938. 'cv_id' => array(
  939. 'name' => 'synonym_type',
  940. ),
  941. );
  942. $syntype = tripal_get_cvterm($values);
  943. // if it doesn't exist then add it
  944. if (!$syntype) {
  945. // build a 'term' object so we can add the missing term
  946. $term = array(
  947. 'name' => $scope,
  948. 'id' => "synonym_type:$scope",
  949. 'definition' => '',
  950. 'is_obsolete' => 0,
  951. 'cv_name' => $syncv->name,
  952. 'is_relationship' => FALSE
  953. );
  954. $syntype = tripal_insert_cvterm($term, array('update_existing' => TRUE));
  955. if (!$syntype) {
  956. throw new Exception("Cannot add synonym type: internal:$scope");
  957. }
  958. }
  959. // make sure the synonym doesn't already exists
  960. $values = array(
  961. 'cvterm_id' => $cvterm->cvterm_id,
  962. 'synonym' => $def
  963. );
  964. $results = chado_select_record('cvtermsynonym', array('*'), $values);
  965. if (count($results) == 0) {
  966. $values = array(
  967. 'cvterm_id' => $cvterm->cvterm_id,
  968. 'synonym' => $def,
  969. 'type_id' => $syntype->cvterm_id
  970. );
  971. $options = array('return_record' => FALSE);
  972. $success = chado_insert_record('cvtermsynonym', $values, $options);
  973. if (!$success) {
  974. throw new Exception("Failed to insert the synonym for term: $cvterm->name ($def)");
  975. }
  976. }
  977. // now add the dbxrefs for the synonym if we have a comma in the middle
  978. // of a description then this will cause problems when splitting os lets
  979. // just change it so it won't mess up our splitting and then set it back
  980. // later.
  981. /**
  982. $synonym = preg_replace('/(".*?),\s(.*?")/','$1,_$2',$synonym);
  983. $dbxrefs = preg_split("/, /",preg_replace('/^.*\[(.*?)\]$/','\1',$synonym));
  984. foreach ($dbxrefs as $dbxref) {
  985. $dbxref = preg_replace('/,_/',", ",$dbxref);
  986. if ($dbxref) {
  987. $this->addCvtermDbxref($syn,$dbxref);
  988. }
  989. }
  990. */
  991. }
  992. }
  993. return TRUE;
  994. }
  995. /**
  996. * Parse the OBO file and populate the templ loading table
  997. *
  998. * @param $file
  999. * The path on the file system where the ontology can be found
  1000. * @param $header
  1001. * An array passed by reference that will be populated with the header
  1002. * information from the OBO file
  1003. *
  1004. * @ingroup tripal_obo_loader
  1005. */
  1006. private function parse($obo_file, &$header) {
  1007. $in_header = 1;
  1008. $stanza = array();
  1009. $default_db = '';
  1010. $line_num = 0;
  1011. $num_read = 0;
  1012. $type = '';
  1013. $filesize = filesize($obo_file);
  1014. $this->setTotalItems($filesize);
  1015. $this->setItemsHandled(0);
  1016. // iterate through the lines in the OBO file and parse the stanzas
  1017. $fh = fopen($obo_file, 'r');
  1018. while ($line = fgets($fh)) {
  1019. $line_num++;
  1020. $size = drupal_strlen($line);
  1021. $num_read += $size;
  1022. $line = trim($line);
  1023. $this->setItemsHandled($num_read);
  1024. // remove newlines
  1025. $line = rtrim($line);
  1026. // remove any special characters that may be hiding
  1027. $line = preg_replace('/[^(\x20-\x7F)]*/', '', $line);
  1028. // skip empty lines
  1029. if (strcmp($line, '') == 0) {
  1030. continue;
  1031. }
  1032. //remove comments from end of lines
  1033. $line = preg_replace('/^(.*?)\!.*$/', '\1', $line); // TODO: if the explamation is escaped
  1034. // at the first stanza we're out of header
  1035. if (preg_match('/^\s*\[/', $line)) {
  1036. $in_header = 0;
  1037. // store the stanza we just finished reading
  1038. if (sizeof($stanza) > 0) {
  1039. // add the term to the temp table
  1040. $values = array(
  1041. 'id' => $stanza['id'][0],
  1042. 'stanza' => base64_encode(serialize($stanza)),
  1043. 'type' => $type,
  1044. );
  1045. $success = chado_insert_record('tripal_obo_temp', $values);
  1046. if (!$success) {
  1047. throw new Exception("Cannot insert stanza into temporary table.");
  1048. }
  1049. }
  1050. // get the stanza type: Term, Typedef or Instance
  1051. $type = preg_replace('/^\s*\[\s*(.+?)\s*\]\s*$/', '\1', $line);
  1052. // start fresh with a new array
  1053. $stanza = array();
  1054. continue;
  1055. }
  1056. // break apart the line into the tag and value but ignore any escaped colons
  1057. preg_replace("/\\:/", "|-|-|", $line); // temporarily replace escaped colons
  1058. $pair = explode(":", $line, 2);
  1059. $tag = $pair[0];
  1060. $value = ltrim(rtrim($pair[1]));// remove surrounding spaces
  1061. // if this is the ID then look for the default DB
  1062. $matches = array();
  1063. if ($tag == 'id' and preg_match('/^(.+?):.*$/', $value, $matches)) {
  1064. $default_db = $matches[1];
  1065. }
  1066. $tag = preg_replace("/\|-\|-\|/", "\:", $tag); // return the escaped colon
  1067. $value = preg_replace("/\|-\|-\|/", "\:", $value);
  1068. if ($in_header) {
  1069. if (!array_key_exists($tag, $header)) {
  1070. $header[$tag] = array();
  1071. }
  1072. $header[$tag][] = $value;
  1073. }
  1074. else {
  1075. if (!array_key_exists($tag, $stanza)) {
  1076. $stanza[$tag] = array();
  1077. }
  1078. $stanza[$tag][] = $value;
  1079. }
  1080. }
  1081. // now add the last term in the file
  1082. if (sizeof($stanza) > 0) {
  1083. $values = array(
  1084. 'id' => $stanza['id'][0],
  1085. 'stanza' => base64_encode(serialize($stanza)),
  1086. 'type' => $type,
  1087. );
  1088. chado_insert_record('tripal_obo_temp', $values);
  1089. if (!$success) {
  1090. throw new Exception("Cannot insert stanza into temporary table.");
  1091. }
  1092. $this->setItemsHandled($num_read);
  1093. }
  1094. return $default_db;
  1095. }
  1096. /**
  1097. * Adds a database reference to a cvterm
  1098. *
  1099. * @param cvterm
  1100. * The database object of the cvterm to which the synonym will be added.
  1101. * @param xref
  1102. * The cross refernce. It should be of the form from the OBO specification
  1103. *
  1104. * @ingroup tripal_obo_loader
  1105. */
  1106. private function addCvtermDbxref($cvterm, $xref) {
  1107. $dbname = preg_replace('/^(.+?):.*$/', '$1', $xref);
  1108. $accession = preg_replace('/^.+?:\s*(.*?)(\{.+$|\[.+$|\s.+$|\".+$|$)/', '$1', $xref);
  1109. $description = preg_replace('/^.+?\"(.+?)\".*?$/', '$1', $xref);
  1110. $dbxrefs = preg_replace('/^.+?\[(.+?)\].*?$/', '$1', $xref);
  1111. if (!$accession) {
  1112. throw new Exception("Cannot add a dbxref without an accession: '$xref'");
  1113. }
  1114. // if the xref is a database link, handle that specially
  1115. if (strcmp($dbname, 'http') == 0) {
  1116. $accession = $xref;
  1117. $dbname = 'URL';
  1118. }
  1119. // add the database
  1120. $db = tripal_insert_db(array('name' => $dbname));
  1121. if (!$db) {
  1122. throw new Exception("Cannot find database '$dbname' in Chado.");
  1123. }
  1124. // now add the dbxref
  1125. $dbxref = $this->addDbxref($db->db_id, $accession, '', $description);
  1126. if (!$dbxref) {
  1127. throw new Exception("Cannot find or add the database reference (dbxref)");
  1128. }
  1129. // finally add the cvterm_dbxref but first check to make sure it exists
  1130. $values = array(
  1131. 'cvterm_id' => $cvterm->cvterm_id,
  1132. 'dbxref_id' => $dbxref->dbxref_id,
  1133. );
  1134. $result = chado_select_record('cvterm_dbxref', array('*'), $values);
  1135. if (count($result) == 0) {
  1136. $ins_options = array('return_record' => FALSE);
  1137. $result = chado_insert_record('cvterm_dbxref', $values, $ins_options);
  1138. if (!$result) {
  1139. throw new Exception("Cannot add cvterm_dbxref: $xref");
  1140. }
  1141. }
  1142. return TRUE;
  1143. }
  1144. /**
  1145. * Adds a property to a cvterm
  1146. *
  1147. * @param cvterm
  1148. * A database object for the cvterm to which properties will be added
  1149. * @param $property
  1150. * The name of the property to add
  1151. * @param $value
  1152. * The value of the property
  1153. * @param rank
  1154. * The rank of the property
  1155. *
  1156. * @ingroup tripal_obo_loader
  1157. */
  1158. private function addCvtermProp($cvterm, $property, $value, $rank) {
  1159. // make sure the 'cvterm_property_type' CV exists
  1160. $cv = tripal_insert_cv('cvterm_property_type', '');
  1161. if (!$cv) {
  1162. throw new Exception("Cannot add/find cvterm_property_type cvterm");
  1163. }
  1164. // get the property type cvterm. If it doesn't exist then we want to add it
  1165. $values = array(
  1166. 'name' => $property,
  1167. 'cv_id' => $cv->cv_id,
  1168. );
  1169. $results = chado_select_record('cvterm', array('*'), $values);
  1170. if (count($results) == 0) {
  1171. $term = array(
  1172. 'name' => $property,
  1173. 'id' => "internal:$property",
  1174. 'definition' => '',
  1175. 'is_obsolete' => 0,
  1176. 'cv_name' => $cv->name,
  1177. 'is_relationship' => FALSE,
  1178. );
  1179. $cvproptype = tripal_insert_cvterm($term, array('update_existing' => FALSE));
  1180. if (!$cvproptype) {
  1181. throw new Exception("Cannot add cvterm property: internal:$property");
  1182. }
  1183. }
  1184. else {
  1185. $cvproptype = $results[0];
  1186. }
  1187. // remove any properties that currently exist for this term. We'll reset them
  1188. if ($rank == 0) {
  1189. $values = array('cvterm_id' => $cvterm->cvterm_id);
  1190. $success = chado_delete_record('cvtermprop', $values);
  1191. if (!$success) {
  1192. throw new Exception("Could not remove existing properties to update property $property for term\n");
  1193. }
  1194. }
  1195. // now add the property
  1196. $values = array(
  1197. 'cvterm_id' => $cvterm->cvterm_id,
  1198. 'type_id' => $cvproptype->cvterm_id,
  1199. 'value' => $value,
  1200. 'rank' => $rank,
  1201. );
  1202. $options = array('return_record' => FALSE);
  1203. $result = chado_insert_record('cvtermprop', $values, $options);
  1204. if (!$result) {
  1205. throw new Exception("Could not add property $property for term\n");
  1206. }
  1207. return TRUE;
  1208. }
  1209. /**
  1210. * Adds a database cross reference to a cvterm
  1211. *
  1212. * @param db_id
  1213. * The database ID of the cross reference
  1214. * @param accession
  1215. * The cross reference's accession
  1216. * @param $version
  1217. * The version of the dbxref
  1218. * @param $description
  1219. * The description of the cross reference
  1220. *
  1221. * @ingroup tripal_obo_loader
  1222. */
  1223. private function addDbxref($db_id, $accession, $version='', $description='') {
  1224. // check to see if the dbxref exists if not, add it
  1225. $values = array(
  1226. 'db_id' => $db_id,
  1227. 'accession' => $accession,
  1228. );
  1229. $result = chado_select_record('dbxref', array('dbxref_id'), $values);
  1230. if (count($result) == 0) {
  1231. $ins_values = array(
  1232. 'db_id' => $db_id,
  1233. 'accession' => $accession,
  1234. 'version' => $version,
  1235. 'description' => $description,
  1236. );
  1237. $ins_options = array('return_record' => FALSE);
  1238. $result = chado_insert_record('dbxref', $ins_values, $ins_options);
  1239. if (!$result) {
  1240. throw new Exception("Failed to insert the dbxref record $accession");
  1241. }
  1242. $result = chado_select_record('dbxref', array('dbxref_id'), $values);
  1243. }
  1244. return $result[0];
  1245. }
  1246. }
  1247. /**
  1248. * Ajax callback for the OBOImporter::form() function.
  1249. */
  1250. function tripal_cv_obo_form_ajax_callback($form, $form_state) {
  1251. return $form['class_elements']['obo_existing'];
  1252. }