]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Activities/EmailReminder.php
Release 6.5.8
[Github/sugarcrm.git] / modules / Activities / EmailReminder.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 require_once("modules/Meetings/Meeting.php");
40 require_once("modules/Calls/Call.php");
41 require_once("modules/Users/User.php");
42 require_once("modules/Contacts/Contact.php");
43 require_once("modules/Leads/Lead.php");
44
45 /**
46  * Class for sending email reminders of meetings and call to invitees
47  * 
48  */
49 class EmailReminder
50 {
51     
52     /**
53      * string db datetime of now
54      */
55     protected $now;
56     
57     /**
58      * string db datetime will be fetched till
59      */
60     protected $max;
61     
62     /**
63      * constructor
64      */
65     public function __construct()
66     {
67         $max_time = 0;
68         if(isset($GLOBALS['app_list_strings']['reminder_time_options'])){
69             foreach($GLOBALS['app_list_strings']['reminder_time_options'] as $seconds => $value ) {
70                 if ( $seconds > $max_time ) {
71                     $max_time = $seconds;
72                 }
73             }
74         }else{
75             $max_time = 8400;
76         }
77         $this->now = $GLOBALS['timedate']->nowDb();
78         $this->max = $GLOBALS['timedate']->getNow()->modify("+{$max_time} seconds")->asDb();
79     }
80     
81     /**
82      * main method that runs reminding process
83      * @return boolean
84      */
85     public function process()
86     {
87
88         $admin = new Administration();
89         $admin->retrieveSettings();
90         
91         $meetings = $this->getMeetingsForRemind();
92         foreach($meetings as $id ) {
93             $recipients = $this->getRecipients($id,'Meetings');
94             $bean = new Meeting();
95             $bean->retrieve($id);
96             if ( $this->sendReminders($bean, $admin, $recipients) ) {
97                 $bean->email_reminder_sent = 1;
98                 $bean->save();
99             }            
100         }
101         
102         $calls = $this->getCallsForRemind();
103         foreach($calls as $id ) {
104             $recipients = $this->getRecipients($id,'Calls');
105             $bean = new Call();
106             $bean->retrieve($id);
107             if ( $this->sendReminders($bean, $admin, $recipients) ) {
108                 $bean->email_reminder_sent = 1;
109                 $bean->save();
110             }
111         }
112         
113         return true;
114     }
115     
116     /**
117      * send reminders
118      * @param SugarBean $bean
119      * @param Administration $admin
120      * @param array $recipients
121      * @return boolean
122      */
123     protected function sendReminders(SugarBean $bean, Administration $admin, $recipients)
124     {
125         
126         if ( empty($_SESSION['authenticated_user_language']) ) {
127             $current_language = $GLOBALS['sugar_config']['default_language'];
128         }else{
129             $current_language = $_SESSION['authenticated_user_language'];
130         }            
131                 
132                 if ( !empty($bean->created_by) ) {
133             $user_id = $bean->created_by;
134         }else if ( !empty($bean->assigned_user_id) ) {
135             $user_id = $bean->assigned_user_id;
136         }else {
137             $user_id = $GLOBLAS['current_user']->id;
138         }
139         $user = new User();
140         $user->retrieve($bean->created_by);
141             
142         $OBCharset = $GLOBALS['locale']->getPrecedentPreference('default_email_charset');
143         require_once("include/SugarPHPMailer.php");
144         $mail = new SugarPHPMailer();
145         $mail->setMailerForSystem();
146         
147         if(empty($admin->settings['notify_send_from_assigning_user']))
148         {
149             $from_address = $admin->settings['notify_fromaddress'];
150             $from_name = $admin->settings['notify_fromname'] ? "" : $admin->settings['notify_fromname'];
151         }
152         else
153         {
154             $from_address = $user->emailAddress->getReplyToAddress($user);
155             $from_name = $user->full_name;
156         }
157
158         $mail->From = $from_address;
159         $mail->FromName = $from_name;
160         
161         $xtpl = new XTemplate(get_notify_template_file($current_language));
162         $xtpl = $this->setReminderBody($xtpl, $bean, $user);
163         
164         $template_name = $GLOBALS['beanList'][$bean->module_dir].'Reminder';
165         $xtpl->parse($template_name);
166         $xtpl->parse($template_name . "_Subject");
167         
168         $mail->Body = from_html(trim($xtpl->text($template_name)));
169                $mail->Subject = from_html($xtpl->text($template_name . "_Subject"));
170                
171                $oe = new OutboundEmail();
172         $oe = $oe->getSystemMailerSettings();
173         if ( empty($oe->mail_smtpserver) ) {
174             $GLOBALS['log']->fatal("Email Reminder: error sending email, system smtp server is not set");
175             return;
176         }
177
178         foreach($recipients as $r ) {
179             $mail->ClearAddresses();
180             $mail->AddAddress($r['email'],$GLOBALS['locale']->translateCharsetMIME(trim($r['name']), 'UTF-8', $OBCharset));    
181             $mail->prepForOutbound();
182             if ( !$mail->Send() ) {
183                 $GLOBALS['log']->fatal("Email Reminder: error sending e-mail (method: {$mail->Mailer}), (error: {$mail->ErrorInfo})");
184             }
185         }
186     
187         return true;
188     }
189     
190     /**
191      * set reminder body
192      * @param XTemplate $xtpl
193      * @param SugarBean $bean
194      * @param User $user
195      * @return XTemplate 
196     */
197     protected function setReminderBody(XTemplate $xtpl, SugarBean $bean, User $user)
198     {
199     
200         $object = strtoupper($bean->object_name);
201
202         $xtpl->assign("{$object}_SUBJECT", $bean->name);
203         $date = $GLOBALS['timedate']->fromUser($bean->date_start,$GLOBALS['current_user']);
204         $xtpl->assign("{$object}_STARTDATE", $GLOBALS['timedate']->asUser($date, $user)." ".TimeDate::userTimezoneSuffix($date, $user));
205         if ( isset($bean->location) ) {
206             $xtpl->assign("{$object}_LOCATION", $bean->location);
207         }
208         $xtpl->assign("{$object}_CREATED_BY", $user->full_name);
209         $xtpl->assign("{$object}_DESCRIPTION", $bean->description);
210
211         return $xtpl;
212     }
213     
214     /**
215      * get meeting ids list for remind
216      * @return array
217      */
218     public function getMeetingsForRemind()
219     {
220         global $db;
221         $query = "
222             SELECT id, date_start, email_reminder_time FROM meetings 
223             WHERE email_reminder_time != -1
224             AND deleted = 0
225             AND email_reminder_sent = 0
226             AND status != 'Held'
227             AND date_start >= '{$this->now}'
228             AND date_start <= '{$this->max}'
229         ";
230         $re = $db->query($query);
231         $meetings = array();
232         while($row = $db->fetchByAssoc($re) ) {
233             $remind_ts = $GLOBALS['timedate']->fromDb($db->fromConvert($row['date_start'],'datetime'))->modify("-{$row['email_reminder_time']} seconds")->ts;
234             $now_ts = $GLOBALS['timedate']->getNow()->ts;
235             if ( $now_ts >= $remind_ts ) {
236                 $meetings[] = $row['id'];
237             }
238         }
239         return $meetings;
240     }
241     
242     /**
243      * get calls ids list for remind
244      * @return array
245      */
246     public function getCallsForRemind()
247     {
248         global $db;
249         $query = "
250             SELECT id, date_start, email_reminder_time FROM calls
251             WHERE email_reminder_time != -1
252             AND deleted = 0
253             AND email_reminder_sent = 0
254             AND status != 'Held'
255             AND date_start >= '{$this->now}'
256             AND date_start <= '{$this->max}'
257         ";
258         $re = $db->query($query);
259         $calls = array();
260         while($row = $db->fetchByAssoc($re) ) {
261             $remind_ts = $GLOBALS['timedate']->fromDb($db->fromConvert($row['date_start'],'datetime'))->modify("-{$row['email_reminder_time']} seconds")->ts;
262             $now_ts = $GLOBALS['timedate']->getNow()->ts;
263             if ( $now_ts >= $remind_ts ) {
264                 $calls[] = $row['id'];
265             }
266         }
267         return $calls;
268     }
269     
270     /**
271      * get recipients of reminding email for specific activity
272      * @param string $id
273      * @param string $module
274      * @return array
275      */
276     protected function getRecipients($id, $module = "Meetings")
277     {
278         global $db;
279     
280         switch($module ) {
281             case "Meetings":
282                 $field_part = "meeting";
283                 break;
284             case "Calls":
285                 $field_part = "call";
286                 break;
287             default:
288                 return array();
289         }
290     
291         $emails = array();
292         // fetch users
293         $query = "SELECT user_id FROM {$field_part}s_users WHERE {$field_part}_id = '{$id}' AND accept_status != 'decline' AND deleted = 0
294         ";
295         $re = $db->query($query);
296         while($row = $db->fetchByAssoc($re) ) {
297             $user = new User();
298             $user->retrieve($row['user_id']);
299             if ( !empty($user->email1) ) {
300                 $arr = array(
301                     'type' => 'Users',
302                     'name' => $user->full_name,
303                     'email' => $user->email1,
304                 );
305                 $emails[] = $arr;
306             }
307         }        
308         // fetch contacts
309         $query = "SELECT contact_id FROM {$field_part}s_contacts WHERE {$field_part}_id = '{$id}' AND accept_status != 'decline' AND deleted = 0";
310         $re = $db->query($query);
311         while($row = $db->fetchByAssoc($re) ) {
312             $contact = new Contact();
313             $contact->retrieve($row['contact_id']);
314             if ( !empty($contact->email1) ) {
315                 $arr = array(
316                     'type' => 'Contacts',
317                     'name' => $contact->full_name,
318                     'email' => $contact->email1,
319                 );
320                 $emails[] = $arr;
321             }
322         }        
323         // fetch leads
324         $query = "SELECT lead_id FROM {$field_part}s_leads WHERE {$field_part}_id = '{$id}' AND accept_status != 'decline' AND deleted = 0";
325         $re = $db->query($query);
326         while($row = $db->fetchByAssoc($re) ) {
327             $lead = new Lead();
328             $lead->retrieve($row['lead_id']);
329             if ( !empty($lead->email1) ) {
330                 $arr = array(
331                     'type' => 'Leads',
332                     'name' => $lead->full_name,
333                     'email' => $lead->email1,
334                 );
335                 $emails[] = $arr;
336             }
337         }
338         return $emails;
339     }
340 }
341