forked from matomo-org/plugin-CustomAlerts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Model.php
executable file
·429 lines (358 loc) · 13.3 KB
/
Model.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
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
<?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 Exception;
use Piwik\Common;
use Piwik\Date;
use Piwik\Db;
use Piwik\DbHelper;
use Piwik\Period;
use Piwik\Translate;
/**
*
*/
class Model
{
public static function install()
{
$tableAlert = "`idalert` INT NOT NULL PRIMARY KEY ,
`name` VARCHAR(100) NOT NULL ,
`login` VARCHAR(100) NOT NULL ,
`period` VARCHAR(5) NOT NULL ,
`report` VARCHAR(150) NOT NULL ,
`report_condition` VARCHAR(50) ,
`report_matched` VARCHAR(255) ,
`metric` VARCHAR(150) NOT NULL ,
`metric_condition` VARCHAR(50) NOT NULL ,
`metric_matched` FLOAT NOT NULL ,
`compared_to` SMALLINT (4) UNSIGNED NOT NULL DEFAULT 1 ,
`email_me` BOOLEAN NOT NULL DEFAULT '0',
`additional_emails` TEXT ,
`phone_numbers` TEXT ";
DbHelper::createTable('alert', $tableAlert);
$tableAlertSite = "`idalert` INT( 11 ) NOT NULL ,
`idsite` INT( 11 ) NOT NULL ,
PRIMARY KEY ( idalert, idsite )";
DbHelper::createTable('alert_site', $tableAlertSite);
$tableAlertLog = "`idtriggered` BIGINT unsigned NOT NULL AUTO_INCREMENT,
`idalert` INT( 11 ) NOT NULL ,
`idsite` INT( 11 ) NOT NULL ,
`ts_triggered` timestamp NOT NULL default CURRENT_TIMESTAMP,
`ts_last_sent` timestamp NULL DEFAULT NULL,
`value_old` DECIMAL (20,3) DEFAULT NULL,
`value_new` DECIMAL (20,3) DEFAULT NULL,
`name` VARCHAR(100) NOT NULL ,
`login` VARCHAR(100) NOT NULL ,
`period` VARCHAR(5) NOT NULL ,
`report` VARCHAR(150) NOT NULL ,
`report_condition` VARCHAR(50) ,
`report_matched` VARCHAR(1000) ,
`metric` VARCHAR(150) NOT NULL ,
`metric_condition` VARCHAR(50) NOT NULL ,
`metric_matched` FLOAT NOT NULL ,
`compared_to` SMALLINT NOT NULL DEFAULT 1 ,
`email_me` BOOLEAN NOT NULL DEFAULT '0',
`additional_emails` TEXT ,
`phone_numbers` TEXT ,
PRIMARY KEY (idtriggered)";
DbHelper::createTable('alert_triggered', $tableAlertLog);
}
public static function uninstall()
{
Db::dropTables(array(
Common::prefixTable('alert'),
Common::prefixTable('alert_triggered'),
Common::prefixTable('alert_site')
));
}
/**
* Returns a single Alert
*
* @param int $idAlert
*
* @return array|null
*/
public function getAlert($idAlert)
{
$query = sprintf('SELECT * FROM %s WHERE idalert = ? LIMIT 1', Common::prefixTable('alert'));
$alerts = Db::fetchAll($query, array(intval($idAlert)));
if (empty($alerts)) {
return;
}
$alerts = $this->completeAlerts($alerts);
$alert = array_shift($alerts);
return $alert;
}
/**
* Returns the Alerts that are defined on the idSites given.
*
* @param array $idSites
* @param bool|string $login false returns alerts for all users
*
* @return array
*/
public function getAlerts($idSites, $login = false)
{
$sql = ("SELECT * FROM " . Common::prefixTable('alert')
. " WHERE idalert IN (" . $this->getInnerSiteQuery($idSites) . ") ");
$values = array();
if ($login !== false) {
$sql .= " AND login = ?";
$values[] = $login;
}
$alerts = Db::fetchAll($sql, $values);
$alerts = $this->completeAlerts($alerts);
return $alerts;
}
public function getTriggeredAlertsForPeriod($period, $date)
{
$piwikDate = Date::factory($date);
$date = Period\Factory::build($period, $piwikDate);
$db = $this->getDb();
$sql = $this->getTriggeredAlertsSelectPart()
. " WHERE period = ? AND ts_triggered BETWEEN ? AND ?";
$values = array(
$period,
$date->getDateStart()->getDateStartUTC(),
$date->getDateEnd()->getDateEndUTC()
);
$alerts = $db->fetchAll($sql, $values);
$alerts = $this->completeAlerts($alerts);
return $alerts;
}
public function getTriggeredAlerts($idSites, $login)
{
$idSites = array_map('intval', $idSites);
$db = $this->getDb();
$sql = $this->getTriggeredAlertsSelectPart()
. " WHERE idsite IN (" . Common::getSqlStringFieldsArray($idSites) . ")"
. " AND login = ?";
$values = $idSites;
$values[] = $login;
$alerts = $db->fetchAll($sql, $values);
$alerts = $this->completeAlerts($alerts);
return $alerts;
}
private function getTriggeredAlertsSelectPart()
{
return "SELECT * FROM ". Common::prefixTable('alert_triggered');
}
public function getAllAlerts()
{
$sql = "SELECT * FROM ". Common::prefixTable('alert');
$alerts = Db::fetchAll($sql);
$alerts = $this->completeAlerts($alerts);
return $alerts;
}
public function getAllAlertsForPeriod($period)
{
$sql = "SELECT * FROM ". Common::prefixTable('alert') . " WHERE period = ?";
$alerts = Db::fetchAll($sql, array($period));
$alerts = $this->completeAlerts($alerts);
return $alerts;
}
/**
* Creates an Alert for given website(s).
*
* @param string $name
* @param int[] $idSites
* @param string $login
* @param string $period
* @param bool $emailMe
* @param array $additionalEmails
* @param array $phoneNumbers
* @param string $metric (nb_uniq_visits, sum_visit_length, ..)
* @param string $metricCondition
* @param float $metricValue
* @param int $comparedTo
* @param string $reportUniqueId
* @param string $reportCondition
* @param string $reportValue
*
* @throws \Exception
* @internal param bool $enableEmail
* @return int ID of new Alert
*/
public function createAlert($name, $idSites, $login, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue)
{
$idAlert = $this->getNextAlertId();
$newAlert = array(
'idalert' => $idAlert,
'name' => $name,
'period' => $period,
'login' => $login,
'email_me' => $emailMe ? 1 : 0,
'additional_emails' => json_encode($additionalEmails),
'phone_numbers' => json_encode($phoneNumbers),
'metric' => $metric,
'metric_condition' => $metricCondition,
'metric_matched' => $metricValue,
'report' => $reportUniqueId,
'compared_to' => $comparedTo,
'report_condition' => $reportCondition,
'report_matched' => $reportValue
);
$db = $this->getDb();
$db->insert(Common::prefixTable('alert'), $newAlert);
$this->setSiteIds($idAlert, $idSites);
return $idAlert;
}
/**
* Edits an Alert for given website(s).
*
* @param $idAlert
* @param string $name Name of Alert
* @param int[] $idSites array of ints of idSites.
* @param string $period Period the alert is defined on.
* @param bool $emailMe
* @param array $additionalEmails
* @param array $phoneNumbers
* @param string $metric (nb_uniq_visits, sum_visit_length, ..)
* @param string $metricCondition
* @param float $metricValue
* @param int $comparedTo
* @param string $reportUniqueId
* @param string $reportCondition
* @param string $reportValue
*
* @throws \Exception
* @internal param bool $enableEmail
* @return boolean
*/
public function updateAlert($idAlert, $name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue)
{
$alert = array(
'name' => $name,
'period' => $period,
'email_me' => $emailMe ? 1 : 0,
'additional_emails' => json_encode($additionalEmails),
'phone_numbers' => json_encode($phoneNumbers),
'metric' => $metric,
'metric_condition' => $metricCondition,
'metric_matched' => $metricValue,
'report' => $reportUniqueId,
'compared_to' => $comparedTo,
'report_condition' => $reportCondition,
'report_matched' => $reportValue
);
$db = $this->getDb();
$db->update(Common::prefixTable('alert'), $alert, "idalert = " . intval($idAlert));
$this->setSiteIds($idAlert, $idSites);
return $idAlert;
}
/**
* Delete alert by id.
*
* @param int $idAlert
*
* @throws \Exception In case alert does not exist or not enough permission
*/
public function deleteAlert($idAlert)
{
$db = $this->getDb();
$db->query("DELETE FROM " . Common::prefixTable("alert") . " WHERE idalert = ?", array($idAlert));
$db->query("DELETE FROM " . Common::prefixTable("alert_triggered") . " WHERE idalert = ?", array($idAlert));
$this->removeAllSites($idAlert);
}
public function triggerAlert($idAlert, $idSite, $valueNew, $valueOld, $datetime)
{
$alert = $this->getAlert($idAlert);
$keysToKeep = array('idalert', 'name', 'login', 'period', 'metric', 'metric_condition', 'metric_matched', 'report', 'report_condition', 'report_matched', 'compared_to', 'email_me', 'additional_emails', 'phone_numbers');
$triggeredAlert = array();
foreach ($keysToKeep as $key) {
$triggeredAlert[$key] = $alert[$key];
}
$triggeredAlert['metric_matched'] = Common::forceDotAsSeparatorForDecimalPoint($triggeredAlert['metric_matched']);
$triggeredAlert['ts_triggered'] = $datetime;
$triggeredAlert['ts_last_sent'] = null;
$triggeredAlert['value_new'] = $valueNew;
$triggeredAlert['value_old'] = $valueOld;
$triggeredAlert['idsite'] = $idSite;
$triggeredAlert['additional_emails'] = json_encode($triggeredAlert['additional_emails']);
$triggeredAlert['phone_numbers'] = json_encode($triggeredAlert['phone_numbers']);
$db = $this->getDb();
$db->insert(
Common::prefixTable('alert_triggered'),
$triggeredAlert
);
}
public function markTriggeredAlertAsSent($idTriggered, $timestamp)
{
$log = array(
'ts_last_sent' => Date::factory($timestamp)->getDatetime()
);
$where = sprintf("idtriggered = %d", $idTriggered);
$db = $this->getDb();
$db->update(Common::prefixTable('alert_triggered'), $log, $where);
}
public function setSiteIds($idAlert, $idSites)
{
$this->removeAllSites($idAlert);
$db = $this->getDb();
foreach ($idSites as $idSite) {
$db->insert(Common::prefixTable('alert_site'), array(
'idalert' => intval($idAlert),
'idsite' => intval($idSite)
));
}
}
public function deleteTriggeredAlertsForSite($idSite)
{
$this->getDb()->query("DELETE FROM " . Common::prefixTable("alert_triggered") . " WHERE idsite = ?", $idSite);
}
private function getDefinedSiteIds($idAlert)
{
$sql = "SELECT idsite FROM " . Common::prefixTable('alert_site') . " WHERE idalert = ?";
$sites = Db::fetchAll($sql, $idAlert, \PDO::FETCH_COLUMN);
$idSites = array();
foreach ($sites as $site) {
$idSites[] = $site['idsite'];
}
return $idSites;
}
private function getNextAlertId()
{
$idAlert = Db::fetchOne("SELECT max(idalert) + 1 FROM " . Common::prefixTable('alert'));
if (empty($idAlert)) {
$idAlert = 1;
}
return $idAlert;
}
private function completeAlerts($alerts)
{
foreach ($alerts as &$alert) {
$alert['additional_emails'] = json_decode($alert['additional_emails']);
$alert['phone_numbers'] = json_decode($alert['phone_numbers']);
$alert['email_me'] = (int) $alert['email_me'];
$alert['compared_to'] = (int) $alert['compared_to'];
$alert['id_sites'] = $this->getDefinedSiteIds($alert['idalert']);
}
return $alerts;
}
private function removeAllSites($idAlert)
{
$this->getDb()->query("DELETE FROM " . Common::prefixTable("alert_site") . " WHERE idalert = ?", $idAlert);
}
/**
* @param $idSites
* @return array
*/
protected function getInnerSiteQuery($idSites)
{
$idSites = array_map('intval', $idSites);
$innerSiteQuery = "SELECT idalert FROM " . Common::prefixTable('alert_site')
. " WHERE idsite IN (" . implode(",", $idSites) . ")";
return $innerSiteQuery;
}
private function getDb()
{
return Db::get();
}
}