Projet

Général

Profil

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

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

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
      $og_group_entities[$entity_type] = @entity_load($entity_type, $gid_x_entity);
194
    }
195

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

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

    
219
  /**
220
   *
221
   */
222
  public function hasAuthorization(&$user, $consumer_id) {
223
    return ldap_authorization_og2_has_consumer_id($consumer_id, $user->uid);
224
  }
225

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

    
235
    og_membership_invalidate_cache();
236

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

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

    
267
  /**
268
   *
269
   */
270
  protected function grantsAndRevokes($op, &$user, &$user_auth_data, $consumers, &$ldap_entry = NULL, $user_save = TRUE) {
271

    
272
    if (!is_array($user_auth_data)) {
273
      $user_auth_data = [];
274
    }
275

    
276
    $detailed_watchdog_log = variable_get('ldap_help_watchdog_detail', 0);
277
    $this->sortConsumerIds($op, $consumers);
278

    
279
    $results = [];
280
    $watchdog_tokens = [];
281
    $watchdog_tokens['%username'] = $user->name;
282
    $watchdog_tokens['%action'] = $op;
283
    $watchdog_tokens['%user_save'] = $user_save;
284

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

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

    
296
    /**
297
     * step #1:  generate $og_actions = array of form $og_actions['revokes'|'grants'][$gid] = $rid
298
     *  based on all consumer ids granted and revokes
299
     */
300
    $og_actions = ['grants' => [], 'revokes' => []];
301
    $consumer_ids_log = "";
302
    $log = "";
303

    
304
    foreach ($consumers as $consumer_id => $consumer) {
305
      if ($detailed_watchdog_log) {
306
        watchdog('ldap_authorization', "consumer_id=$consumer_id, user_save=$user_save, op=$op", $watchdog_tokens, WATCHDOG_DEBUG);
307
      }
308
      $log = "consumer_id=$consumer_id, op=$op,";
309

    
310
      // Does user already have authorization ?
311
      $user_has_authorization = in_array($consumer_id, $users_authorization_consumer_ids);
312
      // Is authorization attribute to ldap_authorization_og in $user->data ?
313
      $user_has_authorization_recorded = isset($user_auth_data[$consumer_id]);
314

    
315
      list($entity_type, $gid, $rid) = $this->og2ConsumerIdParts($consumer_id);
316

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

    
383
    $watchdog_tokens['%consumer_ids_log'] = $consumer_ids_log;
384

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

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

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

    
408
    $this->flushRelatedCaches($consumers, $user);
409

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

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

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

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

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

    
504
  /**
505
   * @see ldapAuthorizationConsumerAbstract::usersAuthorizations
506
   */
507
  public function usersAuthorizations(&$user, $reset = FALSE, $return_data = TRUE) {
508

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

    
527
    $authorizations = [];
528

    
529
    $user_entities = entity_load('user', [$user->uid]);
530
    $memberships = og_get_entity_groups('user', $user_entities[$user->uid]);
531
    foreach ($memberships as $entity_type => $entity_memberships) {
532
      foreach ($entity_memberships as $og_membership_id => $gid) {
533
        $roles = og_get_user_roles($entity_type, $gid, $user->uid);
534
        foreach ($roles as $rid => $discard) {
535
          $authorizations[] = ldap_authorization_og_authorization_id($gid, $rid, $entity_type);
536
        }
537
      }
538
    }
539
    $users[$user->uid] = $authorizations;
540

    
541
    return $authorizations;
542
  }
543

    
544
  /**
545
   * @see ldapAuthorizationConsumerAbstract::convertToFriendlyAuthorizationIds
546
   */
547
  public function convertToFriendlyAuthorizationIds($authorizations) {
548
    $authorization_ids_friendly = [];
549
    foreach ($authorizations as $authorization_id => $authorization) {
550
      $authorization_ids_friendly[] = $authorization['name'] . '  (' . $authorization_id . ')';
551
    }
552
    return $authorization_ids_friendly;
553
  }
554

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

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

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

    
609
    $og_fields = field_info_field(OG_GROUP_FIELD);
610
    $rows = [];
611
    $role_name = OG_AUTHENTICATED_ROLE;
612

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

    
642
    $variables = [
643
      'header' => ['Group Entity - Group Title - OG Membership Type', 'example'],
644
      'rows' => $rows,
645
      'attributes' => [],
646
    ];
647

    
648
    $table = theme('table', $variables);
649
    $link = l(t('admin/config/people/ldap/authorization/test/og_group'), 'admin/config/people/ldap/authorization/test/og_group');
650

    
651
    $examples =
652
    <<<EOT
653

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

659
$table
660

661
EOT;
662
    $examples = t($examples, $tokens);
663
    return $examples;
664
  }
665

    
666
}