role.inc 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * @file
  4. * Plugin to provide access control based upon role membership.
  5. */
  6. /**
  7. * Plugins are described by creating a $plugin array which will be used
  8. * by the system that includes this file.
  9. */
  10. $plugin = array(
  11. 'title' => t("User: role"),
  12. 'description' => t('Control access by role.'),
  13. 'callback' => 'ctools_role_ctools_access_check',
  14. 'default' => array('rids' => array()),
  15. 'settings form' => 'ctools_role_ctools_access_settings',
  16. 'settings form submit' => 'ctools_role_ctools_access_settings_submit',
  17. 'summary' => 'ctools_role_ctools_access_summary',
  18. 'required context' => new ctools_context_required(t('User'), 'user'),
  19. );
  20. /**
  21. * Settings form for the 'by role' access plugin
  22. */
  23. function ctools_role_ctools_access_settings($form, &$form_state, $conf) {
  24. $form['settings']['rids'] = array(
  25. '#type' => 'checkboxes',
  26. '#title' => t('Role'),
  27. '#default_value' => $conf['rids'],
  28. '#options' => ctools_get_roles(),
  29. '#description' => t('Only the checked roles will be granted access.'),
  30. );
  31. return $form;
  32. }
  33. /**
  34. * Compress the roles allowed to the minimum.
  35. */
  36. function ctools_role_ctools_access_settings_submit($form, &$form_state) {
  37. $form_state['values']['settings']['rids'] = array_keys(array_filter($form_state['values']['settings']['rids']));
  38. }
  39. /**
  40. * Check for access.
  41. */
  42. function ctools_role_ctools_access_check($conf, $context) {
  43. // As far as I know there should always be a context at this point, but this
  44. // is safe.
  45. if (empty($context) || empty($context->data) || !isset($context->data->roles)) {
  46. return FALSE;
  47. }
  48. $roles = array_keys($context->data->roles);
  49. $roles[] = $context->data->uid ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
  50. return (bool) array_intersect($conf['rids'], $roles);
  51. }
  52. /**
  53. * Provide a summary description based upon the checked roles.
  54. */
  55. function ctools_role_ctools_access_summary($conf, $context) {
  56. if (!isset($conf['rids'])) {
  57. $conf['rids'] = array();
  58. }
  59. $roles = ctools_get_roles();
  60. $names = array();
  61. foreach (array_filter($conf['rids']) as $rid) {
  62. $names[] = check_plain($roles[$rid]);
  63. }
  64. if (empty($names)) {
  65. return t('@identifier can have any role', array('@identifier' => $context->identifier));
  66. }
  67. return format_plural(count($names), '@identifier has role "@roles"', '@identifier has one of "@roles"', array('@roles' => implode(', ', $names), '@identifier' => $context->identifier));
  68. }