-
Notifications
You must be signed in to change notification settings - Fork 119
/
Client.php
586 lines (517 loc) · 19.4 KB
/
Client.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
<?php
/**
* i-MSCP - internet Multi Server Control Panel
* Copyright (C) 2010-2017 by i-MSCP Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* Returns total number of subdomains that belong to a specific domain
*
* Note, this function doesn't make any differentiation between sub domains and the
* aliasses subdomains. The result is simply the sum of both.
*
* @param int $domain_id Domain unique identifier
* @return int Total number of subdomains
*/
function get_domain_running_sub_cnt($domain_id)
{
$stmt = exec_query('SELECT COUNT(*) AS cnt FROM subdomain WHERE domain_id = ?', $domain_id);
$row = $stmt->fetchRow();
$subdomainCount = $row['cnt'];
$stmt = exec_query(
'
SELECT COUNT(subdomain_alias_id) AS cnt FROM subdomain_alias
WHERE alias_id IN (SELECT alias_id FROM domain_aliasses WHERE domain_id = ?)
',
$domain_id
);
$row = $stmt->fetchRow();
$subdomainCount += $row['cnt'];
return $subdomainCount;
}
/**
* Returns number of domain aliases that belong to a specific domain
*
* @param int $domain_id Domain unique identifier
* @return int Total number of domain aliases
*/
function get_domain_running_als_cnt($domain_id)
{
$stmt = exec_query(
'SELECT COUNT(alias_id) AS cnt FROM domain_aliasses WHERE domain_id = ? AND alias_status != ?',
array($domain_id, 'ordered')
);
return $stmt->fields['cnt'];
}
/**
* Returns information about number of mail account for a specific domain
*
* @param int $domainId Domain unique identifier
* @return array An array of values where the first item is the sum of all other items, and where each other item
* represents total number of a specific Mail account type
*/
function get_domain_running_mail_acc_cnt($domainId)
{
$cfg = iMSCP_Registry::get('config');
$query = "
SELECT COUNT(mail_id) AS cnt FROM mail_users WHERE mail_type RLIKE ? AND mail_type NOT LIKE ? AND domain_id = ?
";
if ($cfg['COUNT_DEFAULT_EMAIL_ADDRESSES'] == 0) {
$query .= " AND mail_acc != 'abuse' AND mail_acc != 'postmaster' AND mail_acc != 'webmaster' ";
}
$stmt = exec_query($query, array('normal_', 'normal_catchall', $domainId));
$dmnMailAcc = $stmt->fields['cnt'];
$stmt = exec_query($query, array('alias_', 'alias_catchall', $domainId));
$alsMailAcc = $stmt->fields['cnt'];
$stmt = exec_query($query, array('subdom_', 'subdom_catchall', $domainId));
$subMailAcc = $stmt->fields['cnt'];
$stmt = exec_query($query, array('alssub_', 'alssub_catchall', $domainId));
$alssubMailAcc = $stmt->fields['cnt'];
return array(
$dmnMailAcc + $alsMailAcc + $subMailAcc + $alssubMailAcc, $dmnMailAcc, $alsMailAcc, $subMailAcc, $alssubMailAcc
);
}
/**
* Returns total number of Ftp account owned by the given customer
*
* @param int $customerId Customer unique identifier
* @return int Number of Ftp account owned by the given customer
*/
function get_customer_running_ftp_acc_cnt($customerId)
{
$stmt = exec_query('SELECT COUNT(userid) AS cnt FROM ftp_users WHERE admin_id = ?', $customerId);
return $stmt->fields['cnt'];
}
/**
* Returns total number of databases that belong to a specific domain
*
* @param int $domainId Domain unique identifier
* @return int Total number of databases for a specific domain
*/
function get_domain_running_sqld_acc_cnt($domainId)
{
$stmt = exec_query('SELECT COUNT(*) AS cnt FROM sql_database WHERE domain_id = ?', $domainId);
return $stmt->fields['cnt'];
}
/**
* Returns total number of SQL user that belong to a specific domain
*
* @param int $domainId Domain unique identifier
* @return int Total number of SQL users for a specific domain
*/
function get_domain_running_sqlu_acc_cnt($domainId)
{
$stmt = exec_query(
'SELECT DISTINCT sqlu_name FROM sql_user INNER JOIN sql_database USING(sqld_id) WHERE domain_id = ?',
$domainId
);
return $stmt->rowCount();
}
/**
* Returns both total number of database and SQL user that belong to a specific domain
*
* @param int $domainId Domain unique identifier
* @return array An array where the first item is the Database total number, and the second the SQL users total number.
*/
function get_domain_running_sql_acc_cnt($domainId)
{
return array(get_domain_running_sqld_acc_cnt($domainId), get_domain_running_sqlu_acc_cnt($domainId));
}
/**
* Get domain limit properties
*
* @param int $domainId Domain unique identifier
* @return array
*/
function get_domain_running_props_cnt($domainId)
{
$subCount = get_domain_running_sub_cnt($domainId);
$alsCount = get_domain_running_als_cnt($domainId);
list($mailAccCount) = get_domain_running_mail_acc_cnt($domainId);
// Transitional query - Will be removed asap
$stmt = exec_query('SELECT domain_admin_id FROM domain WHERE domain_id = ?', $domainId);
$ftpAccCount = get_customer_running_ftp_acc_cnt($stmt->fields['domain_admin_id']);
list($sqlDbCount, $sqlUserCount) = get_domain_running_sql_acc_cnt($domainId);
return array($subCount, $alsCount, $mailAccCount, $ftpAccCount, $sqlDbCount, $sqlUserCount);
}
/**
* Translate mail type
*
* @param string $mailType
* @return string Translated mail type
*/
function user_trans_mail_type($mailType)
{
switch ($mailType) {
case MT_NORMAL_MAIL:
return tr('Domain mail');
case MT_NORMAL_FORWARD:
return tr('Email forward');
case MT_ALIAS_MAIL:
return tr('Alias mail');
case MT_ALIAS_FORWARD:
return tr('Alias forward');
case MT_SUBDOM_MAIL:
return tr('Subdomain mail');
case MT_SUBDOM_FORWARD:
return tr('Subdomain forward');
case MT_ALSSUB_MAIL:
return tr('Alias subdomain mail');
case MT_ALSSUB_FORWARD:
return tr('Alias subdomain forward');
case MT_NORMAL_CATCHALL:
return tr('Domain mail');
case MT_ALIAS_CATCHALL:
return tr('Domain mail');
default:
return tr('Unknown type.');
}
}
/**
* Checks if an user has permissions on a specific SQL user
*
* @param int $sqlUserId SQL user unique identifier
* @return bool TRUE if the logged in user has permission on SQL user, FALSE otherwise
*/
function check_user_sql_perms($sqlUserId)
{
return (who_owns_this($sqlUserId, 'sqlu_id') == $_SESSION['user_id']);
}
/**
* Returns translated gender code
*
* @param string $code Gender code to be returned
* @param bool $nullOnBad Tells whether or not null must be returned on unknow $code
* @return null|string Translated gender or null in some circonstances.
*/
function get_gender_by_code($code, $nullOnBad = false)
{
switch (strtolower($code)) {
case 'm':
case 'M':
return tr('Male');
case 'f':
case 'F':
return tr('Female');
default:
return !$nullOnBad ? tr('Unknown') : null;
}
}
/**
* Tells whether or not the current customer can access to the given feature(s)
*
* @throws iMSCP_Exception When $featureName is not known
* @param array|string $featureNames Feature name(s) (insensitive case)
* @param bool $forceReload If true force data to be reloaded
* @return bool TRUE if $featureName is available for customer, FALSE otherwise
*/
function customerHasFeature($featureNames, $forceReload = false)
{
static $availableFeatures = null;
static $debug = false;
if (null === $availableFeatures || $forceReload) {
$cfg = iMSCP_Registry::get('config');
$debug = (bool)$cfg['DEBUG'];
$dmnProps = get_domain_default_props($_SESSION['user_id']);
$availableFeatures = array(
/*'domain' => ($dmnProps['domain_alias_limit'] != '-1'
|| $dmnProps['domain_subd_limit'] != '-1'
|| $dmnProps['domain_dns'] == 'yes'
|| $dmnProps['phpini_perm_system'] == 'yes'
|| $cfg['ENABLE_SSL']) ? true : false,
*/
'external_mail' => ($dmnProps['domain_external_mail'] == 'yes') ? true : false,
'php' => ($dmnProps['domain_php'] == 'yes') ? true : false,
'php_editor' => $dmnProps['phpini_perm_system'] == 'yes'
&& $dmnProps['phpini_perm_allow_url_fopen'] == 'yes'
|| $dmnProps['phpini_perm_display_errors'] == 'yes'
|| in_array($dmnProps['phpini_perm_disable_functions'], array('yes', 'exec')) ? true : false,
'cgi' => $dmnProps['domain_cgi'] == 'yes' ? true : false,
'ftp' => $dmnProps['domain_ftpacc_limit'] != '-1' ? true : false,
'sql' => $dmnProps['domain_sqld_limit'] != '-1' ? true : false,
'mail' => $dmnProps['domain_mailacc_limit'] != '-1' ? true : false,
'subdomains' => $dmnProps['domain_subd_limit'] != '-1' ? true : false,
'domain_aliases' => $dmnProps['domain_alias_limit'] != '-1' ? true : false,
'custom_dns_records' => $dmnProps['domain_dns'] != 'no' && $cfg['NAMED_SERVER'] != 'external_server' ? true : false,
'webstats' => $cfg['WEBSTATS_PACKAGES'] != 'No' ? true : false,
'backup' => $cfg['BACKUP_DOMAINS'] != 'no' && $dmnProps['allowbackup'] != '' ? true : false,
'protected_areas' => true,
'custom_error_pages' => true,
'aps' => $dmnProps['domain_software_allowed'] != 'no' && $dmnProps['domain_ftpacc_limit'] != '-1' ? true : false,
'ssl' => $cfg['ENABLE_SSL'] ? true : false
);
if ($cfg['IMSCP_SUPPORT_SYSTEM']) {
$stmt = exec_query('SELECT support_system FROM reseller_props WHERE reseller_id = ?', $_SESSION['user_created_by']);
$row = $stmt->fetchRow(PDO::FETCH_ASSOC);
$availableFeatures['support'] = ($row['support_system'] == 'yes') ? true : false;
} else {
$availableFeatures['support'] = false;
}
}
$canAccess = true;
foreach ((array)$featureNames as $featureName) {
$featureName = strtolower($featureName);
if ($debug && !array_key_exists($featureName, $availableFeatures)) {
throw new iMSCP_Exception(sprintf("Feature %s is not known by the customerHasFeature() function.", $featureName));
}
if (!$availableFeatures[$featureName]) {
$canAccess = false;
break;
}
}
return $canAccess;
}
/**
* Tells whether or not the current customer can access the mail or external mail feature.
* @return bool
*/
function customerHasMailOrExtMailFeatures()
{
return (customerHasFeature('mail') || customerHasFeature('external_mail'));
}
/**
* Does the given customer is the owner of the given domain?
*
* @param string $domainName Domain name (dmn,sub,als,alssub)
* @param int $customerId Customer unique identifier
* @return bool TRUE if the given customer is the owner of the given domain, FALSE otherwise
* TODO add admin_id as foreign key in all domain tables too avoid too many jointures
*/
function customerHasDomain($domainName, $customerId)
{
$domainName = encode_idna($domainName);
// Check in domain table
$stmt = exec_query(
"SELECT 'found' FROM domain WHERE domain_admin_id = ? AND domain_name = ?", array($customerId, $domainName)
);
if ($stmt->rowCount()) {
return true;
}
// Check in domain_aliasses table
$stmt = exec_query(
"
SELECT 'found' FROM domain AS t1
INNER JOIN domain_aliasses AS t2 ON(t2.domain_id = t1.domain_id)
WHERE t1.domain_admin_id = ?
AND t2.alias_name = ?
",
array($customerId, $domainName)
);
if ($stmt->rowCount()) {
return true;
}
// Check in subdomain table
$stmt = exec_query(
"
SELECT 'found' FROM domain AS t1
INNER JOIN subdomain AS t2 ON (t2.domain_id = t1.domain_id)
WHERE t1.domain_admin_id = ? AND CONCAT(t2.subdomain_name, '.', t1.domain_name) = ?
",
array($customerId, $domainName)
);
if ($stmt->rowCount()) {
return true;
}
// Check in subdomain_alias table
$stmt = exec_query(
"
SELECT 'found' FROM domain AS t1
INNER JOIN domain_aliasses AS t2 ON(t2.domain_id = t1.domain_id)
INNER JOIN subdomain_alias AS t3 ON(t3.alias_id = t2.alias_id)
WHERE t1.domain_admin_id = ? AND CONCAT(t3.subdomain_alias_name, '.', t2.alias_name) = ?
",
array($customerId, $domainName)
);
if ($stmt->rowCount()) {
return true;
}
return false;
}
/**
* Delete all autoreplies log for which not mail address is found in the mail_users database table
*
* @return void
*/
function delete_autoreplies_log_entries()
{
exec_query("DELETE FROM autoreplies_log WHERE `from` NOT IN (SELECT mail_addr FROM mail_users)");
}
/**
* Get mount points
*
* @throws iMSCP_Exception_Database
* @param int $domainId Main domain unique identifier
* @return array List of mount points
*/
function getMountpoints($domainId)
{
static $mountpoints = array();
if (empty($mountpoints)) {
$stmt = exec_query(
'
SELECT subdomain_mount AS mount_point FROM subdomain WHERE domain_id = ?
UNION ALL
SELECT alias_mount AS mount_point FROM domain_aliasses WHERE domain_id = ?
UNION ALL
SELECT subdomain_alias_mount AS mount_point FROM subdomain_alias
INNER JOIN domain_aliasses USING(alias_id) WHERE domain_id = ?
',
array($domainId, $domainId, $domainId)
);
if ($stmt->rowCount()) {
$mountpoints = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
array_unshift($mountpoints, '/'); // main domain mount point
}
return $mountpoints;
}
/**
* Get mount point and document root for the given domain
*
* @throws iMSCP_Exception
* @param int $domainId Domain unique identifier
* @param string $domainType Domain type (dmn,als,sub,alssub)
* @param int $ownerId Domain owner unique identifier
* @return array Array containing domain mount point and document root
*/
function getDomainMountpoint($domainId, $domainType, $ownerId)
{
switch ($domainType) {
case 'dmn':
$query = "SELECT '/' AS mount_point, document_root FROM domain WHERE domain_id = ? AND domain_admin_id = ?";
break;
case 'sub':
$query = '
SELECT subdomain_mount AS mount_point, subdomain_document_root AS document_root
FROM subdomain
INNER JOIN domain USING(domain_id)
WHERE subdomain_id = ?
AND domain_admin_id = ?
';
break;
case 'als':
$query = '
SELECT alias_mount AS mount_point, alias_document_root AS document_root
FROM domain_aliasses
INNER JOIN domain USING(domain_id)
WHERE alias_id = ?
AND domain_admin_id = ?
';
break;
case 'alssub':
$query = '
SELECT subdomain_alias_mount AS mount_point, subdomain_alias_document_root AS document_root
FROM subdomain_alias
INNER JOIN domain_aliasses USING(alias_id)
INNER JOIN domain USING(domain_id)
WHERE subdomain_alias_id = ?
AND domain_admin_id = ?
';
break;
default:
throw new iMSCP_Exception('Unknown domain type');
}
$stmt = exec_query($query, array($domainId, $ownerId));
if (!$stmt->rowCount()) {
throw new iMSCP_Exception('Could not find domain data');
}
return $stmt->fetchRow(PDO::FETCH_NUM);
}
/**
* Send alias order email
*
* @param string $aliasName
* @return bool TRUE on success, FALSE on failure
*/
function send_alias_order_email($aliasName)
{
$userId = $_SESSION['user_id'];
$resellerId = who_owns_this($userId, 'user');
$stmt = exec_query('SELECT admin_name, fname, lname, email FROM admin WHERE admin_id = ?', $userId);
$row = $stmt->fetchRow();
$data = get_alias_order_email($resellerId);
$ret = send_mail(array(
'mail_id' => 'alias-order-msg',
'fname' => $row['fname'],
'lname' => $row['lname'],
'username' => $row['admin_name'],
'email' => $row['email'],
'subject' => $data['subject'],
'message' => $data['message'],
'placeholders' => array(
'{CUSTOMER}' => decode_idna($row['admin_name']),
'{ALIAS}' => $aliasName
)
));
if (!$ret) {
write_log(sprintf('Could not send alias order to %s', $row['admin_name']), E_USER_ERROR);
return false;
}
return true;
}
/**
* Parse data from the given maildirsize file
*
* Because processing several maildirsize files can be time consuming, the data are stored in session for next 5 minutes.
* It is possible to force update by changing the $refreshData flag valye to TRUE
*
* @see http://www.courier-mta.org/imap/README.maildirquota.html
* @param string $maildirsizeFilePath
* @param bool $refreshData Flag indicating if data must be refreshed
* @return array|bool Array containing maildirsize data, FALSE on failure
*/
function parseMaildirsize($maildirsizeFilePath, $refreshData = FALSE)
{
if (!$refreshData && !empty($_SESSION['maildirsize'][$maildirsizeFilePath])
&& $_SESSION['maildirsize']['TIMESTAMP'] < (time() + 300)
) {
return $_SESSION['maildirsize'][$maildirsizeFilePath];
}
$fh = @fopen($maildirsizeFilePath, 'r');
if (!$fh) {
return false;
}
$_SESSION['maildirsize'][$maildirsizeFilePath] = array(
'QUOTA_BYTES' => 0,
'QUOTA_MESSAGES' => 0,
'BYTE_COUNT' => 0,
'FILE_COUNT' => 0
);
$firstLine = 1;
while (($line = fgets($fh)) !== false) {
if ($firstLine) { # Parse quota definition
list($quotaBytes, $quotaMessages) = explode(',', $line);
if (($quotaBytes) && preg_match('/(\d+)S/i', $quotaBytes, $m)) {
$_SESSION['maildirsize'][$maildirsizeFilePath]['QUOTA_BYTES'] = $m[1];
} else {
break; # No quota data, skipping...
}
if ($quotaMessages && preg_match('/(\d+)C/i', $quotaMessages, $m)) {
$_SESSION['maildirsize'][$maildirsizeFilePath]['QUOTA_MESSAGES'] = $m[1];
}
$firstLine = 0;
continue;
}
# Parse byte count and file count
if (preg_match('/^\s*(-?\d+)\s+(-?\d+)\s*$/', $line, $m)) {
$_SESSION['maildirsize'][$maildirsizeFilePath]['BYTE_COUNT'] += $m[1];
$_SESSION['maildirsize'][$maildirsizeFilePath]['FILE_COUNT'] += $m[2];
}
}
fclose($fh);
$_SESSION['maildirsize'][$maildirsizeFilePath]['TIMESTAMP'] = time();
return $_SESSION['maildirsize'];
}