-
Notifications
You must be signed in to change notification settings - Fork 2
/
functions.inc.php
2211 lines (1909 loc) · 69 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://www.postfixadmin.com or http://postfixadmin.sf.net
*
* @version $Id$
* @license GNU GPL v2 or later.
*
* File: functions.inc.php
* Contains re-usable code.
*/
$version = '2.4 develop';
/**
* 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() {
global $CONF;
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 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-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) {
global $CONF;
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
*/
function authentication_require_role($role) {
global $CONF;
// redirect to appropriate page?
if(authentication_has_role($role)) {
return True;
}
header("Location: login.php");
exit(0);
}
/**
* @return boolean TRUE if a admin, FALSE otherwise.
*/
function authentication_is_admin() {
return authentication_get_usertype() == 'admin';
}
/**
* @return boolean TRUE if a user, FALSE otherwise.
*/
function authentication_is_user() {
return authentication_get_usertype() == 'user';
}
/**
* Add an error message for display on the next page that is rendered.
* @param String/Array message(s) to show.
*
* Stores string in session. Flushed through header template.
* @see _flash_string()
*/
function flash_error($string) {
_flash_string('error', $string);
}
/**
* Used to display an info message on successful update.
* @param String/Array message(s) to show.
* Stores data in session.
* @see _flash_string()
*/
function flash_info($string) {
_flash_string('info', $string);
}
/**
* 'Private' method used for flash_info() and flash_error().
*/
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;
}
//
// check_language
// Action: checks what language the browser uses
// Call: check_language
// Parameter: $use_post - set to 0 if $_POST should NOT be read
//
function check_language ($use_post = 1) {
global $CONF;
global $supported_languages; # from languages/languages.php
$lang = $CONF['default_language'];
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$lang_array = preg_split ('/(\s*,\s*)/', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if (safecookie('lang')) {
array_unshift($lang_array, safecookie('lang')); # prefer language from cookie
}
if ( $use_post && safepost('lang')) {
array_unshift($lang_array, safepost('lang')); # but prefer $_POST['lang'] even more
}
for($i = 0; $i < count($lang_array); $i++) {
$lang_next = $lang_array[$i];
$lang_next = strtolower(trim($lang_next));
if(array_key_exists($lang_next, $supported_languages)) {
$lang = $lang_next;
break;
}
}
}
return $lang;
}
//
// language_selector
// Action: returns a language selector dropdown with the browser (or cookie) language preselected
// Call: language_selector()
//
function language_selector() {
global $supported_languages; # from languages/languages.php
$current_lang = check_language();
$selector = '<select 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;
}
//
// check_string
// Action: checks if a string is valid and returns TRUE if this is the case.
// Call: check_string (string var)
//
function check_string ($var) {
if (preg_match ('/^([A-Za-z0-9 ]+)+$/', $var)) {
return true;
} else {
return false;
}
}
//
// check_domain
// Action: Checks if domain is valid and returns TRUE if this is the case.
// Call: check_domain (string domain)
//
// TODO: make check_domain able to handle as example .local domains
function check_domain ($domain) {
global $CONF;
global $PALANG;
if (!preg_match ('/^([-0-9A-Z]+\.)+' . '([0-9A-Z]){2,6}$/i', ($domain))) {
flash_error(sprintf($PALANG['pInvalidDomainRegex'], htmlentities($domain)));
return false;
}
if (isset($CONF['emailcheck_resolve_domain']) && 'YES' == $CONF['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')) {
// AAAA (IPv6) is only available in PHP v. >= 5
if (version_compare(phpversion(), "5.0.0", ">=")) {
if (checkdnsrr($domain,'AAAA')) return true;
}
if (checkdnsrr($domain,'A')) return true;
if (checkdnsrr($domain,'MX')) return true;
flash_error(sprintf($PALANG['pInvalidDomainDNS'], htmlentities($domain)));
return false;
} else {
flash_error("emailcheck_resolve_domain is enabled, but function (checkdnsrr) missing!");
}
}
return true;
}
/**
* 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 boolean true if it's an email address, else false.
* TODO: make check_email able to handle already added domains
* TODO: don't use flash_error, use return value instead
*/
function check_email ($email) {
global $CONF;
global $PALANG;
$ce_email=$email;
//strip the vacation domain out if we are using it
//and change from blah#[email protected] to [email protected]
if ($CONF['vacation'] == 'YES') {
$vacation_domain = $CONF['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)) {
flash_error($PALANG['pInvalidMailRegex']);
return false;
}
// Determine domain name
$matches=array();
if (!preg_match('|@(.+)$|',$ce_email,$matches)) {
flash_error($PALANG['pInvalidMailRegex']);
return false;
}
$domain=$matches[1];
# check domain name
return check_domain($domain);
}
/**
* Clean a string, escaping any meta characters that could be
* used to disrupt an SQL string. i.e. "'" => "\'" etc.
*
* @param String (or Array)
* @return String (or Array) of cleaned data, suitable for use within an SQL
* statement.
*/
function escape_string ($string) {
global $CONF;
// if the string is actually an array, do a recursive cleaning.
// Note, the array keys are not cleaned.
if(is_array($string)) {
$clean = array();
foreach(array_keys($string) as $row) {
$clean[$row] = escape_string($string[$row]);
}
return $clean;
}
if (get_magic_quotes_gpc ()) {
$string = stripslashes($string);
}
if (!is_numeric($string)) {
$link = db_connect();
if ($CONF['database_type'] == "mysql") {
$escaped_string = mysql_real_escape_string($string, $link);
}
if ($CONF['database_type'] == "mysqli") {
$escaped_string = mysqli_real_escape_string($link, $string);
}
if ($CONF['database_type'] == "pgsql") {
// php 5.2+ allows for $link to be specified.
if (version_compare(phpversion(), "5.2.0", ">=")) {
$escaped_string = pg_escape_string($link, $string);
} else {
$escaped_string = pg_escape_string($string);
}
}
} else {
$escaped_string = $string;
}
return $escaped_string;
}
/**
* 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 parameter name.
* @param String (optional) - default value if key is not set.
* @return String
*/
function safeget ($param, $default="") {
$retval=$default;
if (isset($_GET[$param])) $retval=$_GET[$param];
return $retval;
}
/**
* safepost - similar to safeget()
* @see safeget()
* @param String parameter name
* @param String (optional) default value (defaults to "")
* @return String - value in $_POST[$param] or $default
* same as safeget, but for $_POST
*/
function safepost ($param, $default="") {
$retval=$default;
if (isset($_POST[$param])) $retval=$_POST[$param];
return $retval;
}
/**
* safeserver
* @see safeget()
* @param String $param
* @param String $default (optional)
* @return String value from $_SERVER[$param] or $default
*/
function safeserver ($param, $default="") {
$retval=$default;
if (isset($_SERVER[$param])) $retval=$_SERVER[$param];
return $retval;
}
/**
* safecookie
* @see safeget()
* @param String $param
* @param String $default (optional)
* @return String value from $_COOKIE[$param] or $default
*/
function safecookie ($param, $default="") {
$retval=$default;
if (isset($_COOKIE[$param])) $retval=$_COOKIE[$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 optional $options
* @param int $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(), $not_in_db=0, $dont_write_to_db=0, $select="", $extrafrom="") {
if ($PALANG_label != '') $PALANG_label = Lang::Read($PALANG_label);
if ($PALANG_desc != '') $PALANG_desc = Lang::Read($PALANG_desc );
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.
);
}
//
// get_domain_properties
// Action: Get all the properties of a domain.
// Call: get_domain_properties (string domain)
//
function get_domain_properties ($domain) {
$handler = new DomainHandler();
if (!$handler->init($domain)) {
die("Error: " . join("\n", $handler->errormsg));
}
if (!$handler->view()) {
die("Error: " . join("\n", $handler->errormsg));
}
$result = $handler->return;
return $result;
}
/**
* create_page_browser
* Action: Get page browser for a long list of mailboxes, aliases etc.
* Call: $pagebrowser = create_page_browser('table.field', 'query', 50) # replaces $param = $_GET['param']
*
* @param String idxfield - database field name to use as title
* @param String query - core part of the query (starting at "FROM")
* @return String
*/
function create_page_browser($idxfield, $querypart) {
global $CONF;
$page_size = (int) $CONF['page_size'];
$label_len = 2;
$pagebrowser = array();
if ($page_size < 2) { # will break the page browser
die('$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 ($query);
if ($result['rows'] > 0) {
$row = db_array ($result['result']);
$count_results = $row['counter'] -1; # we start counting at 0, not 1
}
# echo "<p>rows: " . ($count_results +1) . " --- $query";
if ($count_results < $page_size) {
return array(); # only one page - no pagebrowser required
}
# init row counter
$initcount = "SET @row=-1";
if ('pgsql'==$CONF['database_type']) {
$initcount = "CREATE TEMPORARY SEQUENCE rowcount MINVALUE 0";
}
$result = db_query($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, @row := @row + 1 AS row $querypart
) idx WHERE MOD(idx.row, $page_size) IN (0,$page_size_zerobase) OR idx.row = $count_results
";
if ('pgsql'==$CONF['database_type']) {
$query = "
SELECT * FROM (
SELECT $idxfield AS label, nextval('rowcount') AS row $querypart
) idx WHERE MOD(idx.row, $page_size) IN (0,$page_size_zerobase) OR idx.row = $count_results
";
}
# echo "<p>$query";
# TODO: $query is MySQL-specific
# 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 ($query);
if ($result['rows'] > 0) {
while ($row = db_array ($result['result'])) {
if ($row2 = db_array ($result['result'])) {
$label = substr($row['label'],0,$label_len) . '-' . substr($row2['label'],0,$label_len);
$pagebrowser[] = $label;
} else { # only one row remaining
$label = substr($row['label'],0,$label_len);
$pagebrowser[] = $label;
}
}
}
if ('pgsql'==$CONF['database_type']) {
db_query ("DROP SEQUENCE rowcount");
}
return $pagebrowser;
}
//
// get_mailbox_properties
// Action: Get all the properties of a mailbox.
// Call: get_mailbox_properties (string mailbox)
//
function get_mailbox_properties ($username) {
global $CONF;
global $table_mailbox;
$query="SELECT * FROM $table_mailbox WHERE username='$username'";
if ('pgsql'==$CONF['database_type']) {
$query="
SELECT
*,
EXTRACT(epoch FROM created) AS uts_created,
EXTRACT(epoch FROM modified) AS uts_modified
FROM $table_mailbox
WHERE username='$username'
";
}
$result = db_query ($query);
$row = db_array ($result['result']);
$list['name'] = $row['name'];
$list['maildir'] = $row['maildir'];
$list['quota'] = $row['quota'];
$list['domain'] = $row['domain'];
$list['created'] = $row['created'];
$list['modified'] = $row['modified'];
$list['active'] = $row['active'];
if ($CONF['database_type'] == "pgsql") {
$list['active']=('t'==$row['active']) ? 1 : 0;
$list['created']= gmstrftime('%c %Z',$row['uts_created']);
$list['modified']= gmstrftime('%c %Z',$row['uts_modified']);
} else {
$list['active'] = $row['active'];
}
return $list;
}
//
// check_quota
// Action: Checks if the user is creating a mailbox with the correct quota
// Call: check_quota (string domain)
//
# TODO: move to MailboxHandler
# TODO: merge with allowed_quota?
function check_quota ($quota, $domain, $username="") {
global $CONF;
$rval = false;
if ($CONF['quota'] == "NO") {
return true; # enforcing quotas is disabled - just allow it
}
$limit = get_domain_properties ($domain);
if ($limit['maxquota'] == 0) {
$rval = true; # maxquota unlimited -> OK, but domain level quota could still be hit
}
if (($limit['maxquota'] < 0) and ($quota < 0)) {
return true; # maxquota and $quota are both disabled -> OK, no need for more checks
}
if (($limit['maxquota'] > 0) and ($quota == 0)) {
return false; # mailbox with unlimited quota on a domain with maxquota restriction -> not allowed, no more checks needed
}
if ($limit['maxquota'] != 0 && $quota > $limit['maxquota']) {
return false; # mailbox bigger than maxquota restriction (and maxquota != unlimited) -> not allowed, no more checks needed
} else {
$rval = true; # mailbox size looks OK, but domain level quota could still be hit
}
# TODO: detailed error message ("domain quota exceeded", "mailbox quota too big" etc.) via flash_error? Or "available quota: xxx MB"?
if (!$rval || $CONF['domain_quota'] != 'YES') {
return $rval;
} elseif ($limit['quota'] <= 0) { # TODO: CHECK - 0 (unlimited) is fine, not sure about <= -1 (disabled)...
$rval = true;
} else {
$table_mailbox = table_by_key('mailbox');
$query = "SELECT SUM(quota) FROM $table_mailbox WHERE domain = '" . escape_string($domain) . "'";
if ($username != "") {
$query .= " AND username != '" . escape_string($username) . "'";
}
$result = db_query ($query);
$row = db_row ($result['result']);
$cur_quota_total = divide_quota($row[0]); # convert to MB
if ( ($quota + $cur_quota_total) > $limit['quota'] ) {
$rval = false;
} else {
$rval = true;
}
}
return $rval;
}
/**
* Get allowed maximum quota for a mailbox
* @param String $domain
* @param Integer $current_user_quota (in bytes)
* @return Integer allowed maximum quota (in MB)
*/
function allowed_quota($domain, $current_user_quota) {
$domain_properties = get_domain_properties($domain);
$tMaxquota = $domain_properties['maxquota'];
if (boolconf('domain_quota') && $domain_properties['quota']) {
$dquota = $domain_properties['quota'] - $domain_properties['total_quota'] + divide_quota($current_user_quota);
if ($dquota < $tMaxquota) {
$tMaxquota = $dquota;
}
if ($tMaxquota == 0) {
$tMaxquota = $dquota;
}
}
return $tMaxquota;
}
//
// divide_quota
// Action: Recalculates the quota from MBs to bytes (divide, /)
// Call: divide_quota (string $quota)
//
function divide_quota ($quota) {
global $CONF;
if ($quota == -1) return $quota;
$value = round($quota / $CONF['quota_multiplier'],2);
return $value;
}
//
// check_owner
// Action: Checks if the admin is the owner of the domain (or global-admin)
// Call: check_owner (string admin, string domain)
//
function check_owner ($username, $domain) {
global $table_domain_admins;
$E_username = escape_string($username);
$E_domain = escape_string($domain);
$result = db_query ("SELECT 1 FROM $table_domain_admins WHERE username='$E_username' AND (domain='$E_domain' OR domain='ALL') AND active='1'");
if ($result['rows'] == 1 || $result['rows'] == 2) { # "ALL" + specific domain permissions is possible
# TODO: if superadmin, check if given domain exists in the database
return true;
} else {
if ($result['rows'] > 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;
}
}
//
// check_alias_owner
// Action: Checks if the admin is the owner of the alias.
// Call: check_alias_owner (string admin, string alias)
//
function check_alias_owner ($username, $alias) {
global $CONF;
if (authentication_has_role('global-admin')) return true;
$tmp = preg_split('/\@/', $alias);
if (($CONF['special_alias_control'] == 'NO') && array_key_exists($tmp[0], $CONF['default_aliases'])) {
return false;
} else {
return true;
}
}
/**
* List domains for an admin user.
* @param String $username
* @return array of domain names.
*/
function list_domains_for_admin ($username) {
global $CONF;
global $table_domain, $table_domain_admins;
$E_username = escape_string($username);
$query = "SELECT $table_domain.domain FROM $table_domain ";
$condition[] = "$table_domain.domain != 'ALL'";
$result = db_query ("SELECT username FROM $table_domain_admins WHERE username='$E_username' AND domain='ALL'");
if ($result['rows'] < 1) { # not a superadmin
$query .= " LEFT JOIN $table_domain_admins ON $table_domain.domain=$table_domain_admins.domain ";
$condition[] = "$table_domain_admins.username='$E_username' ";
$condition[] = "$table_domain.active='" . db_get_boolean(true) . "'"; # TODO: does it really make sense to exclude inactive...
$condition[] = "$table_domain.backupmx='" . db_get_boolean(False) . "'"; # TODO: ... and backupmx domains for non-superadmins?
}
$query .= " WHERE " . join(' AND ', $condition);
$query .= " ORDER BY $table_domain.domain";
$list = array ();
$result = db_query ($query);
if ($result['rows'] > 0) {
$i = 0;
while ($row = db_array ($result['result'])) {
$list[$i] = $row['domain'];
$i++;
}
}
return $list;
}
//
// list_domains
// Action: List all available domains.
// Call: list_domains ()
//
function list_domains () {
global $table_domain;
$list = array();
$result = db_query ("SELECT domain FROM $table_domain WHERE domain!='ALL' ORDER BY domain");
if ($result['rows'] > 0) {
$i = 0;
while ($row = db_array ($result['result'])) {
$list[$i] = $row['domain'];
$i++;
}
}
return $list;
}
//
// admin_exist
// Action: Checks if the admin already exists.
// Call: admin_exist (string admin)
//
function admin_exist ($username) {
$result = db_query ("SELECT 1 FROM " . table_by_key ('admin') . " WHERE username='$username'");
if ($result['rows'] != 1) {
return false;
} else {
return true;
}
}
//
// domain_exist
// Action: Checks if the domain already exists.
// Call: domain_exist (string domain)
//
function domain_exist ($domain) {
global $table_domain;
$result = db_query("SELECT 1 FROM $table_domain WHERE domain='$domain'");
if ($result['rows'] != 1) {
return false;
} else {
return true;
}
}
//
// list_admins
// Action: Lists all the admins
// Call: list_admins ()
//
// was admin_list_admins
//
function list_admins () {
$handler = new AdminHandler();
if ($handler->getList('1=1')) {
$list = $handler->result();
} else {
$list = array();
# TODO: check if there was an error or simply no admins (which shouldn't happen because nobody could login then...)
}
return $list;
}
//
// 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_password
// Action: Generates a random password
// Call: generate_password ()
//
function generate_password () {
global $CONF;
// length of the generated password
$length = 8;
// 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) {
// pick a random character from the possible ones
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
// we don't want this character if it's already in the password
if (!strstr($password, $char)) {
$password .= $char;
}
}
return $password;
}
/**