-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathAPI.php
More file actions
executable file
·315 lines (265 loc) · 14.1 KB
/
API.php
File metadata and controls
executable file
·315 lines (265 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<?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\CustomAlerts;
use Exception;
use Piwik\Common;
use Piwik\Piwik;
use Piwik\Site;
/**
* Exposes Custom Alerts API endpoints for managing alert definitions and reading triggered alert data.
* These methods let callers create, update, fetch, delete, and evaluate alerts for one or more sites.
*
* @method static \Piwik\Plugins\CustomAlerts\API getInstance()
*/
class API extends \Piwik\Plugin\API
{
private $validator;
/**
* @var Processor
*/
private $processor;
public function __construct(Processor $processor, Validator $validator)
{
$this->validator = $validator;
$this->processor = $processor;
}
/**
* Returns the computed alert value for each site linked to an alert for a past or current period.
* Use 0 to evaluate the current period, 1 for the previous matching period, and so on.
*
* @param int $idAlert Alert ID to evaluate.
* @param int|string $subPeriodN Number of periods in the past to evaluate.
* Use 0 for the current day, week, or month.
*
* @return list<array{idSite: int, value: mixed}> Alert values grouped by site.
*/
public function getValuesForAlertInPast($idAlert, $subPeriodN)
{
$alert = $this->getAlert($idAlert);
$values = [];
foreach ($alert['id_sites'] as $idSite) {
$values[] = array(
'idSite' => (int)$idSite,
'value' => $this->processor->getValueForAlertInPast($alert, $idSite, (int)$subPeriodN)
);
}
return $values;
}
/**
* Returns a single custom alert definition.
*
* @param int $idAlert Alert ID to fetch.
*
* @return array{id_sites: list<int>} & array<string, mixed> Alert definition including the configured site IDs.
*/
public function getAlert($idAlert)
{
$alert = $this->getModel()->getAlert($idAlert);
if (empty($alert)) {
throw new Exception(Piwik::translate('CustomAlerts_AlertDoesNotExist', $idAlert));
}
$this->validator->checkUserHasPermissionForAlert($alert);
return $alert;
}
private function getModel()
{
return new Model();
}
/**
* Returns the custom alerts configured for the requested sites.
*
* @param string|array $idSites Website ID(s) to query.
* Accepts comma-separated IDs, "all", numeric IDs as strings, or ["all"].
* @param bool $ifSuperUserReturnAllAlerts Whether a super user should receive alerts created by all users.
*
* @return list<array<string, mixed>> Alert definitions accessible to the current user for the requested sites.
*/
public function getAlerts($idSites, $ifSuperUserReturnAllAlerts = false)
{
$idSites = Site::getIdSitesFromIdSitesString($idSites);
if (empty($idSites)) {
return [];
}
Piwik::checkUserHasViewAccess($idSites);
if (Piwik::hasUserSuperUserAccess() && $ifSuperUserReturnAllAlerts) {
$login = false;
} else {
$login = Piwik::getCurrentUserLogin();
}
$alerts = $this->getModel()->getAlerts($idSites, $login);
return $alerts;
}
/**
* Creates a custom alert for one or more sites.
*
* @param string $name Alert name.
* @param string|array $idSites Website ID(s) to query.
* Accepts comma-separated IDs, "all", numeric IDs as strings, or ["all"].
* @param 'day'|'week'|'month' $period Alert period.
* Allowed values: day, week, month.
* @param bool $emailMe Whether to notify the current user by email when the alert triggers.
* @param list<string> $additionalEmails Additional email recipients for email notifications.
* @param list<string> $phoneNumbers Mobile Messaging recipients when the mobile channel is enabled.
* @param string $metric Metric unique ID to evaluate, for example nb_uniq_visits or sum_visit_length.
* @param string $metricCondition Comparison rule to apply to the metric.
* Allowed values: less_than, greater_than, decrease_more_than,
* increase_more_than, percentage_decrease_more_than,
* percentage_increase_more_than.
* @param float|int|string $metricValue Threshold value to compare the selected metric against.
* @param int $comparedTo Number of prior periods to compare against.
* Allowed values by period: day => 1, 7, 365; week => 1; month => 1, 12.
* @param string $reportUniqueId Report unique ID in module_action format.
* @param false|string $reportCondition Optional dimension filter condition for report rows.
* Allowed values: matches_any, matches_exactly, does_not_match_exactly,
* matches_regex, does_not_match_regex, contains, does_not_contain,
* starts_with, does_not_start_with, ends_with, does_not_end_with.
* @param false|string $reportValue Value to match when $reportCondition is provided.
* @param list<'email'|'mobile'|'slack'|'teams'> $reportMediums Delivery channels to use for notifications.
* Allowed values: email, mobile, slack, teams.
* @param string $slackChannelID Slack channel ID when the slack channel is enabled.
* @param string $msTeamsWebhookUrl Microsoft Teams webhook URL when the teams channel is enabled.
* @return int ID of the newly created alert.
*/
public function addAlert($name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition = false, $reportValue = false, array $reportMediums = [], string $slackChannelID = '', string $msTeamsWebhookUrl = '')
{
$idSites = Site::getIdSitesFromIdSitesString($idSites);
$this->checkAlert($idSites, $name, $period, $emailMe, $additionalEmails, $phoneNumbers, $slackChannelID, $msTeamsWebhookUrl, $metricCondition, $metric, $comparedTo, $reportCondition, $reportUniqueId, $reportMediums);
$name = Common::unsanitizeInputValue($name);
$login = Piwik::getCurrentUserLogin();
if (empty($reportCondition) || empty($reportValue)) {
$reportCondition = null;
$reportValue = null;
}
$metricValue = Common::forceDotAsSeparatorForDecimalPoint((float)$metricValue);
return $this->getModel()->createAlert($name, $idSites, $login, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue, $reportMediums, $slackChannelID, $msTeamsWebhookUrl);
}
private function filterAdditionalEmails($additionalEmails)
{
if (empty($additionalEmails)) {
return array();
}
foreach ($additionalEmails as &$email) {
$email = trim($email);
if (empty($email)) {
$email = false;
}
}
return array_filter($additionalEmails);
}
private function filterPhoneNumbers($phoneNumbers)
{
$availablePhoneNumbers = (new \Piwik\Plugins\MobileMessaging\Model())->getActivatedPhoneNumbers(Piwik::getCurrentUserLogin());
foreach ($phoneNumbers as $key => &$phoneNumber) {
$phoneNumber = trim($phoneNumber);
if (!in_array($phoneNumber, $availablePhoneNumbers)) {
unset($phoneNumbers[$key]);
}
}
return array_values($phoneNumbers);
}
private function checkAlert($idSites, $name, $period, &$emailMe, &$additionalEmails, &$phoneNumbers, &$slackChannelID, &$msTeamsWebhookUrl, $metricCondition, $metricValue, $comparedTo, $reportCondition, $reportUniqueId, $reportMediums)
{
Piwik::checkUserHasViewAccess($idSites);
$additionalEmails = in_array('email', $reportMediums) ? $this->filterAdditionalEmails($additionalEmails) : [];
$phoneNumbers = in_array('mobile', $reportMediums) ? $this->filterPhoneNumbers($phoneNumbers) : [];
$emailMe = in_array('email', $reportMediums) && $emailMe;
$slackChannelID = in_array('slack', $reportMediums) ? $slackChannelID : '';
$msTeamsWebhookUrl = in_array('teams', $reportMediums) ? $msTeamsWebhookUrl : '';
$this->validator->checkName($name);
$this->validator->checkPeriod($period);
$this->validator->checkComparedTo($period, $comparedTo);
$this->validator->checkMetricCondition($metricCondition);
$this->validator->checkReportCondition($reportCondition);
$this->validator->checkReportMediums($reportMediums);
foreach ($idSites as $idSite) {
$this->validator->checkApiMethodAndMetric($idSite, $reportUniqueId, $metricValue);
}
$this->validator->checkAdditionalEmails($additionalEmails);
foreach ($reportMediums as $reportMedium) {
Piwik::postEvent('CustomAlerts.validateReportParameters', [get_defined_vars(), $reportMedium]);
}
}
/**
* Updates an existing custom alert.
*
* @param int $idAlert Alert ID to update.
* @param string $name Alert name.
* @param string|array $idSites Website ID(s) to query.
* Accepts comma-separated IDs, "all", numeric IDs as strings, or ["all"].
* @param 'day'|'week'|'month' $period Alert period.
* Allowed values: day, week, month.
* @param bool $emailMe Whether to notify the current user by email when the alert triggers.
* @param list<string> $additionalEmails Additional email recipients for email notifications.
* @param list<string> $phoneNumbers Mobile Messaging recipients when the mobile channel is enabled.
* @param string $metric Metric unique ID to evaluate, for example nb_uniq_visits or sum_visit_length.
* @param string $metricCondition Comparison rule to apply to the metric.
* Allowed values: less_than, greater_than, decrease_more_than,
* increase_more_than, percentage_decrease_more_than,
* percentage_increase_more_than.
* @param float|int|string $metricValue Threshold value to compare the selected metric against.
* @param int $comparedTo Number of prior periods to compare against.
* Allowed values by period: day => 1, 7, 365; week => 1; month => 1, 12.
* @param string $reportUniqueId Report unique ID in module_action format.
* @param false|string $reportCondition Optional dimension filter condition for report rows.
* Allowed values: matches_any, matches_exactly, does_not_match_exactly,
* matches_regex, does_not_match_regex, contains, does_not_contain,
* starts_with, does_not_start_with, ends_with, does_not_end_with.
* @param false|string $reportValue Value to match when $reportCondition is provided.
* @param list<'email'|'mobile'|'slack'|'teams'> $reportMediums Delivery channels to use for notifications.
* Allowed values: email, mobile, slack, teams.
* @param string $slackChannelID Slack channel ID when the slack channel is enabled.
* @param string $msTeamsWebhookUrl Microsoft Teams webhook URL when the teams channel is enabled.
*
* @return int Updated alert ID.
*/
public function editAlert($idAlert, $name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition = false, $reportValue = false, array $reportMediums = [], string $slackChannelID = '', string $msTeamsWebhookUrl = '')
{
// make sure alert exists and user has permission to read
$this->getAlert($idAlert);
$idSites = Site::getIdSitesFromIdSitesString($idSites);
$this->checkAlert($idSites, $name, $period, $emailMe, $additionalEmails, $phoneNumbers, $slackChannelID, $msTeamsWebhookUrl, $metricCondition, $metric, $comparedTo, $reportCondition, $reportUniqueId, $reportMediums);
$name = Common::unsanitizeInputValue($name);
if (empty($reportCondition) || empty($reportValue)) {
$reportCondition = null;
$reportValue = null;
}
$metricValue = Common::forceDotAsSeparatorForDecimalPoint((float)$metricValue);
return $this->getModel()->updateAlert($idAlert, $name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue, $reportMediums, $slackChannelID, $msTeamsWebhookUrl);
}
/**
* Deletes an existing custom alert.
*
* @param int $idAlert Alert ID to delete.
*
* @return void
*/
public function deleteAlert($idAlert)
{
// make sure alert exists and user has permission to read
$this->getAlert($idAlert);
$this->getModel()->deleteAlert($idAlert);
}
/**
* Returns triggered alerts for the current user and requested sites.
*
* @param string|array $idSites Website ID(s) to query.
* Accepts comma-separated IDs, "all", numeric IDs as strings, or ["all"].
*
* @return list<array<string, mixed>> Triggered alert entries for the current user and requested sites.
*/
public function getTriggeredAlerts($idSites)
{
if (empty($idSites)) {
return array();
}
$idSites = Site::getIdSitesFromIdSitesString($idSites);
Piwik::checkUserHasViewAccess($idSites);
$login = Piwik::getCurrentUserLogin();
return $this->getModel()->getTriggeredAlerts($idSites, $login);
}
}