]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Activities/EmailReminder.php
Release 6.5.0
[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         $from_address = $user->emailAddress->getReplyToAddress($user);
148         $from_address = !empty($from_address) ? $from_address : $admin->settings['notify_fromaddress'];
149         $mail->From = $from_address;
150         $from_name = !empty($user->full_name) ? $user->full_name : $admin->settings['notify_fromname'];
151         $mail->FromName = $from_name;
152         
153         $xtpl = new XTemplate(get_notify_template_file($current_language));
154         $xtpl = $this->setReminderBody($xtpl, $bean, $user);
155         
156         $template_name = $GLOBALS['beanList'][$bean->module_dir].'Reminder';
157         $xtpl->parse($template_name);
158         $xtpl->parse($template_name . "_Subject");
159         
160         $mail->Body = from_html(trim($xtpl->text($template_name)));
161                $mail->Subject = from_html($xtpl->text($template_name . "_Subject"));
162                
163                $oe = new OutboundEmail();
164         $oe = $oe->getSystemMailerSettings();
165         if ( empty($oe->mail_smtpserver) ) {
166             $GLOBALS['log']->fatal("Email Reminder: error sending email, system smtp server is not set");
167             return;
168         }
169
170         foreach($recipients as $r ) {
171             $mail->ClearAddresses();
172             $mail->AddAddress($r['email'],$GLOBALS['locale']->translateCharsetMIME(trim($r['name']), 'UTF-8', $OBCharset));    
173             $mail->prepForOutbound();
174             if ( !$mail->Send() ) {
175                 $GLOBALS['log']->fatal("Email Reminder: error sending e-mail (method: {$mail->Mailer}), (error: {$mail->ErrorInfo})");
176             }
177         }
178     
179         return true;
180     }
181     
182     /**
183      * set reminder body
184      * @param XTemplate $xtpl
185      * @param SugarBean $bean
186      * @param User $user
187      * @return XTemplate 
188     */
189     protected function setReminderBody(XTemplate $xtpl, SugarBean $bean, User $user)
190     {
191     
192         $object = strtoupper($bean->object_name);
193
194         $xtpl->assign("{$object}_SUBJECT", $bean->name);
195         $date = $GLOBALS['timedate']->fromUser($bean->date_start,$GLOBALS['current_user']);
196         $xtpl->assign("{$object}_STARTDATE", $GLOBALS['timedate']->asUser($date, $user)." ".TimeDate::userTimezoneSuffix($date, $user));
197         if ( isset($bean->location) ) {
198             $xtpl->assign("{$object}_LOCATION", $bean->location);
199         }
200         $xtpl->assign("{$object}_CREATED_BY", $user->full_name);
201         $xtpl->assign("{$object}_DESCRIPTION", $bean->description);
202
203         return $xtpl;
204     }
205     
206     /**
207      * get meeting ids list for remind
208      * @return array
209      */
210     public function getMeetingsForRemind()
211     {
212         global $db;
213         $query = "
214             SELECT id, date_start, email_reminder_time FROM meetings 
215             WHERE email_reminder_time != -1
216             AND deleted = 0
217             AND email_reminder_sent = 0
218             AND status != 'Held'
219             AND date_start >= '{$this->now}'
220             AND date_start <= '{$this->max}'
221         ";
222         $re = $db->query($query);
223         $meetings = array();
224         while($row = $db->fetchByAssoc($re) ) {
225             $remind_ts = $GLOBALS['timedate']->fromDb($db->fromConvert($row['date_start'],'datetime'))->modify("-{$row['email_reminder_time']} seconds")->ts;
226             $now_ts = $GLOBALS['timedate']->getNow()->ts;
227             if ( $now_ts >= $remind_ts ) {
228                 $meetings[] = $row['id'];
229             }
230         }
231         return $meetings;
232     }
233     
234     /**
235      * get calls ids list for remind
236      * @return array
237      */
238     public function getCallsForRemind()
239     {
240         global $db;
241         $query = "
242             SELECT id, date_start, email_reminder_time FROM calls
243             WHERE email_reminder_time != -1
244             AND deleted = 0
245             AND email_reminder_sent = 0
246             AND status != 'Held'
247             AND date_start >= '{$this->now}'
248             AND date_start <= '{$this->max}'
249         ";
250         $re = $db->query($query);
251         $calls = array();
252         while($row = $db->fetchByAssoc($re) ) {
253             $remind_ts = $GLOBALS['timedate']->fromDb($db->fromConvert($row['date_start'],'datetime'))->modify("-{$row['email_reminder_time']} seconds")->ts;
254             $now_ts = $GLOBALS['timedate']->getNow()->ts;
255             if ( $now_ts >= $remind_ts ) {
256                 $calls[] = $row['id'];
257             }
258         }
259         return $calls;
260     }
261     
262     /**
263      * get recipients of reminding email for specific activity
264      * @param string $id
265      * @param string $module
266      * @return array
267      */
268     protected function getRecipients($id, $module = "Meetings")
269     {
270         global $db;
271     
272         switch($module ) {
273             case "Meetings":
274                 $field_part = "meeting";
275                 break;
276             case "Calls":
277                 $field_part = "call";
278                 break;
279             default:
280                 return array();
281         }
282     
283         $emails = array();
284         // fetch users
285         $query = "SELECT user_id FROM {$field_part}s_users WHERE {$field_part}_id = '{$id}' AND accept_status != 'decline' AND deleted = 0
286         ";
287         $re = $db->query($query);
288         while($row = $db->fetchByAssoc($re) ) {
289             $user = new User();
290             $user->retrieve($row['user_id']);
291             if ( !empty($user->email1) ) {
292                 $arr = array(
293                     'type' => 'Users',
294                     'name' => $user->full_name,
295                     'email' => $user->email1,
296                 );
297                 $emails[] = $arr;
298             }
299         }        
300         // fetch contacts
301         $query = "SELECT contact_id FROM {$field_part}s_contacts WHERE {$field_part}_id = '{$id}' AND accept_status != 'decline' AND deleted = 0";
302         $re = $db->query($query);
303         while($row = $db->fetchByAssoc($re) ) {
304             $contact = new Contact();
305             $contact->retrieve($row['contact_id']);
306             if ( !empty($contact->email1) ) {
307                 $arr = array(
308                     'type' => 'Contacts',
309                     'name' => $contact->full_name,
310                     'email' => $contact->email1,
311                 );
312                 $emails[] = $arr;
313             }
314         }        
315         // fetch leads
316         $query = "SELECT lead_id FROM {$field_part}s_leads WHERE {$field_part}_id = '{$id}' AND accept_status != 'decline' AND deleted = 0";
317         $re = $db->query($query);
318         while($row = $db->fetchByAssoc($re) ) {
319             $lead = new Lead();
320             $lead->retrieve($row['lead_id']);
321             if ( !empty($lead->email1) ) {
322                 $arr = array(
323                     'type' => 'Leads',
324                     'name' => $lead->full_name,
325                     'email' => $lead->email1,
326                 );
327                 $emails[] = $arr;
328             }
329         }
330         return $emails;
331     }
332 }
333