Projet

Général

Profil

Paste
Télécharger (10,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / ldap / ldap_authorization / ldap_authorization_drupal_role / LdapAuthorizationConsumerRole.class.php @ 91af538d

1
<?php
2

    
3
/**
4
 * @file
5
 * Class to represent configuration of ldap authorizations to drupal roles.
6
 */
7

    
8
module_load_include('php', 'ldap_authorization', 'LdapAuthorizationConsumerAbstract.class');
9
/**
10
 *
11
 */
12
class LdapAuthorizationConsumerDrupalRole extends LdapAuthorizationConsumerAbstract {
13

    
14
  public $consumerType = 'drupal_role';
15
  public $allowConsumerObjectCreation = TRUE;
16

    
17
  public $defaultConsumerConfProperties = [
18
    'onlyApplyToLdapAuthenticated' => TRUE,
19
    'useMappingsAsFilter' => TRUE,
20
    'synchOnLogon' => TRUE,
21
    'revokeLdapProvisioned' => TRUE,
22
    'regrantLdapProvisioned' => TRUE,
23
    'createConsumers' => TRUE,
24
  ];
25

    
26
  /**
27
   *
28
   */
29
  public function __construct($consumer_type = NULL) {
30
    $params = ldap_authorization_drupal_role_ldap_authorization_consumer();
31
    parent::__construct('drupal_role', $params['drupal_role']);
32
  }
33

    
34
  /**
35
   * @see LdapAuthorizationConsumerAbstract::createConsumer
36
   */
37
  public function createConsumer($consumer_id, $consumer) {
38
    $roles_by_consumer_id = $this->existingRolesByRoleName();
39
    $existing_role = isset($roles_by_consumer_id[$consumer_id]) ? $roles_by_consumer_id[$consumer_id] : FALSE;
40

    
41
    if ($existing_role) {
42
      // Role exists.
43
      return FALSE;
44
    }
45
    elseif (drupal_strlen($consumer_id) > 63) {
46
      watchdog('ldap_authorization_drupal_role', 'Tried to create drupal role
47
        with name of over 63 characters (%group_name).  Please correct your
48
        drupal ldap_authorization settings', ['%group_name' => $consumer_id]);
49
      return FALSE;
50
    }
51

    
52
    $new_role = new stdClass();
53
    $new_role->name = empty($consumer['value']) ? $consumer_id : $consumer['value'];
54
    if (!($status = user_role_save($new_role))) {
55
      // If role is not created, remove from array to user object doesn't have it stored as granted.
56
      watchdog('user', 'failed to create drupal role %role in ldap_authorizations module', ['%role' => $new_role->name]);
57
      return FALSE;
58
    }
59
    else {
60
      // Flush existingRolesByRoleName cache after creating new role.
61
      $roles_by_consumer_id = $this->existingRolesByRoleName(TRUE);
62
      watchdog('user', 'created drupal role %role in ldap_authorizations module', ['%role' => $new_role->name]);
63
    }
64
    return TRUE;
65
  }
66

    
67
  /**
68
   * @see LdapAuthorizationConsumerAbstract::populateConsumersFromConsumerIds
69
   */
70
  public function populateConsumersFromConsumerIds(&$consumers, $create_missing_consumers = FALSE) {
71

    
72
    $roles_by_consumer_id = $this->existingRolesByRoleName(TRUE);
73
    foreach ($consumers as $consumer_id => $consumer) {
74

    
75
      // Role marked as not existing.
76
      if (!$consumer['exists']) {
77
        // Check if is existing.
78
        if (isset($roles_by_consumer_id[$consumer_id])) {
79
          $consumer['exists'] = TRUE;
80
          $consumer['value'] = $roles_by_consumer_id[$consumer_id]['role_name'];
81
          $consumer['name'] = $consumer['map_to_string'];
82
          $consumer['map_to_string'] = $roles_by_consumer_id[$consumer_id]['role_name'];
83
        }
84
        elseif ($create_missing_consumers) {
85
          $consumer['value'] = $consumer['map_to_string'];
86
          $consumer['name'] = $consumer['map_to_string'];
87
          $result = $this->createConsumer($consumer_id, $consumer);
88
          $consumer['exists'] = $result;
89
        }
90
        else {
91
          $consumer['exists'] = FALSE;
92
        }
93
      }
94
      elseif (empty($consumer['value'])) {
95
        $consumer['value'] = $roles_by_consumer_id[$consumer_id]['role_name'];
96
      }
97
      $consumers[$consumer_id] = $consumer;
98
    }
99
  }
100

    
101
  /**
102
   *
103
   */
104
  public function revokeSingleAuthorization(&$user, $consumer_id, $consumer, &$user_auth_data, $user_save = FALSE, $reset = FALSE) {
105

    
106
    $role_name_lcase = $consumer_id;
107
    $role_name = empty($consumer['value']) ? $consumer_id : $consumer['value'];
108
    $rid = $this->getDrupalRoleIdFromRoleName($role_name);
109
    if (!$rid) {
110
      // Role id not found.
111
      $result = FALSE;
112
    }
113
    // User doesn't have role.
114
    elseif (!$user->roles[$rid]) {
115
      if (isset($user_auth_data[$consumer_id])) {
116
        unset($user_auth_data[$consumer_id]);
117
      }
118
      $result = TRUE;
119
    }
120
    else {
121
      unset($user->roles[$rid]);
122
      $user_edit = ['roles' => $user->roles];
123
      $account = user_load($user->uid);
124
      $user = user_save($account, $user_edit);
125
      $result = ($user && !isset($user->roles[$rid]));
126
      if ($result && isset($user_auth_data[$consumer_id])) {
127
        unset($user_auth_data[$consumer_id]);
128
      }
129
    }
130

    
131
    if ($this->detailedWatchdogLog) {
132
      watchdog('ldap_authorization', 'LdapAuthorizationConsumerDrupalRole.revokeSingleAuthorization()
133
        revoked:  rid=%rid, role_name=%role_name for username=%username, result=%result',
134
        [
135
          '%rid' => $rid,
136
          '%role_name' => $role_name,
137
          '%username' => $user->name,
138
          '%result' => $result,
139
        ], WATCHDOG_DEBUG);
140
    }
141

    
142
    return $result;
143

    
144
  }
145

    
146
  /**
147
   * Extends grantSingleAuthorization()
148
   */
149
  public function grantSingleAuthorization(&$user, $consumer_id, $consumer, &$user_auth_data, $user_save = FALSE, $reset = FALSE) {
150

    
151
    $role_name_lcase = $consumer_id;
152
    $role_name = empty($consumer['value']) ? $consumer_id : $consumer['value'];
153
    $rid = $this->getDrupalRoleIdFromRoleName($role_name);
154
    if (is_null($rid)) {
155
      watchdog('ldap_authorization', 'LdapAuthorizationConsumerDrupalRole.grantSingleAuthorization()
156
      failed to grant %username the role %role_name because role does not exist',
157
      ['%role_name' => $role_name, '%username' => $user->name],
158
      WATCHDOG_ERROR);
159
      return FALSE;
160
    }
161

    
162
    $user->roles[$rid] = $role_name;
163
    $user_edit = ['roles' => $user->roles];
164
    if ($this->detailedWatchdogLog) {
165
      watchdog('ldap_authorization', 'grantSingleAuthorization in drupal rold' . print_r($user, TRUE), [], WATCHDOG_DEBUG);
166
    }
167

    
168
    $account = user_load($user->uid);
169
    $user = user_save($account, $user_edit);
170
    $result = ($user && !empty($user->roles[$rid]));
171

    
172
    if ($this->detailedWatchdogLog) {
173
      watchdog('ldap_authorization', 'LdapAuthorizationConsumerDrupalRole.grantSingleAuthorization()
174
        granted: rid=%rid, role_name=%role_name for username=%username, result=%result',
175
        [
176
          '%rid' => $rid,
177
          '%role_name' => $role_name,
178
          '%username' => $user->name,
179
          '%result' => $result,
180
        ], WATCHDOG_DEBUG);
181
    }
182

    
183
    return $result;
184

    
185
  }
186

    
187
  /**
188
   *
189
   */
190
  public function usersAuthorizations(&$user) {
191
    $authorizations = [];
192
    foreach ($user->roles as $rid => $role_name_mixed_case) {
193
      $authorizations[] = drupal_strtolower($role_name_mixed_case);
194
    }
195
    return $authorizations;
196
  }
197

    
198
  /**
199
   *
200
   */
201
  public function validateAuthorizationMappingTarget($mapping, $form_values = NULL, $clear_cache = FALSE) {
202

    
203
    $has_form_values = is_array($form_values);
204
    $message_type = NULL;
205
    $message_text = NULL;
206
    $role_name = $mapping['normalized'];
207
    $tokens = ['!map_to' => $role_name];
208
    $roles_by_name = $this->existingRolesByRoleName();
209
    $pass = isset($roles_by_name[drupal_strtolower($role_name)]);
210

    
211
    if (!$pass) {
212
      $message_text = '"' . t('Drupal role') . ' ' . t('!map_to', $tokens) . '" ' . t('does not map to any existing Drupal roles.');
213
      if ($has_form_values) {
214
        $create_consumers = (isset($form_values['synchronization_actions']['create_consumers']) && $form_values['synchronization_actions']['create_consumers']);
215
      }
216
      else {
217
        $create_consumers = $this->consumerConf->createConsumers;
218
      }
219
      if ($create_consumers && $this->allowConsumerObjectCreation) {
220
        $message_type = 'warning';
221
        $message_text .= ' ' . t('"!map_to" will be created when needed.  If "!map_to" is not intentional, please fix it.', $tokens);
222
      }
223
      elseif (!$this->allowConsumerObjectCreation) {
224
        $message_type = 'error';
225
        $message_text .= ' ' . t('Since automatic Drupal role creation is not possible with this module, an existing role must be mapped to.');
226
      }
227
      elseif (!$create_consumers) {
228
        $message_type = 'error';
229
        $message_text .= ' ' . t('Since automatic Drupal role creation is disabled, an existing role must be mapped to.  Either enable role creation or map to an existing role.');
230
      }
231
    }
232
    return [$message_type, $message_text];
233
  }
234

    
235
  /**
236
   * @param string mixed case $role_name
237
   * @return integer role id
238
   */
239
  private function getDrupalRoleIdFromRoleName($role_name) {
240
    $role_ids_by_name = $this->existingRolesByRoleName();
241
    $role_name_lowercase = drupal_strtolower($role_name);
242
    return empty($role_ids_by_name[$role_name_lowercase]) ? NULL : $role_ids_by_name[$role_name_lowercase]['rid'];
243
  }
244

    
245
  /**
246
   * @param bool $reset
247
   *   to reset static values.
248
   * @return associative array() keyed on lowercase role names with values
249
   *   of array('rid' => role id, 'role_name' => mixed case role name)
250
   */
251
  public function existingRolesByRoleName($reset = FALSE) {
252

    
253
    static $roles_by_name;
254

    
255
    if ($reset || !is_array($roles_by_name)) {
256
      $roles_by_name = [];
257
      foreach (array_flip(user_roles(TRUE)) as $role_name => $rid) {
258
        $roles_by_name[drupal_strtolower($role_name)]['rid'] = $rid;
259
        $roles_by_name[drupal_strtolower($role_name)]['role_name'] = $role_name;
260
      }
261
    }
262
    return $roles_by_name;
263
  }
264

    
265
  /**
266
   * @see LdapAuthorizationConsumerAbstract::normalizeMappings
267
   */
268
  public function normalizeMappings($mappings) {
269

    
270
    $new_mappings = [];
271
    // In rid => role name format.
272
    $roles = user_roles(TRUE);
273
    $roles_by_name = array_flip($roles);
274
    foreach ($mappings as $i => $mapping) {
275
      $new_mapping = [];
276
      $new_mapping['user_entered'] = $mapping[1];
277
      $new_mapping['from'] = $mapping[0];
278
      $new_mapping['normalized'] = $mapping[1];
279
      $new_mapping['simplified'] = $mapping[1];
280
      $create_consumers = (boolean) ($this->allowConsumerObjectCreation && $this->consumerConf->createConsumers);
281
      $new_mapping['valid'] = (boolean) (!$create_consumers && !empty($roles_by_name[$mapping[1]]));
282
      $new_mapping['error_message'] = ($new_mapping['valid']) ? '' : t("Role %role_name does not exist and role creation is not enabled.", ['%role' => $mapping[1]]);
283
      $new_mappings[] = $new_mapping;
284
    }
285

    
286
    return $new_mappings;
287
  }
288

    
289
  /**
290
   * @see ldapAuthorizationConsumerAbstract::convertToFriendlyAuthorizationIds
291
   */
292
  public function convertToFriendlyAuthorizationIds($authorizations) {
293
    $authorization_ids_friendly = [];
294
    foreach ($authorizations as $authorization_id => $authorization) {
295
      $authorization_ids_friendly[] = $authorization['name'] . '  (' . $authorization_id . ')';
296
    }
297
    return $authorization_ids_friendly;
298
  }
299

    
300
}