]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/OutboundEmail/OutboundEmail.php
Release 6.1.4
[Github/sugarcrm.git] / include / OutboundEmail / OutboundEmail.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 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  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42  * Reserved. Contributor(s): ______________________________________..
43  *********************************************************************************/
44
45 class OutboundEmail {
46         /**
47          * Necessary
48          */
49         var $db;
50         var $field_defs = array(
51                 'id',
52                 'name',
53                 'type',
54                 'user_id',
55                 'mail_sendtype',
56                 'mail_smtptype',
57                 'mail_smtpserver',
58                 'mail_smtpport',
59                 'mail_smtpuser',
60                 'mail_smtppass',
61                 'mail_smtpauth_req',
62                 'mail_smtpssl',
63         );
64
65         /**
66          * Columns
67          */
68         var $id;
69         var $name;
70         var $type; // user or system
71         var $user_id; // owner
72         var $mail_sendtype; // smtp
73         var $mail_smtptype;
74         var $mail_smtpserver;
75         var $mail_smtpport = 25;
76         var $mail_smtpuser;
77         var $mail_smtppass;
78         var $mail_smtpauth_req; // bool
79         var $mail_smtpssl; // bool
80         var $mail_smtpdisplay; // calculated value, not in DB
81         var $new_with_id = FALSE;
82         
83         /**
84          * Sole constructor
85          */
86         function OutboundEmail() {
87                 $this->db = DBManagerFactory::getInstance();
88         }
89
90         /**
91          * Retrieves the mailer for a user if they have overriden the username
92          * and password for the default system account.
93          *
94          * @param String $user_id
95          */
96         function getUsersMailerForSystemOverride($user_id)
97         {
98             $query = "SELECT id FROM outbound_email WHERE user_id = '{$user_id}' AND type = 'system-override' ORDER BY name";
99                 $rs = $this->db->query($query);
100                 $row = $this->db->fetchByAssoc($rs);
101                 if(!empty($row['id']))
102                 {
103                   $oe = new OutboundEmail();
104                   $oe->retrieve($row['id']);
105                   return $oe;   
106                 }
107                 else 
108                   return null;
109         }
110         
111         /**
112          * Duplicate the system account for a user, setting new parameters specific to the user.
113          *
114          * @param string $user_id
115          * @param string $user_name
116          * @param string $user_pass
117          */
118         function createUserSystemOverrideAccount($user_id,$user_name = "",$user_pass = "")
119         {
120             $ob = $this->getSystemMailerSettings();
121             $ob->id = create_guid();
122             $ob->new_with_id = TRUE;
123             $ob->user_id = $user_id;
124             $ob->type = 'system-override';
125             $ob->mail_smtpuser = $user_name;
126             $ob->mail_smtppass = $user_pass;
127             $ob->save();
128             
129             return $ob;
130         }
131         
132         /**
133          * Determines if a user needs to set their user name/password for their system
134          * override account.
135          *
136          * @param unknown_type $user_id
137          * @return unknown
138          */
139         function doesUserOverrideAccountRequireCredentials($user_id)
140         {
141             $userCredentialsReq = FALSE;
142             $sys = new OutboundEmail();
143             $ob = $sys->getSystemMailerSettings(); //Dirties '$this'
144             
145             //If auth for system account is disabled or user can use system outbound account return false.
146             if($ob->mail_smtpauth_req == 0 || $this->isAllowUserAccessToSystemDefaultOutbound() || $this->mail_sendtype == 'sendmail')
147                return $userCredentialsReq; 
148             
149             $userOverideAccount = $this->getUsersMailerForSystemOverride($user_id);
150             if( $userOverideAccount == null || empty($userOverideAccount->mail_smtpuser) || empty($userOverideAccount->mail_smtpuser) )
151                $userCredentialsReq = TRUE;
152                
153         return $userCredentialsReq;         
154            
155         }
156         
157         /**
158          * Retrieves name value pairs for opts lists
159          */
160         function getUserMailers($user) {
161                 global $app_strings;
162
163                 $q = "SELECT * FROM outbound_email WHERE user_id = '{$user->id}' AND type = 'user' ORDER BY name";
164                 $r = $this->db->query($q);
165
166                 $ret = array();
167
168                 $system = $this->getSystemMailerSettings();
169                 
170                 //Now add the system default or user override default to the response.
171                 if(!empty($system->id) ) 
172                 {
173                         if ($system->mail_sendtype == 'SMTP') 
174                         {
175                             $systemErrors = "";
176                 $userSystemOverride = $this->getUsersMailerForSystemOverride($user->id);
177                 
178                 //If the user is required to to provide a username and password but they have not done so yet,
179                     //create the account for them.
180                      $autoCreateUserSystemOverride = FALSE;
181                          if( $this->doesUserOverrideAccountRequireCredentials($user->id) )
182                          {
183                               $systemErrors = $app_strings['LBL_EMAIL_WARNING_MISSING_USER_CREDS'];
184                               $autoCreateUserSystemOverride = TRUE;
185                          }
186                  
187                 //Substitute in the users system override if its available.
188                 if($userSystemOverride != null)
189                            $system = $userSystemOverride;
190                         else if ($autoCreateUserSystemOverride)
191                        $system = $this->createUserSystemOverrideAccount($user->id,"","");
192                                             
193                             $isEditable = ($system->type == 'system') ? FALSE : TRUE; //User overrides can be edited.
194                             
195                 if( !empty($system->mail_smtpserver) )
196                                     $ret[] = array('id' =>$system->id, 'name' => "$system->name", 'mail_smtpserver' => $system->mail_smtpdisplay,
197                                                                    'is_editable' => $isEditable, 'type' => $system->type, 'errors' => $systemErrors);
198                         }
199                         else //Sendmail
200                         {
201                                 $ret[] = array('id' =>$system->id, 'name' => "{$system->name} - sendmail", 'mail_smtpserver' => 'sendmail',
202                                                                 'is_editable' => false, 'type' => $system->type, 'errors' => '');
203                         }
204                 }
205
206                 while($a = $this->db->fetchByAssoc($r)) 
207                 {
208                         $oe = array();
209                         if($a['mail_sendtype'] != 'SMTP')
210                                 continue;
211
212                         $oe['id'] =$a['id'];
213                         $oe['name'] = $a['name'];
214                         $oe['type'] = $a['type'];
215                         $oe['is_editable'] = true;
216                         $oe['errors'] = '';
217                         if ( !empty($a['mail_smtptype']) )
218                             $oe['mail_smtpserver'] = $this->_getOutboundServerDisplay($a['mail_smtptype'],$a['mail_smtpserver']);
219                         else
220                             $oe['mail_smtpserver'] = $a['mail_smtpserver'];
221                         
222                         $ret[] = $oe;
223                 }
224
225                 return $ret;
226         }
227
228         /**
229          * Retrieves a cascading mailer set
230          * @param object user
231          * @param string mailer_id
232          * @return object
233          */
234         function getUserMailerSettings(&$user, $mailer_id='', $ieId='') {
235                 $mailer = '';
236
237                 if(!empty($mailer_id)) {
238                         $mailer = "AND id = '{$mailer_id}'";
239                 } elseif(!empty($ieId)) {
240                         $q = "SELECT stored_options FROM inbound_email WHERE id = '{$ieId}'";
241                         $r = $this->db->query($q);
242                         $a = $this->db->fetchByAssoc($r);
243
244                         if(!empty($a)) {
245                                 $opts = unserialize(base64_decode($a['stored_options']));
246
247                                 if(isset($opts['outbound_email'])) {
248                                         $mailer = "AND id = '{$opts['outbound_email']}'";
249                                 }
250                         }
251                 }
252
253                 $q = "SELECT id FROM outbound_email WHERE user_id = '{$user->id}' {$mailer}";
254                 $r = $this->db->query($q);
255                 $a = $this->db->fetchByAssoc($r);
256
257                 if(empty($a)) {
258                         $ret = $this->getSystemMailerSettings();
259                 } else {
260                         $ret = $this->retrieve($a['id']);
261                 }
262                 return $ret;
263         }
264
265         /**
266          * Retrieve an array containing inbound emails ids for all inbound email accounts which have
267          * their outbound account set to this object.
268          *
269          * @param SugarBean $user
270          * @param string $outbound_id
271          * @return array
272          */
273         function getAssociatedInboundAccounts($user)
274         {
275             $query = "SELECT id,stored_options FROM inbound_email WHERE is_personal='1' AND deleted='0' AND created_by = '{$user->id}'";
276                 $rs = $this->db->query($query);
277                 
278         $results = array();
279         while($row = $this->db->fetchByAssoc($rs) )
280         {
281             $opts = unserialize(base64_decode($row['stored_options']));
282             if( isset($opts['outbound_email']) && $opts['outbound_email'] == $this->id) 
283             {
284                 $results[] = $row['id'];
285             } 
286                 }
287                 
288                 return $results;
289         }
290         /**
291          * Retrieves a cascading mailer set
292          * @param object user
293          * @param string mailer_id
294          * @return object
295          */
296         function getInboundMailerSettings(&$user, $mailer_id='', $ieId='') {
297                 $mailer = '';
298
299                 if(!empty($mailer_id)) {
300                         $mailer = "id = '{$mailer_id}'";
301                 } elseif(!empty($ieId)) {
302                         $q = "SELECT stored_options FROM inbound_email WHERE id = '{$ieId}'";
303                         $r = $this->db->query($q);
304                         $a = $this->db->fetchByAssoc($r);
305
306                         if(!empty($a)) {
307                                 $opts = unserialize(base64_decode($a['stored_options']));
308
309                                 if(isset($opts['outbound_email'])) {
310                                         $mailer = "id = '{$opts['outbound_email']}'";
311                                 } else {
312                                         $mailer = "id = '{$ieId}'";
313                                 }
314                         } else {
315                                 // its possible that its an system account
316                                 $mailer = "id = '{$ieId}'";
317                         }
318                 }
319
320                 if (empty($mailer)) {
321                         $mailer = "type = 'system'";
322                 } // if
323                 
324                 $q = "SELECT id FROM outbound_email WHERE {$mailer}";
325                 $r = $this->db->query($q);
326                 $a = $this->db->fetchByAssoc($r);
327
328                 if(empty($a)) {
329                         $ret = $this->getSystemMailerSettings();
330                 } else {
331                         $ret = $this->retrieve($a['id']);
332                 }
333                 return $ret;
334         }
335
336         /**
337          *  Determine if the user is alloweed to use the current system outbound connection.
338          */
339         function isAllowUserAccessToSystemDefaultOutbound()
340         {
341             $allowAccess = FALSE;
342             
343             // first check that a system default exists
344             $q = "SELECT id FROM outbound_email WHERE type = 'system'";
345                 $r = $this->db->query($q);
346                 $a = $this->db->fetchByAssoc($r);
347                 if (!empty($a)) {
348                     // next see if the admin preference for using the system outbound is set
349             $admin = new Administration();
350             $admin->retrieveSettings('',TRUE);
351             if (isset($admin->settings['notify_allow_default_outbound'])
352                 &&  $admin->settings['notify_allow_default_outbound'] == 2 )
353                 $allowAccess = TRUE;
354         }
355         
356         return $allowAccess;
357         }
358         
359         /**
360          * Retrieves the system's Outbound options
361          */
362         function getSystemMailerSettings() {
363                 $q = "SELECT id FROM outbound_email WHERE type = 'system'";
364                 $r = $this->db->query($q);
365                 $a = $this->db->fetchByAssoc($r);
366
367                 if(empty($a)) {
368                         $this->id = "";
369                         $this->name = 'system';
370                         $this->type = 'system';
371                         $this->user_id = '1';
372                         $this->mail_sendtype = 'SMTP';
373                         $this->mail_smtptype = 'other';
374                         $this->mail_smtpserver = '';
375                         $this->mail_smtpport = 25;
376                         $this->mail_smtpuser = '';
377                         $this->mail_smtppass = '';
378                         $this->mail_smtpauth_req = 1;
379                         $this->mail_smtpssl = 0;
380                         $this->mail_smtpdisplay = $this->_getOutboundServerDisplay($this->mail_smtptype,$this->mail_smtpserver);
381                         $this->save();
382                         $ret = $this;
383                 } else {
384                         $ret = $this->retrieve($a['id']);
385                 }
386
387                 return $ret;
388         }
389
390         /**
391          * Populates this instance
392          * @param string $id
393          * @return object $this
394          */
395         function retrieve($id) {
396                 require_once('include/utils/encryption_utils.php');
397                 $q = "SELECT * FROM outbound_email WHERE id = '{$id}'";
398                 $r = $this->db->query($q);
399                 $a = $this->db->fetchByAssoc($r);
400
401                 if(!empty($a)) {
402                         foreach($a as $k => $v) {
403                                 if ($k == 'mail_smtppass' && !empty($v)) {
404                                         $this->$k = blowfishDecode(blowfishGetKey('OutBoundEmail'), $v);
405                                 } else {
406                                         $this->$k = $v;
407                                 } // else
408                         }
409                         if ( !empty($a['mail_smtptype']) )
410                             $this->mail_smtpdisplay = $this->_getOutboundServerDisplay($a['mail_smtptype'],$a['mail_smtpserver']);
411                         else
412                             $this->mail_smtpdisplay = $a['mail_smtpserver'];
413                 }
414
415                 return $this;
416         }
417
418         function populateFromPost() {
419                 foreach($this->field_defs as $def) {
420                         if(isset($_POST[$def])) {
421                                 $this->$def = $_POST[$def];
422                         } else {
423                                 $this->$def = "";
424                         }
425                 }
426         }
427
428         /**
429          * saves an instance
430          */
431         function save() {
432                 require_once('include/utils/encryption_utils.php');
433                 if(empty($this->id) || $this->new_with_id) {
434                     
435                     if( empty($this->id) )
436                             $this->id = create_guid();
437
438                         $cols = '';
439                         $values = '';
440
441                         foreach($this->field_defs as $def) {
442                                 if(!empty($cols)) {
443                                         $cols .= ", ";
444                                 }
445                                 if(!empty($values)) {
446                                         $values .= ", ";
447                                 }
448                                 $cols .= $def;
449                                 if ($def == 'mail_smtppass' && !empty($this->mail_smtppass)) {
450                                         $this->mail_smtppass = blowfishEncode(blowfishGetKey('OutBoundEmail'), $this->mail_smtppass);
451                                 } // if
452                                 if($def == 'mail_smtpauth_req' || $def == 'mail_smtpssl'){
453                                         if(empty($this->$def)){
454                                                 $this->$def = 0;        
455                                         }
456                                         $values .= "{$this->$def}";
457                                 }else{
458                                         $values .= "'{$this->$def}'";
459                                 }
460                         }
461
462                         $q  = "INSERT INTO outbound_email ($cols) VALUES ({$values})";
463                 } else {
464                         $values = "";
465                         foreach($this->field_defs as $def) {
466                                 if(!empty($values)) {
467                                         $values .= ", ";
468                                 }
469
470                                 if ($def == 'mail_smtppass' && !empty($this->$def)) {
471                                         $this->$def = blowfishEncode(blowfishGetKey('OutBoundEmail'), $this->$def);
472                                 } // if
473                                 if($def == 'mail_smtpauth_req' || $def == 'mail_smtpssl'){
474                                         if(empty($this->$def)){
475                                                 $this->$def = 0;        
476                                         }
477                                         $values .= "{$def} = {$this->$def}";
478                                 }else{
479                                         $values .= "{$def} = '{$this->$def}'";
480                                 }
481                         }
482
483                         $q = "UPDATE outbound_email SET {$values} WHERE id = '{$this->id}'";
484                 }
485
486                 $this->db->query($q, true);
487                 return $this;
488         }
489
490         /**
491          * Saves system mailer.  Presumes all values are filled.
492          */
493         function saveSystem() {
494                 $q = "SELECT id FROM outbound_email WHERE type = 'system'";
495                 $r = $this->db->query($q);
496                 $a = $this->db->fetchByAssoc($r);
497
498                 if(empty($a)) {
499                         $a['id'] = ''; // trigger insert
500                 }
501
502                 $this->id = $a['id'];
503                 $this->name = 'system';
504                 $this->type = 'system';
505                 $this->user_id = '1';
506                 $this->save();
507                 
508                 $this->updateUserSystemOverrideAccounts();
509                 
510         }
511
512         /**
513          * Update the user system override accounts with the system information if anything has changed.
514          * 
515          */
516         function updateUserSystemOverrideAccounts()
517         {
518             $updateFields = array('mail_smtptype','mail_sendtype','mail_smtpserver', 'mail_smtpport','mail_smtpauth_req','mail_smtpssl');
519             
520             //Update the username ans password for the override accounts if alloweed access.
521             if( $this->isAllowUserAccessToSystemDefaultOutbound() )
522             {
523                 $updateFields[] = 'mail_smtpuser';
524                 $updateFields[] = 'mail_smtppass';
525             }
526             
527             $values = "";
528             foreach ($updateFields as $singleField)
529             {
530                 if(!empty($values)) 
531                                         $values .= ", ";
532                 if($singleField == 'mail_smtpauth_req' || $singleField == 'mail_smtpssl')
533                 {
534                                 if(empty($this->$singleField))
535                                     $this->$singleField = 0;    
536                                     
537                 $values .= "{$singleField} = {$this->$singleField} ";
538                 }       
539                 else
540                     $values .= "{$singleField} = '{$this->$singleField}' ";
541             }
542             
543             $query = "UPDATE outbound_email set {$values} WHERE type='system-override' ";
544             
545             $this->db->query($query);
546         }
547         /**
548          * Remove all of the user override accounts.  
549          *  
550          */
551         function removeUserOverrideAccounts()
552         {           
553             $query = "DELETE FROM outbound_email WHERE type = 'system-override'";
554                 return $this->db->query($query);
555         }
556         /**
557          * Deletes an instance
558          */
559         function delete() {
560                 if(empty($this->id)) {
561                         return false;
562                 }
563
564                 $q = "DELETE FROM outbound_email WHERE id = '{$this->id}'";
565                 return $this->db->query($q);
566         }
567         
568         private function _getOutboundServerDisplay(
569             $smtptype,
570             $smtpserver
571             )
572         {
573             global $app_strings;
574             
575             switch ($smtptype) {
576         case "yahoomail":
577             return $app_strings['LBL_SMTPTYPE_YAHOO']; break;
578         case "gmail":
579             return $app_strings['LBL_SMTPTYPE_GMAIL']; break;
580         case "exchange":
581             return $smtpserver . ' - ' . $app_strings['LBL_SMTPTYPE_EXCHANGE']; break;
582         default:
583             return $smtpserver; break;
584         }
585         }
586 }