syncFeatures.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. <?php
  2. /**
  3. * @file
  4. * @todo Add file header description
  5. */
  6. # This script can be run as a stand-alone script to sync all the features from chado to drupal
  7. // Parameter f specifies the feature_id to sync
  8. // -f 0 will sync all features
  9. $arguments = getopt("f:");
  10. if (isset($arguments['f'])) {
  11. $drupal_base_url = parse_url('http://www.example.com');
  12. $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
  13. $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
  14. $_SERVER['REMOTE_ADDR'] = NULL;
  15. $_SERVER['REQUEST_METHOD'] = NULL;
  16. require_once 'includes/bootstrap.inc';
  17. drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  18. $feature_id = $arguments['f'];
  19. if ($feature_id > 0 ) {
  20. tripal_feature_sync_feature($feature_id);
  21. }
  22. else{
  23. print "syncing all features...\n";
  24. tripal_feature_sync_features();
  25. }
  26. }
  27. /**
  28. *
  29. */
  30. function tripal_feature_sync_form() {
  31. $form['description'] = array(
  32. '#type' => 'item',
  33. '#value' => t("Add feature types, optionally select an organism and ".
  34. "click the 'Sync all Features' button to create Drupal ".
  35. "content for features in chado. Only features of the types listed ".
  36. "below in the Feature Types box will be synced. You may limit the ".
  37. "features to be synced by a specific organism. Depending on the ".
  38. "number of features in the chado database this may take a long ".
  39. "time to complete. "),
  40. );
  41. $form['feature_types'] = array(
  42. '#title' => t('Feature Types'),
  43. '#type' => 'textarea',
  44. '#description' => t('Enter the names of the sequence types that the ".
  45. "site will support with independent pages. Pages for these data ".
  46. "types will be built automatically for features that exist in the ".
  47. "chado database. The names listed here should be spearated by ".
  48. "spaces or entered separately on new lines. The names must match ".
  49. "exactly (spelling and case) with terms in the sequence ontology'),
  50. '#required' => TRUE,
  51. '#default_value' => variable_get('chado_sync_feature_types', 'gene contig'),
  52. );
  53. // get the list of organisms
  54. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  55. $orgs = tripal_organism_get_synced();
  56. $organisms[] = '';
  57. foreach ($orgs as $organism) {
  58. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  59. }
  60. $form['organism_id'] = array(
  61. '#title' => t('Organism'),
  62. '#type' => t('select'),
  63. '#description' => t("Choose the organism for which features will be deleted."),
  64. '#options' => $organisms,
  65. );
  66. $form['button'] = array(
  67. '#type' => 'submit',
  68. '#value' => t('Sync all Features'),
  69. '#weight' => 3,
  70. );
  71. return $form;
  72. }
  73. /**
  74. *
  75. */
  76. function tripal_feature_sync_form_validate($form, &$form_state) {
  77. $organism_id = $form_state['values']['organism_id'];
  78. $feature_types = $form_state['values']['feature_types'];
  79. // nothing to do
  80. }
  81. /**
  82. *
  83. */
  84. function tripal_feature_sync_form_submit($form, &$form_state) {
  85. global $user;
  86. $organism_id = $form_state['values']['organism_id'];
  87. $feature_types = $form_state['values']['feature_types'];
  88. $job_args = array(0, $organism_id, $feature_types);
  89. if ($organism_id) {
  90. $organism = tripal_core_chado_select('organism', array('genus', 'species'), array('organism_id' => $organism_id));
  91. $title = "Sync all features for " . $organism[0]->genus . " " . $organism[0]->species;
  92. }
  93. else {
  94. $title = t('Sync all features for all synced organisms');
  95. }
  96. variable_set('chado_sync_feature_types', $feature_types);
  97. tripal_add_job($title, 'tripal_feature',
  98. 'tripal_feature_sync_features', $job_args, $user->uid);
  99. }
  100. /**
  101. *
  102. */
  103. function tripal_feature_set_urls($job_id = NULL) {
  104. // first get the list of features that have been synced
  105. $sql = "SELECT * FROM {chado_feature}";
  106. $nodes = db_query($sql);
  107. while ($node = db_fetch_object($nodes)) {
  108. // now get the feature details
  109. $sql = "SELECT *
  110. FROM feature F
  111. INNER JOIN organism O on O.organism_id = F.organism_id
  112. WHERE F.feature_id = %d";
  113. $feature = db_fetch_object(chado_query($sql, $node->feature_id));
  114. if ($feature) {
  115. tripal_feature_set_feature_url($node, $feature);
  116. }
  117. }
  118. }
  119. /**
  120. *
  121. */
  122. function tripal_feature_set_feature_url($node, $feature) {
  123. // determine which URL alias to use
  124. $alias_type = variable_get('chado_feature_url', 'internal ID');
  125. $aprefix = variable_get('chado_feature_accession_prefix', 'ID');
  126. $genus = preg_replace('/\s/', '_', strtolower($feature->genus));
  127. $species = preg_replace('/\s/', '_', strtolower($feature->species));
  128. switch ($alias_type) {
  129. case 'feature name':
  130. $url_alias = $feature->name;
  131. break;
  132. case 'feature unique name':
  133. $url_alias = $feature->uniquename;
  134. break;
  135. case 'genus_species_uqname':
  136. $url_alias = $genus . "/" . $genus . "_" . $species . "/" . $feature->uniquename;
  137. break;
  138. case 'genus species name':
  139. $url_alias = $genus . "/" . $genus . "_" . $species . "/" . $feature->name;
  140. break;
  141. default:
  142. $url_alias = "$aprefix$feature->feature_id";
  143. }
  144. print "Setting URL alias for $feature->name: node/$node->nid => $url_alias\n";
  145. // remove any previous alias
  146. db_query("DELETE FROM {url_alias} WHERE src = '%s'", "node/$node->nid");
  147. // add the new alias
  148. path_set_alias("node/$node->nid", $url_alias);
  149. }
  150. /**
  151. *
  152. *
  153. * @ingroup tripal_feature
  154. */
  155. function tripal_feature_sync_features($max_sync = 0, $organism_id = NULL,
  156. $feature_types = NULL, $job_id = NULL) {
  157. //print "Syncing features (max of $max_sync)\n";
  158. $i = 0;
  159. // get the list of available sequence ontology terms for which
  160. // we will build drupal pages from features in chado. If a feature
  161. // is not one of the specified typse we won't build a node for it.
  162. if (!$feature_types) {
  163. $allowed_types = variable_get('chado_sync_feature_types', 'gene contig');
  164. }
  165. else {
  166. $allowed_types = $feature_types;
  167. }
  168. $allowed_types = preg_replace("/[\s\n\r]+/", " ", $allowed_types);
  169. print "Looking for features of type: $allowed_types\n";
  170. $so_terms = split(' ', $allowed_types);
  171. $where_cvt = "";
  172. foreach ($so_terms as $term) {
  173. $where_cvt .= "CVT.name = '$term' OR ";
  174. }
  175. $where_cvt = drupal_substr($where_cvt, 0, drupal_strlen($where_cvt)-3); # strip trailing 'OR'
  176. // get the list of organisms that are synced and only include features from
  177. // those organisms
  178. $orgs = tripal_organism_get_synced();
  179. $where_org = "";
  180. foreach ($orgs as $org) {
  181. if ($organism_id) {
  182. if ($org->organism_id and $org->organism_id == $organism_id) {
  183. $where_org .= "F.organism_id = $org->organism_id OR ";
  184. }
  185. }
  186. else {
  187. if ($org->organism_id) {
  188. $where_org .= "F.organism_id = $org->organism_id OR ";
  189. }
  190. }
  191. }
  192. $where_org = drupal_substr($where_org, 0, drupal_strlen($where_org)-3); # strip trailing 'OR'
  193. // use this SQL statement to get the features that we're going to upload
  194. $sql = "SELECT feature_id ".
  195. "FROM {FEATURE} F ".
  196. " INNER JOIN Cvterm CVT ON F.type_id = CVT.cvterm_id ".
  197. " INNER JOIN CV on CV.cv_id = CVT.cv_id ".
  198. "WHERE ($where_cvt) AND ($where_org) AND CV.name = 'sequence' ".
  199. "ORDER BY feature_id";
  200. // get the list of features
  201. $results = chado_query($sql);
  202. // load into ids array
  203. $count = 0;
  204. $ids = array();
  205. while ($id = db_fetch_object($results)) {
  206. $ids[$count] = $id->feature_id;
  207. $count++;
  208. }
  209. // make sure our vocabularies are set before proceeding
  210. tripal_feature_set_vocabulary();
  211. // pre-create the SQL statement that will be used to check
  212. // if a feature has already been synced. We skip features
  213. // that have been synced
  214. $sql = "SELECT * FROM {chado_feature} WHERE feature_id = %d";
  215. // Iterate through features that need to be synced
  216. $interval = intval($count * 0.01);
  217. if ($interval < 1) {
  218. $interval = 1;
  219. }
  220. $num_ids = sizeof($ids);
  221. $i = 0;
  222. foreach ($ids as $feature_id) {
  223. // update the job status every 1% features
  224. if ($job_id and $i % $interval == 0) {
  225. tripal_job_set_progress($job_id, intval(($i/$count)*100));
  226. }
  227. // if we have a maximum number to sync then stop when we get there
  228. // if not then just continue on
  229. if ($max_sync and $i == $max_sync) {
  230. return '';
  231. }
  232. if (!db_fetch_object(db_query($sql, $feature_id))) {
  233. # parsing all the features can cause memory overruns
  234. # we are not sure why PHP does not clean up the memory as it goes
  235. # to avoid this problem we will call this script through an
  236. # independent system call
  237. print "$i of $num_ids Syncing feature id: $feature_id\n";
  238. $cmd = "php " . drupal_get_path('module', 'tripal_feature') . "/includes/syncFeatures.inc -f $feature_id ";
  239. system($cmd);
  240. }
  241. $i++;
  242. }
  243. return '';
  244. }
  245. /**
  246. *
  247. *
  248. * @ingroup tripal_feature
  249. */
  250. function tripal_feature_sync_feature($feature_id) {
  251. // print "\tSyncing feature $feature_id\n";
  252. $mem = memory_get_usage(TRUE);
  253. $mb = $mem/1048576;
  254. // print "$mb mb\n";
  255. global $user;
  256. $create_node = 1; // set to 0 if the node exists and we just sync and not create
  257. // get the accession prefix
  258. $aprefix = variable_get('chado_feature_accession_prefix', 'ID');
  259. // if we don't have a feature_id then return
  260. if (!$feature_id) {
  261. drupal_set_message(t("Please provide a feature_id to sync"));
  262. return '';
  263. }
  264. // get information about this feature
  265. $fsql = "SELECT F.feature_id, F.name, F.uniquename,O.genus, ".
  266. " O.species,CVT.name as cvname,F.residues,F.organism_id ".
  267. "FROM {FEATURE} F ".
  268. " INNER JOIN Cvterm CVT ON F.type_id = CVT.cvterm_id ".
  269. " INNER JOIN Organism O ON F.organism_id = O.organism_ID ".
  270. "WHERE F.feature_id = %d";
  271. $feature = db_fetch_object(chado_query($fsql, $feature_id));
  272. // get the synonyms for this feature
  273. $synsql = "SELECT S.name ".
  274. "FROM {feature_synonym} FS ".
  275. " INNER JOIN {synonym} S on FS.synonym_id = S.synonym_id ".
  276. "WHERE FS.feature_id = %d";
  277. $synonyms = chado_query($synsql, $feature_id);
  278. // now add these synonyms to the feature object as a single string
  279. $synstring = '';
  280. while ($synonym = db_fetch_object($synonyms)) {
  281. $synstring .= "$synonym->name\n";
  282. }
  283. $feature->synonyms = $synstring;
  284. // check to make sure that we don't have any nodes with this feature name as a title
  285. // but without a corresponding entry in the chado_feature table if so then we want to
  286. // clean up that node. (If a node is found we don't know if it belongs to our feature or
  287. // not since features can have the same name/title.)
  288. $tsql = "SELECT * FROM {node} N ".
  289. "WHERE title = '%s'";
  290. $cnsql = "SELECT * FROM {chado_feature} ".
  291. "WHERE nid = %d";
  292. $nodes = db_query($tsql, $feature->name);
  293. // cycle through all nodes that may have this title
  294. while ($node = db_fetch_object($nodes)) {
  295. $feature_nid = db_fetch_object(db_query($cnsql, $node->nid));
  296. if (!$feature_nid) {
  297. drupal_set_message(t("%feature_id: A node is present but the chado_feature entry is missing... correcting", array('%feature_id' => $feature_id)));
  298. node_delete($node->nid);
  299. }
  300. }
  301. // check if this feature already exists in the chado_feature table.
  302. // if we have a chado feature, we want to check to see if we have a node
  303. $cfsql = "SELECT * FROM {chado_feature} ".
  304. "WHERE feature_id = %d";
  305. // @coder-ignore: don't need to use db_rewrite_sql() since need all nodes regardless of access control
  306. $nsql = "SELECT * FROM {node} N ".
  307. "WHERE nid = %d";
  308. $chado_feature = db_fetch_object(db_query($cfsql, $feature->feature_id));
  309. if ($chado_feature) {
  310. drupal_set_message(t("%feature_id: A chado_feature entry exists", array('%feature_id' => $feature_id)));
  311. $node = db_fetch_object(db_query($nsql, $chado_feature->nid));
  312. if (!$node) {
  313. // if we have a chado_feature but not a node then we have a problem and
  314. // need to cleanup
  315. drupal_set_message(t("%feature_id: The node is missing, but has a chado_feature entry... correcting", array('%feature_id' => $feature_id)));
  316. $df_sql = "DELETE FROM {chado_feature} WHERE feature_id = %d";
  317. db_query($df_sql, $feature_id);
  318. }
  319. else {
  320. drupal_set_message(t("%feature_id: A corresponding node exists", array('%feature_id' => $feature_id)));
  321. $create_node = 0;
  322. }
  323. }
  324. // if we've encountered an error then just return.
  325. if ($error_msg = db_error()) {
  326. //print "$error_msg\n";
  327. return '';
  328. }
  329. // if a drupal node does not exist for this feature then we want to
  330. // create one. Note that the node_save call in this block
  331. // will call the hook_submit function which
  332. if ($create_node) {
  333. // get the organism for this feature
  334. $sql = "SELECT * FROM {organism} WHERE organism_id = %d";
  335. $organism = db_fetch_object(chado_query($sql, $feature->organism_id));
  336. drupal_set_message(t("%feature_id: Creating node $feature->name", array('%feature_id' => $feature_id)));
  337. $new_node = new stdClass();
  338. $new_node->type = 'chado_feature';
  339. $new_node->uid = $user->uid;
  340. $new_node->title = "$feature->name, $feature->uniquename ($feature->cvname) $organism->genus $organism->species";
  341. $new_node->fname = "$feature->name";
  342. $new_node->uniquename = "$feature->uniquename";
  343. $new_node->feature_id = $feature->feature_id;
  344. $new_node->residues = $feature->residues;
  345. $new_node->organism_id = $feature->organism_id;
  346. $new_node->feature_type = $feature->cvname;
  347. $new_node->synonyms = $feature->synonyms;
  348. // validate the node and if okay then submit
  349. node_validate($new_node);
  350. if ($errors = form_get_errors()) {
  351. foreach ($errors as $key => $msg) {
  352. drupal_set_message(t("%msg", array('%msg' => $msg)));
  353. }
  354. return $errors;
  355. }
  356. else {
  357. $node = node_submit($new_node);
  358. node_save($node);
  359. }
  360. }
  361. else {
  362. $node = $chado_feature;
  363. }
  364. // set the taxonomy for this node
  365. drupal_set_message(t("%feature_id ($node->nid): setting taxonomy", array('%feature_id' => $feature_id)));
  366. tripal_feature_set_taxonomy($node, $feature_id);
  367. // reindex the node
  368. // drupal_set_message(t("$feature_id( $node->nid): indexing"));
  369. // tripal_feature_index_feature ($feature_id,$node->nid);
  370. // set the URL alias for this node
  371. tripal_feature_set_feature_url($node, $feature);
  372. return '';
  373. }