OBOImporter.inc 48 KB

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