-
Notifications
You must be signed in to change notification settings - Fork 71
/
common.php
597 lines (516 loc) · 19.8 KB
/
common.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
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
<?php
use BikeShare\SmsConnector\SmsConnectorFactory;
require_once 'vendor/autoload.php';
$locale = $systemlang . ".utf8";
setlocale(LC_ALL, $locale);
putenv("LANG=" . $locale);
bindtextdomain("messages", dirname(__FILE__) . '/languages');
textdomain("messages");
$sms = (new SmsConnectorFactory())->getConnector(
!empty($connectors["sms"]) ? $connectors["sms"] : 'disabled',
!empty($connectors["config"][$connectors["sms"]]) ? json_decode($connectors["config"][$connectors["sms"]], true) : array(),
DEBUG
);
function error($message)
{
global $db;
$db->conn->rollback();
exit($message);
}
function sendEmail($emailto, $subject, $message)
{
global $systemname, $systememail, $email;
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
//$mail->SMTPDebug = 2;
$mail->Host = $email["smtp"]; // Specify main and backup SMTP servers
$mail->Username = $email["user"]; // SMTP username
$mail->Password = $email["pass"]; // SMTP password
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->SMTPSecure = "ssl"; // Enable SSL
$mail->Port = 465; // TCP port to connect to
$mail->CharSet = "UTF-8";
$mail->From = $systememail;
$mail->FromName = $systemname;
$mail->addAddress($emailto); // Add a recipient
$mail->addBCC($systememail); // Add a recipient
$mail->Subject = $subject;
$mail->Body = $message;
if (DEBUG === FALSE) {
$mail->send();
} else {
echo $email, ' | ', $subject, ' | ', $message;
}
}
function sendSMS($number,$text)
{
global $sms;
$message = $text;
if (strlen($message) > 160) {
$message = chunk_split($message, 160, '|');
$message = explode('|', $message);
foreach ($message as $text) {
$text = trim($text);
if ($text) {
logSendsms($number, $text);
if (DEBUG === true) {
echo $number, ' -> ', $text, '<br />';
} else {
$sms->send($number, $text);
}
}
}
} else {
logSendsms($number, $text);
if (DEBUG === true) {
echo $number, ' -> ', $text, '<br />';
} else {
$sms->send($number, $text);
}
}
}
function logSendsms($number, $text)
{
global $dbserver,$dbuser,$dbpassword,$dbname;
$localdb=new Database($dbserver,$dbuser,$dbpassword,$dbname);
$localdb->connect();
$localdb->conn->autocommit(TRUE);
$number = $localdb->conn->real_escape_string($number);
$text = $localdb->conn->real_escape_string($text);
$result = $localdb->query("INSERT INTO sent SET number='$number',text='$text'");
}
function generatecodes($numcodes,$codelength,$wastage=25)
{
// exclude problem chars: B8G6I1l0OQDS5Z2
// acceptable characters:
$goodchars='ACEFHJKMNPRTUVWXY4937';
// build array allowing for possible wastage through duplicate values
for ($i=0;$i<=$numcodes+$wastage+1;$i++)
{
$codes[]=substr(str_shuffle($goodchars),0,$codelength);
}
return array_slice($codes,0,($numcodes+1));
}
function getprivileges($userid)
{
global $db;
$result = $db->query("SELECT privileges FROM users WHERE userId=$userid");
if ($result->num_rows==1)
{
$row = $result->fetch_assoc();
return $row["privileges"];
}
return FALSE;
}
function getusername($userid)
{
global $db;
$result = $db->query("SELECT userName FROM users WHERE userId=$userid");
if ($result->num_rows==1)
{
$row = $result->fetch_assoc();
return $row["userName"];
}
return FALSE;
}
function getusercity($userid)
{
global $db;
$result = $db->query("SELECT city FROM users WHERE userId=$userid");
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
return $row['city'];
}
return false;
}
function getphonenumber($userid)
{
global $db;
$result = $db->query("SELECT number FROM users WHERE userId=$userid");
if ($result->num_rows==1)
{
$row = $result->fetch_assoc();
return $row["number"];
}
return FALSE;
}
function getuserid($number)
{
global $db;
$result = $db->query("SELECT userId FROM users WHERE number='$number'");
if ($result->num_rows==1)
{
$row = $result->fetch_assoc();
return $row["userId"];
}
return FALSE;
}
function isloggedin()
{
global $db;
if (isset($_COOKIE['loguserid']) and isset($_COOKIE['logsession'])) {
$userid = $db->conn->real_escape_string(trim($_COOKIE['loguserid']));
$session = $db->conn->real_escape_string(trim($_COOKIE['logsession']));
$result = $db->query("SELECT sessionId FROM sessions WHERE userId='$userid' AND sessionId='$session' AND timeStamp>'" . time() . "'");
if ($result->num_rows == 1) {
return 1;
} else {
return 0;
}
}
return 0;
}
function checksession()
{
global $db, $systemURL;
$result = $db->query("DELETE FROM sessions WHERE timeStamp<='" . time() . "'");
if (isset($_COOKIE['loguserid']) and isset($_COOKIE['logsession'])) {
$userid = $db->conn->real_escape_string(trim($_COOKIE['loguserid']));
$session = $db->conn->real_escape_string(trim($_COOKIE['logsession']));
$result = $db->query("SELECT sessionId FROM sessions WHERE userId='$userid' AND sessionId='$session' AND timeStamp>'" . time() . "'");
if ($result->num_rows == 1) {
$timestamp = time() + 86400 * 14;
$result = $db->query("UPDATE sessions SET timeStamp='$timestamp' WHERE userId='$userid' AND sessionId='$session'");
$db->conn->commit();
} else {
$result = $db->query("DELETE FROM sessions WHERE userId='$userid' OR sessionId='$session'");
$db->conn->commit();
setcookie('loguserid', '', time() - 86400);
setcookie('logsession', '', time() - 86400);
header('HTTP/1.1 302 Found');
header('Location: ' . $systemURL . '?error=2');
header('Connection: close');
exit;
}
} else {
header('HTTP/1.1 302 Found');
header('Location: ' . $systemURL . '?error=2');
header('Connection: close');
exit;
}
}
function logrequest($userid)
{
global $dbserver, $dbuser, $dbpassword, $dbname;
$localdb = new Database($dbserver, $dbuser, $dbpassword, $dbname);
$localdb->connect();
$localdb->conn->autocommit(true);
$number = getphonenumber($userid);
$result = $localdb->query("INSERT INTO received SET sender='$number',receive_time='" . date('Y-m-d H:i:s') . "',sms_text='" . $_SERVER['REQUEST_URI'] . "',ip='" . $_SERVER['REMOTE_ADDR'] . "'");
}
function logresult($userid, $text)
{
global $dbserver, $dbuser, $dbpassword, $dbname;
$localdb = new Database($dbserver, $dbuser, $dbpassword, $dbname);
$localdb->connect();
$localdb->conn->autocommit(true);
$userid = $localdb->conn->real_escape_string($userid);
$logtext = '';
if (is_array($text)) {
foreach ($text as $value) {
$logtext .= $value . '; ';
}
} else {
$logtext = $text;
}
$logtext = strip_tags($localdb->conn->real_escape_string($logtext));
$result = $localdb->query("INSERT INTO sent SET number='$userid',text='$logtext'");
}
function checkbikeno($bikeNum)
{
global $db;
$bikeNum = intval($bikeNum);
$result = $db->query("SELECT bikeNum FROM bikes WHERE bikeNum=$bikeNum");
if (!$result->num_rows) {
response('<h3>Bike ' . $bikeNum . ' does not exist!</h3>', ERROR);
}
}
function checkstandname($stand)
{
global $db;
$standname = trim(strtoupper($stand));
$result = $db->query("SELECT standName FROM stands WHERE standName='$stand'");
if (!$result->num_rows) {
response('<h3>' . _('Stand') . ' ' . $stand . ' ' . _('does not exist') . '!</h3>', ERROR);
}
}
/**
* @param int $notificationtype 0 = via SMS, 1 = via email
**/
function notifyAdmins($message, $notificationtype = 0)
{
global $db, $systemname, $watches;
$result = $db->query('SELECT number,mail FROM users where privileges & 2 != 0');
while ($row = $result->fetch_assoc()) {
if ($notificationtype == 0) {
sendSMS($row['number'], $message);
sendEmail($watches['email'], $systemname . ' ' . _('notification'), $message);
} else {
sendEmail($row['mail'], $systemname . ' ' . _('notification'), $message);
}
}
//copy to Trello board -- might be added as a person instead
if ($notificationtype == 0) {
sendEmail('cyklokoalicia1+q31wfjphbgkuelf19hlb@boards.trello.com', $message, $message);
}
}
function sendConfirmationEmail($emailto)
{
global $db, $dbpassword, $systemname, $systemrules, $systemURL;
$subject = _('Registration');
$result = $db->query("SELECT userName,userId FROM users WHERE mail='" . $emailto . "'");
$row = $result->fetch_assoc();
$userId = $row['userId'];
$userKey = hash('sha256', $emailto . $dbpassword . rand(0, 1000000));
$db->query("INSERT INTO registration SET userKey='$userKey',userId='$userId'");
$db->query("INSERT INTO limits SET userId='$userId',userLimit=0");
$db->query("INSERT INTO credit SET userId='$userId',credit=0");
$names = preg_split("/[\s,]+/", $row['userName']);
$firstname = $names[0];
$message = _('Hello') . ' ' . $firstname . ",\n\n" .
_('you have been registered into community bike share system') . ' ' . $systemname . ".\n\n" .
_('System rules are available here:') . "\n" . $systemrules . "\n\n" .
_('By clicking the following link you agree to the System rules:') . "\n" . $systemURL . 'agree.php?key=' . $userKey;
sendEmail($emailto, $subject, $message);
}
function confirmUser($userKey)
{
global $db, $limits;
$userKey = $db->conn->real_escape_string($userKey);
$result = $db->query("SELECT userId FROM registration WHERE userKey='$userKey'");
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
$userId = $row['userId'];
} else {
echo '<div class="alert alert-danger" role="alert">', _('Registration key not found!'), '</div>';
return false;
}
$db->query("UPDATE limits SET userLimit='" . $limits['registration'] . "' WHERE userId=$userId");
$db->query("DELETE FROM registration WHERE userId='$userId'");
echo '<div class="alert alert-success" role="alert">', _('Your account has been activated. Welcome!'), '</div>';
}
function checktopofstack($standid)
{
global $db;
$currentbikes = array();
// find current bikes at stand
$result = $db->query("SELECT bikeNum FROM bikes LEFT JOIN stands ON bikes.currentStand=stands.standId WHERE standId='$standid'");
while ($row = $result->fetch_assoc()) {
$currentbikes[] = $row['bikeNum'];
}
if (count($currentbikes)) {
// find last returned bike at stand
$result = $db->query("SELECT bikeNum FROM history WHERE action IN ('RETURN','FORCERETURN') AND parameter='$standid' AND bikeNum IN (" . implode($currentbikes, ',') . ') ORDER BY time DESC LIMIT 1');
if ($result->num_rows) {
$row = $result->fetch_assoc();
return $row['bikeNum'];
}
}
return false;
}
function checklongrental()
{
global $db, $watches, $notifyuser;
$abusers = '';
$found = 0;
$result = $db->query('SELECT bikeNum,currentUser,userName,number FROM bikes LEFT JOIN users ON bikes.currentUser=users.userId WHERE currentStand IS NULL');
while ($row = $result->fetch_assoc()) {
$bikenum = $row['bikeNum'];
$userid = $row['currentUser'];
$username = $row['userName'];
$userphone = $row['number'];
$result2 = $db->query("SELECT time FROM history WHERE bikeNum=$bikenum AND userId=$userid AND action='RENT' ORDER BY time DESC LIMIT 1");
if ($result2->num_rows) {
$row2 = $result2->fetch_assoc();
$time = $row2['time'];
$time = strtotime($time);
if ($time + ($watches['longrental'] * 3600) <= time()) {
$abusers .= ' b' . $bikenum . ' ' . _('by') . ' ' . $username . ',';
$found = 1;
if ($notifyuser) {
sendSMS($userphone, _('Please, return your bike ') . $bikenum . _(' immediately to the closest stand! Ignoring this warning can get you banned from the system.'));
}
}
}
}
if ($found) {
$abusers = substr($abusers, 0, strlen($abusers) - 1);
notifyAdmins($watches['longrental'] . '+ ' . _('hour rental') . ':' . $abusers);
}
}
// cron - called from cron by default, set to 0 if from rent function, userid needs to be passed if cron=0
function checktoomany($cron = 1, $userid = 0)
{
global $db, $watches;
$abusers = '';
$found = 0;
if ($cron) { // called from cron
$result = $db->query('SELECT users.userId,userName,userLimit FROM users LEFT JOIN limits ON users.userId=limits.userId');
while ($row = $result->fetch_assoc()) {
$userid = $row['userId'];
$username = $row['userName'];
$userlimit = $row['userLimit'];
$currenttime = date('Y-m-d H:i:s', time() - $watches['timetoomany'] * 3600);
$result2 = $db->query("SELECT bikeNum FROM history WHERE userId=$userid AND action='RENT' AND time>'$currenttime'");
if ($result2->num_rows >= ($userlimit + $watches['numbertoomany'])) {
$abusers .= ' ' . $result2->num_rows . ' (' . _('limit') . ' ' . $userlimit . ') ' . _('by') . ' ' . $username . ',';
$found = 1;
}
}
} else { // called from function for user userid
$result = $db->query("SELECT users.userId,userName,userLimit FROM users LEFT JOIN limits ON users.userId=limits.userId WHERE users.userId=$userid");
$row = $result->fetch_assoc();
$username = $row['userName'];
$userlimit = $row['userLimit'];
$currenttime = date('Y-m-d H:i:s', time() - $watches['timetoomany'] * 3600);
$result = $db->query("SELECT bikeNum FROM history WHERE userId=$userid AND action='RENT' AND time>'$currenttime'");
if ($result->num_rows >= ($userlimit + $watches['numbertoomany'])) {
$abusers .= ' ' . $result->num_rows . ' (' . _('limit') . ' ' . $userlimit . ') ' . _('by') . ' ' . $username . ',';
$found = 1;
}
}
if ($found) {
$abusers = substr($abusers, 0, strlen($abusers) - 1);
notifyAdmins(_('Over limit in') . ' ' . $watches['timetoomany'] . ' ' . _('hs') . ':' . $abusers);
}
}
// check if user has credit >= minimum credit+rent fee+long rental fee
function checkrequiredcredit($userid)
{
global $db, $credit;
if (iscreditenabled() == false) {
return;
}
// if credit system disabled, exit
$requiredcredit = $credit['min'] + $credit['rent'] + $credit['longrental'];
$result = $db->query("SELECT credit FROM credit WHERE userId=$userid AND credit>=$requiredcredit");
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
return true;
}
return false;
}
// subtract credit for rental
function changecreditendrental($bike, $userid)
{
global $db, $watches, $credit;
if (iscreditenabled() == false) {
return;
}
// if credit system disabled, exit
$usercredit = getusercredit($userid);
$result = $db->query("SELECT time FROM history WHERE bikeNum=$bike AND userId=$userid AND (action='RENT' OR action='FORCERENT') ORDER BY time DESC LIMIT 1");
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
$starttime = strtotime($row['time']);
$endtime = time();
$timediff = $endtime - $starttime;
$creditchange = 0;
$changelog = '';
//ak vrati a znova pozica bike do 10 min tak free time nebude mať.
$oldRetrun = $db->query("SELECT time FROM history WHERE bikeNum=$bike AND userId=$userid AND (action='RETURN' OR action='FORCERETURN') ORDER BY time DESC LIMIT 1");
if ($oldRetrun->num_rows==1)
{
$oldRow=$oldRetrun->fetch_assoc();
$returntime=strtotime($oldRow["time"]);
if(($starttime-$returntime) < 10*60 && $timediff > 5*60) {
$creditchange = $creditchange + $credit['rent'];
$changelog .= 'rerent-' . $credit['rent'] . ';';
}
}
//end
if ($timediff > $watches['freetime'] * 60) {
$creditchange = $creditchange + $credit['rent'];
$changelog .= 'overfree-' . $credit['rent'] . ';';
}
if ($watches['freetime'] == 0) {
$watches['freetime'] = 1;
}
// for further calculations
if ($credit['pricecycle'] and $timediff > $watches['freetime'] * 60 * 2) { // after first paid period, i.e. freetime*2; if pricecycle enabled
$temptimediff = $timediff - ($watches['freetime'] * 60 * 2);
if ($credit['pricecycle'] == 1) { // flat price per cycle
$cycles = ceil($temptimediff / ($watches['flatpricecycle'] * 60));
$creditchange = $creditchange + ($credit['rent'] * $cycles);
$changelog .= 'flat-' . $credit['rent'] * $cycles . ';';
} elseif ($credit['pricecycle'] == 2) { // double price per cycle
$cycles = ceil($temptimediff / ($watches['doublepricecycle'] * 60));
$tempcreditrent = $credit['rent'];
for ($i = 1; $i <= $cycles; $i++) {
$multiplier = $i;
if ($multiplier > $watches['doublepricecyclecap']) {
$multiplier = $watches['doublepricecyclecap'];
}
// exception for rent=1, otherwise square won't work:
if ($tempcreditrent == 1) {
$tempcreditrent = 2;
}
$creditchange = $creditchange + pow($tempcreditrent, $multiplier);
$changelog .= 'double-' . pow($tempcreditrent, $multiplier) . ';';
}
}
}
if ($timediff > $watches['longrental'] * 3600) {
$creditchange = $creditchange + $credit['longrental'];
$changelog .= 'longrent-' . $credit['longrental'] . ';';
}
$usercredit = $usercredit - $creditchange;
$result = $db->query("UPDATE credit SET credit=$usercredit WHERE userId=$userid");
$result = $db->query("INSERT INTO history SET userId=$userid,bikeNum=$bike,action='CREDITCHANGE',parameter='" . $creditchange . '|' . $changelog . "'");
$result = $db->query("INSERT INTO history SET userId=$userid,bikeNum=$bike,action='CREDIT',parameter=$usercredit");
return $creditchange;
}
}
function iscreditenabled()
{
global $credit;
if ($credit['enabled']) {
return true;
}
return false;
}
function getusercredit($userid)
{
global $db, $credit;
if (iscreditenabled() == false) {
return;
}
// if credit system disabled, exit
$result = $db->query("SELECT credit FROM credit WHERE userId=$userid");
$row = $result->fetch_assoc();
$usercredit = $row['credit'];
return $usercredit;
}
function getcreditcurrency()
{
global $credit;
if (iscreditenabled() == false) {
return;
}
// if credit system disabled, exit
return $credit['currency'];
}
function issmssystemenabled()
{
global $connectors;
if ($connectors['sms'] == '') {
return false;
}
return true;
}
function normalizephonenumber($number)
{
global $countrycode;
$number = str_replace('+', '', $number);
$number = str_replace(' ', '', $number);
$number = str_replace('-', '', $number);
$number = str_replace('/', '', $number);
$number = str_replace('.', '', $number);
if (substr($number, 0, 1) == '0') {
$number = substr($number, 1);
}
if (substr($number, 0, 3) != $countrycode) {
$number = $countrycode . $number;
}
return $number;
}