Repository navigation
Expand file tree
/
Copy pathfunctions.php
More file actions
597 lines (486 loc) · 14.4 KB
/
Copy pathfunctions.php
File metadata and controls
597 lines (486 loc) · 14.4 KB
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
// Home URL
function home()
{
require('config.php');
return (empty($config['APP_SLUG'])) ? $config['APP_URL'] : $config['APP_URL'] . $config['APP_SLUG'] . "/";
}
// Get URl
function url()
{
require('config.php');
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
// Append the host(domain name, ip) to the URL.
$url .= $_SERVER['HTTP_HOST'];
// Append the requested resource location to the URL
$url .= $_SERVER['REQUEST_URI'];
$url = (empty($config['APP_SLUG'])) ? substr(explode("?", $_SERVER['REQUEST_URI'])[0], 1) : substr(explode("?", $_SERVER['REQUEST_URI'])[0], strlen($config['APP_SLUG']) + 2);
$url = (empty($url)) ? home() : home() . $url;
return $url;
}
function errors($enable = true)
{
if ($enable) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
} else {
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);
}
return $enable;
}
function unauthorized()
{
header("HTTP/1.0 401 Unauthorized");
http_response_code(401);
include('views/errors/401.php');
exit;
}
function pageNotFound()
{
http_response_code(404);
header("HTTP/1.0 404 Page Not Found");
include('views/errors/404.php');
exit;
}
// Lock a file
function locked($role = ['user'])
{
controller("Auth");
$auth = new Auth();
if (empty(App::getSession())) {
redirectIfLocked();
exit;
} elseif (!in_array(App::getUser()['role'], $role)) {
return unauthorized();
}
}
function redirectIfLocked()
{
if (url() != route("login"))
return header("Location:" . route("login") . "?back=" . url() . str_replace('&', '$', queryString()));
}
// Redirect to a specific route with optional delay
function redirect($route, $delay = 0){
$regex = "/^(https?|ftp):\/\/[a-z0-9+!*(),;?&=\$_.-]+(\.[a-z0-9+!*(),;?&=\$_.-]+)*(:[0-9]{2,5})?(\/([a-z0-9+_\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?$/i";
?>
<script>
setTimeout(function() {
window.location.href = "<?php if(preg_match($regex, $route)) echo $route; else echo route($route);?>";
}, <?php echo $delay; ?>);
</script>
<?php
}
function assets($path)
{
echo home() . "assets/" . $path;
}
function component($component, $variables = []){
foreach($variables as $variable => $value){
global $$variable;
$$variable = $value;
}
return require('components/' . $component . '.php');
}
function partial($partial, $variables = []){
foreach($variables as $variable => $value){
global $$variable;
$$variable = $value;
}
return require('views/partials/' . $partial . '.php');
}
// Get url for a route
function route($path)
{
return home() . $path;
}
// Get Query String
function queryString()
{
return "?" . $_SERVER['QUERY_STRING'];
}
// Get Complete URl
function getRoute()
{
return url() . "?" . $_SERVER['QUERY_STRING'];
}
// Add Controller
function controller($className)
{
return require('controllers/' . $className . 'Controller.php');
}
// Add API Controller
function APIController($className)
{
return require('controllers/api/' . $className . 'Controller.php');
}
// Add Test
function test($className)
{
return require('tests/' . $className . 'Test.php');
}
/**
* CSRF functions
* */
function csrf()
{
if ($_SERVER['REQUEST_METHOD'] == "GET") {
// Generate CSRF token
$token = bin2hex(random_bytes(32));
// Save the token in the session
$_SESSION['_token'] = $token;
}
// Return the HTML for the CSRF field
echo '<input type="hidden" name="_token" value="' . $_SESSION['_token'] . '"> ';
}
function csrfCheck()
{
// Check if the provided token matches the stored token
if (!empty($_SESSION['_token']) && hash_equals($_SESSION['_token'], $_POST['_token'])) {
// CSRF token is valid
unset($_SESSION['_token']);
return true;
} else {
unauthorized();
exit;
}
}
/**
* visitor analytical functions
* */
function getBrowser()
{
$userAgent = isset($_SERVER['HTTP_SEC_CH_UA']) ? $_SERVER['HTTP_SEC_CH_UA'] : '';
$browserInfo = [];
$browsers = explode(",", $userAgent);
foreach ($browsers as $browser) {
if (!preg_match('/Chromium|Not-A\.Brand/', $browser)) {
$browser = explode(';', $browser);
$browserInfo['name'] = str_replace('"', "", $browser[0]);
$browserInfo['version'] = str_replace('"', "", substr($browser[1], 2));
}
}
return $browserInfo;
}
function getOS()
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$os_platform = "Unknown OS Platform";
$os_array = array(
'/windows nt 11/i' => 'Windows 11',
'/windows nt 10/i' => 'Windows 10',
'/windows nt 6.3/i' => 'Windows 8.1',
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
foreach ($os_array as $regex => $value) {
if (preg_match($regex, $user_agent)) {
$os_platform = $value;
break; // Added break to exit the loop once a match is found
}
}
return $os_platform;
}
function getIP()
{
if (isset($_SERVER["HTTP_CLIENT_IP"])) {
$ip = $_SERVER["HTTP_CLIENT_IP"];
} elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} elseif (isset($_SERVER["HTTP_X_FORWARDED"])) {
$ip = $_SERVER["HTTP_X_FORWARDED"];
} elseif (isset($_SERVER["HTTP_FORWARDED_FOR"])) {
$ip = $_SERVER["HTTP_FORWARDED_FOR"];
} elseif (isset($_SERVER["HTTP_FORWARDED"])) {
$ip = $_SERVER["HTTP_FORWARDED"];
} else {
$ip = $_SERVER["REMOTE_ADDR"];
}
// Strip any secondary IP etc from the IP address
if (strpos($ip, ',') > 0) {
$ip = substr($ip, 0, strpos($ip, ','));
}
return $ip;
}
function getDevice()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version = "";
//First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
} elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
} elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
return array(
'userAgent' => $u_agent,
'browserInfo' => $_SERVER['HTTP_SEC_CH_UA'],
'browser' => getBrowser()['name'],
'os' => getOS(),
'version' => getBrowser()['version'],
'platform' => $platform,
'ip' => getIP()
);
}
function insertVisitorLog()
{
DB::connect();
$visitorInfo = getDevice();
$url = $_SERVER['REQUEST_URI'];
$previousVisitTime = time() - 60;
$result = DB::select('visitors', "COUNT(*) as count", "ip = '{$visitorInfo['ip']}' AND url = '$url' AND visitedAt > FROM_UNIXTIME($previousVisitTime)")->fetchAll();
if ($result[0]['count'] == 0) {
$ip = getIP();
$os = $visitorInfo['os'];
$browser = $visitorInfo['browser'];
$visitedAt = date('Y-m-d H:i:s');
$visitorId = md5($ip.$os.$browser.$visitedAt);
$data = [
'visitorId' => $visitorId,
'ip' => $ip,
'os' => $os,
'browser' => $browser,
'visitedAt' => $visitedAt,
'url' => $url
];
DB::insert('visitors', $data);
}
DB::close();
}
/**
* api functions
* */
function sendRequest($url, $token = "", $method, $fields = "")
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer ' . $token,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($fields) // Encode the fields as JSON
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
function getAuthorizationHeader()
{
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
} else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* get access token from header
* */
function getBearerToken()
{
$headers = getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
return null;
}
function getAPIToken()
{
$headers = null;
if (isset($_SERVER['token'])) {
$headers = trim($_SERVER["token"]);
} elseif (isset($_SERVER['HTTP_TOKEN'])) {
$headers = trim($_SERVER["HTTP_TOKEN"]);
} elseif (isset($_SERVER['HTTP_ACCEPT'])) {
$headers = trim($_SERVER["HTTP_ACCEPT"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['token'])) {
$headers = trim($requestHeaders['token']);
}
}
return $headers;
}
function jsonResponse($message = null, $code = 200)
{
header_remove();
http_response_code($code);
header("Access-Control-Allow-Origin: *");
header('Cache-Control: no-cache, must-revalidate');
header('Content-Type: application/json');
header('Access-Control-Allow-Credentials: true');
$status = array(
200 => '200 OK',
400 => '400 Bad Request',
422 => 'Unprocessable Entity',
500 => '500 Internal Server Error'
);
header('Status: ' . $status[$code]);
$responseArray = array(
'status' => $code < 300
);
echo json_encode($message);
}
/**
* encryption functions
* */
function sha256($string)
{
return hash('sha256', $string);
}
function sha512($string)
{
return hash('sha512', $string);
}
function integerToRoman($integer)
{
$integer = intval($integer);
$result = '';
$lookup = array(
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1
);
foreach ($lookup as $roman => $value) {
$matches = intval($integer / $value);
$result .= str_repeat($roman, $matches);
$integer = $integer % $value;
}
return $result;
}
function relativeTime($timestamp)
{
$time = strtotime($timestamp);
$difference = time() - $time;
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60", "60", "24", "7", "4.35", "12", "10");
for ($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if ($difference != 1)
$periods[$j] .= "s";
return $text = "$difference $periods[$j] ago";
}
function slugify($text, string $divider = '-')
{
$text = preg_replace('~[^\pL\d]+~u', $divider, $text);
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
$text = preg_replace('~[^-\w]+~', '', $text);
$text = trim($text, $divider);
$text = preg_replace('~-+~', $divider, $text);
$text = strtolower($text);
if (empty($text)) {
return 'n-a';
}
return $text;
}
// Convert currency value to INR
function strtoinr($price)
{ // return $price; // Uncomment this line if NumberFormatter isn't installed on your server
$locale = 'hi';
$currency = 'INR';
$inr = new NumberFormatter($locale, NumberFormatter::CURRENCY);
$price = (int) $price;
$formattedPrice = $inr->formatCurrency($price, $currency);
return substr($formattedPrice, 0, strlen($formattedPrice) - 3);
}
function enumToArray($enumDefinition)
{
// Remove the leading "enum(" and trailing ")"
$enumValuesString = substr($enumDefinition, 5, -1);
// Remove single quotes
$enumValuesString = str_replace("'", "", $enumValuesString);
// Split the string into an array using ","
$enumValuesArray = explode(",", $enumValuesString);
return $enumValuesArray;
}
function addDaysToDate($date, $days)
{
$dateObject = new DateTime($date);
$dateInterval = new DateInterval('P' . $days . 'D'); // 'P' stands for Period and 'D' stands for Days
$dateObject->add($dateInterval);
return $dateObject->format('Y-m-d');
}
function formatDuration($days) {
if ($days >= 365) {
$years = floor($days / 365);
$months = floor(($days % 365) / 30);
$additionalDays = ($days % 365) % 30;
$duration = $years . ' ' . ($years > 1 ? 'years' : 'year');
if ($months > 0) {
$duration .= ', ' . $months . ' ' . ($months > 1 ? 'months' : 'month');
}
if ($additionalDays > 0) {
$duration .= ($months > 0 ? ' & ' : ', ') . $additionalDays . ' ' . ($additionalDays > 1 ? 'days' : 'day');
}
return $duration;
} elseif ($days >= 30) {
$months = floor($days / 30);
$additionalDays = $days % 30;
$duration = $months . ' ' . ($months > 1 ? 'months' : 'month');
if ($additionalDays > 0) {
$duration .= ' & ' . $additionalDays . ' ' . ($additionalDays > 1 ? 'days' : 'day');
}
return $duration;
} else {
return $days . ' ' . ($days > 1 ? 'days' : 'day');
}
}