Projet

Général

Profil

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

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

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 = array('data' => $user->data);
587
    $user_edit['data']['ldap_authorizations'][$this->consumerType] = $user_auth_data;
588
    $user = user_save($user, $user_edit);
589
    $user_auth_data = $user->data['ldap_authorizations'][$this->consumerType];  // reset this variable because user save hooks can impact it.
590

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

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

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

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

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

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

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

    
750
    $authorizations = array();
751

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

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

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

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

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

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

    
829
  public function mappingExamples($tokens) {
830

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

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

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

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

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

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

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

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

    
903
            }
904

    
905
          }
906
        }
907
      }
908

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

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

    
919
$examples =
920
<<<EOT
921

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

927
$table
928

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

    
934
}