People.php 21.1 KB
Newer Older
1
<?php
Bertrand Gauthier's avatar
Bertrand Gauthier committed
2

3
4
5
namespace UnicaenLdap\Entity;

use DateTime;
6
use UnicaenLdap\Entity\Base\People as BasePeople;
7
use UnicaenLdap\Entity\Structure as StructureEntity;
8
use UnicaenLdap\Entity\System as SystemEntity;
9
use UnicaenLdap\Exception;
10
use Zend\Ldap\Dn;
11
12

/**
13
 * Classe de gestion des entités de la branche "people" de l'annuaire LDAP.
14
15
16
 *
 * @author Laurent Lécluse <laurent.lecluse at unicaen.fr>
 * @author Bertrand GAUTHIER <bertrand.gauthier@unicaen.fr>
17
 * @author David SURVILLE <david.surville@unicaen.fr>
18
 */
19
class People extends BasePeople
20
21
{
    /**
22
     * Liste des rôles existants
Bertrand Gauthier's avatar
Bertrand Gauthier committed
23
     *
24
     * @var string[]
25
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
26
27
28
29
30
    public static $roles_list = [
        'DIRECTEUR'          => 'D30',
        'RESPONSABLE'        => 'R00',
        'RESP_ADMINISTRATIF' => 'R40',
    ];
31

32
    /**
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
     * Détermine si l'individu est actif ou non
     *
     * @return boolean
     */
    public function isPeople()
    {
        return 'people' == $this->getOu();
    }

    /**
     * Détermine si l'individu est désactivé ou non
     *
     * @return boolean
     */
    public function isDeactivated()
    {
        return 'deactivated' == $this->getOu();
    }

    /**
     * Détermine si l'individu est bloqué ou non
     *
     * @return boolean
     */
    public function isBlocked()
    {
        return 'blocked' == $this->getOu();
    }

    /**
     * Retourne l'Organizational Unit (OU) de l'utilisateur
     *
     * @return string
     */
    public function getOu()
    {
69
        if ($result = $this->getNode()->getDn()->get(1)) {
70
71
            return $result['ou'];
        }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
72

73
74
75
76
        return null;
    }

    /**
77
     * Retourne le nom complet.
78
     *
79
80
81
     * @param boolean $uppercaseName nom de famille en majuscules
     * @param boolean $withCivility inclure la civilité
     * @param boolean $firstNameFirst prénom avant le nom de famille
82
     * @return string
83
     */
84
    public function getNomComplet($uppercaseName = false, $withCivility = false, $firstNameFirst = false)
85
    {
86
        $sn = $this->sn;
87
        $sn = is_array($sn) ? current($sn) : $sn;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
88

89
90
91
92
        if (!$sn) {
            return '';
        }

93
94
95
        $nom = $uppercaseName ? mb_strtoupper($sn, 'UTF-8') : $sn;
        $prenom = $this->givenName;
        $civilite = $withCivility ? $this->supannCivilite . ' ' : '';
96

97
98
99
        return  $civilite . ($firstNameFirst ? $prenom . ' ' . $nom : $nom . ' ' . $prenom);
    }

100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    /**
     * Retourne le nom d'usage
     *
     * @return string|null
     */
    public function getNomUsage()
    {
        return is_array($this->sn) ? $this->sn[0] : $this->sn;
    }

    /**
     * Retourne le nom de famille s'il existe, sinon le nom d'usage
     *
     * @return string|null
     */
    public function getNomFamille()
    {
        return is_array($this->sn) ? $this->sn[1] : $this->sn;
    }

120
121
122
123
124
    /**
     * Retourne la date de naissance
     *
     * @return DateTime|false
     */
125
    public function getDateNaissance()
126
127
128
129
130
131
132
133
134
    {
        return DateTime::createFromFormat('Ymd h:i:s', $this->schacDateOfBirth . ' 00:00:00');
    }

    /**
     * Retourne la date d'expiration
     *
     * @return DateTime|false
     */
135
    public function getDateExpiration()
136
137
138
139
    {
        return DateTime::createFromFormat('Ymd h:i:s', $this->schacExpiryDate . ' 00:00:00');
    }

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
    /**
     * Retourne le responsable de l'entrée Ldap
     *
     * @return People|SystemEntity|string|null
     * @throws Exception
     * @throws \Zend\Ldap\Exception\LdapException
     */
    public function getParrain()
    {
        $systemService = $this->service->getLdapSystemService();
        $node = $this->service->getLdap()->getNode($this->supannParrainDN);
        $branch = $node->getDn()->get(1);
        switch($branch['ou']) {
            case strtolower($this->service->getType()):
                return $this->service->getBy($node->getDnString(), 'dn');
            case strtolower($systemService->getType()):
                return $systemService->getBy($node->getDnString(), 'dn');
            default:
                return $this->supannParrainDN;
        }
    }

162
163
164
    /**
     * Retourne l'adresse postale professionnelle
     *
165
166
     * @param string $type type de l'adresse : 'professionnelle' ou 'personnelle'
     * @return array|null
167
     */
168
    public function getAdressePostale($type = 'professionnelle')
169
    {
170
171
172
173
174
175
176
177
        if(!in_array($type, ['professionnelle', 'personnelle'])) {
            return null;
        }

        $attributes = ($type == 'professionnelle')
            ? $this->postalAddress
            : [$this->ucbnPrivateAddress, $this->ucbnPrivateAddressBis];
        $value = $this->preFormat($attributes);
178
179
180
181
182
183
184
        $value = array_map(function ($val) {
            return explode('$', $val);
        }, $value);

        return 1 == count($value) ? $value[0] : $value;
    }

185
    /**
186
187
     * Test si une valeur est renseignée pour le champ "eduPersonAffiliation"
     *
188
189
190
191
192
     * @param string $status
     * @return bool
     */
    protected function whichStatus(string $status): bool
    {
193
194
        $value = $this->preFormat($this->eduPersonAffiliation);
        return in_array($status, $value);
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    }

    /**
     * Check "affiliate" status
     *
     * @return bool
     */
    public function isAffiliate(): bool
    {
        return $this->whichStatus(parent::STATUS_AFFILIATE);
    }
    /**
     * Check "alum" status
     *
     * @return bool
     */
    public function isAlum(): bool
    {
        return $this->whichStatus(parent::STATUS_ALUM);
    }

    /**
     * Check "emeritus" status
     *
     * @return bool
     */
    public function isEmeritus(): bool
    {
        return $this->whichStatus(parent::STATUS_EMERITUS);
    }

    /**
     * Check "employee" status
     *
     * @return bool
     */
    public function isEmployee(): bool
    {
        return $this->whichStatus(parent::STATUS_EMPLOYEE);
    }

    /**
     * Check "faculty" status
     *
     * @return bool
     */
    public function isFaculty(): bool
    {
        return $this->whichStatus(parent::STATUS_FACULTY);
    }

    /**
     * Check "member" status
     *
     * @return bool
     */
    public function isMember(): bool
    {
        return $this->whichStatus(parent::STATUS_MEMBER);
    }

    /**
     * Check "registered reader" status
     *
     * @return bool
     */
    public function isRegisteredReader(): bool
    {
        return $this->whichStatus(parent::STATUS_REGISTERED_READER);
    }

    /**
     * Check "researcher" status
     *
     * @return bool
     */
    public function isResearcher(): bool
    {
        return $this->whichStatus(parent::STATUS_RESEARCHER);
    }

    /**
     * Check "retired" status
     *
     * @return bool
     */
    public function isRetired(): bool
    {
        return $this->whichStatus(parent::STATUS_RETIRED);
    }

    /**
     * Check "staff" status
     *
     * @return bool
     */
    public function isStaff(): bool
    {
        return $this->whichStatus(parent::STATUS_STAFF);
    }

    /**
     * Check "student" status
     *
     * @return bool
     */
    public function isStudent(): bool
    {
        return $this->whichStatus(parent::STATUS_STUDENT);
    }

    /**
     * Check "teacher" status
     *
     * @return bool
     */
    public function isTeacher(): bool
    {
        return $this->whichStatus(parent::STATUS_TEACHER);
314
315
316
    }

    /**
317
     * Retourne le léocode associé à l'individu
318
     *
319
     * @return string|null
320
     */
321
    public function getLeocarteCode()
322
    {
323
324
325
326
327
328
329
330
331
332
        $attributeValues = $this->preFormat($this->supannRefId);
        $label = $this->getLabel('LEOCODE');

        $value = array_filter($attributeValues, function ($v) use ($label) {
            return preg_match("/^$label(?<identifiant>.+)$/", $v);
        });

        return !empty($value)
            ? str_replace($label, '', array_values($value)[0])
            : null;
333
334
335
    }

    /**
336
     * Retourne le code de la léocarte associée à l'individu
337
     *
338
     * @return string|null
339
     */
340
    public function getLeocarteCSN()
341
    {
342
343
344
345
346
347
348
349
350
351
        $attributeValues = $this->preFormat($this->supannRefId);
        $label = $this->getLabel('UNICAEN', 'REVERSECSN');

        $value = array_filter($attributeValues, function ($v) use ($label) {
            return preg_match("/^$label(?<identifiant>.+)$/", $v);
        });

        return !empty($value)
            ? str_replace($label, '', array_values($value)[0])
            : null;
352
353
354
    }

    /**
355
     * Retourne le numéro d'étudiant
356
     *
357
     * @return string|null
358
     */
359
    public function getEtudiantId()
360
    {
361
362
        return $this->supannEtuId;
    }
363

364
365
366
367
368
369
370
371
    /**
     * Retourne le numéro d'employé
     *
     * @return string|null
     */
    public function getEmployeId()
    {
        return $this->supannEmpId;
372
373
    }

374
    /**
375
     * Retourne l'identifiant de l'individu dans le référentiel
376
     *
377
     * @return string|null
378
     */
379
    public function getReferentielId()
380
    {
381
382
        $attributeValues = $this->preFormat($this->supannRefId);
        $label = $this->getLabel('OCTOPUS', 'ID');
Bertrand Gauthier's avatar
Bertrand Gauthier committed
383

384
385
386
387
388
389
390
        $value = array_filter($attributeValues, function ($v) use ($label) {
            return preg_match("/^$label(?<identifiant>.+)$/", $v);
        });

        return !empty($value)
            ? str_replace($label, '', array_values($value)[0])
            : null;
391
392
393
    }

    /**
394
     * Établissement auquel appartient la personne
395
     *
396
     * @return StructureEntity|null
397
     */
398
    public function getEtablissement()
399
    {
400
401
402
        $rootService = $this->service->getLdapRootService();
        $structureService = $this->service->getLdapStructureService();
        $dn = $this->eduPersonOrgDN;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
403

404
405
406
407
408
409
410
411
412
413
414
        if (empty($dn)) return null;
        switch($dn) {
            case $rootService->getEtablissementDN():
                return $rootService->getStructureEntity();
            default:
                try {
                    return $structureService->getBy($dn, 'dn');
                } catch (Exception $e) {
                    return null;
                }
        }
415
416
417
    }

    /**
418
     * Retourne les structures auxquelles appartient la personne
Bertrand Gauthier's avatar
Bertrand Gauthier committed
419
     *
420
     * @return StructureEntity[]|null
421
     */
422
    public function getStructure()
423
    {
424
        $structureService = $this->service->getLdapStructureService();
425
426
        $value = $this->eduPersonOrgUnitDN;
        if (empty($value)) return null;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
427

428
429
        $value = $structureService->getAllBy($value, 'dn');
        return 1 == count($value) ? array_shift($value) : $value;
430
431
432
    }

    /**
433
     * Retourne la structure principale à laquelle appartient la personne
Bertrand Gauthier's avatar
Bertrand Gauthier committed
434
     *
435
     * @return StructureEntity|null
436
     */
437
    public function getStructurePrincipale()
438
    {
439
        $structureService = $this->service->getLdapStructureService();
440
441
        $value = $this->eduPersonPrimaryOrgUnitDN;
        if (empty($value)) return null;
442

443
444
445
446
447
        try {
            return $structureService->getBy($value, 'dn');
        } catch (Exception $e) {
            return null;
        }
448
449
    }

450
    /**
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
     * Retourne les structures recherche auxquelles appartient la personne
     *
     * @return StructureEntity[]|null
     */
    public function getStructureRecherche()
    {
        $structureService = $this->service->getLdapStructureService();
        $structurePrefixe = $structureService->getCodeStructurePrefixe();

        $value = $this->preFormat($this->ucbnStructureRecherche);
        if (empty($value)) return null;

        $value = array_map(function ($v) use ($structurePrefixe) {
            preg_match(self::$structure_pattern, $v, $matches);
            return $structurePrefixe . $matches['code'];
        }, $value);

        $value = $structureService->getAllBy($value, 'supannCodeEntite');
        return 1 == count($value) ? array_shift($value) : $value;
    }

    /**
     * Vérifie l'appartenance d'une personne à une structure (structures recherche incluses)
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
     *
     * @param string|Dn|StructureEntity $value
     * @return bool
     * @throws Exception
     * @throws \Zend\Ldap\Exception\LdapException
     */
    public function isInStructure($value)
    {
        $structureService = $this->service->getLdapStructureService();
        $structurePrefixe = $structureService->getCodeStructurePrefixe();

        if (is_string($value)) {
            if(Dn::checkDn($value)) {
                $value = $structureService->getBy($value, 'dn');
            }
            else {
                if (0 !== strpos($value, $structurePrefixe)) {
                    $value = $structurePrefixe . $value;
                }
                $value = $structureService->get($value);
            }
        } elseif ($value instanceof Dn) {
            $value = $structureService->getBy($value->toString(), 'dn');
        }

        if(!$value instanceof StructureEntity) {
            return false;
        }

        $structures = $this->preFormat($this->supannEntiteAffectation);
504
505
506
507
508
509
510
511
        $structuresRecherche = $this->preFormat($this->ucbnStructureRecherche);

        $structuresRecherche = array_map(function ($v) use ($structurePrefixe) {
            preg_match(self::$structure_pattern, $v, $matches);
            return $structurePrefixe . $matches['code'];
        }, $structuresRecherche);

        return in_array($value->getId(), array_merge($structures, $structuresRecherche));
512
513
    }

514
    /**
515
     * Retourne les étapes auxquelles appartient l'étudiant
Bertrand Gauthier's avatar
Bertrand Gauthier committed
516
     *
517
518
     * @return mixed|StructureEntity[]|null
     * @throws Exception
519
     */
520
    public function getInscriptionEtape()
521
    {
522
523
        $value = $this->preFormat($this->supannEtuEtape);
        if (empty($value)) return null;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
524

525
526
        $label = $this->getLabel('UAI', $this->service->getLdapRootService()->getEtablissementUAI());
        $structureService = $this->service->getLdapStructureService();
527
528
529
530
531
532
533
534
535
        list($structureKey) = Entity::getNodeParams($structureService->getType());
        $structureBranch = $structureService->getBranches()[0];
        $value = array_map(function ($v) use ($label, $structureKey, $structureBranch) {
            return sprintf('%s=%s,%s',
                $structureKey,
                str_replace($label, '' , $v),
                $structureBranch
            );
        }, $value);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
536

537
538
        $value = $structureService->getAllBy($value, 'dn');
        return 1 == count($value) ? array_shift($value) : $value;
539
540
    }

541
    /**
542
     * Retourne les éléments pédagogiques auxquels appartient l'étudiant
543
     *
544
545
     * @return mixed|StructureEntity[]|null
     * @throws Exception
546
     */
547
    public function getInscriptionElementPedagogique()
548
    {
549
550
        $value = $this->preFormat($this->supannEtuElementPedagogique);
        if (empty($value)) return null;
551

552
553
        $label = $this->getLabel('UAI', $this->service->getLdapRootService()->getEtablissementUAI());
        $structureService = $this->service->getLdapStructureService();
554
555
556
557
558
559
560
561
562
563
564
565
        list($structureKey) = Entity::getNodeParams($structureService->getType());
        $structureBranch = $structureService->getBranches()[0];
        $value = array_map(function ($v) use ($label, $structureKey, $structureBranch) {
            return sprintf('%s=%s,%s',
                $structureKey,
                str_replace($label, '' , $v),
                $structureBranch
            );
        }, $value);

        $value = $structureService->getAllBy($value, 'dn');
        return 1 == count($value) ? array_shift($value) : $value;
566
567
    }

568
569
570
571
572
573
574
575
576
577
578
579
580
581
    /**
     * Retourne les inscriptions complètes d'un étudiant
     *
     * @return array
     */
    public function getInscription()
    {
        $value = $this->preFormat($this->supannEtuInscription);
        if (empty($value)) return null;

        $value = array_map(function ($v) {
            preg_match(self::$inscription_pattern, $v, $matches);
            $affect = $matches['affect'];
            $etape = str_replace($this->getLabel('UAI', $this->service->getLdapRootService()->getEtablissementUAI()), '', $matches['etape']);
582
            $replace = [$this->getLabel('SISE'), $this->getLabel('SUPANN'), $this->getLabel('INCONNU')];
583
584
585
            return [
                'etab'          => str_replace($this->getLabel('UAI'), '', $matches['etab']),
                'anneeinsc'     => $matches['anneeinsc'],
586
587
588
589
                'regimeinsc'    => str_replace($replace, '', $matches['regimeinsc']),
                'sectdisc'      => str_replace($replace, '', $matches['sectdisc']),
                'typedip'       => str_replace($replace, '', $matches['typedip']),
                'cursusann'     => str_replace($replace, '', $matches['cursusann']),
590
                'affect'        => $this->service->getLdapStructureService()->get($affect) ?: $affect,
591
                'diplome'       => str_replace($replace, '', $matches['diplome']),
592
593
594
595
596
597
598
                'etape'         => $this->service->getLdapStructureService()->get($etape) ?: $etape,
            ];
        }, $value);

        return 1 == count($value) ? array_shift($value) : $value;
    }

Bertrand Gauthier's avatar
Bertrand Gauthier committed
599
    /**
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
     * Retourne le complément des inscriptions d'un étudiant
     *
     * @return array
     */
    public function getInscriptionComplement()
    {
        $value = $this->preFormat($this->ucbnEtuComplementInscription);
        if (empty($value)) return null;

        $value = array_map(function ($v) {
            preg_match(self::$inscription_complement_pattern, $v, $matches);
            $uaiLabel = $this->getLabel('UAI', $this->service->getLdapRootService()->getEtablissementUAI());
            $etape = str_replace($uaiLabel, '', $matches['etape']);
            return [
                'anneeinsc' => $matches['anneeinsc'],
                'etape'     => $this->service->getLdapStructureService()->get($etape) ?: $etape,
                'adistance' => str_replace($uaiLabel, '', $matches['adistance'])
            ];
        }, $value);

        return 1 == count($value) ? array_shift($value) : $value;
    }

    /**
     * Retourne les rôles d'une personne
     *
     * @return array
     */
    public function getRole()
    {
        $value = $this->preFormat($this->supannRoleEntite);
        if (empty($value)) return null;

        $value = array_map(function ($v) {
            preg_match(self::$role_pattern, $v, $matches);
            $code = $matches['code'];
            $replace = [$this->getLabel('SUPANN'), $this->getLabel('INCONNU')];
            return [
                'role'      => str_replace($replace, '', $matches['role']),
                'type'      => str_replace($replace, '', $matches['type']),
                'code'      => $this->service->getLdapStructureService()->get($code) ?: $code,
                'libelle'   => $matches['libelle'],
            ];
        }, $value);

        return 1 == count($value) ? array_shift($value) : $value;
    }

    /**
     * Vérifie si la personne à une fonction dans un type de structure et une structure
650
651
     *
     * @param string $role
652
653
     * @param string $type
     * @param string|Dn|StructureEntity|null $value
654
     * @return bool
655
656
     * @throws Exception
     * @throws \Zend\Ldap\Exception\LdapException
657
     */
658
    public function hasRoleInStructure(string $role, string $type, $structure = null): bool
659
    {
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
        $structureService = $this->service->getLdapStructureService();
        $structurePrefixe = $structureService->getCodeStructurePrefixe();

        if($structure == null) {
            $structure = '.*';
        }
        else {
            if (is_string($structure)) {
                if (Dn::checkDn($structure)) {
                    $structure = $structureService->getBy($structure, 'dn');
                } else {
                    if (0 !== strpos($structure, $structurePrefixe)) {
                        $structure = $structurePrefixe . $structure;
                    }
                    $structure = $structureService->get($structure);
                }
            } elseif ($structure instanceof Dn) {
                $structure = $structureService->getBy($structure->toString(), 'dn');
            }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
679

680
681
682
            if (!$structure instanceof StructureEntity) {
                return false;
            }
683
        }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
684

685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
        $structure = $structure instanceof StructureEntity ? $structure->supannCodeEntite : $structure;
        $pattern = "/^\[role=\{SUPANN\}$role\]\[type=\{SUPANN\}$type\]\[code=$structure\]\[libelle=.*\]$/";

        $matches = array_filter($this->supannRoleEntite, function ($v) use ($pattern) {
            return preg_match($pattern, $v);
        });

        return !empty($matches);
    }

    /**
     * Retourne le site d'un personne
     *
     * @return array|null
     */
    public function getSite()
    {
        $value = $this->preFormat($this->ucbnSiteLocalisation);
        if (empty($value)) return null;

        $value = array_map(function ($v) {
            preg_match(self::$localisation_pattern, $v, $matches);
            $code = $matches['code'];
            return [
                'code'      => $matches['code'],
                'libelle'   => $matches['libelle'],
            ];
        }, $value);

        return 1 == count($value) ? array_shift($value) : $value;
715
    }
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733

    /**
     * Modifie l'ensemble des attributs liés au mot de passe
     *
     * @param string $value
     * @return $this
     * @throws \UnicaenLdap\Exception
     * @throws \Zend\Ldap\Exception\LdapException
     */
    public function setPassword(string $value)
    {
        parent::setUserPassword($value);
        parent::setNtPassword($value);
        parent::setSambaNTPassword($value);
        parent::setUcbnSquidHash($value);

        return $this;
    }
734
}