]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/OutboundEmail/OutboundEmail.php
Release 6.1.5
[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->$def)) {
450                                         $this->$def = blowfishEncode(blowfishGetKey('OutBoundEmail'), $this->$def);
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 ($def == 'mail_smtppass') {
467                                 if(!empty($this->mail_smtppass)) {
468                                             $this->mail_smtppass = blowfishEncode(blowfishGetKey('OutBoundEmail'), $this->mail_smtppass);
469                                     } else {
470                                         // ignore empty password unless username is empty too
471                                         if(!empty($this->mail_smtpuser)) {
472                                             continue;
473                                         }
474                                     }
475                                 }
476                             if(!empty($values)) {
477                                         $values .= ", ";
478                                 }
479
480                                 if($def == 'mail_smtpauth_req' || $def == 'mail_smtpssl'){
481                                         if(empty($this->$def)){
482                                                 $this->$def = 0;
483                                         }
484                                         $values .= "{$def} = {$this->$def}";
485                                 }else{
486                                         $values .= "{$def} = '{$this->$def}'";
487                                 }
488                         }
489
490                         $q = "UPDATE outbound_email SET {$values} WHERE id = '{$this->id}'";
491                 }
492
493                 $this->db->query($q, true);
494                 return $this;
495         }
496
497         /**
498          * Saves system mailer.  Presumes all values are filled.
499          */
500         function saveSystem() {
501                 $q = "SELECT id FROM outbound_email WHERE type = 'system'";
502                 $r = $this->db->query($q);
503                 $a = $this->db->fetchByAssoc($r);
504
505                 if(empty($a)) {
506                         $a['id'] = ''; // trigger insert
507                 }
508
509                 $this->id = $a['id'];
510                 $this->name = 'system';
511                 $this->type = 'system';
512                 $this->user_id = '1';
513                 $this->save();
514
515                 $this->updateUserSystemOverrideAccounts();
516
517         }
518
519         /**
520          * Update the user system override accounts with the system information if anything has changed.
521          *
522          */
523         function updateUserSystemOverrideAccounts()
524         {
525             $updateFields = array('mail_smtptype','mail_sendtype','mail_smtpserver', 'mail_smtpport','mail_smtpauth_req','mail_smtpssl');
526
527             //Update the username ans password for the override accounts if alloweed access.
528             if( $this->isAllowUserAccessToSystemDefaultOutbound() )
529             {
530                 $updateFields[] = 'mail_smtpuser';
531                 $updateFields[] = 'mail_smtppass';
532             }
533
534             $values = "";
535             foreach ($updateFields as $singleField)
536             {
537                 if(!empty($values))
538                                         $values .= ", ";
539                 if($singleField == 'mail_smtpauth_req' || $singleField == 'mail_smtpssl')
540                 {
541                                 if(empty($this->$singleField))
542                                     $this->$singleField = 0;
543
544                 $values .= "{$singleField} = {$this->$singleField} ";
545                 }
546                 else
547                     $values .= "{$singleField} = '{$this->$singleField}' ";
548             }
549
550             $query = "UPDATE outbound_email set {$values} WHERE type='system-override' ";
551
552             $this->db->query($query);
553         }
554         /**
555          * Remove all of the user override accounts.
556          *
557          */
558         function removeUserOverrideAccounts()
559         {
560             $query = "DELETE FROM outbound_email WHERE type = 'system-override'";
561                 return $this->db->query($query);
562         }
563         /**
564          * Deletes an instance
565          */
566         function delete() {
567                 if(empty($this->id)) {
568                         return false;
569                 }
570
571                 $q = "DELETE FROM outbound_email WHERE id = '{$this->id}'";
572                 return $this->db->query($q);
573         }
574
575         private function _getOutboundServerDisplay(
576             $smtptype,
577             $smtpserver
578             )
579         {
580             global $app_strings;
581
582             switch ($smtptype) {
583         case "yahoomail":
584             return $app_strings['LBL_SMTPTYPE_YAHOO']; break;
585         case "gmail":
586             return $app_strings['LBL_SMTPTYPE_GMAIL']; break;
587         case "exchange":
588             return $smtpserver . ' - ' . $app_strings['LBL_SMTPTYPE_EXCHANGE']; break;
589         default:
590             return $smtpserver; break;
591         }
592         }
593
594         /**
595          * Get mailer for current user by name
596          * @param User $user
597          * @param string $name
598          * @return OutboundEmail|false
599          */
600         public function getMailerByName($user, $name)
601         {
602             if($name == "system" && !$this->isAllowUserAccessToSystemDefaultOutbound()) {
603                 $oe = $this->getUsersMailerForSystemOverride($user->id);
604                 if(!empty($oe) && !empty($oe->id)) {
605                     return $oe;
606                 }
607             }
608             $res = $this->db->query("SELECT id FROM outbound_email WHERE user_id = '{$user->id}' AND name='".$this->db->quote($name)."'");
609                 $a = $this->db->fetchByAssoc($res);
610         if(!isset($a['id'])) {
611             return false;
612         }
613             return $this->retrieve($a['id']);
614         }
615 }