-
Notifications
You must be signed in to change notification settings - Fork 2
/
Module.php
4278 lines (3817 loc) · 145 KB
/
Module.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
/**
* This code is licensed under AGPLv3 license or Afterlogic Software License
* if commercial version of the product was purchased.
* For full statements of the licenses see LICENSE-AFTERLOGIC and LICENSE-AGPL3 files.
*/
namespace Aurora\Modules\Core;
use Aurora\Api;
use Aurora\Modules\Contacts\Enums\StorageType;
use Aurora\Modules\Contacts\Module as ContactsModule;
use Aurora\Modules\Core\Enums\ErrorCodes;
use Aurora\Modules\Core\Models\Group;
use Aurora\Modules\Core\Models\User;
use Aurora\Modules\Core\Models\UserBlock;
use Aurora\System\Enums\UserRole;
use Aurora\System\Exceptions\ApiException;
use Aurora\System\Notifications;
use Illuminate\Database\Eloquent\Builder;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\BufferedOutput;
use Aurora\System\Logger;
use Aurora\System\Managers\Integrator;
/**
* System module that provides core functionality such as User management, Tenants management.
*
* @license https://www.gnu.org/licenses/agpl-3.0.html AGPL-3.0
* @license https://afterlogic.com/products/common-licensing Afterlogic Software License
* @copyright Copyright (c) 2023, Afterlogic Corp.
*
* @property Settings $oModuleSettings
*
* @package Modules
*/
class Module extends \Aurora\System\Module\AbstractModule
{
protected $oTenantsManager = null;
protected $oChannelsManager = null;
protected $oUsersManager = null;
protected $oIntegratorManager = null;
/**
* @return Module
*/
public static function getInstance()
{
return parent::getInstance();
}
/**
* @return Module
*/
public static function Decorator()
{
return parent::Decorator();
}
/**
* @return Settings
*/
public function getModuleSettings()
{
return $this->oModuleSettings;
}
/**
* @return Managers\Tenants
*/
public function getTenantsManager()
{
if ($this->oTenantsManager === null) {
$this->oTenantsManager = new Managers\Tenants($this);
}
return $this->oTenantsManager;
}
/**
* @return Managers\Channels
*/
public function getChannelsManager()
{
if ($this->oChannelsManager === null) {
$this->oChannelsManager = new Managers\Channels($this);
}
return $this->oChannelsManager;
}
/**
* @return Managers\Users
*/
public function getUsersManager()
{
if ($this->oUsersManager === null) {
$this->oUsersManager = new Managers\Users($this);
}
return $this->oUsersManager;
}
/**
* @return \Aurora\System\Managers\Integrator
*/
public function getIntegratorManager()
{
if ($this->oIntegratorManager === null) {
$this->oIntegratorManager = new \Aurora\System\Managers\Integrator();
}
return $this->oIntegratorManager;
}
/***** private functions *****/
/**
* Initializes Core Module.
*
* @ignore
*/
public function init()
{
$this->aErrors = [
Enums\ErrorCodes::ChannelDoesNotExist => $this->i18N('ERROR_CHANNEL_NOT_EXISTS'),
Enums\ErrorCodes::TenantAlreadyExists => $this->i18N('ERROR_TENANT_ALREADY_EXISTS'),
Enums\ErrorCodes::GroupAlreadyExists => $this->i18N('ERROR_GROUP_ALREADY_EXISTS'),
Enums\ErrorCodes::MySqlConfigError => 'Please make sure your PHP/MySQL environment meets the minimal system requirements.',
];
\Aurora\System\Router::getInstance()->registerArray(
self::GetName(),
[
'api' => [$this, 'EntryApi'],
'ping' => [$this, 'EntryPing'],
'pull' => [$this, 'EntryPull'],
'mobile' => [$this, 'EntryMobile'],
'sso' => [$this, 'EntrySso'],
'postlogin' => [$this, 'EntryPostlogin'],
'file-cache' => [$this, 'EntryFileCache']
]
);
\Aurora\System\EventEmitter::getInstance()->onAny(
[
['CreateAccount', [$this, 'onCreateAccount'], 100],
['Core::GetCompatibilities::after', [$this, 'onAfterGetCompatibilities']],
['System::RunEntry::before', [$this, 'onBeforeRunEntry'], 100]
]
);
$this->denyMethodsCallByWebApi([
'Authenticate',
'UpdateUserObject',
'GetUserByUUID',
'GetUserByPublicId',
'GetAdminUser',
'GetTenantWithoutRoleCheck',
'GetTenantName',
'GetTenantIdByName',
'GetDefaultGlobalTenant',
'UpdateTenantObject',
'GetUserWithoutRoleCheck',
'UpdateTokensValidFromTimestamp',
'GetAccountUsedToAuthorize',
'GetDigestHash',
'VerifyPassword',
'SetAuthDataAndGetAuthToken',
'IsModuleDisabledForObject',
'GetBlockedUser',
'BlockUser',
'IsBlockedUser',
'GetAllGroup',
'CheckIpReputation'
]);
}
/**
*
* @return mixed
*/
private function getUploadData()
{
$mResult = false;
$oFile = null;
if (count($_FILES) > 0) {
$oFile = current($_FILES);
}
if (isset($oFile, $oFile['name'], $oFile['tmp_name'], $oFile['size'], $oFile['type'])) {
$iError = (isset($oFile['error'])) ? (int) $oFile['error'] : UPLOAD_ERR_OK;
$mResult = (UPLOAD_ERR_OK === $iError) ? $oFile : false;
}
return $mResult;
}
/**
* Is called by CreateAccount event. Finds or creates and returns User for new account.
*
* @ignore
* @param array $Args {
* *int* **UserId** Identifier of existing user.
* *int* **TenantId** Identifier of tenant for creating new user in it.
* *int* **$PublicId** New user name.
* }
* @param Models\User $Result
*/
public function onCreateAccount(&$Args, &$Result)
{
$oUser = null;
if (isset($Args['UserId']) && (int)$Args['UserId'] > 0) {
$oUser = $this->getUsersManager()->getUser($Args['UserId']);
} else {
$Email = (isset($Args['Email'])) ? $Args['Email'] : '';
$PublicId = (isset($Args['PublicId'])) ? $Args['PublicId'] : '';
$sPublicId = null;
if (!empty($PublicId)) {
$sPublicId = $PublicId;
} elseif (!empty($Email)) {
$sPublicId = $Email;
}
if (!empty($sPublicId)) {
$oUser = $this->getUsersManager()->getUserByPublicId($sPublicId);
}
if (!isset($oUser)) {
$bPrevState = Api::skipCheckUserRole(true);
$iUserId = self::Decorator()->CreateUser(isset($Args['TenantId']) ? (int) $Args['TenantId'] : 0, $sPublicId);
Api::skipCheckUserRole($bPrevState);
$oUser = $this->getUsersManager()->getUser($iUserId);
}
if (isset($oUser) && isset($oUser->Id)) {
$Args['UserId'] = $oUser->Id;
}
}
$Result = $oUser;
}
/**
* @ignore
* @param array $aArgs
* @param array $mResult
*/
public function onAfterGetCompatibilities($aArgs, &$mResult)
{
$aCompatibility['php.version'] = phpversion();
$aCompatibility['php.version.valid'] = (int) (version_compare($aCompatibility['php.version'], '7.2.5') > -1);
$aCompatibility['safe-mode'] = @ini_get('safe_mode');
$aCompatibility['safe-mode.valid'] = is_numeric($aCompatibility['safe-mode'])
? !((bool) $aCompatibility['safe-mode'])
: ('off' === strtolower($aCompatibility['safe-mode']) || empty($aCompatibility['safe-mode']));
$aCompatibility['mysql.valid'] = (int) extension_loaded('mysql');
$aCompatibility['pdo.valid'] = (int)
((bool) extension_loaded('pdo') && (bool) extension_loaded('pdo_mysql'));
$aCompatibility['mysqlnd.valid'] = (int) (
function_exists('mysqli_fetch_all') &&
strpos(mysqli_get_client_info(), "mysqlnd") !== false
);
$aCompatibility['socket.valid'] = (int) function_exists('fsockopen');
$aCompatibility['iconv.valid'] = (int) function_exists('iconv');
$aCompatibility['curl.valid'] = (int) function_exists('curl_init');
$aCompatibility['mbstring.valid'] = (int) function_exists('mb_detect_encoding');
$aCompatibility['openssl.valid'] = (int) extension_loaded('openssl');
$aCompatibility['xml.valid'] = (int) (class_exists('DOMDocument') && function_exists('xml_parser_create'));
$aCompatibility['json.valid'] = (int) function_exists('json_decode');
$aCompatibility['gd.valid'] = (int) extension_loaded('gd');
$aCompatibility['ini-get.valid'] = (int) function_exists('ini_get');
$aCompatibility['ini-set.valid'] = (int) function_exists('ini_set');
$aCompatibility['set-time-limit.valid'] = (int) function_exists('set_time_limit');
$aCompatibility['session.valid'] = (int) (function_exists('session_start') && isset($_SESSION['checksessionindex']));
$dataPath = Api::DataPath();
$aCompatibility['data.dir'] = $dataPath;
$aCompatibility['data.dir.valid'] = (int) (@is_dir($aCompatibility['data.dir']) && @is_writable($aCompatibility['data.dir']));
$sTempPathName = '_must_be_deleted_' . md5(time());
$aCompatibility['data.dir.create'] =
(int) @mkdir($aCompatibility['data.dir'] . '/' . $sTempPathName);
$aCompatibility['data.file.create'] =
(int) (bool) @fopen($aCompatibility['data.dir'] . '/' . $sTempPathName . '/' . $sTempPathName . '.test', 'w+');
$aCompatibility['data.file.delete'] =
(int) (bool) @unlink($aCompatibility['data.dir'] . '/' . $sTempPathName . '/' . $sTempPathName . '.test');
$aCompatibility['data.dir.delete'] =
(int) @rmdir($aCompatibility['data.dir'] . '/' . $sTempPathName);
$oSettings = &Api::GetSettings();
$aCompatibility['settings.file'] = $oSettings ? $oSettings->GetPath() : '';
$aCompatibility['settings.file.exist'] = (int) @file_exists($aCompatibility['settings.file']);
$aCompatibility['settings.file.read'] = (int) @is_readable($aCompatibility['settings.file']);
$aCompatibility['settings.file.write'] = (int) @is_writable($aCompatibility['settings.file']);
$aCompatibilities = [
[
'Name' => 'PHP version',
'Result' => $aCompatibility['php.version.valid'],
'Value' => $aCompatibility['php.version.valid']
? 'OK'
: [$aCompatibility['php.version'] . ' detected, 7.2.5 or above required.',
'You need to upgrade PHP engine installed on your server.
If it\'s a dedicated or your local server, you can download the latest version of PHP from its
<a href="http://php.net/downloads.php" target="_blank">official site</a> and install it yourself.
In case of a shared hosting, you need to ask your hosting provider to perform the upgrade.']
],
[
'Name' => 'Safe Mode is off',
'Result' => $aCompatibility['safe-mode.valid'],
'Value' => ($aCompatibility['safe-mode.valid'])
? 'OK'
: ['Error, safe_mode is enabled.',
'You need to <a href="http://php.net/manual/en/ini.sect.safe-mode.php" target="_blank">disable it in your php.ini</a>
or contact your hosting provider and ask to do this.']
],
[
'Name' => 'PDO MySQL Extension',
'Result' => $aCompatibility['pdo.valid'],
'Value' => ($aCompatibility['pdo.valid'])
? 'OK'
: ['Error, PHP PDO MySQL extension not detected.',
'You need to install this PHP extension or enable it in php.ini file.']
],
[
'Name' => 'MySQL Native Driver (mysqlnd)',
'Result' => $aCompatibility['mysqlnd.valid'],
'Value' => ($aCompatibility['mysqlnd.valid'])
? 'OK'
: ['Error, MySQL Native Driver not found.',
'You need to install this PHP extension or enable it in php.ini file.']
],
[
'Name' => 'Iconv Extension',
'Result' => $aCompatibility['iconv.valid'],
'Value' => ($aCompatibility['iconv.valid'])
? 'OK'
: ['Error, iconv extension not detected.',
'You need to install this PHP extension or enable it in php.ini file.']
],
[
'Name' => 'Multibyte String Extension',
'Result' => $aCompatibility['mbstring.valid'],
'Value' => ($aCompatibility['mbstring.valid'])
? 'OK'
: ['Error, mb_string extension not detected.',
'You need to install this PHP extension or enable it in php.ini file.']
],
[
'Name' => 'CURL Extension',
'Result' => $aCompatibility['curl.valid'],
'Value' => ($aCompatibility['curl.valid'])
? 'OK'
: ['Error, curl extension not detected.',
'You need to install this PHP extension or enable it in php.ini file.']
],
[
'Name' => 'JSON Extension',
'Result' => $aCompatibility['json.valid'],
'Value' => ($aCompatibility['json.valid'])
? 'OK'
: ['Error, JSON extension not detected.',
'You need to install this PHP extension or enable it in php.ini file.']
],
[
'Name' => 'XML/DOM Extension',
'Result' => $aCompatibility['xml.valid'],
'Value' => ($aCompatibility['xml.valid'])
? 'OK'
: ['Error, xml (DOM) extension not detected.',
'You need to install this PHP extension or enable it in php.ini file.']
],
[
'Name' => 'GD Extension',
'Result' => $aCompatibility['gd.valid'],
'Value' => ($aCompatibility['gd.valid'])
? 'OK'
: ['Error, GD extension not detected.',
'You need to install this PHP extension or enable it in php.ini file.']
],
[
'Name' => 'Sockets',
'Result' => $aCompatibility['socket.valid'],
'Value' => ($aCompatibility['socket.valid'])
? 'OK'
: ['Error, creating network sockets must be enabled.', '
To enable sockets, you should remove fsockopen function from the list of prohibited functions in disable_functions directive of your php.ini file.
In case of a shared hosting, you need to ask your hosting provider to do this.']
],
[
'Name' => 'SSL (OpenSSL extension)',
'Result' => $aCompatibility['openssl.valid'],
'Value' => ($aCompatibility['openssl.valid'])
? 'OK'
: ['SSL connections (like Gmail) will not be available. ', '
You need to enable OpenSSL support in your PHP configuration and make sure OpenSSL library is installed on your server.
For instructions, please refer to the official PHP documentation. In case of a shared hosting,
you need to ask your hosting provider to enable OpenSSL support.
You may ignore this if you\'re not going to connect to SSL-only mail servers (like Gmail).']
],
[
'Name' => 'Setting memory limits',
'Result' => $aCompatibility['ini-get.valid'],
'Value' => ($aCompatibility['ini-get.valid'] && $aCompatibility['ini-set.valid'])
? 'OK'
: ['Opening large e-mails may fail.', '
You need to enable setting memory limits in your PHP configuration, i.e. remove ini_get and ini_set functions
from the list of prohibited functions in disable_functions directive of your php.ini file.
In case of a shared hosting, you need to ask your hosting provider to do this.']
],
[
'Name' => 'Setting script timeout',
'Result' => $aCompatibility['set-time-limit.valid'],
'Value' => ($aCompatibility['set-time-limit.valid'])
? 'OK'
: ['Downloading large mailboxes may fail.', '
To enable setting script timeout, you should remove set_time_limit function from the list
of prohibited functions in disable_functions directive of your php.ini file.
In case of a shared hosting, you need to ask your hosting provider to do this.']
],
[
'Name' => 'WebMail data directory',
'Result' => $aCompatibility['data.dir.valid'],
'Value' => ($aCompatibility['data.dir.valid'])
? 'Found'
: ['Error, data directory path discovery failure.']
],
[
'Name' => 'Creating/deleting directories',
'Result' => $aCompatibility['data.dir.create'] && $aCompatibility['data.dir.delete'],
'Value' => ($aCompatibility['data.dir.create'] && $aCompatibility['data.dir.delete'])
? 'OK'
: ['Error, can\'t create/delete sub-directories in the data directory.', '
You need to grant read/write permission over data directory and all its contents to your web server user.
For instructions, please refer to this section of documentation and our
<a href="https://afterlogic.com/docs/webmail-pro-8/troubleshooting/troubleshooting-issues-with-data-directory" target="_blank">FAQ</a>.']
],
[
'Name' => 'Creating/deleting files',
'Result' => $aCompatibility['data.file.create'] && $aCompatibility['data.file.delete'],
'Value' => ($aCompatibility['data.file.create'] && $aCompatibility['data.file.delete'])
? 'OK'
: ['Error, can\'t create/delete files in the data directory.', '
You need to grant read/write permission over data directory and all its contents to your web server user.
For instructions, please refer to this section of documentation and our
<a href="https://afterlogic.com/docs/webmail-pro-8/troubleshooting/troubleshooting-issues-with-data-directory" target="_blank">FAQ</a>.']
],
[
'Name' => 'WebMail Settings File',
'Result' => $aCompatibility['settings.file.exist'],
'Value' => ($aCompatibility['settings.file.exist'])
? 'Found'
: ['Not Found, can\'t find "' . $aCompatibility['settings.file'] . '" file.', '
Make sure you completely copied the data directory with all its contents from installation package.
By default, the data directory is webmail subdirectory, and if it\'s not the case make sure its location matches one specified in inc_settings_path.php file.']
],
[
'Name' => 'Read/write settings file',
'Result' => $aCompatibility['settings.file.read'] && $aCompatibility['settings.file.write'],
'Value' => ($aCompatibility['settings.file.read'] && $aCompatibility['settings.file.write'])
? 'OK / OK'
: ['Not Found, can\'t find "' . $aCompatibility['settings.file'] . '" file.', '
You should grant read/write permission over settings file to your web server user.
For instructions, please refer to this section of documentation and our
<a href="https://afterlogic.com/docs/webmail-pro-8/troubleshooting/troubleshooting-issues-with-data-directory" target="_blank">FAQ</a>.']
],
];
$mResult[self::GetName()] = $aCompatibilities;
}
public function onBeforeRunEntry($aArgs, &$mResult)
{
\Aurora\Api::removeOldLogs();
return $this->redirectToHttps($aArgs['EntryName'], $mResult);
}
/**
* Recursively deletes temporary files and folders on time.
*
* @param string $sTempPath Path to the temporary folder.
* @param int $iTime2Kill Interval in seconds at which files needs removing.
* @param int $iNow Current Unix timestamp.
*/
protected function removeDirByTime($sTempPath, $iTime2Kill, $iNow)
{
$iFileCount = 0;
if (@is_dir($sTempPath)) {
$rDirH = @opendir($sTempPath);
if ($rDirH) {
while (($sFile = @readdir($rDirH)) !== false) {
if ('.' !== $sFile && '..' !== $sFile) {
if (@is_dir($sTempPath . '/' . $sFile)) {
$this->removeDirByTime($sTempPath . '/' . $sFile, $iTime2Kill, $iNow);
} else {
$iFileCount++;
}
}
}
@closedir($rDirH);
}
if ($iFileCount > 0) {
if ($this->removeFilesByTime($sTempPath, $iTime2Kill, $iNow)) {
@rmdir($sTempPath);
}
} else {
@rmdir($sTempPath);
}
}
}
/**
* Recursively deletes temporary files on time.
*
* @param string $sTempPath Path to the temporary folder.
* @param int $iTime2Kill Interval in seconds at which files needs removing.
* @param int $iNow Current Unix timestamp.
*
* @return bool
*/
protected function removeFilesByTime($sTempPath, $iTime2Kill, $iNow)
{
$bResult = true;
if (@is_dir($sTempPath)) {
$rDirH = @opendir($sTempPath);
if ($rDirH) {
while (($sFile = @readdir($rDirH)) !== false) {
if ($sFile !== '.' && $sFile !== '..') {
if ($iNow - filemtime($sTempPath . '/' . $sFile) > $iTime2Kill) {
@unlink($sTempPath . '/' . $sFile);
} else {
$bResult = false;
}
}
}
@closedir($rDirH);
}
}
return $bResult;
}
protected function redirectToHttps($sEntryName, $mResult)
{
$oSettings = &\Aurora\Api::GetSettings();
if ($oSettings) {
$bRedirectToHttps = $oSettings->RedirectToHttps;
$bHttps = \Aurora\Api::isHttps();
if ($bRedirectToHttps && !$bHttps) {
if (\strtolower($sEntryName) !== 'api') {
\header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
} else {
$mResult = [
'ErrorCode' => 110
];
return true;
}
}
}
}
/***** private functions *****/
/***** static functions *****/
/**
* @ignore
* @return bool
*/
private function deleteTree($dir)
{
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file")) ? $this->deleteTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
/***** static functions *****/
/***** public functions *****/
/**
*
* @return string
* @throws ApiException
*/
public function EntryApi()
{
@ob_start();
if (!is_writable(Api::DataPath())) {
throw new ApiException(Notifications::SystemNotConfigured, null, 'Check the write permission of the data folder');
}
$aResponseItem = null;
$sModule = $this->oHttp->GetPost('Module', null);
$sMethod = $this->oHttp->GetPost('Method', null);
$sParameters = $this->oHttp->GetPost('Parameters', null);
$sFormat = $this->oHttp->GetPost('Format', null);
$sTenantName = $this->oHttp->GetPost('TenantName', null);
if (isset($sModule, $sMethod)) {
$oModule = Api::GetModule($sModule);
if ($oModule instanceof \Aurora\System\Module\AbstractModule) {
try {
Api::Log(" ");
Api::Log(" ===== API: " . $sModule . '::' . $sMethod);
$bIsEmptyAuthToken = !Api::getAuthTokenFromHeaders();
if ($this->oModuleSettings->CsrfTokenProtection && !Api::validateCsrfToken()/* && !$bIsEmptyAuthToken*/) {
throw new ApiException(
Notifications::InvalidToken,
null,
'InvalidToken'
);
}
if (!empty($sModule) && !empty($sMethod)) {
if (!Api::validateAuthToken() && !$bIsEmptyAuthToken) {
throw new ApiException(
Notifications::AuthError,
null,
'AuthError'
);
}
Api::setTenantName($sTenantName);
$aParameters = [];
if (isset($sParameters) && \is_string($sParameters) && !empty($sParameters)) {
$aParameters = @\json_decode($sParameters, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new ApiException(
Notifications::InvalidInputParameter,
null,
'InvalidInputParameter'
);
}
if (!\is_array($aParameters)) {
$aParameters = array($aParameters);
}
}
$mUploadData = $this->getUploadData();
if (\is_array($mUploadData)) {
$aParameters['UploadData'] = $mUploadData;
}
$oModule->CallMethod(
$sMethod,
$aParameters,
true
);
$oLastException = Api::GetModuleManager()->GetLastException();
if (isset($oLastException)) {
throw $oLastException;
}
$aResponseItem = $oModule->DefaultResponse(
$sMethod,
Api::GetModuleManager()->GetResults()
);
}
if (!\is_array($aResponseItem)) {
throw new ApiException(
Notifications::UnknownError,
null,
'UnknownError'
);
}
} catch (\Exception $oException) {
Api::LogException($oException);
$aAdditionalParams = null;
if ($oException instanceof ApiException) {
$aAdditionalParams = $oException->GetObjectParams();
}
$aResponseItem = $oModule->ExceptionResponse(
$sMethod,
$oException,
$aAdditionalParams
);
}
} else {
$oException = new ApiException(
Notifications::ModuleNotFound,
null,
'Module not found'
);
$aResponseItem = $this->ExceptionResponse(
$sMethod,
$oException
);
}
} else {
$oException = new ApiException(
Notifications::InvalidInputParameter,
null,
'Invalid input parameter'
);
$aResponseItem = $this->ExceptionResponse(
$sMethod,
$oException
);
}
if (isset($aResponseItem['Parameters'])) {
unset($aResponseItem['Parameters']);
}
return \Aurora\System\Managers\Response::GetJsonFromObject($sFormat, $aResponseItem);
}
/**
* @ignore
*/
public function EntryMobile()
{
$oApiIntegrator = $this->getIntegratorManager();
$oApiIntegrator->setMobile(true);
Api::Location('./');
}
/**
* @ignore
*/
public function EntrySso()
{
try {
$sHash = $this->oHttp->GetRequest('hash');
if (!empty($sHash)) {
$sData = Api::Cacher()->get('SSO:' . $sHash, true);
$aData = Api::DecodeKeyValues($sData);
if (isset($aData['Password'], $aData['Email'])) {
$sLanguage = $this->oHttp->GetRequest('lang');
$aResult = self::Decorator()->Login($aData['Email'], $aData['Password'], $sLanguage);
if (is_array($aResult) && isset($aResult['AuthToken'])) {
Api::setAuthTokenCookie($aResult['AuthToken']);
} else {
Api::unsetAuthTokenCookie();
}
}
} else {
self::Decorator()->Logout();
}
} catch (\Exception $oExc) {
Api::LogException($oExc);
}
Api::Location('./');
}
/**
* @ignore
*/
public function EntryPostlogin()
{
if ($this->oModuleSettings->AllowPostLogin) {
$sEmail = trim((string) $this->oHttp->GetRequest('Email', ''));
$sLogin = (string) $this->oHttp->GetRequest('Login', '');
$sPassword = (string) $this->oHttp->GetRequest('Password', '');
if ($sLogin === '') {
$sLogin = $sEmail;
}
$aResult = self::Decorator()->Login($sLogin, $sPassword);
if (is_array($aResult) && isset($aResult['AuthToken'])) {
Api::setAuthTokenCookie($aResult['AuthToken']);
}
Api::Location('./');
}
}
public function EntryFileCache()
{
Api::checkUserRoleIsAtLeast(UserRole::NormalUser);
$sRawKey = \Aurora\System\Router::getItemByIndex(1, '');
$sAction = \Aurora\System\Router::getItemByIndex(2, '');
$aValues = Api::DecodeKeyValues($sRawKey);
$bDownload = true;
$bThumbnail = false;
switch ($sAction) {
case 'view':
$bDownload = false;
$bThumbnail = false;
break;
case 'thumb':
$bDownload = false;
$bThumbnail = true;
break;
default:
$bDownload = true;
$bThumbnail = false;
break;
}
$iUserId = (isset($aValues['UserId'])) ? $aValues['UserId'] : 0;
if (isset($aValues['TempFile'], $aValues['TempName'], $aValues['Name'])) {
$sModule = isset($aValues['Module']) && !empty($aValues['Module']) ? $aValues['Module'] : 'System';
$sUUID = Api::getUserUUIDById($iUserId);
$oApiFileCache = new \Aurora\System\Managers\Filecache();
$mResult = $oApiFileCache->getFile($sUUID, $aValues['TempName'], '', $sModule);
if (is_resource($mResult)) {
$sFileName = $aValues['Name'];
$sContentType = (empty($sFileName)) ? 'text/plain' : \MailSo\Base\Utils::MimeContentType($sFileName);
$sFileName = \Aurora\System\Utils::clearFileName($sFileName, $sContentType);
\Aurora\System\Utils::OutputFileResource($sUUID, $sContentType, $sFileName, $mResult, $bThumbnail, $bDownload);
}
}
}
public function IsModuleExists($Module)
{
return Api::GetModuleManager()->ModuleExists($Module);
}
/**
*
* @return string
*/
public function GetVersion()
{
return Api::Version();
}
/**
* Clears temporary files by cron.
*
* @ignore
* @todo check if it works.
*
* @return bool
*/
protected function ClearTempFiles()
{
$sTempPath = Api::DataPath() . '/temp';
if (@is_dir($sTempPath)) {
$iNow = time();
$iTime2Run = $this->oModuleSettings->CronTimeToRunSeconds;
$iTime2Kill = $this->oModuleSettings->CronTimeToKillSeconds;
$sDataFile = $this->oModuleSettings->CronTimeFile;
$iFiletTime = -1;
if (@file_exists(Api::DataPath() . '/' . $sDataFile)) {
$iFiletTime = (int) @file_get_contents(Api::DataPath() . '/' . $sDataFile);
}
if ($iFiletTime === -1 || $iNow - $iFiletTime > $iTime2Run) {
$this->removeDirByTime($sTempPath, $iTime2Kill, $iNow);
@file_put_contents(Api::DataPath() . '/' . $sDataFile, $iNow);
}
}
return true;
}
/**
* !Not public
* This method is restricted to be called by web API (see denyMethodsCallByWebApi method).
*
* Updates user by object.
*
* @param Models\User $oUser
* @return bool
*/
public function UpdateUserObject($oUser)
{
/** This method is restricted to be called by web API (see denyMethodsCallByWebApi method). **/
return $this->getUsersManager()->updateUser($oUser);
}
/**
* !Not public
* This method is restricted to be called by web API (see denyMethodsCallByWebApi method).
*
* Returns user object.
*
* @param int|string $UserId User identifier or UUID.
* @return Models\User
*/
public function GetUserWithoutRoleCheck($UserId = '')
{
/** This method is restricted to be called by web API (see denyMethodsCallByWebApi method). **/
$oUser = $this->getUsersManager()->getUser($UserId);
return $oUser ? $oUser : null;
}
/**
* !Not public
* This method is restricted to be called by web API (see denyMethodsCallByWebApi method).
*
* Returns user object.
*
* @param int $UUID User uuid identifier.
* @return Models\User
*/
public function GetUserByUUID($UUID)
{
/** This method is restricted to be called by web API (see denyMethodsCallByWebApi method). **/
$oUser = $this->getUsersManager()->getUser($UUID);
return $oUser ? $oUser : null;
}
/**
* !Not public
* This method is restricted to be called by web API (see denyMethodsCallByWebApi method).
*
* Returns user object.
*
* @param string $PublicId User public identifier.
* @return Models\User
*/
public function GetUserByPublicId($PublicId)
{
/** This method is restricted to be called by web API (see denyMethodsCallByWebApi method). **/
$oUser = $this->getUsersManager()->getUserByPublicId($PublicId);
return $oUser ? $oUser : null;
}
/**
* !Not public
* This method is restricted to be called by web API (see denyMethodsCallByWebApi method).
*
* Creates and returns user with super administrator role.
*
* @deprecated sinse version 9.7.8
*
* @return Models\User
*/
public function GetAdminUser()
{
/** This method is restricted to be called by web API (see denyMethodsCallByWebApi method). **/
return Integrator::GetAdminUser();
}
/**
* !Not public
* This method is restricted to be called by web API (see denyMethodsCallByWebApi method).
*
* Returns tenant object by identifier.
*
* @param int $Id Tenant identifier.
* @return Models\Tenant|null
*/
public function GetTenantWithoutRoleCheck($Id)
{
/** This method is restricted to be called by web API (see denyMethodsCallByWebApi method). **/
$oTenant = $this->getTenantsManager()->getTenantById($Id);
return $oTenant ? $oTenant : null;
}
/**
* !Not public
* This method is restricted to be called by web API (see denyMethodsCallByWebApi method).
*
* Returns tenant identifier by tenant name.
*
* @param string $TenantName Tenant name.