Welcome to mirror list, hosted at ThFree Co, Russian Federation.

API.php « UsersManager « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b3efa63712f18d3265f3b9434e7a3fb88fc824ac (plain)
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
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
<?php
/**
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Plugins\UsersManager;

use DeviceDetector\DeviceDetector;
use Exception;
use Piwik\Access;
use Piwik\Access\CapabilitiesProvider;
use Piwik\Access\RolesProvider;
use Piwik\Auth\Password;
use Piwik\Common;
use Piwik\Config;
use Piwik\Container\StaticContainer;
use Piwik\Date;
use Piwik\Metrics\Formatter;
use Piwik\NoAccessException;
use Piwik\Option;
use Piwik\Piwik;
use Piwik\Plugin;
use Piwik\Plugins\CoreAdminHome\Emails\UserCreatedEmail;
use Piwik\Plugins\Login\PasswordVerifier;
use Piwik\Plugins\UsersManager\Emails\UserInfoChangedEmail;
use Piwik\Site;
use Piwik\Tracker\Cache;
use Piwik\Plugins\CoreAdminHome\Emails\UserDeletedEmail;

/**
 * The UsersManager API lets you Manage Users and their permissions to access specific websites.
 *
 * You can create users via "addUser", update existing users via "updateUser" and delete users via "deleteUser".
 * There are many ways to list users based on their login "getUser" and "getUsers", their email "getUserByEmail",
 * or which users have permission (view or admin) to access the specified websites "getUsersWithSiteAccess".
 *
 * Existing Permissions are listed given a login via "getSitesAccessFromUser", or a website ID via "getUsersAccessFromSite",
 * or you can list all users and websites for a given permission via "getUsersSitesFromAccess". Permissions are set and updated
 * via the method "setUserAccess".
 * See also the documentation about <a href='http://matomo.org/docs/manage-users/' rel='noreferrer' target='_blank'>Managing Users</a> in Matomo.
 */
class API extends \Piwik\Plugin\API
{
    const OPTION_NAME_PREFERENCE_SEPARATOR = '_';

    public static $UPDATE_USER_REQUIRE_PASSWORD_CONFIRMATION = true;
    public static $SET_SUPERUSER_ACCESS_REQUIRE_PASSWORD_CONFIRMATION = true;

    /**
     * @var Model
     */
    private $model;

    /**
     * @var Password
     */
    private $password;

    /**
     * @var UserAccessFilter
     */
    private $userFilter;

    /**
     * @var Access
     */
    private $access;

    /**
     * @var Access\RolesProvider
     */
    private $roleProvider;

    /**
     * @var Access\CapabilitiesProvider
     */
    private $capabilityProvider;

    /**
     * @var PasswordVerifier
     */
    private $passwordVerifier;

    private $twoFaPluginActivated;

    const PREFERENCE_DEFAULT_REPORT = 'defaultReport';
    const PREFERENCE_DEFAULT_REPORT_DATE = 'defaultReportDate';

    private static $instance = null;

    public function __construct(Model $model, UserAccessFilter $filter, Password $password, Access $access = null, Access\RolesProvider $roleProvider = null, Access\CapabilitiesProvider $capabilityProvider = null, PasswordVerifier $passwordVerifier = null)
    {
        $this->model = $model;
        $this->userFilter = $filter;
        $this->password = $password;
        $this->access = $access ?: StaticContainer::get(Access::class);
        $this->roleProvider = $roleProvider ?: StaticContainer::get(RolesProvider::class);
        $this->capabilityProvider = $capabilityProvider ?: StaticContainer::get(CapabilitiesProvider::class);
        $this->passwordVerifier = $passwordVerifier ?: StaticContainer::get(PasswordVerifier::class);
    }

    /**
     * You can create your own Users Plugin to override this class.
     * Example of how you would overwrite the UsersManager_API with your own class:
     * Call the following in your plugin __construct() for example:
     *
     * StaticContainer::getContainer()->set('UsersManager_API', \Piwik\Plugins\MyCustomUsersManager\API::getInstance());
     *
     * @throws Exception
     * @return \Piwik\Plugins\UsersManager\API
     */
    public static function getInstance()
    {
        try {
            $instance = StaticContainer::get('UsersManager_API');
            if (!($instance instanceof API)) {
                // Exception is caught below and corrected
                throw new Exception('UsersManager_API must inherit API');
            }
            self::$instance = $instance;

        } catch (Exception $e) {
            self::$instance = StaticContainer::get('Piwik\Plugins\UsersManager\API');
            StaticContainer::getContainer()->set('UsersManager_API', self::$instance);
        }

        return self::$instance;
    }

    /**
     * Get the list of all available roles.
     * It does not return the super user role, and neither the "noaccess" role.
     * @return array[]  Returns an array containing information about each role
     */
    public function getAvailableRoles()
    {
        Piwik::checkUserHasSomeAdminAccess();

        $response = array();

        foreach ($this->roleProvider->getAllRoles() as $role) {
            $response[] = array(
                'id' => $role->getId(),
                'name' => $role->getName(),
                'description' => $role->getDescription(),
                'helpUrl' => $role->getHelpUrl(),
            );
        }

        return $response;
    }

    /**
     * Get the list of all available capabilities.
     * @return array[]  Returns an array containing information about each capability
     */
    public function getAvailableCapabilities()
    {
        Piwik::checkUserHasSomeAdminAccess();

        $response = array();

        foreach ($this->capabilityProvider->getAllCapabilities() as $capability) {
            $response[] = array(
                'id' => $capability->getId(),
                'name' => $capability->getName(),
                'description' => $capability->getDescription(),
                'helpUrl' => $capability->getHelpUrl(),
                'includedInRoles' => $capability->getIncludedInRoles(),
                'category' => $capability->getCategory(),
            );
        }

        return $response;
    }

    /**
     * Sets a user preference. Plugins can add custom preference names by declaring them in their plugin config/config.php
     * like this:
     *
     * ```php
     * return array('usersmanager.user_preference_names' => DI\add(array('preference_name_1', 'preference_name_2')));
     * ```
     *
     * @param string $userLogin
     * @param string $preferenceName
     * @param string $preferenceValue
     * @return void
     */
    public function setUserPreference($userLogin, $preferenceName, $preferenceValue)
    {
        Piwik::checkUserHasSuperUserAccessOrIsTheUser($userLogin);

        if (!$this->model->userExists($userLogin)) {
            throw new Exception('User does not exist: ' . $userLogin);
        }

        if ($userLogin === 'anonymous') {
            Piwik::checkUserHasSuperUserAccess();
        }

        $nameIfSupported = $this->getPreferenceId($userLogin, $preferenceName);
        Option::set($nameIfSupported, $preferenceValue);
    }

    /**
     * Gets a user preference
     * @param string $preferenceName
     * @param string|bool $userLogin Optional, defaults to current user log in when set to false.
     * @return bool|string
     */
    public function getUserPreference($preferenceName, $userLogin = false)
    {
        if ($userLogin === false) {
            // the default value for first parameter is there to have it an optional parameter in the HTTP API
            // in PHP it won't be optional. Could move parameter to the end of the method but did not want to break
            // BC
            $userLogin = Piwik::getCurrentUserLogin();
        }
        Piwik::checkUserHasSuperUserAccessOrIsTheUser($userLogin);

        $optionValue = $this->getPreferenceValue($userLogin, $preferenceName);

        if ($optionValue !== false) {
            return $optionValue;
        }

        return $this->getDefaultUserPreference($preferenceName, $userLogin);
    }

    /**
     * Sets a user preference in the DB using the preference's default value.
     * @param string $userLogin
     * @param string $preferenceName
     * @ignore
     */
    public function initUserPreferenceWithDefault($userLogin, $preferenceName)
    {
        Piwik::checkUserHasSuperUserAccessOrIsTheUser($userLogin);

        $optionValue = $this->getPreferenceValue($userLogin, $preferenceName);

        if ($optionValue === false) {
            $defaultValue = $this->getDefaultUserPreference($preferenceName, $userLogin);

            if ($defaultValue !== false) {
                $this->setUserPreference($userLogin, $preferenceName, $defaultValue);
            }
        }
    }

    /**
     * Returns an array of Preferences
     * @param $preferenceNames array of preference names
     * @return array
     * @ignore
     */
    public function getAllUsersPreferences(array $preferenceNames)
    {
        Piwik::checkUserHasSuperUserAccess();

        $userPreferences = array();
        foreach($preferenceNames as $preferenceName) {
            $optionNameMatchAllUsers = $this->getPreferenceId('%', $preferenceName);
            $preferences = Option::getLike($optionNameMatchAllUsers);

            foreach($preferences as $optionName => $optionValue) {
                $lastUnderscore = strrpos($optionName, self::OPTION_NAME_PREFERENCE_SEPARATOR);
                $userName = substr($optionName, 0, $lastUnderscore);
                $preference = substr($optionName, $lastUnderscore + 1);
                $userPreferences[$userName][$preference] = $optionValue;
            }
        }
        return $userPreferences;
    }

    private function getPreferenceId($login, $preference)
    {
        if(false !== strpos($preference, self::OPTION_NAME_PREFERENCE_SEPARATOR)) {
            throw new Exception("Preference name cannot contain underscores.");
        }
        $names = array(
            self::PREFERENCE_DEFAULT_REPORT,
            self::PREFERENCE_DEFAULT_REPORT_DATE,
            'isLDAPUser', // used in loginldap
            'hideSegmentDefinitionChangeMessage',// used in JS
        );
        $customPreferences = StaticContainer::get('usersmanager.user_preference_names');

        if (!in_array($preference, $names, true)
            && !in_array($preference, $customPreferences, true)) {
            throw new Exception('Not supported preference name: ' . $preference);
        }
        return $login . self::OPTION_NAME_PREFERENCE_SEPARATOR . $preference;
    }

    private function getPreferenceValue($userLogin, $preferenceName)
    {
        return Option::get($this->getPreferenceId($userLogin, $preferenceName));
    }

    private function getDefaultUserPreference($preferenceName, $login)
    {
        switch ($preferenceName) {
            case self::PREFERENCE_DEFAULT_REPORT:
                $viewableSiteIds = \Piwik\Plugins\SitesManager\API::getInstance()->getSitesIdWithAtLeastViewAccess($login);
                if (!empty($viewableSiteIds)) {
                    return reset($viewableSiteIds);
                }
                return false;
            case self::PREFERENCE_DEFAULT_REPORT_DATE:
                return Config::getInstance()->General['default_day'];
            default:
                return false;
        }
    }

    /**
     * Returns all users with their role for $idSite.
     *
     * @param int $idSite
     * @param int|null $limit
     * @param int|null $offset
     * @param string|null $filter_search text to search for in the user's login and email (if any)
     * @param string|null $filter_access only select users with this access to $idSite. can be 'noaccess', 'some', 'view', 'admin', 'superuser'
     *                                   Filtering by 'superuser' is only allowed for other superusers.
     * @return array
     */
    public function getUsersPlusRole($idSite, $limit = null, $offset = 0, $filter_search = null, $filter_access = null)
    {
        if (!$this->isUserHasAdminAccessTo($idSite)) {
            // if the user is not an admin to $idSite, they can only see their own user
            if ($offset > 1) {
                Common::sendHeader('X-Matomo-Total-Results: 1');
                return [];
            }

            $user = $this->model->getUser($this->access->getLogin());
            $user['role'] = $this->access->getRoleForSite($idSite);
            $user['capabilities'] = $this->access->getCapabilitiesForSite($idSite);
            $users = [$user];
            $totalResults = 1;
        } else {
            // if the current user is not the superuser, only select users that have access to a site this user
            // has admin access to
            $loginsToLimit = null;
            if (!Piwik::hasUserSuperUserAccess()) {
                $adminIdSites = Access::getInstance()->getSitesIdWithAdminAccess();
                if (empty($adminIdSites)) { // sanity check
                    throw new \Exception("The current admin user does not have access to any sites.");
                }

                $loginsToLimit = $this->model->getUsersWithAccessToSites($adminIdSites);
            }

            if ($loginsToLimit !== null && empty($loginsToLimit)) {
                // if the current user is not the superuser, and getUsersWithAccessToSites() returned an empty result,
                // access is managed by another plugin, and the current user cannot manage any user with UsersManager
                Common::sendHeader('X-Matomo-Total-Results: 0');
                return [];

            } else {
                [$users, $totalResults] = $this->model->getUsersWithRole($idSite, $limit, $offset, $filter_search, $filter_access, $loginsToLimit);

                foreach ($users as &$user) {
                    $user['superuser_access'] = $user['superuser_access'] == 1;
                    if ($user['superuser_access']) {
                        $user['role'] = 'superuser';
                        $user['capabilities'] = [];
                    } else {
                        [$user['role'], $user['capabilities']] = $this->getRoleAndCapabilitiesFromAccess($user['access']);
                        $user['role'] = empty($user['role']) ? 'noaccess' : reset($user['role']);
                    }

                    unset($user['access']);
                }
            }
        }

        $users = $this->enrichUsers($users);
        $users = $this->enrichUsersWithLastSeen($users);

        foreach ($users as &$user) {
            unset($user['password']);
        }

        Common::sendHeader('X-Matomo-Total-Results: ' . $totalResults);
        return $users;
    }

    /**
     * Returns the list of all the users
     *
     * @param string $userLogins Comma separated list of users to select. If not specified, will return all users
     * @return array the list of all the users
     */
    public function getUsers($userLogins = '')
    {
        Piwik::checkUserHasSomeAdminAccess();

        if (!is_string($userLogins)) {
            throw new \Exception('Parameter userLogins needs to be a string containing a comma separated list of users');
        }

        $logins = array();

        if (!empty($userLogins)) {
            $logins = explode(',', $userLogins);
        }

        $users = $this->model->getUsers($logins);
        $users = $this->userFilter->filterUsers($users);
        $users = $this->enrichUsers($users);

        return $users;
    }

    /**
     * Returns the list of all the users login
     *
     * @return array the list of all the users login
     */
    public function getUsersLogin()
    {
        Piwik::checkUserHasSomeAdminAccess();

        $logins = $this->model->getUsersLogin();
        $logins = $this->userFilter->filterLogins($logins);

        return $logins;
    }

    /**
     * For each user, returns the list of website IDs where the user has the supplied $access level.
     * If a user doesn't have the given $access to any website IDs,
     * the user will not be in the returned array.
     *
     * @param string Access can have the following values : 'view' or 'admin'
     *
     * @return array    The returned array has the format
     *                    array(
     *                        login1 => array ( idsite1,idsite2),
     *                        login2 => array(idsite2),
     *                        ...
     *                    )
     */
    public function getUsersSitesFromAccess($access)
    {
        Piwik::checkUserHasSuperUserAccess();

        $this->checkAccessType($access);

        $userSites = $this->model->getUsersSitesFromAccess($access);
        $userSites = $this->userFilter->filterLoginIndexedArray($userSites);

        return $userSites;
    }

    /**
     * Throws an exception if one of the given access types does not exists.
     *
     * @param string|array $access
     * @throws Exception
     */
    private function checkAccessType($access)
    {
        $access = (array) $access;

        foreach ($access as $entry) {
            if (!$this->isValidAccessType($entry)) {
                throw new Exception(Piwik::translate("UsersManager_ExceptionAccessValues", [implode(", ", $this->getAllRolesAndCapabilities()), $entry]));
            }
        }
    }

    /**
     * returns if the given access type exists
     *
     * @param string $access
     * @return bool
     */
    private function isValidAccessType($access)
    {
        return in_array($access, $this->getAllRolesAndCapabilities(), true);
    }

    private function getAllRolesAndCapabilities()
    {
        $roles = $this->roleProvider->getAllRoleIds();
        $capabilities = $this->capabilityProvider->getAllCapabilityIds();
        return array_merge($roles, $capabilities);
    }

    /**
     * For each user, returns their access level for the given $idSite.
     * If a user doesn't have any access to the $idSite ('noaccess'),
     * the user will not be in the returned array.
     *
     * @param int $idSite website ID
     *
     * @return array    The returned array has the format
     *                    array(
     *                        login1 => 'view',
     *                        login2 => 'admin',
     *                        login3 => 'view',
     *                        ...
     *                    )
     */
    public function getUsersAccessFromSite($idSite)
    {
        Piwik::checkUserHasAdminAccess($idSite);

        $usersAccess = $this->model->getUsersAccessFromSite($idSite);
        $usersAccess = $this->userFilter->filterLoginIndexedArray($usersAccess);

        return $usersAccess;
    }

    public function getUsersWithSiteAccess($idSite, $access)
    {
        Piwik::checkUserHasAdminAccess($idSite);
        $this->checkAccessType($access);

        $logins = $this->model->getUsersLoginWithSiteAccess($idSite, $access);

        if (empty($logins)) {
            return array();
        }

        $logins = $this->userFilter->filterLogins($logins);
        $logins = implode(',', $logins);

        return $this->getUsers($logins);
    }

    /**
     * For each website ID, returns the access level of the given $userLogin.
     * If the user doesn't have any access to a website ('noaccess'),
     * this website will not be in the returned array.
     * If the user doesn't have any access, the returned array will be an empty array.
     *
     * @param string $userLogin User that has to be valid
     *
     * @return array    The returned array has the format
     *                    array(
     *                        idsite1 => 'view',
     *                        idsite2 => 'admin',
     *                        idsite3 => 'view',
     *                        ...
     *                    )
     */
    public function getSitesAccessFromUser($userLogin)
    {
        Piwik::checkUserHasSuperUserAccess();
        $this->checkUserExists($userLogin);
        // Super users have 'admin' access for every site
        if (Piwik::hasTheUserSuperUserAccess($userLogin)) {
            $return = array();
            $siteManagerModel = new \Piwik\Plugins\SitesManager\Model();
            $sites = $siteManagerModel->getAllSites();
            foreach ($sites as $site) {
                $return[] = array(
                    'site' => $site['idsite'],
                    'access' => 'admin'
                );
            }
            return $return;
        }
        return $this->model->getSitesAccessFromUser($userLogin);
    }

    /**
     * For each website ID, returns the access level of the given $userLogin (if the user is not a superuser).
     * If the user doesn't have any access to a website ('noaccess'),
     * this website will not be in the returned array.
     * If the user doesn't have any access, the returned array will be an empty array.
     *
     * @param string $userLogin User that has to be valid
     *
     * @param int|null $limit
     * @param int|null $offset
     * @param string|null $filter_search text to search for in site name, URLs, or group.
     * @param string|null $filter_access access level to select for, can be 'some', 'view' or 'admin' (by default 'some')
     * @return array    The returned array has the format
     *                    array(
     *                        ['idsite' => 1, 'site_name' => 'the site', 'access' => 'admin'],
     *                        ['idsite' => 2, 'site_name' => 'the other site', 'access' => 'view'],
     *                        ...
     *                    )
     * @throws Exception
     */
    public function getSitesAccessForUser($userLogin, $limit = null, $offset = 0, $filter_search = null, $filter_access = null)
    {
        Piwik::checkUserHasSomeAdminAccess();
        $this->checkUserExists($userLogin);

        if (Piwik::hasTheUserSuperUserAccess($userLogin)) {
            throw new \Exception("This method should not be used with superusers.");
        }

        $idSites = null;
        if (!Piwik::hasUserSuperUserAccess()) {
            $idSites = $this->access->getSitesIdWithAdminAccess();
            if (empty($idSites)) { // sanity check
                throw new \Exception("The current admin user does not have access to any sites.");
            }
        }

        [$sites, $totalResults] = $this->model->getSitesAccessFromUserWithFilters($userLogin, $limit, $offset, $filter_search, $filter_access, $idSites);
        foreach ($sites as &$siteAccess) {
            [$siteAccess['role'], $siteAccess['capabilities']] = $this->getRoleAndCapabilitiesFromAccess($siteAccess['access']);
            $siteAccess['role'] = empty($siteAccess['role']) ? 'noaccess' : reset($siteAccess['role']);
            unset($siteAccess['access']);
        }

        $hasAccessToAny = $this->model->getSiteAccessCount($userLogin) > 0;

        Common::sendHeader('X-Matomo-Total-Results: ' . $totalResults);
        if ($hasAccessToAny) {
            Common::sendHeader('X-Matomo-Has-Some: 1');
        }
        return $sites;
    }

    /**
     * Returns the user information (login, password hash, email, date_registered, etc.)
     *
     * @param string $userLogin the user login
     *
     * @return array the user information
     */
    public function getUser($userLogin)
    {
        Piwik::checkUserHasSuperUserAccessOrIsTheUser($userLogin);
        $this->checkUserExists($userLogin);

        $user = $this->model->getUser($userLogin);

        $user = $this->userFilter->filterUser($user);
        $user = $this->enrichUser($user);

        return $user;
    }

    /**
     * Returns the user information (login, password hash, email, date_registered, etc.)
     *
     * @param string $userEmail the user email
     *
     * @return array the user information
     */
    public function getUserByEmail($userEmail)
    {
        Piwik::checkUserHasSuperUserAccess();
        $this->checkUserEmailExists($userEmail);

        $user = $this->model->getUserByEmail($userEmail);

        $user = $this->userFilter->filterUser($user);
        $user = $this->enrichUser($user);

        return $user;
    }

    private function checkLogin($userLogin)
    {
        if ($this->userExists($userLogin)) {
            throw new Exception(Piwik::translate('UsersManager_ExceptionLoginExists', $userLogin));
        }

        if ($this->userEmailExists($userLogin)) {
            throw new Exception(Piwik::translate('UsersManager_ExceptionLoginExistsAsEmail', $userLogin));
        }

        Piwik::checkValidLoginString($userLogin);
    }

    private function checkEmail($email, $userLogin = null)
    {
        if ($this->userEmailExists($email)) {
            throw new Exception(Piwik::translate('UsersManager_ExceptionEmailExists', $email));
        }

        if ($userLogin && mb_strtolower($userLogin) !== mb_strtolower($email) && $this->userExists($email)) {
            throw new Exception(Piwik::translate('UsersManager_ExceptionEmailExistsAsLogin', $email));
        }

        if (!$userLogin && $this->userExists($email)) {
            throw new Exception(Piwik::translate('UsersManager_ExceptionEmailExistsAsLogin', $email));
        }

        if (!Piwik::isValidEmailString($email)) {
            throw new Exception(Piwik::translate('UsersManager_ExceptionInvalidEmail'));
        }
    }

    /**
     * Add a user in the database.
     * A user is defined by
     * - a login that has to be unique and valid
     * - a password that has to be valid
     * - an email that has to be in a correct format
     *
     * @see userExists()
     * @see isValidLoginString()
     * @see isValidPasswordString()
     * @see isValidEmailString()
     *
     * @throws Exception in case of an invalid parameter
     */
    public function addUser($userLogin, $password, $email, $_isPasswordHashed = false, $initialIdSite = null)
    {
        Piwik::checkUserHasSomeAdminAccess();
        UsersManager::dieIfUsersAdminIsDisabled();

        if (!Piwik::hasUserSuperUserAccess()) {
            if (empty($initialIdSite)) {
                throw new \Exception(Piwik::translate("UsersManager_AddUserNoInitialAccessError"));
            }

            Piwik::checkUserHasAdminAccess($initialIdSite);
        }

        $this->checkLogin($userLogin);
        $this->checkEmail($email);

        $password = Common::unsanitizeInputValue($password);

        if (!$_isPasswordHashed) {
            UsersManager::checkPassword($password);

            $passwordTransformed = UsersManager::getPasswordHash($password);
        } else {
            $passwordTransformed = $password;
        }

        $passwordTransformed = $this->password->hash($passwordTransformed);

        $this->model->addUser($userLogin, $passwordTransformed, $email, Date::now()->getDatetime());

        $container = StaticContainer::getContainer();
        $mail = $container->make(UserCreatedEmail::class, array(
            'login' => Piwik::getCurrentUserLogin(),
            'emailAddress' => Piwik::getCurrentUserEmail(),
            'userLogin' => $userLogin
        ));
        $mail->safeSend();

        // we reload the access list which doesn't yet take in consideration this new user
        Access::getInstance()->reloadAccess();
        Cache::deleteTrackerCache();

        /**
         * Triggered after a new user is created.
         *
         * @param string $userLogin The new user's login handle.
         */
        Piwik::postEvent('UsersManager.addUser.end', array($userLogin, $email, $password));

        if ($initialIdSite) {
            $this->setUserAccess($userLogin, 'view', $initialIdSite);
        }
    }

    /**
     * Enable or disable Super user access to the given user login. Note: When granting Super User access all previous
     * permissions of the user will be removed as the user gains access to everything.
     *
     * @param string   $userLogin          the user login.
     * @param bool|int $hasSuperUserAccess true or '1' to grant Super User access, false or '0' to remove Super User
     *                                     access.
     * @param string $passwordConfirmation the current user's password. For security purposes, this value should be
     *                                     sent as a POST parameter.
     * @throws \Exception
     */
    public function setSuperUserAccess($userLogin, $hasSuperUserAccess, $passwordConfirmation = null)
    {
        Piwik::checkUserHasSuperUserAccess();
        $this->checkUserIsNotAnonymous($userLogin);
        UsersManager::dieIfUsersAdminIsDisabled();

        $requirePasswordConfirmation = self::$SET_SUPERUSER_ACCESS_REQUIRE_PASSWORD_CONFIRMATION;
        self::$SET_SUPERUSER_ACCESS_REQUIRE_PASSWORD_CONFIRMATION = true;

        $isCliMode = Common::isPhpCliMode() && !(defined('PIWIK_TEST_MODE') && PIWIK_TEST_MODE);
        if (!$isCliMode
            && $requirePasswordConfirmation
        ) {
            $this->confirmCurrentUserPassword($passwordConfirmation);
        }
        $this->checkUserExists($userLogin);

        if (!$hasSuperUserAccess && $this->isUserTheOnlyUserHavingSuperUserAccess($userLogin)) {
            $message = Piwik::translate("UsersManager_ExceptionRemoveSuperUserAccessOnlySuperUser", $userLogin)
                        . " "
                        . Piwik::translate("UsersManager_ExceptionYouMustGrantSuperUserAccessFirst");
            throw new Exception($message);
        }

        $this->model->deleteUserAccess($userLogin);
        $this->model->setSuperUserAccess($userLogin, $hasSuperUserAccess);

        Cache::deleteTrackerCache();
    }

    /**
     * Detect whether the current user has super user access or not.
     *
     * @return bool
     */
    public function hasSuperUserAccess()
    {
        return Piwik::hasUserSuperUserAccess();
    }

    /**
     * Returns a list of all Super Users containing there userLogin and email address.
     *
     * @return array
     */
    public function getUsersHavingSuperUserAccess()
    {
        Piwik::checkUserIsNotAnonymous();

        $users = $this->model->getUsersHavingSuperUserAccess();
        $users = $this->enrichUsers($users);

        // we do not filter these users by access and return them all since we need to print this information in the
        // UI and they are allowed to see this.

        return $users;
    }

    private function enrichUsersWithLastSeen($users)
    {
        $formatter = new Formatter();

        $lastSeenTimes = LastSeenTimeLogger::getLastSeenTimesForAllUsers();
        foreach ($users as &$user) {
            $login = $user['login'];
            if (isset($lastSeenTimes[$login])) {
                $user['last_seen'] = $formatter->getPrettyTimeFromSeconds(time() - $lastSeenTimes[$login]);
            }
        }
        return $users;
    }

    private function enrichUsers($users)
    {
        if (!empty($users)) {
            foreach ($users as $index => $user) {
                $users[$index] = $this->enrichUser($user);
            }
        }
        return $users;
    }

    private function isTwoFactorAuthPluginEnabled()
    {
        if (!isset($this->twoFaPluginActivated)) {
            $this->twoFaPluginActivated = Plugin\Manager::getInstance()->isPluginActivated('TwoFactorAuth');
        }
        return $this->twoFaPluginActivated;
    }

    private function enrichUser($user)
    {
        if (empty($user)) {
            return $user;
        }

        unset($user['token_auth']);
        unset($user['password']);
        unset($user['ts_password_modified']);
        unset($user['idchange_last_viewed']);

        if ($lastSeen = LastSeenTimeLogger::getLastSeenTimeForUser($user['login'])) {
            $user['last_seen'] = Date::getDatetimeFromTimestamp($lastSeen);
        }

        if (Piwik::hasUserSuperUserAccess()) {
            $user['uses_2fa'] = !empty($user['twofactor_secret']) && $this->isTwoFactorAuthPluginEnabled();
            unset($user['twofactor_secret']);
            return $user;
        }

        $newUser = array('login' => $user['login']);

        if ($user['login'] === Piwik::getCurrentUserLogin() || !empty($user['superuser_access'])) {
            $newUser['email'] = $user['email'];
        }

        if (isset($user['role'])) {
            $newUser['role'] = $user['role'] == 'superuser' ? 'admin' : $user['role'];
        }
        if (isset($user['capabilities'])) {
            $newUser['capabilities'] = $user['capabilities'];
        }

        if (isset($user['superuser_access'])) {
            $newUser['superuser_access'] = $user['superuser_access'];
        }

        if (isset($user['last_seen'])) {
            $newUser['last_seen'] = $user['last_seen'];
        }

        return $newUser;
    }

    /**
     * Updates a user in the database.
     * Only login and password are required (case when we update the password).
     *
     * If password or email changes, it is required to also specify the password of the current user needs to be specified
     * to confirm this change.
     *
     * @see addUser() for all the parameters
     */
    public function updateUser($userLogin, $password = false, $email = false,
                               $_isPasswordHashed = false, $passwordConfirmation = false)
    {
        $requirePasswordConfirmation = self::$UPDATE_USER_REQUIRE_PASSWORD_CONFIRMATION;
        self::$UPDATE_USER_REQUIRE_PASSWORD_CONFIRMATION = true;

        $isEmailNotificationOnInConfig = Config::getInstance()->General['enable_update_users_email'];

        Piwik::checkUserHasSuperUserAccessOrIsTheUser($userLogin);
        UsersManager::dieIfUsersAdminIsDisabled();
        $this->checkUserIsNotAnonymous($userLogin);
        $this->checkUserExists($userLogin);

        $userInfo   = $this->model->getUser($userLogin);
        $changeShouldRequirePasswordConfirmation = false;

        $passwordHasBeenUpdated = false;

        if (empty($password)) {
            $password = false;
        } else {
            $changeShouldRequirePasswordConfirmation = true;
            $password = Common::unsanitizeInputValue($password);

            if (!$_isPasswordHashed) {
                UsersManager::checkPassword($password);
                $password = UsersManager::getPasswordHash($password);
            }

            $passwordInfo = $this->password->info($password);

            if (!isset($passwordInfo['algo']) || 0 >= $passwordInfo['algo']) {
                // password may have already been fully hashed
                $password = $this->password->hash($password);
            }

            $passwordHasBeenUpdated = true;
        }

        if (empty($email)) {
            $email = $userInfo['email'];
        }

        $hasEmailChanged = mb_strtolower($email) !== mb_strtolower($userInfo['email']);

        if ($hasEmailChanged) {
            $this->checkEmail($email, $userLogin);
            $changeShouldRequirePasswordConfirmation = true;
        }

        if ($changeShouldRequirePasswordConfirmation && $requirePasswordConfirmation) {
            $this->confirmCurrentUserPassword($passwordConfirmation);
        }

        $this->model->updateUser($userLogin, $password, $email);

        Cache::deleteTrackerCache();

        if ($hasEmailChanged && $isEmailNotificationOnInConfig) {
            $this->sendEmailChangedEmail($userInfo, $email);
        }

        if ($passwordHasBeenUpdated && $requirePasswordConfirmation && $isEmailNotificationOnInConfig) {
            $this->sendPasswordChangedEmail($userInfo);
        }

        /**
         * Triggered after an existing user has been updated.
         * Event notify about password change.
         *
         * @param string $userLogin The user's login handle.
         * @param boolean $passwordHasBeenUpdated Flag containing information about password change.
         */
        Piwik::postEvent('UsersManager.updateUser.end', array($userLogin, $passwordHasBeenUpdated, $email, $password));
    }

    /**
     * Delete one or more users and all its access, given its login.
     *
     * @param string $userLogin the user login(s).
     *
     * @throws Exception if the user doesn't exist or if deleting the users would leave no superusers.
     *
     * @return bool true on success
     */
    public function deleteUser($userLogin)
    {
        Piwik::checkUserHasSuperUserAccess();
        UsersManager::dieIfUsersAdminIsDisabled();
        $this->checkUserIsNotAnonymous($userLogin);

        $this->checkUserExist($userLogin);

        if ($this->isUserTheOnlyUserHavingSuperUserAccess($userLogin)) {
            $message = Piwik::translate("UsersManager_ExceptionDeleteOnlyUserWithSuperUserAccess", $userLogin)
                        . " "
                        . Piwik::translate("UsersManager_ExceptionYouMustGrantSuperUserAccessFirst");
            throw new Exception($message);
        }

        $this->model->deleteUserOnly($userLogin);
        $this->model->deleteUserOptions($userLogin);
        $this->model->deleteUserAccess($userLogin);

        $container = StaticContainer::getContainer();
        $email = $container->make(UserDeletedEmail::class, array(
            'login' => Piwik::getCurrentUserLogin(),
            'emailAddress' => Piwik::getCurrentUserEmail(),
            'userLogin' => $userLogin
        ));
        $email->safeSend();

        Cache::deleteTrackerCache();
    }

    /**
     * Returns true if the given userLogin is known in the database
     *
     * @param string $userLogin
     * @return bool true if the user is known
     */
    public function userExists($userLogin)
    {
        if ($userLogin == 'anonymous') {
            return true;
        }

        Piwik::checkUserIsNotAnonymous();
        Piwik::checkUserHasSomeViewAccess();

        if ($userLogin == Piwik::getCurrentUserLogin()) {
            return true;
        }

        return $this->model->userExists($userLogin);
    }

    /**
     * Returns true if user with given email (userEmail) is known in the database, or the Super User
     *
     * @param string $userEmail
     * @return bool true if the user is known
     */
    public function userEmailExists($userEmail)
    {
        Piwik::checkUserIsNotAnonymous();
        Piwik::checkUserHasSomeViewAccess();

        return $this->model->userEmailExists($userEmail);
    }

    /**
     * Returns the first login name of an existing user that has the given email address. If no user can be found for
     * this user an error will be returned.
     *
     * @param string $userEmail
     * @return bool true if the user is known
     */
    public function getUserLoginFromUserEmail($userEmail)
    {
        Piwik::checkUserIsNotAnonymous();
        Piwik::checkUserHasSomeAdminAccess();

        $this->checkUserEmailExists($userEmail);

        $user = $this->model->getUserByEmail($userEmail);

        // any user with some admin access is allowed to find any user by email, no need to filter by access here

        return $user['login'];
    }

    /**
     * Set an access level to a given user for a list of websites ID.
     *
     * If access = 'noaccess' the current access (if any) will be deleted.
     * If access = 'view' or 'admin' the current access level is deleted and updated with the new value.
     *
     * @param string $userLogin The user login
     * @param string|array $access Access to grant. Must have one of the following value : noaccess, view, write, admin.
     *                              May also be an array to sent additional capabilities
     * @param int|array $idSites The array of idSites on which to apply the access level for the user.
     *       If the value is "all" then we apply the access level to all the websites ID for which the current authentificated user has an 'admin' access.
     * @throws Exception if the user doesn't exist
     * @throws Exception if the access parameter doesn't have a correct value
     * @throws Exception if any of the given website ID doesn't exist
     */
    public function setUserAccess($userLogin, $access, $idSites)
    {
        UsersManager::dieIfUsersAdminIsDisabled();

        if ($access != 'noaccess') {
            $this->checkAccessType($access);
        }

        $idSites = $this->getIdSitesCheckAdminAccess($idSites);

        if ($userLogin === 'anonymous' &&
            (is_array($access) || !in_array($access, array('view', 'noaccess'), true))
        ) {
            throw new Exception(Piwik::translate("UsersManager_ExceptionAnonymousAccessNotPossible", array('noaccess', 'view')));
        }

        $roles = array();
        $capabilities = array();

        if (is_array($access)) {
            // we require one role, and optionally multiple capabilities
            [$roles, $capabilities] = $this->getRoleAndCapabilitiesFromAccess($access);

            if (count($roles) < 1) {
                $ids = implode(', ', $this->roleProvider->getAllRoleIds());
                throw new Exception(Piwik::translate('UsersManager_ExceptionNoRoleSet', $ids));
            }

            if (count($roles) > 1) {
                $ids = implode(', ', $this->roleProvider->getAllRoleIds());
                throw new Exception(Piwik::translate('UsersManager_ExceptionMultipleRoleSet', $ids));
            }

        } else {
            // as only one access is set, we require it to be a role or "noaccess"...
            if ($access !== 'noaccess') {
                $this->roleProvider->checkValidRole($access);
                $roles[] = $access;
            }
        }

        $this->checkUserExist($userLogin);
        $this->checkUsersHasNotSuperUserAccess($userLogin);

        $this->model->deleteUserAccess($userLogin, $idSites);

        if ($access === 'noaccess') {
            // if the access is noaccess then we don't save it as this is the default value
            // when no access are specified
            Piwik::postEvent('UsersManager.removeSiteAccess', array($userLogin, $idSites));
        } else {
            $role = array_shift($roles);
            $this->model->addUserAccess($userLogin, $role, $idSites);
        }

        if (!empty($capabilities)) {
            $this->addCapabilities($userLogin, $capabilities, $idSites);
        }

        // we reload the access list which doesn't yet take in consideration this new user access
        $this->reloadPermissions();
    }

    /**
     * Adds the given capabilities to the given user for the given sites.
     * The capability will be added only when the user also has access to a site, for example View, Write, or Admin.
     * Note: You can neither add any capability to a super user, nor to the anonymous user.
     * Note: If the user has assigned a role which already grants the given capability, the capability will not be added in
     * the backend.
     *
     * @param string $userLogin The user login
     * @param string|string[] $capabilities  To fetch a list of available capabilities call "UsersManager.getAvailableCapabilities".
     * @param int|int[] $idSites
     * @throws Exception
     */
    public function addCapabilities($userLogin, $capabilities, $idSites)
    {
        $idSites = $this->getIdSitesCheckAdminAccess($idSites);

        if ($userLogin == 'anonymous') {
            throw new Exception(Piwik::translate("UsersManager_ExceptionAnonymousNoCapabilities"));
        }

        $this->checkUserExists($userLogin);
        $this->checkUsersHasNotSuperUserAccess([$userLogin]);

        if (!is_array($capabilities)){
            $capabilities = array($capabilities);
        }

        foreach ($capabilities as $entry) {
            $this->capabilityProvider->checkValidCapability($entry);
        }

        [$sitesIdWithRole, $sitesIdWithCapability] = $this->getRolesAndCapabilitiesForLogin($userLogin);

        foreach ($capabilities as $entry) {
            $cap = $this->capabilityProvider->getCapability($entry);

            foreach ($idSites as $idSite) {
                $hasRole = array_key_exists($idSite, $sitesIdWithRole);
                $hasCapabilityAlready = array_key_exists($idSite, $sitesIdWithCapability) && in_array($entry, $sitesIdWithCapability[$idSite], true);

                // so far we are adding the capability only to people that also have a role...
                // to be defined how to handle this... eg we are not throwing an exception currently
                // as it might be used as part of bulk action etc.
                if ($hasRole && !$hasCapabilityAlready) {
                    $theRole = $sitesIdWithRole[$idSite];
                    if ($cap->hasRoleCapability($theRole)) {
                        // todo this behaviour needs to be defined...
                        // when the role already supports this capability we do not add it again
                        continue;
                    }

                    $this->model->addUserAccess($userLogin, $entry, array($idSite));
                }
            }

        }

        // we reload the access list which doesn't yet take in consideration this new user access
        $this->reloadPermissions();
    }

    private function getRolesAndCapabilitiesForLogin($userLogin)
    {
        $sites = $this->model->getSitesAccessFromUser($userLogin);
        $roleIds = $this->roleProvider->getAllRoleIds();

        $sitesIdWithRole = array();
        $sitesIdWithCapability = array();
        foreach ($sites as $site) {
            if (in_array($site['access'], $roleIds, true)) {
                $sitesIdWithRole[(int) $site['site']] = $site['access'];
            } else {
                if (!isset($sitesIdWithCapability[(int) $site['site']])) {
                    $sitesIdWithCapability[(int) $site['site']] = array();
                }
                $sitesIdWithCapability[(int) $site['site']][] = $site['access'];
            }
        }
        return [$sitesIdWithRole, $sitesIdWithCapability];
    }

    /**
     * Removes the given capabilities from the given user for the given sites.
     * The capability will be only removed if it is actually granted as a separate capability. If the user has a role
     * that includes a specific capability, for example "Admin", then the capability will not be removed because the
     * assigned role will always include this capability.
     *
     * @param string $userLogin The user login
     * @param string|string[] $capabilities  To fetch a list of available capabilities call "UsersManager.getAvailableCapabilities".
     * @param int|int[] $idSites
     * @throws Exception
     */
    public function removeCapabilities($userLogin, $capabilities, $idSites)
    {
        $idSites = $this->getIdSitesCheckAdminAccess($idSites);

        $this->checkUserExists($userLogin);

        if (!is_array($capabilities)){
            $capabilities = array($capabilities);
        }

        foreach ($capabilities as $capability) {
            $this->capabilityProvider->checkValidCapability($capability);
        }

        foreach ($capabilities as $capability) {
            $this->model->removeUserAccess($userLogin, $capability, $idSites);
        }

        // we reload the access list which doesn't yet take in consideration this removed capability
        $this->reloadPermissions();
    }

    private function reloadPermissions()
    {
        Access::getInstance()->reloadAccess();
        Cache::deleteTrackerCache();
    }

    private function getIdSitesCheckAdminAccess($idSites)
    {
        // in case idSites is all we grant access to all the websites on which the current connected user has an 'admin' access
        if ($idSites === 'all') {
            $idSites = \Piwik\Plugins\SitesManager\API::getInstance()->getSitesIdWithAdminAccess();
        } // in case the idSites is an integer we build an array
        else {
            $idSites = Site::getIdSitesFromIdSitesString($idSites);
        }

        if (empty($idSites)) {
            throw new Exception('Specify at least one website ID in &idSites=');
        }

        // it is possible to set user access on websites only for the websites admin
        // basically an admin can give the view or the admin access to any user for the websites they manage
        Piwik::checkUserHasAdminAccess($idSites);

        if (!is_array($idSites)) {
            $idSites = array($idSites);
        }

        return $idSites;
    }

    /**
     * Throws an exception is the user login doesn't exist
     *
     * @param string $userLogin user login
     * @throws Exception if the user doesn't exist
     */
    private function checkUserExists($userLogin)
    {
        if (!$this->userExists($userLogin)) {
            throw new Exception(Piwik::translate("UsersManager_ExceptionUserDoesNotExist", $userLogin));
        }
    }

    /**
     * Throws an exception is the user email cannot be found
     *
     * @param string $userEmail user email
     * @throws Exception if the user doesn't exist
     */
    private function checkUserEmailExists($userEmail)
    {
        if (!$this->userEmailExists($userEmail)) {
            throw new Exception(Piwik::translate("UsersManager_ExceptionUserDoesNotExist", $userEmail));
        }
    }

    private function checkUserIsNotAnonymous($userLogin)
    {
        if ($userLogin == 'anonymous') {
            throw new Exception(Piwik::translate("UsersManager_ExceptionEditAnonymous"));
        }
    }

    private function checkUsersHasNotSuperUserAccess($userLogins)
    {
        $userLogins = (array) $userLogins;
        $superusers = $this->getUsersHavingSuperUserAccess();
        $superusers = array_column($superusers, null, 'login');

        foreach ($userLogins as $userLogin) {
            if (isset($superusers[$userLogin])) {
                throw new Exception(Piwik::translate("UsersManager_ExceptionUserHasSuperUserAccess", $userLogin));
            }
        }
    }

    /**
     * @param string|string[] $userLogin
     * @return bool
     */
    private function isUserTheOnlyUserHavingSuperUserAccess($userLogin)
    {
        if (!is_array($userLogin)) {
            $userLogin = [$userLogin];
        }

        $superusers = $this->getUsersHavingSuperUserAccess();
        $superusersByLogin = array_column($superusers, null, 'login');

        foreach ($userLogin as $login) {
            unset($superusersByLogin[$login]);
        }

        return empty($superusersByLogin);
    }

    /**
     * Generates an app specific API token every time you call this method. You should ideally store this token securely
     * in your app and not generate a new token every time.
     *
     * If the username/password combination is incorrect an invalid token will be returned.
     *
     * @param string $userLogin Login or Email address
     * @param string $passwordConfirmation the current user's password. For security purposes, this value should be
     *                                     sent as a POST parameter.
     * @param string $description The description for this app specific password, for example your app name. Max 100 characters are allowed
     * @param string $expireDate Optionally a date when the token should expire
     * @param string $expireHours Optionally number of hours for how long the token should be valid before it expires.
     *                            If expireDate is set and expireHours, then expireDate will be used.
     *                            If expireDate is set and expireHours, then expireDate will be used.
     * @return string
     */
    public function createAppSpecificTokenAuth($userLogin, $passwordConfirmation, $description, $expireDate = null, $expireHours = 0)
    {
        $user = $this->model->getUser($userLogin);
        if (empty($user) && Piwik::isValidEmailString($userLogin)) {
            $user = $this->model->getUserByEmail($userLogin);
            if (!empty($user['login'])) {
                $userLogin = $user['login'];
            }
        }

        $passwordConfirmation = Common::unsanitizeInputValue($passwordConfirmation);
        if (empty($user) || !$this->passwordVerifier->isPasswordCorrect($userLogin, $passwordConfirmation)) {
            if (empty($user)) {
                /**
                 * @ignore
                 * @internal
                 */
                Piwik::postEvent('Login.authenticate.failed', array($userLogin));
            }

            throw new \Exception(Piwik::translate('UsersManager_CurrentPasswordNotCorrect'));
        }

        if (empty($expireDate) && !empty($expireHours) && is_numeric($expireHours)) {
            $expireDate = Date::now()->addHour($expireHours)->getDatetime();
        } elseif (!empty($expireDate)) {
            $expireDate = Date::factory($expireDate)->getDatetime();
        }

        $generatedToken = $this->model->generateRandomTokenAuth();
        $this->model->addTokenAuth($userLogin, $generatedToken, $description, Date::now()->getDatetime(), $expireDate);

        return $generatedToken;
    }

    public function newsletterSignup()
    {
        Piwik::checkUserIsNotAnonymous();

        $userLogin = Piwik::getCurrentUserLogin();
        $email = Piwik::getCurrentUserEmail();

        $success = NewsletterSignup::signupForNewsletter($userLogin, $email, true);
        $result = $success ? array('success' => true) : array('error' => true);
        return $result;
    }

    private function isUserHasAdminAccessTo($idSite)
    {
        try {
            Piwik::checkUserHasAdminAccess([$idSite]);
            return true;
        } catch (NoAccessException $ex) {
            return false;
        }
    }

    private function checkUserExist($userLogin)
    {
        $userExists = $this->model->userExists($userLogin);
        if (!$userExists) {
            throw new Exception(Piwik::translate("UsersManager_ExceptionUserDoesNotExist", $userLogin));
        }
    }

    private function getRoleAndCapabilitiesFromAccess($access)
    {
        $roles = [];
        $capabilities = [];

        foreach ($access as $entry) {
            if (empty($entry)) {
                continue;
            }

            if ($this->roleProvider->isValidRole($entry)) {
                $roles[] = $entry;
            } else {
                if ($this->isValidAccessType($entry)) {
                    $capabilities[] = $entry;
                }
            }
        }
        return [$roles, $capabilities];
    }

    private function confirmCurrentUserPassword($passwordConfirmation)
    {
        if (empty($passwordConfirmation)) {
            throw new Exception(Piwik::translate('UsersManager_ConfirmWithPassword'));
        }

        $passwordConfirmation = Common::unsanitizeInputValue($passwordConfirmation);

        $loginCurrentUser = Piwik::getCurrentUserLogin();
        if (!$this->passwordVerifier->isPasswordCorrect($loginCurrentUser, $passwordConfirmation)) {
            throw new Exception(Piwik::translate('UsersManager_CurrentPasswordNotCorrect'));
        }
    }

    private function sendEmailChangedEmail($user, $newEmail)
    {
        // send the mail to both the old email and the new email
        foreach ([$newEmail, $user['email']] as $emailTo) {
            $this->sendUserInfoChangedEmail('email', $user, $newEmail, $emailTo, 'UsersManager_EmailChangeNotificationSubject');
        }
    }

    private function sendUserInfoChangedEmail($type, $user, $newValue, $emailTo, $subject)
    {
        $deviceDescription = $this->getDeviceDescription();

        $mail = new UserInfoChangedEmail($type, $newValue, $deviceDescription, $user['login']);

        $mail->addTo($emailTo, $user['login']);
        $mail->setSubject(Piwik::translate($subject));

        $mail->send();
    }

    private function sendPasswordChangedEmail($user)
    {
        $this->sendUserInfoChangedEmail('password', $user, null, $user['email'], 'UsersManager_PasswordChangeNotificationSubject');
    }

    private function getDeviceDescription()
    {
        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';

        $uaParser = new DeviceDetector($userAgent);
        $uaParser->parse();

        $deviceName = ucfirst($uaParser->getDeviceName());
        if (!empty($deviceName)) {
            $description = $deviceName;
        } else {
            $description = Piwik::translate('General_Unknown');
        }

        $deviceBrand = $uaParser->getBrandName();
        $deviceModel = $uaParser->getModel();
        if (!empty($deviceBrand)
            || !empty($deviceModel)
        ) {
            $parts = array_filter([$deviceBrand, $deviceModel]);
            $description .= ' (' . implode(' ', $parts) . ')';
        }

        return $description;
    }
}