tripal_core.chado_nodes.api.inc 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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. * Determine the chado base table for a given content type
  92. *
  93. * @param $content_type
  94. * The machine name of the content type (node type) you want to
  95. * determine the base chado table of
  96. * @param $module
  97. * (Optional) The machine-name of the module implementing the
  98. * content type
  99. *
  100. * @return
  101. * The name of the chado base table for the specified content type
  102. *
  103. * @ingroup tripal_chado_node_api
  104. */
  105. function chado_node_get_base_table($content_type, $module = FALSE) {
  106. if ($module) {
  107. $node_info = call_user_func($details['module'] . '_node_info');
  108. }
  109. else {
  110. $node_types = module_invoke_all('node_info');
  111. if (isset($node_types[$content_type])) {
  112. $node_info = $node_types[$content_type];
  113. }
  114. else {
  115. return FALSE;
  116. }
  117. }
  118. if (isset($node_info['chado_node_api']['base_table'])) {
  119. return $node_info['chado_node_api']['base_table'];
  120. }
  121. else {
  122. return FALSE;
  123. }
  124. }
  125. /**
  126. * @section
  127. * Common Functionality for Properties, Dbxrefs and relationships chado node API
  128. */
  129. /**
  130. * Validate the Triggering element from a node form.
  131. *
  132. * We are going to inspect the post to determine what PHP knows is the triggering
  133. * element and if it doesn't agree with Drupal then we are actually going to
  134. * change it in Drupal.
  135. *
  136. * This fixes an obscure bug triggered when a property is added and then
  137. * a relationship removed, Drupal thinks the first property remove button was
  138. * clicked and instead removes a property (not a relationship) and renders the new
  139. * property table in the relationship table page space.
  140. *
  141. * NOTE: Many Drupal issues state that this problem is solved if the #name
  142. * of the button is unique (which it is in our case) but we are still experiencing
  143. * incorrectly determined triggering elements so we need to handle it ourselves.
  144. */
  145. function chado_validate_node_form_triggering_element($form, &$form_state) {
  146. // We are going to inspect the post to determine what PHP knows is the triggering
  147. // element and if it doesn't agree with Drupal then we are actually going to
  148. // change it in Drupal.
  149. if ($_POST['_triggering_element_name'] != $form_state['triggering_element']['#name']) {
  150. $form_state['triggering_element']['#name'] = $_POST['_triggering_element_name'];
  151. }
  152. }
  153. /**
  154. * Validate Adding Subtables entries from the node forms.
  155. * Supported subtables: Properties, Relationships, Additional DBxrefs.
  156. *
  157. * @param array $form
  158. * @param array $form_state
  159. */
  160. function chado_add_node_form_subtables_add_button_validate($form, &$form_state) {
  161. // Based on triggering element call the correct validation function
  162. // ASUMPTION #1: each of the buttons must have property, dbxref or relationship
  163. // as the first part of the #name to uniquely identify the subsection.
  164. if (preg_match('/^([a-z]+).*/', $form_state['triggering_element']['#name'], $matches)) {
  165. $subsection = $matches[1];
  166. switch($subsection) {
  167. case 'properties':
  168. chado_add_node_form_properties_add_button_validate($form, $form_state);
  169. break;
  170. case 'dbxrefs':
  171. chado_add_node_form_dbxrefs_add_button_validate($form, $form_state);
  172. break;
  173. case 'relationships':
  174. chado_add_node_form_relationships_add_button_validate($form, $form_state);
  175. break;
  176. }
  177. }
  178. }
  179. /**
  180. * Add subtable entries to the node forms.
  181. * Supported subtables: Properties, Relationships, Additional DBxrefs.
  182. *
  183. * @param array $form
  184. * @param array $form_state
  185. */
  186. function chado_add_node_form_subtables_add_button_submit($form, &$form_state) {
  187. // Based on triggering element call the correct submit function
  188. // ASUMPTION #1: each of the buttons must have properties, dbxrefs or relationships
  189. // as the first part of the #name to uniquely identify the subsection.
  190. if (preg_match('/^([a-z]+).*/', $form_state['triggering_element']['#name'], $matches)) {
  191. $subsection = $matches[1];
  192. switch($subsection) {
  193. case 'properties':
  194. chado_add_node_form_properties_add_button_submit($form, $form_state);
  195. break;
  196. case 'dbxrefs':
  197. chado_add_node_form_dbxrefs_add_button_submit($form, $form_state);
  198. break;
  199. case 'relationships':
  200. chado_add_node_form_relationships_add_button_submit($form, $form_state);
  201. break;
  202. }
  203. }
  204. // This is needed to ensure the form builder function is called for the node
  205. // form in order for any of these changes to be seen.
  206. $form_state['rebuild'] = TRUE;
  207. }
  208. /**
  209. * Validate Removing Subtables entries from the node forms.
  210. * Supported subtables: Properties, Relationships, Additional DBxrefs.
  211. *
  212. * Since Removing isn't associated with any user input the only thing we
  213. * need to validate is that Drupal has determined the triggering element correctly.
  214. * That said, we will call each subtables associated validate function just incase
  215. * there is some case-specific validation we do not know of or have not anticipated.
  216. *
  217. * @param array $form
  218. * @param array $form_state
  219. */
  220. function chado_add_node_form_subtables_remove_button_validate($form, &$form_state) {
  221. // We need to validate the trigerring element since Drupal has known
  222. // issues determining this correctly when there are multiple buttons
  223. // with the same label.
  224. chado_validate_node_form_triggering_element($form, $form_state);
  225. // Based on triggering element call the correct validation function
  226. // ASUMPTION #1: each of the buttons must have property, dbxref or relationship
  227. // as the first part of the #name to uniquely identify the subsection.
  228. if (preg_match('/^([a-z]+).*/', $form_state['triggering_element']['#name'], $matches)) {
  229. $subsection = $matches[1];
  230. switch($subsection) {
  231. case 'properties':
  232. chado_add_node_form_properties_remove_button_validate($form, $form_state);
  233. break;
  234. case 'dbxrefs':
  235. chado_add_node_form_dbxrefs_remove_button_validate($form, $form_state);
  236. break;
  237. case 'relationships':
  238. chado_add_node_form_relationships_remove_button_validate($form, $form_state);
  239. break;
  240. }
  241. }
  242. }
  243. /**
  244. * Remove subtable entries to the node forms.
  245. * Supported subtables: Properties, Relationships, Additional DBxrefs.
  246. *
  247. * @param array $form
  248. * @param array $form_state
  249. */
  250. function chado_add_node_form_subtables_remove_button_submit($form, &$form_state) {
  251. // Based on triggering element call the correct submit function
  252. // ASUMPTION #1: each of the buttons must have properties, dbxrefs or relationships
  253. // as the first part of the #name to uniquely identify the subsection.
  254. if (preg_match('/^([a-z]+).*/', $form_state['triggering_element']['#name'], $matches)) {
  255. $subsection = $matches[1];
  256. switch($subsection) {
  257. case 'properties':
  258. chado_add_node_form_properties_remove_button_submit($form, $form_state);
  259. break;
  260. case 'dbxrefs':
  261. chado_add_node_form_dbxrefs_remove_button_submit($form, $form_state);
  262. break;
  263. case 'relationships':
  264. chado_add_node_form_relationships_remove_button_submit($form, $form_state);
  265. break;
  266. }
  267. }
  268. // This is needed to ensure the form builder function is called for the node
  269. // form in order for any of these changes to be seen.
  270. $form_state['rebuild'] = TRUE;
  271. }
  272. /**
  273. * Ajax function which returns the section of the form to be re-rendered
  274. * for either the properties, dbxref or relationship sub-sections.
  275. *
  276. * @ingroup tripal_core
  277. */
  278. function chado_add_node_form_subtable_ajax_update($form, &$form_state) {
  279. // We need to validate the trigerring element since Drupal has known
  280. // issues determining this correctly when there are multiple buttons
  281. // with the same label.
  282. chado_validate_node_form_triggering_element($form, $form_state);
  283. // Based on triggering element render the correct part of the form.
  284. // ASUMPTION: each of the buttons must have property, dbxref or relationship
  285. // as the first part of the #name to uniquely identify the subsection.
  286. if (preg_match('/^([a-z]+).*/', $form_state['triggering_element']['#name'], $matches)) {
  287. $subsection = $matches[1];
  288. switch($subsection) {
  289. case 'properties':
  290. return $form['properties']['property_table'];
  291. break;
  292. case 'dbxrefs':
  293. return $form['addtl_dbxrefs']['dbxref_table'];
  294. break;
  295. case 'relationships':
  296. return $form['relationships']['relationship_table'];
  297. break;
  298. }
  299. }
  300. }
  301. /**
  302. * @section
  303. * Sync Form
  304. */
  305. /**
  306. * Generic Sync Form to aid in sync'ing (create drupal nodes linking to chado content)
  307. * any chado node type.
  308. *
  309. * To use this you need to add a call to it from your hook_menu() and
  310. * add some additional information to your hook_node_info(). The Following code gives an
  311. * example of how this might be done:
  312. * @code
  313. function modulename_menu() {
  314. // the machine name of your module
  315. $module_name = 'tripal_example';
  316. // the base specified in hook_node_info
  317. $linking_table = 'chado_example';
  318. // This menu item will be a tab on the admin/tripal/chado/tripal_example page
  319. // that is not selected by default
  320. $items['admin/tripal/chado/tripal_example/sync'] = array(
  321. 'title' => ' Sync',
  322. 'description' => 'Sync examples from Chado with Drupal',
  323. 'page callback' => 'drupal_get_form',
  324. 'page arguments' => array('chado_node_sync_form', $module_name, $linking_table),
  325. 'access arguments' => array('administer tripal examples'),
  326. 'type' => MENU_LOCAL_TASK,
  327. 'weight' => 0
  328. );
  329. return $items;
  330. }
  331. function modulename_node_info() {
  332. return array(
  333. 'chado_example' => array(
  334. 'name' => t('example'),
  335. 'base' => 'chado_example',
  336. 'description' => t('A Chado example is a collection of material that can be sampled and have experiments performed on it.'),
  337. 'has_title' => TRUE,
  338. 'locked' => TRUE,
  339. // this is what differs from the regular Drupal-documented hook_node_info()
  340. 'chado_node_api' => array(
  341. 'base_table' => 'example', // the name of the chado base table
  342. 'hook_prefix' => 'chado_example', // usually the name of the node type
  343. 'record_type_title' => array(
  344. 'singular' => t('Example'), // Singular human-readable title
  345. 'plural' => t('Examples') // Plural human-readable title
  346. ),
  347. 'sync_filters' => array( // filters for syncing
  348. 'type_id' => TRUE, // TRUE if there is an example.type_id field
  349. 'organism_id' => TRUE, // TRUE if there is an example.organism_id field
  350. 'checkboxes' => array('name') // If the 'checkboxes' key is present then the
  351. // value must be an array of column names in
  352. // base table. The values from these columns will
  353. // be retreived, contentated with a space delimeter
  354. // and provided in a list of checkboxes
  355. // for the user to choose which to sync.
  356. ),
  357. )
  358. ),
  359. );
  360. }
  361. * @endcode
  362. *
  363. * For more information on how you can override some of this behaviour while still
  364. * benifiting from as much of the common architecture as possible see the following
  365. * functions: hook_chado_node_sync_create_new_node(), hook_chado_node_sync_form(),
  366. * hook_chado_node_sync_select_query().
  367. *
  368. * @ingroup tripal_chado_node_api
  369. */
  370. function chado_node_sync_form($form, &$form_state) {
  371. $form = array();
  372. if (isset($form_state['build_info']['args'][0])) {
  373. $module = $form_state['build_info']['args'][0];
  374. $linking_table = $form_state['build_info']['args'][1];
  375. $node_info = call_user_func($module . '_node_info');
  376. $args = $node_info[$linking_table]['chado_node_api'];
  377. $form_state['chado_node_api'] = $args;
  378. }
  379. $form['linking_table'] = array(
  380. '#type' => 'hidden',
  381. '#value' => $linking_table
  382. );
  383. // define the fieldsets
  384. $form['sync'] = array(
  385. '#type' => 'fieldset',
  386. '#title' => 'Sync ' . $args['record_type_title']['plural'],
  387. '#descrpition' => '',
  388. );
  389. $form['sync']['description'] = array(
  390. '#type' => 'item',
  391. '#value' => t("%title_plural of the types listed ".
  392. "below in the %title_singular Types box will be synced (leave blank to sync all types). You may limit the ".
  393. "%title_plural to be synced by a specific organism. Depending on the ".
  394. "number of %title_plural in the chado database this may take a long ".
  395. "time to complete. ",
  396. array(
  397. '%title_singular' => $args['record_type_title']['singular'],
  398. '%title_plural' => $args['record_type_title']['plural']
  399. )),
  400. );
  401. if ($args['sync_filters']['type_id']) {
  402. $form['sync']['type_ids'] = array(
  403. '#title' => t('%title_singular Types',
  404. array(
  405. '%title_singular' => $args['record_type_title']['singular'],
  406. '%title_plural' => $args['record_type_title']['plural']
  407. )),
  408. '#type' => 'textarea',
  409. '#description' => t("Enter the names of the %title_singular types to sync. " .
  410. "Leave blank to sync all %title_plural. Separate each type with a comma ".
  411. "or new line. Pages for these %title_singular ".
  412. "types will be created automatically for %title_plural that exist in the ".
  413. "chado database. The names must match ".
  414. "exactly (spelling and case) with terms in the ontologies",
  415. array(
  416. '%title_singular' => strtolower($args['record_type_title']['singular']),
  417. '%title_plural' => strtolower($args['record_type_title']['plural'])
  418. )),
  419. '#default_value' => (isset($form_state['values']['type_id'])) ? $form_state['values']['type_id'] : '',
  420. );
  421. }
  422. // get the list of organisms
  423. if ($args['sync_filters']['organism_id']) {
  424. $sql = "SELECT * FROM {organism} ORDER BY genus, species";
  425. $results = chado_query($sql);
  426. $organisms[] = '';
  427. foreach ($results as $organism) {
  428. $organisms[$organism->organism_id] = "$organism->genus $organism->species ($organism->common_name)";
  429. }
  430. $form['sync']['organism_id'] = array(
  431. '#title' => t('Organism'),
  432. '#type' => t('select'),
  433. '#description' => t("Choose the organism for which %title_plural types set above will be synced.",
  434. array(
  435. '%title_singular' => $args['record_type_title']['singular'],
  436. '%title_plural' => $args['record_type_title']['plural']
  437. )),
  438. '#options' => $organisms,
  439. '#default_value' => (isset($form_state['values']['organism_id'])) ? $form_state['values']['organism_id'] : 0,
  440. );
  441. }
  442. // get the list of organisms
  443. if (array_key_exists('checkboxes', $args['sync_filters'])) {
  444. // get the base schema
  445. $base_table = $args['base_table'];
  446. $table_info = chado_get_schema($base_table);
  447. // if the base table does not have a primary key or has more than one then
  448. // we can't proceed, otherwise, generate the checkboxes
  449. if (array_key_exists('primary key', $table_info) and count($table_info['primary key']) == 1) {
  450. $pkey = $table_info['primary key'][0];
  451. $columns = $args['sync_filters']['checkboxes'];
  452. $select_cols = implode("|| ' ' ||", $columns);
  453. // get non-synced records
  454. $sql = "
  455. SELECT BT.$pkey as id, $select_cols as value
  456. FROM {" . $base_table . "} BT
  457. LEFT JOIN public.$linking_table LT ON LT.$pkey = BT.$pkey
  458. WHERE LT.$pkey IS NULL
  459. ORDER BY value ASC
  460. ";
  461. $results = chado_query($sql);
  462. $values = array();
  463. foreach ($results as $result) {
  464. $values[$result->id] = $result->value;
  465. }
  466. if (count($values) > 0) {
  467. $form['sync']['ids'] = array(
  468. '#title' => 'Avaliable ' . $args['record_type_title']['plural'],
  469. '#type' => 'checkboxes',
  470. '#options' => $values,
  471. '#default_value' => (isset($form_state['values']['ids'])) ? $form_state['values']['ids'] : array(),
  472. '#suffix' => '</div><br>',
  473. '#prefix' => t("The following %title_plural have not been synced. Check those to be synced or leave all unchecked to sync them all.",
  474. array(
  475. '%title_singular' => strtolower($args['record_type_title']['singular']),
  476. '%title_plural' => strtolower($args['record_type_title']['plural'])
  477. )) . '<div style="height: 200px; overflow: scroll">',
  478. );
  479. }
  480. else {
  481. $form['sync']['no_ids'] = array(
  482. '#markup' => "<p>There are no " . strtolower($args['record_type_title']['plural']) . " to sync.</p>",
  483. );
  484. }
  485. }
  486. }
  487. // if we provide a list of checkboxes we shouldn't need a max_sync
  488. else {
  489. $form['sync']['max_sync'] = array(
  490. '#type' => 'textfield',
  491. '#title' => t('Maximum number of records to Sync'),
  492. '#description' => t('Leave this field empty to sync all records, regardless of number'),
  493. '#default_value' => (isset($form_state['values']['max_sync'])) ? $form_state['values']['max_sync'] : '',
  494. );
  495. }
  496. $form['sync']['button'] = array(
  497. '#type' => 'submit',
  498. '#value' => t('Sync ' . $args['record_type_title']['plural']),
  499. '#weight' => 3,
  500. );
  501. $form['cleanup'] = array(
  502. '#type' => 'fieldset',
  503. '#title' => t('Clean Up')
  504. );
  505. $form['cleanup']['description'] = array(
  506. '#markup' => t("<p>With Drupal and chado residing in different databases " .
  507. "it is possible that nodes in Drupal and " . strtolower($args['record_type_title']['plural']) . " in Chado become " .
  508. "\"orphaned\". This can occur if a node in Drupal is " .
  509. "deleted but the corresponding chado records is not and/or vice " .
  510. "versa. Click the button below to resolve these discrepancies.</p>"),
  511. '#weight' => 1,
  512. );
  513. $form['cleanup']['button'] = array(
  514. '#type' => 'submit',
  515. '#value' => 'Clean up orphaned ' . strtolower($args['record_type_title']['plural']),
  516. '#weight' => 2,
  517. );
  518. // Allow each module to alter this form as needed
  519. $hook_form_alter = $args['hook_prefix'] . '_chado_node_sync_form';
  520. if (function_exists($hook_form_alter)) {
  521. $form = call_user_func($hook_form_alter, $form, $form_state);
  522. }
  523. return $form;
  524. }
  525. /**
  526. * Generic Sync Form Submit
  527. *
  528. * @ingroup tripal_core
  529. */
  530. function chado_node_sync_form_submit($form, $form_state) {
  531. global $user;
  532. if (preg_match('/^Sync/', $form_state['values']['op'])) {
  533. // get arguments
  534. $args = $form_state['chado_node_api'];
  535. $module = $form_state['chado_node_api']['hook_prefix'];
  536. $base_table = $form_state['chado_node_api']['base_table'];
  537. $linking_table = $form_state['values']['linking_table'];
  538. // Allow each module to hijack the submit if needed
  539. $hook_form_hijack_submit = $args['hook_prefix'] . '_chado_node_sync_form_submit';
  540. if (function_exists($hook_form_hijack_submit)) {
  541. return call_user_func($hook_form_hijack_submit, $form, $form_state);
  542. }
  543. // Get the types separated into a consistent string
  544. $types = array();
  545. if (isset($form_state['values']['type_ids'])) {
  546. // seperate by new line or comma.
  547. $temp_types = preg_split("/[,\n\r]+/", $form_state['values']['type_ids']);
  548. // remove any extra spacing around the types
  549. for($i = 0; $i < count($temp_types); $i++) {
  550. // skip empty types
  551. if (trim($temp_types[$i]) == '') {
  552. continue;
  553. }
  554. $types[$i] = trim($temp_types[$i]);
  555. }
  556. }
  557. // Get the ids to be synced
  558. $ids = array();
  559. if (array_key_exists('ids', $form_state['values'])){
  560. foreach ($form_state['values']['ids'] as $id => $selected) {
  561. if ($selected) {
  562. $ids[] = $id;
  563. }
  564. }
  565. }
  566. // get the organism to be synced
  567. $organism_id = FALSE;
  568. if (array_key_exists('organism_id', $form_state['values'])) {
  569. $organism_id = $form_state['values']['organism_id'];
  570. }
  571. // Job Arguments
  572. $job_args = array(
  573. 'base_table' => $base_table,
  574. 'max_sync' => (!empty($form_state['values']['max_sync'])) ? $form_state['values']['max_sync'] : FALSE,
  575. 'organism_id' => $organism_id,
  576. 'types' => $types,
  577. 'ids' => $ids,
  578. 'inking_table' => $linking_table
  579. );
  580. $title = "Sync " . $args['record_type_title']['plural'];
  581. tripal_add_job($title, $module, 'chado_node_sync_records', $job_args, $user->uid);
  582. }
  583. if (preg_match('/^Clean up orphaned/', $form_state['values']['op'])) {
  584. $module = $form_state['chado_node_api']['hook_prefix'];
  585. $base_table = $form_state['chado_node_api']['base_table'];
  586. $job_args = array($base_table);
  587. tripal_add_job($form_state['values']['op'], $module, 'chado_cleanup_orphaned_nodes', $job_args, $user->uid);
  588. }
  589. }
  590. /**
  591. * Generic function for syncing records in Chado with Drupal nodes.
  592. *
  593. * @param $base_table
  594. * The name of the Chado table containing the record that should be synced
  595. * @param $max_sync
  596. * Optional: A numeric value to indicate the maximum number of records to sync.
  597. * @param $organism_id
  598. * Optional: Limit the list of records to be synced to only those that
  599. * are associated with this organism_id. If the record is not assocaited
  600. * with an organism then this field is not needed.
  601. * @param $types
  602. * Optional: Limit the list of records to be synced to only those that
  603. * match the types listed in this array.
  604. * @param $ids
  605. * Optional: Limit the list of records to bye synced to only those whose
  606. * primary key value matches the ID provided in this array.
  607. * @param $linking_table
  608. * Optional: Tripal maintains "linking" tables in the Drupal schema
  609. * to link Drupal nodes with Chado records. By default these tables
  610. * are named as 'chado_' . $base_table. But if for some reason the
  611. * linking table is not named in this way then it can be provided by this
  612. * argument.
  613. * @param $job_id
  614. * Optional. Used by the Trpial Jobs system when running this function
  615. * as a job. It is not needed othewise.
  616. *
  617. * @ingroup tripal_chado_node_api
  618. */
  619. function chado_node_sync_records($base_table, $max_sync = FALSE, $organism_id = FALSE,
  620. $types = array(), $ids = array(), $linking_table = FALSE, $job_id = NULL) {
  621. global $user;
  622. $base_table_id = $base_table . '_id';
  623. if (!$linking_table) {
  624. $linking_table = 'chado_' . $base_table;
  625. }
  626. print "\nSync'ing $base_table records. ";
  627. // START BUILDING QUERY TO GET ALL RECORD FROM BASE TABLE THAT MATCH
  628. $select = array("$base_table.*");
  629. $joins = array();
  630. $where_clauses = array();
  631. $where_args = array();
  632. // If types are supplied then handle them
  633. $restrictions = '';
  634. if (count($types) > 0) {
  635. $restrictions .= " Type(s): " . implode(', ',$types) . "\n";
  636. $select[] = 'cvterm.name as cvtname';
  637. $joins[] = "LEFT JOIN {cvterm} cvterm ON $base_table.type_id = cvterm.cvterm_id";
  638. foreach ($types as $type) {
  639. $sanitized_type = str_replace(' ','_',$type);
  640. $where_clauses['type'][] = "cvterm.name = :type_name_$sanitized_type";
  641. $where_args['type'][":type_name_$sanitized_type"] = $type;
  642. }
  643. }
  644. // if IDs have been supplied
  645. if ($ids) {
  646. $restrictions .= " Specific Records: " . count($ids) . " recored(s) specified.\n";
  647. foreach ($ids as $id) {
  648. $where_clauses['id'][] = "$base_table.$base_table_id = :id_$id";
  649. $where_args['id'][":id_$id"] = $id;
  650. }
  651. }
  652. // If Organism is supplied
  653. if ($organism_id) {
  654. $organism = chado_select_record('organism', array('*'), array('organism_id' => $organism_id));
  655. $restrictions .= " Organism: " . $organism[0]->genus . " " . $organism[0]->species . "\n";
  656. $select[] = 'organism.*';
  657. $joins[] = "LEFT JOIN {organism} organism ON organism.organism_id = $base_table.organism_id";
  658. $where_clauses['organism'][] = 'organism.organism_id = :organism_id';
  659. $where_args['organism'][':organism_id'] = $organism_id;
  660. }
  661. // Allow module to add to query
  662. $hook_query_alter = $linking_table . '_chado_node_sync_select_query';
  663. if (function_exists($hook_query_alter)) {
  664. $update = call_user_func($hook_query_alter, array(
  665. 'select' => $select,
  666. 'joins' => $joins,
  667. 'where_clauses' => $where_clauses,
  668. 'where_args' => $where_args,
  669. ));
  670. // Now add in any new changes
  671. if ($update and is_array($update)) {
  672. $select = $update['select'];
  673. $joins = $update['joins'];
  674. $where_clauses = $update['where_clauses'];
  675. $where_args = $update['where_args'];
  676. }
  677. }
  678. // Build Query, we do a left join on the chado_xxxx table in the Drupal schema
  679. // so that if no criteria are specified we only get those items that have not
  680. // yet been synced.
  681. $query = "
  682. SELECT " . implode(', ', $select) . ' ' .
  683. 'FROM {' . $base_table . '} ' . $base_table . ' ' . implode(' ', $joins) . ' '.
  684. " LEFT JOIN public.$linking_table CT ON CT.$base_table_id = $base_table.$base_table_id " .
  685. "WHERE CT.$base_table_id IS NULL ";
  686. // extend the where clause if needed
  687. $where = '';
  688. $sql_args = array();
  689. foreach ($where_clauses as $category => $items) {
  690. $where .= ' AND (';
  691. foreach ($items as $item) {
  692. $where .= $item . ' OR ';
  693. }
  694. $where = substr($where, 0, -4); // remove the trailing 'OR'
  695. $where .= ') ';
  696. $sql_args = array_merge($sql_args, $where_args[$category]);
  697. }
  698. if ($where) {
  699. $query .= $where;
  700. }
  701. $query .- " ORDER BY " . $base_table_id;
  702. // If Maximum number to Sync is supplied
  703. if ($max_sync) {
  704. $query .= " LIMIT $max_sync";
  705. $restrictions .= " Limited to $max_sync records.\n";
  706. }
  707. if ($restrictions) {
  708. print "Records matching these criteria will be synced: \n$restrictions";
  709. }
  710. else {
  711. print "\n";
  712. }
  713. // execute the query
  714. $results = chado_query($query, $sql_args);
  715. // Iterate through records that need to be synced
  716. $count = $results->rowCount();
  717. $interval = intval($count * 0.01);
  718. if ($interval < 1) {
  719. $interval = 1;
  720. }
  721. print "\n$count $base_table records found.\n";
  722. $i = 0;
  723. $transaction = db_transaction();
  724. print "\nNOTE: Syncing is performed using a database transaction. \n" .
  725. "If the sync fails or is terminated prematurely then the entire set of \n" .
  726. "synced items is rolled back and will not be found in the database\n\n";
  727. try {
  728. $percent = 0;
  729. foreach ($results as $record) {
  730. //print "\nLoading $base_table " . ($i + 1) . " of $count ($base_table_id=" . $record->{$base_table_id} . ")...";
  731. // update the job status every 1% features
  732. if ($job_id and $i % $interval == 0) {
  733. $percent = sprintf("%.2f", (($i + 1) / $count) * 100);
  734. print "Syncing $base_table " . ($i + 1) . " of $count (" . $percent . "%). Memory: " . number_format(memory_get_usage()) . " bytes.\r";
  735. tripal_set_job_progress($job_id, intval(($i/$count)*100));
  736. }
  737. // Check if it is in the chado linking table (ie: check to see if it is already linked to a node)
  738. $result = db_select($linking_table, 'lnk')
  739. ->fields('lnk',array('nid'))
  740. ->condition($base_table_id, $record->{$base_table_id}, '=')
  741. ->execute()
  742. ->fetchObject();
  743. if (!empty($result)) {
  744. //print " Previously Sync'd";
  745. }
  746. else {
  747. // Create generic new node
  748. $new_node = new stdClass();
  749. $new_node->type = $linking_table;
  750. $new_node->uid = $user->uid;
  751. $new_node->{$base_table_id} = $record->{$base_table_id};
  752. $new_node->$base_table = $record;
  753. $new_node->language = LANGUAGE_NONE;
  754. // TODO: should we get rid of this hook and use hook_node_presave() instead?
  755. // allow base module to set additional fields as needed
  756. $hook_create_new_node = $linking_table . '_chado_node_sync_create_new_node';
  757. if (function_exists($hook_create_new_node)) {
  758. $new_node = call_user_func($hook_create_new_node, $new_node, $record);
  759. }
  760. // Validate and Save New Node
  761. $form = array();
  762. $form_state = array();
  763. node_validate($new_node, $form, $form_state);
  764. if (!form_get_errors()) {
  765. $node = node_submit($new_node);
  766. node_save($node);
  767. //print " Node Created (nid=".$node->nid.")";
  768. }
  769. else {
  770. watchdog('trp-fsync', "Failed to insert $base_table: %title", array('%title' => $new_node->title), WATCHDOG_ERROR);
  771. }
  772. }
  773. $i++;
  774. }
  775. print "\n\nComplete!\n";
  776. }
  777. catch (Exception $e) {
  778. $transaction->rollback();
  779. print "\n"; // make sure we start errors on new line
  780. watchdog_exception('trp-fsync', $e);
  781. print "FAILED: Rolling back database changes...\n";
  782. }
  783. }
  784. /**
  785. * This function will delete Drupal nodes for any sync'ed table (e.g.
  786. * feature, organism, analysis, stock, library) if the chado record has been
  787. * deleted or the entry in the chado_[table] table has been removed.
  788. *
  789. * @param $table
  790. * The name of the table that corresonds to the node type we want to clean up.
  791. * @param $job_id
  792. * This should be the job id from the Tripal jobs system. This function
  793. * will update the job status using the provided job ID.
  794. *
  795. * @ingroup tripal_chado_node_api
  796. */
  797. function chado_cleanup_orphaned_nodes($table, $job_id = NULL) {
  798. $count = 0;
  799. // build the SQL statments needed to check if nodes point to valid analyses
  800. $dsql = "SELECT * FROM {node} WHERE type = 'chado_" . $table . "' order by nid";
  801. $nsql = "SELECT * FROM {node} WHERE nid = :nid";
  802. $csql = "SELECT * FROM {chado_" . $table . "} WHERE nid = :nid ";
  803. $clsql= "SELECT * FROM {chado_" . $table . "}";
  804. $lsql = "SELECT * FROM {" . $table . "} where " . $table . "_id = :" . $table . "_id ";
  805. // load into nodes array
  806. print "Getting nodes\n";
  807. $nodes = array();
  808. $res = db_query($dsql);
  809. foreach ($res as $node) {
  810. $nodes[$count] = $node;
  811. $count++;
  812. }
  813. // load the chado_$table into an array
  814. print "Getting chado_$table\n";
  815. $cnodes = array();
  816. $res = db_query($clsql);
  817. foreach ($res as $node) {
  818. $cnodes[$count] = $node;
  819. $count++;
  820. }
  821. $interval = intval($count * 0.01);
  822. if ($interval < 1) {
  823. $interval = 1;
  824. }
  825. // iterate through all of the chado_$table entries and remove those
  826. // that don't have a node or don't have a $table record in chado.libary
  827. print "Verifying all chado_$table Entries\n";
  828. $deleted = 0;
  829. foreach ($cnodes as $nid) {
  830. // update the job status every 1% analyses
  831. if ($job_id and $i % $interval == 0) {
  832. tripal_set_job_progress($job_id, intval(($i / $count) * 100));
  833. }
  834. // see if the node exits, if not remove the entry from the chado_$table table
  835. $results = db_query($nsql, array(':nid' => $nid->nid));
  836. $node = $results->fetchObject();
  837. if (!$node) {
  838. $deleted++;
  839. db_query("DELETE FROM {chado_" . $table . "} WHERE nid = :nid", array(':nid' => $nid->nid));
  840. $message = "chado_$table missing node.... DELETING: $nid->nid";
  841. watchdog('tripal_core', $message, array(), WATCHDOG_WARNING);
  842. }
  843. // see if the record in chado exist, if not remove the entry from the chado_$table
  844. $table_id = $table . "_id";
  845. $results = chado_query($lsql, array(":" . $table . "_id" => $nid->$table_id));
  846. $record = $results->fetchObject();
  847. if (!$record) {
  848. $deleted++;
  849. $sql = "DELETE FROM {chado_" . $table . "} WHERE " . $table . "_id = :" . $table . "_id";
  850. db_query($sql, array(":" . $table . "_id" => $nid->$table_id));
  851. $message = "chado_$table missing $table.... DELETING entry.";
  852. watchdog('tripal_core', $message, array(), WATCHDOG_NOTICE);
  853. }
  854. $i++;
  855. }
  856. print "\t$deleted chado_$table entries missing either a node or chado entry.\n";
  857. // iterate through all of the nodes and delete those that don't
  858. // have a corresponding entry in chado_$table
  859. $deleted = 0;
  860. foreach ($nodes as $node) {
  861. // update the job status every 1% libraries
  862. if ($job_id and $i % $interval == 0) {
  863. tripal_set_job_progress($job_id, intval(($i / $count) * 100));
  864. }
  865. // check to see if the node has a corresponding entry
  866. // in the chado_$table table. If not then delete the node.
  867. $results = db_query($csql, array(":nid" => $node->nid));
  868. $link = $results->fetchObject();
  869. if (!$link) {
  870. if (node_access('delete', $node)) {
  871. $deleted++;
  872. $message = "Node missing in chado_$table table.... DELETING node $node->nid";
  873. watchdog("tripal_core", $message, array(), WATCHDOG_NOTICE);
  874. node_delete($node->nid);
  875. }
  876. else {
  877. $message = "Node missing in chado_$table table.... but cannot delete due to improper permissions (node $node->nid)";
  878. watchdog("tripal_core", $message, array(), WATCHDOG_WARNING);
  879. }
  880. }
  881. $i++;
  882. }
  883. print "\t$deleted nodes did not have corresponding chado_$table entries.\n";
  884. return '';
  885. }
  886. /**
  887. * Create New Node
  888. *
  889. * Note: For your own module, replace hook in the function name with the machine-name of
  890. * your chado node type (ie: chado_feature).
  891. *
  892. * @param $new_node:
  893. * a basic new node object
  894. * @param $record:
  895. * the record object from chado specifying the biological data for this node
  896. *
  897. * @return
  898. * A node object containing all the fields necessary to create a new node during sync
  899. *
  900. * @ingroup tripal_chado_node_api
  901. */
  902. function hook_chado_node_sync_create_new_node($new_node, $record) {
  903. // Add relevant chado details to the new node object
  904. // This really only needs to be the fields from the node used during node creation
  905. // including values used to generate the title, etc.
  906. // All additional chado data will be added via nodetype_load when the node is later used
  907. $new_node->uniquename = $record->uniquename;
  908. return $new_node;
  909. }
  910. /**
  911. * Alter the sync form (optional)
  912. *
  913. * This might be necessary if you need additional filtering options for choosing which
  914. * chado records to sync or even if you just want to further customize the help text
  915. * provided by the form.
  916. *
  917. * Note: For your own module, replace hook in the function name with the machine-name of
  918. * your chado node type (ie: chado_feature).
  919. *
  920. * @ingroup tripal_chado_node_api
  921. */
  922. function hook_chado_node_sync_form($form, &$form_state) {
  923. // Change or add to the form array as needed
  924. // Any changes should be made in accordance with the Drupal Form API
  925. return $form;
  926. }
  927. /**
  928. * Bypass chado node api sync form submit (optional). Allows you to use this function
  929. * as your own submit.
  930. *
  931. * This might be necessary if you want to add additional arguements to the tripal job or
  932. * to call your own sync'ing function if the generic chado_node_sync_records() is not
  933. * sufficient.
  934. *
  935. * Note: For your own module, replace hook in the function name with the machine-name of
  936. * your chado node type (ie: chado_feature).
  937. *
  938. * @ingroup tripal_chado_node_api
  939. */
  940. function hook_chado_node_sync_form_submit ($form, $form_state) {
  941. global $user;
  942. $job_args = array(
  943. $base_table, // the base chado table (ie: feature)
  944. $max_sync, // the maximum number of records to sync or FALSE for sync all that match
  945. $organism_id, // the organism_id to restrict records to or FALSE if not to restrict by organism_id
  946. $types // A string with the cvterm.name of the types to restrict to separated by |||
  947. );
  948. // You should register a tripal job
  949. tripal_add_job(
  950. $title, // the title of the job -be descriptive
  951. $module, // the name of your module
  952. 'chado_node_sync_records', // the chado node api sync function
  953. $job_args, // an array with the arguments to pass to the above function
  954. $user->uid // the user who submitted the job
  955. );
  956. }
  957. /**
  958. * Alter the query that retrieves records to be sync'd (optional)
  959. *
  960. * This might be necessary if you need fields from other chado tables to create your node
  961. * or if your chado node type only supports a subset of a given table (ie: a germplasm node
  962. * type might only support node creation for cerain types of stock records in which case
  963. * you would need to filter the results to only those types).
  964. *
  965. * Note: For your own module, replace hook in the function name with the machine-name of
  966. * your chado node type (ie: chado_feature).
  967. *
  968. * @param $query
  969. * An array containing the following:
  970. * 'select': An array of select clauses
  971. * 'joins: An array of joins (ie: a single join could be
  972. * 'LEFT JOIN {chadotable} alias ON base.id=alias.id')
  973. * 'where_clauses: An array of where clauses which will all be AND'ed
  974. * together. Use :placeholders for values.
  975. * 'where_args: An associative array of arguments to be subbed in to the
  976. * where clause where the
  977. *
  978. * @ingroup tripal_chado_node_api
  979. */
  980. function hook_chado_node_sync_select_query($query) {
  981. // You can add fields to be selected. Be sure to prefix each field with the
  982. // tale name.
  983. $query['select'][] = 'example.myfavfield';
  984. // Provide any join you may need to the joins array. Be sure to wrap the
  985. // table name in curly brackets.
  986. $query['joins'][] = 'LEFT JOIN {exampleprop} PROP ON PROP.example_id=EXAMPLE.example_id';
  987. // The category should be a unique id for a group of items that will be
  988. // concatenated together via an SQL 'OR'. By default the $where_clases
  989. // variable will come with categories of 'id', 'organism' and 'type'.
  990. // you can add your own unique category or alter the contents of the existing
  991. // categories. Be sure to make sure the category doesn't already exist
  992. // in the $query['where_clauses']
  993. $category = 'my_category';
  994. // Provide any aditionall where clauses and their necessary arguments.
  995. // Be sure to prefix the field with the table name. Be sure that the
  996. // placeholder is unique across all categories (perhaps add a unique
  997. // prefix/suffix).
  998. $query['where_clauses'][$category][] = 'example.myfavfield = :favvalue';
  999. $query['where_args'][$category][':favvalue'] = 'awesome-ness';
  1000. // Must return the updated query
  1001. return $query;
  1002. }