Projet

Général

Profil

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

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

1
<?php
2

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

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

    
14
  /**
15
   *
16
   */
17
  public function save() {
18

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

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

    
58
      if ($op == 'edit') {
59
        $result = drupal_write_record('ldap_authorization', $values, 'consumer_type');
60
      }
61
      /**
62
 *Insert.
63
 */
64
      else {
65
        $result = drupal_write_record('ldap_authorization', $values);
66
      }
67

    
68
      if ($result) {
69
        $this->inDatabase = TRUE;
70
      }
71
      else {
72
        drupal_set_message(t('Failed to write LDAP Authorization to the database.'));
73
      }
74
    }
75

    
76
  }
77

    
78
  public $fields;
79
  public $consumers;
80

    
81
  /**
82
   *
83
   */
84
  public function delete() {
85
    if ($this->consumerType) {
86
      $this->inDatabase = FALSE;
87
      return db_delete('ldap_authorization')->condition('consumer_type', $this->consumerType)->execute();
88
    }
89
    else {
90
      return FALSE;
91
    }
92
  }
93

    
94
  /**
95
   *
96
   */
97
  public function __construct(&$consumer = NULL, $new = FALSE) {
98
    parent::__construct($consumer, $new);
99
    $this->fields = $this->fields();
100
    $this->consumers = ldap_authorization_get_consumers(NULL, TRUE);
101

    
102
    if ($new) {
103
      foreach ($this->consumer->defaultConsumerConfProperties as $property => $value) {
104
        $this->$property = $value;
105
      }
106
    }
107
  }
108

    
109
  /**
110
   *
111
   */
112
  public function drupalForm($server_options, $op) {
113

    
114
    $consumer_tokens = ldap_authorization_tokens($this->consumer);
115
    $form['intro'] = [
116
      '#type' => 'item',
117
      '#markup' => t('<h1>LDAP to !consumer_name Configuration</h1>', $consumer_tokens),
118
    ];
119

    
120
    $form['status'] = [
121
      '#type' => 'fieldset',
122
      '#title' => t('I.  Basics', $consumer_tokens),
123
      '#collapsible' => TRUE,
124
      '#collapsed' => FALSE,
125
    ];
126

    
127
    $form['status']['sid'] = [
128
      '#type' => 'radios',
129
      '#title' => t('LDAP Server used in !consumer_name configuration.', $consumer_tokens),
130
      '#required' => 1,
131
      '#default_value' => $this->sid,
132
      '#options' => $server_options,
133
    ];
134

    
135
    $form['status']['consumer_type'] = [
136
      '#type' => 'hidden',
137
      '#value' => $this->consumerType,
138
      '#required' => 1,
139
    ];
140

    
141
    $form['status']['status'] = [
142
      '#type' => 'checkbox',
143
      '#title' => t('Enable this configuration', $consumer_tokens),
144
      '#default_value' => $this->status,
145
    ];
146

    
147
    $form['status']['only_ldap_authenticated'] = [
148
      '#type' => 'checkbox',
149
      '#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),
150
      '#default_value' => $this->onlyApplyToLdapAuthenticated,
151
    ];
152

    
153
    if (method_exists($this->consumer, 'mappingExamples')) {
154
      $consumer_tokens['!examples'] = '<fieldset class="collapsible collapsed form-wrapper" id="authorization-mappings">
155
<legend><span class="fieldset-legend">' . t('Examples based on current !consumer_namePlural', $consumer_tokens) . '</span></legend>
156
<div class="fieldset-wrapper">' . $this->consumer->mappingExamples($consumer_tokens) . '<div class="fieldset-wrapper">
157
</fieldset>';
158
    }
159
    else {
160
      $consumer_tokens['!examples'] = '';
161
    }
162
    $form['filter_and_mappings'] = [
163
      '#type' => 'fieldset',
164
      '#title' => t('II. LDAP to !consumer_name mapping and filtering', $consumer_tokens),
165
      '#description' => t('
166
Representations of groups derived from LDAP might initially look like:
167
<ul>
168
<li><code>cn=students,ou=groups,dc=hogwarts,dc=edu</code></li>
169
<li><code>cn=gryffindor,ou=groups,dc=hogwarts,dc=edu</code></li>
170
<li><code>cn=faculty,ou=groups,dc=hogwarts,dc=edu</code></li>
171
<li><code>cn=probation students,ou=groups,dc=hogwarts,dc=edu</code></li>
172
</ul>
173

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

176
!consumer_mappingDirections
177

178
!examples
179

180
', $consumer_tokens),
181
      '#collapsible' => TRUE,
182
      '#collapsed' => !($this->mappings || $this->useMappingsAsFilter || $this->useFirstAttrAsGroupId),
183
    ];
184

    
185
    $form['filter_and_mappings']['use_first_attr_as_groupid'] = [
186
      '#type' => 'checkbox',
187
      '#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),
188
      '#default_value' => $this->useFirstAttrAsGroupId,
189
    ];
190
    $form['filter_and_mappings']['mappings'] = [
191
      '#type' => 'textarea',
192
      '#title' => t('Mapping of LDAP to !consumer_name (one per line)', $consumer_tokens),
193
      '#default_value' => $this->mappingsToPipeList($this->mappings),
194
      '#cols' => 50,
195
      '#rows' => 5,
196
    ];
197
    $form['filter_and_mappings']['use_filter'] = [
198
      '#type' => 'checkbox',
199
      '#title' => t('Only grant !consumer_namePlural that match a filter above.', $consumer_tokens),
200
      '#default_value' => $this->useMappingsAsFilter,
201
      '#description' => t('If enabled, only above mapped !consumer_namePlural will be assigned (e.g. students and administrator).
202
        <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.
203
        </strong>', $consumer_tokens),
204
    ];
205

    
206
    $form['more'] = [
207
      '#type' => 'fieldset',
208
      '#title' => t('Part III.  Even More Settings.'),
209
      '#collapsible' => TRUE,
210
      '#collapsed' => FALSE,
211
    ];
212

    
213
    $synchronization_modes = [];
214
    if ($this->synchOnLogon) {
215
      $synchronization_modes[] = 'user_logon';
216
    }
217
    $form['more']['synchronization_modes'] = [
218
      '#type' => 'checkboxes',
219
      '#title' => t('When should !consumer_namePlural be granted/revoked from user?', $consumer_tokens),
220
      '#options' => [
221
        'user_logon' => t('When a user logs on.'),
222
      ],
223
      '#default_value' => $synchronization_modes,
224
      '#description' => '',
225
    ];
226

    
227
    $synchronization_actions = [];
228
    if ($this->revokeLdapProvisioned) {
229
      $synchronization_actions[] = 'revoke_ldap_provisioned';
230
    }
231
    if ($this->createConsumers) {
232
      $synchronization_actions[] = 'create_consumers';
233
    }
234
    if ($this->regrantLdapProvisioned) {
235
      $synchronization_actions[] = 'regrant_ldap_provisioned';
236
    }
237

    
238
    $options = [
239
      'revoke_ldap_provisioned' => t('Revoke !consumer_namePlural previously granted by LDAP Authorization but no longer valid.', $consumer_tokens),
240
      'regrant_ldap_provisioned' => t('Re grant !consumer_namePlural previously granted by LDAP Authorization but removed manually.', $consumer_tokens),
241
    ];
242
    if ($this->consumer->allowConsumerObjectCreation) {
243
      $options['create_consumers'] = t('Create !consumer_namePlural if they do not exist.', $consumer_tokens);
244
    }
245

    
246
    $form['more']['synchronization_actions'] = [
247
      '#type' => 'checkboxes',
248
      '#title' => t('What actions would you like performed when !consumer_namePlural are granted/revoked from user?', $consumer_tokens),
249
      '#options' => $options,
250
      '#default_value' => $synchronization_actions,
251
    ];
252
    /**
253
     * @todo  some general options for an individual mapping (perhaps in an advance tab).
254
     *
255
     * - on synchronization allow: revoking authorizations made by this module, authorizations made outside of this module
256
     * - on synchronization create authorization contexts not in existance when needed (drupal roles etc)
257
     * - synchronize actual authorizations (not cached) when granting authorizations
258
     */
259

    
260
    switch ($op) {
261
      case 'add':
262
        $action = 'Add';
263
        break;
264

    
265
      case 'edit':
266
        $action = 'Save';
267
        break;
268

    
269
      case 'delete':
270
        $action = 'Delete';
271
        break;
272
    }
273

    
274
    $form['submit'] = [
275
      '#type' => 'submit',
276
      '#value' => $action,
277
    ];
278

    
279
    return $form;
280
  }
281

    
282
  /**
283
   *
284
   */
285
  protected function loadFromForm($values, $op) {
286

    
287
  }
288

    
289
  /**
290
   *
291
   */
292
  public function getLdapAuthorizationConsumerActions() {
293
    $actions = [];
294
    $actions[] = l(t('edit'), LDAP_SERVERS_MENU_BASE_PATH . '/authorization/edit/' . $this->consumerType);
295
    if (property_exists($this, 'type')) {
296
      if ($this->type == 'Overridden') {
297
        $actions[] = l(t('revert'), LDAP_SERVERS_MENU_BASE_PATH . '/authorization/delete/' . $this->consumerType);
298
      }
299
      if ($this->type == 'Normal') {
300
        $actions[] = l(t('delete'), LDAP_SERVERS_MENU_BASE_PATH . '/authorization/delete/' . $this->consumerType);
301
      }
302
    }
303
    else {
304
      $actions[] = l(t('delete'), LDAP_SERVERS_MENU_BASE_PATH . '/authorization/delete/' . $this->consumerType);
305
    }
306
    $actions[] = l(t('test'), LDAP_SERVERS_MENU_BASE_PATH . '/authorization/test/' . $this->consumerType);
307
    return $actions;
308
  }
309

    
310
  /**
311
   *
312
   */
313
  public function drupalFormValidate($op, $values) {
314
    $errors = [];
315

    
316
    if ($op == 'delete') {
317
      if (!$this->consumerType) {
318
        $errors['consumer_type_missing'] = 'Consumer type is missing from delete form.';
319
      }
320
    }
321
    else {
322

    
323
      $this->populateFromDrupalForm($op, $values);
324
      $errors = $this->validate($values);
325
      if (count($this->mappings) == 0 && trim($values['mappings'])) {
326
        $errors['mappings'] = t('Bad mapping syntax.  Text entered but not able to convert to array.');
327
      }
328

    
329
    }
330
    return $errors;
331
  }
332

    
333
  /**
334
   *
335
   */
336
  public function validate($form_values = []) {
337
    $errors = [];
338

    
339
    if (!$this->consumerType) {
340
      $errors['consumer_type'] = t('Consumer type is missing.');
341
    }
342

    
343
    if ($this->inDatabase  && (!$this->consumerType)) {
344
      $errors['consumer_type'] = t('Edit or delete called without consumer type in form.');
345
    }
346

    
347
    if (count($this->mappings) > 0) {
348
      foreach ($this->mappings as $mapping_item) {
349
        list($type, $text) = $this->consumer->validateAuthorizationMappingTarget($mapping_item, $form_values);
350
        if ($type == 'error') {
351
          $errors['mappings'] = $text;
352
        }
353
        elseif ($type == 'warning' ||  $type == 'status') {
354
          drupal_set_message(check_plain($text), $type);
355
        }
356
      }
357
    }
358
    if ($this->useMappingsAsFilter && !count($this->mappings)) {
359
      $errors['mappings'] = t('Mappings are missing.  Mappings must be supplied if filtering is enabled.');
360
    }
361
    return $errors;
362
  }
363

    
364
  /**
365
   *
366
   */
367
  protected function populateFromDrupalForm($op, $values) {
368

    
369
    $this->inDatabase = (drupal_strtolower($op) == 'edit' || drupal_strtolower($op) == 'save');
370
    $this->consumerType = $values['consumer_type'];
371

    
372
    $this->sid = $values['sid'];
373

    
374
    $this->status = (bool) $values['status'];
375
    $this->onlyApplyToLdapAuthenticated = (bool) (@$values['only_ldap_authenticated']);
376
    $this->useFirstAttrAsGroupId = (bool) ($values['use_first_attr_as_groupid']);
377

    
378
    $this->mappings = $this->consumer->normalizeMappings($this->pipeListToArray($values['mappings'], FALSE));
379
    $this->useMappingsAsFilter = (bool) (@$values['use_filter']);
380

    
381
    $this->synchOnLogon = (bool) (@$values['synchronization_modes']['user_logon']);
382
    $this->regrantLdapProvisioned = (bool) (@$values['synchronization_actions']['regrant_ldap_provisioned']);
383
    $this->revokeLdapProvisioned = (bool) (@$values['synchronization_actions']['revoke_ldap_provisioned']);
384
    $this->createConsumers = (bool) (@$values['synchronization_actions']['create_consumers']);
385

    
386
  }
387

    
388
  /**
389
   *
390
   */
391
  public function drupalFormSubmit($op, $values) {
392

    
393
    $this->populateFromDrupalForm($op, $values);
394
    if ($op == 'delete') {
395
      $this->delete();
396
    }
397
    // Add or edit.
398
    else {
399

    
400
      try {
401
        $save_result = $this->save();
402
      }
403
      catch (Exception $e) {
404
        $this->errorName = 'Save Error';
405
        $this->errorMsg = t('Failed to save object.  Your form data was not saved.');
406
        $this->hasError = TRUE;
407
      }
408
    }
409
  }
410

    
411
  /**
412
   *
413
   */
414
  public static function fields() {
415

    
416
    /**
417
     * consumer_type is tag (unique alphanumeric id) of consuming authorization such as
418
     *   drupal_roles, og_groups, civicrm_memberships
419
     */
420
    $fields = [
421
      'numeric_consumer_conf_id' => [
422
        'schema' => [
423
          'type' => 'serial',
424
          'unsigned' => TRUE,
425
          'not null' => TRUE,
426
          'description' => 'Primary ID field for the table.  Only used internally.',
427
          'no export' => TRUE,
428
        ],
429
      ],
430
      'sid' => [
431
        'schema' => [
432
          'type' => 'varchar',
433
          'length' => 20,
434
          'not null' => TRUE,
435
        ],
436
      ],
437
      'consumer_type' => [
438
        'schema' => [
439
          'type' => 'varchar',
440
          'length' => 20,
441
          'not null' => TRUE,
442
        ],
443
      ],
444
      'consumer_module' => [
445
        'schema' => [
446
          'type' => 'varchar',
447
          'length' => 30,
448
          'not null' => TRUE,
449
        ],
450
      ],
451

    
452
      'status' => [
453
        'schema' => [
454
          'type' => 'int',
455
          'size' => 'tiny',
456
          'not null' => TRUE,
457
          'default' => 0,
458
        ],
459
      ],
460
      'only_ldap_authenticated' => [
461
        'schema' => [
462
          'type' => 'int',
463
          'size' => 'tiny',
464
          'not null' => TRUE,
465
          'default' => 1,
466
        ],
467
      ],
468

    
469
      'use_first_attr_as_groupid' => [
470
        'schema' => [
471
          'type' => 'int',
472
          'size' => 'tiny',
473
          'not null' => TRUE,
474
          'default' => 0,
475
        ],
476
      ],
477

    
478
      'mappings'  => [
479
        'form_default' => [],
480
        'schema' => [
481
          'type' => 'text',
482
          'size' => 'medium',
483
          'not null' => FALSE,
484
          'default' => NULL,
485
        ],
486
      ],
487

    
488
      'use_filter' => [
489
        'schema' => [
490
          'type' => 'int',
491
          'size' => 'tiny',
492
          'not null' => TRUE,
493
          'default' => 1,
494
        ],
495
      ],
496

    
497
      'synchronization_modes' => [
498
        'form_default' => ['user_logon'],
499
      ],
500

    
501
      'synchronization_actions' => [
502
        'form_default' => ['revoke_ldap_provisioned', 'create_consumers'],
503
      ],
504

    
505
      'synch_to_ldap'  => [
506
        'schema' => [
507
          'type' => 'int',
508
          'size' => 'tiny',
509
          'not null' => TRUE,
510
          'default' => 0,
511
        ],
512
      ],
513

    
514
      'synch_on_logon'  => [
515
        'schema' => [
516
          'type' => 'int',
517
          'size' => 'tiny',
518
          'not null' => TRUE,
519
          'default' => 0,
520
        ],
521
      ],
522

    
523
      'revoke_ldap_provisioned'  => [
524
        'schema' => [
525
          'type' => 'int',
526
          'size' => 'tiny',
527
          'not null' => TRUE,
528
          'default' => 0,
529
        ],
530
      ],
531

    
532
      'create_consumers'  => [
533
        'schema' => [
534
          'type' => 'int',
535
          'size' => 'tiny',
536
          'not null' => TRUE,
537
          'default' => 0,
538
        ],
539
      ],
540

    
541
      'regrant_ldap_provisioned'  => [
542
        'schema' => [
543
          'type' => 'int',
544
          'size' => 'tiny',
545
          'not null' => TRUE,
546
          'default' => 0,
547
        ],
548
      ],
549
    ];
550
    return $fields;
551
  }
552

    
553
  /**
554
   *
555
   */
556
  protected function mappingsToPipeList($mappings) {
557
    $result_text = "";
558
    foreach ($mappings as $map) {
559
      $result_text .= $map['from'] . '|' . $map['user_entered'] . "\n";
560
    }
561
    return $result_text;
562
  }
563

    
564
}