Projet

Général

Profil

Paste
Télécharger (17 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / ldap / ldap_authorization / LdapAuthorizationConsumerConfAdmin.class.php @ 59ae487e

1
<?php
2

    
3
/**
4
 * @file
5
 * class to encapsulate an ldap authorization ldap entry to authorization ids mapping
6
 *
7
 */
8

    
9
module_load_include('php', 'ldap_authorization', 'LdapAuthorizationConsumerConf.class');
10
  /**
11
   * LDAP Authorization Consumer Configration Admin Class
12
   */
13
class LdapAuthorizationConsumerConfAdmin extends LdapAuthorizationConsumerConf {
14

    
15

    
16
  public function save() {
17

    
18
    $op = $this->inDatabase ? 'edit' : 'insert';
19
    $values = new stdClass; // $this;
20
    $values->sid = $this->sid;
21
    $values->numeric_consumer_conf_id = $this->numericConsumerConfId;
22
    $values->consumer_type = $this->consumerType;
23
    $values->consumer_module = $this->consumer->consumerModule;
24
    $values->status = ($this->status) ? 1 : 0;
25
    $values->only_ldap_authenticated = (int)$this->onlyApplyToLdapAuthenticated;
26
    $values->use_first_attr_as_groupid = (int)$this->useFirstAttrAsGroupId;
27
    $values->mappings = serialize($this->mappings);
28
    $values->use_filter = (int)$this->useMappingsAsFilter;
29
    $values->synch_to_ldap = (int)$this->synchToLdap;
30
    $values->synch_on_logon = (int)$this->synchOnLogon;
31
    $values->revoke_ldap_provisioned = (int)$this->revokeLdapProvisioned;
32
    $values->create_consumers = (int)$this->createConsumers;
33
    $values->regrant_ldap_provisioned = (int)$this->regrantLdapProvisioned;
34

    
35
    if (module_exists('ctools')) {
36
      ctools_include('export');
37
      // Populate our object with ctool's properties
38
      $object = ctools_export_crud_new('ldap_authorization');
39
      foreach ($object as $property => $value) {
40
        if (!isset($values->$property)) {
41
          $values->$property = $value;
42
        }
43
      }
44
      try {
45
        $values->export_type = NULL;
46
        $result = ctools_export_crud_save('ldap_authorization', $values);
47
      } catch (Exception $e) {
48
        $values->export_type = EXPORT_IN_DATABASE;
49
        $result = ctools_export_crud_save('ldap_authorization', $values);
50
      }
51
      ctools_export_load_object_reset('ldap_authorization'); // ctools_export_crud_save doesn't invalidate cache
52
    }
53
    else {
54

    
55
      if ($op == 'edit') {
56
        $result = drupal_write_record('ldap_authorization', $values, 'consumer_type');
57
      }
58
      else { // insert
59
        $result = drupal_write_record('ldap_authorization', $values);
60
      }
61

    
62
      if ($result) {
63
        $this->inDatabase = TRUE;
64
      }
65
      else {
66
        drupal_set_message(t('Failed to write LDAP Authorization to the database.'));
67
      }
68
    }
69

    
70
  }
71

    
72
  public $fields;
73
  public $consumers;
74

    
75
  public function delete() {
76
    if ($this->consumerType) {
77
      $this->inDatabase = FALSE;
78
      return db_delete('ldap_authorization')->condition('consumer_type', $this->consumerType)->execute();
79
    }
80
    else {
81
      return FALSE;
82
    }
83
  }
84

    
85
  public function __construct(&$consumer = NULL, $new = FALSE) {
86
    parent::__construct($consumer, $new);
87
    $this->fields = $this->fields();
88
    $this->consumers = ldap_authorization_get_consumers(NULL, TRUE);
89

    
90
    if ($new) {
91
      foreach ($this->consumer->defaultConsumerConfProperties as $property => $value) {
92
        $this->$property = $value;
93
      }
94
    }
95
  }
96

    
97
  public function drupalForm($server_options, $op) {
98

    
99
    $consumer_tokens = ldap_authorization_tokens($this->consumer);
100
    $form['intro'] = array(
101
        '#type' => 'item',
102
        '#markup' => t('<h1>LDAP to !consumer_name Configuration</h1>', $consumer_tokens),
103
    );
104

    
105
    $form['status'] = array(
106
      '#type' => 'fieldset',
107
      '#title' => t('I.  Basics', $consumer_tokens),
108
      '#collapsible' => TRUE,
109
      '#collapsed' => FALSE,
110
    );
111

    
112
    $form['status']['sid'] = array(
113
      '#type' => 'radios',
114
      '#title' => t('LDAP Server used in !consumer_name configuration.', $consumer_tokens),
115
      '#required' => 1,
116
      '#default_value' => $this->sid,
117
      '#options' => $server_options,
118
    );
119

    
120
    $form['status']['consumer_type'] = array(
121
      '#type' => 'hidden',
122
      '#value' => $this->consumerType,
123
      '#required' => 1,
124
    );
125

    
126
    $form['status']['status'] = array(
127
      '#type' => 'checkbox',
128
      '#title' => t('Enable this configuration', $consumer_tokens),
129
      '#default_value' =>  $this->status,
130
    );
131

    
132
    $form['status']['only_ldap_authenticated'] = array(
133
      '#type' => 'checkbox',
134
      '#title' => t('Only apply the following LDAP to !consumer_name configuration to users authenticated via LDAP.  One uncommon reason for disabling this is when you are using Drupal authentication, but want to leverage LDAP for authorization; for this to work the Drupal username still has to map to an LDAP entry.', $consumer_tokens),
135
      '#default_value' =>  $this->onlyApplyToLdapAuthenticated,
136
    );
137

    
138

    
139
    if (method_exists($this->consumer, 'mappingExamples')) {
140
      $consumer_tokens['!examples'] = '<fieldset class="collapsible collapsed form-wrapper" id="authorization-mappings">
141
<legend><span class="fieldset-legend">' . t('Examples based on current !consumer_namePlural', $consumer_tokens) . '</span></legend>
142
<div class="fieldset-wrapper">'. $this->consumer->mappingExamples($consumer_tokens) . '<div class="fieldset-wrapper">
143
</fieldset>';
144
    }
145
    else {
146
      $consumer_tokens['!examples'] = '';
147
    }
148
    $form['filter_and_mappings'] = array(
149
      '#type' => 'fieldset',
150
      '#title' => t('II. LDAP to !consumer_name mapping and filtering', $consumer_tokens),
151
      '#description' => t('
152
Representations of groups derived from LDAP might initially look like:
153
<ul>
154
<li><code>cn=students,ou=groups,dc=hogwarts,dc=edu</code></li>
155
<li><code>cn=gryffindor,ou=groups,dc=hogwarts,dc=edu</code></li>
156
<li><code>cn=faculty,ou=groups,dc=hogwarts,dc=edu</code></li>
157
<li><code>cn=probation students,ou=groups,dc=hogwarts,dc=edu</code></li>
158
</ul>
159

160
<p><strong>Mappings are used to convert and filter these group representations to !consumer_namePlural.</strong></p>
161

162
!consumer_mappingDirections
163

164
!examples
165

166
', $consumer_tokens),
167
      '#collapsible' => TRUE,
168
      '#collapsed' => !($this->mappings || $this->useMappingsAsFilter || $this->useFirstAttrAsGroupId),
169
    );
170

    
171
    $form['filter_and_mappings']['use_first_attr_as_groupid'] = array(
172
      '#type' => 'checkbox',
173
      '#title' => t('Convert full dn to value of first attribute before mapping.  e.g.  <code>cn=students,ou=groups,dc=hogwarts,dc=edu</code> would be converted to <code>students</code>', $consumer_tokens),
174
      '#default_value' => $this->useFirstAttrAsGroupId,
175
    );
176
    $form['filter_and_mappings']['mappings'] = array(
177
      '#type' => 'textarea',
178
      '#title' => t('Mapping of LDAP to !consumer_name (one per line)', $consumer_tokens),
179
      '#default_value' => $this->mappingsToPipeList($this->mappings),
180
      '#cols' => 50,
181
      '#rows' => 5,
182
    );
183
    $form['filter_and_mappings']['use_filter'] = array(
184
      '#type' => 'checkbox',
185
      '#title' => t('Only grant !consumer_namePlural that match a filter above.', $consumer_tokens),
186
      '#default_value' => $this->useMappingsAsFilter,
187
      '#description' => t('If enabled, only above mapped !consumer_namePlural will be assigned (e.g. students and administrator).
188
        <strong>If not checked, !consumer_namePlural not mapped above also may be created and granted (e.g. gryffindor and probation students).  In some LDAPs this can lead to hundreds of !consumer_namePlural being created if "Create !consumer_namePlural if they do not exist" is enabled below.
189
        </strong>', $consumer_tokens)
190
    );
191

    
192

    
193
    $form['more'] = array(
194
      '#type' => 'fieldset',
195
      '#title' => t('Part III.  Even More Settings.'),
196
      '#collapsible' => TRUE,
197
      '#collapsed' => FALSE,
198
    );
199

    
200
    $synchronization_modes = array();
201
    if ($this->synchOnLogon)  {
202
      $synchronization_modes[] = 'user_logon';
203
    }
204
    $form['more']['synchronization_modes'] = array(
205
      '#type' => 'checkboxes',
206
      '#title' => t('When should !consumer_namePlural be granted/revoked from user?', $consumer_tokens),
207
      '#options' => array(
208
          'user_logon' => t('When a user logs on.'),
209
      ),
210
      '#default_value' => $synchronization_modes,
211
      '#description' => '',
212
    );
213

    
214
    $synchronization_actions = array();
215
    if ($this->revokeLdapProvisioned)  {
216
      $synchronization_actions[] = 'revoke_ldap_provisioned';
217
    }
218
    if ($this->createConsumers)  {
219
      $synchronization_actions[] = 'create_consumers';
220
    }
221
    if ($this->regrantLdapProvisioned)  {
222
      $synchronization_actions[] = 'regrant_ldap_provisioned';
223
    }
224

    
225
    $options =  array(
226
      'revoke_ldap_provisioned' => t('Revoke !consumer_namePlural previously granted by LDAP Authorization but no longer valid.', $consumer_tokens),
227
      'regrant_ldap_provisioned' => t('Re grant !consumer_namePlural previously granted by LDAP Authorization but removed manually.', $consumer_tokens),
228
    );
229
    if ($this->consumer->allowConsumerObjectCreation) {
230
      $options['create_consumers'] = t('Create !consumer_namePlural if they do not exist.', $consumer_tokens);
231
    }
232

    
233
    $form['more']['synchronization_actions'] = array(
234
      '#type' => 'checkboxes',
235
      '#title' => t('What actions would you like performed when !consumer_namePlural are granted/revoked from user?', $consumer_tokens),
236
      '#options' => $options,
237
      '#default_value' => $synchronization_actions,
238
    );
239
    /**
240
     * @todo  some general options for an individual mapping (perhaps in an advance tab).
241
     *
242
     * - on synchronization allow: revoking authorizations made by this module, authorizations made outside of this module
243
     * - on synchronization create authorization contexts not in existance when needed (drupal roles etc)
244
     * - synchronize actual authorizations (not cached) when granting authorizations
245
     */
246

    
247
    switch ($op) {
248
      case 'add':
249
      $action = 'Add';
250
      break;
251

    
252
      case 'edit':
253
      $action = 'Save';
254
      break;
255

    
256
      case 'delete':
257
      $action = 'Delete';
258
      break;
259
    }
260

    
261
    $form['submit'] = array(
262
      '#type' => 'submit',
263
      '#value' => $action,
264
    );
265

    
266
  return $form;
267
  }
268

    
269

    
270
  protected function loadFromForm($values, $op) {
271

    
272
  }
273

    
274
  public function getLdapAuthorizationConsumerActions() {
275
    $actions = array();
276
    $actions[] =  l(t('edit'), LDAP_SERVERS_MENU_BASE_PATH . '/authorization/edit/' . $this->consumerType);
277
    if (property_exists($this, 'type')) {
278
      if ($this->type == 'Overridden') {
279
          $actions[] = l(t('revert'), LDAP_SERVERS_MENU_BASE_PATH . '/authorization/delete/' . $this->consumerType);
280
      }
281
      if ($this->type == 'Normal') {
282
          $actions[] = l(t('delete'), LDAP_SERVERS_MENU_BASE_PATH . '/authorization/delete/' . $this->consumerType);
283
      }
284
    }
285
    else {
286
        $actions[] = l(t('delete'), LDAP_SERVERS_MENU_BASE_PATH . '/authorization/delete/' . $this->consumerType);
287
    }
288
    $actions[] = l(t('test'), LDAP_SERVERS_MENU_BASE_PATH . '/authorization/test/' . $this->consumerType);
289
    return $actions;
290
  }
291

    
292
  public function drupalFormValidate($op, $values)  {
293
    $errors = array();
294

    
295
    if ($op == 'delete') {
296
      if (!$this->consumerType) {
297
        $errors['consumer_type_missing'] = 'Consumer type is missing from delete form.';
298
      }
299
    }
300
    else {
301

    
302
      $this->populateFromDrupalForm($op, $values);
303
      $errors = $this->validate($values);
304
      if (count($this->mappings) == 0 && trim($values['mappings'])) {
305
        $errors['mappings'] = t('Bad mapping syntax.  Text entered but not able to convert to array.');
306
      }
307

    
308
    }
309
    return $errors;
310
  }
311

    
312
  public function validate($form_values = array()) {
313
    $errors = array();
314

    
315
    if (!$this->consumerType) {
316
      $errors['consumer_type'] = t('Consumer type is missing.');
317
    }
318

    
319
    if ($this->inDatabase  && (!$this->consumerType)) {
320
      $errors['consumer_type'] = t('Edit or delete called without consumer type in form.');
321
    }
322

    
323
    if (count($this->mappings) > 0) {
324
      foreach ($this->mappings as $mapping_item) {
325
        list($type, $text) = $this->consumer->validateAuthorizationMappingTarget($mapping_item, $form_values);
326
        if ($type == 'error') {
327
          $errors['mappings'] = $text;
328
        }
329
        elseif ($type == 'warning' ||  $type == 'status') {
330
          drupal_set_message(check_plain($text), $type);
331
        }
332
      }
333
    }
334
    if ($this->useMappingsAsFilter && !count($this->mappings)) {
335
      $errors['mappings'] = t('Mappings are missing.  Mappings must be supplied if filtering is enabled.');
336
    }
337
    return $errors;
338
  }
339

    
340
  protected function populateFromDrupalForm($op, $values) {
341

    
342
    $this->inDatabase = (drupal_strtolower($op) == 'edit' || drupal_strtolower($op) == 'save');
343
    $this->consumerType = $values['consumer_type'];
344

    
345
    $this->sid = $values['sid'];
346

    
347
    $this->status = (bool)$values['status'];
348
    $this->onlyApplyToLdapAuthenticated  = (bool)(@$values['only_ldap_authenticated']);
349
    $this->useFirstAttrAsGroupId  = (bool)($values['use_first_attr_as_groupid']);
350

    
351
    $this->mappings = $this->consumer->normalizeMappings($this->pipeListToArray($values['mappings'], FALSE));
352
    $this->useMappingsAsFilter  = (bool)(@$values['use_filter']);
353

    
354
    $this->synchOnLogon = (bool)(@$values['synchronization_modes']['user_logon']);
355
    $this->regrantLdapProvisioned = (bool)(@$values['synchronization_actions']['regrant_ldap_provisioned']);
356
    $this->revokeLdapProvisioned = (bool)(@$values['synchronization_actions']['revoke_ldap_provisioned']);
357
    $this->createConsumers = (bool)(@$values['synchronization_actions']['create_consumers']);
358

    
359
  }
360

    
361
  public function drupalFormSubmit($op, $values) {
362

    
363
    $this->populateFromDrupalForm($op, $values);
364
    if ($op == 'delete') {
365
      $this->delete();
366
    }
367
    else { // add or edit
368

    
369
      try {
370
        $save_result = $this->save();
371
      }
372
      catch (Exception $e) {
373
        $this->errorName = 'Save Error';
374
        $this->errorMsg = t('Failed to save object.  Your form data was not saved.');
375
        $this->hasError = TRUE;
376
      }
377
    }
378
  }
379

    
380

    
381
  public static function fields() {
382

    
383
     /**
384
     * consumer_type is tag (unique alphanumeric id) of consuming authorization such as
385
     *   drupal_roles, og_groups, civicrm_memberships
386
     */
387
    $fields = array(
388
      'numeric_consumer_conf_id' => array(
389
          'schema' => array(
390
            'type' => 'serial',
391
            'unsigned' => TRUE,
392
            'not null' => TRUE,
393
            'description' => 'Primary ID field for the table.  Only used internally.',
394
            'no export' => TRUE,
395
          ),
396
        ),
397
      'sid' => array(
398
        'schema' => array(
399
          'type' => 'varchar',
400
          'length' => 20,
401
          'not null' => TRUE,
402
        )
403
      ),
404
      'consumer_type' => array(
405
         'schema' => array(
406
            'type' => 'varchar',
407
            'length' => 20,
408
            'not null' => TRUE,
409
        )
410
      ),
411
     'consumer_module' => array(
412
         'schema' => array(
413
            'type' => 'varchar',
414
            'length' => 30,
415
            'not null' => TRUE,
416
        )
417
      ),
418

    
419
      'status' => array(
420
          'schema' => array(
421
            'type' => 'int',
422
            'size' => 'tiny',
423
            'not null' => TRUE,
424
            'default' => 0,
425
          )
426
      ),
427
      'only_ldap_authenticated' => array(
428
        'schema' => array(
429
          'type' => 'int',
430
          'size' => 'tiny',
431
          'not null' => TRUE,
432
          'default' => 1,
433
        )
434
      ),
435

    
436
      'use_first_attr_as_groupid' => array(
437
        'schema' => array(
438
          'type' => 'int',
439
          'size' => 'tiny',
440
          'not null' => TRUE,
441
          'default' => 0,
442
        )
443
      ),
444

    
445
      'mappings'  => array(
446
        'form_default' => array(),
447
        'schema' => array(
448
          'type' => 'text',
449
          'size' => 'medium',
450
          'not null' => FALSE,
451
          'default' => NULL,
452
        )
453
      ),
454

    
455
      'use_filter' => array(
456
        'schema' => array(
457
          'type' => 'int',
458
          'size' => 'tiny',
459
          'not null' => TRUE,
460
          'default' => 1,
461
        )
462
      ),
463

    
464
      'synchronization_modes' => array(
465
        'form_default' =>  array('user_logon'),
466
      ),
467

    
468
      'synchronization_actions' => array(
469
        'form_default' =>  array('revoke_ldap_provisioned', 'create_consumers'),
470
      ),
471

    
472
      'synch_to_ldap'  => array(
473
        'schema' => array(
474
          'type' => 'int',
475
          'size' => 'tiny',
476
          'not null' => TRUE,
477
          'default' => 0,
478
        ),
479
      ),
480

    
481
      'synch_on_logon'  => array(
482
        'schema' => array(
483
          'type' => 'int',
484
          'size' => 'tiny',
485
          'not null' => TRUE,
486
          'default' => 0,
487
        ),
488
      ),
489

    
490
      'revoke_ldap_provisioned'  => array(
491
        'schema' => array(
492
          'type' => 'int',
493
          'size' => 'tiny',
494
          'not null' => TRUE,
495
          'default' => 0,
496
        ),
497
      ),
498

    
499
     'create_consumers'  => array(
500
        'schema' => array(
501
          'type' => 'int',
502
          'size' => 'tiny',
503
          'not null' => TRUE,
504
          'default' => 0,
505
        ),
506
      ),
507

    
508
     'regrant_ldap_provisioned'  => array(
509
        'schema' => array(
510
          'type' => 'int',
511
          'size' => 'tiny',
512
          'not null' => TRUE,
513
          'default' => 0,
514
        ),
515
      ),
516
    );
517
    return $fields;
518
  }
519

    
520

    
521
  protected function mappingsToPipeList($mappings) {
522
    $result_text = "";
523
    foreach ($mappings as $map) {
524
      $result_text .= $map['from'] . '|' . $map['user_entered'] . "\n";
525
    }
526
    return $result_text;
527
  }
528

    
529

    
530
}