tripal_stock.sync_stocks.inc 14 KB

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