synchronizationScript.php 20.8 KB
Newer Older
1
2
3
4
5
6
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
<?php

/**
 * Copyright Maarch since 2008 under licence GPLv3.
 * See LICENCE.txt file at the root folder for more details.
 * This file is part of Maarch software.
 *
 */

/**
 * @brief Synchronization Script
 * @author dev@maarch.org
 */

chdir('../..');

require 'vendor/autoload.php';

$customId = null;
if (!empty($argv[1]) && $argv[1] == '--customId' && !empty($argv[2])) {
    $customId = $argv[2];
}

$xmlfile = initialize($customId);
$synchronizeUsers = false;
if (!empty($xmlfile->synchronizeUsers) && (string)$xmlfile->synchronizeUsers == 'true') {
    $synchronizeUsers = true;
}
$synchronizeEntities = false;
if (!empty($xmlfile->synchronizeEntities) && (string)$xmlfile->synchronizeEntities == 'true') {
    $synchronizeEntities = true;
}

if ($synchronizeUsers) {
35
    $maarchUsers = \User\models\UserModel::get(['select' => ['id', 'user_id', 'firstname', 'lastname', 'phone', 'mail', 'status', 'mode']]);
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    $ldapUsers = getUsersEntries($xmlfile);
    if (!empty($ldapUsers['errors'])) {
        writeLog(['message' => "[ERROR] {$ldapUsers['errors']}"]);
        $synchronizeUsers = false;
        $ldapUsers = null;
    }
}
if ($synchronizeEntities) {
    $maarchEntities = \Entity\models\EntityModel::get(['select' => ['id', 'entity_id', 'entity_label', 'short_label', 'entity_type', 'parent_entity_id']]);
    $ldapEntities = getEntitiesEntries($xmlfile);
    if (!empty($ldapEntities['errors'])) {
        writeLog(['message' => "[ERROR] {$ldapEntities['errors']}"]);
        $synchronizeEntities = false;
        $ldapEntities = null;
    }
}

if (!empty($ldapUsers)) {
    foreach ($ldapUsers as $key => $ldapUser) {
        if (!empty($ldapUser['entityId'])) {
            if (!empty($ldapEntities)) {
                foreach ($ldapEntities as $ldapEntity) {
                    if ($ldapEntity['dn'] == $ldapUser['entityId']) {
                        $ldapUsers[$key]['entityId'] = $ldapEntity['entity_id'];
                        break;
                    }
                }
            } else {
                $ldapUsers[$key]['entityId'] = null;
            }
        }
    }
}

if ($synchronizeUsers) {
    synchronizeUsers($ldapUsers, $maarchUsers);
}
if ($synchronizeEntities) {
    synchronizeEntities($ldapEntities, $maarchEntities);
}

function initialize($customId)
{
    \SrcCore\models\DatabasePDO::reset();
    new \SrcCore\models\DatabasePDO(['customId' => $customId]);


    $path = 'modules/ldap/xml/config.xml';
    if (!empty($customId) && is_file("custom/{$customId}/{$path}")) {
        $path = "custom/{$customId}/{$path}";
    }
    if (!is_file($path)) {
        writeLog(['message' => "[ERROR] Ldap configuration file is missing"]);
        exit();
    }
    $xmlfile = simplexml_load_file($path);
    if (empty($xmlfile) || empty($xmlfile->config->ldap)) {
        writeLog(['message' => "[ERROR] No ldap configurations"]);
        exit();
    }
96
    if (empty((string)$xmlfile->userWS) || empty((string)$xmlfile->passwordWS)) {
97
98
99
        writeLog(['message' => "[ERROR] Rest user informations are missing"]);
        exit();
    }
100
101
    $GLOBALS['user'] = (string)$xmlfile->userWS;
    $GLOBALS['password'] = (string)$xmlfile->passwordWS;
102

103
    $path = 'config/config.json';
104
    if (!empty($customId)) {
105
        $path = "custom/{$customId}/config/config.json";
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    }
    $file = file_get_contents($path);
    $file = json_decode($file, true);
    if (empty($file['config']['maarchUrl'])) {
        writeLog(['message' => "[ERROR] Tag maarchUrl is missing in config.json"]);
        exit();
    }
    $GLOBALS['maarchUrl'] = $file['config']['maarchUrl'];

    return $xmlfile;
}

function getUsersEntries($xmlfile)
{
    $domain = (string)$xmlfile->config->ldap->domain;
    $ssl = (string)$xmlfile->config->ldap->ssl;
    $uri = ($ssl == 'true' ? "LDAPS://{$domain}" : $domain);
123
124
    $prefix = (string)$xmlfile->config->ldap->prefix_login;
    $suffix = (string)$xmlfile->config->ldap->suffix_login;
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

    $login = (string)$xmlfile->config->ldap->login_admin;
    $password = (string)$xmlfile->config->ldap->pass;

    if (empty($xmlfile->mapping->user->user_id)) {
        return ['errors' => 'No mapping configurations (user_id)'];
    }
    $mapping = [
        'user_id'       => (string)$xmlfile->mapping->user->user_id,
        'firstname'     => (string)$xmlfile->mapping->user->firstname,
        'lastname'      => (string)$xmlfile->mapping->user->lastname,
        'phone'         => (string)$xmlfile->mapping->user->phone,
        'mail'          => (string)$xmlfile->mapping->user->mail,
        'entityId'      => (string)$xmlfile->mapping->user->user_entity ?? null
    ];
    $defaultEntity = (string)$xmlfile->mapping->user->defaultEntity ?? null;

    foreach ($xmlfile->filter->dn as $valueDN) {
        if ((string)$valueDN['type'] == 'users') {
            $dn = (string)$valueDN['id'];
145
            $filters = empty((string)$valueDN->user) ? null : (string)$valueDN->user;
146
147
148
149
150
151
152
153
154
155
156
157
158
159
        }
    }
    if (empty($dn)) {
        return ['errors' => 'No DN found'];
    }

    $ldap = @ldap_connect($uri);
    if ($ldap === false) {
        return ['errors' => 'Ldap connect failed : uri is maybe wrong'];
    }
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, 10);

160
161
162
163
    $ldapLogin = (!empty($prefix) ? $prefix . '\\' . $login : $login);
    $ldapLogin = (!empty($suffix) ? $ldapLogin . $suffix : $ldapLogin);

    $authenticated = @ldap_bind($ldap, $ldapLogin, $password);
164
165
166
167
    if (!$authenticated) {
        return ['errors' => 'Ldap bind failed : Authentication failed'];
    }

168
    $search = @ldap_search($ldap, $dn, ($filters ?? 'cn=*'));
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
197
198
199
200
201
202
203
204
205
206
207
208
209
    if ($search === false) {
        return ['errors' => 'Ldap search failed : ' . ldap_error($ldap)];
    }
    $entries = mb_convert_encoding(ldap_get_entries($ldap, $search), 'utf-8');

    $ldapEntries = [];
    foreach ($entries as $key => $entry) {
        if (!is_int($key)) {
            continue;
        }
        $user = [
            'defaultEntity' => $defaultEntity
        ];
        foreach ($mapping as $mcField => $ldapField) {
            if (empty($ldapField)) {
                continue;
            }
            if (isset($entry[$ldapField]) && is_array($entry[$ldapField])) {
                if (count($entry[$ldapField]) === 1 || (isset($entry[$ldapField]['count']) && $entry[$ldapField]['count'] === 1)) {
                    $user[$mcField] = $entry[$ldapField][0];
                } elseif (count($entry[$ldapField]) > 1) {
                    $user[$mcField] = $entry[$ldapField];
                } else {
                    $user[$mcField] = '';
                }
            } else {
                $user[$mcField] = '';
            }
        }
        $ldapEntries[$key] = $user;
    }
    ldap_unbind($ldap);

    return $ldapEntries;
}

function getEntitiesEntries($xmlfile)
{
    $domain = (string)$xmlfile->config->ldap->domain;
    $ssl = (string)$xmlfile->config->ldap->ssl;
    $uri = ($ssl == 'true' ? "LDAPS://{$domain}" : $domain);
210
211
    $prefix = (string)$xmlfile->config->ldap->prefix_login;
    $suffix = (string)$xmlfile->config->ldap->suffix_login;
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

    $login = (string)$xmlfile->config->ldap->login_admin;
    $password = (string)$xmlfile->config->ldap->pass;

    if (empty($xmlfile->mapping->entity->entity_id)) {
        return ['errors' => 'No mapping configurations (entity_id)'];
    }
    $mapping = [
        'entity_id'         => (string)$xmlfile->mapping->entity->entity_id,
        'entity_label'      => (string)$xmlfile->mapping->entity->entity_label,
        'parent_entity_id'  => (string)$xmlfile->mapping->entity->parent_entity_id
    ];

    foreach ($xmlfile->filter->dn as $valueDN) {
        if ((string)$valueDN['type'] == 'entities') {
            $dn = (string)$valueDN['id'];
228
            $filters = empty((string)$valueDN->user) ? null : (string)$valueDN->user;
229
230
231
232
233
234
235
236
237
238
239
240
241
242
        }
    }
    if (empty($dn)) {
        return ['errors' => 'No DN found'];
    }

    $ldap = @ldap_connect($uri);
    if ($ldap === false) {
        return ['errors' => 'Ldap connect failed : uri is maybe wrong'];
    }
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, 10);

243
244
245
246
    $ldapLogin = (!empty($prefix) ? $prefix . '\\' . $login : $login);
    $ldapLogin = (!empty($suffix) ? $ldapLogin . $suffix : $ldapLogin);

    $authenticated = @ldap_bind($ldap, $ldapLogin, $password);
247
248
249
250
    if (!$authenticated) {
        return ['errors' => 'Ldap bind failed : Authentication failed'];
    }

251
    $search = ldap_search($ldap, $dn, ($filters ?? 'cn=*'));
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
    $entries = mb_convert_encoding(ldap_get_entries($ldap, $search), 'utf-8');

    $ldapEntries = [];
    foreach ($entries as $key => $entry) {
        if (!is_int($key)) {
            continue;
        }
        $entity = ['dn' => $entry['dn']];

        foreach ($mapping as $mcField => $ldapField) {
            if (empty($ldapField)) {
                continue;
            }
            if (isset($entry[$ldapField]) && is_array($entry[$ldapField])) {
                if (count($entry[$ldapField]) === 1 || (isset($entry[$ldapField]['count']) && $entry[$ldapField]['count'] === 1)) {
                    $entity[$mcField] = $entry[$ldapField][0];
                } elseif (count($entry[$ldapField]) > 1) {
                    $entity[$mcField] = $entry[$ldapField];
                } else {
                    $entity[$mcField] = '';
                }
            } else {
                $entity[$mcField] = '';
            }
        }
        $ldapEntries[$key] = $entity;
    }
    ldap_unbind($ldap);

    if (!empty($mapping['parent_entity_id'])) {
        foreach ($ldapEntries as $key => $entry) {
            if (empty($entry['parent_entity_id'])) {
                unset($ldapEntries[$key]['parent_entity_id']);
                continue;
            }
            foreach ($ldapEntries as $parentKey => $parentEntry) {
                if ($entry['parent_entity_id'] === $parentEntry['dn']) {
                    $ldapEntries[$key]['parent_entity_id'] = $parentEntry['entity_id'];
                    break;
                }
            }
        }
    }

    return $ldapEntries;
}

function synchronizeUsers(array $ldapUsers, array $maarchUsers)
{
    $maarchUsersLogin = [];
    foreach ($maarchUsers as $maarchUser) {
        $maarchUsersLogin[$maarchUser['user_id']] = $maarchUser;
    }
    $ldapUsersLogin = [];
    foreach ($ldapUsers as $ldapUser) {
        $ldapUsersLogin[$ldapUser['user_id']] = $ldapUser;
    }

    foreach ($ldapUsers as $user) {
        $user['userId'] = $user['user_id'];
312
        if (!empty($maarchUsersLogin[$user['userId']]) && $maarchUsersLogin[$user['userId']]['status'] != 'DEL') {
313
            if ($maarchUsersLogin[$user['userId']]['status'] == 'SPD') {
314
                $curlResponse = \SrcCore\models\CurlModel::exec([
315
316
317
318
319
320
321
                    'url'           => rtrim($GLOBALS['maarchUrl'], '/') . '/rest/users/' . $maarchUsersLogin[$user['user_id']]['id'] . '/status',
                    'basicAuth'     => ['user' => $GLOBALS['user'], 'password' => $GLOBALS['password']],
                    'headers'       => ['content-type:application/json'],
                    'method'        => 'PUT',
                    'body'          => json_encode(['status' => 'OK'])
                ]);
                if ($curlResponse['code'] != 200) {
322
323
                    writeLog(['message' => "[ERROR] Update user [{$maarchUsersLogin[$user['user_id']]['user_id']}] status failed : {$curlResponse['response']['errors']}"]);
                    continue;
324
325
326
327
328
329
330
                }
            }
            if ($user['firstname'] != $maarchUsersLogin[$user['user_id']]['firstname']
                || $user['lastname'] != $maarchUsersLogin[$user['user_id']]['lastname']
                || $user['phone'] != $maarchUsersLogin[$user['user_id']]['phone']
                || $user['mail'] != $maarchUsersLogin[$user['user_id']]['mail']
            ) {
331
                $curlResponse = \SrcCore\models\CurlModel::exec([
332
333
334
335
336
337
338
                    'url'           => rtrim($GLOBALS['maarchUrl'], '/') . '/rest/users/' . $maarchUsersLogin[$user['user_id']]['id'],
                    'basicAuth'     => ['user' => $GLOBALS['user'], 'password' => $GLOBALS['password']],
                    'headers'       => ['content-type:application/json'],
                    'method'        => 'PUT',
                    'body'          => json_encode($user)
                ]);
                if ($curlResponse['code'] != 204) {
339
340
                    writeLog(['message' => "[ERROR] Update user [{$maarchUsersLogin[$user['user_id']]['user_id']}] failed : {$curlResponse['response']['errors']}"]);
                    continue;
341
                }
342
                userAddEntity($maarchUsersLogin[$user['user_id']]['id'], $user);
343
344
            }
        } else {
345
346
347
348
349
350
            $control = controlUser($user);
            if (!empty($control['errors'])) {
                writeLog(['message' => "[ERROR] Control create user [{$maarchUsersLogin[$user['user_id']]['user_id']}] failed : {$control['errors']}"]);
                continue;
            }

351
            $curlResponse = \SrcCore\models\CurlModel::exec([
352
353
354
355
356
357
358
                'url'           => rtrim($GLOBALS['maarchUrl'], '/') . '/rest/users',
                'basicAuth'     => ['user' => $GLOBALS['user'], 'password' => $GLOBALS['password']],
                'headers'       => ['content-type:application/json'],
                'method'        => 'POST',
                'body'          => json_encode($user)
            ]);
            if ($curlResponse['code'] != 200) {
359
360
                writeLog(['message' => "[ERROR] Create user [{$maarchUsersLogin[$user['user_id']]['user_id']}] failed : {$curlResponse['response']['errors']}"]);
                continue;
361
362
            }

363
            userAddEntity($curlResponse['response']['id'], $user);
364
365
366
367
        }
    }

    foreach ($maarchUsers as $user) {
368
        if (empty($ldapUsersLogin[$user['user_id']]) && $user['status'] != 'DEL' && $user['mode'] != 'rest') {
369
            $curlResponse = \SrcCore\models\CurlModel::exec([
370
371
372
373
374
375
                'url'           => rtrim($GLOBALS['maarchUrl'], '/') . '/rest/users/' . $user['id'] . '/suspend',
                'basicAuth'     => ['user' => $GLOBALS['user'], 'password' => $GLOBALS['password']],
                'headers'       => ['content-type:application/json'],
                'method'        => 'PUT'
            ]);
            if ($curlResponse['code'] != 204) {
376
                writeLog(['message' => "[ERROR] Suspend user [{$maarchUsersLogin[$user['user_id']]['user_id']}] failed  : {$curlResponse['response']['errors']}"]);
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
            }
        }
    }

    return true;
}

function synchronizeEntities(array $ldapEntities, array $maarchEntities)
{
    $maarchEntitiesId = [];
    foreach ($maarchEntities as $maarchEntity) {
        $maarchEntitiesId[$maarchEntity['entity_id']] = $maarchEntity;
    }
    $ldapEntitiesId = [];
    foreach ($ldapEntities as $ldapEntity) {
        $ldapEntitiesId[$ldapEntity['entity_id']] = $ldapEntity;
    }

    foreach ($ldapEntities as $entity) {
        if (!empty($maarchEntitiesId[$entity['entity_id']])) {
            if ($entity['entity_label'] != $maarchEntitiesId[$entity['entity_id']]['entity_label']
                || $entity['parent_entity_id'] != $maarchEntitiesId[$entity['entity_id']]['parent_entity_id']
            ) {
                $entity['short_label'] = $maarchEntitiesId[$entity['entity_id']]['short_label'];
                $entity['entity_type'] = $maarchEntitiesId[$entity['entity_id']]['entity_type'];
402
                $curlResponse = \SrcCore\models\CurlModel::exec([
403
404
405
406
407
408
409
410
411
412
413
414
415
                    'url'           => rtrim($GLOBALS['maarchUrl'], '/') . '/rest/entities/' . $entity['entity_id'],
                    'basicAuth'     => ['user' => $GLOBALS['user'], 'password' => $GLOBALS['password']],
                    'headers'       => ['content-type:application/json'],
                    'method'        => 'PUT',
                    'body'          => json_encode($entity)
                ]);
                if ($curlResponse['code'] != 200) {
                    writeLog(['message' => "[ERROR] Update entity failed : {$curlResponse['response']['errors']}"]);
                }
            }
        } else {
            $entity['short_label'] = $entity['entity_label'];
            $entity['entity_type'] = 'Service';
416
            $curlResponse = \SrcCore\models\CurlModel::exec([
417
418
419
420
421
422
423
424
425
426
427
428
429
430
                'url'           => rtrim($GLOBALS['maarchUrl'], '/') . '/rest/entities',
                'basicAuth'     => ['user' => $GLOBALS['user'], 'password' => $GLOBALS['password']],
                'headers'       => ['content-type:application/json'],
                'method'        => 'POST',
                'body'          => json_encode($entity)
            ]);
            if ($curlResponse['code'] != 200) {
                writeLog(['message' => "[ERROR] Create entity failed : {$curlResponse['response']['errors']}"]);
            }
        }
    }

    foreach ($maarchEntities as $entity) {
        if (empty($ldapEntitiesId[$entity['entity_id']])) {
431
            $curlResponse = \SrcCore\models\CurlModel::exec([
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
                'url'           => rtrim($GLOBALS['maarchUrl'], '/') . '/rest/entities/' . $entity['entity_id'],
                'basicAuth'     => ['user' => $GLOBALS['user'], 'password' => $GLOBALS['password']],
                'headers'       => ['content-type:application/json'],
                'method'        => 'DELETE'
            ]);
            if ($curlResponse['code'] != 200) {
                writeLog(['message' => "[ERROR] Delete entity failed : {$curlResponse['response']['errors']}"]);
            }
        }
    }

    return true;
}

function writeLog(array $args)
{
    if (strpos($args['message'], '[ERROR]') === 0) {
        \SrcCore\controllers\LogsController::add([
            'isTech'    => true,
            'moduleId'  => 'synchronizationLddap',
            'level'     => 'ERROR',
            'tableName' => '',
            'recordId'  => 'synchronizationLddap',
            'eventType' => 'synchronizationLddap',
            'eventId'   => $args['message']
        ]);
    } else {
        \SrcCore\controllers\LogsController::add([
            'isTech'    => true,
            'moduleId'  => 'synchronizationLddap',
            'level'     => 'INFO',
            'tableName' => '',
            'recordId'  => 'synchronizationLddap',
            'eventType' => 'synchronizationLddap',
            'eventId'   => $args['message']
        ]);
    }
}
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486

function controlUser(array $user)
{
    if (!\Respect\Validation\Validator::stringType()->length(1, 128)->notEmpty()->validate($user['userId'] ?? null) || !preg_match("/^[\w.@-]*$/", $user['userId'])) {
        return ['errors' => 'Body userId is empty, not a string or not valid'];
    } elseif (!\Respect\Validation\Validator::stringType()->length(1, 255)->notEmpty()->validate($user['firstname'] ?? null)) {
        return ['errors' => 'Body firstname is empty or not a string'];
    } elseif (!\Respect\Validation\Validator::stringType()->length(1, 255)->notEmpty()->validate($user['lastname'] ?? null)) {
        return ['errors' => 'Body lastname is empty or not a string'];
    } elseif (!\Respect\Validation\Validator::stringType()->length(1, 255)->notEmpty()->validate($user['mail'] ?? null) || !filter_var($user['mail'], FILTER_VALIDATE_EMAIL)) {
        return ['errors' => 'Body mail is empty or not valid'];
    } elseif (!empty($user['phone']) && (!preg_match("/\+?((|\ |\.|\(|\)|\-)?(\d)*)*\d$/", $user['phone']) || !\Respect\Validation\Validator::stringType()->length(0, 32)->validate($user['phone'] ?? ''))) {
        return ['errors' => 'Body phone is not valid'];
    }

    return true;
}
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519

function userAddEntity($userId, $user)
{
    $entityId = null;
    if (!empty($user['entityId'])) {
        $entityExists = \Entity\models\EntityModel::getByEntityId(['entityId' => $user['entityId'], 'select' => [1]]);
    }
    if (!empty($user['defaultEntity'])) {
        $defaultEntityExists = \Entity\models\EntityModel::getByEntityId(['entityId' => $user['defaultEntity'], 'select' => [1]]);
    }

    if(!empty($entityExists)) {
        $entityId = $user['entityId'];
    } elseif (!empty($defaultEntityExists)) {
        $entityId = $user['defaultEntity'];
    }

    if(!empty($entityId)) {
        $curlResponse = \SrcCore\models\CurlModel::exec([
            'url'           => rtrim($GLOBALS['maarchUrl'], '/') . '/rest/users/' . $userId . '/entities',
            'basicAuth'     => ['user' => $GLOBALS['user'], 'password' => $GLOBALS['password']],
            'headers'       => ['content-type:application/json'],
            'method'        => 'POST',
            'body'          => json_encode(['entityId' => $entityId])
        ]);
        if ($curlResponse['code'] != 200) {
            writeLog(['message' => "[ERROR] Add entity to user failed : {$curlResponse['response']['errors']}"]);
        }
    }
    else{
        writeLog(['message' => "[ERROR] Add entity to user failed : {Entity not found}"]);
    }
}