Projet

Général

Profil

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

root / htmltest / sites / all / modules / ldap / ldap_authorization / ldap_authorization_og / LdapAuthorizationConsumerOG.class.php @ dd54aff9

1
<?php
2

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

    
11
if (function_exists('ldap_servers_module_load_include')) {
12
  ldap_servers_module_load_include('php', 'ldap_authorization', 'LdapAuthorizationConsumerAbstract.class');
13
}
14
else {
15
  module_load_include('php', 'ldap_authorization', 'LdapAuthorizationConsumerAbstract.class');
16
}
17

    
18
class LdapAuthorizationConsumerOG extends LdapAuthorizationConsumerAbstract {
19

    
20
  public $consumerType = 'og_group';
21
  public $allowConsumerObjectCreation = FALSE;
22
  public $ogVersion = NULL; // 1, 2, etc.
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
  function __construct($consumer_type) {
35

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

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

    
52
  public function og1ConsumerIdParts($consumer_id) {
53
    if (!is_scalar($consumer_id)) {
54
      return array(NULL, NULL);
55
    }
56
    $parts = explode('-', $consumer_id);
57
    return (count($parts) != 2) ? array(NULL, NULL) : $parts;
58
  }
59

    
60
  public function og2ConsumerIdParts($consumer_id) {
61
    if (!is_scalar($consumer_id)) {
62
      return array(NULL, NULL, NULL);
63
    }
64
    $parts = explode(':', $consumer_id);
65
    return (count($parts) != 3) ? array(NULL, NULL, NULL) : $parts;
66
  }
67

    
68

    
69
  /**
70
   * @see LdapAuthorizationConsumerAbstract::createConsumer
71
   *
72
   * this function is not implemented for og, but could be
73
   * if a use case for generating og groups and roles on the
74
   * fly existed.
75
   */
76

    
77
  public function createConsumer($consumer_id, $consumer) {
78
    return FALSE;
79
  }
80

    
81
  /**
82
   * @see LdapAuthorizationConsumerAbstract::normalizeMappings
83
   */
84
  public function normalizeMappings($mappings) {
85

    
86
    $new_mappings = array();
87
    if ($this->ogVersion == 2) {
88
      $group_entity_types = og_get_all_group_bundle();
89
      foreach ($mappings as $i => $mapping) {
90
        $from = $mapping[0];
91
        $to = $mapping[1];
92
        $to_parts = explode('(raw: ', $to);
93
        $user_entered = $to_parts[0];
94
        $new_mapping = array(
95
          'from' => $from,
96
          'user_entered' => $user_entered,
97
          'valid' => TRUE,
98
          'error_message' => '',
99
        );
100

    
101
        if (count($to_parts) == 2) { // has simplified and normalized part in (). update normalized part as validation
102
          $to_normalized = trim($to_parts[1], ')');
103
          /**
104
           * users (node:35:1)
105
           * node:students (node:21:1)
106
           * faculty (node:33:2)
107
           * node:35:1 (node:35:1)
108
           * node:35 (node:35:1)
109
           */
110

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

    
169

    
170
        }
171

    
172
        $new_mappings[] = $new_mapping;
173
      }
174
    }
175
    else { // og 1
176
      foreach ($mappings as $i => $mapping) {
177
        $new_mapping = array(
178
          'from' => $mapping[0],
179
          'user_entered' => $mapping[1],
180
          'normalized' => NULL,
181
          'simplified' => NULL,
182
          'valid' => TRUE,
183
          'error_message' => '',
184
        );
185

    
186
        $gid = NULL;
187
        $rid = NULL;
188
        $correct_syntax = "gid=43,rid=2 or group-name=students,role-name=member or node.title=students,role-name=member";
189
        $incorrect_syntax = t('Incorrect mapping syntax.  Correct examples are:') . $correct_syntax;
190
        $targets = explode(',', $mapping[1]);
191
        if (count($targets) != 2) {
192
          $new_mapping['valid'] = FALSE;
193
          $new_mapping['error_message'] = $incorrect_syntax;
194
          continue;
195
        }
196

    
197
        $group_target_and_value =  explode('=', $targets[0]);
198
        if (count($group_target_and_value) != 2) {
199
          $new_mapping['valid'] = FALSE;
200
          $new_mapping['error_message'] = $incorrect_syntax;
201
          continue;
202
        }
203

    
204
        list($group_target, $group_target_value) = $group_target_and_value;
205

    
206
        $role_target_and_value = explode('=', $targets[1]);
207
        if (count($role_target_and_value) != 2) {
208
          $new_mapping['valid'] = FALSE;
209
          $new_mapping['error_message'] = $incorrect_syntax;
210
          continue;
211
        }
212
        list($role_target, $role_target_value) = $role_target_and_value;
213

    
214

    
215
        $og_group = FALSE;
216
        if ($group_target == 'gid') {
217
          $gid = $group_target_value;
218
        }
219
        elseif ($group_target == 'group-name') {
220
          list($og_group, $og_node) = ldap_authorization_og1_get_group($group_target_value, 'group_name', 'object');
221
          if (is_object($og_group) && property_exists($og_group, 'gid') && $og_group->gid) {
222
            $gid = $og_group->gid;
223
          }
224
        }
225
        else {
226
          $entity_type_and_field = explode('.', $group_target);
227
          if (count($entity_type_and_field) != 2) {
228
            $new_mapping['valid'] = FALSE;
229
            $new_mapping['error_message'] = $incorrect_syntax;
230
            continue;
231
          }
232
          list($entity_type, $field) = $entity_type_and_field;
233

    
234
          $query = new EntityFieldQuery();
235
          $query->entityCondition('entity_type', $entity_type)
236
            ->fieldCondition($field, 'value', $group_target_value, '=')
237
            ->addMetaData('account', user_load(1)); // run the query as user 1
238

    
239
          $result = $query->execute();
240
          if (is_array($result) && isset($result[$entity_type]) && count($result[$entity_type]) == 1) {
241
            $entities = array_keys($result[$entity_type]);
242
            $gid = ldap_authorization_og1_entity_id_to_gid($entities[0]);
243
          }
244

    
245
        }
246
        if (!$og_group && $gid) {
247
          $og_group = og_load($gid);
248
        }
249

    
250

    
251
        if ($role_target == 'rid') {
252
          $role_name = ldap_authorization_og1_role_name_from_rid($role_target_value);
253
          $rid = $role_target_value;
254
        }
255
        elseif ($role_target == 'role-name') {
256
          $rid = ldap_authorization_og_rid_from_role_name($role_target_value);
257
          $role_name = $role_target_value;
258
        }
259

    
260
        $new_mapping['simplified'] = $og_group->label . ', '. $role_name;
261
        $new_mapping['normalized'] = ($gid && $rid) ? ldap_authorization_og_authorization_id($gid, $rid) : FALSE;
262

    
263
        $new_mappings[] = $new_mapping;
264
      }
265

    
266
    }
267
    return $new_mappings;
268
  }
269

    
270
/**
271
 * 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.
272
 * But, granting member role (2), revokes other roles such as admin in OG.  So for granting we want the order:
273
 * 3-1, 3-2, 3-3 such that 3-3 is retained.  For revoking, the order should not matter, but reverse sorting makes
274
 * intuitive sense.
275
 */
276

    
277
  public function sortConsumerIds($op, &$consumers) {
278
    if ($op == 'revoke') {
279
      krsort($consumers, SORT_STRING);
280
    }
281
    else {
282
      ksort($consumers, SORT_STRING);
283
    }
284
  }
285

    
286
  /**
287
   * @see LdapAuthorizationConsumerAbstract::populateConsumersFromConsumerIds
288
   */
289

    
290
  public function populateConsumersFromConsumerIds(&$consumers, $create_missing_consumers = FALSE) {
291

    
292
    // generate a query for all og groups of interest
293
    $gids = array();
294
    foreach ($consumers as $consumer_id => $consumer) {
295
      if (ldap_authorization_og_og_version() == 1) {
296
        list($gid, $rid) = $this->og1ConsumerIdParts($consumer_id);
297
        $gids[] = $gid;
298
      }
299
      else  {
300
        list($entity_type, $gid, $rid) = explode(':', $consumer_id);
301
        $gids[$entity_type][] = $gid;
302
      }
303

    
304
    }
305
    if (ldap_authorization_og_og_version() == 1) {
306
      $og_group_entities = og_load_multiple($gids);
307
    }
308
    else {
309
      foreach ($gids as $entity_type => $gid_x_entity) {
310
        $og_group_entities[$entity_type] = @entity_load($entity_type, $gid_x_entity);
311
      }
312
    }
313

    
314
    foreach ($consumers as $consumer_id => $consumer) {
315
      if (ldap_authorization_og_og_version() == 1) {
316
        list($gid, $rid) = $this->og1ConsumerIdParts($consumer_id);
317
        $consumer['exists'] = isset($og_group_entities[$gid]);
318
        if ($consumer['exists']) {
319
          $consumer['value'] = $og_group_entities[$gid];
320
          if (empty($consumer['name']) && property_exists($og_group_entities[$gid], 'title')) {
321
            $consumer['name'] = $og_group_entities[$gid]->title;
322
          }
323
          $consumer['name'] =  $consumer_id;
324
        }
325
        else {
326
          $consumer['value'] = NULL;
327
          $consumer['name'] = NULL;
328
        }
329

    
330
        $consumer['map_to_string'] = $consumer_id;
331
      }
332
      else  {
333
        list($entity_type, $gid, $rid) = explode(':', $consumer_id);
334
        $consumer['exists'] = isset($og_group_entities[$entity_type][$gid]);
335
        $consumer['value'] = ($consumer['exists']) ? $og_group_entities[$entity_type][$gid] : NULL;
336
        $consumer['map_to_string'] = $consumer_id;
337
        if (
338
          empty($consumer['name']) &&
339
          !empty($og_group_entities[$entity_type][$gid]) &&
340
          property_exists($og_group_entities[$entity_type][$gid], 'title')
341
        ) {
342
          $consumer['name'] = $og_group_entities[$entity_type][$gid]->title;
343
        }
344
      }
345

    
346
      if (!$consumer['exists'] && $create_missing_consumers) {
347
         // @todo if creation of og groups were implemented, function would be called here
348
         // this would mean mapping would need to have enough info to configure a group,
349
         // or settings would need to include a default group type to create (entity type,
350
         // bundle, etc.)
351
      }
352
      $consumers[$consumer_id] = $consumer;
353
    }
354
  }
355

    
356

    
357
  public function hasAuthorization(&$user, $consumer_id) {
358

    
359
    if ($this->ogVersion == 1) {
360
      $result = FALSE;
361
      list($gid, $rid) = $this->og1ConsumerIdParts($consumer_id);
362
      return ldap_authorization_og1_has_membership($gid, $user->uid) && ldap_authorization_og1_has_role($gid, $user->uid, $rid);
363
    }
364
    else {
365
      return ldap_authorization_og2_has_consumer_id($consumer_id, $user->uid);
366
    }
367
  }
368

    
369
  
370
  public function flushRelatedCaches($consumers = NULL, $user = NULL) {
371
    if ($user) {
372
      $this->usersAuthorizations($user, TRUE, FALSE); // clear user authorizations cache
373
    }
374
    
375
    if ($this->ogVersion == 1) {
376
      og_group_membership_invalidate_cache();
377
    }
378
    else {
379
      og_membership_invalidate_cache();
380
    }
381
    
382
    if ($consumers) {
383
      $gids_to_clear_cache = array();
384
      foreach ($consumers as $i => $consumer_id) {
385
        if ($this->ogVersion == 1) { // og 7.x-1.x
386
          list($gid, $rid) = $this->og1ConsumerIdParts($consumer_id);
387
        }
388
        else {
389
          list($entity_type, $gid, $rid) = $this->og2ConsumerIdParts($consumer_id);
390
        }
391
        $gids_to_clear_cache[$gid] = $gid;
392
      }
393
      og_invalidate_cache(array_keys($gids_to_clear_cache));
394
    }
395
    else {
396
      og_invalidate_cache();
397
    }
398
  }
399

    
400
 /**
401
   * @param string $op 'grant' or 'revoke' signifying what to do with the $consumer_ids
402
   * @param drupal user object $object
403
   * @param array $user_auth_data is array specific to this consumer_type.  Stored at $user->data['ldap_authorizations'][<consumer_type>]
404
   * @param $consumers as associative array in form of LdapAuthorizationConsumerAbstract::populateConsumersFromConsumerIds
405
   * @param array $ldap_entry, when available user's ldap entry.
406
   * @param boolean $user_save indicates is user data array should be saved or not.  this is always overridden for og
407
   */
408
  public function authorizationDiff($existing, $desired) {
409
    if ($this->ogVersion != 1) {
410
      return parent::authorizationDiff($existing, $desired);
411
    }
412

    
413
    /**
414
     * for og 1.5, goal is not to recognize X-2 consumer ids if X-N exist
415
     * since X-2 consumer ids are granted as a prerequisite of X-N
416
     */
417

    
418
    $diff = array_diff($existing, $desired);
419
    $desired_group_ids = array();
420
    foreach ($desired as $i => $consumer_id) {
421
      list($gid, $rid) = $this->og1ConsumerIdParts($consumer_id);
422
      $desired_group_ids[$gid] = TRUE;
423
    }
424
    foreach ($diff as $i => $consumer_id) {
425
      list($gid, $rid) = $this->og1ConsumerIdParts($consumer_id);
426
      // if there are still roles in this group that are desired, do
427
      // not remove default mambership role id
428
      if ($rid == $this->defaultMembershipRid && !empty($desired_group_ids[$gid])) {
429
        unset($diff[$i]);
430
      }
431
    }
432
   // dpm("diff"); dpm($diff); dpm("existing"); dpm($existing);  dpm("desired"); dpm($desired); dpm("final diff"); dpm($diff);
433
    return $diff;
434
  }
435

    
436
  protected function grantsAndRevokes($op, &$user, &$user_auth_data, $consumers, &$ldap_entry = NULL, $user_save = TRUE) {
437
   // debug("grantsAndRevokes, op=$op, user_save=$user_save"); debug($user_auth_data); debug($consumers);
438

    
439
    if (!is_array($user_auth_data)) {
440
      $user_auth_data = array();
441
    }
442

    
443
    $detailed_watchdog_log = variable_get('ldap_help_watchdog_detail', 0);
444
    $this->sortConsumerIds($op, $consumers);
445

    
446
    $results = array();
447
    $watchdog_tokens = array();
448
    $watchdog_tokens['%username'] = $user->name;
449
    $watchdog_tokens['%action'] = $op;
450
    $watchdog_tokens['%user_save'] = $user_save;
451

    
452
    /**
453
     * get authorizations that exist, regardless of origin or ldap_authorization $user->data
454
     * in form $users_authorization_consumer_ids = array('3-2', '3,3', '4-2')
455
     */
456
    $users_authorization_consumer_ids = $this->usersAuthorizations($user, TRUE);
457

    
458
    $watchdog_tokens['%users_authorization_ids'] = join(', ', $users_authorization_consumer_ids);
459
    if ($detailed_watchdog_log) {
460
      watchdog('ldap_authorization', "on call of grantsAndRevokes: user_auth_data=" . print_r($user_auth_data, TRUE), $watchdog_tokens, WATCHDOG_DEBUG);
461
    }
462

    
463
    /**
464
     * step #1:  generate $og_actions = array of form $og_actions['revokes'|'grants'][$gid] = $rid
465
     *  based on all consumer ids granted and revokes
466
     */
467
    $og_actions = array('grants' => array(), 'revokes' => array());
468
    $consumer_ids_log = "";
469
    $log = "";
470

    
471
    //dpm('consumers');dpm($consumers); dpm('users_authorization_consumer_ids'); dpm($users_authorization_consumer_ids);
472
    foreach ($consumers as $consumer_id => $consumer) {
473
      if ($detailed_watchdog_log) {
474
        watchdog('ldap_authorization', "consumer_id=$consumer_id, user_save=$user_save, op=$op", $watchdog_tokens, WATCHDOG_DEBUG);
475
      }
476
      $log = "consumer_id=$consumer_id, op=$op,";
477

    
478
      $user_has_authorization = in_array($consumer_id, $users_authorization_consumer_ids); // does user already have authorization ?
479
      $user_has_authorization_recorded = isset($user_auth_data[$consumer_id]);  // is authorization attribute to ldap_authorization_og in $user->data ?
480
      
481
      if ($this->ogVersion == 1) {
482
        list($gid, $rid) = $this->og1ConsumerIdParts($consumer_id);
483
        if ($rid == $this->anonymousRid) {
484
          continue;
485
        }
486
      }
487
      else {
488
        list($entity_type, $gid, $rid) = $this->og2ConsumerIdParts($consumer_id);
489
      }
490
      
491
      /** grants **/
492
      if ($op == 'grant') {
493
        if ($user_has_authorization && !$user_has_authorization_recorded) {
494
        // grant case 1: authorization id already exists for user, but is not ldap provisioned.  mark as ldap provisioned, but don't regrant
495
          $results[$consumer_id] = TRUE;
496
          $user_auth_data[$consumer_id] = array(
497
            'date_granted' => time(),
498
            'consumer_id_mixed_case' => $consumer_id,
499
          );
500
          $log .= "grant case 1: authorization id already exists for user, but is not ldap provisioned.  mark as ldap provisioned, but don't regrant";
501
          $log .= $consumer_id;
502
        }
503
        elseif (!$user_has_authorization && $consumer['exists']) {
504
        // grant case 2: consumer exists, but user is not member. grant authorization
505
          if ($this->ogVersion == 1) {
506
            $og_actions['grants'][$gid][] = $rid;
507
          }
508
          else {
509
            $og_actions['grants'][$entity_type][$gid][] = $rid;
510
          }
511
          $log .= "grant case 2: consumer exists, but user is not member. grant authorization";
512
          $log .= " ".$entity_type . ":" . $gid .":" . $rid;
513
        }
514
        elseif ($consumer['exists'] !== TRUE) {
515
        // grant case 3: something is wrong. consumers should have been created before calling grantsAndRevokes
516
          $results[$consumer_id] = FALSE;
517
          $log .= "grant case 3: something is wrong. consumers should have been created before calling grantsAndRevokes";
518
          $log .= " ".$consumer_id;        }
519
        elseif ($consumer['exists'] === TRUE) {
520
        // grant case 4: consumer exists and user has authorization recorded. do nothing
521
          $results[$consumer_id] = TRUE;
522
          $log .= "grant case 4: consumer exists and user has authorization recorded. do nothing";
523
          $log .= " ".$consumer_id;
524
        }
525
        else {
526
        // grant case 5: $consumer['exists'] has not been properly set before calling function
527
          $results[$consumer_id] = FALSE;
528
          watchdog('ldap_authorization', "grantsAndRevokes consumer[exists] not properly set. consumer_id=$consumer_id, op=$op, username=%username", $watchdog_tokens, WATCHDOG_ERROR);
529
            $log .= "grantsAndRevokes consumer[exists] not properly set. consumer_id=$consumer_id, op=$op, username=%username";
530
          }
531
          $consumer_ids_log .= $log;      }
532
      /** revokes **/
533
      elseif ($op == 'revoke') {
534
        if ($user_has_authorization) {
535
          // revoke case 1: user has authorization, revoke it.  revokeSingleAuthorization will remove $user_auth_data[$consumer_id]
536
          if ($this->ogVersion == 1) {
537
            $og_actions['revokes'][$gid][] = $rid;
538
          }
539
          else {
540
            $og_actions['revokes'][$entity_type][$gid][] = $rid;
541
          }
542
          $log .= "revoke case 1: user has authorization, revoke it.  revokeSingleAuthorization will remove $consumer_id";
543
          $log .=" ".$entity_type . ":" . $gid .":" . $rid ;          
544
        }
545
        elseif ($user_has_authorization_recorded)  {
546
          // revoke case 2: user does not have authorization, but has record of it. remove record of it.
547
          unset($user_auth_data[$consumer_id]);
548
          $results[$consumer_id] = TRUE;
549
          $log .= "revoke case 2: user does not have authorization, but has record of it. remove record of it.";
550
          $log .= $consumer_id;
551
        }
552
        else {
553
          // revoke case 3: trying to revoke something that isn't there
554
          $results[$consumer_id] = TRUE;
555
          $log .= "revoke case 3: trying to revoke something that isn't there";
556
          $log .= $consumer_id;
557
        }
558
      }
559
      if ($detailed_watchdog_log) {
560
        watchdog('ldap_authorization', "user_auth_data after consumer $consumer_id" . print_r($user_auth_data, TRUE), $watchdog_tokens, WATCHDOG_DEBUG);
561
      }
562
      $consumer_ids_log .= $log;
563
    }
564
    
565
    $watchdog_tokens['%consumer_ids_log'] = $consumer_ids_log;
566
    
567
    /**
568
     * Step #2: from array of form:
569
     *   og1.5: $og_actions['grants'|'revokes'][$gid][$rid]\
570
     *   og2:   $og_actions['grants'|'revokes'][$entity_type][$gid][$rid]
571
     * - generate $user->data['ldap_authorizations'][<consumer_id>]
572
     * - remove and grant og memberships
573
     * - remove and grant og roles
574
     * - flush appropriate caches
575
     */
576
    //debug("og_actions"); debug($og_actions); debug("user_auth_data"); debug($user_auth_data);
577
    if ($this->ogVersion == 1) {
578
      $this->og1Grants($og_actions, $user, $user_auth_data);
579
      $this->og1Revokes($og_actions, $user, $user_auth_data);
580
    }
581
    else {
582
      $this->og2Grants($og_actions, $user, $user_auth_data);
583
      $this->og2Revokes($og_actions, $user, $user_auth_data); 
584
    }
585

    
586
    $user_edit['data']['ldap_authorizations'][$this->consumerType] = $user_auth_data;
587
    $user = user_save($user, $user_edit);
588
    $user_auth_data = $user->data['ldap_authorizations'][$this->consumerType];  // reset this variable because user save hooks can impact it.
589

    
590
    $this->flushRelatedCaches($consumers, $user);
591

    
592
    if ($detailed_watchdog_log) {
593
      watchdog('ldap_authorization', '%username:
594
        <hr/>LdapAuthorizationConsumerAbstract grantsAndRevokes() method log.  action=%action:<br/> %consumer_ids_log
595
        ',
596
        $watchdog_tokens, WATCHDOG_DEBUG);
597
    }
598
  }
599

    
600
  public function og1Grants($og_actions, &$user, &$user_auth_data) {
601
    foreach ($og_actions['grants'] as $gid => $rids) {
602
      $existing_roles = og_get_user_roles($gid, $user->uid);
603
      if (!in_array($this->defaultMembershipRid, array_values($existing_roles))) {
604
        $user->{OG_AUDIENCE_FIELD}[LANGUAGE_NONE][] = array('gid' => $gid);
605
        og_entity_presave($user, 'user');
606
        $consumer_id = ldap_authorization_og_authorization_id($gid, $this->defaultMembershipRid);
607
        $user_auth_data[$consumer_id] = array(
608
          'date_granted' => time(),
609
          'consumer_id_mixed_case' => $consumer_id,
610
        );
611
      }
612
      foreach ($rids as $rid) {
613
        if ($rid != $this->defaultMembershipRid && $rid != $this->anonymousRid) {
614
          og_role_grant($gid, $user->uid, $rid);
615
          $consumer_id = ldap_authorization_og_authorization_id($gid, $rid);
616
          $user_auth_data[$consumer_id] = array(
617
            'date_granted' => time(),
618
            'consumer_id_mixed_case' => $consumer_id,
619
            );
620
        }
621
      }
622
    }
623
  }
624

    
625
  public function og2Grants($og_actions, &$user, &$user_auth_data) {
626
    foreach ($og_actions['grants'] as $group_entity_type => $gids) {
627
      foreach ($gids as $gid => $granting_rids) { // all rids ldap believes user should be granted and attributed to ldap
628
        $all_group_roles = og_roles($group_entity_type, FALSE, $gid, FALSE, TRUE); // all roles rid => role_name array w/ authen or anon roles
629
        $authenticated_rid = array_search(OG_AUTHENTICATED_ROLE, $all_group_roles);
630
        $anonymous_rid = array_search(OG_ANONYMOUS_ROLE, $all_group_roles);
631
        $all_group_rids = array_keys($all_group_roles); // all rids array w/ authen or anon rids
632
        $users_group_rids = array_keys(og_get_user_roles($group_entity_type, $gid, $user->uid, TRUE)); // users current rids w/authen or anon roles returned
633
        $users_group_rids = array_diff($users_group_rids, array($anonymous_rid));
634
        $new_rids = array_diff($granting_rids, $users_group_rids, array($anonymous_rid)); // rids to be added without anonymous rid
635
      //  debug("new rids"); debug($new_rids);debug("granting_rids"); debug($granting_rids);debug("users_group_rids"); debug($users_group_rids);
636
        
637
        // if adding OG_AUTHENTICATED_ROLE or any other role and does not currently have OG_AUTHENTICATED_ROLE, group
638
        if (!in_array($authenticated_rid, $users_group_rids) && count($new_rids) > 0) {
639
          $values = array(
640
            'entity_type' => 'user',
641
            'entity' => $user->uid,
642
            'field_name' => FALSE,
643
            'state' => OG_STATE_ACTIVE,
644
          );
645
          $og_membership = og_group($group_entity_type, $gid, $values);
646
          // debug("consumer_id=$consumer_id, og group called( $group_entity_type, $gid, values:"); debug($values); debug("response og_membership"); debug($og_membership);
647
          $consumer_id = join(':', array($group_entity_type, $gid, $authenticated_rid));
648
          $user_auth_data[$consumer_id] = array(
649
            'date_granted' => time(),
650
            'consumer_id_mixed_case' => $consumer_id,
651
          );
652
          $new_rids = array_diff($new_rids, array($authenticated_rid)); // granted on membership creation
653
         
654
        }
655
        foreach ($new_rids as $i => $rid) {
656
        //  debug("role grant $group_entity_type $gid $user->uid $rid");
657
          og_role_grant($group_entity_type, $gid, $user->uid, $rid);
658
        }
659
        foreach ($granting_rids as $i => $rid) {
660
          // attribute to ldap regardless of if is being granted.
661
          $consumer_id = join(':', array($group_entity_type, $gid, $rid));
662
          $user_auth_data[$consumer_id] = array(
663
            'date_granted' => time(),
664
            'consumer_id_mixed_case' => $consumer_id,
665
          );
666
        }
667
      }
668
    }
669
  }
670
  
671
  
672
  public function og1Revokes($og_actions, &$user, &$user_auth_data) {
673
    $group_audience_gids = empty($user->{OG_AUDIENCE_FIELD}[LANGUAGE_NONE]['gid']) ? array() : $user->{OG_AUDIENCE_FIELD}[LANGUAGE_NONE]['gid'];
674
    foreach ($og_actions['revokes'] as $gid => $rids) {
675
      $existing_roles = og_get_user_roles($gid, $user->uid);
676
      if (in_array($this->defaultMembershipRid, array_values($existing_roles))) {
677
        // ungroup and set audience
678
        foreach ($group_audience_gids as $i => $_audience_gid) {
679
           if ($_audience_gid == $gid) {
680
             unset($user->{OG_AUDIENCE_FIELD}[LANGUAGE_NONE][$i]);
681
           }
682
        }
683
        og_entity_presave($user, 'user');
684
        $user = og_ungroup($gid, 'user', $user, TRUE);
685
        foreach (array_values($existing_roles) as $rid) {
686
          $consumer_id = ldap_authorization_og_authorization_id($gid, $rid);
687
          if (isset($user_auth_data[$consumer_id])) {
688
            unset($user_auth_data[$consumer_id]);
689
          }
690
        }
691
      }
692
      else {
693
        foreach ($existing_roles as $rid) {
694
          if ($rid != $this->defaultMembershipRid && $this->defaultMembershipRid != 1) {
695
            og_role_revoke($gid, $user->uid, $rid);
696
            unset($user_auth_data[ldap_authorization_og_authorization_id($gid, $rid)]);
697
          }
698
        }
699
      }
700
    }
701
  }
702
  
703
  public function og2Revokes($og_actions, &$user, &$user_auth_data) {
704
    foreach ($og_actions['revokes'] as $group_entity_type => $gids) {
705
      foreach ($gids as $gid => $revoking_rids) { // $revoking_rids are all rids to be removed.  may include authen rids
706
        $all_group_roles = og_roles($group_entity_type, FALSE, $gid, FALSE, TRUE); // all roles rid => role_name array w/ authen or anon roles
707
        $all_group_rids = array_keys($all_group_roles); // all rids array w/ authen or anon rids
708
        $users_group_rids = array_keys(og_get_user_roles($group_entity_type, $gid, $user->uid, TRUE)); // users current rids w/authen or anon roles returned
709
        $remaining_rids = array_diff($users_group_rids, $revoking_rids); // rids to be left at end of revoke process
710
        $authenticated_rid = array_search(OG_AUTHENTICATED_ROLE, $all_group_roles);
711
        // remove autenticated and anon rids here
712
        foreach ($revoking_rids as $i => $rid) {
713
          // revoke if user has role
714
          if (in_array($rid, $users_group_rids)) {
715
            og_role_revoke($group_entity_type, $gid, $user->uid, $rid);
716
          }
717
          // unattribute to ldap even if user does not currently have role
718
          unset($user_auth_data[ldap_authorization_og_authorization_id($gid, $rid, $group_entity_type)]);
719
        }
720
        // define('OG_ANONYMOUS_ROLE', 'non-member'); define('OG_AUTHENTICATED_ROLE', 'member');
721
        if (in_array($authenticated_rid, $revoking_rids) || count($remaining_rids) == 0) {  // ungroup if only authenticated and anonymous role left
722
          $entity = og_ungroup($group_entity_type, $gid, 'user', $user->uid);
723
          $result = (boolean)($entity);
724
        }
725
      }
726
    }
727
  }
728

    
729
  /**
730
   * @see ldapAuthorizationConsumerAbstract::usersAuthorizations
731
   */
732

    
733
  public function usersAuthorizations(&$user, $reset = FALSE, $return_data = TRUE) {
734

    
735
    static $users;
736
    if (!is_array($users)) {
737
      $users = array(); // no cache exists, create static array
738
    }
739
    elseif ($reset && isset($users[$user->uid])) {
740
      unset($users[$user->uid]); // clear users cache
741
    }
742
    elseif (!$return_data) {
743
      return NULL; // simply clearing cache
744
    }
745
    elseif (!empty($users[$user->uid])) {
746
      return $users[$user->uid]; // return cached data
747
    }
748

    
749
    $authorizations = array();
750

    
751
    if ($this->ogVersion == 1) {
752
      $gids = og_get_groups_by_user($user);
753
      foreach ($gids as $i => $gid) {
754
        $roles = og_get_user_roles($gid, $user->uid);
755
        if (!empty($roles[$this->defaultMembershipRid])) { // if you aren't a member, doesn't matter what roles you have in og 1.5
756
          if (isset($roles[$this->anonymousRid])) {
757
            unset($roles[$this->anonymousRid]);
758
          } // ignore anonymous role
759
          $rids = array_values($roles);
760
          asort($rids, SORT_NUMERIC); // go low to high to get default memberships first
761
          foreach ($rids as $rid) {
762
            $authorizations[] = ldap_authorization_og_authorization_id($gid, $rid);
763
          }
764
        }
765
      }
766
    }
767
    else { // og 7.x-2.x
768
      $user_entities = entity_load('user', array($user->uid));
769
      $memberships = og_get_entity_groups('user', $user_entities[$user->uid]);
770
      foreach ($memberships as $entity_type => $entity_memberships) {
771
        foreach ($entity_memberships as $og_membership_id => $gid) {
772
          $roles = og_get_user_roles($entity_type, $gid, $user->uid);
773
          foreach ($roles as $rid => $discard) {
774
            $authorizations[] =  ldap_authorization_og_authorization_id($gid, $rid, $entity_type);
775
          }
776
        }
777
      }
778
    }
779
    $users[$user->uid] = $authorizations;
780
    
781
    return $authorizations;
782
  }
783

    
784
  /**
785
   * @see ldapAuthorizationConsumerAbstract::convertToFriendlyAuthorizationIds
786
   */
787
  public function convertToFriendlyAuthorizationIds($authorizations) {
788
    $authorization_ids_friendly = array();
789
    foreach ($authorizations as $authorization_id => $authorization) {
790
      $authorization_ids_friendly[] = $authorization['name'] . '  (' . $authorization_id . ')';
791
    }
792
    return $authorization_ids_friendly;
793
  }
794

    
795
  /**
796
   * @see ldapAuthorizationConsumerAbstract::validateAuthorizationMappingTarget
797
   */
798
  public function validateAuthorizationMappingTarget($mapping, $form_values = NULL, $clear_cache = FALSE) {
799
    // these mappings have already been through the normalizeMappings() method, so no real querying needed here.
800

    
801
    $has_form_values = is_array($form_values);
802
    $message_type = NULL;
803
    $message_text = NULL;
804
    $pass = !empty($mapping['valid']) && $mapping['valid'] === TRUE;
805

    
806
    /**
807
     * @todo need to look this over
808
     *
809
     */
810
    if (!$pass) {
811
      $tokens = array(
812
        '!from' => $mapping['from'],
813
        '!user_entered' => $mapping['user_entered'],
814
        '!error' => $mapping['error_message'],
815
        );
816
      $message_text = '<code>"' . t('!map_to|!user_entered', $tokens) . '"</code> ' . t('has the following error: !error.', $tokens);
817
    }
818
    return array($message_type, $message_text);
819
  }
820

    
821
  /**
822
   * Get list of mappings based on existing Organic Groups and roles
823
   *
824
   * @param associative array $tokens of tokens and replacement values
825
   * @return html examples of mapping values
826
   */
827

    
828
  public function mappingExamples($tokens) {
829

    
830
    if ($this->ogVersion == 1) {
831
      $groups = og_get_all_group();
832
      $ogEntities = og_load_multiple($groups);
833
      $OGroles = og_roles(0);
834

    
835
      $rows = array();
836
      foreach ($ogEntities as $group) {
837
        foreach ($OGroles as $rid => $role) {
838
          $example =   "<code>ou=IT,dc=myorg,dc=mytld,dc=edu|gid=" . $group->gid . ',rid=' . $rid . '</code><br/>' .
839
            '<code>ou=IT,dc=myorg,dc=mytld,dc=edu|group-name=' . $group->label . ',role-name=' . $role . '</code>';
840
          $rows[] = array(
841
            $group->label,
842
            $group->gid,
843
            $role,
844
            $example,
845
          );
846
        }
847
      }
848

    
849
      $variables = array(
850
      'header' => array('Group Name', 'OG Group ID', 'OG Membership Type', 'example'),
851
      'rows' => $rows,
852
      'attributes' => array(),
853
      );
854
    }
855
    else {
856

    
857
      /**
858
       * OG 7.x-2.x mappings:
859
       * $entity_type = $group_type,
860
       * $bundle = $group_bundle
861
       * $etid = $gid where edid is nid, uid, etc.
862
       *
863
       * og group is: entity_type (eg node) x entity_id ($gid) eg. node:17
864
       * group identifier = group_type:gid; aka entity_type:etid e.g. node:17
865
       *
866
       * membership identifier is:  group_type:gid:entity_type:etid
867
       * in our case: group_type:gid:user:uid aka entity_type:etid:user:uid e.g. node:17:user:2
868
       *
869
       * roles are simply rids ((1,2,3) and names (non-member, member, and administrator member) in og_role table
870
       * og_users_roles is simply uid x rid x gid
871
       *
872
       * .. so authorization mappings should look like:
873
       *    <ldap group>|group_type:gid:rid such as staff|node:17:2
874
       */
875

    
876
      $og_fields = field_info_field(OG_GROUP_FIELD);
877
      $rows = array();
878
      $role_name = OG_AUTHENTICATED_ROLE;
879

    
880
      if (!empty($og_fields['bundles'])) {
881
        foreach ($og_fields['bundles'] as $entity_type => $bundles) {
882

    
883
          foreach ($bundles as $i => $bundle) {
884

    
885
            $query = new EntityFieldQuery();
886
            $query->entityCondition('entity_type', $entity_type)
887
              ->entityCondition('bundle', $bundle)
888
              ->range(0, 5)
889
              ->addMetaData('account', user_load(1)); // run the query as user 1
890
            $result = $query->execute();
891
            $entities = entity_load($entity_type, array_keys($result[$entity_type]));
892
            $i=0;
893
            foreach ($entities as $entity_id => $entity) {
894
              $i++;
895
              $rid = ldap_authorization_og2_rid_from_role_name($entity_type, $bundle, $entity_id, OG_AUTHENTICATED_ROLE);
896
              $title = (is_object($entity) && property_exists($entity, 'title')) ? $entity->title : '';
897
              $middle = ($title && $i < 3) ? $title : $entity_id;
898
              $group_role_identifier = ldap_authorization_og_authorization_id($middle, $rid, $entity_type);
899
              $example = "<code>ou=IT,dc=myorg,dc=mytld,dc=edu|$group_role_identifier</code>";
900
              $rows[] = array("$entity_type $title - $role_name", $example);
901

    
902
            }
903

    
904
          }
905
        }
906
      }
907

    
908
      $variables = array(
909
        'header' => array('Group Entity - Group Title - OG Membership Type', 'example'),
910
        'rows' => $rows,
911
        'attributes' => array(),
912
      );
913
    }
914

    
915
    $table = theme('table', $variables);
916
    $link = l(t('admin/config/people/ldap/authorization/test/og_group'), 'admin/config/people/ldap/authorization/test/og_group');
917

    
918
$examples =
919
<<<EOT
920

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

926
$table
927

928
EOT;
929
    $examples = t($examples, $tokens);
930
    return $examples;
931
  }
932

    
933
}