<?php

/**
 * This is the model class for table "sysconfig".
 *
 * The followings are the available columns in table 'sysconfig':
 * @property integer $id
 * @property string $key
 * @property string $value
 */
class SysconfigValueType
{

    const DROPDOWN = 'dropDownList';
    const PASSWORD = 'passwordField';
    const TEXT = 'textField';
    const TEXTAREA = 'textArea';
    const INT = 'intTextField';
    const BOOL = 'Checkbox';
    const MULTI = 'multiDropDown';   //this is for the Name Pattern Fields

}

class Sysconfig extends PhonalisaRecord
{

    public $id;
    public $key;
    public $descr;
    public $value;
    public $standard;
    public $short;
    public $typ;
    public $defaultValue;
    public $readOnly = false;
    public $hideDefault;
    public $optionValueCallback = NULL;
    private $m_DefaultValues = NULL;
    public $m_ConfigSections = array();
    public $m_ConfigSectionsHumanReadableNames = array();
    public $m_LastConfigSection = NULL;

    public static function myAttributes()
    {

        return array(
            'key' => 'key',
            'value' => 'value',
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Sysconfig the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function getConfigSectionHumanReadableName()
    {
        if ($this->m_ConfigSectionsHumanReadableNames == NULL) {
            $this->buildConfigSections();
        }
        return $this->m_ConfigSectionsHumanReadableNames;
    }

    public function getConfigItemsArray()
    {
        if ($this->m_ConfigSections == NULL) {
            $this->buildConfigSections();
        }
        return $this->m_ConfigSections;
    }

    private function addConfigSection($sectionName, $humanName)
    {
        if (!array_key_exists($sectionName, $this->m_ConfigSectionsHumanReadableNames)) {
            $this->m_ConfigSectionsHumanReadableNames[$sectionName] = $humanName;
        }
        if (!array_key_exists($sectionName, $this->m_ConfigSections)) {
            $this->m_ConfigSections[$sectionName] = array();
        }

        $this->m_LastConfigSection = $sectionName;
    }

    private function addConfigOption($key, $defaultValue, $typ)
    {
        if ($this->m_LastConfigSection == NULL) {
            Log::e("Last config section not set!", "phonalisa-webinterface-config");
            return;
        }

        $section = $this->m_LastConfigSection;
        $devModeKey = '';

        if (Yii::app()->params->devMode) {
            $devModeKey = 'KEY: ' . $key;
        }

        $this->m_DefaultValues[$key] = $defaultValue;
        $this->m_ConfigSections[$section][$key] = array(
            "key" => $key,
            "descr" => '<section data-translation-id="SYSTEM_GLOBAL_CONFIG_KEY_' . $key . '_FULL">' . __('SYSTEM_GLOBAL_CONFIG_KEY_' . $key . '_FULL') . '</section>' . $devModeKey,
            "short" => '<section data-translation-id="SYSTEM_GLOBAL_CONFIG_KEY_' . $key . '_SHORT">' . __('SYSTEM_GLOBAL_CONFIG_KEY_' . $key . '_SHORT') . '</section>',
            "typ" => $typ,
            "defaultValue" => $defaultValue,
            'readOnly' => false,
            "hideDefault" => false, // set it to FALSE if you want to show the defaultValue or TRUE if you want to hide it
            'optionValueCallback' => NULL
        );
    }

    private function _setConfigOptionBehavior($key, $behavior, $value)
    {
        if ($this->m_LastConfigSection == NULL) {
            Log::e("Last config section not set!", "phonalisa-webinterface-config");
            return;
        }

        $section = $this->m_LastConfigSection;
        if (!array_key_exists($key, $this->m_ConfigSections[$section])) {
            Log::e("Config key " . $key . " does not exists in section " . $section . "!", "phonalisa-webinterface-config");
            return;
        }
        $this->m_ConfigSections[$section][$key][$behavior] = $value;
    }

    private function setConfigOptionReadOnly($key, $bool = true)
    {
        $this->_setConfigOptionBehavior($key, "readOnly", $bool);
    }

    private function setConfigOptionDefaultValueHidden($key, $bool = true)
    {
        $this->_setConfigOptionBehavior($key, "hideDefault", $bool);
    }

    public function setConfigOptionValueCallback($key, $function)
    {
        $this->_setConfigOptionBehavior($key, "optionValueCallback", $function);
    }

    public function getDefaultValueForKey($key)
    {
        if (!$this->m_DefaultValues) {
            $this->buildConfigSections();
        }
        return isset($this->m_DefaultValues[$key]) ? $this->m_DefaultValues[$key] : null;
    }
    /*
     *  Add a new Section with $this->addSectionSECTION_NAME. Then write your Section-options to this new function addSectionSECTION_NAME.  
     */

    private function buildConfigSections()
    {
        $this->m_ConfigSections = array();
        $this->m_ConfigSectionsHumanReadableNames = array();

        $this->addSectionLocalSettings();
        $this->addSectionDPConfig();
        $this->addSectionProvisioning();
        $this->addSectionSystem();
        $this->addSectionMessaging();
        $this->addSectionProxy();
        $this->addSectionSIP();
        $this->addSectionRTP();
    }
    /*
     * With $this->addConfigSection('SECTION_NAME', __('TRANSLATION_TAG_FOR_SECTION')); you create a new section.
     * With $this->addConfigOption('KEY_NAME', 'DEFAULT_VALUE', SysconfigValueType::TYPE); you create a new option.
     * Types for SysconfigValueType::TYPE are dropdown, text, int, bool and multi.
     * If you use a dropdown, then write the data list into a function and invoke it with $this->setConfigOptionValueCallback("KEY_NAME", "FUNCTION");. 
     * With $this->setConfigOptionReadOnly('KEY_NAME'); you can make an option read-only.
     * With $this->setConfigOptionDefaultValueHidden('NAME_PATTERN'); you can hide the default value.
     */

    private function addSectionLocalSettings()
    {
        $this->addConfigSection("LOCAL_SETTINGS", __("SYSTEM_GLOBAL_CONFIG_SECTION_TITLE_LOCAL_SETTINGS"));

        $this->addConfigOption("PHONALISA_NAME", $this->getDefaultValue("PHONALISA_NAME"), SysconfigValueType::TEXT);
        $this->addConfigOption("TIMEZONE", $this->getDefaultValue("TIMEZONE"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("TIMEZONE", "getTimeZones");
        $this->addConfigOption("USER_DATE_FORMAT", $this->getDefaultValue("USER_DATE_FORMAT"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("USER_DATE_FORMAT", "getDateFormat");
        $this->addConfigOption("USER_TIME_FORMAT", $this->getDefaultValue("USER_TIME_FORMAT"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("USER_TIME_FORMAT", "getTimeFormat");
        $this->addConfigOption("GUI_LANGS", $this->getDefaultValue("GUI_LANGS"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("GUI_LANGS", "getLanguageArray");
        $this->addConfigOption("NAME_PATTERN", $this->getDefaultValue("NAME_PATTERN"), SysconfigValueType::MULTI);
        $this->setConfigOptionDefaultValueHidden('NAME_PATTERN');
// 		$this->addConfigOption("INTL_LANG", __("de_de"), "text");
        $this->addConfigOption('DEFAULT_NEW_USER_PIN', $this->getDefaultValue("DEFAULT_NEW_USER_PIN"), SysconfigValueType::TEXT);
        $this->addConfigOption('DEFAULT_NEW_USER_PASSWORD', $this->getDefaultValue("DEFAULT_NEW_USER_PASSWORD"), SysconfigValueType::TEXT);
        if (Yii::app()->params->devMode) {
            $this->addConfigOption("TRANSLATE_MODE", $this->getDefaultValue("TRANSLATE_MODE"), SysconfigValueType::BOOL);
        }
        $this->addConfigOption("WEB_USER_MONITOR_ENABLED", $this->getDefaultValue("WEB_USER_MONITOR_ENABLED"), SysconfigValueType::BOOL);
        $this->addConfigOption("UI_THEME", $this->getDefaultValue("UI_THEME"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("UI_THEME", "getUIThemes");
    }

    private function addSectionDPConfig()
    {
        $this->addConfigSection("DP_CONFIG", __("SYSTEM_GLOBAL_CONFIG_SECTION_TITLE_DP_CONFIG"));

        $this->addConfigOption("CALL_PROTECTION_API_KEY", $this->getDefaultValue("CALL_PROTECTION_API_KEY"), SysconfigValueType::TEXT);
        $this->addConfigOption("CALL_PROTECTION_SCORE", $this->getDefaultValue("CALL_PROTECTION_SCORE"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("CALL_PROTECTION_SCORE", "getCallProtectionScores");
        $this->addConfigOption("CALL_PROTECTION_CRON_JOB", $this->getDefaultValue("CALL_PROTECTION_CRON_JOB"), SysconfigValueType::TEXT);
        $this->addConfigOption("VMBOX_ALWAYS_ASK_PIN", $this->getDefaultValue("VMBOX_ALWAYS_ASK_PIN"), SysconfigValueType::BOOL);
        $this->addConfigOption("DP_MOBILITY_ALWAYS_ASK_PIN", $this->getDefaultValue("DP_MOBILITY_ALWAYS_ASK_PIN"), SysconfigValueType::BOOL);
        $this->addConfigOption("DP_MOBILIY_PREFIX", $this->getDefaultValue("DP_MOBILIY_PREFIX"), SysconfigValueType::TEXT);
        $this->setConfigOptionReadOnly('DP_MOBILIY_PREFIX');
        $this->addConfigOption("DP_FWD_ON_PREFIX", $this->getDefaultValue("DP_FWD_ON_PREFIX"), SysconfigValueType::TEXT);
        $this->addConfigOption("DP_SPEED_DIAL_ON_PREFIX", $this->getDefaultValue("DP_SPEED_DIAL_ON_PREFIX"), SysconfigValueType::TEXT);
        $this->addConfigOption("DP_CLIR_PREFIX", $this->getDefaultValue("DP_CLIR_PREFIX"), SysconfigValueType::TEXT);
        $this->setConfigOptionReadOnly('DP_CLIR_PREFIX');
        $this->addConfigOption("DP_DND_ON_PREFIX", $this->getDefaultValue("DP_DND_ON_PREFIX"), SysconfigValueType::TEXT);
        $this->setConfigOptionReadOnly('DP_DND_ON_PREFIX');
        $this->addConfigOption("DP_EAVESDROP_PREFIX", $this->getDefaultValue("DP_EAVESDROP_PREFIX"), SysconfigValueType::TEXT);
        $this->setConfigOptionReadOnly('DP_EAVESDROP_PREFIX');
        $this->addConfigOption("DP_PICKUP_PREFIX", $this->getDefaultValue("DP_PICKUP_PREFIX"), SysconfigValueType::TEXT);
        $this->setConfigOptionReadOnly('DP_PICKUP_PREFIX');
        $this->addConfigOption("DP_QUEUE_PREFIX", $this->getDefaultValue("DP_QUEUE_PREFIX"), SysconfigValueType::TEXT);
        $this->setConfigOptionReadOnly('DP_QUEUE_PREFIX');
        $this->addConfigOption("DP_CALLGROUP_PREFIX", $this->getDefaultValue("DP_CALLGROUP_PREFIX"), SysconfigValueType::TEXT);
        $this->setConfigOptionReadOnly('DP_CALLGROUP_PREFIX');
        $this->addConfigOption("DP_VOICEMAIL_LISTENING_PREFIX", $this->getDefaultValue("DP_VOICEMAIL_LISTENING_PREFIX"), SysconfigValueType::TEXT);
        $this->addConfigOption("DP_CONFERENCE_PREFIX", $this->getDefaultValue("DP_CONFERENCE_PREFIX"), SysconfigValueType::TEXT);
        $this->addConfigOption("DP_PLAYLIST_ID", $this->getDefaultValue("DP_PLAYLIST_ID"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionDefaultValueHidden('DP_PLAYLIST_ID');
        $this->setConfigOptionValueCallback("DP_PLAYLIST_ID", "getPlaylists");

        if (PhonalisaLicenseManager::routingExternalHostEnabled()) {
            $this->addConfigOption("DP_BRANCH_PREFIX", $this->getDefaultValue("DP_BRANCH_PREFIX"), SysconfigValueType::TEXT);
        }

        $this->addConfigOption("DP_INTL_PREFIX", $this->getDefaultValue("DP_INTL_PREFIX"), SysconfigValueType::TEXT);
        $this->addConfigOption("DP_INTL_PREFIX_SHOW", $this->getDefaultValue("DP_INTL_PREFIX_SHOW"), SysconfigValueType::BOOL);

        $this->addConfigOption("DP_AUTO_DIALOUT_PREFIX", $this->getDefaultValue("DP_AUTO_DIALOUT_PREFIX"), SysconfigValueType::TEXT);
        $this->addConfigOption("DP_USE_OUTBOUND_USER_ORIGIN_TO_FORWARD", $this->getDefaultValue("DP_USE_OUTBOUND_USER_ORIGIN_TO_FORWARD"), SysconfigValueType::BOOL);
        $this->addConfigOption("DP_DIAL_TIMEOUT", $this->getDefaultValue("DP_DIAL_TIMEOUT"), SysconfigValueType::INT);
        $this->addConfigOption("DP_VMAIL_MAX_LENGTH", $this->getDefaultValue("DP_VMAIL_MAX_LENGTH"), SysconfigValueType::INT);
        $this->addConfigOption("DP_VMAIL_SILENCE_TRESHOLD", $this->getDefaultValue("DP_VMAIL_SILENCE_TRESHOLD"), SysconfigValueType::INT);
        $this->addConfigOption("DP_AGENT_BUSY_DELAY_TIME", $this->getDefaultValue("DP_AGENT_BUSY_DELAY_TIME"), SysconfigValueType::INT);
        $this->addConfigOption("DP_DROPTARGET", $this->getDefaultValue("DP_DROPTARGET"), SysconfigValueType::TEXT);
        $this->addConfigOption("DP_BEHAVIOR_ON_BUSY_USER", $this->getDefaultValue("DP_BEHAVIOR_ON_BUSY_USER"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("DP_BEHAVIOR_ON_BUSY_USER", "getBehaviorOnBusySettings");
        $this->setConfigOptionDefaultValueHidden('DP_BEHAVIOR_ON_BUSY_USER');
// 		$this->addConfigOption("INTL_ASTERISK_LANG", __("de_de"), SysconfigValueType::dropdown);
        $this->addConfigOption("DP_EMERGENCY_NUMBERS", $this->getDefaultValue("DP_EMERGENCY_NUMBERS"), SysconfigValueType::TEXT);
//        if (PhonalisaLicenseManager::routingScriptExtensionMax() !== 0) {
//            $this->addConfigOption("DP_SCRIPT_EXTENSION", $this->getDefaultValue("DP_SCRIPT_EXTENSION"), SysconfigValueType::dropdown);
//            $this->setConfigOptionValueCallback("DP_SCRIPT_EXTENSION", "getScriptExtensions");
//        }
    }

    private function addSectionProvisioning()
    {
        $this->addConfigSection("PROVISIONING", __("SYSTEM_GLOBAL_CONFIG_SECTION_TITLE_PROVISIONING"));

        $this->addConfigOption("PROV_PROTOCOL", $this->getDefaultValue("PROV_PROTOCOL"), SysconfigValueType::TEXT);
        $this->addConfigOption("PROV_HOST", $this->getDefaultValue("PROV_HOST"), SysconfigValueType::TEXT);
        $this->addConfigOption("PROV_PORT", $this->getDefaultValue("PROV_PORT"), SysconfigValueType::TEXT);
        $this->addConfigOption("PROV_PORT_SECURE", $this->getDefaultValue("PROV_PORT_SECURE"), SysconfigValueType::TEXT);
        $this->addConfigOption("PROV_BASEPATH", $this->getDefaultValue("PROV_BASEPATH"), SysconfigValueType::TEXT);
        $this->addConfigOption("SIP_HOST", $this->getDefaultValue("SIP_HOST"), SysconfigValueType::TEXT);
        $this->addConfigOption("NTP_HOST", $this->getDefaultValue("NTP_HOST"), SysconfigValueType::TEXT);

        $this->addConfigOption("INTERN_SUBNET_MASK_LIST", $this->getDefaultValue("INTERN_SUBNET_MASK_LIST"), SysconfigValueType::TEXT);

        $this->addConfigOption("DUMMY_PROV_PROFILE", $this->getDefaultValue("DUMMY_PROV_PROFILE"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("DUMMY_PROV_PROFILE", "getDummyProvisioningProfiles");
        $this->addConfigOption("DUMMY_KEY_PROFILE", $this->getDefaultValue("DUMMY_KEY_PROFILE"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("DUMMY_KEY_PROFILE", "getDummyKeyProfiles");
        $this->addConfigOption("STANDARD_EXPIRE_TIME", $this->getDefaultValue("STANDARD_EXPIRE_TIME"), SysconfigValueType::TEXT);
        $this->addConfigOption('CALL_INIT_FROM_NET', $this->getDefaultValue('CALL_INIT_FROM_NET'), SysconfigValueType::TEXT);
        $this->addConfigOption('PROV_INIT_FROM_NET', $this->getDefaultValue('PROV_INIT_FROM_NET'), SysconfigValueType::TEXT);
        $this->addConfigOption('CALL_SERVICE_AUTHTOKEN', $this->getDefaultValue('CALL_SERVICE_AUTHTOKEN'), SysconfigValueType::TEXT);
        $this->setConfigOptionDefaultValueHidden('CALL_SERVICE_AUTHTOKEN');
        $this->addConfigOption('TAPI_MULTI_USER_AUTHTOKEN', $this->getDefaultValue('TAPI_MULTI_USER_AUTHTOKEN'), SysconfigValueType::TEXT);
        $this->setConfigOptionDefaultValueHidden('TAPI_MULTI_USER_AUTHTOKEN');
        $this->addConfigOption('CDR_EXPORT_AUTHTOKEN', $this->getDefaultValue('CDR_EXPORT_AUTHTOKEN'), SysconfigValueType::TEXT);
        $this->setConfigOptionDefaultValueHidden('CDR_EXPORT_AUTHTOKEN');
        $this->addConfigOption("USER_RINGTONE_UPLOAD", $this->getDefaultValue("USER_RINGTONE_UPLOAD"), SysconfigValueType::BOOL);
        $this->addConfigOption("WEBRTC_ENABLED", $this->getDefaultValue("WEBRTC_ENABLED"), SysconfigValueType::BOOL);
        $this->addConfigOption('WEBRTC_WSS_URL', $this->getDefaultValue('WEBRTC_WSS_URL'), SysconfigValueType::TEXT);
        $this->addConfigOption("USER_RINGTONE_UPLOAD", $this->getDefaultValue("USER_RINGTONE_UPLOAD"), SysconfigValueType::BOOL);
        $this->addConfigOption('GIGASET_DECT_DEVICE_MAX', $this->getDefaultValue('GIGASET_DECT_DEVICE_MAX'), SysconfigValueType::TEXT);
        $this->addConfigOption('PROV_PHONE_ADMIN_PASSWORD', $this->getDefaultValue('PROV_PHONE_ADMIN_PASSWORD'), SysconfigValueType::PASSWORD);

    }

    private function addSectionSystem()
    {
        $this->addConfigSection("SYSTEM", __("SYSTEM_GLOBAL_CONFIG_SECTION_TITLE_SYSTEM"));

        $this->addConfigOption("LOG_LEVEL", $this->getDefaultValue("LOG_LEVEL"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("LOG_LEVEL", "getLogLevels");

        $this->addConfigOption('BACKUP_CRON_JOB', $this->getDefaultValue("BACKUP_CRON_JOB"), SysconfigValueType::TEXT);
        $this->addConfigOption('BACKUP_STORE_DAYS', $this->getDefaultValue("BACKUP_STORE_DAYS"), SysconfigValueType::INT);

        $this->addConfigOption("PASSWORD_STRENGTH", $this->getDefaultValue("PASSWORD_STRENGTH"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("PASSWORD_STRENGTH", "getPasswordStrengthLevels");

        if (app()->params->applianceMode) {
            $this->addConfigOption('SYSTEM_SSH_PUBLIC_KEYS', $this->getDefaultValue("SYSTEM_SSH_PUBLIC_KEYS"), SysconfigValueType::TEXTAREA);
            $this->addConfigOption("AUTO_SYSTEM_UPDATE", $this->getDefaultValue("AUTO_SYSTEM_UPDATE"), SysconfigValueType::BOOL);
            $this->addConfigOption('UPDATE_CRON_JOB', $this->getDefaultValue("UPDATE_CRON_JOB"), SysconfigValueType::TEXT);
        }
        $this->addConfigOption('LIFETIME_CDR', $this->getDefaultValue("LIFETIME_CDR"), SysconfigValueType::TEXT);
        $this->addConfigOption('LIFETIME_CALL_LIST', $this->getDefaultValue("LIFETIME_CALL_LIST"), SysconfigValueType::TEXT);
        $this->addConfigOption('CLEANUP_CRON_JOB', $this->getDefaultValue("CLEANUP_CRON_JOB"), SysconfigValueType::TEXT);
    }

    private function addSectionMessaging()
    {
        $this->addConfigSection("MESSAGING", __("SYSTEM_GLOBAL_CONFIG_SECTION_TITLE_MESSAGING"));

        $this->addConfigOption("JABBER_DOMAIN", $this->getDefaultValue("JABBER_DOMAIN"), SysconfigValueType::TEXT);
        $this->addConfigOption("EMAIL_SERVER", $this->getDefaultValue("EMAIL_SERVER"), SysconfigValueType::TEXT);
        $this->addConfigOption("EMAIL_SERVER_PORT", $this->getDefaultValue("EMAIL_SERVER_PORT"), SysconfigValueType::TEXT);
        $this->addConfigOption("EMAIL_AUTH_ON", $this->getDefaultValue("EMAIL_AUTH_ON"), SysconfigValueType::BOOL);
        $this->addConfigOption("EMAIL_AUTHTYPE", $this->getDefaultValue("EMAIL_AUTHTYPE"), SysconfigValueType::DROPDOWN);
        $this->setConfigOptionValueCallback("EMAIL_AUTHTYPE", "getEmailAuthTypes");
        $this->setConfigOptionDefaultValueHidden('EMAIL_AUTHTYPE');
        $this->addConfigOption("EMAIL_USER", $this->getDefaultValue("EMAIL_USER"), SysconfigValueType::TEXT);
        $this->addConfigOption("EMAIL_PASS", $this->getDefaultValue("EMAIL_PASS"), SysconfigValueType::PASSWORD);
        $this->addConfigOption("EMAIL_TLS_ON", $this->getDefaultValue("EMAIL_TLS_ON"), SysconfigValueType::BOOL);
        $this->addConfigOption("EMAIL_TLS_CHECKCERT_ON", $this->getDefaultValue("EMAIL_TLS_CHECKCERT_ON"), SysconfigValueType::BOOL);
        $this->addConfigOption("EMAIL_NAME", $this->getDefaultValue("EMAIL_NAME"), SysconfigValueType::TEXT);
        $this->addConfigOption("EMAIL_ADDRESS", $this->getDefaultValue("EMAIL_ADDRESS"), SysconfigValueType::TEXT);
        $this->addConfigOption("SEND_WELCOME_EMAIL_USER", $this->getDefaultValue("SEND_WELCOME_EMAIL_USER"), SysconfigValueType::BOOL);

        if (PhonalisaLicenseManager::faxGUIEnabled()) {
            $this->addConfigOption("FAX_HEADER_TEXT", $this->getDefaultValue("FAX_HEADER_TEXT"), SysconfigValueType::TEXT);
            $this->addConfigOption("FAX_HEADER_NUMBER", $this->getDefaultValue("FAX_HEADER_NUMBER"), SysconfigValueType::TEXT);
        }
    }

    private function addSectionProxy()
    {
        $this->addConfigSection("PROXY", __("SYSTEM_GLOBAL_CONFIG_SECTION_TITLE_PROXY"));

        $this->addConfigOption("HTTP_PROXY_IP_ADDRESS", $this->getDefaultValue("HTTP_PROXY_IP_ADDRESS"), SysconfigValueType::TEXT);
        $this->addConfigOption("HTTP_PROXY_PORT", $this->getDefaultValue("HTTP_PROXY_PORT"), SysconfigValueType::TEXT);
        $this->addConfigOption("HTTP_PROXY_USERNAME", $this->getDefaultValue("HTTP_PROXY_USERNAME"), SysconfigValueType::TEXT);
        $this->addConfigOption("HTTP_PROXY_PASSWORD", $this->getDefaultValue("HTTP_PROXY_PASSWORD"), SysconfigValueType::PASSWORD);
        $this->addConfigOption("HTTPS_PROXY_IP_ADDRESS", $this->getDefaultValue("HTTPS_PROXY_IP_ADDRESS"), SysconfigValueType::TEXT);
        $this->addConfigOption("HTTPS_PROXY_PORT", $this->getDefaultValue("HTTPS_PROXY_PORT"), SysconfigValueType::TEXT);
        $this->addConfigOption("HTTPS_PROXY_USERNAME", $this->getDefaultValue("HTTPS_PROXY_USERNAME"), SysconfigValueType::TEXT);
        $this->addConfigOption("HTTPS_PROXY_PASSWORD", $this->getDefaultValue("HTTPS_PROXY_PASSWORD"), SysconfigValueType::PASSWORD);
    }

    private function addSectionSIP()
    {
        $this->addConfigSection("SIP", __("SYSTEM_GLOBAL_CONFIG_SECTION_TITLE_SIP"));

        $this->addConfigOption("EXTERNAL_SIP_IP", $this->getDefaultValue("EXTERNAL_SIP_IP"), SysconfigValueType::TEXT);
        $this->addConfigOption("ALLOW_EXTERNAL_ANONYMOUS_CALLS", $this->getDefaultValue("ALLOW_EXTERNAL_ANONYMOUS_CALLS"), SysconfigValueType::BOOL);
        $this->addConfigOption("COMPACT_HEADERS_ENABLE", $this->getDefaultValue("COMPACT_HEADERS_ENABLE"), SysconfigValueType::BOOL);
        $this->addConfigOption("INTERNAL_SIP_LISTEN_IPS", $this->getDefaultValue("INTERNAL_SIP_LISTEN_IPS"), SysconfigValueType::TEXT);
        $this->addConfigOption("INTERNAL_SIP_PORT", $this->getDefaultValue("INTERNAL_SIP_PORT"), SysconfigValueType::TEXT);
        $this->addConfigOption("INTERNAL_TLS_PORT", $this->getDefaultValue("INTERNAL_TLS_PORT"), SysconfigValueType::TEXT);
        $this->addConfigOption("INTERNAL_SSL_ENABLE", $this->getDefaultValue("INTERNAL_SSL_ENABLE"), SysconfigValueType::BOOL);
        $this->addConfigOption("EXTERNAL_SIP_LISTEN_IP", $this->getDefaultValue("EXTERNAL_SIP_LISTEN_IP"), SysconfigValueType::TEXT);
        $this->addConfigOption("EXTERNAL_SIP_PORT", $this->getDefaultValue("EXTERNAL_SIP_PORT"), SysconfigValueType::TEXT);
        $this->addConfigOption("EXTERNAL_TLS_PORT", $this->getDefaultValue("EXTERNAL_TLS_PORT"), SysconfigValueType::TEXT);
        $this->addConfigOption("EXTERNAL_SSL_ENABLE", $this->getDefaultValue("EXTERNAL_SSL_ENABLE"), SysconfigValueType::BOOL);
        $this->addConfigOption("GLOBAL_CODEC_PREFS", $this->getDefaultValue("GLOBAL_CODEC_PREFS"), SysconfigValueType::TEXT);
        $this->addConfigOption("SIP_CAPTURE_SERVER", $this->getDefaultValue("SIP_CAPTURE_SERVER"), SysconfigValueType::TEXT);
        $this->addConfigOption("SIP_CAPTURE_INTERNAL_ENABLED", $this->getDefaultValue("SIP_CAPTURE_INTERNAL_ENABLED"), SysconfigValueType::BOOL);
        $this->addConfigOption("SIP_CAPTURE_EXTERNAL_ENABLED", $this->getDefaultValue("SIP_CAPTURE_EXTERNAL_ENABLED"), SysconfigValueType::BOOL);

    }

    private function addSectionRTP()
    {
        $this->addConfigSection("RTP", __("SYSTEM_GLOBAL_CONFIG_SECTION_TITLE_RTP"));

        $this->addConfigOption("RTP_ENABLE_ZRTP", $this->getDefaultValue("RTP_ENABLE_ZRTP"), SysconfigValueType::BOOL);
        $this->addConfigOption("RTP_ZRTP_PASSTHRU", $this->getDefaultValue("RTP_ZRTP_PASSTHRU"), SysconfigValueType::BOOL);
        $this->addConfigOption("RTP_PROXY_MEDIA_ON_ZRTP", $this->getDefaultValue("RTP_PROXY_MEDIA_ON_ZRTP"), SysconfigValueType::BOOL);

        $this->addConfigOption("RTP_ENABLE_SRTP", $this->getDefaultValue("RTP_ENABLE_SRTP"), SysconfigValueType::BOOL);

        //$this->addConfigOption("RTP_BYPASS_MEDIA", "0", SysconfigValueType::bool);

        $this->addConfigOption("RTP_START_PORT", $this->getDefaultValue("RTP_START_PORT"), SysconfigValueType::TEXT);
        $this->addConfigOption("RTP_END_PORT", $this->getDefaultValue("RTP_END_PORT"), SysconfigValueType::TEXT);
        $this->addConfigOption("EXTERNAL_RTP_IP", $this->getDefaultValue("EXTERNAL_RTP_IP"), SysconfigValueType::TEXT);
        $this->addConfigOption("CNG_VALUE", $this->getDefaultValue("CNG_VALUE"), SysconfigValueType::TEXT);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'sysconfig';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('key', 'required'),
            array('key', 'length', 'max' => 80),
            array('descr', 'length', 'max' => 255),
            array('value', 'length', 'max' => 10000),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, key, value, defaultValue', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => __('ID'),
            'key' => __('Key'),
            'value' => __('Value'),
            'descr' => __('Description'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function getSectionItems($section)
    {
        $configSections = $this->getConfigItemsArray();
        $configs = isset($configSections[$section]) ? $configSections[$section] : $configSections['LOCAL_SETTINGS'];
        $arrayDataProviderConfigs = array();

        foreach ($configs as $config) {
            $mod = new Sysconfig();
            $mod->key = $config["key"];
            $mod->descr = $config["descr"];
            $mod->defaultValue = $config["defaultValue"];
            $mod->short = $config["short"];
            $mod->typ = $config["typ"];
            $mod->hideDefault = $config["hideDefault"];
            $mod->readOnly = $config["readOnly"];
            $mod->optionValueCallback = $config["optionValueCallback"];

            $value = cfg($mod->key);

            if ($value != NULL) {
                $mod->value = $value;
            } else {
                $mod->value = $mod->defaultValue;
            }

            $arrayDataProviderConfigs[] = $mod;
        }

        $dataProvider = new CArrayDataProvider($arrayDataProviderConfigs, array(
            'id' => 'key',
            'pagination' => false,
            'sort' => array(
                'attributes' => array(
                    'key'),
            ),
        ));
        $this->changeUppercaseForUiThemes($dataProvider);
        return $dataProvider;
    }

    //NOTE: added function for backward compatibility (UI Theme names changed to lowercase) since version 6.3.4
    private function changeUppercaseForUiThemes($dataProvider)
    {
        foreach ($dataProvider->rawData as $rawData) {
            if ($rawData->key == "UI_THEME") {
                $rawData->value = strtolower($rawData->value);
            }
        }
    }

    public function getTimeFormat()
    {
        $timeformats = array(
            '12' => __('SYSTEM_GLOBAL_CONFIG_TIME_FORMAT_12H'),
            '24' => __('SYSTEM_GLOBAL_CONFIG_TIME_FORMAT_24H'),
        );
        asort($timeformats);
        return $timeformats;
    }

    public function getDateFormat()
    {
        $timeZones = array(
            'yyyy-MM-dd' => __('SYSTEM_GLOBAL_CONFIG_DATE_FORMAT_Y_M_D'),
            'dd.MM.yyyy' => __('SYSTEM_GLOBAL_CONFIG_DATE_FORMAT_D_M_Y'),
            'MM/dd/yyyy' => __('SYSTEM_GLOBAL_CONFIG_DATE_FORMAT_M_D_Y')
        );
        asort($timeZones);
        return $timeZones;
    }

    public function getNamePattern()
    {
        $namePattern = array(
            '%NONE%' => '---',
            '%TITLE%' => __('SYSTEM_GLOBAL_CONFIG_NAME_PATTERN_TITLE'),
            '%F%' => __('SYSTEM_GLOBAL_CONFIG_NAME_PATTERN_F'),
            '%FI%' => __('SYSTEM_GLOBAL_CONFIG_NAME_PATTERN_FI'),
            '%FIRSTNAME%' => __('SYSTEM_GLOBAL_CONFIG_NAME_PATTERN_FIRSTNAME'),
            '%LASTNAME%' => __('SYSTEM_GLOBAL_CONFIG_NAME_PATTERN_LASTNAME'),
            '%COMPANY%' => __('SYSTEM_GLOBAL_CONFIG_NAME_PATTERN_COMPANY'),
        );
        asort($namePattern);
        return $namePattern;
    }

    public function getPlaylists()
    {
        $data = CHtml::listData(MusicOnHold::model()->find(array(), 'name'), 'id', 'name');
        $ldata['default'] = __("DEFAULT_MOH_PLAYLIST_NAME");
        $data = array_merge($ldata, $data);
        return $data;
    }

    public function getLanguageArray()
    {
        $languages = Yii::app()->params->languages;
        asort($languages);
        return $languages;
    }

    public function getLogLevels()
    {
        $logLevels = array(
            'DEBUG' => 'DEBUG',
            'VERBOSE' => 'VERBOSE',
            'WARNING' => 'WARNING',
            'ERROR' => 'ERROR',
        );
        return $logLevels;
    }

    public function getPasswordStrengthLevels()
    {
        $passwordStrengthLevels = array(
            'NONE' => __('PASSWORD_STRENGTH_NONE'),
            'MODERATE' => __('PASSWORD_STRENGTH_MODERATE'),
            'STRONG' => __('PASSWORD_STRENGTH_STRONG'),
            'PARANOID' => __('PASSWORD_STRENGTH_PARANOID'),
        );
        return $passwordStrengthLevels;
    }

    public function getUIThemes()
    {
        $themes = Yii::app()->params->themes;
        asort($themes);
        return $themes;
    }

    /**
     * Returns a nested array of timzones by continant. Suitable for input into
     */
    public static function getTimeZones()
    {
        return array(
            'Africa' => array(
                'Africa/Casablanca' => '[GMT+00:00] Western European Time (Africa/Casablanca)',
                'Africa/Algiers' => '[GMT+01:00] Central European Time (Africa/Algiers)',
                'Africa/Bangui' => '[GMT+01:00] Western African Time (Africa/Bangui)',
                'Africa/Windhoek' => '[GMT+01:00] Western African Time (Africa/Windhoek)',
                'Africa/Tripoli' => '[GMT+02:00] Eastern European Time (Africa/Tripoli)',
                'Africa/Johannesburg' => '[GMT+02:00] South Africa Standard Time (Africa/Johannesburg)',
                'Africa/Dar_es_Salaam' => '[GMT+03:00] Eastern African Time (EAT)',
            ),
            'America (North & South)' => array(
                'America/Scoresbysund' => '[GMT-01:00] Eastern Greenland Time (America/Scoresbysund)',
                'America/Noronha' => '[GMT-02:00] Fernando de Noronha Time (America/Noronha)',
                'America/Argentina/Buenos_Aires' => '[GMT-03:00] Argentine Time (AGT)',
                'America/Belem' => '[GMT-03:00] Brazil Time (America/Belem)',
                'America/Sao_Paulo' => '[GMT-03:00] Brazil Time (BET)',
                'America/Cayenne' => '[GMT-03:00] French Guiana Time (America/Cayenne)',
                'America/Miquelon' => '[GMT-03:00] Pierre & Miquelon Standard Time (America/Miquelon)',
                'America/Paramaribo' => '[GMT-03:00] Suriname Time (America/Paramaribo)',
                'America/Montevideo' => '[GMT-03:00] Uruguay Time (America/Montevideo)',
                'America/Godthab' => '[GMT-03:00] Western Greenland Time (America/Godthab)',
                'America/St_Johns' => '[GMT-03:30] Newfoundland Standard Time (America/St Johns)',
                'America/Cuiaba' => '[GMT-04:00] Amazon Standard Time (America/Cuiaba)',
                'America/Glace_Bay' => '[GMT-04:00] Atlantic Standard Time (America/Glace Bay)',
                'America/La_Paz' => '[GMT-04:00] Bolivia Time (America/La Paz)',
                'America/Santiago' => '[GMT-04:00] Chile Time (America/Santiago)',
                'America/Guyana' => '[GMT-04:00] Guyana Time (America/Guyana)',
                'America/Asuncion' => '[GMT-04:00] Paraguay Time (America/Asuncion)',
                'America/Caracas' => '[GMT-04:00] Venezuela Time (America/Caracas)',
                'America/Porto_Acre' => '[GMT-05:00] Acre Time (America/Porto Acre)',
                'America/Havana' => '[GMT-05:00] Central Standard Time (America/Havana)',
                'America/Bogota' => '[GMT-05:00] Colombia Time (America/Bogota)',
                'America/Jamaica' => '[GMT-05:00] Eastern Standard Time (America/Jamaica)',
                'America/Indianapolis' => '[GMT-05:00] Eastern Standard Time (US/East-Indiana)',
                'America/Guayaquil' => '[GMT-05:00] Ecuador Time (America/Guayaquil)',
                'America/Lima' => '[GMT-05:00] Peru Time (America/Lima)',
                'America/El_Salvador' => '[GMT-06:00] Central Standard Time (America/El Salvador)',
                'America/Regina' => '[GMT-06:00] Central Standard Time (Canada/Saskatchewan)',
                'America/Chicago' => '[GMT-06:00] Central Standard Time (US & Canada)',
                'America/Phoenix' => '[GMT-07:00] Mountain Standard Time (US/Arizona)',
                'America/Los_Angeles' => '[GMT-08:00] Pacific Standard Time (US & Canada)',
                'America/Anchorage' => '[GMT-09:00] Alaska Standard Time (AST)',
                'America/Adak' => '[GMT-10:00] Hawaii-Aleutian Standard Time (America/Adak)',
            ),
            'Antarctica' => array(
                'Antarctica/Syowa' => '[GMT+03:00] Syowa Time (Antarctica/Syowa)',
                'Antarctica/Mawson' => '[GMT+06:00] Mawson Time (Antarctica/Mawson)',
                'Antarctica/Vostok' => '[GMT+06:00] Vostok Time (Antarctica/Vostok)',
                'Antarctica/Davis' => '[GMT+07:00] Davis Time (Antarctica/Davis)',
                'Antarctica/DumontDUrville' => '[GMT+10:00] Dumont-d\'Urville Time (Antarctica/DumontDUrville)',
                'Antarctica/Rothera' => '[GMT-03:00] Rothera Time (Antarctica/Rothera)',
            ),
            'Asia' => array(
                'Asia/Jerusalem' => '[GMT+02:00] Israel Standard Time (Asia/Jerusalem)',
                'Asia/Baghdad' => '[GMT+03:00] Arabia Standard Time (Asia/Baghdad)',
                'Asia/Kuwait' => '[GMT+03:00] Arabia Standard Time (Asia/Kuwait)',
                'Asia/Tehran' => '[GMT+03:30] Iran Standard Time (Asia/Tehran)',
                'Asia/Aqtau' => '[GMT+04:00] Aqtau Time (Asia/Aqtau)',
                'Asia/Yerevan' => '[GMT+04:00] Armenia Time (NET)',
                'Asia/Baku' => '[GMT+04:00] Azerbaijan Time (Asia/Baku)',
                'Asia/Tbilisi' => '[GMT+04:00] Georgia Time (Asia/Tbilisi)',
                'Asia/Dubai' => '[GMT+04:00] Gulf Standard Time (Asia/Dubai)',
                'Asia/Oral' => '[GMT+04:00] Oral Time (Asia/Oral)',
                'Asia/Kabul' => '[GMT+04:30] Afghanistan Time (Asia/Kabul)',
                'Asia/Aqtobe' => '[GMT+05:00] Aqtobe Time (Asia/Aqtobe)',
                'Asia/Bishkek' => '[GMT+05:00] Kirgizstan Time (Asia/Bishkek)',
                'Asia/Karachi' => '[GMT+05:00] Pakistan Time (PLT)',
                'Asia/Dushanbe' => '[GMT+05:00] Tajikistan Time (Asia/Dushanbe)',
                'Asia/Ashgabat' => '[GMT+05:00] Turkmenistan Time (Asia/Ashgabat)',
                'Asia/Tashkent' => '[GMT+05:00] Uzbekistan Time (Asia/Tashkent)',
                'Asia/Yekaterinburg' => '[GMT+05:00] Yekaterinburg Time (Asia/Yekaterinburg)',
                'Asia/Katmandu' => '[GMT+05:45] Nepal Time (Asia/Katmandu)',
                'Asia/Almaty' => '[GMT+06:00] Alma-Ata Time (Asia/Almaty)',
                'Asia/Thimbu' => '[GMT+06:00] Bhutan Time (Asia/Thimbu)',
                'Asia/Novosibirsk' => '[GMT+06:00] Novosibirsk Time (Asia/Novosibirsk)',
                'Asia/Omsk' => '[GMT+06:00] Omsk Time (Asia/Omsk)',
                'Asia/Qyzylorda' => '[GMT+06:00] Qyzylorda Time (Asia/Qyzylorda)',
                'Asia/Colombo' => '[GMT+06:00] Sri Lanka Time (Asia/Colombo)',
                'Asia/Rangoon' => '[GMT+06:30] Myanmar Time (Asia/Rangoon)',
                'Asia/Hovd' => '[GMT+07:00] Hovd Time (Asia/Hovd)',
                'Asia/Krasnoyarsk' => '[GMT+07:00] Krasnoyarsk Time (Asia/Krasnoyarsk)',
                'Asia/Jakarta' => '[GMT+07:00] West Indonesia Time (Asia/Jakarta)',
                'Asia/Brunei' => '[GMT+08:00] Brunei Time (Asia/Brunei)',
                'Asia/Makassar' => '[GMT+08:00] Central Indonesia Time (Asia/Makassar)',
                'Asia/Hong_Kong' => '[GMT+08:00] Hong Kong Time (Asia/Hong Kong)',
                'Asia/Irkutsk' => '[GMT+08:00] Irkutsk Time (Asia/Irkutsk)',
                'Asia/Kuala_Lumpur' => '[GMT+08:00] Malaysia Time (Asia/Kuala Lumpur)',
                'Asia/Manila' => '[GMT+08:00] Philippines Time (Asia/Manila)',
                'Asia/Shanghai' => '[GMT+08:00] Shanghai Time (Asia/Shanghai)',
                'Asia/Singapore' => '[GMT+08:00] Singapore Time (Asia/Singapore)',
                'Asia/Taipei' => '[GMT+08:00] Taipei Time (Asia/Taipei)',
                'Asia/Ulaanbaatar' => '[GMT+08:00] Ulaanbaatar Time (Asia/Ulaanbaatar)',
                'Asia/Choibalsan' => '[GMT+09:00] Choibalsan Time (Asia/Choibalsan)',
                'Asia/Jayapura' => '[GMT+09:00] East Indonesia Time (Asia/Jayapura)',
                'Asia/Dili' => '[GMT+09:00] East Timor Time (Asia/Dili)',
                'Asia/Tokyo' => '[GMT+09:00] Japan Standard Time (JST)',
                'Asia/Seoul' => '[GMT+09:00] Korea Standard Time (Asia/Seoul)',
                'Asia/Yakutsk' => '[GMT+09:00] Yakutsk Time (Asia/Yakutsk)',
                'Asia/Sakhalin' => '[GMT+10:00] Sakhalin Time (Asia/Sakhalin)',
                'Asia/Vladivostok' => '[GMT+10:00] Vladivostok Time (Asia/Vladivostok)',
                'Asia/Magadan' => '[GMT+11:00] Magadan Time (Asia/Magadan)',
                'Asia/Anadyr' => '[GMT+12:00] Anadyr Time (Asia/Anadyr)',
                'Asia/Kamchatka' => '[GMT+12:00] Petropavlovsk-Kamchatski Time (Asia/Kamchatka)',
            ),
            'Atlantic Ocean' => array(
                'Atlantic/Jan_Mayen' => '[GMT+01:00] Eastern Greenland Time (Atlantic/Jan Mayen)',
                'Atlantic/Azores' => '[GMT-01:00] Azores Time (Atlantic/Azores)',
                'Atlantic/Cape_Verde' => '[GMT-01:00] Cape Verde Time (Atlantic/Cape Verde)',
                'Atlantic/South_Georgia' => '[GMT-02:00] South Georgia Standard Time (Atlantic/South Georgia)',
                'Atlantic/Bermuda' => '[GMT-04:00] Atlantic Standard Time (Atlantic/Bermuda)',
                'Atlantic/Stanley' => '[GMT-04:00] Falkland Is. Time (Atlantic/Stanley)',
            ),
            'Australia' => array(
                'Australia/Perth' => '[GMT+08:00] Western Standard Time (Australia) (Australia/Perth)',
                'Australia/Broken_Hill' => '[GMT+09:30] Central Standard Time (Australia/Broken Hill)',
                'Australia/Darwin' => '[GMT+09:30] Central Standard Time (Northern Territory) (ACT)',
                'Australia/Adelaide' => '[GMT+09:30] Central Standard Time (South Australia) (Australia/Adelaide)',
                'Australia/Sydney' => '[GMT+10:00] Eastern Standard Time (New South Wales) (Australia/Sydney)',
                'Australia/Brisbane' => '[GMT+10:00] Eastern Standard Time (Queensland) (Australia/Brisbane)',
                'Australia/Hobart' => '[GMT+10:00] Eastern Standard Time (Tasmania) (Australia/Hobart)',
                'Australia/Melbourne' => '[GMT+10:00] Eastern Standard Time (Victoria) (Australia/Melbourne)',
                'Australia/Lord_Howe' => '[GMT+10:30] Load Howe Standard Time (Australia/Lord Howe)',
            ),
            'Europe' => array(
                'Europe/Lisbon' => '[GMT+00:00] Western European Time (Europe/Lisbon)',
                'Europe/Berlin' => '[GMT+01:00] Central European Time (Europe/Berlin)',
                'Europe/Istanbul' => '[GMT+02:00] Eastern European Time (Europe/Istanbul)',
                'Europe/Moscow' => '[GMT+03:00] Moscow Standard Time (Europe/Moscow)',
                'Europe/Samara' => '[GMT+04:00] Samara Time (Europe/Samara)',
            ),
            'Indian' => array(
                'Indian/Mauritius' => '[GMT+04:00] Mauritius Time (Indian/Mauritius)',
                'Indian/Reunion' => '[GMT+04:00] Reunion Time (Indian/Reunion)',
                'Indian/Mahe' => '[GMT+04:00] Seychelles Time (Indian/Mahe)',
                'Indian/Kerguelen' => '[GMT+05:00] French Southern & Antarctic Lands Time (Indian/Kerguelen)',
                'Indian/Maldives' => '[GMT+05:00] Maldives Time (Indian/Maldives)',
                'Indian/Chagos' => '[GMT+06:00] Indian Ocean Territory Time (Indian/Chagos)',
                'Indian/Cocos' => '[GMT+06:30] Cocos Islands Time (Indian/Cocos)',
                'Indian/Christmas' => '[GMT+07:00] Christmas Island Time (Indian/Christmas)',
            ),
            'Pacific Ocean' => array(
                'Pacific/Palau' => '[GMT+09:00] Palau Time (Pacific/Palau)',
                'Pacific/Guam' => '[GMT+10:00] Chamorro Standard Time (Pacific/Guam)',
                'Pacific/Port_Moresby' => '[GMT+10:00] Papua New Guinea Time (Pacific/Port Moresby)',
                'Pacific/Truk' => '[GMT+10:00] Truk Time (Pacific/Truk)',
                'Pacific/Yap' => '[GMT+10:00] Yap Time (Pacific/Yap)',
                'Pacific/Kosrae' => '[GMT+11:00] Kosrae Time (Pacific/Kosrae)',
                'Pacific/Noumea' => '[GMT+11:00] New Caledonia Time (Pacific/Noumea)',
                'Pacific/Ponape' => '[GMT+11:00] Ponape Time (Pacific/Ponape)',
                'Pacific/Efate' => '[GMT+11:00] Vanuatu Time (Pacific/Efate)',
                'Pacific/Norfolk' => '[GMT+11:30] Norfolk Time (Pacific/Norfolk)',
                'Pacific/Fiji' => '[GMT+12:00] Fiji Time (Pacific/Fiji)',
                'Pacific/Tarawa' => '[GMT+12:00] Gilbert Is. Time (Pacific/Tarawa)',
                'Pacific/Majuro' => '[GMT+12:00] Marshall Islands Time (Pacific/Majuro)',
                'Pacific/Nauru' => '[GMT+12:00] Nauru Time (Pacific/Nauru)',
                'Pacific/Auckland' => '[GMT+12:00] New Zealand Standard Time (Pacific/Auckland)',
                'Pacific/Funafuti' => '[GMT+12:00] Tuvalu Time (Pacific/Funafuti)',
                'Pacific/Wake' => '[GMT+12:00] Wake Time (Pacific/Wake)',
                'Pacific/Wallis' => '[GMT+12:00] Wallis & Futuna Time (Pacific/Wallis)',
                'Pacific/Chatham' => '[GMT+12:45] Chatham Standard Time (Pacific/Chatham)',
                'Pacific/Enderbury' => '[GMT+13:00] Phoenix Is. Time (Pacific/Enderbury)',
                'Pacific/Tongatapu' => '[GMT+13:00] Tonga Time (Pacific/Tongatapu)',
                'Pacific/Kiritimati' => '[GMT+14:00] Line Is. Time (Pacific/Kiritimati)',
                'Pacific/Easter' => '[GMT-06:00] Easter Is. Time (Pacific/Easter)',
                'Pacific/Galapagos' => '[GMT-06:00] Galapagos Time (Pacific/Galapagos)',
                'Pacific/Pitcairn' => '[GMT-08:00] Pitcairn Standard Time (Pacific/Pitcairn)',
                'Pacific/Gambier' => '[GMT-09:00] Gambier Time (Pacific/Gambier)',
                'Pacific/Marquesas' => '[GMT-09:30] Marquesas Time (Pacific/Marquesas)',
                'Pacific/Rarotonga' => '[GMT-10:00] Cook Is. Time (Pacific/Rarotonga)',
                'Pacific/Tahiti' => '[GMT-10:00] Tahiti Time (Pacific/Tahiti)',
                'Pacific/Fakaofo' => '[GMT-10:00] Tokelau Time (Pacific/Fakaofo)',
                'Pacific/Niue' => '[GMT-11:00] Niue Time (Pacific/Niue)',
                'Pacific/Apia' => '[GMT-11:00] West Samoa Time (MIT)',
            ),
        );
    }

    public function getEmailAuthTypes()
    {
        return array(
            'AUTH PLAIN',
            'AUTH LOGIN',
        );
    }

    public function beforeSave()
    {
        $this->value = str_replace('"', '\"', $this->value);
        if ($this->key == 'CALL_PROTECTION_API_KEY' && $this->value != '') {
            $this->setCallProtectionCronJobRule();
        }
        return parent::beforeSave();
    }

    private function setCallProtectionCronJobRule()
    {
        if ($this->value != cfg('CALL_PROTECTION_API_KEY') && empty(cfg('CALL_PROTECTION_CRON_JOB'))) {
            $cronRule = mt_rand(0, 59) . " 22 * * *";
            setCfg('CALL_PROTECTION_CRON_JOB', $cronRule);
        }
    }

    public function afterSave()
    {
        PhonalisaConfig::updateSettingsCacheFile();
        return parent::afterSave();
    }

    private function getDefaultValue($key)
    {
        $defaultValue = $this->getDefaultValuesArray();
        $result = $defaultValue[$key];

        $globalConfigDefault = Yii::app()->params->globalConfigDefault;
        if (is_array($globalConfigDefault)) {
            $replacedArray = array_replace($defaultValue, $globalConfigDefault);
            $result = $replacedArray[$key];
        }

        return $result;
    }

    private function getDefaultValuesArray()
    {
        return array(
            //LOCAL_SETTINGS
            "PHONALISA_NAME" => "Phonalisa Telefonanlage",
            "TIMEZONE" => "Europe/Berlin",
            "USER_DATE_FORMAT" => "dd.MM.yyyy",
            "USER_TIME_FORMAT" => "24",
            "GUI_LANGS" => "en_us",
            "NAME_PATTERN" => "%TITLE%\n.\n%FIRSTNAME%\n \n%LASTNAME%\n-\n%COMPANY%",
            "DEFAULT_NEW_USER_PIN" => "",
            "DEFAULT_NEW_USER_PASSWORD" => "",
            "TRANSLATE_MODE" => '0',
            "WEB_USER_MONITOR_ENABLED" => '1',
            "UI_THEME" => "default",
            "BACKUP_CRON_JOB" => '',
            "BACKUP_STORE_DAYS" => '0',
            //DP_CONFIG
            "CALL_PROTECTION_API_KEY" => '',
            "CALL_PROTECTION_SCORE" => '7',
            "VMBOX_ALWAYS_ASK_PIN" => "0",
            "DP_MOBILITY_ALWAYS_ASK_PIN" => "1",
            "DP_MOBILIY_PREFIX" => "*0",
            "DP_FWD_ON_PREFIX" => "*2",
            "DP_SPEED_DIAL_ON_PREFIX" => "#",
            "DP_CLIR_PREFIX" => "*31",
            "DP_DND_ON_PREFIX" => "*43",
            "DP_EAVESDROP_PREFIX" => "*86*",
            "DP_PICKUP_PREFIX" => "*81*",
            "DP_QUEUE_PREFIX" => "*5",
            "DP_CALLGROUP_PREFIX" => "*6",
            "DP_VOICEMAIL_LISTENING_PREFIX" => "80",
            "DP_CONFERENCE_PREFIX" => "88",
            "DP_PLAYLIST_ID" => "default",
            "DP_BRANCH_PREFIX" => "",
            "DP_INTL_PREFIX" => "0049",
            "DP_INTL_PREFIX_SHOW" => "0",
            "DP_AUTO_DIALOUT_PREFIX" => "",
            "DP_USE_OUTBOUND_USER_ORIGIN_TO_FORWARD" => "0",
            "DP_DIAL_TIMEOUT" => "45",
            "DP_VMAIL_MAX_LENGTH" => "360",
            "DP_VMAIL_SILENCE_TRESHOLD" => "200",
            "DP_AGENT_BUSY_DELAY_TIME" => "60",
            "DP_DROPTARGET" => "",
            "DP_EMERGENCY_NUMBERS" => '110,112,911',
            "DP_SCRIPT_EXTENSION" => "SCRIPT_EXTENSION_EMPTY",
            "USER_RINGTONE_UPLOAD" => "1",
            //PROVISIONING
            "PROV_PROTOCOL" => "http://",
            "PROV_HOST" => "192.168.1.130",
            "PROV_PORT" => "",
            "PROV_PORT_SECURE" => "",
            "PROV_BASEPATH" => "/",
            "PROV_PHONE_ADMIN_PASSWORD" => "admin",
            "SIP_HOST" => "192.168.1.130",
            "NTP_HOST" => "192.168.1.130",
            "INTERN_SUBNET_MASK_LIST" => "",
            "DP_BEHAVIOR_ON_BUSY_USER" => "",
            "DUMMY_PROV_PROFILE" => "",
            "DUMMY_KEY_PROFILE" => "",
            "STANDARD_EXPIRE_TIME" => "3000-3600",
            "CALL_INIT_FROM_NET" => "",
            "PROV_INIT_FROM_NET" => '',
            "CALL_SERVICE_AUTHTOKEN" => '',
            "TAPI_MULTI_USER_AUTHTOKEN" => '',
            "CDR_EXPORT_AUTHTOKEN" => '',
            "WEBRTC_ENABLED" => '0',
            "WEBRTC_WSS_URL" => "",
            "CALL_SERVICE_AUTHTOKEN" => '',
            'GIGASET_DECT_DEVICE_MAX' => '10',
            //SYSTEM
            "LOG_LEVEL" => "VERBOSE",
            "FIREWALL_ENABLED" => '1',
            "UPDATE_CRON_JOB" => '',
            "AUTO_SYSTEM_UPDATE" => '1',
            "LIFETIME_CDR" => '365', // 365
            "LIFETIME_CALL_LIST" => '60', // 60
            "CLEANUP_CRON_JOB" => '',
            'CALL_PROTECTION_CRON_JOB' => '',
            // Security
            "PASSWORD_STRENGTH" => "STRONG",
            //MESSAGING
            "JABBER_DOMAIN" => "phonalisa.local",
            "EMAIL_SERVER" => "smtp.phonalisa.de",
            "EMAIL_SERVER_PORT" => "25",
            "EMAIL_AUTH_ON" => "1",
            "EMAIL_AUTHTYPE" => "0",
            "EMAIL_USER" => "",
            "EMAIL_PASS" => "",
            "EMAIL_TLS_ON" => "1",
            "EMAIL_TLS_CHECKCERT_ON" => "0",
            "EMAIL_NAME" => "Phonalisa Telefonanlage",
            "EMAIL_ADDRESS" => "noreply@phonalisa.de",
            "SEND_WELCOME_EMAIL_USER" => "1",
            "FAX_HEADER_TEXT" => "",
            "FAX_HEADER_NUMBER" => "",
            //PROXY
            "HTTP_PROXY_IP_ADDRESS" => "",
            "HTTP_PROXY_PORT" => "",
            "HTTP_PROXY_USERNAME" => "",
            "HTTP_PROXY_PASSWORD" => "",
            "HTTPS_PROXY_IP_ADDRESS" => "",
            "HTTPS_PROXY_PORT" => "",
            "HTTPS_PROXY_USERNAME" => "",
            "HTTPS_PROXY_PASSWORD" => "",
            //SIP
            "EXTERNAL_SIP_IP" => "auto-nat",
            "ALLOW_EXTERNAL_ANONYMOUS_CALLS" => "0",
            "COMPACT_HEADERS_ENABLE" => "0",
            "INTERNAL_SIP_LISTEN_IPS" => "",
            "INTERNAL_SIP_PORT" => "5060",
            "INTERNAL_TLS_PORT" => "5061",
            "INTERNAL_SSL_ENABLE" => "0",
            "EXTERNAL_SIP_LISTEN_IP" => "",
            "EXTERNAL_SIP_PORT" => "5080",
            "EXTERNAL_TLS_PORT" => "5081",
            "EXTERNAL_SSL_ENABLE" => "0",
            "GLOBAL_CODEC_PREFS" => "G722,PCMA,PCMU,GSM",
            //RTP
            "RTP_ENABLE_ZRTP" => "0",
            "RTP_ZRTP_PASSTHRU" => "0",
            "RTP_PROXY_MEDIA_ON_ZRTP" => "0",
            "RTP_ENABLE_SRTP" => "0",
            "RTP_START_PORT" => "16384",
            "RTP_END_PORT" => "32768",
            "EXTERNAL_RTP_IP" => "auto-nat",
            "SYSTEM_SSH_PUBLIC_KEYS" => "",
            "CNG_VALUE" => '',
            "SIP_CAPTURE_SERVER" => '',
            "SIP_CAPTURE_INTERNAL_ENABLED" => "0",
            "SIP_CAPTURE_EXTERNAL_ENABLED" => "0",
        );
    }

    public function getDummyProvisioningProfiles()
    {
        $lData = array('' => __('DUMMY_PROFILE_EMPTY'));
        $listData = CHtml::listData(ProvisioningProfile::model()->find(array(), 'name'), 'id', 'name');
        return array_merge($lData, $listData);
    }

    public function getDummyKeyProfiles()
    {
        $lData = array('' => __('DUMMY_PROFILE_EMPTY'));
        $listData = CHtml::listData(ProvisioningKeyProfile::model()->find(array(), 'name'), 'id', 'name');
        return array_merge($lData, $listData);
    }

    public function getScriptExtensions()
    {
        return ScriptExtension::model()->listData;
    }

    public function getBehaviorOnBusySettings()
    {
        return array(
            '' => __('SYSTEM_GLOBAL_BEHAVIOR_ON_BUSY_USER_HANGUP_SEND_BUSY'),
            'ACCEPT_SEND_BUSY' => __('SYSTEM_GLOBAL_BEHAVIOR_ON_BUSY_USER_ACCEPT_SEND_BUSY')
                //'REDIRECT_TO_DROPTARGET' => __('SYSTEM_GLOBAL_BEHAVIOR_ON_BUSY_USER_REDIRECT_TO_DROPTARGET'),
                //__('SYSTEM_GLOBAL_BEHAVIOR_ON_BUSY_USER_PLAY_ANNOUNCEMENT') => $this->getSystemAnnouncement()
        );
    }

    protected function getSystemAnnouncement()
    {
        $audioFileList = AudioFile::model()->getAudioFileList();
        unset($audioFileList['']);
        return $audioFileList;
    }

    public function getTranslationForDefaultValue($defaultValue)
    {
        $passwordStrength = $this->getPasswordStrengthLevels();
        $dateFormat = $this->getDateFormat();
        $language = $this->getLanguageArray();
        $timeZones = $this->getTimeZones();
        $timeFormat = $this->getTimeFormat();
        $uiThemes = $this->getUIThemes();
        $logLevels = $this->getLogLevels();

        $translations = array(
            'STRONG' => $passwordStrength['STRONG'],
            'DUMMY_PROFILE_EMPTY' => __('DUMMY_PROFILE_EMPTY'),
            'SCRIPT_EXTENSION_EMPTY' => __('SCRIPT_EXTENSION_EMPTY'),
            'dd.MM.yyyy' => $dateFormat['dd.MM.yyyy'],
            'en_us' => $language['en_us'],
            'Europe/Berlin' => $timeZones['Europe']['Europe/Berlin'],
            '24' => $timeFormat['24'],
            'default' => $uiThemes['default'],
            'VERBOSE' => $logLevels['VERBOSE']
        );

        if (isset($translations[$defaultValue])) {
            $defaultValue = $translations[$defaultValue];
        }
        return $defaultValue;
    }

    public function getCallProtectionScores()
    {
        $scores = array();
        for ($i = 1; $i <= 9; $i++) {
            $scores[$i] = $i;
        }
        return $scores;
    }
}
