LdapConnectionsTable.php 50.3 KB
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 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 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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 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 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 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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 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 364 365 366 367 368 369 370 371 372 373 374 375 376 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 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 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 482 483 484 485 486 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 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 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 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 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 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 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 847 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 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Core\Exception\Exception;
use App\Model\Entity\User;

// Idem Controller/UsersController
const DEFAULT_AUTH_TYPE = 'uid';

// On active systématiquement le cache ldap (table bd users) ou pas ? (activation forcée)
// - OUI => le CACHE LDAP (table users) est systématiquement utilisé
const LDAP_CACHE_ALWAYS_ON = true;
// - NON => le CACHE LDAP (table users) n'est utilisé QUE si l'option ldap_cached est activée dans la config
//const LDAP_CACHE_ALWAYS_ON = false;

// DEBUG temporaire, uniquement pour ce fichier (module level)
//const DEBUG = true;
const DEBUG = false;


class LdapConnectionsTable extends AppTable
{
    
    private $DEBUG_MODE; // read from config

    private $authenticationType;

    // (EP 23/5/19) Optimisation: 
    // Les utilisateurs sont stockés dans un cache (BD)
    // pour limiter les accès au LDAP
    private $LDAP_CACHED = FALSE;
    // Max time for ldap cache validity (in minutes) : 60 = 1h
    private $LDAP_CACHE_VALIDITY_DURATION = 2;
    
    public $useTable = false;

    private $host;

    private $port;

    private $baseDn;


    private $filter;
    
    /*MCM*/
    // EP
    //private $anonymous;
    private $ldap_authentified;
    private $bindDn;
    private $bindPass;
    /* fin MCM*/

    private $LDAP_USED = TRUE;
    
    private $fakeLDAPUsers = [];
    
    // print only if debug mode ON
    private function mydebugmsg($arg, $stop = false)
    {
        if ($this->DEBUG_MODE) {
            //Configure::write('debug', true);
            debug($arg);
            if ($stop) exit();
        }
    }
    
    public function __construct()
    {
        parent::__construct();
    }

    // EP
    /*
    public function useFakeLdap()
    {
        return ! $this->useLdap();
    }

    public function useLdap()
    {
        $this->_checkConfiguration();
        return $this->LDAP_USED;
    }
    */

    // LDAP format ==> DB format
    // @param: array $user (LDAP-like formatted)
    // @return: object(App\Model\Entity\User)
    private function _getLDAPuserFormattedAsDB($user_from_LDAP) {
        
        /* (INPUT) Voici le format d'un user du LDAP :
        [
            'sn' => [
        		(int) 0 => 'Pallier'
        	],
        	'mail' => [
        		(int) 0 => 'Etienne.Pallier@irap.omp.eu'
        	],
        	'givenname' => [
        		(int) 0 => 'Etienne'
        	],
        	'uid' => [
        		(int) 0 => 'epallier'
        	],
        	'userpassword' => [
        		(int) 0 => '<mot de passe crypté>'
        	]
        ]
        */
        
        /* (OUTPUT) Voici le format d'un user de la table users (BD) ( object(App\Model\Entity\User) ) :
        // - Champs de la table :
        'id' => (int) 2,
        'nom' => 'Pallier Etienne',
        'username' => 'epallier',
        'email' => 'Etienne.Pallier@irap.omp.eu',
        'role' => 'Super Administrateur',
        'groupes_metier_id' => (int) 3,
        'password' => 'pass crypté...',
        'groupes_thematique_id' => null,
        'sur_categorie_id' => null,
        
        // - Champs ajoutés par CakePhp3:
        '[new]' => false,
        '[accessible]' => [
        '*' => true,
        'id' => false
        ],
        '[dirty]' => [],
        '[original]' => [],
        '[virtual]' => [],
        '[hasErrors]' => false,
        '[errors]' => [],
        '[invalid]' => [],
        '[repository]' => 'Users'
        */
        
        $usersTable = TableRegistry::getTableLocator()->get('Users');
        
        $user = $usersTable->newEntity();
        $user->nom = $user_from_LDAP['sn'][0].' '.$user_from_LDAP['givenname'][0];
        //$user->username = $user_from_LDAP['uid'];
        $user->username = $user_from_LDAP[$this->authenticationType][0];
        $user->email = isset($user_from_LDAP['mail']) ? $user_from_LDAP['mail'][0] : "NO_MAIL";
        // Par defaut, role = UTILISATEUR
        $user->role = 'Utilisateur';
        /*
         * (EP 5/6/19 on ne fait plus ça car le ldap ne retourne pas les passwords)
        // C'est la version "cryptée" qui doit etre stockée
        $user->password = $user_from_LDAP['userpassword'][0];
        */
        return $user;
        
    }
    
    private function _getDBusersFormattedAsLDAP($usersfromDB) {
        $usersFormattedAsLDAP = [];
        foreach ($usersfromDB as $userfromDB) $usersFormattedAsLDAP[] = $this->_getDBuserFormattedAsLDAP($userfromDB);
        $usersFormattedAsLDAP['count'] = sizeof($usersFormattedAsLDAP);
        //$this->mydebugmsg("count : ".$usersFormattedAsLDAP['count']);
        return $usersFormattedAsLDAP;
    }
    
    
    // DB format ==> LDAP format
    private function _getDBuserFormattedAsLDAP($user) {
        $names = explode(" ", $user['nom']);
        $givenName = isset($names[1]) ? $names[1] : " ";
        return [
            // Nom
            'sn' => [
                $names[0]
            ],
            // Email
            'mail' => [
                $user['email']
            ],
            // Pnom
            'givenname' => [
                $givenName
            ],
            // Login ("uid" for IRAP, "samaccountname" for CRAL)
            $this->authenticationType => [
                $user['username']
            ],
            // Pass
            'userpassword' => [
                $user['password']
            ]
        ];
    }
    private function _getFakeDBuserFormattedAsLDAP($user) {
        return [
            // Nom
            'sn' => [
                $user['sn']
            ],
            // Email
            'mail' => [
                $user['mail']
            ],
            // Pnom
            'givenname' => [
                $user['givenname']
            ],
            // Login ("uid" for IRAP, "samaccountname" for CRAL)
            //$this->authenticationType => [
            /*
            'uid' => [
                $user['uid']
            ],
            */
            DEFAULT_AUTH_TYPE => [
                $user[DEFAULT_AUTH_TYPE]    
            ],
            // Pass
            'userpassword' => [
                $user['userpassword']
            ]
        ];
    }
    
    private function _buildFakeLdapUsers()
    {
        return $this->_buildFakeLdapUsersFromDB();
    }

    // return users list from DB table fakeldapusers, formatted as LDAP
    private function _buildFakeLdapUsersFromDB()
    {
        //NEW
        //$users = TableRegistry::getTableLocator()->get('Users')->find();
        $users = TableRegistry::getTableLocator()->get('Fakeldapusers')->find();
        
        $ldapUsers = [];
        //$ldapUsers = $users->toArray();
        
        foreach ($users as $user) {
            //debug($user);
            /* Voici le format d'un user de la table users (BD)

            // - Champs de la table :
        	'id' => (int) 2,
        	'nom' => 'Pallier Etienne',
        	'username' => 'epallier',
        	'email' => 'Etienne.Pallier@irap.omp.eu',
        	'role' => 'Super Administrateur',
        	'groupes_metier_id' => (int) 3,
        	'password' => 'pass crypté...',
        	'groupes_thematique_id' => null,
        	'sur_categorie_id' => null,

            // - Champs ajoutés par CakePhp3:
        	'[new]' => false,
        	'[accessible]' => [
        		'*' => true,
        		'id' => false
        	],
        	'[dirty]' => [],
        	'[original]' => [],
        	'[virtual]' => [],
        	'[hasErrors]' => false,
        	'[errors]' => [],
        	'[invalid]' => [],
        	'[repository]' => 'Users'
        	
             */
            //NEW
            //$ldapUsers[] = $this->_getDBuserFormattedAsLDAP($user);
            $ldapUsers[] = $this->_getFakeDBuserFormattedAsLDAP($user);
            /*
            $names = explode(" ", $user['nom']);
            $givenName = isset($names[1]) ? $names[1] : " ";
            $ldapUsers[] = [
                // Nom
                'sn' => [
                    $names[0]
                ],
                // Email
                'mail' => [
                    $user['email']
                ],
                // Pnom
                'givenname' => [
                    $givenName
                ],
                // Login ("uid" for IRAP, "samaccountname" for CRAL)
                $this->authenticationType => [
                    $user['username']
                ],
                // Pass
                'userpassword' => [
                    $user['password']
                ]
            ];
            */
        }
        
        /* EP (aout 2017)
         * ATTENTION : Utilisateur IMPORTANT.
         * Avec cet utilisateur, on simule un utilisateur qui n'est PAS dans la table utilisateurs
         * Il devrait donc se voir attribuer un role "Utilisateur" sans pour autant que ça soit écrit dans la table !!!
         * login = '_NouvelUtilisateur_username'
         * pass = '_NouvelUtilisateur_password'
         * $prefix = "_NouvelUtilisateur_";
         */
        /* (EP 20210201) : DÉSORMAIS INUTILE 
         * car TOUS les utilisateurs doivent être dans la table users, sinon ils ne peuvent pas se connecter.
         * Avant, on avait besoin de ça car en mode LDAP, la table users ne contenait QUE les users privilégiés
         * et donc un user du ldap pouvait se connecter même s'il n'était pas dans la table users, 
         * et on lui affectait automatiquement un profil "Utilisateur"
         * 
        $ldapUsers[] = [
            'sn' => [
                'UTILISATEUR'
            ],
            'givenname' => [
                'FAKE_LDAP'
            ],
            // 'mail' => [$login.'email'],
            'mail' => [
                'fakeldapuser@domain.fr'
            ],
            // $this->authenticationType => [$prefix.'username'],
            //'uid' => [
            $this->authenticationType => [
                $this->_getTheFakeLdapUser()['login']
            ],
            // $this->authenticationType => ['usere'],
            'userpassword' => [
                $this->_getTheFakeLdapUser()['pass']
            ]
            // 'userpassword' => ['toto'],
        ];
        $ldapUsers[] = [
            'sn' => [
                'SUPERADMIN'
            ],
            'givenname' => [
                'FAKE_LDAP'
            ],
            // 'mail' => [$login.'email'],
            'mail' => [
                'fakeldapuser@domain.fr'
            ],
            // $this->authenticationType => [$prefix.'username'],
            //'uid' => [
            $this->authenticationType => [
                'superadmin'
            ],
            // $this->authenticationType => ['usere'],
            'userpassword' => [
                '$2y$10$LZzpws3oDidBcqO/Fy1RTedLLk3ENTmplny5J7bZ6R1PqFoGOw3Ma'
            ]
            // 'userpassword' => ['toto'],
        ];
        */ 
        
        return $ldapUsers;
    }

    private function _checkAndGetConfiguration()
    {
        $this->configurationsTable = TableRegistry::getTableLocator()->get('Configurations');
        $this->CONF = $this->configurationsTable
			->find()
            ->where(['id =' => 1])
            ->first();
        
            // Activation forcée de l'option ldap_cached si LDAP_CACHE_ALWAYS_ON
        // (EP) Ca résoud un bug dû au fait que des infos sont cherchées dans la table users alors que le user n'y est pas...
		if (LDAP_CACHE_ALWAYS_ON) $this->CONF->ldap_cached = true;
        $config = $this->CONF;
		
        $this->usersTable = TableRegistry::getTableLocator()->get('Users');
        
        $this->DEBUG_MODE = $config->mode_debug;
        $this->LDAP_USED = $config->ldap_used;
        
        // (1) Mode "local" (sans ldap, ou FAKE ldap)
        if (! $this->LDAP_USED) {
            // Seulement pour tester le mode ldap_cached en mode FAKE LDAP:
            //$this->CONF->ldap_cached = TRUE;
            
            // (EP 202102) bugfix, en mode fakldap, on est toujours en 'uid' 
            //$this->authenticationType = $config->ldap_authenticationType;
            $this->authenticationType = DEFAULT_AUTH_TYPE;
            if (empty($this->fakeLDAPUsers))
                $this->fakeLDAPUsers = $this->_buildFakeLdapUsers();
            return true;
        }
        // debug($this->fakeLDAPUsers);        
        
        // (2) Mode "LDAP" (avec ldap)
        if (! empty($config->ldap_host) && ! empty($config->ldap_port) && ! empty($config->ldap_baseDn) && ! empty($config->ldap_authenticationType) && ! empty($config->ldap_filter)) {
            $this->host = $config->ldap_host;
            $this->port = $config->ldap_port;
            $this->baseDn = $config->ldap_baseDn;
            $this->filter = $config->ldap_filter;
            $this->authenticationType = $config->ldap_authenticationType;
            $this->ldap_authentified = $config->ldap_authentified;
            $this->bindDn = $config->ldap_bindDn;
            $this->bindPass = $config->ldap_bindPass;
            
            return true;
        }

        // (3) Si on est toujours là, c'est pas normal => EXCEPTION
        $ldapConfig = $config->toArray();
        throw new Exception('The ldap configuration is not valid : <br />
			<ul>
				<li>host = ' . @$ldapConfig['host'] . '</li>
				<li>port = ' . @$ldapConfig['port'] . '</li>
				<li>baseDn = ' . @$ldapConfig['baseDn'] . '</li>
				<li>filter = ' . @$ldapConfig['filter'] . '</li>
				<li>authenticationType = ' . @$ldapConfig['authenticationType'] . '</li>
			</ul>');
    }
    
    
    

    
    
    
    // @return ldap users from DB users table
    private function _getAllUsersFromDB($do_update=false) {
        // (EP202102) inutile puisque on fait déjà ça à la connexion (login)
        if ($do_update) $this->_updateUsersCacheIfNeeded();
        return $this->usersTable->find();
    }

    
    private function _getAllUsersFromLDAP() {
        return $this->LDAP_USED ? $this->_ldapSearch($this->filter, []) : $this->fakeLDAPUsers;
    }

    /**
     * @return $users_fetched or FALSE
     */
    // REAL or FAKE LDAP
    public function getAllLdapUsers()
    {
        if (! $this->_checkAndGetConfiguration()) return FALSE;
        
        // By default, nothing found, ERROR
        $users_fetched = FALSE;
        
        // LDAP optimized (cached)
        if ($this->CONF->ldap_cached) {
            //TODO:
            // Les 3 types de LDAP (cache, real, et fake) doivent etre 3 objets ayant exactement les MEMES methodes
            // Par defaut, $this-> doit pointer vers le REAL ldap, les 2 autres sont accessibles via $this->cache-> et $this->fake->
            // $this->cache->_getAllLdapUsers(); // envoyés directement dans le bon format
            $users_fetched = $this->_getAllUsersFromDB();
            $users_fetched = $this->_getDBusersFormattedAsLDAP($users_fetched);
        }
        
        // LDAP direct (no optimization)
        else {
            //try {
                $users_fetched = $this->_getAllUsersFromLDAP();
                // $from = $this->LDAP_USED ? $this : $this->fake
                // return $from->_getllLdapUsers();
                // Noter que $user_fetched peut etre egal a FALSE (si rien trouvé)
                //return $users_fetched;
            //}
            //catch (Exception $e) {}
        }
        
        return $users_fetched;
    }
    
        
    public function getAuthenticationType()
    {
        return $this->authenticationType;
    }

    // EP added
    public function getFakeLdapUser($login)
    {
        foreach ($this->fakeLDAPUsers as $user) {
            //debug($login);
            //debug($user[DEFAULT_AUTH_TYPE][0]);
            //if ($login == $user[$this->authenticationType][0])
            if ($login == $user[DEFAULT_AUTH_TYPE][0])
                return $user;
        }
        return FALSE;
    }

    /**
     * Return a list of Users with key = username => value = [login, email]
     */
    public function getUsersLoginAndEmail() {
        $usersWithNameAndEmail = [];
        // Get all users (with ALL their attributes)
        $u = $this->getAllLdapUsers();
        // Sort users
        //sort($u);
        //debug($u);
        $this->mydebugmsg("ldap users 0 and 1:");
        $this->mydebugmsg($u[0]);
        //$this->mydebugmsg($u[1]);
        // (EP) Refactorisation pour éviter code redondant du "bon vieux" temps des stagiaires...
        // Il suffit souvent de réfléchir un peu pour résumer 10 lignes en 1 seule...
        if ($this->LDAP_USED) $this->mydebugmsg("total count is : ".$u['count']); // 440 for IRAP 6/6/19 (LDAP direct), 441 (LDAP cached because 1 old user to be deleted = imoro)
        //$this->mydebugmsg($u);
        $nb_users = $this->LDAP_USED ? $u['count'] : sizeof($u)-1;
        for ($i = 0; $i < $nb_users; $i ++) {
            // $utilisateurs["Pallier Etienne"] = ["email"]
            ////$usersWithNameAndEmail[ $u[$i]['sn'][0].' '.$u[$i]['givenname'][0] ] = $u[$i]['mail'][0];
            $email = isset($u[$i]['mail']) ? $u[$i]['mail'][0] : "NO_MAIL";
            $usersWithNameAndEmail[ $u[$i]['sn'][0].' '.$u[$i]['givenname'][0] ] = array(
                //"login" => $u[$i]['uid'][0] // (IRAP)
                //"login" => $u[$i]['samaccountname'][0] // CRAL
                "login" => $u[$i][$this->authenticationType][0],
                "email" => $email
            ); 
        }
        // Sort users (without modifying the keys, don't use sort() but asort() !!!!!!!!!!!!!)
        ksort($usersWithNameAndEmail);
        //debug($usersWithNameAndEmail);
        return $usersWithNameAndEmail;
    }
    
    /**
     * Return a list of Users with key = username & value = username
     */
    public function getListUsers()
    {
        $utilisateurs = [];
        
        // Get all users (with ALL their attributes)
        $u = $this->getAllLdapUsers();
        // Sort users
        //sort($u);
        //debug($u);
        
        // (EP) Refactorisation pour éviter code redondant ci-dessous, c'était pourtant pas compliqué, poil dans la main...
        $nb_users = $this->LDAP_USED ? $u['count'] : sizeof($u)-1;
        // $utilisateurs["Pallier Etienne"] = "Pallier Etienne"
        for ($i = 0; $i < $nb_users; $i ++)
            $utilisateurs[ $u[$i]['sn'][0].' '.$u[$i]['givenname'][0] ] = $u[$i]['sn'][0].' '.$u[$i]['givenname'][0];
		//debug($utilisateurs);
		// Sort users (without modifying the keys, don't use sort() but asort() !!!!!!!!!!!!!)
		ksort($utilisateurs);
		//debug($utilisateurs);
		return $utilisateurs;
    }
    
    
    /**
     * Return a list of login of Users with key = username & value = login
     */
    public function getListLoginUsers()
    {
        $u = $this->getAllLdapUsers();
        $utilisateurs = [];
        
        if ($this->LDAP_USED) {
            for ($i = 0; $i < $u['count']; $i ++) {
                $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = $u[$i][$this->authenticationType][0];
            }
        } else {
            for ($i = 0; $i < sizeof($u) - 1; $i ++) {
                $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = $u[$i][$this->authenticationType][0];
            }
        }
        
        return $utilisateurs;
    }

    /**
     * Return a list of mail of Users with key = username & value = mail
     */
    public function getListEmailUsers()
    {
        $u = $this->getAllLdapUsers();
        $utilisateurs = [];
        
        if ($this->LDAP_USED) {
            for ($i = 0; $i < $u['count']; $i ++) {
                if (isset($u[$i]['mail'][0])) {
                    $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = $u[$i]['mail'][0];
                } else {
                    $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = 'N/A';
                }
            }
        } else {
            for ($i = 0; $i < sizeof($u) - 1; $i ++) {
                $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = $u[$i]['mail'][0];
            }
        }
        
        return $utilisateurs;
    }

    /**
     * Return size of list users
    public function getNbUsers()
    {
        $u = $this->getAllLdapUsers();
        
        if ($this->LDAP_USED) {
            $nbUsers = $u['count'];
        } else {
            $nbUsers = sizeof($u) - 1;
        }
        return $nbUsers;
    }
    */

    // Utilisateur du ldap qui n'est pas dans la table utilisateurs
    // => il a donc le role "Utilisateur" PAR DEFAUT
    private function _getTheFakeLdapUser()
    {
        return [
            'login' => '_fake_ldap_user_',
            //'pass' => '_fake_ldap_user_pass'
            'pass' => '$2y$10$Vx8E8VirQGnoLYpn7qqNAO4UhTJMyrUVCzkcy0Obh3ceABuxMxk.q'
        ];
    }
    

    // @return user from DB user table whith login = $userLogin (or NULL)
    //private function _getUserFromDBByLogin) {
    private function _getCachedUserByLogin($userLogin) {
        //debug($userLogin); exit;
        //$ldapUser = TableRegistry::getTableLocator()->get('Users')->find()
        return $this->usersTable->find()
            ->where([
                'username' => $userLogin
            ])
            ->first();
    }

    /**
     * @return boolean
     *  - FALSE if cache is up to date 
     *  - TRUE if cache is expired (outdated or NULL)
     */
    private function _ldapCacheIsExpired() {
        if (is_null($this->CONF->ldap_cache_last_update)) return TRUE;
        
        /* About strtotime("") :
         * - forward slash (/) signifies American M/D/Y formatting => strtotime("11/12/10") 
         * - a dash (-) signifies European D-M-Y => strtotime("11-12-10"))
         * - a period (.) signifies ISO Y.M.D. => strtotime("11.12.10")
         */
        $date_now = date("Y-m-d H:i:s");
        ####$this->mydebugmsg("now :".$date_now);
        $date_now = new \DateTime($date_now);

        $date_cached = $this->CONF->ldap_cache_last_update;
        // Pourquoi j'ai pas les secondes qui s'affichent ???!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        ####$this->mydebugmsg("cached :".$date_cached);
        /* bugfixing $date_cached pour Inventirap (IRAP) (php5 ou vieux mysql ou pb de config ???) :
         * Inventirap affiche l'année sur 2 chiffres : 'cached :05/06/19 15:36'
         * Ma version perso affiche l'année sur 4 chiffres : 'cached :05/06/2019 15:36'
         * => Il faut donc remettre l'année sur 4 chiffres si besoin
         */
        //$date_cached='05/06/19 15:36';
        //$this->mydebugmsg("cached :".$date_cached); // '05/06/19 15:36' (if wrong format)
        if ( strpos($date_cached,'/') !== FALSE ) {
            $year = substr(strrchr($date_cached, '/'), 0,4); // '/19 ' ou '/201'
            if (substr($year,-1) == ' ')
                //$year = '20'.substr($y,1,2); // '2019'
                $date_cached = substr($date_cached,0,6)."20".substr($year,1,2).substr($date_cached,8); // '05/06/19 15:36';
        }
        ####$this->mydebugmsg("cached2 :".$date_cached);
        $date_cached = \DateTime::createFromFormat('d/m/Y H:i',$date_cached);
        //debug("now :".$date_now->format('Y-m-d H:i:s') );
        //debug("cached :".$date_cached->format('Y-m-d H:i:s') );
        ####$this->mydebugmsg("Temps écoulé depuis last save:"); $this->mydebugmsg($date_now->diff($date_cached)->format('%i mn %s sec'));
        
        
        $date_cached->add(new \DateInterval('PT'.$this->CONF->ldap_cache_validity_duration.'M'));
        ####$this->mydebugmsg("date_cached (added) :".$date_cached->format('Y-m-d H:i:s') );
        
        /*
        $date_now = $date_now->getTimestamp();
        $date_cached = $date_cached->getTimestamp();
        debug("now :".$date_now);
        debug("cached :".$date_cached);
        $date_now = strtotime($date_now);
        $date_cached = strtotime($date_cached);
        debug("now :".  date("Y-m-d H:i:s", $date_now));
        debug("cached :".  date("Y-m-d H:i:s", $date_cached));
        
        //debug($this->CONF->ldap_cache_last_update ." plus ".$this->CONF->ldap_cache_validity_duration." minutes < $now ?");
        debug($date_cached ." plus ".$this->CONF->ldap_cache_validity_duration." minutes < $date_now ?");
        $last_save_date_plus_delay = strtotime( "+".$this->CONF->ldap_cache_validity_duration." minutes", strtotime($this->CONF->ldap_cache_last_update) );
        */
        
        //debug("decalage ?");
        //debug($date_cached < $date_now);
        
        // TEST
        /*
        $now = new \DateTime("2019-05-29 15:32:00");
        debug("now :".$now->format('Y-m-d H:i:s') );
        $d = $this->CONF->ldap_cache_last_update;
        $d = \DateTime::createFromFormat('d/m/Y H:i',$d);
        debug("d :".$d->format('Y-m-d H:i:s') );
        
        $d->add(new \DateInterval('PT1M'));
        debug("d :".$d->format('Y-m-d H:i:s') );
        debug($d > $now);

        $d->sub(new \DateInterval('PT2M'));
        debug("d :".$d->format('Y-m-d H:i:s') );
        debug($d < $now);
        
        $d->add(new \DateInterval('PT1M'));
        debug("d :".$d->format('Y-m-d H:i:s') );
        debug($d == $now);
        */
        
        ####$this->mydebugmsg("expired ?"); $this->mydebugmsg($date_cached < $date_now);
        return ($date_cached < $date_now); 
        //return TRUE;
    }

    
    private function _updateUserPassword($userId, $newPwd) {
        $query = $this->usersTable->query();
        $query->update()
        ->set(['password' => $newPwd])
        ->where(['id' => $userId])
        ->execute();
    }
     
    
    private function _isUserAlreadyCachedForLogin(array $user_login) {
        //debug($user_logged);
        //$user_login = $this->_getUserLogin($user_logged);
        return $this->_getCachedUserByLogin($user_login) !== null;
    }

    private function _getUserLogin(array $user) {
        return $user[$this->authenticationType][0];
    }
    
    // Return true if logged user $user_logged is exactly same user as cached user $user_cached
    private function _isExactSameUser($userFromLDAP,$user_cached) {
        $BOURRIN=false;
        //$this->mydebugmsg("user already exists => update it");
        
        // Same email ?
        if ( 
            isset($userFromLDAP['mail'])
            && 
            ( $BOURRIN || ($user_cached->email != $userFromLDAP['mail'][0]) )
        ) return false;

        // Same name AND firstname ?
        if ( 
            ( isset($userFromLDAP['sn']) && isset($userFromLDAP['givenname']) )
            && 
            strtolower($user_cached->nom) != strtolower( $userFromLDAP['sn'][0].' '.$userFromLDAP['givenname'][0] )
        ) return false;

        // SAME user
        return true;
    }

    private function _addNewUserInCacheFromLdapUser($userFromLDAP) {
        $this->usersTable->save($this->_getLDAPuserFormattedAsDB($userFromLDAP));
        ####$this->mydebugmsg("added new user"); $this->mydebugmsg($userFromLDAP);
    }

    private function _updateChangedUserInCacheFromLdapUser($userFromLDAP, $user_cached) {
        $user_cached->email = $userFromLDAP['mail'][0];
        // Tant qu'on y est, on met aussi à jour le nom et prenom
        $user_cached->nom = $userFromLDAP['sn'][0].' '.$userFromLDAP['givenname'][0];
        $this->usersTable->save($user_cached);
        ####$this->mydebugmsg("updated changed user"); $this->mydebugmsg($userFromLDAP);
    }

    /* 
     * UPDATE users CACHE 
     * (save all (fake)LDAP users into "users" db table)
     * ONLY if necessary
     */
    //private function _updateLdapCacheIfNeeded() {
    private function _updateUsersCacheIfNeeded(array $user_logged = null) {
        
        /* $user_logged looks like this (from fakeLDAP) :
            [
                'sn' => [
                    (int) 0 => 'SuperAdmin'
                ],
                'mail' => [
                    (int) 0 => 'superadmin@emailnew.com'
                ],
                'givenname' => [
                    (int) 0 => 'Stephane'
                ],
                'uid' => [
                    (int) 0 => 'superadminnew'
                ],
                'userpassword' => [
                    (int) 0 => '$2y$10$LZzpws3oDidBcqO/Fy1RTedLLk3ENTmplny5J7bZ6R1PqFoGOw3Ma'
                ]
            ]
        */

        // Si cache pas activé => return
        //debug("C1");
        //if (!LDAP_CACHE_ALWAYS_ON && !$this->CONF->ldap_cached) return;
        /*
        TODO:
        EP 22/12/2022
        DEAC
        Je désactive cette ligne car on est bien OBLIGÉ d'utiliser un cache
        Puisqu'on va toujours chercher la liste des users dans la table users
        ET que c'est dans cette table qu'on trouve leurs rolez !!!

        if (! $this->CONF->ldap_cached) return;
        */

        #
        # 1) ADD or UPDATE user $user_logged (if not null), only if NEW or CHANGED
        #

        if ($user_logged) {
            //$user_cached = $this->_getUserCachedForUserLogged($user_logged);
            $user_cached = $this->_getCachedUserByLogin($this->_getUserLogin($user_logged));
            // NEW user ?
            if (is_null($user_cached)) 
                $this->_addNewUserInCacheFromLdapUser($user_logged);
            // Existing user but CHANGED ?
            elseif ( ! $this->_isExactSameUser($user_logged,$user_cached) )
                $this->_updateChangedUserInCacheFromLdapUser($user_logged, $user_cached);
                // UPDATE THIS user in CACHE (users table)
        }
        
        #
        # 2) Update all users, only if CACHE expired
        #
        if (! $this->_ldapCacheIsExpired()) return;

        #DEBUG && debug("NEW User (pas dans DB users table)");
        
        // Get all users from (fake)LDAP
        $usersFromLDAP = $this->_getAllUsersFromLDAP();
        // LDAP should return at least some users, otherwise ERROR
        assert(!empty($usersFromLDAP));
        
        // Get all users from DB
        $users_cached = $this->_getAllUsersFromDB(FALSE);
        
        // Add new(fake)ldap users (only) and update existing users
        foreach ($usersFromLDAP as $userFromLDAP) {
            //$this->mydebugmsg("current user is ".$userFromLDAP['uid'][0]);
            ////$this->mydebugmsg("current user is ".$userFromLDAP[$this->authenticationType][0]);
            // Si utilisateur mal formé (pas de nom, pas de login, pas de mail) => ne pas l'enregistrer, passer au suivant
            if ( 
                ( // pas de champ login
                    !isset($userFromLDAP[$this->authenticationType]) 
                    || !isset($userFromLDAP[$this->authenticationType][0]) 
                    || $userFromLDAP[$this->authenticationType][0]=='' 
                )
                ||
                ( // pas de champ sn 
                    !isset($userFromLDAP['sn']) || !isset($userFromLDAP['sn'][0]) || $userFromLDAP['sn'][0]=='' 
                )
            ) {
                $this->mydebugmsg("Utilisateur LDAP mal formé => je ne le stocke pas");
                continue;
            }
            
            //$userFromLDAPLogin = $userFromLDAP[$this->authenticationType][0];
            $userFromLDAPLogin = $this->_getUserLogin($userFromLDAP);
            
            // (EP 5/6/19 : on n'a pas accès au password stocké dans le ldap, on ne peut donc pas le stocker dans le cache)
            //$currentLdapUserPwd = $userFromLDAP['userpassword'][0];
            
            //$this->mydebugmsg("current user is ".$currentLdapUserLogin);
            // Do not save fake ldap user in DB
            if ($userFromLDAPLogin == '_fake_ldap_user_') continue;
            
            $user_cached = $this->_getCachedUserByLogin($userFromLDAPLogin);

            // (1) NEW user ? => ADD
            if (is_null($user_cached)) 
                $this->_addNewUserInCacheFromLdapUser($userFromLDAP);

            // (2) Existing user but CHANGED ? => UPDATE
            elseif ( ! $this->_isExactSameUser($userFromLDAP,$user_cached) )
                $this->_updateChangedUserInCacheFromLdapUser($userFromLDAP, $user_cached);

        }
        
        // (3) DELETE old users (which are no more in LDAP)
        // dangereux, et faire attention de ne pas supprimer le user superadmin ldap créé au début du projet...
        //$DO_DELETE = false;
        $DO_DELETE = true;
        // - Select only the login (['uid']) column
        $usersFromLDAPLogins = array_column($usersFromLDAP, $this->authenticationType);
        ####$this->mydebugmsg($usersFromLDAPLogins);
        /*
         * Avec LDAP IRAP, on obtient pour $usersFromLDAPLogins, 0 à 439 (440 users) :
        [
        	(int) 0 => [
        		'count' => (int) 1,
        		(int) 0 => 'chillembrand'
        	],
        	(int) 1 => [
        		'count' => (int) 1,
        		(int) 0 => 'ablanchard'
        	],
        	(int) 2 => [
        		'count' => (int) 1,
        		(int) 0 => 'ahui-bon-hoa'
        	],
        	(int) 3 => [
        		'count' => (int) 1,
        		(int) 0 => 'jatteia'
        	],
        	...
        ]
        */
        // - Select only the [0] column
        $usersFromLDAPLogins = array_column($usersFromLDAPLogins, 0);
        ####$this->mydebugmsg($usersFromLDAPLogins);
        /*
         * Avec LDAP IRAP, on obtient pour $usersFromLDAPLogins, 0 à 439 (440 users) :
        [
            [0]=>
            string(12) "chillembrand"
            [1]=>
            string(10) "ablanchard"
            [2]=>
            string(12) "ahui-bon-hoa"
            [3]=>
            string(7) "jatteia"
            ...
        ]
        */
        foreach ($users_cached as $user_cached) {
            /*
            debug("DELETE");
            debug("look for $userFromDB->username");
            debug("in ");
            */
            //debug($usersFromLDAP);
            //$usersFromLDAPLogins = array_column($usersFromLDAP, 'uid');
            if (! in_array($user_cached->username, $usersFromLDAPLogins)) {
                // (6/6/19) 3 users found (superadmin, imoro, mimelhaine)
                ####$this->mydebugmsg("OLD user should be deleted:"); $this->mydebugmsg($user_cached->username);
                #$this->mydebugmsg($user_cached);
                $DO_DELETE && $this->usersTable->delete($user_cached);
            }
        }

        // Update LDAP cache last update time (= NOW)
        $this->CONF->ldap_cache_last_update = date("Y-m-d H:i:s"); // 2019-05-28 03:25:34
        $this->configurationsTable->save($this->CONF);
        
        DEBUG && debug("CACHE (table users) mis à jour");
        //exit;

    } // _updateUsersCacheIfNeeded()
    
    
    
    /*
    // REAL LDAP only
    // from DB ==> to LDAP
    // @return: ldap user if ok (else FALSE)
    //private function checkAndFetchLDAPUserFromDB($user_login, $user_password) {
    private function _getLdapUserFromDB($user_login) {
        // Doit aussi return false si ce user_login est "périmé" (sa date "created" est > 2 mois par exemple),
        // ce qui obligera à relire ses données dans le LDAP et donc se mettre à jour
        //if (! $this->LDAP_CACHED) return FALSE;
        
        // If LDAP cache (in users table) is expired, update it (save again ldap into DB)
        //if ($this->_ldapCacheIsExpired()) $this->_updateLdapCache();
        $this->_updateUsersCacheIfNeeded();
        
        // 1) Search user in DB
        $ldapUser = $this->_getUserFromDBByCachedLogir_login);
        /S
        $ldapUser = TableRegistry::getTableLocator()->get('Users')->find()
            ->where([
                'username' => $user_login
            ])
           ->first();
        S/   
            
        // User not found => fail
        if (is_null($ldapUser)) return FALSE;

        /S
        // 2) Check password
        // Bad password => fail
        if ( ! (new DefaultPasswordHasher())->check($user_password,$ldapUser['userpassword'][0]) ) return FALSE;
        // User found and password ok => return it
        S/

        // User found ok => return it formatted as ldap
        return $this->_getDBuserFormattedAsLDAP($ldapUser);
    }
    */
    
    
    
    /* (EP202102) inutile car il ne faut pas sauver (cacher) uniquement CE user, mais TOUS les users du (fake)ldap
    // from (fake)LDAP ==> to DB
    // SAVE new user in DB
    private function _saveNewUserInDB($user_from_LDAP) {
        if (! $this->CONF->ldap_cached) return TRUE;
        
        // 1) Format LDAP user as for DB
        $user_from_LDAP_formatted_as_DB = $this->_getLDAPuserFormattedAsDB($user_from_LDAP);
        
        // 2) Save DB formatted user into DB
        $usersTable = TableRegistry::getTableLocator()->get('Users');
        if ( ! $usersTable->save($user_from_LDAP_formatted_as_DB, [
            //'checkRules' => false,
            'checkExisting' => TRUE
        ])) return FALSE;
        // user has been saved (cached) ok
        return TRUE;
    }
    */
    
    
    // REAL LDAP only
    // SEARCH en 4 étapes
    //private function _ldapSearch($filter, $just_these, $user_login=NULL, $user_password=NULL) {
    private function _ldapSearch($filter, $just_these) {

        // (1) CONNEXION
        // Pour faire du ldaps : entrer 'ldaps://' devant $this->host
        $ldapConnection = ldap_connect($this->host, $this->port)
            or die("Impossible de se connecter au serveur ldap $this->host:$this->port");

        // (2) SET OPTIONS
        ldap_set_option($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3)
            or die("Impossible de positionner l'option LDAP LDAP_OPT_PROTOCOL_VERSION=".LDAP_OPT_PROTOCOL_VERSION.", 3");

        // (3) BINDING simple
        // Signature de ldap_bind : ($link_identifier, $bind_rdn = null, $bind_password = null)
        // => return bool true on success or false on failure
        if ($this->ldap_authentified)
            // - ldap authentifié => binding authentifié
            $ldapbind = @ldap_bind($ldapConnection, $this->bindDn, $this->bindPass);
        else
            // - ldap anonyme => binding anonyme
            $ldapbind = @ldap_bind($ldapConnection);
        if (! $ldapbind) {
            die("Impossible de faire un BIND simple sur le serveur ldap " . $this->ldap_authentified ? "(mode authentifié) !" : "(mode anonyme) !");
        }

        // (4) SEARCH : Recherche d'infos (sur le user qui se connecte, ou bien sur tous les users)
        // $filter = "(&".$this->filter."(".$this->authenticationType . '=' . $user_login."))";
        // ex: (&(compteinfo=Oui)(uid=epallier))
        $results = ldap_search($ldapConnection, $this->baseDn, $filter, $just_these)
            or die("Impossible de faire une recherche sur le serveur LDAP, réponse: " . ldap_error($ldapConnection) );
        $search = ldap_get_entries($ldapConnection, $results);
        //echo $results["count"]." entries returned\n";
        if ($search === FALSE)
            die("Impossible de récupérer les attributs utilisateur(s) du serveur LDAP, réponse: " . ldap_error($ldapConnection) );
        //return $search[0];
        return $search;
        
    } // _ldapSearch()
    
    private function _ldapAuth($user, $password) {
        $ldapConnection = ldap_connect($this->host, $this->port)
            or die("Impossible de se connecter au serveur ldap $this->host:$this->port");

        ldap_set_option($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3)
            or die("Impossible de positionner l'option LDAP LDAP_OPT_PROTOCOL_VERSION=".LDAP_OPT_PROTOCOL_VERSION.", 3");

        $ldapbind = @ldap_bind($ldapConnection, $user, $password);

        if ($ldapbind) return TRUE;

        return FALSE;
    }
        





    private function _ldapAuthenticationREAL($user_login, $user_password) {
        // No connexion allowed without password
        if (strlen(trim($user_password)) == 0) return FALSE;
                            
        /*
        // TODO: optimisation possible
        // 1) Search user in CACHE (DB)
        $user_fetched = $this->checkAndFetchLDAPUserFromDB($user_login, $user_password);
        $this->mydebugmsg("(1) user found in DB is:");
        $this->mydebugmsg($user_fetched);
        //TODO: A VIRER !!!
        //$user_fetched = FALSE;
        // 2) If not CACHED, search user in LDAP
        if ($user_fetched === FALSE) {
        */
        //$user_fetched = $this->checkAndFetchUserFromLdap($user_login, $user_password);
        $just_these = [];
        // TODO: vérifier si cette ligne est bien utile ou pas... (avant on faisait ça)
        //if (! $this->ldap_authentified) $just_these = array("cn");
        // Construction du filtre avec le filtre de la base de données avec un & sur le login de l'utilisateur
        // Si aucun filtre n'est défini dans la base de données on aura juste (& ($this->authenticationType=$user_login))
        // ex: "(&(objectClass=person)(memberOf:1.2.840.113556.1.4.1941:=cn=ucbl.osu.cral,ou=groups,ou=27,ou=sim,ou=univ-lyon1,dc=univ-lyon1,dc=fr)(sAMAccountName=$user_login))";
        $filter = '(&'.$this->filter.'('.$this->authenticationType.'='.$user_login.'))';
        //TODO: optimisation, refactoriser si comportement général
        //$binddn .= ','.$this->baseDn;
        //$user_fetched = $this->_ldapSearch($filter, $just_these, $user_login, $user_password);
        $user_fetched = $this->_ldapSearch($filter, $just_these);
        //$this->mydebugmsg("(1) user found in LDAP is:");
        //$this->mydebugmsg($user_fetched);
        //$this->mydebugmsg($user_fetched[0]);
        if ($user_fetched['count'] != 0) {
            $user_fetched = $user_fetched[0];
            if ($this->_ldapAuth($user_fetched["dn"], $user_password)) {
                // CACHE the new user in DB for next time
                ///$this->_saveNewUserInDB($user_fetched[0]);
                // CACHE ALL ldap users
                ####$this->_updateUsersCacheIfNeeded($user_fetched);
                // return logged user (authentified)
                return $user_fetched;
            }
            //return null;
            //return FALSE;
        }
        return FALSE;
        //return $user_fetched; // Noter que $user_fetched peut etre egal a FALSE (si pas trouvé)
    }


    private function _ldapAuthenticationFAKE($user_login, $user_password) {
        //debug($this->baseDn);
        $user_fetched = $this->getFakeLdapUser($user_login);
        /*
		debug($this->fakeLDAPUsers);
        debug($user_login);
        debug($user_password);
        debug($user_fetched);
        exit;
        */
        ####$this->mydebugmsg("(1) user found in FAKE LDAP is:"); $this->mydebugmsg($user_fetched);
        /* Voici un exemple de ce qui est dans $user_fetched (fake ldap) :
        [
            'sn' => [
        		(int) 0 => 'Pallier'
        	],
        	'mail' => [
        		(int) 0 => 'Etienne.Pallier@irap.omp.eu'
        	],
        	'givenname' => [
        		(int) 0 => 'Etienne'
        	],
        	'uid' => [
        		(int) 0 => 'epallier'
        	],
        	'userpassword' => [
        		(int) 0 => '<mot de passe crypté>'
        	]
        ]
        */
        // debug($user);
        //if ($user === false) return FALSE;
        if ($user_fetched !== false) {

            /* $user_fetched looks like this (from fakeLDAP) :
                [
                    'sn' => [
                        (int) 0 => 'SuperAdmin'
                    ],
                    'mail' => [
                        (int) 0 => 'superadmin@emailnew.com'
                    ],
                    'givenname' => [
                        (int) 0 => 'Stephane'
                    ],
                    'uid' => [
                        (int) 0 => 'superadminnew'
                    ],
                    'userpassword' => [
                        (int) 0 => '$2y$10$LZzpws3oDidBcqO/Fy1RTedLLk3ENTmplny5J7bZ6R1PqFoGOw3Ma'
                    ]
                ]
            */

            // $this->authenticationType peut valoir "uid" ou "cn"... (par défaut "uid" pour le fake ldap, à confirmer...)
            // if ($user['uid'][0] == "_NouvelUtilisateur_username" && $user['userpassword'][0] == "_NouvelUtilisateur_password") return $user;
            // if ($user[$this->authenticationType][0] == "_NouvelUtilisateur_username" && $user['userpassword'][0] == "_NouvelUtilisateur_password") return $user;
			
            /* EP 23/12/22 On n'utilise plus ça
            *
            // Est-ce le user FAKE LDAP par defaut (_fake_ldap_user_) ? si oui, on le laisse passer
            //if ($user_fetched[$this->authenticationType][0] == $this->_getTheFakeLdapUser()['login'] && $user_fetched['userpassword'][0] == $this->_getTheFakeLdapUser()['pass'])
            if ($user_fetched[DEFAULT_AUTH_TYPE][0] == $this->_getTheFakeLdapUser()['login'] && $user_fetched['userpassword'][0] == $this->_getTheFakeLdapUser()['pass'])
                return $user_fetched;
            */

            /*
            debug("user_password = ".$user_password);
            debug("user found in db is ");
            debug($user_fetched);
            debug($user_fetched['userpassword'][0]);
            debug($user_fetched['userpassword'][0]);
            exit;
            */
			
            // Sinon, on regarde si c'est un user de la table fakeldapusers
            if ( (new DefaultPasswordHasher())->check($user_password,$user_fetched['userpassword'][0]) ) {
                ####$this->_updateUsersCacheIfNeeded($user_fetched);
                return $user_fetched;
            }
        }
        
        // Ce login n'existe pas, ou alors il y a eu un problème sur fake ldap
        return FALSE;
        // END FAKE_LDAP

        // On met à jour le cache des users (si nécessaire)
        //if ($user_fetched !== FALSE) $this->_updateUsersCacheIfNeeded($user_fetched);
        // Retourne le user authentifié ou bien FALSE
        //return $user_fetched;    
    }

 
    // MAIN ENTRY POINT of this class
    /*
     * @param string $user_login
     * @param string $user_password
     * @return logged user LDAP attributes (FALSE if user not found in LDAP)
     */
    public function ldapAuthentication($user_login, $user_password) {

        // Bad configuration => FAIL
        if (! $this->_checkAndGetConfiguration()) return FALSE;
        
        // Par défaut, on retourne FALSE (échec de connexion)
        //$user_fetched = FALSE;
        
        // (EP 5/6/19 : on n'a pas accès au password stocké dans le ldap, on ne peut donc pas le stocker dans le cache)
        
        #
        # 1 - REAL LDAP
        #
        if ($this->LDAP_USED) 
            try {
                $user_fetched = $this->_ldapAuthenticationREAL($user_login, $user_password);
            }
            catch (Exception $e) {
                //echo 'Exception LDAP : ',  $e->getMessage(), "\n";
                debug('Exception LDAP : ');
                debug($e->getMessage());
                exit;
            } // REAL LDAP
            
        #
        # 2 - FAKE LDAP used
        #
        else
            $user_fetched = $this->_ldapAuthenticationFAKE($user_login, $user_password);

        if ($user_fetched !== FALSE)
            // Update Users cache if needed (especially for the logged user)
            $this->_updateUsersCacheIfNeeded($user_fetched);
        
        return $user_fetched;

    } // ldapAuthentication()
    
/* Voici un exemple de ce qui est dans $user_fetched[0] (structure LDAP IRAP) :

// ce qui est retourné par le fake ldap (imitation bien faite non ?)
[
    'sn' => [
    (int) 0 => 'Pallier'
    ],
    'mail' => [
    (int) 0 => 'Etienne.Pallier@irap.omp.eu'
    ],
    'givenname' => [
    (int) 0 => 'Etienne'
    ],
    'uid' => [
    (int) 0 => 'epallier'
    ],
    'userpassword' => [
    (int) 0 => '<mot de passe crypté>'
    ]
]

// VRAI LDAP, juste un extrait utile :
[
'sn' => [
'count' => (int) 1,
(int) 0 => 'Pallier'
],
(int) 14 => 'sn',
'givenname' => [
'count' => (int) 1,
(int) 0 => 'Etienne'
],
]

// VRAI LDAP, au complet :
[
'cn' => [
'count' => (int) 1,
(int) 0 => 'Etienne Pallier'
],
(int) 0 => 'cn',
'homedirectory' => [
'count' => (int) 1,
(int) 0 => '/home/epallier'
],
(int) 1 => 'homedirectory',
'uidnumber' => [
'count' => (int) 1,
(int) 0 => '20172'
],
(int) 2 => 'uidnumber',
'objectclass' => [
'count' => (int) 9,
(int) 0 => 'top',
(int) 1 => 'person',
(int) 2 => 'organizationalPerson',
(int) 3 => 'inetOrgPerson',
(int) 4 => 'posixAccount',
(int) 5 => 'shadowAccount',
(int) 6 => 'irap',
(int) 7 => 'hostObject',
(int) 8 => 'sambaSamAccount'
],
(int) 3 => 'objectclass',
'sambasid' => [
'count' => (int) 1,
(int) 0 => 'S-1-5-21-3149873848-2002230563-1027543705-41344'
],
(int) 4 => 'sambasid',
'mail' => [
'count' => (int) 1,
(int) 0 => 'Etienne.Pallier@irap.omp.eu'
],
(int) 5 => 'mail',
'olddn' => [
'count' => (int) 1,
(int) 0 => 'uid=pallier,ou=users,ou=laboratoire,dc=cesr,dc=fr'
],
(int) 6 => 'olddn',
'userpassword' => [
'count' => (int) 1,
(int) 0 => '{SASL}epallier@IRAP.OMP.EU'
],
(int) 7 => 'userpassword',
'sambantpassword' => [
'count' => (int) 1,
(int) 0 => 'ED9A0ECE0C6C7560A8DDF6A23B2C7C36'
],
(int) 8 => 'sambantpassword',
'sambapwdlastset' => [
'count' => (int) 1,
(int) 0 => '1317291687'
],
(int) 9 => 'sambapwdlastset',
'loginshell' => [
'count' => (int) 1,
(int) 0 => '/bin/bash'
],
(int) 10 => 'loginshell',
'shadowexpire' => [
'count' => (int) 1,
(int) 0 => '-1'
],
(int) 11 => 'shadowexpire',
'host' => [
'count' => (int) 3,
(int) 0 => 'gitlab1.irap.omp.eu',
(int) 1 => 'gw.irap.omp.eu',
(int) 2 => 'version2.irap.omp.eu'
],
(int) 12 => 'host',
'uid' => [
'count' => (int) 1,
(int) 0 => 'epallier'
],
(int) 13 => 'uid',
'sn' => [
'count' => (int) 1,
(int) 0 => 'Pallier'
],
(int) 14 => 'sn',
'givenname' => [
'count' => (int) 1,
(int) 0 => 'Etienne'
],
(int) 15 => 'givenname',
'gecos' => [
'count' => (int) 1,
(int) 0 => 'Etienne.Pallier'
],
(int) 16 => 'gecos',
'gidnumber' => [
'count' => (int) 1,
(int) 0 => '2001'
],
(int) 17 => 'gidnumber',
'tagmail' => [
'count' => (int) 1,
(int) 0 => 'Oui'
],
(int) 18 => 'tagmail',
'compteinfo' => [
'count' => (int) 1,
(int) 0 => 'Oui'
],
(int) 19 => 'compteinfo',
'arrivaldate' => [
'count' => (int) 1,
(int) 0 => '01/01/1933'
],
(int) 20 => 'arrivaldate',
'birthday' => [
'count' => (int) 1,
(int) 0 => '07/08/1968'
],
(int) 21 => 'birthday',
'telephonenumber' => [
'count' => (int) 1,
(int) 0 => '0561556648'
],
(int) 22 => 'telephonenumber',
'roomnumber' => [
'count' => (int) 1,
(int) 0 => 'J039'
],
(int) 23 => 'roomnumber',
'mailperso' => [
'count' => (int) 1,
(int) 0 => 'N/A'
],
(int) 24 => 'mailperso',
'title' => [
'count' => (int) 1,
(int) 0 => 'M'
],
(int) 25 => 'title',
'site' => [
'count' => (int) 1,
(int) 0 => 'Roche'
],
(int) 26 => 'site',
'manager' => [
'count' => (int) 1,
(int) 0 => 'uid=mgiard,ou=users,dc=irap,dc=omp,dc=eu'
],
(int) 27 => 'manager',
'statut1' => [
'count' => (int) 1,
(int) 0 => 'ITA'
],
(int) 28 => 'statut1',
'o' => [
'count' => (int) 1,
(int) 0 => 'UPS'
],
(int) 29 => 'o',
'gt1' => [
'count' => (int) 1,
(int) 0 => 'PEPS'
],
(int) 30 => 'gt1',
'gt2' => [
'count' => (int) 1,
(int) 0 => 'GAHEC'
],
(int) 31 => 'gt2',
'statut2' => [
'count' => (int) 1,
(int) 0 => 'GT2I'
],
(int) 32 => 'statut2',
'affichageannuaire' => [
'count' => (int) 1,
(int) 0 => 'Oui'
],
(int) 33 => 'affichageannuaire',
'count' => (int) 34,
'dn' => 'uid=epallier,ou=users,dc=irap,dc=omp,dc=eu'
]
*/

    
} // fin de class LdapConnectionsTable

?>