tripal_core.chado_nodes.api.inc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. <?php
  2. /**
  3. * @file
  4. * API to handle much of the common functionality implemented when creating a drupal node type.
  5. */
  6. /**
  7. * @defgroup tripal_chado_node_api Chado Node API
  8. * @ingroup tripal_chado_api
  9. * @{
  10. * Many Tripal modules implement Drupal node types as a means of displaying chado
  11. * records individually through Drupal as a single web page. In order to do this, many of
  12. * the same drupal hooks are implemented and the code between modules is actually quite
  13. * similar. This API aims to abstract much of the common functionality in order to make
  14. * it easier for new Tripal modules to implement drupal node types and to centralize the
  15. * maintenance effort as much as possible.
  16. *
  17. * A generic sync form has been created. See chado_node_sync_form() for
  18. * instructions on how to implement this form in your module.
  19. *
  20. * Many of the base chado tables also have associated prop, _dbxref and _relationship
  21. * tables. Generic mini-forms have been created to help you handle these forms. To
  22. * implement this functionality you call the mini-form from your module node form and
  23. * then call the associated update functions from both your hook_insert and hook_update.
  24. * The functions of interest are as follows:
  25. * - chado_add_node_form_properties() and chado_update_node_form_properties()
  26. * to provide an interface for adding/removing properties
  27. * - chado_add_node_form_dbxrefs() and chado_update_node_form_dbxrefs()
  28. * to provide an interface for adding/removing additional database references
  29. * - chado_add_node_form_relationships() and chado_update_node_form_relationships()
  30. * to provide an interface for adding/removing relationships between chado records
  31. * from your base table
  32. * @}
  33. */
  34. /**
  35. * Sync'ing chado records with Drupal by creating nodes
  36. *
  37. * How to Use:
  38. * @code
  39. function modulename_menu() {
  40. $module_name = 'tripal_example'; // the machine name of your module
  41. $linking_table = 'chado_example'; // the base specified in hook_node_info
  42. // This menu item will be a tab on the admin/tripal/chado/tripal_example page
  43. // that is not selected by default
  44. $items['admin/tripal/chado/tripal_example/sync'] = array(
  45. 'title' => ' Sync',
  46. 'description' => 'Sync examples from Chado with Drupal',
  47. 'page callback' => 'drupal_get_form',
  48. 'page arguments' => array('chado_node_sync_form', $module_name, $linking_table),
  49. 'access arguments' => array('administer tripal examples'),
  50. 'type' => MENU_LOCAL_TASK,
  51. 'weight' => 0
  52. );
  53. return $items;
  54. }
  55. modulename_node_info() {
  56. return array(
  57. 'chado_example' => array(
  58. 'name' => t('example'),
  59. 'base' => 'chado_example',
  60. 'description' => t('A Chado example is a collection of material that can be sampled and have experiments performed on it.'),
  61. 'has_title' => TRUE,
  62. 'has_body' => FALSE,
  63. // this is what differs from the regular Drupal-documented hook_node_info()
  64. 'chado_node_api' => array(
  65. 'base_table' => 'example', // the name of the chado base table
  66. 'hook_prefix' => 'chado_example', // usually the name of the node type
  67. 'record_type_title' => array(
  68. 'singular' => t('Example'), // Singular human-readable title
  69. 'plural' => t('Examples') // Plural human-readable title
  70. ),
  71. 'sync_filters' => array( // filters for syncing
  72. 'type_id' => TRUE, // TRUE if there is an example.type_id field
  73. 'organism_id' => TRUE, // TRUE if there is an example.organism_id field
  74. 'checkboxes' => array('name') // If the 'checkboxes' key is present then the
  75. // value must be an array of column names in
  76. // base table. The values from these columns will
  77. // be retreived, contentated with a space delimeter
  78. // and provided in a list of checkboxes
  79. // for the user to choose which to sync.
  80. ),
  81. )
  82. ),
  83. );
  84. }
  85. // Create New Node
  86. // @param $new_node: a basic new node object
  87. // @param $record: the record object from chado specifying the biological data for this node
  88. function chado_example_chado_node_sync_create_new_node($new_node, $record) {
  89. // Add relevant chado details to the new node object
  90. // This really only needs to be the fields from the node used during node creation
  91. // including values used to generate the title, etc.
  92. // All additional chado data will be added via nodetype_load when the node is later used
  93. $new_node->uniquename = $record->uniquename;
  94. return $new_node;
  95. }
  96. // Alter the sync form (optional)
  97. function chado_example_chado_node_sync_form($form, $form_state) {
  98. // Change or add to the form array as needed
  99. // Any changes should be made in accordance with the Drupal Form API
  100. return $form;
  101. }
  102. // Bypass chado node api sync form submit (optional)
  103. // Allows you to use this function as your own submit
  104. function chado_example_chado_node_sync_form ($form, $form_state) {
  105. global $user;
  106. $job_args = array(
  107. $base_table, // the base chado table (ie: feature)
  108. $max_sync, // the maximum number of records to sync or FALSE for sync all that match
  109. $organism_id, // the organism_id to restrict records to or FALSE if not to restrict by organism_id
  110. $types // A string with the cvterm.name of the types to restrict to separated by |||
  111. );
  112. // You should register a tripal job
  113. tripal_add_job(
  114. $title, // the title of the job -be descriptive
  115. $module, // the name of your module
  116. 'chado_node_sync_records', // the chado node api sync function
  117. $job_args, // an array with the arguments to pass to the above function
  118. $user->uid // the user who submitted the job
  119. );
  120. }
  121. // Alter the query for the chado database which gets the chado records to be sync'd (optional)
  122. // @param $select: an array of select clauses
  123. // @param $joins: an array of joins (ie: a single join could be 'LEFT JOIN {chadotable} alias ON base.id=alias.id')
  124. // @param $where_clauses: an array of where clauses which will all be AND'ed together. Use :placeholders for values.
  125. // @param $where_args: an associative array of arguments to be subbed in to the where clause
  126. // where the key = :placeholder and the value is the actual argument to be subbed in
  127. function chado_example_chado_node_sync_select_query (&$select, &$joins, &$where_clauses, &$where_args) {
  128. // You can add fields to be selected
  129. $select[] = 'example.myfavfield';
  130. // Or joins to important tables
  131. $joins[] = 'LEFT JOIN {exampleprop} PROP ON PROP.example_id=EXAMPLE.example_id';
  132. // Or filter the query using where clauses
  133. $where_clauses[] = 'example.myfavfield = :favvalue';
  134. $where_args[':favvalue'] = 'awesome-ness';
  135. }
  136. * @endcode
  137. *
  138. * @ingroup tripal_chado_node_api
  139. */
  140. /**
  141. * Generic Sync Form
  142. *
  143. * @ingroup tripal_chado_node_api
  144. */
  145. function chado_node_sync_form($form, &$form_state) {
  146. $form = array();
  147. if (isset($form_state['build_info']['args'][0])) {
  148. $module = $form_state['build_info']['args'][0];
  149. $linking_table = $form_state['build_info']['args'][1];
  150. $node_info = call_user_func($module . '_node_info');
  151. $args = $node_info[$linking_table]['chado_node_api'];
  152. $form_state['chado_node_api'] = $args;
  153. }
  154. // define the fieldsets
  155. $form['sync'] = array(
  156. '#type' => 'fieldset',
  157. '#title' => 'Sync ' . $args['record_type_title']['plural'],
  158. '#descrpition' => '',
  159. );
  160. $form['sync']['description'] = array(
  161. '#type' => 'item',
  162. '#value' => t("%title_plural of the types listed ".
  163. "below in the %title_singular Types box will be synced (leave blank to sync all types). You may limit the ".
  164. "%title_plural to be synced by a specific organism. Depending on the ".
  165. "number of %title_plural in the chado database this may take a long ".
  166. "time to complete. ",
  167. array(
  168. '%title_singular' => $args['record_type_title']['singular'],
  169. '%title_plural' => $args['record_type_title']['plural']
  170. )),
  171. );
  172. if ($args['sync_filters']['type_id']) {
  173. $form['sync']['type_ids'] = array(
  174. '#title' => t('%title_singular Types',
  175. array(
  176. '%title_singular' => $args['record_type_title']['singular'],
  177. '%title_plural' => $args['record_type_title']['plural']
  178. )),
  179. '#type' => 'textarea',
  180. '#description' => t("Enter the names of the %title_singular types to sync. " .
  181. "Leave blank to sync all %title_plural. Separate each type with a comma ".
  182. "or new line. Pages for these %title_singular ".
  183. "types will be created automatically for %title_plural that exist in the ".
  184. "chado database. The names must match ".
  185. "exactly (spelling and case) with terms in the ontologies",
  186. array(
  187. '%title_singular' => strtolower($args['record_type_title']['singular']),
  188. '%title_plural' => strtolower($args['record_type_title']['plural'])
  189. )),
  190. '#default_value' => (isset($form_state['values']['type_id'])) ? $form_state['values']['type_id'] : '',
  191. );
  192. }
  193. // get the list of organisms
  194. if ($args['sync_filters']['organism_id']) {
  195. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  196. $results = chado_query($sql);
  197. $organisms[] = '';
  198. foreach ($results as $organism) {
  199. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  200. }
  201. $form['sync']['organism_id'] = array(
  202. '#title' => t('Organism'),
  203. '#type' => t('select'),
  204. '#description' => t("Choose the organism for which %title_plural types set above will be synced.",
  205. array(
  206. '%title_singular' => $args['record_type_title']['singular'],
  207. '%title_plural' => $args['record_type_title']['plural']
  208. )),
  209. '#options' => $organisms,
  210. '#default_value' => (isset($form_state['values']['organism_id'])) ? $form_state['values']['organism_id'] : 0,
  211. );
  212. }
  213. // get the list of organisms
  214. if (array_key_exists('checkboxes', $args['sync_filters'])) {
  215. // get the base schema
  216. $base_table = $args['base_table'];
  217. $table_info = chado_get_schema($base_table);
  218. // if the base table does not have a primary key or has more than one then
  219. // we can't proceed, otherwise, generate the checkboxes
  220. if (array_key_exists('primary key', $table_info) and count($table_info['primary key']) == 1) {
  221. $pkey = $table_info['primary key'][0];
  222. $columns = $args['sync_filters']['checkboxes'];
  223. $select_cols = implode("|| ' ' ||", $columns);
  224. // get non-synced records
  225. $sql = "
  226. SELECT BT.$pkey as id, $select_cols as value
  227. FROM {" . $base_table . "} BT
  228. LEFT JOIN public.$linking_table LT ON LT.$pkey = BT.$pkey
  229. WHERE LT.$pkey IS NULL
  230. ORDER BY value ASC
  231. ";
  232. $results = chado_query($sql);
  233. $values = array();
  234. foreach ($results as $result) {
  235. $values[$result->id] = $result->value;
  236. }
  237. if (count($values) > 0) {
  238. $form['sync']['ids'] = array(
  239. '#title' => 'Avaliable ' . $args['record_type_title']['plural'],
  240. '#type' => 'checkboxes',
  241. '#description' => t("The above %title_plural have not been synced. Check those to be synced or leave all unchecked to sync them all.",
  242. array(
  243. '%title_singular' => strtolower($args['record_type_title']['singular']),
  244. '%title_plural' => strtolower($args['record_type_title']['plural'])
  245. )),
  246. '#options' => $values,
  247. '#default_value' => (isset($form_state['values']['ids'])) ? $form_state['values']['ids'] : array(),
  248. '#prefix' => '<div style="height: 200px; overflow: scroll">',
  249. '#suffix' => '</div><br>',
  250. );
  251. }
  252. else {
  253. $form['sync']['no_ids'] = array(
  254. '#markup' => "<p>There are no " . strtolower($args['record_type_title']['plural']) . " to sync.</p>",
  255. );
  256. }
  257. }
  258. }
  259. // if we provide a list of checkboxes we shouldn't need a max_sync
  260. else {
  261. $form['sync']['max_sync'] = array(
  262. '#type' => 'textfield',
  263. '#title' => t('Maximum number of records to Sync'),
  264. '#description' => t('Leave this field empty to sync all records, regardless of number'),
  265. '#default_value' => (isset($form_state['values']['max_sync'])) ? $form_state['values']['max_sync'] : '',
  266. );
  267. }
  268. $form['sync']['button'] = array(
  269. '#type' => 'submit',
  270. '#value' => t('Sync ' . $args['record_type_title']['plural']),
  271. '#weight' => 3,
  272. );
  273. $form['cleanup'] = array(
  274. '#type' => 'fieldset',
  275. '#title' => t('Clean Up')
  276. );
  277. $form['cleanup']['description'] = array(
  278. '#markup' => t("<p>With Drupal and chado residing in different databases " .
  279. "it is possible that nodes in Drupal and " . strtolower($args['record_type_title']['plural']) . " in Chado become " .
  280. "\"orphaned\". This can occur if a node in Drupal is " .
  281. "deleted but the corresponding chado records is not and/or vice " .
  282. "versa. Click the button below to resolve these discrepancies.</p>"),
  283. '#weight' => 1,
  284. );
  285. $form['cleanup']['button'] = array(
  286. '#type' => 'submit',
  287. '#value' => 'Clean up orphaned ' . strtolower($args['record_type_title']['plural']),
  288. '#weight' => 2,
  289. );
  290. // Allow each module to alter this form as needed
  291. $hook_form_alter = $args['hook_prefix'] . '_chado_node_sync_form';
  292. if (function_exists($hook_form_alter)) {
  293. $form = call_user_func($hook_form_alter, $form, $form_state);
  294. }
  295. return $form;
  296. }
  297. /**
  298. * Generic Sync Form Submit
  299. *
  300. * @ingroup tripal_core
  301. */
  302. function chado_node_sync_form_submit($form, $form_state) {
  303. global $user;
  304. if (preg_match('/^Sync/', $form_state['values']['op'])) {
  305. // get arguments
  306. $args = $form_state['chado_node_api'];
  307. $module = $form_state['chado_node_api']['hook_prefix'];
  308. $base_table = $form_state['chado_node_api']['base_table'];
  309. // Allow each module to hijack the submit if needed
  310. $hook_form_hijack_submit = $args['hook_prefix'] . '_chado_node_sync_form_submit';
  311. if (function_exists($hook_form_hijack_submit)) {
  312. return call_user_func($hook_form_hijack_submit, $form, $form_state);
  313. }
  314. // Get the types separated into a consistent string
  315. $types = array();
  316. if (isset($form_state['values']['type_ids'])) {
  317. // seperate by new line or comma.
  318. $temp_types = preg_split("/[,\n\r]+/", $form_state['values']['type_ids']);
  319. // remove any extra spacing around the types
  320. for($i = 0; $i < count($temp_types); $i++) {
  321. // skip empty types
  322. if (trim($temp_types[$i]) == '') {
  323. continue;
  324. }
  325. $types[$i] = trim($temp_types[$i]);
  326. }
  327. }
  328. // Get the ids to be synced
  329. $ids = array();
  330. if (array_key_exists('ids', $form_state['values'])){
  331. foreach ($form_state['values']['ids'] as $id => $selected) {
  332. if ($selected) {
  333. $ids[] = $id;
  334. }
  335. }
  336. }
  337. // get the organism to be synced
  338. $organism_id = FALSE;
  339. if (array_key_exists('organism_id', $form_state['values'])) {
  340. $organism_id = $form_state['values']['organism_id'];
  341. }
  342. // Job Arguments
  343. $job_args = array(
  344. 'base_table' => $base_table,
  345. 'max_sync' => (!empty($form_state['values']['max_sync'])) ? $form_state['values']['max_sync'] : FALSE,
  346. 'organism_id' => $organism_id,
  347. 'types' => $types,
  348. 'ids' => $ids,
  349. );
  350. $title = "Sync " . $args['record_type_title']['plural'];
  351. tripal_add_job($title, $module, 'chado_node_sync_records', $job_args, $user->uid);
  352. }
  353. if (preg_match('/^Clean up orphaned/', $form_state['values']['op'])) {
  354. $module = $form_state['chado_node_api']['hook_prefix'];
  355. $base_table = $form_state['chado_node_api']['base_table'];
  356. $job_args = array($base_table);
  357. tripal_add_job($form_state['values']['op'], $module, 'chado_cleanup_orphaned_nodes', $job_args, $user->uid);
  358. }
  359. }
  360. /**
  361. * Actual Sync Function. Works on a group of records
  362. *
  363. * @ingroup tripal_chado_node_api
  364. */
  365. function chado_node_sync_records($base_table, $max_sync = FALSE, $organism_id = FALSE,
  366. $types = array(), $ids = array(), $job_id = NULL) {
  367. global $user;
  368. $base_table_id = $base_table . '_id';
  369. print "\nSync'ing $base_table records. ";
  370. // START BUILDING QUERY TO GET ALL RECORD FROM BASE TABLE THAT MATCH
  371. $select = array("$base_table.*");
  372. $joins = array();
  373. $where_clauses = array();
  374. $where_args = array();
  375. // If types are supplied then handle them
  376. $restrictions = '';
  377. if (count($types) > 0) {
  378. $restrictions .= " Type(s): " . implode(', ',$types) . "\n";
  379. $select[] = 'cvterm.name as cvtname';
  380. $joins[] = "LEFT JOIN {cvterm} cvterm ON $base_table.type_id = cvterm.cvterm_id";
  381. foreach ($types as $type) {
  382. $where_clauses['type'][] = "cvterm.name = :type_name_$type";
  383. $where_args['type'][":type_name_$type"] = $type;
  384. }
  385. }
  386. // if IDs have been supplied
  387. if ($ids) {
  388. $restrictions .= " Specific Records: " . count($ids) . " recored(s) specified.\n";
  389. foreach ($ids as $id) {
  390. $where_clauses['id'][] = "$base_table.$base_table_id = :id_$id";
  391. $where_args['id'][":id_$id"] = $id;
  392. }
  393. }
  394. // If Organism is supplied
  395. if ($organism_id) {
  396. $organism = chado_select_record('organism', array('*'), array('organism_id' => $organism_id));
  397. $restrictions .= " Organism: " . $organism[0]->genus . " " . $organism[0]->species . "\n";
  398. $select[] = 'organism.*';
  399. $joins[] = "LEFT JOIN {organism} organism ON organism.organism_id = $base_table.organism_id";
  400. $where_clauses['organism'][] = 'organism.organism_id = :organism_id';
  401. $where_args['organism'][':organism_id'] = $organism_id;
  402. }
  403. // Allow module to add to query
  404. $hook_query_alter = 'chado_' . $base_table . '_chado_node_sync_select_query';
  405. if (function_exists($hook_query_alter)) {
  406. call_user_func($hook_query_alter, $select, $joins, $where_clauses, $where_args);
  407. }
  408. // Build Query, we do a left join on the chado_xxxx table in the Drupal schema
  409. // so that if no criteria are specified we only get those items that have not
  410. // yet been synced.
  411. $query = "
  412. SELECT " . implode(', ',$select) . ' ' .
  413. 'FROM {' . $base_table . '} ' . $base_table . ' ' . implode(' ', $joins) . ' '.
  414. " LEFT JOIN public.chado_$base_table CT ON CT.$base_table_id = $base_table.$base_table_id " .
  415. "WHERE CT.$base_table_id IS NULL AND";
  416. // extend the where clause if needed
  417. $where = '';
  418. $sql_args = array();
  419. if (count($where_clauses['type']) > 0) {
  420. $where .= '(' . implode(' OR ', $where_clauses['type']) . ') AND';
  421. $sql_args = array_merge($sql_args, $where_args['type']);
  422. }
  423. if (count($where_clauses['organism']) > 0) {
  424. $where .= '(' . implode(' OR ', $where_clauses['organism']) . ') AND';
  425. $sql_args = array_merge($sql_args, $where_args['organism']);
  426. }
  427. if (count($where_clauses['id']) > 0) {
  428. $where .= '(' . implode(' OR ', $where_clauses['id']) . ') AND';
  429. $sql_args = array_merge($sql_args, $where_args['id']);
  430. }
  431. if ($where) {
  432. $query .= $where;
  433. }
  434. $query = substr($query, 0, -4); // remove the trailing 'AND'
  435. $query .- " ORDER BY " . $base_table_id;
  436. // If Maximum number to Sync is supplied
  437. if ($max_sync) {
  438. $query .= " LIMIT $max_sync";
  439. $restrictions .= " Limited to $max_sync records.\n";
  440. }
  441. if ($restrictions) {
  442. print "Records matching these criteria will be synced: \n$restrictions";
  443. }
  444. else {
  445. print "\n";
  446. }
  447. // execute the query
  448. $results = chado_query($query, $sql_args);
  449. // Iterate through features that need to be synced
  450. $count = $results->rowCount();
  451. $interval = intval($count * 0.01);
  452. if ($interval < 1) {
  453. $interval = 1;
  454. }
  455. print "\n$count $base_table records found.\n";
  456. $i = 0;
  457. $transaction = db_transaction();
  458. try {
  459. foreach ($results as $record) {
  460. print "\nLoading $base_table " . ($i + 1) . " of $count ($base_table_id=".$record->{$base_table_id}.")...";
  461. // update the job status every 1% features
  462. if ($job_id and $i % $interval == 0) {
  463. $percent = sprintf("%.2f", ($i / $count) * 100);
  464. print "Parsing Line $line_num (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\n";
  465. tripal_set_job_progress($job_id, intval(($i/$count)*100));
  466. }
  467. // Check if it is in the chado linking table (ie: check to see if it is already linked to a node)
  468. $result = db_select('chado_'.$base_table, 'lnk')
  469. ->fields('lnk',array('nid'))
  470. ->condition($base_table_id, $record->{$base_table_id}, '=')
  471. ->execute()
  472. ->fetchObject();
  473. if (!empty($result)) {
  474. print " Previously Sync'd";
  475. }
  476. else {
  477. // Create generic new node
  478. $new_node = new stdClass();
  479. $new_node->type = 'chado_' . $base_table;
  480. $new_node->uid = $user->uid;
  481. $new_node->{$base_table_id} = $record->{$base_table_id};
  482. $new_node->$base_table = $record;
  483. // TODO: should we get rid of this hook and use hook_node_presave() instead?
  484. // allow base module to set additional fields as needed
  485. $hook_create_new_node = 'chado_' . $base_table . '_chado_node_sync_create_new_node';
  486. if (function_exists($hook_create_new_node)) {
  487. $new_node = call_user_func($hook_create_new_node, $new_node, $record);
  488. }
  489. // Validate and Save New Node
  490. $form = array();
  491. $form_state = array();
  492. node_validate($new_node, $form, $form_state);
  493. if (!form_get_errors()) {
  494. $node = node_submit($new_node);
  495. node_save($node);
  496. print " Node Created (nid=".$node->nid.")";
  497. }
  498. else {
  499. watchdog('trp-fsync', "Failed to insert $base_table: %title", array('%title' => $new_node->title), WATCHDOG_ERROR);
  500. }
  501. }
  502. $i++;
  503. }
  504. print "\n\nComplete!\n";
  505. }
  506. catch (Exception $e) {
  507. print "\n"; // make sure we start errors on new line
  508. watchdog_exception('trp-fsync', $e);
  509. $transaction->rollback();
  510. print "FAILED: Rolling back database changes...\n";
  511. }
  512. }
  513. /**
  514. * This function will delete Drupal nodes for any sync'ed table (e.g.
  515. * feature, organism, analysis, stock, library) if the chado record has been
  516. * deleted or the entry in the chado_[table] table has been removed.
  517. *
  518. * @param $table
  519. * The name of the table that corresonds to the node type we want to clean up.
  520. * @param $job_id
  521. * This should be the job id from the Tripal jobs system. This function
  522. * will update the job status using the provided job ID.
  523. *
  524. * @ingroup tripal_chado_node_api
  525. */
  526. function chado_cleanup_orphaned_nodes($table, $job_id = NULL) {
  527. $count = 0;
  528. // build the SQL statments needed to check if nodes point to valid analyses
  529. $dsql = "SELECT * FROM {node} WHERE type = 'chado_" . $table . "' order by nid";
  530. $nsql = "SELECT * FROM {node} WHERE nid = :nid";
  531. $csql = "SELECT * FROM {chado_" . $table . "} WHERE nid = :nid ";
  532. $clsql= "SELECT * FROM {chado_" . $table . "}";
  533. $lsql = "SELECT * FROM {" . $table . "} where " . $table . "_id = :" . $table . "_id ";
  534. // load into nodes array
  535. print "Getting nodes\n";
  536. $nodes = array();
  537. $res = db_query($dsql);
  538. foreach ($res as $node) {
  539. $nodes[$count] = $node;
  540. $count++;
  541. }
  542. // load the chado_$table into an array
  543. print "Getting chado_$table\n";
  544. $cnodes = array();
  545. $res = db_query($clsql);
  546. foreach ($res as $node) {
  547. $cnodes[$count] = $node;
  548. $count++;
  549. }
  550. $interval = intval($count * 0.01);
  551. if ($interval < 1) {
  552. $interval = 1;
  553. }
  554. // iterate through all of the chado_$table entries and remove those
  555. // that don't have a node or don't have a $table record in chado.libary
  556. print "Verifying all chado_$table Entries\n";
  557. $deleted = 0;
  558. foreach ($cnodes as $nid) {
  559. // update the job status every 1% analyses
  560. if ($job_id and $i % $interval == 0) {
  561. tripal_set_job_progress($job_id, intval(($i / $count) * 100));
  562. }
  563. // see if the node exits, if not remove the entry from the chado_$table table
  564. $results = db_query($nsql, array(':nid' => $nid->nid));
  565. $node = $results->fetchObject();
  566. if (!$node) {
  567. $deleted++;
  568. db_query("DELETE FROM {chado_" . $table . "} WHERE nid = :nid", array(':nid' => $nid->nid));
  569. $message = "chado_$table missing node.... DELETING: $nid->nid";
  570. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  571. }
  572. // see if the record in chado exist, if not remove the entry from the chado_$table
  573. $table_id = $table . "_id";
  574. $results = chado_query($lsql, array(":" . $table . "_id" => $nid->$table_id));
  575. $record = $results->fetchObject();
  576. if (!$record) {
  577. $deleted++;
  578. $sql = "DELETE FROM {chado_" . $table . "} WHERE " . $table . "_id = :" . $table . "_id";
  579. db_query($sql, array(":" . $table . "_id" => $nid->$table_id));
  580. $message = "chado_$table missing $table.... DELETING entry.";
  581. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  582. }
  583. $i++;
  584. }
  585. print "\t$deleted chado_$table entries missing either a node or chado entry.\n";
  586. // iterate through all of the nodes and delete those that don't
  587. // have a corresponding entry in chado_$table
  588. $deleted = 0;
  589. foreach ($nodes as $node) {
  590. // update the job status every 1% libraries
  591. if ($job_id and $i % $interval == 0) {
  592. tripal_set_job_progress($job_id, intval(($i / $count) * 100));
  593. }
  594. // check to see if the node has a corresponding entry
  595. // in the chado_$table table. If not then delete the node.
  596. $results = db_query($csql, array(":nid" => $node->nid));
  597. $link = $results->fetchObject();
  598. if (!$link) {
  599. if (node_access('delete', $node)) {
  600. $deleted++;
  601. $message = "Node missing in chado_$table table.... DELETING node $node->nid";
  602. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  603. node_delete($node->nid);
  604. }
  605. else {
  606. $message = "Node missing in chado_$table table.... but cannot delete due to improper permissions (node $node->nid)";
  607. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  608. }
  609. }
  610. $i++;
  611. }
  612. print "\t$deleted nodes did not have corresponding chado_$table entries.\n";
  613. return '';
  614. }