tripal_core.chado_nodes.api.inc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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. * Get chado id for a node. E.g, if you want to get 'analysis_id' from the
  36. * 'analysis' table for a synced 'chado_analysis' node, (the same for
  37. * organisms and features):
  38. * $analysis_id = chado_get_id_from_nid ('analysis', $node->nid)
  39. * $organism_id = chado_get_id_from_nid ('organism', $node->nid)
  40. * $feature_id = chado_get_id_from_nid ('feature', $node->nid)
  41. *
  42. * @param $table
  43. * The chado table the chado record is from
  44. * @param $nid
  45. * The value of the primary key of node
  46. * @param $linking_table
  47. * The Drupal table linking the chado record to it's node.
  48. * This field is optional and defaults to chado_$table
  49. *
  50. * @return
  51. * The chado id of the associated chado record
  52. *
  53. * @ingroup tripal_chado_node_api
  54. */
  55. function chado_get_id_from_nid($table, $nid, $linking_table = NULL) {
  56. if (empty($linking_table)) {
  57. $linking_table = 'chado_' . $table;
  58. }
  59. $sql = "SELECT " . $table . "_id as id FROM {$linking_table} WHERE nid = :nid";
  60. return db_query($sql, array(':nid' => $nid))->fetchField();
  61. }
  62. /**
  63. * Get node id for a chado feature/organism/analysis. E.g, if you want to
  64. * get the node id for an analysis, use:
  65. * $nid = chado_get_nid_from_id ('analysis', $analysis_id)
  66. * Likewise,
  67. * $nid = chado_get_nid_from_id ('organism', $organism_id)
  68. * $nid = chado_get_nid_from_id ('feature', $feature_id)
  69. *
  70. * @param $table
  71. * The chado table the id is from
  72. * @param $id
  73. * The value of the primary key from the $table chado table (ie: feature_id)
  74. * @param $linking_table
  75. * The Drupal table linking the chado record to it's node.
  76. * This field is optional and defaults to chado_$table
  77. *
  78. * @return
  79. * The nid of the associated node
  80. *
  81. * @ingroup tripal_chado_node_api
  82. */
  83. function chado_get_nid_from_id($table, $id, $linking_table = NULL) {
  84. if (empty($linking_table)) {
  85. $linking_table = 'chado_' . $table;
  86. }
  87. $sql = "SELECT nid FROM {" . $linking_table . "} WHERE " . $table . "_id = :" . $table . "_id";
  88. return db_query($sql, array(":" . $table . "_id" => $id))->fetchField();
  89. }
  90. /**
  91. * Generic Sync Form to aid in sync'ing (create drupal nodes linking to chado content)
  92. * any chado node type.
  93. *
  94. * To use this you need to add a call to it from your hook_menu() and
  95. * add some additional information to your hook_node_info(). The Following code gives an
  96. * example of how this might be done:
  97. * @code
  98. function modulename_menu() {
  99. $module_name = 'tripal_example'; // the machine name of your module
  100. $linking_table = 'chado_example'; // the base specified in hook_node_info
  101. // This menu item will be a tab on the admin/tripal/chado/tripal_example page
  102. // that is not selected by default
  103. $items['admin/tripal/chado/tripal_example/sync'] = array(
  104. 'title' => ' Sync',
  105. 'description' => 'Sync examples from Chado with Drupal',
  106. 'page callback' => 'drupal_get_form',
  107. 'page arguments' => array('chado_node_sync_form', $module_name, $linking_table),
  108. 'access arguments' => array('administer tripal examples'),
  109. 'type' => MENU_LOCAL_TASK,
  110. 'weight' => 0
  111. );
  112. return $items;
  113. }
  114. function modulename_node_info() {
  115. return array(
  116. 'chado_example' => array(
  117. 'name' => t('example'),
  118. 'base' => 'chado_example',
  119. 'description' => t('A Chado example is a collection of material that can be sampled and have experiments performed on it.'),
  120. 'has_title' => TRUE,
  121. 'locked' => TRUE,
  122. // this is what differs from the regular Drupal-documented hook_node_info()
  123. 'chado_node_api' => array(
  124. 'base_table' => 'example', // the name of the chado base table
  125. 'hook_prefix' => 'chado_example', // usually the name of the node type
  126. 'record_type_title' => array(
  127. 'singular' => t('Example'), // Singular human-readable title
  128. 'plural' => t('Examples') // Plural human-readable title
  129. ),
  130. 'sync_filters' => array( // filters for syncing
  131. 'type_id' => TRUE, // TRUE if there is an example.type_id field
  132. 'organism_id' => TRUE, // TRUE if there is an example.organism_id field
  133. 'checkboxes' => array('name') // If the 'checkboxes' key is present then the
  134. // value must be an array of column names in
  135. // base table. The values from these columns will
  136. // be retreived, contentated with a space delimeter
  137. // and provided in a list of checkboxes
  138. // for the user to choose which to sync.
  139. ),
  140. )
  141. ),
  142. );
  143. }
  144. * @endcode
  145. *
  146. * For more information on how you can override some of this behaviour while still
  147. * benifiting from as much of the common architecture as possible see the following
  148. * functions: hook_chado_node_sync_create_new_node(), hook_chado_node_sync_form(),
  149. * hook_chado_node_sync_select_query().
  150. *
  151. * @ingroup tripal_chado_node_api
  152. */
  153. function chado_node_sync_form($form, &$form_state) {
  154. $form = array();
  155. if (isset($form_state['build_info']['args'][0])) {
  156. $module = $form_state['build_info']['args'][0];
  157. $linking_table = $form_state['build_info']['args'][1];
  158. $node_info = call_user_func($module . '_node_info');
  159. $args = $node_info[$linking_table]['chado_node_api'];
  160. $form_state['chado_node_api'] = $args;
  161. }
  162. $form['linking_table'] = array(
  163. '#type' => 'hidden',
  164. '#value' => $linking_table
  165. );
  166. // define the fieldsets
  167. $form['sync'] = array(
  168. '#type' => 'fieldset',
  169. '#title' => 'Sync ' . $args['record_type_title']['plural'],
  170. '#descrpition' => '',
  171. );
  172. $form['sync']['description'] = array(
  173. '#type' => 'item',
  174. '#value' => t("%title_plural of the types listed ".
  175. "below in the %title_singular Types box will be synced (leave blank to sync all types). You may limit the ".
  176. "%title_plural to be synced by a specific organism. Depending on the ".
  177. "number of %title_plural in the chado database this may take a long ".
  178. "time to complete. ",
  179. array(
  180. '%title_singular' => $args['record_type_title']['singular'],
  181. '%title_plural' => $args['record_type_title']['plural']
  182. )),
  183. );
  184. if ($args['sync_filters']['type_id']) {
  185. $form['sync']['type_ids'] = array(
  186. '#title' => t('%title_singular Types',
  187. array(
  188. '%title_singular' => $args['record_type_title']['singular'],
  189. '%title_plural' => $args['record_type_title']['plural']
  190. )),
  191. '#type' => 'textarea',
  192. '#description' => t("Enter the names of the %title_singular types to sync. " .
  193. "Leave blank to sync all %title_plural. Separate each type with a comma ".
  194. "or new line. Pages for these %title_singular ".
  195. "types will be created automatically for %title_plural that exist in the ".
  196. "chado database. The names must match ".
  197. "exactly (spelling and case) with terms in the ontologies",
  198. array(
  199. '%title_singular' => strtolower($args['record_type_title']['singular']),
  200. '%title_plural' => strtolower($args['record_type_title']['plural'])
  201. )),
  202. '#default_value' => (isset($form_state['values']['type_id'])) ? $form_state['values']['type_id'] : '',
  203. );
  204. }
  205. // get the list of organisms
  206. if ($args['sync_filters']['organism_id']) {
  207. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  208. $results = chado_query($sql);
  209. $organisms[] = '';
  210. foreach ($results as $organism) {
  211. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  212. }
  213. $form['sync']['organism_id'] = array(
  214. '#title' => t('Organism'),
  215. '#type' => t('select'),
  216. '#description' => t("Choose the organism for which %title_plural types set above will be synced.",
  217. array(
  218. '%title_singular' => $args['record_type_title']['singular'],
  219. '%title_plural' => $args['record_type_title']['plural']
  220. )),
  221. '#options' => $organisms,
  222. '#default_value' => (isset($form_state['values']['organism_id'])) ? $form_state['values']['organism_id'] : 0,
  223. );
  224. }
  225. // get the list of organisms
  226. if (array_key_exists('checkboxes', $args['sync_filters'])) {
  227. // get the base schema
  228. $base_table = $args['base_table'];
  229. $table_info = chado_get_schema($base_table);
  230. // if the base table does not have a primary key or has more than one then
  231. // we can't proceed, otherwise, generate the checkboxes
  232. if (array_key_exists('primary key', $table_info) and count($table_info['primary key']) == 1) {
  233. $pkey = $table_info['primary key'][0];
  234. $columns = $args['sync_filters']['checkboxes'];
  235. $select_cols = implode("|| ' ' ||", $columns);
  236. // get non-synced records
  237. $sql = "
  238. SELECT BT.$pkey as id, $select_cols as value
  239. FROM {" . $base_table . "} BT
  240. LEFT JOIN public.$linking_table LT ON LT.$pkey = BT.$pkey
  241. WHERE LT.$pkey IS NULL
  242. ORDER BY value ASC
  243. ";
  244. $results = chado_query($sql);
  245. $values = array();
  246. foreach ($results as $result) {
  247. $values[$result->id] = $result->value;
  248. }
  249. if (count($values) > 0) {
  250. $form['sync']['ids'] = array(
  251. '#title' => 'Avaliable ' . $args['record_type_title']['plural'],
  252. '#type' => 'checkboxes',
  253. '#options' => $values,
  254. '#default_value' => (isset($form_state['values']['ids'])) ? $form_state['values']['ids'] : array(),
  255. '#suffix' => '</div><br>',
  256. '#prefix' => t("The following %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. )) . '<div style="height: 200px; overflow: scroll">',
  261. );
  262. }
  263. else {
  264. $form['sync']['no_ids'] = array(
  265. '#markup' => "<p>There are no " . strtolower($args['record_type_title']['plural']) . " to sync.</p>",
  266. );
  267. }
  268. }
  269. }
  270. // if we provide a list of checkboxes we shouldn't need a max_sync
  271. else {
  272. $form['sync']['max_sync'] = array(
  273. '#type' => 'textfield',
  274. '#title' => t('Maximum number of records to Sync'),
  275. '#description' => t('Leave this field empty to sync all records, regardless of number'),
  276. '#default_value' => (isset($form_state['values']['max_sync'])) ? $form_state['values']['max_sync'] : '',
  277. );
  278. }
  279. $form['sync']['button'] = array(
  280. '#type' => 'submit',
  281. '#value' => t('Sync ' . $args['record_type_title']['plural']),
  282. '#weight' => 3,
  283. );
  284. $form['cleanup'] = array(
  285. '#type' => 'fieldset',
  286. '#title' => t('Clean Up')
  287. );
  288. $form['cleanup']['description'] = array(
  289. '#markup' => t("<p>With Drupal and chado residing in different databases " .
  290. "it is possible that nodes in Drupal and " . strtolower($args['record_type_title']['plural']) . " in Chado become " .
  291. "\"orphaned\". This can occur if a node in Drupal is " .
  292. "deleted but the corresponding chado records is not and/or vice " .
  293. "versa. Click the button below to resolve these discrepancies.</p>"),
  294. '#weight' => 1,
  295. );
  296. $form['cleanup']['button'] = array(
  297. '#type' => 'submit',
  298. '#value' => 'Clean up orphaned ' . strtolower($args['record_type_title']['plural']),
  299. '#weight' => 2,
  300. );
  301. // Allow each module to alter this form as needed
  302. $hook_form_alter = $args['hook_prefix'] . '_chado_node_sync_form';
  303. if (function_exists($hook_form_alter)) {
  304. $form = call_user_func($hook_form_alter, $form, $form_state);
  305. }
  306. return $form;
  307. }
  308. /**
  309. * Generic Sync Form Submit
  310. *
  311. * @ingroup tripal_core
  312. */
  313. function chado_node_sync_form_submit($form, $form_state) {
  314. global $user;
  315. if (preg_match('/^Sync/', $form_state['values']['op'])) {
  316. // get arguments
  317. $args = $form_state['chado_node_api'];
  318. $module = $form_state['chado_node_api']['hook_prefix'];
  319. $base_table = $form_state['chado_node_api']['base_table'];
  320. $linking_table = $form_state['values']['linking_table'];
  321. // Allow each module to hijack the submit if needed
  322. $hook_form_hijack_submit = $args['hook_prefix'] . '_chado_node_sync_form_submit';
  323. if (function_exists($hook_form_hijack_submit)) {
  324. return call_user_func($hook_form_hijack_submit, $form, $form_state);
  325. }
  326. // Get the types separated into a consistent string
  327. $types = array();
  328. if (isset($form_state['values']['type_ids'])) {
  329. // seperate by new line or comma.
  330. $temp_types = preg_split("/[,\n\r]+/", $form_state['values']['type_ids']);
  331. // remove any extra spacing around the types
  332. for($i = 0; $i < count($temp_types); $i++) {
  333. // skip empty types
  334. if (trim($temp_types[$i]) == '') {
  335. continue;
  336. }
  337. $types[$i] = trim($temp_types[$i]);
  338. }
  339. }
  340. // Get the ids to be synced
  341. $ids = array();
  342. if (array_key_exists('ids', $form_state['values'])){
  343. foreach ($form_state['values']['ids'] as $id => $selected) {
  344. if ($selected) {
  345. $ids[] = $id;
  346. }
  347. }
  348. }
  349. // get the organism to be synced
  350. $organism_id = FALSE;
  351. if (array_key_exists('organism_id', $form_state['values'])) {
  352. $organism_id = $form_state['values']['organism_id'];
  353. }
  354. // Job Arguments
  355. $job_args = array(
  356. 'base_table' => $base_table,
  357. 'max_sync' => (!empty($form_state['values']['max_sync'])) ? $form_state['values']['max_sync'] : FALSE,
  358. 'organism_id' => $organism_id,
  359. 'types' => $types,
  360. 'ids' => $ids,
  361. 'inking_table' => $linking_table
  362. );
  363. $title = "Sync " . $args['record_type_title']['plural'];
  364. tripal_add_job($title, $module, 'chado_node_sync_records', $job_args, $user->uid);
  365. }
  366. if (preg_match('/^Clean up orphaned/', $form_state['values']['op'])) {
  367. $module = $form_state['chado_node_api']['hook_prefix'];
  368. $base_table = $form_state['chado_node_api']['base_table'];
  369. $job_args = array($base_table);
  370. tripal_add_job($form_state['values']['op'], $module, 'chado_cleanup_orphaned_nodes', $job_args, $user->uid);
  371. }
  372. }
  373. /**
  374. * Actual Sync Function. Works on a group of records
  375. *
  376. * @ingroup tripal_chado_node_api
  377. */
  378. function chado_node_sync_records($base_table, $max_sync = FALSE, $organism_id = FALSE,
  379. $types = array(), $ids = array(), $linking_table = FALSE, $job_id = NULL) {
  380. global $user;
  381. $base_table_id = $base_table . '_id';
  382. if (!$linking_table) {
  383. $linking_table = 'chado_' . $base_table;
  384. }
  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 = $linking_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.$linking_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 records 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($linking_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 = $linking_table;
  496. $new_node->uid = $user->uid;
  497. $new_node->{$base_table_id} = $record->{$base_table_id};
  498. $new_node->$base_table = $record;
  499. $new_node->language = LANGUAGE_NONE;
  500. // TODO: should we get rid of this hook and use hook_node_presave() instead?
  501. // allow base module to set additional fields as needed
  502. $hook_create_new_node = $linking_table . '_chado_node_sync_create_new_node';
  503. if (function_exists($hook_create_new_node)) {
  504. $new_node = call_user_func($hook_create_new_node, $new_node, $record);
  505. }
  506. // Validate and Save New Node
  507. $form = array();
  508. $form_state = array();
  509. node_validate($new_node, $form, $form_state);
  510. if (!form_get_errors()) {
  511. $node = node_submit($new_node);
  512. node_save($node);
  513. print " Node Created (nid=".$node->nid.")";
  514. }
  515. else {
  516. watchdog('trp-fsync', "Failed to insert $base_table: %title", array('%title' => $new_node->title), WATCHDOG_ERROR);
  517. }
  518. }
  519. $i++;
  520. }
  521. print "\n\nComplete!\n";
  522. }
  523. catch (Exception $e) {
  524. print "\n"; // make sure we start errors on new line
  525. watchdog_exception('trp-fsync', $e);
  526. $transaction->rollback();
  527. print "FAILED: Rolling back database changes...\n";
  528. }
  529. }
  530. /**
  531. * This function will delete Drupal nodes for any sync'ed table (e.g.
  532. * feature, organism, analysis, stock, library) if the chado record has been
  533. * deleted or the entry in the chado_[table] table has been removed.
  534. *
  535. * @param $table
  536. * The name of the table that corresonds to the node type we want to clean up.
  537. * @param $job_id
  538. * This should be the job id from the Tripal jobs system. This function
  539. * will update the job status using the provided job ID.
  540. *
  541. * @ingroup tripal_chado_node_api
  542. */
  543. function chado_cleanup_orphaned_nodes($table, $job_id = NULL) {
  544. $count = 0;
  545. // build the SQL statments needed to check if nodes point to valid analyses
  546. $dsql = "SELECT * FROM {node} WHERE type = 'chado_" . $table . "' order by nid";
  547. $nsql = "SELECT * FROM {node} WHERE nid = :nid";
  548. $csql = "SELECT * FROM {chado_" . $table . "} WHERE nid = :nid ";
  549. $clsql= "SELECT * FROM {chado_" . $table . "}";
  550. $lsql = "SELECT * FROM {" . $table . "} where " . $table . "_id = :" . $table . "_id ";
  551. // load into nodes array
  552. print "Getting nodes\n";
  553. $nodes = array();
  554. $res = db_query($dsql);
  555. foreach ($res as $node) {
  556. $nodes[$count] = $node;
  557. $count++;
  558. }
  559. // load the chado_$table into an array
  560. print "Getting chado_$table\n";
  561. $cnodes = array();
  562. $res = db_query($clsql);
  563. foreach ($res as $node) {
  564. $cnodes[$count] = $node;
  565. $count++;
  566. }
  567. $interval = intval($count * 0.01);
  568. if ($interval < 1) {
  569. $interval = 1;
  570. }
  571. // iterate through all of the chado_$table entries and remove those
  572. // that don't have a node or don't have a $table record in chado.libary
  573. print "Verifying all chado_$table Entries\n";
  574. $deleted = 0;
  575. foreach ($cnodes as $nid) {
  576. // update the job status every 1% analyses
  577. if ($job_id and $i % $interval == 0) {
  578. tripal_set_job_progress($job_id, intval(($i / $count) * 100));
  579. }
  580. // see if the node exits, if not remove the entry from the chado_$table table
  581. $results = db_query($nsql, array(':nid' => $nid->nid));
  582. $node = $results->fetchObject();
  583. if (!$node) {
  584. $deleted++;
  585. db_query("DELETE FROM {chado_" . $table . "} WHERE nid = :nid", array(':nid' => $nid->nid));
  586. $message = "chado_$table missing node.... DELETING: $nid->nid";
  587. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  588. }
  589. // see if the record in chado exist, if not remove the entry from the chado_$table
  590. $table_id = $table . "_id";
  591. $results = chado_query($lsql, array(":" . $table . "_id" => $nid->$table_id));
  592. $record = $results->fetchObject();
  593. if (!$record) {
  594. $deleted++;
  595. $sql = "DELETE FROM {chado_" . $table . "} WHERE " . $table . "_id = :" . $table . "_id";
  596. db_query($sql, array(":" . $table . "_id" => $nid->$table_id));
  597. $message = "chado_$table missing $table.... DELETING entry.";
  598. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  599. }
  600. $i++;
  601. }
  602. print "\t$deleted chado_$table entries missing either a node or chado entry.\n";
  603. // iterate through all of the nodes and delete those that don't
  604. // have a corresponding entry in chado_$table
  605. $deleted = 0;
  606. foreach ($nodes as $node) {
  607. // update the job status every 1% libraries
  608. if ($job_id and $i % $interval == 0) {
  609. tripal_set_job_progress($job_id, intval(($i / $count) * 100));
  610. }
  611. // check to see if the node has a corresponding entry
  612. // in the chado_$table table. If not then delete the node.
  613. $results = db_query($csql, array(":nid" => $node->nid));
  614. $link = $results->fetchObject();
  615. if (!$link) {
  616. if (node_access('delete', $node)) {
  617. $deleted++;
  618. $message = "Node missing in chado_$table table.... DELETING node $node->nid";
  619. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  620. node_delete($node->nid);
  621. }
  622. else {
  623. $message = "Node missing in chado_$table table.... but cannot delete due to improper permissions (node $node->nid)";
  624. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  625. }
  626. }
  627. $i++;
  628. }
  629. print "\t$deleted nodes did not have corresponding chado_$table entries.\n";
  630. return '';
  631. }
  632. /**
  633. * Create New Node
  634. *
  635. * Note: For your own module, replace hook in the function name with the machine-name of
  636. * your chado node type (ie: chado_feature).
  637. *
  638. * @param $new_node:
  639. * a basic new node object
  640. * @param $record:
  641. * the record object from chado specifying the biological data for this node
  642. *
  643. * @return
  644. * A node object containing all the fields necessary to create a new node during sync
  645. *
  646. * @ingroup tripal_chado_node_api
  647. */
  648. function hook_chado_node_sync_create_new_node($new_node, $record) {
  649. // Add relevant chado details to the new node object
  650. // This really only needs to be the fields from the node used during node creation
  651. // including values used to generate the title, etc.
  652. // All additional chado data will be added via nodetype_load when the node is later used
  653. $new_node->uniquename = $record->uniquename;
  654. return $new_node;
  655. }
  656. /**
  657. * Alter the sync form (optional)
  658. *
  659. * This might be necessary if you need additional filtering options for choosing which
  660. * chado records to sync or even if you just want to further customize the help text
  661. * provided by the form.
  662. *
  663. * Note: For your own module, replace hook in the function name with the machine-name of
  664. * your chado node type (ie: chado_feature).
  665. *
  666. * @ingroup tripal_chado_node_api
  667. */
  668. function hook_chado_node_sync_form($form, $form_state) {
  669. // Change or add to the form array as needed
  670. // Any changes should be made in accordance with the Drupal Form API
  671. return $form;
  672. }
  673. /**
  674. * Bypass chado node api sync form submit (optional). Allows you to use this function
  675. * as your own submit.
  676. *
  677. * This might be necessary if you want to add additional arguements to the tripal job or
  678. * to call your own sync'ing function if the generic chado_node_sync_records() is not
  679. * sufficient.
  680. *
  681. * Note: For your own module, replace hook in the function name with the machine-name of
  682. * your chado node type (ie: chado_feature).
  683. *
  684. * @ingroup tripal_chado_node_api
  685. */
  686. function hook_chado_node_sync_form_submit ($form, $form_state) {
  687. global $user;
  688. $job_args = array(
  689. $base_table, // the base chado table (ie: feature)
  690. $max_sync, // the maximum number of records to sync or FALSE for sync all that match
  691. $organism_id, // the organism_id to restrict records to or FALSE if not to restrict by organism_id
  692. $types // A string with the cvterm.name of the types to restrict to separated by |||
  693. );
  694. // You should register a tripal job
  695. tripal_add_job(
  696. $title, // the title of the job -be descriptive
  697. $module, // the name of your module
  698. 'chado_node_sync_records', // the chado node api sync function
  699. $job_args, // an array with the arguments to pass to the above function
  700. $user->uid // the user who submitted the job
  701. );
  702. }
  703. /**
  704. * Alter the query for the chado database which gets the chado records to be sync'd (optional)
  705. *
  706. * This might be necessary if you need fields from other chado tables to create your node
  707. * or if your chado node type only supports a subset of a given table (ie: a germplasm node
  708. * type might only support node creation for cerain types of stock records in which case
  709. * you would need to filter the results to only those types).
  710. *
  711. * Note: For your own module, replace hook in the function name with the machine-name of
  712. * your chado node type (ie: chado_feature).
  713. *
  714. * @param $select:
  715. * An array of select clauses
  716. * @param $joins:
  717. * An array of joins (ie: a single join could be 'LEFT JOIN {chadotable} alias ON base.id=alias.id')
  718. * @param $where_clauses:
  719. * An array of where clauses which will all be AND'ed together. Use :placeholders for values.
  720. * @param $where_args:
  721. * An associative array of arguments to be subbed in to the where clause where the
  722. * key = :placeholder and the value is the actual argument to be subbed in.
  723. *
  724. * @ingroup tripal_chado_node_api
  725. */
  726. function hook_chado_node_sync_select_query (&$select, &$joins, &$where_clauses, &$where_args) {
  727. // You can add fields to be selected
  728. $select[] = 'example.myfavfield';
  729. // Or joins to important tables
  730. $joins[] = 'LEFT JOIN {exampleprop} PROP ON PROP.example_id=EXAMPLE.example_id';
  731. // Or filter the query using where clauses
  732. $where_clauses[] = 'example.myfavfield = :favvalue';
  733. $where_args[':favvalue'] = 'awesome-ness';
  734. }