forked from postfixadmin/postfixadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.inc.php
2479 lines (2144 loc) · 75.8 KB
/
functions.inc.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
/**
* Postfix Admin
*
* LICENSE
* This source file is subject to the GPL license that is bundled with
* this package in the file LICENSE.TXT.
*
* Further details on the project are available at http://postfixadmin.sf.net
*
* @license GNU GPL v2 or later.
*
* File: functions.inc.php
* Contains re-usable code.
*/
$min_db_version = 1844; # update (at least) before a release with the latest function numbrer in upgrade.php
/**
* Check if the user already provided a password but not the second factor
* @return boolean
*/
function authentication_mfa_incomplete()
{
if (isset($_SESSION['sessid'])) {
if (isset($_SESSION['sessid']['mfa_complete'])) {
if ($_SESSION['sessid']['mfa_complete'] == false) {
return true;
}
}
}
return false;
}
/**
* check_session
* Action: Check if a session already exists, if not redirect to login.php
* Call: check_session ()
* @return String username (e.g. [email protected])
*/
function authentication_get_username()
{
if (defined('POSTFIXADMIN_CLI')) {
return 'CLI';
}
if (defined('POSTFIXADMIN_SETUP')) {
return 'SETUP.PHP';
}
if (!isset($_SESSION['sessid'])) {
header("Location: login.php");
exit(0);
}
$SESSID_USERNAME = $_SESSION['sessid']['username'];
return $SESSID_USERNAME;
}
/**
* Returns the type of user - either 'user' or 'admin'
* Returns false if neither (E.g. if not logged in)
* @return string|bool admin or user or (boolean) false.
*/
function authentication_get_usertype()
{
if (isset($_SESSION['sessid'])) {
if (isset($_SESSION['sessid']['type'])) {
return $_SESSION['sessid']['type'];
}
}
return false;
}
/**
*
* Used to determine whether a user has a particular role.
* @param string $role role-name. (E.g. admin, global-admin or user)
* @return boolean True if they have the requested role in their session.
* Note, user < admin < global-admin
*/
function authentication_has_role($role)
{
if (isset($_SESSION['sessid'])) {
if (isset($_SESSION['sessid']['roles'])) {
if (in_array($role, $_SESSION['sessid']['roles'])) {
return true;
}
}
}
return false;
}
/**
* Used to enforce that $user has a particular role when
* viewing a page.
* If they are lacking a role, redirect them to login.php
*
* Note, user < admin < global-admin
* @param string $role
* @return bool
*/
function authentication_require_role($role)
{
// redirect to appropriate page?
if (authentication_has_role($role)) {
return true;
}
header("Location: login.php");
exit(0);
}
/**
* Initialize a user or admin session
*
* @param String $username the user or admin name
* @param boolean $is_admin true if the user is an admin, false otherwise
* @return boolean true on success
*/
function init_session($username, $is_admin = false, $mfa_complete = false)
{
$status = session_regenerate_id(true);
$_SESSION['sessid'] = array();
$_SESSION['sessid']['roles'] = array();
if ($mfa_complete) {
$_SESSION['sessid']['roles'][] = $is_admin ? 'admin' : 'user';
$_SESSION['sessid']['mfa_complete'] = true;
} else {
$_SESSION['sessid']['mfa_complete'] = false;
}
$_SESSION['sessid']['username'] = $username;
$_SESSION['PFA_token'] = md5(random_bytes(8) . uniqid('pfa', true));
return $status;
}
/**
* Add an error message for display on the next page that is rendered.
* @param string|array $string message(s) to show.
*
* Stores string in session. Flushed through header template.
* @return void
* @see _flash_string()
*/
function flash_error($string)
{
_flash_string('error', $string);
}
/**
* Used to display an info message on successful update.
* @param string|array $string message(s) to show.
* Stores data in session.
* @return void
* @see _flash_string()
*/
function flash_info($string)
{
_flash_string('info', $string);
}
/**
* 'Private' method used for flash_info() and flash_error().
* @param string $type
* @param array|string $string
* @retrn void
*/
function _flash_string($type, $string)
{
if (is_array($string)) {
foreach ($string as $singlestring) {
_flash_string($type, $singlestring);
}
return;
}
if (!isset($_SESSION['flash'])) {
$_SESSION['flash'] = array();
}
if (!isset($_SESSION['flash'][$type])) {
$_SESSION['flash'][$type] = array();
}
$_SESSION['flash'][$type][] = $string;
}
/**
* @param bool $use_post - set to 0 if $_POST should NOT be read
* @return string e.g en
* Try to figure out what language the user wants based on browser / cookie
*/
function check_language($use_post = true)
{
global $supported_languages; # from languages/languages.php
// prefer a $_POST['lang'] if present
if ($use_post && safepost('lang')) {
$lang = safepost('lang');
if (is_string($lang) && array_key_exists($lang, $supported_languages)) {
return $lang;
}
}
// Failing that, is there a $_COOKIE['lang'] ?
if (safecookie('lang')) {
$lang = safecookie('lang');
if (is_string($lang) && array_key_exists($lang, $supported_languages)) {
return $lang;
}
}
$lang = Config::read_string('default_language');
// If not, did the browser give us any hint(s)?
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$lang_array = preg_split('/(\s*,\s*)/', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($lang_array as $value) {
$lang_next = strtolower(trim($value));
$lang_next = preg_replace('/;.*$/', '', $lang_next); # remove things like ";q=0.8"
if (array_key_exists($lang_next, $supported_languages)) {
return $lang_next;
}
}
}
return $lang;
}
/**
* Action: returns a language selector dropdown with the browser (or cookie) language preselected
* @return string
*
*
*/
function language_selector()
{
global $supported_languages; # from languages/languages.php
$current_lang = check_language();
$selector = '<select id="lang" name="lang" xml:lang="en" dir="ltr">';
foreach ($supported_languages as $lang => $lang_name) {
if ($lang == $current_lang) {
$selected = ' selected="selected"';
} else {
$selected = '';
}
$selector .= "<option value='$lang'$selected>$lang_name</option>";
}
$selector .= "</select>";
return $selector;
}
/**
* Checks if a domain is valid
* @param string $domain
* @return string empty if the domain is valid, otherwise string with the errormessage
*
* @todo make check_domain able to handle as example .local domains
* @todo skip DNS check if the domain exists in PostfixAdmin?
*/
function check_domain($domain)
{
if (!preg_match('/^([-0-9A-Z]+\.)+' . '([-0-9A-Z]){1,13}$/i', ($domain))) {
return sprintf(Config::lang('pInvalidDomainRegex'), htmlentities($domain));
}
if (Config::bool('emailcheck_resolve_domain') && 'WINDOWS' != (strtoupper(substr(php_uname('s'), 0, 7)))) {
// Look for an AAAA, A, or MX record for the domain
if (function_exists('checkdnsrr')) {
$start = microtime(true); # check for slow nameservers, part 1
// AAAA (IPv6) is only available in PHP v. >= 5
if (version_compare(phpversion(), "5.0.0", ">=") && checkdnsrr($domain, 'AAAA')) {
$retval = '';
} elseif (checkdnsrr($domain, 'A')) {
$retval = '';
} elseif (checkdnsrr($domain, 'MX')) {
$retval = '';
} elseif (checkdnsrr($domain, 'NS')) {
error_log("DNS is not correctly configured for $domain to send or receive email");
$retval = '';
} else {
$retval = sprintf(Config::lang('pInvalidDomainDNS'), htmlentities($domain));
}
$end = microtime(true); # check for slow nameservers, part 2
$time_needed = $end - $start;
if ($time_needed > 2) {
error_log("Warning: slow nameserver - lookup for $domain took $time_needed seconds");
}
return $retval;
} else {
return 'emailcheck_resolve_domain is enabled, but function (checkdnsrr) missing!';
}
}
return '';
}
/**
* Get password expiration value for a domain
* @param string $domain - a string that may be a domain
* @return int password expiration value for this domain (DAYS, or zero if not enabled)
*/
function get_password_expiration_value(string $domain)
{
$table_domain = table_by_key('domain');
$query = "SELECT password_expiry FROM $table_domain WHERE domain= :domain";
$result = db_query_one($query, array('domain' => $domain));
if (is_array($result) && isset($result['password_expiry'])) {
return $result['password_expiry'];
}
return 0;
}
/**
* check_email
* Checks if an email is valid - if it is, return true, else false.
* @param string $email - a string that may be an email address.
* @return string empty if it's a valid email address, otherwise string with the errormessage
* @todo make check_email able to handle already added domains
*/
function check_email($email)
{
$ce_email = $email;
//strip the vacation domain out if we are using it
//and change from blah#[email protected] to [email protected]
if (Config::bool('vacation')) {
$vacation_domain = Config::read_string('vacation_domain');
$ce_email = preg_replace("/@$vacation_domain\$/", '', $ce_email);
$ce_email = preg_replace("/#/", '@', $ce_email);
}
// Perform non-domain-part sanity checks
if (!preg_match('/^[-!#$%&\'*+\\.\/0-9=?A-Z^_{|}~]+' . '@' . '[^@]+$/i', $ce_email)) {
return "" . Config::lang_f('pInvalidMailRegex', $email);
}
if (function_exists('filter_var')) {
$check = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$check) {
return "" . Config::lang_f('pInvalidMailRegex', $email);
}
}
// Determine domain name
$matches = array();
if (preg_match('|@(.+)$|', $ce_email, $matches)) {
$domain = $matches[1];
# check domain name
return "" . check_domain($domain);
}
return "" . Config::lang_f('pInvalidMailRegex', $email);
}
/**
* Clean a string, escaping any meta characters that could be
* used to disrupt an SQL string. The method of the escaping is dependent on the underlying DB
* and MAY NOT be just \' ing. (e.g. sqlite and PgSQL change "it's" to "it''s".
*
* The PDO quote function surrounds what you pass in with quote marks; for legacy reasons we remove these,
* but assume the caller will actually add them back in (!).
*
* e.g. caller code looks like :
*
* <code>
* $sql = "SELECT * FROM foo WHERE x = '" . escape_string('fish') . "'";
* </code>
*
* @param int|string $string_or_int parameters to escape
* @return string cleaned data, suitable for use within an SQL statement.
*/
function escape_string($string_or_int)
{
$link = db_connect();
$string_or_int = (string)$string_or_int;
$quoted = $link->quote($string_or_int);
return trim($quoted, "'");
}
/**
* safeget
* Action: get value from $_GET[$param], or $default if $_GET[$param] is not set
* Call: $param = safeget('param') # replaces $param = $_GET['param']
* - or -
* $param = safeget('param', 'default')
*
* @param string $param parameter name.
* @param string $default (optional) - default value if key is not set.
* @return string
*/
function safeget($param, $default = "")
{
$retval = $default;
if (isset($_GET[$param]) && is_string($_GET[$param])) {
$retval = $_GET[$param];
}
return $retval;
}
/**
* safepost - similar to safeget() but for $_POST
* @param string $param parameter name
* @param string $default (optional) default value (defaults to "")
* @return string - value in $_POST[$param] or $default
* @see safeget()
*/
function safepost($param, $default = "")
{
$retval = $default;
if (isset($_POST[$param]) && is_string($_POST[$param])) {
$retval = $_POST[$param];
}
return $retval;
}
/**
* safecookie
* @param string $param
* @param string $default (optional)
* @return string value from $_COOKIE[$param] or $default
* @see safeget()
*/
function safecookie($param, $default = "")
{
$retval = $default;
if (isset($_COOKIE[$param])) {
$retval = $_COOKIE[$param];
}
return $retval;
}
/**
* safesession
* @param string $param
* @param string $default (optional)
* @return string value from $_SESSION[$param] or $default
* @see safeget()
*/
function safesession($param, $default = "")
{
$retval = $default;
if (isset($_SESSION[$param]) && is_string($_SESSION[$param])) {
$retval = $_SESSION[$param];
}
return $retval;
}
/**
* pacol
* @param int $allow_editing
* @param int $display_in_form
* @param int display_in_list
* @param string $type
* @param string PALANG_label
* @param string PALANG_desc
* @param any optional $default
* @param array $options optional options
* @param int or $not_in_db - if array, can contain the remaining parameters as associated array. Otherwise counts as $not_in_db
* @return array for $struct
*/
function pacol($allow_editing, $display_in_form, $display_in_list, $type, $PALANG_label, $PALANG_desc, $default = "", $options = array(), $multiopt = 0, $dont_write_to_db = 0, $select = "", $extrafrom = "", $linkto = "")
{
if ($PALANG_label != '') {
$PALANG_label = Config::lang($PALANG_label);
}
if ($PALANG_desc != '') {
$PALANG_desc = Config::lang($PALANG_desc);
}
if (is_array($multiopt)) { # remaining parameters provided in named array
$not_in_db = 0; # keep default value
foreach ($multiopt as $key => $value) {
$$key = $value; # extract everything to the matching variable
}
} else {
$not_in_db = $multiopt;
}
return array(
'editable' => $allow_editing,
'display_in_form' => $display_in_form,
'display_in_list' => $display_in_list,
'type' => $type,
'label' => $PALANG_label, # $PALANG field label
'desc' => $PALANG_desc, # $PALANG field description
'default' => $default,
'options' => $options,
'not_in_db' => $not_in_db,
'dont_write_to_db' => $dont_write_to_db,
'select' => $select, # replaces the field name after SELECT
'extrafrom' => $extrafrom, # added after FROM xy - useful for JOINs etc.
'linkto' => $linkto, # make the value a link - %s will be replaced with the ID
);
}
/**
* Action: Get all the properties of a domain.
* @param string $domain
* @return array
*/
function get_domain_properties($domain)
{
$handler = new DomainHandler();
if (!$handler->init($domain)) {
throw new Exception("Error: " . join("\n", $handler->errormsg));
}
if (!$handler->view()) {
throw new Exception("Error: " . join("\n", $handler->errormsg));
}
$result = $handler->result();
return $result;
}
/**
* create_page_browser
* Action: Get page browser for a long list of mailboxes, aliases etc.
*
* @param string $idxfield - database field name to use as title e.g. alias.address
* @param string $querypart - core part of the query (starting at "FROM") e.g. FROM alias WHERE address like ...
* @return array
*/
function create_page_browser($idxfield, $querypart, $sql_params = [])
{
global $CONF;
$page_size = (int)$CONF['page_size'];
$label_len = 2;
$pagebrowser = array();
$count_results = 0;
if ($page_size < 2) { # will break the page browser
throw new Exception('$CONF[\'page_size\'] must be 2 or more!');
}
# get number of rows
$query = "SELECT count(*) as counter FROM (SELECT $idxfield $querypart) AS tmp";
$result = db_query_one($query, $sql_params);
if ($result && isset($result['counter'])) {
$count_results = $result['counter'] - 1; # we start counting at 0, not 1
}
if ($count_results < $page_size) {
return array(); # only one page - no pagebrowser required
}
# init row counter
$initcount = "SET @r=-1";
if (db_pgsql()) {
$initcount = "CREATE TEMPORARY SEQUENCE rowcount MINVALUE 0";
}
if (!db_sqlite()) {
db_execute($initcount);
}
# get labels for relevant rows (first and last of each page)
$page_size_zerobase = $page_size - 1;
$query = "
SELECT * FROM (
SELECT $idxfield AS label, @r := @r + 1 AS 'r' $querypart
) idx WHERE MOD(idx.r, $page_size) IN (0,$page_size_zerobase) OR idx.r = $count_results
";
if (db_pgsql()) {
$query = "
SELECT * FROM (
SELECT $idxfield AS label, nextval('rowcount') AS r $querypart
) idx WHERE MOD(idx.r, $page_size) IN (0,$page_size_zerobase) OR idx.r = $count_results
";
}
if (db_sqlite()) {
$end = $idxfield;
if (strpos($idxfield, '.') !== false) {
$bits = explode('.', $idxfield);
$end = $bits[1];
}
$query = "
WITH idx AS (SELECT * $querypart)
SELECT $end AS label, (SELECT (COUNT(*) - 1) FROM idx t1 WHERE t1.$end <= t2.$end ) AS r
FROM idx t2
WHERE (r % $page_size) IN (0,$page_size_zerobase) OR r = $count_results";
}
# PostgreSQL:
# http://www.postgresql.org/docs/8.1/static/sql-createsequence.html
# http://www.postgresonline.com/journal/archives/79-Simulating-Row-Number-in-PostgreSQL-Pre-8.4.html
# http://www.pg-forum.de/sql/1518-nummerierung-der-abfrageergebnisse.html
# CREATE TEMPORARY SEQUENCE foo MINVALUE 0 MAXVALUE $page_size_zerobase CYCLE
# afterwards: DROP SEQUENCE foo
$result = db_query_all($query, $sql_params);
for ($k = 0; $k < count($result); $k += 2) {
if (isset($result[$k + 1])) {
$label = substr($result[$k]['label'], 0, $label_len) . '-' . substr($result[$k + 1]['label'], 0, $label_len);
} else {
$label = substr($result[$k]['label'], 0, $label_len);
}
$pagebrowser[] = $label;
}
if (db_pgsql()) {
db_execute("DROP SEQUENCE rowcount");
}
return $pagebrowser;
}
/**
* Recalculates the quota from MBs to bytes (divide, /)
* @param int $quota
* @return float
*/
function divide_quota($quota)
{
if ($quota == -1) {
return $quota;
}
$value = round($quota / (int)Config::read_string('quota_multiplier'), 2);
return $value;
}
/**
* Checks if the admin is the owner of the domain (or global-admin)
* @param string $username
* @param string $domain
* @return bool
*/
function check_owner($username, $domain)
{
$table_domain_admins = table_by_key('domain_admins');
$result = db_query_all(
"SELECT 1 FROM $table_domain_admins WHERE username= ? AND (domain = ? OR domain = 'ALL') AND active = ?",
array($username, $domain, db_get_boolean(true))
);
if (sizeof($result) == 1 || sizeof($result) == 2) { # "ALL" + specific domain permissions is possible
# TODO: if superadmin, check if given domain exists in the database
return true;
} else {
if (sizeof($result) > 2) { # more than 2 results means something really strange happened...
flash_error("Permission check returned multiple results. Please go to 'edit admin' for your username and press the save "
. "button once to fix the database. If this doesn't help, open a bugreport.");
}
return false;
}
}
/**
* List domains for an admin user.
* @param string $username
* @return array of domain names.
*/
function list_domains_for_admin($username)
{
$table_domain = table_by_key('domain');
$table_domain_admins = table_by_key('domain_admins');
$condition = array();
$E_username = escape_string($username);
$query = "SELECT $table_domain.domain FROM $table_domain ";
$condition[] = "$table_domain.domain != 'ALL'";
$pvalues = array();
$result = db_query_one("SELECT username FROM $table_domain_admins WHERE username= :username AND domain='ALL'", array('username' => $username));
if (empty($result)) { # not a superadmin
$pvalues['username'] = $username;
$pvalues['active'] = db_get_boolean(true);
$pvalues['backupmx'] = db_get_boolean(false);
$query .= " LEFT JOIN $table_domain_admins ON $table_domain.domain=$table_domain_admins.domain ";
$condition[] = "$table_domain_admins.username = :username ";
$condition[] = "$table_domain.active = :active "; # TODO: does it really make sense to exclude inactive...
$condition[] = "$table_domain.backupmx = :backupmx"; # TODO: ... and backupmx domains for non-superadmins?
}
$query .= " WHERE " . join(' AND ', $condition);
$query .= " ORDER BY $table_domain.domain";
$result = db_query_all($query, $pvalues);
return array_column($result, 'domain');
}
/**
* List all available domains.
*
* @return array
*/
function list_domains()
{
$list = array();
$table_domain = table_by_key('domain');
$result = db_query_all("SELECT domain FROM $table_domain WHERE domain!='ALL' ORDER BY domain");
$i = 0;
foreach ($result as $row) {
$list[$i] = $row['domain'];
$i++;
}
return $list;
}
//
// list_admins
// Action: Lists all the admins
// Call: list_admins ()
//
// was admin_list_admins
//
function list_admins()
{
$handler = new AdminHandler();
$handler->getList('');
return $handler->result();
}
//
// encode_header
// Action: Encode a string according to RFC 1522 for use in headers if it contains 8-bit characters.
// Call: encode_header (string header, string charset)
//
function encode_header($string, $default_charset = "utf-8")
{
if (strtolower($default_charset) == 'iso-8859-1') {
$string = str_replace("\240", ' ', $string);
}
$j = strlen($string);
$max_l = 75 - strlen($default_charset) - 7;
$aRet = array();
$ret = '';
$iEncStart = $enc_init = false;
$cur_l = $iOffset = 0;
for ($i = 0; $i < $j; ++$i) {
switch ($string[$i]) {
case '=':
case '<':
case '>':
case ',':
case '?':
case '_':
if ($iEncStart === false) {
$iEncStart = $i;
}
$cur_l += 3;
if ($cur_l > ($max_l - 2)) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?=";
$iOffset = $i;
$cur_l = 0;
$ret = '';
$iEncStart = false;
} else {
$ret .= sprintf("=%02X", ord($string[$i]));
}
break;
case '(':
case ')':
if ($iEncStart !== false) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?=";
$iOffset = $i;
$cur_l = 0;
$ret = '';
$iEncStart = false;
}
break;
case ' ':
if ($iEncStart !== false) {
$cur_l++;
if ($cur_l > $max_l) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?=";
$iOffset = $i;
$cur_l = 0;
$ret = '';
$iEncStart = false;
} else {
$ret .= '_';
}
}
break;
default:
$k = ord($string[$i]);
if ($k > 126) {
if ($iEncStart === false) {
// do not start encoding in the middle of a string, also take the rest of the word.
$sLeadString = substr($string, 0, $i);
$aLeadString = explode(' ', $sLeadString);
$sToBeEncoded = array_pop($aLeadString);
$iEncStart = $i - strlen($sToBeEncoded);
$ret .= $sToBeEncoded;
$cur_l += strlen($sToBeEncoded);
}
$cur_l += 3;
// first we add the encoded string that reached it's max size
if ($cur_l > ($max_l - 2)) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?= ";
$cur_l = 3;
$ret = '';
$iOffset = $i;
$iEncStart = $i;
}
$enc_init = true;
$ret .= sprintf("=%02X", $k);
} else {
if ($iEncStart !== false) {
$cur_l++;
if ($cur_l > $max_l) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?=";
$iEncStart = false;
$iOffset = $i;
$cur_l = 0;
$ret = '';
} else {
$ret .= $string[$i];
}
}
}
break;
# end switch
}
}
if ($enc_init) {
if ($iEncStart !== false) {
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
$aRet[] = "=?$default_charset?Q?$ret?=";
} else {
$aRet[] = substr($string, $iOffset);
}
$string = implode('', $aRet);
}
return $string;
}
/**
* Generate a random password of $length characters.
* @param int $length (optional, default: 12)
* @return string
*
*/
function generate_password($length = 12)
{
// define possible characters
$possible = "2345678923456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"; # skip 0 and 1 to avoid confusion with O and l
// add random characters to $password until $length is reached
$password = "";
while (strlen($password) < $length) {
$random = random_int(0, strlen($possible) - 1);
$char = substr($possible, $random, 1);
// we don't want this character if it's already in the password
if (!strstr($password, $char)) {
$password .= $char;
}
}
return $password;
}
/**
* Check if a password is strong enough based on the conditions in $CONF['password_validation']
* @param string $password
* @return array of error messages, or empty array if the password is ok
*/
function validate_password($password)
{
$result = array();
$config = Config::getInstance()->getAll();
$val_conf = $config['password_validation'] ?? [];
$minlen = $config['min_password_length'] ?? null;
if (is_numeric($minlen) && $minlen > 0) {
$minlen = (int)$minlen; # used up to 2.3.x -
$val_conf['/.{' . $minlen . '}/'] = "password_too_short $minlen";
}
foreach ($val_conf as $regex => $message) {
if (is_callable($message)) {
$ret = $message($password);
if (!empty($ret)) {
$result[] = $ret;
}
continue;
}
if (!preg_match($regex, $password)) {
$msgparts = preg_split("/ /", $message, 2);
if (count($msgparts) == 1) {
$result[] = Config::lang($msgparts[0]);
} else {
$result[] = sprintf(Config::lang($msgparts[0]), $msgparts[1]);
}
}
}
return $result;
}
/**
* @param string $pw
* @param string $pw_db - encrypted hash
* @return string crypt'ed password, should equal $pw_db if $pw matches the original
* @deprecated
*/
function _pacrypt_md5crypt($pw, $pw_db = '')
{
if ($pw_db) {
$split_salt = preg_split('/\$/', $pw_db);
if (isset($split_salt[2])) {
$salt = $split_salt[2];
return md5crypt($pw, $salt);
}
}
return md5crypt($pw);
}
/**
* @todo fix this to not throw an E_NOTICE or deprecate/remove.
* @deprecated
*/
function _pacrypt_crypt($pw, $pw_db = '')
{
if ($pw_db) {
return crypt($pw, $pw_db);
}
// PHP8 - we have to specify a salt here....
$salt = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 2);
return crypt($pw, $salt);
}
/**
* Crypt with MySQL's ENCRYPT function
*
* @param string $pw
* @param string $pw_db (hashed password)
* @return string if $pw_db and the return value match then $pw matches the original password.
*/
function _pacrypt_mysql_encrypt($pw, $pw_db = '')
{
// See https://sourceforge.net/tracker/?func=detail&atid=937966&aid=1793352&group_id=191583
// this is apparently useful for pam_mysql etc.
if ($pw_db) {
$res = db_query_one("SELECT ENCRYPT(:pw,:pw_db) as result", ['pw' => $pw, 'pw_db' => $pw_db]);
} else {
// see https://security.stackexchange.com/questions/150687/is-it-safe-to-use-the-encrypt-function-in-mysql-to-hash-passwords
// if no existing password, use a random SHA512 salt.
$salt = _php_crypt_generate_crypt_salt();
$res = db_query_one("SELECT ENCRYPT(:pw, CONCAT('$6$', '$salt')) as result", ['pw' => $pw]);
}
if (!is_string($res['result'])) {
throw new \InvalidArgumentException("Unexpected DB result");
}
return $res['result'];
}
/**
* Create/Validate courier authlib style crypt'ed passwords. (md5, md5raw, crypt, sha1)
*