]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Campaigns/Campaign.php
Release 6.5.1
[Github/sugarcrm.git] / modules / Campaigns / Campaign.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-2012 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:
41  ********************************************************************************/
42
43 class Campaign extends SugarBean {
44         var $field_name_map;
45
46         // Stored fields
47         var $id;
48         var $date_entered;
49         var $date_modified;
50         var $modified_user_id;
51         var $assigned_user_id;
52         var $created_by;
53         var $created_by_name;
54     var $currency_id;
55         var $modified_by_name;
56         var $name;
57         var $start_date;
58         var $end_date;
59         var $status;
60         var $expected_cost;
61         var $budget;
62         var $actual_cost;
63         var $expected_revenue;
64         var $campaign_type;
65         var $objective;
66         var $content;
67         var $tracker_key;
68         var $tracker_text;
69         var $tracker_count;
70         var $refer_url;
71     var $impressions;
72
73         // These are related
74         var $assigned_user_name;
75
76         // module name definitions and table relations
77         var $table_name = "campaigns";
78         var $rel_prospect_list_table = "prospect_list_campaigns";
79         var $object_name = "Campaign";
80         var $module_dir = 'Campaigns';
81         var $importable = true;
82
83         // This is used to retrieve related fields from form posts.
84         var $additional_column_fields = array(
85                                 'assigned_user_name', 'assigned_user_id',
86         );
87
88         var $relationship_fields = Array('prospect_list_id'=>'prospect_lists');
89
90         var $new_schema = true;
91
92         function list_view_parse_additional_sections(&$listTmpl) {
93                 global $locale;
94
95                 // take $assigned_user_id and get the Username value to assign
96                 $assId = $this->getFieldValue('assigned_user_id');
97
98                 $query = "SELECT first_name, last_name FROM users WHERE id = '".$assId."'";
99                 $result = $this->db->query($query);
100                 $user = $this->db->fetchByAssoc($result);
101
102                 //_ppd($user);
103                 if(!empty($user)) {
104                         $fullName = $locale->getLocaleFormattedName($user->first_name, $user->last_name);
105                         $listTmpl->assign('ASSIGNED_USER_NAME', $fullName);
106                 }
107         }
108
109
110         function get_summary_text()
111         {
112                 return $this->name;
113         }
114
115         function create_export_query(&$order_by, &$where, $relate_link_join='')
116         {
117                 $custom_join = $this->custom_fields->getJOIN(true, true,$where);
118                         if($custom_join)
119                                 $custom_join['join'] .= $relate_link_join;
120             $query = "SELECT
121             campaigns.*,
122             users.user_name as assigned_user_name ";
123                 if($custom_join){
124                                 $query .=  $custom_join['select'];
125                         }
126                 $query .= " FROM campaigns ";
127                         $query .= "LEFT JOIN users
128                       ON campaigns.assigned_user_id=users.id";
129                 if($custom_join){
130                                 $query .=  $custom_join['join'];
131                         }
132
133                 $where_auto = " campaigns.deleted=0";
134
135         if($where != "")
136                 $query .= " where $where AND ".$where_auto;
137         else
138                 $query .= " where ".$where_auto;
139
140         if($order_by != "")
141                 $query .= " ORDER BY $order_by";
142         else
143                 $query .= " ORDER BY campaigns.name";
144         return $query;
145     }
146
147
148
149         function clear_campaign_prospect_list_relationship($campaign_id, $prospect_list_id='')
150         {
151                 if(!empty($prospect_list_id))
152                         $prospect_clause = " and prospect_list_id = '$prospect_list_id' ";
153                 else
154                         $prospect_clause = '';
155
156                 $query = "DELETE FROM $this->rel_prospect_list_table WHERE campaign_id='$campaign_id' AND deleted = '0' " . $prospect_clause;
157                 $this->db->query($query, true, "Error clearing campaign to prospect_list relationship: ");
158         }
159
160
161
162         function mark_relationships_deleted($id)
163         {
164                 $this->clear_campaign_prospect_list_relationship($id);
165         }
166
167         function fill_in_additional_list_fields()
168         {
169                 parent::fill_in_additional_list_fields();
170         }
171
172         function fill_in_additional_detail_fields()
173         {
174         parent::fill_in_additional_detail_fields();
175                 //format numbers.
176
177                 //don't need additional formatting here.
178                 //$this->budget=format_number($this->budget);
179                 //$this->expected_cost=format_number($this->expected_cost);
180                 //$this->actual_cost=format_number($this->actual_cost);
181                 //$this->expected_revenue=format_number($this->expected_revenue);
182         }
183
184
185         function update_currency_id($fromid, $toid){
186         }
187
188
189         function get_list_view_data(){
190
191                 $temp_array = $this->get_list_view_array();
192                 if ($this->campaign_type != 'Email') {
193                         $temp_array['OPTIONAL_LINK']="display:none";
194                 }
195                 $temp_array['TRACK_CAMPAIGN_TITLE'] = translate("LBL_TRACK_BUTTON_TITLE",'Campaigns');
196                 $temp_array['TRACK_CAMPAIGN_IMAGE'] = SugarThemeRegistry::current()->getImageURL('view_status.gif');
197                 $temp_array['LAUNCH_WIZARD_TITLE'] = translate("LBL_TO_WIZARD_TITLE",'Campaigns');
198                 $temp_array['LAUNCH_WIZARD_IMAGE'] = SugarThemeRegistry::current()->getImageURL('edit_wizard.gif');
199         $temp_array['TRACK_VIEW_ALT_TEXT'] = translate("LBL_TRACK_BUTTON_TITLE",'Campaigns');
200         $temp_array['LAUNCH_WIZ_ALT_TEXT'] = translate("LBL_TO_WIZARD_TITLE",'Campaigns');
201
202                 return $temp_array;
203         }
204         /**
205                 builds a generic search based on the query string using or
206                 do not include any $this-> because this is called on without having the class instantiated
207         */
208         function build_generic_where_clause ($the_query_string)
209         {
210                 $where_clauses = Array();
211                 $the_query_string = $this->db->quote($the_query_string);
212                 array_push($where_clauses, "campaigns.name like '$the_query_string%'");
213
214                 $the_where = "";
215                 foreach($where_clauses as $clause)
216                 {
217                         if($the_where != "") $the_where .= " or ";
218                         $the_where .= $clause;
219                 }
220
221
222                 return $the_where;
223         }
224
225         function save($check_notify = FALSE) {
226
227                         //US DOLLAR
228                         if(isset($this->amount) && !empty($this->amount)){
229
230                                 $currency = new Currency();
231                                 $currency->retrieve($this->currency_id);
232                                 $this->amount_usdollar = $currency->convertToDollar($this->amount);
233
234                         }
235
236                 $this->unformat_all_fields();
237
238                 // Bug53301
239                 if($this->campaign_type != 'NewsLetter') {
240                     $this->frequency = '';
241                 }
242                 
243                 return parent::save($check_notify);
244
245         }
246
247
248         function mark_deleted($id){
249         $query = "update contacts set campaign_id = null where campaign_id = '{$id}' ";
250         $this->db->query($query);
251         $query = "update accounts set campaign_id = null where campaign_id = '{$id}' ";
252         $this->db->query($query);
253         // bug49632 - delete campaign logs for the campaign as well
254         $query = "update campaign_log set deleted = 1 where campaign_id = '{$id}' ";
255         $this->db->query($query);
256                 return parent::mark_deleted($id);
257         }
258
259         function set_notification_body($xtpl, $camp)
260         {
261                 $xtpl->assign("CAMPAIGN_NAME", $camp->name);
262                 $xtpl->assign("CAMPAIGN_AMOUNT", $camp->budget);
263                 $xtpl->assign("CAMPAIGN_CLOSEDATE", $camp->end_date);
264                 $xtpl->assign("CAMPAIGN_STATUS", $camp->status);
265                 $xtpl->assign("CAMPAIGN_DESCRIPTION", $camp->content);
266
267                 return $xtpl;
268         }
269
270     function track_log_leads()
271     {
272         $this->load_relationship('log_entries');
273         $query_array = $this->log_entries->getQuery(true);
274
275         $query_array['select'] = 'SELECT campaign_log.* ';
276         $query_array['where']  = $query_array['where']. " AND activity_type = 'lead' AND archived = 0 AND target_id IS NOT NULL";
277
278         return implode(' ', $query_array);
279     }
280
281         function track_log_entries($type=array()) {
282         //get arguments being passed in
283         $args = func_get_args();
284         $mkt_id ='';
285
286                 $this->load_relationship('log_entries');
287                 $query_array = $this->log_entries->getQuery(true);
288
289         //if one of the arguments is marketing ID, then we need to filter by it
290         foreach($args as $arg){
291             if(isset($arg['EMAIL_MARKETING_ID_VALUE'])){
292                 $mkt_id = $arg['EMAIL_MARKETING_ID_VALUE'];
293             }
294
295             if(isset($arg['group_by'])) {
296                 $query_array['group_by'] = $arg['group_by'];
297             }
298         }
299
300
301
302                 if (empty($type))
303                         $type[0]='targeted';
304
305                 $query_array['select'] ="SELECT campaign_log.* ";
306                 $query_array['where'] = $query_array['where']. " AND activity_type='{$type[0]}' AND archived=0";
307         //add filtering by marketing id, if it exists
308         if (!empty($mkt_id)) $query_array['where'] = $query_array['where']. " AND marketing_id ='$mkt_id' ";
309
310         //B.F. #37943
311         if( isset($query_array['group_by']))
312         {
313                         //perform the inner join with the group by if a marketing id is defined, which means we need to filter out duplicates.
314                         //if no marketing id is specified then we are displaying results from multiple marketing emails and it is understood there might be duplicate target entries
315                         if (!empty($mkt_id)){
316                                 $group_by = str_replace("campaign_log", "cl", $query_array['group_by']);
317                                 $join_where = str_replace("campaign_log", "cl", $query_array['where']);
318                                 $query_array['from'] .= " INNER JOIN (select min(id) as id from campaign_log cl $join_where GROUP BY $group_by  ) secondary
319                                         on campaign_log.id = secondary.id       ";
320                         }
321             unset($query_array['group_by']);
322         } else if(isset($query_array['group_by'])) {
323            $query_array['where'] = $query_array['where'] . ' GROUP BY ' . $query_array['group_by'];
324            unset($query_array['group_by']);
325         }
326
327         $query = (implode(" ",$query_array));
328         return $query;
329         }
330
331
332         function get_queue_items() {
333         //get arguments being passed in
334         $args = func_get_args();
335         $mkt_id ='';
336
337         $this->load_relationship('queueitems');
338                 $query_array = $this->queueitems->getQuery(true);
339
340         //if one of the arguments is marketing ID, then we need to filter by it
341         foreach($args as $arg){
342             if(isset($arg['EMAIL_MARKETING_ID_VALUE'])){
343                 $mkt_id = $arg['EMAIL_MARKETING_ID_VALUE'];
344             }
345
346             if(isset($arg['group_by'])) {
347                 $query_array['group_by'] = $arg['group_by'];
348             }
349         }
350
351         //add filtering by marketing id, if it exists, and if where key is not empty
352         if (!empty($mkt_id) && !empty($query_array['where'])){
353              $query_array['where'] = $query_array['where']. " AND marketing_id ='$mkt_id' ";
354         }
355
356                 //get select query from email man
357                 $man = new EmailMan();
358                 $listquery= $man->create_queue_items_query('',str_replace(array("WHERE","where"),"",$query_array['where']),null,$query_array);
359                 return $listquery;
360
361         }
362 //      function get_prospect_list_entries() {
363 //              $this->load_relationship('prospectlists');
364 //              $query_array = $this->prospectlists->getQuery(true);
365 //
366 //              $query=<<<EOQ
367 //                      SELECT distinct prospect_lists.*,
368 //                      (case  when (email_marketing.id is null) then default_message.id else email_marketing.id end) marketing_id,
369 //                      (case  when  (email_marketing.id is null) then default_message.name else email_marketing.name end) marketing_name
370 //
371 //                      FROM prospect_lists
372 //
373 //                      INNER JOIN prospect_list_campaigns ON (prospect_lists.id=prospect_list_campaigns.prospect_list_id AND prospect_list_campaigns.campaign_id='{$this->id}')
374 //
375 //                      LEFT JOIN email_marketing on email_marketing.message_for = prospect_lists.id and email_marketing.campaign_id = '{$this->id}'
376 //                      and email_marketing.deleted =0 and email_marketing.status='active'
377 //
378 //                      LEFT JOIN email_marketing default_message on default_message.message_for = prospect_list_campaigns.campaign_id and
379 //                      default_message.campaign_id = '{$this->id}' and default_message.deleted =0
380 //                      and default_message.status='active'
381 //
382 //                      WHERE prospect_list_campaigns.deleted=0 AND prospect_lists.deleted=0
383 //
384 //EOQ;
385 //              return $query;
386 //      }
387
388          function bean_implements($interface){
389                 switch($interface){
390                         case 'ACL':return true;
391                 }
392                 return false;
393         }
394
395
396         /**
397          * create_list_count_query
398          * Overrode this method from SugarBean to handle the distinct parameter used to filter out
399          * duplicate entries for some of the subpanel listivews.  Without the distinct filter, the
400          * list count would be inaccurate because one-to-many email_marketing entries may be associated
401          * with a campaign.
402      *
403      * @param string $query Select query string
404      * @param array $param array of arguments
405      * @return string count query
406      *
407          */
408     function create_list_count_query($query, $params=array())
409     {
410                 //include the distinct filter if a marketing id is defined, which means we need to filter out duplicates by the passed in group by.
411                 //if no marketing id is specified, it is understood there might be duplicate target entries so no need to filter out
412                 if((strpos($query,'marketing_id') !== false )&& isset($params['distinct'])) {
413                    $pattern = '/SELECT(.*?)(\s){1}FROM(\s){1}/is';  // ignores the case
414            $replacement = 'SELECT COUNT(DISTINCT ' . $params['distinct'] . ') c FROM ';
415            $query = preg_replace($pattern, $replacement, $query, 1);
416            return $query;
417                 }
418
419                 //If distinct parameter not found, default to SugarBean's function
420         return parent::create_list_count_query($query);
421     }
422
423     /**
424      * Returns count of deleted leads,
425      * which were created through generated lead form
426      *
427      * @return integer
428      */
429     function getDeletedCampaignLogLeadsCount()
430     {
431         $query = "SELECT COUNT(*) AS count FROM campaign_log WHERE campaign_id = '" . $this->getFieldValue('id') . "' AND target_id IS NULL AND activity_type = 'lead'";
432         $result = $this->db->fetchOne($query);
433
434         return (int)$result['count'];
435     }
436 }
437 ?>