forked from emoncms/event_archived
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_model.php
473 lines (396 loc) · 21.1 KB
/
event_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
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
<?php
/*
All Emoncms code is released under the GNU Affero General Public License.
See COPYRIGHT.txt and LICENSE.txt.
---------------------------------------------------------------------
Emoncms - open source energy visualisation
Part of the OpenEnergyMonitor project:
http://openenergymonitor.org
*/
// no direct access
defined('EMONCMS_EXEC') or die('Restricted access');
class Event
{
private $mysqli;
private $redis;
public function __construct($mysqli,$redis)
{
$this->mysqli = $mysqli;
$this->redis = $redis;
}
/*
$this->mysqli->query("INSERT INTO table (`field`) VALUES ('$value')");
$this->mysqli->query("SELECT * FROM table WHERE `field` = '$value'");
$this->mysqli->query(UPDATE table SET field = '$value' WHERE `field` = '$value');
*/
public function set_lasttime($userid,$id,$time)
{
$this->mysqli->query("UPDATE event SET `lasttime` = '$time' WHERE `userid` = '$userid' AND `id` = '$id' ");
}
public function update($userid,$id,$eventfeed,$eventtype,$eventvalue,$action,$setfeed,$setemail,$setvalue,$callcurl,$message,$mutetime,$priority,$mqtttopic,$mqttqos)
{
$sql = "UPDATE event SET eventfeed = $eventfeed, eventtype = $eventtype, eventvalue = $eventvalue, action = $action, setfeed = $setfeed, setemail = '$setemail', setvalue = $setvalue, callcurl = '$callcurl', mutetime = $mutetime, priority = $priority, message = '$message', mqtttopic = '$mqtttopic', mqttqos = '$mqttqos' WHERE `userid` = '$userid' AND `id` = '$id' ";
error_log('Mysql Query: ' + $sql);
$result = $this->mysqli->query($sql);
if (!$result){
error_log('Event Update: Mysql Error: ' + $this->mysqli->error);
}
}
public function add($userid,$eventfeed,$eventtype,$eventvalue,$action,$setfeed,$setemail,$setvalue,$callcurl,$message,$mutetime,$priority,$mqtttopic,$mqttqos)
{
$sql = "INSERT INTO event (`userid`,`eventfeed`, `eventtype`, `eventvalue`, `action`, `setfeed`, `setemail`, `setvalue`, `lasttime`, `callcurl`, `mutetime`, `priority`, `message`, `disabled`, `mqtttopic`, `mqttqos`) VALUES ('$userid','$eventfeed','$eventtype','$eventvalue','$action','$setfeed','$setemail','$setvalue','0','$callcurl','$mutetime','$priority','$message','0','$mqtttopic','$mqttqos')";
error_log('Mysql Query: ' + $sql);
$result = $this->mysqli->query($sql);
if (!$result){
error_log('Event Add: Mysql Error: ' + $this->mysqli->error);
}
}
public function delete($userid,$id)
{
$this->mysqli->query("DELETE FROM event WHERE `userid` = '$userid' AND `id` = '$id'");
}
public function eventlist($userid)
{
$list = array();
$result = $this->mysqli->query("SELECT * FROM event WHERE `userid` = '$userid'");
while ($row = $result->fetch_array())
{
$list[] = $row;
}
return $list;
}
// Set all event settings in one save
public function set_settings($userid,$prowlkey,$consumerkey,$consumersecret,$usertoken,$usersecret,$smtpserver,$smtpuser,$smtppassword,$smtpport,$nmakey,$mqttbrokerip,$mqttbrokerport,$mqttusername,$mqttpassword)
{
$result = $this->mysqli->query("SELECT userid FROM event_settings WHERE `userid` = '$userid'");
$row = $result->fetch_array();
if (!$row) {
$result = $this->mysqli->query("INSERT INTO event_settings (`userid`) VALUES ('$userid')");
}
else {
$result = $this->mysqli->query("UPDATE event_settings SET prowlkey = '$prowlkey', consumerkey = '$consumerkey', consumersecret = '$consumersecret', usertoken = '$usertoken', usersecret = '$usersecret', smtpserver = '$smtpserver', smtpuser = '$smtpuser', smtppassword = '$smtppassword', smtpport = '$smtpport', nmakey = '$nmakey',mqttbrokerip='$mqttbrokerip', mqttbrokerport='$mqttbrokerport', mqttusername='$mqttusername', mqttpassword='$mqttpassword' WHERE userid='$userid'");
}
return $result;
}
public function set_status($userid, $id, $status)
{
$this->mysqli->query("UPDATE event SET disabled = '$status' WHERE userid='$userid' and id = $id");
}
public function get_settings($userid) {
$result = $this->mysqli->query("SELECT * FROM event_settings WHERE `userid` = '$userid'");
$row = $result->fetch_array();
return $row;
}
public function get_user_smtp($userid) {
$result = $this->mysqli->query("SELECT smtpserver, smtpuser, smtppassword, smtpport FROM event_settings WHERE `userid` = '$userid'");
$row = $result->fetch_array();
return $row;
}
public function get_user_twitter($userid) {
$result = $this->mysqli->query("SELECT consumerkey, consumersecret, usertoken, usersecret FROM event_settings WHERE `userid` = '$userid'");
$row = $result->fetch_array();
return $row;
}
public function get_user_prowl($userid) {
$result = $this->mysqli->query("SELECT prowlkey FROM event_settings WHERE `userid` = '$userid'");
$row = $result->fetch_array();
return $row;
}
public function get_user_nma($userid) {
$result = $this->mysqli->query("SELECT nmakey FROM event_settings WHERE `userid` = '$userid'");
$row = $result->fetch_array();
return $row;
}
public function get_user_mqtt($userid) {
$result = $this->mysqli->query("SELECT mqttbrokerip, mqttbrokerport, mqttusername, mqttpassword FROM event_settings WHERE `userid` = '$userid'");
$row = $result->fetch_array();
return $row;
}
public function test($userid,$id,$feedid)
{
global $feed;
$t = time();
$f = $feed->get($feedid);
if($f){
$this->check_feed_event($id,$t,$t,$f['value'],null,true);
}else{
return("Wrong input parameters");
}
}
public function check_feed_event($feedid,$updatetime,$feedtime,$value,$row=NULL,$test=false) {
global $user,$session,$feed;
$userid = $session['userid'];
$sqlFeed = "SELECT * FROM event WHERE `userid` = '$userid'";
if ($test){
$sqlFeed = $sqlFeed. " and id = $feedid";
}else{
$sqlFeed = $sqlFeed. " and (`disabled` <> 1 or `disabled` IS NULL) and (eventfeed = $feedid or eventtype=3)";
}
$result = $this->mysqli->query($sqlFeed);
// check type
while ($row = $result->fetch_array()) {
if ($row['lasttime']+$row['mutetime'] > time() && !$test) {
continue;
}
if ($test){
$sendAlert = 1;
}else{
$sendAlert = 0;
switch($row['eventtype']) {
case 0:
// more than
if ($value > $row['eventvalue']) {
$sendAlert = 1;
}
break;
case 1:
// less than
if ($value < $row['eventvalue']) {
$sendAlert = 1;
}
break;
case 2:
// equal to
if ($value == $row['eventvalue']) {
$sendAlert = 1;
}
break;
case 3:
// inactive
// not sure this can be called as no feed updated
//if (((time()-$row['lasttime'])/3600)>24) {}
$feedData = $feed->get($row['eventfeed']);
//error_log("Feeddata: " .$feedData->time);
$t = time()- strtotime($feedData['time']);
//error_log("t: " .$t);
if ($t > $row['eventvalue']){
$sendAlert = 1;
}
break;
case 4:
// updated
$sendAlert = 1;
break;
case 5:
// increased by
$feedname = 'feed_'.$feedid;
$resultprev = $this->mysqli->query("SELECT * FROM $feedname ORDER BY `time` DESC LIMIT 1,1");
$rowprev = $resultprev->fetch_array();
//echo "INC == ".$value." > ".$rowprev['data']."+".$row['eventvalue'];
if ($value > ($rowprev['data']+$row['eventvalue'])) {
$sendAlert = 1;
}
break;
case 6:
// decreased by
$feedname = 'feed_'.$feedid;
$resultprev = $this->mysqli->query("SELECT * FROM $feedname ORDER BY `time` DESC LIMIT 1,1");
$rowprev = $resultprev->fetch_array();
//echo "DEC == ".$value."<". $rowprev['data']."-".$row['eventvalue'];
if ($value < ($rowprev['data']-$row['eventvalue'])) {
$sendAlert = 1;
}
break;
case 7:
// manual update
// Check if event.lasttime is less than feed.time
$feedData = $feed->get($feedid);
if ($feedData['time'] > $row['lasttime']){
$sendAlert = 1;
}
}
}
$feedData = $feed->get($row['eventfeed']);
$message = $row['message'];
$message = str_replace('{feed}', $feedData['name'], $message);
$message = str_replace('{value}', $value, $message);
$message = htmlspecialchars($message);
if (empty($message)) { $message = "No message body"; }
if($test){
$message = 'TEST - '.$message;
}
// event type
if ($sendAlert == 1) {
switch($row['action']) {
case 0:
// email
require_once(realpath(dirname(__FILE__)).'/../event/scripts/phpmailer/class.phpmailer.php');
require_once(realpath(dirname(__FILE__)).'/../event/scripts/phpmailer/class.smtp.php');
$smtp = $this->get_settings($userid);
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 0; // SMTP debug information (for testing)
// 0 No output
// 1 Commands
// 2 Data and commands
// 3 As 2 plus connection status
// 4 Low-level data output
$mail->SMTPAuth = true; // enable SMTP authentication
if ($smtp['smtpport'] == 587)
{$mail->SMTPSecure = "tls";} // use it for gmail ssl is deprecated
else if ($smtp['smtpport'] == 465)
{$mail->SMTPSecure = "ssl";} // sets the prefix to the server
$mail->Host = $smtp['smtpserver']; // sets GMAIL as the SMTP server
$mail->Port = $smtp['smtpport']; // set the SMTP port for the GMAIL server
$mail->Username = $smtp['smtpuser']; // GMAIL username
$salt = $user->get_salt($userid);
$c = base64_decode($smtp['smtppassword']);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$mail->Password = openssl_decrypt($ciphertext_raw, $cipher, $salt, $options=OPENSSL_RAW_DATA, $iv); // GMAIL password
$address = $smtp['smtpuser'];
$mail->SetFrom($address, 'emoncms');
//$mail->AddReplyTo("[email protected]', 'First Last");
$mail->Subject = $message;
//$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($message);
$dest = $address;
if ($row['setemail'] != ''){
$dest = $row['setemail'];
}
// Allows multiple recipients for the event email. Seperate by semi-colon ;
if (strpos($dest,';') !== false) {
$addresses = explode(';', $dest);
foreach ($addresses as &$addressee) {
$mail->AddAddress($addressee, "emoncms");
}
}
else {
$mail->AddAddress($dest, "emoncms");
}
//$mail->AddAttachment("images/phpmailer.gif"); // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
error_log("Mailer Error: " . $mail->ErrorInfo);
} else {
echo "Message sent!";
error_log("Message sent");
}
break;
case 1:
// set feed
$setfeed = $row['setfeed'];
$setvalue = $row['setvalue'];
$this->redis->hMset("feed:lastvalue:$setfeed", array('value' => $setvalue, 'time' => $updatetime));
// $this->mysqli->query("UPDATE feeds SET value = '$setvalue', time = '$updatetime' WHERE id='$setfeed'");
break;
case 2:
// call url
$explodedUrl = preg_split('/[?]+/', $row['callcurl'],-1);
if (count($explodedUrl) > 1){
$explodedUrl[1] = str_replace(' ', '%20', str_replace('{value}', $value, str_replace('{feed}', $feedData->name, $explodedUrl[1])));
}
$ch = curl_init();
$body = $explodedUrl[0] . '?' . $explodedUrl[1];
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $body);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
// grab URL and pass it to the browser
if(curl_exec($ch) === false){
error_log("Curl Error:".curl_error($ch));
}
// close cURL resource, and free up system resources
curl_close($ch);
error_log("Curl Log:".$body);
break;
case 3:
// Twitter
require_once(realpath(dirname(__FILE__)).'/../event/scripts/twitter/twitter-api-php/TwitterAPIExchange.php');
$twitter = $this->get_user_twitter($userid);
// Twitter disallow duplicate tweets within an unspecified and variable time per account
// so add the feed time to make each tweet unique.
$message = $message.' at '.date("H:i:s", $feedtime);;
// Set the OAauth values
$settings = array(
'oauth_access_token' => $twitter['usertoken'],
'oauth_access_token_secret' => $twitter['usersecret'],
'consumer_key' => $twitter['consumerkey'],
'consumer_secret' => $twitter['consumersecret']
);
// Make the API call
$url = 'https://api.twitter.com/1.1/statuses/update.json';
$requestMethod = 'POST';
$postfields = array(
'status' => $message );
$tweet = new TwitterAPIExchange($settings);
echo $tweet->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
break;
case 4:
// Prowl
require_once realpath(dirname(__FILE__)).'/scripts/prowlphp/ProwlConnector.class.php';
require_once realpath(dirname(__FILE__)).'/scripts/prowlphp/ProwlMessage.class.php';
require_once realpath(dirname(__FILE__)).'/scripts/prowlphp/ProwlResponse.class.php';
$prowl = $this->get_user_prowl($userid);
$oProwl = new ProwlConnector();
$oMsg = new ProwlMessage();
$oProwl->setIsPostRequest(true);
$oMsg->setPriority($row['priority']);
$oMsg->addApiKey($prowl['prowlkey']);
$oMsg->setEvent($message);
// These are optional:
$message = 'event at '.date("Y-m-d H:i:s",time());
$oMsg->setDescription($message);
$oMsg->setApplication('emoncms');
$oResponse = $oProwl->push($oMsg);
if ($oResponse->isError()) {
error_log("Prowl error:".$oResponse->getErrorAsString());
}
break;
case 5:
// NMA
require_once realpath(dirname(__FILE__)).'/scripts/nma/nmaApi.class.php';
$nmakey = $this->get_user_nma($userid);
$nma = new nmaApi(array('apikey' => $nmakey['nmakey']));
$priority = $row['priority'];
if($nma->verify()){
$nma->notify('EmonCMS '.$message, 'EmonCMS', $message, $priority);
}
break;
case 6:
// MQTT
require_once realpath(dirname(__FILE__)).'/scripts/mqtt/phpMQTT.php';
$mqttSettings = $this->get_user_mqtt($userid);
$salt = $user->get_salt($userid);
$mqtttopic = $row['mqtttopic'];
$mqtttopic = str_replace('{feed}', $feedData['name'], $mqtttopic);
$mqtttopic = str_replace('{value}', $value, $mqtttopic);
$mqtttopic = htmlspecialchars($mqtttopic);
$mqttqos = $row['mqttqos'];
if (empty($mqttqos)) { $mqttqos = 0; }
// setup connection
$mqtt = new phpMQTT($mqttSettings['mqttbrokerip'],$mqttSettings['mqttbrokerport'], "emoncms");
if(empty($mqttSettings['mqttusername'])){
$mqttConnected = $mqtt->connect();
}else{
$mqttusername = $mqttSettings['mqttusername'];
$c = base64_decode($settings['mqttpassword']);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$mqttpassword = openssl_decrypt($ciphertext_raw, $cipher, $salt, $options=OPENSSL_RAW_DATA, $iv);
$mqttConnected = $mqtt->connect(false, NULL, $mqttusername, $mqttpassword);
}
if ($mqttConnected) {
$mqtt->publish($mqtttopic,$message,$mqttqos);
}else{
error_log("MQTT connection failed");
}
$mqtt->close();
break;
}
// update the lasttime called
if(!$test){
$this->mysqli->query("UPDATE event SET lasttime = '".time()."' WHERE id='".$row['id']."'");
}
}
}
}
}