class_posixAccount.inc 32.5 KB
Newer Older
1
2
3
<?php
/*
  This code is part of FusionDirectory (http://www.fusiondirectory.org/)
4

5
  Copyright (C) 2003  Cajus Pollmeier
6
  Copyright (C) 2011-2019  FusionDirectory
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/

/*!
  \brief   posixAccount plugin
  \author  Cajus Pollmeier <pollmeier@gonicus.de>
  \version 2.00
  \date    24.07.2003

  This class provides the functionality to read and write all attributes
  relevant for posixAccounts and shadowAccounts from/to the LDAP. It
  does syntax checking and displays the formulars required.
 */

class posixAccount extends simplePlugin
{
36
  protected $displayHeader        = TRUE;
37

38
39
40
  protected $locks                = [];
  protected $fromTemplate         = FALSE;
  protected $savedGroupMembership = [];
41

42
  static function plInfo (): array
43
  {
44
    return [
45
46
      'plShortName'   => _('Unix'),
      'plDescription' => _('Edit users POSIX settings'),
47
      'plFilter'      => '(objectClass=posixAccount)',
48
49
50
51
      'plIcon'        => 'geticon.php?context=applications&icon=os-linux&size=48',
      'plSmallIcon'   => 'geticon.php?context=applications&icon=os-linux&size=16',
      'plSelfModify'  => TRUE,
      'plPriority'    => 2,
52
      'plObjectClass' => ['posixAccount', 'shadowAccount'],
53
54
      /* shadowAccount is not required */
      'plFilter'      => '(objectClass=posixAccount)',
55
56
57
58
59
60
61
62
63
64
65
66
      'plObjectType'  => ['user'],
      'plForeignKeys' => [
        'gidNumber' => [
          ['posixGroup','gidNumber'],
          ['mixedGroup','gidNumber'],
        ],
        'host'      => [
          ['serverGeneric', 'cn'],
          ['workstationGeneric', 'cn'],
          ['terminalGeneric', 'cn'],
        ]
      ],
67
68

      'plProvidedAcls'  => parent::generatePlProvidedAcls(static::getAttributesInfo())
69
    ];
70
71
72
  }

  // The main function : information about attributes
73
  static function getAttributesInfo (): array
74
75
  {
    global $config;
76
77
    return [
      'main' => [
78
79
        'name'  => _('Unix'),
        'icon'  => 'geticon.php?context=applications&icon=os-linux&size=16',
80
        'attrs' => [
81
82
83
84
85
86
87
88
          new PathAttribute(
            _('Home directory'), _('The path to the home directory of this user'),
            'homeDirectory', TRUE
          ),
          new StringAttribute('gecos', 'gecos', 'gecos'),
          new SelectAttribute(
            _('Shell'), _('Which shell should be used when this user log in'),
            'loginShell', TRUE,
89
            $config->get_cfg_value('Shells', [_('unconfigured')]),
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
            $config->get_cfg_value('DefaultShell', '')
          ),
          new SelectAttribute(
            _('Primary group'), _('Primary group for this user'),
            'primaryGroup', FALSE
          ),
          new DisplayAttribute(
            _('Status'), _('Status of this user unix account'),
            'posixStatus', FALSE
          ),
          new BooleanAttribute(
            _('Force user/group id'), _('Force user id and group id values for this user'),
            'force_ids', FALSE
          ),
          new IntAttribute(
            _('User id'), _('User id value for this user'),
            'uidNumber', FALSE,
107
            $config->get_cfg_value('minId', 0), FALSE, ''
108
109
110
111
          ),
          new IntAttribute(
            _('Group id'), _('Group id value for this user'),
            'gidNumber', FALSE,
112
            $config->get_cfg_value('minId', 0), FALSE, ''
113
          )
114
115
116
        ]
      ],
      'groups' => [
117
118
        'name'  => _('Group membership'),
        'icon'  => 'geticon.php?context=types&icon=user-group&size=16',
119
        'attrs' => [
120
121
122
123
124
          new ObjectsAttribute(
            '', _('Group membership'),
            'groupMembership', FALSE,
            ['group']
          ),
125
126
127
        ]
      ],
      'account' => [
128
129
        'name'  => _('Account'),
        'icon'  => 'geticon.php?context=devices&icon=terminal&size=16',
130
        'attrs' => [
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
          new BooleanAttribute(
            _('User must change password on first login'), _('User must change password on first login (needs a value for Delay before forcing password change)'),
            'mustchangepassword', FALSE
          ),
          new IntAttribute(
            _('Minimum delay between password changes (days)'), _('The user won\'t be able to change his password before this number of days (leave empty to disable)'),
            'shadowMin', FALSE,
            0, FALSE, ''
          ),
          new IntAttribute(
            _('Delay before forcing password change (days)'), _('The user will be forced to change his password after this number of days (leave empty to disable)'),
            'shadowMax', FALSE,
            0, FALSE, ''
          ),
          new EpochDaysDateAttribute(
            _('Password expiration date'), _('Date after which this user password will expire (leave empty to disable)'),
            'shadowExpire', FALSE,
            ''
          ),
          new IntAttribute(
            _('Delay of inactivity before disabling user (days)'), _('Maximum delay of inactivity after password expiration before the user is disabled (leave empty to disable)'),
            'shadowInactive', FALSE,
            0, FALSE, ''
          ),
          new IntAttribute(
            _('Delay for user warning before password expiry (days)'), _('The user will be warned this number of days before his password expiration (leave empty to disable)'),
            'shadowWarning', FALSE,
            0, FALSE, ''
          ),
          new IntAttribute(
            'No label', 'No description',
            'shadowLastChange', FALSE,
            0, FALSE, ''
          ),
165
166
167
        ]
      ],
      'system_trust' => [
168
169
        'name'  => _('System trust'),
        'icon'  => 'geticon.php?context=categories&icon=acl&size=16',
170
        'attrs' => [
171
172
173
          new SelectAttribute(
            _('Trust mode'), _('Type of authorization for those hosts'),
            'trustMode', FALSE,
174
            ['', 'fullaccess', 'byhost'],
175
            '',
176
            [_('disabled'), _('full access'), _('allow access to these hosts')]
177
178
179
180
181
          ),
          new SystemsAttribute(
            '', _('Only allow this user to connect to this list of hosts'),
            'host', FALSE
          )
182
183
184
        ]
      ]
    ];
185
186
187
188
189
190
191
192
193
194
195
196
  }

  function __construct ($dn = NULL, $object = NULL, $parent = NULL, $mainTab = FALSE)
  {
    global $config;
    parent::__construct($dn, $object, $parent, $mainTab);

    $this->attributesAccess['gecos']->setVisible(FALSE);

    $this->attributesAccess['trustMode']->setInLdap(FALSE);
    if (!class_available('systemManagement')) {
      $this->attributesAccess['trustMode']->setChoices(
197
198
            ['', 'fullaccess'],
            [_('disabled'), _('full access')]
199
200
201
      );
    }
    $this->attributesAccess['trustMode']->setManagedAttributes(
202
203
204
205
206
207
      [
        'multiplevalues' => ['notbyhost' => ['','fullaccess']],
        'erase' => [
          'notbyhost' => ['host']
        ]
      ]
208
209
210
211
212
213
214
    );
    if ((count($this->host) == 1) && ($this->host[0] == '*')) {
      $this->trustMode = 'fullaccess';
    } elseif (count($this->host) > 0) {
      $this->trustMode = 'byhost';
    }

215
    $this->attributesAccess['uidNumber']->setUnique('whole');
216
217
    $this->attributesAccess['force_ids']->setInLdap(FALSE);
    $this->attributesAccess['force_ids']->setManagedAttributes(
218
219
220
      [
        'disable' => [
          FALSE => [
221
222
            'uidNumber',
            'gidNumber',
223
224
225
          ]
        ]
      ]
226
227
228
229
230
231
    );
    $this->attributesAccess['primaryGroup']->setInLdap(FALSE);

    $this->attributesAccess['mustchangepassword']->setInLdap(FALSE);
    $this->attributesAccess['shadowLastChange']->setVisible(FALSE);
    $this->attributesAccess['shadowMax']->setManagedAttributes(
232
233
234
      [
        'disable' => [
          '' => [
235
            'mustchangepassword',
236
237
238
          ]
        ]
      ]
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    );

    if ($dn !== NULL) {
      /* Fill group */
      $this->primaryGroup = $this->gidNumber;
    }

    /* Generate shell list from config */
    $loginShellList = $this->attributesAccess['loginShell']->getChoices();

    /* Insert possibly missing loginShell */
    $loginShell = $this->attributesAccess['loginShell']->getValue();
    if (($loginShell != '') && !in_array($loginShell, $loginShellList)) {
      $loginShellList[] = $loginShell;
    }
    $this->attributesAccess['loginShell']->setChoices($loginShellList);

256
    $secondaryGroups = [];
Côme Chilliet's avatar
Côme Chilliet committed
257
    $secondaryGroups[''] = '- '._('automatic').' -';
258
259
    $ldap = $config->get_ldap_link();
    $ldap->cd($config->current['BASE']);
260
    $ldap->search('(objectClass=posixGroup)', ['cn', 'gidNumber']);
261
262
263
    while ($attrs = $ldap->fetch()) {
      $secondaryGroups[$attrs['gidNumber'][0]] = $attrs['cn'][0];
    }
Côme Chilliet's avatar
Côme Chilliet committed
264
    asort($secondaryGroups);
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    $this->attributesAccess['primaryGroup']->setChoices(array_keys($secondaryGroups), array_values($secondaryGroups));

    $this->attributesAccess['groupMembership']->setInLdap(FALSE);
    if (class_available('mixedGroup')) {
      $this->attributesAccess['groupMembership']->setDisabled(TRUE);
      $this->attributesAccess['groupMembership']->setVisible(FALSE);
    } else {
      if ($this->is_template) {
        if (isset($this->attrs['posixGroups'])) {
          unset($this->attrs['posixGroups']['count']);
          $this->groupMembership = $this->attrs['posixGroups'];
        }
      } else {
        /* Groups handling */
        $ldap->cd($config->current['BASE']);
280
281
        $ldap->search('(&(objectClass=posixGroup)(memberUid='.ldap_escape_f($this->getUid()).'))', ['cn', 'description']);
        $groupMembership = [];
282
        while ($attrs = $ldap->fetch()) {
Côme Chilliet's avatar
Côme Chilliet committed
283
284
285
          $entry = $attrs['cn'][0];
          if (isset($attrs['description'][0])) {
            $entry .= ' ['.$attrs['description'][0].']';
286
287
288
289
290
291
292
293
294
295
296
          }
          $groupMembership[$attrs['dn']] = $entry;
        }
        asort($groupMembership);
        reset($groupMembership);
        $this->attributesAccess['groupMembership']->setValue(array_keys($groupMembership));
        $this->attributesAccess['groupMembership']->setDisplayValues(array_values($groupMembership));
        $this->savedGroupMembership = array_keys($groupMembership);
      }
    }
    if ($this->is_template) {
Côme Chilliet's avatar
Côme Chilliet committed
297
      /* Template specific handling */
298
299
300
      if (isset($this->attrs['force_ids'])) {
        $this->force_ids = ($this->attrs['force_ids'][0] != 'FALSE');
      }
301
302
303
304
      if (!$this->force_ids) {
        $this->uidNumber = '';
        $this->gidNumber = '';
      }
305
306
307
      if (isset($this->attrs['mustchangepassword'])) {
        $this->mustchangepassword = ($this->attrs['mustchangepassword'][0] != 'FALSE');
      }
Côme Chilliet's avatar
Côme Chilliet committed
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
    } else {
      /* Status is not computed for templates */
      $current = floor(date('U') / EpochDaysDateAttribute::$secondsPerDay);

      $shadowExpire     = $this->attributesAccess['shadowExpire']->getEpochDays();
      $shadowInactive   = $this->attributesAccess['shadowInactive']->getValue();
      $shadowMin        = $this->attributesAccess['shadowMin']->getValue();
      $shadowMax        = $this->attributesAccess['shadowMax']->getValue();
      $shadowLastChange = $this->attributesAccess['shadowLastChange']->getValue();
      if (($current >= $shadowExpire) && ($shadowExpire > 0)) {
        $status = _('expired');
        if ($shadowInactive != '' && ($current - $shadowExpire) < $shadowInactive) {
          $status .= ', '._('grace time active');
        }
      } elseif ($shadowMax != '' && ($shadowLastChange + $shadowMax) <= $current) {
        $status = _('active').', '._('password expired');
      } elseif ($shadowMin != '' && ($shadowLastChange + $shadowMin) <= $current) {
        $status = _('active').', '._('password not changeable');
      } else {
        $status = _('active');
      }
      $this->attributesAccess['posixStatus']->setValue($status);
330
331
332
    }
  }

333
  function getUid ()
334
335
336
337
338
339
340
341
342
343
  {
    if (isset($this->parent)) {
      $baseobject = $this->parent->getBaseObject();
      return $baseobject->uid;
    }
    if (isset($this->attrs['uid'][0])) {
      return $this->attrs['uid'][0];
    }
  }

344
  function resetCopyInfos ()
345
346
347
348
  {
    global $config;
    parent::resetCopyInfos();

349
    $this->savedGroupMembership = [];
350
351
352

    $ldap = $config->get_ldap_link();
    $ldap->cd($config->current['BASE']);
353
    $ldap->search('(&(objectClass=posixGroup)(gidNumber='.ldap_escape_f($this->gidNumber).')(cn='.ldap_escape_f($this->getUid()).'))', ['cn','gidNumber']);
354
355
356
357
358
359
360
361
362
363
364
365
366

    if ($ldap->count() > 0) {
      /* The copied user had its own group: switch back to automatic */
      $this->primaryGroup = 0;
    }

    $this->force_ids = FALSE;
    $this->attributesAccess['uidNumber']->setInitialValue('');
    $this->attributesAccess['gidNumber']->setInitialValue('');
    $this->uidNumber = '';
    $this->gidNumber = '';
  }

367
  function check (): array
368
369
370
  {
    global $config;

371
    $message = parent::check();
372
373

    /* Check shadow settings */
Côme Chilliet's avatar
Côme Chilliet committed
374
375
376
    if ($this->shadowWarning !== '') {
      if ($this->shadowMax === '') {
        $message[] = msgPool::depends('shadowWarning', 'shadowMax');
377
378
      }
      if ($this->shadowWarning > $this->shadowMax) {
Côme Chilliet's avatar
Côme Chilliet committed
379
        $message[] = msgPool::toobig('shadowWarning', 'shadowMax');
380
      }
Côme Chilliet's avatar
Côme Chilliet committed
381
382
      if (($this->shadowMin !== '') && ($this->shadowWarning < $this->shadowMin)) {
        $message[] = msgPool::toosmall('shadowWarning', 'shadowMin');
383
384
385
      }
    }

Côme Chilliet's avatar
Côme Chilliet committed
386
387
    if (($this->shadowInactive !== '') && ($this->shadowMax === '')) {
      $message[] = msgPool::depends('shadowInactive', 'shadowMax');
388
    }
Côme Chilliet's avatar
Côme Chilliet committed
389
    if (($this->shadowMin !== '') && ($this->shadowMax !== '') &&
390
        ($this->shadowMin > $this->shadowMax)) {
Côme Chilliet's avatar
Côme Chilliet committed
391
      $message[] = msgPool::toobig('shadowMin', 'shadowMax');
392
393
394
395
396
    }

    return $message;
  }

397
  protected function prepare_save (): array
398
399
  {
    global $config;
400

401
402
403
404
    /* Fill gecos */
    if (isset($this->parent) && $this->parent !== NULL) {
      $this->gecos = rewrite($this->parent->getBaseObject()->cn);
      if (!preg_match('/^[a-z0-9 -]+$/i', $this->gecos)) {
Côme Chilliet's avatar
Côme Chilliet committed
405
        $this->gecos = '';
406
407
408
409
410
411
412
413
      }
    }

    if (!$this->force_ids) {
      /* Handle uidNumber.
       * - use existing number if possible
       * - if not, try to create a new uniqe one.
       * */
414
415
      if ($this->is_template) {
        $this->uidNumber = '';
416
      } else {
417
418
419
        if ($this->attributesAccess['uidNumber']->getInitialValue() != '') {
          $this->uidNumber = $this->attributesAccess['uidNumber']->getInitialValue();
        } else {
420
          $this->uidNumber = static::getNextIdLock('uidNumber', $this->dn);
421
422
          $this->locks[] = 'uidNumber';
        }
423
424
425
426
427
428
429
430
431
432
433
434
      }
    }

    /* Handle gidNumber
     * - If we do not have a primary group selected (automatic), we will check if there
     *    is already a group  with the same name and use this as primary.
     * - .. if we couldn't find a group with the same name, we will create a new one,
     *    using the users uid as cn and a generated uniqe gidNumber.
     * */
    if ($this->is_template && $this->force_ids) {
      /* Nothing to do in this case */
    } elseif ($this->is_template && ($this->primaryGroup == 0)) {
435
      $this->gidNumber = '';
436
437
438
439
440
441
442
    } elseif (($this->primaryGroup == 0) || $this->force_ids) {
      /* Search for existing group */
      $ldap = $config->get_ldap_link();
      $ldap->cd($config->current['BASE']);

      /* Are we forced to use a special gidNumber? */
      if ($this->force_ids) {
443
        $ldap->search('(&(objectClass=posixGroup)(gidNumber='.ldap_escape_f($this->gidNumber).'))',      ['cn','gidNumber']);
444
      } else {
445
        $ldap->search('(&(objectClass=posixGroup)(gidNumber=*)(cn='.ldap_escape_f($this->getUid()).'))', ['cn','gidNumber']);
446
447
448
449
450
451
452
453
      }

      /* No primary group found, create a new one */
      if ($ldap->count() == 0) {
        $groupcn  = $this->getUid();

        /* Request a new and unique gidNumber, if required */
        if (!$this->force_ids) {
454
          $this->gidNumber = static::getNextIdLock('gidNumber', $this->dn);
455
456
457
458
459
460
          $this->locks[] = 'gidNumber';
        }

        /* If forced gidNumber could not be found, then check if the given group name already exists.
         */
        $cnt = 0;
461
        $ldap->search('(&(objectClass=posixGroup)(cn='.ldap_escape_f($groupcn).'))', ['cn']);
462
463
464
        while ($ldap->count() && ($cnt < 100)) {
          $cnt++;
          $groupcn = $this->getUid().'_'.$cnt;
465
          $ldap->search('(&(objectClass=posixGroup)(cn='.ldap_escape_f($groupcn).'))', ['cn']);
466
467
468
469
470
471
472
473
        }

        /* Create new primary group and enforce the new gidNumber */
        if (class_available('mixedGroup')) {
          $tabObject = objects::create('ogroup');
        } else {
          $tabObject  = objects::create('group');
        }
474
475
476
477
        if ($this->fromTemplate) {
          /* When creating a user through a template we bypass ACLs */
          $tabObject->setIgnoreAcls(TRUE);
        }
478
479
480
481
482

        $baseObject = $tabObject->getBaseObject();

        $baseObject->cn           = $groupcn;
        $baseObject->description  = sprintf(_('Group of user %s'), $this->getUid());
483
        $baseObject->base         = $this->parent->getBaseObject()->base;
484
485
        if (class_available('mixedGroup')) {
          // fake attrs as this user may not exists yet
486
487
          $attrs = [
            'objectClass' => ['inetOrgPerson','organizationalPerson','person','posixAccount','shadowAccount'],
488
489
            'cn' => $this->getUid(),
            'uid' => $this->getUid(),
490
          ];
491
          $baseObject->attributesAccess['member']->addValue($this->dn, $attrs);
492
          $tabObject->loadTabs();
493
494
495
496
497
498
499
          $posixTab = $tabObject->by_object['mixedGroup'];
        } else {
          $posixTab = $baseObject;
        }
        $posixTab->force_id   = 1;
        $posixTab->gidNumber  = $this->gidNumber;

500
501
        $errors = $tabObject->save();
        if (!empty($errors)) {
502
503
504
505
506
          array_unshift(
            $errors,
            sprintf(_('Could not create automatic primary group (using gidNumber "%s"), because of the following errors'), $this->gidNumber)
          );
          return $errors;
507
        } else {
508
          @DEBUG(DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
509
510
            sprintf('Primary group "%s" created, using gidNumber "%s".', $tabObject->dn, $this->gidNumber), '');
        }
511
512
513
      } else {
        $attrs = $ldap->fetch();
        $this->gidNumber = $attrs['gidNumber'][0];
514
        @DEBUG(DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
Côme Chilliet's avatar
Côme Chilliet committed
515
516
          'Found and used: <i>'.$attrs['dn'].'</i>',
          sprintf('Primary group "%s" exists, gidNumber is "%s".', $this->getUid(), $this->gidNumber));
517
518
519
520
      }
    } else {
      /* Primary group was selected by user */
      $this->gidNumber = $this->primaryGroup;
521
      @DEBUG(DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
Côme Chilliet's avatar
Côme Chilliet committed
522
523
        sprintf('Primary group "%s" for user "%s" manually selected.',
        $this->gidNumber, $this->getUid()), '');
524
525
526
527
528
529
530
531
532
533
534
535
536
537
    }

    if (!$this->is_template) {
      if ($this->mustchangepassword) {
        $this->shadowLastChange =
          floor(date('U') / EpochDaysDateAttribute::$secondsPerDay) - $this->shadowMax - 1;
      } elseif (
          ($this->is_account && !$this->initially_was_account) ||
          $this->parent->getBaseObject()->attributesAccess['userPassword']->hasChanged()
        ) {
        $this->shadowLastChange = floor(date('U') / EpochDaysDateAttribute::$secondsPerDay);
      }
    }

538
539
540
541
    $errors = parent::prepare_save();
    if (!empty($errors)) {
      return $errors;
    }
542
543

    if ($this->trustMode == 'fullaccess') {
544
      $this->attrs['host'] = ['*'];
545
546
547
    }

    /* Trust accounts */
Côme Chilliet's avatar
Côme Chilliet committed
548
    if (($this->trustMode != '') && !in_array('hostObject', $this->attrs['objectClass'])) {
549
      $this->attrs['objectClass'][] = 'hostObject';
Côme Chilliet's avatar
Côme Chilliet committed
550
    } elseif (($this->trustMode == '') && (($key = array_search('hostObject', $this->attrs['objectClass'])) !== FALSE)) {
551
552
553
554
555
556
      unset($this->attrs['objectClass'][$key]);
    }

    if ($this->is_template) {
      $this->attrs['posixGroups'] = $this->groupMembership;
      if ($this->force_ids) {
Côme Chilliet's avatar
Côme Chilliet committed
557
        if (($this->uidNumber == '%askme%') || ($this->gidNumber == '%askme%')) {
558
559
560
561
562
563
564
565
566
          $this->attrs['force_ids'] = '%askme%';
        } else {
          $this->attrs['force_ids'] = 'TRUE';
        }
      } else {
        $this->attrs['force_ids']   = 'FALSE';
      }
      $this->attrs['mustchangepassword'] = ($this->mustchangepassword ? 'TRUE' : 'FALSE');
    }
567
568

    return $errors;
569
570
  }

571
  protected function shouldSave (): bool
572
573
574
575
576
577
578
579
580
581
  {
    if (parent::shouldSave()) {
      return TRUE;
    }
    if (array_differs($this->groupMembership, $this->savedGroupMembership)) {
      return TRUE;
    }
    return FALSE;
  }

582
  function save (): array
583
584
585
586
587
588
  {
    $errors = parent::save();

    foreach ($this->locks as $lock) {
      del_lock($lock);
    }
589
    $this->locks = [];
590
591
592
593

    return $errors;
  }

594
  protected function ldap_save (): array
595
596
597
598
599
600
601
602
603
604
605
606
  {
    $errors = parent::ldap_save();

    if (!empty($errors)) {
      return $errors;
    }

    if (!$this->is_template && !class_available('mixedGroup')) {
      /* Take care about groupMembership values: add to groups */
      $groupMembership = $this->attributesAccess['groupMembership']->getValue();
      foreach ($groupMembership as $value) {
        if (!in_array($value, $this->savedGroupMembership)) {
607
608
609
610
611
612
613
614
615
616
617
          try {
            $g = objects::open($value, 'group');
            $g->getBaseObject()->addUser($this->dn, $this->getUid());
            $msg = $g->save();
            if (empty($msg)) {
              $this->savedGroupMembership[] = $value;
            } else {
              $errors = array_merge($errors, $msg);
            }
          } catch (FusionDirectoryException $e) {
            $errors[] = 'Exception: '.$e->getMessage();
618
619
620
621
622
623
624
          }
        }
      }

      /* Remove groups not listed in groupMembership */
      foreach ($this->savedGroupMembership as $key => $value) {
        if (!in_array($value, $groupMembership)) {
625
626
627
628
629
630
631
632
633
634
635
          try {
            $g = objects::open($value, 'group');
            $g->getBaseObject()->removeUser($this->getUid());
            $msg = $g->save();
            if (empty($msg)) {
              unset($this->savedGroupMembership[$key]);
            } else {
              $errors = array_merge($errors, $msg);
            }
          } catch (FusionDirectoryException $e) {
            $errors[] = 'Exception: '.$e->getMessage();
636
637
638
639
640
641
642
643
          }
        }
      }
    }

    return $errors;
  }

644
  protected function ldap_remove (): array
645
646
  {
    /* Remove and write to LDAP */
647
    $errors = parent::ldap_remove();
648
649
650
651
    if (!empty($errors)) {
      return $errors;
    }

652
653
    if (!$this->is_template) {
      /* Delete group only if cn is uid and there are no other members inside */
654
655
656
657
658
      if (class_available('mixedGroup')) {
        $type = 'ogroup';
      } else {
        $type = 'group';
      }
659
      $groups = objects::ls($type, ['cn' => 1, 'memberUid' => '*'], NULL, '(&(objectClass=posixGroup)(gidNumber='.ldap_escape_f($this->gidNumber).')(cn='.ldap_escape_f($this->getUid()).'))');
660
661
662
663
      foreach ($groups as $dn => $group) {
        if (empty($group['memberUid']) || ((count($group['memberUid']) == 1) && ($group['memberUid'][0] == $this->getUid()))) {
          $tabobject = objects::open($dn, $type);
          $tabobject->delete();
664
        }
665
666
      }
    }
667

668
    return [];
669
670
671
  }

  /* Adapt from template, using 'dn' */
672
  function adapt_from_template (array $attrs, array $skip = [])
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
  {
    /* Include global link_info */

    parent::adapt_from_template($attrs, $skip);

    $this->savedGroupMembership = $this->groupMembership;
    if (isset($this->attrs['posixGroups'])) {
      unset($this->attrs['posixGroups']['count']);
      $this->groupMembership = $this->attrs['posixGroups'];
    }

    if (isset($this->attrs['force_ids'])) {
      $this->force_ids = ($this->attrs['force_ids'][0] != 'FALSE');
    }

    if (isset($this->attrs['mustchangepassword'])) {
      $this->mustchangepassword = ($this->attrs['mustchangepassword'][0] != 'FALSE');
    }

    $this->primaryGroup = $this->gidNumber;

    if ((count($this->host) == 1) && ($this->host[0] == '*')) {
      $this->trustMode = 'fullaccess';
    } elseif (count($this->host) > 0) {
      $this->trustMode = 'byhost';
    }
699
700

    $this->fromTemplate = TRUE;
701
702
  }

703
  function foreignKeyUpdate (string $field, $oldvalue, $newvalue, array $source)
704
705
706
707
708
709
710
711
712
713
714
715
  {
    $ret = parent::foreignKeyUpdate($field, $oldvalue, $newvalue, $source);
    if ($field == 'gidNumber') {
      if ($newvalue === NULL) {
        $this->primaryGroup = 0;
      } else {
        $this->primaryGroup = $this->gidNumber;
      }
    }
    return $ret;
  }

716
717
718
719
720
721
722
723
724
  /*!
   * \brief Get next id
   *
   * \param string $attrib attribute to use to find the next id.
   *
   * \param String $dn Dn we want an id for.
   *
   * \return Return the next id or NULL if failed
   */
725
  static function getNextId ($attrib, $dn)
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
  {
    global $config;

    if ($config->get_cfg_value('nextIdHook') != '') {
      return static::getNextIdHook($attrib, $dn);
    }

    switch ($config->get_cfg_value('idAllocationMethod', 'traditional')) {
      case 'pool':
        return static::getNextIdPool($attrib);
      default:
        msg_dialog::display(_('Warning'), sprintf(_('Unknown ID allocation method "%s"!'), $config->get_cfg_value('idAllocationMethod', 'traditional')), WARNING_DIALOG);
      case 'traditional':
        return static::getNextIdTraditional($attrib);
    }
  }

  /*!
   * \brief Get next id and add a lock to prevent other user to use it before us
   */
746
  static function getNextIdLock ($attrib, $dn)
747
748
749
750
751
752
  {
    /* Calculate new id's. We need to place a lock before calling getNextId
       to get real unique values.
     */
    $wait = 10;
    while ($user = get_lock($attrib)) {
753
      sleep(1);
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775

      /* Oups - timed out */
      if ($wait-- == 0) {
        msg_dialog::display(
          _('Warning'),
          sprintf(_('Timeout while waiting for lock. Ignoring lock from %s!'), $user),
          WARNING_DIALOG
        );
        break;
      }
    }
    add_lock($attrib, $dn);
    return static::getNextId($attrib, $dn);
  }

  /*!
   * \brief Get next id from the sambaUnixIdPool
   *
   * \param string $attrib attribute to use to find the next id.
   *
   * \return Return the next id or NULL if failed
   */
776
  protected static function getNextIdPool ($attrib)
777
778
779
780
781
782
783
784
785
  {
    global $config;

    /* Fill informational values */
    $min = $config->get_cfg_value("${attrib}PoolMin", 10000);
    $max = $config->get_cfg_value("${attrib}PoolMax", 40000);

    /* Sanity check */
    if ($min >= $max) {
Côme Chilliet's avatar
Côme Chilliet committed
786
      msg_dialog::display(_('Error'), _('Cannot allocate a free ID:').' '.sprintf(_('%sPoolMin >= %sPoolMax!'), $attrib), ERROR_DIALOG);
787
788
789
790
791
792
793
794
795
796
797
798
      return NULL;
    }

    /* ID to skip */
    $ldap = $config->get_ldap_link();
    $id   = NULL;

    /* Try to allocate the ID several times before failing */
    $tries = 3;
    while ($tries--) {

      /* Look for ID map entry */
799
      $ldap->cd($config->current['BASE']);
800
      $ldap->search("(&(objectClass=sambaUnixIdPool)($attrib=*))", ["$attrib"]);
801
802
803
804
805
806
807
808

      /* If it does not exist, create one with these defaults */
      if ($ldap->count() == 0) {
        /* Fill informational values */
        $minUserId  = $config->get_cfg_value('uidPoolMin',  10000);
        $minGroupId = $config->get_cfg_value('gidPoolMin',  10000);

        /* Add as default */
809
810
        $attrs = [
          'objectClass' => ['organizationalUnit', 'sambaUnixIdPool'],
811
812
813
          'ou'          => 'idmap',
          'uidNumber'   => $minUserId,
          'gidNumber'   => $minGroupId,
814
        ];
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
        $ldap->cd('ou=idmap,'.$config->current['BASE']);
        $ldap->add($attrs);
        if (!$ldap->success()) {
          msg_dialog::display(_('LDAP error'), msgPool::ldaperror($ldap->get_error(), 'ou=idmap,'.$config->current['BASE'], LDAP_ADD, ERROR_DIALOG));
          return NULL;
        }
        $tries++;
        continue;
      }
      /* Bail out if it's not unique */
      if ($ldap->count() != 1) {
        msg_dialog::display(_('Error'), _('Cannot allocate a free ID:').' '._('sambaUnixIdPool is not unique!'), ERROR_DIALOG);
        return NULL;
      }

      /* Store old attrib and generate new */
      $attrs    = $ldap->fetch();
      $dn       = $attrs['dn'];
      $oldAttr  = $attrs[$attrib][0];
      $newAttr  = $oldAttr + 1;

      /* Sanity check */
      if ($newAttr >= $max) {
        msg_dialog::display(_('Error'), _('Cannot allocate a free ID:').' '._('no ID available!'), ERROR_DIALOG);
        return NULL;
      }
      if ($newAttr < $min) {
        msg_dialog::display(_('Error'), _('Cannot allocate a free ID:').' '._('no ID available!'), ERROR_DIALOG);
        return NULL;
      }

      $ldap->cd($dn);
847
      $ldap->modify([$attrib => $newAttr]);
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
      if (!$ldap->success()) {
        msg_dialog::display(_('Error'), _('Cannot allocate a free ID:').' '.$ldap->get_error(), ERROR_DIALOG);
        return NULL;
      } else {
        return $oldAttr;
      }
    }

    /* Bail out if we had problems getting the next id */
    if (!$tries) {
      msg_dialog::display(_('Error'), _('Cannot allocate a free ID:').' '._('maximum tries exceeded!'), ERROR_DIALOG);
    }

    return $id;
  }

  /*!
   * \brief Get next id in a traditional unix way
   *
   * \param string $attrib attribute to use to find the next id.
   *
   * \param String $dn Dn we want an id for.
   *
   * \return Return the next id
   */
873
  protected static function getNextIdTraditional ($attrib)
874
875
876
  {
    global $config;

877
    $ids = [];
878
879
    $ldap = $config->get_ldap_link();

880
    $ldap->cd($config->current['BASE']);
881
882
883
884
885
    if (preg_match('/gidNumber/i', $attrib)) {
      $oc = 'posixGroup';
    } else {
      $oc = 'posixAccount';
    }
886
    $ldap->search("(&(objectClass=$oc)($attrib=*))", ["$attrib"]);
887
888
889
890
891
892
893
894
895
896

    /* Get list of ids */
    while ($attrs = $ldap->fetch()) {
      $ids[] = (int)$attrs["$attrib"][0];
    }

    /* Add the nobody id */
    $ids[] = 65534;

    /* get the ranges */
897
    $tmp = ['0' => 1000];
898
899
900
901
902
903
904
905
906
907
908
    if (preg_match('/posixAccount/', $oc) && $config->get_cfg_value('uidNumberBase') != '') {
      $tmp = explode('-', $config->get_cfg_value('uidNumberBase'));
    } elseif ($config->get_cfg_value('gidNumberBase') != '') {
      $tmp = explode('-', $config->get_cfg_value('gidNumberBase'));
    }

    /* Set hwm to max if not set - for backward compatibility */
    $base = $tmp[0];
    if (isset($tmp[1])) {
      $hwm = $tmp[1];
    } else {
909
      $hwm = (2 ** 32);
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
    }
    /* Find out next free id near to UID_BASE */
    for ($id = $base; $id++; $id < $hwm) {
      if (!in_array($id, $ids)) {
        return $id;
      }
    }

    /* Should not happen */
    if ($id == $hwm) {
      msg_dialog::display(_('Error'), _('Cannot allocate a free ID!'), ERROR_DIALOG);
      exit;
    }
  }

  /*!
   * \brief Get idNumber from external hook
   *
   * \param array $attrib
   *
   * \param string $dn The DN
   */
932
  protected static function getNextIdHook ($attrib, $dn)
933
934
935
  {
    global $config;

Côme Chilliet's avatar
Côme Chilliet committed
936
    if ($config->get_cfg_value('nextIdHook') != '') {
937
      /* Call hook script - if present */
Côme Chilliet's avatar
Côme Chilliet committed
938
      $command = $config->get_cfg_value('nextIdHook');
939

940
      $command .= ' '.escapeshellarg($dn).' '.escapeshellarg($attrib);
941
      @DEBUG(DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, 'Execute');
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
      exec($command, $output, $returnCode);

      $str = implode("\n", $output);
      if ($returnCode != 0) {
        /* Failure */
        @DEBUG(DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, 'Execution failed code: '.$returnCode);
        msg_dialog::display(
          _('Warning'),
          sprintf(
            _("%s\nResult: %s\nUsing default base!"),
            msgPool::cmdexecfailed('nextIdHook', $command),
            $str
          ),
          WARNING_DIALOG
        );
        return $config->get_cfg_value('uidNumberBase');
      } elseif (isset($output[0]) && is_numeric($output[0])) {
        /* Success */
        @DEBUG(DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, 'Result: '.$str);
        return $output[0];
      } else {
963
        @DEBUG(DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, 'Result: '.$str);
964
965
966
967
968
969
970
971
972
973
974
        /* Invalid output */
        msg_dialog::display(
          _('Warning'),
          sprintf(
            _("%s\nResult: %s\nUsing default base!"),
            _('"nextIdHook" did not return a valid output!'),
            $str
          ),
          WARNING_DIALOG
        );
        return $config->get_cfg_value('uidNumberBase');
975
976
977
      }
    }

Côme Chilliet's avatar
Côme Chilliet committed
978
979
    msg_dialog::display(_('Warning'), _('"nextIdHook" is not available. Using default base!'), WARNING_DIALOG);
    return $config->get_cfg_value('uidNumberBase');
980
981
  }
}