Projet

Général

Profil

Paste
Télécharger (25,9 ko) Statistiques
| Branche: | Révision:

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

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 = [
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
    $this->defaultMembershipRid = NULL;
40
    $this->anonymousRid = NULL;
41

    
42
    $params = ldap_authorization_og_ldap_authorization_consumer();
43
    parent::__construct('og_group', $params['og_group']);
44
  }
45

    
46
  /**
47
   *
48
   */
49
  public function og2ConsumerIdParts($consumer_id) {
50
    if (!is_scalar($consumer_id)) {
51
      return [NULL, NULL, NULL];
52
    }
53
    $parts = explode(':', $consumer_id);
54
    return (count($parts) != 3) ? [NULL, NULL, NULL] : $parts;
55
  }
56

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

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

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

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

    
157
      }
158

    
159
      $new_mappings[] = $new_mapping;
160
    }
161
    return $new_mappings;
162
  }
163

    
164
  /**
165
   * 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.
166
   * But, granting member role (2), revokes other roles such as admin in OG.  So for granting we want the order:
167
   * 3-1, 3-2, 3-3 such that 3-3 is retained.  For revoking, the order should not matter, but reverse sorting makes
168
   * intuitive sense.
169
   */
170
  public function sortConsumerIds($op, &$consumers) {
171
    if ($op == 'revoke') {
172
      krsort($consumers, SORT_STRING);
173
    }
174
    else {
175
      ksort($consumers, SORT_STRING);
176
    }
177
  }
178

    
179
  /**
180
   * @see LdapAuthorizationConsumerAbstract::populateConsumersFromConsumerIds
181
   */
182
  public function populateConsumersFromConsumerIds(&$consumers, $create_missing_consumers = FALSE) {
183

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

    
190
    }
191

    
192
    foreach ($gids as $entity_type => $gid_x_entity) {
193
      if ($entity_type !== NULL) {
194
        $og_group_entities[$entity_type] = @entity_load($entity_type, $gid_x_entity);
195
      }
196
      else {
197
        watchdog("ldap_authorization_og", "Entity type of 'NULL' found while populating consumers.", WATCHDOG_ERROR);
198
      }
199
    }
200

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

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

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

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

    
240
    og_membership_invalidate_cache();
241

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

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

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

    
277
    if (!is_array($user_auth_data)) {
278
      $user_auth_data = [];
279
    }
280

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
475
  /**
476
   *
477
   */
478
  public function og2Revokes($og_actions, &$user, &$user_auth_data) {
479
    foreach ($og_actions['revokes'] as $group_entity_type => $gids) {
480
      // $revoking_rids are all rids to be removed.  may include authen rids.
481
      foreach ($gids as $gid => $revoking_rids) {
482
        // All roles rid => role_name array w/ authen or anon roles.
483
        $all_group_roles = og_roles($group_entity_type, FALSE, $gid, FALSE, TRUE);
484
        // All rids array w/ authen or anon rids.
485
        $all_group_rids = array_keys($all_group_roles);
486
        // Users current rids w/authen or anon roles returned.
487
        $users_group_rids = array_keys(og_get_user_roles($group_entity_type, $gid, $user->uid, TRUE));
488
        // Rids to be left at end of revoke process.
489
        $remaining_rids = array_diff($users_group_rids, $revoking_rids);
490
        $authenticated_rid = array_search(OG_AUTHENTICATED_ROLE, $all_group_roles);
491
        // Remove autenticated and anon rids here.
492
        foreach ($revoking_rids as $i => $rid) {
493
          // Revoke if user has role.
494
          if (in_array($rid, $users_group_rids)) {
495
            og_role_revoke($group_entity_type, $gid, $user->uid, $rid);
496
          }
497
          // Unattribute to ldap even if user does not currently have role.
498
          unset($user_auth_data[ldap_authorization_og_authorization_id($gid, $rid, $group_entity_type)]);
499
        }
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 = [];
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 = [];
533

    
534
    $user_entities = entity_load('user', [$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 = [];
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 = [
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 [$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 = [];
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 = [
648
      'header' => ['Group Entity - Group Title - OG Membership Type', 'example'],
649
      'rows' => $rows,
650
      'attributes' => [],
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
}