Ejemplo n.º 1
0
 /**
  * Initialize feedback, sets feedback_id from UUID value
  * This value can be provided via the url or a cookie and
  * will be stored in a session
  *
  * If no valid feedback code is found in the request string, the cookie
  * or in the session (also a cookie) then return false
  *
  * @return	integer		feeback_id
  */
 private function _init()
 {
     $request = Zend_Controller_Front::getInstance()->getRequest();
     $conference = Zend_Registry::get('conference');
     $sessionNs = $conference['abbreviation'] . '_feedback';
     // check if feedback deadline has passed
     if (isset($conference['feedback_end'])) {
         if (Zend_Date::now()->isLater($conference['feedback_end'])) {
             return false;
         }
     }
     // check if session is set
     if (Zend_Session::namespaceIsset($sessionNs)) {
         $session = new Zend_Session_Namespace($sessionNs, true);
         return $this->_feedback_id = $session->feedback_id;
     }
     // for uuid parameter, first try Request value, if not available use Cookie value
     $uuid = $request->getParam('uuid', $request->getCookie('feedback_code'));
     // use parameter to set session and cookie
     if ($uuid) {
         if ($feedback = $this->getFeedbackByUuid($uuid)) {
             $session = new Zend_Session_Namespace($sessionNs, true);
             // cookie expires in 14 days
             if ($request->getParam('uuid')) {
                 // only set cookie if it is not already set
                 setcookie('feedback_code', $uuid, time() + 14 * 3600 * 24, '/', $conference['hostname']);
             }
             return $this->_feedback_id = $session->feedback_id = (int) $feedback->code_id;
         }
     }
     // If no UUID is found in Request, Cookie or Session then return
     return false;
 }
Ejemplo n.º 2
0
 /**
  * function that checks if a user session is set
  * @author lekha
  * @date 3/22/2012
  * 
  */
 public function isLoggedIn()
 {
     if (Zend_Session::namespaceIsset('UserSession')) {
         return 1;
     } else {
         return 0;
     }
 }
 function isLoggedin()
 {
     foreach (array('user', 'advertiser', 'administrator') as $person) {
         if (Zend_Session::namespaceIsset($person)) {
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 4
0
 public function preDispatch()
 {
     $controller = $this->getRequest()->getControllerName();
     $action = $this->getRequest()->getActionName();
     $authNamespace = new Zend_Session_Namespace('Zend_Auth');
     // print_r($controller);die;
     if ($this->filter($controller, $action)) {
         if (!Zend_Auth::getInstance()->hasIdentity()) {
             $config = Zend_Registry::get('config');
             $lang = $this->_request->getParam('lang');
             if (isset($lang) && $lang != null) {
                 $langNamespace = new Zend_Session_Namespace('Lang');
                 $langNamespace->lang = $lang;
             }
             if (substr($action, 0, 5) == 'admin') {
                 $this->_redirector = $this->_helper->getHelper('Redirector');
                 $this->_redirector->gotoUrl('/admin?url=' . $this->getRequest()->getPathInfo());
             } else {
                 if (substr($action, 0, 6) == 'client') {
                     $this->_helper->redirector('login', 'client');
                 } else {
                     $this->_redirector = $this->_helper->getHelper('Redirector');
                     $this->_redirector->gotoUrl('/index/index?url=' . $this->getRequest()->getPathInfo());
                 }
             }
         } else {
             //2011-04-08 ham.bao separate the sessions with admin
             if (substr($action, 0, 5) == 'admin' && $this->_currentAdmin->getTableClass() != 'Admin') {
                 //$this->_helper->redirector('login','admin');
                 $this->_redirector = $this->_helper->getHelper('Redirector');
                 $this->_redirector->gotoUrl('/admin?url=' . $this->getRequest()->getPathInfo());
             } else {
                 if (substr($action, 0, 6) == 'client') {
                     //$this->_helper->redirector('login','client');
                     //2011-04-08 ham.bao separate the sessions with client
                     //if ($this->_currentUser->getTableClass() != 'Client'){
                     if ($this->_currentClient->getTableClass() != 'Client') {
                         $this->_redirector = $this->_helper->getHelper('Redirector');
                         $this->_redirector->gotoUrl('/client?url=' . $this->getRequest()->getPathInfo());
                     } else {
                         //check client new message count
                         if (Zend_Session::namespaceIsset("ClientMessage")) {
                             $namespace = new Zend_Session_Namespace('ClientMessage');
                             $attrName = "count_" . $this->_currentUser->id;
                             if ($namespace->{$attrName} > 0) {
                                 $this->view->client_message_count = "(" . $namespace->{$attrName} . ")";
                             }
                         }
                     }
                 }
             }
         }
     }
 }
 function getPerson()
 {
     Zend_Session::start();
     $person = 'visitor';
     foreach (Site::getPersons() as $who) {
         if (Zend_Session::namespaceIsset($who)) {
             $session = new Zend_Session_Namespace($who);
             if ($session->{$who} != null) {
                 $person = $who;
                 break;
             }
         }
     }
     return $person;
 }
Ejemplo n.º 6
0
 /**
  *
  */
 public function init()
 {
     if (Zend_Session::isStarted() && Zend_Session::namespaceIsset('SwIRS_Web')) {
         $session = Zend_Session::namespaceGet('SwIRS_Web');
         $this->getRequest()->setParam('CustomerState', $session['customerState']);
         $this->getRequest()->setParam('CustomerUserId', $session['customerUserId']);
         $this->getRequest()->setParam('CustomerAccountId', $session['customerAccountId']);
         $this->getRequest()->setParam('SecondaryCustomerAccountId', $session['secondaryCustomerAccountId']);
         $this->getRequest()->setParam('Profile', $session['profile']);
         $webservice = $this->getResource('webservice');
         $webservice->setAuth(array('user' => $session['username'], 'password' => $session['password']));
     }
     $front = $this->getResource('FrontController');
     $front->setRequest($this->getRequest());
 }
Ejemplo n.º 7
0
/**
 * Generates the page messages to display on client browser
 *
 * Note: The default level for message is sets to 'info'.
 * See the {@link set_page_message()} function for more information.
 *
 * @param  iMSCP_pTemplate $tpl iMSCP_pTemplate instance
 * @return void
 */
function generatePageMessage($tpl)
{
    $namespace = new Zend_Session_Namespace('pageMessages');
    if (Zend_Session::namespaceIsset('pageMessages')) {
        foreach (array('success', 'error', 'warning', 'info', 'static_success', 'static_error', 'static_warning', 'static_info') as $level) {
            if (isset($namespace->{$level})) {
                $tpl->assign(array('MESSAGE_CLS' => $level, 'MESSAGE' => $namespace->{$level}));
                $tpl->parse('PAGE_MESSAGE', '.page_message');
            }
        }
        Zend_Session::namespaceUnset('pageMessages');
    } else {
        $tpl->assign('PAGE_MESSAGE', '');
    }
}
Ejemplo n.º 8
0
 public function switchBackAction()
 {
     $auth = Zend_Auth::getInstance();
     if ($auth->hasIdentity()) {
         $session = new Zend_Session_Namespace('superadmin');
         if (!isset($session->identity)) {
             $session = new Zend_Session_Namespace('groupadmin');
         }
         if (Zend_Session::namespaceIsset('superadmin')) {
             if (isset($session->identity)) {
                 $auth->getStorage()->write(unserialize($session->identity));
                 Zend_Session::namespaceUnset('superadmin');
                 $this->_redirect('/admin/list-organisation');
             } else {
                 $this->_redirect('/wep/dashboard');
             }
         } elseif (Zend_Session::namespaceIsset('groupadmin')) {
             if (isset($session->identity)) {
                 $auth->getStorage()->write(unserialize($session->identity));
                 Zend_Session::namespaceUnset('groupadmin');
                 $this->_redirect('/group/list-organisation');
             } else {
                 $this->_redirect('/group/dashboard');
             }
         } else {
             $this->_redirect('/wep/dashboard');
         }
     }
 }
Ejemplo n.º 9
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;
}
Ejemplo n.º 10
0
 function thankyouAction()
 {
     $adminAddSession = Zend_Session::namespaceGet("adminAddSession");
     $id = (int) $this->_request->getParam('survey', 0);
     $currentTime = date("Y-m-d H:i:s");
     $code = $this->_request->getParam('c');
     if (isset($adminAddSession['consumer'])) {
         $consumer_id = $adminAddSession['consumer'];
     } else {
         $consumer = $this->_currentUser;
         $consumer_id = $consumer->id;
         // $id = 266;
         if ($consumer->getTableClass() == 'Admin') {
             // if admin get report from session (sms report)
             if (Zend_Session::namespaceIsset("AgentReports")) {
                 $session = Zend_Session::namespaceGet("AgentReports");
                 if (isset($session[$code]) && $session[$code] != null) {
                     $consumer_id = $session[$code];
                     $session[$code] = null;
                     // delete this accesscode
                     $this->view->adminredirect = true;
                     // for admin redirect
                 }
             }
         }
     }
     $reportModel = new Report();
     $duplicatedReport = $reportModel->fetchAll('report.accesscode = "' . $code . '"');
     $campaignModel = new Campaign();
     $campaign = $campaignModel->fetchRow("i2_survey_id =" . $id . " or " . "i2_survey_id_en =" . $id);
     //create a record in report table
     if (count($duplicatedReport) == 0) {
         $report = $reportModel->createRow();
         $report->consumer_id = $consumer_id;
         $report->campaign_id = $campaign->id;
         $report->create_date = $currentTime;
         $session = Zend_Session::namespaceGet("AgentReports");
         if (isset($session[$code]) && $session[$code] != null) {
             $report->source = $session[$code . '_source'];
             $session[$code . '_source'] = null;
         }
         //ham.bao 2011/04/29 admin add the report
         $adminAddSession = Zend_Session::namespaceGet("adminAddSession");
         if (isset($adminAddSession['consumer'])) {
             $this->view->adminredirect = true;
             $report->source = $adminAddSession['source'];
             $report->consumer_id = $adminAddSession['consumer'];
             $report->campaign_id = $adminAddSession['campaign'];
         }
         $report->state = 'NEW';
         $report->accesscode = $code;
         $reportId = $report->save();
         $this->view->reportId = $reportId;
         if ($this->view->adminredirect) {
             //ham.bao 2010-10-13 update the incoming_email state
             if (Zend_Session::namespaceIsset("IncomingEmail")) {
                 $emailSession = new Zend_Session_Namespace('IncomingEmail');
                 $incomingEmailModel = new IncomingEmail();
                 $incomingEmailModel->update(array('report_id' => $reportId), 'id=' . $emailSession->id);
                 $this->_helper->redirector('successconvert', 'email');
             }
             //ham.bao 2011/04/29 admin add the report
             if (isset($adminAddSession['consumer'])) {
                 $this->_helper->redirector('successconvert', 'email');
             }
         }
         //change state in campaign_particpation table
         //			$invitationModel = new CampaignInvitation();
         //			$invitation = $invitationModel->fetchRow("campaign_id =".$campaign->id." and consumer_id=".$consumer->id);
         //
         //			$participationModel = new CampaignParticipation();
         //			$participation = $participationModel->fetchRow('campaign_invitation_id = '.$invitation->id);
         //			$participation->state = 'REPORT SUBMITTED';
         //			$participation->save();
     } else {
         $this->view->reportId = $duplicatedReport[0]['id'];
     }
     $option = array($this->view->reportId, $consumer_id);
     $form = new ReportForm($option);
     $this->view->form = $form;
     if ($this->_request->isPost()) {
         $image = $form->getValue('image');
         if ($image != '') {
             $reportImage = new ReportImages();
             $row = $reportImage->createRow();
             $row->name = $image;
             $row->consumer = $consumer_id;
             $row->report = $this->view->reportId;
             $row->crdate = date('Y-m-d H:i:s');
             $row->save();
             $this->view->saved = 1;
         } else {
             $this->view->saved = -1;
         }
         //var_dump($image);die;
     }
     $this->view->consumer = $consumer_id;
     $this->view->title = $this->view->title = $this->view->translate("Wildfire") . " - " . $this->view->translate("Thanks_For_report");
 }
Ejemplo n.º 11
0
/**
 * Check input data
 *
 * @return bool TRUE if data are valid, FALSE otherwise
 */
function checkInputData()
{
    global $name, $description, $sub, $als, $mail, $mailQuota, $ftp, $sqld, $sqlu, $traffic, $diskSpace, $php, $cgi, $dns, $backup, $aps, $extMail, $webFolderProtection, $status;
    $name = isset($_POST['name']) ? clean_input($_POST['name']) : $name;
    $description = isset($_POST['description']) ? clean_input($_POST['description']) : $description;
    $sub = isset($_POST['sub']) ? clean_input($_POST['sub']) : $sub;
    $als = isset($_POST['als']) ? clean_input($_POST['als']) : $als;
    $mail = isset($_POST['mail']) ? clean_input($_POST['mail']) : $mail;
    $mailQuota = isset($_POST['mail_quota']) ? clean_input($_POST['mail_quota']) : $mailQuota;
    $ftp = isset($_POST['ftp']) ? clean_input($_POST['ftp']) : $ftp;
    $sqld = isset($_POST['sql_db']) ? clean_input($_POST['sql_db']) : $sqld;
    $sqlu = isset($_POST['sql_user']) ? clean_input($_POST['sql_user']) : $sqlu;
    $traffic = isset($_POST['traff']) ? clean_input($_POST['traff']) : $traffic;
    $diskSpace = isset($_POST['disk']) ? clean_input($_POST['disk']) : $diskSpace;
    $php = isset($_POST['php']) ? clean_input($_POST['php']) : $php;
    $cgi = isset($_POST['cgi']) ? clean_input($_POST['cgi']) : $cgi;
    $dns = isset($_POST['dns']) ? clean_input($_POST['dns']) : $dns;
    $backup = isset($_POST['backup']) && is_array($_POST['backup']) ? $_POST['backup'] : $backup;
    $aps = isset($_POST['softwares_installer']) ? clean_input($_POST['softwares_installer']) : $aps;
    $extMail = isset($_POST['external_mail']) ? clean_input($_POST['external_mail']) : $extMail;
    $webFolderProtection = isset($_POST['protected_webfolders']) ? clean_input($_POST['protected_webfolders']) : $webFolderProtection;
    $status = isset($_POST['status']) ? clean_input($_POST['status']) : $status;
    $php = $php === '_yes_' ? '_yes_' : '_no_';
    $cgi = $cgi === '_yes_' ? '_yes_' : '_no_';
    $dns = resellerHasFeature('custom_dns_records') && $dns === '_yes_' ? '_yes_' : '_no_';
    $backup = resellerHasFeature('backup') ? array_intersect($backup, array('_dmn_', '_sql_', '_mail_')) : array();
    $aps = resellerHasFeature('aps') && $aps === '_yes_' ? '_yes_' : '_no_';
    $extMail = $extMail === '_yes_' ? '_yes_' : '_no_';
    $webFolderProtection = $webFolderProtection === '_yes_' ? '_yes_' : '_no_';
    $errFieldsStack = array();
    if ($aps == '_yes_') {
        // Ensure that PHP is enabled when software installer is enabled
        $php = '_yes_';
    }
    if ($name === '') {
        set_page_message(tr('Name cannot be empty.'), 'error');
        $errFieldsStack[] = 'name';
    }
    if ($description === '') {
        set_page_message(tr('Description cannot be empty.'), 'error');
        $errFieldsStack[] = 'description';
    }
    if (!resellerHasFeature('subdomains')) {
        $sub = '-1';
    } elseif (!imscp_limit_check($sub, -1)) {
        set_page_message(tr('Incorrect subdomain limit.'), 'error');
        $errFieldsStack[] = 'sub';
    }
    if (!resellerHasFeature('domain_aliases')) {
        $als = '-1';
    } elseif (!imscp_limit_check($als, -1)) {
        set_page_message(tr('Incorrect domain alias limit.'), 'error');
        $errFieldsStack[] = 'als';
    }
    if (!resellerHasFeature('mail')) {
        $mail = '-1';
    } elseif (!imscp_limit_check($mail, -1)) {
        set_page_message(tr('Incorrect email account limit.'), 'error');
        $errFieldsStack[] = 'mail';
    }
    if (!resellerHasFeature('ftp')) {
        $ftp = '-1';
    } elseif (!imscp_limit_check($ftp, -1)) {
        set_page_message(tr('Incorrect FTP account limit.'), 'error');
        $errFieldsStack[] = 'ftp';
    }
    if (!resellerHasFeature('sql_db')) {
        $sqld = '-1';
    } elseif (!imscp_limit_check($sqld, -1)) {
        set_page_message(tr('Incorrect SQL database limit.'), 'error');
        $errFieldsStack[] = 'sql_db';
    } elseif ($sqlu != -1 && $sqld == -1) {
        set_page_message(tr('SQL user limit is <i>disabled</i>.'), 'error');
        $errFieldsStack[] = 'sql_db';
        $errFieldsStack[] = 'sql_user';
    }
    if (!resellerHasFeature('sql_user')) {
        $sqlu = '-1';
    } elseif (!imscp_limit_check($sqlu, -1)) {
        set_page_message(tr('Incorrect SQL user limit.'), 'error');
        $errFieldsStack[] = 'sql_user';
    } elseif ($sqlu == -1 && $sqld != -1) {
        set_page_message(tr('SQL database limit is not <i>disabled</i>.'), 'error');
        $errFieldsStack[] = 'sql_user';
        $errFieldsStack[] = 'sql_db';
    }
    if (!imscp_limit_check($traffic, null)) {
        set_page_message(tr('Incorrect monthly traffic limit.'), 'error');
        $errFieldsStack[] = 'traff';
    }
    if (!imscp_limit_check($diskSpace, null)) {
        set_page_message(tr('Incorrect disk space limit.'), 'error');
        $errFieldsStack[] = 'disk';
    }
    if (!imscp_limit_check($mailQuota, null)) {
        set_page_message(tr('Wrong syntax for the mail quota value.'), 'error');
        $errFieldsStack[] = 'mail_quota';
    } elseif ($diskSpace != 0 && $mailQuota > $diskSpace) {
        set_page_message(tr('Email quota cannot be bigger than disk space limit.'), 'error');
        $errFieldsStack[] = 'mail_quota';
    } elseif ($diskSpace != 0 && $mailQuota == 0) {
        set_page_message(tr('Email quota cannot be unlimited. Max value is %d MiB.', $diskSpace), 'error');
        $errFieldsStack[] = 'mail_quota';
    }
    $phpini = iMSCP_PHPini::getInstance();
    if (isset($_POST['php_ini_system']) && $php != '_no_' && $phpini->resellerHasPermission('phpiniSystem')) {
        $phpini->setClientPermission('phpiniSystem', clean_input($_POST['php_ini_system']));
        if ($phpini->clientHasPermission('phpiniSystem')) {
            if (isset($_POST['phpini_perm_allow_url_fopen'])) {
                $phpini->setClientPermission('phpiniAllowUrlFopen', clean_input($_POST['phpini_perm_allow_url_fopen']));
            }
            if (isset($_POST['phpini_perm_display_errors'])) {
                $phpini->setClientPermission('phpiniDisplayErrors', clean_input($_POST['phpini_perm_display_errors']));
            }
            if (isset($_POST['phpini_perm_disable_functions'])) {
                $phpini->setClientPermission('phpiniDisableFunctions', clean_input($_POST['phpini_perm_disable_functions']));
            }
            if (isset($_POST['phpini_perm_mail_function'])) {
                $phpini->setClientPermission('phpiniMailFunction', clean_input($_POST['phpini_perm_mail_function']));
            }
            if (isset($_POST['memory_limit'])) {
                // Must be set before phpiniPostMaxSize
                $phpini->setDomainIni('phpiniMemoryLimit', clean_input($_POST['memory_limit']));
            }
            if (isset($_POST['post_max_size'])) {
                // Must be set before phpiniUploadMaxFileSize
                $phpini->setDomainIni('phpiniPostMaxSize', clean_input($_POST['post_max_size']));
            }
            if (isset($_POST['upload_max_filesize'])) {
                $phpini->setDomainIni('phpiniUploadMaxFileSize', clean_input($_POST['upload_max_filesize']));
            }
            if (isset($_POST['max_execution_time'])) {
                $phpini->setDomainIni('phpiniMaxExecutionTime', clean_input($_POST['max_execution_time']));
            }
            if (isset($_POST['max_input_time'])) {
                $phpini->setDomainIni('phpiniMaxInputTime', clean_input($_POST['max_input_time']));
            }
        } else {
            $phpini->loadClientPermissions();
            // Reset client PHP permissions to default values
            $phpini->loadDomainIni();
            // Reset domain PHP configuration options to default values
        }
    } else {
        $phpini->loadClientPermissions();
        // Reset client PHP permissions to default values
        $phpini->loadDomainIni();
        // Reset domain PHP configuration options to default values
    }
    if (!Zend_Session::namespaceIsset('pageMessages')) {
        return true;
    }
    if (!empty($errFieldsStack)) {
        iMSCP_Registry::set('errFieldsStack', $errFieldsStack);
    }
    return false;
}
Ejemplo n.º 12
0
/**
 * Validates a service port and sets an appropriate message on error.
 *
 * @param string $name Service name
 * @param string $ip Ip address
 * @param int $port Port
 * @param string $protocol Protocle
 * @param bool $show Tell whether or not service must be show on status page
 * @param string $index Item index on update, empty value otherwise
 * @return bool TRUE if valid, FALSE otherwise
 */
function admin_validatesService($name, $ip, $port, $protocol, $show, $index = '')
{
    /** @var $dbConfig iMSCP_Config_Handler_Db */
    $dbConfig = iMSCP_Registry::get('dbConfig');
    // Get a reference to the array that contain all error fields ids
    $errorFieldsIds =& iMSCP_Registry::get('errorFieldsIds');
    $dbServiceName = "PORT_{$name}";
    $ip = $ip == 'localhost' ? '127.0.0.1' : $ip;
    // Check for service name syntax
    if (!is_basicString($name)) {
        set_page_message(tr("Error with '{$name}': Only letters, numbers, dash and underscore are allowed for services names."), 'error');
        $errorFieldsIds[] = "name{$index}";
    }
    // Check for IP syntax
    if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
        set_page_message(tr(' Wrong IP address.'), 'error');
        $errorFieldsIds[] = "ip{$index}";
    }
    // Check for port syntax
    if (!is_number($port) || $port < 1 || $port > 65535) {
        set_page_message(tr('Only numbers in range from 0 to 65535 are allowed.'), 'error');
        $errorFieldsIds[] = "port{$index}";
    }
    // Check for service port existences
    if (!is_int($index) && isset($dbConfig[$dbServiceName])) {
        set_page_message(tr('Service name already exists.'), 'error');
        $errorFieldsIds[] = "name{$index}";
    }
    // Check for protocol and show option
    if ($protocol != 'tcp' && $protocol != 'udp' || $show != '0' && $show != '1') {
        showBadRequestErrorPage();
    }
    return Zend_Session::namespaceIsset('pageMessages') ? false : true;
}
Ejemplo n.º 13
0
 /**
  * Delete
  *
  * @param  array $params Request data
  * @access public
  * @return mixed Result of dao execution
  */
 public function delete(array $params)
 {
     if ($this->_before(__FUNCTION__) === false) {
         return false;
     }
     $this->setRules('deleteRules', $params);
     if ($this->isValid($params) === false) {
         return false;
     }
     $ret = $this->_delete($params);
     if ($ret === false) {
         $this->setMessages($this->_apptranslate->_('Fail to update.'));
         return false;
     }
     if ($this->_after(__FUNCTION__) === false) {
         return false;
     }
     $namespace = $this->_session->getNamespace();
     if (Zend_Session::namespaceIsset($namespace) === true) {
         $this->_session->remove($namespace);
     }
     return $ret;
 }
Ejemplo n.º 14
0
/**
 * Check and updates reseller data
 *
 * @throws iMSCP_Exception_Database
 * @param int $resellerId Reseller unique identifier
 * @return bool TRUE on success, FALSE otherwise
 */
function admin_checkAndUpdateData($resellerId)
{
    iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditUser, array('userId' => $resellerId));
    $errFieldsStack = array();
    $data =& admin_getData($resellerId, true);
    $db = iMSCP_Database::getInstance();
    try {
        $db->beginTransaction();
        // check for password (if needed)
        if ($data['password'] !== '' && $data['pasword_confirmation'] !== '') {
            if ($data['password'] !== $data['password_confirmation']) {
                set_page_message(tr('Passwords do not match.'), 'error');
            }
            checkPasswordSyntax($data['password']);
            if (Zend_Session::namespaceIsset('pageMessages')) {
                $errFieldsStack[] = 'password';
                $errFieldsStack[] = 'password_confirmation';
            }
        }
        // Check for email address
        if (!chk_email($data['email'])) {
            set_page_message(tr('Incorrect syntax for email address.'), 'error');
            $errFieldsStack[] = 'email';
        }
        // Check for ip addresses
        $resellerIps = array();
        foreach ($data['server_ips'] as $serverIpData) {
            if (in_array($serverIpData['ip_id'], $data['reseller_ips'], true)) {
                $resellerIps[] = $serverIpData['ip_id'];
            }
        }
        $resellerIps = array_unique(array_merge($resellerIps, $data['used_ips']));
        sort($resellerIps);
        if (empty($resellerIps)) {
            set_page_message(tr('You must assign at least one IP to this reseller.'), 'error');
        }
        // Check for max domains limit
        if (imscp_limit_check($data['max_dmn_cnt'], null)) {
            $rs = admin_checkResellerLimit($data['max_dmn_cnt'], $data['current_dmn_cnt'], $data['nbDomains'], '0', tr('domains'));
        } else {
            set_page_message(tr('Incorrect limit for %s.', tr('domain')), 'error');
            $rs = false;
        }
        if (!$rs) {
            $errFieldsStack[] = 'max_dmn_cnt';
        }
        // Check for max subdomains limit
        if (imscp_limit_check($data['max_sub_cnt'])) {
            $rs = admin_checkResellerLimit($data['max_sub_cnt'], $data['current_sub_cnt'], $data['nbSubdomains'], $data['unlimitedSubdomains'], tr('subdomains'));
        } else {
            set_page_message(tr('Incorrect limit for %s.', tr('subdomains')), 'error');
            $rs = false;
        }
        if (!$rs) {
            $errFieldsStack[] = 'max_sub_cnt';
        }
        // check for max domain aliases limit
        if (imscp_limit_check($data['max_als_cnt'])) {
            $rs = admin_checkResellerLimit($data['max_als_cnt'], $data['current_als_cnt'], $data['nbDomainAliases'], $data['unlimitedDomainAliases'], tr('domain aliases'));
        } else {
            set_page_message(tr('Incorrect limit for %s.', tr('domain aliases')), 'error');
            $rs = false;
        }
        if (!$rs) {
            $errFieldsStack[] = 'max_als_cnt';
        }
        // Check for max mail accounts limit
        if (imscp_limit_check($data['max_mail_cnt'])) {
            $rs = admin_checkResellerLimit($data['max_mail_cnt'], $data['current_mail_cnt'], $data['nbMailAccounts'], $data['unlimitedMailAccounts'], tr('mail'));
        } else {
            set_page_message(tr('Incorrect limit for %s.', tr('email accounts')), 'error');
            $rs = false;
        }
        if (!$rs) {
            $errFieldsStack[] = 'max_mail_cnt';
        }
        // Check for max ftp accounts limit
        if (imscp_limit_check($data['max_ftp_cnt'])) {
            $rs = admin_checkResellerLimit($data['max_ftp_cnt'], $data['current_ftp_cnt'], $data['nbFtpAccounts'], $data['unlimitedFtpAccounts'], tr('Ftp'));
        } else {
            set_page_message(tr('Incorrect limit for %s.', tr('Ftp accounts')), 'error');
            $rs = false;
        }
        if (!$rs) {
            $errFieldsStack[] = 'max_ftp_cnt';
        }
        // Check for max Sql databases limit
        if (!($rs = imscp_limit_check($data['max_sql_db_cnt']))) {
            set_page_message(tr('Incorrect limit for %s.', tr('SQL databases')), 'error');
        } elseif ($data['max_sql_db_cnt'] == -1 && $data['max_sql_user_cnt'] != -1) {
            set_page_message(tr('SQL database limit is disabled but SQL user limit is not.'), 'error');
            $rs = false;
        } else {
            $rs = admin_checkResellerLimit($data['max_sql_db_cnt'], $data['current_sql_db_cnt'], $data['nbSqlDatabases'], $data['unlimitedSqlDatabases'], tr('SQL databases'));
        }
        if (!$rs) {
            $errFieldsStack[] = 'max_sql_db_cnt';
        }
        // Check for max Sql users limit
        if (!($rs = imscp_limit_check($data['max_sql_user_cnt']))) {
            set_page_message(tr('Incorrect limit for %s.', tr('SQL users')), 'error');
        } elseif ($data['max_sql_db_cnt'] != -1 && $data['max_sql_user_cnt'] == -1) {
            set_page_message(tr('SQL user limit is disabled but SQL database limit is not.'), 'error');
            $rs = false;
        } else {
            $rs = admin_checkResellerLimit($data['max_sql_user_cnt'], $data['current_sql_user_cnt'], $data['nbSqlUsers'], $data['unlimitedSqlUsers'], tr('SQL users'));
        }
        if (!$rs) {
            $errFieldsStack[] = 'max_sql_user_cnt';
        }
        // Check for max monthly traffic limit
        if (imscp_limit_check($data['max_traff_amnt'], null)) {
            $rs = admin_checkResellerLimit($data['max_traff_amnt'], $data['current_traff_amnt'], $data['totalTraffic'] / 1048576, $data['unlimitedTraffic'], tr('traffic'));
        } else {
            set_page_message(tr('Incorrect limit for %s.', tr('traffic')), 'error');
            $rs = false;
        }
        if (!$rs) {
            $errFieldsStack[] = 'max_traff_amnt';
        }
        // Check for max disk space limit
        if (imscp_limit_check($data['max_disk_amnt'], null)) {
            $rs = admin_checkResellerLimit($data['max_disk_amnt'], $data['current_disk_amnt'], $data['totalDiskspace'] / 1048576, $data['unlimitedDiskspace'], tr('disk space'));
        } else {
            set_page_message(tr('Incorrect limit for %s.', tr('disk space')), 'error');
            $rs = false;
        }
        if (!$rs) {
            $errFieldsStack[] = 'max_disk_amnt';
        }
        $needDaemonRequest = false;
        // Check for PHP settings
        $phpini = iMSCP_PHPini::getInstance();
        $resellerPhpPermissions = $phpini->getResellerPermission();
        $phpini->setResellerPermission('phpiniSystem', $data['php_ini_system']);
        if ($phpini->resellerHasPermission('phpiniSystem')) {
            // We are safe here; If a value is not valid, previous value is used
            $phpini->setResellerPermission('phpiniDisableFunctions', $data['php_ini_al_disable_functions']);
            $phpini->setResellerPermission('phpiniMailFunction', $data['php_ini_al_mail_function']);
            $phpini->setResellerPermission('phpiniAllowUrlFopen', $data['php_ini_al_allow_url_fopen']);
            $phpini->setResellerPermission('phpiniDisplayErrors', $data['php_ini_al_display_errors']);
            $phpini->setResellerPermission('phpiniMemoryLimit', $data['memory_limit']);
            // Must be set before phpiniPostMaxSize
            $phpini->setResellerPermission('phpiniPostMaxSize', $data['post_max_size']);
            // Must be set before phpiniUploadMaxFileSize
            $phpini->setResellerPermission('phpiniUploadMaxFileSize', $data['upload_max_filesize']);
            $phpini->setResellerPermission('phpiniMaxExecutionTime', $data['max_execution_time']);
            $phpini->setResellerPermission('phpiniMaxInputTime', $data['max_input_time']);
        } else {
            $phpini->loadResellerPermissions();
            // Reset reseller PHP permissions to default values
        }
        if (array_diff_assoc($resellerPhpPermissions, $phpini->getResellerPermission())) {
            // A least one reseller permission has changed. We must synchronize customers permissions
            $phpini->syncClientPermissionsWithResellerPermissions($resellerId);
            $needDaemonRequest = true;
        }
        unset($resellerPhpPermissions);
        if (empty($errFieldsStack) && !Zend_Session::namespaceIsset('pageMessages')) {
            // Update process begin here
            $oldValues = $newValues = array();
            foreach ($data as $property => $value) {
                if (strpos($property, 'fallback_') !== false) {
                    $property = substr($property, 9);
                    $oldValues[$property] = $value;
                    $newValues[$property] = $data[$property];
                }
            }
            // Nothing has been changed ?
            if ($newValues == $oldValues) {
                set_page_message(tr('Nothing has been changed.'), 'info');
                return true;
            }
            // Update reseller personal data (including password if needed)
            $bindParams = array($data['fname'], $data['lname'], $data['gender'], $data['firm'], $data['zip'], $data['city'], $data['state'], $data['country'], $data['email'], $data['phone'], $data['fax'], $data['street1'], $data['street2'], $resellerId);
            if ($data['password'] != '') {
                $setPassword = '******';
                array_unshift($bindParams, cryptPasswordWithSalt($data['password']));
            } else {
                $setPassword = '';
            }
            exec_query("\n                    UPDATE admin SET {$setPassword} fname = ?, lname = ?, gender = ?, firm = ?, zip = ?, city = ?,\n                        state = ?, country = ?, email = ?, phone = ?, fax = ?, street1 = ?, street2 = ?\n                    WHERE admin_id = ?\n            ", $bindParams);
            // Update reseller properties
            exec_query('
                    UPDATE
                        reseller_props
                    SET
                        max_dmn_cnt = ?, max_sub_cnt = ?, max_als_cnt = ?, max_mail_cnt = ?, max_ftp_cnt = ?,
                        max_sql_db_cnt = ?, max_sql_user_cnt = ?, max_traff_amnt = ?, max_disk_amnt = ?,
                        reseller_ips = ?, customer_id = ?, software_allowed = ?, softwaredepot_allowed = ?,
                        websoftwaredepot_allowed = ?, support_system = ?, php_ini_system = ?, php_ini_al_disable_functions = ?, php_ini_al_mail_function = ?,
                        php_ini_al_allow_url_fopen = ?, php_ini_al_display_errors = ?, php_ini_max_post_max_size = ?,
                        php_ini_max_upload_max_filesize = ?, php_ini_max_max_execution_time = ?,
                        php_ini_max_max_input_time = ?, php_ini_max_memory_limit = ?
                    WHERE
                        reseller_id = ?
                ', array($data['max_dmn_cnt'], $data['max_sub_cnt'], $data['max_als_cnt'], $data['max_mail_cnt'], $data['max_ftp_cnt'], $data['max_sql_db_cnt'], $data['max_sql_user_cnt'], $data['max_traff_amnt'], $data['max_disk_amnt'], implode(';', $resellerIps) . ';', $data['customer_id'], $data['software_allowed'], $data['softwaredepot_allowed'], $data['websoftwaredepot_allowed'], $data['support_system'], $phpini->getResellerPermission('phpiniSystem'), $phpini->getResellerPermission('phpiniDisableFunctions'), $phpini->getResellerPermission('phpiniMailFunction'), $phpini->getResellerPermission('phpiniAllowUrlFopen'), $phpini->getResellerPermission('phpiniDisplayErrors'), $phpini->getResellerPermission('phpiniPostMaxSize'), $phpini->getResellerPermission('phpiniUploadMaxFileSize'), $phpini->getResellerPermission('phpiniMaxExecutionTime'), $phpini->getResellerPermission('phpiniMaxInputTime'), $phpini->getResellerPermission('phpiniMemoryLimit'), $resellerId));
            // Updating software installer properties
            if ($data['software_allowed'] == 'no') {
                exec_query('
                        UPDATE domain INNER JOIN admin ON(admin_id = domain_admin_id) SET domain_software_allowed = ?
                        WHERE created_by = ?
                    ', array($data['softwaredepot_allowed'], $resellerId));
            }
            if ($data['websoftwaredepot_allowed'] == 'no') {
                $stmt = exec_query('SELECT software_id FROM web_software WHERE software_depot = ? AND reseller_id = ?', array('yes', $resellerId));
                if ($stmt->rowCount()) {
                    while ($row = $stmt->fetchRow(PDO::FETCH_ASSOC)) {
                        exec_query('UPDATE web_software_inst SET software_res_del = ? WHERE software_id = ?', array('1', $row['software_id']));
                    }
                    exec_query('DELETE FROM web_software WHERE software_depot = ? AND reseller_id = ?', array('yes', $resellerId));
                }
            }
            $db->commit();
            iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditUser, array('userId' => $resellerId));
            // Send mail to reseller for new password
            if ($data['password'] != '') {
                send_add_user_auto_msg($_SESSION['user_id'], $data['admin_name'], $data['password'], $data['email'], $data['fname'], $data['lname'], tr('Reseller'));
            }
            if ($needDaemonRequest) {
                send_request();
            }
            write_log(sprintf('The %s reseller account has been updated by %s', $data['admin_name'], $_SESSION['user_logged']), E_USER_NOTICE);
            set_page_message(tr('Reseller account successfully updated.'), 'success');
            return true;
        }
    } catch (iMSCP_Exception_Database $e) {
        $db->rollBack();
        throw $e;
    }
    if (!empty($errFieldsStack)) {
        iMSCP_Registry::set('errFieldsStack', $errFieldsStack);
    }
    return false;
}
Ejemplo n.º 15
0
 protected function _initLocale()
 {
     if (Zend_Session::namespaceIsset('language') && !isset($_GET['lan'])) {
         $sess = new Zend_Session_Namespace('language');
         $ssLan = $sess->language;
     } else {
         $ssLan = isset($_GET['lan']) ? $_GET['lan'] : 'en';
         $sess = new Zend_Session_Namespace('language');
         $sess->language = $ssLan;
     }
     // define locale
     //$ssLan=(isset($_GET['lan']))?$_GET['lan']:'fr';
     $locale = new Zend_Locale($ssLan);
     // register it so that it can be used all over the website
     Zend_Registry::set('Zend_Locale', $locale);
 }
Ejemplo n.º 16
0
/**
 * Check user data
 *
 * @param  bool $noPass If true skip password check
 * @return bool True if user data are valid, false otherwise
 */
function check_ruser_data($noPass = false)
{
    global $password, $passwordRepeat, $email, $customerId, $firstName, $lastName, $gender, $firm, $street1, $street2, $zip, $city, $state, $country, $phone, $fax, $domainIp;
    // Get data for fields from previous page
    if (isset($_POST['userpassword'])) {
        $password = clean_input($_POST['userpassword']);
    } else {
        $password = '';
    }
    if (isset($_POST['userpassword_repeat'])) {
        $passwordRepeat = clean_input($_POST['userpassword_repeat']);
    } else {
        $passwordRepeat = '';
    }
    if (isset($_POST['useremail'])) {
        $email = clean_input($_POST['useremail']);
    } else {
        $email = '';
    }
    if (isset($_POST['useruid'])) {
        $customerId = clean_input($_POST['useruid']);
    } else {
        $customerId = '';
    }
    if (isset($_POST['userfname'])) {
        $firstName = clean_input($_POST['userfname']);
    } else {
        $firstName = '';
    }
    if (isset($_POST['userlname'])) {
        $lastName = clean_input($_POST['userlname']);
    } else {
        $lastName = '';
    }
    if (isset($_POST['gender']) && get_gender_by_code($_POST['gender'], true) !== null) {
        $gender = $_POST['gender'];
    } else {
        $gender = 'U';
    }
    if (isset($_POST['userfirm'])) {
        $firm = clean_input($_POST['userfirm']);
    } else {
        $firm = '';
    }
    if (isset($_POST['userstreet1'])) {
        $street1 = clean_input($_POST['userstreet1']);
    } else {
        $street1 = '';
    }
    if (isset($_POST['userstreet2'])) {
        $street2 = clean_input($_POST['userstreet2']);
    } else {
        $street2 = '';
    }
    if (isset($_POST['userzip'])) {
        $zip = clean_input($_POST['userzip']);
    } else {
        $zip = '';
    }
    if (isset($_POST['usercity'])) {
        $city = clean_input($_POST['usercity']);
    } else {
        $city = '';
    }
    if (isset($_POST['userstate'])) {
        $state = clean_input($_POST['userstate']);
    } else {
        $state = '';
    }
    if (isset($_POST['usercountry'])) {
        $country = clean_input($_POST['usercountry']);
    } else {
        $country = '';
    }
    if (isset($_POST['userphone'])) {
        $phone = clean_input($_POST['userphone']);
    } else {
        $phone = '';
    }
    if (isset($_POST['userfax'])) {
        $fax = clean_input($_POST['userfax']);
    } else {
        $fax = '';
    }
    if (isset($_POST['domain_ip'])) {
        $domainIp = clean_input($_POST['domain_ip']);
    } else {
        $domainIp = '';
    }
    if (!$noPass) {
        if ('' === $passwordRepeat || '' === $password) {
            set_page_message(tr('Please fill up both data fields for password.'), 'error');
        } elseif ($passwordRepeat !== $password) {
            set_page_message(tr("Passwords do not match."), 'error');
        } else {
            checkPasswordSyntax($password);
        }
    }
    if (!chk_email($email)) {
        set_page_message(tr('Incorrect email length or syntax.'), 'error');
    }
    if ($customerId != '' && strlen($customerId) > 200) {
        set_page_message(tr('Customer ID cannot have more than 200 characters'), 'error');
    }
    if ($firstName != '' && strlen($firstName) > 200) {
        set_page_message(tr('First name cannot have more than 200 characters.'), 'error');
    }
    if ($lastName != '' && strlen($lastName) > 200) {
        set_page_message(tr('Last name cannot have more than 200 characters.'), 'error');
    }
    if ($zip != '' && (strlen($zip) > 200 || is_number(!$zip))) {
        set_page_message(tr('Incorrect post code length or syntax!'), 'error');
    }
    if (Zend_Session::namespaceIsset('pageMessages')) {
        return false;
    }
    return true;
}
Ejemplo n.º 17
0
/**
 * Check if menu is valid.
 *
 * @param string $menuName Menu name
 * @param string $menuLink Menu link
 * @param string $menuTarget Menu target
 * @param string $menuLevel Menu level
 * @param int $menuOrder Menu order
 * @return bool TRUE if menu data are valid, FALSE otherwise
 */
function admin_isValidMenu($menuName, $menuLink, $menuTarget, $menuLevel, $menuOrder)
{
    $errorFieldsStack = array();
    if (empty($menuName)) {
        set_page_message(tr('Invalid name.'), 'error');
        $errorFieldsStack[] = 'menu_name';
    }
    if (empty($menuLink) || !filter_var($menuLink, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED)) {
        set_page_message(tr('Invalid URL.'), 'error');
        $errorFieldsStack[] = 'menu_link';
    }
    if (!empty($menuTarget) && !in_array($menuTarget, array('_blank', '_parent', '_self', '_top'))) {
        set_page_message(tr('Invalid target.'), 'error');
        $errorFieldsStack[] = 'menu_target';
    }
    if (!in_array($menuLevel, array('A', 'R', 'C', 'AR', 'AC', 'RC', 'ARC'))) {
        showBadRequestErrorPage();
    }
    if (!empty($menuOrder) && !is_numeric($menuOrder)) {
        set_page_message(tr('Invalid menu order.'), 'error');
        $errorFieldsStack[] = 'menu_order';
    }
    if (Zend_Session::namespaceIsset('pageMessages')) {
        iMSCP_Registry::set('errorFieldsStack', $errorFieldsStack);
        return false;
    }
    return true;
}
Ejemplo n.º 18
0
 if (!empty($mailIds)) {
     /** @var $db iMSCP_Database */
     $db = iMSCP_Database::getInstance();
     try {
         $db->beginTransaction();
         foreach ($mailIds as $mailId) {
             $mailId = clean_input($mailId);
             client_deleteMailAccount($mailId, $mainDmnProps);
             $nbDeletedMails++;
         }
         $db->commit();
         send_request();
         write_log(sprintf("{$_SESSION['user_logged']} deleted %d mail account(s)", $nbDeletedMails), E_USER_NOTICE);
     } catch (iMSCP_Exception $e) {
         $db->rollBack();
         if (Zend_Session::namespaceIsset('pageMessages')) {
             Zend_Session::namespaceUnset('pageMessages');
         }
         $errorMessage = $e->getMessage();
         $code = $e->getCode();
         write_log(sprintf('An unexpected error occurred while attempting to delete mail account with ID %s: %s', $mailId, $errorMessage), E_USER_ERROR);
         if ($code == 403) {
             set_page_message(tr('Operation canceled: %s', $errorMessage), 'warning');
         } elseif ($e->getCode() == 400) {
             showBadRequestErrorPage();
         } else {
             set_page_message(tr('An unexpected error occurred. Please contact your reseller.'), 'error');
         }
     }
 } else {
     set_page_message(tr('You must select a least one mail account to delete.'), 'error');
Ejemplo n.º 19
0
 /**
  * 名前空間が存在するかチェック
  *
  * @static
  * @access public
  * @param  string $namespace 名前空間名
  */
 public static function namespaceIsset($namespace)
 {
     return parent::namespaceIsset($namespace);
 }
Ejemplo n.º 20
0
/**
 * Checks IP data.
 *
 * @param string $ipNumber IP number
 * @param string $netcard Network card
 * @return bool TRUE if data are valid, FALSE otherwise
 */
function client_checkIpData($ipNumber, $netcard)
{
    /** @var $networkCardObject iMSCP_NetworkCard */
    $networkCardObject = iMSCP_Registry::get('networkCardObject');
    $errFieldsStack = array();
    $query = "SELECT COUNT(IF(`ip_number` = ?, 1, NULL)) `isRegisteredIp` FROM `server_ips`";
    $stmt = exec_query($query, $ipNumber);
    if (filter_var($ipNumber, FILTER_VALIDATE_IP) === false) {
        set_page_message(tr('Wrong IP address.'), 'error');
        $errFieldsStack[] = 'ip_number';
    } elseif ($stmt->fields['isRegisteredIp']) {
        set_page_message(tr('IP address already under the control of i-MSCP.'), 'error');
        $errFieldsStack[] = 'ip_number';
    }
    if (!in_array($netcard, $networkCardObject->getAvailableInterface())) {
        set_page_message(tr('You must select a network interface.'), 'error');
    }
    if (Zend_Session::namespaceIsset('pageMessages')) {
        if (!empty($errFieldsStack)) {
            iMSCP_Registry::set('errFieldsStack', $errFieldsStack);
        }
        return false;
    }
    return true;
}
Ejemplo n.º 21
0
/**
 * Check and updates domain data
 *
 * @throws iMSCP_Exception_Database
 * @param int $domainId Domain unique identifier
 * @return bool TRUE on success, FALSE otherwise
 */
function reseller_checkAndUpdateData($domainId)
{
    $db = iMSCP_Database::getInstance();
    $errFieldsStack = array();
    try {
        // Getting domain data
        $data =& reseller_getData($domainId, true);
        // Check for expires date
        if ($data['domain_never_expires'] == 'off') {
            if (!preg_match('%^\\d{2}/\\d{2}/\\d{4}$%', $data['domain_expires']) || ($timestamp = strtotime($data['domain_expires'])) === false) {
                $data['domain_expires_ok'] = false;
                set_page_message(tr('Wrong syntax for new expire date.'), 'error');
                $errFieldsStack[] = 'domain_expires';
            } elseif ($timestamp != 0 && $timestamp <= time()) {
                $data['domain_expires'] = $timestamp;
                set_page_message(tr('You cannot set expire date in past.'), 'error');
                $errFieldsStack[] = 'domain_expires';
            } else {
                $data['domain_expires'] = $timestamp;
            }
        } else {
            $data['domain_expires'] = 0;
        }
        // Check for the subdomains limit
        if ($data['fallback_domain_subd_limit'] != -1) {
            if (!imscp_limit_check($data['domain_subd_limit'])) {
                set_page_message(tr('Wrong syntax for the %s limit.', tr('subdomains')), 'error');
                $errFieldsStack[] = 'domain_subd_limit';
            } elseif (!_reseller_isValidServiceLimit($data['domain_subd_limit'], $data['nbSubdomains'], $data["fallback_domain_subd_limit"], $data['current_sub_cnt'], $data['max_sub_cnt'], $data['nbSubdomains'] > 1 ? tr('subdomains') : tr('subdomain'))) {
                $errFieldsStack[] = 'domain_subd_limit';
            }
        }
        // Check for the domain aliases limit
        if ($data['fallback_domain_alias_limit'] != -1) {
            if (!imscp_limit_check($data['domain_alias_limit'])) {
                set_page_message(tr('Wrong syntax for the %s limit.', tr('domain aliases')), 'error');
                $errFieldsStack[] = 'domain_alias_limit';
            } elseif (!_reseller_isValidServiceLimit($data['domain_alias_limit'], $data['nbAliasses'], $data["fallback_domain_alias_limit"], $data['current_als_cnt'], $data['max_als_cnt'], $data['nbAliasses'] > 1 ? tr('domain aliases') : tr('domain alias'))) {
                $errFieldsStack[] = 'domain_alias_limit';
            }
        }
        // Check for the mail accounts limit
        if ($data['fallback_domain_mailacc_limit'] != -1) {
            if (!imscp_limit_check($data['domain_mailacc_limit'])) {
                set_page_message(tr('Wrong syntax for the %s limit.', tr('email accounts')), 'error');
                $errFieldsStack[] = 'domain_mailacc_limit';
            } elseif (!_reseller_isValidServiceLimit($data['domain_mailacc_limit'], $data['nbMailAccounts'], $data["fallback_domain_mailacc_limit"], $data['current_mail_cnt'], $data['max_mail_cnt'], $data["nbMailAccounts"] > 1 ? tr('email accounts') : tr('email account'))) {
                $errFieldsStack[] = 'domain_mailacc_limit';
            }
        }
        // Check for the Ftp accounts limit
        if ($data['fallback_domain_ftpacc_limit'] != -1) {
            if (!imscp_limit_check($data['domain_ftpacc_limit'])) {
                set_page_message(tr('Wrong syntax for the %s limit.', tr('Ftp accounts')), 'error');
                $errFieldsStack[] = 'domain_ftpacc_limit';
            } elseif (!_reseller_isValidServiceLimit($data['domain_ftpacc_limit'], $data['nbFtpAccounts'], $data["fallback_domain_ftpacc_limit"], $data['current_ftp_cnt'], $data['max_ftp_cnt'], $data['nbFtpAccounts'] > 1 ? tr('Ftp accounts') : tr('Ftp account'))) {
                $errFieldsStack[] = 'domain_ftpacc_limit';
            }
        }
        // Check for the Sql databases limit
        if ($data['fallback_domain_sqld_limit'] != -1) {
            if (!imscp_limit_check($data['domain_sqld_limit'])) {
                set_page_message(tr('Wrong syntax for the %s limit.', tr('SQL databases')), 'error');
                $errFieldsStack[] = 'domain_sqld_limit';
            } elseif (!_reseller_isValidServiceLimit($data['domain_sqld_limit'], $data['nbSqlDatabases'], $data["fallback_domain_sqld_limit"], $data['current_sql_db_cnt'], $data['max_sql_db_cnt'], $data['nbSqlDatabases'] > 1 ? tr('SQL databases') : tr('SQL database'))) {
                $errFieldsStack[] = 'domain_sqld_limit';
            } elseif ($data['domain_sqld_limit'] != -1 && $data['domain_sqlu_limit'] == -1) {
                set_page_message(tr('SQL user limit is disabled.'), 'error');
                $errFieldsStack[] = 'domain_sqld_limit';
                $errFieldsStack[] = 'domain_sqlu_limit';
            }
        }
        // Check for the Sql users limit
        if ($data['fallback_domain_sqlu_limit'] != -1) {
            if (!imscp_limit_check($data['domain_sqlu_limit'])) {
                set_page_message(tr('Wrong syntax for the %s limit.', tr('SQL users')), 'error');
                $errFieldsStack[] = 'domain_sqlu_limit';
            } elseif (!_reseller_isValidServiceLimit($data['domain_sqlu_limit'], $data['nbSqlUsers'], $data["fallback_domain_sqlu_limit"], $data['current_sql_user_cnt'], $data['max_sql_user_cnt'], $data['nbSqlUsers'] > 1 ? tr('SQL users') : tr('SQL user'))) {
                $errFieldsStack[] = 'domain_sqlu_limit';
            } elseif ($data['domain_sqlu_limit'] != -1 && $data['domain_sqld_limit'] == -1) {
                set_page_message(tr('SQL database limit is disabled.'), 'error');
                $errFieldsStack[] = 'domain_sqlu_limit';
                $errFieldsStack[] = 'domain_sqld_limit';
            }
        }
        // Check for the monthly traffic limit
        if (!imscp_limit_check($data['domain_traffic_limit'], null)) {
            set_page_message(tr('Wrong syntax for the %s limit.', tr('traffic')), 'error');
            $errFieldsStack[] = 'domain_traffic_limit';
        } elseif (!_reseller_isValidServiceLimit($data['domain_traffic_limit'], $data['domainTraffic'] / 1048576, $data["fallback_domain_traffic_limit"], $data['current_traff_amnt'], $data['max_traff_amnt'], tr('traffic'))) {
            $errFieldsStack[] = 'domain_traffic_limit';
        }
        // Check for the disk space limit
        if (!imscp_limit_check($data['domain_disk_limit'], null)) {
            set_page_message(tr('Wrong syntax for the %s limit.', tr('disk space')), 'error');
            $errFieldsStack[] = 'domain_disk_limit';
        } elseif (!_reseller_isValidServiceLimit($data['domain_disk_limit'], $data['domain_disk_usage'] / 1048576, $data["fallback_domain_disk_limit"], $data['current_disk_amnt'], $data['max_disk_amnt'], tr('disk space'))) {
            $errFieldsStack[] = 'domain_disk_limit';
        }
        // Check for mail quota
        if ($data['fallback_domain_mailacc_limit'] != -1) {
            if (!imscp_limit_check($data['mail_quota'], null)) {
                set_page_message(tr('Wrong syntax for the mail quota value.'), 'error');
                $errFieldsStack[] = 'mail_quota';
            } elseif ($data['domain_disk_limit'] != 0 && $data['mail_quota'] > $data['domain_disk_limit']) {
                set_page_message(tr('Email quota cannot be bigger than disk space limit.'), 'error');
                $errFieldsStack[] = 'mail_quota';
            } elseif ($data['domain_disk_limit'] != 0 && $data['mail_quota'] == 0) {
                set_page_message(tr('Email quota cannot be unlimited. Max value is %d MiB.', $data['domain_disk_limit']), 'error');
                $errFieldsStack[] = 'mail_quota';
            } else {
                $mailData = reseller_getMailData($data['domain_id'], $data['fallback_mail_quota']);
                if ($data['mail_quota'] != 0 && $data['mail_quota'] < $mailData['nb_mailboxes']) {
                    set_page_message(tr('Email quota cannot be lower than %d. Each mailbox should have a least 1 MiB quota.', $mailData['nb_mailboxes']), 'error');
                    $errFieldsStack[] = 'mail_quota';
                }
            }
        } else {
            $data['mail_quota'] = 0;
        }
        // Check for PHP support
        $data['domain_php'] = in_array($data['domain_php'], array('no', 'yes')) ? $data['domain_php'] : $data['fallback_domain_php'];
        // PHP editor
        $phpini = iMSCP_PHPini::getInstance();
        // Needed to track changes
        $phpiniClientPerms = $phpini->getClientPermission();
        $phpiniDomainConf = $phpini->getDomainIni();
        if (isset($_POST['php_ini_system']) && $data['domain_php'] == 'yes' && $phpini->resellerHasPermission('phpiniSystem')) {
            $phpini->setClientPermission('phpiniSystem', clean_input($_POST['php_ini_system']));
            if ($phpini->clientHasPermission('phpiniSystem')) {
                if (isset($_POST['phpini_perm_allow_url_fopen'])) {
                    $phpini->setClientPermission('phpiniAllowUrlFopen', clean_input($_POST['phpini_perm_allow_url_fopen']));
                }
                if (isset($_POST['phpini_perm_display_errors'])) {
                    $phpini->setClientPermission('phpiniDisplayErrors', clean_input($_POST['phpini_perm_display_errors']));
                }
                if (isset($_POST['phpini_perm_disable_functions'])) {
                    $phpini->setClientPermission('phpiniDisableFunctions', clean_input($_POST['phpini_perm_disable_functions']));
                }
                if (isset($_POST['phpini_perm_mail_function'])) {
                    $phpini->setClientPermission('phpiniMailFunction', clean_input($_POST['phpini_perm_mail_function']));
                }
                if (isset($_POST['memory_limit'])) {
                    // Must be set before phpiniPostMaxSize
                    $phpini->setDomainIni('phpiniMemoryLimit', clean_input($_POST['memory_limit']));
                }
                if (isset($_POST['post_max_size'])) {
                    // Must be set before phpiniUploadMaxFileSize
                    $phpini->setDomainIni('phpiniPostMaxSize', clean_input($_POST['post_max_size']));
                }
                if (isset($_POST['upload_max_filezize'])) {
                    $phpini->setDomainIni('phpiniUploadMaxFileSize', clean_input($_POST['upload_max_filezize']));
                }
                if (isset($_POST['max_execution_time'])) {
                    $phpini->setDomainIni('phpiniMaxExecutionTime', clean_input($_POST['max_execution_time']));
                }
                if (isset($_POST['max_input_time'])) {
                    $phpini->setDomainIni('phpiniMaxInputTime', clean_input($_POST['max_input_time']));
                }
            } else {
                $phpini->loadClientPermissions();
                // Reset client PHP permissions
                $phpini->loadDomainIni();
                // Reset domain PHP configuration options
            }
        } else {
            $phpini->loadClientPermissions();
            // Reset client PHP permissions
            $phpini->loadDomainIni();
            // Reset domain PHP configuration options
        }
        // Check for CGI support
        $data['domain_cgi'] = in_array($data['domain_cgi'], array('no', 'yes')) ? $data['domain_cgi'] : $data['fallback_domain_cgi'];
        // Check for custom DNS records support
        $data['domain_dns'] = in_array($data['domain_dns'], array('no', 'yes')) ? $data['domain_dns'] : $data['fallback_domain_dns'];
        // Check for APS support
        $data['domain_software_allowed'] = in_array($data['domain_software_allowed'], array('no', 'yes')) ? $data['domain_software_allowed'] : $data['fallback_domain_software_allowed'];
        // Check for External mail server support
        $data['domain_external_mail'] = in_array($data['domain_external_mail'], array('no', 'yes')) ? $data['domain_external_mail'] : $data['fallback_domain_external_mail'];
        // Check for backup support
        $data['allowbackup'] = is_array($data['allowbackup']) ? array_intersect($data['allowbackup'], array('dmn', 'sql', 'mail')) : $data['fallback_allowbackup'];
        // Check for Web folder protection support
        $data['web_folder_protection'] = in_array($data['web_folder_protection'], array('no', 'yes')) ? $data['web_folder_protection'] : $data['fallback_web_folder_protection'];
        if (empty($errFieldsStack) && !Zend_Session::namespaceIsset('pageMessages')) {
            // Update process begin here
            $oldValues = array();
            $newValues = array();
            foreach ($data as $property => $value) {
                if (strpos($property, 'fallback_') !== false) {
                    $property = substr($property, 9);
                    $oldValues[$property] = $value;
                    $newValues[$property] = $data[$property];
                }
            }
            $needDaemonRequest = false;
            if ($newValues == $oldValues && $phpiniClientPerms == $phpini->getClientPermission() && $phpiniDomainConf == $phpini->getDomainIni()) {
                set_page_message(tr('Nothing has been changed.'), 'info');
                return true;
            }
            iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeEditDomain, array('domainId' => $domainId));
            $db->beginTransaction();
            if ($phpiniClientPerms != $phpini->getClientPermission() || $phpiniDomainConf != $phpini->getDomainIni()) {
                $phpini->updateDomainConfigOptions($data['admin_id']);
                $needDaemonRequest = true;
            }
            // PHP or CGI was either enabled or disabled or PHP Settings were changed, web folder protection
            // properties have been updated, or domain IP was changed, so we must update the vhosts files
            // of all domain entities (dmn, sub, als, alssub)
            if ($needDaemonRequest || $data['domain_php'] != $data['fallback_domain_php'] || $data['domain_cgi'] != $data['fallback_domain_cgi'] || $data['web_folder_protection'] != $data['fallback_web_folder_protection'] || $data['domain_ip_id'] != $data['fallback_domain_ip_id']) {
                if ($data['domain_alias_limit'] != '-1') {
                    exec_query('UPDATE domain_aliasses SET alias_status = ? WHERE domain_id = ? AND alias_status <> ?', array('tochange', $domainId, 'ordered'));
                }
                $needDaemonRequest = true;
            }
            if ($data['domain_dns'] != $data['fallback_domain_dns'] && $data['domain_dns'] == 'no') {
                // Support for custom DNS records is now disabled - We must delete all custom DNS entries
                // (except those that are protected), and update the DNS zone file
                exec_query('DELETE FROM domain_dns WHERE domain_id = ? AND owned_by = ?', array($domainId, 'custom_dns_feature'));
                $needDaemonRequest = true;
            }
            // Update domain properties
            exec_query('
                    UPDATE
                        domain
                    SET
                        domain_expires = ?, domain_last_modified = ?, domain_mailacc_limit = ?, domain_ftpacc_limit = ?,
                        domain_traffic_limit = ?, domain_sqld_limit = ?, domain_sqlu_limit = ?, domain_status = ?,
                        domain_alias_limit = ?, domain_subd_limit = ?, domain_ip_id = ?, domain_disk_limit = ?,
                        domain_php = ?, domain_cgi = ?, allowbackup = ?, domain_dns = ?,  domain_software_allowed = ?,
                        phpini_perm_system = ?, phpini_perm_allow_url_fopen = ?, phpini_perm_display_errors = ?,
                        phpini_perm_disable_functions = ?, phpini_perm_mail_function = ?, domain_external_mail = ?,
                        web_folder_protection = ?,
                        mail_quota = ?
                    WHERE
                        domain_id = ?
                ', array($data['domain_expires'], time(), $data['domain_mailacc_limit'], $data['domain_ftpacc_limit'], $data['domain_traffic_limit'], $data['domain_sqld_limit'], $data['domain_sqlu_limit'], $needDaemonRequest ? 'tochange' : 'ok', $data['domain_alias_limit'], $data['domain_subd_limit'], $data['domain_ip_id'], $data['domain_disk_limit'], $data['domain_php'], $data['domain_cgi'], implode('|', $data['allowbackup']), $data['domain_dns'], $data['domain_software_allowed'], $phpini->getClientPermission('phpiniSystem'), $phpini->getClientPermission('phpiniAllowUrlFopen'), $phpini->getClientPermission('phpiniDisplayErrors'), $phpini->getClientPermission('phpiniDisableFunctions'), $phpini->getClientPermission('phpiniMailFunction'), $data['domain_external_mail'], $data['web_folder_protection'], $data['mail_quota'] * 1048576, $domainId));
            //print 'ouch'; exit;
            // Sync mailboxes quota if needed
            if ($data['fallback_mail_quota'] != $data['mail_quota'] * 1048576) {
                sync_mailboxes_quota($domainId, $data['mail_quota'] * 1048576);
            }
            // Update domain alias IP if needed
            if ($data['domain_ip_id'] != $data['fallback_domain_ip_id']) {
                if ($data['domain_alias_limit'] != '-1') {
                    exec_query('UPDATE domain_aliasses SET alias_ip_id = ? WHERE domain_id = ?', array($data['domain_ip_id'], $domainId));
                }
            }
            // Update Ftp quota limit if needed
            if ($data['domain_disk_limit'] != $data['fallback_domain_disk_limit']) {
                exec_query('
                        REPLACE INTO quotalimits (
                            name, quota_type, per_session, limit_type, bytes_in_avail, bytes_out_avail,
                            bytes_xfer_avail, files_in_avail, files_out_avail, files_xfer_avail
                        ) VALUES (
                            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
                        )
                    ', array($data['domain_name'], 'group', 'false', 'hard', $data['domain_disk_limit'] * 1048576, 0, 0, 0, 0, 0));
            }
            // Update reseller properties
            update_reseller_c_props($data['reseller_id']);
            $db->commit();
            iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterEditDomain, array('domainId' => $domainId));
            if ($needDaemonRequest) {
                send_request();
                set_page_message(tr('Domain scheduled for update.'), 'success');
            } else {
                set_page_message(tr('Domain successfully updated.'), 'success');
            }
            $userLogged = isset($_SESSION['logged_from']) ? $_SESSION['logged_from'] : $_SESSION['user_logged'];
            write_log("Domain " . decode_idna($data['domain_name']) . " has been updated by {$userLogged}", E_USER_NOTICE);
            return true;
        }
    } catch (iMSCP_Exception_Database $e) {
        $db->rollBack();
        throw $e;
    }
    if (!empty($errFieldsStack)) {
        iMSCP_Registry::set('errFieldsStack', $errFieldsStack);
    }
    return false;
}
Ejemplo n.º 22
0
Archivo: Request.php Proyecto: cwcw/cms
 /**
  *
  * @param Zend_Controller_Request_Abstract $request The instance request
  *
  * @return boolean The status on whether or nor is visitor
  */
 public static function isVisitor(Zend_Controller_Request_Abstract $request)
 {
     return Zend_Session::isStarted() && !Zend_Session::namespaceIsset('SwIRS_Web');
 }
Ejemplo n.º 23
0
 public static function has()
 {
     Zend_Session::start(true);
     return Zend_Session::namespaceIsset('USER');
 }
Ejemplo n.º 24
0
/**
 * Create reseller account
 *
 * @throws Exception
 * @throws iMSCP_Exception
 * @throws iMSCP_Exception_Database
 * @return bool
 */
function admin_checkAndCreateResellerAccount()
{
    iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onBeforeAddUser);
    $cfg = iMSCP_Registry::get('config');
    $errFieldsStack = array();
    $data =& admin_getData();
    /** @var $db iMSCP_Database */
    $db = iMSCP_Database::getInstance();
    try {
        $db->beginTransaction();
        // Check for reseller name
        $stmt = exec_query('SELECT COUNT(`admin_id`) `usernameExist` FROM `admin` WHERE `admin_name` = ? LIMIT 1', $data['admin_name']);
        $row = $stmt->fetchRow(PDO::FETCH_ASSOC);
        if ($row['usernameExist']) {
            set_page_message(tr("The username %s is not available.", '<b>' . $data['admin_name'] . '</b>'), 'error');
            $errFieldsStack[] = 'admin_name';
        } elseif (!validates_username($data['admin_name'])) {
            set_page_message(tr('Incorrect username length or syntax.'), 'error');
            $errFieldsStack[] = 'admin_name';
        }
        // check for password
        if (empty($data['password'])) {
            set_page_message(tr('You must provide a password.'), 'error');
            $errFieldsStack[] = 'password';
            $errFieldsStack[] = 'password_confirmation';
        } elseif ($data['password'] != $data['password_confirmation']) {
            set_page_message(tr("Passwords do not match."), 'error');
            $errFieldsStack[] = 'password';
            $errFieldsStack[] = 'password_confirmation';
        } elseif (!checkPasswordSyntax($data['password'])) {
            $errFieldsStack[] = 'password';
            $errFieldsStack[] = 'password_confirmation';
        }
        // Check for email address
        if (!chk_email($data['email'])) {
            set_page_message(tr('Incorrect syntax for email address.'), 'error');
            $errFieldsStack[] = 'email';
        }
        // Check for ip addresses - We are safe here
        $resellerIps = array();
        foreach ($data['server_ips'] as $serverIpData) {
            if (in_array($serverIpData['ip_id'], $data['reseller_ips'])) {
                $resellerIps[] = $serverIpData['ip_id'];
            }
        }
        sort($resellerIps);
        if (empty($resellerIps)) {
            set_page_message(tr('You must assign at least one IP to this reseller.'), 'error');
        }
        // Check for max domains limit
        if (!imscp_limit_check($data['max_dmn_cnt'], null)) {
            set_page_message(tr('Incorrect limit for %s.', tr('domain')), 'error');
            $errFieldsStack[] = 'max_dmn_cnt';
        }
        // Check for max subdomains limit
        if (!imscp_limit_check($data['max_sub_cnt'])) {
            set_page_message(tr('Incorrect limit for %s.', tr('subdomains')), 'error');
            $errFieldsStack[] = 'max_sub_cnt';
        }
        // check for max domain aliases limit
        if (!imscp_limit_check($data['max_als_cnt'])) {
            set_page_message(tr('Incorrect limit for %s.', tr('domain aliases')), 'error');
            $errFieldsStack[] = 'max_als_cnt';
        }
        // Check for max mail accounts limit
        if (!imscp_limit_check($data['max_mail_cnt'])) {
            set_page_message(tr('Incorrect limit for %s.', tr('email accounts')), 'error');
            $errFieldsStack[] = 'max_mail_cnt';
        }
        // Check for max ftp accounts limit
        if (!imscp_limit_check($data['max_ftp_cnt'])) {
            set_page_message(tr('Incorrect limit for %s.', tr('Ftp accounts')), 'error');
            $errFieldsStack[] = 'max_ftp_cnt';
        }
        // Check for max Sql databases limit
        if (!imscp_limit_check($data['max_sql_db_cnt'])) {
            set_page_message(tr('Incorrect limit for %s.', tr('SQL databases')), 'error');
            $errFieldsStack[] = 'max_sql_db_cnt';
        } elseif ($_POST['max_sql_db_cnt'] == -1 && $_POST['max_sql_user_cnt'] != -1) {
            set_page_message(tr('SQL database limit is disabled but SQL user limit is not.'), 'error');
            $errFieldsStack[] = 'max_sql_db_cnt';
        }
        // Check for max Sql users limit
        if (!imscp_limit_check($data['max_sql_user_cnt'])) {
            set_page_message(tr('Incorrect limit for %s.', tr('SQL users')), 'error');
            $errFieldsStack[] = 'max_sql_user_cnt';
        } elseif ($_POST['max_sql_user_cnt'] == -1 && $_POST['max_sql_db_cnt'] != -1) {
            set_page_message(tr('SQL user limit is disabled but SQL database limit is not.'), 'error');
            $errFieldsStack[] = 'max_sql_user_cnt';
        }
        // Check for max monthly traffic limit
        if (!imscp_limit_check($data['max_traff_amnt'], null)) {
            set_page_message(tr('Incorrect limit for %s.', tr('traffic')), 'error');
            $errFieldsStack[] = 'max_traff_amnt';
        }
        // Check for max disk space limit
        if (!imscp_limit_check($data['max_disk_amnt'], null)) {
            set_page_message(tr('Incorrect limit for %s.', tr('Disk space')), 'error');
            $errFieldsStack[] = 'max_disk_amnt';
        }
        // Check for PHP settings
        $phpini = iMSCP_PHPini::getInstance();
        $phpini->setResellerPermission('phpiniSystem', $data['php_ini_system']);
        if ($phpini->resellerHasPermission('phpiniSystem')) {
            $phpini->setResellerPermission('phpiniAllowUrlFopen', $data['php_ini_al_allow_url_fopen']);
            $phpini->setResellerPermission('phpiniDisplayErrors', $data['php_ini_al_display_errors']);
            $phpini->setResellerPermission('phpiniDisableFunctions', $data['php_ini_al_disable_functions']);
            $phpini->setResellerPermission('phpiniMailFunction', $data['php_ini_al_mail_function']);
            $phpini->setResellerPermission('phpiniMemoryLimit', $data['memory_limit']);
            // Must be set before phpiniPostMaxSize
            $phpini->setResellerPermission('phpiniPostMaxSize', $data['post_max_size']);
            // Must be set before phpiniUploadMaxFileSize
            $phpini->setResellerPermission('phpiniUploadMaxFileSize', $data['upload_max_filesize']);
            $phpini->setResellerPermission('phpiniMaxExecutionTime', $data['max_execution_time']);
            $phpini->setResellerPermission('phpiniMaxInputTime', $data['max_input_time']);
        }
        if (empty($errFieldsStack) && !Zend_Session::namespaceIsset('pageMessages')) {
            // Update process begin here
            // Insert reseller personal data into database
            exec_query('
                    INSERT INTO admin (
                        admin_name, admin_pass, admin_type, domain_created, created_by, fname, lname, firm, zip, city,
                        state, country, email, phone, fax, street1, street2, gender
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
                    )
                ', array($data['admin_name'], cryptPasswordWithSalt($data['password']), 'reseller', time(), $_SESSION['user_id'], $data['fname'], $data['lname'], $data['firm'], $data['zip'], $data['city'], $data['state'], $data['country'], $data['email'], $data['phone'], $data['fax'], $data['street1'], $data['street2'], $data['gender']));
            // Get new reseller unique identifier
            $resellerId = $db->insertId();
            // Insert reseller GUI properties into database
            exec_query('INSERT INTO user_gui_props (user_id, lang, layout) VALUES (?, ?, ?)', array($resellerId, $cfg['USER_INITIAL_LANG'], $cfg['USER_INITIAL_THEME']));
            // Insert reseller properties into database
            exec_query('
                    INSERT INTO reseller_props (
                        reseller_id, reseller_ips, max_dmn_cnt, current_dmn_cnt, max_sub_cnt, current_sub_cnt,
                        max_als_cnt, current_als_cnt, max_mail_cnt, current_mail_cnt, max_ftp_cnt, current_ftp_cnt,
                        max_sql_db_cnt, current_sql_db_cnt, max_sql_user_cnt, current_sql_user_cnt, max_traff_amnt,
                        current_traff_amnt, max_disk_amnt, current_disk_amnt, support_system, customer_id,
                        software_allowed, softwaredepot_allowed, websoftwaredepot_allowed, php_ini_system,
                        php_ini_al_disable_functions, php_ini_al_mail_function, php_ini_al_allow_url_fopen,
                        php_ini_al_display_errors, php_ini_max_post_max_size, php_ini_max_upload_max_filesize,
                        php_ini_max_max_execution_time, php_ini_max_max_input_time, php_ini_max_memory_limit
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                        ?, ?, ?
                    )
                ', array($resellerId, implode(';', $resellerIps) . ';', $data['max_dmn_cnt'], '0', $data['max_sub_cnt'], '0', $data['max_als_cnt'], '0', $data['max_mail_cnt'], '0', $data['max_ftp_cnt'], '0', $data['max_sql_db_cnt'], '0', $data['max_sql_user_cnt'], '0', $data['max_traff_amnt'], '0', $data['max_disk_amnt'], '0', $data['support_system'], $data['customer_id'], $data['software_allowed'], $data['softwaredepot_allowed'], $data['websoftwaredepot_allowed'], $phpini->getResellerPermission('phpiniSystem'), $phpini->getResellerPermission('phpiniDisableFunctions'), $phpini->getResellerPermission('phpiniMailFunction'), $phpini->getResellerPermission('phpiniAllowUrlFopen'), $phpini->getResellerPermission('phpiniDisplayErrors'), $phpini->getResellerPermission('phpiniPostMaxSize'), $phpini->getResellerPermission('phpiniUploadMaxFileSize'), $phpini->getResellerPermission('phpiniMaxExecutionTime'), $phpini->getResellerPermission('phpiniMaxInputTime'), $phpini->getResellerPermission('phpiniMemoryLimit')));
            $db->commit();
            // Creating Software repository for reseller if needed
            if ($data['software_allowed'] == 'yes' && !@mkdir($cfg['GUI_APS_DIR'] . '/' . $resellerId, 0750, true)) {
                write_log(sprintf('System was unable to create the %s directory for reseller software repository', "{$cfg['GUI_APS_DIR']}/{$resellerId}"), E_USER_ERROR);
            }
            iMSCP_Events_Aggregator::getInstance()->dispatch(iMSCP_Events::onAfterAddUser);
            send_add_user_auto_msg($_SESSION['user_id'], $data['admin_name'], $data['password'], $data['email'], $data['fname'], $data['lname'], tr('Reseller'));
            write_log(sprintf('A new reseller account (%s) has been created by %s', $data['admin_name'], $_SESSION['user_logged']), E_USER_NOTICE);
            set_page_message(tr('Reseller account successfully created.'), 'success');
            return true;
        }
    } catch (iMSCP_Exception_Database $e) {
        $db->rollBack();
        throw $e;
    }
    if (!empty($errFieldsStack)) {
        iMSCP_Registry::set('errFieldsStack', $errFieldsStack);
    }
    return false;
}
Ejemplo n.º 25
0
 /**
  * test for existence of namespace; expected true
  *
  * @return void
  */
 public function testNamespaceIsset()
 {
     try {
         $this->assertFalse(Zend_Session::namespaceIsset('trees'), 'namespaceIsset() should have returned false for a namespace with no keys set');
         $s = new Zend_Session_Namespace('trees');
         $this->assertFalse(Zend_Session::namespaceIsset('trees'), 'namespaceIsset() should have returned false for a namespace with no keys set');
         $s->cherry = 'bing';
         $this->assertTrue(Zend_Session::namespaceIsset('trees'), 'namespaceIsset() should have returned true for a namespace with keys set');
     } catch (Zend_Session_Exception $e) {
         $this->fail('Unexpected exception returned when attempting to fetch the value of non-existent key');
     }
 }
Ejemplo n.º 26
0
 public static function federalTax($amount = 0)
 {
     $oOrderParams = new ParametersObject();
     $tps = $oOrderParams->getValueByName('CP_TauxTaxeFed');
     $tps = $tps / 100;
     $taxValue = $amount * $tps;
     $taxValue = (double) $taxValue;
     if (Zend_Session::namespaceIsset('order')) {
         $session = new Zend_Session_Namespace('order');
         $session->tps = $taxValue;
     }
     return $taxValue;
 }
Ejemplo n.º 27
0
/**
 * Validate input data
 *
 * @access private
 * @return bool TRUE if data are valid, FALSE otherwise
 */
function admin_isValidData()
{
    if (!chk_email($_POST['email'])) {
        set_page_message(tr("Incorrect email length or syntax."), 'error');
    }
    if (!empty($_POST['password']) && !empty($_POST['password_confirmation'])) {
        if ($_POST['password'] != $_POST['password_confirmation']) {
            set_page_message(tr("Passwords do not match."), 'error');
        }
        checkPasswordSyntax($_POST['password']);
    }
    if (Zend_Session::namespaceIsset('pageMessages')) {
        return false;
    }
    return true;
}
Ejemplo n.º 28
0
 public function removeNameSpace($namespace){
 	if(Zend_Session::namespaceIsset($namespace)){
 		$ns = new Zend_Session_Namespace($namespace);
 		$ns->unsetAll();
 	}
 }