OBOImporter.inc 46 KB

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