<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/ //
//$Id: CommonController.php, v 1.0 2011/06/14 20:52:11
//
class CommonController {
    public $assignedDateFormat;
    public $ObjView;
    public $ObjSession;
    public $ObjCookie;
    //Admin User Details
    public $manageUserID;
    public $mangeUserTypeID;
    public $manageUserName;
    //Privilege
    public $fullPrivilegeList;
    public $userPrivilegeList;
 
    public $langArray;
    public $viewpublicpath;   
    public $defaultLogoImg; 

    //CONSTRUCTOR
    public function __construct($ObjView, $ObjSession, $ObjCookie) {
        $this->ObjView         = $ObjView;
        $this->ObjSession      = $ObjSession;
        $this->ObjCookie       = $ObjCookie;
        //Admin User Details
        $manageSessionID       = $this->ObjSession->getSessionID();
        $this->manageUserID    = $this->ObjSession->getSession("MANAGE_USER_ID" . $manageSessionID); //1; 
        
        $this->mangeUserTypeID = $this->ObjSession->getSession("MANAGE_USER_TYPE_ID" . $manageSessionID); //1;
        $this->manageUserName  = $this->ObjSession->getSession("MANAGE_USER_NAME" . $manageSessionID); //"Mr Bibu Babu";
        $this->objCache        = new Cache("file");
        $this->setCommonSettings();
        $this->isAjax = $this->isAjaxRequest();
        $this->setLanguage();
        $this->checkSettingsTimeout();
        $this->setHistoryURL();
        $this->setManageAccess();
        $this->setCurrencyFormatPlugin();
        $this->setAddressFormatPlugin();
        $this->setCustomDateWithFormat();
        if (!$this->isAjax) {
            $this->setManageRoles();
            $this->setMenu();
            $this->setTopNotificationCount();
            //For tracking Admin User's Activities
            //@Usage=>Analytics Module
            if (__ANALYTICS_MODULE) {
                $this->logTracking();
            }
        }
    }
    private function setCommonSettings() { 
        //Set Time zone : Mysql & PHP Server
        /*
        setServerSessionTimeZone	- 	To set the Mysql server timezone 
        date_default_timezone_set	-	To set the PHP server timezone 
        */
        $ObjTimeZone     = new TimezoneModel();
        $defaultTimezone = $this->getSettingValue('site_settings', 'default_timezone');
       
        $global_http_url       = rtrim($this->getSettingValue('site_settings', 'global_http_url'), "/");
        $resTimeZone     = $ObjTimeZone->getTimezoneDetails($defaultTimezone, 'timeZoneDetail,timeZoneAbbreviation,timeZoneDiff');
        date_default_timezone_set($resTimeZone['timeZoneDetail']);
        $ObjTimeZone->setServerSessionTimeZone('', $resTimeZone['timeZoneDiff']);
        //CDN Public Path
        $uploadImagesTo = $this->getSettingValue('site_settings', 'upload_images_to');
        if ($uploadImagesTo == 'amazon') {
            $cdnBaseUrlImage = $this->getSettingValue('site_settings', 'cdn_baseurl_image');
        } else if ($uploadImagesTo == 'rackspace') {
            $enableSSLCheckout = $this->getSettingValue('site_settings', 'enable_ssl_checkout');
            $cdnBaseUrlImage   = ($enableSSLCheckout == 'Enable') ? $this->getSettingValue('site_settings', 'rackspace_cdn_base_httpsurl_image') : $this->getSettingValue('site_settings', 'rackspace_cdn_base_httpurl_image');
        }
        if (isset($cdnBaseUrlImage) && $cdnBaseUrlImage != "") {

            $this->ObjView->assign("view_public_path", rtrim($cdnBaseUrlImage, '/') . '/' . __DIR_PUBLIC);           
            $this->viewpublicpath= rtrim($cdnBaseUrlImage, '/') . '/' . __DIR_PUBLIC; 
        } else {
            $this->ObjView->assign("view_public_path", $global_http_url . '/' . __DIR_PUBLIC);       
            $this->viewpublicpath= $global_http_url. '/' . __DIR_PUBLIC; 
        }
        //Set Date Time Format For Date Picker 
        $dateFormat = $this->getSettingValue('site_settings', 'date_format');
        $timeFormat = $this->getSettingValue('site_settings', 'time_format');
        switch ($dateFormat) {
            case '%Y-%m-%d':
                $datePickerDateFormat = 'yy-mm-dd';
                break;
            case '%m/%d/%Y':
                $datePickerDateFormat = 'mm/dd/yy';
                break;
            case '%d-%m-%Y':
                $datePickerDateFormat = 'dd-mm-yy';
                break;
            default:
                $datePickerDateFormat = 'mm/dd/yy';
        }
        //Set Main Caption
        $siteName              = trim($this->getSettingValue('site_settings', 'site_name'));
        $siteNameStrPos        = strpos($siteName, " ");
        $siteNameStrLeft       = substr(stripslashes($siteName), 0, $siteNameStrPos);
        $siteNameStrRight      = substr(stripslashes($siteName), $siteNameStrPos);
        $viewCommonLogoCaption = $siteNameStrLeft . "<em>" . $siteNameStrRight . "</em>";
        $settingsTaxApplicable         = $this->getSettingValue('product_cart_settings', 'tax_applicable');
        $this->ObjView->assign("view_common_site_name", $siteName);
        $this->ObjView->assign("global_http_url", $global_http_url);
        $this->ObjView->assign("view_common_logo_caption", $viewCommonLogoCaption);
        $this->ObjView->assign('settingsDateFormat', $dateFormat);
        $this->ObjView->assign('settingsTimeFormat', $timeFormat);
        $this->ObjView->assign("datePickerDateFormat", $datePickerDateFormat);
        $this->ObjView->assign("date_format", $dateFormat);
        $this->ObjView->assign("common_admin_timezone", $resTimeZone['timeZoneAbbreviation']);
        $this->ObjView->assign("timeZoneAbbreviation", $resTimeZone['timeZoneAbbreviation']);
        $this->ObjView->assign("time_format", $timeFormat);
        $this->ObjView->assign("commonSiteName", $siteName);
        $this->ObjView->assign('settingsTaxApplicable', $settingsTaxApplicable);
        $this->ObjView->assign("commonYear", date("Y"));
    }
    //FUNCTION to set the top section header notification counters
    private function setTopNotificationCount() {
        if ($this->manageUserID > 0) {
            $this->ObjView->assign("profileEditPrivilege", $this->hasPrivilege('adminuser/profileedit/'));
        }
    }
    //TO SET MANAGE ACCESS
    public function setManageAccess() {
        $managePublicPages = explode(',', MANAGE_PUBLIC_ACCESS_PAGES);
        $manageUserID      = $this->manageUserID;
        $mangeUserTypeID   = $this->mangeUserTypeID;
        if ($manageUserID) {
            $ObjAdminusers = new AdminuserModel();
            //Check Active Admin/Role
            if (!$ObjAdminusers->checkAdminUser($manageUserID, $mangeUserTypeID)) {
                if (strtolower($this->ObjView->_controller) == 'adminuser' && strtolower($this->ObjView->_action) != 'logout') {
                    $this->setRedirect("adminuser/logout/");
                } elseif (strtolower($this->ObjView->_controller) != 'adminuser' && strtolower($this->ObjView->_action) != 'logout') {
                    $this->setRedirect("adminuser/logout/");
                }
            }
        }
        if (substr($this->ObjView->_views_request_url, -1) != '/') {
        }
        if (substr($this->ObjView->_views_request_url, (strlen($this->ObjView->_views_request_url) - 6), strlen($this->ObjView->_views_request_url)) == $this->ObjView->_section) {
            $this->setRedirect("/index/");
        }
        //Issue with  loading login page on  ajax request page while clearing cookies or session logout
        if (!$manageUserID && $this->isAjax) {
            echo "AJAX_OORJIT_MANAGE_TIMEOUT";
            exit;
        }
        if (!$manageUserID && !in_array($this->ObjView->_controller, $managePublicPages)) {
            if (substr($this->ObjView->_views_request_url, (strlen($this->ObjView->_views_request_url) - 1), strlen($this->ObjView->_views_request_url)) == "/") {
                $this->setRedirect("login/");
            } else {
                $this->setRedirect("/login/");
            }
        } else {
            //Issue with pop up loading login page while clearing cookies or session logout
            if ($this->ObjView->_controller == 'Login') {
                echo '<script type="text/javascript">
					if(window.parent.document.getElementById("colorbox")){
						window.parent.location = window.parent.location.href;
						parent.$.colorbox.close();} </script>';
            }
            $this->ObjView->assign("view_common_manageUserID", $manageUserID);
            $this->ObjView->assign("view_common_manageUserTypeID", $this->mangeUserTypeID);
            $this->ObjView->assign("view_common_manageUserName", $this->manageUserName);
        }
    }
    //END OF FUNCTION
    //TO SET HISTORY URL
    public function setHistoryURL() {
        $PrevHistoryURL = $this->ObjSession->getSession('COMMON_BROWSER_HISTORY_URL');
        $HistoryURL     = array();
        if (count($PrevHistoryURL) < 1) {
            $HistoryURL[0] = $this->ObjView->_views_url;
        } else if (isset($PrevHistoryURL[1]) && (($PrevHistoryURL[1]) != ($this->ObjView->_views_url))) {
            $HistoryURL[0] = (empty($this->ObjView->_views_url)) ? "Index/" : $this->ObjView->_views_url;
            $HistoryURL[1] = (empty($PrevHistoryURL[0])) ? $HistoryURL[0] : $PrevHistoryURL[0];
            $HistoryURL[2] = (empty($PrevHistoryURL[1])) ? $HistoryURL[1] : $PrevHistoryURL[1];
            $HistoryURL[3] = (empty($PrevHistoryURL[2])) ? $HistoryURL[2] : $PrevHistoryURL[2];
            $HistoryURL[4] = (empty($PrevHistoryURL[3])) ? $HistoryURL[3] : $PrevHistoryURL[3];
        } else {
            $HistoryURL = $PrevHistoryURL;
        }
        $this->ObjSession->unsetSession('COMMON_BROWSER_HISTORY_URL');
        $this->ObjSession->setSession('COMMON_BROWSER_HISTORY_URL', $HistoryURL);
    }
    //END OF FUNCTION  
    //TO SET AJAX SECTIONS
    public function isAjaxRequest() {
        $manageAjaxSections = "AjaxUploadImage,Ajax";
        //AJAX CONTROLLERS
        $manageAjaxSections = explode(',', $manageAjaxSections);
        if (@in_array($this->ObjView->_controller, $manageAjaxSections) || (substr_count(strtolower($this->ObjView->_action), "ajax") > 0)) {
            return true;
        } else {
            return false;
        }
    }
    //END OF FUNCTION  
    //FUNCTION  TO SET CURRENCY FORMAT PLUGIN
    public function setCurrencyFormatPlugin() {
        $ObjCurrency   = new CurrencyModel();
        $resCurrencies = $ObjCurrency->listCurrencies(NULL, NULL, NULL, 'No', '');
        if (count($resCurrencies) > 0) {
            foreach ($resCurrencies as $currency) {
                if ($currency['currencyDefault'] == 'Yes') {
                    $this->ObjView->_defaultCurrency = $currency['currencyID'];
                    $this->ObjView->assign('defCurrencySymbol', $currency['currencySymbolLeft']);
                }
                $currencies[$currency['currencyID']] = $currency;
            }
        }
        $this->ObjView->_currencies = $currencies;
        $this->ObjView->registerPlugin("modifier", "price", array(
            $this->ObjView,
            "getFormattedCurrency"
        ));
        $this->ObjView->registerPlugin("modifier", "price_no_symbol", array(
            $this->ObjView,
            "getFormattedAmount"
        ));
         $this->ObjView->registerPlugin("modifier", "price_order", array(
            $this->ObjView,
            "getFormattedCurrencyOrder"
        ));
         $this->ObjView->registerPlugin("modifier", "decode_str", array(
            $this,
            "getDecodeString"
        ));
    }
    //END OF FUNCTION 
    //FUNCTION  TO SET ADDRESS FORMAT PLUGIN
    public function setAddressFormatPlugin() {
        $ObjCountry = new CountryModel();
        $this->ObjView->registerPlugin("modifier", "address_format", array(
            $ObjCountry,
            "getFormattedAddress"
        ));
    }
    //END OF FUNCTION
    //date modifier for getting the custom date with system assigned format
    public function setCustomDateWithFormat() {
        $this->ObjView->registerPlugin("modifier", "customDate", array(
            $this,
            "getFormattedDate"
        ));
    }    
    //TO GET SETTING VALUE
    public function getSettingValue($keyGroupID, $keyID = "") {
        $_settings                      = Registry::getInstance('_settings');
        $_settings[$keyGroupID]         = isset($_settings[$keyGroupID]) ? $_settings[$keyGroupID] : '';
        $_settings[$keyGroupID][$keyID] = isset($_settings[$keyGroupID][$keyID]) ? $_settings[$keyGroupID][$keyID] : '';
        $setting_value                  = ((empty($keyID)) ? ($_settings[$keyGroupID]) : ($_settings[$keyGroupID][$keyID]));
        // $setting_value=utf8_decode($setting_value);
        return $setting_value;
    }
    //END OF FUNCTION
	//TO GET SETTING VALUE BY BRAND
    public function getSettingValuebyBrand($keyGroupID, $keyID = "",$brandID) {
        $ObjSettings 		= new SettingsModel();
		$setting_value      = $ObjSettings->getSettingValuebyBrand($keyGroupID,$keyID,$brandID);
        return $setting_value;
    }
    //END OF FUNCTION
    //TO SET LANGUAGE 
    public function setLanguage() {
        $ObjLanguage          = new LanguageModel();
        //$resListLanguages     = $ObjLanguage->listLanguages();
		$params         = array(
			'brandKey' 		=> "BMW"
		);   
		$resListLanguages = $ObjLanguage->listAllLanguages($params);			
        $cookieLanguageID     = $this->ObjCookie->getCookie($this->ObjView->_section . '_CurrentLanguageID');
        $cookieLanguageStatus = false;
        foreach ($resListLanguages as $language) {
			$language['languageLogo'] = $language['brandLanguageLogo'] ;
            if ($language['languageDefault'] == 'Yes') {
                $this->languageIDs['Default'] = $language['languageID'];
                $defaultLanguageDetails       = $language;
                $defaultLCID                  = $language['LanguageLCIDstring'];
            }
            if ($language['languageID'] == $cookieLanguageID && $language['languageStatus'] == 'Active') {
                $cookieLanguageStatus   = true;
                $currentLanguageDetails = $language;
            }
            //Active Languages Only
            if ($language['languageStatus'] == 'Active') {
                $this->languageIDs['All'][] = $language['languageID'];
                $activeLanguages[]          = $language;
            }
            //All languages including Inactive	   
            $this->languageIDs['AllList'][]           = $language['languageID'];
            $this->langArray[$language['languageID']] = $language;
        }
        if ($cookieLanguageID > 0 && $cookieLanguageStatus) {
            $this->languageIDs['Current'] = $cookieLanguageID;
        } else {
            $this->languageIDs['Current'] = $this->languageIDs['Default'];
            $currentLanguageDetails       = $defaultLanguageDetails;
        }
        //Content Language ID
        $contentlanguageID              = $ObjLanguage->getContentlanguageID($this->languageIDs['Default'], $this->languageIDs);
        $resContentLanguages            = $this->langArray[$contentlanguageID];
        //Content Language to $this->languageIDs
        $this->languageIDs['Content']   = $contentlanguageID;
        $this->ObjView->languageIDs     = $this->languageIDs;
        $this->ObjView->languageIDsList = $resListLanguages;
        //Load current lang xml
        $this->ObjView->_languageXML    = $this->loadLanguageXml($currentLanguageDetails['LanguageLCIDstring']);
        $this->ObjView->assign('language', $this->ObjView->_languageXML);
        $this->ObjView->assign('currentLanguageID', $this->languageIDs['Current']);
        $this->ObjView->assign('defaultLogo', $currentLanguageDetails['languageLogo']);
        $this->defaultLogoImg= $currentLanguageDetails['languageLogo']; 

        $this->ObjSession->setSession($ObjLanguage->getSection() . '_ContentDefaultLCID', $defaultLCID);
        $this->ObjView->assign('languageIDs', $this->languageIDs);
        $this->ObjView->assign('AjaxCurrLanguage', $currentLanguageDetails['LanguageLCIDstring']);
        $this->ObjView->assign('view_common_languages', $activeLanguages);
        $this->ObjView->assign("view_common_languageName", $currentLanguageDetails['languageName']);
        $this->ObjView->assign("view_common_languageImage", $currentLanguageDetails['languageImage']);
        $this->ObjView->assign("view_content_languageName", $resContentLanguages['languageName']);
        $this->ObjView->assign("view_content_languageImage", $resContentLanguages['languageImage']);
        $this->ObjView->assign("indexLanguageArray", $this->langArray);
    }
    //END OF FUNCTION 
    //TO SET MENU
    public function setMenu() {
        $ObjMenu    = new MenuModel();
        $userTypeID = $this->mangeUserTypeID;
        /*file caching for menus*/
        if ($userTypeID > 0 && !$view_common_top_menu = $this->objCache->get('m_menu_list_' . $userTypeID . '_' . $this->ObjView->languageIDs['Current'])) {
            $campignEnable        = $this->getSettingValue("third_paty_mail_settings", "campaign_api_key");
            $ObjTool              = Registry::getInstance('Tool');
            $campignEnable        = $ObjTool->encryptDecrypt("decrypt", $campignEnable);
            $params               = array(
                'languageXml' => $this->ObjView->_languageXML,
                'campignEnable' => $campignEnable,
                'userTypeID' => $userTypeID,
                'manageUserID' => $this->manageUserID,
                '_url_path' => $this->ObjView->_views_url_path,
                'privilegeData' => $this->userPrivilegeList
            );
            $view_common_top_menu = $ObjMenu->setAdminMenu($params);
            $this->objCache->set('m_menu_list_' . $userTypeID . '_' . $this->ObjView->languageIDs['Current'], $view_common_top_menu, CACHE_TTL_LEVEL_1);
        }
        /*file caching for menus*/
        $this->ObjView->assign("view_common_top_menu", isset($view_common_top_menu) ? $view_common_top_menu : '');
    }
    //END OF FUNCTION
    //END OF FUNCTION
    //FUNCTION TO REDIRECT URL 
    public function setRedirect($location_url = '', $dynamic_url = "Yes") {
        if ($dynamic_url == "Yes") {
            if ($location_url == '') {
                $ObjRewrite   = Registry::getInstance('Rewrite');
                $location_url = implode($ObjRewrite->_queryDelimiter, $ObjRewrite->_queryString);
            }
            $location_url = $this->ObjView->_base_path . '/' . ltrim($location_url, '/');
        }
        header("Location:$location_url");
        exit;
    }
    //END OF FUNCTION  
    //FUNCTION TO SET ROLES
    public function setManageRoles() {
        //Controller +  Action
        $action = strtolower($this->ObjView->_action);
        if ($action == '') {
            $action = 'index';
        }
        $urlToCheck = strtolower($this->ObjView->_controller) . "/" . $action . "/";
        $this->askPrivilege($urlToCheck);
    }
    //END OF FUNCTION 
    //FUNCTION  TO CHECK SETTINGS TIME OUT
    public function checkSettingsTimeout() {
        $curr_url        = strtolower($this->ObjView->_controller . '/' . $this->ObjView->_action . '/');
        $ajaxKeyword     = 'ajax';
        $_settings       = Registry::getInstance('_settings');
        $timeOut         = $_settings['security_settings']['security_admin_timeout'];
        $manageSessionID = $this->ObjSession->getSessionID();
        if ($this->ObjSession->getSession("TIMEOUT" . $manageSessionID)) {
            $userTimeout  = $this->ObjSession->getSession("TIMEOUT" . $manageSessionID);
            $session_life = time() - $userTimeout;
            if ($session_life > $timeOut && $timeOut != '') {
                $SessionDestroy = $this->ObjSession->unsetSession('TIMEOUT' . $manageSessionID);
                $this->setRedirect("adminuser/logout/");
            }
        }
        $this->ObjSession->setSession("TIMEOUT" . $manageSessionID, time());
    }
    //END OF FUNCTION  
    public function getEmailCommonBottom($languageIDs = '',$brandID = '') {
        if ($languageIDs == '') {
            $languageIDs = $this->languageIDs;
        }
        $ObjEmail        = new EmailtemplateModel();
		if($brandID == '') {
			$siteName        = $this->getSettingValue('site_settings', 'site_name');
			$contactEmail    = $this->getSettingValue('site_settings', 'contact_email');
			$httpURL         = rtrim($this->getSettingValue('site_settings', 'global_http_url'), '/');
			$dateFormat      = $this->getSettingValue('site_settings', 'date_format');
		} else {
			$siteName        = $this->getSettingValuebyBrand('site_settings', 'site_name',$brandID);
			$contactEmail    = $this->getSettingValuebyBrand('site_settings', 'contact_email',$brandID);
			$httpURL         = rtrim($this->getSettingValuebyBrand('site_settings', 'global_http_url',$brandID), '/');
			$dateFormat      = $this->getSettingValuebyBrand('site_settings', 'date_format',$brandID);
		}
        //Get Email Bottom
        $resCommonBottom = $ObjEmail->getEmailTempSection($languageIDs, 'email_bottom', 'sectionContent');
        $emailBottom     = $resCommonBottom['sectionContent'];
        //Replace variables
        $emailBottom     = str_replace('{$siteName}', $siteName, $emailBottom);
        $emailBottom     = str_replace('{$contactEmailAdress}', $contactEmail, $emailBottom);
        $emailBottom     = str_replace('{$siteURL}', $httpURL . '/', $emailBottom);
        //Set mail date

        $date            = date('m/d/Y');
        $datetime        = strtotime('-1 day', strtotime($date));
        $currDate        = date('m/d/Y 00:00', $datetime);
        $formatedDate    = $this->formatDate($currDate, (isset($dateFormat) ? $dateFormat : ''));
        //Assign variables for email layout tpl
        $this->ObjView->assign("emailBottom", $emailBottom);
        $this->ObjView->assign("date", $formatedDate);
        $this->ObjView->assign("siteUrl", $httpURL);
        $this->ObjView->assign("siteName", $siteName);
        $this->ObjView->assign("commonSiteName", $siteName);
		if($brandID == '') {
			$this->ObjView->assign("companyLogo", $this->getSettingValue('company_information', 'company_logo'));
			$this->ObjView->assign("settingsFacebookPage", $this->getSettingValue('social_media_settings', 'facebook_page'));
			$this->ObjView->assign("settingsTwitterPage", $this->getSettingValue('social_media_settings', 'twitter_page'));
		} else {
			$this->ObjView->assign("companyLogo", $this->getSettingValuebyBrand('company_information', 'company_logo',$brandID));
			$this->ObjView->assign("settingsFacebookPage", $this->getSettingValuebyBrand('social_media_settings', 'facebook_page',$brandID));
			$this->ObjView->assign("settingsTwitterPage", $this->getSettingValuebyBrand('social_media_settings', 'twitter_page',$brandID));
		}
    }
    //To format date
    public function formatDate($date, $dateFormat = '', $timeFormat = '') {
        $_dateMap      = array(
            '%B %e, %Y' => 'F d, Y',
            '%A, %B %e, %Y' => 'l  F d, Y',
            '%m/%d/%Y' => 'm/d/Y',
            '%d/%m/%Y' => 'd/m/Y',
            '%d-%m-%Y' => 'd-m-Y',
            '%Y-%m-%d' => 'Y-m-d'
        );
        $_timeMap      = array(
            '%I:%M %p' => 'h:i A',
            '%l:%I %p' => 'g:i A',
            '%H:%M' => 'H:i'
        );
        $phpDateFormat = (isset($_dateMap[$dateFormat])) ? $_dateMap[$dateFormat] : '';
        $phpTimeFormat = (isset($_timeMap[$timeFormat])) ? $_timeMap[$timeFormat] : '';
        $format        = $phpDateFormat . ' ' . $phpTimeFormat;
        if ($format) {
            $date = new DateTime($date);
            return $date->format($format);
        } else {
            return $date;
        }
    }
    public function fetch($layoutTemplate, $languageIDsOthers = "",$brandID ="") {
		$ObjLanguage      = new LanguageModel();
		////$resListLanguages = $ObjLanguage->listLanguages("", $status = "Active");
		$params         = array(
			'status' 	=> "Active",
			'brandKey' 	=> "BMW"
		);   
		$resListLanguages = $ObjLanguage->listAllLanguages($params);
		foreach ($resListLanguages as $language) {
			$language['languageLogo'] = $language['brandLanguageLogo'] ;
            if ($language['languageDefault'] == 'Yes') {
                $this->languageIDs['Default'] = $language['languageID'];
                $defaultLanguageDetails       = $language;
				
            }                      
        }
		$currentLanguageDetails       = $defaultLanguageDetails;
		$settingsCompanyLogo = $this->getSettingValue('company_information', 'company_logo');
		 $httpUrlType         = ($this->request_protocol == "https") ? 'global_https_url' : 'global_http_url';
		$companyLogoUrl      = rtrim($this->getSettingValue('site_settings', $httpUrlType), '/');

        
		 $this->ObjView->assign('defaultLogo', $currentLanguageDetails['languageLogo']);
		
        $this->getEmailCommonBottom($languageIDsOthers, $brandID);
        $body = $this->ObjView->fetch($layoutTemplate);
        return $body;
    }
    //FUNCTION FOR TRACKING VISITORS URL
    public function logTracking() {
        $settingsSiteUrl = '';
        $ObjLog          = new LogModel();
        $userType        = "manage";
        $sslEnable       = 0; //Counter For Checking Whether SSL is enabled or not	
        $visitorID       = $this->ObjCookie->getCookie("AD_VISITORID");
        $visitorType     = $this->ObjCookie->getCookie("AD_VISITORTYPE");
        $controllerName  = $this->ObjView->_controller;
        if (@$_SERVER["HTTPS"] == "on") {
            $sslEnable = 1;
        }
        $httpUrl           = $this->getSettingValue('site_settings', 'global_http_url');
        $httpsURL          = $this->getSettingValue('site_settings', 'global_https_url');
        $currentURL        = $ObjLog->getCurrentUrl($httpUrl, $httpsURL); //fetching Current URL	
        $httpReferer       = $ObjLog->getCurrentReferrer($httpUrl, $httpsURL, '', $sslEnable);
        $bannedURLs        = array(
            "validate",
            "ajax",
            "productCatKeyExists",
            "productCategoryExits",
            "productCatKeyExists",
            "checkName",
            "linkexists",
            "/destroy",
            "checkproductTypeExists",
            "statesAjax",
            "Ajax",
            "samplecsv",
            "remarketingID",
            "conversionID",
            "businessTypeExits",
            "mssg",
            "task"
        );
        $traverseBannedURL = 0;
        foreach ($bannedURLs as $key) {
            if (strpos(strtolower($currentURL), strtolower($key)) != false) {
                $traverseBannedURL = 1;
                break;
            } else {
                $traverseBannedURL = 0;
            }
        }
        $currentURLSession  = $this->ObjSession->getSession("CURRENT_URL");
        $httpRefererSession = $this->ObjSession->getSession("REFERRER_URL");
        if (!$visitorID) {
            $isDirect  = $ObjLog->getCurrentReferrer($settingsSiteUrl, $checkDirect = 1);
            $visitorID = $ObjLog->saveVisitorDetails($userType, $currentURL, $isDirect); //Save Visitors Basic Details
            $this->ObjCookie->setCookie("AD_VISITORID", $visitorID, 1800, "/"); //Setting Of VisitorId Cookie
            $this->ObjCookie->setCookie("AD_VISITORTYPE", $userType, 1800, "/"); //setting Of Visitor Type Cookie
        }
        if ($visitorID) {
            if ($traverseBannedURL == 0) {
                //TO SKIP DUPLICATE URL IN CASE IF THE SAME URL ATTACHED WITH INDEX ACTION
                $indexInCurrentURL = strpos($currentURL, "/index");
                if (!$indexInCurrentURL || $indexInCurrentURL == '') {
                    $checkCurrentURl = $currentURL . "index/";
                } else {
                    $checkCurrentURl = $currentURL;
                }
                $indexInCurrentSession = strpos($currentURLSession, "/index");
                if (!$indexInCurrentSession || $indexInCurrentSession == '') {
                    $checkCurrenttSession = $currentURLSession . "index/";
                } else {
                    $checkCurrenttSession = $currentURLSession;
                }
                //SKIPING URLS ATTACH WITH INDEX ACTION ENDS HERE
                $siteURL = isset($siteURL) ? $siteURL : '';
                if (($currentURL != $currentURLSession) && ($currentURL != $siteURL) && $checkCurrentURl != $checkCurrenttSession) {
                    $ObjLog->saveURLInfo($visitorID, $currentURL, '', $httpReferer, $userType); //for saving each and every Urls
                    $this->ObjCookie->setCookie("AD_VISITORID", $visitorID, 1800, "/"); //Setting Of VisitorId Cookie
                    $this->ObjCookie->setCookie("AD_VISITORTYPE", $userType, 1800, "/"); //setting Of Visitor Type Cookie
                    $this->ObjSession->setSession("CURRENT_URL", $currentURL);
                    $this->ObjSession->setSession("REFERRER_URL", $httpReferer);
                }
            }
        }
    }
    
    /*
    $type = "unique" for unique Key
    */
    public function generateKey($section = "", $name, $objectID = "", $type = "") {
        $key = '';
        if ($name != '') {
            $key = str_replace(" ", "-", trim($name)); // Replaces all spaces with hyphens.
            $key = preg_replace('/[^A-Za-z0-9\-]/', '-', $key); // Removes special chars.
            $key = preg_replace('/-+/', '-', $key); // Removes continuous hypens with a single hypen.
            //if($section == "cms")
            $key = trim($key, "-");
        }
        if ($key == '') {
            for ($i = 0; $i < 4; $i++) {
                $key .= chr(rand(ord('a'), ord('z')));
            }
        }
        if ($type == "unique") {
            $ObjUrlrewrite = new UrlrewriteModel();
            switch ($section) {
                case "cms":
                    $tableDtls = array(
                        "fieldIdNme" => "contentID",
                        "fieldKeyNme" => "contentUrlKey",
                        "tbleName" => "content_pages"
                    );
                    break;
                case "menuitem":
                    $tableDtls = array(
                        "fieldIdNme" => "menuItemID",
                        "fieldKeyNme" => "menuItemKey",
                        "tbleName" => "menu_item"
                    );
                    break;
                case "catalog":
                    $tableDtls = array(
                        "fieldIdNme" => "productCategoryID",
                        "fieldKeyNme" => "productCategoryKey",
                        "tbleName" => "product_categories"
                    );
                    break;
                case "business":
                    $tableDtls = array(
                        "fieldIdNme" => "businessID",
                        "fieldKeyNme" => "businessKey",
                        "tbleName" => "business"
                    );
                    break;
            }
            $tableDtls["key"]      = $key;
            $tableDtls["objectID"] = $objectID;
            $key                   = $ObjUrlrewrite->checkKeyExists($tableDtls);
        }
        return strtolower($key);
    }
    //Read privilege File
    public function getPrivilegeData() {
        if (!empty($this->userPrivilegeList)) {
            $privilegeArrayUrl = $this->userPrivilegeList;
        } else {
            $ObjRoles                = new RolesModel();
            $privilegeArrayUrl       = $ObjRoles->getPrivilageFile($this->mangeUserTypeID);
            $this->userPrivilegeList = $privilegeArrayUrl;
        }
        return $privilegeArrayUrl;
    }
    //Check User privilege
    public function hasPrivilege($urlToCheck) {
        $manageUserTypeID = $this->mangeUserTypeID;
        $accessprivilage  = true;
        if ($manageUserTypeID != 1 && $manageUserTypeID > 1) {
            $urlToCheck = strtolower($urlToCheck);
            if (strpos($urlToCheck, 'ajax') == false) {
                //PRIVILEGE_ARRAY = roles data of a particular user type
                $privilegeArray  = $this->getPrivilegeData();
                $accessprivilage = false;
                //Checks whether URL exists in PRIVILEGE_ARRAY
                if ($privilegeArray && in_array($urlToCheck, $privilegeArray)) {
                    $accessprivilage = true;
                } else //Checking if it is a Privileged URL 
                    {
                    //PRIVILEGE_FULL_ARRAY = Get Full privilege URLs
                    $privilegeFullArray = $this->listRolesData();
                    //if URL not exists in PRIVILEGE_FULL_ARRAY , Access Permitted
                    if (!in_array($urlToCheck, $privilegeFullArray)) {
                        $accessprivilage = true;
                    }
                }
            }
        }
        return $accessprivilage;
    }
    //List Roles Data
    private function listRolesData() {
        //Check in Common Controller Variable
        if (!empty($this->fullPrivilegeList)) {
            $roles = $this->fullPrivilegeList;
        } elseif (!$roles = $this->objCache->get('m_full_roles_list')) //Check in Cache
            {
            $ObjRoles    = new RolesModel();
            //Roles Schema
            $schemaRoles = $ObjRoles->includeRolesSchema();
            $params      = array(
                'schemaData' => $schemaRoles['permissions'],
                'rolesStr' => ''
            );
            $roles       = explode("~*", $this->listRolesItems($params));
            $this->objCache->set('m_full_roles_list', $roles, CACHE_TTL_LEVEL_1);
            //Assign to Common Controller Variable
            $this->fullPrivilegeList = $roles;
        }
        return $roles;
    }
    //List Roles Items
    private function listRolesItems($params) {
        extract($params);
        $rolesStr = '';
        if (!empty($schemaData)) {
            foreach ($schemaData as $arrayKey => $schema) {
                $currRoleKey      = $schema['adminModuleURLKey'];
                $resSubRolesCount = isset($schema['adminSubMenu']) ? count($schema['adminSubMenu']) : 0;
                if ($currRoleKey != '') {
                    $rolesStr .= $currRoleKey . "~*";
                }
                if ($resSubRolesCount > 0) {
                    $params = array(
                        'schemaData' => $schema['adminSubMenu']
                    );
                    $rolesStr .= $this->listRolesItems($params);
                }
            }
        }
        return $rolesStr;
    }
    //Ask privilege : to be used for checking privilege & redirect 
    public function askPrivilege($urlToCheck = '') {
        if ($urlToCheck != '' && !$this->hasPrivilege($urlToCheck)) {
            $this->redirectToPrivilegePage();
        }
    }
    //redirect to privilege page
    public function redirectToPrivilegePage() {
        $this->setRedirect('privilege/');
        exit;
    }
    // get Formatted Date
    public function getFormattedDate($originalDate) {
        if ($originalDate == '') {
            return "";
        } else {
            $assignedDateformat = $this->getSettingValue("site_settings", "date_format");
            if ($assignedDateformat == '')
                $assignedDateformat = '%Y-%m-%d';
            if (substr_count($originalDate, ':') > 1)
                $assignedDateformat .= ' %H:%M:%S';
            else if (substr_count($originalDate, ':') == 1)
                $assignedDateformat .= ' %H:%M';
            return strftime($assignedDateformat, strtotime($originalDate));
        }
    }
    //Load language xml
    public function loadLanguageXml($languageLCIDstring = '', $languageID = '') {
        $ObjLanguage = new LanguageModel();
        if ($languageLCIDstring == '' && $languageID > 0) {
            $languageLCIDstring = $this->langArray[$languageID]['LanguageLCIDstring'];
        }
        return $ObjLanguage->loadLanguageXMLtoArray(__CORE_PUBLIC_MANAGE_PATH . '/' . __DIR_LANGUAGE . '/' . $languageLCIDstring . '.xml');
    }
    //Current Url
    public function selfURL() {
        $s              = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
        $serverProtocol = strtolower($_SERVER["SERVER_PROTOCOL"]);
        $protocol       = substr($serverProtocol, 0, strpos($serverProtocol, "/")) . $s;
        $port           = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":" . $_SERVER["SERVER_PORT"]);
        return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
    }
    //decode string
    public function getDecodeString($originalString) {
        
        $ObjContent          = new ContentModel();       
        return $ObjContent->getDecode($originalString);
    }
}
