]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Campaigns/utils.php
Release 6.5.10
[Github/sugarcrm.git] / modules / Campaigns / utils.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description:  Defines the English language pack for the base application.
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42  * All Rights Reserved.
43  * Contributor(s): ______________________________________..
44  ********************************************************************************/
45
46 /*
47  *returns a list of objects a message can be scoped by, the list contacts the current campaign
48  *name and list of all prospects associated with this campaign..
49  *
50  */
51 function get_message_scope_dom($campaign_id, $campaign_name,$db=null, $mod_strings=array()) {
52
53     //find prospect list attached to this campaign..
54     $query =  "SELECT prospect_list_id, prospect_lists.name ";
55     $query .= "FROM prospect_list_campaigns ";
56     $query .= "INNER join prospect_lists on prospect_lists.id = prospect_list_campaigns.prospect_list_id ";
57     $query .= "WHERE prospect_lists.deleted = 0 ";
58     $query .= "AND prospect_list_campaigns.deleted=0 ";
59     $query .= "AND campaign_id='".$campaign_id."'";
60     $query.=" and prospect_lists.list_type not like 'exempt%'";
61
62     if (empty($db)) {
63         $db = DBManagerFactory::getInstance();
64     }
65     if (empty($mod_strings) or !isset($mod_strings['LBL_DEFAULT'])) {
66         global $current_language;
67         $mod_strings = return_module_language($current_language, 'Campaigns');
68     }
69
70     //add campaign to the result array.
71     //$return_array[$campaign_id]= $campaign_name . ' (' . $mod_strings['LBL_DEFAULT'] . ')';
72
73     $result=$db->query($query);
74     while(($row=$db->fetchByAssoc($result))!= null) {
75         $return_array[$row['prospect_list_id']]=$row['name'];
76     }
77     if (empty($return_array)) $return_array=array();
78     else return $return_array;
79 }
80 /**
81  * Return bounce handling mailboxes for campaign.
82  *
83  * @param unknown_type $emails
84  * @param unknown_type $get_box_name, Set it to false if want to get "From Name" other than the InboundEmail Name.
85  * @return $get_name=true, bounce handling mailboxes' name; $get_name=false, bounce handling mailboxes' from name.
86  */
87 function get_campaign_mailboxes(&$emails, $get_name=true) {
88     if (!class_exists('InboundEmail')) {
89         require('modules/InboundEmail/InboundEmail.php');
90     }
91     $query =  "select id,name,stored_options from inbound_email where mailbox_type='bounce' and status='Active' and deleted='0'";
92     $db = DBManagerFactory::getInstance();
93     $result=$db->query($query);
94     while(($row=$db->fetchByAssoc($result))!= null) {
95         if($get_name) {
96                 $return_array[$row['id']] = $row['name'];
97         } else {
98                 $return_array[$row['id']]= InboundEmail::get_stored_options('from_name',$row['name'],$row['stored_options']);
99         }
100         $emails[$row['id']]=InboundEmail::get_stored_options('from_addr','nobody@example.com',$row['stored_options']);
101     }
102
103     if (empty($return_array)) $return_array=array(''=>'');
104     return $return_array;
105
106 }
107
108 function get_campaign_mailboxes_with_stored_options() {
109         $ret = array();
110
111     if(!class_exists('InboundEmail')) {
112         require('modules/InboundEmail/InboundEmail.php');
113     }
114
115     $q = "SELECT id, name, stored_options FROM inbound_email WHERE mailbox_type='bounce' AND status='Active' AND deleted='0'";
116
117     $db = DBManagerFactory::getInstance();
118
119     $r = $db->query($q);
120
121     while($a = $db->fetchByAssoc($r)) {
122         $ret[$a['id']] = unserialize(base64_decode($a['stored_options']));
123     }
124         return $ret;
125 }
126
127 function log_campaign_activity($identifier, $activity, $update=true, $clicked_url_key=null) {
128
129     $return_array = array();
130
131     $db = DBManagerFactory::getInstance();
132
133
134
135      //check to see if the identifier has been replaced with Banner string
136     if($identifier == 'BANNER' && isset($clicked_url_key)  && !empty($clicked_url_key))
137     {
138         // create md5 encrypted string using the client ip, this will be used for tracker id purposes
139         $enc_id = 'BNR'.md5($_SERVER['REMOTE_ADDR']);
140
141         //default the identifier to ip address
142         $identifier = $enc_id;
143
144         //if user has chosen to not use this mode of id generation, then replace identifier with plain guid.
145         //difference is that guid will generate a new campaign log for EACH CLICK!!
146         //encrypted generation will generate 1 campaign log and update the hit counter for each click
147         if(isset($sugar_config['campaign_banner_id_generation'])  && $sugar_config['campaign_banner_id_generation'] != 'md5'){
148             $identifier = create_guid();
149         }
150
151         //retrieve campaign log.
152         $trkr_query = "select * from campaign_log where target_tracker_key='$identifier' and related_id = '$clicked_url_key'";
153         $current_trkr=$db->query($trkr_query);
154         $row=$db->fetchByAssoc($current_trkr);
155
156         //if campaign log is not retrieved (this is a new ip address or we have chosen to create
157         //unique entries for each click
158         if($row==null  || empty($row)){
159
160
161                 //retrieve campaign id
162                 $trkr_query = "select ct.campaign_id from campaign_trkrs ct, campaigns c where c.id = ct.campaign_id and ct.id = '$clicked_url_key'";
163                 $current_trkr=$db->query($trkr_query);
164                 $row=$db->fetchByAssoc($current_trkr);
165
166
167                 //create new campaign log with minimal info.  Note that we are creating new unique id
168                 //as target id, since we do not link banner/web campaigns to any users
169
170                 $data['target_id']="'" . create_guid() . "'";
171                 $data['target_type']= "'Prospects'";
172                 $data['id']="'" . create_guid() . "'";
173                 $data['campaign_id']="'" . $row['campaign_id'] . "'";
174                 $data['target_tracker_key']="'" . $identifier . "'";
175                 $data['activity_type']="'" .  $activity . "'";
176                 $data['activity_date']="'" . TimeDate::getInstance()->nowDb() . "'";
177                 $data['hits']=1;
178                 $data['deleted']=0;
179                 if (!empty($clicked_url_key)) {
180                     $data['related_id']="'".$clicked_url_key."'";
181                     $data['related_type']="'".'CampaignTrackers'."'";
182                 }
183
184                 //values for return array..
185                 $return_array['target_id']=$data['target_id'];
186                 $return_array['target_type']=$data['target_type'];
187
188                 //create insert query for new campaign log
189                 $insert_query="INSERT into campaign_log (" . implode(",",array_keys($data)) . ")";
190                 $insert_query.=" VALUES  (" . implode(",",array_values($data)) . ")";
191                 $db->query($insert_query);
192             }else{
193
194                 //campaign log already exists, so just set the return array and update hits column
195                 $return_array['target_id']= $row['target_id'];
196                 $return_array['target_type']= $row['target_type'];
197                 $query1="update campaign_log set hits=hits+1 where id='{$row['id']}'";
198                 $current=$db->query($query1);
199
200
201            }
202
203         //return array and exit
204         return $return_array;
205
206     }
207
208
209
210     $query1="select * from campaign_log where target_tracker_key='$identifier' and activity_type='$activity'";
211     if (!empty($clicked_url_key)) {
212         $query1.=" AND related_id='$clicked_url_key'";
213     }
214     $current=$db->query($query1);
215     $row=$db->fetchByAssoc($current);
216
217         if ($row==null) {
218             $query="select * from campaign_log where target_tracker_key='$identifier' and activity_type='targeted'";
219             $targeted=$db->query($query);
220             $row=$db->fetchByAssoc($targeted);
221
222             //if activity is removed and target type is users, then a user is trying to opt out
223             //of emails.  This is not possible as Users Table does not have opt out column.
224             if ($row  && (strtolower($row['target_type']) == 'users' &&  $activity == 'removed' )) {
225                 $return_array['target_id']= $row['target_id'];
226                 $return_array['target_type']= $row['target_type'];
227                 return $return_array;
228             }
229             elseif ($row){
230                 $data['id']="'" . create_guid() . "'";
231                 $data['campaign_id']="'" . $row['campaign_id'] . "'";
232                 $data['target_tracker_key']="'" . $identifier . "'";
233                 $data['target_id']="'" .  $row['target_id'] . "'";
234                 $data['target_type']="'" .  $row['target_type'] . "'";
235                 $data['activity_type']="'" .  $activity . "'";
236                 $data['activity_date']="'" . TimeDate::getInstance()->nowDb() . "'";
237                 $data['list_id']="'" .  $row['list_id'] . "'";
238                 $data['marketing_id']="'" .  $row['marketing_id'] . "'";
239                 $data['hits']=1;
240                 $data['deleted']=0;
241                 if (!empty($clicked_url_key)) {
242                     $data['related_id']="'".$clicked_url_key."'";
243                     $data['related_type']="'".'CampaignTrackers'."'";
244                 }
245                 //values for return array..
246                 $return_array['target_id']=$row['target_id'];
247                 $return_array['target_type']=$row['target_type'];
248                 $insert_query="INSERT into campaign_log (" . implode(",",array_keys($data)) . ")";
249                 $insert_query.=" VALUES  (" . implode(",",array_values($data)) . ")";
250                 $db->query($insert_query);
251             }
252         } else {
253
254             $return_array['target_id']= $row['target_id'];
255             $return_array['target_type']= $row['target_type'];
256
257             $query1="update campaign_log set hits=hits+1 where id='{$row['id']}'";
258             $current=$db->query($query1);
259
260         }
261         //check to see if this is a removal action
262         if ($row  && $activity == 'removed' ) {
263             //retrieve campaign and check it's type, we are looking for newsletter Campaigns
264             $query = "SELECT campaigns.* FROM campaigns WHERE campaigns.id = '".$row['campaign_id']."' ";
265             $result = $db->query($query);
266             if(!empty($result))
267             {
268                 $c_row = $db->fetchByAssoc($result);
269
270                 //if type is newsletter, then add campaign id to return_array for further processing.
271                 if(isset($c_row['campaign_type']) && $c_row['campaign_type'] == 'NewsLetter'){
272                     $return_array['campaign_id']=$c_row['id'];
273                 }
274             }
275         }
276         return $return_array;
277     }
278
279
280  /**
281      *
282      * This method is deprecated
283      * @deprecated 62_Joneses - June 24, 2011
284      * @see campaign_log_lead_or_contact_entry()
285      */
286 function campaign_log_lead_entry($campaign_id, $parent_bean,$child_bean,$activity_type){
287     campaign_log_lead_or_contact_entry($campaign_id, $parent_bean,$child_bean,$activity_type);
288 }
289
290
291 function campaign_log_lead_or_contact_entry($campaign_id, $parent_bean,$child_bean,$activity_type){
292     global $timedate;
293
294     //create campaign tracker id and retrieve related bio bean
295      $tracker_id = create_guid();
296     //create new campaign log record.
297     $campaign_log = new CampaignLog();
298     $campaign_log->campaign_id = $campaign_id;
299     $campaign_log->target_tracker_key = $tracker_id;
300     $campaign_log->related_id = $parent_bean->id;
301     $campaign_log->related_type = $parent_bean->module_dir;
302     $campaign_log->target_id = $child_bean->id;
303     $campaign_log->target_type = $child_bean->module_dir;
304     $campaign_log->activity_date = $timedate->now();
305     $campaign_log->activity_type = $activity_type;
306     //save the campaign log entry
307     $campaign_log->save();
308 }
309
310
311 function get_campaign_urls($campaign_id) {
312     $return_array=array();
313
314     if (!empty($campaign_id)) {
315
316         $db = DBManagerFactory::getInstance();
317
318         $query1="select * from campaign_trkrs where campaign_id='$campaign_id' and deleted=0";
319         $current=$db->query($query1);
320         while (($row=$db->fetchByAssoc($current)) != null) {
321             $return_array['{'.$row['tracker_name'].'}']=$row['tracker_name'] . ' : ' . $row['tracker_url'];
322         }
323     }
324     return $return_array;
325 }
326
327 /**
328  * Queries for the list
329  */
330 function get_subscription_lists_query($focus, $additional_fields = null) {
331     //get all prospect lists belonging to Campaigns of type newsletter
332     $all_news_type_pl_query = "select c.name, pl.list_type, plc.campaign_id, plc.prospect_list_id";
333     if(is_array($additional_fields) && !empty($additional_fields)) $all_news_type_pl_query .= ', ' . implode(', ', $additional_fields);
334     $all_news_type_pl_query .= " from prospect_list_campaigns plc , prospect_lists pl, campaigns c ";
335
336
337         $all_news_type_pl_query .= "where plc.campaign_id = c.id ";
338     $all_news_type_pl_query .= "and plc.prospect_list_id = pl.id ";
339     $all_news_type_pl_query .= "and c.campaign_type = 'NewsLetter'  and pl.deleted = 0 and c.deleted=0 and plc.deleted=0 ";
340     $all_news_type_pl_query .= "and (pl.list_type like 'exempt%' or pl.list_type ='default') ";
341
342     $all_news_type_list =$focus->db->query($all_news_type_pl_query);
343
344     //build array of all newsletter campaigns
345     $news_type_list_arr = array();
346     while ($row = $focus->db->fetchByAssoc($all_news_type_list)){$news_type_list_arr[] = $row;}
347
348     //now get all the campaigns that the current user is assigned to
349     $all_plp_current = "select prospect_list_id from prospect_lists_prospects where related_id = '$focus->id' and deleted = 0 ";
350
351     //build array of prospect lists that this user belongs to
352     $current_plp =$focus->db->query($all_plp_current );
353     $current_plp_arr = array();
354     while ($row = $focus->db->fetchByAssoc($current_plp)){$current_plp_arr[] = $row;}
355
356     return array('current_plp_arr' => $current_plp_arr, 'news_type_list_arr' => $news_type_list_arr);
357 }
358 /*
359  * This function takes in a bean from a lead, prospect, or contact and returns an array containing
360  * all subscription lists that the bean is a part of, and all the subscriptions that the bean is not
361  * a part of.  The array elements have the key names of "subscribed" and "unsusbscribed".  These elements contain an array
362  * of the corresponding list.  In other words, the "subscribed" element holds another array that holds the subscription information.
363  *
364  * The subscription information is a concatenated string that holds the prospect list id and the campaign id, separated by at "@" character.
365  * To parse these information string into something more usable, use the "process subscriptions()" function
366  *
367  * */
368 function get_subscription_lists($focus, $descriptions = false) {
369     $subs_arr = array();
370     $unsubs_arr = array();
371
372     $results = get_subscription_lists_query($focus, $descriptions);
373
374     $news_type_list_arr = $results['news_type_list_arr'];
375     $current_plp_arr = $results['current_plp_arr'];
376
377    //For each  prospect list of type 'NewsLetter', check to see if current user is already in list,
378     foreach($news_type_list_arr as $news_list){
379         $match = 'false';
380
381         //perform this check against each prospect list this user belongs to
382         foreach($current_plp_arr as $current_list_key => $current_list){//echo " new entry from current lists user is subscribed to-------------";
383             //compare current user list id against newsletter id
384             if ($news_list['prospect_list_id'] == $current_list['prospect_list_id']){
385                 //if id's match, user is subscribed to this list, check to see if this is an exempt list,
386                 if(strpos($news_list['list_type'],  'exempt')!== false){
387                     //this is an exempt list, so process
388                     if(array_key_exists($news_list['name'],$subs_arr)){
389                         //first, add to unsubscribed array
390                         $unsubs_arr[$news_list['name']] = $subs_arr[$news_list['name']];
391                         //now remove from exempt subscription list
392                         unset($subs_arr[$news_list['name']]);
393                     }else{
394                         //we know this is an exempt list the user belongs to, but the
395                         //non exempt list has not been processed yet, so just add to exempt array
396                         $unsubs_arr[$news_list['name']] = "prospect_list@".$news_list['prospect_list_id']."@campaign@".$news_list['campaign_id'];
397                     }
398                     $match = 'false';//although match is false, this is an exempt array, so
399                     //it will not be added a second time down below
400                 }else{
401                     //this list is not exempt, and user is subscribed, so add to subscribed array, and unset from the unsubs_arr
402                     //as long as this list is not in exempt array
403                         $temp = "prospect_list@".$news_list['prospect_list_id']."@campaign@".$news_list['campaign_id'];
404                         if(!array_search($temp,$unsubs_arr)){
405                         $subs_arr[$news_list['name']] = "prospect_list@".$news_list['prospect_list_id']."@campaign@".$news_list['campaign_id'];
406                         $match = 'true';
407                         unset($unsubs_arr[$news_list['name']]);
408                     }
409                 }
410             }else{
411                 //do nothing, there is no match
412                 }
413         }
414          //if this newsletter id never matched a user subscription..
415          //..then add to available(unsubscribed) NewsLetters if list is not of type exempt
416         if (($match == 'false') && (strpos($news_list['list_type'], 'exempt') === false) && (!array_key_exists($news_list['name'], $subs_arr)))
417         {
418             $unsubs_arr[$news_list['name']] = "prospect_list@".$news_list['prospect_list_id']."@campaign@".$news_list['campaign_id'];
419         }
420
421     }
422     $return_array['unsubscribed'] = $unsubs_arr;
423     $return_array['subscribed'] = $subs_arr;
424     return $return_array;
425 }
426
427 /**
428  * same function as get_subscription_lists, but with the data separated in an associated array
429  */
430 function get_subscription_lists_keyed($focus) {
431     $subs_arr = array();
432     $unsubs_arr = array();
433
434     $results = get_subscription_lists_query($focus, array('c.content', 'c.frequency'));
435
436     $news_type_list_arr = $results['news_type_list_arr'];
437     $current_plp_arr = $results['current_plp_arr'];
438
439    //For each  prospect list of type 'NewsLetter', check to see if current user is already in list,
440     foreach($news_type_list_arr as $news_list){
441         $match = false;
442
443         $news_list_data = array('prospect_list_id' => $news_list['prospect_list_id'],
444                                 'campaign_id'      => $news_list['campaign_id'],
445                                 'description'      => $news_list['content'],
446                                 'frequency'        => $news_list['frequency']);
447
448         //perform this check against each prospect list this user belongs to
449         foreach($current_plp_arr as $current_list_key => $current_list){//echo " new entry from current lists user is subscribed to-------------";
450             //compare current user list id against newsletter id
451             if ($news_list['prospect_list_id'] == $current_list['prospect_list_id']){
452                 //if id's match, user is subscribed to this list, check to see if this is an exempt list,
453
454                 if($news_list['list_type'] == 'exempt'){
455                     //this is an exempt list, so process
456                     if(array_key_exists($news_list['name'],$subs_arr)){
457                         //first, add to unsubscribed array
458                         $unsubs_arr[$news_list['name']] = $subs_arr[$news_list['name']];
459                         //now remove from exempt subscription list
460                         unset($subs_arr[$news_list['name']]);
461                     }else{
462                         //we know this is an exempt list the user belongs to, but the
463                         //non exempt list has not been processed yet, so just add to exempt array
464                         $unsubs_arr[$news_list['name']] = $news_list_data;
465                     }
466                     $match = false;//although match is false, this is an exempt array, so
467                     //it will not be added a second time down below
468                 }else{
469                     //this list is not exempt, and user is subscribed, so add to subscribed array
470                     //as long as this list is not in exempt array
471                     if(!array_key_exists($news_list['name'],$unsubs_arr)){
472                         $subs_arr[$news_list['name']] = $news_list_data;
473                         $match = 'true';
474                     }
475                 }
476             }else{
477                 //do nothing, there is no match
478                 }
479         }
480          //if this newsletter id never matched a user subscription..
481          //..then add to available(unsubscribed) NewsLetters if list is not of type exempt
482          if(($match == false) && ($news_list['list_type'] != 'exempt')){
483             $unsubs_arr[$news_list['name']] = $news_list_data;
484         }
485
486     }
487
488     $return_array['unsubscribed'] = $unsubs_arr;
489     $return_array['subscribed'] = $subs_arr;
490     return $return_array;
491 }
492
493
494
495 /*
496  * This function will take an array of strings that have been created by the "get_subscription_lists()" method
497  * and parses it into an array.  The returned array has it's key's labeled in a specific fashion.
498  *
499  * Each string produces a campaign and a prospect id.  The keys are appended with a number specifying the order
500  * it was process in.  So an input array containing 3 strings will have the following key values:
501  * "prospect_list0", "campaign0"
502  * "prospect_list1", "campaign1"
503  * "prospect_list2", "campaign2"
504  *
505  * */
506 function process_subscriptions($subscription_string_to_parse) {
507     $subs_change = array();
508
509     //parse through and build list of id's'.  We are retrieving the campaign_id and
510     //the prospect_list id from the selected subscriptions
511     $i = 0;
512     foreach($subscription_string_to_parse as $subs_changes){
513         $subs_changes = trim($subs_changes);
514         if(!empty($subs_changes)){
515             $ids_arr = explode("@", $subs_changes);
516             $subs_change[$ids_arr[0].$i] = $ids_arr[1];
517             $subs_change[$ids_arr[2].$i] = $ids_arr[3];
518             $i = $i+1;
519         }
520     }
521     return $subs_change;
522 }
523
524
525     /*This function is used by the Manage Subscriptions page in order to add the user
526      * to the default prospect lists of the passed in campaign
527      * Takes in campaign and prospect list id's we are subscribing to.
528      * It also takes in a bean of the user (lead,target,prospect) we are subscribing
529      * */
530     function subscribe($campaign, $prospect_list, $focus, $default_list = false) {
531             $relationship = strtolower($focus->getObjectName()).'s';
532
533             //--grab all the lists for the passed in campaign id
534             $pl_qry ="select id, list_type from prospect_lists where id in (select prospect_list_id from prospect_list_campaigns ";
535             $pl_qry .= "where campaign_id = '$campaign') and deleted = 0 ";
536             $GLOBALS['log']->debug("In Campaigns Util: subscribe function, about to run query: ".$pl_qry );
537             $pl_qry_result = $focus->db->query($pl_qry);
538
539             //build the array of all prospect_lists
540             $pl_arr = array();
541             while ($row = $focus->db->fetchByAssoc($pl_qry_result)){$pl_arr[] = $row;}
542
543             //--grab all the prospect_lists this user belongs to
544             $curr_pl_qry ="select prospect_list_id, related_id  from prospect_lists_prospects ";
545             $curr_pl_qry .="where related_id = '$focus->id'  and deleted = 0 ";
546             $GLOBALS['log']->debug("In Campaigns Util: subscribe function, about to run query: ".$curr_pl_qry );
547             $curr_pl_qry_result = $focus->db->query($curr_pl_qry);
548
549             //build the array of all prospect lists that this current user belongs to
550             $curr_pl_arr = array();
551             while ($row = $focus->db->fetchByAssoc($curr_pl_qry_result)){$curr_pl_arr[] = $row;}
552
553             //search through prospect lists for this campaign and identifiy the "unsubscription list"
554             $exempt_id = '';
555            foreach($pl_arr as $subscription_list){
556                 if(strpos($subscription_list['list_type'],  'exempt')!== false){
557                     $exempt_id = $subscription_list['id'];
558                 }
559
560                 if($subscription_list['list_type'] == 'default' && $default_list) {
561                     $prospect_list = $subscription_list['id'];
562                 }
563            }
564
565            //now that we have exempt (unsubscription) list id, compare against user list id's
566            if(!empty($exempt_id)){
567             $exempt_array['exempt_id'] = $exempt_id;
568
569                foreach($curr_pl_arr as $curr_subscription_list){
570                     if($curr_subscription_list['prospect_list_id'] == $exempt_id){
571                         //--if we are in here then user is subscribing to a list in which they are exempt.
572                         // we need to remove the user from this unsubscription list.
573                         //Begin by retrieving unsubscription prospect list
574                         $exempt_subscription_list = new ProspectList();
575
576
577                         $exempt_result = $exempt_subscription_list->retrieve($exempt_id);
578                         if($exempt_result == null)
579                         {//error happened while retrieving this list
580                             return;
581                         }
582                         //load realationships and delete user from unsubscription list
583                         $exempt_subscription_list->load_relationship($relationship);
584                         $exempt_subscription_list->$relationship->delete($exempt_id,$focus->id);
585
586                     }
587                }
588            }
589
590             //Now we need to check if user is already in subscription list
591             $already_here = 'false';
592             //for each list user is subscribed to, compare id's with current list id'
593             foreach($curr_pl_arr as $user_list){
594                 if(in_array($prospect_list, $user_list)){
595                     //if user already exists, then set flag to true
596                     $already_here = 'true';
597                 }
598             }
599             if($already_here ==='true'){
600                 //do nothing, user is already subscribed
601             }else{
602                 //user is not subscribed already, so add to subscription list
603                 $subscription_list = new ProspectList();
604                 $subs_result = $subscription_list->retrieve($prospect_list);
605                 if($subs_result == null)
606                 {//error happened while retrieving this list, iterate and continue
607                     return;
608                 }
609                 //load subscription list and add this user
610                 $GLOBALS['log']->debug("In Campaigns Util, loading relationship: ".$relationship);
611                 $subscription_list->load_relationship($relationship);
612                 $subscription_list->$relationship->add($focus->id);
613             }
614 }
615
616
617     /*This function is used by the Manage Subscriptions page in order to add the user
618      * to the exempt prospect lists of the passed in campaign
619      * Takes in campaign and focus parameters.
620      * */
621     function unsubscribe($campaign, $focus) {
622         $relationship = strtolower($focus->getObjectName()).'s';
623         //--grab all the list for this campaign id
624         $pl_qry ="select id, list_type from prospect_lists where id in (select prospect_list_id from prospect_list_campaigns ";
625         $pl_qry .= "where campaign_id = '$campaign') and deleted = 0 ";
626         $pl_qry_result = $focus->db->query($pl_qry);
627         //build the array with list information
628         $pl_arr = array();
629         $GLOBALS['log']->debug("In Campaigns Util, about to run query: ".$pl_qry);
630         while ($row = $focus->db->fetchByAssoc($pl_qry_result)){$pl_arr[] = $row;}
631
632         //retrieve lists that this user belongs to
633         $curr_pl_qry ="select prospect_list_id, related_id  from prospect_lists_prospects ";
634         $curr_pl_qry .="where related_id = '$focus->id'  and deleted = 0 ";
635         $GLOBALS['log']->debug("In Campaigns Util, unsubscribe function about to run query: ".$curr_pl_qry );
636         $curr_pl_qry_result = $focus->db->query($curr_pl_qry);
637
638         //build the array with current user list information
639         $curr_pl_arr = array();
640         while ($row = $focus->db->fetchByAssoc($curr_pl_qry_result)){$curr_pl_arr[] = $row;}
641          //check to see if user is already there in prospect list
642         $already_here = 'false';
643         $exempt_id = '';
644
645         foreach($curr_pl_arr as $user_list){
646                 foreach($pl_arr as $v){
647                         //if list is exempt list
648                 if($v['list_type'] == 'exempt'){
649                         //save the exempt list id for later use
650                         $exempt_id = $v['id'];
651                                         //check to see if user is already in this exempt list
652                         if(in_array($v['id'], $user_list)){
653                                 $already_here = 'true';
654                         }
655
656                         break 2;
657                 }
658                 }
659         }
660
661         //unsubscribe subscripted newsletter
662         foreach($pl_arr as $subscription_list){
663                         //create a new instance of the prospect list
664                 $exempt_list = new ProspectList();
665                 $exempt_list->retrieve($subscription_list['id']);
666                 $exempt_list->load_relationship($relationship);
667                         //if list type is default, then delete the relationship
668             //if list type is exempt, then add the relationship to unsubscription list
669             if($subscription_list['list_type'] == 'exempt') {
670                         $exempt_list->$relationship->add($focus->id);
671             }elseif($subscription_list['list_type'] == 'default' || $subscription_list['list_type'] == 'test'){
672                 //if list type is default or test, then delete the relationship
673                 //$exempt_list->$relationship->delete($subscription_list['id'],$focus->id);
674             }
675
676         }
677
678         if($already_here =='true'){
679             //do nothing, user is already exempted
680
681         }else{
682             //user is not exempted yet , so add to unsubscription list
683
684
685             $exempt_result = $exempt_list->retrieve($exempt_id);
686             if($exempt_result == null)
687             {//error happened while retrieving this list
688                 return;
689             }
690             $GLOBALS['log']->debug("In Campaigns Util, loading relationship: ".$relationship);
691             $exempt_list->load_relationship($relationship);
692             $exempt_list->$relationship->add($focus->id);
693         }
694
695     }
696
697
698     /*
699      *This function will return a string to the newsletter wizard if campaign check
700      *does not return 100% healthy.
701      */
702     function diagnose()
703     {
704         global $mod_strings;
705         global $current_user;
706         $msg = " <table class='detail view small' width='100%'><tr><td> ".$mod_strings['LNK_CAMPAIGN_DIGNOSTIC_LINK']."</td></tr>";
707         //Start with email components
708         //monitored mailbox section
709         $focus = new Administration();
710         $focus->retrieveSettings(); //retrieve all admin settings.
711
712
713         //run query for mail boxes of type 'bounce'
714         $email_health = 0;
715         $email_components = 2;
716         $mbox_qry = "select * from inbound_email where deleted ='0' and mailbox_type = 'bounce'";
717         $mbox_res = $focus->db->query($mbox_qry);
718
719         $mbox = array();
720         while ($mbox_row = $focus->db->fetchByAssoc($mbox_res)){$mbox[] = $mbox_row;}
721         //if the array is not empty, then set "good" message
722         if(isset($mbox) && count($mbox)>0){
723             //everything is ok, do nothing
724
725         }else{
726             //if array is empty, then increment health counter
727             $email_health =$email_health +1;
728             $msg  .=  "<tr><td ><font color='red'><b>". $mod_strings['LBL_MAILBOX_CHECK1_BAD']."</b></font></td></tr>";
729         }
730
731
732         if (strstr($focus->settings['notify_fromaddress'], 'example.com')){
733             //if "from_address" is the default, then set "bad" message and increment health counter
734             $email_health =$email_health +1;
735             $msg .= "<tr><td ><font color='red'><b> ".$mod_strings['LBL_MAILBOX_CHECK2_BAD']." </b></font></td></tr>";
736         }else{
737             //do nothing, address has been changed
738         }
739         //if health counter is above 1, then show admin link
740         if($email_health>0){
741             if (is_admin($current_user)){
742                 $msg.="<tr><td ><a href='index.php?module=Campaigns&action=WizardEmailSetup";
743                 if(isset($_REQUEST['return_module'])){
744                     $msg.="&return_module=".$_REQUEST['return_module'];
745                 }
746                 if(isset($_REQUEST['return_action'])){
747                     $msg.="&return_action=".$_REQUEST['return_action'];
748                 }
749                 $msg.="'>".$mod_strings['LBL_EMAIL_SETUP_WIZ']."</a></td></tr>";
750             }else{
751                 $msg.="<tr><td >".$mod_strings['LBL_NON_ADMIN_ERROR_MSG']."</td></tr>";
752
753             }
754
755         }
756
757
758         // proceed with scheduler components
759
760         //create and run the scheduler queries
761         $sched_qry = "select job, name, status from schedulers where deleted = 0 and status = 'Active'";
762         $sched_res = $focus->db->query($sched_qry);
763         $sched_health = 0;
764         $sched = array();
765         $check_sched1 = 'function::runMassEmailCampaign';
766         $check_sched2 = 'function::pollMonitoredInboxesForBouncedCampaignEmails';
767         $sched_mes = '';
768         $sched_mes_body = '';
769         $scheds = array();
770
771         while ($sched_row = $focus->db->fetchByAssoc($sched_res)){$scheds[] = $sched_row;}
772         //iterate through and see which jobs were found
773         foreach ($scheds as $funct){
774           if( ($funct['job']==$check_sched1)  ||   ($funct['job']==$check_sched2)){
775                 if($funct['job']==$check_sched1){
776                     $check_sched1 ="found";
777                 }else{
778                     $check_sched2 ="found";
779                 }
780
781           }
782         }
783         //determine if error messages need to be displayed for schedulers
784         if($check_sched2 != 'found'){
785             $sched_health =$sched_health +1;
786             $msg.= "<tr><td><font color='red'><b>".$mod_strings['LBL_SCHEDULER_CHECK1_BAD']."</b></font></td></tr>";
787         }
788         if($check_sched1 != 'found'){
789             $sched_health =$sched_health +1;
790             $msg.= "<tr><td><font color='red'><b>".$mod_strings['LBL_SCHEDULER_CHECK2_BAD']."</b></font></td></tr>";
791         }
792         //if health counter is above 1, then show admin link
793         if($sched_health>0){
794             global $current_user;
795             if (is_admin($current_user)){
796                 $msg.="<tr><td ><a href='index.php?module=Schedulers&action=index'>".$mod_strings['LBL_SCHEDULER_LINK']."</a></td></tr>";
797             }else{
798                 $msg.="<tr><td >".$mod_strings['LBL_NON_ADMIN_ERROR_MSG']."</td></tr>";
799             }
800
801         }
802
803         //determine whether message should be returned
804         if(($sched_health + $email_health)>0){
805             $msg  .= "</table> ";
806         }else{
807             $msg = '';
808         }
809         return $msg;
810     }
811
812
813 /**
814  * Handle campaign log entry creation for mail-merge activity. The function will be called by the soap component.
815  *
816  * @param String campaign_id Primary key of the campaign
817  * @param array targets List of keys for entries from prospect_lists_prosects table
818  */
819  function campaign_log_mail_merge($campaign_id, $targets) {
820
821     $campaign= new Campaign();
822     $campaign->retrieve($campaign_id);
823
824     if (empty($campaign->id)) {
825         $GLOBALS['log']->debug('set_campaign_merge: Invalid campaign id'. $campaign_id);
826     } else {
827         foreach ($targets as $target_list_id) {
828             $pl_query = "select * from prospect_lists_prospects where id='".$GLOBALS['db']->quote($target_list_id)."'";
829             $result=$GLOBALS['db']->query($pl_query);
830             $row=$GLOBALS['db']->fetchByAssoc($result);
831             if (!empty($row)) {
832                 write_mail_merge_log_entry($campaign_id,$row);
833             }
834         }
835     }
836
837  }
838 /**
839  * Function creates a campaign_log entry for campaigns processesed using the mail-merge feature. If any entry
840  * exist the hit counter is updated. target_tracker_key is used to locate duplicate entries.
841  * @param string campaign_id Primary key of the campaign
842  * @param array $pl_row A row of data from prospect_lists_prospects table.
843  */
844 function write_mail_merge_log_entry($campaign_id,$pl_row) {
845
846     //Update the log entry if it exists.
847     $update="update campaign_log set hits=hits+1 where campaign_id='".$GLOBALS['db']->quote($campaign_id)."' and target_tracker_key='" . $GLOBALS['db']->quote($pl_row['id']) . "'";
848     $result=$GLOBALS['db']->query($update);
849
850     //get affected row count...
851     $count=$GLOBALS['db']->getAffectedRowCount();
852     if ($count==0) {
853         $data=array();
854
855         $data['id']="'" . create_guid() . "'";
856         $data['campaign_id']="'" . $GLOBALS['db']->quote($campaign_id) . "'";
857         $data['target_tracker_key']="'" . $GLOBALS['db']->quote($pl_row['id']) . "'";
858         $data['target_id']="'" .  $GLOBALS['db']->quote($pl_row['related_id']) . "'";
859         $data['target_type']="'" .  $GLOBALS['db']->quote($pl_row['related_type']) . "'";
860         $data['activity_type']="'targeted'";
861         $data['activity_date']="'" . TimeDate::getInstance()->nowDb() . "'";
862         $data['list_id']="'" .  $GLOBALS['db']->quote($pl_row['prospect_list_id']) . "'";
863         $data['hits']=1;
864         $data['deleted']=0;
865         $insert_query="INSERT into campaign_log (" . implode(",",array_keys($data)) . ")";
866         $insert_query.=" VALUES  (" . implode(",",array_values($data)) . ")";
867         $GLOBALS['db']->query($insert_query);
868     }
869 }
870
871     function track_campaign_prospects($focus){
872         $campaign_id = $GLOBALS['db']->quote($focus->id);
873         $delete_query="delete from campaign_log where campaign_id='".$campaign_id."' and activity_type='targeted'";
874         $focus->db->query($delete_query);
875
876         $current_date = $focus->db->now();
877         $guidSQL = $focus->db->getGuidSQL();
878
879         $insert_query= "INSERT INTO campaign_log (id,activity_date, campaign_id, target_tracker_key,list_id, target_id, target_type, activity_type, deleted";
880         $insert_query.=')';
881         $insert_query.="SELECT {$guidSQL}, $current_date, plc.campaign_id,{$guidSQL},plp.prospect_list_id, plp.related_id, plp.related_type,'targeted',0 ";
882         $insert_query.="FROM prospect_lists INNER JOIN prospect_lists_prospects plp ON plp.prospect_list_id = prospect_lists.id";
883         $insert_query.=" INNER JOIN prospect_list_campaigns plc ON plc.prospect_list_id = prospect_lists.id";
884         $insert_query.=" WHERE plc.campaign_id='".$GLOBALS['db']->quote($focus->id)."'";
885         $insert_query.=" AND prospect_lists.deleted=0";
886         $insert_query.=" AND plc.deleted=0";
887         $insert_query.=" AND plp.deleted=0";
888         $insert_query.=" AND prospect_lists.list_type!='test' AND prospect_lists.list_type not like 'exempt%'";
889         $focus->db->query($insert_query);
890
891         global $mod_strings;
892         //return success message
893         return $mod_strings['LBL_DEFAULT_LIST_ENTRIES_WERE_PROCESSED'];
894     }
895
896     function create_campaign_log_entry($campaign_id, $focus, $rel_name, $rel_bean, $target_id = ''){
897         global $timedate;
898
899         $target_ids = array();
900         //check if this is specified for one target/contact/prospect/lead (from contact/lead detail subpanel)
901         if(!empty($target_id)){
902             $target_ids[] = $target_id;
903         }else{
904             //this is specified for all, so load target/prospect relationships (mark as sent button)
905             $focus->load_relationship($rel_name);
906             $target_ids = $focus->$rel_name->get();
907
908         }
909         if(count($target_ids)>0){
910
911
912             //retrieve the target beans and create campaign log entry
913             foreach($target_ids as $id){
914                  //perform duplicate check
915                  $dup_query = "select id from campaign_log where campaign_id = '$campaign_id' and target_id = '$id'";
916                  $dup_result = $focus->db->query($dup_query);
917                  $row = $focus->db->fetchByAssoc($dup_result);
918
919                 //process if this is not a duplicate campaign log entry
920                 if(empty($row)){
921                     //create campaign tracker id and retrieve related bio bean
922                      $tracker_id = create_guid();
923                      $rel_bean->retrieve($id);
924
925                     //create new campaign log record.
926                     $campaign_log = new CampaignLog();
927                     $campaign_log->campaign_id = $campaign_id;
928                     $campaign_log->target_tracker_key = $tracker_id;
929                     $campaign_log->target_id = $rel_bean->id;
930                     $campaign_log->target_type = $rel_bean->module_dir;
931                     $campaign_log->activity_type = 'targeted';
932                     $campaign_log->activity_date=$timedate->now();
933                     //save the campaign log entry
934                     $campaign_log->save();
935                 }
936             }
937         }
938
939     }
940
941     /*
942      * This function will return an array that has been formatted to work as a Quick Search Object for prospect lists
943      */
944     function getProspectListQSObjects($source = '', $return_field_name='name', $return_field_id='id' ) {
945         global $app_strings;
946         //if source has not been specified, then search across all prospect lists
947         if(empty($source)){
948             $qsProspectList = array('method' => 'query',
949                                 'modules'=> array('ProspectLists'),
950                                 'group' => 'and',
951                                 'field_list' => array('name', 'id'),
952                                 'populate_list' => array('prospect_list_name', 'prospect_list_id'),
953                                 'conditions' => array( array('name'=>'name','op'=>'like_custom','end'=>'%','value'=>'') ),
954                                 'order' => 'name',
955                                 'limit' => '30',
956                                 'no_match_text' => $app_strings['ERR_SQS_NO_MATCH']);
957         }else{
958              //source has been specified use it to tell quicksearch.js which html input to use to get filter value
959             $qsProspectList = array('method' => 'query',
960                                 'modules'=> array('ProspectLists'),
961                                 'group' => 'and',
962                                 'field_list' => array('name', 'id'),
963                                 'populate_list' => array($return_field_name, $return_field_id),
964                                 'conditions' => array(
965                                                     array('name'=>'name','op'=>'like_custom','end'=>'%','value'=>''),
966                                                     //this condition has the source parameter defined, meaning the query will take the value specified below
967                                                     array('name'=>'list_type', 'op'=>'like_custom', 'end'=>'%','value'=>'', 'source' => $source)
968                                 ),
969                                 'order' => 'name',
970                                 'limit' => '30',
971                                 'no_match_text' => $app_strings['ERR_SQS_NO_MATCH']);
972
973         }
974
975         return $qsProspectList;
976     }
977
978
979 ?>