class_sinapsRequest.inc 19.6 KB
Newer Older
1
2
3
<?php
/*
  This code is part of FusionDirectory (http://www.fusiondirectory.org/)
4
  Copyright (C) 2017-2019 FusionDirectory
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

  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.
*/

class sinapsRequestException extends Exception
{
}

class sinapsRequest
{
  protected $data;

29
  public function __construct ($xml)
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  {
    $this->data = new SimpleXMLElement($xml);
    if (!isset($this->data->domaine)) {
      throw new sinapsRequestException('XML content is missing "domaine" tag');
    }
    if (!isset($this->data->domaine['code'])) {
      throw new sinapsRequestException('"domaine" tag is missing "code" attribute');
    }
    if (!isset($this->data->domaine->donnees->operation)) {
      throw new sinapsRequestException('XML content is missing "domaine>donnees>operation" tag');
    }
    if (!isset($this->data->domaine->donnees->operation['codeOperation'])) {
      throw new sinapsRequestException('"operation" tag is missing "codeOperation" attribute');
    }
    if (!isset($this->data->domaine->identifiantTransaction)) {
      throw new sinapsRequestException('"identifiantTransaction" tag is missing from "domaine" tag');
    }
  }

49
  public function codeDomaine ()
50
51
52
53
  {
    return $this->data->domaine['code'];
  }

54
  public function codeOperation ()
55
56
57
58
  {
    return $this->data->domaine->donnees->operation['codeOperation'];
  }

59
  public function operationVersion ()
60
61
62
63
  {
    return $this->data->domaine->donnees->operation['version'];
  }

64
  public function identifiantTransaction ()
65
66
67
68
  {
    return $this->data->domaine->identifiantTransaction;
  }

69
  public function getOperationStructure ()
70
71
72
73
  {
    return $this->data->domaine->donnees->operation->structure;
  }

74
  public function getOperationPersonne ()
75
76
77
78
  {
    return $this->data->domaine->donnees->operation->personne;
  }

79
  public static function acquittementFonctionnel ($responseCode = 200, $codeAcquittement = 0, $message = '', $identifiantObjApp = NULL, $synchrone = TRUE)
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
  {
    $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>
    <Acquittement xmlns:acq="http://referentiels.SINAPS.amue.fr/acquittementFonctionnel">
    </Acquittement>');
    $xml->addChild('ResponseCode', $responseCode);
    $xml->addChild('messageAcquittement', $message);
    $xml->addChild('codeAcquittement', $codeAcquittement);
    if ($identifiantObjApp) {
      $xml->addChild('identifiantObjApp', $identifiantObjApp);
    } else {
      $xml->addChild('identifiantObjApp');
    }

    if ($synchrone) {
      /* Hack because SINAPS API makes no sense and needs a prefix for Acquittement only for synchrone mode */
      return preg_replace(
96
97
        ['|<Acquittement |',   '|</Acquittement>$|'],
        ['<acq:Acquittement ', '</acq:Acquittement>'],
98
99
100
101
102
103
104
105
        $xml->asXML(),
        1
      );
    } else {
      return $xml->asXML();
    }
  }

106
  public function acquittementTechnique ($responseCode = 200, $message = '')
107
108
109
110
111
112
113
114
115
116
117
  {
    $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>
    <WebServiceHTTPResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="acquittementTechnique.xsd">
    </WebServiceHTTPResponse>');
    $xml->addChild('IdentifiantTransaction', $this->identifiantTransaction());
    $xml->addChild('ResponseCode', $responseCode);
    $xml->addChild('ResponseMessage', $message);

    return $xml->asXML();
  }

118
  public function getSupannEntiteValues ($identifiantApplication, $identifiantApplicationSync, $uuidPrefix, $ldapUuidToCodeEntiteCallback)
119
120
121
122
  {
    $structure  = $this->getOperationStructure();
    $now        = new DateTime();

123
124
125
126
127
128
129
130
131
132
133
    $mapping = [
      'libelle20'         => ['entite','ou'],
      'descriptifLong'    => ['entite','description'],
      'codeStructure'     => ['entite','supannCodeEntite'],
      'codeSousType'      => ['entite','supannTypeEntite'],
      'dateDebutValidite' => ['supannStructureExt','fdSupannStartDate'],
      'dateFinValidite'   => ['supannStructureExt','fdSupannEndDate'],
    ];
    $values = [
      'entite' => [
        'supannRefId'               => [],
134
        'postalAddress'             => '',
135
        'supannCodeEntiteParent'    => [],
136
137
      ],
    ];
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156

    $uuid = '';

    if (isset($structure->referenceCroisee->identifiantsExternes)) {
      foreach ($structure->referenceCroisee->identifiantsExternes as $ref) {
        if ($ref->identifiantApplication == $identifiantApplication) {
          $uuid = $ref->identifiantExterne;
        } elseif (in_array($ref->identifiantApplication, $identifiantApplicationSync)) {
          $values['entite']['supannRefId'][] = '{'.$ref->identifiantApplication.'}'.$ref->identifiantExterne;
        }
      }
    }

    if (empty($uuid)) {
      $uuid = static::genUUID();
    }

    array_unshift($values['entite']['supannRefId'], '{'.$uuidPrefix.'}'.$uuid);

157
    foreach ($mapping as $sinapsAttr => list($fdTab, $fdAttr)) {
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
      if (isset($structure->$sinapsAttr)) {
        $values[$fdTab][$fdAttr] = (string)$structure->$sinapsAttr;
      } else {
        $values[$fdTab][$fdAttr] = '';
      }
    }

    if (isset($structure->methodesDeContact->methodeDeContact)) {
      foreach ($structure->methodesDeContact->methodeDeContact as $method) {
        if (!$this->checkValidite($method, $now)) {
          continue;
        }
        switch ((string)$method->codeTypeMethodeContact) {
          case 'ADR':
            if ((string)$method->adresse->temoinAdressePrincipale != 'true') {
              trigger_error('Ignore adresse non principale');
              continue;
            }
            $adresse = $this->convertAddress($method->adresse);
            if ($adresse === FALSE) {
              trigger_error('Ignore adresse non FR non ETR');
              continue;
            }
            $values['entite']['postalAddress'] = $adresse;
            break;
          default:
            trigger_error('ignoring codeTypeMethodeContact '.$method->codeTypeMethodeContact);
        }
      }
    }

    if (isset($structure->liensStructure->lienStructure)) {
      foreach ($structure->liensStructure->lienStructure as $lienStructure) {
        if (((string)$lienStructure->codeTypeLien == 'HIE') && isset($lienStructure->codeStructureMere)) {
          if (!$this->checkValidite($lienStructure, $now)) {
            continue;
          }
          $mereUUID = $this->getUUIDFromReferenceCroisee($identifiantApplication, $lienStructure->referenceCroisee);
          if (!empty($mereUUID)) {
197
            $values['entite']['supannCodeEntiteParent'][] = $ldapUuidToCodeEntiteCallback($mereUUID)['supannCodeEntite'];
198
199
200
201
202
203
204
205
          }
        }
      }
    }

    return $values;
  }

206
  public function getUserValues ($identifiantApplication, array $identifiantApplicationSync, $uuidPrefix, $ldapUuidToCodeEntiteCallback, array $userRoles)
207
208
209
  {
    $personne   = $this->getOperationPersonne();
    $now        = new DateTime();
210
211
212
213
214
215
216
217
    $mapping = [
      'civilite'        => ['supannAccount','supannCivilite'],
      'nomUsage'        => ['user','sn'],
      'descriptifLong'  => ['user','description'],
      'dateNaissance'   => ['personalInfo','dateOfBirth'],
      'sexe'            => ['personalInfo','gender'],
    ];
    $values = [
218
      'lock'          => FALSE,
219
      'user'          => [
220
221
222
223
        'homePhone'                 => '',
        'postalAddress'             => '',
        'homePostalAddress'         => '',
        'employeeNumber'            => '',
224
225
226
227
228
229
230
231
      ],
      'supannAccount' => [
        'supannRefId'                       => [],
        'supannEntiteAffectation'           => [],
        'supannRoleGenerique'               => [],
        'supannTypeEntiteAffectation'       => [],
        'supannRoleEntite'                  => [],
        'supannActivite'                    => [],
232
233
        'supannEmpCorps'                    => '',
        'supannEntiteAffectationPrincipale' => '',
234
235
236
237
238
      ],
      'personalInfo'  => [
        'fdPrivateMail' => [],
      ],
    ];
239
240
241
242
243
244

    $uuid = '';

    if (isset($personne->referenceCroisee->identifiantsExternes)) {
      foreach ($personne->referenceCroisee->identifiantsExternes as $ref) {
        if ($ref->identifiantApplication == $identifiantApplication) {
245
          $uuid = (string)$ref->identifiantExterne;
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
        } elseif (in_array($ref->identifiantApplication, $identifiantApplicationSync)) {
          $values['supannAccount']['supannRefId'][] = '{'.$ref->identifiantApplication.'}'.$ref->identifiantExterne;
        }
        if ($ref->identifiantApplication == 'SAP') {
          $values['user']['employeeNumber'] = $ref->identifiantExterne;
        }
      }
    }

    if (empty($uuid)) {
      $uuid = static::genUUID();
    }

    array_unshift($values['supannAccount']['supannRefId'], '{'.$uuidPrefix.'}'.$uuid);

261
    /* Check if the user still has at least one role which means he exists, otherwise this is a deletion */
262
    $userRoleExists = [];
263
264
265
266
267
268
269
270
271
272
273
274
    foreach ($userRoles as $typeRole) {
      if (preg_match('^([^/]+)/(.+)$', $typeRole, $m)) {
        $userRoleExists[$m[1]][] = $m[2];
      } else {
        $userRoleExists[$typeRole] = TRUE;
      }
    }
    $deletion = TRUE;
    if (isset($personne->rattachements->rattachement)) {
      foreach ($personne->rattachements->rattachement as $rattachement) {
        if (isset($rattachement->roles->role)) {
          foreach ($rattachement->roles->role as $role) {
275
276
            if (isset($userRoleExists[(string)$role->typeRole])) {
              if ($userRoleExists[(string)$role->typeRole] === TRUE) {
277
278
279
                $deletion = FALSE;
                break 2;
              }
280
              if (in_array_ics((string)$role->externe->typeExterne, $userRoleExists[(string)$role->typeRole])) {
281
282
283
284
285
286
287
288
289
                $deletion = FALSE;
                break 2;
              }
            }
          }
        }
      }
    }
    if ($deletion) {
290
291
292
293
294
295
296
297
298
299
300
301
302
      /* This is a deletion */
      /* Store current date as end of contract */
      $values['personalInfo']['fdContractEndDate'] = $now->format('d.m.Y');
      /* Lock the account */
      $values['lock'] = TRUE;
      /* Remove all contact info */
      $values['user']['telephoneNumber']          = '';
      $values['user']['facsimileTelephoneNumber'] = '';
      $values['user']['mobile']                   = '';
      $values['mailAccount']                      = FALSE;
      return $values;
    }

303
    foreach ($mapping as $sinapsAttr => list($fdTab, $fdAttr)) {
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
      if (isset($personne->$sinapsAttr)) {
        $values[$fdTab][$fdAttr] = (string)$personne->$sinapsAttr;
      } else {
        $values[$fdTab][$fdAttr] = '';
      }
    }

    if (isset($personne->prenoms)) {
      $values['user']['givenName'] = preg_replace('/;.*$/', '', $personne->prenoms);
    }

    if (isset($personne->methodesDeContact->methodeContact)) {
      foreach ($personne->methodesDeContact->methodeContact as $method) {
        if (!$this->checkValidite($method, $now)) {
          continue;
        }
        switch ((string)$method->typeMethodeContact) {
          case 'TELPERSO':
            $values['user']['homePhone'] = (string)$method->valeur;
            break;
          case 'MAILPERSO':
            $values['personalInfo']['fdPrivateMail'][] = (string)$method->valeur;
            break;
          case 'ADR':
            if ((string)$method->adresse->temoinAdressePrincipale != 'true') {
              trigger_error('Ignore adresse non principale');
              continue;
            }
            $adresse = $this->convertAddress($method->adresse);
            if ($adresse === FALSE) {
              trigger_error('Ignore adresse non FR non ETR');
              continue;
            }
337
            if ((string)$method->adresse->codeTypeAdresse == 'ADRPERSO') {
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
              $values['user']['homePostalAddress'] = $adresse;
            } else {
              $values['user']['postalAddress'] = $adresse;
            }
            break;
          default:
            trigger_error('ignoring codeTypeMethodeContact '.$method->typeMethodeContact);
        }
      }
    }

    if (isset($personne->rattachements->rattachement)) {
      foreach ($personne->rattachements->rattachement as $rattachement) {
        if (!$this->checkValidite($rattachement, $now)) {
          continue;
        }

        if (isset($rattachement->roles->role)) {
          foreach ($rattachement->roles->role as $role) {
            if (!$this->checkValidite($role, $now)) {
              continue;
            }
            if ($role->typeRole != 'PR') {
              continue;
            }
            if (isset($role->personneRessource->affectations->affectation)) {
364
              $quotiteMax = NULL;
365
366
367
368
              foreach ($role->personneRessource->affectations->affectation as $affectation) {
                if (!$this->checkValidite($affectation, $now)) {
                  continue;
                }
369
                $UUID     = (string)$affectation->identifiantStructureInterne;
370
                $quotite  = (isset($affectation->quotite) ? (int)$affectation->quotite : 0);
371
372
                if (!empty($UUID)) {
                  $entite = $ldapUuidToCodeEntiteCallback($UUID);
373
374
375
                  if (isset($entite['supannTypeEntite'])) {
                    $values['supannAccount']['supannTypeEntiteAffectation'][] = $entite['supannTypeEntite'];
                  }
376
                  $values['supannAccount']['supannEntiteAffectation'][]         = $entite['supannCodeEntite'];
377
                  if (($quotiteMax === NULL) || ($quotite > $quotiteMax)) {
378
                    $quotiteMax                                                   = $quotite;
379
380
                    $values['supannAccount']['supannEntiteAffectationPrincipale'] = $entite['supannCodeEntite'];
                  }
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
                }
              }
            }
            if (isset($role->personneRessource->elementsDeCarriere->elementCarriere)) {
              foreach ($role->personneRessource->elementsDeCarriere->elementCarriere as $elementCarriere) {
                if (!$this->checkValidite($elementCarriere, $now)) {
                  continue;
                }
                /* Warning: supannEmpCorps and employeeType are mono-value so we replace them */
                if (isset($elementCarriere->corps)) {
                  $values['supannAccount']['supannEmpCorps'] = (string)$elementCarriere->corps;
                }
                if (isset($elementCarriere->bapReferens)) {
                  $values['supannAccount']['supannActivite'][] = (string)$elementCarriere->bapReferens;
                }
              }
            }
          }
        }
        if (isset($rattachement->fonctionsOccupees->fonctionOccupee)) {
          foreach ($rattachement->fonctionsOccupees->fonctionOccupee as $fonctionOccupee) {
            if (!$this->checkValidite($fonctionOccupee, $now)) {
              continue;
            }
            $values['supannAccount']['supannRoleGenerique'][] = (string)$fonctionOccupee->fonctionRh;
406
            $UUID                                             = (string)$fonctionOccupee->identifiantStructureInterne;
407
            if (!empty($UUID)) {
408
              $entite = $ldapUuidToCodeEntiteCallback($UUID, TRUE);
409
410
411
412
413
414
415
416
417
418
419
420
              $values['supannAccount']['supannTypeEntiteAffectation'][] = $entite['supannTypeEntite'];
              $values['supannAccount']['supannEntiteAffectation'][] = $entite['supannCodeEntite'];
              $values['supannAccount']['supannRoleEntite'][] =
                '[role='.$fonctionOccupee->fonctionRh.']'.
                '[type='.$entite['supannTypeEntite'].']'.
                '[code='.$entite['supannCodeEntite'].']';
            }
          }
        }
      }
    }

421
    foreach (['supannRefId','supannEntiteAffectation','supannRoleGenerique','supannTypeEntiteAffectation','supannRoleEntite','supannActivite'] as $arrayattribute) {
422
423
424
425
426
427
      $values['supannAccount'][$arrayattribute] = array_values(array_unique($values['supannAccount'][$arrayattribute]));
    }

    return $values;
  }

428
  protected function convertAddress (SimpleXMLElement $address)
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
474
475
476
477
478
479
480
481
  {
    $adresse = '';
    if (!empty($address->adresseFR)) {
      if (!empty($address->adresseFR->batiment)) {
        $adresse .= $address->adresseFR->batiment;
        if (!empty($address->adresseFR->etage)) {
          $adresse .= ', '.$address->adresseFR->etage;
        }
        $adresse .= "\n";
      }
      $adresse .= $address->adresseFR->numeroVoie;
      if (!empty($address->adresseFR->codeBTQC)) {
        $adresse .= ' '.$address->adresseFR->codeBTQC;
      }
      $adresse .= ' '.$address->adresseFR->typeVoie;
      $adresse .= ' '.$address->adresseFR->nomVoie;
      $adresse .= "\n";
      if (!empty($address->adresseFR->complement)) {
        $adresse .= $address->adresseFR->complement."\n";
      }
      if (!empty($address->adresseFR->lieuDit)) {
        $adresse .= $address->adresseFR->lieuDit."\n";
      }
      $adresse .= $address->adresseFR->codePostal;
      $adresse .= ' '.$address->adresseFR->BD;
      $adresse .= "\n";
      $adresse .= "FRANCE\n";
    } elseif (!empty($address->adresseEtr)) {
      if (!empty($address->adresseEtr->batiment)) {
        $adresse .= $address->adresseEtr->batiment;
        if (!empty($address->adresseEtr->etage)) {
          $adresse .= ', '.$address->adresseEtr->etage;
        }
        $adresse .= "\n";
      }
      $adresse .= $address->adresseEtr->numeroVoie;
      $adresse .= ' '.$address->adresseEtr->nomVoie;
      $adresse .= "\n";
      if (!empty($address->adresseEtr->complement)) {
        $adresse .= $address->adresseEtr->complement."\n";
      }
      $adresse .= $address->adresseEtr->codePostal;
      $adresse .= ' '.$address->adresseEtr->ville;
      $adresse .= "\n";
      $adresse .= $address->adresseEtr->etat."\n";
      $adresse .= $address->adresseEtr->pays."\n";
    } else {
      $adresse = FALSE;
    }

    return $adresse;
  }

482
  protected function checkValidite (SimpleXMLElement $object, DateTime $now)
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
  {
    if ($object->dateDebutValidite) {
      $dateDebutValidite = new DateTime($object->dateDebutValidite);
      if ($dateDebutValidite >= $now) {
        // Object is not valid yet, skip it
        return FALSE;
      }
    }
    if ($object->dateFinValidite) {
      $dateFinValidite = new DateTime($object->dateFinValidite);
      if ($dateFinValidite < $now) {
        // Object is not valid anymore, skip it
        return FALSE;
      }
    }
    return TRUE;
  }

501
  protected function getUUIDFromReferenceCroisee ($identifiantApplication, $referenceCroisee)
502
503
504
505
506
507
508
509
510
511
  {
    foreach ($referenceCroisee->identifiantsExternes as $ref) {
      if ($ref->identifiantApplication == $identifiantApplication) {
        return $ref->identifiantExterne;
      }
    }

    return '';
  }

512
  public static function genUUID ()
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
  {
    //UUID v4
    return sprintf(
      '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
      // 32 bits for "time_low"
      mt_rand(0, 0xffff), mt_rand(0, 0xffff),
      // 16 bits for "time_mid"
      mt_rand(0, 0xffff),
      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 4
      mt_rand(0, 0x0fff) | 0x4000,
      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      mt_rand(0, 0x3fff) | 0x8000,
      // 48 bits for "node"
      mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
  }
}