Projet

Général

Profil

Paste
Télécharger (26,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / ldap / ldap_authorization / ldap_authorization_og / LdapAuthorizationConsumerOG.class.php @ bc175c27

1
<?php
2

    
3
/**
4
 * @file
5
 * Class for ldap authorization of organic groups.
6
 *
7
 * @see LdapAuthorizationConsumerAbstract for property
8
 */
9

    
10
if (function_exists('ldap_servers_module_load_include')) {
11
  ldap_servers_module_load_include('php', 'ldap_authorization', 'LdapAuthorizationConsumerAbstract.class');
12
}
13
else {
14
  module_load_include('php', 'ldap_authorization', 'LdapAuthorizationConsumerAbstract.class');
15
}
16
/**
17
 *
18
 */
19
class LdapAuthorizationConsumerOG extends LdapAuthorizationConsumerAbstract {
20

    
21
  public $consumerType = 'og_group';
22
  public $allowConsumerObjectCreation = FALSE;
23
  public $defaultMembershipRid;
24
  public $anonymousRid;
25
  public $defaultConsumerConfProperties = array(
26
    'onlyApplyToLdapAuthenticated' => TRUE,
27
    'useMappingsAsFilter' => TRUE,
28
    'synchOnLogon' => TRUE,
29
    'revokeLdapProvisioned' => TRUE,
30
    'regrantLdapProvisioned' => TRUE,
31
    'createConsumers' => TRUE,
32
  );
33

    
34
  /**
35
   *
36
   */
37
  public function __construct($consumer_type) {
38

    
39
    // @todo these properties are not used in ldap og 2, but when they are their derivation needs to be examined and tested
40
    // as they may be per entity rids, not global.
41
    // ldap_authorization_og_rid_from_role_name(OG_AUTHENTICATED_ROLE);
42
    $this->defaultMembershipRid = NULL;
43
    // ldap_authorization_og_rid_from_role_name(OG_ANONYMOUS_ROLE);
44
    $this->anonymousRid = NULL;
45

    
46
    $params = ldap_authorization_og_ldap_authorization_consumer();
47
    parent::__construct('og_group', $params['og_group']);
48
  }
49

    
50
  /**
51
   *
52
   */
53
  public function og2ConsumerIdParts($consumer_id) {
54
    if (!is_scalar($consumer_id)) {
55
      return array(NULL, NULL, NULL);
56
    }
57
    $parts = explode(':', $consumer_id);
58
    return (count($parts) != 3) ? array(NULL, NULL, NULL) : $parts;
59
  }
60

    
61
  /**
62
   * @see LdapAuthorizationConsumerAbstract::createConsumer
63
   *
64
   * this function is not implemented for og, but could be
65
   * if a use case for generating og groups and roles on the
66
   * fly existed.
67
   */
68
  public function createConsumer($consumer_id, $consumer) {
69
    return FALSE;
70
  }
71

    
72
  /**
73
   * @see LdapAuthorizationConsumerAbstract::normalizeMappings
74
   */
75
  public function normalizeMappings($mappings) {
76
    $new_mappings = array();
77
    $group_entity_types = og_get_all_group_bundle();
78
    foreach ($mappings as $i => $mapping) {
79
      $from = $mapping[0];
80
      $to = $mapping[1];
81
      $to_parts = explode('(raw: ', $to);
82
      $user_entered = $to_parts[0];
83
      $new_mapping = array(
84
        'from' => $from,
85
        'user_entered' => $user_entered,
86
        'valid' => TRUE,
87
        'error_message' => '',
88
      );
89

    
90
      // Has simplified and normalized part in (). update normalized part as validation.
91
      if (count($to_parts) == 2) {
92
        $to_normalized = trim($to_parts[1], ')');
93
        /**
94
         * users (node:35:1)
95
         * node:students (node:21:1)
96
         * faculty (node:33:2)
97
         * node:35:1 (node:35:1)
98
         * node:35 (node:35:1)
99
         */
100

    
101
        $to_simplified = $to_parts[0];
102
        $to_simplified_parts = explode(':', trim($to_simplified));
103
        $entity_type = (count($to_simplified_parts) == 1) ? 'node' : $to_simplified_parts[0];
104
        $role = (count($to_simplified_parts) < 3) ? OG_AUTHENTICATED_ROLE : $to_simplified_parts[2];
105
        $group_name = (count($to_simplified_parts) == 1) ? $to_simplified_parts[0] : $to_simplified_parts[1];
106
        list($group_entity, $group_entity_id) = ldap_authorization_og2_get_group_from_name($entity_type, $group_name);
107
        $to_simplified = join(':', array($entity_type, $group_name));
108
      }
109
      // May be simplified or normalized, but not both.
110
      else {
111
        /**
112
         * users
113
         * node:students
114
         * faculty
115
         * node:35:1
116
         * node:35
117
         */
118
        $to_parts = explode(':', trim($to));
119
        $entity_type = (count($to_parts) == 1) ? 'node' : $to_parts[0];
120
        $role = (count($to_parts) < 3) ? OG_AUTHENTICATED_ROLE : $to_parts[2];
121
        $group_name_or_entity_id = (count($to_parts) == 1) ? $to_parts[0] : $to_parts[1];
122
        list($group_entity, $group_entity_id) = ldap_authorization_og2_get_group_from_name($entity_type, $group_name_or_entity_id);
123
        // If load by name works, $group_name_or_entity_id is group title.
124
        if ($group_entity) {
125
          $to_simplified = join(':', array($entity_type, $group_name_or_entity_id));
126
        }
127
        else {
128
          $to_simplified = FALSE;
129
        }
130
        $simplified = (boolean) ($group_entity);
131
        if (!$group_entity && ($group_entity = @entity_load_single($entity_type, $group_name_or_entity_id))) {
132
          $group_entity_id = $group_name_or_entity_id;
133
        }
134
      }
135
      if (!$group_entity) {
136
        $new_mapping['normalized'] = FALSE;
137
        $new_mapping['simplified'] = FALSE;
138
        $new_mapping['valid'] = FALSE;
139
        $new_mapping['error_message'] = t("cannot find matching group: !to", array('!to' => $to));
140
      }
141
      else {
142
        $role_id = is_numeric($role) ? $role : ldap_authorization_og2_rid_from_role_name($entity_type, $group_entity->type, $group_entity_id, $role);
143
        $roles = og_roles($entity_type, isset($group_entity->type) ? $group_entity->type : NULL, 0, FALSE, TRUE);
144
        $role_name = is_numeric($role) ? $roles[$role] : $role;
145
        $to_normalized = join(':', array($entity_type, $group_entity_id, $role_id));
146
        $to_simplified = ($to_simplified) ? $to_simplified . ':' . $role_name : $to_normalized;
147
        $new_mapping['normalized'] = $to_normalized;
148
        $new_mapping['simplified'] = $to_simplified;
149
        if ($to == $to_normalized) {
150
          /**  if not using simplified notation, do not convert to simplified.
151
           * this would create a situation where an og group
152
           * can change its title and the authorizations change when the
153
           * admin specified the group by entity id
154
           */
155
          $new_mapping['user_entered'] = $to;
156
        }
157
        else {
158
          $new_mapping['user_entered'] = $to_simplified . ' (raw: ' . $to_normalized . ')';
159
        }
160

    
161
      }
162

    
163
      $new_mappings[] = $new_mapping;
164
    }
165
    return $new_mappings;
166
  }
167

    
168
  /**
169
   * In organic groups 7.x-1.x, consumer ids are in form gid-rid such as 3-2, 3-3.  We want highest authorization available granted.
170
   * But, granting member role (2), revokes other roles such as admin in OG.  So for granting we want the order:
171
   * 3-1, 3-2, 3-3 such that 3-3 is retained.  For revoking, the order should not matter, but reverse sorting makes
172
   * intuitive sense.
173
   */
174
  public function sortConsumerIds($op, &$consumers) {
175
    if ($op == 'revoke') {
176
      krsort($consumers, SORT_STRING);
177
    }
178
    else {
179
      ksort($consumers, SORT_STRING);
180
    }
181
  }
182

    
183
  /**
184
   * @see LdapAuthorizationConsumerAbstract::populateConsumersFromConsumerIds
185
   */
186
  public function populateConsumersFromConsumerIds(&$consumers, $create_missing_consumers = FALSE) {
187

    
188
    // Generate a query for all og groups of interest.
189
    $gids = array();
190
    foreach ($consumers as $consumer_id => $consumer) {
191
      list($entity_type, $gid, $rid) = explode(':', $consumer_id);
192
      $gids[$entity_type][] = $gid;
193

    
194
    }
195

    
196
    foreach ($gids as $entity_type => $gid_x_entity) {
197
      $og_group_entities[$entity_type] = @entity_load($entity_type, $gid_x_entity);
198
    }
199

    
200
    foreach ($consumers as $consumer_id => $consumer) {
201
      list($entity_type, $gid, $rid) = explode(':', $consumer_id);
202
      $consumer['exists'] = isset($og_group_entities[$entity_type][$gid]);
203
      $consumer['value'] = ($consumer['exists']) ? $og_group_entities[$entity_type][$gid] : NULL;
204
      $consumer['map_to_string'] = $consumer_id;
205
      if (
206
        empty($consumer['name']) &&
207
        !empty($og_group_entities[$entity_type][$gid]) &&
208
        property_exists($og_group_entities[$entity_type][$gid], 'title')
209
      ) {
210
        $consumer['name'] = $og_group_entities[$entity_type][$gid]->title;
211
      }
212

    
213
      if (!$consumer['exists'] && $create_missing_consumers) {
214
        // @todo if creation of og groups were implemented, function would be called here
215
        // this would mean mapping would need to have enough info to configure a group,
216
        // or settings would need to include a default group type to create (entity type,
217
        // bundle, etc.)
218
      }
219
      $consumers[$consumer_id] = $consumer;
220
    }
221
  }
222

    
223
  /**
224
   *
225
   */
226
  public function hasAuthorization(&$user, $consumer_id) {
227
    return ldap_authorization_og2_has_consumer_id($consumer_id, $user->uid);
228
  }
229

    
230
  /**
231
   *
232
   */
233
  public function flushRelatedCaches($consumers = NULL, $user = NULL) {
234
    if ($user) {
235
      // Clear user authorizations cache.
236
      $this->usersAuthorizations($user, TRUE, FALSE);
237
    }
238

    
239
    og_membership_invalidate_cache();
240

    
241
    if ($consumers) {
242
      $gids_to_clear_cache = array();
243
      foreach ($consumers as $i => $consumer_id) {
244
        list($entity_type, $gid, $rid) = $this->og2ConsumerIdParts($consumer_id);
245
        $gids_to_clear_cache[$gid] = $gid;
246
      }
247
      og_invalidate_cache(array_keys($gids_to_clear_cache));
248
    }
249
    else {
250
      og_invalidate_cache();
251
    }
252
  }
253

    
254
  /**
255
   * @param string $op
256
   *   'grant' or 'revoke' signifying what to do with the $consumer_ids.
257
   * @param drupal user object $object
258
   * @param array $user_auth_data
259
   *   is array specific to this consumer_type.  Stored at $user->data['ldap_authorizations'][<consumer_type>].
260
   * @param $consumers
261
   *   as associative array in form of LdapAuthorizationConsumerAbstract::populateConsumersFromConsumerIds
262
   * @param array $ldap_entry,
263
   *   when available user's ldap entry.
264
   * @param bool $user_save
265
   *   indicates is user data array should be saved or not.  this is always overridden for og.
266
   */
267
  public function authorizationDiff($existing, $desired) {
268
    return parent::authorizationDiff($existing, $desired);
269
  }
270

    
271
  /**
272
   *
273
   */
274
  protected function grantsAndRevokes($op, &$user, &$user_auth_data, $consumers, &$ldap_entry = NULL, $user_save = TRUE) {
275

    
276
    if (!is_array($user_auth_data)) {
277
      $user_auth_data = array();
278
    }
279

    
280
    $detailed_watchdog_log = variable_get('ldap_help_watchdog_detail', 0);
281
    $this->sortConsumerIds($op, $consumers);
282

    
283
    $results = array();
284
    $watchdog_tokens = array();
285
    $watchdog_tokens['%username'] = $user->name;
286
    $watchdog_tokens['%action'] = $op;
287
    $watchdog_tokens['%user_save'] = $user_save;
288

    
289
    /**
290
     * get authorizations that exist, regardless of origin or ldap_authorization $user->data
291
     * in form $users_authorization_consumer_ids = array('3-2', '3,3', '4-2')
292
     */
293
    $users_authorization_consumer_ids = $this->usersAuthorizations($user, TRUE);
294

    
295
    $watchdog_tokens['%users_authorization_ids'] = join(', ', $users_authorization_consumer_ids);
296
    if ($detailed_watchdog_log) {
297
      watchdog('ldap_authorization', "on call of grantsAndRevokes: user_auth_data=" . print_r($user_auth_data, TRUE), $watchdog_tokens, WATCHDOG_DEBUG);
298
    }
299

    
300
    /**
301
     * step #1:  generate $og_actions = array of form $og_actions['revokes'|'grants'][$gid] = $rid
302
     *  based on all consumer ids granted and revokes
303
     */
304
    $og_actions = array('grants' => array(), 'revokes' => array());
305
    $consumer_ids_log = "";
306
    $log = "";
307

    
308
    foreach ($consumers as $consumer_id => $consumer) {
309
      if ($detailed_watchdog_log) {
310
        watchdog('ldap_authorization', "consumer_id=$consumer_id, user_save=$user_save, op=$op", $watchdog_tokens, WATCHDOG_DEBUG);
311
      }
312
      $log = "consumer_id=$consumer_id, op=$op,";
313

    
314
      // Does user already have authorization ?
315
      $user_has_authorization = in_array($consumer_id, $users_authorization_consumer_ids);
316
      // Is authorization attribute to ldap_authorization_og in $user->data ?
317
      $user_has_authorization_recorded = isset($user_auth_data[$consumer_id]);
318

    
319
      list($entity_type, $gid, $rid) = $this->og2ConsumerIdParts($consumer_id);
320

    
321
      /** grants **/
322
      if ($op == 'grant') {
323
        if ($user_has_authorization && !$user_has_authorization_recorded) {
324
          // Grant case 1: authorization id already exists for user, but is not ldap provisioned.  mark as ldap provisioned, but don't regrant.
325
          $results[$consumer_id] = TRUE;
326
          $user_auth_data[$consumer_id] = array(
327
            'date_granted' => time(),
328
            'consumer_id_mixed_case' => $consumer_id,
329
          );
330
          $log .= "grant case 1: authorization id already exists for user, but is not ldap provisioned.  mark as ldap provisioned, but don't regrant";
331
          $log .= $consumer_id;
332
        }
333
        elseif (!$user_has_authorization && $consumer['exists']) {
334
          // Grant case 2: consumer exists, but user is not member. grant authorization.
335
          $og_actions['grants'][$entity_type][$gid][] = $rid;
336
          $log .= "grant case 2: consumer exists, but user is not member. grant authorization";
337
          $log .= " " . $entity_type . ":" . $gid . ":" . $rid;
338
        }
339
        elseif ($consumer['exists'] !== TRUE) {
340
          // Grant case 3: something is wrong. consumers should have been created before calling grantsAndRevokes.
341
          $results[$consumer_id] = FALSE;
342
          $log .= "grant case 3: something is wrong. consumers should have been created before calling grantsAndRevokes";
343
          $log .= " " . $consumer_id;
344
        }
345
        elseif ($consumer['exists'] === TRUE) {
346
          // Grant case 4: consumer exists and user has authorization recorded. do nothing.
347
          $results[$consumer_id] = TRUE;
348
          $log .= "grant case 4: consumer exists and user has authorization recorded. do nothing";
349
          $log .= " " . $consumer_id;
350
        }
351
        else {
352
          // Grant case 5: $consumer['exists'] has not been properly set before calling function.
353
          $results[$consumer_id] = FALSE;
354
          watchdog('ldap_authorization', "grantsAndRevokes consumer[exists] not properly set. consumer_id=$consumer_id, op=$op, username=%username", $watchdog_tokens, WATCHDOG_ERROR);
355
          $log .= "grantsAndRevokes consumer[exists] not properly set. consumer_id=$consumer_id, op=$op, username=%username";
356
        }
357
        $consumer_ids_log .= $log;
358
      }
359
      /** revokes **/
360
      elseif ($op == 'revoke') {
361
        if ($user_has_authorization) {
362
          // Revoke case 1: user has authorization, revoke it.  revokeSingleAuthorization will remove $user_auth_data[$consumer_id].
363
          $og_actions['revokes'][$entity_type][$gid][] = $rid;
364
          $log .= "revoke case 1: user has authorization, revoke it.  revokeSingleAuthorization will remove $consumer_id";
365
          $log .= " " . $entity_type . ":" . $gid . ":" . $rid;
366
        }
367
        elseif ($user_has_authorization_recorded) {
368
          // Revoke case 2: user does not have authorization, but has record of it. remove record of it.
369
          unset($user_auth_data[$consumer_id]);
370
          $results[$consumer_id] = TRUE;
371
          $log .= "revoke case 2: user does not have authorization, but has record of it. remove record of it.";
372
          $log .= $consumer_id;
373
        }
374
        else {
375
          // Revoke case 3: trying to revoke something that isn't there.
376
          $results[$consumer_id] = TRUE;
377
          $log .= "revoke case 3: trying to revoke something that isn't there";
378
          $log .= $consumer_id;
379
        }
380
      }
381
      if ($detailed_watchdog_log) {
382
        watchdog('ldap_authorization', "user_auth_data after consumer $consumer_id" . print_r($user_auth_data, TRUE), $watchdog_tokens, WATCHDOG_DEBUG);
383
      }
384
      $consumer_ids_log .= $log;
385
    }
386

    
387
    $watchdog_tokens['%consumer_ids_log'] = $consumer_ids_log;
388

    
389
    /**
390
     * Step #2: from array of form:
391
     *   $og_actions['grants'|'revokes'][$entity_type][$gid][$rid]
392
     * - generate $user->data['ldap_authorizations'][<consumer_id>]
393
     * - remove and grant og memberships
394
     * - remove and grant og roles
395
     * - flush appropriate caches
396
     */
397
    $this->og2Grants($og_actions, $user, $user_auth_data);
398
    $this->og2Revokes($og_actions, $user, $user_auth_data);
399

    
400
    $user_edit = array('data' => $user->data);
401
    $user_edit['data']['ldap_authorizations'][$this->consumerType] = $user_auth_data;
402
    // Force a reload of the user object, since changes made through the grant-
403
    // and revoke-functions above might have changed og-related field data.
404
    // Those changes will not yet be reflected in $user, potentially causing
405
    // data loss when user_save() is called with stale data.
406
    $user = user_load($user->uid, TRUE);
407
    $user = user_save($user, $user_edit);
408

    
409
    // Reset this variable because user save hooks can impact it.
410
    $user_auth_data = $user->data['ldap_authorizations'][$this->consumerType];
411

    
412
    $this->flushRelatedCaches($consumers, $user);
413

    
414
    if ($detailed_watchdog_log) {
415
      watchdog('ldap_authorization', '%username:
416
        <hr/>LdapAuthorizationConsumerAbstract grantsAndRevokes() method log.  action=%action:<br/> %consumer_ids_log
417
        ',
418
        $watchdog_tokens, WATCHDOG_DEBUG);
419
    }
420
  }
421

    
422
  /**
423
   *
424
   */
425
  public function og2Grants($og_actions, &$user, &$user_auth_data) {
426
    foreach ($og_actions['grants'] as $group_entity_type => $gids) {
427
      // All rids ldap believes user should be granted and attributed to ldap.
428
      foreach ($gids as $gid => $granting_rids) {
429
        // All roles rid => role_name array w/ authen or anon roles.
430
        $all_group_roles = og_roles($group_entity_type, FALSE, $gid, FALSE, TRUE);
431
        $authenticated_rid = array_search(OG_AUTHENTICATED_ROLE, $all_group_roles);
432
        $anonymous_rid = array_search(OG_ANONYMOUS_ROLE, $all_group_roles);
433
        // All rids array w/ authen or anon rids.
434
        $all_group_rids = array_keys($all_group_roles);
435
        // Users current rids w/authen or anon roles returned.
436
        $users_group_rids = array_keys(og_get_user_roles($group_entity_type, $gid, $user->uid, TRUE));
437
        $users_group_rids = array_diff($users_group_rids, array($anonymous_rid));
438
        // Rids to be added without anonymous rid.
439
        $new_rids = array_diff($granting_rids, $users_group_rids, array($anonymous_rid));
440

    
441
        // If adding OG_AUTHENTICATED_ROLE or any other role and does not currently have OG_AUTHENTICATED_ROLE, group.
442
        if (!in_array($authenticated_rid, $users_group_rids) && count($new_rids) > 0) {
443
          $values = array(
444
            'entity_type' => 'user',
445
            'entity' => $user->uid,
446
            'field_name' => FALSE,
447
            'state' => OG_STATE_ACTIVE,
448
          );
449
          $og_membership = og_group($group_entity_type, $gid, $values);
450
          $consumer_id = join(':', array($group_entity_type, $gid, $authenticated_rid));
451
          $user_auth_data[$consumer_id] = array(
452
            'date_granted' => time(),
453
            'consumer_id_mixed_case' => $consumer_id,
454
          );
455
          // Granted on membership creation.
456
          $new_rids = array_diff($new_rids, array($authenticated_rid));
457

    
458
        }
459
        foreach ($new_rids as $i => $rid) {
460
          og_role_grant($group_entity_type, $gid, $user->uid, $rid);
461
        }
462
        foreach ($granting_rids as $i => $rid) {
463
          // Attribute to ldap regardless of if is being granted.
464
          $consumer_id = join(':', array($group_entity_type, $gid, $rid));
465
          $user_auth_data[$consumer_id] = array(
466
            'date_granted' => time(),
467
            'consumer_id_mixed_case' => $consumer_id,
468
          );
469
        }
470
      }
471
    }
472
  }
473

    
474
  /**
475
   *
476
   */
477
  public function og2Revokes($og_actions, &$user, &$user_auth_data) {
478
    foreach ($og_actions['revokes'] as $group_entity_type => $gids) {
479
      // $revoking_rids are all rids to be removed.  may include authen rids.
480
      foreach ($gids as $gid => $revoking_rids) {
481
        // All roles rid => role_name array w/ authen or anon roles.
482
        $all_group_roles = og_roles($group_entity_type, FALSE, $gid, FALSE, TRUE);
483
        // All rids array w/ authen or anon rids.
484
        $all_group_rids = array_keys($all_group_roles);
485
        // Users current rids w/authen or anon roles returned.
486
        $users_group_rids = array_keys(og_get_user_roles($group_entity_type, $gid, $user->uid, TRUE));
487
        // Rids to be left at end of revoke process.
488
        $remaining_rids = array_diff($users_group_rids, $revoking_rids);
489
        $authenticated_rid = array_search(OG_AUTHENTICATED_ROLE, $all_group_roles);
490
        // Remove autenticated and anon rids here.
491
        foreach ($revoking_rids as $i => $rid) {
492
          // Revoke if user has role.
493
          if (in_array($rid, $users_group_rids)) {
494
            og_role_revoke($group_entity_type, $gid, $user->uid, $rid);
495
          }
496
          // Unattribute to ldap even if user does not currently have role.
497
          unset($user_auth_data[ldap_authorization_og_authorization_id($gid, $rid, $group_entity_type)]);
498
        }
499
        // define('OG_ANONYMOUS_ROLE', 'non-member'); define('OG_AUTHENTICATED_ROLE', 'member');
500
        // ungroup if only authenticated and anonymous role left.
501
        if (in_array($authenticated_rid, $revoking_rids) || count($remaining_rids) == 0) {
502
          $entity = og_ungroup($group_entity_type, $gid, 'user', $user->uid);
503
          $result = (boolean) ($entity);
504
        }
505
      }
506
    }
507
  }
508

    
509
  /**
510
   * @see ldapAuthorizationConsumerAbstract::usersAuthorizations
511
   */
512
  public function usersAuthorizations(&$user, $reset = FALSE, $return_data = TRUE) {
513

    
514
    static $users;
515
    if (!is_array($users)) {
516
      // No cache exists, create static array.
517
      $users = array();
518
    }
519
    elseif ($reset && isset($users[$user->uid])) {
520
      // Clear users cache.
521
      unset($users[$user->uid]);
522
    }
523
    elseif (!$return_data) {
524
      // Simply clearing cache.
525
      return NULL;
526
    }
527
    elseif (!empty($users[$user->uid])) {
528
      // Return cached data.
529
      return $users[$user->uid];
530
    }
531

    
532
    $authorizations = array();
533

    
534
    $user_entities = entity_load('user', array($user->uid));
535
    $memberships = og_get_entity_groups('user', $user_entities[$user->uid]);
536
    foreach ($memberships as $entity_type => $entity_memberships) {
537
      foreach ($entity_memberships as $og_membership_id => $gid) {
538
        $roles = og_get_user_roles($entity_type, $gid, $user->uid);
539
        foreach ($roles as $rid => $discard) {
540
          $authorizations[] = ldap_authorization_og_authorization_id($gid, $rid, $entity_type);
541
        }
542
      }
543
    }
544
    $users[$user->uid] = $authorizations;
545

    
546
    return $authorizations;
547
  }
548

    
549
  /**
550
   * @see ldapAuthorizationConsumerAbstract::convertToFriendlyAuthorizationIds
551
   */
552
  public function convertToFriendlyAuthorizationIds($authorizations) {
553
    $authorization_ids_friendly = array();
554
    foreach ($authorizations as $authorization_id => $authorization) {
555
      $authorization_ids_friendly[] = $authorization['name'] . '  (' . $authorization_id . ')';
556
    }
557
    return $authorization_ids_friendly;
558
  }
559

    
560
  /**
561
   * @see ldapAuthorizationConsumerAbstract::validateAuthorizationMappingTarget
562
   */
563
  public function validateAuthorizationMappingTarget($mapping, $form_values = NULL, $clear_cache = FALSE) {
564
    // These mappings have already been through the normalizeMappings() method, so no real querying needed here.
565
    $has_form_values = is_array($form_values);
566
    $message_type = NULL;
567
    $message_text = NULL;
568
    $pass = !empty($mapping['valid']) && $mapping['valid'] === TRUE;
569

    
570
    /**
571
     * @todo need to look this over
572
     *
573
     */
574
    if (!$pass) {
575
      $tokens = array(
576
        '!from' => $mapping['from'],
577
        '!user_entered' => $mapping['user_entered'],
578
        '!error' => $mapping['error_message'],
579
      );
580
      $message_text = '<code>"' . t('!map_to|!user_entered', $tokens) . '"</code> ' . t('has the following error: !error.', $tokens);
581
    }
582
    return array($message_type, $message_text);
583
  }
584

    
585
  /**
586
   * Get list of mappings based on existing Organic Groups and roles.
587
   *
588
   * @param array $tokens
589
   *   Array of tokens and replacement values.
590
   *
591
   * @return
592
   *   HTML examples of mapping values.
593
   */
594
  public function mappingExamples($tokens) {
595
    /**
596
     * OG 7.x-2.x mappings:
597
     * $entity_type = $group_type,
598
     * $bundle = $group_bundle
599
     * $etid = $gid where edid is nid, uid, etc.
600
     *
601
     * og group is: entity_type (eg node) x entity_id ($gid) eg. node:17
602
     * group identifier = group_type:gid; aka entity_type:etid e.g. node:17
603
     *
604
     * membership identifier is:  group_type:gid:entity_type:etid
605
     * in our case: group_type:gid:user:uid aka entity_type:etid:user:uid e.g. node:17:user:2
606
     *
607
     * roles are simply rids ((1,2,3) and names (non-member, member, and administrator member) in og_role table
608
     * og_users_roles is simply uid x rid x gid
609
     *
610
     * .. so authorization mappings should look like:
611
     *    <ldap group>|group_type:gid:rid such as staff|node:17:2
612
     */
613

    
614
    $og_fields = field_info_field(OG_GROUP_FIELD);
615
    $rows = array();
616
    $role_name = OG_AUTHENTICATED_ROLE;
617

    
618
    if (!empty($og_fields['bundles'])) {
619
      foreach ($og_fields['bundles'] as $entity_type => $bundles) {
620
        foreach ($bundles as $i => $bundle) {
621
          $query = new EntityFieldQuery();
622
          $query->entityCondition('entity_type', $entity_type)
623
            ->entityCondition('bundle', $bundle)
624
            ->range(0, 5)
625
          // Run the query as user 1.
626
            ->addMetaData('account', user_load(1));
627
          $result = $query->execute();
628
          if (!empty($result)) {
629
            $entities = entity_load($entity_type, array_keys($result[$entity_type]));
630
            $i = 0;
631
            if ($entities) {
632
              foreach ($entities as $entity_id => $entity) {
633
                $i++;
634
                $rid = ldap_authorization_og2_rid_from_role_name($entity_type, $bundle, $entity_id, OG_AUTHENTICATED_ROLE);
635
                $title = (is_object($entity) && property_exists($entity, 'title')) ? $entity->title : '';
636
                $middle = ($title && $i < 3) ? $title : $entity_id;
637
                $group_role_identifier = ldap_authorization_og_authorization_id($middle, $rid, $entity_type);
638
                $example = "<code>ou=IT,dc=myorg,dc=mytld,dc=edu|$group_role_identifier</code>";
639
                $rows[] = ["$entity_type $title - $role_name", $example];
640
              }
641
            }
642
          }
643
        }
644
      }
645
    }
646

    
647
    $variables = array(
648
      'header' => array('Group Entity - Group Title - OG Membership Type', 'example'),
649
      'rows' => $rows,
650
      'attributes' => array(),
651
    );
652

    
653
    $table = theme('table', $variables);
654
    $link = l(t('admin/config/people/ldap/authorization/test/og_group'), 'admin/config/people/ldap/authorization/test/og_group');
655

    
656
    $examples =
657
    <<<EOT
658

659
<br/>
660
Examples for some (or all) existing OG Group IDs can be found in the table below.
661
This is complex.  To test what is going to happen, uncheck "When a user logs on" in IV.B.
662
and use $link to see what memberships sample users would receive.
663

664
$table
665

666
EOT;
667
    $examples = t($examples, $tokens);
668
    return $examples;
669
  }
670

    
671
}