<?php
/**********************************************************
* Source Copyright 2014 Author                            *
* Unauthorized reproduction is not allowed                *
* Author: JPK Software Solutions Pvt. Ltd.                *
* Email: sales@visionhelpdesk.com                         *
* Owner: www.visionhelpdesk.com                           *
**********************************************************/

if(!defined('_VIS_')) die('Error: Call from undefined function');
class parser {
    var $error;
    var $message;
    var $ticket;
    var $client;
    var $logid;
    var $submitter=1;
    var $source=0;
    var $parselog_status=1; //Default success status

    function parser($pos=false) {
        if($pos) {
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'parser.php');
            $this->message=new class_parser();
        }
    }

    function read_email($path=false) {
        $this->message->read_email($path);
    }

    function parser_email() {
        $this->message->process_email(($this->message->email));
        if(!strstr($this->message->header_detail['subject'], '\"') || !strstr($this->message->header_detail['subject'], "\'"))
        {
			$this->message->header_detail['subject'] = addslashes(stripcslashes($this->message->header_detail['subject']));
		}
		$this->ticket['vis_subject']=$this->message->header_detail['subject'];
        $this->ticket['vis_status']=1; 
        if(is_numeric($this->message->header_detail['importance']) && $this->message->header_detail['importance']<=3)$prority = $this->message->header_detail['importance'];
        else if(is_numeric($this->message->header_detail['importance']) && $this->message->header_detail['importance']>3)$prority =  1;
        else {
			if(strtolower($this->message->header_detail['importance']) == 'normal')$prority = 2;
			else if(strtolower($this->message->header_detail['importance']) == 'high')$prority = 3;
			else if(strtolower($this->message->header_detail['importance']) == 'low')$prority =  1;
			else $prority = 1;
		}
        $this->ticket['vis_priority']=$prority;
        $this->ticket['vis_type']=1;
        $this->ticket['vis_channel']=1;
        $this->client['vis_group']=1;
        $this->ticket['vis_people']='';
        $this->ticket['vis_bcc']='';
        $this->client['vis_group']=1;
        $this->ticket['vis_flag']=1;
    }

    function set_people($mailqueue) {
        for($i=0;$i<count($this->message->header_detail['to_list']);$i++) {
            if($mailqueue['email']!=$this->message->header_detail['to_list'][$i]['email']) $this->ticket['vis_people'].=$this->message->header_detail['to_list'][$i]['email'].',';
        }
        for($i=0;$i<count($this->message->header_detail['cc_list']);$i++) {
            if($mailqueue['email']!=$this->message->header_detail['cc_list'][$i]['email']) $this->ticket['vis_people'].=$this->message->header_detail['cc_list'][$i]['email'].',';
        }
        $this->ticket['vis_people']=trim($this->ticket['vis_people'], ',; ');
        //if(isset($this->message->header_detail['reply-to']) && $this->message->header_detail['reply-to']!='') $this->ticket['reply_to']=$this->message->header_detail['reply-to'];
    }

    function is_mailqueue($email) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        list($cnt, $ret)=$object->get_mailqueue(VIS_TABLE_PREFIX.'mailqueue.is_enabled=1 and email="'.$email.'"', '', 0, '', 0, 0);
        $database->database_disconnect();
        return ($ret==-1)?false:$ret[0];
    }

    function is_client($email, $domain) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object=new class_client($database);
        list($cnt, $ret)=$object->get_client('( additional_email ="'.$email.'"  OR email="'.$email.'" ) and '.VIS_TABLE_PREFIX.'domain.domain_id='.$domain, '', 0, '', 0, 0,0,1);
        if($ret!=-1) {
            if($ret[0]['parent_id']!=0) {
                $subdetails=$object->get_subclient_setting($ret[0]['client_id'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
                if($subdetails[3]==0) {
					$this->parselog_status = 5;// contact access
					$ret[0]['is_banned']=1;
				}
            }
            if($ret[0]['verify']==0 && ($ret[0]['additional_email']!='' && $ret[0]['additional_email'] == $email))
            { 
				return false;
			}
        }
        $database->database_disconnect();
        return ($ret==-1)?false:$ret[0];
    }

    function is_staff($email, $department) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        $object=new class_staff($database);
        $ret=$object->get_staff('email="'.$email.'"', 0, VIS_LOCATION_AREA, $department);
        return ($ret==-1)?false:$ret[0];
    }

    function add_client($client) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $object=new class_client($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
        $mobject=new class_mail($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting=new class_setting($database);
       
        $client['vis_module']='client';
        $client['vis_operation']='add_client';
        $client['vis_is_approved']=1;
        $val=$object->get_setting('module_id=3 and title="vis_approval" and domain_id='.VIS_DOMAIN, 0, VIS_LOCATION_AREA);
        if(isset($val['content']) && $val['content']==0) $client['vis_is_approved']=0;
        $this->ticket['is_approved']=$client['vis_is_approved'];
        $this->ticket['is_banned']=0;
        $this->client['registration_required'];
        if($this->client['registration_required']!=1) {
			$ret=$object->add_client($client, 0, VIS_LOCATION_AREA);
            if($ret && $this->ticket['is_approved']==1) {
				$twofactorsetting=$object->get_setting('title="vis_two_factor_auth" ', VIS_STAFF_ID, VIS_LOCATION_AREA);
				if(isset($twofactorsetting['content']) && $twofactorsetting['content']==1){
					    $this->parselog_status=3; //Client email not verified - two factor auth
						$object->unverify_email($ret, VIS_STAFF_ID, VIS_LOCATION_AREA);
						$data['vis_module']='client';
						$setting->update_parserlog(array('status'=>$this->parselog_status), $this->logid, '', VIS_LOCATION_AREA);
						$ret=$mobject->email_notify($client, 'two_factor_auth', VIS_STAFF_ID, VIS_LOCATION_AREA);
				}
				else {
					$operation_hnd=new operation();
					$client['vis_client_id']=$ret;
					$operation_hnd->check_automation($client, $database);
					$operation_hnd->operation_flow($client, 0, VIS_LOCATION_AREA, $database);
				}
			}
		    
        }
        else {   
            $client['registration_required']=1;
            $mobject->email_notify($client, 'add_client', VIS_STAFF_ID, VIS_LOCATION_AREA);
            $this->parselog_status=4; //registration required
        	$setting->update_parserlog(array('status'=>4), $this->logid, '', VIS_LOCATION_AREA);// Client registration required
            return false;
        }
        $database->database_disconnect();
        return $ret;
    }

    function check_breaklines($message) { 
	    $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        list($breakline_count,$breaklines)=$object->get_breaklines('is_enabled=1', '', 0);
        $database->database_disconnect();
        if($breaklines!=-1) for($i=0;$i<count($breaklines);$i++) {
            if($breaklines[$i]['is_expression']==1 && preg_match('/'.$breaklines[$i]['expression'].'/', $message, $match)) { 
				$message = preg_replace("/<\/?div[^>]*\>/i", "", $message); 
				$message=preg_replace('/('.$breaklines[$i]['expression'].')/', '<div class="vis_ticket_post_break_area" onclick="$(this).find(\'div.vis_ticket_post_break_hidden_area\').toggle()">...<div class="vis_ticket_post_break_hidden_area" style="display:none"><div>$1', $message).'</div></div>';
                break;
            }
            elseif(strstr($message, $breaklines[$i]['expression'])) {
				$pos=strpos($message, $breaklines[$i]['expression']);
                $start=substr($message, 0, $pos);
                $end=substr($message, $pos);
                $start = preg_replace("/<div>/i", "", $start); 
                $end = preg_replace("/<\/?div[^>]*\>/i", "", $end); 
                $message=$start.'<div class="vis_ticket_post_break_area" onclick="$(this).find(\'div.vis_ticket_post_break_hidden_area\').toggle()">...<div class="vis_ticket_post_break_hidden_area">'.$end.'</div></div>';
                break;
            }
        }
        return $message;
    }

    function check_catchall() {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting=new class_setting($database);
        $this->parselog_status = 2; // Mailqueue not existed
        $this->logid=$setting->add_parserlog($this->message->header_detail, $this->source, $this->message->email, 0, VIS_LOCATION_AREA,$this->parselog_status);
        return false;
    }

    function check_isreply() {
        $database=new class_database();
        $domain=(isset($this->ticket['vis_domain']))?$this->ticket['vis_domain']:VIS_DOMAIN;
        $subjectSetting = $this->get_ticket_subject_setting($domain);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $object=new class_ticket($database);
        $subflag=false;
        $sub=preg_match("/^(.*)\[(.*)\]:(.*)/i", $this->ticket['vis_subject'], $matches_sb);
        if(preg_match_all("/\[[a-zA-Z0-9-]{1,}\]:/i", $this->ticket['vis_subject'], $matches)) {
            for($i=0;$i<count($matches[0]);$i++) {
                $ids=trim($matches[0][$i], '[]: ');
                // recipients like "%'.$this->message->header_detail['from_detail']['email'].'%" and
				if(VIS_SATELLITE_HELPDESK==1)
                list($cnt, $ret)=$object->get_ticket('ticket_hash="'.$ids.'" and is_deleted=0 and '.VIS_TABLE_PREFIX.'department.domain_id='.$domain, '', 0, '', 0, 0);
				else
				  list($cnt, $ret)=$object->get_ticket('ticket_hash="'.$ids.'" and is_deleted=0', '', 0, '', 0, 0);
                if($ret!=-1) $subflag=$ret[0];
            }

            if($subflag) {
                $this->ticket['vis_subject']=trim($matches_sb[3]);
                $this->ticket['vis_ticket_id']=$subflag['ticket_id'];
                $this->ticket['is_approved']=$subflag['is_approved'];
                $this->ticket['is_banned']=$subflag['is_banned'];
                $this->ticket['is_verified']=$subflag['is_verified'];
                $this->ticket['vis_department']=$subflag['department_id'];
                $this->ticket['vis_domain']=$subflag['domain_id'];
                $this->ticket['channel_id']=$subflag['channel_id'];
            }
        }
        else if($subjectSetting == 1)
        {
			if(preg_match("/Re: /i", $this->ticket['vis_subject']) === 1)
			{
				$subjectArray =  preg_split("/Re: /i",$this->ticket['vis_subject']);
				$subject = $subjectArray[1];
			}
			else if(preg_match("/FW: /i", $this->ticket['vis_subject']) === 1)
			{
				$subjectArray = preg_split("/FW: /i",$this->ticket['vis_subject']);
				$subject = $subjectArray[1];
			}
			else if(preg_match("/Fwd: /i", $this->ticket['vis_subject']) === 1)
			{
				$subjectArray =  preg_split("/Fwd: /i",$this->ticket['vis_subject']);
				$subject = $subjectArray[1];
			}
			else 
			{
				$subject = $this->ticket['vis_subject'];
			}
			$peopleEmailids = ($this->ticket['vis_people']!='')?' or email="'.$this->ticket['vis_people'].'"':'';
				
			list($cnt, $ret)=$object->get_ticket('(subject="'.$subject.'") and is_deleted=0  and  '.VIS_TABLE_PREFIX.'department.domain_id='.$domain, '', 0, '', 0, 0);

			if($ret==-1) $ret=false;
			
			else
			{
				$is_staff_reply=$this->is_staff($this->message->header_detail['from_detail']['email'], $object->ticket['vis_department']);

				if(!$is_staff_reply){ 
					$clientEmail=$currentSenderEmail='';
					for($count = 0 ;$count< count($ret) ;$count++)
					{
						$currentSenderEmail = $this->message->header_detail['from_detail']['email']; // current email send id
						include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
                        $object=new class_client($database);
                        $domain =  (VIS_SATELLITE_HELPDESK == 2 || VIS_SATELLITE_HELPDESK == 3) ? 1 : $domain;
						list($clientCnt, $clientret)=$object->get_client('( additional_email ="'.$currentSenderEmail.'"  OR email="'.$currentSenderEmail.'" ) and '.VIS_TABLE_PREFIX.'domain.domain_id='.$domain.' and '.VIS_TABLE_PREFIX.'client.client_id='.$ret[$count]['client_id'], '', 0, '', 0, 0,0,1);
						
						if($clientret==-1){$subflag=false;}
						else
						{
							$this->message->header_detail['from_detail']['email'];
							$this->ticket['vis_subject']=$this->ticket['vis_subject'];
							$this->ticket['vis_ticket_id']=$ret[$count]['ticket_id'];
							$this->ticket['is_approved']=$ret[$count]['is_approved'];
							$this->ticket['is_banned']=$ret[$count]['is_banned'];
							$this->ticket['is_verified']=$ret[$count]['is_verified'];
							$this->ticket['channel_id']=$ret[$count]['channel_id'];
							$subflag=$ret[$count];
							break;
						}
					}
						 
				}
				else
				{
					$this->ticket['vis_subject']=$this->ticket['vis_subject'];
					$this->ticket['vis_ticket_id']=$ret[0]['ticket_id'];
					$this->ticket['is_approved']=$ret[0]['is_approved'];
					$this->ticket['is_banned']=$ret[0]['is_banned'];
					$this->ticket['is_verified']=$ret[0]['is_verified'];
					$this->ticket['channel_id']=$ret[0]['channel_id'];
					$subflag=$ret[0];
				}
			}
	    } 
        return $subflag;
    }

    function create_ticket($ticket) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_ticket($database);
        $setting=new class_setting($database);
        $ret=$object->add_ticket($ticket, $ticket['vis_client'], 1);
        $ticket['vis_ticket_id']=$ticket['ticket_id']=$ret;
        if($ret) $setting->update_parserlog(array('ticket_id'=>$ticket['ticket_id'], 'mailqueue_id'=>$ticket['mail_queue'],'status'=>$this->parselog_status), $this->logid, $ticket['vis_client'], VIS_LOCATION_AREA);
        else {
			$this->parselog_status = 11;// Ticket creation error
			$setting->update_parserlog(array('status'=>$this->parselog_status), $this->logid, '', VIS_LOCATION_AREA);
			$this->forward_failed_mail($this->logid,$ticket);
		}
        if($ret) {
			include_once(VIS_PATH_FUNCTION.VIS_FUNCTION_PREFIX.'selfhelp.php'); 
			$mobject_selfhelp = new selfhelp();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'selfhelp.php');
			$selfhelp_object=new class_selfhelp($database);
			$data=explode(' ', $ticket['vis_subject']);
			$filter=VIS_TABLE_PREFIX.'selfhelp_article.language=1 and domain_id='.$ticket['vis_domain'].' and display_status!=2 and (';
			$count=count($data);
			for($i=0;$i<$count;$i++) {
				$filter.=' (';
				$sfilter='';
				for($j=0;$j<$count-$i;$j++) if(trim($data[$j])!='' && strlen($data[$j])>2) $sfilter.=' content like "%'.$data[$j].'%" and';
				$filter.=substr($sfilter, 0, -3).') or ';
			}
			$sfilter=' (';
			for($j=0;$j<$count;$j++) $sfilter.=' content like "%'.$data[$j].'%" or ';
			$filter.=substr($sfilter, 0, -3).')) limit 5';
			list($articles_info, $selfhelp)=$selfhelp_object->get_article($filter, VIS_CLIENT_ID, VIS_LOCATION_AREA);
			for($k=0; $k<count($selfhelp); $k++){
				$op['vis_article_id']=$selfhelp[$k]['article_id'];
				$selfhelp_url[$k]=$mobject_selfhelp->add_quick_url($op,$vis_email=1);
			}
			for($a=0; $a<=count($selfhelp_url); $a++){
			$ticket['art_url'].= $selfhelp_url[$a].'<br>';
			}
			
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
			$client_obj=new class_client($database);
			$subdetails=$client_obj->get_subclient_setting($ticket['vis_client'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
			$sc_parent_id = $ticket['vis_client'];
			$sc_cc ='';
			if($ticket['vis_parent_id']!=0) {	
				$sc_parent_id = $ticket['vis_parent_id'];
				list($pclinfo, $parent_client)=$client_obj->get_client('client_id='.$ticket['vis_parent_id'], '', 0, '', '', VIS_LOCATION_AREA);
				
				if($subdetails[6]==1){ 
					//Parent client should receive a copy of emails submitted by this contact
					$sc_cc =	trim($parent_client[0]['email']);						
				}				
			}
			//Receive a copy of emails submitted by parent client and other contacts
			//for seting id 7
			$sub_contatct_emaillist = $client_obj->get_subcontact_email("AND ct.parent_id =".$sc_parent_id." AND ct.client_id!=".$ticket['vis_client']);
			
			if($sub_contatct_emaillist!=-1){
				for($sc=0;$sc<count($sub_contatct_emaillist);$sc++){
					$sc_cc .= ','.trim($sub_contatct_emaillist[$sc]['email']);
				}
			}
			$ticket['sub_contact_cc'] = trim($sc_cc,',');		
				
            $operation_hnd=new operation();
            $ticket['vis_module']='ticket';
            $ticket['vis_operation']='open_new_ticket';
            $operation_hnd=new operation();
            $data=array('vis_operation'=>'open_new_ticket', 'vis_ticket_id'=>$ticket['ticket_id'], 'vis_department'=>$ticket['vis_department']);
            $operation_hnd->check_automation($data, $database);
            $operation_hnd->operation_flow($ticket, $ticket['vis_client'], VIS_LOCATION_AREA, $database);
            include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
			$staff=new class_staff($database);
			$staff->apply_roundrobin($ticket, $ticket['vis_client'], VIS_LOCATION_AREA, $database);
			$staff->apply_task_automation($ticket,$ticket['vis_client'], VIS_LOCATION_AREA, $database);			
        }
		
        $database->database_disconnect();
        return $ret;
    }

    function add_ticket_post($ticket) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
		$staff_object=new class_staff($database);
        $object=new class_ticket($database);
        $setting=new class_setting($database);
        $ticket['vis_module']='ticket';
        $ticket['vis_operation']='reply_ticket';
        $ret=$object->reply_ticket($ticket, $ticket['vis_client'], $this->submitter);
        $setting->update_parserlog(array('ticket_id'=>$ticket['vis_ticket_id'], 'ticket_post_id'=>$ret, 'mailqueue_id'=>$ticket['mail_queue'],'status'=>$this->parselog_status), $this->logid, $ticket['vis_client'], VIS_LOCATION_AREA);
        if($ret) {
            $operation_hnd=new operation();
            $ticket['vis_post_id']=$ret;
            
            if($this->submitter==2 && $ticket['channel_id']==4) {
                $tweet=$object->add_reply_tweet($ticket, $ticket['vis_client'], $this->submitter);
            }
            elseif($this->submitter==2 && $ticket['channel_id']==3) {
                $fb_msg=$object->add_reply_fb_comment($ticket, $ticket['vis_client'], $this->submitter);
            }
            
            // access code 
            if(is_numeric(VIS_STAFF_ACCESS))
            {				 
            	include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
				$client_obj=new class_client($database);
				$subdetails=$client_obj->get_subclient_setting($ticket['client_id'], VIS_CLIENT_ID, VIS_LOCATION_AREA);
				$sc_parent_id = $ticket['client_id'];
				$sc_cc ='';
				if($tickets['vis_parent_id']!=0) {	
					$sc_parent_id = $tickets['vis_parent_id'];
					list($pclinfo, $parent_client)=$client_obj->get_client('client_id='.$tickets['vis_parent_id'], '', 0, '', '', VIS_LOCATION_AREA);
					if($subdetails[6]==1){ 
						//Parent client should receive a copy of emails submitted by this contact
						$sc_cc =	trim($parent_client[0]['email']);						
					}				
				}
				//Receive a copy of emails submitted by parent client and other contacts
				//for seting id 7
				$sub_contatct_emaillist = $client_obj->get_subcontact_email("AND ct.parent_id =".$sc_parent_id." AND ct.client_id!=".$ticket['client_id']);			
				if($sub_contatct_emaillist!=-1){
					for($sc=0;$sc<count($sub_contatct_emaillist);$sc++){
						$sc_cc .= ','.trim($sub_contatct_emaillist[$sc]['email']);
					}
				}
				$tickets['sub_contact_cc'] = trim($sc_cc,','); 		
			}
			
            $operation_hnd->check_automation($ticket);
            $operation_hnd->operation_flow($ticket, $ticket['vis_client'], $this->submitter, $database);
			$staff_object->apply_task_automation($ticket, $ticket['vis_client'], $this->submitter, $database);
        }
        $database->database_disconnect();
        return $ret;
    }

    function fetch_email($mailmessage, $department_id, $domain_id, $mailqueue)  {
        $mailqueue_id=$mailqueue['mailqueue_id'];
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'parser.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $this->message=new class_parser();
        $this->message->email=$mailmessage;
        $this->parser_email();
        $database=new class_database();
        $mail_object=new class_mail($database);
        $object=new class_setting($database);
        $ret = $object->update_mailqueue_count(1,$mailqueue_id , 1, 0);
        if(!isset($this->message->header_detail['message-id']) || $this->message->header_detail['message-id']=='')
            $this->message->header_detail['message-id']=$this->message->header_detail['date'];
        $filter='unique_id="'.$this->message->header_detail['message-id'].'"';
        $message_id=$mail_object->get_fetchmail($filter, 0, VIS_LOCATION_AREA);
        if($message_id != -1) return 0;
        $message_id=$mail_object->set_fetchmail($this->message->header_detail['message-id'], 0, VIS_LOCATION_AREA);
        //$database->database_disconnect();
        if(isset($this->message->header_detail['to_list'])) {
            $count=count($this->message->header_detail['to_list']);
            for($i=0;$i<$count;$i++) {
                $mailqueue=$this->is_mailqueue($this->message->header_detail['to_list'][$i]['email']);
                if($mailqueue) {
                    $mailqueue_id=$mailqueue['mailqueue_id'];
                    $department_id=$mailqueue['department_id'];
                    $domain_id = $mailqueue['domain_id'];
                    break;
                }
            }
        }
        $this->ticket['mail_queue']=$mailqueue_id;
        $this->ticket['vis_department']=$department_id;
        $this->ticket['vis_domain']=$domain_id;
        $this->ticket['from_name']=$mailqueue['override_name'];
        $this->ticket['from_email']=$mailqueue['override_email'];
        $this->ticket['vis_from']=$mailqueue['override_name'].' <'.$mailqueue['override_email'].'>';
        $this->client['registration_required']=$mailqueue['registered_client'];
        $this->set_people($mailqueue);
        $this->process_mail($mailqueue_id, $department_id, $domain_id, $this);
        unset($this->message);
        unset($this->ticket);
    }

    function check_workflow($data, $userid, $user) {
		
        $operations['open_new_ticket']=0;
        $operations['reply_ticket']=($user==1 || $user==4)?1:2;
        $workflow_selected=array();
        $ignore_email=false;
        $reply_email=true;
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $setting=new class_setting($database);
        $operation=new operation();
        $tkt_object=new class_ticket($database);
        if(isset($operations[$data['vis_operation']])) {
            $temps=$setting->get_workflow('is_enabled=1 and FIND_IN_SET('.$operations[$data['vis_operation']].', event)', '', 0, '', $userid, $user);
            list($workinfo, $workflow)=$temps;
        }
        if(isset($workflow) && $workflow!=-1) {
            $data['subject']=$data['vis_subject'];
            $data['email']=$data['vis_from_email'];
            $data['department_id']=$data['vis_department'];
            $data['status_id']=$data['vis_status'];
            $data['priority_id']=$data['vis_priority'];
            $data['domain_id']=$data['vis_domain'];
            $data['first_name']=$data['vis_from_name'];
            $data['type_id']=$data['vis_type'];
            $data['channel_id']=$data['vis_channel'];
            $data['group_id']=$data['vis_group']; 
            $data['attachment_count'] = count($data['vis_attachment']);
            $data['flag_id']=$data['vis_flag'];
            for($i=0;$i<count($workflow);$i++) {
                $criterias=$setting->get_workflow_criteria($workflow[$i]['workflow_id'], $userid, $user);
                if($criterias!=-1 && $operation->check_workflow_criteria($criterias, $workflow[$i]['concat_type'], $data, $userid, $user))
                    $workflow_selected[]=$workflow[$i]['workflow_id'];
            }
            for($i=0;$i<count($workflow_selected);$i++) {
                $workflow_action=$setting->get_workflow_action($workflow_selected[$i], $userid, $user);
                if($workflow_action!=-1) foreach($workflow_action as $action=>$content) {
                    $database=new class_database();
                    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
                    $object=new class_ticket($database);
                    if($action==9 && $content!=0) $ignore_email=true;
                    elseif($action==12 && $content!=0) $reply_email=false;
                    elseif($action==26 && $content!=0) {
                        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
                        $mail=new class_mail($database);
                        $data['template_id']=$content;
                        //$mail->email_notify($data, 'custom_mail', $userid, $user);
                    }
                }
            }
        }
        return array(0=>$ignore_email, 1=>$reply_email);
    }

    function process_mail($mailqueue_id, $department_id, $domain_id, $object) {
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'staff.php');
        $staff_object=new class_staff($database);
        $set_object=new class_setting($database);
		$domains=$set_object->get_domain(VIS_TABLE_PREFIX.'domain.is_enabled=1 and '.VIS_TABLE_PREFIX.'domain.domain_id='.$domain_id,'','','', VIS_STAFF_ID, VIS_LOCATION_AREA); $domains= $domains[1];
		$language_id  = $domains[0]['language_id'];
        define('VIS_DOMAIN', $object->ticket['vis_domain']);
        if(!defined('VIS_LANGUAGE')) define('VIS_LANGUAGE', $language_id);

        $subjectSetting = $this->get_ticket_subject_setting($domain_id);

        if($subjectSetting == 1)
        {          
			if(preg_match("/Re: /i", $object->ticket['vis_subject']) === 1)
			{
				$subjectArray =  preg_split("/Re: /i",$object->ticket['vis_subject']);
				for($p=0;$p<count($subjectArray);$p++){
					if($subjectArray[$p]!=''){
					  $object->ticket['vis_subject'] = $subjectArray[$p];
					}
			    }
			}
			else if(preg_match("/FW: /i", $object->ticket['vis_subject']) === 1)
			{
				$subjectArray = preg_split("/FW: /i",$object->ticket['vis_subject']);
				for($p=0;$p<count($subjectArray);$p++){
					if($subjectArray[$p]!='')
					{
					  $object->ticket['vis_subject'] = $subjectArray[$p];
					}
			   }
			}
			else if(preg_match("/Fwd: /i", $object->ticket['vis_subject']) === 1)
			{
				$subjectArray = preg_split("/Fwd: /i",$object->ticket['vis_subject']);
				for($p=0;$p<count($subjectArray);$p++){
					if($subjectArray[$p]!='')
					{
						  $object->ticket['vis_subject'] = $subjectArray[$p];
					}
			    }
			}
		
	    }
        //if($this->pipe_fetchmail()==1) return false;
        if(!is_array($object->ticket))$this->parselog_status = 11;
        $this->logid=$set_object->add_parserlog($this->message->header_detail, $this->source, $this->message->email, 0, 0,$this->parselog_status);

        $is_reply=$object->check_isreply();
        if($is_reply) {
            $is_staff_reply=$object->is_staff($object->message->header_detail['from_detail']['email'], $object->ticket['vis_department']);
            if($is_staff_reply) {
				
                $staff=$staff_object->get_staff('staff_id='.$is_staff_reply['staff_id'], $is_staff_reply['staff_id'], VIS_LOCATION_AREA);
                $staff_a=$staff_object->get_staff_group('group_id='.$staff[0]['group_id'], $is_staff_reply['staff_id'], VIS_LOCATION_AREA);
                $access=explode(',', $staff_a[0]['access']);
                if(isset($access[3]) && $access[3]==0){
			         $this->parselog_status=10; // staff team access 
			         $set_object->update_parserlog(array('status'=>$this->parselog_status), $this->logid, '', VIS_LOCATION_AREA);//Staff access 
					 return false;
					 
                }
                $object->ticket['client_id']=$is_reply['client_id'];
                 $object->ticket['vis_parent_id']=$is_reply['parent_id'];
                $object->ticket['vis_to_email']=$is_reply['facebook_id'];
                $object->ticket['vis_client']=$is_staff_reply['staff_id'];
                
                $object->ticket['vis_priority']=$is_reply['priority_id'];
                $object->ticket['vis_type']=$is_reply['type_id'];
                $object->ticket['vis_flag']=$is_reply['flag_id'];
                $object->ticket['vis_status']=$is_reply['status_id'];
                
                $object->ticket['vis_from_name']=$object->message->header_detail['from_detail']['name'];
                $object->ticket['vis_from_email']=$object->message->header_detail['from_detail']['email'];
                //$object->ticket['vis_from']=$object->ticket['from_email'];
                $object->ticket['vis_to_email']=(trim($is_reply['recipients'])!='')?$is_reply['recipients']:$is_reply['email'];
                $object->submitter=2;
                define('VIS_STATUS_ACCESS', $access[27]);
                define('VIS_DEPARTMENT_ACCESS', $access[25]);
				define('VIS_PRIORITY_ACCESS', $access[28]);
				define('VIS_STAFF_ACCESS', $access[29]);
				$object->ticket['vis_send_mail_no']=1;
				define('VIS_STAFF_ID', $is_staff_reply['staff_id']);
				
            }
            else {
                $object->ticket['vis_client']=$is_reply['client_id'];
                $object->ticket['vis_from_name']=$object->message->header_detail['from_detail']['name'];
                $object->ticket['vis_from_email']=$object->message->header_detail['from_detail']['email'];
            }
            $object->ticket['vis_operation']='reply_ticket';
        }
        else {
				$vis_domain =  (VIS_SATELLITE_HELPDESK == 2 || VIS_SATELLITE_HELPDESK == 3) ? 1 : $object->ticket['vis_domain'];	
              $ret=$object->is_client($object->message->header_detail['from_detail']['email'], $vis_domain);
           
            if(!$ret) {
                //pending auto client reg allow check
                if(trim($object->message->header_detail['from_detail']['name'])!='') {
                    $name=$object->message->header_detail['from_detail']['name'];
                    $pos=strpos($name, ' ');
                    if($pos) {
                        $object->client['vis_firstname']=trim(substr($name, 0, $pos));
                        $object->client['vis_lastname']=trim(substr($name, $pos));
                    }
                    else {
                        $object->client['vis_firstname']=$object->message->header_detail['from_detail']['name'];
                    }
                }
                else {
                    $name=$object->message->header_detail['from_detail']['email'];
                    $pos=strpos($name, '@');
                    $object->client['vis_firstname']=trim(substr($name, 0, $pos));
                }

                $object->client['vis_email']=$object->message->header_detail['from_detail']['email'];
                $object->client['vis_domain']=$object->ticket['vis_domain'];
                $object->client['vis_language']=VIS_LANGUAGE;
                $client=$object->add_client($object->client);
                if($client && is_numeric($client)) {
                    $object->ticket['vis_client']=$client;
                    //$object->ticket['to_email']=$object->client['vis_email'];
                    $object->ticket['vis_from_name']=$object->message->header_detail['from_detail']['name'];
                    $object->ticket['vis_from_email']=$object->message->header_detail['from_detail']['email'];
                }
                else {
                    //client register error
                     $this->parselog_status=6;     
			         $set_object->update_parserlog(array('status'=>$this->parselog_status), $this->logid, '', VIS_LOCATION_AREA);//Staff access 
					 return false;
                }
            }
            else {
				$object->ticket['vis_client']=$ret['client_id'];
				$object->ticket['vis_parent_id']=$ret['parent_id'];
                //$object->ticket['to_email']=$ret['email'];
                $object->ticket['vis_from_name']=$ret['first_name'].' '.$ret['last_name'];
                $object->ticket['vis_from_email']=($object->message->header_detail['from_detail']['email']!='')?$object->message->header_detail['from_detail']['email']:$ret['email'];
                $object->ticket['is_approved']=$ret['is_approved'];
                $object->ticket['is_banned']=$ret['is_banned'];
                $object->ticket['vis_spam']=$ret['is_spam'];
                $object->ticket['is_verified']=$ret['is_verified'];
            }
            $object->ticket['vis_operation']='open_new_ticket';
        }
        if($object->ticket['is_approved'] == 1) 
        {
			$object->ticket['vis_to_email']=(isset($object->ticket['vis_to_email']) && $object->ticket['vis_to_email']!="")?$object->ticket['vis_to_email']:$object->message->header_detail['to'];
	    }
	     $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $set_object=new class_setting($database);
        			
        $object->ticket['received_via']=2;
        define('VIS_CLIENT_ID', $object->ticket['vis_client']);
        if($object->ticket['is_banned']==1) { 
		    if($this->parselog_status==5)
		    $set_object->update_parserlog(array('status'=>5), $this->logid, '', VIS_LOCATION_AREA);//Client acceess 
			else $set_object->update_parserlog(array('status'=>7), $this->logid, '', VIS_LOCATION_AREA);//ban client
			return false;}
        if($object->ticket['is_approved']==0) {
			$set_object->update_parserlog(array('status'=>8), $this->logid, '', VIS_LOCATION_AREA); //Not approved
            $operation_hnd=new operation();
            $object->ticket['vis_module']='ticket';
            $object->ticket['vis_operation']='open_new_ticket';
            $operation_hnd->operation_flow($object->ticket, $object->ticket['vis_client'], VIS_LOCATION_AREA);
            return false;
        }
        $database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client_obj = new class_client($database);
        $twofactorsetting=$client_obj->get_setting('title="vis_two_factor_auth" ', VIS_STAFF_ID, VIS_LOCATION_AREA);
        if(isset($twofactorsetting['content']) && $twofactorsetting['content']==1)
		{  
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
			$mobject=new class_mail($database);
			   
			if($object->ticket['is_verified'] == 0){ 
				$ret['vis_module']='client';
				$ret['vis_email'] = $ret['email'];
				$ret=$mobject->email_notify($ret, 'two_factor_auth', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$set_object->update_parserlog(array('status'=>3), $this->logid, '', VIS_LOCATION_AREA);// Client email not verified
				return false;
			}
		}
		
        if(isset($object->message->message_array['text_formatted']) && $object->message->message_array['text_formatted']!='')
            $object->ticket['vis_ticket_post']=$object->message->message_array['text_formatted'];
        else
            $object->ticket['vis_ticket_post']=nl2br($object->message->message_array['text_plain']);

        $object->ticket['vis_ticket_post']=$object->check_breaklines($object->ticket['vis_ticket_post']);
        if(isset($object->message->attachment) && is_array($object->message->attachment)) $object->ticket['vis_attachment']=$object->message->attachment;
        $workflowArray = array_merge($object->ticket,$object->client);
        $pre_action=$this->check_workflow($workflowArray, $object->ticket['vis_client'], $object->submitter);
        if(is_array($pre_action) && $pre_action[0]){
			 $set_object->update_parserlog(array('status'=>9), $this->logid, '', VIS_LOCATION_AREA);// Ignore email
			 return true;
	    }
        elseif(is_array($pre_action) && $pre_action[1]==false) $is_reply=false;
		$object->ticket['vis_private']=1;
		$object->ticket['vis_ticket_post']=addslashes($object->ticket['vis_ticket_post']);
		$object->ticket['in-reply-to'] = $this->message->header_detail['message-id'];
        if($is_reply)
            $object->add_ticket_post($object->ticket);
        else
            $object->create_ticket($object->ticket);
		
        $object->ticket['reply_to']='';

        /*$is_reply=$object->check_isreply();
        if($is_reply) {
            $object->ticket['vis_client']=$is_reply['client_id'];
            $object->ticket['vis_from_name']=$object->message->header_detail['from_detail']['name'];
            $object->ticket['vis_from_email']=$object->message->header_detail['from_detail']['email'];
        }
        else {
            $ret=$object->is_client($object->message->header_detail['from_detail']['email'], $object->ticket['vis_domain']);
            if(!$ret) {
                //pending auto client reg allow check
                $object->client['vis_email']=$object->message->header_detail['from_detail']['email'];
                $object->client['vis_domain']=$object->ticket['vis_domain'];
                $client=$object->add_client($object->client);
                if($client && is_numeric($client)) {
                    $object->ticket['vis_client']=$client;
                    $object->ticket['to_email']=$object->client['vis_email'];
                    $object->ticket['vis_from_name']=$object->message->header_detail['from_detail']['name'];
                    $object->ticket['vis_from_email']=$object->message->header_detail['from_detail']['email'];
                }
                else {
                    //client register error
                    return false;
                }
            }
            else {
                $object->ticket['vis_client']=$ret['client_id'];
                $object->ticket['to_email']=$ret['email'];
                $object->ticket['vis_from_name']=$ret['first_name'].' '.$ret['last_name'];
                $object->ticket['vis_from_email']=$ret['email'];
            }
        }
        define('VIS_DOMAIN', $object->ticket['vis_domain']);
        define('VIS_LANGUAGE', 1);
        define('VIS_CLIENT_ID', $object->ticket['vis_client']);

        if(isset($object->message->message_array['text_formatted']) && $object->message->message_array['text_formatted']!='')
            $object->ticket['vis_ticket_post']=$object->message->message_array['text_formatted'];
        else
            $object->ticket['vis_ticket_post']=nl2br($object->message->message_array['text_plain']);

        $object->ticket['vis_ticket_post']=$object->check_breaklines($object->ticket['vis_ticket_post']);
        $object->ticket['vis_attachment']=$object->message->attachment;

        if($is_reply)
            $object->add_ticket_post($object->ticket);
        else
            $object->create_ticket($object->ticket);*/
    }

    function execute_cron(){
        $database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting = new class_setting($database);
        $filter='title="last_mailqueue"';
        $last_mailqueue=$setting->get_settings($filter, 0, VIS_LOCATION_AREA);
        $last_mailqueue=$last_mailqueue[0]['content'];
        $filter='title="mailqueue_count"';
        $mailqueue_count=$setting->get_settings($filter, 0, VIS_LOCATION_AREA);
        $mailqueue_count=$mailqueue_count[0]['content'];
        $filter = 'mailqueue_type != 0 and ('.VIS_TABLE_PREFIX.'mailqueue.is_enabled = 1 OR '.VIS_TABLE_PREFIX.'mailqueue.is_enabled = 3)';
        $limit='';
        list($mailqueue_info,$mailqueue_details)=$setting->get_mailqueue($filter, $limit, 0, 0, 0, VIS_LOCATION_AREA);
        if($mailqueue_details != -1){
            for($i=0;$i<count($mailqueue_details);$i++){
                if($mailqueue_details[$i]['mailqueue_type'] == 1 || $mailqueue_details[$i]['mailqueue_type'] == 2 || $mailqueue_details[$i]['mailqueue_type'] == 3){
                    $this->check_pop3($mailqueue_details[$i]['host_name'], $mailqueue_details[$i]['port_number'], $mailqueue_details[$i]['user_name'], password_decrypt($mailqueue_details[$i]['authentication'],VIS_PASSWORD_KEY), $mailqueue_details[$i]['mailqueue_type'],  $mailqueue_details[$i]['can_delete'], $mailqueue_details[$i]['fetch_count'], $mailqueue_details[$i]['last_count'], $mailqueue_details[$i]['department_id'], $mailqueue_details[$i]['domain_id'], $mailqueue_details[$i]);
                }
                if($mailqueue_details[$i]['mailqueue_type'] == 4 || $mailqueue_details[$i]['mailqueue_type'] == 5 || $mailqueue_details[$i]['mailqueue_type'] == 6){
                     $this->check_imap($mailqueue_details[$i]['host_name'], $mailqueue_details[$i]['port_number'], $mailqueue_details[$i]['user_name'], password_decrypt($mailqueue_details[$i]['authentication'],VIS_PASSWORD_KEY), $mailqueue_details[$i]['mailqueue_type'],  $mailqueue_details[$i]['can_delete'], $mailqueue_details[$i]['fetch_count'], $mailqueue_details[$i]['last_count'], $mailqueue_details[$i]['department_id'], $mailqueue_details[$i]['domain_id'], $mailqueue_details[$i]);
                }
            }
        }
        $database->database_disconnect();
    }

    function check_imap($host, $port, $user, $password, $queue_type, $can_del, $fetch_count, $last_count, $department_id, $domain_id, $mailqueue){
		//echo '<br/><br/>mailqueue_id: '. $mailqueue['mailqueue_id'].' | Host: '.$host . ' | User: ' . $user.' | Port: '.$port.' | Queue type: '.$queue_type;
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'imap.php');
        $imap = new class_imap($user, $password, $user, $host, 'imap', $port, $queue_type);
        $imap->connect();
        $this->source=$queue_type;
        $conn = 1;
        $imap_errors = imap_errors(); // When imap_errors() is called, the error stack is subsequently cleared.
        //echo '<pre>';print_r($imap_errors); echo "</pre>"; //echo end($imap_errors);        
        if(!empty($imap_errors)){
			if(strstr(end($imap_errors), 'Invalid credentials')){
				$conn = 2;	// authentication err
				echo '<br/>Authentication to server failed'; 
			}
			else{
				$conn = 3; // connection err
				echo '<br/>Connecting to server failed'; 
			}
		}
        if($conn != $mailqueue['is_enabled'])
           $this->update_mailqueue_status(array('is_enabled' => $conn, 'mailqueue_id' => $mailqueue['mailqueue_id']));
        if($conn == 2 || $conn == 3){			
			echo '<br/>'.end($imap_errors);              
			return false;
        }
        if($imap->marubox) echo '<br/>Connected to server ';
        $new_mail_status=$imap->getTotalMails();
        //echo '<br/>new_mail_status: '. $new_mail_status;
        echo $new_mail_status;
        $st_count = $new_mail_status;
        $c=$last_count+1;
        $count = $c+$fetch_count;
        if($st_count < $count){
            $count = $st_count;
        }
        if($c>$count){
            $c=$count-20;
            if($c<=0) $c=1;
        }
        elseif($st_count==$row['last_ticket']){
            echo '<br/>There are no new emails';
            $imap->close_mailbox();
            return true;
        }
        for($i=$c;$i<=$count;$i++){
            $head=$imap->getHeaders($i);
            $body=$imap->getBody($i);
            $mailmessage = addslashes($imap->mail_message);
            if($mailmessage!=false)
            $ret=$this->fetch_email($mailmessage, $department_id, $domain_id, $mailqueue);
            if($can_del==1) $imap->deleteMails($i);
        }
        $imap->close_mailbox();
    }

    function check_pop3($host, $port, $user, $password, $queue_type, $can_del, $fetch_count, $last_count, $department_id, $domain_id, $mailqueue) {
		//echo '<br/><br/>mailqueue_id: '. $mailqueue['mailqueue_id'].' | Host: '.$host . ' | User: ' . $user.' | Port: '.$port.' | Queue type: '.$queue_type;
         include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'pop3.php');
         $pop3=new pop3();
         $this->source=$queue_type;
		$conn = 1;
         $connect=$pop3->connect($host, $port, "25" , "10,500", $queue_type);
         if(!$connect) {
            $this->update_mailqueue_status(array('is_enabled' => 3, 'mailqueue_id' => $mailqueue['mailqueue_id']));
            echo '<br/>'.$pop3->error;      
			return false;            
		}
        echo '<br/>Connected to server';
		$login = $pop3->login($user, $password);
		if(!$login){
			$conn = (stristr($pop3->error, 'Username') || stristr($pop3->error, 'password')) ? 2 : 3;			
			echo '<br/>'.$pop3->error;
			$this->update_mailqueue_status(array('is_enabled' => $conn, 'mailqueue_id' => $mailqueue['mailqueue_id']));
			return false;
		}
        echo '<br/>Authentication successful';
		$this->update_mailqueue_status(array('is_enabled' => 1, 'mailqueue_id' => $mailqueue['mailqueue_id']));
         $new_mail_status = $pop3->get_office_status();
         if(!$new_mail_status) {
            echo '<br/>'.$pop3->error;
            return true;
         }
        $st_count = $new_mail_status['count_mails'];
        $c=$last_count+1;
        $count = $c+$fetch_count;
        if($st_count < $count){
            $count = $st_count;
        }
        if($c>$count){
            $c=$count-20;
            if($c<=0) $c=1;
        } 
        elseif($st_count==$row['last_ticket']){
             echo '<br/>There are no new emails';
             $pop3->close();
             return true;
         }
         for($i=$c;$i<=$count;$i++){
			 $mailmessage=addslashes($pop3->get_mail($i));
             if($mailmessage != false)
             $ret=$this->fetch_email($mailmessage, $department_id, $domain_id, $mailqueue);
             if($can_del==1) $pop3->delete_mail($i);
         }
         $pop3->close();
    }

    function pipe_fetchmail() {
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
        $database=new class_database();
        $mail_object=new class_mail($database);
        if(!isset($this->message->header_detail['message-id']) || $this->message->header_detail['message-id']=='') return 0;
        $filter='unique_id="'.$this->message->header_detail['message-id'].'"';
        $message_id=$mail_object->get_fetchmail($filter, 0, VIS_LOCATION_AREA);
        if($message_id != -1) return 1;
        $message_id=$mail_object->set_fetchmail($this->message->header_detail['message-id'], 0, VIS_LOCATION_AREA);
        return 0;
    }

    function parse_facebook($database) {
	    if(!function_exists('file_get_contents')) {echo 'file_get_contents function missing'; return false;}
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'subsetting.php');
        $sub_object=new class_subsetting($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client_object=new class_client($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
        $mail_object=new class_mail($database);
        list($fb_info,$fb_details)=$object->get_fb_details('integration_type=4 and is_enabled=1','', 0, 0);
		//echo 'fb details count'.count($fb_details).'<br>';
	    if($fb_details!=-1) for($i=0;$i<count($fb_details);$i++) { 
			//echo 'fb-count'.$i.'<br>';
            $token=$fb_details[$i]['db_password'];
			if($token!=''){
				$filter = 'app_id='.$fb_details[$i]['integration_id'];
				list($pages_info,$pages_details)=$object->get_pages($filter,$limit,$userid, $user);
				for($p=0;$p<count($pages_details);$p++){
				if($pages_details[$p]['is_enabled']==1){
					$department_filter=VIS_TABLE_PREFIX.'department.is_enabled=1 and '.VIS_TABLE_PREFIX.'department.department_id='.$pages_details[$p]['department_id'];
					list($dpinfo, $department)=$sub_object->get_department($department_filter,'','','', VIS_STAFF_ID, VIS_LOCATION_AREA);
				$pageid=$pages_details[$p]['unique_page_id'];
				$graph_url = "https://graph.facebook.com/$pageid/feed?access_token=$token&fields=id,message,link,message_tags,name,picture,status_type,from,to,type";
				$feeds=json_decode(file_get_contents($graph_url));
				if(count($feeds->data)>0){
				for($j=0;$j<count($feeds->data);$j++){
					if($feeds->data[$j]->id!=''){
						$filter='unique_id="'.$feeds->data[$j]->id.'"';
						
						if($fb_details[$i]['admin_password']==1){
							$submitter_check = 1;		
						}else{
							$submitter_check=($pageid==$feeds->data[$j]->from->id)?0:1;
						}	
						
						if($submitter_check==1){
						$message_id=$mail_object->get_fetchmail($filter, 0, VIS_LOCATION_AREA);
						if($message_id!=-1) {
							$this->check_fb_comment($feeds->data[$j], $ticket_object, $client_object,$mail_object, $fb_details[$i],$department);
							continue;
						}else{
							//echo $feeds->data[$j]->id.'=1038464986182379_1038469682848576';  
							//echo '<br>test2<br>';
							$message_id=$mail_object->set_fetchmail($feeds->data[$j]->id, 0, VIS_LOCATION_AREA);
							$client=array();
							list($clinfo, $client)=$client_object->get_client(VIS_TABLE_PREFIX.'client.domain_id='.$department[0]['domain_id'].' and facebook_id='.$feeds->data[$j]->from->id, '', 0, '', 0, VIS_LOCATION_AREA);
							if($client!=-1)
								define('VIS_CLIENT_ID',$client[0]['client_id']);
							if($client==-1) {
								if($department[0]['registration']==1) continue;
								$client_info=array('vis_facebook_id'=>$feeds->data[$j]->from->id, 'vis_firstname'=>$feeds->data[$j]->from->name, 'vis_domain'=>$department[0]['domain_id'],'vis_department'=>$pages_details[$p]['department_id'],'vis_is_approved'=>'1','vis_login_as'=>'1');
								$client_id=$client_object->add_client($client_info, 0, VIS_LOCATION_AREA);
								if($client_id===false) {echo 'Error in client adding'; break;}
								if($client_id) {
									$operation_hnd=new operation();
									$client_info['vis_module']='client';
									$client_info['vis_operation']='add_client';
									$client_info['vis_client_id']=$client_id;
									$operation_hnd->check_automation($client_info);
									$operation_hnd->operation_flow($client_info, $client_id, VIS_LOCATION_AREA, $database);
								}
		
								list($clinfo, $client)=$client_object->get_client('client_id='.$client_id, '', 0, '', 0, VIS_LOCATION_AREA);
							}
							else $client_id=$client[0]['client_id'];
					
					        if($client[0]['is_banned']==1 || $client[0]['is_spam']==1) continue;
							$subject=substr(strip_tags($feeds->data[$j]->message),0, 20);
							$message=nl2br($feeds->data[$j]->message);
							if(isset($feeds->data[$j]->picture) && $feeds->data[$j]->picture!='') {
								//echo '<br>test4<br>';
							   $message.='<br /><img src='.$feeds->data[$j]->picture.' />';
								if($feeds->data[$j]->story!='') {
									if($subject=='') $subject=$feeds->data[$j]->story;
								}
								else {
									if($subject=='') $subject=$feeds->data[$j]->from->name.' added a new photo.';
								}
							}
							if(isset($feeds->data[$j]->description) && $feeds->data[$j]->description!='') $message.='<br />'.$feeds->data[$j]->description; else
							$ticket=array(
								'vis_domain'=>$department[0]['domain_id'],
								'vis_department'=>$department[0]['department_id'],
								'vis_status'=>1,
								'vis_priority'=>1,
								'vis_subject'=>$subject,
								'vis_type'=>1,
								'vis_channel'=>3,
								'vis_client'=>$client_id,
								'vis_ticket_post'=>$message,
								'vis_from_name'=>$feeds->data[$j]->from->name,
								'reply_to' => $feeds->data[$j]->id,
								'vis_integration_link_id'=>$feeds->data[$j]->id,
								'vis_as_client' =>'0',
								'vis_is_facebook' =>'1'
							);	
							$ret=$ticket_object->add_ticket($ticket, $client_id, VIS_LOCATION_AREA);
							if(!$ret) return false;
							if($ret) {
								$operation_hnd=new operation();
								$ticket['vis_module']='ticket';
								$ticket['vis_operation']='open_new_ticket';
								$ticket['vis_ticket_id']=$ret;
								$operation_hnd=new operation();
								$operation_hnd->check_automation($ticket, $database);
								$operation_hnd->operation_flow($ticket, $ticket['vis_client'], VIS_LOCATION_AREA, $database);
							}
					}
					}
					}
				}
				}
				}
			}
			}
	   }
        return true;
    }

    function check_fb_comment($feed, $ticket_object, $client_object,$mail_object, $fb_details,$department) {
		$comments=json_decode(file_get_contents('https://graph.facebook.com/'.$feed->id.'/comments?access_token='.$fb_details['user_name']));
	    if(isset($comments->data) && count($comments->data)!=0) {
            $users=explode('_', $feed->id);
		    for($i=0;$i<count($comments->data);$i++) {
				$filter='unique_id="'.$comments->data[$i]->id.'"';
			    $message_id=$mail_object->get_fetchmail($filter, 0, VIS_LOCATION_AREA);
			    if($message_id==-1){
					$ticket=$ticket_object->get_ticket_post_link('integration_link="'.$feed->id.'"');
					$submitter=($users[0]==$comments->data[$i]->from->id)?2:1;
					$message=nl2br($comments->data[$i]->message);
					if(isset($comments->data[$i]->picture) && $comments->data[$i]->picture!='') $message.='<br /><img src="'.$comments->data[$i]->picture.'" />';
               
                	if($ticket!=-1) {
						list($clinfo, $client)=$client_object->get_client(VIS_TABLE_PREFIX.'client.domain_id='.$department[0]['domain_id'].' and facebook_id='.$comments->data[$i]->from->id, '', 0, '', 0, VIS_LOCATION_AREA);
							
							if($client!=-1)
								define('VIS_CLIENT_ID',$client[0]['client_id']);
							if($client==-1) {
								if($department[0]['registration']==1) continue;
								$client_info=array('vis_facebook_id'=>$comments->data[$i]->from->id, 'vis_firstname'=>$comments->data[$i]->from->name, 'vis_domain'=>$department[0]['domain_id'],'vis_department'=>$department[0]['department_id'],'vis_is_approved'=>'1','vis_login_as'=>'1');
								$client_id=$client_object->add_client($client_info, 0, VIS_LOCATION_AREA);
								if($client_id===false) {echo 'Error in client adding'; break;}
								if($client_id) {
									$operation_hnd=new operation();
									$client_info['vis_module']='client';
									$client_info['vis_operation']='add_client';
									$client_info['vis_client_id']=$client_id;
									$operation_hnd->check_automation($client_info);
									$operation_hnd->operation_flow($client_info, $client_id, VIS_LOCATION_AREA, $database);
								}
		
								list($clinfo, $client)=$client_object->get_client('client_id='.$client_id, '', 0, '', 0, VIS_LOCATION_AREA);
							}
							else $client_id=$client[0]['client_id'];
							if($client[0]['is_banned']==1 || $client[0]['is_spam']==1) continue;
								$ticket=$ticket[0];
								$ticket['vis_ticket_id']=$ticket['ticket_id'];
								$ticket['ticket_id']=$ticket['ticket_id'];
								$ticket['vis_ticket_post']=str_replace(array(','), '' , $message);
								$ticket['vis_from_name']=$comments->data[$i]->from->name;
								$ticket['vis_channel']=3;
								$ticket['vis_as_client']=0;
								$ticket['vis_priority']=1;
								$ticket['vis_status']=1;
								$ticket['vis_is_facebook']=1;
								$ticket['vis_integration_link_id']=$comments->data[$i]->id;
						    $ret=$ticket_object->reply_ticket($ticket, $client_id, VIS_LOCATION_AREA);
						if($ret){
							$message_id=$mail_object->set_fetchmail($comments->data[$i]->id, 0, VIS_LOCATION_AREA);
							$ticket['vis_module']='ticket';
							$ticket['vis_operation']='reply_ticket';
							 global $operation_hnd;
							 $operation_hnd->check_automation($ticket);
							 $operation_hnd->operation_flow($ticket, $client_id, VIS_LOCATION_AREA, $database);
							//$reply=json_decode(file_get_contents('https://graph.facebook.com/'.$comments->data[$i]->id.'/comments?access_token='.$fb_details['user_name']));
							//echo '<pre>';
							//print_r($reply);
							//for($r=0;$r<count($reply->data);$r++){
								
							//}
						}
						
					
					
                	}
				
				}								
            }
        }
        return true;
    }

    function parse_twitter($database) {
	    include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $object=new class_setting($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'client.php');
        $client_object=new class_client($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'ticket.php');
        $ticket_object=new class_ticket($database);
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
        $mail_object=new class_mail($database);
	    list($twitter_info, $twitter)=$object->get_twitter_details('integration_type=2 and db_prefix=1','', 0, 0);
        if($twitter!=-1) for($i=0;$i<count($twitter);$i++) {
            require_once(VIS_PATH_PLUGINS."twitter/twitteroauth.php");
            $twitteroauth=new TwitterOAuth(base64_decode($twitter[$i]['user_name']), base64_decode($twitter[$i]['db_name']),base64_decode($twitter[$i]['db_password']), base64_decode($twitter[$i]['api_key']));
            $tweets=$twitteroauth->get($twitteroauth->host.'statuses/mentions_timeline.json', array('q'=>urlencode($content)));
			if(!isset($tweets->errors)) for($j=0;$j<count($tweets);$j++) {
				if(empty($tweets[$j]->in_reply_to_status_id_str)){
			    $filter='unique_id="tw_'.$tweets[$j]->id_str.'"';
                $message_id=$mail_object->get_fetchmail($filter, 0, VIS_LOCATION_AREA);
                if($message_id!=-1) continue;
                $message_id=$mail_object->set_fetchmail('tw_'.$tweets[$j]->id_str, 0, VIS_LOCATION_AREA);
                //create ticket here
                $client=array();
                list($clinfo, $client)=$client_object->get_client(VIS_TABLE_PREFIX.'client.department='.$twitter[$i]['department_id'].' and twitter_id="@'.$tweets[$j]->user->screen_name.'"', '', 0, '', 0, VIS_LOCATION_AREA);
				if($client!=-1)
					define('VIS_CLIENT_ID',$client[0]['client_id']);
			    if($client==-1) {
                    $dept=$ticket_object->get_department('department_id='.$twitter[$i]['department_id'], 0, VIS_LOCATION_AREA);
				    if($dept[0]['registration']==1) continue;
                    $client_info=array('vis_email'=>'@'.$tweets[$j]->user->screen_name, 'vis_twitter_id'=>'@'.$tweets[$j]->user->screen_name, 'vis_firstname'=>$tweets[$j]->user->name,'vis_is_approved'=>'1','vis_login_as'=>'3','vis_domain'=>$dept[0]['domain_id'],'vis_department'=>$dept[0]['department_id']);
				    $client_id=$client_object->add_client($client_info, 0, VIS_LOCATION_AREA);
				    if($client_id===false) {echo 'Error in client adding'; break;}
                    if($ret) {
                        $operation_hnd=new operation();
                        $ticket['vis_module']='ticket';
                        $ticket['vis_operation']='reply_ticket';
                        $ticket['vis_post_id']=$ret;
                        $operation_hnd=new operation();
                        $client_info['vis_module']='client';
                        $client_info['vis_operation']='add_client';
                        $client_info['vis_client_id']=$client_id;
                        $operation_hnd->check_automation($client_info);
                        $operation_hnd->operation_flow($client_info, $client_id, VIS_LOCATION_AREA, $database);
                    }

                    list($clinfo, $client)=$client_object->get_client('client_id='.$client_id, '', 0, '', 0, VIS_LOCATION_AREA);
                }
                else $client_id=$client[0]['client_id'];
			    if($client[0]['is_banned']==1 || $client[0]['is_spam']==1) continue;
                $subject=substr(strip_tags($tweets[$j]->text),0, 20);
                $message=nl2br($tweets[$j]->text);
                $ticket=array(
                    'vis_domain'=>$twitter[$i]['domain_id'],
                    'vis_department'=>$twitter[$i]['department_id'],
                    'vis_status'=>1,
                    'vis_priority'=>1,
                    'vis_subject'=>$subject,
                    'vis_type'=>1,
                    'vis_channel'=>4,
                    'vis_client'=>$client_id,
                    'vis_ticket_post'=>$message,
                    'vis_from_name'=>$tweets[$j]->user->name,
                    'vis_integration_link_id'=>$tweets[$j]->id,
				    'reply_to' => $tweets[$j]->id_str,
                 	'vis_as_client' =>'0',
					'vis_is_twitter' =>'1'
                );
			    $ret=$ticket_object->add_ticket($ticket, $client_id, VIS_LOCATION_AREA);
                if(!$ret) return false;
                if($ret) {
                    $operation_hnd=new operation();
                    $ticket['vis_module']='ticket';
                    $ticket['vis_operation']='open_new_ticket';
                    $ticket['vis_ticket_id']=$ret;
                    $operation_hnd=new operation();
                    $operation_hnd->check_automation($ticket, $database);
                    $operation_hnd->operation_flow($ticket, $ticket['vis_client'], VIS_LOCATION_AREA, $database);
                }
				}elseif(!empty($tweets[$j]->in_reply_to_status_id_str)){
					$filter='unique_id="tw_'.$tweets[$j]->in_reply_to_status_id_str.'"';
					$message_id=$mail_object->get_fetchmail($filter, 0, VIS_LOCATION_AREA);
					if($message_id!=-1) {
						list($clinfo, $client)=$client_object->get_client(VIS_TABLE_PREFIX.'client.department='.$twitter[$i]['department_id'].' and twitter_id="@'.$tweets[$j]->user->screen_name.'"', '', 0, '', 0, VIS_LOCATION_AREA);
					if($client!=-1)
						define('VIS_CLIENT_ID',$client[0]['client_id']);
						$this->check_tw_comment($tweets[$j], $ticket_object, $client[0]['client_id'], $mail_object, $twitter[$i]);
						continue;
					}
				}
            }
        }
        return true;
    }

    function check_tw_comment($tweet, $ticket_object, $client_id, $mail_object, $twitter) {
		$filter='unique_id="tw_'.$tweet->id_str.'"';
        $message_id=$mail_object->get_fetchmail($filter, 0, VIS_LOCATION_AREA);
		if($message_id==-1){
			$ticket_post=$ticket_object->get_ticket_post_link('integration_link="'.$tweet->in_reply_to_status_id_str.'"');
			if($ticket_post!=-1){ 
				$message_id=$mail_object->set_fetchmail('tw_'.$tweet->id_str, 0, VIS_LOCATION_AREA);
				$ticket=$ticket_post[0];
				$ticket['vis_ticket_id']=$ticket['ticket_id'];
				$ticket['ticket_id']=$ticket['ticket_id'];
				$ticket['vis_ticket_post']=$tweet->text;
				$ticket['vis_from_name']=$tweet->user->name;
				$ticket['channel_id']=4;
				$ticket['vis_as_client']=0;
				$ticket['vis_priority']=1;
				$ticket['vis_status']=1;
				$ticket['vis_is_twitter']=1;
				$ticket['vis_integration_link_id']=$tweet->id_str;
				$ret=$ticket_object->reply_ticket($ticket, $client_id, VIS_LOCATION_AREA);
				if($ret){
					$ticket['vis_module']='ticket';
					$ticket['vis_operation']='reply_ticket';
					 global $operation_hnd;
					 $operation_hnd->check_automation($ticket);
					 $operation_hnd->operation_flow($ticket, $client_id, VIS_LOCATION_AREA, $database);
				}
			}
		}
        return true;
    }
    
    function update_mailqueue_status($data){
    	// update email queue status to 2
           $database = new class_database();
	   include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
	   $setting_obj = new class_setting($database);
	   $ret = $setting_obj->update_mailqueue_status($data);
	   $database->database_disconnect();
    }
    
    function forward_failed_mail($logid,$ticket) {
		$database=new class_database();
        include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
		$setting=new class_setting($database);
		$filter = 'mailqueue_id = '.$ticket['mail_queue'];
		$limit='';
		list($mailqueue_info,$mailqueue_details)=$setting->get_mailqueue($filter, $limit, 0, 0, 0, VIS_LOCATION_AREA);
		if($mailqueue_details[0]['forward_email_flag']==1 && $mailqueue_details[0]['forward_email'] != '') {
			$data = array();
			include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'mail.php');
			$mail = new class_mail($database);
			$filter_log  = " parserlog_id=".$logid;
			$parser_log  = $setting->get_parser_log($filter_log, $limit, 0, 0, 0, VIS_LOCATION_AREA);
			$parser_data = $setting->get_parser_data($this->logid,0,VIS_LOCATION_AREA);
			$data['email'] = $mailqueue_details[0]['forward_email'];
			$data['from_email'] = $parser_log[1][0]['from_email'];
			$data['vis_department'] = $ticket['vis_department'];
			$data['vis_domain'] = $ticket['vis_domain'];
			$data['subject'] = $parser_log[1][0]['subject'];
			$data['content'] = addslashes($ticket['vis_ticket_post']);
			$data['template_id'] = 14;
			$data['mail_queue'] = $ticket['mail_queue'];
			$ret=$mail->email_notify($data, 'forward_failed_email', VIS_STAFF_ID, VIS_LOCATION_AREA);
		}
		$database->database_disconnect();
	}
	function get_ticket_subject_setting($domain)
	{
		$database=new class_database();
		include_once(VIS_PATH_CLASS.VIS_CLASS_PREFIX.'setting.php');
        $setting_obj = new class_setting($database);
        $module_setting=$setting_obj->get_module_setting('domain_id='.$domain.' and module_id=2 ', 0, VIS_LOCATION_AREA);
        return $module_setting['vis_enable_subject_match'];
    }
}
?>
