/** * Activate OpenDKIM for the given customer * * @throws DatabaseException * @param int $customerId Customer unique identifier */ function opendkim_activate($customerId) { $stmt = exec_query(' SELECT domain_id, domain_name FROM domain INNER JOIN admin ON(admin_id = domain_admin_id) WHERE admin_id = ? AND created_by = ? AND admin_status = ? ', array($customerId, $_SESSION['user_id'], 'ok')); if ($stmt->rowCount()) { $row = $stmt->fetchRow(PDO::FETCH_ASSOC); $db = Database::getInstance(); try { $db->beginTransaction(); exec_query('INSERT INTO opendkim (admin_id, domain_id, domain_name, opendkim_status) VALUES (?, ?, ?, ?)', array($customerId, $row['domain_id'], $row['domain_name'], 'toadd')); exec_query(' INSERT INTO opendkim (admin_id, domain_id, alias_id, domain_name, opendkim_status) SELECT ?, domain_id, alias_id, alias_name, ? FROM domain_aliasses WHERE domain_id = ? AND alias_status = ? ', array($customerId, 'toadd', $row['domain_id'], 'ok')); $db->commit(); send_request(); set_page_message(tr('OpenDKIM support scheduled for activation. This can take few seconds.'), 'success'); } catch (DatabaseException $e) { $db->rollBack(); throw $e; } } else { showBadRequestErrorPage(); } }
/** * Activate autoresponder of the given mail account with the given autoreponder message * * @param int $mailAccountId Mail account id * @param string $autoresponderMessage Auto-responder message * @return void */ function client_ActivateAutoresponder($mailAccountId, $autoresponderMessage) { $autoresponderMessage = clean_input($autoresponderMessage); if ($autoresponderMessage == '') { set_page_message(tr('Auto-responder message cannot be empty.'), 'error'); redirectTo("mail_autoresponder_enable.php?mail_account_id={$mailAccountId}"); } else { $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); $query = "SELECT `mail_addr` FROM `mail_users` WHERE `mail_id` = ?"; $stmt = exec_query($query, $mailAccountId); $query = ' UPDATE `mail_users` SET `status` = ?, `mail_auto_respond` = ?, `mail_auto_respond_text` = ? WHERE `mail_id` = ? '; exec_query($query, array('tochange', 1, $autoresponderMessage, $mailAccountId)); // Purge autoreplies log entries delete_autoreplies_log_entries(); $db->commit(); // Ask iMSCP daemon to trigger engine dispatcher send_request(); write_log(sprintf("%s: activated auto-responder for the '%s' mail account", $_SESSION['user_logged'], $stmt->fields['mail_addr']), E_USER_NOTICE); set_page_message(tr('Auto-responder successfully scheduled for activation.'), 'success'); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); throw $e; } } }
/** * onAfterAddDomainAlias listener * * @throws iMSCP_Exception * @throws iMSCP_Exception_Database * @param iMSCP_Events_Event $event * @throws Exception */ public function onAfterAddDomainAlias(iMSCP_Events_Event $event) { $userIdentity = iMSCP_Authentication::getInstance()->getIdentity(); if ($userIdentity->admin_type == 'user') { $disallowedDomains = (array) $this->getConfigParam('ignored_domains', array()); $domainAliasNameAscii = $event->getParam('domainAliasName'); # Only domain aliases which are not listed in the ignored_domains list are auto-approved if (!in_array(decode_idna($domainAliasNameAscii), $disallowedDomains)) { $username = decode_idna($userIdentity->admin_name); $approvalRule = $this->getConfigParam('approval_rule', true); $userAccounts = (array) $this->getConfigParam('user_accounts', array()); if ($approvalRule) { # Only domain aliases added by user accounts which are listed in the user_accounts list are # auto-approved if (!in_array($username, $userAccounts)) { $username = false; } } elseif (in_array($username, $userAccounts)) { # Only domain aliases added by user accounts which are not listed in the user_accounts list are # auto-approved $username = false; } if ($username !== false) { $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); $domainAliasId = $event->getParam('domainAliasId'); exec_query('UPDATE domain_aliasses SET alias_status = ? WHERE alias_id = ?', array('toadd', $domainAliasId)); if (iMSCP_Registry::get('config')->CREATE_DEFAULT_EMAIL_ADDRESSES) { if ($userIdentity->email) { client_mail_add_default_accounts(get_user_domain_id($userIdentity->admin_id), $userIdentity->email, $domainAliasNameAscii, 'alias', $domainAliasId); } } $db->commit(); send_request(); $domainAliasName = decode_idna($domainAliasNameAscii); $username = decode_idna($username); write_log(sprintf('DomainAutoApproval: The %s domain alias has been auto-approved', $domainAliasName), E_USER_NOTICE); write_log(sprintf('DomainAutoApproval: %s scheduled addition of domain alias: %s', $username, $domainAliasName), E_USER_NOTICE); set_page_message(tr('Domain alias successfully scheduled for addition.'), 'success'); redirectTo('domains_manage.php'); } catch (iMSCP_Exception $e) { $db->rollBack(); throw $e; } } } } }
/** * Deactivate autoresponder of the given mail account * * @param int $mailAccountId Mail account id * @return void */ function client_deactivateAutoresponder($mailAccountId) { $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); $query = "SELECT `mail_addr` FROM `mail_users` WHERE `mail_id` = ?"; $stmt = exec_query($query, $mailAccountId); $query = "UPDATE `mail_users` SET `status` = ?, `mail_auto_respond` = ? WHERE `mail_id` = ?"; exec_query($query, array('tochange', 0, $mailAccountId)); // Purge autoreplies log entries delete_autoreplies_log_entries(); $db->commit(); // Ask iMSCP daemon to trigger engine dispatcher send_request(); write_log(sprintf("%s: deactivated auto-responder for the '%s' mail account", $_SESSION['user_logged'], $stmt->fields['mail_addr']), E_USER_NOTICE); set_page_message(tr('Auto-responder successfully scheduled for deactivation.'), 'success'); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); throw $e; } }
/** * onAfterAddDomainAlias listener * * @throws iMSCP_Exception * @throws iMSCP_Exception_Database * @param iMSCP_Events_Event $event * @throws Exception * @return void */ public function onAfterAddDomainAlias(iMSCP_Events_Event $event) { $userIdentity = iMSCP_Authentication::getInstance()->getIdentity(); // 1. Do not act if the logged-in user is not the real client (due to changes in i-MSCP v1.2.12) // 2. Do not act if the event has been triggered from reseller interface if (isset($_SESSION['logged_from_type']) || $userIdentity->admin_type == 'reseller') { return; } $disallowedDomains = (array) $this->getConfigParam('ignored_domains', array()); $domainAliasNameAscii = $event->getParam('domainAliasName'); if (in_array(decode_idna($domainAliasNameAscii), $disallowedDomains)) { return; # Only domain aliases which are not listed in the ignored_domains list are auto-approved } $username = decode_idna($userIdentity->admin_name); $approvalRule = $this->getConfigParam('approval_rule', true); $userAccounts = (array) $this->getConfigParam('user_accounts', array()); # 1. Only domain aliases added by user which are listed in the 'user_accounts' list are auto-approved # 2. Only domain aliases added by user which are not listed in the 'user_accounts' list are auto-approved if ($approvalRule && !in_array($username, $userAccounts) || in_array($username, $userAccounts)) { return; } $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); $domainAliasId = $event->getParam('domainAliasId'); exec_query('UPDATE domain_aliasses SET alias_status = ? WHERE alias_id = ?', array('toadd', $domainAliasId)); $config = iMSCP_Registry::get('config'); if ($config['CREATE_DEFAULT_EMAIL_ADDRESSES'] && $userIdentity->email !== '') { client_mail_add_default_accounts(get_user_domain_id($userIdentity->admin_id), $userIdentity->email, $domainAliasNameAscii, 'alias', $domainAliasId); } $db->commit(); send_request(); write_log(sprintf('DomainAutoApproval plugin: The `%s` domain alias has been auto-approved', decode_idna($domainAliasNameAscii)), E_USER_NOTICE); set_page_message(tr('Domain alias auto-approved.'), 'success'); } catch (iMSCP_Exception $e) { $db->rollBack(); throw $e; } }
/** * Check and updates reseller data * * @throws iMSCP_Exception_Database * @param int $resellerId Reseller unique identifier * @return bool TRUE on success, FALSE otherwise */ function admin_checkAndUpdateData($resellerId) { iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditUser, array('userId' => $resellerId)); $errFieldsStack = array(); $data =& admin_getData($resellerId, true); $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); // check for password (if needed) if ($data['password'] !== '' && $data['pasword_confirmation'] !== '') { if ($data['password'] !== $data['password_confirmation']) { set_page_message(tr('Passwords do not match.'), 'error'); } checkPasswordSyntax($data['password']); if (Zend_Session::namespaceIsset('pageMessages')) { $errFieldsStack[] = 'password'; $errFieldsStack[] = 'password_confirmation'; } } // Check for email address if (!chk_email($data['email'])) { set_page_message(tr('Incorrect syntax for email address.'), 'error'); $errFieldsStack[] = 'email'; } // Check for ip addresses $resellerIps = array(); foreach ($data['server_ips'] as $serverIpData) { if (in_array($serverIpData['ip_id'], $data['reseller_ips'], true)) { $resellerIps[] = $serverIpData['ip_id']; } } $resellerIps = array_unique(array_merge($resellerIps, $data['used_ips'])); sort($resellerIps); if (empty($resellerIps)) { set_page_message(tr('You must assign at least one IP to this reseller.'), 'error'); } // Check for max domains limit if (imscp_limit_check($data['max_dmn_cnt'], null)) { $rs = admin_checkResellerLimit($data['max_dmn_cnt'], $data['current_dmn_cnt'], $data['nbDomains'], '0', tr('domains')); } else { set_page_message(tr('Incorrect limit for %s.', tr('domain')), 'error'); $rs = false; } if (!$rs) { $errFieldsStack[] = 'max_dmn_cnt'; } // Check for max subdomains limit if (imscp_limit_check($data['max_sub_cnt'])) { $rs = admin_checkResellerLimit($data['max_sub_cnt'], $data['current_sub_cnt'], $data['nbSubdomains'], $data['unlimitedSubdomains'], tr('subdomains')); } else { set_page_message(tr('Incorrect limit for %s.', tr('subdomains')), 'error'); $rs = false; } if (!$rs) { $errFieldsStack[] = 'max_sub_cnt'; } // check for max domain aliases limit if (imscp_limit_check($data['max_als_cnt'])) { $rs = admin_checkResellerLimit($data['max_als_cnt'], $data['current_als_cnt'], $data['nbDomainAliases'], $data['unlimitedDomainAliases'], tr('domain aliases')); } else { set_page_message(tr('Incorrect limit for %s.', tr('domain aliases')), 'error'); $rs = false; } if (!$rs) { $errFieldsStack[] = 'max_als_cnt'; } // Check for max mail accounts limit if (imscp_limit_check($data['max_mail_cnt'])) { $rs = admin_checkResellerLimit($data['max_mail_cnt'], $data['current_mail_cnt'], $data['nbMailAccounts'], $data['unlimitedMailAccounts'], tr('mail')); } else { set_page_message(tr('Incorrect limit for %s.', tr('email accounts')), 'error'); $rs = false; } if (!$rs) { $errFieldsStack[] = 'max_mail_cnt'; } // Check for max ftp accounts limit if (imscp_limit_check($data['max_ftp_cnt'])) { $rs = admin_checkResellerLimit($data['max_ftp_cnt'], $data['current_ftp_cnt'], $data['nbFtpAccounts'], $data['unlimitedFtpAccounts'], tr('Ftp')); } else { set_page_message(tr('Incorrect limit for %s.', tr('Ftp accounts')), 'error'); $rs = false; } if (!$rs) { $errFieldsStack[] = 'max_ftp_cnt'; } // Check for max Sql databases limit if (!($rs = imscp_limit_check($data['max_sql_db_cnt']))) { set_page_message(tr('Incorrect limit for %s.', tr('SQL databases')), 'error'); } elseif ($data['max_sql_db_cnt'] == -1 && $data['max_sql_user_cnt'] != -1) { set_page_message(tr('SQL database limit is disabled but SQL user limit is not.'), 'error'); $rs = false; } else { $rs = admin_checkResellerLimit($data['max_sql_db_cnt'], $data['current_sql_db_cnt'], $data['nbSqlDatabases'], $data['unlimitedSqlDatabases'], tr('SQL databases')); } if (!$rs) { $errFieldsStack[] = 'max_sql_db_cnt'; } // Check for max Sql users limit if (!($rs = imscp_limit_check($data['max_sql_user_cnt']))) { set_page_message(tr('Incorrect limit for %s.', tr('SQL users')), 'error'); } elseif ($data['max_sql_db_cnt'] != -1 && $data['max_sql_user_cnt'] == -1) { set_page_message(tr('SQL user limit is disabled but SQL database limit is not.'), 'error'); $rs = false; } else { $rs = admin_checkResellerLimit($data['max_sql_user_cnt'], $data['current_sql_user_cnt'], $data['nbSqlUsers'], $data['unlimitedSqlUsers'], tr('SQL users')); } if (!$rs) { $errFieldsStack[] = 'max_sql_user_cnt'; } // Check for max monthly traffic limit if (imscp_limit_check($data['max_traff_amnt'], null)) { $rs = admin_checkResellerLimit($data['max_traff_amnt'], $data['current_traff_amnt'], $data['totalTraffic'] / 1048576, $data['unlimitedTraffic'], tr('traffic')); } else { set_page_message(tr('Incorrect limit for %s.', tr('traffic')), 'error'); $rs = false; } if (!$rs) { $errFieldsStack[] = 'max_traff_amnt'; } // Check for max disk space limit if (imscp_limit_check($data['max_disk_amnt'], null)) { $rs = admin_checkResellerLimit($data['max_disk_amnt'], $data['current_disk_amnt'], $data['totalDiskspace'] / 1048576, $data['unlimitedDiskspace'], tr('disk space')); } else { set_page_message(tr('Incorrect limit for %s.', tr('disk space')), 'error'); $rs = false; } if (!$rs) { $errFieldsStack[] = 'max_disk_amnt'; } $needDaemonRequest = false; // Check for PHP settings $phpini = iMSCP_PHPini::getInstance(); $resellerPhpPermissions = $phpini->getResellerPermission(); $phpini->setResellerPermission('phpiniSystem', $data['php_ini_system']); if ($phpini->resellerHasPermission('phpiniSystem')) { // We are safe here; If a value is not valid, previous value is used $phpini->setResellerPermission('phpiniDisableFunctions', $data['php_ini_al_disable_functions']); $phpini->setResellerPermission('phpiniMailFunction', $data['php_ini_al_mail_function']); $phpini->setResellerPermission('phpiniAllowUrlFopen', $data['php_ini_al_allow_url_fopen']); $phpini->setResellerPermission('phpiniDisplayErrors', $data['php_ini_al_display_errors']); $phpini->setResellerPermission('phpiniMemoryLimit', $data['memory_limit']); // Must be set before phpiniPostMaxSize $phpini->setResellerPermission('phpiniPostMaxSize', $data['post_max_size']); // Must be set before phpiniUploadMaxFileSize $phpini->setResellerPermission('phpiniUploadMaxFileSize', $data['upload_max_filesize']); $phpini->setResellerPermission('phpiniMaxExecutionTime', $data['max_execution_time']); $phpini->setResellerPermission('phpiniMaxInputTime', $data['max_input_time']); } else { $phpini->loadResellerPermissions(); // Reset reseller PHP permissions to default values } if (array_diff_assoc($resellerPhpPermissions, $phpini->getResellerPermission())) { // A least one reseller permission has changed. We must synchronize customers permissions $phpini->syncClientPermissionsWithResellerPermissions($resellerId); $needDaemonRequest = true; } unset($resellerPhpPermissions); if (empty($errFieldsStack) && !Zend_Session::namespaceIsset('pageMessages')) { // Update process begin here $oldValues = $newValues = array(); foreach ($data as $property => $value) { if (strpos($property, 'fallback_') !== false) { $property = substr($property, 9); $oldValues[$property] = $value; $newValues[$property] = $data[$property]; } } // Nothing has been changed ? if ($newValues == $oldValues) { set_page_message(tr('Nothing has been changed.'), 'info'); return true; } // Update reseller personal data (including password if needed) $bindParams = array($data['fname'], $data['lname'], $data['gender'], $data['firm'], $data['zip'], $data['city'], $data['state'], $data['country'], $data['email'], $data['phone'], $data['fax'], $data['street1'], $data['street2'], $resellerId); if ($data['password'] != '') { $setPassword = '******'; array_unshift($bindParams, cryptPasswordWithSalt($data['password'])); } else { $setPassword = ''; } exec_query("\n UPDATE admin SET {$setPassword} fname = ?, lname = ?, gender = ?, firm = ?, zip = ?, city = ?,\n state = ?, country = ?, email = ?, phone = ?, fax = ?, street1 = ?, street2 = ?\n WHERE admin_id = ?\n ", $bindParams); // Update reseller properties exec_query(' UPDATE reseller_props SET max_dmn_cnt = ?, max_sub_cnt = ?, max_als_cnt = ?, max_mail_cnt = ?, max_ftp_cnt = ?, max_sql_db_cnt = ?, max_sql_user_cnt = ?, max_traff_amnt = ?, max_disk_amnt = ?, reseller_ips = ?, customer_id = ?, software_allowed = ?, softwaredepot_allowed = ?, websoftwaredepot_allowed = ?, support_system = ?, php_ini_system = ?, php_ini_al_disable_functions = ?, php_ini_al_mail_function = ?, php_ini_al_allow_url_fopen = ?, php_ini_al_display_errors = ?, php_ini_max_post_max_size = ?, php_ini_max_upload_max_filesize = ?, php_ini_max_max_execution_time = ?, php_ini_max_max_input_time = ?, php_ini_max_memory_limit = ? WHERE reseller_id = ? ', array($data['max_dmn_cnt'], $data['max_sub_cnt'], $data['max_als_cnt'], $data['max_mail_cnt'], $data['max_ftp_cnt'], $data['max_sql_db_cnt'], $data['max_sql_user_cnt'], $data['max_traff_amnt'], $data['max_disk_amnt'], implode(';', $resellerIps) . ';', $data['customer_id'], $data['software_allowed'], $data['softwaredepot_allowed'], $data['websoftwaredepot_allowed'], $data['support_system'], $phpini->getResellerPermission('phpiniSystem'), $phpini->getResellerPermission('phpiniDisableFunctions'), $phpini->getResellerPermission('phpiniMailFunction'), $phpini->getResellerPermission('phpiniAllowUrlFopen'), $phpini->getResellerPermission('phpiniDisplayErrors'), $phpini->getResellerPermission('phpiniPostMaxSize'), $phpini->getResellerPermission('phpiniUploadMaxFileSize'), $phpini->getResellerPermission('phpiniMaxExecutionTime'), $phpini->getResellerPermission('phpiniMaxInputTime'), $phpini->getResellerPermission('phpiniMemoryLimit'), $resellerId)); // Updating software installer properties if ($data['software_allowed'] == 'no') { exec_query(' UPDATE domain INNER JOIN admin ON(admin_id = domain_admin_id) SET domain_software_allowed = ? WHERE created_by = ? ', array($data['softwaredepot_allowed'], $resellerId)); } if ($data['websoftwaredepot_allowed'] == 'no') { $stmt = exec_query('SELECT software_id FROM web_software WHERE software_depot = ? AND reseller_id = ?', array('yes', $resellerId)); if ($stmt->rowCount()) { while ($row = $stmt->fetchRow(PDO::FETCH_ASSOC)) { exec_query('UPDATE web_software_inst SET software_res_del = ? WHERE software_id = ?', array('1', $row['software_id'])); } exec_query('DELETE FROM web_software WHERE software_depot = ? AND reseller_id = ?', array('yes', $resellerId)); } } $db->commit(); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditUser, array('userId' => $resellerId)); // Send mail to reseller for new password if ($data['password'] != '') { send_add_user_auto_msg($_SESSION['user_id'], $data['admin_name'], $data['password'], $data['email'], $data['fname'], $data['lname'], tr('Reseller')); } if ($needDaemonRequest) { send_request(); } write_log(sprintf('The %s reseller account has been updated by %s', $data['admin_name'], $_SESSION['user_logged']), E_USER_NOTICE); set_page_message(tr('Reseller account successfully updated.'), 'success'); return true; } } catch (iMSCP_Exception_Database $e) { $db->rollBack(); throw $e; } if (!empty($errFieldsStack)) { iMSCP_Registry::set('errFieldsStack', $errFieldsStack); } return false; }
/** * Update external mail server entries * * Note: In case all entries are marked as to be deleted, the external mail server is deactivated * * @throws iMSCP_Exception_Database * @param array $item Item data (item id and item type) * @return void */ function client_editExternalMailServerEntries($item) { $verifiedData = _client_getVerifiedData($item[0], $item[1]); if (!empty($_POST)) { // Preparing entries stack $data['to_update'] = isset($_POST['to_update']) ? $_POST['to_update'] : array(); $data['to_delete'] = isset($_POST['to_delete']) ? $_POST['to_delete'] : array(); $data['type'] = isset($_POST['type']) ? $_POST['type'] : array(); $data['priority'] = isset($_POST['priority']) ? $_POST['priority'] : array(); $data['host'] = isset($_POST['host']) ? $_POST['host'] : array(); $responses = iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddExternalMailServer, array('externalMailServerEntries' => $data)); if (!$responses->isStopped()) { $entriesCount = count($data['type']); $error = false; // Validate all entries for ($index = 0; $index < $entriesCount; $index++) { if (isset($data['type'][$index]) && isset($data['priority'][$index]) && isset($data['host'][$index])) { $data['host'][$index] = strtolower(rtrim($data['host'][$index], '.')); if (empty($data['to_delete'][$index]) && !_client_validateDnsMxRecord($data['type'][$index], $data['priority'][$index], $data['host'][$index], $verifiedData)) { $error = true; } } else { // Not all expected data were received showBadRequestErrorPage(); } } // Add entries into database if (!$error) { /** @var $db iMSCP_Database */ $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); $dnsEntriesIds = ''; # Spam Filter ( filter ) MX type has highter precedence $spamFilterMX = false; $wildcardMxOnly = true; for ($index = 0; $index < $entriesCount; $index++) { if (!empty($data['to_delete'][$index]) && in_array($data['to_delete'][$index], $verifiedData['external_mail_dns_ids'])) { // Entry to delete if (empty($data['to_update']) && empty($data['type'])) { exec_query('UPDATE domain_dns SET domain_dns_status = ? WHERE domain_dns_id = ?', array('todelete', $data['to_delete'][$index])); } else { exec_query('DELETE FROM domain_dns WHERE domain_dns_id = ?', $data['to_delete'][$index]); } } elseif (!empty($data['to_update'][$index]) && in_array($data['to_update'][$index], $verifiedData['external_mail_dns_ids'])) { // Entry to update if ($data['type'][$index] == 'filter') { $spamFilterMX = true; $wildcardMxOnly = false; } elseif ($data['type'][$index] == 'domain') { $wildcardMxOnly = false; } exec_query(' UPDATE domain_dns SET domain_dns = ?, domain_text = ?, domain_dns_status = ? WHERE domain_dns_id = ? ', array($data['type'][$index] != 'wildcard' ? $verifiedData['item_name'] . '.' : '*.' . $verifiedData['item_name'] . '.', $data['priority'][$index] . "\t" . encode_idna($data['host'][$index]) . '.', 'tochange', $data['to_update'][$index])); $dnsEntriesIds .= ',' . $data['to_update'][$index]; } else { // Entry to add if ($data['type'][$index] == 'filter') { $spamFilterMX = true; $wildcardMxOnly = false; } elseif ($data['type'][$index] == 'domain') { $wildcardMxOnly = false; } exec_query(' INSERT INTO domain_dns ( domain_id, alias_id, domain_dns, domain_class, domain_type, domain_text, owned_by, domain_dns_status ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? ) ', array($verifiedData['domain_id'], $verifiedData['item_type'] == 'alias' ? $verifiedData['item_id'] : 0, $data['type'][$index] != 'wildcard' ? $verifiedData['item_name'] . '.' : '*.' . $verifiedData['item_name'] . '.', 'IN', 'MX', "{$data['priority'][$index]}\t" . encode_idna($data['host'][$index]) . '.', 'ext_mail_feature', 'toadd')); $dnsEntriesIds .= ',' . $db->insertId(); } } $externalMailServer = $dnsEntriesIds !== '' ? $spamFilterMX ? 'filter' : ($wildcardMxOnly ? 'wildcard' : 'domain') : 'off'; if ($verifiedData['item_type'] == 'normal') { exec_query(' UPDATE domain SET external_mail = ?, domain_status = ?, external_mail_dns_ids = ? WHERE domain_id = ? ', array($externalMailServer, 'tochange', ltrim($dnsEntriesIds, ','), $verifiedData['item_id'])); } else { exec_query(' UPDATE domain_aliasses SET external_mail = ?, alias_status = ?, external_mail_dns_ids = ? WHERE alias_id = ? ', array($externalMailServer, 'tochange', ltrim($dnsEntriesIds, ','), $verifiedData['item_id'])); } $db->commit(); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddExternalMailServer, array('externalMailServerEntries' => $data)); send_request(); if ($externalMailServer !== 'off') { set_page_message(tr('External mail server successfully scheduled for update.'), 'success'); } else { set_page_message(tr('External mail server successfully scheduled for deactivation.'), 'success'); } redirectTo('mail_external.php'); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); if ($e->getCode() === 23000) { set_page_message(tr('An entry is defined twice.'), 'error'); } else { throw $e; } } } } else { redirectTo('mail_external.php'); } } else { if (!empty($verifiedData['external_mail_dns_ids'])) { $stmt = execute_query(' SELECT * FROM domain_dns WHERE domain_dns_id IN(' . implode(',', $verifiedData['external_mail_dns_ids']) . ') '); if ($stmt->rowCount()) { $data = array(); while ($row = $stmt->fetchRow(PDO::FETCH_ASSOC)) { $data['to_update'][] = $row['domain_dns_id']; $data['type'][] = strpos($row['domain_dns'], '*') === false ? $verifiedData['external_mail_type'] == 'domain' ? 'domain' : 'filter' : 'wildcard'; list($priority, $host) = explode("\t", $row['domain_text'], 2); $data['priority'][] = trim($priority); $data['host'][] = rtrim($host, '.'); } } else { // DNS entries pointed by domain or domain alias were not found ( should never occurs ) if ($verifiedData['item_type'] == 'normal') { $query = ' UPDATE domain SET domain_status = ?, external_mail = ?, external_mail_dns_ids = ? WHERE domain_id = ? '; } else { $query = ' UPDATE domain_aliasses SET alias_status = ?, external_mail = ?, external_mail_dns_ids = ? WHERE alias_id = ? '; } exec_query($query, array('tochange', 'off', null, $verifiedData['item_id'])); send_request(); set_page_message(tr('Entries associated to your external mail servers were not found. A Resynchronization has been scheduled.'), 'warning'); redirectTo('mail_external.php'); exit; // Only to make some IDE happy } } else { set_page_message('An unexpected error occurred.', 'error'); redirectTo('mail_external.php'); // No domain or domain alias data found ( should never occurs ) exit; // Only to make some IDE happy } } client_generateView($verifiedData, $data); }
/** * Delete an SSL certificate * * @throws iMSCP_Exception * @throws iMSCP_Exception_Database * @param int $domainId domain unique identifier * @param string $domainType Domain type (dmn, als, sub, alssub) * @return void */ function client_deleteSslCert($domainId, $domainType) { $domainName = _client_getDomainName($domainId, $domainType); if ($domainName === false) { showBadRequestErrorPage(); } if (!isset($_POST['cert_id'])) { showBadRequestErrorPage(); } $certId = intval($_POST['cert_id']); $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); exec_query('UPDATE ssl_certs SET status = ? WHERE cert_id = ? AND domain_id = ? AND domain_type = ?', array('todelete', $certId, $domainId, $domainType)); _client_updateDomainStatus($domainType, $domainId); $db->commit(); send_request(); set_page_message(tr('SSL certificate successfully scheduled for deletion.'), 'success'); write_log(sprintf('%s deleted SSL certificate for the %s domain.', decode_idna($_SESSION['user_logged']), decode_idna($domainName)), E_USER_NOTICE); redirectTo('domains_manage.php'); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); write_log(sprintf('Could not export SSL certificate: %s', $e->getMessage()), E_USER_ERROR); set_page_message(tr('Could not delete SSL certificate. An unexpected error occurred.'), 'error'); } }
/** * Add Ftp account * * @throws iMSCP_Exception_Database * @param string $mainDmnName Customer main domain * @return bool TRUE on success, FALSE otherwise */ function ftp_addAccount($mainDmnName) { $ret = true; if (isset($_POST['domain_type']) && isset($_POST['username']) && isset($_POST['domain_name']) && isset($_POST['password']) && isset($_POST['password_repeat']) && isset($_POST['home_dir'])) { $username = clean_input($_POST['username']); $dmnName = clean_input($_POST['domain_name']); $passwd = clean_input($_POST['password']); $passwdRepeat = clean_input($_POST['password_repeat']); $homeDir = clean_input($_POST['home_dir']); if (!validates_username($username)) { set_page_message(tr("Incorrect username length or syntax."), 'error'); $ret = false; } if ($passwd !== $passwdRepeat) { set_page_message(tr("Passwords do not match"), 'error'); $ret = false; } elseif (!checkPasswordSyntax($passwd)) { $ret = false; } // Check for home directory existence if ($homeDir != '/' && $homeDir != '') { // Strip possible double-slashes $homeDir = str_replace('//', '/', $homeDir); // Check for updirs '..' if (strpos($homeDir, '..') !== false) { set_page_message(tr('Invalid home directory.'), 'error'); $ret = false; } if ($ret) { $vfs = new iMSCP_VirtualFileSystem($mainDmnName); if (!$vfs->exists($homeDir)) { set_page_message(tr("Home directory '%s' doesn't exist", $homeDir), 'error'); $ret = false; } } } if ($ret) { // Check that the customer is the owner of the domain for which the ftp Account is added if (!customerHasDomain($dmnName, $_SESSION['user_id'])) { showBadRequestErrorPage(); } /** @var $cfg iMSCP_Config_Handler_File */ $cfg = iMSCP_Registry::get('config'); $userid = $username . '@' . decode_idna($dmnName); $encryptedPassword = cryptPasswordWithSalt($passwd); $shell = '/bin/sh'; $homeDir = rtrim(str_replace('//', '/', $cfg->USER_WEB_DIR . '/' . $mainDmnName . '/' . $homeDir), '/'); // Retrieve customer uid/gid $query = ' SELECT `t1`.`admin_name`, `t1`.`admin_sys_uid`, `t1`.`admin_sys_gid`, `t2`.`domain_disk_limit`, count(`t3`.`name`) AS `quota_entry` FROM `admin` AS `t1` LEFT JOIN `domain` AS `t2` ON (`t2`.`domain_admin_id` = `t1`.`admin_id` ) LEFT JOIN `quotalimits` AS `t3` ON (`t3`.`name` = `t1`.`admin_name` ) WHERE `t1`.`admin_id` = ? '; $stmt = exec_query($query, $_SESSION['user_id']); $groupName = $stmt->fields['admin_name']; $uid = $stmt->fields['admin_sys_uid']; $gid = $stmt->fields['admin_sys_gid']; $diskspaceLimit = $stmt->fields['domain_disk_limit']; $quotaEntriesExist = $stmt->fields['quota_entry'] ? true : false; iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddFtp, array('ftpUserId' => $userid, 'ftpPassword' => $encryptedPassword, 'ftpRawPassword' => $passwd, 'ftpUserUid' => $uid, 'ftpUserGid' => $gid, 'ftpUserShell' => $shell, 'ftpUserHome' => $homeDir)); /** @var $db iMSCP_Database */ $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); // Add ftp user $query = "\n\t\t\t\t\tINSERT INTO `ftp_users` (\n\t\t\t\t\t\t`userid`, `admin_id`, `passwd`, `rawpasswd`, `uid`, `gid`, `shell`, `homedir`\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?\n\t\t\t\t\t)\n\t\t\t\t"; exec_query($query, array($userid, $_SESSION['user_id'], $encryptedPassword, $passwd, $uid, $gid, $shell, $homeDir)); $query = "SELECT `members` FROM `ftp_group` WHERE `groupname` = ? LIMIT 1"; $stmt = exec_query($query, $groupName); // Ftp group if (!$stmt->rowCount()) { $query = "INSERT INTO `ftp_group` (`groupname`, `gid`, `members`) VALUES (?, ?, ?)"; exec_query($query, array($groupName, $gid, $userid)); } else { $query = "UPDATE `ftp_group` SET `members` = ? WHERE `groupname` = ?"; exec_query($query, array("{$stmt->fields['members']},{$userid}", $groupName)); } // Quota limit if (!$quotaEntriesExist) { $query = "\n\t\t\t\t\t\tINSERT INTO `quotalimits` (\n\t\t\t\t\t\t\t`name`, `quota_type`, `per_session`, `limit_type`, `bytes_in_avail`, `bytes_out_avail`,\n\t\t\t\t\t\t\t`bytes_xfer_avail`, `files_in_avail`, `files_out_avail`, `files_xfer_avail`\n\t\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?, ?, ?, ?\n\t\t\t\t\t\t)\n\t\t\t\t\t"; exec_query($query, array($groupName, 'group', 'false', 'hard', $diskspaceLimit * 1024 * 1024, 0, 0, 0, 0, 0)); } $db->commit(); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); if ($e->getCode() == 23000) { set_page_message(tr('Ftp account with same username already exists.'), 'error'); $ret = false; } else { throw $e; } } if ($ret) { iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddFtp, array('ftpUserId' => $userid, 'ftpPassword' => $encryptedPassword, 'ftpRawPassword' => $passwd, 'ftpUserUid' => $uid, 'ftpUserGid' => $gid, 'ftpUserShell' => $shell, 'ftpUserHome' => $homeDir)); write_log(sprintf("%s added Ftp account: %s", $_SESSION['user_logged'], $userid), E_USER_NOTICE); set_page_message(tr('FTP account successfully added.'), 'success'); } } } else { showBadRequestErrorPage(); } return $ret; }
/** * Store plugins info and config as json data instead of serialized data * * @return array SQL statements to be executed */ protected function r145() { $sqlUdp = array(); $stmt = execute_query('SELECT plugin_id, plugin_info, plugin_config FROM plugin'); if ($stmt->rowCount()) { $db = iMSCP_Database::getRawInstance(); while ($row = $stmt->fetchRow(PDO::FETCH_ASSOC)) { if (!isJson($row['plugin_info'])) { $pluginInfo = $db->quote(json_encode(unserialize($row['plugin_info']))); } else { $pluginInfo = $db->quote($row['plugin_info']); } if (!isJson($row['plugin_config'])) { $pluginConfig = $db->quote(json_encode(unserialize($row['plugin_config']))); } else { $pluginConfig = $db->quote($row['plugin_config']); } $sqlUdp[] = "\n\t\t\t\t\tUPDATE\n\t\t\t\t\t\tplugin\n\t\t\t\t\tSET\n\t\t\t\t\t\tplugin_info = {$pluginInfo}, plugin_config = {$pluginConfig}\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tplugin_id = {$row['plugin_id']}\n\t\t\t\t"; } } return $sqlUdp; }
/** * Add default emails accounts for domain or domain alias. * * @throws iMSCP_Exception_Database * @param int $dmnId Domain unique identifier * @param string $userEmail User email * @param string $dmnName Domain name * @param string $dmnType Domain type * @param int $subId * @return void */ function client_mail_add_default_accounts($dmnId, $userEmail, $dmnName, $dmnType = 'domain', $subId = 0) { $forwardType = $dmnType == 'alias' ? 'alias_forward' : 'normal_forward'; $resellerEmail = $_SESSION['user_email']; $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); // Prepare the statement once $stmt = $db->getRawInstance()->prepare(' INSERT INTO mail_users ( mail_acc, mail_pass, mail_forward, domain_id, mail_type, sub_id, status, mail_auto_respond, quota, mail_addr ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) '); foreach (array('abuse' => $resellerEmail, 'hostmaster' => $resellerEmail, 'postmaster' => $resellerEmail, 'webmaster' => $userEmail) as $umail => $forwardTo) { $stmt->execute(array($umail, '_no_', $forwardTo, $dmnId, $forwardType, $subId, 'toadd', 0, null, $umail . '@' . $dmnName)); } $db->commit(); } catch (PDOException $e) { $db->rollBack(); throw new iMSCP_Exception_Database($e->getMessage(), $e->getCode(), null, $e); } }
/** * Add external mail server entries * * @throws iMSCP_Exception_Database * @param array $item Item data (item id and item type) * @return void */ function client_addExternalMailServerEntries($item) { $verifiedData = _client_getVerifiedData($item[0], $item[1]); if (!empty($_POST)) { // Preparing entries stack $data['type'] = isset($_POST['type']) ? $_POST['type'] : array(); $data['priority'] = isset($_POST['priority']) ? $_POST['priority'] : array(); $data['host'] = isset($_POST['host']) ? $_POST['host'] : array(); $responses = iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddExternalMailServer, array('externalMailServerEntries' => $data)); if (!$responses->isStopped()) { $entriesCount = count($data['type']); $error = false; # Spam Filter ( filter ) MX type has highter precedence $spamFilterMX = false; $wildcardMxOnly = true; // Validate all entries for ($index = 0; $index < $entriesCount; $index++) { if (isset($data['type'][$index]) && isset($data['priority'][$index]) && isset($data['host'][$index])) { $data['host'][$index] = strtolower(rtrim($data['host'][$index], '.')); if (!_client_validateDnsMxRecord($data['type'][$index], $data['priority'][$index], $data['host'][$index], $verifiedData)) { $error = true; } if ($data['type'][$index] == 'filter') { $spamFilterMX = true; $wildcardMxOnly = false; } elseif ($data['type'][$index] == 'domain') { $wildcardMxOnly = false; } } else { // Not all expected data were received showBadRequestErrorPage(); } } // Add DNS entries into database if (!$error) { /** @var $db iMSCP_Database */ $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); // All successfully inserted or nothing $dnsEntriesIds = ''; for ($index = 0; $index < $entriesCount; $index++) { // Add MX record exec_query(' INSERT INTO domain_dns ( domain_id, alias_id, domain_dns, domain_class, domain_type, domain_text, owned_by, domain_dns_status ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? ) ', array($verifiedData['domain_id'], $verifiedData['item_type'] == 'alias' ? $verifiedData['item_id'] : 0, $data['type'][$index] != 'wildcard' ? $verifiedData['item_name'] . '.' : '*.' . $verifiedData['item_name'] . '.', 'IN', 'MX', "{$data['priority'][$index]}\t" . encode_idna($data['host'][$index]) . '.', 'ext_mail_feature', 'toadd')); $dnsEntriesIds .= ',' . $db->insertId(); } if ($verifiedData['item_type'] == 'normal') { exec_query(' UPDATE domain SET external_mail = ?, domain_status = ?, external_mail_dns_ids = ? WHERE domain_id = ? ', array($spamFilterMX ? 'filter' : ($wildcardMxOnly ? 'wildcard' : 'domain'), 'tochange', ltrim($dnsEntriesIds, ','), $verifiedData['domain_id'])); } else { exec_query(' UPDATE domain_aliasses SET external_mail = ?, alias_status = ?, external_mail_dns_ids = ? WHERE alias_id = ? ', array($spamFilterMX ? 'filter' : ($wildcardMxOnly ? 'wildcard' : 'domain'), 'tochange', ltrim($dnsEntriesIds, ','), $verifiedData['item_id'])); } $db->commit(); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddExternalMailServer, array('externalMailServerEntries' => $data)); send_request(); set_page_message(tr('External mail server successfully scheduled for addition.'), 'success'); redirectTo('mail_external.php'); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); if ($e->getCode() === 23000) { set_page_message(tr('An entry is defined twice.'), 'error'); } else { throw $e; } } } } else { redirectTo('mail_external.php'); } } else { $data['type'][] = 'domain'; $data['priority'][] = '5'; $data['host'][] = ''; } client_generateView($verifiedData, $data); }
/** * Add catchall * * @param string $itemId * @return void */ function client_addCatchall($itemId) { list($realId, $type) = explode(';', $itemId); // Check if user is owner of the domain if (!preg_match('(normal|alias|subdom|alssub)', $type) || who_owns_this($realId, $type) != $_SESSION['user_id']) { set_page_message(tr('User do not exist or you do not have permission to access this interface'), 'error'); redirectTo('mail_catchall.php'); } $match = array(); $mailType = $dmnId = $subId = $mailAddr = ''; if (isset($_POST['mail_type'])) { if ($_POST['mail_type'] === 'normal' && isset($_POST['mail_id'])) { if (preg_match('/^\\d+;(normal|alias|subdom|alssub)$/', $itemId, $match)) { $itemType = $match[1]; $postMailId = clean_input($_POST['mail_id']); if (preg_match('/(\\d+);([^;]+);/', $postMailId, $match)) { $mailId = $match[1]; $mailAccount = $match[2]; if ($itemType === 'normal') { $mailType = MT_NORMAL_CATCHALL; } elseif ($itemType === 'alias') { $mailType = MT_ALIAS_CATCHALL; } elseif ($itemType === 'subdom') { $mailType = MT_SUBDOM_CATCHALL; } elseif ($itemType === 'alssub') { $mailType = MT_ALSSUB_CATCHALL; } else { showBadRequestErrorPage(); } $stmt = exec_query('SELECT domain_id, sub_id FROM mail_users WHERE mail_id = ?', $mailId); if ($stmt->rowCount()) { $row = $stmt->fetchRow(PDO::FETCH_ASSOC); $dmnId = $row['domain_id']; $subId = $row['sub_id']; // Find the mail_addr (catchall -> "@(sub/alias)domain.tld", should be domain part of mail_acc $match = explode('@', $mailAccount); $mailAddr = '@' . $match[1]; iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddMailCatchall, array('mailCatchall' => $mailAddr, 'mailForwardList' => array($mailAccount))); exec_query(' INSERT INTO mail_users ( mail_acc, mail_pass, mail_forward, domain_id, mail_type, sub_id, status, mail_auto_respond, quota, mail_addr ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ', array($mailAccount, '_no_', '_no_', $dmnId, $mailType, $subId, 'toadd', '_no_', NULL, $mailAddr)); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddMailCatchall, array('mailCatchallId' => iMSCP_Database::getInstance()->insertId(), 'mailCatchall' => $mailAddr, 'mailForwardList' => array($mailAccount))); send_request(); write_log("{$_SESSION['user_logged']} added new catch all", E_USER_NOTICE); set_page_message(tr('Catch all successfully scheduled for addition.'), 'success'); redirectTo('mail_catchall.php'); } else { showBadRequestErrorPage(); } } else { redirectTo('mail_catchall.php'); } } } else { if ($_POST['mail_type'] === 'forward' && isset($_POST['forward_list'])) { if (preg_match('/^(\\d+);(normal|alias|subdom|alssub)$/', $itemId, $match) == 1) { $itemId = $match[1]; $itemType = $match[2]; if ($itemType === 'normal') { $mailType = MT_NORMAL_CATCHALL; $subId = '0'; $dmnId = $itemId; $stmt = exec_query('SELECT domain_name FROM domain WHERE domain_id = ?', $dmnId); if ($stmt->rowCount()) { $row = $stmt->fetchRow(PDO::FETCH_ASSOC); $mailAddr = '@' . $row['domain_name']; } else { showBadRequestErrorPage(); } } elseif ($itemType == 'alias') { $mailType = MT_ALIAS_CATCHALL; $subId = $itemId; $stmt = exec_query('SELECT domain_id, alias_name FROM domain_aliasses WHERE alias_id = ?', $itemId); if ($stmt->rowCount()) { $row = $stmt->fetchRow(PDO::FETCH_ASSOC); $dmnId = $row['domain_id']; $mailAddr = '@' . $row['alias_name']; } else { showBadRequestErrorPage(); } } elseif ($itemType === 'subdom') { $mailType = MT_SUBDOM_CATCHALL; $subId = $itemId; $stmt = exec_query("\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tdomain_id, CONCAT(subdomain_name, '.', domain_name) AS subdomain_name\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\tsubdomain\n\t\t\t\t\t\t\tINNER JOIN\n\t\t\t\t\t\t\t\tdomain USING(domain_id)\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tsubdomain_id = ?\n\t\t\t\t\t\t", $itemId); if ($stmt->rowCount()) { $row = $stmt->fetchRow(PDO::FETCH_ASSOC); $dmnId = $row['domain_id']; $mailAddr = '@' . $row['subdomain_name']; } else { showBadRequestErrorPage(); } } elseif ($itemType === 'alssub') { $mailType = MT_ALSSUB_CATCHALL; $subId = $itemId; $stmt = exec_query("\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tdomain_id, CONCAT(subdomain_alias_name, '.', alias_name) AS subdomain_alias_name\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\tsubdomain_alias\n\t\t\t\t\t\t\tINNER JOIN\n\t\t\t\t\t\t\t\tdomain_aliasses USING(alias_id)\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tsubdomain_alias_id = ?\n\t\t\t\t\t\t", $itemId); if ($stmt->rowCount()) { $row = $stmt->fetchRow(PDO::FETCH_ASSOC); $dmnId = $row['domain_id']; $mailAddr = '@' . $row['subdomain_alias_name']; } else { showBadRequestErrorPage(); } } else { showBadRequestErrorPage(); } $mailForward = clean_input($_POST['forward_list']); $mailAccount = array(); $faray = preg_split("/[\n,]+/", $mailForward); foreach ($faray as $value) { $value = trim($value); if (!chk_email($value) && $value != '') { set_page_message(tr('An email addresse is not valid in mail forward list.'), 'error'); return; } else { if ($value == '') { set_page_message(tr('Syntax error found in mail forward list.'), 'error'); return; } } $mailAccount[] = $value; } iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddMailCatchall, array('mailCatchall' => $mailAddr, 'mailForwardList' => $mailAccount)); exec_query(' INSERT INTO mail_users ( mail_acc, mail_pass, mail_forward, domain_id, mail_type, sub_id, status, mail_auto_respond, quota, mail_addr ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ', array(implode(',', $mailAccount), '_no_', '_no_', $dmnId, $mailType, $subId, 'toadd', '_no_', NULL, $mailAddr)); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddMailCatchall, array('mailCatchallId' => iMSCP_Database::getInstance()->insertId(), 'mailCatchall' => $mailAddr, 'mailForwardList' => $mailAccount)); send_request(); write_log("{$_SESSION['user_logged']} added new catch all", E_USER_NOTICE); set_page_message(tr('Catch all successfully scheduled for addition.'), 'success'); redirectTo('mail_catchall.php'); } else { redirectTo('mail_catchall.php'); } } else { showBadRequestErrorPage(); } } } else { showBadRequestErrorPage(); } }
/** * Add new subdomain * * @return bool TRUE on success, FALSE on failure */ function client_addSubdomain() { global $mainDmnProps; // Basic check if (empty($_POST['subdomain_name'])) { set_page_message(tr('You must enter a subdomain name.'), 'error'); return false; } if (empty($_POST['domain_name'])) { showBadRequestErrorPage(); } // Check for parent domain $domainName = clean_input($_POST['domain_name']); $domainType = $domainId = null; $domainList = _client_getDomainsList(); foreach ($domainList as $domain) { if (($domain['type'] == 'dmn' || $domain['type'] == 'als') && $domain['name'] == $domainName) { $domainType = $domain['type']; $domainId = $domain['id']; } } if (null === $domainType) { showBadRequestErrorPage(); } $subLabel = clean_input(strtolower($_POST['subdomain_name'])); if ($subLabel == 'www' || strpos($subLabel, 'www.') !== false) { set_page_message(tr('%s is not allowed as subdomain label.', "<strong>www</strong>"), 'error'); return false; } $subdomainName = $subLabel . '.' . $domainName; // Check for subdomain syntax if (!isValidDomainName($subdomainName)) { set_page_message(tr('Subdomain name is not valid.'), 'error'); return false; } // Ensure that this subdomain doesn't already exists as domain or domain alias $stmt = exec_query(' SELECT domain_id FROM domain WHERE domain_name = :subdomain_name UNION ALL SELECT alias_id FROM domain_aliasses WHERE alias_name = :subdomain_name', array('subdomain_name' => $subdomainName)); if ($stmt->rowCount()) { set_page_message(tr('Subdomain %s is unavailable.', "<strong>{$subdomainName}</strong>"), 'error'); return false; } $subLabelAscii = clean_input(encode_idna(strtolower($_POST['subdomain_name']))); $subdomainNameAscii = encode_idna($subdomainName); // Check for sudomain existence foreach ($domainList as $domain) { if ($domain['name'] == $subdomainNameAscii) { set_page_message(tr('Subdomain %s already exist.', "<strong>{$subdomainName}</strong>"), 'error'); return false; } } // Set default mount point if ($domainType == 'dmn') { if (in_array($subLabelAscii, array('backups', 'cgi-bin', 'errors', 'logs', 'phptmp'))) { $mountPoint = "/sub_{$subLabelAscii}"; } else { $mountPoint = "/{$subLabelAscii}"; } } else { if (in_array($subLabelAscii, array('cgi-bin', 'phptmp'))) { $mountPoint = "/{$domainName}/sub_{$subLabelAscii}"; } else { $mountPoint = "/{$domainName}/{$subLabelAscii}"; } } // Check for shared mount point option if (isset($_POST['shared_mount_point']) && $_POST['shared_mount_point'] == 'yes') { // We are safe here if (!isset($_POST['shared_mount_point_domain'])) { showBadRequestErrorPage(); } $sharedMountPointDomain = clean_input($_POST['shared_mount_point_domain']); // Get shared mount point foreach ($domainList as $domain) { if ($domain['name'] == $sharedMountPointDomain) { $mountPoint = $domain['mount_point']; } } } // Check for URL forwarding option $forwardUrl = 'no'; if (isset($_POST['url_forwarding']) && $_POST['url_forwarding'] == 'yes') { // We are safe here if (isset($_POST['forward_url_scheme']) && isset($_POST['forward_url'])) { $forwardUrl = clean_input($_POST['forward_url_scheme']) . clean_input($_POST['forward_url']); try { try { $uri = iMSCP_Uri_Redirect::fromString($forwardUrl); } catch (Zend_Uri_Exception $e) { throw new iMSCP_Exception(tr('Forward URL %s is not valid.', "<strong>{$forwardUrl}</strong>")); } $uri->setHost(encode_idna($uri->getHost())); if ($uri->getHost() == $subdomainNameAscii && $uri->getPath() == '/') { throw new iMSCP_Exception(tr('Forward URL %s is not valid.', "<strong>{$forwardUrl}</strong>") . ' ' . tr('Subdomain %s cannot be forwarded on itself.', "<strong>{$subdomainName}</strong>")); } $forwardUrl = $uri->getUri(); } catch (Exception $e) { set_page_message($e->getMessage(), 'error'); return false; } } else { showBadRequestErrorPage(); } } $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddSubdomain, array('subdomainName' => $subdomainName, 'subdomainType' => $domainType, 'parentDomainId' => $domainId, 'mountPoint' => $mountPoint, 'forwardUrl' => $forwardUrl, 'customerId' => $_SESSION['user_id'])); if ($domainType == 'als') { $query = "\n INSERT INTO subdomain_alias (\n alias_id, subdomain_alias_name, subdomain_alias_mount, subdomain_alias_url_forward,\n subdomain_alias_status\n ) VALUES (\n ?, ?, ?, ?, ?\n )\n "; } else { $query = "\n INSERT INTO subdomain (\n domain_id, subdomain_name, subdomain_mount, subdomain_url_forward, subdomain_status\n ) VALUES (\n ?, ?, ?, ?, ?\n )\n "; } exec_query($query, array($domainId, $subLabelAscii, $mountPoint, $forwardUrl, 'toadd')); $subdomainId = $db->insertId(); // Create the phpini entry for that subdomain $phpini = iMSCP_PHPini::getInstance(); $phpini->loadResellerPermissions($_SESSION['user_created_by']); // Load reseller PHP permissions $phpini->loadClientPermissions($_SESSION['user_id']); // Load client PHP permissions $phpini->loadDomainIni($_SESSION['user_id'], $mainDmnProps['domain_id'], 'dmn'); // Load main domain PHP configuration options $phpini->saveDomainIni($_SESSION['user_id'], $subdomainId, $domainType == 'dmn' ? 'sub' : 'subals'); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddSubdomain, array('subdomainName' => $subdomainName, 'subdomainType' => $domainType, 'parentDomainId' => $domainId, 'mountPoint' => $mountPoint, 'forwardUrl' => $forwardUrl, 'customerId' => $_SESSION['user_id'], 'subdomainId' => $subdomainId)); $db->commit(); send_request(); write_log(sprintf('A new `%s` subdomain has been created by %s', $subdomainName, decode_idna($_SESSION['user_logged'])), E_USER_NOTICE); return true; } catch (iMSCP_Exception_Database $e) { $db->rollBack(); write_log(sprintf('System was unable to create the `%s` subdomain: %s', $subdomainName, $e->getMessage()), E_USER_ERROR); set_page_message('Could not create subdomain. An unexpected error occurred.', 'error'); return false; } }
/** * Delete one or many external mail server related entries * * @throws iMSCP_Exception_Database * @param array $items Item(s) to delete * @param bool $postRequest Flag indicating whether POST data were received * @return void */ function client_deleteExternalMailServers($items, $postRequest) { if (isset($items['normal']) || isset($items['alias'])) { $domainId = get_user_domain_id($_SESSION['user_id']); /** @var $db iMSCP_Database */ $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); $numberDeletedEntries = 0; if (!empty($items['normal'])) { $itemId = array_shift($items['normal']); if ($itemId == $domainId) { $stmt = exec_query('SELECT external_mail_dns_ids FROM domain WHERE domain_id = ?', $domainId); if ($stmt->rowCount()) { $row = $stmt->fetchRow(PDO::FETCH_ASSOC); if ($row['external_mail_dns_ids'] != '') { exec_query(' UPDATE domain_dns SET domain_dns_status = ? WHERE domain_dns_id IN(' . $row['external_mail_dns_ids'] . ') ', 'todelete'); exec_query(' UPDATE domain SET external_mail = ?, domain_status = ?, external_mail_dns_ids = ? WHERE domain_id = ? ', array('off', 'tochange', null, $itemId)); $numberDeletedEntries++; } } } } if (!empty($items['alias'])) { foreach ((array) $items['alias'] as $itemId) { $stmt = exec_query(' SELECT alias_name, external_mail_dns_ids FROM domain_aliasses WHERE alias_id = ? AND domain_id = ? ', array($itemId, $domainId)); if ($stmt->rowCount()) { $row = $stmt->fetchRow(PDO::FETCH_ASSOC); if ($row['external_mail_dns_ids'] != '') { exec_query(' UPDATE domain_dns SET domain_dns_status = ? WHERE domain_dns_id IN(' . $row['external_mail_dns_ids'] . ') ', 'todelete'); exec_query(' UPDATE domain_aliasses SET external_mail = ?, alias_status = ?, external_mail_dns_ids = ? WHERE alias_id = ? AND domain_id = ? ', array('off', 'tochange', null, $itemId, $domainId)); $numberDeletedEntries++; } } } } $db->commit(); send_request(); if ($numberDeletedEntries > 0) { set_page_message(tr('External mail server successfully scheduled for deactivation.'), 'success'); } else { set_page_message(tr('Nothing has been scheduled for deactivation.'), 'error'); } } catch (iMSCP_Exception_Database $e) { $db->rollBack(); throw $e; } } else { if ($postRequest) { set_page_message(tr('You must select a least one item to deactivate.'), 'warning'); } else { showBadRequestErrorPage(); } } }
/** * Load configuration parameters from the database * * This function retrieves all the parameters from the database and merge them with the basis configuration object. * * Parameters that exists in the basis configuration object will be replaced by those that come from the database. * The basis configuration object contains parameters that come from the i-mscp.conf configuration file or any * parameter defined in the {@link environment.php} file. * * @throws iMSCP_Exception * @return void */ protected function loadConfig() { /** @var $pdo PDO */ $pdo = iMSCP_Database::getRawInstance(); if (is_readable(DBCONFIG_CACHE_FILE_PATH)) { if (!$this->config['DEBUG']) { /** @var iMSCP_Config_Handler_Db $dbConfig */ $dbConfig = unserialize(file_get_contents(DBCONFIG_CACHE_FILE_PATH)); $dbConfig->setDb($pdo); } else { @unlink(DBCONFIG_CACHE_FILE_PATH); goto FORCE_DBCONFIG_RELOAD; } } else { FORCE_DBCONFIG_RELOAD: // Creating new Db configuration handler. $dbConfig = new iMSCP_Config_Handler_Db($pdo); if (!$this->config['DEBUG'] && PHP_SAPI != 'cli') { @file_put_contents(DBCONFIG_CACHE_FILE_PATH, serialize($dbConfig), LOCK_EX); } } // Merge main configuration object with the dbConfig object $this->config->merge($dbConfig); // Add the dbconfig object into the registry for later use iMSCP_Registry::set('dbConfig', $dbConfig); }
/** * Check and updates domain data * * @throws iMSCP_Exception_Database * @param int $domainId Domain unique identifier * @return bool TRUE on success, FALSE otherwise */ function reseller_checkAndUpdateData($domainId) { $db = iMSCP_Database::getInstance(); $errFieldsStack = array(); try { // Getting domain data $data =& reseller_getData($domainId, true); // Check for expires date if ($data['domain_never_expires'] == 'off') { if (!preg_match('%^\\d{2}/\\d{2}/\\d{4}$%', $data['domain_expires']) || ($timestamp = strtotime($data['domain_expires'])) === false) { $data['domain_expires_ok'] = false; set_page_message(tr('Wrong syntax for new expire date.'), 'error'); $errFieldsStack[] = 'domain_expires'; } elseif ($timestamp != 0 && $timestamp <= time()) { $data['domain_expires'] = $timestamp; set_page_message(tr('You cannot set expire date in past.'), 'error'); $errFieldsStack[] = 'domain_expires'; } else { $data['domain_expires'] = $timestamp; } } else { $data['domain_expires'] = 0; } // Check for the subdomains limit if ($data['fallback_domain_subd_limit'] != -1) { if (!imscp_limit_check($data['domain_subd_limit'])) { set_page_message(tr('Wrong syntax for the %s limit.', tr('subdomains')), 'error'); $errFieldsStack[] = 'domain_subd_limit'; } elseif (!_reseller_isValidServiceLimit($data['domain_subd_limit'], $data['nbSubdomains'], $data["fallback_domain_subd_limit"], $data['current_sub_cnt'], $data['max_sub_cnt'], $data['nbSubdomains'] > 1 ? tr('subdomains') : tr('subdomain'))) { $errFieldsStack[] = 'domain_subd_limit'; } } // Check for the domain aliases limit if ($data['fallback_domain_alias_limit'] != -1) { if (!imscp_limit_check($data['domain_alias_limit'])) { set_page_message(tr('Wrong syntax for the %s limit.', tr('domain aliases')), 'error'); $errFieldsStack[] = 'domain_alias_limit'; } elseif (!_reseller_isValidServiceLimit($data['domain_alias_limit'], $data['nbAliasses'], $data["fallback_domain_alias_limit"], $data['current_als_cnt'], $data['max_als_cnt'], $data['nbAliasses'] > 1 ? tr('domain aliases') : tr('domain alias'))) { $errFieldsStack[] = 'domain_alias_limit'; } } // Check for the mail accounts limit if ($data['fallback_domain_mailacc_limit'] != -1) { if (!imscp_limit_check($data['domain_mailacc_limit'])) { set_page_message(tr('Wrong syntax for the %s limit.', tr('email accounts')), 'error'); $errFieldsStack[] = 'domain_mailacc_limit'; } elseif (!_reseller_isValidServiceLimit($data['domain_mailacc_limit'], $data['nbMailAccounts'], $data["fallback_domain_mailacc_limit"], $data['current_mail_cnt'], $data['max_mail_cnt'], $data["nbMailAccounts"] > 1 ? tr('email accounts') : tr('email account'))) { $errFieldsStack[] = 'domain_mailacc_limit'; } } // Check for the Ftp accounts limit if ($data['fallback_domain_ftpacc_limit'] != -1) { if (!imscp_limit_check($data['domain_ftpacc_limit'])) { set_page_message(tr('Wrong syntax for the %s limit.', tr('Ftp accounts')), 'error'); $errFieldsStack[] = 'domain_ftpacc_limit'; } elseif (!_reseller_isValidServiceLimit($data['domain_ftpacc_limit'], $data['nbFtpAccounts'], $data["fallback_domain_ftpacc_limit"], $data['current_ftp_cnt'], $data['max_ftp_cnt'], $data['nbFtpAccounts'] > 1 ? tr('Ftp accounts') : tr('Ftp account'))) { $errFieldsStack[] = 'domain_ftpacc_limit'; } } // Check for the Sql databases limit if ($data['fallback_domain_sqld_limit'] != -1) { if (!imscp_limit_check($data['domain_sqld_limit'])) { set_page_message(tr('Wrong syntax for the %s limit.', tr('SQL databases')), 'error'); $errFieldsStack[] = 'domain_sqld_limit'; } elseif (!_reseller_isValidServiceLimit($data['domain_sqld_limit'], $data['nbSqlDatabases'], $data["fallback_domain_sqld_limit"], $data['current_sql_db_cnt'], $data['max_sql_db_cnt'], $data['nbSqlDatabases'] > 1 ? tr('SQL databases') : tr('SQL database'))) { $errFieldsStack[] = 'domain_sqld_limit'; } elseif ($data['domain_sqld_limit'] != -1 && $data['domain_sqlu_limit'] == -1) { set_page_message(tr('SQL user limit is disabled.'), 'error'); $errFieldsStack[] = 'domain_sqld_limit'; $errFieldsStack[] = 'domain_sqlu_limit'; } } // Check for the Sql users limit if ($data['fallback_domain_sqlu_limit'] != -1) { if (!imscp_limit_check($data['domain_sqlu_limit'])) { set_page_message(tr('Wrong syntax for the %s limit.', tr('SQL users')), 'error'); $errFieldsStack[] = 'domain_sqlu_limit'; } elseif (!_reseller_isValidServiceLimit($data['domain_sqlu_limit'], $data['nbSqlUsers'], $data["fallback_domain_sqlu_limit"], $data['current_sql_user_cnt'], $data['max_sql_user_cnt'], $data['nbSqlUsers'] > 1 ? tr('SQL users') : tr('SQL user'))) { $errFieldsStack[] = 'domain_sqlu_limit'; } elseif ($data['domain_sqlu_limit'] != -1 && $data['domain_sqld_limit'] == -1) { set_page_message(tr('SQL database limit is disabled.'), 'error'); $errFieldsStack[] = 'domain_sqlu_limit'; $errFieldsStack[] = 'domain_sqld_limit'; } } // Check for the monthly traffic limit if (!imscp_limit_check($data['domain_traffic_limit'], null)) { set_page_message(tr('Wrong syntax for the %s limit.', tr('traffic')), 'error'); $errFieldsStack[] = 'domain_traffic_limit'; } elseif (!_reseller_isValidServiceLimit($data['domain_traffic_limit'], $data['domainTraffic'] / 1048576, $data["fallback_domain_traffic_limit"], $data['current_traff_amnt'], $data['max_traff_amnt'], tr('traffic'))) { $errFieldsStack[] = 'domain_traffic_limit'; } // Check for the disk space limit if (!imscp_limit_check($data['domain_disk_limit'], null)) { set_page_message(tr('Wrong syntax for the %s limit.', tr('disk space')), 'error'); $errFieldsStack[] = 'domain_disk_limit'; } elseif (!_reseller_isValidServiceLimit($data['domain_disk_limit'], $data['domain_disk_usage'] / 1048576, $data["fallback_domain_disk_limit"], $data['current_disk_amnt'], $data['max_disk_amnt'], tr('disk space'))) { $errFieldsStack[] = 'domain_disk_limit'; } // Check for mail quota if ($data['fallback_domain_mailacc_limit'] != -1) { if (!imscp_limit_check($data['mail_quota'], null)) { set_page_message(tr('Wrong syntax for the mail quota value.'), 'error'); $errFieldsStack[] = 'mail_quota'; } elseif ($data['domain_disk_limit'] != 0 && $data['mail_quota'] > $data['domain_disk_limit']) { set_page_message(tr('Email quota cannot be bigger than disk space limit.'), 'error'); $errFieldsStack[] = 'mail_quota'; } elseif ($data['domain_disk_limit'] != 0 && $data['mail_quota'] == 0) { set_page_message(tr('Email quota cannot be unlimited. Max value is %d MiB.', $data['domain_disk_limit']), 'error'); $errFieldsStack[] = 'mail_quota'; } else { $mailData = reseller_getMailData($data['domain_id'], $data['fallback_mail_quota']); if ($data['mail_quota'] != 0 && $data['mail_quota'] < $mailData['nb_mailboxes']) { set_page_message(tr('Email quota cannot be lower than %d. Each mailbox should have a least 1 MiB quota.', $mailData['nb_mailboxes']), 'error'); $errFieldsStack[] = 'mail_quota'; } } } else { $data['mail_quota'] = 0; } // Check for PHP support $data['domain_php'] = in_array($data['domain_php'], array('no', 'yes')) ? $data['domain_php'] : $data['fallback_domain_php']; // PHP editor $phpini = iMSCP_PHPini::getInstance(); // Needed to track changes $phpiniClientPerms = $phpini->getClientPermission(); $phpiniDomainConf = $phpini->getDomainIni(); if (isset($_POST['php_ini_system']) && $data['domain_php'] == 'yes' && $phpini->resellerHasPermission('phpiniSystem')) { $phpini->setClientPermission('phpiniSystem', clean_input($_POST['php_ini_system'])); if ($phpini->clientHasPermission('phpiniSystem')) { if (isset($_POST['phpini_perm_allow_url_fopen'])) { $phpini->setClientPermission('phpiniAllowUrlFopen', clean_input($_POST['phpini_perm_allow_url_fopen'])); } if (isset($_POST['phpini_perm_display_errors'])) { $phpini->setClientPermission('phpiniDisplayErrors', clean_input($_POST['phpini_perm_display_errors'])); } if (isset($_POST['phpini_perm_disable_functions'])) { $phpini->setClientPermission('phpiniDisableFunctions', clean_input($_POST['phpini_perm_disable_functions'])); } if (isset($_POST['phpini_perm_mail_function'])) { $phpini->setClientPermission('phpiniMailFunction', clean_input($_POST['phpini_perm_mail_function'])); } if (isset($_POST['memory_limit'])) { // Must be set before phpiniPostMaxSize $phpini->setDomainIni('phpiniMemoryLimit', clean_input($_POST['memory_limit'])); } if (isset($_POST['post_max_size'])) { // Must be set before phpiniUploadMaxFileSize $phpini->setDomainIni('phpiniPostMaxSize', clean_input($_POST['post_max_size'])); } if (isset($_POST['upload_max_filezize'])) { $phpini->setDomainIni('phpiniUploadMaxFileSize', clean_input($_POST['upload_max_filezize'])); } if (isset($_POST['max_execution_time'])) { $phpini->setDomainIni('phpiniMaxExecutionTime', clean_input($_POST['max_execution_time'])); } if (isset($_POST['max_input_time'])) { $phpini->setDomainIni('phpiniMaxInputTime', clean_input($_POST['max_input_time'])); } } else { $phpini->loadClientPermissions(); // Reset client PHP permissions $phpini->loadDomainIni(); // Reset domain PHP configuration options } } else { $phpini->loadClientPermissions(); // Reset client PHP permissions $phpini->loadDomainIni(); // Reset domain PHP configuration options } // Check for CGI support $data['domain_cgi'] = in_array($data['domain_cgi'], array('no', 'yes')) ? $data['domain_cgi'] : $data['fallback_domain_cgi']; // Check for custom DNS records support $data['domain_dns'] = in_array($data['domain_dns'], array('no', 'yes')) ? $data['domain_dns'] : $data['fallback_domain_dns']; // Check for APS support $data['domain_software_allowed'] = in_array($data['domain_software_allowed'], array('no', 'yes')) ? $data['domain_software_allowed'] : $data['fallback_domain_software_allowed']; // Check for External mail server support $data['domain_external_mail'] = in_array($data['domain_external_mail'], array('no', 'yes')) ? $data['domain_external_mail'] : $data['fallback_domain_external_mail']; // Check for backup support $data['allowbackup'] = is_array($data['allowbackup']) ? array_intersect($data['allowbackup'], array('dmn', 'sql', 'mail')) : $data['fallback_allowbackup']; // Check for Web folder protection support $data['web_folder_protection'] = in_array($data['web_folder_protection'], array('no', 'yes')) ? $data['web_folder_protection'] : $data['fallback_web_folder_protection']; if (empty($errFieldsStack) && !Zend_Session::namespaceIsset('pageMessages')) { // Update process begin here $oldValues = array(); $newValues = array(); foreach ($data as $property => $value) { if (strpos($property, 'fallback_') !== false) { $property = substr($property, 9); $oldValues[$property] = $value; $newValues[$property] = $data[$property]; } } $needDaemonRequest = false; if ($newValues == $oldValues && $phpiniClientPerms == $phpini->getClientPermission() && $phpiniDomainConf == $phpini->getDomainIni()) { set_page_message(tr('Nothing has been changed.'), 'info'); return true; } iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditDomain, array('domainId' => $domainId)); $db->beginTransaction(); if ($phpiniClientPerms != $phpini->getClientPermission() || $phpiniDomainConf != $phpini->getDomainIni()) { $phpini->updateDomainConfigOptions($data['admin_id']); $needDaemonRequest = true; } // PHP or CGI was either enabled or disabled or PHP Settings were changed, web folder protection // properties have been updated, or domain IP was changed, so we must update the vhosts files // of all domain entities (dmn, sub, als, alssub) if ($needDaemonRequest || $data['domain_php'] != $data['fallback_domain_php'] || $data['domain_cgi'] != $data['fallback_domain_cgi'] || $data['web_folder_protection'] != $data['fallback_web_folder_protection'] || $data['domain_ip_id'] != $data['fallback_domain_ip_id']) { if ($data['domain_alias_limit'] != '-1') { exec_query('UPDATE domain_aliasses SET alias_status = ? WHERE domain_id = ? AND alias_status <> ?', array('tochange', $domainId, 'ordered')); } $needDaemonRequest = true; } if ($data['domain_dns'] != $data['fallback_domain_dns'] && $data['domain_dns'] == 'no') { // Support for custom DNS records is now disabled - We must delete all custom DNS entries // (except those that are protected), and update the DNS zone file exec_query('DELETE FROM domain_dns WHERE domain_id = ? AND owned_by = ?', array($domainId, 'custom_dns_feature')); $needDaemonRequest = true; } // Update domain properties exec_query(' UPDATE domain SET domain_expires = ?, domain_last_modified = ?, domain_mailacc_limit = ?, domain_ftpacc_limit = ?, domain_traffic_limit = ?, domain_sqld_limit = ?, domain_sqlu_limit = ?, domain_status = ?, domain_alias_limit = ?, domain_subd_limit = ?, domain_ip_id = ?, domain_disk_limit = ?, domain_php = ?, domain_cgi = ?, allowbackup = ?, domain_dns = ?, domain_software_allowed = ?, phpini_perm_system = ?, phpini_perm_allow_url_fopen = ?, phpini_perm_display_errors = ?, phpini_perm_disable_functions = ?, phpini_perm_mail_function = ?, domain_external_mail = ?, web_folder_protection = ?, mail_quota = ? WHERE domain_id = ? ', array($data['domain_expires'], time(), $data['domain_mailacc_limit'], $data['domain_ftpacc_limit'], $data['domain_traffic_limit'], $data['domain_sqld_limit'], $data['domain_sqlu_limit'], $needDaemonRequest ? 'tochange' : 'ok', $data['domain_alias_limit'], $data['domain_subd_limit'], $data['domain_ip_id'], $data['domain_disk_limit'], $data['domain_php'], $data['domain_cgi'], implode('|', $data['allowbackup']), $data['domain_dns'], $data['domain_software_allowed'], $phpini->getClientPermission('phpiniSystem'), $phpini->getClientPermission('phpiniAllowUrlFopen'), $phpini->getClientPermission('phpiniDisplayErrors'), $phpini->getClientPermission('phpiniDisableFunctions'), $phpini->getClientPermission('phpiniMailFunction'), $data['domain_external_mail'], $data['web_folder_protection'], $data['mail_quota'] * 1048576, $domainId)); //print 'ouch'; exit; // Sync mailboxes quota if needed if ($data['fallback_mail_quota'] != $data['mail_quota'] * 1048576) { sync_mailboxes_quota($domainId, $data['mail_quota'] * 1048576); } // Update domain alias IP if needed if ($data['domain_ip_id'] != $data['fallback_domain_ip_id']) { if ($data['domain_alias_limit'] != '-1') { exec_query('UPDATE domain_aliasses SET alias_ip_id = ? WHERE domain_id = ?', array($data['domain_ip_id'], $domainId)); } } // Update Ftp quota limit if needed if ($data['domain_disk_limit'] != $data['fallback_domain_disk_limit']) { exec_query(' REPLACE INTO quotalimits ( name, quota_type, per_session, limit_type, bytes_in_avail, bytes_out_avail, bytes_xfer_avail, files_in_avail, files_out_avail, files_xfer_avail ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ', array($data['domain_name'], 'group', 'false', 'hard', $data['domain_disk_limit'] * 1048576, 0, 0, 0, 0, 0)); } // Update reseller properties update_reseller_c_props($data['reseller_id']); $db->commit(); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditDomain, array('domainId' => $domainId)); if ($needDaemonRequest) { send_request(); set_page_message(tr('Domain scheduled for update.'), 'success'); } else { set_page_message(tr('Domain successfully updated.'), 'success'); } $userLogged = isset($_SESSION['logged_from']) ? $_SESSION['logged_from'] : $_SESSION['user_logged']; write_log("Domain " . decode_idna($data['domain_name']) . " has been updated by {$userLogged}", E_USER_NOTICE); return true; } } catch (iMSCP_Exception_Database $e) { $db->rollBack(); throw $e; } if (!empty($errFieldsStack)) { iMSCP_Registry::set('errFieldsStack', $errFieldsStack); } return false; }
/** * Create reseller account * * @throws Exception * @throws iMSCP_Exception * @throws iMSCP_Exception_Database * @return bool */ function admin_checkAndCreateResellerAccount() { iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddUser); $cfg = iMSCP_Registry::get('config'); $errFieldsStack = array(); $data =& admin_getData(); /** @var $db iMSCP_Database */ $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); // Check for reseller name $stmt = exec_query('SELECT COUNT(`admin_id`) `usernameExist` FROM `admin` WHERE `admin_name` = ? LIMIT 1', $data['admin_name']); $row = $stmt->fetchRow(PDO::FETCH_ASSOC); if ($row['usernameExist']) { set_page_message(tr("The username %s is not available.", '<b>' . $data['admin_name'] . '</b>'), 'error'); $errFieldsStack[] = 'admin_name'; } elseif (!validates_username($data['admin_name'])) { set_page_message(tr('Incorrect username length or syntax.'), 'error'); $errFieldsStack[] = 'admin_name'; } // check for password if (empty($data['password'])) { set_page_message(tr('You must provide a password.'), 'error'); $errFieldsStack[] = 'password'; $errFieldsStack[] = 'password_confirmation'; } elseif ($data['password'] != $data['password_confirmation']) { set_page_message(tr("Passwords do not match."), 'error'); $errFieldsStack[] = 'password'; $errFieldsStack[] = 'password_confirmation'; } elseif (!checkPasswordSyntax($data['password'])) { $errFieldsStack[] = 'password'; $errFieldsStack[] = 'password_confirmation'; } // Check for email address if (!chk_email($data['email'])) { set_page_message(tr('Incorrect syntax for email address.'), 'error'); $errFieldsStack[] = 'email'; } // Check for ip addresses - We are safe here $resellerIps = array(); foreach ($data['server_ips'] as $serverIpData) { if (in_array($serverIpData['ip_id'], $data['reseller_ips'])) { $resellerIps[] = $serverIpData['ip_id']; } } sort($resellerIps); if (empty($resellerIps)) { set_page_message(tr('You must assign at least one IP to this reseller.'), 'error'); } // Check for max domains limit if (!imscp_limit_check($data['max_dmn_cnt'], null)) { set_page_message(tr('Incorrect limit for %s.', tr('domain')), 'error'); $errFieldsStack[] = 'max_dmn_cnt'; } // Check for max subdomains limit if (!imscp_limit_check($data['max_sub_cnt'])) { set_page_message(tr('Incorrect limit for %s.', tr('subdomains')), 'error'); $errFieldsStack[] = 'max_sub_cnt'; } // check for max domain aliases limit if (!imscp_limit_check($data['max_als_cnt'])) { set_page_message(tr('Incorrect limit for %s.', tr('domain aliases')), 'error'); $errFieldsStack[] = 'max_als_cnt'; } // Check for max mail accounts limit if (!imscp_limit_check($data['max_mail_cnt'])) { set_page_message(tr('Incorrect limit for %s.', tr('email accounts')), 'error'); $errFieldsStack[] = 'max_mail_cnt'; } // Check for max ftp accounts limit if (!imscp_limit_check($data['max_ftp_cnt'])) { set_page_message(tr('Incorrect limit for %s.', tr('Ftp accounts')), 'error'); $errFieldsStack[] = 'max_ftp_cnt'; } // Check for max Sql databases limit if (!imscp_limit_check($data['max_sql_db_cnt'])) { set_page_message(tr('Incorrect limit for %s.', tr('SQL databases')), 'error'); $errFieldsStack[] = 'max_sql_db_cnt'; } elseif ($_POST['max_sql_db_cnt'] == -1 && $_POST['max_sql_user_cnt'] != -1) { set_page_message(tr('SQL database limit is disabled but SQL user limit is not.'), 'error'); $errFieldsStack[] = 'max_sql_db_cnt'; } // Check for max Sql users limit if (!imscp_limit_check($data['max_sql_user_cnt'])) { set_page_message(tr('Incorrect limit for %s.', tr('SQL users')), 'error'); $errFieldsStack[] = 'max_sql_user_cnt'; } elseif ($_POST['max_sql_user_cnt'] == -1 && $_POST['max_sql_db_cnt'] != -1) { set_page_message(tr('SQL user limit is disabled but SQL database limit is not.'), 'error'); $errFieldsStack[] = 'max_sql_user_cnt'; } // Check for max monthly traffic limit if (!imscp_limit_check($data['max_traff_amnt'], null)) { set_page_message(tr('Incorrect limit for %s.', tr('traffic')), 'error'); $errFieldsStack[] = 'max_traff_amnt'; } // Check for max disk space limit if (!imscp_limit_check($data['max_disk_amnt'], null)) { set_page_message(tr('Incorrect limit for %s.', tr('Disk space')), 'error'); $errFieldsStack[] = 'max_disk_amnt'; } // Check for PHP settings $phpini = iMSCP_PHPini::getInstance(); $phpini->setResellerPermission('phpiniSystem', $data['php_ini_system']); if ($phpini->resellerHasPermission('phpiniSystem')) { $phpini->setResellerPermission('phpiniAllowUrlFopen', $data['php_ini_al_allow_url_fopen']); $phpini->setResellerPermission('phpiniDisplayErrors', $data['php_ini_al_display_errors']); $phpini->setResellerPermission('phpiniDisableFunctions', $data['php_ini_al_disable_functions']); $phpini->setResellerPermission('phpiniMailFunction', $data['php_ini_al_mail_function']); $phpini->setResellerPermission('phpiniMemoryLimit', $data['memory_limit']); // Must be set before phpiniPostMaxSize $phpini->setResellerPermission('phpiniPostMaxSize', $data['post_max_size']); // Must be set before phpiniUploadMaxFileSize $phpini->setResellerPermission('phpiniUploadMaxFileSize', $data['upload_max_filesize']); $phpini->setResellerPermission('phpiniMaxExecutionTime', $data['max_execution_time']); $phpini->setResellerPermission('phpiniMaxInputTime', $data['max_input_time']); } if (empty($errFieldsStack) && !Zend_Session::namespaceIsset('pageMessages')) { // Update process begin here // Insert reseller personal data into database exec_query(' INSERT INTO admin ( admin_name, admin_pass, admin_type, domain_created, created_by, fname, lname, firm, zip, city, state, country, email, phone, fax, street1, street2, gender ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ', array($data['admin_name'], cryptPasswordWithSalt($data['password']), 'reseller', time(), $_SESSION['user_id'], $data['fname'], $data['lname'], $data['firm'], $data['zip'], $data['city'], $data['state'], $data['country'], $data['email'], $data['phone'], $data['fax'], $data['street1'], $data['street2'], $data['gender'])); // Get new reseller unique identifier $resellerId = $db->insertId(); // Insert reseller GUI properties into database exec_query('INSERT INTO user_gui_props (user_id, lang, layout) VALUES (?, ?, ?)', array($resellerId, $cfg['USER_INITIAL_LANG'], $cfg['USER_INITIAL_THEME'])); // Insert reseller properties into database exec_query(' INSERT INTO reseller_props ( reseller_id, reseller_ips, max_dmn_cnt, current_dmn_cnt, max_sub_cnt, current_sub_cnt, max_als_cnt, current_als_cnt, max_mail_cnt, current_mail_cnt, max_ftp_cnt, current_ftp_cnt, max_sql_db_cnt, current_sql_db_cnt, max_sql_user_cnt, current_sql_user_cnt, max_traff_amnt, current_traff_amnt, max_disk_amnt, current_disk_amnt, support_system, customer_id, software_allowed, softwaredepot_allowed, websoftwaredepot_allowed, php_ini_system, php_ini_al_disable_functions, php_ini_al_mail_function, php_ini_al_allow_url_fopen, php_ini_al_display_errors, php_ini_max_post_max_size, php_ini_max_upload_max_filesize, php_ini_max_max_execution_time, php_ini_max_max_input_time, php_ini_max_memory_limit ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ', array($resellerId, implode(';', $resellerIps) . ';', $data['max_dmn_cnt'], '0', $data['max_sub_cnt'], '0', $data['max_als_cnt'], '0', $data['max_mail_cnt'], '0', $data['max_ftp_cnt'], '0', $data['max_sql_db_cnt'], '0', $data['max_sql_user_cnt'], '0', $data['max_traff_amnt'], '0', $data['max_disk_amnt'], '0', $data['support_system'], $data['customer_id'], $data['software_allowed'], $data['softwaredepot_allowed'], $data['websoftwaredepot_allowed'], $phpini->getResellerPermission('phpiniSystem'), $phpini->getResellerPermission('phpiniDisableFunctions'), $phpini->getResellerPermission('phpiniMailFunction'), $phpini->getResellerPermission('phpiniAllowUrlFopen'), $phpini->getResellerPermission('phpiniDisplayErrors'), $phpini->getResellerPermission('phpiniPostMaxSize'), $phpini->getResellerPermission('phpiniUploadMaxFileSize'), $phpini->getResellerPermission('phpiniMaxExecutionTime'), $phpini->getResellerPermission('phpiniMaxInputTime'), $phpini->getResellerPermission('phpiniMemoryLimit'))); $db->commit(); // Creating Software repository for reseller if needed if ($data['software_allowed'] == 'yes' && !@mkdir($cfg['GUI_APS_DIR'] . '/' . $resellerId, 0750, true)) { write_log(sprintf('System was unable to create the %s directory for reseller software repository', "{$cfg['GUI_APS_DIR']}/{$resellerId}"), E_USER_ERROR); } iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddUser); send_add_user_auto_msg($_SESSION['user_id'], $data['admin_name'], $data['password'], $data['email'], $data['fname'], $data['lname'], tr('Reseller')); write_log(sprintf('A new reseller account (%s) has been created by %s', $data['admin_name'], $_SESSION['user_logged']), E_USER_NOTICE); set_page_message(tr('Reseller account successfully created.'), 'success'); return true; } } catch (iMSCP_Exception_Database $e) { $db->rollBack(); throw $e; } if (!empty($errFieldsStack)) { iMSCP_Registry::set('errFieldsStack', $errFieldsStack); } return false; }
showBadRequestErrorPage(); } $row = $stmt->fetchRow(PDO::FETCH_ASSOC); $name = $row['subdomain_alias_name']; $stmt = exec_query('SELECT mail_id FROM mail_users WHERE (mail_type LIKE ? OR mail_type = ?) AND sub_id = ? LIMIT 1', array(MT_ALSSUB_MAIL . '%', MT_ALSSUB_FORWARD, $id)); if ($stmt->rowCount()) { set_page_message(tr('Subdomain you are trying to remove has email accounts. Please remove them first.'), 'error'); redirectTo('domains_manage.php'); } $stmt = exec_query('SELECT userid FROM ftp_users WHERE userid LIKE ? LIMIT 1', "%@{$name}"); if ($stmt->rowCount()) { set_page_message(tr('Subdomain alias you are trying to remove has Ftp accounts. Please remove them first.'), 'error'); redirectTo('domains_manage.php'); } iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeDeleteSubdomain, array('subdomainId' => $id, 'subdomainName' => $name, 'type' => 'alssub')); $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); exec_query('DELETE FROM php_ini WHERE domain_id = ? AND domain_type = ?', array($id, 'subals')); exec_query('UPDATE subdomain_alias SET subdomain_alias_status = ? WHERE subdomain_alias_id = ?', array('todelete', $id)); exec_query('UPDATE ssl_certs SET status = ? WHERE domain_id = ? AND domain_type = ?', array('todelete', $id, 'alssub')); $db->commit(); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); write_log(sprintf('System was unable to remove a subdomain: %s', $e->getMessage()), E_ERROR); set_page_message('Could not remove subdomain. An unexpected error occurred.', 'error'); redirectTo('domains_manage.php'); } iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterDeleteSubdomain, array('subdomainId' => $id, 'subdomainName' => $name, 'type' => 'alssub')); send_request(); write_log(sprintf('%s scheduled deletion of the `%s` subdomain alias', decode_idna($_SESSION['user_logged']), $name), E_USER_NOTICE);
/** * Deletes an admin or reseller user * * @throws iMSCP_Exception_Database * @param int $userId User unique identifier */ function admin_deleteUser($userId) { iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeDeleteUser, array('userId' => $userId)); $userId = (int) $userId; /** @var $cfg iMSCP_Config_Handler_File */ $cfg = iMSCP_Registry::get('config'); /** @var $db iMSCP_Database */ $db = iMSCP_Database::getInstance(); $stmt = exec_query(' SELECT a.admin_type, b.logo FROM admin a LEFT JOIN user_gui_props b ON (b.user_id = a.admin_id) WHERE admin_id = ? ', $userId); $row = $stmt->fetchRow(PDO::FETCH_ASSOC); $userType = $row['admin_type']; if (empty($userType) || $userType == 'user') { showBadRequestErrorPage(); } // Users (admins/resellers) common items to delete $itemsToDelete = array('admin' => 'admin_id = ?', 'email_tpls' => 'owner_id = ?', 'tickets' => 'ticket_from = ? OR ticket_to = ?', 'user_gui_props' => 'user_id = ?'); // Note: Admin can also have they own hosting_plans bug must not be considerated // as common item since first admin must be never removed if ($userType == 'reseller') { // Getting reseller's software packages to remove if any $stmt = exec_query('SELECT software_id, software_archive FROM web_software WHERE reseller_id = ?', $userId); $swPackages = $stmt->fetchAll(PDO::FETCH_ASSOC); // Getting custom reseller isp logo if set $resellerLogo = $row['logo']; // Add specific reseller items to remove $itemsToDelete = array_merge(array('hosting_plans' => 'reseller_id = ?', 'reseller_props' => 'reseller_id = ?', 'web_software' => 'reseller_id = ?'), $itemsToDelete); } // We are using transaction to ensure data consistency and prevent any garbage in // the database. If one query fail, the whole process is reverted. try { // Cleanup database $db->beginTransaction(); foreach ($itemsToDelete as $table => $where) { // Build the DELETE statement $query = "DELETE FROM " . quoteIdentifier($table) . ($where ? " WHERE {$where}" : ''); exec_query($query, array_fill(0, substr_count($where, '?'), $userId)); } $db->commit(); // Cleanup files system // We are safe here. We don't stop the process even if files cannot be removed. That can result in garbages but // the sysadmin can easily delete them through ssh. // Deleting reseller software instaler local repository if (isset($swPackages) && !empty($swPackages)) { _admin_deleteResellerSwPackages($userId, $swPackages); } elseif ($userType == 'reseller' && is_dir($cfg['GUI_APS_DIR'] . '/' . $userId) && @rmdir($cfg['GUI_APS_DIR'] . '/' . $userId) == false) { write_log('Unable to remove reseller software directory: ' . $cfg['GUI_APS_DIR'] . '/' . $userId, E_USER_ERROR); } // Deleting user logo if (isset($resellerLogo) && !empty($resellerLogo)) { $logoPath = $cfg['GUI_ROOT_DIR'] . '/data/persistent/ispLogos/' . $resellerLogo; if (file_exists($logoPath) && @unlink($logoPath) == false) { write_log('Unable to remove user logo ' . $logoPath, E_USER_ERROR); } } $userTr = $userType == 'reseller' ? tr('Reseller') : tr('Admin'); set_page_message(tr('%s account successfully deleted.', $userTr), 'success'); write_log($_SESSION['user_logged'] . ": deletes user " . $userId, E_USER_NOTICE); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); throw $e; } iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterDeleteUser, array('userId' => $userId)); redirectTo('manage_users.php'); }
/** * Convenience method to prepare and execute a query. * * @throws iMSCP_Exception_Database When query fail * @param string $query Sql statement * @param string|int|array $bind Data to bind to the placeholders * @return iMSCP_Database_ResultSet|null A iMSCP_Database_ResultSet object that represents a result set */ function exec_query($query, $bind = null) { static $db = null; if (null === $db) { $db = iMSCP_Database::getInstance(); } try { $stmt = $db->execute($db->prepare($query), $bind); } catch (PDOException $e) { throw new iMSCP_Exception_Database($e->getMessage(), $query, $e->getCode(), $e); } return $stmt; }
/** * Add customer * * @throws iMSCP_Exception_Database * @return void */ function addCustomer() { global $hpId, $dmnName, $dmnExpire, $domainIp, $adminName, $email, $password, $customerId, $firstName, $lastName, $gender, $firm, $zip, $city, $state, $country, $phone, $fax, $street1, $street2; $cfg = iMSCP_Registry::get('config'); if (isset($_SESSION['ch_hpprops'])) { $props = $_SESSION['ch_hpprops']; unset($_SESSION['ch_hpprops']); } else { $stmt = exec_query('SELECT props FROM hosting_plans WHERE reseller_id = ? AND id = ?', array($_SESSION['user_id'], $hpId)); $data = $stmt->fetchRow(); $props = $data['props']; } list($php, $cgi, $sub, $als, $mail, $ftp, $sql_db, $sql_user, $traff, $disk, $backup, $dns, $aps, $phpEditor, $phpiniAllowUrlFopen, $phpiniDisplayErrors, $phpiniDisableFunctions, $phpMailFunction, $phpiniPostMaxSize, $phpiniUploadMaxFileSize, $phpiniMaxExecutionTime, $phpiniMaxInputTime, $phpiniMemoryLimit, $extMailServer, $webFolderProtection, $mailQuota) = explode(';', $props); $php = str_replace('_', '', $php); $cgi = str_replace('_', '', $cgi); $backup = str_replace('_', '', $backup); $dns = str_replace('_', '', $dns); $aps = str_replace('_', '', $aps); $extMailServer = str_replace('_', '', $extMailServer); $webFolderProtection = str_replace('_', '', $webFolderProtection); $encryptedPassword = cryptPasswordWithSalt($password); $db = iMSCP_Database::getInstance(); try { iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddDomain, array('domainName' => $dmnName, 'createdBy' => $_SESSION['user_id'], 'customerId' => $customerId, 'customerEmail' => $email)); $db->beginTransaction(); exec_query(' INSERT INTO admin ( admin_name, admin_pass, admin_type, domain_created, created_by, fname, lname, firm, zip, city, state, country, email, phone, fax, street1, street2, customer_id, gender, admin_status ) VALUES ( ?, ?, ?, unix_timestamp(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ', array($adminName, $encryptedPassword, 'user', $_SESSION['user_id'], $firstName, $lastName, $firm, $zip, $city, $state, $country, $email, $phone, $fax, $street1, $street2, $customerId, $gender, 'toadd')); $adminId = $db->insertId(); exec_query(' INSERT INTO domain ( domain_name, domain_admin_id, domain_created, domain_expires, domain_mailacc_limit, domain_ftpacc_limit, domain_traffic_limit, domain_sqld_limit, domain_sqlu_limit, domain_status, domain_alias_limit, domain_subd_limit, domain_ip_id, domain_disk_limit, domain_disk_usage, domain_php, domain_cgi, allowbackup, domain_dns, domain_software_allowed, phpini_perm_system, phpini_perm_allow_url_fopen, phpini_perm_display_errors, phpini_perm_disable_functions, phpini_perm_mail_function, domain_external_mail, web_folder_protection, mail_quota ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ', array($dmnName, $adminId, time(), $dmnExpire, $mail, $ftp, $traff, $sql_db, $sql_user, 'toadd', $als, $sub, $domainIp, $disk, 0, $php, $cgi, $backup, $dns, $aps, $phpEditor, $phpiniAllowUrlFopen, $phpiniDisplayErrors, $phpiniDisableFunctions, $phpMailFunction, $extMailServer, $webFolderProtection, $mailQuota)); $dmnId = $db->insertId(); if ($phpEditor == 'yes') { $phpini = iMSCP_PHPini::getInstance(); $phpini->setDomainIni('phpiniMemoryLimit', $phpiniMemoryLimit); // Must be set before phpiniPostMaxSize $phpini->setDomainIni('phpiniPostMaxSize', $phpiniPostMaxSize); // Must be set before phpiniUploadMaxFileSize $phpini->setDomainIni('phpiniUploadMaxFileSize', $phpiniUploadMaxFileSize); $phpini->setDomainIni('phpiniMaxExecutionTime', $phpiniMaxExecutionTime); $phpini->setDomainIni('phpiniMaxInputTime', $phpiniMaxInputTime); $phpini->saveDomainIni($adminId, $dmnId, 'dmn'); } exec_query('INSERT INTO htaccess_users (dmn_id, uname, upass, status) VALUES (?, ?, ?, ?)', array($dmnId, $dmnName, $encryptedPassword, 'toadd')); exec_query('INSERT INTO htaccess_groups (dmn_id, ugroup, members, status) VALUES (?, ?, ?, ?)', array($dmnId, 'statistics', $db->insertId(), 'toadd')); if ($cfg['CREATE_DEFAULT_EMAIL_ADDRESSES']) { client_mail_add_default_accounts($dmnId, $email, $dmnName); } send_add_user_auto_msg($_SESSION['user_id'], $adminName, $password, $email, $firstName, $lastName, tr('Customer')); exec_query('INSERT INTO user_gui_props (user_id, lang, layout) VALUES (?, ?, ?)', array($adminId, $cfg['USER_INITIAL_LANG'], $cfg['USER_INITIAL_THEME'])); update_reseller_c_props($_SESSION['user_id']); $db->commit(); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddDomain, array('domainName' => $dmnName, 'createdBy' => $_SESSION['user_id'], 'customerId' => $adminId, 'customerEmail' => $email, 'domainId' => $dmnId)); send_request(); write_log("{$_SESSION['user_logged']} added new customer: {$adminName}", E_USER_NOTICE); set_page_message(tr('Customer account successfully scheduled for creation.'), 'success'); redirectTo('users.php'); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); throw $e; } }
/** * Update resellers limit * * @throws iMSCP_Exception_Database * @param int $toReseller Reseller for which the givens customer are moved to * @param int $fromReseller Reseller for wich the givens customers are moved from * @param array $users List of user to move * @param array $errorsStack Error stack * @return bool */ function admin_updateResellerLimits($toReseller, $fromReseller, $users, &$errorsStack) { $toResellerProperties = imscp_getResellerProperties($toReseller); $fromResellerProperties = imscp_getResellerProperties($fromReseller, true); $usersList = explode(';', $users); for ($i = 0, $countUsersList = count($usersList) - 1; $i < $countUsersList; $i++) { $stmt = exec_query('SELECT domain_name FROM domain WHERE domain_admin_id = ?', $usersList[$i]); if ($stmt->rowCount()) { $domainName = $stmt->fields['domain_name']; list($subdomainsLimit, , $domainAliasesLimit, , $mailAccountsLimit, , $ftpAccountsLimit, , $sqlDatabasesLimit, , $sqlUsersLimit, , $trafficLimit, $diskspaceLimit) = shared_getCustomerProps($usersList[$i]); calculate_reseller_dvals($toResellerProperties['current_dmn_cnt'], $toResellerProperties['max_dmn_cnt'], $src_dmn_current, $fromResellerProperties['max_dmn_cnt'], 1, $errorsStack, 'Domain', $domainName); if ($errorsStack == '_off_') { calculate_reseller_dvals($toResellerProperties['current_sub_cnt'], $toResellerProperties['max_sub_cnt'], $fromResellerProperties['current_sub_cnt'], $fromResellerProperties['max_sub_cnt'], $subdomainsLimit, $errorsStack, 'Subdomain', $domainName); calculate_reseller_dvals($toResellerProperties['current_als_cnt'], $toResellerProperties['max_als_cnt'], $fromResellerProperties['current_als_cnt'], $fromResellerProperties['max_als_cnt'], $domainAliasesLimit, $errorsStack, 'Alias', $domainName); calculate_reseller_dvals($toResellerProperties['current_mail_cnt'], $toResellerProperties['max_mail_cnt'], $fromResellerProperties['current_mail_cnt'], $fromResellerProperties['max_mail_cnt'], $mailAccountsLimit, $errorsStack, 'Mail', $domainName); calculate_reseller_dvals($toResellerProperties['current_ftp_cnt'], $toResellerProperties['max_ftp_cnt'], $fromResellerProperties['current_ftp_cnt'], $fromResellerProperties['max_ftp_cnt'], $ftpAccountsLimit, $errorsStack, 'FTP', $domainName); calculate_reseller_dvals($toResellerProperties['current_sql_db_cnt'], $toResellerProperties['max_sql_db_cnt'], $fromResellerProperties['current_sql_db_cnt'], $fromResellerProperties['max_sql_db_cnt'], $sqlDatabasesLimit, $errorsStack, 'SQL Database', $domainName); calculate_reseller_dvals($toResellerProperties['current_sql_user_cnt'], $toResellerProperties['max_sql_user_cnt'], $fromResellerProperties['current_sql_user_cnt'], $fromResellerProperties['max_sql_user_cnt'], $sqlUsersLimit, $errorsStack, 'SQL User', $domainName); calculate_reseller_dvals($toResellerProperties['current_traff_amnt'], $toResellerProperties['max_traff_amnt'], $fromResellerProperties['current_traff_amnt'], $fromResellerProperties['max_traff_amnt'], $trafficLimit, $errorsStack, 'Traffic', $domainName); calculate_reseller_dvals($toResellerProperties['current_disk_amnt'], $toResellerProperties['max_disk_amnt'], $fromResellerProperties['current_disk_amnt'], $fromResellerProperties['max_disk_amnt'], $diskspaceLimit, $errorsStack, 'Disk', $domainName); } if ($errorsStack != '_off_') { return false; } } else { } } // Update reseller properties /** @var $db iMSCP_Database */ $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); $newFromResellerProperties = "{$fromResellerProperties['current_dmn_cnt']};{$fromResellerProperties['max_dmn_cnt']};"; $newFromResellerProperties .= "{$fromResellerProperties['current_sub_cnt']};{$fromResellerProperties['max_sub_cnt']};"; $newFromResellerProperties .= "{$fromResellerProperties['current_als_cnt']};{$fromResellerProperties['max_als_cnt']};"; $newFromResellerProperties .= "{$fromResellerProperties['current_mail_cnt']};{$fromResellerProperties['max_mail_cnt']};"; $newFromResellerProperties .= "{$fromResellerProperties['current_ftp_cnt']};{$fromResellerProperties['max_ftp_cnt']};"; $newFromResellerProperties .= "{$fromResellerProperties['current_sql_db_cnt']};{$fromResellerProperties['max_sql_db_cnt']};"; $newFromResellerProperties .= "{$fromResellerProperties['current_sql_user_cnt']};{$fromResellerProperties['max_sql_user_cnt']};"; $newFromResellerProperties .= "{$fromResellerProperties['current_traff_amnt']};{$fromResellerProperties['max_traff_amnt']};"; $newFromResellerProperties .= "{$fromResellerProperties['current_disk_amnt']};{$fromResellerProperties['max_disk_amnt']};"; update_reseller_props($fromReseller, $newFromResellerProperties); $newToResellerProperties = "{$toResellerProperties['current_dmn_cnt']};{$toResellerProperties['max_dmn_cnt']};"; $newToResellerProperties .= "{$toResellerProperties['current_sub_cnt']};{$toResellerProperties['max_sub_cnt']};"; $newToResellerProperties .= "{$toResellerProperties['current_als_cnt']};{$toResellerProperties['max_als_cnt']};"; $newToResellerProperties .= "{$toResellerProperties['current_mail_cnt']};{$toResellerProperties['max_mail_cnt']};"; $newToResellerProperties .= "{$toResellerProperties['current_ftp_cnt']};{$toResellerProperties['max_ftp_cnt']};"; $newToResellerProperties .= "{$toResellerProperties['current_sql_db_cnt']};{$toResellerProperties['max_sql_db_cnt']};"; $newToResellerProperties .= "{$toResellerProperties['current_sql_user_cnt']};{$toResellerProperties['max_sql_user_cnt']};"; $newToResellerProperties .= "{$toResellerProperties['current_traff_amnt']};{$toResellerProperties['max_traff_amnt']};"; $newToResellerProperties .= "{$toResellerProperties['current_disk_amnt']};{$toResellerProperties['max_disk_amnt']};"; update_reseller_props($toReseller, $newToResellerProperties); for ($i = 0, $countUsersList = count($usersList) - 1; $i < $countUsersList; $i++) { $query = 'UPDATE `admin` SET `created_by` = ? WHERE `admin_id` = ?'; exec_query($query, array($toReseller, $usersList[$i])); } $db->commit(); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); throw $e; } return true; }
/** * Add new domain alias * * @return bool TRUE on success, FALSE on failure */ function addDomainAlias() { global $mainDmnProps; // Basic check if (empty($_POST['domain_alias_name'])) { set_page_message(tr('You must enter a domain alias name.'), 'error'); return false; } $domainAliasName = clean_input(strtolower($_POST['domain_alias_name'])); // Check for domain alias name syntax global $dmnNameValidationErrMsg; if (!isValidDomainName($domainAliasName)) { set_page_message($dmnNameValidationErrMsg, 'error'); return false; } // www is considered as an alias of the domain alias while (strpos($domainAliasName, 'www.') !== false) { $domainAliasName = substr($domainAliasName, 4); } // Check for domain alias existence if (imscp_domain_exists($domainAliasName, $_SESSION['user_created_by'])) { set_page_message(tr('Domain %s is unavailable.', "<strong>{$domainAliasName}</strong>"), 'error'); return false; } $domainAliasNameAscii = encode_idna($domainAliasName); // Set default mount point $mountPoint = "/{$domainAliasNameAscii}"; // Check for shared mount point option if (isset($_POST['shared_mount_point']) && $_POST['shared_mount_point'] == 'yes') { // We are safe here if (!isset($_POST['shared_mount_point_domain'])) { showBadRequestErrorPage(); } $sharedMountPointDomain = clean_input($_POST['shared_mount_point_domain']); $domainList = _client_getDomainsList(); // Get shared mount point foreach ($domainList as $domain) { if ($domain['name'] == $sharedMountPointDomain) { $mountPoint = $domain['mount_point']; } } } // Check for URL forwarding option $forwardUrl = 'no'; if (isset($_POST['url_forwarding']) && $_POST['url_forwarding'] == 'yes') { if (!isset($_POST['forward_url_scheme']) || isset($_POST['forward_url'])) { showBadRequestErrorPage(); } $forwardUrl = clean_input($_POST['forward_url_scheme']) . clean_input($_POST['forward_url']); try { try { $uri = iMSCP_Uri_Redirect::fromString($forwardUrl); } catch (Zend_Uri_Exception $e) { throw new iMSCP_Exception(tr('Forward URL %s is not valid.', "<strong>{$forwardUrl}</strong>")); } $uri->setHost(encode_idna($uri->getHost())); if ($uri->getHost() == $domainAliasNameAscii && $uri->getPath() == '/') { throw new iMSCP_Exception(tr('Forward URL %s is not valid.', "<strong>{$forwardUrl}</strong>") . ' ' . tr('Domain alias %s cannot be forwarded on itself.', "<strong>{$domainAliasName}</strong>")); } $forwardUrl = $uri->getUri(); } catch (Exception $e) { set_page_message($e->getMessage(), 'error'); return false; } } $isSuUser = isset($_SESSION['logged_from_type']); # See http://youtrack.i-mscp.net/issue/IP-1486 $userEmail = isset($_SESSION['user_email']) ? $_SESSION['user_email'] : ''; $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddDomainAlias, array('domainId' => $mainDmnProps['domain_id'], 'domainAliasName' => $domainAliasNameAscii)); exec_query(' INSERT INTO domain_aliasses ( domain_id, alias_name, alias_mount, alias_status, alias_ip_id, url_forward ) VALUES ( ?, ?, ?, ?, ?, ? ) ', array($mainDmnProps['domain_id'], $domainAliasNameAscii, $mountPoint, $isSuUser ? 'toadd' : 'ordered', $mainDmnProps['domain_ip_id'], $forwardUrl)); $id = $db->insertId(); // Create the phpini entry for that domain alias $phpini = iMSCP_PHPini::getInstance(); $phpini->loadResellerPermissions($_SESSION['user_created_by']); // Load reseller PHP permissions $phpini->loadClientPermissions($_SESSION['user_id']); // Load client PHP permissions $phpini->loadDomainIni($_SESSION['user_id'], $mainDmnProps['domain_id'], 'dmn'); // Load main domain PHP configuration options $phpini->saveDomainIni($_SESSION['user_id'], $id, 'als'); if ($isSuUser) { $cfg = iMSCP_Registry::get('config'); if ($cfg['CREATE_DEFAULT_EMAIL_ADDRESSES'] && $userEmail !== '') { client_mail_add_default_accounts($mainDmnProps['domain_id'], $userEmail, $domainAliasNameAscii, 'alias', $id); } } $db->commit(); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddDomainAlias, array('domainId' => $mainDmnProps['domain_id'], 'domainAliasName' => $domainAliasNameAscii, 'domainAliasId' => $id)); if ($isSuUser) { send_request(); write_log(sprintf('A new `%s` domain alias has been created by: %s', $domainAliasName, $_SESSION['user_logged']), E_USER_NOTICE); set_page_message(tr('Domain alias successfully created.'), 'success'); } else { send_alias_order_email($domainAliasName); write_log(sprintf('A new `%s` domain alias has been ordered by: %s', $domainAliasName, decode_idna($_SESSION['user_logged'])), E_USER_NOTICE); set_page_message(tr('Domain alias successfully ordered.'), 'success'); } } catch (iMSCP_Exception_Database $e) { $db->rollBack(); write_log(sprintf('System was unable to create the `%s` domain alias: %s', $domainAliasName, $e->getMessage()), E_USER_ERROR); set_page_message(tr('Could not create domain alias. An unexpected error occurred.'), 'error'); return false; } return true; }
/** * Check database connection. * * @param string $sql_database * @param string $sql_user * @param string $sql_pass * @return bool */ function check_db_connection($sql_database, $sql_user, $sql_pass) { /** @var $cfg iMSCP_Config_Handler_File */ $cfg = iMSCP_Registry::get('config'); try { iMSCP_Database::connect($sql_user, $sql_pass, $cfg->DATABASE_TYPE, $cfg->DATABASE_HOST, $sql_database, 'privateConnection'); } catch (PDOException $e) { return false; } return true; }