tripal_core.chado_nodes.api.inc 27 KB

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