<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
 * The contents of this file are subject to the SugarCRM Public License Version
 * 1.1.3 ("License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by SugarCRM" logo and
 *    (ii) the SugarCRM copyright notice
 * in the same form as they appear in the distribution.  See full license for
 * requirements.
 *
 * The Original Code is: SugarCRM Open Source
 * The Initial Developer of the Original Code is SugarCRM, Inc.
 * Portions created by SugarCRM are Copyright (C) 2004-2006 SugarCRM, Inc.;
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 ********************************************************************************/
/*********************************************************************************

 * Description:  Defines the English language pack for the base application.
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 ********************************************************************************/

/*
 *returns a list of objects a message can be scoped by, the list contacts the current campaign
 *name and list of all prospects associated with this campaign..
 *
 */
function get_message_scope_dom($campaign_id, $campaign_name,$db=null, $mod_strings=array()) {
		
	//find prospect list attached to this campaign..
	$query =  "SELECT prospect_list_id, prospect_lists.name "; 
	$query .= "FROM prospect_list_campaigns ";
	$query .= "INNER join prospect_lists on prospect_lists.id = prospect_list_campaigns.prospect_list_id "; 
	$query .= "WHERE prospect_lists.deleted = 0 "; 
	$query .= "AND prospect_list_campaigns.deleted=0 "; 
	$query .= "AND campaign_id='".$campaign_id."'";
	$query.=" and prospect_lists.list_type not like 'exempt%'";
	
	if (empty($db)) {
		if (!class_exists('PearDatabase')) {
			
		}
		$db = & PearDatabase::getInstance();
	}
	if (empty($mod_strings) or !isset($mod_strings['LBL_DEFAULT'])) {
		global $current_language;
		$mod_strings = return_module_language($current_language, 'Campaigns');
	}
	
	//add campaign to the result array.
	//$return_array[$campaign_id]= $campaign_name . ' (' . $mod_strings['LBL_DEFAULT'] . ')';
	
	$result=$db->query($query);
	while(($row=$db->fetchByAssoc($result))!= null) {
		$return_array[$row['prospect_list_id']]=$row['name'];
	}
	if (empty($return_array)) $return_array=array(); 	
	else return $return_array;
}

function get_campaign_mailboxes(&$emails) {
	if (!class_exists('InboundEmail')) {
		require('modules/InboundEmail/InboundEmail.php');
	}
	$query =  "select id,name,stored_options from inbound_email where mailbox_type='bounce' and status='Active' and deleted='0'"; 
	if (empty($db)) {
		if (!class_exists('PearDatabase')) {
			
		}
		$db = & PearDatabase::getInstance();
	}
	$result=$db->query($query);
	while(($row=$db->fetchByAssoc($result))!= null) {
		$return_array[$row['id']]=$row['name'];
		
		$emails[$row['id']]=InboundEmail::get_stored_options('from_addr','nobody@example.com',$row['stored_options']);
		
	}

	if (empty($return_array)) $return_array=array(''=>''); 	
	return $return_array;
	
}

function log_campaign_activity($identifier, $activity, $update=true, $clicked_url_key=null) {

	$return_array = array();
		
	if (!class_exists('PearDatabase')) {
		
	}
	$db = & PearDatabase::getInstance();

	$query1="select * from campaign_log where target_tracker_key='$identifier' and activity_type='$activity'";
	if (!empty($clicked_url_key)) {
		$query1.=" AND related_id='$clicked_url_key'";
	}
	$current=$db->query($query1);
	$row=$db->fetchByAssoc($current);

    	if ($row==null) {	
    		$query="select * from campaign_log where target_tracker_key='$identifier' and activity_type='targeted'";
    		$targeted=$db->query($query);
    		$row=$db->fetchByAssoc($targeted);
            
            //if activity is removed and target type is users, then a user is trying to opt out
            //of emails.  This is not possible as Users Table does not have opt out column. 
            if ($row  && (strtolower($row['target_type']) == 'users' &&  $activity == 'removed' )) {
                $return_array['target_id']= $row['target_id'];
                $return_array['target_type']= $row['target_type']; 
                return $return_array;
            }
            elseif ($row){                
    			$data['id']="'" . create_guid() . "'";
    			$data['campaign_id']="'" . $row['campaign_id'] . "'";
    			$data['target_tracker_key']="'" . $identifier . "'";
    			$data['target_id']="'" .  $row['target_id'] . "'";
    			$data['target_type']="'" .  $row['target_type'] . "'";
    			$data['activity_type']="'" .  $activity . "'";
    			$data['activity_date']="'" . gmdate("Y-m-d H:i:s") . "'";
    			$data['list_id']="'" .  $row['list_id'] . "'";
                $data['marketing_id']="'" .  $row['marketing_id'] . "'";
    			$data['hits']=1;
    			if (!empty($clicked_url_key)) {
    				$data['related_id']="'".$clicked_url_key."'";
    				$data['related_type']="'".'CampaignTrackers'."'";				
    			}
    			//values for return array..
    			$return_array['target_id']=$row['target_id'];
    			$return_array['target_type']=$row['target_type'];		
       			$insert_query="INSERT into campaign_log (" . implode(",",array_keys($data)) . ")"; 
       			$insert_query.=" VALUES  (" . implode(",",array_values($data)) . ")"; 
       			$db->query($insert_query);
    		}
    	} else {
    
    		$return_array['target_id']= $row['target_id'];
    		$return_array['target_type']= $row['target_type'];		
    
    		$query1="update campaign_log set hits=hits+1 where id='{$row['id']}'";
    		$current=$db->query($query1);
            
    	}
        
    	return $return_array;
    }


function campaign_log_lead_entry($campaign_id, $target_id,$rel_bean,$activity_type){
    	if (!class_exists('PearDatabase')) {
		
	    }
    	$db = & PearDatabase::getInstance();        
            require_once('modules/CampaignLog/CampaignLog.php');                      

                    //create campaign tracker id and retrieve related bio bean                 
                     $tracker_id = create_guid();                          
                    //create new campaign log record.
                    $campaign_log = new CampaignLog();
                    $campaign_log->campaign_id = $campaign_id;
                    $campaign_log->target_tracker_key = $tracker_id;
                    $campaign_log->target_id = $target_id;
                    $campaign_log->related_id = $rel_bean->id;
                    $campaign_log->target_type = $rel_bean->module_dir;
                    $campaign_log->activity_type = $activity_type;
                    //save the campaign log entry
                    $campaign_log->save();                                        
}

function get_campaign_urls($campaign_id) {
	$return_array=array();

	if (!empty($campaign_id)) {
		
		if (!class_exists('PearDatabase')) {
			
		}
		$db = & PearDatabase::getInstance();

		$query1="select * from campaign_trkrs where campaign_id='$campaign_id' and deleted=0";
		$current=$db->query($query1);
		while (($row=$db->fetchByAssoc($current)) != null) {
			$return_array['{'.$row['tracker_name'].'}']=$row['tracker_name'] . ' : ' . $row['tracker_url'];
		}		
	}
	return $return_array;
}

/*
 * This function takes in a bean from a lead, propsect, or contact and returns an array containing 
 * all subscription lists that the bean is a part of, and all the subscriptions that the bean is not 
 * a part of.  The array elements have the key names of "subscribed" and "unsusbscribed".  These elements contain an array
 * of the corresponding list.  In other words, the "subscribed" element holds another array that holds the subscription information. 
 * 
 * The subscription information is a concatenated string that holds the prospect list id and the campaign id, seperated by at "@" character.
 * To parse these information string into something more usable, use the "process subscriptions()" function
 *  
 * */
function get_subscription_lists($focus) {
    $subs_arr = array();
    $unsubs_arr = array();
  
    //get all prospect lists belonging to Campaigns of type newsletter
    $all_news_type_pl_query = "select c.name, pl.list_type, plc.campaign_id, plc.prospect_list_id "; 
    $all_news_type_pl_query .= "from prospect_list_campaigns plc , campaigns c, prospect_lists pl "; 
    $all_news_type_pl_query .= "where plc.campaign_id = c.id ";
    $all_news_type_pl_query .= "and plc.prospect_list_id = pl.id ";
    $all_news_type_pl_query .= "and c.campaign_type = 'NewsLetter'  and pl.deleted = 0 ";
    $all_news_type_pl_query .= "and (pl.list_type ='exempt' or pl.list_type ='default') ";
    $all_news_type_list =$focus->db->query($all_news_type_pl_query);

    //build array of all newsletter campaigns  
    $news_type_list_arr = array();
    while ($row = $focus->db->fetchByAssoc($all_news_type_list)){$news_type_list_arr[] = $row;}        

    //now get all the campaigns that the current user is assigned to
    $all_plp_current = "select prospect_list_id from prospect_lists_prospects where related_id = '$focus->id' and deleted = 0 ";

    //build array of prospect lists that this user belongs to
    $current_plp =$focus->db->query($all_plp_current );
    $current_plp_arr = array();
    while ($row = $focus->db->fetchByAssoc($current_plp)){$current_plp_arr[] = $row;}

   //For each  prospect list of type 'NewsLetter', check to see if current user is already in list, 
    foreach($news_type_list_arr as $news_list){
        $match = 'false';

        //perform this check against each prospect list this user belongs to
        foreach($current_plp_arr as $current_list_key => $current_list){//echo " new entry from current lists user is subscribed to-------------"; 
            //compare current user list id against newsletter id
            if ($news_list['prospect_list_id'] == $current_list['prospect_list_id']){
                //if id's match, user is subscribed to this list, check to see if this is an exempt list,

                if($news_list['list_type'] == 'exempt'){
                    //this is an exempt list, so process
                    if(array_key_exists($news_list['name'],$subs_arr)){
                        //first, add to unsubscribed array
                        $unsubs_arr[$news_list['name']] = $subs_arr[$news_list['name']];
                        //now remove from exempt subscription list
                        unset($subs_arr[$news_list['name']]);
                    }else{
                        //we know this is an exempt list the user belongs to, but the
                        //non exempt list has not been processed yet, so just add to exempt array
                        $unsubs_arr[$news_list['name']] = "prospect_list@".$news_list['prospect_list_id']."@campaign@".$news_list['campaign_id'];
                    }
                    $match = 'false';//although match is false, this is an exempt array, so 
                    //it will not be added a second time down below
                }else{
                    //this list is not exempt, and user is subscribed, so add to subscribed array
                    //as long as this list is not in exempt array
                    if(!array_key_exists($news_list['name'],$unsubs_arr)){
                        $subs_arr[$news_list['name']] = "prospect_list@".$news_list['prospect_list_id']."@campaign@".$news_list['campaign_id'];
                        $match = 'true';   
                    }
                }
            }else{
                //do nothing, there is no match
                }
        }
         //if this newsletter id never matched a user subscription..
         //..then add to available(unsubscribed) NewsLetters if list is not of type exempt
         if(($match == 'false') && ($news_list['list_type'] != 'exempt')){  
            $unsubs_arr[$news_list['name']] = "prospect_list@".$news_list['prospect_list_id']."@campaign@".$news_list['campaign_id'];                
        }
    
    }
    $return_array['unsubscribed'] = $unsubs_arr;
    $return_array['subscribed'] = $subs_arr; 
    return $return_array;
}


/*
 * This function will take an array of strings that have been created by the "get_subscription_lists()" method
 * and parses it into an array.  The returned array has it's key's labeled in a specific fashion.  
 * 
 * Each string produces a campaign and a prospect id.  The keys are appended with a number specifying the order 
 * it was process in.  So an input array containing 3 strings will have the following key values:
 * "prospect_list0", "campaign0"
 * "prospect_list1", "campaign1"
 * "prospect_list2", "campaign2" 
 * 
 * */
function process_subscriptions($subscription_string_to_parse) {
    $subs_change = array();

    //parse through and build list of id's'.  We are retrieving the campaign_id and 
    //the prospect_list id from the selected subscriptions 
    $i = 0;
    foreach($subscription_string_to_parse as $subs_changes){
        $subs_changes = trim($subs_changes);
        if(!empty($subs_changes)){
            $ids_arr = explode("@", $subs_changes);
            $subs_change[$ids_arr[0].$i] = $ids_arr[1];
            $subs_change[$ids_arr[2].$i] = $ids_arr[3];
            $i = $i+1;
        }
    }
    return $subs_change;
}


    /*This function is used by the Manage Subscriptions page in order to add the user
     * to the default prospect lists of the passed in campaign 
     * Takes in campaign and prospect list id's we are subscribing to.  
     * It also takes in a bean of the user (lead,target,prospect) we are subscribing
     * */
    function subscribe($campaign, $prospect_list, $focus) {
            $relationship = strtolower($focus->getObjectName()).'s';

            //--grab all the lists for the passed in campaign id
            $pl_qry ="select id, list_type from prospect_lists where id in (select prospect_list_id from prospect_list_campaigns "; 
            $pl_qry .= "where campaign_id = '$campaign') and deleted = 0 ";
            $GLOBALS['log']->debug("In Campaigns Util: subscribe function, about to run query: ".$pl_qry );
            $pl_qry_result = $focus->db->query($pl_qry);
    
            //build the array of all prospect_lists 
            $pl_arr = array();
            while ($row = $focus->db->fetchByAssoc($pl_qry_result)){$pl_arr[] = $row;}
    
            //--grab all the prospect_lists this user belongs to
            $curr_pl_qry ="select prospect_list_id, related_id  from prospect_lists_prospects ";
            $curr_pl_qry .="where related_id = '$focus->id'  and deleted = 0 ";
            $GLOBALS['log']->debug("In Campaigns Util: subscribe function, about to run query: ".$curr_pl_qry );
            $curr_pl_qry_result = $focus->db->query($curr_pl_qry);
    
            //build the array of all prospect lists that this current user belongs to
            $curr_pl_arr = array();
            while ($row = $focus->db->fetchByAssoc($curr_pl_qry_result)){$curr_pl_arr[] = $row;}
    
            //search through prospect lists for this campaign and identifiy the "unsubscription list"
            $exempt_id = '';
           foreach($pl_arr as $subscription_list){
                if($subscription_list['list_type'] == 'exempt'){
                    $exempt_id = $subscription_list['id'];
                }
           } 
           
           //now that we have exempt (unsubscription) list id, compare against user list id's
           if(!empty($exempt_id)){
            $exempt_array['exempt_id'] = $exempt_id;
                
               foreach($curr_pl_arr as $curr_subscription_list){
                    if($curr_subscription_list['prospect_list_id'] == $exempt_id){
                        //--if we are in here then user is subscribing to a list in which they are exempt.
                        // we need to remove the user from this unsubscription list.
                        //Begin by retrieving unsubscription prospect list
                        $exempt_subscription_list = new ProspectList();
                        $exempt_result = $exempt_subscription_list->retrieve($exempt_id);
                        if($exempt_result == null)
                        {//error happened while retrieving this list
                            return;
                        }
                        //load realationships and delete user from unsubscription list
                        $exempt_subscription_list->load_relationship($relationship);
                        $exempt_subscription_list->$relationship->delete($exempt_id,$focus->id);
                        
                    }
               } 
           }    
    
            //Now we need to check if user is already in subscription list
            $already_here = 'false';
            //for each list user is subscribed to, compare id's with current list id'
            foreach($curr_pl_arr as $user_list){
                if(in_array($prospect_list, $user_list)){
                    //if user already exists, then set flag to true
                    $already_here = 'true';    
                }    
            }
            if($already_here ==='true'){
                //do nothing, user is already subscribed
            }else{
                //user is not subscribed already, so add to subscription list
                $subscription_list = new ProspectList();
                $subs_result = $subscription_list->retrieve($prospect_list);
                if($subs_result == null)
                {//error happened while retrieving this list, iterate and continue
                    return;
                }
                //load subscription list and add this user
                $GLOBALS['log']->debug("In Campaigns Util, loading relationship: ".$relationship);
                $subscription_list->load_relationship($relationship);
                $subscription_list->$relationship->add($focus->id);
            }
}


    /*This function is used by the Manage Subscriptions page in order to add the user
     * to the exempt prospect lists of the passed in campaign 
     * Takes in campaign and focus parameters.  
     * */
    function unsubscribe($campaign, $focus) {
        $relationship = strtolower($focus->getObjectName()).'s';
    
        //--grab the exempt list for this campaign id
        $pl_qry ="select id from prospect_lists where id in (select prospect_list_id from prospect_list_campaigns "; 
        $pl_qry .= "where campaign_id = '$campaign')";
        $pl_qry .= "and list_type = 'exempt' and deleted = 0 "; 
        $pl_qry_result = $focus->db->query($pl_qry);
        //build the array with list information
        $pl_arr = array();
        $GLOBALS['log']->debug("In Campaigns Util, about to run query: ".$pl_qry_result);
        $pl_arr = $focus->db->fetchByAssoc($pl_qry_result);
        
        //retrieve lists that this user belongs to
        $curr_pl_qry ="select prospect_list_id, related_id  from prospect_lists_prospects ";
        $curr_pl_qry .="where related_id = '$focus->id'  and deleted = 0 ";
        $GLOBALS['log']->debug("In Campaigns Util, unsubscribe function about to run query: ".$curr_pl_qry );
        $curr_pl_qry_result = $focus->db->query($curr_pl_qry);
        
        //build the array with current user list information
        $curr_pl_arr = array();
        while ($row = $focus->db->fetchByAssoc($curr_pl_qry_result)){$curr_pl_arr[] = $row;}
        
        //check to see if user is already there in prospect list
        $already_here = 'false';
        foreach($curr_pl_arr as $user_list){
            if(in_array($pl_arr['id'], $user_list)){
                $already_here = 'true';    
            }    
        }
        if($already_here =='true'){
            //do nothing, user is already exempted
        
        }else{
            //user is not exempted yet , so add to unsubscription list
            $exempt_list = new ProspectList();
            $exempt_result = $exempt_list->retrieve($pl_arr['id']);
            if($exempt_result == null)
            {//error happened while retrieving this list
                $i = $i +1;
                continue;
            }
            $GLOBALS['log']->debug("In Campaigns Util, loading relationship: ".$relationship);
            $exempt_list->load_relationship($relationship);
            $exempt_list->$relationship->add($focus->id);
        }
    
    }
    
    
    /*
     *This function will return a string to the newsletter wizard if campaign check 
     *does not return 100% healthy. 
     */
    function diagnose()
    {
        global $mod_strings;
        global $current_user;
        $msg = " <table class='tabDetailView' width='100%'><tr><td> ".$mod_strings['LNK_CAMPAIGN_DIGNOSTIC_LINK']."</td></tr>";
        //Start with email components
        //monitored mailbox section
        $focus = new Administration();
        $focus->retrieveSettings(); //retrieve all admin settings.
        
        
        //run query for mail boxes of type 'bounce' 
        $email_health = 0;
        $email_components = 2;
        $mbox_qry = "select * from inbound_email where deleted ='0' and mailbox_type = 'bounce'";
        $mbox_res = $focus->db->query($mbox_qry);
        
        $mbox = array();
        while ($mbox_row = $focus->db->fetchByAssoc($mbox_res)){$mbox[] = $mbox_row;}
        //if the array is not empty, then set "good" message
        if(isset($mbox) && count($mbox)>0){
            //everything is ok, do nothing
        
        }else{
            //if array is empty, then increment health counter
            $email_health =$email_health +1;
            $msg  .=  "<tr><td ><font color='red'><b>". $mod_strings['LBL_MAILBOX_CHECK1_BAD']."</b></font></td></tr>";
        }
        
        
        if (strstr($focus->settings['notify_fromaddress'], 'example.com')){
            //if "from_address" is the default, then set "bad" message and increment health counter
            $email_health =$email_health +1;
            $msg .= "<tr><td ><font color='red'><b> ".$mod_strings['LBL_MAILBOX_CHECK2_BAD']." </b></font></td></tr>";
        }else{
            //do nothing, address has been changed
        }
        //if health counter is above 1, then show admin link            
        if($email_health>0){
            if (is_admin($current_user)){
                $msg.="<tr><td ><a href='index.php?module=Campaigns&action=WizardEmailSetup";
                if(isset($_REQUEST['return_module'])){
                    $msg.="&return_module=".$_REQUEST['return_module'];
                }
                if(isset($_REQUEST['return_action'])){
                    $msg.="&return_action=".$_REQUEST['return_action'];
                }                
                $msg.="'>".$mod_strings['LBL_EMAIL_SETUP_WIZ']."</a></td></tr>";
            }else{
                $msg.="<tr><td >".$mod_strings['LBL_NON_ADMIN_ERROR_MSG']."</td></tr>";
                
            }    
            
        }      
        

        // proceed with scheduler components 
        
        //create and run the scheduler queries 
        $sched_qry = "select job, name, status from schedulers where deleted = 0 and status = 'Active'";
        $sched_res = $focus->db->query($sched_qry);
        $sched_health = 0;
        $sched = array();
        $check_sched1 = 'function::runMassEmailCampaign';
        $check_sched2 = 'function::pollMonitoredInboxesForBouncedCampaignEmails';
        $sched_mes = '';
        $sched_mes_body = '';
        $scheds = array();
        
        while ($sched_row = $focus->db->fetchByAssoc($sched_res)){$scheds[] = $sched_row;}
        //iterate through and see which jobs were found
        foreach ($scheds as $funct){
          if( ($funct['job']==$check_sched1)  ||   ($funct['job']==$check_sched2)){
                if($funct['job']==$check_sched1){
                    $check_sched1 ="found";
                }else{
                    $check_sched2 ="found";
                }  
                
          }
        }
        //determine if error messages need to be displayed for schedulers
        if($check_sched2 != 'found'){
            $sched_health =$sched_health +1;
            $msg.= "<tr><td><font color='red'><b>".$mod_strings['LBL_SCHEDULER_CHECK1_BAD']."</b></font></td></tr>";
        }
        if($check_sched1 != 'found'){
            $sched_health =$sched_health +1;
            $msg.= "<tr><td><font color='red'><b>".$mod_strings['LBL_SCHEDULER_CHECK2_BAD']."</b></font></td></tr>";
        }
        //if health counter is above 1, then show admin link            
        if($sched_health>0){
            global $current_user;
            if (is_admin($current_user)){
                $msg.="<tr><td ><a href='index.php?module=Schedulers&action=index'>".$mod_strings['LBL_SCHEDULER_LINK']."</a></td></tr>";
            }else{
                $msg.="<tr><td >".$mod_strings['LBL_NON_ADMIN_ERROR_MSG']."</td></tr>";
            }    
            
        }      

        //determine whether message should be returned
        if(($sched_health + $email_health)>0){
            $msg  .= "</table> ";    
        }else{
            $msg = '';
        }
        return $msg;        
    }
    
    
/**
 * Handle campaign log entry creation for mail-merge activity. The function will be called by the soap component.
 * 
 * @param String campaign_id Primary key of the campaign
 * @param array targets List of keys for entries from prospect_lists_prosects table
 */
 function campaign_log_mail_merge($campaign_id, $targets) {
    require_once('modules/Campaigns/Campaign.php');
    $campaign= new Campaign();
    $campaign->retrieve($campaign_id);
       
    if (empty($campaign->id)) {
        $GLOBALS['log']->debug('set_campaign_merge: Invalid campaign id'. $campaign_id);
    } else {
        foreach ($targets as $target_list_id) {
            $pl_query = "select * from prospect_lists_prospects where id='$target_list_id'";
            $result=$GLOBALS['db']->query($pl_query);
            $row=$GLOBALS['db']->fetchByAssoc($result);
            if (!empty($row)) {
                write_mail_merge_log_entry($campaign_id,$row);
            }
        }        
    }
 
 }
/**
 * Function creates a campaign_log entry for campaigns processesed using the mail-merge feature. If any entry
 * exist the hit counter is updated. target_tracker_key is used to locate duplicate entries.
 * @param string campaign_id Primary key of the campaign
 * @param array $pl_row A row of data from prospect_lists_prospects table.
 */
function write_mail_merge_log_entry($campaign_id,$pl_row) {
    
    //Update the log entry if it exists.
    $update="update campaign_log set hits=hits+1 where campaign_id='$campaign_id' and target_tracker_key='" . $pl_row['id'] . "'";
    $result=$GLOBALS['db']->query($update);
    
    //get affected row count...
    if ($GLOBALS['db']->dbType=='oci8')
        $count=$GLOBALS['db']->getRowCount($result);
    else {
        $count=$GLOBALS['db']->getAffectedRowCount($result);
    }
    if ($count==0) {
        $data=array();
        
        $data['id']="'" . create_guid() . "'";
        $data['campaign_id']="'" . $campaign_id . "'";
        $data['target_tracker_key']="'" . $pl_row['id'] . "'";
        $data['target_id']="'" .  $pl_row['related_id'] . "'";
        $data['target_type']="'" .  $pl_row['related_type'] . "'";
        $data['activity_type']="'targeted'";
        $data['activity_date']="'" . gmdate("Y-m-d H:i:s") . "'";
        $data['list_id']="'" .  $pl_row['prospect_list_id'] . "'";
        $data['hits']=1;
        
        $insert_query="INSERT into campaign_log (" . implode(",",array_keys($data)) . ")"; 
        $insert_query.=" VALUES  (" . implode(",",array_values($data)) . ")"; 
        $GLOBALS['db']->query($insert_query);       
    }
}     

    function track_campaign_prospects($focus){
        global $mod_strings;
        
         //load target list relationships
        $focus->load_relationship('prospectlists');
        $target_lists = $focus->prospectlists->get();
        $prospect_lists = array();
        require_once('modules/ProspectLists/ProspectList.php');       

        //retrieve the default target list if it exists
        foreach($target_lists as $list){
             //create subscription list     
             $p_list = new ProspectList();
             $p_list->retrieve($list);
             if($p_list->list_type == 'default'){
                $prospect_lists[] = $p_list;
             }
        }
        //list does not exist, send back error message
        if(count($prospect_lists) == 0){
            return $mod_strings['LBL_DEFAULT_LIST_NOT_FOUND'];
        }
        
        //iterate through each Prospect list and make sure entries exist.
        $entry_count =0;
        foreach($prospect_lists as $default_target_list){
            $entry_count = $entry_count + $default_target_list->get_entry_count();
        }
        //if no entries exist, then return error message.
        if($entry_count == 0){
            return $mod_strings['LBL_DEFAULT_LIST_ENTRIES_NOT_FOUND'];
        }
        

        //iterate through each member of list and enter campaign log
        foreach($prospect_lists as $default_target_list){
            //process targets/prospects          
            require_once('modules/Prospects/Prospect.php');
            $rel_bean = new Prospect();
            create_campaign_log_entry($focus->id, $default_target_list, 'prospects', $rel_bean);
    
            //process users          
            require_once('modules/Users/User.php');
            $rel_bean = new User();
            create_campaign_log_entry($focus->id, $default_target_list, 'users', $rel_bean);
    
            //process contacts          
            require_once('modules/Contacts/Contact.php');
            $rel_bean = new Contact();
            create_campaign_log_entry($focus->id, $default_target_list, 'contacts', $rel_bean);
    
            //process leads          
            require_once('modules/Leads/Lead.php');
            $rel_bean = new Lead();
            create_campaign_log_entry($focus->id, $default_target_list, 'leads', $rel_bean);
            
        }
        
        
        
        
        //return success message   
        return $mod_strings['LBL_DEFAULT_LIST_ENTRIES_WERE_PROCESSED'];
        
    }
    
    function create_campaign_log_entry($campaign_id, $focus, $rel_name, $rel_bean){
        global $timedate;
        //load target/prospect relationships
        $focus->load_relationship($rel_name);
        $target_ids = $focus->$rel_name->get();
        if(count($target_ids)>0){
            require_once('modules/CampaignLog/CampaignLog.php');
          
            //retrieve the target beans and create campaign log entry
            foreach($target_ids as $id){
                 //perform duplicate check
                 $dup_query = "select id from campaign_log where campaign_id = '$campaign_id' and target_id = '$id'";
                 $dup_result = $focus->db->query($dup_query);
                 $row = $focus->db->fetchByAssoc($dup_result);

                //process if this is not a duplicate campaign log entry
                if(empty($row)){
                    //create campaign tracker id and retrieve related bio bean                 
                     $tracker_id = create_guid();     
                     $rel_bean->retrieve($id);
    
                    //create new campaign log record.
                    $campaign_log = new CampaignLog();
                    $campaign_log->campaign_id = $campaign_id;
                    $campaign_log->target_tracker_key = $tracker_id;
                    $campaign_log->target_id = $rel_bean->id;
                    $campaign_log->target_type = $rel_bean->module_dir;
                    $campaign_log->activity_type = 'targeted';
                    $campaign_log->activity_date=$timedate->to_display_date_time(gmdate("Y-m-d H:i:s"));                    
                    //save the campaign log entry
                    $campaign_log->save();
                }
            }    
        }
    
    }
?>
