tripal_stock.sync_stocks.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. * @param $na
  99. * Tripal expects all jobs to have at least one argument. For this function
  100. * we don't need any, so we have this dummy argument as a filler
  101. * @param $job_id
  102. */
  103. function tripal_stock_set_urls($na = NULL, $job = NULL) {
  104. // begin the transaction
  105. db_query("BEGIN");
  106. print "\nNOTE: Setting of URLs is performed using a database transaction. \n" .
  107. "If the load fails or is terminated prematurely then the entire set of \n" .
  108. "new URLs will be rolled back and no changes will be made\n\n";
  109. // get the number of records we need to set URLs for
  110. $csql = "SELECT count(*) FROM {chado_stock}";
  111. $num_nodes = db_result(db_query($csql));
  112. // calculate the interval at which we will print an update on the screen
  113. $num_set = 0;
  114. $num_per_interval = 100;
  115. // prepate the statements which will quickly add url alias. Because these
  116. // are not Chado tables we must manually prepare them
  117. $psql = "
  118. PREPARE del_url_alias_by_src (text) AS
  119. DELETE FROM {url_alias} WHERE src = \$1
  120. ";
  121. db_query($psql);
  122. $psql = "
  123. PREPARE ins_url_alias_nisrds (text, text) AS
  124. INSERT INTO url_alias (src, dst) VALUES (\$1, \$2)
  125. ";
  126. db_query($psql);
  127. // get the URL alias syntax string
  128. $url_alias = variable_get('chado_stock_url_string', '/stock/[genus]/[species]/[type]/[uniquename]');
  129. if (!$url_alias) {
  130. $url_alias = '/stock/[genus]/[species]/[type]/[uniquename]';
  131. }
  132. $url_alias = preg_replace('/^\//', '', $url_alias); // remove any preceeding forward slash
  133. // get the list of stocks that have been synced
  134. $sql = "SELECT * FROM {chado_stock}";
  135. $nodes = db_query($sql);
  136. while ($node = db_fetch_object($nodes)) {
  137. // remove any previous alias
  138. $src = "node/$node->nid";
  139. $dst = tripal_stock_get_stock_url($node, $url_alias);
  140. $success = db_query("EXECUTE del_url_alias_by_src('%s')", $src);
  141. $success = db_query("EXECUTE ins_url_alias_nisrds('%s', '%s')", $src, $dst);
  142. // update the job status every 1% stocks
  143. if ($job and $num_set % $num_per_interval == 0) {
  144. $percent = ($num_set / $num_nodes) * 100;
  145. tripal_job_set_progress($job, intval($percent));
  146. $percent = sprintf("%.2f", $percent);
  147. print "Setting URLs (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  148. }
  149. $num_set++;
  150. }
  151. $percent = ($num_set / $num_nodes) * 100;
  152. tripal_job_set_progress($job, intval($percent));
  153. $percent = sprintf("%.2f", $percent);
  154. print "Setting URLs (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  155. print "\nDone. Set " . number_format($num_set) . " URLs\n";
  156. // unprepare the statements
  157. db_query('DEALLOCATE "del_url_alias_by_src"');
  158. db_query('DEALLOCATE "ins_url_alias_nisrds"');
  159. db_query("COMMIT");
  160. }
  161. /**
  162. *
  163. * @param $node
  164. * A node object containing at least the stock_id and nid
  165. * @param $url_alias
  166. * Optional. This should be the URL alias syntax string that contains
  167. * placeholders such as [id], [genus], [species], [name], [uniquename],
  168. * and [type]. These placeholders will be substituted for actual values.
  169. * If this parameter is not provided then the value of the
  170. * chado_stock_url_string Drupal variable will be used.
  171. */
  172. function tripal_stock_get_stock_url($node, $url_alias = NULL) {
  173. // get the starting URL alias
  174. if(!$url_alias) {
  175. $url_alias = variable_get('chado_stock_url_string', '/stock/[genus]/[species]/[type]/[uniquename]');
  176. if (!$url_alias) {
  177. $url_alias = '/stock/[genus]/[species]/[type]/[uniquename]';
  178. }
  179. $url_alias = preg_replace('/^\//', '', $url_alias); // remove any preceeding forward slash
  180. }
  181. // get the stock
  182. $values = array('stock_id' => $node->stock_id);
  183. $options = array('statement_name' => 'sel_stock_id');
  184. $stock = tripal_core_chado_select('stock', array('*'), $values, $options);
  185. $stock = (object) $stock[0];
  186. // get the organism
  187. $values = array('organism_id' => $stock->organism_id);
  188. $options = array('statement_name' => 'sel_organism_id');
  189. $organism = tripal_core_chado_select('organism', array('*'), $values, $options);
  190. $genus = preg_replace('/\s/', '_', strtolower($organism[0]->genus));
  191. $species = preg_replace('/\s/', '_', strtolower($organism[0]->species));
  192. // get the type
  193. $values = array('cvterm_id' => $stock->type_id);
  194. $options = array('statement_name' => 'sel_cvterm_id');
  195. $cvterm = tripal_core_chado_select('cvterm', array('name'), $values, $options);
  196. $type = preg_replace('/\s/', '_', $cvterm[0]->name);
  197. // now substitute in the values
  198. $url_alias = preg_replace('/\[id\]/', $stock->stock_id, $url_alias);
  199. $url_alias = preg_replace('/\[genus\]/', $genus, $url_alias);
  200. $url_alias = preg_replace('/\[species\]/', $species, $url_alias);
  201. $url_alias = preg_replace('/\[type\]/', $type, $url_alias);
  202. $url_alias = preg_replace('/\[name\]/', $stock->name, $url_alias);
  203. $url_alias = preg_replace('/\[uniquename\]/', $stock->uniquename, $url_alias);
  204. return $url_alias;
  205. }
  206. /**
  207. *
  208. *
  209. * @ingroup tripal_stock
  210. */
  211. function tripal_stock_sync_stocks($max_sync = 0, $organism_id = NULL,
  212. $stock_types = NULL, $job_id = NULL) {
  213. //print "Syncing stocks (max of $max_sync)\n";
  214. $i = 0;
  215. // get the list of available sequence ontology terms for which
  216. // we will build drupal pages from stocks in chado. If a stock
  217. // is not one of the specified typse we won't build a node for it.
  218. if (!$stock_types) {
  219. $allowed_types = variable_get('chado_sync_stock_types', '');
  220. }
  221. else {
  222. $allowed_types = $stock_types;
  223. }
  224. if ($allowed_types) {
  225. $allowed_types = preg_replace("/[\s\n\r]+/", " ", $allowed_types);
  226. print "Looking for stocks of type: $allowed_types\n";
  227. $so_terms = split(' ', $allowed_types);
  228. $where_cvt = "";
  229. foreach ($so_terms as $term) {
  230. $where_cvt .= "CVT.name = '$term' OR ";
  231. }
  232. $where_cvt = drupal_substr($where_cvt, 0, drupal_strlen($where_cvt)-3); # strip trailing 'OR'
  233. }
  234. else {
  235. $where_cvt = '1=1';
  236. }
  237. // get the list of organisms that are synced and only include stocks from
  238. // those organisms
  239. $orgs = tripal_organism_get_synced();
  240. $where_org = "";
  241. foreach ($orgs as $org) {
  242. if ($organism_id) {
  243. if ($org->organism_id and $org->organism_id == $organism_id) {
  244. $where_org .= "S.organism_id = $org->organism_id OR ";
  245. }
  246. }
  247. else {
  248. if ($org->organism_id) {
  249. $where_org .= "S.organism_id = $org->organism_id OR ";
  250. }
  251. }
  252. }
  253. $where_org = drupal_substr($where_org, 0, drupal_strlen($where_org)-3); # strip trailing 'OR'
  254. // use this SQL statement to get the stocks that we're going to upload
  255. $sql = "SELECT stock_id ".
  256. "FROM {stock} S ".
  257. " INNER JOIN {cvterm} CVT ON S.type_id = CVT.cvterm_id ".
  258. "WHERE ($where_cvt) AND ($where_org) ".
  259. "ORDER BY stock_id";
  260. // get the list of stocks
  261. $results = chado_query($sql);
  262. // load into ids array
  263. $count = 0;
  264. $ids = array();
  265. while ($id = db_fetch_object($results)) {
  266. $ids[$count] = $id->stock_id;
  267. $count++;
  268. }
  269. // make sure our vocabularies are set before proceeding
  270. // tripal_stock_set_vocabulary();
  271. // pre-create the SQL statement that will be used to check
  272. // if a stock has already been synced. We skip stocks
  273. // that have been synced
  274. $sql = "SELECT * FROM {chado_stock} WHERE stock_id = %d";
  275. // Iterate through stocks that need to be synced
  276. $interval = intval($count * 0.01);
  277. if ($interval < 1) {
  278. $interval = 1;
  279. }
  280. $num_ids = sizeof($ids);
  281. $i = 0;
  282. foreach ($ids as $stock_id) {
  283. // update the job status every 1% stocks
  284. if ($job_id and $i % $interval == 0) {
  285. tripal_job_set_progress($job_id, intval(($i/$count)*100));
  286. }
  287. // if we have a maximum number to sync then stop when we get there
  288. // if not then just continue on
  289. if ($max_sync and $i == $max_sync) {
  290. return '';
  291. }
  292. if (!db_fetch_object(db_query($sql, $stock_id))) {
  293. # parsing all the stocks can cause memory overruns
  294. # we are not sure why PHP does not clean up the memory as it goes
  295. # to avoid this problem we will call this script through an
  296. # independent system call
  297. print ($i + 1) . " of $num_ids Syncing stock id: $stock_id\n";
  298. $cmd = "php " . drupal_get_path('module', 'tripal_stock') . "/includes/tripal_stock.sync_stocks.inc -f $stock_id -t chado_stock";
  299. print "$cmd\n";
  300. system($cmd);
  301. }
  302. $i++;
  303. }
  304. return '';
  305. }
  306. /**
  307. *
  308. *
  309. * @ingroup tripal_stock
  310. */
  311. function tripal_stock_sync_stock($stock_id) {
  312. print "\tSyncing stock $stock_id\n";
  313. global $user;
  314. $create_node = 1; // set to 0 if the node exists and we just sync and not create
  315. // get the accession prefix
  316. $aprefix = variable_get('chado_stock_accession_prefix', 'SID');
  317. // if we don't have a stock_id then return
  318. if (!$stock_id) {
  319. drupal_set_message(t("Please provide a stock_id to sync"));
  320. return '';
  321. }
  322. // get information about this stock
  323. $fsql = "SELECT S.*, O.genus, O.species,CVT.name as cvname ".
  324. "FROM {stock} S ".
  325. " INNER JOIN {cvterm} CVT ON S.type_id = CVT.cvterm_id ".
  326. " INNER JOIN {organism} O ON S.organism_id = O.organism_ID ".
  327. "WHERE S.stock_id = %d";
  328. $stock = db_fetch_object(chado_query($fsql, $stock_id));
  329. /*
  330. // get the synonyms for this stock
  331. $synsql = "SELECT S.name ".
  332. "FROM {stock_synonym} SS ".
  333. " INNER JOIN {synonym} S on SS.synonym_id = S.synonym_id ".
  334. "WHERE SS.stock_id = %d";
  335. $synonyms = chado_query($synsql, $stock_id);
  336. // now add these synonyms to the stock object as a single string
  337. $synstring = '';
  338. while ($synonym = db_fetch_object($synonyms)) {
  339. $synstring .= "$synonym->name\n";
  340. }
  341. $stock->synonyms = $synstring;
  342. */
  343. // check to make sure that we don't have any nodes with this stock name as a title
  344. // but without a corresponding entry in the chado_stock table if so then we want to
  345. // clean up that node. (If a node is found we don't know if it belongs to our stock or
  346. // not since stocks can have the same name/title.)
  347. $tsql = "SELECT * FROM {node} N ".
  348. "WHERE title = '%s'";
  349. $cnsql = "SELECT * FROM {chado_stock} ".
  350. "WHERE nid = %d";
  351. $nodes = db_query($tsql, $stock->name);
  352. // cycle through all nodes that may have this title
  353. while ($node = db_fetch_object($nodes)) {
  354. $stock_nid = db_fetch_object(db_query($cnsql, $node->nid));
  355. if (!$stock_nid) {
  356. drupal_set_message(t("%stock_id: A node is present but the chado_stock entry is missing... correcting", array('%stock_id' => $stock_id)));
  357. node_delete($node->nid);
  358. }
  359. }
  360. // check if this stock already exists in the chado_stock table.
  361. // if we have a chado stock, we want to check to see if we have a node
  362. $cfsql = "SELECT * FROM {chado_stock} ".
  363. "WHERE stock_id = %d";
  364. $nsql = "SELECT * FROM {node} N ".
  365. "WHERE nid = %d";
  366. $chado_stock = db_fetch_object(db_query($cfsql, $stock->stock_id));
  367. if ($chado_stock) {
  368. drupal_set_message(t("%stock_id: A chado_stock entry exists", array('%stock_id' => $stock_id)));
  369. $node = db_fetch_object(db_query($nsql, $chado_stock->nid));
  370. if (!$node) {
  371. // if we have a chado_stock but not a node then we have a problem and
  372. // need to cleanup
  373. drupal_set_message(t("%stock_id: The node is missing, but has a chado_stock entry... correcting", array('%stock_id' => $stock_id)));
  374. $df_sql = "DELETE FROM {chado_stock} WHERE stock_id = %d";
  375. db_query($df_sql, $stock_id);
  376. }
  377. else {
  378. drupal_set_message(t("%stock_id: A corresponding node exists", array('%stock_id' => $stock_id)));
  379. $create_node = 0;
  380. }
  381. }
  382. // if we've encountered an error then just return.
  383. if ($error_msg = db_error()) {
  384. //print "$error_msg\n";
  385. return '';
  386. }
  387. // if a drupal node does not exist for this stock then we want to
  388. // create one. Note that the node_save call in this block
  389. // will call the hook_submit function which
  390. if ($create_node) {
  391. // get the organism for this stock
  392. $sql = "SELECT * FROM {organism} WHERE organism_id = %d";
  393. $organism = db_fetch_object(chado_query($sql, $stock->organism_id));
  394. drupal_set_message(t("%stock_id: Creating node $stock->name", array('%stock_id' => $stock_id)));
  395. $new_node = new stdClass();
  396. $new_node->type = 'chado_stock';
  397. $new_node->uid = $user->uid;
  398. $new_node->title = "$stock->name, $stock->uniquename ($stock->cvname) $organism->genus $organism->species";
  399. $new_node->sname = "$stock->name";
  400. $new_node->uniquename = "$stock->uniquename";
  401. $new_node->type_id = $stock->type_id;
  402. $new_node->organism_id = $stock->organism_id;
  403. $new_node->stock_id = $stock->stock_id;
  404. $new_node->chado_stock_exists = TRUE;
  405. // validate the node and if okay then submit
  406. node_validate($new_node);
  407. if ($errors = form_get_errors()) {
  408. print "Error encountered validating new node. Cannot sync: $msg\n";
  409. foreach ($errors as $key => $msg) {
  410. watchdog('trp-fsync', "%msg", array('%msg' => $msg), 'error');
  411. }
  412. exit;
  413. }
  414. else {
  415. $node = node_submit($new_node);
  416. node_save($node);
  417. }
  418. }
  419. else {
  420. $node = $chado_stock;
  421. }
  422. return '';
  423. }