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

API.php « SitesManager « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 493d6656cc41cb4420976c4bfa23c0483380a1e9 (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
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
<?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\SitesManager;

use DateTimeZone;
use Exception;
use Matomo\Network\IPUtils;
use Piwik\Access;
use Piwik\Common;
use Piwik\Container\StaticContainer;
use Piwik\DataAccess\Model as CoreModel;
use Piwik\Date;
use Piwik\Exception\UnexpectedWebsiteFoundException;
use Piwik\Intl\Data\Provider\CurrencyDataProvider;
use Piwik\Option;
use Piwik\Piwik;
use Piwik\Plugin\SettingsProvider;
use Piwik\Plugins\CorePluginsAdmin\SettingsMetadata;
use Piwik\Plugins\WebsiteMeasurable\Settings\Urls;
use Piwik\ProxyHttp;
use Piwik\Scheduler\Scheduler;
use Piwik\Settings\Measurable\MeasurableProperty;
use Piwik\Settings\Measurable\MeasurableSettings;
use Piwik\SettingsPiwik;
use Piwik\SettingsServer;
use Piwik\Site;
use Piwik\Tracker\Cache;
use Piwik\Tracker\TrackerCodeGenerator;
use Piwik\Translation\Translator;
use Piwik\Url;
use Piwik\UrlHelper;

/**
 * The SitesManager API gives you full control on Websites in Matomo (create, update and delete), and many methods to retrieve websites based on various attributes.
 *
 * This API lets you create websites via "addSite", update existing websites via "updateSite" and delete websites via "deleteSite".
 * When creating websites, it can be useful to access internal codes used by Matomo for currencies via "getCurrencyList", or timezones via "getTimezonesList".
 *
 * There are also many ways to request a list of websites: from the website ID via "getSiteFromId" or the site URL via "getSitesIdFromSiteUrl".
 * Often, the most useful technique is to list all websites that are known to a current user, based on the token_auth, via
 * "getSitesWithAdminAccess", "getSitesWithViewAccess" or "getSitesWithAtLeastViewAccess" (which returns both).
 *
 * Some methods will affect all websites globally: "setGlobalExcludedIps" will set the list of IPs to be excluded on all websites,
 * "setGlobalExcludedQueryParameters" will set the list of URL parameters to remove from URLs for all websites.
 * The existing values can be fetched via "getExcludedIpsGlobal" and "getExcludedQueryParametersGlobal".
 * See also the documentation about <a href='http://matomo.org/docs/manage-websites/' rel='noreferrer' target='_blank'>Managing Websites</a> in Matomo.
 * @method static \Piwik\Plugins\SitesManager\API getInstance()
 */
class API extends \Piwik\Plugin\API
{
    const DEFAULT_SEARCH_KEYWORD_PARAMETERS = 'q,query,s,search,searchword,k,keyword';
    const OPTION_EXCLUDED_IPS_GLOBAL = 'SitesManager_ExcludedIpsGlobal';
    const OPTION_DEFAULT_TIMEZONE = 'SitesManager_DefaultTimezone';
    const OPTION_DEFAULT_CURRENCY = 'SitesManager_DefaultCurrency';
    const OPTION_EXCLUDED_QUERY_PARAMETERS_GLOBAL = 'SitesManager_ExcludedQueryParameters';
    const OPTION_SEARCH_KEYWORD_QUERY_PARAMETERS_GLOBAL = 'SitesManager_SearchKeywordParameters';
    const OPTION_SEARCH_CATEGORY_QUERY_PARAMETERS_GLOBAL = 'SitesManager_SearchCategoryParameters';
    const OPTION_EXCLUDED_USER_AGENTS_GLOBAL = 'SitesManager_ExcludedUserAgentsGlobal';
    const OPTION_EXCLUDED_REFERRERS_GLOBAL = 'SitesManager_ExcludedReferrersGlobal';
    const OPTION_KEEP_URL_FRAGMENTS_GLOBAL = 'SitesManager_KeepURLFragmentsGlobal';

    /**
     * @var SettingsProvider
     */
    private $settingsProvider;

    /**
     * @var SettingsMetadata
     */
    private $settingsMetadata;

    /**
     * @var Translator
     */
    private $translator;

    private $timezoneNameCache = [];

    public function __construct(SettingsProvider $provider, SettingsMetadata $settingsMetadata, Translator $translator)
    {
        $this->settingsProvider = $provider;
        $this->settingsMetadata = $settingsMetadata;
        $this->translator = $translator;
    }

    /**
     * Returns the javascript tag for the given idSite.
     * This tag must be included on every page to be tracked by Matomo
     *
     * @param int    $idSite
     * @param string $piwikUrl
     * @param bool   $mergeSubdomains
     * @param bool   $groupPageTitlesByDomain
     * @param bool   $mergeAliasUrls
     * @param bool   $visitorCustomVariables
     * @param bool   $pageCustomVariables
     * @param bool   $customCampaignNameQueryParam
     * @param bool   $customCampaignKeywordParam
     * @param bool   $doNotTrack
     * @param bool   $disableCookies
     * @param bool   $trackNoScript
     * @param bool   $crossDomain
     * @param bool   $forceMatomoEndpoint Whether the Matomo endpoint should be forced if Matomo was installed prior 3.7.0.
     * @param bool   $excludedQueryParams
     * @param mixed  $excludedReferrers array or comma separated string of ignored referrers. Defaults to configured ignored referrers
     *
     * @return string The Javascript tag ready to be included on the HTML pages
     * @throws Exception
     */
    public function getJavascriptTag(
        $idSite,
        $piwikUrl = '',
        $mergeSubdomains = false,
        $groupPageTitlesByDomain = false,
        $mergeAliasUrls = false,
        $visitorCustomVariables = false,
        $pageCustomVariables = false,
        $customCampaignNameQueryParam = false,
        $customCampaignKeywordParam = false,
        $doNotTrack = false,
        $disableCookies = false,
        $trackNoScript = false,
        $crossDomain = false,
        $forceMatomoEndpoint = false,
        $excludedQueryParams = false,
        $excludedReferrers = false
    ) {
        Piwik::checkUserHasViewAccess($idSite);

        if (empty($piwikUrl)) {
            $piwikUrl = SettingsPiwik::getPiwikUrl();
        }

        // Revert the automatic encoding
        // TODO remove that when https://github.com/piwik/piwik/issues/4231 is fixed
        $piwikUrl = Common::unsanitizeInputValue($piwikUrl);
        $visitorCustomVariables = Common::unsanitizeInputValues($visitorCustomVariables);
        $pageCustomVariables = Common::unsanitizeInputValues($pageCustomVariables);
        $customCampaignNameQueryParam = Common::unsanitizeInputValue($customCampaignNameQueryParam);
        $customCampaignKeywordParam = Common::unsanitizeInputValue($customCampaignKeywordParam);

        if (is_array($excludedQueryParams)) {
            $excludedQueryParams = implode(',', $excludedQueryParams);
        }
        $excludedQueryParams = Common::unsanitizeInputValue($excludedQueryParams);

        $generator = new TrackerCodeGenerator();
        if ($forceMatomoEndpoint) {
            $generator->forceMatomoEndpoint();
        }

        $code = $generator->generate(
            $idSite,
            $piwikUrl,
            $mergeSubdomains,
            $groupPageTitlesByDomain,
            $mergeAliasUrls,
            $visitorCustomVariables,
            $pageCustomVariables,
            $customCampaignNameQueryParam,
            $customCampaignKeywordParam,
            $doNotTrack,
            $disableCookies,
            $trackNoScript,
            $crossDomain,
            $excludedQueryParams,
            $excludedReferrers
        );

        return str_replace(['<br>', '<br />', '<br/>'], '', $code);
    }

    /**
     * Returns image link tracking code for a given site with specified options.
     *
     * @param int $idSite The ID to generate tracking code for.
     * @param string $piwikUrl The domain and URL path to the Matomo installation.
     * @param int $idGoal An ID for a goal to trigger a conversion for.
     * @param int $revenue The revenue of the goal conversion. Only used if $idGoal is supplied.
     * @param bool $forceMatomoEndpoint Whether the Matomo endpoint should be forced if Matomo was installed prior 3.7.0.
     * @return string The HTML tracking code.
     */
    public function getImageTrackingCode(
        $idSite,
        $piwikUrl = '',
        $actionName = false,
        $idGoal = false,
        $revenue = false,
        $forceMatomoEndpoint = false
    ) {
        $urlParams = ['idsite' => $idSite, 'rec' => 1];

        if ($actionName !== false) {
            $urlParams['action_name'] = urlencode(Common::unsanitizeInputValue($actionName));
        }

        if ($idGoal !== false) {
            $urlParams['idgoal'] = $idGoal;
            if ($revenue !== false) {
                $urlParams['revenue'] = $revenue;
            }
        }

        /**
         * Triggered when generating image link tracking code server side. Plugins can use
         * this event to customise the image tracking code that is displayed to the
         * user.
         *
         * @param string &$piwikHost The domain and URL path to the Matomo installation, eg,
         *                           `'examplepiwik.com/path/to/piwik'`.
         * @param array &$urlParams The query parameters used in the <img> element's src
         *                          URL. See Matomo's image tracking docs for more info.
         */
        Piwik::postEvent('SitesManager.getImageTrackingCode', [&$piwikUrl, &$urlParams]);

        $trackerCodeGenerator = new TrackerCodeGenerator();
        if ($forceMatomoEndpoint) {
            $trackerCodeGenerator->forceMatomoEndpoint();
        }
        $matomoPhp = $trackerCodeGenerator->getPhpTrackerEndpoint();

        $url = (ProxyHttp::isHttps() ? "https://" : "http://") . rtrim($piwikUrl, '/') . '/' . $matomoPhp . '?' . Url::getQueryStringFromParameters($urlParams);
        $html = "<!-- Matomo Image Tracker-->
<img referrerpolicy=\"no-referrer-when-downgrade\" src=\"" . htmlspecialchars($url, ENT_COMPAT, 'UTF-8') . "\" style=\"border:0\" alt=\"\" />
<!-- End Matomo -->";
        return htmlspecialchars($html, ENT_COMPAT, 'UTF-8');
    }

    /**
     * Returns all websites belonging to the specified group
     * @param string $group Group name
     * @return array of sites
     */
    public function getSitesFromGroup($group = '')
    {
        Piwik::checkUserHasSuperUserAccess();

        $group = trim($group);
        $sites = $this->getModel()->getSitesFromGroup($group);

        foreach ($sites as &$site) {
            $this->enrichSite($site);
        }

        $sites = Site::setSitesFromArray($sites);
        return $sites;
    }

    /**
     * Returns the list of website groups, including the empty group
     * if no group were specified for some websites
     *
     * @return array of group names strings
     */
    public function getSitesGroups()
    {
        Piwik::checkUserHasSuperUserAccess();

        $groups = $this->getModel()->getSitesGroups();
        $cleanedGroups = array_map('trim', $groups);

        return $cleanedGroups;
    }

    /**
     * Returns the website information : name, main_url
     *
     * @throws Exception if the site ID doesn't exist or the user doesn't have access to it
     * @param int $idSite
     * @return array
     */
    public function getSiteFromId($idSite)
    {
        Piwik::checkUserHasViewAccess($idSite);

        $site = $this->getModel()->getSiteFromId($idSite);

        if ($site) {
            $this->enrichSite($site);
        }

        Site::setSiteFromArray($idSite, $site);

        return $site;
    }

    private function getModel()
    {
        return new Model();
    }

    /**
     * Returns the list of all URLs registered for the given idSite (main_url + alias URLs).
     *
     * @throws Exception if the website ID doesn't exist or the user doesn't have access to it
     * @param int $idSite
     * @return array list of URLs
     */
    public function getSiteUrlsFromId($idSite)
    {
        Piwik::checkUserHasViewAccess($idSite);
        return $this->getModel()->getSiteUrlsFromId($idSite);
    }

    private function getSitesId()
    {
        return $this->getModel()->getSitesId();
    }

    /**
     * Returns all websites, requires Super User access
     *
     * @return array The list of websites, indexed by idsite
     */
    public function getAllSites()
    {
        Piwik::checkUserHasSuperUserAccess();

        $sites  = $this->getModel()->getAllSites();
        $return = [];
        foreach ($sites as $site) {
            $this->enrichSite($site);
            $return[$site['idsite']] = $site;
        }

        $return = Site::setSitesFromArray($return);

        return $return;
    }

    /**
     * Returns the list of all the website IDs registered.
     * Requires Super User access.
     *
     * @return array The list of website IDs
     */
    public function getAllSitesId()
    {
        Piwik::checkUserHasSuperUserAccess();
        try {
            return $this->getSitesId();
        } catch (Exception $e) {
            // can be called before Matomo tables are created so return empty
            return [];
        }
    }

    /**
     * Returns the list of websites with the 'admin' access for the current user.
     * For the superUser it returns all the websites in the database.
     *
     * @param bool $fetchAliasUrls
     * @param false|string $pattern
     * @param false|int    $limit
     * @param []|int[] $sitesToExclude optional array of Integer IDs of sites to exclude from the result.
     * @return array for each site, an array of information (idsite, name, main_url, etc.)
     */
    public function getSitesWithAdminAccess($fetchAliasUrls = false, $pattern = false, $limit = false, $sitesToExclude = [])
    {
        $sitesId = $this->getSitesIdWithAdminAccess();

        // Remove the sites to exclude from the list of IDs.
        if (is_array($sitesId) && is_array($sitesToExclude) && count($sitesToExclude)) {
            $sitesId = array_diff($sitesId, $sitesToExclude);
        }

        if ($pattern === false) {
            $sites = $this->getSitesFromIds($sitesId, $limit);
        } else {
            $sites = $this->getModel()->getPatternMatchSites($sitesId, $pattern, $limit);

            foreach ($sites as &$site) {
                $this->enrichSite($site);
            }

            $sites = Site::setSitesFromArray($sites);
        }

        if ($fetchAliasUrls) {
            foreach ($sites as &$site) {
                $site['alias_urls'] = $this->getSiteUrlsFromId($site['idsite']);
            }
        }

        return $sites;
    }

    /**
     * Returns the list of websites with the 'view' access for the current user.
     * For the superUser it doesn't return any result because the superUser has admin access on all the websites (use getSitesWithAtLeastViewAccess() instead).
     *
     * @return array for each site, an array of information (idsite, name, main_url, etc.)
     */
    public function getSitesWithViewAccess()
    {
        $sitesId = $this->getSitesIdWithViewAccess();
        return $this->getSitesFromIds($sitesId);
    }

    /**
     * Returns the list of websites with the 'view' or 'admin' access for the current user.
     * For the superUser it returns all the websites in the database.
     *
     * @param bool|int $limit Specify max number of sites to return
     * @param bool $_restrictSitesToLogin Hack necessary when running scheduled tasks, where "Super User" is forced, but sometimes not desired, see #3017
     * @return array array for each site, an array of information (idsite, name, main_url, etc.)
     */
    public function getSitesWithAtLeastViewAccess($limit = false, $_restrictSitesToLogin = false)
    {
        $sitesId = $this->getSitesIdWithAtLeastViewAccess($_restrictSitesToLogin);
        return $this->getSitesFromIds($sitesId, $limit);
    }

    /**
     * Returns the list of websites ID with the 'admin' access for the current user.
     * For the superUser it returns all the websites in the database.
     *
     * @return array list of websites ID
     */
    public function getSitesIdWithAdminAccess()
    {
        $sitesId = Access::getInstance()->getSitesIdWithAdminAccess();
        return $sitesId;
    }

    /**
     * Returns the list of websites ID with the 'view' access for the current user.
     * For the superUser it doesn't return any result because the superUser has admin access on all the websites (use getSitesIdWithAtLeastViewAccess() instead).
     *
     * @return array list of websites ID
     */
    public function getSitesIdWithViewAccess()
    {
        return Access::getInstance()->getSitesIdWithViewAccess();
    }

    /**
     * Returns the list of websites ID with the 'write' access for the current user.
     * For the superUser it doesn't return any result because the superUser has write access on all the websites (use getSitesIdWithAtLeastWriteAccess() instead).
     *
     * @return array list of websites ID
     */
    public function getSitesIdWithWriteAccess()
    {
        return Access::getInstance()->getSitesIdWithWriteAccess();
    }

    /**
     * Returns the list of websites ID with the 'view' or 'admin' access for the current user.
     * For the superUser it returns all the websites in the database.
     *
     * @param bool $_restrictSitesToLogin
     * @return array list of websites ID
     */
    public function getSitesIdWithAtLeastViewAccess($_restrictSitesToLogin = false)
    {
        /** @var Scheduler $scheduler */
        $scheduler = StaticContainer::getContainer()->get('Piwik\Scheduler\Scheduler');

        if (Piwik::hasUserSuperUserAccess() && !$scheduler->isRunningTask()) {
            return Access::getInstance()->getSitesIdWithAtLeastViewAccess();
        }

        if (
            !empty($_restrictSitesToLogin)
            // Only Super User or logged in user can see viewable sites for a specific login,
            // but during scheduled task execution, we sometimes want to restrict sites to
            // a different login than the superuser.
            && (Piwik::hasUserSuperUserAccessOrIsTheUser($_restrictSitesToLogin)
                || $scheduler->isRunningTask())
        ) {
            if (Piwik::hasTheUserSuperUserAccess($_restrictSitesToLogin)) {
                return Access::getInstance()->getSitesIdWithAtLeastViewAccess();
            }

            $accessRaw = Access::getInstance()->getRawSitesWithSomeViewAccess($_restrictSitesToLogin);
            $sitesId   = [];

            foreach ($accessRaw as $access) {
                $sitesId[] = $access['idsite'];
            }

            return $sitesId;
        } else {
            return Access::getInstance()->getSitesIdWithAtLeastViewAccess();
        }
    }

    /**
     * Returns the list of websites from the ID array in parameters.
     * The user access is not checked in this method so the ID have to be accessible by the user!
     *
     * @param array $idSites list of website ID
     * @param bool $limit
     * @return array
     */
    private function getSitesFromIds($idSites, $limit = false)
    {
        $sites = $this->getModel()->getSitesFromIds($idSites, $limit);

        foreach ($sites as &$site) {
            $this->enrichSite($site);
        }

        $sites = Site::setSitesFromArray($sites);

        return $sites;
    }

    protected function getNormalizedUrls($url)
    {
        // if found, remove scheme and www. from URL
        $hostname = str_replace('www.', '', $url);
        $hostname = str_replace('http://', '', $hostname);
        $hostname = str_replace('https://', '', $hostname);

        // return all variations of the URL
        return [
            $url,
            "http://" . $hostname,
            "http://www." . $hostname,
            "https://" . $hostname,
            "https://www." . $hostname
        ];
    }

    /**
     * Returns the list of websites ID associated with a URL.
     *
     * @param string $url
     * @return array list of websites ID
     */
    public function getSitesIdFromSiteUrl($url)
    {
        $url = $this->removeTrailingSlash($url);
        $normalisedUrls = $this->getNormalizedUrls($url);

        if (Piwik::hasUserSuperUserAccess()) {
            $ids   = $this->getModel()->getAllSitesIdFromSiteUrl($normalisedUrls);
        } else {
            $login = Piwik::getCurrentUserLogin();
            $ids   = $this->getModel()->getSitesIdFromSiteUrlHavingAccess($login, $normalisedUrls);
        }

        return $ids;
    }

    /**
     * Returns all websites with a timezone matching one the specified timezones
     *
     * @param array $timezones
     * @return array
     * @ignore
     */
    public function getSitesIdFromTimezones($timezones)
    {
        Piwik::checkUserHasSuperUserAccess();

        $timezones = Piwik::getArrayFromApiParameter($timezones);
        $timezones = array_unique($timezones);

        $ids = $this->getModel()->getSitesFromTimezones($timezones);

        $return = [];
        foreach ($ids as $id) {
            $return[] = $id['idsite'];
        }

        return $return;
    }

    private function enrichSite(&$site)
    {
        $cacheKey = $site['timezone'] . $this->translator->getCurrentLanguage();
        if (!isset($this->timezoneNameCache[$cacheKey])) {
            //cached as this can be called VERY often and getTimezoneName is quite slow
            $this->timezoneNameCache[$cacheKey] = $this->getTimezoneName($site['timezone']);
        }
        $site['timezone_name'] = $this->timezoneNameCache[$cacheKey];

        $key = 'Intl_Currency_' . $site['currency'];
        $name = $this->translator->translate($key);

        $site['currency_name'] = ($key === $name) ? $site['currency'] : $name;

        // don't want to expose other user logins here
        if (!Piwik::hasUserSuperUserAccess()) {
            unset($site['creator_login']);
        }
    }

    /**
     * Add a website.
     * Requires Super User access.
     *
     * The website is defined by a name and an array of URLs.
     * @param string $siteName Site name
     * @param array|string $urls The URLs array must contain at least one URL called the 'main_url' ;
     *                        if several URLs are provided in the array, they will be recorded
     *                        as Alias URLs for this website.
     *                        When calling API via HTTP specify multiple URLs via `&urls[]=http...&urls[]=http...`.
     * @param int $ecommerce Is Ecommerce Reporting enabled for this website?
     * @param null $siteSearch
     * @param string $searchKeywordParameters Comma separated list of search keyword parameter names
     * @param string $searchCategoryParameters Comma separated list of search category parameter names
     * @param string $excludedIps Comma separated list of IPs to exclude from the reports (allows wildcards)
     * @param null $excludedQueryParameters
     * @param string $timezone Timezone string, eg. 'Europe/London'
     * @param string $currency Currency, eg. 'EUR'
     * @param string $group Website group identifier
     * @param string $startDate Date at which the statistics for this website will start. Defaults to today's date in YYYY-MM-DD format
     * @param null|string $excludedUserAgents
     * @param int $keepURLFragments If 1, URL fragments will be kept when tracking. If 2, they
     *                              will be removed. If 0, the default global behavior will be used.
     * @param array|null $settingValues JSON serialized settings eg {settingName: settingValue, ...}
     * @see getKeepURLFragmentsGlobal.
     * @param string $type The website type, defaults to "website" if not set.
     * @param bool|null $excludeUnknownUrls Track only URL matching one of website URLs
     * @param string|null $excludedReferrers Comma separated list of hosts/urls to exclude from referrer detection
     *
     * @return int the website ID created
     */
    public function addSite(
        $siteName,
        $urls = null,
        $ecommerce = null,
        $siteSearch = null,
        $searchKeywordParameters = null,
        $searchCategoryParameters = null,
        $excludedIps = null,
        $excludedQueryParameters = null,
        $timezone = null,
        $currency = null,
        $group = null,
        $startDate = null,
        $excludedUserAgents = null,
        $keepURLFragments = null,
        $type = null,
        $settingValues = null,
        $excludeUnknownUrls = null,
        $excludedReferrers = null
    ) {
        Piwik::checkUserHasSuperUserAccess();
        SitesManager::dieIfSitesAdminIsDisabled();

        $this->checkName($siteName);

        if (!isset($settingValues)) {
            $settingValues = [];
        }

        $coreProperties = [];
        $coreProperties = $this->setSettingValue('urls', $urls, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('ecommerce', $ecommerce, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('group', $group, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('sitesearch', $siteSearch, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('sitesearch_keyword_parameters', explode(',', $searchKeywordParameters ?? ''), $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('sitesearch_category_parameters', explode(',', $searchCategoryParameters ?? ''), $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('keep_url_fragment', $keepURLFragments, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('exclude_unknown_urls', $excludeUnknownUrls, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('excluded_ips', explode(',', $excludedIps ?? ''), $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('excluded_parameters', explode(',', $excludedQueryParameters ?? ''), $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('excluded_user_agents', explode(',', $excludedUserAgents ?? ''), $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('excluded_referrers', explode(',', $excludedReferrers ?? ''), $coreProperties, $settingValues);

        $timezone = trim($timezone ?? '');
        if (empty($timezone)) {
            $timezone = $this->getDefaultTimezone();
        }
        $this->checkValidTimezone($timezone);

        if (empty($currency)) {
            $currency = $this->getDefaultCurrency();
        }
        $this->checkValidCurrency($currency);

        $bind = ['name' => $siteName];
        $bind['timezone']   = $timezone;
        $bind['currency']   = $currency;
        $bind['main_url']   = '';

        if (is_null($startDate)) {
            $bind['ts_created'] = Date::now()->getDatetime();
        } else {
            $bind['ts_created'] = Date::factory($startDate)->getDatetime();
        }

        $bind['type'] = $this->checkAndReturnType($type);

        if (!empty($group) && Piwik::hasUserSuperUserAccess()) {
            $bind['group'] = trim($group);
        } else {
            $bind['group'] = "";
        }

        $bind['creator_login'] = Piwik::getCurrentUserLogin();

        $allSettings = $this->setAndValidateMeasurableSettings(0, 'website', $coreProperties);

        // any setting specified in setting values will overwrite other setting
        if (!empty($settingValues)) {
            $this->setAndValidateMeasurableSettings(0, $bind['type'], $settingValues);
        }

        foreach ($allSettings as $settings) {
            foreach ($settings->getSettingsWritableByCurrentUser() as $setting) {
                $name = $setting->getName();
                if ($setting instanceof MeasurableProperty && $name !== 'urls') {
                    $default = $setting->getDefaultValue();
                    if (is_bool($default)) {
                        $default = (int) $default;
                    } elseif (is_array($default)) {
                        $default = implode(',', $default);
                    }

                    $bind[$name] = $default;
                }
            }
        }

        $idSite = $this->getModel()->createSite($bind);

        if (!empty($coreProperties)) {
            $this->saveMeasurableSettings($idSite, 'website', $coreProperties);
        }
        if (!empty($settingValues)) {
            $this->saveMeasurableSettings($idSite, $bind['type'], $settingValues);
        }

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

        $this->postUpdateWebsite($idSite);

        /**
         * Triggered after a site has been added.
         *
         * @param int $idSite The ID of the site that was added.
         */
        Piwik::postEvent('SitesManager.addSite.end', [$idSite]);

        return (int) $idSite;
    }

    private function setSettingValue($fieldName, $value, $coreProperties, $settingValues)
    {
        $pluginName = 'WebsiteMeasurable';

        if (isset($value)) {
            if (empty($coreProperties[$pluginName])) {
                $coreProperties[$pluginName] = [];
            }

            $coreProperties[$pluginName][] = ['name' => $fieldName, 'value' => $value];
        } elseif (!empty($settingValues[$pluginName])) {
            // we check if the value is defined in the setting values instead
            foreach ($settingValues[$pluginName] as $key => $setting) {
                if ($setting['name'] === $fieldName) {
                    if (empty($coreProperties[$pluginName])) {
                        $coreProperties[$pluginName] = [];
                    }

                    $coreProperties[$pluginName][] = ['name' => $fieldName, 'value' => $setting['value']];
                    return $coreProperties;
                }
            }
        }

        return $coreProperties;
    }

    public function getSiteSettings($idSite)
    {
        Piwik::checkUserHasAdminAccess($idSite);

        $measurableSettings = $this->settingsProvider->getAllMeasurableSettings($idSite, $idMeasurableType = false);

        return $this->settingsMetadata->formatSettings($measurableSettings);
    }

    private function setAndValidateMeasurableSettings($idSite, $idType, $settingValues)
    {
        $measurableSettings = $this->settingsProvider->getAllMeasurableSettings($idSite, $idType);

        $this->settingsMetadata->setPluginSettings($measurableSettings, $settingValues);

        return $measurableSettings;
    }

    /**
     * @param MeasurableSettings[] $measurableSettings
     */
    private function saveMeasurableSettings($idSite, $idType, $settingValues)
    {
        $measurableSettings = $this->setAndValidateMeasurableSettings($idSite, $idType, $settingValues);

        foreach ($measurableSettings as $measurableSetting) {
            $measurableSetting->save();
        }
    }

    private function postUpdateWebsite($idSite)
    {
        Site::clearCache();
        Cache::regenerateCacheWebsiteAttributes($idSite);
        Cache::clearCacheGeneral();
        SiteUrls::clearSitesCache();
    }

    /**
     * Delete a website from the database, given its Id. The method deletes the actual site as well as some associated
     * data. However, it does not delete any logs or archives that belong to this website. You can delete logs and
     * archives for a site manually as described in this FAQ: http://matomo.org/faq/how-to/faq_73/ .
     *
     * Requires Super User access.
     *
     * @param int $idSite
     * @param string $passwordConfirmation the current user's password, only required when the request is authenticated with session token auth
     * @throws Exception
     */
    public function deleteSite($idSite, $passwordConfirmation = null)
    {
        Piwik::checkUserHasSuperUserAccess();
        SitesManager::dieIfSitesAdminIsDisabled();

        if (Common::getRequestVar('force_api_session', 0)) {
            $this->confirmCurrentUserPassword($passwordConfirmation);
        }

        $idSites = $this->getSitesId();
        if (!in_array($idSite, $idSites)) {
            throw new Exception("website id = $idSite not found");
        }
        $nbSites = count($idSites);
        if ($nbSites == 1) {
            throw new Exception($this->translator->translate("SitesManager_ExceptionDeleteSite"));
        }

        $this->getModel()->deleteSite($idSite);

        $coreModel = new CoreModel();
        $coreModel->deleteInvalidationsForSites([$idSite]);

        /**
         * Triggered after a site has been deleted.
         *
         * Plugins can use this event to remove site specific values or settings, such as removing all
         * goals that belong to a specific website. If you store any data related to a website you
         * should clean up that information here.
         *
         * @param int $idSite The ID of the site being deleted.
         */
        Piwik::postEvent('SitesManager.deleteSite.end', [$idSite]);
    }

    private function checkValidTimezone($timezone)
    {
        $timezones = $this->getTimezonesList();
        foreach (array_values($timezones) as $cities) {
            foreach ($cities as $timezoneId => $city) {
                if ($timezoneId == $timezone) {
                    return true;
                }
            }
        }
        throw new Exception($this->translator->translate('SitesManager_ExceptionInvalidTimezone', [$timezone]));
    }

    private function checkValidCurrency($currency)
    {
        if (!in_array($currency, array_keys($this->getCurrencyList()))) {
            throw new Exception($this->translator->translate('SitesManager_ExceptionInvalidCurrency', [$currency, "USD, EUR, etc."]));
        }
    }

    private function checkAndReturnType($type)
    {
        if (empty($type)) {
            $type = Site::DEFAULT_SITE_TYPE;
        }

        if (!is_string($type)) {
            throw new Exception("Invalid website type $type");
        }

        return $type;
    }

    /**
     * Checks that the submitted IPs (comma separated list) are valid
     * Returns the cleaned up IPs
     *
     * @param string $excludedIps Comma separated list of IP addresses
     * @throws Exception
     * @return string Comma separated list of IP addresses
     */
    private function checkAndReturnExcludedIps($excludedIps)
    {
        if (empty($excludedIps)) {
            return '';
        }

        $ips = explode(',', $excludedIps);
        $ips = array_map('trim', $ips);
        $ips = array_filter($ips, 'strlen');

        foreach ($ips as $ip) {
            if (!$this->isValidIp($ip)) {
                throw new Exception(
                    $this->translator->translate(
                        'SitesManager_ExceptionInvalidIPFormat',
                        [$ip, "1.2.3.4, 1.2.3.*, or 1.2.3.4/5"]
                    )
                );
            }
        }

        return implode(',', $ips);
    }

    /**
     * Add a list of alias Urls to the given idSite
     *
     * If some URLs given in parameter are already recorded as alias URLs for this website,
     * they won't be duplicated. The 'main_url' of the website won't be affected by this method.
     *
     * @param int $idSite
     * @param array|string $urls When calling API via HTTP specify multiple URLs via `&urls[]=http...&urls[]=http...`.
     * @return int the number of inserted URLs
     */
    public function addSiteAliasUrls($idSite, $urls)
    {
        Piwik::checkUserHasAdminAccess($idSite);

        if (empty($urls)) {
            return 0;
        }

        if (!is_array($urls)) {
            $urls = [$urls];
        }

        $urlsInit = $this->getSiteUrlsFromId($idSite);
        $toInsert = array_merge($urlsInit, $urls);

        $urlsProperty = new Urls($idSite);
        $urlsProperty->setValue($toInsert);
        $urlsProperty->save();

        $inserted = array_diff($urlsProperty->getValue(), $urlsInit);

        $this->postUpdateWebsite($idSite);

        return count($inserted);
    }

    /**
     * Set the list of alias Urls for the given idSite
     *
     * Completely overwrites the current list of URLs with the provided list.
     * The 'main_url' of the website won't be affected by this method.
     *
     * @return int the number of inserted URLs
     */
    public function setSiteAliasUrls($idSite, $urls = [])
    {
        Piwik::checkUserHasAdminAccess($idSite);

        $mainUrl = Site::getMainUrlFor($idSite);
        array_unshift($urls, $mainUrl);

        $urlsProperty = new Urls($idSite);
        $urlsProperty->setValue($urls);
        $urlsProperty->save();

        $inserted = array_diff($urlsProperty->getValue(), $urls);

        $this->postUpdateWebsite($idSite);

        return count($inserted);
    }

    /**
     * Get the start and end IP addresses for an IP address range
     *
     * @param string $ipRange IP address range in presentation format
     * @return array|false Array( low, high ) IP addresses in presentation format; or false if error
     */
    public function getIpsForRange($ipRange)
    {
        $range = IPUtils::getIPRangeBounds($ipRange);
        if ($range === null) {
            return false;
        }

        return [IPUtils::binaryToStringIP($range[0]), IPUtils::binaryToStringIP($range[1])];
    }

    /**
     * Sets IPs to be excluded from all websites. IPs can contain wildcards.
     * Will also apply to websites created in the future.
     *
     * @param string $excludedIps Comma separated list of IPs to exclude from being tracked (allows wildcards)
     * @return bool
     */
    public function setGlobalExcludedIps($excludedIps)
    {
        Piwik::checkUserHasSuperUserAccess();
        $excludedIps = $this->checkAndReturnExcludedIps($excludedIps);
        Option::set(self::OPTION_EXCLUDED_IPS_GLOBAL, $excludedIps);
        Cache::deleteTrackerCache();
        return true;
    }

    /**
     * Sets Site Search keyword/category parameter names, to be used on websites which have not specified these values
     * Expects Comma separated list of query params names
     *
     * @param string
     * @param string
     * @return bool
     */
    public function setGlobalSearchParameters($searchKeywordParameters, $searchCategoryParameters)
    {
        Piwik::checkUserHasSuperUserAccess();
        Option::set(self::OPTION_SEARCH_KEYWORD_QUERY_PARAMETERS_GLOBAL, $searchKeywordParameters);
        Option::set(self::OPTION_SEARCH_CATEGORY_QUERY_PARAMETERS_GLOBAL, $searchCategoryParameters);
        Cache::deleteTrackerCache();
        return true;
    }

    /**
     * @return string Comma separated list of URL parameters
     */
    public function getSearchKeywordParametersGlobal()
    {
        Piwik::checkUserHasSomeAdminAccess();
        $names = Option::get(self::OPTION_SEARCH_KEYWORD_QUERY_PARAMETERS_GLOBAL);
        if ($names === false) {
            $names = self::DEFAULT_SEARCH_KEYWORD_PARAMETERS;
        }
        if (empty($names)) {
            $names = '';
        }
        return $names;
    }

    /**
     * @return string Comma separated list of URL parameters
     */
    public function getSearchCategoryParametersGlobal()
    {
        Piwik::checkUserHasSomeAdminAccess();
        return Option::get(self::OPTION_SEARCH_CATEGORY_QUERY_PARAMETERS_GLOBAL);
    }

    /**
     * Returns the list of URL query parameters that are excluded from all websites
     *
     * @return string Comma separated list of URL parameters
     */
    public function getExcludedQueryParametersGlobal()
    {
        Piwik::checkUserHasSomeViewAccess();
        return Option::get(self::OPTION_EXCLUDED_QUERY_PARAMETERS_GLOBAL);
    }

    /**
     * Returns the list of user agent substrings to look for when excluding visits for
     * all websites. If a visitor's user agent string contains one of these substrings,
     * their visits will not be included.
     *
     * @return string Comma separated list of strings.
     */
    public function getExcludedUserAgentsGlobal()
    {
        Piwik::checkUserHasSomeAdminAccess();
        return Option::get(self::OPTION_EXCLUDED_USER_AGENTS_GLOBAL);
    }

    /**
     * Sets list of user agent substrings to look for when excluding visits. For more info,
     * @see getExcludedUserAgentsGlobal.
     *
     * @param string $excludedUserAgents Comma separated list of strings. Each element is trimmed,
     *                                   and empty strings are removed.
     */
    public function setGlobalExcludedUserAgents($excludedUserAgents)
    {
        Piwik::checkUserHasSuperUserAccess();

        // update option
        $excludedUserAgents = $this->checkAndReturnCommaSeparatedStringList($excludedUserAgents);
        Option::set(self::OPTION_EXCLUDED_USER_AGENTS_GLOBAL, $excludedUserAgents);

        // make sure tracker cache will reflect change
        Cache::deleteTrackerCache();
    }

    /**
     * Returns the list of urls/hosts that should be ignored when detecting referrers for the given site.
     *
     * @return array list of urls/hosts
     */
    public function getExcludedReferrers($idSite)
    {
        try {
            $attributes = Cache::getCacheWebsiteAttributes($idSite);

            if (isset($attributes['excluded_referrers'])) {
                return $attributes['excluded_referrers'];
            }
        } catch (UnexpectedWebsiteFoundException $e) {
            $cached = Cache::getCacheGeneral();
            if (isset($cached['global_excluded_referrers'])) {
                return $cached['global_excluded_referrers'];
            }
        }

        return [];
    }

    /**
     * Returns the global list of urls/hosts that should be ignored when detecting referrers.
     * If a visitor is coming from a site on this list, it will be treated as direct entry
     *
     * @return string Comma separated list of strings
     */
    public function getExcludedReferrersGlobal(): string
    {
        Piwik::checkUserHasSomeAdminAccess();
        $exclusion = Option::get(self::OPTION_EXCLUDED_REFERRERS_GLOBAL);

        return is_string($exclusion) ? $exclusion : '';
    }

    /**
     * Sets list of urls/hosts that should be ignored when detecting referrers. For more info,
     * @see getExcludedReferrersGlobal.
     *
     * @param string $excludedReferrers Comma separated list of strings. Each element is trimmed,
     *                                   and empty strings are removed.
     */
    public function setGlobalExcludedReferrers(string $excludedReferrers): void
    {
        Piwik::checkUserHasSuperUserAccess();

        $excludedUrls = $this->checkAndReturnCommaSeparatedStringList($excludedReferrers);

        foreach (!empty($excludedUrls) ? explode(',', $excludedUrls) : [] as $url) {
            // We allow urls to be provided:
            // - fully qualified like http://example.url/path
            // - without protocol like example.url/path
            // - with subdomain wildcard like .example.url/path
            $prefixedUrl = 'https://' . ltrim(preg_replace('/^https?:\/\//', '', $url), '.');
            $parsedUrl = @parse_url($prefixedUrl);
            if (false === $parsedUrl || !UrlHelper::isLookLikeUrl($prefixedUrl)) {
                throw new Exception(Piwik::translate('SitesManager_ExceptionInvalidUrl', [$url]));
            }
        }

        // update option
        Option::set(self::OPTION_EXCLUDED_REFERRERS_GLOBAL, $excludedUrls);

        // make sure tracker cache will reflect change
        Cache::deleteTrackerCache();
    }

    /**
     * Returns true if the default behavior is to keep URL fragments when tracking,
     * false if otherwise.
     *
     * @return bool
     */
    public function getKeepURLFragmentsGlobal()
    {
        Piwik::checkUserHasSomeViewAccess();
        return (bool)Option::get(self::OPTION_KEEP_URL_FRAGMENTS_GLOBAL);
    }

    /**
     * Sets whether the default behavior should be to keep URL fragments when
     * tracking or not.
     *
     * @param $enabled bool If true, the default behavior will be to keep URL
     *                      fragments when tracking. If false, the default
     *                      behavior will be to remove them.
     */
    public function setKeepURLFragmentsGlobal($enabled)
    {
        Piwik::checkUserHasSuperUserAccess();

        // update option
        Option::set(self::OPTION_KEEP_URL_FRAGMENTS_GLOBAL, $enabled);

        // make sure tracker cache will reflect change
        Cache::deleteTrackerCache();
    }

    /**
     * Sets list of URL query parameters to be excluded on all websites.
     * Will also apply to websites created in the future.
     *
     * @param string $excludedQueryParameters Comma separated list of URL query parameters to exclude from URLs
     * @return bool
     */
    public function setGlobalExcludedQueryParameters($excludedQueryParameters)
    {
        Piwik::checkUserHasSuperUserAccess();
        $excludedQueryParameters = $this->checkAndReturnCommaSeparatedStringList($excludedQueryParameters);
        Option::set(self::OPTION_EXCLUDED_QUERY_PARAMETERS_GLOBAL, $excludedQueryParameters);
        Cache::deleteTrackerCache();
        return true;
    }

    /**
     * Returns the list of IPs that are excluded from all websites
     *
     * @return string Comma separated list of IPs
     */
    public function getExcludedIpsGlobal()
    {
        Piwik::checkUserHasSomeAdminAccess();
        return Option::get(self::OPTION_EXCLUDED_IPS_GLOBAL);
    }

    /**
     * Returns the default currency that will be set when creating a website through the API.
     *
     * @return string Currency ID eg. 'USD'
     */
    public function getDefaultCurrency()
    {
        Piwik::checkUserHasSomeAdminAccess();
        $defaultCurrency = Option::get(self::OPTION_DEFAULT_CURRENCY);
        if ($defaultCurrency) {
            return $defaultCurrency;
        }
        return 'USD';
    }

    /**
     * Sets the default currency that will be used when creating websites
     *
     * @param string $defaultCurrency Currency code, eg. 'USD'
     * @return bool
     */
    public function setDefaultCurrency($defaultCurrency)
    {
        Piwik::checkUserHasSuperUserAccess();
        $this->checkValidCurrency($defaultCurrency);
        Option::set(self::OPTION_DEFAULT_CURRENCY, $defaultCurrency);
        return true;
    }

    /**
     * Returns the default timezone that will be set when creating a website through the API.
     * Via the UI, if the default timezone is not UTC, it will be pre-selected in the drop down
     *
     * @return string Timezone eg. UTC+7 or Europe/Paris
     */
    public function getDefaultTimezone()
    {
        $defaultTimezone = Option::get(self::OPTION_DEFAULT_TIMEZONE);
        if ($defaultTimezone) {
            return $defaultTimezone;
        }
        return 'UTC';
    }

    /**
     * Sets the default timezone that will be used when creating websites
     *
     * @param string $defaultTimezone Timezone string eg. Europe/Paris or UTC+8
     * @return bool
     */
    public function setDefaultTimezone($defaultTimezone)
    {
        Piwik::checkUserHasSuperUserAccess();
        $this->checkValidTimezone($defaultTimezone);
        Option::set(self::OPTION_DEFAULT_TIMEZONE, $defaultTimezone);
        return true;
    }

    /**
     * Update an existing website.
     * If only one URL is specified then only the main url will be updated.
     * If several URLs are specified, both the main URL and the alias URLs will be updated.
     *
     * @param int $idSite website ID defining the website to edit
     * @param string $siteName website name
     * @param string|array $urls the website URLs
     *                           When calling API via HTTP specify multiple URLs via `&urls[]=http...&urls[]=http...`.
     * @param int $ecommerce Whether Ecommerce is enabled, 0 or 1
     * @param null|int $siteSearch Whether site search is enabled, 0 or 1
     * @param string $searchKeywordParameters Comma separated list of search keyword parameter names
     * @param string $searchCategoryParameters Comma separated list of search category parameter names
     * @param string $excludedIps Comma separated list of IPs to exclude from being tracked (allows wildcards)
     * @param null|string $excludedQueryParameters
     * @param string $timezone Timezone
     * @param string $currency Currency code
     * @param string $group Group name where this website belongs
     * @param string $startDate Date at which the statistics for this website will start. Defaults to today's date in YYYY-MM-DD format
     * @param null|string $excludedUserAgents
     * @param int|null $keepURLFragments If 1, URL fragments will be kept when tracking. If 2, they
     *                                   will be removed. If 0, the default global behavior will be used.
     * @param string $type The Website type, default value is "website"
     * @param array|null $settingValues JSON serialized settings eg {settingName: settingValue, ...}
     * @param bool|null $excludeUnknownUrls Track only URL matching one of website URLs
     * @param string|null $excludedReferrers Comma separated list of hosts/urls to exclude from referrer detection
     * @throws Exception
     * @see getKeepURLFragmentsGlobal. If null, the existing value will
     *                                   not be modified.
     *
     * @return bool true on success
     */
    public function updateSite(
        $idSite,
        $siteName = null,
        $urls = null,
        $ecommerce = null,
        $siteSearch = null,
        $searchKeywordParameters = null,
        $searchCategoryParameters = null,
        $excludedIps = null,
        $excludedQueryParameters = null,
        $timezone = null,
        $currency = null,
        $group = null,
        $startDate = null,
        $excludedUserAgents = null,
        $keepURLFragments = null,
        $type = null,
        $settingValues = null,
        $excludeUnknownUrls = null,
        $excludedReferrers = null
    ) {
        Piwik::checkUserHasAdminAccess($idSite);
        SitesManager::dieIfSitesAdminIsDisabled();

        $idSites = $this->getSitesId();

        if (!in_array($idSite, $idSites)) {
            throw new Exception("website id = $idSite not found");
        }

        // Build the SQL UPDATE based on specified updates to perform
        $bind = [];

        if (!is_null($siteName)) {
            $this->checkName($siteName);
            $bind['name'] = $siteName;
        }

        if (!isset($settingValues)) {
            $settingValues = [];
        }

        if (empty($coreProperties)) {
            $coreProperties = [];
        }

        $coreProperties = $this->setSettingValue('urls', $urls, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('group', $group, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('ecommerce', $ecommerce, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('sitesearch', $siteSearch, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('sitesearch_keyword_parameters', explode(',', $searchKeywordParameters ?? ''), $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('sitesearch_category_parameters', explode(',', $searchCategoryParameters ?? ''), $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('keep_url_fragment', $keepURLFragments, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('exclude_unknown_urls', $excludeUnknownUrls, $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('excluded_ips', explode(',', $excludedIps ?? ''), $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('excluded_parameters', explode(',', $excludedQueryParameters ?? ''), $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('excluded_user_agents', explode(',', $excludedUserAgents ?? ''), $coreProperties, $settingValues);
        $coreProperties = $this->setSettingValue('excluded_referrers', explode(',', $excludedReferrers ?? ''), $coreProperties, $settingValues);

        if (isset($currency)) {
            $currency = trim($currency);
            $this->checkValidCurrency($currency);
            $bind['currency'] = $currency;
        }
        if (isset($timezone)) {
            $timezone = trim($timezone);
            $this->checkValidTimezone($timezone);
            $bind['timezone'] = $timezone;
        }
        if (
            isset($group)
            && Piwik::hasUserSuperUserAccess()
        ) {
            $bind['group'] = trim($group);
        }
        if (isset($startDate)) {
            $bind['ts_created'] = Date::factory($startDate)->getDatetime();
        }

        if (isset($type)) {
            $bind['type'] = $this->checkAndReturnType($type);
        }

        if (!empty($coreProperties)) {
            $this->setAndValidateMeasurableSettings($idSite, $idType = 'website', $coreProperties);
        }

        if (!empty($settingValues)) {
            $this->setAndValidateMeasurableSettings($idSite, $idType = null, $settingValues);
        }

        if (!empty($bind)) {
            $this->getModel()->updateSite($bind, $idSite);
        }

        if (!empty($coreProperties)) {
            $this->saveMeasurableSettings($idSite, $idType = 'website', $coreProperties);
        }

        if (!empty($settingValues)) {
            $this->saveMeasurableSettings($idSite, $idType = null, $settingValues);
        }

        $this->postUpdateWebsite($idSite);
    }

    /**
     * Updates the field ts_created for the specified websites.
     *
     * @param $idSites int Id Site to update ts_created
     * @param $minDate Date to set as creation date. To play it safe it will subtract one more day.
     *
     * @ignore
     */
    public function updateSiteCreatedTime($idSites, Date $minDate)
    {
        $idSites = Site::getIdSitesFromIdSitesString($idSites);
        Piwik::checkUserHasAdminAccess($idSites);

        $minDateSql = $minDate->subDay(1)->getDatetime();

        $this->getModel()->updateSiteCreatedTime($idSites, $minDateSql);
    }

    private function checkAndReturnCommaSeparatedStringList($parameters)
    {
        $parameters = trim($parameters);
        if (empty($parameters)) {
            return '';
        }

        $parameters = explode(',', $parameters);
        $parameters = array_map('trim', $parameters);
        $parameters = array_filter($parameters, 'strlen');
        $parameters = array_unique($parameters);
        return implode(',', $parameters);
    }

    /**
     * Returns the list of supported currencies
     * @see getCurrencySymbols()
     * @return array ( currencyId => currencyName)
     */
    public function getCurrencyList()
    {
        /** @var CurrencyDataProvider $dataProvider */
        $dataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\CurrencyDataProvider');
        $currency = $dataProvider->getCurrencyList();

        $return = [];
        foreach (array_keys($currency) as $currencyCode) {
            $return[$currencyCode] = $this->translator->translate('Intl_Currency_' . $currencyCode) .
              ' (' . $this->translator->translate('Intl_CurrencySymbol_' . $currencyCode) . ')';
        }

        asort($return);

        return $return;
    }

    /**
     * Returns the list of currency symbols
     * @see getCurrencyList()
     * @return array( currencyId => currencySymbol )
     */
    public function getCurrencySymbols()
    {
        /** @var CurrencyDataProvider $dataProvider */
        $dataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\CurrencyDataProvider');
        $currencies =  $dataProvider->getCurrencyList();

        return array_map(function ($a) {
            return $a[0];
        }, $currencies);
    }

    /**
     * Return true if Timezone support is enabled on server
     *
     * @return bool
     */
    public function isTimezoneSupportEnabled()
    {
        Piwik::checkUserHasSomeViewAccess();
        return SettingsServer::isTimezoneSupportEnabled();
    }

    /**
     * Returns the list of timezones supported.
     * Used for addSite and updateSite
     *
     * @return array of timezone strings
     */
    public function getTimezonesList()
    {
        if (!SettingsServer::isTimezoneSupportEnabled()) {
            return ['UTC' => $this->getTimezonesListUTCOffsets()];
        }

        $countries = StaticContainer::get('Piwik\Intl\Data\Provider\RegionDataProvider')->getCountryList();

        $return = [];
        $continents = [];
        foreach ($countries as $countryCode => $continentCode) {
            $countryCode = strtoupper($countryCode);
            $timezones = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $countryCode);
            foreach ($timezones as $timezone) {
                if (!isset($continents[$continentCode])) {
                    $continents[$continentCode] = $this->translator->translate('Intl_Continent_' . $continentCode);
                }
                $continent = $continents[$continentCode];

                $return[$continent][$timezone] = $this->getTimezoneName($timezone, $countryCode, count($timezones) > 1);
            }
        }

        // Sort by continent name and then by country name.
        ksort($return);
        foreach ($return as $continent => $countries) {
            asort($return[$continent]);
        }

        $return['UTC'] = $this->getTimezonesListUTCOffsets();
        return $return;
    }

    /**
     * Returns a user-friendly label for a timezone.
     * This is usually the country name of the timezone. For countries spanning multiple timezones,
     * a city/location name is added to avoid ambiguity.
     *
     * @param string $timezone a timezone, e.g. "Asia/Tokyo" or "America/Los_Angeles"
     * @param string $countryCode an upper-case country code (if not supplied, it will be looked up)
     * @param bool $multipleTimezonesInCountry whether there are multiple timezones in the country (if not supplied, it will be looked up)
     * @return string a timezone label, e.g. "Japan" or "United States - Los Angeles"
     */
    public function getTimezoneName($timezone, $countryCode = null, $multipleTimezonesInCountry = null)
    {
        if (substr($timezone, 0, 3) === 'UTC') {
            return $this->translator->translate('SitesManager_Format_Utc', str_replace(['.25', '.5', '.75'], [':15', ':30', ':45'], substr($timezone, 3)));
        }

        if (!isset($countryCode)) {
            try {
                $zone = new DateTimeZone($timezone);
                $location = $zone->getLocation();
                if (isset($location['country_code']) && $location['country_code'] !== '??') {
                    $countryCode = $location['country_code'];
                }
            } catch (Exception $e) {
            }
        }

        if (!$countryCode) {
            $timezoneExploded = explode('/', $timezone);
            return str_replace('_', ' ', end($timezoneExploded));
        }

        if (!isset($multipleTimezonesInCountry)) {
            $timezonesInCountry = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $countryCode);
            $multipleTimezonesInCountry = (count($timezonesInCountry) > 1);
        }

        $return = $this->translator->translate('Intl_Country_' . $countryCode);

        if ($multipleTimezonesInCountry) {
            $translationId = 'Intl_Timezone_' . str_replace(['_', '/'], ['', '_'], $timezone);
            $city = $this->translator->translate($translationId);

            // Fall back to English identifier, if translation is missing due to differences in tzdata in different PHP versions.
            if ($city === $translationId) {
                $timezoneExploded = explode('/', $timezone);
                $city = str_replace('_', ' ', end($timezoneExploded));
            }

            $return .= ' - ' . $city;
        }

        return $return;
    }

    private function getTimezonesListUTCOffsets()
    {
        // manually add the UTC offsets
        $GmtOffsets = [-12, -11.5, -11, -10.5, -10, -9.5, -9, -8.5, -8, -7.5, -7, -6.5, -6, -5.5, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1.5, -1, -0.5,
                            0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 5.75, 6, 6.5, 7, 7.5, 8, 8.5, 8.75, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.75, 13, 13.75, 14];

        $return = [];
        foreach ($GmtOffsets as $offset) {
            $offset = Common::forceDotAsSeparatorForDecimalPoint($offset);

            if ($offset > 0) {
                $offset = '+' . $offset;
            } elseif ($offset == 0) {
                $offset = '';
            }
            $timezone = 'UTC' . $offset;
            $return[$timezone] = $this->getTimezoneName($timezone);
        }
        return $return;
    }

    /**
     * Returns the list of unique timezones from all configured sites.
     *
     * @return array ( string )
     */
    public function getUniqueSiteTimezones()
    {
        Piwik::checkUserHasSuperUserAccess();

        return $this->getModel()->getUniqueSiteTimezones();
    }

    /**
     * Remove the final slash in the URLs if found
     *
     * @param string $url
     * @return string the URL without the trailing slash
     */
    private function removeTrailingSlash($url)
    {
        // if there is a final slash, we take the URL without this slash (expected URL format)
        if (
            strlen($url) > 5
            && $url[strlen($url) - 1] == '/'
        ) {
            $url = substr($url, 0, strlen($url) - 1);
        }

        return $url;
    }

    /**
     * Tests if the URL is a valid URL
     *
     * @param string $url
     * @return bool
     */
    private function isValidUrl($url)
    {
        return UrlHelper::isLookLikeUrl($url);
    }

    /**
     * Tests if the IP is a valid IP, allowing wildcards, except in the first octet.
     * Wildcards can only be used from right to left, ie. 1.1.*.* is allowed, but 1.1.*.1 is not.
     *
     * @param string $ip IP address
     * @return bool
     */
    private function isValidIp($ip)
    {
        return IPUtils::getIPRangeBounds($ip) !== null;
    }

    /**
     * Check that the website name has a correct format.
     *
     * @param $siteName
     * @throws Exception
     */
    private function checkName($siteName)
    {
        if (empty($siteName)) {
            throw new Exception($this->translator->translate("SitesManager_ExceptionEmptyName"));
        }
    }

    public function renameGroup($oldGroupName, $newGroupName)
    {
        Piwik::checkUserHasSuperUserAccess();

        if ($oldGroupName == $newGroupName) {
            return true;
        }

        $sitesHavingOldGroup = $this->getSitesFromGroup($oldGroupName);

        foreach ($sitesHavingOldGroup as $site) {
            $this->updateSite(
                $site['idsite'],
                $siteName = null,
                $urls = null,
                $ecommerce = null,
                $siteSearch = null,
                $searchKeywordParameters = null,
                $searchCategoryParameters = null,
                $excludedIps = null,
                $excludedQueryParameters = null,
                $timezone = null,
                $currency = null,
                $newGroupName
            );
        }

        return true;
    }

    /**
     * Find websites matching the given pattern.
     *
     * Any website will be returned that matches the pattern in the name, URL or group.
     * To limit the number of returned sites you can either specify `filter_limit` as usual or `limit` which is
     * faster.
     *
     * @param string $pattern
     * @param int|false $limit
     * @param []|int[] $sitesToExclude optional array of Integer IDs of sites to exclude from the result.
     * @return array
     */
    public function getPatternMatchSites($pattern, $limit = false, $sitesToExclude = [])
    {
        $ids = $this->getSitesIdWithAtLeastViewAccess();

        // Remove the sites to exclude from the list of IDs.
        if (is_array($ids) && is_array($sitesToExclude) && count($sitesToExclude)) {
            $ids = array_diff($ids, $sitesToExclude);
        }

        if (empty($ids)) {
            return [];
        }

        $sites = $this->getModel()->getPatternMatchSites($ids, $pattern, $limit);

        foreach ($sites as &$site) {
            $this->enrichSite($site);
        }

        $sites = Site::setSitesFromArray($sites);

        return $sites;
    }

    /**
     * Returns the number of websites to display per page.
     *
     * For example this is used in the All Websites Dashboard, in the Website Selector etc. If multiple websites are
     * shown somewhere, one should request this method to detect how many websites should be shown per page when
     * using paging. To use paging is always recommended since some installations have thousands of websites.
     *
     * @return int
     */
    public function getNumWebsitesToDisplayPerPage()
    {
        Piwik::checkUserHasSomeViewAccess();

        return SettingsPiwik::getWebsitesCountToDisplay();
    }
}