Skip to content
Snippets Groups Projects
class.config.php 38.4 KiB
Newer Older
Jared Hancock's avatar
Jared Hancock committed
<?php
/*********************************************************************
    class.config.php

    osTicket config info manager.
Jared Hancock's avatar
Jared Hancock committed

    Peter Rotich <peter@osticket.com>
    Copyright (c)  2006-2013 osTicket
Jared Hancock's avatar
Jared Hancock committed
    http://www.osticket.com

    Released under the GNU General Public License WITHOUT ANY WARRANTY.
    See LICENSE.TXT for details.

    vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/

class Config {
    var $section = null;                    # Default namespace ('core')
    var $table = CONFIG_TABLE;              # Table name (with prefix)
    var $section_column = 'namespace';      # namespace column name
    var $session = null;                    # Session-backed configuration
    # Defaults for this configuration. If settings don't exist in the
    # database yet, the ->getInfo() method will not include the (default)
    # values in the returned array. $defaults allows developers to define
    # new settings and the corresponding default values.
    var $defaults = array();                # List of default values

    function Config($section=null) {
        if ($section)
            $this->section = $section;
        if ($this->section === null)
            return false;
        if (!isset($_SESSION['cfg:'.$this->section]))
            $_SESSION['cfg:'.$this->section] = array();
        $this->session = &$_SESSION['cfg:'.$this->section];

        $sql='SELECT id, `key`, value, `updated` FROM '.$this->table
            .' WHERE `'.$this->section_column.'` = '.db_input($this->section);
        if(($res=db_query($sql)) && db_num_rows($res))
            while ($row = db_fetch_array($res))
                $this->config[$row['key']] = $row;
    function getNamespace() {
        return $this->section;
    }

Jared Hancock's avatar
Jared Hancock committed
    function getInfo() {
        $info = $this->defaults;
Jared Hancock's avatar
Jared Hancock committed
        foreach ($this->config as $key=>$setting)
            $info[$key] = $setting['value'];
        return $info;
    }

    function get($key, $default=null) {
        if (isset($this->session[$key]))
            return $this->session[$key];
        elseif (isset($this->config[$key]))
            return $this->config[$key]['value'];
        elseif (isset($this->defaults[$key]))
            return $this->defaults[$key];

        return $default;
    function exists($key) {
        return $this->get($key, null) ? true : false;
    }

    function set($key, $value) {
        return ($this->update($key, $value)) ? $value : null;
    function persist($key, $value) {
        $this->session[$key] = $value;
        return true;
    }

    function lastModified($key) {
        if (isset($this->config[$key]))
            return $this->config[$key]['updated'];
        else
            return false;
    }

    function create($key, $value) {
        $sql = 'INSERT INTO '.$this->table
            .' SET `'.$this->section_column.'`='.db_input($this->section)
            .', `key`='.db_input($key)
            .', value='.db_input($value);
        if (!db_query($sql) || !($id=db_insert_id()))
            return false;

        $this->config[$key] = array('key'=>$key, 'value'=>$value, 'id'=>$id);
        return true;
    }

    function update($key, $value) {
Jared Hancock's avatar
Jared Hancock committed
        if (!$key)
            return false;
        elseif (!isset($this->config[$key]))
            return $this->create($key, $value);

        $setting = &$this->config[$key];
        if ($setting['value'] == $value)
            return true;

        if (!db_query('UPDATE '.$this->table.' SET updated=NOW(), value='
                .db_input($value).' WHERE id='.db_input($setting['id'])))
        $setting['value'] = $value;
        return true;
    }

    function updateAll($updates) {
        foreach ($updates as $key=>$value)
            if (!$this->update($key, $value))
                return false;
        return true;
    }
Peter Rotich's avatar
Peter Rotich committed
    function destroy() {

        $sql='DELETE FROM '.$this->table
            .' WHERE `'.$this->section_column.'` = '.db_input($this->section);

        db_query($sql);
        unset($this->session);
    }
}

class OsticketConfig extends Config {
    var $table = CONFIG_TABLE;
    var $section = 'core';

    var $defaultDept;   //Default Department
    var $defaultSLA;   //Default SLA
    var $defaultEmail;  //Default Email
    var $alertEmail;  //Alert Email
    var $defaultSMTPEmail; //Default  SMTP Email

    var $defaults = array(
        'allow_pw_reset' =>     true,
        'pw_reset_window' =>    30,
        'enable_html_thread' => true,
        'allow_attachments' =>  true,
        'allow_email_attachments' => true,
        'allow_online_attachments' => true,
        'allow_online_attachments_onlogin' => false,
        'name_format' =>        'full', # First Last
        'auto_claim_tickets'=>  true,
        'system_language' =>    'en_US',
        'default_storage_bk' => 'D',
        'allow_client_updates' => false,
        'message_autoresponder_collabs' => true,
        'add_email_collabs' => true,
        'clients_only' => false,
        'client_registration' => 'closed',
        'accept_unregistered_email' => true,
    function OsticketConfig($section=null) {
        parent::Config($section);
        if (count($this->config) == 0) {
            // Fallback for osticket < 1.7@852ca89e
            $sql='SELECT * FROM '.$this->table.' WHERE id = 1';
            if (($res=db_query($sql)) && db_num_rows($res))
                foreach (db_fetch_array($res) as $key=>$value)
                    $this->config[$key] = array('value'=>$value);
        }

        //Get the default time zone
        // We can't JOIN timezone table above due to upgrade support.
        if ($this->get('default_timezone_id')) {
            if (!$this->exists('tz_offset'))
                $this->persist('tz_offset',
                    Timezone::getOffsetById($this->get('default_timezone_id')));
        } else
            // Previous osTicket versions saved the offset value instead of
            // a timezone instance. This is compatibility for the upgrader
            $this->persist('tz_offset', 0);
    function lastModified($key=false) {
        return max(array_map(array('parent', 'lastModified'),
            array_keys($this->config)));
    }

Jared Hancock's avatar
Jared Hancock committed
    function isHelpDeskOffline() {
        return ($this->get('isonline'));
    function isKnowledgebaseEnabled() {
Jared Hancock's avatar
Jared Hancock committed
        require_once(INCLUDE_DIR.'class.faq.php');
        return ($this->get('enable_kb') && FAQ::countPublishedFAQs());
Jared Hancock's avatar
Jared Hancock committed
    }

    function getVersion() {
    function getSchemaSignature($section=null) {
        if ((!$section || $section == $this->section)
                && ($v=$this->get('schema_signature')))
            return $v;

        // 1.7 after namespaced configuration, other namespace
        if ($section) {
            $sql='SELECT value FROM '.$this->table
                .' WHERE `key` = "schema_signature" and namespace='.db_input($section);
            if (($res=db_query($sql, false)) && db_num_rows($res))
                return db_result($res);
        }
Peter Rotich's avatar
Peter Rotich committed

        // 1.7 before namespaced configuration
        $sql='SELECT `schema_signature` FROM '.$this->table
            .' WHERE id=1';
        if (($res=db_query($sql, false)) && db_num_rows($res))
            return db_result($res);
        // old version 1.6
        return md5(self::getDBVersion());
        if (!$this->exists('db_tz_offset')) {
            $sql='SELECT (TIME_TO_SEC(TIMEDIFF(NOW(), UTC_TIMESTAMP()))/3600) as db_tz_offset';
            if(($res=db_query($sql)) && db_num_rows($res))
                $this->persist('db_tz_offset', db_result($res));
        return $this->get('db_tz_offset');
    function getDefaultTimezoneId() {
        return $this->get('default_timezone_id');
    }

Jared Hancock's avatar
Jared Hancock committed
    /* Date & Time Formats */
    function observeDaylightSaving() {
        return ($this->get('enable_daylight_saving'));
Jared Hancock's avatar
Jared Hancock committed
    }
    function getTimeFormat() {
        return $this->get('time_format');
Jared Hancock's avatar
Jared Hancock committed
    }
    function getDateFormat() {
        return $this->get('date_format');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getDateTimeFormat() {
        return $this->get('datetime_format');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getDayDateTimeFormat() {
        return $this->get('daydatetime_format');
    function getConfigInfo() {
Jared Hancock's avatar
Jared Hancock committed
        return $this->getInfo();
Jared Hancock's avatar
Jared Hancock committed
    function getTitle() {
        return $this->get('helpdesk_title');
Jared Hancock's avatar
Jared Hancock committed
    function getUrl() {
        return $this->get('helpdesk_url');
Jared Hancock's avatar
Jared Hancock committed
    function getBaseUrl() { //Same as above with no trailing slash.
        return rtrim($this->getUrl(),'/');
    }

    function getTZOffset() {
        return $this->get('tz_offset');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getPageSize() {
        return $this->get('max_page_size');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getGracePeriod() {
        return $this->get('overdue_grace_period');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getPasswdResetPeriod() {
        return $this->get('passwd_reset_period');
    function isHtmlThreadEnabled() {
        return $this->get('enable_html_thread');
    }

    function allowClientUpdates() {
        return $this->get('allow_client_updates');
    }

Jared Hancock's avatar
Jared Hancock committed
    function getClientTimeout() {
        return $this->getClientSessionTimeout();
    }
Jared Hancock's avatar
Jared Hancock committed
    function getClientSessionTimeout() {
        return $this->get('client_session_timeout')*60;
Jared Hancock's avatar
Jared Hancock committed
    }

    function getClientLoginTimeout() {
        return $this->get('client_login_timeout')*60;
Jared Hancock's avatar
Jared Hancock committed
    }

    function getClientMaxLogins() {
        return $this->get('client_max_logins');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getStaffTimeout() {
        return $this->getStaffSessionTimeout();
    }

    function getStaffSessionTimeout() {
        return $this->get('staff_session_timeout')*60;
Jared Hancock's avatar
Jared Hancock committed
    }

    function getStaffLoginTimeout() {
        return $this->get('staff_login_timeout')*60;
Jared Hancock's avatar
Jared Hancock committed
    }

    function getStaffMaxLogins() {
        return $this->get('staff_max_logins');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getLockTime() {
        return $this->get('autolock_minutes');
    function getDefaultNameFormat() {
        return $this->get('name_format');
    }

Jared Hancock's avatar
Jared Hancock committed
    function getDefaultDeptId() {
        return $this->get('default_dept_id');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getDefaultDept() {

        if(!$this->defaultDept && $this->getDefaultDeptId())
            $this->defaultDept=Dept::lookup($this->getDefaultDeptId());

        return $this->defaultDept;
Jared Hancock's avatar
Jared Hancock committed

    function getDefaultEmailId() {
        return $this->get('default_email_id');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getDefaultEmail() {

        if(!$this->defaultEmail && $this->getDefaultEmailId())
            $this->defaultEmail = Email::lookup($this->getDefaultEmailId());
Jared Hancock's avatar
Jared Hancock committed

        return $this->defaultEmail;
    }

    function getDefaultEmailAddress() {
        return ($email=$this->getDefaultEmail()) ? $email->getAddress() : null;
Jared Hancock's avatar
Jared Hancock committed
    }

    function getDefaultSLAId() {
        return $this->get('default_sla_id');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getDefaultSLA() {

        if(!$this->defaultSLA && $this->getDefaultSLAId())
            $this->defaultSLA = SLA::lookup($this->getDefaultSLAId());
Jared Hancock's avatar
Jared Hancock committed

        return $this->defaultSLA;
    }

    function getAlertEmailId() {
        return $this->get('alert_email_id');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getAlertEmail() {

        if(!$this->alertEmail)
            if(!($this->alertEmail = Email::lookup($this->getAlertEmailId())))
                $this->alertEmail = $this->getDefaultEmail();

Jared Hancock's avatar
Jared Hancock committed
        return $this->alertEmail;
    }

    function getDefaultSMTPEmail() {

        if(!$this->defaultSMTPEmail && $this->get('default_smtp_id'))
            $this->defaultSMTPEmail = Email::lookup($this->get('default_smtp_id'));

Jared Hancock's avatar
Jared Hancock committed
        return $this->defaultSMTPEmail;
    }

    function getDefaultPriorityId() {
        return $this->get('default_priority_id');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getDefaultTemplateId() {
        return $this->get('default_template_id');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getDefaultTemplate() {
Jared Hancock's avatar
Jared Hancock committed
        if(!$this->defaultTemplate && $this->getDefaultTemplateId())
            $this->defaultTemplate = EmailTemplateGroup::lookup($this->getDefaultTemplateId());
Jared Hancock's avatar
Jared Hancock committed

        return $this->defaultTemplate;
    }

    function getLandingPageId() {
        return $this->get('landing_page_id');
    }

    function getLandingPage() {

        if(!$this->landing_page && $this->getLandingPageId())
            $this->landing_page = Page::lookup($this->getLandingPageId());

        return $this->landing_page;
    }

    function getOfflinePageId() {
        return $this->get('offline_page_id');
    }

    function getOfflinePage() {

        if(!$this->offline_page && $this->getOfflinePageId())
            $this->offline_page = Page::lookup($this->getOfflinePageId());

        return $this->offline_page;
    }

    function getThankYouPageId() {
        return $this->get('thank-you_page_id');
    }

    function getThankYouPage() {

        if(!$this->thankyou_page && $this->getThankYouPageId())
            $this->thankyou_page = Page::lookup($this->getThankYouPageId());

        return $this->thankyou_page;
    }

    function getDefaultPages() {
        /* Array of ids...as opposed to objects */
        return array(
                $this->getLandingPageId(),
                $this->getOfflinePageId(),
                $this->getThankYouPageId(),
                );
    }

Jared Hancock's avatar
Jared Hancock committed
    function getMaxOpenTickets() {
         return $this->get('max_open_tickets');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getMaxFileSize() {
        return $this->get('max_file_size');
    function getStaffMaxFileUploads() {
        return $this->get('max_staff_file_uploads');
    function getClientMaxFileUploads() {
        //TODO: change max_user_file_uploads to max_client_file_uploads
        return $this->get('max_user_file_uploads');
Jared Hancock's avatar
Jared Hancock committed
    function getLogLevel() {
        return $this->get('log_level');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getLogGracePeriod() {
        return $this->get('log_graceperiod');
Jared Hancock's avatar
Jared Hancock committed
    }

    function enableStaffIPBinding() {
        return ($this->get('staff_ip_binding'));
    /**
     * Configuration: allow_pw_reset
     *
     * TRUE if the <a>Forgot my password</a> link and system should be
     * enabled, and FALSE otherwise.
     */
    function allowPasswordReset() {
        return $this->get('allow_pw_reset');
    }

    /**
     * Configuration: pw_reset_window
     *
     * Number of minutes for which the password reset token is valid.
     *
     * Returns: Number of seconds the password reset token is valid. The
     *      number of minutes from the database is automatically converted
     *      to seconds here.
     */
    function getPwResetWindow() {
        // pw_reset_window is stored in minutes. Return value in seconds
        return $this->get('pw_reset_window') * 60;
    }

    function isClientLoginRequired() {
        return $this->get('clients_only');
    }

    function isClientRegistrationEnabled() {
        return in_array($this->getClientRegistrationMode(),
            array('public', 'auto'));
    }

    function getClientRegistrationMode() {
        return $this->get('client_registration');
    }

    function isCaptchaEnabled() {
        return (extension_loaded('gd') && function_exists('gd_info') && $this->get('enable_captcha'));
    function isAutoCronEnabled() {
        return ($this->get('enable_auto_cron'));

    function isEmailPollingEnabled() {
        return ($this->get('enable_mail_polling'));
Jared Hancock's avatar
Jared Hancock committed
    function useEmailPriority() {
        return ($this->get('use_email_priority'));
    function acceptUnregisteredEmail() {
        return $this->get('accept_unregistered_email');
    }

    function addCollabsViaEmail() {
        return ($this->get('add_email_collabs'));
    }

Jared Hancock's avatar
Jared Hancock committed
    function getAdminEmail() {
         return $this->get('admin_email');
Jared Hancock's avatar
Jared Hancock committed
    }

    function getReplySeparator() {
        return $this->get('reply_separator');
Jared Hancock's avatar
Jared Hancock committed
    function stripQuotedReply() {
        return ($this->get('strip_quoted_reply'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function saveEmailHeaders() {
        return true; //No longer an option...hint: big plans for headers coming!!
    }
Jared Hancock's avatar
Jared Hancock committed
    function useRandomIds() {
        return ($this->get('random_ticket_ids'));
Jared Hancock's avatar
Jared Hancock committed
    }

    /* autoresponders  & Alerts */
    function autoRespONNewTicket() {
        return ($this->get('ticket_autoresponder'));
Jared Hancock's avatar
Jared Hancock committed
    function autoRespONNewMessage() {
        return ($this->get('message_autoresponder'));
    function notifyCollabsONNewMessage() {
        return ($this->get('message_autoresponder_collabs'));
    }

Jared Hancock's avatar
Jared Hancock committed
    function notifyONNewStaffTicket() {
        return ($this->get('ticket_notice_active'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertONNewMessage() {
        return ($this->get('message_alert_active'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertLastRespondentONNewMessage() {
        return ($this->get('message_alert_laststaff'));
Jared Hancock's avatar
Jared Hancock committed
    function alertAssignedONNewMessage() {
        return ($this->get('message_alert_assigned'));
Jared Hancock's avatar
Jared Hancock committed
    function alertDeptManagerONNewMessage() {
        return ($this->get('message_alert_dept_manager'));
    function alertAcctManagerONNewMessage() {
        return ($this->get('message_alert_acct_manager'));
    }

Jared Hancock's avatar
Jared Hancock committed
    function alertONNewNote() {
        return ($this->get('note_alert_active'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertLastRespondentONNewNote() {
        return ($this->get('note_alert_laststaff'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertAssignedONNewNote() {
        return ($this->get('note_alert_assigned'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertDeptManagerONNewNote() {
        return ($this->get('note_alert_dept_manager'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertONNewTicket() {
        return ($this->get('ticket_alert_active'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertAdminONNewTicket() {
        return ($this->get('ticket_alert_admin'));
Jared Hancock's avatar
Jared Hancock committed
    function alertDeptManagerONNewTicket() {
        return ($this->get('ticket_alert_dept_manager'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertDeptMembersONNewTicket() {
        return ($this->get('ticket_alert_dept_members'));
    function alertAcctManagerONNewTicket() {
        return ($this->get('ticket_alert_acct_manager'));
    }

Jared Hancock's avatar
Jared Hancock committed
    function alertONTransfer() {
        return ($this->get('transfer_alert_active'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertAssignedONTransfer() {
        return ($this->get('transfer_alert_assigned'));
Jared Hancock's avatar
Jared Hancock committed
    function alertDeptManagerONTransfer() {
        return ($this->get('transfer_alert_dept_manager'));
Jared Hancock's avatar
Jared Hancock committed
    function alertDeptMembersONTransfer() {
        return ($this->get('transfer_alert_dept_members'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertONAssignment() {
        return ($this->get('assigned_alert_active'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertStaffONAssignment() {
        return ($this->get('assigned_alert_staff'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertTeamLeadONAssignment() {
        return ($this->get('assigned_alert_team_lead'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertTeamMembersONAssignment() {
        return ($this->get('assigned_alert_team_members'));
Jared Hancock's avatar
Jared Hancock committed
    }


    function alertONOverdueTicket() {
        return ($this->get('overdue_alert_active'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertAssignedONOverdueTicket() {
        return ($this->get('overdue_alert_assigned'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertDeptManagerONOverdueTicket() {
        return ($this->get('overdue_alert_dept_manager'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function alertDeptMembersONOverdueTicket() {
        return ($this->get('overdue_alert_dept_members'));
    function autoClaimTickets() {
        return $this->get('auto_claim_tickets');
Jared Hancock's avatar
Jared Hancock committed
    }

    function showAssignedTickets() {
        return ($this->get('show_assigned_tickets'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function showAnsweredTickets() {
        return ($this->get('show_answered_tickets'));
Jared Hancock's avatar
Jared Hancock committed
    function hideStaffName() {
        return ($this->get('hide_staff_name'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function sendOverLimitNotice() {
        return ($this->get('overlimit_notice_active'));
Jared Hancock's avatar
Jared Hancock committed
    /* Error alerts sent to admin email when enabled */
    function alertONSQLError() {
        return ($this->get('send_sql_errors'));
Jared Hancock's avatar
Jared Hancock committed
    }
    function alertONLoginError() {
        return ($this->get('send_login_errors'));
Jared Hancock's avatar
Jared Hancock committed

    /* Attachments */
    function getAllowedFileTypes() {
        return trim($this->get('allowed_filetypes'));
Jared Hancock's avatar
Jared Hancock committed

    function emailAttachments() {
        return ($this->get('email_attachments'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function allowAttachments() {
        return ($this->get('allow_attachments'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function allowOnlineAttachments() {
        return ($this->allowAttachments() && $this->get('allow_online_attachments'));
Jared Hancock's avatar
Jared Hancock committed
    }

    function allowAttachmentsOnlogin() {
        return ($this->allowOnlineAttachments() && $this->get('allow_online_attachments_onlogin'));
Jared Hancock's avatar
Jared Hancock committed
    function allowEmailAttachments() {
        return ($this->allowAttachments() && $this->get('allow_email_attachments'));
    function getSystemLanguage() {
        return $this->get('system_language');
    }

    //TODO: change db field to allow_api_attachments - which will include  email/json/xml attachments
    //       terminology changed on the UI
    function allowAPIAttachments() {
        return $this->allowEmailAttachments();
    }

    /* Needed by upgrader on 1.6 and older releases upgrade - not not remove */
Jared Hancock's avatar
Jared Hancock committed
    function getUploadDir() {
        return $this->get('upload_dir');
    function getDefaultStorageBackendChar() {
        return $this->get('default_storage_bk');
    }

    function getVar($name) {
        return $this->get($name);
    }

    function updateSettings($vars, &$errors) {
Jared Hancock's avatar
Jared Hancock committed

        if(!$vars || $errors)
            return false;
Jared Hancock's avatar
Jared Hancock committed
        switch(strtolower($vars['t'])) {
            case 'system':
                return $this->updateSystemSettings($vars, $errors);
Jared Hancock's avatar
Jared Hancock committed
                break;
            case 'tickets':
                return $this->updateTicketsSettings($vars, $errors);
Jared Hancock's avatar
Jared Hancock committed
                break;
            case 'emails':
                return $this->updateEmailsSettings($vars, $errors);
Jared Hancock's avatar
Jared Hancock committed
                break;
            case 'pages':
                return $this->updatePagesSettings($vars, $errors);
                break;
            case 'access':
                return $this->updateAccessSettings($vars, $errors);
                break;
            case 'autoresp':
                return $this->updateAutoresponderSettings($vars, $errors);
Jared Hancock's avatar
Jared Hancock committed
                break;
            case 'alerts':
                return $this->updateAlertsSettings($vars, $errors);
Jared Hancock's avatar
Jared Hancock committed
                break;
            case 'kb':
                return $this->updateKBSettings($vars, $errors);
Jared Hancock's avatar
Jared Hancock committed
                break;
            default:
                $errors['err']='Unknown setting option. Get technical support.';
        }

        return false;
    }

    function updateSystemSettings($vars, &$errors) {
Jared Hancock's avatar
Jared Hancock committed

        $f=array();
        $f['helpdesk_url']=array('type'=>'string',   'required'=>1, 'error'=>'Helpdesk URl required');
        $f['helpdesk_title']=array('type'=>'string',   'required'=>1, 'error'=>'Helpdesk title required');
        $f['default_dept_id']=array('type'=>'int',   'required'=>1, 'error'=>'Default Dept. required');
        //Date & Time Options
        $f['time_format']=array('type'=>'string',   'required'=>1, 'error'=>'Time format required');
        $f['date_format']=array('type'=>'string',   'required'=>1, 'error'=>'Date format required');
        $f['datetime_format']=array('type'=>'string',   'required'=>1, 'error'=>'Datetime format required');
        $f['daydatetime_format']=array('type'=>'string',   'required'=>1, 'error'=>'Day, Datetime format required');
        $f['default_timezone_id']=array('type'=>'int',   'required'=>1, 'error'=>'Default Timezone required');
        if(!Validator::process($f, $vars, $errors) || $errors)
Jared Hancock's avatar
Jared Hancock committed
            return false;

        return $this->updateAll(array(
            'isonline'=>$vars['isonline'],
            'helpdesk_title'=>$vars['helpdesk_title'],
            'helpdesk_url'=>$vars['helpdesk_url'],
            'default_dept_id'=>$vars['default_dept_id'],
            'max_page_size'=>$vars['max_page_size'],
            'log_level'=>$vars['log_level'],
            'log_graceperiod'=>$vars['log_graceperiod'],
            'name_format'=>$vars['name_format'],
            'time_format'=>$vars['time_format'],
            'date_format'=>$vars['date_format'],
            'datetime_format'=>$vars['datetime_format'],
            'daydatetime_format'=>$vars['daydatetime_format'],
            'default_timezone_id'=>$vars['default_timezone_id'],
            'enable_daylight_saving'=>isset($vars['enable_daylight_saving'])?1:0,
        ));
    }

    function updateAccessSettings($vars, &$errors) {
        $f=array();
        $f['staff_session_timeout']=array('type'=>'int',   'required'=>1, 'error'=>'Enter idle time in minutes');
        $f['client_session_timeout']=array('type'=>'int',   'required'=>1, 'error'=>'Enter idle time in minutes');
        $f['pw_reset_window']=array('type'=>'int', 'required'=>1, 'min'=>1,
            'error'=>'Valid password reset window required');


        if(!Validator::process($f, $vars, $errors) || $errors)
            return false;

        return $this->updateAll(array(
            'passwd_reset_period'=>$vars['passwd_reset_period'],
            'staff_max_logins'=>$vars['staff_max_logins'],
            'staff_login_timeout'=>$vars['staff_login_timeout'],
            'staff_session_timeout'=>$vars['staff_session_timeout'],
            'staff_ip_binding'=>isset($vars['staff_ip_binding'])?1:0,
            'client_max_logins'=>$vars['client_max_logins'],
            'client_login_timeout'=>$vars['client_login_timeout'],
            'client_session_timeout'=>$vars['client_session_timeout'],
            'allow_pw_reset'=>isset($vars['allow_pw_reset'])?1:0,
            'pw_reset_window'=>$vars['pw_reset_window'],
            'clients_only'=>isset($vars['clients_only'])?1:0,
            'client_registration'=>$vars['client_registration'],
    function updateTicketsSettings($vars, &$errors) {
Jared Hancock's avatar
Jared Hancock committed
        $f=array();
        $f['default_sla_id']=array('type'=>'int',   'required'=>1, 'error'=>'Selection required');
        $f['default_priority_id']=array('type'=>'int',   'required'=>1, 'error'=>'Selection required');
        $f['max_open_tickets']=array('type'=>'int',   'required'=>1, 'error'=>'Enter valid numeric value');
        $f['autolock_minutes']=array('type'=>'int',   'required'=>1, 'error'=>'Enter lock time in minutes');


        if($vars['enable_captcha']) {
            if (!extension_loaded('gd'))
                $errors['enable_captcha']='The GD extension required';
            elseif(!function_exists('imagepng'))
                $errors['enable_captcha']='PNG support required for Image Captcha';
        }

        if($vars['allow_attachments']) {

            if(!ini_get('file_uploads'))
                $errors['err']='The \'file_uploads\' directive is disabled in php.ini';

            if(!is_numeric($vars['max_file_size']))
                $errors['max_file_size']='Maximum file size required';

            if(!$vars['allowed_filetypes'])
                $errors['allowed_filetypes']='Allowed file extentions required';

            if(!($maxfileuploads=ini_get('max_file_uploads')))
                $maxfileuploads=DEFAULT_MAX_FILE_UPLOADS;

            if(!$vars['max_user_file_uploads'] || $vars['max_user_file_uploads']>$maxfileuploads)
                $errors['max_user_file_uploads']='Invalid selection. Must be less than '.$maxfileuploads;

            if(!$vars['max_staff_file_uploads'] || $vars['max_staff_file_uploads']>$maxfileuploads)
                $errors['max_staff_file_uploads']='Invalid selection. Must be less than '.$maxfileuploads;
        }



        if(!Validator::process($f, $vars, $errors) || $errors)
Jared Hancock's avatar
Jared Hancock committed
            return false;

        if (isset($vars['default_storage_bk']))
            $this->update('default_storage_bk', $vars['default_storage_bk']);

        return $this->updateAll(array(
            'random_ticket_ids'=>$vars['random_ticket_ids'],
            'default_priority_id'=>$vars['default_priority_id'],
            'default_sla_id'=>$vars['default_sla_id'],
            'max_open_tickets'=>$vars['max_open_tickets'],
            'autolock_minutes'=>$vars['autolock_minutes'],
            'enable_captcha'=>isset($vars['enable_captcha'])?1:0,
            'auto_claim_tickets'=>isset($vars['auto_claim_tickets'])?1:0,
Peter Rotich's avatar
Peter Rotich committed
            'show_assigned_tickets'=>isset($vars['show_assigned_tickets'])?0:1,
            'show_answered_tickets'=>isset($vars['show_answered_tickets'])?0:1,
            'show_related_tickets'=>isset($vars['show_related_tickets'])?1:0,
            'hide_staff_name'=>isset($vars['hide_staff_name'])?1:0,
            'enable_html_thread'=>isset($vars['enable_html_thread'])?1:0,
            'allow_client_updates'=>isset($vars['allow_client_updates'])?1:0,
            'allow_attachments'=>isset($vars['allow_attachments'])?1:0,
            'allowed_filetypes'=>strtolower(preg_replace("/\n\r|\r\n|\n|\r/", '',trim($vars['allowed_filetypes']))),
            'max_file_size'=>$vars['max_file_size'],
            'max_user_file_uploads'=>$vars['max_user_file_uploads'],
            'max_staff_file_uploads'=>$vars['max_staff_file_uploads'],
            'email_attachments'=>isset($vars['email_attachments'])?1:0,
            'allow_email_attachments'=>isset($vars['allow_email_attachments'])?1:0,
            'allow_online_attachments'=>isset($vars['allow_online_attachments'])?1:0,
            'allow_online_attachments_onlogin'=>isset($vars['allow_online_attachments_onlogin'])?1:0,
    function updateEmailsSettings($vars, &$errors) {
Jared Hancock's avatar
Jared Hancock committed

        $f=array();
        $f['default_template_id']=array('type'=>'int',   'required'=>1, 'error'=>'You must select template.');
Jared Hancock's avatar
Jared Hancock committed
        $f['default_email_id']=array('type'=>'int',   'required'=>1, 'error'=>'Default email required');
        $f['alert_email_id']=array('type'=>'int',   'required'=>1, 'error'=>'Selection required');
        $f['admin_email']=array('type'=>'email',   'required'=>1, 'error'=>'System admin email required');
        if($vars['strip_quoted_reply'] && !trim($vars['reply_separator']))
Jared Hancock's avatar
Jared Hancock committed
            $errors['reply_separator']='Reply separator required to strip quoted reply.';
Jared Hancock's avatar
Jared Hancock committed
        if($vars['admin_email'] && Email::getIdByEmail($vars['admin_email'])) //Make sure admin email is not also a system email.
            $errors['admin_email']='Email already setup as system email';

        if(!Validator::process($f,$vars,$errors) || $errors)
            return false;

        return $this->updateAll(array(
            'default_template_id'=>$vars['default_template_id'],
            'default_email_id'=>$vars['default_email_id'],
            'alert_email_id'=>$vars['alert_email_id'],
            'default_smtp_id'=>$vars['default_smtp_id'],
            'admin_email'=>$vars['admin_email'],
            'enable_auto_cron'=>isset($vars['enable_auto_cron'])?1:0,
            'enable_mail_polling'=>isset($vars['enable_mail_polling'])?1:0,
            'strip_quoted_reply'=>isset($vars['strip_quoted_reply'])?1:0,
            'use_email_priority'=>isset($vars['use_email_priority'])?1:0,
            'accept_unregistered_email'=>isset($vars['accept_unregistered_email'])?1:0,
            'add_email_collabs'=>isset($vars['add_email_collabs'])?1:0,
            'reply_separator'=>$vars['reply_separator'],
    function getLogo($site) {
        $id = $this->get("{$site}_logo_id", false);
        return ($id) ? AttachmentFile::lookup($id) : null;
    }
    function getClientLogo() {
        return $this->getLogo('client');
    }
    function getLogoId($site) {
        return $this->get("{$site}_logo_id", false);
    }