OBOImporter.inc 47 KB

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