-
Notifications
You must be signed in to change notification settings - Fork 71
/
common.php
338 lines (291 loc) · 11.9 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
<?php
require_once 'vendor/autoload.php';
use BikeShare\App\Configuration;
use BikeShare\App\Kernel;
use BikeShare\Authentication\Auth;
use BikeShare\Credit\CodeGenerator\CodeGeneratorInterface;
use BikeShare\Credit\CreditSystemInterface;
use BikeShare\Db\DbInterface;
use BikeShare\Db\MysqliDb;
use BikeShare\Mail\MailSenderInterface;
use BikeShare\Purifier\PhonePurifierInterface;
use BikeShare\Rent\RentSystemFactory;
use BikeShare\Sms\SmsSenderInterface;
use BikeShare\SmsConnector\SmsConnectorInterface;
use BikeShare\User\User;
use Symfony\Component\Dotenv\Dotenv;
/**
* should be removed
*/
global $configuration,
$sms,
$db,
$db,
$mailer,
$smsSender,
$codeGenerator,
$phonePurifier,
$creditSystem,
$user,
$auth,
$rentSystemFactory,
$translator,
$logger;
if (empty($kernel)) {
$dotenv = new Dotenv();
$dotenv->setProdEnvs(['prod']);
$dotenv->bootEnv(__DIR__.'/.env', 'dev', ['test'], true);
$kernel = new Kernel($_ENV['APP_ENV'], (bool) $_ENV['APP_DEBUG']);
$kernel->boot();
$container = $kernel->getContainer();
$logger = $kernel->getContainer()->get('logger');
Monolog\ErrorHandler::register($logger);
#Should be removed in the future. Currently, we are using it to log errors in old code
set_error_handler(
function ($severity, $message, $file, $line) use ($logger) {
$logger->error($message, ['severity' => $severity, 'file' => $file, 'line' => $line]);
return true;
}
);
}
$logger = $kernel->getContainer()->get('logger');
$configuration = $kernel->getContainer()->get(Configuration::class);
$sms = $kernel->getContainer()->get(SmsConnectorInterface::class);
$db = $kernel->getContainer()->get(DbInterface::class);
$db = $kernel->getContainer()->get(DbInterface::class);
$mailer = $kernel->getContainer()->get(MailSenderInterface::class);
$smsSender = $kernel->getContainer()->get(SmsSenderInterface::class);
$codeGenerator = $kernel->getContainer()->get(CodeGeneratorInterface::class);
$phonePurifier = $kernel->getContainer()->get(PhonePurifierInterface::class);
$creditSystem = $kernel->getContainer()->get(CreditSystemInterface::class);
$user = $kernel->getContainer()->get(User::class);
$auth = $kernel->getContainer()->get(Auth::class);
$rentSystemFactory = $kernel->getContainer()->get(RentSystemFactory::class);
$translator = $kernel->getContainer()->get('translator');
$locale = $configuration->get('systemlang') . ".utf8";
setlocale(LC_ALL, $locale);
putenv("LANG=" . $locale);
bindtextdomain("messages", dirname(__FILE__) . '/languages');
textdomain("messages");
function t(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string
{
global $translator;
return $translator->trans($id, $parameters, $domain, $locale);
}
function error($message)
{
global $db;
$db->rollback();
exit($message);
}
function logrequest($userid)
{
global $configuration, $user, $logger;
/**
* @var DbInterface
*/
$localdb = new MysqliDb(
$configuration->get('dbserver'),
$configuration->get('dbuser'),
$configuration->get('dbpassword'),
$configuration->get('dbname'),
$logger
);
#TODO does it needed???
$localdb->setAutocommit(true);
$number = $user->findPhoneNumber($userid);
$localdb->query("INSERT INTO received SET sms_uuid='', 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 $configuration, $logger;
/**
* @var DbInterface
*/
$localdb = new MysqliDb(
$configuration->get('dbserver'),
$configuration->get('dbuser'),
$configuration->get('dbpassword'),
$configuration->get('dbname'),
$logger
);
#TODO does it needed???
$localdb->setAutocommit(true);
$userid = $localdb->escape($userid);
$logtext="";
if (is_array($text))
{
foreach ($text as $value)
{
$logtext.=$value."; ";
}
}
else
{
$logtext=$text;
}
$logtext = substr(strip_tags($localdb->escape($logtext)), 0, 200);
$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, $configuration, $mailer, $smsSender;
$result = $db->query('SELECT number,mail FROM users where privileges & 2 != 0');
while ($row = $result->fetch_assoc()) {
if ($notificationtype == 0) {
$smsSender->send($row['number'], $message);
$mailer->sendMail($configuration->get('watches')['email'], $configuration->get('systemname') . ' ' . _('notification'), $message);
} else {
$mailer->sendMail($row['mail'], $configuration->get('systemname') . ' ' . _('notification'), $message);
}
}
}
function sendConfirmationEmail($emailto)
{
global $db, $configuration, $mailer;
$subject = _('Registration');
$result = $db->query("SELECT userName,userId FROM users WHERE mail='" . $emailto . "'");
$row = $result->fetch_assoc();
$userId = $row['userId'];
$userKey = hash('sha256', $emailto . $configuration->get('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') . ' ' . $configuration->get('systemname') . ".\n\n" .
_('System rules are available here:') . "\n" . $configuration->get('systemrules') . "\n\n" .
_('By clicking the following link you agree to the System rules:') . "\n" . $configuration->get('systemURL') . 'agree.php?key=' . $userKey;
$mailer->sendMail($emailto, $subject, $message);
}
function confirmUser($userKey)
{
global $db, $configuration;
$userKey = $db->escape($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='" . $configuration->get('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, $smsSender, $configuration;
$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 + ($configuration->get('watches')['longrental'] * 3600) <= time()) {
$abusers .= ' b' . $bikenum . ' ' . _('by') . ' ' . $username . ',';
$found = 1;
if ($configuration->get('notifyuser')) {
$smsSender->send($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($configuration->get('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, $configuration;
$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() - $configuration->get('watches')['timetoomany'] * 3600);
$result2 = $db->query("SELECT bikeNum FROM history WHERE userId=$userid AND action='RENT' AND time>'$currenttime'");
if ($result2->num_rows >= ($userlimit + $configuration->get('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() - $configuration->get('watches')['timetoomany'] * 3600);
$result = $db->query("SELECT bikeNum FROM history WHERE userId=$userid AND action='RENT' AND time>'$currenttime'");
if ($result->num_rows >= ($userlimit + $configuration->get('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') . ' ' . $configuration->get('watches')['timetoomany'] . ' ' . _('hs') . ':' . $abusers);
}
}
function issmssystemenabled()
{
global $configuration;
if ($configuration->get('connectors')['sms'] == '') {
return false;
}
return true;
}