'English', 'ko' => 'Korean', 'chi' => 'Chinese'); /** * Initialization hook method. * * Use this method to add common initialization code like loading components. * * e.g. `$this->loadComponent('Security');` * * @return void */ public function initialize() { parent::initialize(); $this->loadComponent('RequestHandler'); $this->loadComponent('Cookie', ['expiry' => '1 day']); $this->loadComponent('Flash'); $this->loadModel('Settings'); $controller = 'Cmsusers'; $loginRedirect_controller = 'Dashboard'; if ($this->request->params['controller'] == "Guest") { $controller = 'Guest'; $loginRedirect_controller = 'Guestform'; } $this->loadComponent('Auth', [ 'authorize' => ['Controller'], 'authenticate' => [ 'Form' => [ 'userModel' => $controller, 'passwordHasher' => [ 'className' => 'Cms' ], 'fields' => [ 'username' => 'email', 'password' => 'password' ] ] ], 'loginAction' => [ 'controller' => $controller, 'action' => 'login' ], 'loginRedirect' => [ 'controller' => $loginRedirect_controller, 'action' => 'index' ], 'logoutRedirect' => [ 'controller' => $controller, 'action' => 'login' ] ]); $this->setCompanyID(); $this->adminTickets(); $this->Auth->allow(['display']); $setting = $this->Settings->getCurrentSettings(); $this->set('setting', $setting); $this->manageDomainName(); // pr($_SESSION);exit; } public function beforeFilter(Event $event) { if ($this->request->session()->read('Config.language')) { $language = $this->request->session()->read('Config.language'); if ($language != I18n::defaultLocale()) { I18n::locale($language); $this->set("current_lang", $language); } else { $this->set("current_lang", I18n::defaultLocale()); } } else { $this->set("current_lang", I18n::defaultLocale()); } if ($this->request->session()->read('Auth.User.id')) { $this->set('current_module', $this->getModules()); $this->set('sub_modules', $this->getSubModules()); $this->set('module_pages', $this->getPages()); $current_url = strtolower(Router::url()); // if($this->request->is('ajax')){ // return $event->data['response']; // } $this->setClientStatusConstant(); if ($_SESSION['userType'] == CMS_USER_INDICATOR || Permission::isEmployeeAsAdmin()) { $this->loadModel("TeamMessages"); $this->loadModel("Crmusers"); $this->loadModel("PdfLetters"); $statistics_url[] = strtolower(Router::url('/Statistics')); $statistics_url[] = strtolower(Router::url('/users/logout/')); $statistics_url[] = strtolower(Router::url('/Statistics/getPurchase')); if($_SESSION['limited_time_days'] > 0 && !in_array($current_url, $statistics_url)){ return $this->redirect(['controller' => 'statistics', 'action' => 'index']); } $commonLogic = new \App\Helper\commonLogic; $member_notification = $this->getAllNotificationsForMember($commonLogic); $affiliate_message = $member_notification['affiliate_messages_data']; $member_remainder = $this->getAllRemainderForMember(); $member_note = $this->getAllNoteForMember(); //pr($member_remainder);exit; $affiliate_note_against_client = $member_notification["affiliate_note_against_client"]; $team_messages_info =$commonLogic->getAllTeamMessagesByMemberId($this->Auth->user('id'),0); $employee_to_member_messages = $team_messages_info['employee_messages']; $employee_info_for_message = $team_messages_info['employee_info']; $total_employee_message = count($employee_to_member_messages); // save letters //dd($member_notification); $pdf_letters = $this->PdfLetters->getPdfLettersPopupInfoByMemberId($this->Auth->user('id')); $total_save_letter = count($pdf_letters); $this->set(compact('total_save_letter','pdf_letters','total_employee_message','employee_to_member_messages','member_notification','employee_info_for_message', 'member_remainder', 'member_note', 'affiliate_note_against_client', 'affiliate_message')); } else if ($_SESSION['userType'] == CONTACT_USER_INDICATOR) { $client_notification = $this->getAllNotificationsForClient(); $_SESSION['client_notification'] = $client_notification; $this->set(compact('client_notification')); } else if ($_SESSION['userType'] == CRM_USER_INDICATOR && $_SESSION['Auth']['User']['type'] == 1 && !Permission::isEmployeeAsAdmin()) { $employee_notification = $this->getAllNotificationsForEmployee(); $this->loadModel("MemberReminders"); $this->loadModel("MemberRemindersOthers"); $this->loadModel("MemberNotes"); $this->loadModel("TeamMessages"); $this->loadModel("PdfLetters"); $this->loadModel("ClientAssignments"); $this->loadModel("Clients"); $member_remainder = $this->MemberReminders->getRemindersForEmployees($this->Auth->user('user_id'),3, 10,false,true,1); $member_remainder_others = $this->MemberRemindersOthers->getRemindersOthersForEmployees($this->Auth->user('user_id'),3, 10); $member_note = $this->MemberNotes->getNotesForEmployees($this->Auth->user('user_id'),3,0, 10,false,true,0); $member_note_others = $this->MemberNotes->getNotesOthersForEmployees($this->Auth->user('user_id'),3, 10); $employee_messages = $this->TeamMessages->getTeamReadUnreadMessagesByType(1,$this->Auth->user('user_id'),3,0); $team_member_messages = null; $employeeInfoList = []; if(Permission::isPermitted(TEAM_MESSAGING_CONTROLLER_ID)) { $this->loadModel('Crmusers'); $employeeInfoList = $this->Crmusers->getEmployeeSeparateInfoByMemberId($this->Auth->user('id'),['id !='=>$this->Auth->user('user_id')]); $team_member_messages = $this->TeamMessages->getTeamMembersUnreadMessages($this->Auth->user('user_id'), 3, 0); } $isShowAllclients = $this->isShowAllClients(); $pdf_letters = null; if(Permission::isPermitted(SAVE_DOWNLOAD_PRINT_LETTER_CONTROLLER_ID)) { if ($isShowAllclients) { $client_assoc = $this->Clients->getClientList($this->Auth->user('id'), "", false, true); } else { $emp_client_ids = $this->ClientAssignments->getClientsByUserTypeIdAndCondition($this->Auth->user('user_id'), "refference_type = 3"); if (!empty($emp_client_ids)) { $emp_client_ids = array_unique($emp_client_ids); $client_assoc = $this->Clients->getClientListByIds($emp_client_ids); } } if (isset($client_assoc['name_email']) && !empty($client_assoc['name_email'])) { $client_ids = array_keys($client_assoc['name_email']); } if (!empty($client_ids)) { $pdf_letters = $this->PdfLetters->getPdfLettersPopupInfoByMemberId($this->Auth->user('id'), $client_ids); } else { $pdf_letters = null; } } $total_save_letter = count($pdf_letters); $this->set(compact('total_save_letter','pdf_letters','employeeInfoList','team_member_messages','employee_notification','member_note', 'member_note_others', 'member_remainder','member_remainder_others','employee_messages')); } else if ($_SESSION['userType'] == CRM_USER_INDICATOR && $_SESSION['Auth']['User']['type'] == 2) { $notification = $this->getAffliliateNotesNotification(); $affliliate_message = $notification['affliliate_message']; $affliliate_note_notification = $notification['notes']; $affiliate_notes_against = $notification['affiliate_notes']; $this->set(compact('affliliate_note_notification', 'affiliate_notes_against', 'affliliate_message')); } } $this->user_id = $user_id = $this->request->session()->read('Auth.User.id'); $base_url = Router::url('/'); $this->set('base_url', $base_url); if ($_SESSION['userType'] == CONTACT_USER_INDICATOR && $this->Auth->user()) { $this->loadModel('AgreementAssignments'); $member_id = $user_id; $client_id = $this->request->session()->read('Auth.User.client_id'); $hasAgrement = $this->AgreementAssignments->hasAgreementByMemberAndClientId($member_id, $client_id); if ($hasAgrement) { $_SESSION['has_agreement'] = 1; //echo $current_url;exit;users/logout $required_url[] = strtolower(Router::url('/Clientdashboard/clientsignature')); $required_url[] = strtolower(Router::url('/users/logout')); if (!in_array($current_url, $required_url)) { return $this->redirect(['controller' => 'Clientdashboard', 'action' => 'clientsignature']); } } } } public function setCompanyID() { $this->set('company_id', $this->Auth->user('company_id')); $this->loadModel('Clients'); $supports = $this->getTicketNotification(); //pr($supports);exit; $this->set('parentIDs', $supports['parentIDs']); $this->set('supports', $supports['supports']); $this->set('supportsList', $supports['supports']); //echo'
'; sizeof($supports['supportMsg']);exit;
        
        
        $count = 0;
        if (!empty($supports['supports'])) {
            foreach ($supports['supports'] as $sp) {
               if($sp->is_read == 0){
                    $count++;
               }
            }
        }
        
        $this->set('supportMsg', $supports['ticket_count']);
    }

    protected function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    
     public function sendMultipleEmail($templateName, $templateContentArray, $personalize = null) {
        $APP_SMTP_USERNAME = APP_SMTP_USERNAME;
        $APP_SMTP_FROM_NAME = APP_SMTP_FROM_NAME;
        $APP_EMAIL_CLASS = APP_EMAIL_CLASS;
        $APP_SMTP_HOST = APP_SMTP_HOST;
        $APP_SMTP_PORT = APP_SMTP_PORT;
        $APP_SMTP_TIMEOUT = APP_SMTP_TIMEOUT;
        $APP_SMTP_PASSWORD = APP_SMTP_PASSWORD;
        $APP_SMTP_IS_TLS = APP_SMTP_IS_TLS;
        
       
        if (!empty($personalize)) {
            $templateContent['email_signature'] = $personalize->email_signature;
            if ($personalize->is_smtp == 1) {
                $APP_SMTP_USERNAME = $personalize->username;
                $APP_SMTP_FROM_NAME = $personalize->smtp_from;
                $APP_SMTP_HOST = $personalize->smtp_host;
                $APP_SMTP_PORT = $personalize->smtp_port;
                $APP_SMTP_PASSWORD = $personalize->password;
            }
        }

        $default = [
            'className' => $APP_EMAIL_CLASS,
            'host' => $APP_SMTP_HOST,
            'port' => $APP_SMTP_PORT,
            'timeout' => $APP_SMTP_TIMEOUT,
            'username' => $APP_SMTP_USERNAME,
            'password' => $APP_SMTP_PASSWORD,
            'tls' => $APP_SMTP_IS_TLS,
        ];

        $SMTP_FORM_EMAIL = $APP_SMTP_USERNAME;

        if($APP_SMTP_HOST == 'sandbox.smtp.mailtrap.io'){
            $SMTP_FORM_EMAIL = $APP_SMTP_FROM_NAME;
        }
        
        if(isset($templateContent['company_email']) && !empty($templateContent['company_email'])){
            $SMTP_FORM_EMAIL = $templateContent['company_email'];
        }
        
        if(isset($templateContent['company_name']) && !empty($templateContent['company_name'])){
            $APP_SMTP_FROM_NAME = $templateContent['company_name'];
        }
        $templateContent['email_body'] = stripslashes($templateContent['email_body']);
        try {

            $email = new Email();

            if (!empty($personalize) && $personalize->is_smtp == 1) {
                Email::configTransport('custom', $default);
                $email->transport('custom');

            } else {
                $email->transport('default');

            }

            if(!empty($templateContentArray)){
                foreach($templateContentArray as $templateContent){
                    
                    $to = $templateContent['to'];
                    $sub = $templateContent['sub'];
                    $attachment = $templateContent['attachment'];

                    if(IS_QUEUE_ENABLE){
                        $data = $templateContent;
                        $options['member_id'] = 0;
                        if (!empty($personalize) && $personalize->is_smtp == 1) {
                            if($personalize->member_id > 0){
                                $options['member_id'] = $personalize->member_id;
                            }
                        }
                        $new_file_link = "";
                        if(!empty($attachment) && file_exists($attachment)){
                            $att_email_queue_dir = WWW_ROOT."email_queue/".$this->Auth->user('id');
                            if(!is_dir($att_email_queue_dir)){
                                mkdir($att_email_queue_dir,0777,true);
                            }
                            
                            $extension = pathinfo($attachment, PATHINFO_EXTENSION);
                            $new_file_name = uniqid()."_".time().".".$extension;
                            $new_file_link = $att_email_queue_dir."/".$new_file_name;
                            @copy($attachment, $new_file_link);
                        }
                        
                        $options['from_name'] = $SMTP_FORM_EMAIL;
                        $options['from_email'] = $SMTP_FORM_EMAIL;
                        $options['subject'] = $sub;
                        $options['template'] = $templateName;
                        $options['format'] = 'html';
                        $options['attachments'] = $new_file_link;
                        EmailQueue::enqueue($to, $data, $options);
                    }else{
                        if (isset($templateContent['no_reply']) && !empty($templateContent['no_reply'])) {
                            $email = $email->from($APP_SMTP_FROM_NAME);
                        } else {
                            $email = $email->from($SMTP_FORM_EMAIL,$APP_SMTP_FROM_NAME);
                        }

                        $email->template($templateName)
                                ->emailFormat('html')
                                ->to($to)
                                ->viewVars($templateContent)
                                ->subject($sub);

                        if (!empty($attachment)) {
                            $email->addAttachments($attachment);
                        }
                        $email->send();
                    } 
                }
            }
        } catch (Exception $ex) {
            $this->log($ex);
        }
    }


    
    public function sendEmail($templateName, $templateContent, $to, $sub = "New RTG registration", $attachment = "", $personalize = null) {
        $APP_SMTP_USERNAME = APP_SMTP_USERNAME;
        $APP_SMTP_FROM_NAME = APP_SMTP_FROM_NAME;
        $APP_EMAIL_CLASS = APP_EMAIL_CLASS;
        $APP_SMTP_HOST = APP_SMTP_HOST;
        $APP_SMTP_PORT = APP_SMTP_PORT;
        $APP_SMTP_TIMEOUT = APP_SMTP_TIMEOUT;
        $APP_SMTP_PASSWORD = APP_SMTP_PASSWORD;
        $APP_SMTP_IS_TLS = APP_SMTP_IS_TLS;
        
       
        if (!empty($personalize)) {
            $templateContent['email_signature'] = $personalize->email_signature;
            if ($personalize->is_smtp == 1) {
                $APP_SMTP_USERNAME = $personalize->username;
                $APP_SMTP_FROM_NAME = $personalize->smtp_from;
                $APP_SMTP_HOST = $personalize->smtp_host;
                $APP_SMTP_PORT = $personalize->smtp_port;
                $APP_SMTP_PASSWORD = $personalize->password;
            }
        }

        
        
        $SMTP_FORM_EMAIL = $APP_SMTP_USERNAME;
        $is_yahoo = false;
        if($APP_SMTP_HOST == 'sandbox.smtp.mailtrap.io'){
            $SMTP_FORM_EMAIL = $APP_SMTP_FROM_NAME;
        }else if($APP_SMTP_HOST == "smtp.mail.yahoo.com"){
            $APP_SMTP_IS_TLS = true;
            $is_yahoo = true;
        }
        
        $default = [
            'className' => $APP_EMAIL_CLASS,
            'host' => $APP_SMTP_HOST,
            'port' => $APP_SMTP_PORT,
            //'timeout' => $APP_SMTP_TIMEOUT,
            'username' => $APP_SMTP_USERNAME,
            'password' => $APP_SMTP_PASSWORD,
            //'tls' => $APP_SMTP_IS_TLS,
            'tls' => true,
            //'log'=> true
        ];
        
        
        
        if(isset($templateContent['company_email']) && !empty($templateContent['company_email'])){
            $SMTP_FORM_EMAIL = $templateContent['company_email'];
        }
        
        if(isset($templateContent['company_name']) && !empty($templateContent['company_name'])){
            $APP_SMTP_FROM_NAME = $templateContent['company_name'];
        }
        
         if(IS_QUEUE_ENABLE){
            $data = $templateContent;
            $options['member_id'] = 0;
            if (!empty($personalize) && $personalize->is_smtp == 1) {
                if($personalize->member_id > 0){
                    $options['member_id'] = $personalize->member_id;
                }
            }
            $new_file_link = "";
            if(!empty($attachment) && file_exists($attachment)){
                $att_email_queue_dir = WWW_ROOT."email_queue/".$this->Auth->user('id');
                if(!is_dir($att_email_queue_dir)){
                    mkdir($att_email_queue_dir,0777,true);
                }
                $extension = pathinfo($attachment, PATHINFO_EXTENSION);
                $new_file_name = time().".".$extension;
                $new_file_link = $att_email_queue_dir."/".$new_file_name;
                @copy($attachment, $new_file_link);
            }
            //$options['from_name'] = $APP_SMTP_FROM_NAME;
            $options['from_name'] = $APP_SMTP_FROM_NAME;
            $options['from_email'] = $SMTP_FORM_EMAIL;
            $options['subject'] = $sub;
            $options['template'] = $templateName;
            $options['format'] = 'html';
            $options['attachments'] = $new_file_link;
            EmailQueue::enqueue($to, $data, $options);
            
         }
         else{
             
             try {
                $email = new Email();
                if (!empty($personalize) && $personalize->is_smtp == 1) {
                    if($is_yahoo){
                        Email::configTransport('custom', $default);
                        $email->transport('custom');
                    }else{
                        $email->config($default);
                    }
                } else {
                    $email->transport('default');
                }


                if (isset($templateContent['no_reply']) && !empty($templateContent['no_reply'])) {
                    $email = $email->from($APP_SMTP_FROM_NAME);
                } else {
                    $email = $email->from($SMTP_FORM_EMAIL,$APP_SMTP_FROM_NAME);
                }

                $email->template($templateName)
                        ->emailFormat('html')
                        ->to($to)
                        ->viewVars($templateContent)
                        ->subject($sub);

                if (!empty($attachment)) {
                    $email->addAttachments($attachment);
                }


                $email->send();

                } catch (Exception $ex) {
                    $this->log($ex);
//                    dd($ex->getMessage());
                }
         }
 
    }

    /**
     * Before render callback.
     *
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return void
     */
    public function beforeRender(Event $event) {

        if (!array_key_exists('_serialize', $this->viewVars) &&
                in_array($this->response->type(), ['application/json', 'application/xml'])
        ) {
            $this->set('_serialize', true);
        }
    }

    public function isAuthorized($user) {
        $controller = $this->request->params['controller'];
        $access_controllers_name = array();
        //  echo  $_SESSION["userType"];exit;
        if ($_SESSION["userType"] == CMS_USER_INDICATOR) {
            //echo 'this is';exit;
            // get current controller
            // get CRM controller list from constant
            // if current controller exist in CRM controller list then no need to check further code. Just return true
            // echo "sdfsdf";exit;
            $session = $this->request->session();
            //TODO - Change the logic of saving the user permissions
            $previous_permission_version = $session->read('permission_version');
            $current_permission_version = TableRegistry::get('cmsusers')->get($user['id'])->permission_version;
            if ($current_permission_version !== $previous_permission_version) {
                unset($_SESSION['hasEpicVelocity']);
                unset($_SESSION['hasVelocity']);
                unset($_SESSION['hasLS_Fax_Rtg_user']);
                unset($_SESSION['has_only_super_rtg_user']);
                unset($_SESSION['has_limited_version']);
                unset($_SESSION['has_limited_time']);
                
                $this->loadModel('MemberPackages');
                $member_id = $user['id'];
                $result = $this->MemberPackages->hasEpicOrVelocityuser($member_id);
                if (!empty($result)) {
                    if ($result['hasEpicVelocity']) {
                        $_SESSION['hasEpicVelocity'] = true;
                    }

                    if ($result['hasVelocity']) {
                        $_SESSION['hasVelocity'] = true;
                    }
                    
                    if ($result['hasLS_Fax_Rtg_user']) {
                        $_SESSION['hasLS_Fax_Rtg_user'] = true;
                    }
                    
                    if ($result['has_super_rtg_user']) {
                        $_SESSION['has_only_super_rtg_user'] = true;
                    }
                    
                    if($result['has_limited_version']){
                       $_SESSION['has_limited_version'] = true;
                    }
                    
                     if($result['has_limited_time']){
                       $_SESSION['has_limited_time'] = true;
                    }
                    
                }
                
                $this->addPermissionsAndVersionToSession($session, $user, $current_permission_version);
                $this->limitedTimePkgCheck();
            }

            $user_permissions = $session->read('user_permissions');

            $request_action = strtolower($this->request->params['action']);

            $pages = $this->getPages();
            // print_r($pages);exit;
            if (array_key_exists($request_action, $pages)) {
                $action_page_id = $pages[$request_action];
                foreach ($user_permissions as $permission) {
                    if ($permission['page_id'] == $action_page_id) {
                        return true;
                    }
                }
            }

            if (!array_key_exists("Dashboard", $this->getModules())) {
                $this->Flash->error(__('You do not have permission to access this page'));
            }
        } else if ($_SESSION["userType"] == CRM_USER_INDICATOR) {
            // CRM user


            foreach ($_SESSION['access_controller'] as $key => $access_conroller) {
                // pr($access_conroller['controller_name']);
                $access_controllers_name[] = $access_conroller['controller_name'];
            }
            if($_SESSION['Auth']['User']['type'] == 1){
                //pr($this->Auth->user());exit;
                if(!in_array("Uploadhtml",$access_controllers_name) && $this->Auth->user('has_analysis_analyzer') == 1){
                    $access_controllers_name[] = "Uploadhtml";
                }
                
            }
            
            if (in_array($controller, $access_controllers_name)) {

                $session = $this->request->session();
                //TODO - Change the logic of saving the user permissions
                $previous_permission_version = $session->read('permission_version');
                $current_permission_version = TableRegistry::get('cmsusers')->get($user['id'])->permission_version;


                if ($current_permission_version !== $previous_permission_version) {
                    $this->addPermissionsAndVersionToSession($session, $user, $current_permission_version);
                }

                // $this->Flash->error(__('You do not have permission to access this page'));
                return true;
            }
            // Get current controller name
            // get   controller list from $_SESSION['access_controller']
            // check the current controller name exist in user's DB controller access list or not
            // if not, return false;
            // return true;
        } else if ($_SESSION["userType"] == CONTACT_USER_INDICATOR) {

            $this->loadModel('Contacts');
            $cmsuser_id = $this->Auth->user('id');
            $contact_id = $this->Auth->user('user_id');
            $client_info = $this->Contacts->find('all')->where(['id' => $contact_id, 'cmsuser_id' => $cmsuser_id])->toArray();
            $client_id = $client_info[0]['client_id'];

            $_SESSION['global_client_id'] = $client_id;
            foreach ($_SESSION['access_controller'] as $key => $access_conroller) {
                // pr($access_conroller['controller_name']);
                $access_controllers_name[] = $access_conroller['controller_name'];
            }
            //echo $controller;exit;
            if (in_array($controller, $access_controllers_name)) {
                $session = $this->request->session();
                //TODO - Change the logic of saving the user permissions
                $previous_permission_version = $session->read('permission_version');
                $current_permission_version = TableRegistry::get('cmsusers')->get($user['id'])->permission_version;
                //pr($current_permission_version);exit;
                if ($current_permission_version !== $previous_permission_version) {
                    $this->addPermissionsAndVersionToSession($session, $user, $current_permission_version);
                }
                return true;
            }
        } else if ($_SESSION["userType"] == STAF_USER_INDICATOR) {

            $session = $this->request->session();
            //TODO - Change the logic of saving the user permissions
            $previous_permission_version = $session->read('permission_version');
            $current_permission_version = TableRegistry::get('cmsusers')->get($user['id'])->permission_version;
            if ($current_permission_version !== $previous_permission_version) {
                $this->addPermissionsAndVersionToSession($session, $user, $current_permission_version);
            }

            foreach ($_SESSION['access_controller'] as $key => $access_conroller) {
                // pr($access_conroller['controller_name']);
                $access_controllers_name[] = $access_conroller['controller_name'];
            }
            if (in_array($controller, $access_controllers_name)) {


                return true;
            }
        } elseif ($_SESSION["userType"] == GUEST_USER_INDICATOR) {
            return true;
        }


        //echo $_SESSION["userType"];exit;
    }

    protected function addPermissionsAndVersionToSession($session, $user, $current_permission_version) {
        $connection = ConnectionManager::get('default');
        
        $permission_sql = 'SELECT  cmsusers.id AS user_id,pages.id AS page_id, pages.name AS page_name, modules.id AS module_id, sub_modules.name AS submodule_name, sub_modules.id AS submodule_id
FROM            cmsusers
					INNER JOIN cmsuser_usergroups ON cmsusers.id = cmsuser_usergroups.cms_user_id
					INNER JOIN usergroups ON cmsuser_usergroups.usergroup_id = usergroups.id
					INNER JOIN usergroup_roles ON usergroups.id = usergroup_roles.usergroup_id
					INNER JOIN roles ON usergroup_roles.role_id = roles.id
					INNER JOIN role_pages ON roles.id = role_pages.role_id
					INNER JOIN pages ON role_pages.page_id = pages.id
					INNER JOIN sub_modules ON pages.sub_module_id = sub_modules.id
					INNER JOIN modules ON sub_modules.module_id = modules.id
					WHERE cmsusers.id =' . $user['id'] . " order by modules.id,sub_modules.id,pages.id";

        $user_permissions = $connection->execute($permission_sql)->fetchAll('assoc');


        $session->write('user_permissions', $user_permissions);
        $session->write('permission_version', $current_permission_version);

        if ($this->Auth->user('id') == SUPER_SUPER_ADMIN_ID) {
            $modules = TableRegistry::get('modules')->find('all')->contain([
                        'SubModules' => [
                            'sort' => ['SubModules.sequence' => 'ASC']
                        ],
                        'SubModules.Pages' => [
                            'sort' => ['Pages.method_name' => 'ASC']
                        ]
                    ])
                    ->order(['sequence' => 'ASC'])
                    ->toArray();
        } else {
            $modules = TableRegistry::get('modules')->find('all')->contain([
                        'SubModules' => [
                            'sort' => ['SubModules.sequence' => 'ASC']
                        ],
                        'SubModules.Pages' => [
                            'sort' => ['Pages.method_name' => 'ASC']
                        ]
                    ])->where([
                        'id NOT IN' => [1001, 1002, 1007]
                    ])
                    ->order(['sequence' => 'ASC'])
                    ->toArray();
        }

        $modules = serialize($modules);
        $session->write('modules', $modules);
        //debug($modules);
//        $session->write('permission_version_db', $user['permission_version']);
//
//        $this->log($session->read('user_permissions'));
//        $this->log($session->read('permission_version'));
//        $this->log($session->read('permission_version_db'));
    }

    public function getModules() {
        $request_controller = strtolower($this->request->params['controller']);
        if ($request_controller == "dashboard") {
            return array('Dashboard' => 'Dashboard');
        }
        $current_module_arr = array();
        $current_submodule_arr = $this->getSubModules();
        $modules = unserialize($this->request->session()->read('modules'));
        if (!empty($modules)) {
            foreach ($modules as $module) {
                foreach ($module['sub_modules'] as $submodule) {
                    if (current($current_submodule_arr) == $submodule['id']) {
                        $current_module_arr = array($module['name'] => $module['id']);
                        break 2;
                    }
                }
            }
        }

        return $current_module_arr;
        //return  ['Master Data' =>'1002'];
    }

    public function getSubModules() {

        $request_controller = strtolower($this->request->params['controller']);
        if ($request_controller == "dashboard") {
            return array();
        }
        $current_submodule_arr = array();
        $modules = unserialize($this->request->session()->read('modules'));
        if (!empty($modules)) {
            foreach ($modules as $module) {
                foreach ($module['sub_modules'] as $submodule) {
                    if ($request_controller == strtolower($submodule['controller_name'])) {
                        $current_submodule_arr = array($submodule['name'] => $submodule['id']);
                        break 2;
                    }
                }
            }
        }
        return $current_submodule_arr; // return ['Page Management' => '2022'];
    }

    public function getPages() {
        $request_controller = strtolower($this->request->params['controller']);
        if ($request_controller == "dashboard") {
            return array();
        }
        $pages_arr = array();
        $current_submodule_arr = $this->getSubModules();
        $modules = unserialize($this->request->session()->read('modules'));
        if (!empty($modules)) {
            foreach ($modules as $module) {
                foreach ($module['sub_modules'] as $submodule) {
                    if (current($current_submodule_arr) == $submodule['id']) {
                        foreach ($submodule['pages'] as $page) {
                            $pages_arr[$page['method_name']] = $page['id'];
                        }
                        break 2;
                    }
                }
            }
        }


        // print_r( $pages_arr);exit;

        return $pages_arr;

        /*
          return ['index' =>'3035',
          'add' => '3036',
          'edit' => '3037',
          'delete' =>'3038']; */
    }

    // Function to get the client IP address
    public function get_client_ip() {
        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if (isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';
        
         if (strlen($ipaddress) > 45){
            $ipaddress = substr($ipaddress, 0,45);
        }

        
        return $ipaddress;
    }

    public function ipRestrict($current_ip = null) {

        $result = false;

        $email = $this->request->session()->read('Auth.User.email');
        if ($email) {
            $this->loadModel('Cmsusers');
            $user = $this->Cmsusers->find('all')
                    ->select(['id', 'email', 'ip', 'is_first_login'])
                    ->where(['email' => $email])
                    ->first();
            // pr($user);
            $current_ipArr = explode('.', $current_ip);

            //if there is no value initially in DB
            if (empty($user->ip)) {
                //save with current IP
                $user->ip = $current_ip . ';';
                $this->Cmsusers->save($user);
            } else {

                $allIP = explode(';', rtrim($user->ip, ";"));


                // if sum of db ips and the current ip do not cross max
                if (count($allIP) < MAXIMUM_ALLOW_IP) {
                    // save the current IP with Previous IP
                    foreach ($allIP as $key => $prev_ip) {
                        if (empty($this->getTwoFirstDigitIP($prev_ip)) || ($this->getTwoFirstDigitIP($prev_ip) == $this->getTwoFirstDigitIP($current_ip))) {
                            $user->ip = "";
                            break;
                        } else {
                            $user->ip .= $current_ip . ';';
                        }
                    }

                    if (!empty($user->ip)) {
                        $this->Cmsusers->save($user);
                    }
                } else {

                    $matching = false;

                    foreach ($allIP as $key => $prev_ip) {

                        $previousIPStr = "";
                        $currentIPStr = "";

                        $prev_ipArr = explode('.', $prev_ip);

                        //prepare previous IP string
                        if (isset($prev_ipArr[0])) {
                            $previousIPStr = $prev_ipArr[0];
                        }

                        if (isset($prev_ipArr[1])) {
                            $previousIPStr .= "." . $prev_ipArr[1];
                        }


                        //prepare current IP string
                        if (isset($current_ipArr[0])) {
                            $currentIPStr = $current_ipArr[0];
                        }

                        if (isset($current_ipArr[1])) {
                            $currentIPStr .= "." . $current_ipArr[1];
                        }

                        if ($previousIPStr == $currentIPStr) {
                            $matching = true;
                            break;
                        }
                    }

                    $result = !$matching;
                }
            }
        }

        return $result;
    }

    private function getTwoFirstDigitIP($fullIP) {

        $firstTwoPart = "";
        if (!empty($fullIP)) {

            $fullIP = trim($fullIP);

            $fullIPArray = explode(".", $fullIP);

            if (isset($fullIPArray[0]) && !empty($fullIPArray[0])) {
                $firstTwoPart = $fullIPArray[0];
            }

            if (isset($fullIPArray[1]) && !empty($fullIPArray[1])) {
                $firstTwoPart .= $fullIPArray[1];
            }
        }

        return $firstTwoPart;
    }

    public function isUserFirstLogin($user) {
        $returnValue = true;



        if (!empty($user)) {
            /* $this->loadModel('Cmsusers');
              $user = $this->Cmsusers->find('all')
              ->select(['id','email','ip','is_first_login'])
              ->where(['email' => $email])
              ->first(); */
            if ($user['is_first_login'] != 1) {
                $returnValue = false;
            } /* else {
              $user->is_first_login = 1;
              $this->Cmsusers->save($user);
              } */
        }
        return $returnValue;
    }

    public function getCategoryNameById($id = null) {
        $categoriesTable = TableRegistry::get('Categories');
        $categories = $categoriesTable->find('all')
                ->select(['id', 'name'])
                ->where([
                    'Categories.status' => 1,
                    'Categories.id' => $id
                ])
                ->first();
        $category_name = $categories->name;
        return $category_name;
    }

    public function getDateDifference($start_date = null, $end_date = null) {
        if (strtotime($start_date) > strtotime($end_date)) {
            return 0;
        } else {
            $start_date = date_create($start_date);
            $end_date = date_create($end_date);

            $interval = date_diff($start_date, $end_date);
            // return $interval->format($differenceFormat);
            return $interval->days;
        }
    }

    private function isStaffUser($user, $CmsuserUsergroupsData = null) {

        $returnValue = false;

        if (empty($CmsuserUsergroupsData)) {
            $table = TableRegistry::get("CmsuserUsergroups");
            $CmsuserUsergroupsData = $table->find('all')
                    ->select(['usergroup_id'])
                    ->where(['CmsuserUsergroups.cms_user_id' => $user['id']])
                    ->first();
        }

        // pr($users); die;
        if (isset($CmsuserUsergroupsData) && $CmsuserUsergroupsData->usergroup_id == STAFF_GROUP_ID) {
            $returnValue = true;
        }
        return $returnValue;
    }

    function _getAllStaticForms() {
        $connection = ConnectionManager::get('default');
        $packages_query = "SELECT 
            pf.package_id, 
            pf.form_id, 
            frm.category_id,
            frm.sub_category_id,
            frm.short_name form_short_name,
            frm.long_name form_long_name,
            frm.description form_description,
            frm.video_url form_video_url, 
            sc.name sub_category_name,
            pkg.name package_name
        FROM packages pkg 
        INNER JOIN package_forms pf ON pf.package_id = pkg.id
        INNER JOIN forms frm ON frm.id = pf.form_id
        INNER JOIN sub_categories sc ON sc.id = frm.sub_category_id
        WHERE pkg.type = 1 
        ORDER BY pkg.id ASC, frm.weight asc";

        $packages = $connection->execute($packages_query)->fetchAll('assoc');
        //pr($packages); die;

        $allForms = [];
        $allFormNames = [];
        if (!empty($packages)) {
            foreach ($packages as $key => $value) {
                $allForms[$value['package_id']]['name'] = $value['package_name'];
                $allForms[$value['package_id']]['forms'][$value['form_id']] = $value;
                $allFormNames[$value['form_id']] = $value['form_long_name'];
            }
        }
        // pr($allForms);
        return array($allForms, $allFormNames);
    }

    function _getAllFormsByUser($user, $package_type = null) {

        $trial_user_condition = "";
        if (!empty($user)) {
            if($user['is_trial_user'] == 1){
              //  $trial_user_condition = "AND pkg.id IN (".implode(',',TRIAL_USER_PACKAGES).")";
            }
            $connection = ConnectionManager::get('default');
            $packages_query = "SELECT mp.member_id,mp.package_id, pf.form_id, 
            frm.category_id,
            frm.sub_category_id,
            frm.short_name form_short_name,
            frm.long_name form_long_name,
            frm.description form_description,
            frm.video_url form_video_url, 
            sc.name sub_category_name,
            pkg.name package_name
        FROM member_packages mp
        INNER JOIN packages pkg ON pkg.id = mp.package_id
        INNER JOIN package_forms pf ON pf.package_id = mp.package_id
        INNER JOIN forms frm ON frm.id = pf.form_id
        INNER JOIN sub_categories sc ON sc.id = frm.sub_category_id
        WHERE pkg.type = " . $package_type . " AND mp.status = 1 AND mp.member_id = " . $user['id'] . "
        "." ".$trial_user_condition." ORDER BY pkg.id ASC, frm.weight asc";
        
            $packages = $connection->execute($packages_query)->fetchAll('assoc');
        }


        $allForms = [];
        $allFormNames = [];
        if (!empty($packages)) {
            foreach ($packages as $key => $value) {
                $allForms[$value['package_id']]['name'] = $value['package_name'];
                $allForms[$value['package_id']]['forms'][$value['form_id']] = $value;
                $allFormNames[$value['form_id']] = $value['form_long_name'];
            }
        }
        // pr($allForms);
        return array($allForms, $allFormNames);
    }

    function _getPackageWiseAllForms($package_id = null) {
        $connection = ConnectionManager::get('default');
        $packages_query = "SELECT 
            pf.package_id, 
            pf.form_id, 
            frm.category_id, frm.sub_category_id, 
            frm.short_name form_short_name, 
            frm.long_name form_long_name, 
            frm.description form_description, 
            frm.video_url form_video_url, 
            sc.name sub_category_name, 
            pkg.name package_name 

            FROM package_forms pf 
            INNER JOIN packages pkg ON pkg.id = pf.package_id 
            INNER JOIN forms frm ON frm.id = pf.form_id 
            INNER JOIN sub_categories sc ON sc.id = frm.sub_category_id

            WHERE pkg.id = $package_id 
            ORDER BY pkg.id ASC, frm.weight ASC";

        $packages = $connection->execute($packages_query)->fetchAll('assoc');
        // pr($packages); die;

        $allForms = [];
        if (!empty($packages)) {
            foreach ($packages as $key => $value) {
                $allForms[$value['package_id']]['name'] = $value['package_name'];
                $allForms[$value['package_id']]['forms'][$value['form_id']] = $value;
            }
        }
        return $allForms;
    }

    function _getSettingData() {
        $settings = [];
        $settingsTable = TableRegistry::get('Settings');
        $settings = $settingsTable->find('all')
                ->where(['Settings.id' => 1])
                ->first();
        return $settings;
    }

    private function isStaticFormPermitted($user,$assigned_package_ids,$package_id){
        $result = true;
        if($user['is_detect_trial_user'] == 1){
            if(!in_array($package_id,$assigned_package_ids)){
                $result = false;
            }
        }
       
        return $result;
    }
    private function hasPackageForUser($user_id, $package_id) {
        //$user_id = 363;
        $table_member_packages = TableRegistry::get("MemberPackages");
        $memberPackage = $table_member_packages->find('all')
                ->where([
                    'MemberPackages.member_id' => $user_id,
                    'MemberPackages.package_id' => $package_id,
                    'MemberPackages.status' => 1
                ])
                //->contain(['Packages'])
                //->order('MemberPackages.id desc')
                // ->contain(['Cmsusers', 'Packages'])
                ->toArray();
        //pr($memberPackage);exit;
        // return $memberPackage;
        if (!empty($memberPackage)) {
            return true;
        }
        return false;
    }

    public function getRTG($user) {

        if (isset($_SESSION['userType']) && $_SESSION['userType'] == STAF_USER_INDICATOR) {
            $user['id'] = $user['user_id'];
        }
        
        
        $CmsuserUsergroupsData = null;

        try {
            if (!empty($user)) {
                $table = TableRegistry::get("CmsuserUsergroups");
                $CmsuserUsergroupsData = $table->find('all')
                        ->select(['usergroup_id'])
                        ->where(['CmsuserUsergroups.cms_user_id' => $user['id']])
                        ->first();
            }
        } catch (Exception $ex) {
            
        }
        if (!empty($user) && empty($CmsuserUsergroupsData)) {
            $this->forceLoggedOut('Please pay your monthly bill in order to login into the system');
        }

        if ($this->isStaffUser($user, $CmsuserUsergroupsData)) {
            $this->redirect(['controller' => 'staff-contents', 'action' => 'show']);
        }


        // checking IP restriction
        // $restriction = $this->ipRestrict( $this->get_client_ip() );
        $restriction = false;
        if ($restriction) {
            $this->Flash->error(__('Your IP is not Allow'));
            return $this->redirect(['controller' => 'users', 'action' => 'logout']);
        } else {
            $is_first_login = $this->isUserFirstLogin($user);
            if ($is_first_login) {
                // redirect to terms and condition page
                //echo "first time";exit;
                if (!empty($user))
                    return $this->redirect(['controller' => 'Registrations', 'action' => 'terms']);
                else {
                    $this->forceLoggedOut('You are now logged out.');
                }
            }
        }


        // dashboard functionality start here
        // $user = $this->Auth->user();

        $user_creation_time = $user['created_on'];

        $current_time = date('Y-m-d h:i:s');
        $user_days = $this->getDateDifference($user_creation_time, $current_time);

        

        $allStaticForms = $this->_getAllStaticForms();

        $this->set('allStaticForms', $allStaticForms[0]);

        $allForms = $this->_getAllFormsByUser($user, 0);
        
        

        $userWiseAllForms = $allForms[0];
        $form_name_list = $allForms[1];
        $assigned_package_ids = array_keys($userWiseAllForms);

        // if($user_days >= USER_GET_REWARDED_FORM_WITHIN_DAYS){
        // for Package 2
        $userGetFormsForPackage2 = [];
        $userHasPackage = [];

        if($this->isStaticFormPermitted($user,$assigned_package_ids,PACKAGE_WAVE_2_ID))
        $package2WiseForms = $this->_getPackageWiseAllForms(PACKAGE_WAVE_2_ID);

        // pr($package2WiseForms);
        // check if the user has the same package before
        if($this->isStaticFormPermitted($user,$assigned_package_ids,PACKAGE_WAVE_2_ID))
        if (!$this->hasPackageForUser($user_id = $user['id'], $package_id = PACKAGE_WAVE_2_ID)) {

            $userHasPackage[PACKAGE_WAVE_2_ID] = -1;
            $user_get_no_of_forms_for_package_2 = floor($user_days / USER_GET_REWARDED_FORM_WITHIN_DAYS);

            // Imran change
            if ($user_get_no_of_forms_for_package_2 >= 1) {
                $user_get_no_of_forms_for_package_2++;
            }

            // Imran change
            if ($user_get_no_of_forms_for_package_2 == 0) {

                $userGetFormsForPackage2[PACKAGE_WAVE_2_ID]['name'] = (!empty($package2WiseForms[PACKAGE_WAVE_2_ID]['name'])) ? $package2WiseForms[PACKAGE_WAVE_2_ID]['name'] : '';
                $userGetFormsForPackage2[PACKAGE_WAVE_2_ID]['forms'] = [];
            } else {

                if (!empty($package2WiseForms)) {
                    foreach ($package2WiseForms as $key => $value) {

                        if ($key == PACKAGE_WAVE_2_ID) {
                            $userGetFormsForPackage2[$key]['name'] = $value['name'];

                            if (!empty($value['forms'])) {
                                foreach ($value['forms'] as $z => $frm) {
                                    if ($user_get_no_of_forms_for_package_2 == 0) {
                                        break;
                                    } else {
                                        $form_name_list[$frm['form_id']] = $frm['form_short_name'];
                                        $userGetFormsForPackage2[$key]['forms'][$frm['form_id']] = $frm;
                                        $user_get_no_of_forms_for_package_2--;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else {

            $userHasPackage[PACKAGE_WAVE_2_ID] = 1;
        }

        // end for Package 2
        // for Package 3
        $userGetFormsForPackage3 = [];
        if($this->isStaticFormPermitted($user,$assigned_package_ids,PACKAGE_WAVE_3_ID))
        $package3WiseForms = $this->_getPackageWiseAllForms(PACKAGE_WAVE_3_ID);
        // check if the user has the same package before
        if($this->isStaticFormPermitted($user,$assigned_package_ids,PACKAGE_WAVE_3_ID))
        if (!$this->hasPackageForUser($user_id = $user['id'], $package_id = PACKAGE_WAVE_3_ID)) {
            $userHasPackage[PACKAGE_WAVE_3_ID] = -1;
            $userGetFormsForPackage3[PACKAGE_WAVE_3_ID]['name'] = (!empty($package3WiseForms[PACKAGE_WAVE_3_ID]['name'])) ? $package3WiseForms[PACKAGE_WAVE_3_ID]['name'] : '';
            $userGetFormsForPackage3[PACKAGE_WAVE_3_ID]['forms'] = [];
        } else {
            $userHasPackage[PACKAGE_WAVE_3_ID] = 1;
        }
        // end for Package 3
        // for Package 4
        $userGetFormsForPackage4 = [];
        if($this->isStaticFormPermitted($user,$assigned_package_ids,PACKAGE_WAVE_4_ID))
        $package4WiseForms = $this->_getPackageWiseAllForms(PACKAGE_WAVE_4_ID);
        // check if the user has the same package before
        if($this->isStaticFormPermitted($user,$assigned_package_ids,PACKAGE_WAVE_4_ID))
        if (!$this->hasPackageForUser($user_id = $user['id'], $package_id = PACKAGE_WAVE_4_ID)) {
            $userHasPackage[PACKAGE_WAVE_4_ID] = -1;
            $userGetFormsForPackage4[PACKAGE_WAVE_4_ID]['name'] = (!empty($package4WiseForms[PACKAGE_WAVE_4_ID]['name'])) ? $package4WiseForms[PACKAGE_WAVE_4_ID]['name'] : '';
            $userGetFormsForPackage4[PACKAGE_WAVE_4_ID]['forms'] = [];
        } else {
            $userHasPackage[PACKAGE_WAVE_4_ID] = 1;
        }
        // end for Package 4
        // for Package 5
        $userGetFormsForPackage5 = [];
        if($this->isStaticFormPermitted($user,$assigned_package_ids,PACKAGE_WAVE_5_ID))
        $package5WiseForms = $this->_getPackageWiseAllForms(PACKAGE_WAVE_5_ID);
        // check if the user has the same package before
        if($this->isStaticFormPermitted($user,$assigned_package_ids,PACKAGE_WAVE_5_ID))
        if (!$this->hasPackageForUser($user_id = $user['id'], $package_id = PACKAGE_WAVE_5_ID)) {
            $userHasPackage[PACKAGE_WAVE_5_ID] = -1;
            $userGetFormsForPackage5[PACKAGE_WAVE_5_ID]['name'] = (!empty($package5WiseForms[PACKAGE_WAVE_5_ID]['name'])) ? $package5WiseForms[PACKAGE_WAVE_5_ID]['name'] : '';
            $userGetFormsForPackage5[PACKAGE_WAVE_5_ID]['forms'] = [];
        } else {
            $userHasPackage[PACKAGE_WAVE_5_ID] = 1;
        }
        // end for Package 5
        // for Package 6
        $userGetFormsForPackage6 = [];
        if($this->isStaticFormPermitted($user,$assigned_package_ids,PACKAGE_WAVE_6_ID))
        $package6WiseForms = $this->_getPackageWiseAllForms(PACKAGE_WAVE_6_ID);
        // check if the user has the same package before
        if($this->isStaticFormPermitted($user,$assigned_package_ids,PACKAGE_WAVE_6_ID))
        if (!$this->hasPackageForUser($user_id = $user['id'], $package_id = PACKAGE_WAVE_6_ID)) {
            $userHasPackage[PACKAGE_WAVE_6_ID] = -1;
            $userGetFormsForPackage6[PACKAGE_WAVE_6_ID]['name'] = (!empty($package6WiseForms[PACKAGE_WAVE_6_ID]['name'])) ? $package6WiseForms[PACKAGE_WAVE_6_ID]['name'] : '';
            $userGetFormsForPackage6[PACKAGE_WAVE_6_ID]['forms'] = [];
        } else {
            $userHasPackage[PACKAGE_WAVE_6_ID] = 1;
        }
        // end for Package 6

        $userWiseAllForms = array_merge($userWiseAllForms, $userGetFormsForPackage2, $userGetFormsForPackage3, $userGetFormsForPackage4, $userGetFormsForPackage5, $userGetFormsForPackage6);
        // }
        // pr($userGetFormsForPackage2);exit;
        $this->set('allForms', $userWiseAllForms);

        $this->request->session()->write('form_name_list', $form_name_list);

        if (empty($allForms[0])) {

            return $this->redirect(['controller' => 'settings', 'action' => 'index']);
        }
        $form_id = 0;
        $settingData = $this->_getSettingData();
        $this->set(compact('settingData', 'userHasPackage', 'form_id'));
        // pr($settingData);


        $table_package = TableRegistry::get("Packages");
        $packages = $table_package->find('all')
                // ->select(['name','price'])
                ->where([
                    'Packages.status' => 1,
                    'NOT' => ['Packages.id IN' => [PACKAGE_ID, PACKAGE_WAVE_1_ID]]
                ])
                ->toArray();
        // pr($packages);
        $allPackages = [];
        if (!empty($packages)) {
            foreach ($packages as $key => $value) {
                $allPackages[$value->id]['name'] = $value->name;
                $allPackages[$value->id]['price'] = $value->price;
            }
        }
         
        $this->set(compact('allPackages'));


        //$this->viewBuilder()->layout("after_login");
        $this->viewBuilder()->layout("new_dashboard");
    }

    public function isRTGUser($user) {

        $result = true;

        $userType = 2;
        if (isset($_SESSION["userType"])) {
            $userType = $_SESSION["userType"];
        }

        if (!empty($user) &&
                ($user["id"] == "1" || $user["id"] == "2" || $user["id"] == "1477") && $userType == 1) {
            $result = false;
        //} else if ($userType == 2 || $userType == 3) {
        } else if ($userType == 2 || $userType == 3) {
            $result = false;
        }
        
        if($_SESSION["userType"] == CRM_USER_INDICATOR){
            $result = true;
        }
//pr($userType);exit;
        return $result;
    }

    public function setUserType() {

        if (isset($_SESSION['userType'])) {
            $userType = $_SESSION['userType'];
            if ($userType == CRM_USER_INDICATOR && !Permission::isEmployeeAsAdmin()) {
                $this->viewBuilder()->layout("new_user_dashboard");
            } else if ($userType == CMS_USER_INDICATOR || Permission::isEmployeeAsAdmin()) {
                $this->viewBuilder()->layout("new_dashboard");
            } else if ($userType == CONTACT_USER_INDICATOR) {
                $this->viewBuilder()->layout("new_contact_user_dashboard");
            } else if ($userType == STAF_USER_INDICATOR) {
                $this->viewBuilder()->layout("new_dashboard");
            } elseif ($_SESSION["userType"] == 5) {

                $this->viewBuilder()->layout("custom_layout");
            }
        }
    }

    public function checkRTGuser() {
        $user = $this->Auth->user();
        
        if ($this->isRTGUser($user)) {
            $this->request->session()->write("Auth.user.hasRTG", 1);
            //check if staff or not. In case of staff, redirect to the staff form page
            $this->getRTG($user);
        } else if (!empty($user)) {

            // echo ' initialize ';
            $this->viewBuilder()->layout("custom_layout");
            //$this->redirect(['controller' => 'Dashboard','action' => 'index']);
        }
    }

    public function getTicketNotification() {
        $this->loadModel('Supports');
        $cmsuser_id = $this->Auth->user('id');

        $supports = $this->Supports->find('all')->where(['Supports.cms_user_id' => $cmsuser_id, 'Supports.parent_id' => 0,'Supports.is_read'=>0])->order(['Supports.reply_date' => 'DESC']);
        
        $ticket_count = 0;
        $supportIDs = array();
        foreach ($supports as $support) {
            
            array_push($supportIDs, $support->id);
        }
        
        
        $supportMsg = "";
        $unique_parent_ids = [];
        if (!empty($supportIDs)) {
            $supportIDs = array_unique($supportIDs);
            $supportMsg = $this->Supports->find('all')->where(['Supports.parent_id IN ' => $supportIDs,'Supports.is_read'=>0])->toArray();
        }
        
        $innerCount = array();
        if (!empty($supportMsg)) {
            foreach ($supportMsg as $s) {
                $unique_parent_ids[$s->parent_id] = 1;
                array_push($innerCount, $s->parent_id);
            }
        }
        
        $ticket_count += count($unique_parent_ids);
        $innerCount = array_count_values($innerCount);
        //echo '
';print_r($innerCount);exit;
        $result = ['supports' => $supports->toArray(), 'supportMsg' => $supportMsg, 'parentIDs' => $innerCount,'ticket_count'=>$ticket_count];

        return $result;
    }

    public function verifyUser($member_id, $auth_user_id) {
        $result = false;
        if ($member_id != $auth_user_id) {
            $result = true;
        }
        return $result;
    }

    public function hasVelocityForEmployee() {
        $result = false;
        if ($_SESSION['userType'] == CRM_USER_INDICATOR) {
            $auth_user_id = $this->Auth->user('user_id');
            if (isset($_SESSION['crm_has_velocity']) && $_SESSION['crm_has_velocity'] == 1) {
                $result = true;
            }
        }

        return $result;
    }

    public function forceLoggedOut($message) {
        $session = $this->request->session();
        $session->delete("user_permissions");
        $session->delete('permission_version');
        $session->delete('modules');
        $this->Flash->loginSuccess($message);
        return $this->redirect($this->Auth->logout());
        exit;
    }

    public function isAccessAllClients() {
        $result = false;
        if ($_SESSION['userType'] == CRM_USER_INDICATOR) {
            $auth_employee_id = $this->Auth->user('user_id');
            $is_show_all_clients = $this->Auth->user('is_show_all_clients');
            if ($is_show_all_clients == 2) {
                $result = true;
            }
        }

        return $result;
    }

    public function hasEpicvelocityForEmployee() {
        $result = false;
        if ($_SESSION['userType'] == CRM_USER_INDICATOR) {
            $auth_employee_id = $this->Auth->user('user_id');
            $is_show_all_clients = $this->Auth->user('is_show_all_clients');
            if ($is_show_all_clients == 2) {
                $access_controller = $_SESSION['access_controller'];
                if (!empty($access_controller)) {
                    foreach ($access_controller as $access) {
                        if ($access['id'] == EPICVELOCITY_CONTROLLER_ID) {
                            $result = true;
                            break;
                        }
                    }
                }
            }
        }

        return $result;
    }

    private function getAllRemainderForMember($user_type = 1, $offset = 0) {
        $this->loadModel("MemberReminders");
        $this->loadModel("App");
        $member_id = $this->Auth->user('id');
        
        if ($user_type == 2 || $user_type == 3) {
            $member_id = $this->Auth->user('user_id');
        }
        // $params['user_type'] = 1;
        // $current_remainder = $this->App->reminderOrganizeList($this->MemberReminders->hasRemainderMemberId($member_id, $user_type, false, false, $params,0,true)); // for due today 1
        
         $current_remainder = $this->MemberReminders->getReminderNotifications($member_id, $user_type,0,1); // for due today 1
         //dd($current_remainder);
        $current_remainder_others = $this->MemberReminders->getReminderNotifications($member_id, $user_type,10,2); // for over 2
        
        $return['due_today'] = $current_remainder;
        $return['others'] = $current_remainder_others;
        
        return $return;
    }

    private function getAllNoteForMember($user_type = 1, $offset = 0) {
        $this->loadModel("MemberNotes");
        $member_id = $this->Auth->user('id');
        
        if ($user_type == 2 || $user_type == 3) {
            $member_id = $this->Auth->user('user_id');
        }
        $current_note = $this->MemberNotes->getMemberNoteNotifications($member_id, $user_type,10,1); // for due today 1
        $current_note_others = $this->MemberNotes->getMemberNoteNotifications($member_id, $user_type,10,2); // for over 2
        
        $return['due_today'] = $current_note;
        $return['others'] = $current_note_others;
        return $return;
    }

    private function getAllNotificationsForMember($commonLogic = null) {
        $this->loadModel("Contacts");
        $this->loadModel("NoteDetails");
        $this->loadModel("Crmusers");
        $member_id = $this->Auth->user('id');
        $current_notification = $this->Contacts->hasNotesNotificationMemberId($member_id);
        $current_affiliate_note_notification = $this->NoteDetails->getNoteNotificationMemberId($member_id);
        //$affiliate_message = $this->Crmusers->hasMessageNotificationMemberId($member_id);
        $affiliate_message = $commonLogic->getAllAffiliateMessagesByMemberId($this->Auth->user('id'),0);
        $notification['client_message'] = $current_notification['messages'];
        $notification['affiliate_messages_data'] = $affiliate_message;
        $notification['client_note'] = $current_notification['notes'];
        $notification['affiliate_note_against_client'] = $current_affiliate_note_notification;

        return $notification;
    }

    private function getAllNotificationsForEmployee() {
        $this->loadModel("Contacts");
        $member_id = $this->Auth->user('id');
        $employee_id = $this->Auth->user('user_id');
        $current_notification = $this->Contacts->hasNotesNotificationEmployee($member_id, $employee_id);
        $notification['client_message'] = $current_notification['messages'];
        $notification['client_note'] = $current_notification['notes'];
        return $notification;
    }

    private function getAllNotificationsForClient() {
        $this->loadModel("ClientMessages");
        $this->loadModel("NoteDetails");
        $client_id = $this->Auth->user('client_id');
        $member_id = $this->Auth->user('id');
        $notification['client_message'] = $this->ClientMessages->hasMessageNotificationByClientId($client_id);
        $notification['client_note'] = $this->NoteDetails->getNotesDetailsByNoteIdWithMemberIdClientId($member_id, $client_id);

        return $notification;
    }

    public function setClientControllerAccess() {
        $result = false;
        if ($this->Auth->user() && $_SESSION['userType'] == CONTACT_USER_INDICATOR) {
            $result = true;
        }
        return $result;
    }

    public function setAffiliateControllerAccess() {
        $result = false;
        if ($this->Auth->user() && $_SESSION['userType'] == CRM_USER_INDICATOR && $_SESSION['Auth']['User']['type'] == 2) {
            $result = true;
        }

        return $result;
    }

    public function employeeAccessMethod() {
        $result = false;
        if ($_SESSION['userType'] == CRM_USER_INDICATOR && $_SESSION['Auth']['User']['type'] == 1) {
            $controller = $this->request->params['controller'];
            if (!empty($_SESSION['access_controller'])) {
                foreach ($_SESSION['access_controller'] as $cont) {

                    if (strtolower($cont['controller_name']) == strtolower($controller)) {
                        $result = true;

                        break;
                    }
                }
            }
        }

        return $result;
    }

    public function generateAffiliateList($employee_id = "",$is_employee = false) { // 1 = staff, 2 = affiliate
        $this->loadModel('Crmusers');
        $member_id = $this->Auth->user('id');
        $affiliate_client_list = [];
        $condition = "";
        $employee_list = [];
        $employee_email_list = [];
        if ($_SESSION['userType'] == CRM_USER_INDICATOR && !Permission::isEmployeeAsAdmin()) {
            $condition = "Crmusers.type = " . AFFILIATE_USER_TYPE;
        }

        if ($this->hasVelocityForEmployee() && !Permission::isEmployeeAsAdmin()) {
            $auth_employee_id = $this->Auth->user('user_id');
            if (!empty($condition)) {
                $condition .= " AND Crmusers.employee_id = " . $auth_employee_id;
            } else {
                $condition = " Crmusers.employee_id = " . $auth_employee_id;
            }
        }
        
        if($is_employee){
            if ($_SESSION['userType'] == CRM_USER_INDICATOR && $_SESSION['Auth']['User']['type'] == 1 && !Permission::isEmployeeAsAdmin()) {
                $auth_employee_id = $this->Auth->user('user_id');
                if (!empty($condition)) {
                    $condition .= " AND Crmusers.employee_id = " . $auth_employee_id;
                } else {
                    $condition = " Crmusers.employee_id = " . $auth_employee_id;
                }
            }
        }
        
        //echo $condition;exit;
        $new_condition = "";

        $affiliateList = $this->Crmusers->find('all')
                ->select(['email' => 'Crmusers.email', 'id' => 'Crmusers.id', 'name' => 'CONCAT(Crmusers.first_name," ",Crmusers.last_name)', 'type' => 'Crmusers.type', 'employee_id' => 'Crmusers.employee_id'])
                ->where(['Crmusers.cmsuser_id' => $member_id, $condition])
                ->toList();
        
        $employee_affiliate_list = [];
        $employee_new_affiliate_list = [];
        if (!empty($affiliateList)) {
            foreach ($affiliateList as $affiliate) {
                if (!empty($affiliate->email)) {
                    $affiliate->name = $affiliate->name . " (" . $affiliate->email . ")";
                }

                if ($affiliate->id > 0) {
                    if ($affiliate->type == AFFILIATE_USER_TYPE) {

                        if ($affiliate->employee_id > 0) {
                            if ($employee_id == $affiliate->employee_id) {
                                $employee_new_affiliate_list[$affiliate->id] = $affiliate->name;
                            } else {
                                $employee_affiliate_list[$affiliate->id] = $affiliate->name;
                            }
                        } else {
                            $affiliate_client_list[$affiliate->id] = $affiliate->name;
                        }
                    } else if ($affiliate->type == EMPLOYEE_TYPE) {
                        $employee_list[$affiliate->id] = $affiliate->name;
                        $employee_email_list[$affiliate->id] = $affiliate->email;
                    }
                }
            }
        }

        if (!empty($employee_id)) {
            $employee_affiliate_list = $employee_new_affiliate_list;
        }
        // pr($employee_list);exit;
        return [$affiliate_client_list, $employee_list, $employee_affiliate_list, $employee_email_list];
    }

    private function getAffliliateNotesNotification() {
        $this->loadModel('Notes');
        $this->loadModel('NoteDetails');
        $this->loadModel('ClientMessages');
        $this->loadModel('TeamMessages');
        
        $member_id = $this->Auth->user('id');
        $crmuser_id = $this->Auth->user('user_id');
        //$affliliate_message = $this->ClientMessages->hasMessageNotificationByClientId($crmuser_id, 2);
        $affliliate_message = $this->TeamMessages->getTeamReadUnreadMessagesCountByType($this->Auth->user('id'),1,$this->Auth->user('user_id'),2,0);
        
        $result = $this->Notes->getUnreadNotesByCrmuserIdWithMemberId($member_id, $crmuser_id);
        $current_affiliate_note_notification = $this->NoteDetails->getNoteNotificationCrmuserId($member_id, $crmuser_id);
        $final_result['notes'] = $result->toArray();
        $final_result['affiliate_notes'] = $current_affiliate_note_notification;
        $final_result['affliliate_message'] = $affliliate_message;
        return $final_result;
    }

    public function setSteps($step_name, $member_id) {
        $this->loadModel('CmsuserStatus');
        $result = 1;
        $memberStatusObj = $this->CmsuserStatus->getCmsuserStatusByMemberId($member_id)->toArray();
        if ($memberStatusObj[$step_name] == 0) {
            $result = 0;
        }

        $this->set("step_status", $result);
        return $result;
    }

    public function manageDomainName($personalizeObject = null, $isSetDefault = 0) {
        if (!defined('APP_SERVER_HOST_URL')) {
            if (!empty($personalizeObject)) {
                $www = "";
                if ($personalizeObject->is_www == 1) {
                    $www = "www.";
                }
                $_SESSION['APP_SERVER_HOST_URL'] = $personalizeObject->domain_type . $www . $personalizeObject->domain . "/";
                if (isset($_SESSION['APP_SERVER_HOST_URL']) && !empty($_SESSION['APP_SERVER_HOST_URL'])) {
                    define('APP_SERVER_HOST_URL', $_SESSION['APP_SERVER_HOST_URL']);
                }
            } else if (isset($_SESSION['APP_SERVER_HOST_URL']) && !empty($_SESSION['APP_SERVER_HOST_URL'])) {
                define('APP_SERVER_HOST_URL', $_SESSION['APP_SERVER_HOST_URL']);
            } elseif ($isSetDefault == 1) {
                define('APP_SERVER_HOST_URL', APP_SERVER_HOST_URL_DEFAULT);
                $_SESSION['APP_SERVER_HOST_URL'] = APP_SERVER_HOST_URL_DEFAULT;
            }
        }

        if (defined('APP_SERVER_HOST_URL')) {
            //unset($_SESSION['APP_SERVER_HOST_URL']);
        }

        //echo APP_SERVER_HOST_URL."
"; } public function getCurrentDomain() { $parse_url = parse_url($_SERVER['HTTP_REFERER']); if (isset($_SESSION['referer_domain']) && $isFromLogout == 1) { $domain = $_SESSION['referer_domain']; } else { $domain = $parse_url['host']; $_SESSION['referer_domain'] = $domain; } if (empty($domain)) { if (!empty($_SERVER['HTTP_HOST'])) { $domain = $_SERVER['HTTP_HOST']; } } $domain = str_replace("www.", "", $domain); // echo $domain; return $domain; } function getBaseUrl() { // output: /myproject/index.php $currentPath = $_SERVER['PHP_SELF']; // output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index ) $pathInfo = pathinfo($currentPath); // output: localhost $hostName = $_SERVER['HTTP_HOST']; // output: http:// $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http'; // return: http://localhost/myproject/ return $protocol.'://'.$hostName; } public function isUserMembershipActive($member_id) { $this->loadModel('Cmsusers'); if (!$this->Cmsusers->isMembershipActive($member_id)) { return $this->redirect(['controller' => 'Cmsusers', 'action' => 'logout']); } } public function filePermissionSet($file_path, $code = 0664) { //chmod($file_path, $code); } public function applicationLog($data) { $data['request']['html_content'] = "HTML_CONTENT"; Log::write("info", json_encode($data)); } public function isShowAddressDropdown() { $member_id = $this->Auth->user('id'); $is_show_dropdown = false; $this->loadModel('MemberPackages'); $member_pkg_list = $this->MemberPackages->hasSuperRTGAccessPkgByMemberId($member_id); if (in_array(SERTG_PACKAGE_ID, $member_pkg_list) || in_array(EPIC_VELOCITY_PACKAGE_ID, $member_pkg_list) || in_array(SUPER_RTG_LS_FAX_PKG_ID, $member_pkg_list)) { $is_show_dropdown = true; } return $is_show_dropdown; } public function adminTickets(){ if(isset($_SESSION["adminType"])){ $this->loadModel('Supports'); $admin_supports = $this->Supports->find('all')->where(['Status'=>1, 'is_admin_read'=>0])->orderDesc('id')->toArray(); //pr($admin_supports);exit; $temp_ticket = []; $parent_tickets = []; $parent_ids = []; if(!empty($admin_supports)){ foreach ($admin_supports as $ticket){ if($ticket->parent_id > 0){ $parent_ids[] = $ticket->parent_id; $temp_ticket[$ticket->parent_id]['children'][] = $ticket; }else{ $temp_ticket[$ticket->id]['parent'] = $ticket; } } } if(!empty($parent_ids)){ $parent_ids = array_unique($parent_ids); $admin_children = $this->Supports->find('all')->where(['id IN'=>$parent_ids])->orderDesc('id')->toArray(); if(!empty($admin_children)){ foreach ($admin_children as $ticket){ $temp_ticket[$ticket->id]['parent'] = $ticket; } } }//pr($temp_ticket);exit; $admin_supports = $temp_ticket; //pr($admin_supports);exit; $this->set(compact('admin_supports')); } } public function isLimitedVersionEnable(){ $result['status'] = false; if(isset($_SESSION['has_limited_version']) && $_SESSION['has_limited_version']){ $this->loadModel('Clients'); $this->loadModel('Settings'); $settings = $this->Settings->getCurrentSettings(['limited_version_client_count']); $total_client = $this->Clients->getTotalClientByMemberId($this->Auth->user('id')); if($total_client > $settings->limited_version_client_count){ $result['status'] = true; $result['message'] = LIMITED_VERSION_EXCEED_MESSAGE; if(!empty($result['message'])){ $result['message'] = str_replace('#_LIMITED_VERSION_CLIENT_COUNT_#', $settings->limited_version_client_count, $result['message']); } } } return $result; } public function isClientAddRestriction(){ // add customer restriction $result['status'] = false; $permitted_clients = $this->Auth->user('no_of_customers'); if($permitted_clients == 0){ return $result; } $this->loadModel('Clients'); $total_client = $this->Clients->getTotalClientByMemberId($this->Auth->user('id')); $total_client++; if($total_client > $permitted_clients){ $result['status'] = true; $result['message'] = LIMITED_VERSION_EXCEED_MESSAGE; if(!empty($result['message'])){ $result['message'] = str_replace('#_LIMITED_VERSION_CLIENT_COUNT_#', $permitted_clients, $result['message']); } } return $result; } public function systemPermission() { $user_permissions = $this->request->session()->read('user_permissions'); $this->set('user_permission', $user_permissions); $this->set('current_module', $this->getModules()); $this->set('page_list', $this->getPages()); $this->set('module_pages', $this->getPages()); } public function limitedTimePkgCheck(){ $_SESSION['limited_time_days'] = 0; $result = false; if(isset($_SESSION['has_limited_time']) && $_SESSION['has_limited_time']){ $this->loadModel('App'); $this->loadModel('Settings'); $setting = $this->Settings->getCurrentSettings(); $required_days = $setting->limited_time_count; if($required_days > 0){ $days = $this->App->daysBetween($this->Auth->user('created_on'),$this->App->getSystemCurrentTimeStamp()); if($days > $required_days){ $result = true; $_SESSION['limited_time_days'] = $required_days; } } } return $result; } // Function for user log public function appLog($data){ /*$userType = $_SESSION['userType']; if ($userType == CRM_USER_INDICATOR) { $data['action_by_type'] = 'CRMUSER'; } else if ($userType == CMS_USER_INDICATOR) { $data['action_by_type'] = 'MEMBER'; } else if ($userType == CONTACT_USER_INDICATOR) { $data['action_by_type'] = 'CONTACT_USER'; } $auth_user = $this->Auth->user(); if(!empty($auth_user)){ $data['auth_user_data'] = $auth_user; unset($data['auth_user_data']['password']); unset($data['auth_user_data']['reset_password_token']); unset($data['auth_user_data']['backup_old_password']); } $data['auth_user_ip'] = $this->get_client_ip(); $data['auth_user_agent'] = $this->getUserAgent(); if($data['request']['html_content']) { $data['request']['html_content'] = "HTML_CONTENT"; } //use Cake\Log\Log; \Cake\Log\Log::write("info", json_encode($data));*/ $manageLog = new ManageLog(); $manageLog->userLog($data); } public function array_flatten($array) { if (!is_array($array)) { return FALSE; } $result = array(); foreach ($array as $key => $value) { if (is_array($value)) { $result = array_merge($result, $this->array_flatten($value)); } else { $result[$key] = $value; } } return $result; } // Function for get current user agent public function getUserAgent() { $maxlength = 80; $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : ''; if (strlen($userAgent) < 80) { $maxlength = strlen($userAgent); } return substr($userAgent, 0, $maxlength); } public function removePasswordFromArray($array) { $flatten_array = $this->array_flatten($array); //pr($flatten_array);exit; return array_filter( // the array you wanna search in $flatten_array, // callback function to search for certain sting function ($key){ return(strpos($key,'password') !== false); }, // flag to let the array_filter(); know that you deal with array keys ARRAY_FILTER_USE_KEY ); } public function getCurrentUserType(){ $common = new \App\Utility\Common; return $common->getCurrentUserInfo(); } public function isShowAllClients() { $result = false; if ($this->getCurrentUserType() == "EMPLOYEE" ) { $is_show_all_clients = $this->Auth->user('is_show_all_clients'); if ($is_show_all_clients == 1) { $result = true; } } return $result; } public function employeeHasPermission($array, $key, $val) { foreach($array as $item) if (isset($item[$key]) && $item[$key] == $val) return true; return false; } public function splitString($string,$limit = 100){ $small = ""; if(!empty($string)){ $small = substr($string, 0, $limit); if(!empty($small) && strlen($string) > $limit){ $small .= "..."; } } return $small; } public function sendDirectEmail($templateName, $templateContent, $to, $sub = "New RTG registration", $attachment = "", $personalize = null) { $APP_SMTP_USERNAME = APP_SMTP_USERNAME; $APP_SMTP_FROM_NAME = APP_SMTP_FROM_NAME; $APP_EMAIL_CLASS = APP_EMAIL_CLASS; $APP_SMTP_HOST = APP_SMTP_HOST; $APP_SMTP_PORT = APP_SMTP_PORT; $APP_SMTP_TIMEOUT = APP_SMTP_TIMEOUT; $APP_SMTP_PASSWORD = APP_SMTP_PASSWORD; $APP_SMTP_IS_TLS = APP_SMTP_IS_TLS; if (!empty($personalize)) { $templateContent['email_signature'] = $personalize->email_signature; if ($personalize->is_smtp == 1) { $APP_SMTP_USERNAME = $personalize->username; $APP_SMTP_FROM_NAME = $personalize->smtp_from; $APP_SMTP_HOST = $personalize->smtp_host; $APP_SMTP_PORT = $personalize->smtp_port; $APP_SMTP_PASSWORD = $personalize->password; } } $SMTP_FORM_EMAIL = $APP_SMTP_USERNAME; $is_yahoo = false; if($APP_SMTP_HOST == 'sandbox.smtp.mailtrap.io'){ $SMTP_FORM_EMAIL = $APP_SMTP_FROM_NAME; }else if($APP_SMTP_HOST == "smtp.mail.yahoo.com"){ $APP_SMTP_IS_TLS = true; $is_yahoo = true; } $default = [ 'className' => $APP_EMAIL_CLASS, 'host' => $APP_SMTP_HOST, 'port' => $APP_SMTP_PORT, 'timeout' => $APP_SMTP_TIMEOUT, 'username' => $APP_SMTP_USERNAME, 'password' => $APP_SMTP_PASSWORD, 'tls' => $APP_SMTP_IS_TLS, 'log'=> true ]; if(isset($templateContent['company_email']) && !empty($templateContent['company_email'])){ $SMTP_FORM_EMAIL = $templateContent['company_email']; } if(isset($templateContent['company_name']) && !empty($templateContent['company_name'])){ $APP_SMTP_FROM_NAME = $templateContent['company_name']; } // pr($default); // pr($personalize); // exit; try { $email = new Email(); if (!empty($personalize) && $personalize->is_smtp == 1) { if($is_yahoo){ Email::configTransport('custom', $default); $email->transport('custom'); }else{ $email->config($default); } } else { $email->transport('default'); } if (isset($templateContent['no_reply']) && !empty($templateContent['no_reply'])) { $email = $email->from($APP_SMTP_FROM_NAME); } else { $email = $email->from($SMTP_FORM_EMAIL,$APP_SMTP_FROM_NAME); } $email->template($templateName) ->emailFormat('html') ->to($to) ->viewVars($templateContent) ->subject($sub); if (!empty($attachment)) { $email->addAttachments($attachment); } $email->send(); } catch (Exception $ex) { $this->log($ex); } } protected function getJsonData(){ $data = file_get_contents("php://input"); $this->data = (isset($data) && $data != '') ? json_decode($data, true) : array(); } protected function getApiResponse($response){ $this->response->type('json'); // this will convert your response to json $this->response->body(json_encode($response)); // Set your response in body $this->response->send(); // It will send your response $this->response->stop(); // At the end stop the response } protected function isValidEmployee($employee_id,$client_id){ $result = false; $is_show_all_clients = $this->Auth->user('is_show_all_clients'); //pr($this->Auth->user());exit; if($employee_id > 0 && $client_id > 0){ $this->loadModel('ClientAssignments'); $user_type = 1; if($_SESSION['Auth']['User']['type'] == 1){ $user_type = 3; } $client = $this->ClientAssignments->isExistClientId($employee_id,$client_id,$user_type); if(!empty($client)){ $result = true; } } //var_dump($result);exit; return $result; } // client login protected function isContactUser($email,$password){ $result = 0; $contactUserTable = TableRegistry::get('contacts'); $cmsUserTable = TableRegistry::get('cmsusers'); $clientTable = TableRegistry::get('clients'); $this->loadModel('Personalizes'); $this->loadModel('App'); $contact = $contactUserTable->find()->where(['email'=>$email,'password'=>$password])->toArray(); $removeArrayToContact = current($contact); $client_id = $removeArrayToContact->client_id; if($client_id > 0) { $status = $clientTable->getClientStatusByClientId($client_id); if ($status['is_portal_access'] == 0) { return 3; // for disable login access } if ($status['status'] == 2) { // 1 = Active, 2 = Inactive, 3 = Graduated/Complete return $status['status']; } } if(!empty($removeArrayToContact)){ $removeArrayToContact->last_login_time = $this->App->getSystemCurrentTimeStamp(); $contactUserTable->save($removeArrayToContact); } //dd($contactInfoInstance); //pr($contact[0]['cmsuser_id']);exit; $cmsuser_id_from_contact = $contact[0]->cmsuser_id; // if membership is revoked member id redirected to the login page if($cmsuser_id_from_contact > 0){ $this->isUserMembershipActive($cmsuser_id_from_contact); } if($contact){ $id = $contact[0]->id; $employee_id = $status['employee_id']; $cmsUser = $cmsUserTable->find()->where(['id' => $contact[0]->cmsuser_id])->toArray(); /*if(!empty($removeArrayToContact)){ $removeArrayToContact->last_login_time = $this->App->getSystemCurrentTimeStamp($cmsUser[0]->time_zone); $contactUserTable->save($removeArrayToContact); }*/ $client_name = $contact[0]->first_name." ".$contact[0]->last_name; $personalize = $this->Personalizes->getPersonalizeByMemberId($contact[0]->cmsuser_id); $member_website = ""; if(!empty($cmsUser[0]->website)){ $member_website = $cmsUser[0]->website; } //contact_name $member_name = $cmsUser[0]->username; if(!empty($cmsUser[0]->contact_name)){ $member_name = $cmsUser[0]->contact_name; } if(empty($member_name)){ $member_name = $cmsUser[0]->email; } $contactUserInfo = [ 'id'=>$contact[0]->cmsuser_id, 'email'=>$contact[0]->email, 'user_id'=>$id, 'employee_id'=>$employee_id, 'identity_iq_link'=>$cmsUser[0]->identity_iq_link, 'smart_credit_link'=>$cmsUser[0]->smart_credit_link, 'member_contact_email'=>$cmsUser[0]->contact_email, 'member_website'=>$member_website, 'member_phone'=>$cmsUser[0]->phone, 'member_name'=>$member_name, 'member_header'=>$personalize->header, 'member_footer'=>$personalize->footer, 'company_name'=>$cmsUser[0]->company_name, 'member_email'=>$cmsUser[0]->email, 'client_id'=>$client_id, 'client_name'=>$client_name, 'logo'=>$cmsUser[0]->logo, 'image_path'=>$cmsUser[0]->img_path, 'member_time_zone'=>$cmsUser[0]->time_zone ]; // IMPORTANT::::Remember, Auth->seetUser will reset all of your session to null $this->Auth->setUser($contactUserInfo); $_SESSION['client_logo_path'] = $cmsUser[0]->logo; $_SESSION['userType'] = 3; $result = 1; } return $result; } protected function isUserPermitted($controller_id){ if($this->request->is('ajax')){ return true; } if(!Permission::isPermitted($controller_id)){ $this->Flash->error('You do not have permission.'); return $this->redirect($this->referer()); } } protected function setClientStatusConstant(){ if(isset($_SESSION['client_status_list']) && !empty($_SESSION['client_status_list'])){ define("CLIENT_ACTIVE_STATUS",1); define("CLIENT_STATUS_LIST", $_SESSION['client_status_list']); } } protected function setClientStatus(){ $this->loadModel('ClientStatusTypes'); $client_status_list = $this->ClientStatusTypes->getActiveClientStatusByMemberId($this->Auth->user('id')); if(!empty($client_status_list)){ $_SESSION['client_status_list'] = $client_status_list; } } }