tripal_core.chado_nodes.api.inc 27 KB

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