tripal_stock.sync_stocks.inc

@todo Add file header description

File

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