/** * Updates htaccess user. * * @param int $dmn_id Domain unique identifier * @param int $uuser_id Htaccess user unique identifier * @return */ function client_updateHtaccessUser(&$dmn_id, &$uuser_id) { if (isset($_POST['uaction']) && $_POST['uaction'] == 'modify_user') { // we have to add the user if (isset($_POST['pass']) && isset($_POST['pass_rep'])) { if (!checkPasswordSyntax($_POST['pass'])) { return; } if ($_POST['pass'] !== $_POST['pass_rep']) { set_page_message(tr("Passwords do not match."), 'error'); return; } $nadmin_password = cryptPasswordWithSalt($_POST['pass'], generateRandomSalt(true)); $change_status = 'tochange'; $query = "\n\t\t\t\tUPDATE\n\t\t\t\t\t`htaccess_users`\n\t\t\t\tSET\n\t\t\t\t\t`upass` = ?, `status` = ?\n\t\t\t\tWHERE\n\t\t\t\t\t`dmn_id` = ?\n\t\t\t\tAND\n\t\t\t\t\t`id` = ?\n\t\t\t"; exec_query($query, array($nadmin_password, $change_status, $dmn_id, $uuser_id)); send_request(); $query = "\n\t\t\t\tSELECT\n\t\t\t\t\t`uname`\n\t\t\t\tFROM\n\t\t\t\t\t`htaccess_users`\n\t\t\t\tWHERE\n\t\t\t\t\t`dmn_id` = ?\n\t\t\t\tAND\n\t\t\t\t\t`id` = ?\n\t\t\t"; $rs = exec_query($query, array($dmn_id, $uuser_id)); $uname = $rs->fields['uname']; $admin_login = $_SESSION['user_logged']; write_log("{$admin_login}: updated htaccess user ID: {$uname}", E_USER_NOTICE); redirectTo('protected_user_manage.php'); } } else { return; } }
/** * Update Ftp account * * @param string $userid Ftp userid * @param string $mainDomainName Main domain name * @return bool TRUE on success, FALSE on failure */ function updateFtpAccount($userid, $mainDomainName) { $ret = true; if (!empty($_POST['password'])) { if (empty($_POST['password_repeat']) || $_POST['password'] !== $_POST['password_repeat']) { set_page_message(tr("Passwords do not match."), 'error'); $ret = false; } if (!checkPasswordSyntax($_POST['password'])) { $ret = false; } $rawPassword = $_POST['password']; $password = cryptPasswordWithSalt($rawPassword); } if (isset($_POST['home_dir'])) { $homeDir = clean_input($_POST['home_dir']); 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($mainDomainName); // Check for directory existence if (!$vfs->exists($homeDir)) { set_page_message(tr("Home directory '%s' doesn't exist", $homeDir), 'error'); $ret = false; } } } } else { showBadRequestErrorPage(); exit; } if ($ret) { iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditFtp, array('ftpUserId' => $userid)); /** @var $cfg iMSCP_Config_Handler_File */ $cfg = iMSCP_Registry::get('config'); $homeDir = rtrim(str_replace('//', '/', $cfg->USER_WEB_DIR . '/' . $mainDomainName . '/' . $homeDir), '/'); if (isset($rawPassword) && isset($password) && isset($homeDir)) { $query = "UPDATE `ftp_users` SET `passwd` = ?, `rawpasswd` = ?, `homedir` = ? WHERE `userid` = ?"; exec_query($query, array($password, $rawPassword, $homeDir, $userid)); } else { $query = "UPDATE `ftp_users` SET `homedir` = ? WHERE `userid` = ?"; exec_query($query, array($homeDir, $userid)); } iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditFtp, array('ftpUserId' => $userid)); write_log(sprintf("%s updated Ftp account: %s", $_SESSION['user_logged'], $userid), E_USER_NOTICE); set_page_message(tr('FTP account successfully updated.'), 'success'); } return $ret; }
/** * Update SQL user password * * @param int $id Sql user id * @param string $user Sql user name * @param string $host SQL user host * @çeturn void */ function client_updateSqlUserPassword($id, $user, $host) { if (!isset($_POST['uaction'])) { return; } if (!isset($_POST['password']) || !isset($_POST['password_confirmation'])) { showBadRequestErrorPage(); } $password = clean_input($_POST['password']); $passwordConf = clean_input($_POST['password_confirmation']); if ($password === '') { set_page_message(tr('Password cannot be empty.'), 'error'); return; } if ($passwordConf === '') { set_page_message(tr('Please confirm the password.'), 'error'); return; } if ($password !== $passwordConf) { set_page_message(tr('Passwords do not match.'), 'error'); return; } if (!checkPasswordSyntax($password)) { return; } $config = iMSCP_Registry::get('config'); $mysqlConfig = new iMSCP_Config_Handler_File($config['CONF_DIR'] . '/mysql/mysql.data'); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditSqlUser, array('sqlUserId' => $id)); // Here we cannot use transaction due to statements that cause an implicit commit. Thus we execute // those statements first to let the i-MSCP database in clean state if one of them fails. // See https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html for more details // Update SQL user password in the mysql system tables; if (strpos('mariadb', $config['SQL_SERVER']) !== false || version_compare($mysqlConfig['SQLD_VERSION'], '5.7.6', '<')) { exec_query('SET PASSWORD FOR ?@? = PASSWORD(?)', array($user, $host, $password)); } else { exec_query('ALTER USER ?@? IDENTIFIED BY ? PASSWORD EXPIRE NEVER', array($user, $host, $password)); } exec_query('UPDATE sql_user SET sqlu_pass = ? WHERE sqlu_name = ? AND sqlu_host = ?', array($password, $user, $host)); set_page_message(tr('SQL user password successfully updated.'), 'success'); write_log(sprintf('%s updated %s@%s SQL user password.', decode_idna($_SESSION['user_logged']), $user, $host), E_USER_NOTICE); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditSqlUser, array('sqlUserId' => $id)); redirectTo('sql_manage.php'); }
/** * Add Htaccess user. * * @param int $domainId Domain unique identifier * @return */ function client_addHtaccessUser($domainId) { if (isset($_POST['uaction']) && $_POST['uaction'] == 'add_user') { // we have to add the user if (isset($_POST['username']) && isset($_POST['pass']) && isset($_POST['pass_rep'])) { if (!validates_username($_POST['username'])) { set_page_message(tr('Wrong username.'), 'error'); return; } if (!checkPasswordSyntax($_POST['pass'])) { return; } if ($_POST['pass'] !== $_POST['pass_rep']) { set_page_message(tr("Passwords do not match."), 'error'); return; } $status = 'toadd'; $uname = clean_input($_POST['username']); $upass = cryptPasswordWithSalt($_POST['pass'], generateRandomSalt(true)); $query = "\n\t\t\t\tSELECT\n\t\t\t\t\t`id`\n\t\t\t\tFROM\n\t\t\t\t\t`htaccess_users`\n\t\t\t\tWHERE\n\t\t\t\t\t`uname` = ?\n\t\t\t\tAND\n\t\t\t\t\t`dmn_id` = ?\n\t\t\t"; $rs = exec_query($query, array($uname, $domainId)); if ($rs->rowCount() == 0) { $query = "\n\t\t\t\t\tINSERT INTO `htaccess_users` (\n\t\t\t\t\t `dmn_id`, `uname`, `upass`, `status`\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t ?, ?, ?, ?\n\t\t\t\t\t)\n\t\t\t\t"; exec_query($query, array($domainId, $uname, $upass, $status)); send_request(); set_page_message(tr('Htaccess user successfully scheduled for addition.'), 'success'); $admin_login = $_SESSION['user_logged']; write_log("{$admin_login}: added new htaccess user: {$uname}", E_USER_NOTICE); redirectTo('protected_user_manage.php'); } else { set_page_message(tr('This htaccess user already exist.'), 'error'); return; } } } else { return; } }
/** * Update admin password. * * @return void */ function reseller_updatePassword() { if (!empty($_POST)) { $userId = $_SESSION['user_id']; iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditUser, array('userId' => $userId)); if (empty($_POST['current_password']) || empty($_POST['password']) || empty($_POST['password_confirmation'])) { set_page_message(tr('All fields are required.'), 'error'); } else { if (!_reseller_checkCurrentPassword($_POST['current_password'])) { set_page_message(tr('Current password is invalid.'), 'error'); } else { if ($_POST['password'] !== $_POST['password_confirmation']) { set_page_message(tr("Passwords do not match."), 'error'); } elseif (checkPasswordSyntax($_POST['password'])) { $query = 'UPDATE `admin` SET `admin_pass` = ? WHERE `admin_id` = ?'; exec_query($query, array(cryptPasswordWithSalt($_POST['password']), $userId)); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditUser, array('userId' => $userId)); write_log($_SESSION['user_logged'] . ': updated password.', E_USER_NOTICE); set_page_message(tr('Password successfully updated.'), 'success'); } } } } }
/** * 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; }
/** * Edit mail account * * @throws iMSCP_Exception * @return bool TRUE on success, FALSE otherwise */ function client_editMailAccount() { if (isset($_POST['password']) && isset($_POST['password_rep']) && isset($_POST['quota']) && isset($_POST['forward_list'])) { $mailData = client_getEmailAccountData(clean_input($_GET['id'])); $mainDmnProps = get_domain_default_props($_SESSION['user_id']); $password = $forwardList = '_no_'; $mailType = ''; $quota = null; if (preg_match('/^(.*?)_(?:mail|forward)/', $mailData['mail_type'], $match)) { $domainType = $match[1]; } else { throw new iMSCP_Exception('Unable to determine mail type'); } $mailTypeNormal = isset($_POST['account_type']) && in_array($_POST['account_type'], array('1', '3')); $mailTypeForward = isset($_POST['account_type']) && in_array($_POST['account_type'], array('2', '3')); if (!$mailTypeNormal && !$mailTypeForward) { showBadRequestErrorPage(); } $mailAddr = $mailData['mail_addr']; if ($mailTypeNormal) { // Check for pasword $password = clean_input($_POST['password']); $password_rep = clean_input($_POST['password_rep']); if ($mailData['mail_pass'] == '_no_' || $password != '' || $password_rep != '') { if ($password == '') { set_page_message(tr('Password is missing.'), 'error'); return false; } elseif ($password_rep == '') { set_page_message(tr('You must confirm your password.'), 'error'); return false; } elseif ($password !== $password_rep) { set_page_message(tr("Passwords do not match."), 'error'); return false; } elseif (!checkPasswordSyntax($password)) { return false; } } else { $password = $mailData['mail_pass']; } // Check for quota $quota = clean_input($_POST['quota']); if (is_number($quota)) { $quota *= 1048576; // MiB to Bytes if ($mainDmnProps['mail_quota'] != '0') { if ($quota == '0') { set_page_message(tr('Incorrect Email quota.'), 'error'); return false; } $stmt = exec_query('SELECT SUM(`quota`) AS `quota` FROM `mail_users` WHERE `domain_id` = ? AND `quota` IS NOT NULL', $mainDmnProps['domain_id']); $quotaLimit = floor($mainDmnProps['mail_quota'] - ($stmt->fields['quota'] - $mailData['quota'])); if ($quota > $quotaLimit) { set_page_message(tr('Email quota cannot be bigger than %s', bytesHuman($quotaLimit, 'MiB')), 'error'); return false; } } } else { set_page_message(tr('Email quota must be a number.'), 'error'); return false; } switch ($domainType) { case 'normal': $mailType = MT_NORMAL_MAIL; break; case 'subdom': $mailType = MT_SUBDOM_MAIL; break; case 'alias': $mailType = MT_ALIAS_MAIL; break; case 'alssub': $mailType = MT_ALSSUB_MAIL; } } if ($mailTypeForward) { // Check forward list $forwardList = clean_input($_POST['forward_list']); if ($forwardList == '') { set_page_message(tr('Forward list is empty.'), 'error'); return false; } $forwardList = preg_split("/[\n,]+/", $forwardList); foreach ($forwardList as $key => &$forwardEmailAddr) { $forwardEmailAddr = encode_idna(trim($forwardEmailAddr)); if ($forwardEmailAddr == '') { unset($forwardList[$key]); } elseif (!chk_email($forwardEmailAddr)) { set_page_message(tr('Wrong mail syntax in forward list.'), 'error'); return false; } elseif ($forwardEmailAddr == $mailAddr) { set_page_message(tr('You cannot forward %s on itself.', $mailAddr), 'error'); return false; } } $forwardList = implode(',', array_unique($forwardList)); switch ($domainType) { case 'normal': $mailType .= ($mailType != '' ? ',' : '') . MT_NORMAL_FORWARD; break; case 'subdom': $mailType .= ($mailType != '' ? ',' : '') . MT_SUBDOM_FORWARD; break; case 'alias': $mailType .= ($mailType != '' ? ',' : '') . MT_ALIAS_FORWARD; break; case 'alssub': $mailType .= ($mailType != '' ? ',' : '') . MT_ALSSUB_FORWARD; } } // Update mail account into database iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditMail, array('mailId' => $mailData['mail_id'])); $query = ' UPDATE `mail_users` SET `mail_pass` = ?, `mail_forward` = ?, `mail_type` = ?, `status` = ?, `quota` = ? WHERE `mail_id` = ? '; exec_query($query, array($password, $forwardList, $mailType, 'tochange', $quota, $mailData['mail_id'])); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditMail, array('mailId' => $mailData['mail_id'])); // Schedule mail account addition send_request(); write_log("{$_SESSION['user_logged']}: Updated Email account: {$mailAddr}", E_USER_NOTICE); set_page_message(tr('Email account successfully scheduled for update.'), 'success'); } else { showBadRequestErrorPage(); } return true; }
/** * @return bool */ function check_user_data() { if (!validates_username($_POST['username'])) { set_page_message(tr('Incorrect username length or syntax.'), 'error'); return false; } if ($_POST['password'] != $_POST['password_confirmation']) { set_page_message(tr("Passwords do not match."), 'error'); return false; } if (!checkPasswordSyntax($_POST['password'])) { return false; } if (!chk_email($_POST['email'])) { set_page_message(tr("Incorrect email length or syntax."), 'error'); return false; } $query = "SELECT `admin_id` FROM `admin` WHERE `admin_name` = ?"; $username = clean_input($_POST['username']); $rs = exec_query($query, $username); if ($rs->recordCount() != 0) { set_page_message(tr('This user name already exist.'), 'warning'); return false; } return true; }
mail_auto_respond_text, quota, mail_addr ) VALUES ( :mail_acc, :mail_pass, :mail_forward, :domain_id, :mail_type, :sub_id, :status, :mail_auto_respond, :mail_auto_respond_text, :quota, :mail_addr ) '); // Create i-MSCP mail accounts using entries from CSV file while (($csvEntry = fgetcsv($handle, 1024, $csvDelimiter)) !== false) { $mailAddr = trim($csvEntry[0]); $asciiMailAddr = encode_idna($mailAddr); $mailPassword = trim($csvEntry[1]); try { if (!chk_email($asciiMailAddr)) { throw new iMSCP_Exception(sprintf('%s is not a valid email address.', $mailAddr)); } if (checkPasswordSyntax($mailPassword)) { list($mailUser, $mailDomain) = explode('@', $asciiMailAddr); $mailAccount = array_merge(cli_getMailData($mailDomain), array('mail_acc' => $mailUser, 'mail_pass' => $mailPassword, 'mail_forward' => '_no_', 'status' => 'toadd', 'mail_auto_respond' => '0', 'mail_auto_respond_text' => null, 'quota' => '0', 'mail_addr' => $asciiMailAddr)); try { $stmt->execute($mailAccount); printf("The %s mail account has been successfully inserted into the i-MSCP database.\n", $mailAddr); } catch (PDOException $e) { if ($e->getCode() == 23000) { printf("WARN: The %s mail account already exists in the i-MSCP database. Skipping.\n", $mailAddr); } else { fwrite(STDERR, sprintf("ERROR: Unable to insert the %s mail account in the i-MSCP database: %s\n", $mailAddr, $e->getMessage())); } } } else { throw new iMSCP_Exception(sprintf('Wrong password syntax or length for the %s mail account.', $mailAddr)); }
/** * Function to update changes into db * * @param int $adminId Customer unique identifier * @return void */ function reseller_updateUserData($adminId) { iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditUser, array('userId' => $adminId)); global $adminName, $email, $customerId, $firstName, $lastName, $firm, $zip, $gender, $city, $state, $country, $street1, $street2, $phone, $fax, $password, $passwordRepeat; $resellerId = intval($_SESSION['user_id']); if ($password === '' && $passwordRepeat === '') { // Save without password exec_query(' UPDATE admin SET fname = ?, lname = ?, firm = ?, zip = ?, city = ?, state = ?, country = ?, email = ?, phone = ?, fax = ?, street1 = ?, street2 = ?, gender = ?, customer_id = ? WHERE admin_id = ? AND created_by = ? ', array($firstName, $lastName, $firm, $zip, $city, $state, $country, $email, $phone, $fax, $street1, $street2, $gender, $customerId, $adminId, $resellerId)); } else { // Change password if ($password != $passwordRepeat) { set_page_message(tr("Passwords do not match."), 'error'); redirectTo('user_edit.php?edit_id=' . $adminId); } if (!checkPasswordSyntax($password)) { redirectTo('user_edit.php?edit_id=' . $adminId); } $encryptedPassword = cryptPasswordWithSalt($password); exec_query(' UPDATE admin SET admin_pass = ?, fname = ?, lname = ?, firm = ?, zip = ?, city = ?, state = ?, country = ?, email = ?, phone = ?, fax = ?, street1 = ?, street2 = ?, gender = ?, customer_id = ? WHERE admin_id = ? AND created_by = ? ', array($encryptedPassword, $firstName, $lastName, $firm, $zip, $city, $state, $country, $email, $phone, $fax, $street1, $street2, $gender, $customerId, $adminId, $resellerId)); $adminName = get_user_name($adminId); exec_query('DELETE FROM login WHERE user_name = ?', $adminName); } iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditUser, array('userId' => $adminId)); set_page_message(tr('User data successfully updated'), 'success'); write_log("{$_SESSION['user_logged']} updated data for {$adminName}.", E_USER_NOTICE); if (isset($_POST['send_data']) && $password !== '') { send_add_user_auto_msg($resellerId, $adminName, $password, $email, $firstName, $lastName, tr('Customer')); } redirectTo('users.php'); }
/** * Add mail account * * @return bool TRUE on success, FALSE otherwise */ function client_addMailAccount() { if (isset($_POST['username']) && isset($_POST['domain_name']) && isset($_POST['password']) && isset($_POST['password_rep']) && isset($_POST['quota']) && isset($_POST['forward_list'])) { $mainDmnProps = get_domain_default_props($_SESSION['user_id']); $password = $forwardList = '_no_'; $mailType = $subId = ''; $quota = null; $mailTypeNormal = isset($_POST['account_type']) && in_array($_POST['account_type'], array('1', '3')); $mailTypeForward = isset($_POST['account_type']) && in_array($_POST['account_type'], array('2', '3')); if (!$mailTypeNormal && !$mailTypeForward) { showBadRequestErrorPage(); } // Check for username $username = strtolower(clean_input($_POST['username'])); if ($_POST['username'] == '' || !chk_email($username, true)) { set_page_message(tr('Invalid email username.'), 'error'); return false; } // Check for domain existence and owner $domainName = clean_input($_POST['domain_name']); $domainType = null; $domainId = null; foreach (_client_getDomainsList() as $domain) { if ($domain['name'] == $domainName) { $domainType = $domain['type']; $domainId = $domain['id']; $subId = $domainType != 'dmn' ? $domainId : '0'; } } if (null !== $domainType) { $mailAddr = $username . '@' . $domainName; if ($mailTypeNormal) { // Check for pasword $password = clean_input($_POST['password']); $password_rep = clean_input($_POST['password_rep']); if ($password == '') { set_page_message(tr('Password is missing.'), 'error'); return false; } elseif ($password_rep == '') { set_page_message(tr('You must confirm your password.'), 'error'); return false; } elseif ($password !== $password_rep) { set_page_message(tr("Passwords do not match."), 'error'); return false; } elseif (!checkPasswordSyntax($password)) { return false; } // Check for quota $quota = clean_input($_POST['quota']); if (is_number($quota)) { $quota *= 1048576; // MiB to Bytes if ($mainDmnProps['mail_quota'] != '0') { if ($quota == '0') { set_page_message(tr('Incorrect email quota.'), 'error'); return false; } $stmt = exec_query('SELECT SUM(`quota`) AS `quota` FROM `mail_users` WHERE `domain_id` = ? AND `quota` IS NOT NULL', $mainDmnProps['domain_id']); $quotaLimit = floor($mainDmnProps['mail_quota'] - $stmt->fields['quota']); if ($quota > $quotaLimit) { set_page_message(tr('Email quota cannot be bigger than %s', bytesHuman($quotaLimit, 'MiB')), 'error'); return false; } } } else { set_page_message(tr('Email quota must be a number.'), 'error'); return false; } switch ($domainType) { case 'dmn': $mailType = MT_NORMAL_MAIL; break; case 'sub': $mailType = MT_SUBDOM_MAIL; break; case 'als': $mailType = MT_ALIAS_MAIL; break; case 'alssub': $mailType = MT_ALSSUB_MAIL; } } if ($mailTypeForward) { // Check forward list $forwardList = clean_input($_POST['forward_list']); if ($forwardList == '') { set_page_message(tr('Forward list is empty.'), 'error'); return false; } $forwardList = preg_split("/[\n,]+/", $forwardList); foreach ($forwardList as $key => &$forwardEmailAddr) { $forwardEmailAddr = encode_idna(trim($forwardEmailAddr)); if ($forwardEmailAddr == '') { unset($forwardList[$key]); } elseif (!chk_email($forwardEmailAddr)) { set_page_message(tr('Wrong mail syntax in forward list.'), 'error'); return false; } elseif ($forwardEmailAddr == $mailAddr) { set_page_message(tr('You cannot forward %s on itself.', $mailAddr), 'error'); return false; } } $forwardList = implode(',', array_unique($forwardList)); switch ($domainType) { case 'dmn': $mailType .= ($mailType != '' ? ',' : '') . MT_NORMAL_FORWARD; break; case 'sub': $mailType .= ($mailType != '' ? ',' : '') . MT_SUBDOM_FORWARD; break; case 'als': $mailType .= ($mailType != '' ? ',' : '') . MT_ALIAS_FORWARD; break; case 'alssub': $mailType .= ($mailType != '' ? ',' : '') . MT_ALSSUB_FORWARD; } } // Add mail account into database try { /** @var $db iMSCP_Database */ $db = iMSCP_Registry::get('db'); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddMail, array('mailUsername' => $username, 'MailAddress' => $mailAddr)); $query = ' INSERT INTO `mail_users` ( `mail_acc`, `mail_pass`, `mail_forward`, `domain_id`, `mail_type`, `sub_id`, `status`, `mail_auto_respond`, `mail_auto_respond_text`, `quota`, `mail_addr` ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) '; exec_query($query, array($username, $password, $forwardList, $mainDmnProps['domain_id'], $mailType, $subId, 'toadd', '0', NULL, $quota, $mailAddr)); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddMail, array('mailUsername' => $username, 'mailAddress' => $mailAddr, 'mailId' => $db->insertId())); // Schedule mail account addition send_request(); write_log("{$_SESSION['user_logged']}: added new Email account: {$mailAddr}", E_USER_NOTICE); set_page_message(tr('Email account successfully scheduled for addition.'), 'success'); } catch (iMSCP_Exception_Database $e) { if ($e->getCode() == 23000) { set_page_message(tr('Email account already exists.'), 'error'); return false; } } } else { showBadRequestErrorPage(); } } else { showBadRequestErrorPage(); } return true; }
/** * 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; }
/** * Generates random password matching the checkPasswordSyntax() criteria. * * @see _passgen() * @return String password */ function passgen() { $password = null; while ($password == null || !checkPasswordSyntax($password, '', true)) { $password = _passgen(); } return $password; }
/** * Add SQL user for the given database * * @throws Exception * @throws iMSCP_Exception_Database * @param int $customerId Customer unique identifier * @param int $dbId * @return void */ function client_addSqlUser($customerId, $dbId) { if (empty($_POST)) { return; } if (!isset($_POST['uaction'])) { showBadRequestErrorPage(); } $dmnId = get_user_domain_id($customerId); if (!isset($_POST['Add_Exist'])) { $needUserCreate = true; if (!isset($_POST['user_name']) || !isset($_POST['user_host']) || !isset($_POST['pass']) || !isset($_POST['pass_rep'])) { showBadRequestErrorPage(); } $user = clean_input($_POST['user_name']); $host = clean_input($_POST['user_host']); $password = clean_input($_POST['pass']); $passwordConf = clean_input($_POST['pass_rep']); if ($user === '') { set_page_message(tr('Please enter an username.'), 'error'); return; } if (preg_match('/[%|\\?]+/', $user)) { set_page_message(tr("Wildcards such as '%s' and '%s' are not allowed in username.", '%', '?'), 'error'); return; } if ($host === '') { set_page_message(tr('Please enter an SQL user host.'), 'error'); return; } $host = encode_idna(clean_input($_POST['user_host'])); if ($host !== '%' && $host !== 'localhost' && !iMSCP_Validate::getInstance()->hostname($host, array('allow' => Zend_Validate_Hostname::ALLOW_DNS | Zend_Validate_Hostname::ALLOW_IP))) { set_page_message(tr('Invalid SQL user host: %s', iMSCP_Validate::getInstance()->getLastValidationMessages()), 'error'); return; } if ($password === '') { set_page_message(tr('Please enter a password.'), 'error'); return; } if ($password !== $passwordConf) { set_page_message(tr("Passwords do not match."), 'error'); return; } if (strlen($password) > 32) { set_page_message(tr('Password is too long.'), 'error'); return; } if (!checkPasswordSyntax($password)) { set_page_message(tr('Only printable characters from the ASCII table (not extended), excepted the space, are allowed.'), 'error'); return; } if (isset($_POST['use_dmn_id']) && $_POST['use_dmn_id'] == 'on' && isset($_POST['id_pos']) && $_POST['id_pos'] == 'start') { $user = $dmnId . '_' . clean_input($_POST['user_name']); } elseif (isset($_POST['use_dmn_id']) && $_POST['use_dmn_id'] == 'on' && isset($_POST['id_pos']) && $_POST['id_pos'] == 'end') { $user = clean_input($_POST['user_name']) . '_' . $dmnId; } else { $user = clean_input($_POST['user_name']); } if (strlen($user) > 16) { set_page_message(tr('Username is too long.'), 'error'); return; } if (client_isSqlUser($user, $host)) { set_page_message(tr('SQL user %s already exits.', $user . '@' . decode_idna($host)), 'error'); return; } } elseif (isset($_POST['sqluser_id'])) { // Using existing SQL user as specified in input data $needUserCreate = false; $userId = intval($_POST['sqluser_id']); $stmt = exec_query('SELECT sqlu_name, sqlu_host, sqlu_pass FROM sql_user WHERE sqlu_id = ?', $userId); if (!$stmt->rowCount()) { showBadRequestErrorPage(); } $row = $stmt->fetchRow(PDO::FETCH_ASSOC); $user = $row['sqlu_name']; $host = $row['sqlu_host']; $password = $row['sqlu_pass']; } else { showBadRequestErrorPage(); return; } # Retrieve database to which SQL user should be assigned $stmt = exec_query('SELECT sqld_name FROM sql_database WHERE sqld_id = ? AND domain_id = ?', array($dbId, $dmnId)); if (!$stmt->rowCount()) { showBadRequestErrorPage(); } $row = $stmt->fetchRow(PDO::FETCH_ASSOC); $dbName = $row['sqld_name']; $dbName = preg_replace('/([_%\\?\\*])/', '\\\\$1', $dbName); $config = iMSCP_Registry::get('config'); $mysqlConfig = new iMSCP_Config_Handler_File($config['CONF_DIR'] . '/mysql/mysql.data'); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddSqlUser); // Here we cannot use transaction due to statements that cause an implicit commit. Thus we execute // those statements first to let the i-MSCP database in clean state if one of them fails. // See https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html for more details if ($needUserCreate) { if (strpos('mariadb', $config['SQL_SERVER']) !== false || version_compare($mysqlConfig['SQLD_VERSION'], '5.7.6', '<')) { exec_query('CREATE USER ?@? IDENTIFIED BY ?', array($user, $host, $password)); } else { exec_query('CREATE USER ?@? IDENTIFIED BY ? PASSWORD EXPIRE NEVER', array($user, $host, $password)); } } execute_query(sprintf('GRANT ALL PRIVILEGES ON %s.* to %s@%s', quoteIdentifier($dbName), quoteValue($user), quoteValue($host))); exec_query('INSERT INTO sql_user (sqld_id, sqlu_name, sqlu_host, sqlu_pass) VALUES (?, ?, ?, ?)', array($dbId, $user, $host, $password)); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddSqlUser); set_page_message(tr('SQL user successfully added.'), 'success'); write_log(sprintf("%s added new SQL user: %s", $_SESSION['user_logged'], tohtml($user)), E_USER_NOTICE); redirectTo('sql_manage.php'); }
/** * Check user data * * @param bool $noPass If true skip password check * @return bool True if user data are valid, false otherwise */ function check_ruser_data($noPass = false) { global $password, $passwordRepeat, $email, $customerId, $firstName, $lastName, $gender, $firm, $street1, $street2, $zip, $city, $state, $country, $phone, $fax, $domainIp; // Get data for fields from previous page if (isset($_POST['userpassword'])) { $password = clean_input($_POST['userpassword']); } else { $password = ''; } if (isset($_POST['userpassword_repeat'])) { $passwordRepeat = clean_input($_POST['userpassword_repeat']); } else { $passwordRepeat = ''; } if (isset($_POST['useremail'])) { $email = clean_input($_POST['useremail']); } else { $email = ''; } if (isset($_POST['useruid'])) { $customerId = clean_input($_POST['useruid']); } else { $customerId = ''; } if (isset($_POST['userfname'])) { $firstName = clean_input($_POST['userfname']); } else { $firstName = ''; } if (isset($_POST['userlname'])) { $lastName = clean_input($_POST['userlname']); } else { $lastName = ''; } if (isset($_POST['gender']) && get_gender_by_code($_POST['gender'], true) !== null) { $gender = $_POST['gender']; } else { $gender = 'U'; } if (isset($_POST['userfirm'])) { $firm = clean_input($_POST['userfirm']); } else { $firm = ''; } if (isset($_POST['userstreet1'])) { $street1 = clean_input($_POST['userstreet1']); } else { $street1 = ''; } if (isset($_POST['userstreet2'])) { $street2 = clean_input($_POST['userstreet2']); } else { $street2 = ''; } if (isset($_POST['userzip'])) { $zip = clean_input($_POST['userzip']); } else { $zip = ''; } if (isset($_POST['usercity'])) { $city = clean_input($_POST['usercity']); } else { $city = ''; } if (isset($_POST['userstate'])) { $state = clean_input($_POST['userstate']); } else { $state = ''; } if (isset($_POST['usercountry'])) { $country = clean_input($_POST['usercountry']); } else { $country = ''; } if (isset($_POST['userphone'])) { $phone = clean_input($_POST['userphone']); } else { $phone = ''; } if (isset($_POST['userfax'])) { $fax = clean_input($_POST['userfax']); } else { $fax = ''; } if (isset($_POST['domain_ip'])) { $domainIp = clean_input($_POST['domain_ip']); } else { $domainIp = ''; } if (!$noPass) { if ('' === $passwordRepeat || '' === $password) { set_page_message(tr('Please fill up both data fields for password.'), 'error'); } elseif ($passwordRepeat !== $password) { set_page_message(tr("Passwords do not match."), 'error'); } else { checkPasswordSyntax($password); } } if (!chk_email($email)) { set_page_message(tr('Incorrect email length or syntax.'), 'error'); } if ($customerId != '' && strlen($customerId) > 200) { set_page_message(tr('Customer ID cannot have more than 200 characters'), 'error'); } if ($firstName != '' && strlen($firstName) > 200) { set_page_message(tr('First name cannot have more than 200 characters.'), 'error'); } if ($lastName != '' && strlen($lastName) > 200) { set_page_message(tr('Last name cannot have more than 200 characters.'), 'error'); } if ($zip != '' && (strlen($zip) > 200 || is_number(!$zip))) { set_page_message(tr('Incorrect post code length or syntax!'), 'error'); } if (Zend_Session::namespaceIsset('pageMessages')) { return false; } return true; }
', array($domainId, $otherDir)); if ($stmt->rowCount()) { $row = $stmt->fetchRow(PDO::FETCH_ASSOC); set_page_message(tr('Please select another directory. %s (%s) is installed there.', $row['software_name'], $row['software_version']), 'error'); $error = true; } } } # Note: Comma is not allowed in input data because it is used as data delimiter by the backend. # Check application username if (!validates_username($appLoginName)) { set_page_message(tr('Invalid username.'), 'error'); $error = true; } # Check application password if (!checkPasswordSyntax($appPassword)) { $error = true; } elseif (strpos($appPassword, ',') !== false) { set_page_message(tr('Password with comma(s) are not accepted.'), 'error'); $error = true; } # Check application email if (!chk_email($appEmail)) { set_page_message(tr('Invalid email address.'), 'error'); $error = true; } elseif (strpos($appLoginName, ',') !== false) { set_page_message(tr('Email address with comma(s) are not accepted.'), 'error'); $error = true; } # Check application database if required if ($softwareData['software_db']) {
/** * 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; }
/** * Validate input data * * @access private * @return bool TRUE if data are valid, FALSE otherwise */ function admin_isValidData() { if (!chk_email($_POST['email'])) { set_page_message(tr("Incorrect email length or syntax."), 'error'); } if (!empty($_POST['password']) && !empty($_POST['password_confirmation'])) { if ($_POST['password'] != $_POST['password_confirmation']) { set_page_message(tr("Passwords do not match."), 'error'); } checkPasswordSyntax($_POST['password']); } if (Zend_Session::namespaceIsset('pageMessages')) { return false; } return true; }
/** * Add or update a mailing list * * @return boolean TRUE on success, FALSE otherwise */ function addList() { if (isset($_POST['list_id']) && isset($_POST['list_name']) && isset($_POST['admin_email']) && isset($_POST['admin_password']) && isset($_POST['admin_password_confirm'])) { $error = false; $listId = intval($_POST['list_id']); $listName = strtolower(clean_input($_POST['list_name'])); $adminEmail = clean_input($_POST['admin_email']); $adminPassword = clean_input($_POST['admin_password']); $adminPasswordConfirm = clean_input($_POST['admin_password_confirm']); if (preg_match('/[^a-z0-9-_]/', $listName) || $listName == 'mailman') { set_page_message(tr('List name is either reserved or not valid.'), 'error'); $error = true; } if (!chk_email($adminEmail)) { set_page_message(tr("Email is not valid."), 'error'); $error = true; } if ($adminPassword !== $adminPasswordConfirm) { set_page_message(tr("Passwords do not match."), 'error'); $error = true; } elseif (!checkPasswordSyntax($adminPassword)) { $error = true; } if (!$error) { if (!$listId) { // Add list try { $mainDmnProps = get_domain_default_props($_SESSION['user_id']); exec_query(' INSERT INTO mailman ( mailman_admin_id, mailman_admin_email, mailman_admin_password, mailman_list_name, mailman_status ) VALUES( ?, ?, ?, ?, ? ) ', array($mainDmnProps['domain_admin_id'], $adminEmail, $adminPassword, $listName, 'toadd')); } catch (DatabaseException $e) { if ($e->getCode() == 23000) { // Duplicate entries set_page_message(tr("This list already exist. Please, choose other name.", $listName), 'warning'); return false; } } } else { // Update list $stmt = exec_query(' UPDATE mailman SET mailman_admin_email = ?, mailman_admin_password = ?, mailman_status = ? WHERE mailman_id = ? AND mailman_admin_id = ? AND mailman_status = ? ', array($adminEmail, $adminPassword, 'tochange', $listId, $_SESSION['user_id'], 'ok')); if (!$stmt->rowCount()) { showBadRequestErrorPage(); } } send_request(); return true; } else { return false; } } else { showBadRequestErrorPage(); exit; } }