-
-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathorganizr.class.php
7865 lines (7570 loc) · 253 KB
/
organizr.class.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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
use Dibi\Connection;
class Organizr
{
// Use Custom Functions From Traits;
use TwoFAFunctions;
use ApiFunctions;
use AuthFunctions;
use BackupFunctions;
use ConfigFunctions;
use DemoFunctions;
use HomepageConnectFunctions;
use HomepageFunctions;
use LogFunctions;
use NetDataFunctions;
use NormalFunctions;
use OAuthFunctions;
use OptionsFunction;
use OrganizrFunctions;
use PluginFunctions;
use StaticFunctions;
use SSOFunctions;
use TokenFunctions;
use UpdateFunctions;
use UpgradeFunctions;
// Use homepage item functions
use BookmarksHomepageItem;
use CalendarHomepageItem;
use CouchPotatoHomepageItem;
use DelugeHomepageItem;
use DonateHomepageItem;
use EmbyHomepageItem;
use HealthChecksHomepageItem;
use HTMLHomepageItem;
use ICalHomepageItem;
use JackettHomepageItem;
use ProwlarrHomepageItem;
use JDownloaderHomepageItem;
use JellyfinHomepageItem;
use LidarrHomepageItem;
use MiscHomepageItem;
use MonitorrHomepageItem;
use NetDataHomepageItem;
use NZBGetHomepageItem;
use OctoPrintHomepageItem;
use OmbiHomepageItem;
use OverseerrHomepageItem;
use PiHoleHomepageItem;
use AdGuardHomepageItem;
use PlexHomepageItem;
use QBitTorrentHomepageItem;
use RadarrHomepageItem;
use RTorrentHomepageItem;
use SabNZBdHomepageItem;
use SickRageHomepageItem;
use SonarrHomepageItem;
use SpeedTestHomepageItem;
use TautulliHomepageItem;
use TraktHomepageItem;
use TransmissionHomepageItem;
use UnifiHomepageItem;
use WeatherHomepageItem;
use uTorrentHomepageItem;
// ===================================
// Organizr Version
public $version = '2.1.2400';
// ===================================
// Quick php Version check
public $minimumPHP = '7.4';
// ===================================
protected $db;
protected $otherDb;
public $config;
public $user;
public $userConfigPath;
public $defaultConfigPath;
public $currentTime;
public $docker;
public $dev;
public $demo;
public $commit;
public $fileHash;
public $cookieName;
public $logFile;
public $timeExecution;
public $root;
public $paths;
public $checkForUpdates;
public $groupOptions;
public $warnings;
public $errors;
public bool $loggerSetup = false;
public \Nekonomokochan\PhpJsonLogger\Logger $logger;
public function __construct($checkForUpdates = false)
{
// Constructed from Updater?
$this->checkForUpdates = $checkForUpdates;
// Set Project Root directory and paths
$this->root = dirname(__DIR__, 2);
$this->paths = [
'Root Folder' => $this->root . DIRECTORY_SEPARATOR,
'Cache Folder' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR,
'Tab Folder' => $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR,
'API Folder' => dirname(__DIR__, 1) . DIRECTORY_SEPARATOR
];
// Temp Set Errors
$this->errors = E_ERROR;//E_ALL & ~E_NOTICE
// Set current time
$this->currentTime = gmdate('Y-m-d\TH:i:s\Z');
// Set variable if install is for official docker
$this->docker = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Docker.txt'));
// Set variable if install is for develop and set php Error levels
$this->dev = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Dev.txt'));
// Set variable if install is for demo
$this->demo = (file_exists(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Demo.txt'));
// Set variable if install has commit hash and variable to be used as hash for files
$this->commit = ($this->docker && !$this->dev) ? file_get_contents(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'Github.txt') : null;
$this->fileHash = ($this->commit) ?? $this->version;
$this->fileHash = trim($this->fileHash);
// Set location path to user config path
$this->chooseConfigFile();
// Set location path to default config path
$this->defaultConfigPath = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'default.php';
// Load Config file
$this->config = $this->config();
// Set cookie name for Organizr Instance
$this->cookieName = ($this->hasConfig()) ? $this->config['uuid'] !== '' ? 'organizr_token_' . $this->config['uuid'] : 'organizr_token_temp' : 'organizr_token_temp';
// Set custom Error handler
set_error_handler([$this, 'setAPIErrorResponse'], $this->errors);
// Next Check PHP Version
$this->checkPHP();
// Check Disk Space
$this->checkDiskSpace();
// Set UUID for device
$this->setDeviceUUID();
// Add Plugin prefix to plugin global
$this->setPluginListNameFromConfigPrefix();
// Add database path to paths
$this->addDatabaseToPaths();
// Set Start Execution Time
$this->timeExecution = $this->timeExecution();
$this->phpErrors();
// Set organizr Logs and logger
$this->logFile = $this->setOrganizrLog();
$this->setLoggerChannel();
// Connect to DB
$this->connectDB();
// Check DB Writable
$this->checkWritableDB();
// Get token form cookie and validate
$this->setCurrentUser();
// might just run this at index
$this->upgradeCheck();
// Is Page load Organizr OAuth?
$this->checkForOrganizrOAuth();
// Is user Blacklisted?
$this->checkIfUserIsBlacklisted();
}
public function __destruct()
{
$this->disconnectDB();
}
public function addDatabaseToPaths()
{
if ($this->hasConfig()) {
$this->paths = array_merge($this->paths, ['DB Folder' => $this->config['dbLocation']]);
}
}
public function chooseConfigFile()
{
$oldUserConfigPath = dirname(__DIR__, 1) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
$userConfigPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
if (file_exists($userConfigPath) && file_exists($oldUserConfigPath)) {
$this->userConfigPath = $userConfigPath;
} elseif (file_exists($oldUserConfigPath)) {
$this->makeDir(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR);
if ($this->rcopy($oldUserConfigPath, $userConfigPath)) {
$this->userConfigPath = $userConfigPath;
@unlink($oldUserConfigPath);
} else {
$this->userConfigPath = $oldUserConfigPath;
}
} else {
$this->userConfigPath = $userConfigPath;
}
}
public function hasConfig()
{
return (file_exists($this->userConfigPath)) ?? false;
}
public function hasDatabase($file = null)
{
$databaseType = $this->config['driver'];
if (!$this->hasConfig()) {
return false;
}
switch (strtolower($databaseType)) {
case 'sqlite3':
$file = $file ? $this->config['dbLocation'] . $file : $this->config['dbLocation'] . $this->config['dbName'];
return [
'driver' => 'sqlite3',
'database' => $file
];
case 'mysql':
case 'mysqli':
$db = $file ? 'tempMigration' : $this->config['dbName'];
return [
'driver' => 'mysqli',
'host' => $this->config['dbHost'],
'username' => $this->config['dbUsername'],
'password' => $this->decrypt($this->config['dbPassword']),
'database' => $db,
'options' => [
MYSQLI_OPT_CONNECT_TIMEOUT => 60,
],
'flags' => MYSQLI_CLIENT_COMPRESS,
];
case 'postgre':
$config = [
'driver' => 'postgre',
'username' => $this->config['dbUsername'],
'password' => $this->decrypt($this->config['dbPassword']),
'persistent' => true,
];
$host = $this->qualifyURL($this->config['dbHost'], true);
if ($host['port']) {
$config = array_merge($config, ['port' => ltrim($host['port'], ':')]);
}
if ($host['host']) {
$config = array_merge($config, ['host' => $host['host']]);
}
if (!$host['host'] && $host['path']) {
$config = array_merge($config, ['host' => $host['path']]);
}
return $config;
default:
return false;
}
}
protected function connectDB()
{
$databaseConnection = $this->hasDatabase();
//$this->prettyPrint($databaseConnection);
if ($databaseConnection) {
try {
$this->db = new Connection($databaseConnection);
} catch (Dibi\Exception $e) {
$this->db = null;
}
} else {
$this->db = null;
}
}
public function disconnectDB()
{
if ($this->db) {
$this->db->disconnect();
$this->db = null;
unset($this->db);
}
}
public function connectOtherDB($file = null)
{
$databaseConnection = $this->hasDatabase('tempMigration.db');
if ($databaseConnection) {
try {
$this->otherDb = new Connection($databaseConnection);
} catch (Dibi\Exception $e) {
$this->prettyPrint($e->getMessage());
$this->otherDb = null;
}
} else {
$this->otherDb = null;
}
}
public function setDeviceUUID()
{
if (!isset($_COOKIE['organizr_user_uuid'])) {
$this->coookie('set', 'organizr_user_uuid', $this->gen_uuid(), 7);
}
}
public function refreshDeviceUUID()
{
if (isset($_COOKIE['organizr_user_uuid'])) {
$this->coookie('delete', 'organizr_user_uuid');
}
$this->coookie('set', 'organizr_user_uuid', $this->gen_uuid(), 7);
}
public function setCurrentUser($validate = true)
{
$user = false;
if ($this->hasDatabase()) {
if ($this->hasCookie()) {
$user = $this->getUserFromToken($_COOKIE[$this->cookieName]);
}
}
$this->user = ($user) ?: $this->guestUser();
$this->setLoggerChannel(null, $this->user['username']);
if ($validate) {
$this->checkUserTokenForValidation();
}
}
public function checkUserTokenForValidation()
{
if ($this->hasDB()) {
if ($this->hasCookie()) {
$this->validateToken($_COOKIE[$this->cookieName]);
}
}
}
public function phpErrors()
{
$errorTypes = $this->dev ? E_ERROR | E_WARNING | E_PARSE | E_NOTICE : 0;
// Temp overwrite for now
$displayErrors = $this->dev ? 1 : 0;
error_reporting($this->errors);
ini_set('display_errors', $displayErrors);
}
public function checkForOrganizrOAuth()
{
// Oauth?
if ($this->hasDB() && $this->user) {
if ($this->user['groupID'] == '999') {
$this->setLoggerChannel('OAuth')->debug('Starting OAuth login check');
$data = [
'enabled' => $this->config['authProxyEnabled'],
'header_name' => $this->config['authProxyHeaderName'],
'header_name_email' => $this->config['authProxyHeaderNameEmail'],
'whitelist' => $this->config['authProxyWhitelist'],
];
if ($this->config['authProxyEnabled'] && ($this->config['authProxyHeaderName'] !== '' || $this->config['authProxyHeaderNameEmail'] !== '') && $this->config['authProxyWhitelist'] !== '') {
if (isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderName'])]) || isset($this->getallheadersi()[strtolower($this->config['authProxyHeaderNameEmail'])])) {
$this->coookieSeconds('set', 'organizrOAuth', 'true', 20000, false);
$this->setLoggerChannel('OAuth')->info('OAuth pre-check passed - adding organizrOAuth cookie', $data);
} else {
$data = array_merge($data, ['headers' => $this->getallheadersi()]);
$this->setLoggerChannel('OAuth')->debug('Headers not set', $data);
}
} else {
$this->setLoggerChannel('OAuth')->debug('OAuth not triggered', $data);
}
}
}
}
public function checkIfUserIsBlacklisted()
{
if ($this->hasConfig()) {
$currentIP = $this->userIP();
if ($this->config['blacklisted'] !== '') {
if (in_array($currentIP, $this->arrayIP($this->config['blacklisted']))) {
$this->setLoggerChannel('Authentication');
$this->logger->debug('User was sent to black hole', ['blacklist' => $this->config['blacklisted']]);
die($this->showHTML('Blacklisted', $this->config['blacklistedMessage']));
}
}
}
}
public function checkDiskSpace($directory = './')
{
$readable = @is_readable($directory);
if ($readable) {
$disk = $this->checkDisk($directory);
$diskLevels = [
'warn' => 1000000000,
'warn_human_readable' => $this->human_filesize(1000000000, 0),
'error' => 100000000,
'error_human_readable' => $this->human_filesize(100000000, 0),
];
if ($disk['free']['raw'] <= $diskLevels['error']) {
die($this->showHTML('Low Disk Space', 'You are dangerously low on disk space.<br/>There is only ' . $disk['free']['human_readable'] . ' remaining.<br/><b>Percent Used = ' . $disk['used']['percent_used'] . '%</b>'));
} elseif ($disk['free']['raw'] <= $diskLevels['warn']) {
$this->warnings[] = 'You are low on disk space. There is only ' . $disk['free']['human_readable'] . ' remaining. This warning shows up because you are past the warning threshold of ' . $diskLevels['warn_human_readable'];
}
}
return true;
}
public function getFreeSpace($directory = './')
{
$disk = disk_free_space($directory);
return [
'raw' => $disk,
'human_readable' => $this->human_filesize($disk, 0)
];
}
public function getDiskSpace($directory = './')
{
$disk = disk_total_space($directory);
return [
'raw' => $disk,
'human_readable' => $this->human_filesize($disk, 0)
];
}
public function getUsedSpace($directory = './')
{
$diskFree = $this->getFreeSpace($directory);
$diskTotal = $this->getDiskSpace($directory);
$diskUsed = $diskTotal['raw'] - $diskFree['raw'];
$percentUsed = ($diskUsed / $diskTotal['raw']) * 100;
$percentFree = 100 - $percentUsed;
return [
'raw' => $diskUsed,
'human_readable' => $this->human_filesize($diskUsed, 0),
'percent_used' => round($percentUsed),
'percent_free' => round($percentFree)
];
}
public function checkDisk($directory = './')
{
$readable = @is_readable($directory);
if ($readable) {
return [
'free' => $this->getFreeSpace($directory),
'used' => $this->getUsedSpace($directory),
'total' => $this->getDiskSpace($directory),
];
} else {
return [
'free' => 'error accessing path',
'used' => 'error accessing path',
'total' => 'error accessing path',
];
}
}
public function errorCodes($error = 000)
{
$errorCodes = [
400 => [
'type' => 'Bad Request',
'description' => 'The request was incorrect'
],
401 => [
'type' => 'Unauthorized ',
'description' => 'You are not authorized to view this page'
],
402 => [
'type' => 'Payment Required',
'description' => 'Payment required before you can view this page'
],
403 => [
'type' => 'Forbidden',
'description' => 'You are forbidden to view this page'
],
404 => [
'type' => 'Not Found',
'description' => 'The requested resource was not found'
],
405 => [
'type' => 'Method Not Allowed',
'description' => 'The requested method is not allowed'
],
406 => [
'type' => 'Not Acceptable',
'description' => 'There was an issue with the requests Headers'
],
407 => [
'type' => 'Proxy Authentication Required',
'description' => 'Authentication is required and was not passed'
],
408 => [
'type' => 'Request Time-out',
'description' => 'The request has timed out'
],
409 => [
'type' => 'Conflict',
'description' => 'An error has occurred'
],
410 => [
'type' => 'Gone',
'description' => 'The requested resource is no longer available and has been permanently removed'
],
411 => [
'type' => 'Length Required',
'description' => 'The request can not be processed without a "Content-Length" header field'
],
412 => [
'type' => 'Precondition Failed',
'description' => ' A header needed was not found'
],
413 => [
'type' => 'Request Entity Too Large',
'description' => 'The query was too large to be processed by the server'
],
414 => [
'type' => 'Request-URI Too Long',
'description' => 'The URI of the request was too long'
],
415 => [
'type' => 'Unsupported Media Type',
'description' => 'The contents of the request has been submitted with invalid or out of defined media type'
],
416 => [
'type' => 'Requested range not satisfiable',
'description' => 'The requested resource was part of an invalid or is not on the server'
],
417 => [
'type' => 'Expectation Failed',
'description' => 'Expected Header was not found'
],
444 => [
'type' => 'No Response',
'description' => 'Nothing was returned from server'
],
500 => [
'type' => 'Internal Server Error',
'description' => 'An unexpected server error'
],
501 => [
'type' => 'Not Implemented',
'description' => 'The functionality to process the request is not available from this server'
],
502 => [
'type' => 'Bad Gateway',
'description' => 'The server could not fulfill its function as a gateway or proxy'
],
503 => [
'type' => 'Service Unavailable',
'description' => 'The server is temporarily unavailable, due to overloading or maintenance'
],
504 => [
'type' => 'Gateway Time-out',
'description' => 'The server could not fulfill its function as a gateway or proxy'
],
505 => [
'type' => 'HTTP version not supported',
'description' => 'The used version of HTTP is not supported by the server or rejected'
],
507 => [
'type' => 'Insufficient Storage',
'description' => 'The request could not be processed because the server disk space it currently is not sufficient'
],
509 => [
'type' => 'Bandwidth Limit Exceeded',
'description' => 'The request was rejected, because otherwise the bandwidth would be exceeded'
],
510 => [
'type' => 'Not Extended',
'description' => 'The request does not contain all information that is waiting for the requested server extension imperative'
],
000 => [
'type' => 'Unexpected Error',
'description' => 'An unexpected error occurred'
],
];
return (isset($errorCodes[$error])) ? $errorCodes[$error] : $errorCodes[000];
}
public function showTopBarHamburger()
{
if ($this->config['allowCollapsableSideMenu']) {
if ($this->config['sideMenuCollapsed']) {
return '<a class="toggle-side-menu" href="javascript:void(0)"><i class="ti-menu fa-fw"></i></a>';
} else {
return '<a class="toggle-side-menu hidden" href="javascript:void(0)"><i class="ti-menu fa-fw"></i></a>';
}
}
return '';
}
public function showSideBarHamburger()
{
if ($this->config['allowCollapsableSideMenu']) {
if (!$this->config['sideMenuCollapsed']) {
return '<i class="hidden-xs ti-shift-left mouse"></i>';
}
}
return '<i class="ti-menu hidden-xs"></i>';
}
public function showSideBarText()
{
if ($this->config['allowCollapsableSideMenu']) {
if (!$this->config['sideMenuCollapsed']) {
return '<span class="hide-menu hidden-xs" lang="en">Hide Menu</span>';
}
}
return '<span class="hide-menu hidden-xs" lang="en">Navigation</span>';
}
public function auth()
{
if ($this->hasDB()) {
$this->setLoggerChannel('Auth');
if (isset($_GET['type'])) {
switch (strtolower($_GET['type'])) {
case 'whitelist':
case 'white':
case 'w':
case 'wl':
case 'allow':
$_GET['whitelist'] = $_GET['ips'] ?? false;
break;
case 'blacklist':
case 'black':
case 'b':
case 'bl':
case 'deny':
$_GET['blacklist'] = $_GET['ips'] ?? false;
break;
default:
$this->setAPIResponse('error', $_GET['type'] . ' is not a valid type', 401);
return true;
}
}
$whitelist = $_GET['whitelist'] ?? false;
$blacklist = $_GET['blacklist'] ?? false;
$group = 0;
$groupParam = ($_GET['group']) ?? 0;
$redirect = false;
if (isset($groupParam)) {
if (is_numeric($groupParam)) {
$group = (int)$groupParam;
} else {
$group = $this->getTabGroupByTabName($groupParam);
}
}
$currentIP = $this->userIP();
$unlocked = !($this->user['locked'] == '1');
if (isset($this->user)) {
$currentUser = $this->user['username'];
$currentGroup = $this->user['groupID'];
$currentEmail = $this->user['email'];
} else {
$currentUser = 'Guest';
$currentGroup = $this->getUserLevel();
$currentEmail = 'guest@guest.com';
}
$userInfo = [
"user" => $currentUser,
"group" => $currentGroup,
"email" => $currentEmail,
"user_ip" => $currentIP,
"requested_group" => $group,
"uuid" => $_COOKIE['organizr_user_uuid'] ?? 'n/a'
];
$this->logger->debug('Starting check', $userInfo);
$responseMessage = 'User is not Authorized or User is locked';
if ($whitelist) {
if (in_array($currentIP, $this->arrayIP($whitelist))) {
$responseMessage = 'User is whitelisted';
$this->setAPIResponse('success', $responseMessage, 200, $userInfo);
$this->logger->debug($responseMessage, $userInfo);
return true;
}
}
if ($blacklist) {
if (in_array($currentIP, $this->arrayIP($blacklist))) {
$responseMessage = 'User is blacklisted';
$this->setAPIResponse('error', $responseMessage, 401, $userInfo);
$this->logger->debug($responseMessage, $userInfo);
return true;
}
}
if ($group !== null) {
if ((isset($_SERVER['HTTP_X_FORWARDED_SERVER']) && $_SERVER['HTTP_X_FORWARDED_SERVER'] == 'traefik') || $this->config['traefikAuthEnable']) {
$return = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) && isset($_SERVER['HTTP_X_FORWARDED_URI']) && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) ? '?return=' . $_SERVER['HTTP_X_FORWARDED_PROTO'] . '://' . $_SERVER['HTTP_X_FORWARDED_HOST'] . $_SERVER['HTTP_X_FORWARDED_URI'] : '';
$redirectDomain = ($this->config['traefikDomainOverride'] !== '') ? $this->config['traefikDomainOverride'] : $this->getServerPath();
$redirect = 'Location: ' . $redirectDomain . $return;
}
if ($this->qualifyRequest($group) && $unlocked) {
header("X-Organizr-User: $currentUser");
header("X-Organizr-Email: $currentEmail");
header("X-Organizr-Group: $currentGroup");
$responseMessage = 'User is authorized';
$this->setAPIResponse('success', $responseMessage, 200, $userInfo);
$this->logger->debug($responseMessage, $userInfo);
} else {
if (!$redirect) {
$this->setAPIResponse('error', $responseMessage, 401, $userInfo);
$this->logger->debug($responseMessage, $userInfo);
} else {
exit(http_response_code(401) . header($redirect));
}
}
} else {
$this->setAPIResponse('error', 'Missing info', 401);
$this->logger->debug('Missing info', $userInfo);
}
return true;
} else {
$this->setAPIResponse('error', 'Organizr is not setup or an error occurred', 401);
return false;
}
}
public function getIpInfo($ip = null)
{
if (!$ip) {
$this->setResponse(422, 'No IP Address supplied');
return false;
}
try {
$options = array('verify' => false);
$response = Requests::get('https://ipinfo.io/' . $ip . '/?token=ddd0c072ad5021', array(), $options);
if ($response->success) {
$api = json_decode($response->body, true);
$this->setResponse(200, null, $api);
return true;
} else {
$this->setResponse(500, 'An error occurred', null);
}
} catch (Requests_Exception $e) {
$this->setResponse(500, 'An error occurred', $e->getMessage());
}
return false;
}
public function setAPIResponse($result = null, $message = null, $responseCode = null, $data = null)
{
if ($result) {
$GLOBALS['api']['response']['result'] = $result;
}
if ($message) {
$GLOBALS['api']['response']['message'] = $message;
}
if ($responseCode) {
$GLOBALS['responseCode'] = $responseCode;
}
if ($data) {
$GLOBALS['api']['response']['data'] = $data;
}
}
public function setResponse(int $responseCode = 200, string $message = null, $data = null)
{
switch ($responseCode) {
case 200:
case 201:
case 204:
$result = 'success';
break;
default:
$result = 'error';
break;
}
$GLOBALS['api']['response']['result'] = $result;
if ($message) {
$GLOBALS['api']['response']['message'] = $message;
}
if ($responseCode) {
$GLOBALS['responseCode'] = $responseCode;
}
if ($data) {
$GLOBALS['api']['response']['data'] = $data;
}
}
public function printWarningsAndErrors()
{
if (isset($GLOBALS['api']['response']['exceptions'])) {
$this->prettyPrint($GLOBALS['api']['response']['exceptions'], true);
} else {
$this->prettyPrint('No Errors');
}
}
public function setAPIErrorResponse($number, $message, $file, $line)
{
if (!(error_reporting() & $number)) {
return;
}
$exceptions = [
E_ERROR => 'E_ERROR',
E_WARNING => 'E_WARNING',
E_PARSE => 'E_PARSE',
E_NOTICE => 'E_NOTICE',
E_CORE_ERROR => 'E_CORE_ERROR',
E_CORE_WARNING => 'E_CORE_WARNING',
E_COMPILE_ERROR => 'E_COMPILE_ERROR',
E_COMPILE_WARNING => 'E_COMPILE_WARNING',
E_USER_ERROR => 'E_USER_ERROR',
E_USER_WARNING => 'E_USER_WARNING',
E_USER_NOTICE => 'E_USER_NOTICE',
E_STRICT => 'E_STRICT',
E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR',
E_DEPRECATED => 'E_DEPRECATED',
E_USER_DEPRECATED => 'E_USER_DEPRECATED',
E_ALL => 'E_ALL'
];
switch ($number) {
case E_USER_ERROR:
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_RECOVERABLE_ERROR:
$type = 'errors';
break;
case E_USER_WARNING:
case E_WARNING:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
$type = 'warnings';
break;
case E_USER_NOTICE:
case E_PARSE:
case E_DEPRECATED:
case E_USER_DEPRECATED:
case E_NOTICE:
$type = 'notice';
break;
default:
$type = 'other';
break;
}
if ($this->qualifyRequest(1)) {
$count = isset($GLOBALS['api']['response']['exceptions'][$type]) ? count($GLOBALS['api']['response']['exceptions'][$type]) : 0;
if ($count <= 10) {
$GLOBALS['api']['response']['exceptions'][$type][] = [
'error' => $exceptions[$number],
'message' => $message,
'file' => $file,
'line' => $line
];
}
}
$this->handleError($exceptions[$number], $message, $file, $line, $type);
}
public function setErrorResponse($number, $message, $file, $line)
{
$error = [
'error' => $number,
'message' => $message,
'file' => $file,