Exemple #1
0
/**
 * Check input data
 *
 * @return void
 */
function reseller_checkData()
{
    $cfg = iMSCP_Registry::get('config');
    if (!isset($_POST['dmn_name']) || $_POST['dmn_name'] === '') {
        set_page_message(tr('Domain name cannot be empty.'), 'error');
        return;
    }
    $dmnName = clean_input($_POST['dmn_name']);
    global $dmnNameValidationErrMsg;
    if (!isValidDomainName($dmnName)) {
        set_page_message($dmnNameValidationErrMsg, 'error');
        return;
    }
    // www is considered as an alias of the domain
    while (strpos($dmnName, 'www.') !== false) {
        $dmnName = substr($dmnName, 4);
    }
    $asciiDmnName = encode_idna($dmnName);
    if (imscp_domain_exists($asciiDmnName, $_SESSION['user_id']) || $asciiDmnName == $cfg['BASE_SERVER_VHOST']) {
        set_page_message(tr('Domain %s is unavailable.', "<strong>{$dmnName}</strong>"), 'error');
        return;
    }
    if ((!isset($_POST['datepicker']) || $_POST['datepicker'] === '') && !isset($_POST['never_expire'])) {
        set_page_message(tr('Domain expiration date must be filled.'), 'error');
        return;
    }
    $dmnExpire = isset($_POST['datepicker']) ? @strtotime(clean_input($_POST['datepicker'])) : 0;
    if ($dmnExpire === false) {
        set_page_message('Invalid expiration date.', 'error');
        return;
    }
    $hpId = isset($_POST['dmn_tpl']) ? clean_input($_POST['dmn_tpl']) : 0;
    $customizeHp = $hpId > 0 && isset($_POST['chtpl']) ? $_POST['chtpl'] : '_no_';
    if ($hpId == 0 || $customizeHp == '_yes_') {
        $_SESSION['dmn_name'] = $asciiDmnName;
        $_SESSION['dmn_expire'] = $dmnExpire;
        $_SESSION['dmn_tpl'] = $hpId;
        $_SESSION['chtpl'] = '_yes_';
        $_SESSION['step_one'] = '_yes_';
        redirectTo('user_add2.php');
    }
    if (reseller_limits_check($_SESSION['user_id'], $hpId)) {
        $_SESSION['dmn_name'] = $asciiDmnName;
        $_SESSION['dmn_expire'] = $dmnExpire;
        $_SESSION['dmn_tpl'] = $hpId;
        $_SESSION['chtpl'] = $customizeHp;
        $_SESSION['step_one'] = '_yes_';
        redirectTo('user_add3.php');
    }
    set_page_message(tr('Hosting plan limits exceed reseller limits.'), 'error');
}
Exemple #2
0
/**
 * Send email
 *
 * @param string $senderName Sender name
 * @param string $senderEmail Sender email
 * @param string $subject Subject
 * @param string $body Body
 * @param array $rcptToData Recipient data
 */
function reseller_sendEmail($senderName, $senderEmail, $subject, $body, $rcptToData)
{
    if ($rcptToData['email'] != '') {
        $senderEmail = encode_idna($senderEmail);
        if (!empty($rcptToData['fname']) && !empty($rcptToData['lname'])) {
            $to = $rcptToData['fname'] . ' ' . $rcptToData['lname'];
        } elseif (!empty($rcptToData['fname'])) {
            $to = $rcptToData['fname'];
        } elseif (!empty($rcptToData['lname'])) {
            $to = $rcptToData['lname'];
        } else {
            $to = $rcptToData['admin_name'];
        }
        $from = encode_mime_header($senderName) . " <{$senderEmail}>";
        $to = encode_mime_header($to) . " <{$rcptToData['email']}>";
        $headers = "From: {$from}\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/plain; charset=utf-8\r\n";
        $headers .= "Content-Transfer-Encoding: 8bit\r\n";
        $headers .= "X-Mailer: i-MSCP mailer";
        mail($to, encode_mime_header($subject), $body, $headers, "-f {$senderEmail}");
    }
}
Exemple #3
0
/**
 * 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;
}
$csvDelimiter = ',';
if (($handle = fopen($csvFilePath, 'r')) !== false) {
    $db = iMSCP_Database::getRawInstance();
    $stmt = $db->prepare('
			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 (
				: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 {
Exemple #5
0
 /**
  * Returns credentials to push in select element
  *
  * @return array
  */
 protected function getCredentials()
 {
     $credentials = array();
     foreach ($this->getConfigParam('user_accounts') as $account) {
         if (isset($account['label']) && isset($account['username']) && isset($account['password'])) {
             $stmt = exec_query('SELECT admin_pass FROM admin WHERE admin_name = ?', encode_idna($account['username']));
             if ($stmt->rowCount()) {
                 $dbPassword = $stmt->fields['admin_pass'];
                 if (crypt($account['password'], $dbPassword) == $dbPassword || $dbPassword == md5($account['password'])) {
                     $credentials[] = array('label' => $account['label'], 'username' => $account['username'], 'password' => $account['password']);
                 }
             }
         }
     }
     return $credentials;
 }
Exemple #6
0
/**
 * 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;
}
Exemple #7
0
 /**
  * onAfterAddDomainAlias event listener
  *
  * @param iMSCP_Events_Event $event
  * @return void
  */
 public function onAfterAddDomainAlias(iMSCP_Events_Event $event)
 {
     // Check that the domain alias is being added and not simply ordered
     $stmt = exec_query('SELECT alias_id FROM domain_aliasses WHERE alias_id = ? AND alias_status = ?', array($event->getParam('domainAliasId'), 'toadd'));
     if ($stmt->rowCount()) {
         // In case OpenDKIM is activated for the parent domain, we must activate it also for the domain alias which
         // is being added
         $stmt = exec_query('SELECT admin_id FROM opendkim WHERE domain_id = ? AND alias_id IS NULL AND opendkim_status = ?', array($event->getParam('domainId'), 'ok'));
         if ($stmt->rowCount()) {
             $row = $stmt->fetchRow(PDO::FETCH_ASSOC);
             exec_query('
                     INSERT INTO opendkim (
                         admin_id, domain_id, alias_id, domain_name, opendkim_status
                     ) VALUES (
                         ?, ?, ?, ?, ?
                     )
                 ', array($row['admin_id'], $event->getParam('domainId'), $event->getParam('domainAliasId'), encode_idna($event->getParam('domainAliasName')), 'toadd'));
         }
     }
 }
Exemple #8
0
/**
 * Does the given customer is the owner of the given domain?
 *
 * @param string $domainName Domain name (dmn,sub,als,alssub)
 * @param int $customerId Customer unique identifier
 * @return bool TRUE if the given customer is the owner of the given domain, FALSE otherwise
 * TODO add admin_id as foreign key in all domain tables too avoid too many jointures
 */
function customerHasDomain($domainName, $customerId)
{
    $domainName = encode_idna($domainName);
    // Check in domain table
    $stmt = exec_query("SELECT 'found' FROM domain WHERE domain_admin_id = ? AND domain_name = ?", array($customerId, $domainName));
    if ($stmt->rowCount()) {
        return true;
    }
    // Check in domain_aliasses table
    $stmt = exec_query("\n\t\t\tSELECT\n\t\t\t\t'found'\n\t\t\tFROM\n\t\t\t\tdomain AS t1\n\t\t\tINNER JOIN\n\t\t\t\tdomain_aliasses AS t2 ON(t2.domain_id = t1.domain_id)\n\t\t\tWHERE\n\t\t\t\tt1.domain_admin_id = ?\n\t\t\tAND\n\t\t\t\tt2.alias_name = ?\n\t\t", array($customerId, $domainName));
    if ($stmt->rowCount()) {
        return true;
    }
    // Check in subdomain table
    $stmt = exec_query("\n\t\t\tSELECT\n\t\t\t\t'found'\n\t\t\tFROM\n\t\t\t\tdomain AS t1\n\t\t\tINNER JOIN\n\t\t\t\tsubdomain AS t2 ON (t2.domain_id = t1.domain_id)\n\t\t\tWHERE\n\t\t\t\tt1.domain_admin_id = ?\n\t\t\tAND\n\t\t\t\tCONCAT(t2.subdomain_name, '.', t1.domain_name) = ?\n\t\t", array($customerId, $domainName));
    if ($stmt->rowCount()) {
        return true;
    }
    // Check in subdomain_alias table
    $stmt = exec_query("\n\t\t\tSELECT\n\t\t\t\t'found'\n\t\t\tFROM\n\t\t\t\tdomain AS t1\n\t\t\tINNER JOIN\n\t\t\t\tdomain_aliasses AS t2 ON(t2.domain_id = t1.domain_id)\n\t\t\tINNER JOIN\n\t\t\t \tsubdomain_alias AS t3 ON(t3.alias_id = t2.alias_id)\n\t\t\tWHERE\n\t\t\t\tt1.domain_admin_id = ?\n\t\t\tAND\n\t\t\t\tCONCAT(t3.subdomain_alias_name, '.', t2.alias_name) = ?\n\t\t", array($customerId, $domainName));
    if ($stmt->rowCount()) {
        return true;
    }
    return false;
}
Exemple #9
0
/**
 * Edit domain alias
 *
 * @return bool TRUE on success, FALSE on failure
 */
function client_editDomainAlias()
{
    if (isset($_GET['id'])) {
        $domainAliasId = clean_input($_GET['id']);
        if ($domainAliasData = _client_getAliasData($domainAliasId)) {
            // Check for URL forwarding option
            $forwardUrl = 'no';
            if (isset($_POST['url_forwarding']) && $_POST['url_forwarding'] == 'yes') {
                // We are safe here
                if (isset($_POST['forward_url_scheme']) && isset($_POST['forward_url'])) {
                    $forwardUrl = clean_input($_POST['forward_url_scheme']) . clean_input($_POST['forward_url']);
                    try {
                        try {
                            $uri = iMSCP_Uri_Redirect::fromString($forwardUrl);
                        } catch (Zend_Uri_Exception $e) {
                            throw new iMSCP_Exception(tr('Forward URL %s is not valid.', "<strong>{$forwardUrl}</strong>"));
                        }
                        $uri->setHost(encode_idna($uri->getHost()));
                        if ($uri->getHost() == $domainAliasData['alias_name'] && $uri->getPath() == '/') {
                            throw new iMSCP_Exception(tr('Forward URL %s is not valid.', "<strong>{$forwardUrl}</strong>") . ' ' . tr('Domain alias %s cannot be forwarded on itself.', "<strong>{$domainAliasData['alias_name_utf8']}</strong>"));
                        }
                        $forwardUrl = $uri->getUri();
                    } catch (Exception $e) {
                        set_page_message($e->getMessage(), 'error');
                        return false;
                    }
                } else {
                    showBadRequestErrorPage();
                }
            }
            iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditDomainAlias, array('domainAliasId' => $domainAliasId));
            exec_query('UPDATE `domain_aliasses` SET `url_forward` = ?, `alias_status` = ? WHERE `alias_id` = ?', array($forwardUrl, 'tochange', $domainAliasId));
            iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditDomainALias, array('domainAliasId' => $domainAliasId));
            send_request();
            write_log("{$_SESSION['user_logged']}: scheduled update of domain alias: {$domainAliasData['alias_name_utf8']}.", E_USER_NOTICE);
        } else {
            showBadRequestErrorPage();
        }
    } else {
        showBadRequestErrorPage();
    }
    return true;
}
Exemple #10
0
/**
 * Should be documented
 *
 * @param $arr
 * @param bool $asPath
 * @return string
 */
function array_encode_idna($arr, $asPath = false)
{
    if ($asPath && !is_array($arr)) {
        return implode('/', array_encode_idna(explode('/', $arr)));
    }
    foreach ($arr as $k => $v) {
        if (strpos($v, 'xn--') === 0) {
            $arr[$k] = $v;
        } else {
            $arr[$k] = encode_idna($v);
        }
    }
    return $arr;
}
Exemple #11
0
    // Prevent external login (i.e. check for valid local referer) separated in admin, reseller and client.
    // This option allows to use external login scripts
    //
    // 1: prevent external login, check for referer, more secure
    // 0: allow external login, do not check for referer, less security (risky)
    $config['PREVENT_EXTERNAL_LOGIN_ADMIN'] = 1;
    $config['PREVENT_EXTERNAL_LOGIN_RESELLER'] = 1;
    $config['PREVENT_EXTERNAL_LOGIN_CLIENT'] = 1;
    // Automatic search for new version
    $config['CHECK_FOR_UPDATES'] = 0;
    $config['ENABLE_SSL'] = 1;
    // Converting some possible IDN to ACE
    $config['DEFAULT_ADMIN_ADDRESS'] = encode_idna($config->get('DEFAULT_ADMIN_ADDRESS'));
    $config['SERVER_HOSTNAME'] = encode_idna($config->get('SERVER_HOSTNAME'));
    $config['BASE_SERVER_VHOST'] = encode_idna($config->get('BASE_SERVER_VHOST'));
    $config['DATABASE_HOST'] = encode_idna($config->get('DATABASE_HOST'));
    // Server traffic settings
    $config['SERVER_TRAFFIC_LIMIT'] = 0;
    $config['SERVER_TRAFFIC_WARN'] = 0;
    // Paths appended to the default PHP open_basedir directive of customers
    $config['PHPINI_OPEN_BASEDIR'] = '';
    // Store file last modification time to force reloading of configuration file if needed
    $config['__filemtime__'] = filemtime(CONFIG_FILE_PATH);
    if (!$config['DEBUG']) {
        @file_put_contents(CONFIG_CACHE_FILE_PATH, serialize($config), LOCK_EX);
    }
}
// Initialize application
iMSCP_Initializer::run($config);
// Remove useless variable
unset($configFilePath, $cachedConfigFilePath, $config);
Exemple #12
0
/**
 * Check and save DNS record
 *
 * @throws iMSCP_Exception_Database
 * @param int $dnsRecordId DNS record unique identifier (0 for new record)
 * @return bool TRUE on success, FALSE otherwise
 */
function client_saveDnsRecord($dnsRecordId)
{
    $mainDmnProps = get_domain_default_props($_SESSION['user_id']);
    $mainDmnId = $mainDmnProps['domain_id'];
    $errorString = '';
    $dnsRecordName = '';
    $dnsRecordClass = client_getPost('class');
    $dnsRecordType = client_getPost('type');
    if ($dnsRecordClass != 'IN' || !in_array($dnsRecordType, array('A', 'AAAA', 'CNAME', 'SRV', 'TXT'))) {
        showBadRequestErrorPage();
    }
    $dnsRecordData = '';
    if (!$dnsRecordId) {
        if ($_POST['domain_id'] == 0) {
            $domainName = $mainDmnProps['domain_name'];
            $domainId = 0;
        } else {
            $stmt = exec_query('SELECT alias_id, alias_name FROM domain_aliasses WHERE alias_id = ? AND domain_id = ?', array($_POST['domain_id'], $mainDmnId));
            if (!$stmt->rowCount()) {
                showBadRequestErrorPage();
            }
            $domainName = $stmt->fields['alias_name'];
            $domainId = $stmt->fields['alias_id'];
        }
    } else {
        $stmt = exec_query('
				SELECT
					t1.*, IFNULL(t3.alias_name, t2.domain_name) domain_name,
					IFNULL(t3.alias_status, t2.domain_status) domain_status
				FROM
					domain_dns AS t1
				LEFT JOIN
					domain AS t2 USING(domain_id)
				LEFT JOIN
					domain_aliasses AS t3 USING (alias_id)
				WHERE
					domain_dns_id = ?
				AND
					t1.domain_id = ?
			', array($dnsRecordId, $mainDmnId));
        if (!$stmt->rowCount()) {
            showBadRequestErrorPage();
        }
        $row = $stmt->fetchRow(PDO::FETCH_ASSOC);
        $domainId = $row['alias_id'] ? $row['alias_id'] : $row['domain_id'];
        $domainName = $row['domain_name'];
        $dnsRecordName = $row['domain_dns'];
    }
    $nameValidationError = '';
    if (in_array($dnsRecordType, array('A', 'AAAA', 'CNAME'))) {
        if (!client_validate_NAME(client_getPost('dns_name'), $domainName, $nameValidationError)) {
            set_page_message(sprintf(tr("Cannot validate record: %s"), $nameValidationError), 'error');
        }
    }
    if (!Zend_Session::namespaceIsset('pageMessages')) {
        switch ($dnsRecordType) {
            case 'CNAME':
                $cname = client_getPost('dns_cname');
                $newName = encode_idna(substr(client_getPost('dns_name'), -1) == '.' ? client_getPost('dns_name') : client_getPost('dns_name') . '.' . $domainName);
                $oldName = $dnsRecordName != '' ? substr($dnsRecordName, -1) == '.' ? $dnsRecordName : $dnsRecordName . '.' . $domainName : '';
                if (!client_validate_CNAME($cname, $domainName, $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                } elseif ($newName != $oldName && !client_checkConflict($newName, 'CNAME', $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                } elseif ($newName != $oldName && !client_checkConflict($newName, 'A', $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                } elseif ($newName != $oldName && !client_checkConflict($newName, 'AAAA', $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                }
                $dnsRecordName = encode_idna(client_getPost('dns_name'));
                if ($cname != '@') {
                    $dnsRecordData = encode_idna($cname);
                } else {
                    $dnsRecordData = $cname;
                }
                break;
            case 'A':
                $ip = client_getPost('dns_A_address');
                $newName = encode_idna(substr(client_getPost('dns_name'), -1) == '.' ? client_getPost('dns_name') : client_getPost('dns_name') . '.' . $domainName);
                if (!client_validate_A($ip, $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                } elseif (!client_checkConflict($newName, 'CNAME', $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                } elseif (!client_checkConflict($newName, 'A', $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                }
                $dnsRecordName = encode_idna(client_getPost('dns_name'));
                $dnsRecordData = $ip;
                break;
            case 'AAAA':
                $ip = client_getPost('dns_AAAA_address');
                $newName = encode_idna(substr(client_getPost('dns_name'), -1) == '.' ? client_getPost('dns_name') : client_getPost('dns_name') . '.' . $domainName);
                if (!client_validate_AAAA(client_getPost('dns_AAAA_address'), $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                } elseif (!client_checkConflict($newName, 'CNAME', $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate %s record: %s"), $errorString), 'error');
                } elseif (!client_checkConflict($newName, 'AAAA', $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                }
                $dnsRecordName = encode_idna(client_getPost('dns_name'));
                $dnsRecordData = $ip;
                break;
            case 'SRV':
                if (!client_validate_SRV($_POST, $errorString, $dnsRecordName, $dnsRecordData)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                }
                break;
            case 'TXT':
                if (!client_validate_TXT($_POST, $errorString)) {
                    set_page_message(sprintf(tr("Cannot validate record: %s"), $errorString), 'error');
                }
                $dnsRecordData = '"' . str_replace('"', '', $_POST['dns_txt_data']) . '"';
                $dnsRecordName = $domainName . '.';
                break;
            default:
                showBadRequestErrorPage();
                exit;
        }
        if (!Zend_Session::namespaceIsset('pageMessages')) {
            try {
                if (!$dnsRecordId) {
                    exec_query('
							INSERT INTO domain_dns (
								domain_id, alias_id, domain_dns, domain_class, domain_type, domain_text, owned_by,
								domain_dns_status
							) VALUES (
								?, ?, ?, ?, ?, ?, ?, ?
							)
						', array($mainDmnId, $domainId, $dnsRecordName, $dnsRecordClass, $dnsRecordType, $dnsRecordData, 'custom_dns_feature', 'toadd'));
                } else {
                    exec_query('
							UPDATE
								domain_dns
							SET
								domain_dns = ?, domain_class = ?, domain_type = ?, domain_text = ?, domain_dns_status = ?
							WHERE
								domain_dns_id = ?
					', array($dnsRecordName, $dnsRecordClass, $dnsRecordType, $dnsRecordData, 'tochange', $dnsRecordId));
                }
                send_request();
                write_log(sprintf('Custom DNS record has been scheduled for %s by %s', $dnsRecordId ? tr('update') : tr('addition'), $_SESSION['user_logged']), E_USER_NOTICE);
            } catch (iMSCP_Exception_Database $e) {
                if ($e->getCode() == 23000) {
                    // Duplicate entries
                    set_page_message(tr('DNS record already exist.'), 'error');
                    return false;
                }
                throw $e;
            }
            return true;
        }
    }
    return false;
}
Exemple #13
0
/**
 * Generate query for user search form
 *
 * @param  string &$searchQuery
 * @param  string &$countQuery
 * @param  int $startIndex
 * @param  int $rowsPerPage
 * @param  string $searchFor
 * @param  string $searchCommon
 * @param  string $searchStatus
 * @return void
 */
function gen_admin_domain_query(&$searchQuery, &$countQuery, $startIndex, $rowsPerPage, $searchFor, $searchCommon, $searchStatus)
{
    $condition = '';
    $startIndex = intval($startIndex);
    $rowsPerPage = intval($rowsPerPage);
    if ($searchFor == 'n/a' && $searchCommon == 'n/a' && $searchStatus == 'n/a') {
        // We have pure list query;
        $countQuery = 'SELECT COUNT(*) AS cnt FROM domain';
        $searchQuery = "\n\t\t\tSELECT\n\t\t\t\t*\n\t\t\tFROM\n\t\t\t\tdomain AS t1\n\t\t\tINNER JOIN\n\t\t\t\tadmin AS t2 ON (t2.admin_id = t1.domain_admin_id)\n\t\t\tORDER BY\n\t\t\t\tt1.domain_name ASC\n\t\t\tLIMIT\n\t\t\t\t{$startIndex}, {$rowsPerPage}\n\t\t";
    } else {
        /** @var iMSCP_Database $db */
        $db = iMSCP_Registry::get('db');
        $searchFor = str_replace(array('!', '_', '%'), array('!!', '!_', '!%'), $searchFor);
        if ($searchFor == '' && $searchStatus != '') {
            if ($searchStatus != 'all') {
                $condition = 'WHERE t1.domain_status = ' . $db->quote($searchStatus);
            }
            $countQuery = "SELECT COUNT(*) AS cnt FROM domain AS t1 {$condition}";
            $searchQuery = "\n\t\t\t\tSELECT\n\t\t\t\t\t*\n\t\t\t\tFROM\n\t\t\t\t\tdomain AS t1\n\t\t\t\tINNER JOIN\n\t\t\t\t\tadmin AS t2 ON (t2.admin_id = t1.domain_admin_id)\n\t\t\t\t{$condition}\n\t\t\t\tORDER BY\n\t\t\t\t\tt1.domain_name ASC\n\t\t\t\tLIMIT\n\t\t\t\t\t{$startIndex}, {$rowsPerPage}\n        \t";
        } elseif ($searchFor != '') {
            $searchFor = str_replace(array('!', '_', '%'), array('!!', '!_', '!%'), $searchFor);
            if ($searchCommon == 'domain_name') {
                $searchFor = $db->quote('%' . encode_idna($searchFor) . '%');
                $condition = "WHERE t1.domain_name LIKE {$searchFor} ESCAPE '!'";
            } elseif ($searchCommon == 'customer_id') {
                $searchFor = $db->quote("%{$searchFor}%");
                $condition = "WHERE t2.customer_id LIKE {$searchFor} ESCAPE '!'";
            } elseif ($searchCommon == 'lname') {
                $searchFor = $db->quote("%{$searchFor}%");
                $condition = "WHERE (t2.lname LIKE {$searchFor} ESCAPE '=' OR fname LIKE {$searchFor} ESCAPE '!')";
            } elseif ($searchCommon == 'firm') {
                $searchFor = $db->quote("%{$searchFor}%");
                $condition = "WHERE t2.firm LIKE {$searchFor} ESCAPE '!'";
            } elseif ($searchCommon == 'city') {
                $searchFor = $db->quote("%{$searchFor}%");
                $condition = "WHERE t2.city LIKE {$searchFor} ESCAPE '!'";
            } elseif ($searchCommon == 'state') {
                $searchFor = $db->quote("%{$searchFor}%");
                $condition = "WHERE t2.state LIKE {$searchFor} ESCAPE '!'";
            } elseif ($searchCommon == 'country') {
                $searchFor = $db->quote("%{$searchFor}%");
                $condition = "WHERE t2.country LIKE {$searchFor} ESCAPE '!'";
            }
            if ($condition != '') {
                if ($searchStatus != 'all') {
                    $condition .= ' AND t1.domain_status = ' . $db->quote($searchStatus);
                }
                $countQuery = "\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tCOUNT(*) AS cnt\n\t\t\t\t   \tFROM\n\t\t\t\t\t\tdomain AS t1\n\t\t\t\t    INNER JOIN\n\t\t\t\t\t\tadmin AS t2 ON(t2.admin_id = t1.domain_admin_id)\n\t\t\t\t\t{$condition}\n\t\t\t    ";
                $searchQuery = "\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tt2.admin_id, t2.admin_status, t2.created_by, t1.*\n\t\t\t\t\tFROM\n\t\t\t\t\t\tdomain AS t1\n\t\t\t\t\tINNER JOIN\n\t\t\t\t\t\tadmin AS t2 ON(t2.admin_id = t1.domain_admin_id)\n\t\t\t\t\t{$condition}\n\t\t\t\t\tORDER BY\n\t\t\t\t\t\tt1.domain_name ASC\n\t\t\t\t\tLIMIT\n\t\t\t\t\t\t{$startIndex}, {$rowsPerPage}\n\t\t\t\t";
            }
        }
    }
}
Exemple #14
0
/**
 * Check input data
 * @param EasySCP_TemplateEngine $tpl
 * @param EasySCP_Database $sql
 * @param int $subdomain_id
 * @param string $dmn_type
 */
function check_fwd_data($tpl, $sql, $subdomain_id, $dmn_type, $dmn_id)
{
    $forward_url = clean_input($_POST['forward']);
    // unset errors
    $ed_error = '_off_';
    if (isset($_POST['status']) && $_POST['status'] == 1) {
        $forward_prefix = clean_input($_POST['forward_prefix']);
        $surl = @parse_url($forward_prefix . decode_idna($forward_url));
        $domain = $surl['host'];
        if (substr_count($domain, '.') <= 2) {
            $ret = validates_dname($domain);
        } else {
            $ret = validates_dname($domain, true);
        }
        if (!$ret) {
            $ed_error = tr('Wrong domain part in forward URL!');
        } else {
            $forward_url = encode_idna($forward_prefix . $forward_url);
        }
        $check_en = 'checked="checked"';
        $check_dis = '';
        $tpl->assign(array('FORWARD' => $forward_url, 'HTTP_YES' => $forward_prefix === 'http://' ? 'selected="selected"' : '', 'HTTPS_YES' => $forward_prefix === 'https://' ? 'selected="selected"' : '', 'FTP_YES' => $forward_prefix === 'ftp://' ? 'selected="selected"' : '', 'CHECK_EN' => $check_en, 'CHECK_DIS' => $check_dis));
    } else {
        $check_en = '';
        $check_dis = 'checked="checked"';
        $forward_url = 'no';
        $tpl->assign(array('READONLY_FORWARD' => ' readonly', 'DISABLE_FORWARD' => ' disabled="disabled"', 'CHECK_EN' => $check_en, 'CHECK_DIS' => $check_dis));
    }
    if ($ed_error === '_off_') {
        if ($dmn_type === 'dmn') {
            $subdomainQuery = '
				UPDATE
					`subdomain`
				SET
					`subdomain_url_forward` = ?,
					`status` = ?
				 WHERE
					`subdomain_id` = ?
			';
            $domainQuery = '
				UPDATE
					domain
				SET
					status = ?
				where 
					domain_id = ?
			';
        } else {
            $subdomainQuery = '
				UPDATE
					`subdomain_alias`
				SET
					`subdomain_alias_url_forward` = ?,
					`status` = ?
				WHERE
					`subdomain_alias_id` = ?
			';
            $domainQuery = '
				UPDATE
					domain_aliasses
				SET
					status = ?
				where 
					alias_id = ?
			';
        }
        exec_query($sql, $subdomainQuery, array($forward_url, EasySCP_Registry::get('Config')->ITEM_CHANGE_STATUS, $subdomain_id));
        exec_query($sql, $domainQuery, array(EasySCP_Registry::get('Config')->ITEM_CHANGE_STATUS, $dmn_id));
        if ($_POST['dmn_type'] == 'als') {
            send_request('110 DOMAIN alias ' . $dmn_id);
        } else {
            send_request('110 DOMAIN domain ' . $dmn_id);
        }
        $admin_login = $_SESSION['user_logged'];
        write_log("{$admin_login}: change domain alias forward: " . $subdomain_id);
        unset($_SESSION['edit_ID']);
        $tpl->assign('MESSAGE', '');
        return true;
    } else {
        $tpl->assign('MESSAGE', $ed_error);
        return false;
    }
}
Exemple #15
0
/**
 * Update repository index
 *
 * @param string $repositoryIndexFile Repository index file URI
 * @param string $webRepositoryLastUpdate Web repository last update
 */
function update_webdepot_software_list($repositoryIndexFile, $webRepositoryLastUpdate)
{
    $options = array('http' => array('user_agent' => 'PHP libxml agent'));
    $context = stream_context_create($options);
    libxml_set_streams_context($context);
    $webRepositoryIndexFile = new DOMDocument('1.0', 'UTF-8');
    $webRepositoryIndexFile->load($repositoryIndexFile);
    $webRepositoryIndexFile = simplexml_import_dom($webRepositoryIndexFile);
    if (utf8_decode($webRepositoryIndexFile->LAST_UPDATE->DATE) != $webRepositoryLastUpdate) {
        $truncatequery = 'TRUNCATE TABLE `web_software_depot`';
        exec_query($truncatequery);
        $badSoftwarePackageDefinition = 0;
        foreach ($webRepositoryIndexFile->PACKAGE as $package) {
            if (!empty($package->INSTALL_TYPE) && !empty($package->TITLE) && !empty($package->VERSION) && !empty($package->LANGUAGE) && !empty($package->TYPE) && !empty($package->DESCRIPTION) && !empty($package->VENDOR_HP) && !empty($package->DOWNLOAD_LINK) && !empty($package->SIGNATURE_LINK)) {
                $query = '
					INSERT INTO
						`web_software_depot` (
							`package_install_type`, `package_title`, `package_version`, `package_language`,
							`package_type`, `package_description`, `package_vendor_hp`, `package_download_link`,
							`package_signature_link`
						) VALUES (
							?, ?, ?, ?, ?, ?, ?, ?, ?
						)
				';
                exec_query($query, array(clean_input($package->INSTALL_TYPE), clean_input($package->TITLE), clean_input($package->VERSION), clean_input($package->LANGUAGE), clean_input($package->TYPE), clean_input($package->DESCRIPTION), encode_idna(strtolower(clean_input($package->VENDOR_HP))), encode_idna(strtolower(clean_input($package->DOWNLOAD_LINK))), encode_idna(strtolower(clean_input($package->SIGNATURE_LINK)))));
            } else {
                $badSoftwarePackageDefinition++;
                break;
            }
        }
        if (!$badSoftwarePackageDefinition) {
            exec_query('UPDATE `web_software_options` SET `webdepot_last_update` = ?', array($webRepositoryIndexFile->LAST_UPDATE->DATE));
            set_page_message(tr('Web software repository index been successfully updated.'), 'success');
        } else {
            set_page_message(tr('Update of Web software repository index has been aborted. Missing or empty fields.'), 'error');
        }
    } else {
        set_page_message(tr('Web software repository index is already up to date.'), 'info');
    }
}
Exemple #16
0
/**
 * Generate page
 *
 * @throws iMSCP_Exception
 * @throws iMSCP_Exception_Database
 * @param iMSCP_pTemplate $tpl Template engine instance
 * @param int $domainId Domain entity unique identifier
 * @param string $domainType Domain entity type
 * @return void
 */
function client_generatePage($tpl, $domainId, $domainType)
{
    $domainName = _client_getDomainName($domainId, $domainType);
    if ($domainName === false) {
        showBadRequestErrorPage();
    }
    $stmt = exec_query('SELECT * FROM ssl_certs WHERE domain_id = ? AND domain_type = ?', array($domainId, $domainType));
    if ($stmt->rowCount()) {
        $row = $stmt->fetchRow(PDO::FETCH_ASSOC);
        $dynTitle = customerHasFeature('ssl') && $row['status'] == 'ok' ? tr('Edit SSL certificate') : tr('Show SSL certificate');
        $certId = $row['cert_id'];
        $privateKey = tohtml($row['private_key']);
        $certificate = tohtml($row['certificate']);
        $caBundle = tohtml($row['ca_bundle']);
        $trAction = tr('Update');
        $status = $row['status'];
        $tpl->assign('STATUS', translate_dmn_status($status));
    } else {
        if (customerHasFeature('ssl')) {
            $dynTitle = tr('Add SSL certificate');
            $trAction = tr('Add');
            $certId = '0';
            $privateKey = '';
            $certificate = '';
            $caBundle = '';
            $tpl->assign('SSL_CERTIFICATE_STATUS', '');
        } else {
            set_page_message('SSL feature is currently disabled.', 'static_warning');
            redirectTo('domains_manage.php');
            return;
        }
    }
    if (customerHasFeature('ssl') && isset($_POST['cert_id']) && isset($_POST['private_key']) && isset($_POST['certificate']) && isset($_POST['ca_bundle'])) {
        $certId = $_POST['cert_id'];
        $privateKey = $_POST['private_key'];
        $certificate = $_POST['certificate'];
        $caBundle = $_POST['ca_bundle'];
    }
    $tpl->assign(array('TR_DYNAMIC_TITLE' => $dynTitle, 'DOMAIN_NAME' => tohtml(encode_idna($domainName)), 'KEY_CERT' => tohtml(trim($privateKey)), 'CERTIFICATE' => tohtml(trim($certificate)), 'CA_BUNDLE' => tohtml(trim($caBundle)), 'CERT_ID' => tohtml(trim($certId)), 'TR_ACTION' => $trAction));
    if (!customerHasFeature('ssl') || isset($status) && in_array($status, array('toadd', 'tochange', 'todelete'))) {
        $tpl->assign('SSL_CERTIFICATE_ACTIONS', '');
        if (!customerHasFeature('ssl')) {
            set_page_message(tr('SSL feature is not available. You can only view your certificate.'), 'static_warning');
        }
    }
}
/**
 * Update external mail server entries
 *
 * Note: In case all entries are marked as to be deleted, the external mail server is deactivated
 *
 * @throws iMSCP_Exception_Database
 * @param array $item Item data (item id and item type)
 * @return void
 */
function client_editExternalMailServerEntries($item)
{
    $verifiedData = _client_getVerifiedData($item[0], $item[1]);
    if (!empty($_POST)) {
        // Preparing entries stack
        $data['to_update'] = isset($_POST['to_update']) ? $_POST['to_update'] : array();
        $data['to_delete'] = isset($_POST['to_delete']) ? $_POST['to_delete'] : array();
        $data['type'] = isset($_POST['type']) ? $_POST['type'] : array();
        $data['priority'] = isset($_POST['priority']) ? $_POST['priority'] : array();
        $data['host'] = isset($_POST['host']) ? $_POST['host'] : array();
        $responses = iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddExternalMailServer, array('externalMailServerEntries' => $data));
        if (!$responses->isStopped()) {
            $entriesCount = count($data['type']);
            $error = false;
            // Validate all entries
            for ($index = 0; $index < $entriesCount; $index++) {
                if (isset($data['type'][$index]) && isset($data['priority'][$index]) && isset($data['host'][$index])) {
                    $data['host'][$index] = strtolower(rtrim($data['host'][$index], '.'));
                    if (empty($data['to_delete'][$index]) && !_client_validateDnsMxRecord($data['type'][$index], $data['priority'][$index], $data['host'][$index], $verifiedData)) {
                        $error = true;
                    }
                } else {
                    // Not all expected data were received
                    showBadRequestErrorPage();
                }
            }
            // Add entries into database
            if (!$error) {
                /** @var $db iMSCP_Database */
                $db = iMSCP_Database::getInstance();
                try {
                    $db->beginTransaction();
                    $dnsEntriesIds = '';
                    # Spam Filter ( filter ) MX type has highter precedence
                    $spamFilterMX = false;
                    $wildcardMxOnly = true;
                    for ($index = 0; $index < $entriesCount; $index++) {
                        if (!empty($data['to_delete'][$index]) && in_array($data['to_delete'][$index], $verifiedData['external_mail_dns_ids'])) {
                            // Entry to delete
                            if (empty($data['to_update']) && empty($data['type'])) {
                                exec_query('UPDATE domain_dns SET domain_dns_status = ? WHERE domain_dns_id = ?', array('todelete', $data['to_delete'][$index]));
                            } else {
                                exec_query('DELETE FROM domain_dns WHERE domain_dns_id = ?', $data['to_delete'][$index]);
                            }
                        } elseif (!empty($data['to_update'][$index]) && in_array($data['to_update'][$index], $verifiedData['external_mail_dns_ids'])) {
                            //  Entry to update
                            if ($data['type'][$index] == 'filter') {
                                $spamFilterMX = true;
                                $wildcardMxOnly = false;
                            } elseif ($data['type'][$index] == 'domain') {
                                $wildcardMxOnly = false;
                            }
                            exec_query('
									UPDATE
										domain_dns SET domain_dns = ?, domain_text = ?, domain_dns_status = ?
									WHERE
										domain_dns_id = ?
								', array($data['type'][$index] != 'wildcard' ? $verifiedData['item_name'] . '.' : '*.' . $verifiedData['item_name'] . '.', $data['priority'][$index] . "\t" . encode_idna($data['host'][$index]) . '.', 'tochange', $data['to_update'][$index]));
                            $dnsEntriesIds .= ',' . $data['to_update'][$index];
                        } else {
                            // Entry to add
                            if ($data['type'][$index] == 'filter') {
                                $spamFilterMX = true;
                                $wildcardMxOnly = false;
                            } elseif ($data['type'][$index] == 'domain') {
                                $wildcardMxOnly = false;
                            }
                            exec_query('
									INSERT INTO domain_dns (
										domain_id, alias_id, domain_dns, domain_class, domain_type, domain_text,
										owned_by, domain_dns_status
									) VALUES (
										?, ?, ?, ?, ?, ?, ?, ?
									)
								', array($verifiedData['domain_id'], $verifiedData['item_type'] == 'alias' ? $verifiedData['item_id'] : 0, $data['type'][$index] != 'wildcard' ? $verifiedData['item_name'] . '.' : '*.' . $verifiedData['item_name'] . '.', 'IN', 'MX', "{$data['priority'][$index]}\t" . encode_idna($data['host'][$index]) . '.', 'ext_mail_feature', 'toadd'));
                            $dnsEntriesIds .= ',' . $db->insertId();
                        }
                    }
                    $externalMailServer = $dnsEntriesIds !== '' ? $spamFilterMX ? 'filter' : ($wildcardMxOnly ? 'wildcard' : 'domain') : 'off';
                    if ($verifiedData['item_type'] == 'normal') {
                        exec_query('
								UPDATE
									domain SET external_mail = ?, domain_status = ?, external_mail_dns_ids = ?
								WHERE
									domain_id = ?
							', array($externalMailServer, 'tochange', ltrim($dnsEntriesIds, ','), $verifiedData['item_id']));
                    } else {
                        exec_query('
								UPDATE
									domain_aliasses SET external_mail = ?, alias_status = ?, external_mail_dns_ids = ?
								WHERE
									alias_id = ?
							', array($externalMailServer, 'tochange', ltrim($dnsEntriesIds, ','), $verifiedData['item_id']));
                    }
                    $db->commit();
                    iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddExternalMailServer, array('externalMailServerEntries' => $data));
                    send_request();
                    if ($externalMailServer !== 'off') {
                        set_page_message(tr('External mail server successfully scheduled for update.'), 'success');
                    } else {
                        set_page_message(tr('External mail server successfully scheduled for deactivation.'), 'success');
                    }
                    redirectTo('mail_external.php');
                } catch (iMSCP_Exception_Database $e) {
                    $db->rollBack();
                    if ($e->getCode() === 23000) {
                        set_page_message(tr('An entry is defined twice.'), 'error');
                    } else {
                        throw $e;
                    }
                }
            }
        } else {
            redirectTo('mail_external.php');
        }
    } else {
        if (!empty($verifiedData['external_mail_dns_ids'])) {
            $stmt = execute_query('
					SELECT
						*
					FROM
						domain_dns
					WHERE
						domain_dns_id IN(' . implode(',', $verifiedData['external_mail_dns_ids']) . ')
				');
            if ($stmt->rowCount()) {
                $data = array();
                while ($row = $stmt->fetchRow(PDO::FETCH_ASSOC)) {
                    $data['to_update'][] = $row['domain_dns_id'];
                    $data['type'][] = strpos($row['domain_dns'], '*') === false ? $verifiedData['external_mail_type'] == 'domain' ? 'domain' : 'filter' : 'wildcard';
                    list($priority, $host) = explode("\t", $row['domain_text'], 2);
                    $data['priority'][] = trim($priority);
                    $data['host'][] = rtrim($host, '.');
                }
            } else {
                // DNS entries pointed by domain or domain alias were not found ( should never occurs )
                if ($verifiedData['item_type'] == 'normal') {
                    $query = '
						UPDATE
							domain
						SET
							domain_status = ?,  external_mail = ?, external_mail_dns_ids = ?
						WHERE
							domain_id = ?
					';
                } else {
                    $query = '
						UPDATE
							domain_aliasses
						SET
							alias_status = ?, external_mail = ?, external_mail_dns_ids = ?
						WHERE
							alias_id = ?
					';
                }
                exec_query($query, array('tochange', 'off', null, $verifiedData['item_id']));
                send_request();
                set_page_message(tr('Entries associated to your external mail servers were not found. A Resynchronization has been scheduled.'), 'warning');
                redirectTo('mail_external.php');
                exit;
                // Only to make some IDE happy
            }
        } else {
            set_page_message('An unexpected error occurred.', 'error');
            redirectTo('mail_external.php');
            // No domain or domain alias data found ( should never occurs )
            exit;
            // Only to make some IDE happy
        }
    }
    client_generateView($verifiedData, $data);
}
Exemple #18
0
/**
 * Add new subdomain
 *
 * @return bool TRUE on success, FALSE on failure
 */
function client_addSubdomain()
{
    global $mainDmnProps;
    // Basic check
    if (empty($_POST['subdomain_name'])) {
        set_page_message(tr('You must enter a subdomain name.'), 'error');
        return false;
    }
    if (empty($_POST['domain_name'])) {
        showBadRequestErrorPage();
    }
    // Check for parent domain
    $domainName = clean_input($_POST['domain_name']);
    $domainType = $domainId = null;
    $domainList = _client_getDomainsList();
    foreach ($domainList as $domain) {
        if (($domain['type'] == 'dmn' || $domain['type'] == 'als') && $domain['name'] == $domainName) {
            $domainType = $domain['type'];
            $domainId = $domain['id'];
        }
    }
    if (null === $domainType) {
        showBadRequestErrorPage();
    }
    $subLabel = clean_input(strtolower($_POST['subdomain_name']));
    if ($subLabel == 'www' || strpos($subLabel, 'www.') !== false) {
        set_page_message(tr('%s is not allowed as subdomain label.', "<strong>www</strong>"), 'error');
        return false;
    }
    $subdomainName = $subLabel . '.' . $domainName;
    // Check for subdomain syntax
    if (!isValidDomainName($subdomainName)) {
        set_page_message(tr('Subdomain name is not valid.'), 'error');
        return false;
    }
    // Ensure that this subdomain doesn't already exists as domain or domain alias
    $stmt = exec_query('
        SELECT domain_id FROM domain WHERE domain_name = :subdomain_name
        UNION ALL
        SELECT alias_id FROM domain_aliasses WHERE alias_name = :subdomain_name', array('subdomain_name' => $subdomainName));
    if ($stmt->rowCount()) {
        set_page_message(tr('Subdomain %s is unavailable.', "<strong>{$subdomainName}</strong>"), 'error');
        return false;
    }
    $subLabelAscii = clean_input(encode_idna(strtolower($_POST['subdomain_name'])));
    $subdomainNameAscii = encode_idna($subdomainName);
    // Check for sudomain existence
    foreach ($domainList as $domain) {
        if ($domain['name'] == $subdomainNameAscii) {
            set_page_message(tr('Subdomain %s already exist.', "<strong>{$subdomainName}</strong>"), 'error');
            return false;
        }
    }
    // Set default mount point
    if ($domainType == 'dmn') {
        if (in_array($subLabelAscii, array('backups', 'cgi-bin', 'errors', 'logs', 'phptmp'))) {
            $mountPoint = "/sub_{$subLabelAscii}";
        } else {
            $mountPoint = "/{$subLabelAscii}";
        }
    } else {
        if (in_array($subLabelAscii, array('cgi-bin', 'phptmp'))) {
            $mountPoint = "/{$domainName}/sub_{$subLabelAscii}";
        } else {
            $mountPoint = "/{$domainName}/{$subLabelAscii}";
        }
    }
    // Check for shared mount point option
    if (isset($_POST['shared_mount_point']) && $_POST['shared_mount_point'] == 'yes') {
        // We are safe here
        if (!isset($_POST['shared_mount_point_domain'])) {
            showBadRequestErrorPage();
        }
        $sharedMountPointDomain = clean_input($_POST['shared_mount_point_domain']);
        // Get shared mount point
        foreach ($domainList as $domain) {
            if ($domain['name'] == $sharedMountPointDomain) {
                $mountPoint = $domain['mount_point'];
            }
        }
    }
    // Check for URL forwarding option
    $forwardUrl = 'no';
    if (isset($_POST['url_forwarding']) && $_POST['url_forwarding'] == 'yes') {
        // We are safe here
        if (isset($_POST['forward_url_scheme']) && isset($_POST['forward_url'])) {
            $forwardUrl = clean_input($_POST['forward_url_scheme']) . clean_input($_POST['forward_url']);
            try {
                try {
                    $uri = iMSCP_Uri_Redirect::fromString($forwardUrl);
                } catch (Zend_Uri_Exception $e) {
                    throw new iMSCP_Exception(tr('Forward URL %s is not valid.', "<strong>{$forwardUrl}</strong>"));
                }
                $uri->setHost(encode_idna($uri->getHost()));
                if ($uri->getHost() == $subdomainNameAscii && $uri->getPath() == '/') {
                    throw new iMSCP_Exception(tr('Forward URL %s is not valid.', "<strong>{$forwardUrl}</strong>") . ' ' . tr('Subdomain %s cannot be forwarded on itself.', "<strong>{$subdomainName}</strong>"));
                }
                $forwardUrl = $uri->getUri();
            } catch (Exception $e) {
                set_page_message($e->getMessage(), 'error');
                return false;
            }
        } else {
            showBadRequestErrorPage();
        }
    }
    $db = iMSCP_Database::getInstance();
    try {
        $db->beginTransaction();
        iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddSubdomain, array('subdomainName' => $subdomainName, 'subdomainType' => $domainType, 'parentDomainId' => $domainId, 'mountPoint' => $mountPoint, 'forwardUrl' => $forwardUrl, 'customerId' => $_SESSION['user_id']));
        if ($domainType == 'als') {
            $query = "\n                INSERT INTO subdomain_alias (\n                    alias_id, subdomain_alias_name, subdomain_alias_mount, subdomain_alias_url_forward,\n                    subdomain_alias_status\n                ) VALUES (\n                    ?, ?, ?, ?, ?\n                )\n            ";
        } else {
            $query = "\n                INSERT INTO subdomain (\n                    domain_id, subdomain_name, subdomain_mount, subdomain_url_forward, subdomain_status\n                ) VALUES (\n                    ?, ?, ?, ?, ?\n                )\n            ";
        }
        exec_query($query, array($domainId, $subLabelAscii, $mountPoint, $forwardUrl, 'toadd'));
        $subdomainId = $db->insertId();
        // Create the phpini entry for that subdomain
        $phpini = iMSCP_PHPini::getInstance();
        $phpini->loadResellerPermissions($_SESSION['user_created_by']);
        // Load reseller PHP permissions
        $phpini->loadClientPermissions($_SESSION['user_id']);
        // Load client PHP permissions
        $phpini->loadDomainIni($_SESSION['user_id'], $mainDmnProps['domain_id'], 'dmn');
        // Load main domain PHP configuration options
        $phpini->saveDomainIni($_SESSION['user_id'], $subdomainId, $domainType == 'dmn' ? 'sub' : 'subals');
        iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddSubdomain, array('subdomainName' => $subdomainName, 'subdomainType' => $domainType, 'parentDomainId' => $domainId, 'mountPoint' => $mountPoint, 'forwardUrl' => $forwardUrl, 'customerId' => $_SESSION['user_id'], 'subdomainId' => $subdomainId));
        $db->commit();
        send_request();
        write_log(sprintf('A new `%s` subdomain has been created by %s', $subdomainName, decode_idna($_SESSION['user_logged'])), E_USER_NOTICE);
        return true;
    } catch (iMSCP_Exception_Database $e) {
        $db->rollBack();
        write_log(sprintf('System was unable to create the `%s` subdomain: %s', $subdomainName, $e->getMessage()), E_USER_ERROR);
        set_page_message('Could not create subdomain. An unexpected error occurred.', 'error');
        return false;
    }
}
Exemple #19
0
/**
 * Check correction of entered users data
 */
function check_user_data()
{
    global $dmn_name;
    // domain name
    global $dmn_expire;
    // Domain expire date
    global $dmn_chp;
    // choosed hosting plan
    global $dmn_pt;
    global $validation_err_msg;
    $sql = EasySCP_Registry::get('Db');
    $cfg = EasySCP_Registry::get('Config');
    // personal template
    $event_txt = '';
    if (isset($_POST['dmn_name'])) {
        $dmn_name = strtolower(trim($_POST['dmn_name']));
    }
    if (isset($_POST['dmn_expire_date'])) {
        $dmn_expire = clean_input($_POST['dmn_expire_date']);
    }
    if (isset($_POST['dmn_tpl'])) {
        $dmn_chp = $_POST['dmn_tpl'];
    }
    if (isset($_POST['chtpl'])) {
        $dmn_pt = $_POST['chtpl'];
    }
    // Check if input string is a valid domain names
    if (!validates_dname($dmn_name)) {
        set_page_message($validation_err_msg, 'warning');
        return false;
    }
    // Should be perfomed after domain names syntax validation now
    $dmn_name = encode_idna($dmn_name);
    if (easyscp_domain_exists($dmn_name, $_SESSION['user_id'])) {
        $event_txt = tr('Domain with that name already exists on the system!');
    } else {
        if ($dmn_name == $cfg->BASE_SERVER_VHOST) {
            $event_txt = tr('Master domain cannot be used!');
        }
    }
    // we have plans only for admins
    if (isset($cfg->HOSTING_PLANS_LEVEL) && $cfg->HOSTING_PLANS_LEVEL === 'admin') {
        $dmn_pt = '_no_';
    }
    if (!empty($event_txt)) {
        // There are wrong input data
        set_page_message($event_txt, 'error');
        return false;
    } else {
        if ($dmn_pt == '_yes_' || !isset($_POST['dmn_tpl'])) {
            // send through the session the data
            $_SESSION['dmn_name'] = $dmn_name;
            $_SESSION['dmn_expire_date'] = $dmn_expire;
            $_SESSION['dmn_tpl'] = $dmn_chp;
            $_SESSION['chtpl'] = $dmn_pt;
            $_SESSION['step_one'] = "_yes_";
            user_goto('user_add2.php');
        } else {
            // check if reseller limits are not touched
            $ehp_error = '';
            // fill dummy to satisfy warning...
            if (reseller_limits_check($sql, $ehp_error, $_SESSION['user_id'], $dmn_chp)) {
                // send through the session the data
                $_SESSION['dmn_name'] = $dmn_name;
                $_SESSION['dmn_expire_date'] = $dmn_expire;
                $_SESSION['dmn_tpl'] = $dmn_chp;
                $_SESSION['chtpl'] = $dmn_pt;
                $_SESSION['step_one'] = "_yes_";
                user_goto('user_add3.php');
            } else {
                set_page_message(tr("Hosting plan values exceed reseller maximum values!"), 'warning');
                return false;
            }
        }
    }
}
Exemple #20
0
// E_USER_WARNING: switching to an other account, etc
// E_USER_ERROR: "admin MUST know" messages
$config->LOG_LEVEL = E_USER_NOTICE;
// Creation of webmaster, postmaster and abuse forwarders when
// domain/alias/ subdomain is created
$config->CREATE_DEFAULT_EMAIL_ADDRESSES = true;
// Use hard mail suspension when suspending a domain:
// true: email accounts are hard suspended (completely unreachable)
// false: email accounts are soft suspended (passwords are modified so
// user can't access the accounts)
$config->HARD_MAIL_SUSPENSION = true;
// Prevent external login (i.e. check for valid local referer)
// separated in admin, reseller and client
// This option allows to use external login scripts
// true: prevent external login, check for referer, more secure
// false: allow external login, do not check for referer, less
// security (risky)
$config->PREVENT_EXTERNAL_LOGIN_ADMIN = true;
$config->PREVENT_EXTERNAL_LOGIN_RESELLER = true;
$config->PREVENT_EXTERNAL_LOGIN_CLIENT = true;
// Automatic search for new version
$config->CHECK_FOR_UPDATES = true;
# Converting some possible IDN to ACE (see #2476)
$config->DEFAULT_ADMIN_ADDRESS = encode_idna($config->DEFAULT_ADMIN_ADDRESS);
$config->SERVER_HOSTNAME = encode_idna($config->SERVER_HOSTNAME);
$config->BASE_SERVER_VHOST = encode_idna($config->BASE_SERVER_VHOST);
$config->DATABASE_HOST = encode_idna($config->DATABASE_HOST);
// Initialize the application
EasySCP_Initializer::run($config);
// Remove useless variable
unset($config);
Exemple #21
0
/**
 * Check input data
 * @param EasySCP_TemplateEngine $tpl
 * @param int $alias_id
 */
function check_fwd_data($tpl, $alias_id)
{
    $sql = EasySCP_Registry::get('Db');
    $cfg = EasySCP_Registry::get('Config');
    $forward_url = strtolower(clean_input($_POST['forward']));
    // unset errors
    $ed_error = '_off_';
    // NXW: Unused variable so...
    // $admin_login = '';
    if (isset($_POST['status']) && $_POST['status'] == 1) {
        $forward_prefix = clean_input($_POST['forward_prefix']);
        if (substr_count($forward_url, '.') <= 2) {
            $ret = validates_dname($forward_url);
        } else {
            $ret = validates_dname($forward_url, true);
        }
        if (!$ret) {
            $ed_error = tr("Wrong domain part in forward URL!");
        } else {
            $forward_url = encode_idna($forward_prefix . $forward_url);
        }
        $check_en = $cfg->HTML_CHECKED;
        $check_dis = '';
        $tpl->assign(array('FORWARD' => tohtml($forward_url), 'HTTP_YES' => $forward_prefix === 'http://' ? $cfg->HTML_SELECTED : '', 'HTTPS_YES' => $forward_prefix === 'https://' ? $cfg->HTML_SELECTED : '', 'FTP_YES' => $forward_prefix === 'ftp://' ? $cfg->HTML_SELECTED : '', 'CHECK_EN' => $check_en, 'CHECK_DIS' => $check_dis, 'DISABLE_FORWARD' => '', 'READONLY_FORWARD' => ''));
    } else {
        $check_en = $cfg->HTML_CHECKED;
        $check_dis = '';
        $forward_url = 'no';
        $tpl->assign(array('READONLY_FORWARD' => $cfg->HTML_READONLY, 'DISABLE_FORWARD' => $cfg->HTML_DISABLED, 'CHECK_EN' => $check_en, 'CHECK_DIS' => $check_dis));
    }
    if ($ed_error === '_off_') {
        $query = "\n\t\t\tUPDATE\n\t\t\t\t`domain_aliasses`\n\t\t\tSET\n\t\t\t\t`url_forward` = ?,\n\t\t\t\t`status` = ?\n\t\t\tWHERE\n\t\t\t\t`alias_id` = ?\n\t\t";
        exec_query($sql, $query, array($forward_url, $cfg->ITEM_CHANGE_STATUS, $alias_id));
        $query = "\n\t\t\tUPDATE\n\t\t\t\t`subdomain_alias`\n\t\t\tSET\n\t\t\t\t`status` = ?\n\t\t\tWHERE\n\t\t\t\t`alias_id` = ?\n\t\t";
        exec_query($sql, $query, array($cfg->ITEM_CHANGE_STATUS, $alias_id));
        send_request('110 DOMAIN alias ' . $alias_id);
        // NXW: oh my god... Should be review...
        /*
        $admin_login = $_SESSION['user_logged'];
        write_log("$admin_login: changes domain alias forward: " . $rs->fields['t1.alias_name']);
        */
        unset($_SESSION['edit_ID']);
        $tpl->assign('MESSAGE', "");
        return true;
    } else {
        $tpl->assign('MESSAGE', $ed_error);
        return false;
    }
}
Exemple #22
0
/**
 *
 * @global <type> $cr_user_id
 * @global <type> $alias_name
 * @global <type> $domain_ip
 * @global <type> $forward
 * @global <type> $forward_prefix
 * @global <type> $mount_point
 * @global <type> $validation_err_msg
 * @param <type> $err_al
 * @return <type>
 */
function add_domain_alias(&$err_al)
{
    global $cr_user_id, $alias_name, $domain_ip, $forward, $forward_prefix, $mount_point, $validation_err_msg;
    $cfg = EasySCP_Registry::get('Config');
    $sql = EasySCP_Registry::get('Db');
    $cr_user_id = $dmn_id = $_SESSION['dmn_id'];
    $alias_name = strtolower(clean_input($_POST['ndomain_name']));
    $domain_ip = $_SESSION['dmn_ip'];
    $mount_point = array_encode_idna(strtolower($_POST['ndomain_mpoint']), true);
    if ($_POST['status'] == 1) {
        $forward = encode_idna(strtolower(clean_input($_POST['forward'])));
        $forward_prefix = clean_input($_POST['forward_prefix']);
    } else {
        $forward = 'no';
        $forward_prefix = '';
    }
    // Check if input string is a valid domain names
    if (!validates_dname($alias_name)) {
        set_page_message($validation_err_msg, 'warning');
        return;
    }
    // Should be perfomed after domain names syntax validation now
    $alias_name = encode_idna($alias_name);
    if (easyscp_domain_exists($alias_name, $_SESSION['user_id'])) {
        $err_al = tr('Domain with that name already exists on the system!');
    } else {
        if (!validates_mpoint($mount_point) && $mount_point != '/') {
            $err_al = tr("Incorrect mount point syntax");
        } else {
            if ($_POST['status'] == 1) {
                $aurl = @parse_url($forward_prefix . decode_idna($forward));
                if ($aurl === false) {
                    $err_al = tr("Wrong address in forward URL!");
                } else {
                    $domain = $aurl['host'];
                    if (substr_count($domain, '.') <= 2) {
                        $ret = validates_dname($domain);
                    } else {
                        $ret = validates_dname($domain, true);
                    }
                    if (!$ret) {
                        $err_al = tr("Wrong domain part in forward URL!");
                    } else {
                        $domain = encode_idna($aurl['host']);
                        $forward = $aurl['scheme'] . '://';
                        if (isset($aurl['user'])) {
                            $forward .= $aurl['user'] . (isset($aurl['pass']) ? ':' . $aurl['pass'] : '') . '@';
                        }
                        $forward .= $domain;
                        if (isset($aurl['port'])) {
                            $forward .= ':' . $aurl['port'];
                        }
                        if (isset($aurl['path'])) {
                            $forward .= $aurl['path'];
                        } else {
                            $forward .= '/';
                        }
                        if (isset($aurl['query'])) {
                            $forward .= '?' . $aurl['query'];
                        }
                        if (isset($aurl['fragment'])) {
                            $forward .= '#' . $aurl['fragment'];
                        }
                    }
                }
            } else {
                $query = "\n\t\t\tSELECT\n\t\t\t\t`domain_id`\n\t\t\tFROM\n\t\t\t\t`domain_aliasses`\n\t\t\tWHERE\n\t\t\t\t`alias_name` = ?\n\t\t;";
                $res = exec_query($sql, $query, $alias_name);
                $query = "\n\t\t\tSELECT\n\t\t\t\t`domain_id`\n\t\t\tFROM\n\t\t\t\t`domain`\n\t\t\tWHERE\n\t\t\t\t`domain_name` = ?\n\t\t;";
                $res2 = exec_query($sql, $query, $alias_name);
                if ($res->rowCount() > 0 || $res2->rowCount() > 0) {
                    // we already have a domain with this name
                    $err_al = tr("Domain with this name already exist");
                }
                if (mount_point_exists($dmn_id, $mount_point)) {
                    $err_al = tr('Mount point already in use!');
                }
            }
        }
    }
    if ('_off_' !== $err_al) {
        set_page_message($err_al, 'error');
        return;
    }
    // Begin add new alias domain
    $query = "\n\t\tINSERT INTO\n\t\t\t`domain_aliasses` (\n\t\t\t\t`domain_id`, `alias_name`, `alias_mount`, `status`,\n\t\t\t\t`alias_ip_id`, `url_forward`\n\t\t\t)\n\t\tVALUES\n\t\t\t(?, ?, ?, ?, ?, ?)\n\t;";
    exec_query($sql, $query, array($cr_user_id, $alias_name, $mount_point, $cfg->ITEM_ADD_STATUS, $domain_ip, $forward));
    $alias_id = $sql->insertId();
    update_reseller_c_props(get_reseller_id($cr_user_id));
    send_request('110 DOMAIN alias ' . $alias_id);
    $admin_login = $_SESSION['user_logged'];
    write_log("{$admin_login}: add domain alias: {$alias_name}");
    $_SESSION['alias_added_succesfully'] = 1;
    user_goto('user_add4.php?accout=' . $cr_user_id);
}
Exemple #23
0
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * @link 		http://www.easyscp.net
 * @author 		EasySCP Team
 */
require_once '../include/easyscp-lib.php';
$cfg = EasySCP_Registry::get('Config');
if (isset($_GET['logout'])) {
    unset_user_login_data();
}
do_session_timeout();
init_login();
if (isset($_POST['uname']) && !empty($_POST['uname']) && isset($_POST['upass']) && !empty($_POST['upass'])) {
    check_input(trim($_POST['uname']));
    check_input(trim($_POST['upass']));
    $uname = encode_idna($_POST['uname']);
    if (register_user($uname, $_POST['upass'])) {
        redirect_to_level_page();
    }
    user_goto('index.php');
}
if (check_user_login() && !redirect_to_level_page()) {
    unset_user_login_data();
}
shall_user_wait();
$theme_color = isset($_SESSION['user_theme']) ? $_SESSION['user_theme'] : $cfg->USER_INITIAL_THEME;
$tpl = EasySCP_TemplateEngine::getInstance();
if (($cfg->MAINTENANCEMODE || EasySCP_Update_Database::getInstance()->checkUpdateExists()) && !isset($_POST['admin'])) {
    $template = 'maintenancemode.tpl';
    $tpl->assign(array('TR_PAGE_TITLE' => tr('EasySCP a Virtual Hosting Control System'), 'TR_MESSAGE' => nl2br(tohtml($cfg->MAINTENANCEMODE_MESSAGE)), 'TR_ADMINLOGIN' => tr('Administrator login'), 'TR_SSL_LINK' => isset($_SERVER['HTTPS']) ? 'http://' . htmlentities($_SERVER['HTTP_HOST']) : 'https://' . htmlentities($_SERVER['HTTP_HOST']), 'TR_WEBMAIL_SSL_LINK' => "webmail", 'TR_FTP_SSL_LINK' => "ftp", 'TR_PMA_SSL_LINK' => "pma", 'TR_SSL_IMAGE' => isset($_SERVER['HTTPS']) ? 'lock.png' : 'unlock.png', 'TR_SSL_DESCRIPTION' => !isset($_SERVER['HTTPS']) ? tr('Secure Connection') : tr('Normal Connection')));
} else {
/**
 * Add external mail server entries
 *
 * @throws iMSCP_Exception_Database
 * @param array $item Item data (item id and item type)
 * @return void
 */
function client_addExternalMailServerEntries($item)
{
    $verifiedData = _client_getVerifiedData($item[0], $item[1]);
    if (!empty($_POST)) {
        // Preparing entries stack
        $data['type'] = isset($_POST['type']) ? $_POST['type'] : array();
        $data['priority'] = isset($_POST['priority']) ? $_POST['priority'] : array();
        $data['host'] = isset($_POST['host']) ? $_POST['host'] : array();
        $responses = iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddExternalMailServer, array('externalMailServerEntries' => $data));
        if (!$responses->isStopped()) {
            $entriesCount = count($data['type']);
            $error = false;
            # Spam Filter ( filter ) MX type has highter precedence
            $spamFilterMX = false;
            $wildcardMxOnly = true;
            // Validate all entries
            for ($index = 0; $index < $entriesCount; $index++) {
                if (isset($data['type'][$index]) && isset($data['priority'][$index]) && isset($data['host'][$index])) {
                    $data['host'][$index] = strtolower(rtrim($data['host'][$index], '.'));
                    if (!_client_validateDnsMxRecord($data['type'][$index], $data['priority'][$index], $data['host'][$index], $verifiedData)) {
                        $error = true;
                    }
                    if ($data['type'][$index] == 'filter') {
                        $spamFilterMX = true;
                        $wildcardMxOnly = false;
                    } elseif ($data['type'][$index] == 'domain') {
                        $wildcardMxOnly = false;
                    }
                } else {
                    // Not all expected data were received
                    showBadRequestErrorPage();
                }
            }
            // Add DNS entries into database
            if (!$error) {
                /** @var $db iMSCP_Database */
                $db = iMSCP_Database::getInstance();
                try {
                    $db->beginTransaction();
                    // All successfully inserted or nothing
                    $dnsEntriesIds = '';
                    for ($index = 0; $index < $entriesCount; $index++) {
                        // Add MX record
                        exec_query('
								INSERT INTO domain_dns (
									domain_id, alias_id, domain_dns, domain_class, domain_type, domain_text, owned_by,
									domain_dns_status
								) VALUES (
									?, ?, ?, ?, ?, ?, ?, ?
								)
							', array($verifiedData['domain_id'], $verifiedData['item_type'] == 'alias' ? $verifiedData['item_id'] : 0, $data['type'][$index] != 'wildcard' ? $verifiedData['item_name'] . '.' : '*.' . $verifiedData['item_name'] . '.', 'IN', 'MX', "{$data['priority'][$index]}\t" . encode_idna($data['host'][$index]) . '.', 'ext_mail_feature', 'toadd'));
                        $dnsEntriesIds .= ',' . $db->insertId();
                    }
                    if ($verifiedData['item_type'] == 'normal') {
                        exec_query('
								UPDATE
									domain SET external_mail = ?, domain_status = ?, external_mail_dns_ids = ?
								WHERE
									domain_id = ?
							', array($spamFilterMX ? 'filter' : ($wildcardMxOnly ? 'wildcard' : 'domain'), 'tochange', ltrim($dnsEntriesIds, ','), $verifiedData['domain_id']));
                    } else {
                        exec_query('
								UPDATE
									domain_aliasses SET external_mail = ?, alias_status = ?, external_mail_dns_ids = ?
								WHERE
									alias_id = ?
							', array($spamFilterMX ? 'filter' : ($wildcardMxOnly ? 'wildcard' : 'domain'), 'tochange', ltrim($dnsEntriesIds, ','), $verifiedData['item_id']));
                    }
                    $db->commit();
                    iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddExternalMailServer, array('externalMailServerEntries' => $data));
                    send_request();
                    set_page_message(tr('External mail server successfully scheduled for addition.'), 'success');
                    redirectTo('mail_external.php');
                } catch (iMSCP_Exception_Database $e) {
                    $db->rollBack();
                    if ($e->getCode() === 23000) {
                        set_page_message(tr('An entry is defined twice.'), 'error');
                    } else {
                        throw $e;
                    }
                }
            }
        } else {
            redirectTo('mail_external.php');
        }
    } else {
        $data['type'][] = 'domain';
        $data['priority'][] = '5';
        $data['host'][] = '';
    }
    client_generateView($verifiedData, $data);
}
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
// Include core library
require 'imscp-lib.php';
iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAdminScriptStart);
check_login('admin');
/** @var $cfg iMSCP_Config_Handler_File */
$cfg = iMSCP_Registry::get('config');
$tpl = new iMSCP_pTemplate();
$tpl->define_dynamic(array('layout' => 'shared/layouts/ui.tpl', 'page' => 'admin/software_options.tpl', 'page_message' => 'layout'));
$tpl->assign('TR_PAGE_TITLE', tr('Admin / Settings / Software Options'));
if (isset($_POST['uaction']) && $_POST['uaction'] == 'apply') {
    $error = "";
    $webdepot_xml_url = encode_idna(strtolower(clean_input($_POST['webdepot_xml_url'])));
    strlen($webdepot_xml_url) > 0 ? $use_webdepot = $_POST['use_webdepot'] : ($use_webdepot = '0');
    if (strlen($webdepot_xml_url) > 0 && $use_webdepot === '1') {
        $xml_file = @file_get_contents($webdepot_xml_url);
        if (!strpos($xml_file, 'i-MSCP web software repositories list')) {
            set_page_message(tr("Unable to read xml file for web software."), 'error');
            $error = 1;
        }
    }
    if (!$error) {
        $query = "\n            UPDATE\n                `web_software_options`\n            SET\n                `use_webdepot` = '" . $use_webdepot . "',\n                `webdepot_xml_url` = '" . $webdepot_xml_url . "'\n        ";
        execute_query($query);
        set_page_message(tr("Software installer options successfully updated."), 'success');
    }
}
$query = "SELECT * FROM `web_software_options`";
Exemple #26
0
/**
 * Must be documented
 *
 * @param $searchQuery
 * @param $countQuery
 * @param int $resellerId Reseller unique identifier
 * @param $startIndex
 * @param $rowsPerPage
 * @param $searchFor
 * @param $searchCommon
 * @param $searchStatus
 * @return void
 */
function gen_manage_domain_query(&$searchQuery, &$countQuery, $resellerId, $startIndex, $rowsPerPage, $searchFor, $searchCommon, $searchStatus)
{
    if ($searchFor === 'n/a' && $searchCommon === 'n/a' && $searchStatus === 'n/a') {
        // We have pure list query;
        $countQuery = "\n\t\t\tSELECT\n\t\t\t\tCOUNT(domain_id) AS cnt\n\t\t\tFROM\n\t\t\t\tdomain\n\t\t\tINNER JOIN\n\t\t\t\tadmin ON(admin_id = domain_admin_id)\n\t\t\tWHERE\n\t\t\t\tcreated_by = '{$resellerId}'\n\t\t";
        $searchQuery = "\n\t\t\tSELECT\n\t\t\t\t*\n\t\t\tFROM\n\t\t\t\tdomain\n\t\t\tINNER JOIN\n\t\t\t\tadmin ON(admin_id = domain_admin_id)\n\t\t\tWHERE\n\t\t\t\tcreated_by = '{$resellerId}'\n\t\t\tORDER BY\n\t\t\t\tdomain_name ASC\n\t\t\tLIMIT\n\t\t\t\t{$startIndex}, {$rowsPerPage}\n\t\t";
    } elseif ($searchFor == '' && $searchStatus != '') {
        if ($searchStatus == 'all') {
            $addQuery = "created_by = '{$resellerId}'";
        } else {
            $addQuery = "created_by = '{$resellerId}' AND domain_status = '{$searchStatus}'";
        }
        $countQuery = "SELECT COUNT(domain_id) AS cnt FROM domain WHERE {$addQuery}";
        $searchQuery = "\n\t\t\tSELECT\n\t\t\t\t*\n\t\t\tFROM\n\t\t\t\tdomain\n\t\t\tINNER JOIN\n\t\t\t\tadmin ON(admin_id = domain_admin_id)\n\t\t\tWHERE\n\t\t\t\t{$addQuery}\n\t\t\tORDER BY\n\t\t\t\tdomain_name ASC\n\t\t\tLIMIT\n\t\t\t\t{$startIndex}, {$rowsPerPage}\n\t\t";
    } elseif ($searchFor != '') {
        if ($searchCommon == 'domain_name') {
            $searchFor = encode_idna($searchFor);
            $addQuery = "WHERE admin_name RLIKE '" . addslashes($searchFor) . "' %s";
        } elseif ($searchCommon == 'customer_id') {
            $addQuery = "WHERE customer_id RLIKE '" . addslashes($searchFor) . "' %s";
        } elseif ($searchCommon == 'lname') {
            $addQuery = "WHERE (lname RLIKE '" . addslashes($searchFor) . "' OR fname RLIKE '" . addslashes($searchFor) . "') %s";
        } elseif ($searchCommon == 'firm') {
            $addQuery = "WHERE firm RLIKE '" . addslashes($searchFor) . "' %s";
        } elseif ($searchCommon == 'city') {
            $addQuery = "WHERE city RLIKE '" . addslashes($searchFor) . "' %s";
        } elseif ($searchCommon == 'state') {
            $addQuery = "WHERE state RLIKE '" . addslashes($searchFor) . "' %s";
        } elseif ($searchCommon == 'country') {
            $addQuery = "WHERE country RLIKE '" . addslashes($searchFor) . "' %s";
        }
        if (isset($addQuery)) {
            if ($searchStatus != 'all') {
                $addQuery = sprintf($addQuery, " AND created_by = '{$resellerId}' AND domain_status = '{$searchStatus}'");
                $countQuery = "\n\t\t\t\t    SELECT\n\t\t\t\t\t    COUNT(admin_id) AS cnt\n\t\t\t\t    FROM\n\t\t\t\t\t    admin AS t1, domain AS t2\n\t\t\t\t    {$addQuery}\n\t\t\t\tAND\n\t\t\t\t\tt1.admin_id = t2.domain_admin_id\n\t\t\t";
            } else {
                $addQuery = sprintf($addQuery, " AND `created_by` = '{$resellerId}'");
                $countQuery = "SELECT COUNT(admin_id) AS cnt FROM admin {$addQuery}";
            }
            $searchQuery = "\n\t\t\t    SELECT\n\t\t\t\t    t1.admin_id, t1.admin_status, t2.*\n\t\t\t    FROM\n\t\t\t\t    admin AS t1, domain AS t2\n\t\t\t    {$addQuery}\n\t\t\t    AND\n\t\t\t\t    t1.admin_id = t2.domain_admin_id\n\t\t\t    ORDER BY\n\t\t\t\t    t2.domain_name ASC\n\t\t\t    LIMIT\n\t\t\t\t    {$startIndex}, {$rowsPerPage}\n\t\t    ";
        }
    }
}
Exemple #27
0
/**
 * Validate a domain name
 *
 * @param string $domainName Domain name
 * @return bool TRUE if the given domain name is valid, FALSE otherwise
 */
function isValidDomainName($domainName)
{
    global $dmnNameValidationErrMsg;
    if (strpos($domainName, '.') === 0 || substr($domainName, -1) == '.') {
        $dmnNameValidationErrMsg = tr('Domain name cannot start nor end with dot.');
        return false;
    } elseif (($asciiDomainName = encode_idna($domainName)) !== false) {
        $asciiDomainName = strtolower($asciiDomainName);
        if (strlen($asciiDomainName) > 255) {
            $dmnNameValidationErrMsg = tr('Domain name (ASCII form) cannot be greater than 255 characters.');
            return false;
        }
        if (preg_match('/([^a-z0-9\\-\\.])/', $asciiDomainName, $m)) {
            $dmnNameValidationErrMsg = tr('Domain name contains an invalid character: %s', $m[1]);
            return false;
        } elseif (strpos($asciiDomainName, '..') !== false) {
            $dmnNameValidationErrMsg = tr('Usage of dot in domain name labels is prohibited.');
            return false;
        }
        $labels = explode('.', $asciiDomainName);
        if (sizeof($labels) > 1) {
            foreach ($labels as $label) {
                if (strlen($label) > 63) {
                    $dmnNameValidationErrMsg = tr('Domain name labels cannot be greater than 63 characters.');
                    return false;
                } elseif (preg_match('/([^a-z0-9\\-])/', $label, $m)) {
                    $dmnNameValidationErrMsg = tr("Domain name label '%s' contain an invalid character: %s", $label, $m[1]);
                    return false;
                } elseif (preg_match('/^[\\-]|[\\-]$/', $label)) {
                    $dmnNameValidationErrMsg = tr('Domain name labels cannot start nor end with hyphen.');
                    return false;
                }
            }
        } else {
            $dmnNameValidationErrMsg = tr('Invalid domain name.');
            return false;
        }
    } else {
        $dmnNameValidationErrMsg = tr('Invalid domain name.');
        return false;
    }
    return true;
}
Exemple #28
0
/**
 * 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');
}
Exemple #29
0
/**
 * Add new domain alias
 *
 * @return bool TRUE on success, FALSE on failure
 */
function addDomainAlias()
{
    global $mainDmnProps;
    // Basic check
    if (empty($_POST['domain_alias_name'])) {
        set_page_message(tr('You must enter a domain alias name.'), 'error');
        return false;
    }
    $domainAliasName = clean_input(strtolower($_POST['domain_alias_name']));
    // Check for domain alias name syntax
    global $dmnNameValidationErrMsg;
    if (!isValidDomainName($domainAliasName)) {
        set_page_message($dmnNameValidationErrMsg, 'error');
        return false;
    }
    // www is considered as an alias of the domain alias
    while (strpos($domainAliasName, 'www.') !== false) {
        $domainAliasName = substr($domainAliasName, 4);
    }
    // Check for domain alias existence
    if (imscp_domain_exists($domainAliasName, $_SESSION['user_created_by'])) {
        set_page_message(tr('Domain %s is unavailable.', "<strong>{$domainAliasName}</strong>"), 'error');
        return false;
    }
    $domainAliasNameAscii = encode_idna($domainAliasName);
    // Set default mount point
    $mountPoint = "/{$domainAliasNameAscii}";
    // Check for shared mount point option
    if (isset($_POST['shared_mount_point']) && $_POST['shared_mount_point'] == 'yes') {
        // We are safe here
        if (!isset($_POST['shared_mount_point_domain'])) {
            showBadRequestErrorPage();
        }
        $sharedMountPointDomain = clean_input($_POST['shared_mount_point_domain']);
        $domainList = _client_getDomainsList();
        // Get shared mount point
        foreach ($domainList as $domain) {
            if ($domain['name'] == $sharedMountPointDomain) {
                $mountPoint = $domain['mount_point'];
            }
        }
    }
    // Check for URL forwarding option
    $forwardUrl = 'no';
    if (isset($_POST['url_forwarding']) && $_POST['url_forwarding'] == 'yes') {
        if (!isset($_POST['forward_url_scheme']) || isset($_POST['forward_url'])) {
            showBadRequestErrorPage();
        }
        $forwardUrl = clean_input($_POST['forward_url_scheme']) . clean_input($_POST['forward_url']);
        try {
            try {
                $uri = iMSCP_Uri_Redirect::fromString($forwardUrl);
            } catch (Zend_Uri_Exception $e) {
                throw new iMSCP_Exception(tr('Forward URL %s is not valid.', "<strong>{$forwardUrl}</strong>"));
            }
            $uri->setHost(encode_idna($uri->getHost()));
            if ($uri->getHost() == $domainAliasNameAscii && $uri->getPath() == '/') {
                throw new iMSCP_Exception(tr('Forward URL %s is not valid.', "<strong>{$forwardUrl}</strong>") . ' ' . tr('Domain alias %s cannot be forwarded on itself.', "<strong>{$domainAliasName}</strong>"));
            }
            $forwardUrl = $uri->getUri();
        } catch (Exception $e) {
            set_page_message($e->getMessage(), 'error');
            return false;
        }
    }
    $isSuUser = isset($_SESSION['logged_from_type']);
    # See http://youtrack.i-mscp.net/issue/IP-1486
    $userEmail = isset($_SESSION['user_email']) ? $_SESSION['user_email'] : '';
    $db = iMSCP_Database::getInstance();
    try {
        $db->beginTransaction();
        iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddDomainAlias, array('domainId' => $mainDmnProps['domain_id'], 'domainAliasName' => $domainAliasNameAscii));
        exec_query('
                INSERT INTO domain_aliasses (
                    domain_id, alias_name, alias_mount, alias_status, alias_ip_id, url_forward
                ) VALUES (
                    ?, ?, ?, ?, ?, ?
                )
            ', array($mainDmnProps['domain_id'], $domainAliasNameAscii, $mountPoint, $isSuUser ? 'toadd' : 'ordered', $mainDmnProps['domain_ip_id'], $forwardUrl));
        $id = $db->insertId();
        // Create the phpini entry for that domain alias
        $phpini = iMSCP_PHPini::getInstance();
        $phpini->loadResellerPermissions($_SESSION['user_created_by']);
        // Load reseller PHP permissions
        $phpini->loadClientPermissions($_SESSION['user_id']);
        // Load client PHP permissions
        $phpini->loadDomainIni($_SESSION['user_id'], $mainDmnProps['domain_id'], 'dmn');
        // Load main domain PHP configuration options
        $phpini->saveDomainIni($_SESSION['user_id'], $id, 'als');
        if ($isSuUser) {
            $cfg = iMSCP_Registry::get('config');
            if ($cfg['CREATE_DEFAULT_EMAIL_ADDRESSES'] && $userEmail !== '') {
                client_mail_add_default_accounts($mainDmnProps['domain_id'], $userEmail, $domainAliasNameAscii, 'alias', $id);
            }
        }
        $db->commit();
        iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddDomainAlias, array('domainId' => $mainDmnProps['domain_id'], 'domainAliasName' => $domainAliasNameAscii, 'domainAliasId' => $id));
        if ($isSuUser) {
            send_request();
            write_log(sprintf('A new `%s` domain alias has been created by: %s', $domainAliasName, $_SESSION['user_logged']), E_USER_NOTICE);
            set_page_message(tr('Domain alias successfully created.'), 'success');
        } else {
            send_alias_order_email($domainAliasName);
            write_log(sprintf('A new `%s` domain alias has been ordered by: %s', $domainAliasName, decode_idna($_SESSION['user_logged'])), E_USER_NOTICE);
            set_page_message(tr('Domain alias successfully ordered.'), 'success');
        }
    } catch (iMSCP_Exception_Database $e) {
        $db->rollBack();
        write_log(sprintf('System was unable to create the `%s` domain alias: %s', $domainAliasName, $e->getMessage()), E_USER_ERROR);
        set_page_message(tr('Could not create domain alias. An unexpected error occurred.'), 'error');
        return false;
    }
    return true;
}
Exemple #30
0
/**
 * @global <type> $validation_err_msg
 * @param $err_sub
 * @param int $user_id
 * @param $dmn_name
 * @return void <type>
 */
function check_subdomain_data(&$err_sub, $user_id, $dmn_name)
{
    global $validation_err_msg;
    $cfg = EasySCP_Registry::get('Config');
    $sql = EasySCP_Registry::get('Db');
    //	$vfs = new EasySCP_VirtualFileSystem($dmn_name, $sql);
    $dmn_id = $domain_id = get_user_domain_id($user_id);
    if (isset($_POST['uaction']) && $_POST['uaction'] === 'add_subd') {
        if (empty($_POST['subdomain_name'])) {
            $err_sub = tr('Please specify subdomain name!');
            return;
        }
        $sub_name = strtolower($_POST['subdomain_name']);
        if ($_POST['status'] == 1) {
            $forward = clean_input($_POST['forward']);
            $forward_prefix = clean_input($_POST['forward_prefix']);
        } else {
            $forward = 'no';
            $forward_prefix = '';
        }
        // Should be perfomed after domain names syntax validation now
        //$sub_name = encode_idna($sub_name);
        if (isset($_POST['subdomain_mnt_pt']) && $_POST['subdomain_mnt_pt'] !== '') {
            $sub_mnt_pt = array_encode_idna(strtolower($_POST['subdomain_mnt_pt']), true);
        } else {
            $sub_mnt_pt = "/";
        }
        if ($_POST['dmn_type'] === 'als') {
            if (!isset($_POST['als_id'])) {
                $err_sub = tr('No valid alias domain selected!');
                return;
            }
            //			$query_alias = "
            //				SELECT
            //					`alias_mount`
            //				FROM
            //					`domain_aliasses`
            //				WHERE
            //					`alias_id` = ?
            //			;";
            //
            //			$rs = exec_query($sql, $query_alias, $_POST['als_id']);
            //
            //			$als_mnt = $rs->fields['alias_mount'];
            $query_dmn = "\n\t\t\t\tSELECT\n\t\t\t\t\tdomain_name\n\t\t\t\tFROM \n\t\t\t\t\tdomain_aliasses,\n\t\t\t\t\tdomain\n\t\t\t\tWHERE\n\t\t\t\t\tdomain_aliasses.domain_id = domain.domain_id\n\t\t\t\tAND\n\t\t\t\t\talias_id = ?\n\t\t\t";
            $dmn_rs = exec_query($sql, $query_dmn, $_POST['als_id']);
            $master_dmn_name = $dmn_rs->fields['domain_name'];
            if ($sub_mnt_pt[0] != '/') {
                $sub_mnt_pt = '/' . $sub_mnt_pt;
            }
            //			$sub_mnt_pt = $als_mnt.$sub_mnt_pt;
            $sub_mnt_pt = str_replace('//', '/', $sub_mnt_pt);
            $domain_id = $_POST['als_id'];
            $sub_mnt_path = $cfg->APACHE_WWW_DIR . '/' . $master_dmn_name . $sub_mnt_pt;
        } else {
            $sub_mnt_path = $cfg->APACHE_WWW_DIR . '/' . $dmn_name . $sub_mnt_pt;
        }
        // First check if input string is a valid domain names
        if (!validates_subdname($sub_name, decode_idna($dmn_name))) {
            $err_sub = $validation_err_msg;
            return;
        }
        // Should be perfomed after domain names syntax validation now
        $sub_name = encode_idna($sub_name);
        if (subdmn_exists($user_id, $domain_id, $sub_name)) {
            $err_sub = tr('Subdomain already exists or is not allowed!');
        } elseif ($_POST['dmn_type'] != 'als' && mount_point_exists($dmn_id, array_encode_idna($sub_mnt_pt, true))) {
            $err_sub = tr('Mount point already in use!');
        } elseif ($_POST['dmn_type'] != 'als' && send_request('160 SYSTEM direxists ' . array_encode_idna($sub_mnt_path, true))) {
            $err_sub = tr("Can't use an existing folder as mount point!");
            //		}elseif ($vfs->exists($sub_mnt_pt)) {
            //			$err_sub = tr("Can't use an existing folder as mount point!");
        } elseif ($_POST['dmn_type'] != 'als' && !validates_mpoint($sub_mnt_pt)) {
            $err_sub = tr('Incorrect mount point syntax!');
        } elseif ($_POST['status'] == 1) {
            $surl = @parse_url($forward_prefix . decode_idna($forward));
            if ($surl === false) {
                $err_sub = tr('Wrong domain part in forward URL!');
            } else {
                $domain = $surl['host'];
                if (substr_count($domain, '.') <= 2) {
                    $ret = validates_dname($domain);
                } else {
                    $ret = validates_dname($domain, true);
                }
                if (!$ret) {
                    $err_sub = tr('Wrong domain part in forward URL!');
                } else {
                    $domain = encode_idna($surl['host']);
                    $forward = $surl['scheme'] . '://';
                    if (isset($surl['user'])) {
                        $forward .= $surl['user'] . (isset($surl['pass']) ? ':' . $surl['pass'] : '') . '@';
                    }
                    $forward .= $domain;
                    if (isset($surl['port'])) {
                        $forward .= ':' . $surl['port'];
                    }
                    if (isset($surl['path'])) {
                        $forward .= $surl['path'];
                    } else {
                        $forward .= '/';
                    }
                    if (isset($surl['query'])) {
                        $forward .= '?' . $surl['query'];
                    }
                    if (isset($surl['fragment'])) {
                        $forward .= '#' . $surl['fragment'];
                    }
                }
            }
        } else {
            // now let's fix the mountpoint
            $sub_mnt_pt = array_encode_idna($sub_mnt_pt, true);
        }
        if ('_off_' !== $err_sub) {
            return;
        }
        $subdomain_id = $_POST['subdmn_id'];
        subdomain_schedule($user_id, $domain_id, $sub_name, $sub_mnt_pt, $forward, $subdomain_id);
        set_page_message(tr('Subdomain scheduled for addition!'), 'success');
        user_goto('domains_manage.php');
    }
}