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-2013 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
39 * Outbuound email management
47 var $field_defs = array(
67 var $type; // user or system
68 var $user_id; // owner
69 var $mail_sendtype; // smtp
72 var $mail_smtpport = 25;
75 var $mail_smtpauth_req; // bool
76 var $mail_smtpssl; // bool
77 var $mail_smtpdisplay; // calculated value, not in DB
78 var $new_with_id = FALSE;
83 function OutboundEmail() {
84 $this->db = DBManagerFactory::getInstance();
88 * Retrieves the mailer for a user if they have overriden the username
89 * and password for the default system account.
91 * @param String $user_id
93 function getUsersMailerForSystemOverride($user_id)
95 $query = "SELECT id FROM outbound_email WHERE user_id = '{$user_id}' AND type = 'system-override' ORDER BY name";
96 $rs = $this->db->query($query);
97 $row = $this->db->fetchByAssoc($rs);
98 if(!empty($row['id']))
100 $oe = new OutboundEmail();
101 $oe->retrieve($row['id']);
109 * Duplicate the system account for a user, setting new parameters specific to the user.
111 * @param string $user_id
112 * @param string $user_name
113 * @param string $user_pass
115 function createUserSystemOverrideAccount($user_id,$user_name = "",$user_pass = "")
117 $ob = $this->getSystemMailerSettings();
118 $ob->id = create_guid();
119 $ob->new_with_id = TRUE;
120 $ob->user_id = $user_id;
121 $ob->type = 'system-override';
122 $ob->mail_smtpuser = $user_name;
123 $ob->mail_smtppass = $user_pass;
130 * Determines if a user needs to set their user name/password for their system
133 * @param unknown_type $user_id
136 function doesUserOverrideAccountRequireCredentials($user_id)
138 $userCredentialsReq = FALSE;
139 $sys = new OutboundEmail();
140 $ob = $sys->getSystemMailerSettings(); //Dirties '$this'
142 //If auth for system account is disabled or user can use system outbound account return false.
143 if($ob->mail_smtpauth_req == 0 || $this->isAllowUserAccessToSystemDefaultOutbound() || $this->mail_sendtype == 'sendmail')
144 return $userCredentialsReq;
146 $userOverideAccount = $this->getUsersMailerForSystemOverride($user_id);
147 if( $userOverideAccount == null || empty($userOverideAccount->mail_smtpuser) || empty($userOverideAccount->mail_smtpuser) )
148 $userCredentialsReq = TRUE;
150 return $userCredentialsReq;
155 * Retrieves name value pairs for opts lists
157 function getUserMailers($user) {
160 $q = "SELECT * FROM outbound_email WHERE user_id = '{$user->id}' AND type = 'user' ORDER BY name";
161 $r = $this->db->query($q);
165 $system = $this->getSystemMailerSettings();
167 //Now add the system default or user override default to the response.
168 if(!empty($system->id) )
170 if ($system->mail_sendtype == 'SMTP')
173 $userSystemOverride = $this->getUsersMailerForSystemOverride($user->id);
175 //If the user is required to to provide a username and password but they have not done so yet,
176 //create the account for them.
177 $autoCreateUserSystemOverride = FALSE;
178 if( $this->doesUserOverrideAccountRequireCredentials($user->id) )
180 $systemErrors = $app_strings['LBL_EMAIL_WARNING_MISSING_USER_CREDS'];
181 $autoCreateUserSystemOverride = TRUE;
184 //Substitute in the users system override if its available.
185 if($userSystemOverride != null)
186 $system = $userSystemOverride;
187 else if ($autoCreateUserSystemOverride)
188 $system = $this->createUserSystemOverrideAccount($user->id,"","");
190 $isEditable = ($system->type == 'system') ? FALSE : TRUE; //User overrides can be edited.
192 if( !empty($system->mail_smtpserver) )
193 $ret[] = array('id' =>$system->id, 'name' => "$system->name", 'mail_smtpserver' => $system->mail_smtpdisplay,
194 'is_editable' => $isEditable, 'type' => $system->type, 'errors' => $systemErrors);
198 $ret[] = array('id' =>$system->id, 'name' => "{$system->name} - sendmail", 'mail_smtpserver' => 'sendmail',
199 'is_editable' => false, 'type' => $system->type, 'errors' => '');
203 while($a = $this->db->fetchByAssoc($r))
206 if($a['mail_sendtype'] != 'SMTP')
210 $oe['name'] = $a['name'];
211 $oe['type'] = $a['type'];
212 $oe['is_editable'] = true;
214 if ( !empty($a['mail_smtptype']) )
215 $oe['mail_smtpserver'] = $this->_getOutboundServerDisplay($a['mail_smtptype'],$a['mail_smtpserver']);
217 $oe['mail_smtpserver'] = $a['mail_smtpserver'];
226 * Retrieves a cascading mailer set
228 * @param string mailer_id
231 function getUserMailerSettings(&$user, $mailer_id='', $ieId='') {
234 if(!empty($mailer_id)) {
235 $mailer = "AND id = '{$mailer_id}'";
236 } elseif(!empty($ieId)) {
237 $q = "SELECT stored_options FROM inbound_email WHERE id = '{$ieId}'";
238 $r = $this->db->query($q);
239 $a = $this->db->fetchByAssoc($r);
242 $opts = unserialize(base64_decode($a['stored_options']));
244 if(isset($opts['outbound_email'])) {
245 $mailer = "AND id = '{$opts['outbound_email']}'";
250 $q = "SELECT id FROM outbound_email WHERE user_id = '{$user->id}' {$mailer}";
251 $r = $this->db->query($q);
252 $a = $this->db->fetchByAssoc($r);
255 $ret = $this->getSystemMailerSettings();
257 $ret = $this->retrieve($a['id']);
263 * Retrieve an array containing inbound emails ids for all inbound email accounts which have
264 * their outbound account set to this object.
266 * @param SugarBean $user
267 * @param string $outbound_id
270 function getAssociatedInboundAccounts($user)
272 $query = "SELECT id,stored_options FROM inbound_email WHERE is_personal='1' AND deleted='0' AND created_by = '{$user->id}'";
273 $rs = $this->db->query($query);
276 while($row = $this->db->fetchByAssoc($rs) )
278 $opts = unserialize(base64_decode($row['stored_options']));
279 if( isset($opts['outbound_email']) && $opts['outbound_email'] == $this->id)
281 $results[] = $row['id'];
288 * Retrieves a cascading mailer set
290 * @param string mailer_id
293 function getInboundMailerSettings($user, $mailer_id='', $ieId='') {
296 if(!empty($mailer_id)) {
297 $mailer = "id = '{$mailer_id}'";
298 } elseif(!empty($ieId)) {
299 $q = "SELECT stored_options FROM inbound_email WHERE id = '{$ieId}'";
300 $r = $this->db->query($q);
301 $a = $this->db->fetchByAssoc($r);
304 $opts = unserialize(base64_decode($a['stored_options']));
306 if(isset($opts['outbound_email'])) {
307 $mailer = "id = '{$opts['outbound_email']}'";
309 $mailer = "id = '{$ieId}'";
312 // its possible that its an system account
313 $mailer = "id = '{$ieId}'";
317 if (empty($mailer)) {
318 $mailer = "type = 'system'";
321 $q = "SELECT id FROM outbound_email WHERE {$mailer}";
322 $r = $this->db->query($q);
323 $a = $this->db->fetchByAssoc($r);
326 $ret = $this->getSystemMailerSettings();
328 $ret = $this->retrieve($a['id']);
334 * Determine if the user is allowed to use the current system outbound connection.
336 function isAllowUserAccessToSystemDefaultOutbound()
338 $allowAccess = FALSE;
340 // first check that a system default exists
341 $q = "SELECT id FROM outbound_email WHERE type = 'system'";
342 $r = $this->db->query($q);
343 $a = $this->db->fetchByAssoc($r);
345 // next see if the admin preference for using the system outbound is set
346 $admin = new Administration();
347 $admin->retrieveSettings('',TRUE);
348 if (isset($admin->settings['notify_allow_default_outbound'])
349 && $admin->settings['notify_allow_default_outbound'] == 2 )
357 * Retrieves the system's Outbound options
359 function getSystemMailerSettings() {
360 $q = "SELECT id FROM outbound_email WHERE type = 'system'";
361 $r = $this->db->query($q);
362 $a = $this->db->fetchByAssoc($r);
366 $this->name = 'system';
367 $this->type = 'system';
368 $this->user_id = '1';
369 $this->mail_sendtype = 'SMTP';
370 $this->mail_smtptype = 'other';
371 $this->mail_smtpserver = '';
372 $this->mail_smtpport = 25;
373 $this->mail_smtpuser = '';
374 $this->mail_smtppass = '';
375 $this->mail_smtpauth_req = 1;
376 $this->mail_smtpssl = 0;
377 $this->mail_smtpdisplay = $this->_getOutboundServerDisplay($this->mail_smtptype,$this->mail_smtpserver);
381 $ret = $this->retrieve($a['id']);
388 * Populates this instance
390 * @return object $this
392 function retrieve($id) {
393 require_once('include/utils/encryption_utils.php');
394 $q = "SELECT * FROM outbound_email WHERE id = '{$id}'";
395 $r = $this->db->query($q);
396 $a = $this->db->fetchByAssoc($r);
399 foreach($a as $k => $v) {
400 if ($k == 'mail_smtppass' && !empty($v)) {
401 $this->$k = blowfishDecode(blowfishGetKey('OutBoundEmail'), $v);
406 if ( !empty($a['mail_smtptype']) )
407 $this->mail_smtpdisplay = $this->_getOutboundServerDisplay($a['mail_smtptype'],$a['mail_smtpserver']);
409 $this->mail_smtpdisplay = $a['mail_smtpserver'];
415 function populateFromPost() {
416 foreach($this->field_defs as $def) {
417 if(isset($_POST[$def])) {
418 $this->$def = $_POST[$def];
419 } else if ($def != 'mail_smtppass') {
426 * Generate values for saving into outbound_emails table
430 protected function getValues(&$keys)
433 $validKeys = array();
435 foreach($keys as $def) {
436 if ($def == 'mail_smtppass' && !empty($this->$def)) {
437 $this->$def = blowfishEncode(blowfishGetKey('OutBoundEmail'), $this->$def);
439 if($def == 'mail_smtpauth_req' || $def == 'mail_smtpssl' || $def == 'mail_smtpport'){
440 if(empty($this->$def)){
443 $values[] = intval($this->$def);
445 } else if (isset($this->$def)) {
446 $values[] = $this->db->quoted($this->$def);
458 require_once('include/utils/encryption_utils.php');
459 if( empty($this->id) ) {
460 $this->id = create_guid();
461 $this->new_with_id = true;
464 $cols = $this->field_defs;
465 $values = $this->getValues($cols);
467 if($this->new_with_id) {
468 $q = sprintf("INSERT INTO outbound_email (%s) VALUES (%s)", implode($cols, ","), implode($values, ","));
470 $updvalues = array();
471 foreach($values as $k => $val) {
472 $updvalues[] = "{$cols[$k]} = $val";
474 $q = "UPDATE outbound_email SET ".implode(', ', $updvalues)." WHERE id = ".$this->db->quoted($this->id);
477 $this->db->query($q, true);
482 * Saves system mailer. Presumes all values are filled.
484 function saveSystem() {
485 $q = "SELECT id FROM outbound_email WHERE type = 'system'";
486 $r = $this->db->query($q);
487 $a = $this->db->fetchByAssoc($r);
490 $a['id'] = ''; // trigger insert
493 $this->id = $a['id'];
494 $this->name = 'system';
495 $this->type = 'system';
496 $this->user_id = '1';
499 $this->updateUserSystemOverrideAccounts();
504 * Update the user system override accounts with the system information if anything has changed.
507 function updateUserSystemOverrideAccounts()
509 require_once('include/utils/encryption_utils.php');
510 $updateFields = array('mail_smtptype','mail_sendtype','mail_smtpserver', 'mail_smtpport','mail_smtpauth_req','mail_smtpssl');
512 //Update the username ans password for the override accounts if alloweed access.
513 if( $this->isAllowUserAccessToSystemDefaultOutbound() )
515 $updateFields[] = 'mail_smtpuser';
516 $updateFields[] = 'mail_smtppass';
518 $values = $this->getValues($updateFields);
519 $updvalues = array();
520 foreach($values as $k => $val) {
521 $updvalues[] = "{$updateFields[$k]} = $val";
523 $query = "UPDATE outbound_email set ".implode(', ', $updvalues)." WHERE type='system-override' ";
525 $this->db->query($query);
528 * Remove all of the user override accounts.
531 function removeUserOverrideAccounts()
533 $query = "DELETE FROM outbound_email WHERE type = 'system-override'";
534 return $this->db->query($query);
537 * Deletes an instance
540 if(empty($this->id)) {
544 $q = "DELETE FROM outbound_email WHERE id = ".$this->db->quoted($this->id);
545 return $this->db->query($q);
548 private function _getOutboundServerDisplay(
557 return $app_strings['LBL_SMTPTYPE_YAHOO']; break;
559 return $app_strings['LBL_SMTPTYPE_GMAIL']; break;
561 return $smtpserver . ' - ' . $app_strings['LBL_SMTPTYPE_EXCHANGE']; break;
563 return $smtpserver; break;
568 * Get mailer for current user by name
570 * @param string $name
571 * @return OutboundEmail|false
573 public function getMailerByName($user, $name)
575 if($name == "system" && !$this->isAllowUserAccessToSystemDefaultOutbound()) {
576 $oe = $this->getUsersMailerForSystemOverride($user->id);
577 if(!empty($oe) && !empty($oe->id)) {
581 return $this->getSystemMailerSettings();
584 $res = $this->db->query("SELECT id FROM outbound_email WHERE user_id = '{$user->id}' AND name='".$this->db->quote($name)."'");
585 $a = $this->db->fetchByAssoc($res);
586 if(!isset($a['id'])) {
589 return $this->retrieve($a['id']);