/** * 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; }
/** * Check admin current password. * * @access private * @param string $password Admin current password * @return bool TRUE if current password is valid, FALSE otherwise */ function _reseller_checkCurrentPassword($password) { $stmt = exec_query('SELECT `admin_pass` FROM `admin` WHERE `admin_id` = ?', $_SESSION['user_id']); if (!$stmt->rowCount()) { set_page_message(tr('Unable to retrieve your password from the database.'), 'error'); return false; } elseif (cryptPasswordWithSalt($password, $stmt->fields['admin_pass']) !== $stmt->fields['admin_pass']) { return false; } return true; }
/** * @param $tpl iMSCP_pTemplate * @return void */ function add_user($tpl) { /** @var $cfg iMSCP_Config_Handler_File */ $cfg = iMSCP_Registry::get('config'); if (isset($_POST['uaction']) && $_POST['uaction'] === 'add_user') { iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddUser); if (check_user_data()) { $upass = cryptPasswordWithSalt(clean_input($_POST['password'])); $user_id = $_SESSION['user_id']; $username = clean_input($_POST['username']); $fname = clean_input($_POST['fname']); $lname = clean_input($_POST['lname']); $gender = clean_input($_POST['gender']); $firm = clean_input($_POST['firm']); $zip = clean_input($_POST['zip']); $city = clean_input($_POST['city']); $state = clean_input($_POST['state']); $country = clean_input($_POST['country']); $email = clean_input($_POST['email']); $phone = clean_input($_POST['phone']); $fax = clean_input($_POST['fax']); $street1 = clean_input($_POST['street1']); $street2 = clean_input($_POST['street2']); if (get_gender_by_code($gender, true) === null) { $gender = ''; } $query = "\n\t\t\t\tINSERT INTO `admin` (\n\t\t\t\t\t`admin_name`, `admin_pass`, `admin_type`, `domain_created`, `created_by`, `fname`, `lname`, `firm`,\n\t\t\t\t\t`zip`, `city`, `state`, `country`, `email`, `phone`, `fax`, `street1`, `street2`, `gender`\n\t\t\t\t) VALUES (\n\t\t\t\t\t?, ?, 'admin', unix_timestamp(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?\n\t\t\t\t)\n\t\t\t"; exec_query($query, array($username, $upass, $user_id, $fname, $lname, $firm, $zip, $city, $state, $country, $email, $phone, $fax, $street1, $street2, $gender)); /** @var $db iMSCP_Database */ $db = iMSCP_Registry::get('db'); $new_admin_id = $db->insertId(); $user_logged = $_SESSION['user_logged']; write_log("{$user_logged}: add admin: {$username}", E_USER_WARNING); $user_def_lang = $cfg->USER_INITIAL_LANG; $user_theme_color = $cfg->USER_INITIAL_THEME; $query = "\n\t\t\t\tREPLACE INTO `user_gui_props` (\n\t\t\t\t\t`user_id`, `lang`, `layout`\n\t\t\t\t) VALUES (\n\t\t\t\t\t?, ?, ?\n\t\t\t\t)\n\t\t\t"; exec_query($query, array($new_admin_id, $user_def_lang, $user_theme_color)); iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddUser); send_add_user_auto_msg($user_id, clean_input($_POST['username']), clean_input($_POST['password']), clean_input($_POST['email']), clean_input($_POST['fname']), clean_input($_POST['lname']), tr('Administrator')); //$_SESSION['user_added'] = 1; set_page_message(tr('Admin account successfully created.'), 'success'); redirectTo('manage_users.php'); } else { // check user data $tpl->assign(array('EMAIL' => clean_input($_POST['email'], true), 'USERNAME' => clean_input($_POST['username'], true), 'FIRST_NAME' => clean_input($_POST['fname'], true), 'LAST_NAME' => clean_input($_POST['lname'], true), 'FIRM' => clean_input($_POST['firm'], true), 'ZIP' => clean_input($_POST['zip'], true), 'CITY' => clean_input($_POST['city'], true), 'STATE' => clean_input($_POST['state'], true), 'COUNTRY' => clean_input($_POST['country'], true), 'STREET_1' => clean_input($_POST['street1'], true), 'STREET_2' => clean_input($_POST['street2'], true), 'PHONE' => clean_input($_POST['phone'], true), 'FAX' => clean_input($_POST['fax'], true), 'VL_MALE' => $_POST['gender'] == 'M' ? $cfg->HTML_SELECTED : '', 'VL_FEMALE' => $_POST['gender'] == 'F' ? $cfg->HTML_SELECTED : '', 'VL_UNKNOWN' => $_POST['gender'] == 'U' || empty($_POST['gender']) ? $cfg->HTML_SELECTED : '')); } } else { $tpl->assign(array('EMAIL' => '', 'USERNAME' => '', 'FIRST_NAME' => '', 'LAST_NAME' => '', 'FIRM' => '', 'ZIP' => '', 'CITY' => '', 'STATE' => '', 'COUNTRY' => '', 'STREET_1' => '', 'STREET_2' => '', 'PHONE' => '', 'FAX' => '', 'VL_MALE' => '', 'VL_FEMALE' => '', 'VL_UNKNOWN' => $cfg->HTML_SELECTED)); } }
/** * Update user data * * @param int $userId Customer unique identifier * @return void */ function admin_updateUserData($userId) { iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditUser, array('userId' => $userId)); $fname = isset($_POST['fname']) ? clean_input($_POST['fname']) : ''; $lname = isset($_POST['lname']) ? clean_input($_POST['lname']) : ''; $firm = isset($_POST['firm']) ? clean_input($_POST['firm']) : ''; $gender = isset($_POST['gender']) ? clean_input($_POST['gender']) : ''; $zip = isset($_POST['zip']) ? clean_input($_POST['zip']) : ''; $city = isset($_POST['city']) ? clean_input($_POST['city']) : ''; $state = isset($_POST['state']) ? clean_input($_POST['state']) : ''; $country = isset($_POST['country']) ? clean_input($_POST['country']) : ''; $email = isset($_POST['email']) ? clean_input($_POST['email']) : ''; $phone = isset($_POST['phone']) ? clean_input($_POST['phone']) : ''; $fax = isset($_POST['fax']) ? clean_input($_POST['fax']) : ''; $street1 = isset($_POST['street1']) ? clean_input($_POST['street1']) : ''; $street2 = isset($_POST['street2']) ? clean_input($_POST['street2']) : ''; $userName = get_user_name($userId); if (empty($_POST['password'])) { $query = "\n\t\t\tUPDATE\n\t\t\t\t`admin`\n\t\t\tSET\n\t\t\t\t`fname` = ?, `lname` = ?, `firm` = ?, `zip` = ?, `city` = ?, `state` = ?, `country` = ?, `email` = ?,\n\t\t\t\t`phone` = ?, `fax` = ?, `street1` = ?, `street2` = ?, `gender` = ?\n\t\t\tWHERE\n\t\t\t\t`admin_id` = ?\n\t\t"; exec_query($query, array($fname, $lname, $firm, $zip, $city, $state, $country, $email, $phone, $fax, $street1, $street2, $gender, $userId)); } else { $query = "\n\t\t\tUPDATE\n\t\t\t\t`admin`\n\t\t\tSET\n\t\t\t\t`admin_pass` = ?, `fname` = ?, `lname` = ?, `firm` = ?, `zip` = ?, `city` = ?, `state` = ?,\n\t\t\t\t`country` = ?, `email` = ?, `phone` = ?, `fax` = ?, `street1` = ?, `street2` = ?, `gender` = ?\n\t\t\tWHERE\n\t\t\t\t`admin_id` = ?\n\t\t"; exec_query($query, array(cryptPasswordWithSalt($_POST['password']), $fname, $lname, $firm, $zip, $city, $state, $country, $email, $phone, $fax, $street1, $street2, $gender, $userId)); $query = "DELETE FROM `login` WHERE `user_name` = ?"; $stmt = exec_query($query, $userName); if ($stmt->rowCount()) { set_page_message(tr('User session successfully killed for password change.'), 'success'); } } iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditUser, array('userId' => $userId)); if (isset($_POST['send_data']) && !empty($_POST['password'])) { $query = 'SELECT `admin_type` FROM `admin` WHERE `admin_id` = ?'; $stmt = exec_query($query, $userId); if ($stmt->fields['admin_type'] == 'admin') { $admin_type = tr('Administrator'); } elseif ($stmt->fields['admin_type'] == 'reseller') { $admin_type = tr('Reseller'); } else { $admin_type = tr('Customer'); } send_add_user_auto_msg($userId, $userName, $_POST['password'], $_POST['email'], $_POST['fname'], $_POST['lname'], $admin_type); set_page_message(tr('Login data successfully sent to %s.', $userName), 'success'); } }
/** * 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; } }
/** * Credentials authentication handler * * @param iMSCP_Events_Event $event * @return iMSCP_Authentication_Result * @throws iMSCP_Exception_Database */ function login_credentials($event) { $username = !empty($_POST['uname']) ? encode_idna(clean_input($_POST['uname'])) : ''; $password = !empty($_POST['upass']) ? clean_input($_POST['upass']) : ''; if (empty($username) || empty($password)) { if (empty($username)) { $message[] = tr('The username field is empty.'); } if (empty($password)) { $message[] = tr('The password field is empty.'); } } if (!isset($message)) { $stmt = exec_query('SELECT admin_id, admin_name, admin_pass, admin_type, email, created_by FROM admin WHERE admin_name = ?', $username); if (!$stmt->rowCount()) { $result = new iMSCP_Authentication_Result(iMSCP_Authentication_Result::FAILURE_IDENTITY_NOT_FOUND, null, tr('Unknown username.')); } else { $identity = $stmt->fetchRow(PDO::FETCH_OBJ); $dbPassword = $identity->admin_pass; if ($dbPassword != md5($password) && crypt($password, $dbPassword) != $dbPassword) { $result = new iMSCP_Authentication_Result(iMSCP_Authentication_Result::FAILURE_CREDENTIAL_INVALID, null, tr('Bad password.')); } else { if (strpos($dbPassword, '$') !== 0) { # Not a password encrypted with crypt(), then re-encrypt it exec_query('UPDATE admin SET admin_pass = ? WHERE admin_id = ?', array(cryptPasswordWithSalt($password), $identity->admin_id)); write_log(sprintf('Info: Password for user %s has been re-encrypted using the best available algorithm', $identity->admin_name), E_USER_NOTICE); } $result = new iMSCP_Authentication_Result(iMSCP_Authentication_Result::SUCCESS, $identity); $event->stopPropagation(); } } } else { $result = new iMSCP_Authentication_Result(count($message) == 2 ? iMSCP_Authentication_Result::FAILURE_CREDENTIAL_EMPTY : iMSCP_Authentication_Result::FAILURE_CREDENTIAL_INVALID, null, $message); } return $result; }
/** * 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'); }
/** * 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; }
/** * 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; }
/** * Set password * * @param string $uniqueKey * @param string $userPassword * @return void */ function setPassword($uniqueKey, $userPassword) { if ($uniqueKey == '') { exit; } exec_query('UPDATE `admin` SET `admin_pass` = ? WHERE `uniqkey` = ?', array(cryptPasswordWithSalt($userPassword), $uniqueKey)); }
/** * 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; } }
/** * 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; }
/** * Create a temporary FTP user * * @return boolean TRUE on success, FALSE on failure */ protected function _createTmpUser() { /** @var $cfg iMSCP_Config_Handler_File */ $cfg = iMSCP_Registry::get('config'); // Get user uid/gid $query = "\n\t\t\tSELECT\n\t\t\t\t`admin_sys_uid`, `admin_sys_gid`\n\t\t\tFROM\n\t\t\t\t`admin`\n\t\t\tINNER JOIN\n\t\t\t\t`domain` ON (`domain_admin_id` = `admin_id`)\n\t\t\tWHERE\n\t\t\t\t`domain_name` = ?\n "; $stmt = exec_query($query, $this->_domain); if (!$stmt) { return false; } // Generate a random userid and password $user = uniqid('tmp_') . '@' . $this->_domain; $this->_passwd = uniqid('tmp_', true); $password = cryptPasswordWithSalt($this->_passwd); // Create the temporary user $query = "\n\t\t\tINSERT INTO\n\t\t\t\t`ftp_users` (\n\t\t\t\t\t`userid`, `passwd`, `uid`, `gid`, `shell`, `homedir`\n\t\t\t\t) VALUES (\n\t\t\t\t\t?, ?, ?, ?, ?, ?\n\t\t\t\t)\n\t\t"; $stmt = exec_query($query, array($user, $password, $stmt->fields['admin_sys_uid'], $stmt->fields['admin_sys_gid'], '/bin/sh', "{$cfg->USER_WEB_DIR}/{$this->_domain}")); if (!$stmt) { return false; } $this->_user = $user; return true; }