forked from cyklokoalicia/OpenSourceBikeShare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.php
618 lines (549 loc) · 17.5 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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
<?php
require("external/PHPMailer/PHPMailerAutoload.php");
require("external/htmlpurifier/HTMLPurifier.standalone.php");
$htmlpurconfig=HTMLPurifier_Config::createDefault();
$purifier=new HTMLPurifier($htmlpurconfig);
@$purifier->purify($_GET);
@$purifier->purify($_POST);
@$purifier->purify($_COOKIE);
@$purifier->purify($_FILES);
@$purifier->purify($_SERVER);
$locale=$systemlang.".utf8";
setlocale(LC_ALL, $locale);
putenv("LANG=".$locale);
bindtextdomain("messages", dirname(__FILE__).'/languages');
textdomain("messages");
if (issmssystemenabled()==TRUE)
{
require("connectors/".$connectors["sms"].".php");
}
else
{
require("connectors/disabled.php");
}
$sms=new SMSConnector();
function error($message)
{
R::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)
{
log_sendsms($number,$text);
if (DEBUG===TRUE)
{
echo $number,' -> ',$text,'<br />';
}
else
{
$sms->Send($number,$text);
}
}
}
}
else
{
log_sendsms($number,$text);
if (DEBUG===TRUE)
{
echo $number,' -> ',$text,'<br />';
}
else
{
$sms->Send($number,$text);
}
}
}
function log_sendsms($number,$text)
{
R::selectDatabase('localdb');
R::begin();
$logger=R::dispense('sent');
$logger->number=$number;
$logger->text=$text;
R::store($logger);
R::commit();
R::selectDatabase('default');
}
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)
{
$user=R::load('users',$userid);
if ($user->id)
{
return $user->privileges;
}
return FALSE;
}
function getusername($userid)
{
$user=R::load('users',$userid);
if ($user->id)
{
return $user->username;
}
return FALSE;
}
function getphonenumber($userid)
{
$user=R::load('users',$userid);
if ($user->id)
{
return $user->number;
}
return FALSE;
}
function getuserid($number)
{
$user=R::findOne('users','number=?',[$number]);
if (!empty($user))
{
return $user->id;
}
return FALSE;
}
function isloggedin()
{
global $userid, $sessionid;
if (isset($_COOKIE["loguserid"]) AND isset($_COOKIE["logsession"]))
{
$session=R::findOne('sessions','userid=:userid AND sessionid=:sessionid AND timestamp>:timestamp',[':userid'=>$userid,':sessionid'=>$sessionid,':timestamp'=>time()]);
if (!empty($session)) return 1;
else return 0;
}
return 0;
}
function checksession()
{
global $systemURL;
$sessions=R::find('sessions','timestamp<=?',[time()]);
R::trashAll($sessions);
if (isset($_COOKIE["loguserid"]) AND isset($_COOKIE["logsession"]))
{
$session=R::findOne('sessions','userid=:userid AND sessionid=:sessionid AND timestamp>:timestamp',[':userid'=>$_COOKIE["loguserid"],':sessionid'=>$_COOKIE["logsession"],':timestamp'=>time()]);
if (!empty($session))
{
$session->timestamp=time()+86400*14;
R::store($session);
R::commit();
R::begin();
}
else
{
$sessions=R::find('sessions','userid=:userid OR sessionid=:sessionid',[':userid'=>$_COOKIE["loguserid"],':sessionid'=>$_COOKIE["logsession"]]);
R::trashAll($sessions);
R::commit();
setcookie("loguserid","",time()-86400);
setcookie("logsession","",time()-86400);
header("HTTP/1.1 301 Moved permanently");
header("Location: ".$systemURL."?error=2&time=".time());
header("Connection: close");
exit;
}
}
else
{
header("HTTP/1.1 301 Moved permanently");
header("Location: ".$systemURL."?error=2&time=".time());
header("Connection: close");
exit;
}
}
function logrequest($userid)
{
R::selectDatabase('localdb');
R::begin();
$received=R::dispense('received');
$received->sender=getphonenumber($userid);
$received->receivetime=date("Y-m-d H:i:s");
$received->smstext=$_SERVER['REQUEST_URI'];
$received->ip=$_SERVER['REMOTE_ADDR'];
R::store($received);
R::commit();
R::selectDatabase('default');
}
function logresult($userid,$text)
{
R::selectDatabase('localdb');
R::begin();
$logtext="";
if (is_array($text))
{
foreach ($text as $value)
{
$logtext.=$value."; ";
}
}
else
{
$logtext=$text;
}
$logtext=strip_tags($logtext);
$sent=R::dispense('sent');
$sent->number=$userid;
$sent->text=$logtext;
R::store($sent);
R::commit();
R::selectDatabase('default');
}
function checkbikeno($bikenum)
{
$bike=R::load('bikes',$bikenum);
if (!$bike->id)
{
response('<h3>Bike '.$bikenum.' does not exist!</h3>',ERROR);
}
}
function checkstandname($standname)
{
$standname=trim(strtoupper($standname));
$stand=R::findOne('stands','standname=?',[$standname]);
if (empty($stand))
{
response('<h3>'._('Stand').' '.$standname.' '._('does not exist').'!</h3>',ERROR);
}
}
/**
* @param int $notificationtype 0 = via SMS, 1 = via email
**/
function notifyAdmins($message,$notificationtype=0)
{
global $systemname,$watches;
$admins=R::find('users','privileges=?',[1]);
if (!empty($admins))
{
foreach($admins as $admin)
{
if ($notificationtype==0)
{
sendSMS($admin->number,$message);
sendEmail($watches["email"],$systemname." "._('notification'),$message);
}
else
{
sendEmail($admin->mail,$systemname." "._('notification'),$message);
}
}
}
}
function sendConfirmationEmail($emailto)
{
global $dbpassword, $systemname, $systemrules, $systemURL;
$subject=_('Registration');
$user=R::findOne('users','mail=?',[$emailto]);
$registration=R::dispense('registration');
$registration->userid=$user->id;
$registration->userkey=hash('sha256', $emailto.$dbpassword.rand(0,1000000));
R::store($registration);
$limit=R::dispense('limits');
$limit->userid=$user->id;
$limit->userlimit=0;
R::store($limit);
$credit=R::dispense('credit');
$credit->userid=$user->id;
$credit->credit=0;
R::store($credit);
$names=preg_split("/[\s,]+/",$user->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=".$registration->userkey;
sendEmail($emailto,$subject,$message);
}
function confirmUser($userkey)
{
global $limits;
$user=R::findOne('registration','userkey=?',[$userkey]);
if (!empty($user))
{
$limit=R::findOne('limits','userid=?',[$user->id]);
$limit->userlimit=$limits["registration"];
R::store($limit);
$registration=R::findOne('registration','userid=?',[$user->id]);
R::trash($registration);
echo '<div class="alert alert-success" role="alert">',_('Your account has been activated. Welcome!'),'</div>';
}
else
{
echo '<div class="alert alert-danger" role="alert">',_('Registration key not found!'),'</div>';
return FALSE;
}
}
function checktopofstack($standid)
{
$currentbikes=array();
// find current bikes at stand
$rows=R::getAll('SELECT * FROM bikes LEFT JOIN stands ON bikes.currentstand=stands.id WHERE stands.id=?',[$standid]);
$bikes=R::convertToBeans('bikes',$rows);
if (!empty($bikes))
{
foreach ($bikes as $bike)
{
$currentbikes[]=$bike->bikenum;
}
if (count($currentbikes))
{
// find last returned bike at stand
$history=R::findOne('history','FIND_IN_SET(action,:action) AND parameter=:standid AND FIND_IN_SET(bikenum,:currentbikes) ORDER BY time DESC LIMIT 1',[':action'=>'RETURN,FORCERETURN',':standid'=>$standid,':currentbikes'=>implode($currentbikes,",")]);
if (!empty($history))
{
return $history->bikenum;
}
}
}
return FALSE;
}
function checklongrental()
{
global $watches,$notifyuser;
$abusers=""; $found=0;
$rows=R::getAll('SELECT * FROM bikes LEFT JOIN users ON bikes.currentuser=users.id WHERE currentstand IS NULL');
$bikes=R::convertToBeans('bikes',$rows);
if (!empty($bikes))
{
foreach ($bikes as $bike)
{
$history=R::find('history','bikenum=:bikenum AND userid=$userid AND action=:action ORDER BY time DESC LIMIT 1',[':bikenum'=>$bike->bikenum,':userid'=>$bike->currentuser,':action'=>'RENT']);
if (!empty($history))
{
foreach($history as $historyitem)
{
$time=strtotime($historyitem->time);
if ($time+($watches["longrental"]*3600)<=time())
{
$abusers.=" b".$bike->bikenum." "._('by')." ".$bike->username.",";
$found=1;
if ($notifyuser) sendSMS($bike->number,_('Please, return your bike ').$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 $watches;
$abusers=""; $found=0;
if ($cron) // called from cron
{
$rows=R::getAll('SELECT * FROM users LEFT JOIN limits ON users.id=limits.userid');
$users=R::convertToBeans('users',$rows);
if (!empty($users))
{
foreach($users as $user)
{
$numberofrentals=R::count('history','userid=:userid AND action=:action AND time>:time',[':userid'=>$user->id,':action'=>'RENT','time'=>date("Y-m-d H:i:s",time()-$watches["timetoomany"]*3600)]);
if ($numberofrentals>=($userlimit+$watches["numbertoomany"]))
{
$abusers.=" ".$numberofrentals." ("._('limit')." ".$user->userlimit.") "._('by')." ".$user->username.",";
$found=1;
}
}
}
}
else // called from function for user userid
{
$rows=R::getAll('SELECT * FROM users LEFT JOIN limits ON users.id=limits.userid WHERE users.id=?',[$userid]);
$users=R::convertToBeans('users',$rows);
if (!empty($users))
{
foreach($users as $user)
{
$numberofrentals=R::count('history','userid=:userid AND action=:action AND time>:time',[':userid'=>$user->id,':action'=>'RENT','time'=>date("Y-m-d H:i:s",time()-$watches["timetoomany"]*3600)]);
if ($result->num_rows>=($userlimit+$watches["numbertoomany"]))
{
$abusers.=" ".$numberofrentals." ("._('limit')." ".$user->userlimit.") "._('by')." ".$user->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 getrequiredcredit()
{
global $credit;
if (iscreditenabled()==FALSE) return; // if credit system disabled, exit
$requiredcredit=$credit["min"]+$credit["rent"]+$credit["longrental"];
return $requiredcredit;
}
// check if user has credit >= minimum credit+rent fee+long rental fee
function checkrequiredcredit($userid)
{
global $credit;
if (iscreditenabled()==FALSE) return; // if credit system disabled, exit
$requiredcredit=getrequiredcredit();
$credit=R::findOne('credit','userid=:userid AND credit>=:requiredcredit',[':userid'=>$userid,':requiredcredit'=>$requiredcredit]);
if (!empty($credit))
{
return TRUE;
}
return FALSE;
}
// subtract credit for rental
function changecreditendrental($bikenum,$userid)
{
global $watches,$credit;
if (iscreditenabled()==FALSE) return; // if credit system disabled, exit
$usercredit=getusercredit($userid);
$history=R::find('history','bikenum=:bikenum AND userid=:userid AND FIND_IN_SET(action,:action) ORDER BY time DESC LIMIT 1',[':bikenum'=>$bikenum,':userid'=>$userid,':action:'=>'RENT,FORCERENT']);
if (!empty($history))
{
$starttime=strtotime($history->time);
$endtime=time();
$timediff=$endtime-$starttime;
$creditchange=0;
$changelog="";
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;
$credit=R::findOne('credit','userid=?',[$userid]);
$credit->credit=$usercredit;
R::store($credit);
$history=R::dispense('history');
$history->userid=$userid;
$history->bikenum=$bikenum;
$history->action='CREDITCHANGE';
$history->paremeter=$creditchange.'|'.$changelog;
R::store($history);
$history=R::dispense('history');
$history->userid=$userid;
$history->bikenum=$bikenum;
$history->action='CREDIT';
$history->paremeter=$usercredit;
R::store($history);
return $creditchange;
}
}
function iscreditenabled()
{
global $credit;
if ($credit["enabled"]) return TRUE;
return FALSE;
}
function getusercredit($userid)
{
if (iscreditenabled()==FALSE) return; // if credit system disabled, exit
$credit=R::findOne('credit','userid=?',[$userid]);
return $credit->credit;
}
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;
}
?>