Issue #1479454 by Hugo Wetterberg, galooph, dawehner, andypost, marcingy, heyrocker...
[project/drupal.git] / core / modules / user / lib / Drupal / user / Plugin / views / access / Role.php
1 <?php
2
3 /**
4 * @file
5 * Definition of Drupal\user\Plugin\views\access\Role.
6 */
7
8 namespace Drupal\user\Plugin\views\access;
9
10 use Drupal\Core\Annotation\Plugin;
11 use Drupal\views\Plugin\views\access\AccessPluginBase;
12 use Drupal\Core\Annotation\Translation;
13
14 /**
15 * Access plugin that provides role-based access control.
16 *
17 * @ingroup views_access_plugins
18 *
19 * @Plugin(
20 * id = "role",
21 * title = @Translation("Role"),
22 * help = @Translation("Access will be granted to users with any of the specified roles.")
23 * )
24 */
25 class Role extends AccessPluginBase {
26
27 /**
28 * Overrides Drupal\views\Plugin\Plugin::$usesOptions.
29 */
30 protected $usesOptions = TRUE;
31
32 public function access($account) {
33 return views_check_roles(array_filter($this->options['role']), $account);
34 }
35
36 function get_access_callback() {
37 return array('views_check_roles', array(array_filter($this->options['role'])));
38 }
39
40 public function summaryTitle() {
41 $count = count($this->options['role']);
42 if ($count < 1) {
43 return t('No role(s) selected');
44 }
45 elseif ($count > 1) {
46 return t('Multiple roles');
47 }
48 else {
49 $rids = user_role_names();
50 $rid = reset($this->options['role']);
51 return check_plain($rids[$rid]);
52 }
53 }
54
55
56 protected function defineOptions() {
57 $options = parent::defineOptions();
58 $options['role'] = array('default' => array());
59
60 return $options;
61 }
62
63 public function buildOptionsForm(&$form, &$form_state) {
64 parent::buildOptionsForm($form, $form_state);
65 $form['role'] = array(
66 '#type' => 'checkboxes',
67 '#title' => t('Role'),
68 '#default_value' => $this->options['role'],
69 '#options' => array_map('check_plain', $this->getRoles()),
70 '#description' => t('Only the checked roles will be able to access this display. Note that users with "access all views" can see any view, regardless of role.'),
71 );
72 }
73
74 public function validateOptionsForm(&$form, &$form_state) {
75 if (!array_filter($form_state['values']['access_options']['role'])) {
76 form_error($form['role'], t('You must select at least one role if type is "by role"'));
77 }
78 }
79
80 public function submitOptionsForm(&$form, &$form_state) {
81 // I hate checkboxes.
82 $form_state['values']['access_options']['role'] = array_filter($form_state['values']['access_options']['role']);
83 }
84
85 }