forked from matomo-org/plugin-CustomAlerts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Processor.php
executable file
·345 lines (291 loc) · 10.5 KB
/
Processor.php
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
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html Gpl v3 or later
* @version $Id$
*
*/
namespace Piwik\Plugins\CustomAlerts;
use Piwik\API\Request as ApiRequest;
use Piwik\Common;
use Piwik\DataTable;
use Piwik\Date;
use Piwik\Plugins\API\ProcessedReport;
use Piwik\Site;
/**
*
*/
class Processor
{
public static function getComparablesDates()
{
return array(
'day' => array(
'CustomAlerts_DayComparedToPreviousWeek' => 7,
'CustomAlerts_DayComparedToPreviousDay' => 1,
'CustomAlerts_DayComparedToPreviousYear' => 365,
),
'week' => array(
'CustomAlerts_WeekComparedToPreviousWeek' => 1,
),
'month' => array(
'CustomAlerts_MonthComparedToPreviousMonth' => 1,
'CustomAlerts_MonthComparedToPreviousYear' => 12,
)
);
}
public static function getGroupConditions()
{
return array(
'CustomAlerts_MatchesAnyExpression' => 'matches_any',
'CustomAlerts_OperationIs' => 'matches_exactly',
'CustomAlerts_OperationIsNot' => 'does_not_match_exactly',
'CustomAlerts_MatchesRegularExpression' => 'matches_regex',
'CustomAlerts_DoesNotMatchRegularExpression' => 'does_not_match_regex',
'CustomAlerts_OperationContains' => 'contains',
'CustomAlerts_OperationDoesNotContain' => 'does_not_contain',
'CustomAlerts_StartsWith' => 'starts_with',
'CustomAlerts_DoesNotStartWith' => 'does_not_start_with',
'CustomAlerts_EndsWith' => 'ends_with',
'CustomAlerts_DoesNotEndWith' => 'does_not_end_with',
);
}
public static function getMetricConditions()
{
return array(
'CustomAlerts_IsLessThan' => 'less_than',
'CustomAlerts_IsGreaterThan' => 'greater_than',
'CustomAlerts_DecreasesMoreThan' => 'decrease_more_than',
'CustomAlerts_IncreasesMoreThan' => 'increase_more_than',
'CustomAlerts_PercentageDecreasesMoreThan' => 'percentage_decrease_more_than',
'CustomAlerts_PercentageIncreasesMoreThan' => 'percentage_increase_more_than',
);
}
public function processAlerts($period, $idSite)
{
$alerts = $this->getAllAlerts($period);
foreach ($alerts as $alert) {
$this->processAlert($alert, $idSite);
}
}
protected function processAlert($alert, $idSite)
{
if (!$this->shouldBeProcessed($alert, $idSite)) {
return;
}
$valueNew = $this->getValueForAlertInPast($alert, $idSite, 1);
if (is_null($valueNew)) {
$valueNew = 0;
}
if (365 == $alert['compared_to'] && Date::today()->isLeapYear()) {
$alert['compared_to'] = 366;
}
$valueOld = $this->getValueForAlertInPast($alert, $idSite, 1 + $alert['compared_to']);
if ($this->shouldBeTriggered($alert, $valueNew, $valueOld)) {
$this->triggerAlert($alert, $idSite, $valueNew, $valueOld);
}
}
private function shouldBeProcessed($alert, $idSite)
{
if (empty($alert['id_sites']) || !in_array($idSite, $alert['id_sites'])) {
return false;
}
$validator = new Validator();
if (!$validator->isValidComparableDate($alert['period'], $alert['compared_to'])) {
// actually it would be nice to log or send a notification or whatever that we have skipped an alert
return false;
}
if (!$this->reportExists($idSite, $alert['report'], $alert['metric'])) {
// actually it would be nice to log or send a notification or whatever that we have skipped an alert
return false;
}
return true;
}
private function reportExists($idSite, $report, $metric)
{
try {
$validator = new Validator();
$validator->checkApiMethodAndMetric($idSite, $report, $metric);
} catch (\Exception $e) {
return false;
}
return true;
}
private function needsBothValuesToTrigger($alert)
{
$comparisons = array(
'decrease_more_than',
'increase_more_than',
'percentage_decrease_more_than',
'percentage_increase_more_than'
);
return in_array($alert['metric_condition'], $comparisons);
}
protected function shouldBeTriggered($alert, $valueNew, $valueOld)
{
if ($this->needsBothValuesToTrigger($alert) && empty($valueOld) && empty($valueNew)) {
return false;
}
if (!empty($valueOld)) {
$percentage = ((($valueNew / $valueOld) * 100) - 100);
} else {
$percentage = $valueNew;
}
$metricMatched = floatval($alert['metric_matched']);
switch ($alert['metric_condition']) {
case 'greater_than':
return ($valueNew > $metricMatched);
case 'less_than':
return ($valueNew < $metricMatched);
case 'decrease_more_than':
return (($valueOld - $valueNew) > $metricMatched);
case 'increase_more_than':
return (($valueNew - $valueOld) > $metricMatched);
case 'percentage_decrease_more_than':
return ((-1 * $metricMatched) > $percentage && $percentage < 0);
case 'percentage_increase_more_than':
return ($metricMatched < $percentage && $percentage >= 0);
}
throw new \Exception('Metric condition is not supported');
}
/**
* @param DataTable $dataTable DataTable
* @param string $metric Metric to fetch from row.
* @param string $filterCond Condition to filter for.
* @param string $filterValue Value to find
*
* @return mixed
*/
protected function aggregateToOneValue($dataTable, $metric, $filterCond = '', $filterValue = '')
{
if (!empty($filterValue)) {
$this->filterDataTable($dataTable, $filterCond, $filterValue);
}
if ($dataTable->getRowsCount() > 1) {
$dataTable->filter('Truncate', array(0, null, $metric));
}
$dataTable->applyQueuedFilters();
$dataRow = $dataTable->getFirstRow();
if (!$dataRow) {
return null;
}
$value = $dataRow->getColumn($metric);
if ($value && is_string($value)) {
$value = str_replace(array('%', 's'), '', $value);
}
return $value;
}
/**
* @param $dataTable
* @param $condition
* @param $value
* @throws \Exception
*/
protected function filterDataTable($dataTable, $condition, $value)
{
$invert = false;
$value = Common::unsanitizeInputValue($value);
if ('matches_regex' != $condition && 'does_not_match_regex' != $condition) {
$value = str_replace(array('?', '+', '*'), array('\?', '\+', '\*'), $value);
}
// Some escaping?
switch ($condition) {
case 'matches_any':
return;
case 'matches_exactly':
$pattern = sprintf("^%s$", $value);
break;
case 'matches_regex':
$pattern = $value;
break;
case 'does_not_match_exactly':
$pattern = sprintf("^%s$", $value);
$invert = true;
break;
case 'does_not_match_regex':
$pattern = sprintf("%s", $value);
$invert = true;
break;
case 'contains':
$pattern = $value;
break;
case 'does_not_contain':
$pattern = $value;
$invert = true;
break;
case 'starts_with':
$pattern = sprintf("^%s", $value);
break;
case 'does_not_start_with':
$pattern = sprintf("^%s", $value);
$invert = true;
break;
case 'ends_with':
$pattern = sprintf("%s$", $value);
break;
case 'does_not_end_with':
$pattern = sprintf("%s$", $value);
$invert = true;
break;
default:
throw new \Exception('Filter condition not supported');
}
$dataTable->filter('Pattern', array('label', $pattern, $invert));
}
private function getDateForAlertInPast($idSite, $period, $subPeriodN)
{
$timezone = Site::getTimezoneFor($idSite);
$date = Date::now();
$date = Date::factory($date->getDatetime(), $timezone);
if ($subPeriodN) {
$date = $date->subPeriod($subPeriodN, $period);
}
return $date->toString();
}
/**
* @param array $alert
* @param int $idSite
* @param int $subPeriodN
*
* @return array
*/
public function getValueForAlertInPast($alert, $idSite, $subPeriodN)
{
$processedReport = new ProcessedReport();
$report = $processedReport->getReportMetadataByUniqueId($idSite, $alert['report']);
$dateInPast = $this->getDateForAlertInPast($idSite, $alert['period'], $subPeriodN);
$params = array(
'method' => $report['module'] . '.' . $report['action'],
'format' => 'original',
'idSite' => $idSite,
'period' => $alert['period'],
'date' => $dateInPast,
'flat' => 1,
'disable_queued_filters' => 1,
'filter_limit' => -1
);
if (!empty($report['parameters'])) {
$params = array_merge($params, $report['parameters']);
}
$subtableId = DataTable\Manager::getInstance()->getMostRecentTableId();
$request = new ApiRequest($params);
$table = $request->process();
$value = $this->aggregateToOneValue($table, $alert['metric'], $alert['report_condition'], $alert['report_matched']);
DataTable\Manager::getInstance()->deleteAll($subtableId);
return $value;
}
protected function triggerAlert($alert, $idSite, $valueNew, $valueOld)
{
$this->getModel()->triggerAlert($alert['idalert'], $idSite, $valueNew, $valueOld, Date::now()->getDatetime());
}
private function getAllAlerts($period)
{
return $this->getModel()->getAllAlertsForPeriod($period);
}
private function getModel()
{
return new Model();
}
}