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.
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 ********************************************************************************/
38 /*********************************************************************************
41 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42 * Reserved. Contributor(s): ______________________________________..
43 *********************************************************************************/
46 require_once("include/JSON.php");
49 class SugarEmailAddress extends SugarBean {
50 var $table_name = 'email_addresses';
51 var $module_name = "EmailAddresses";
52 var $module_dir = 'EmailAddresses';
53 var $object_name = 'EmailAddress';
55 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
56 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
57 var $regex = "/^(?:['\.\-\+&#!\$\*=\?\^_`\{\}~\/\w]+)@(?:(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|\w+(?:[\.-]*\w+)*(?:\.[\w-]{2,})+)\$/";
58 var $disable_custom_fields = true;
61 var $addresses = array(); // array of emails
63 private $stateBeforeWorkflow;
70 function SugarEmailAddress() {
72 $this->index = self::$count;
77 * Legacy email address handling. This is to allow support for SOAP or customizations
79 * @param string $module
81 function handleLegacySave($bean, $prefix = "") {
82 if(!isset($_REQUEST) || !isset($_REQUEST['useEmailWidget'])) {
83 if (empty($this->addresses) || !isset($_REQUEST['massupdate'])) {
84 $this->addresses = array();
85 $optOut = (isset($bean->email_opt_out) && $bean->email_opt_out == "1") ? true : false;
86 $invalid = (isset($bean->invalid_email) && $bean->invalid_email == "1") ? true : false;
89 for($i = 1; $i <= 10; $i++){
91 if(isset($bean->$email) && !empty($bean->$email)){
92 $opt_out_field = $email.'_opt_out';
93 $invalid_field = $email.'_invalid';
94 $field_optOut = (isset($bean->$opt_out_field)) ? $bean->$opt_out_field : $optOut;
95 $field_invalid = (isset($bean->$invalid_field)) ? $bean->$invalid_field : $invalid;
96 $this->addAddress($bean->$email, $isPrimary, false, $field_invalid, $field_optOut);
102 $this->populateAddresses($bean->id, $bean->module_dir, array(),'');
103 if(isset($_REQUEST) && isset($_REQUEST['useEmailWidget'])) {
104 $this->populateLegacyFields($bean);
109 * Fills standard email1 legacy fields
111 * @param string module
114 function handleLegacyRetrieve(&$bean) {
115 $module_dir = $this->getCorrectedModule($bean->module_dir);
116 $this->addresses = $this->getAddressesByGUID($bean->id, $module_dir);
117 $this->populateLegacyFields($bean);
118 if (isset($bean->email1) && !isset($bean->fetched_row['email1'])) {
119 $bean->fetched_row['email1'] = $bean->email1;
125 function populateLegacyFields(&$bean){
126 $primary_found = false;
127 $alternate_found = false;
128 $alternate2_found = false;
129 foreach($this->addresses as $k=>$address) {
130 if ($primary_found && $alternate_found)
132 if ($address['primary_address'] == 1 && !$primary_found) {
134 $primary_found = true;
135 } elseif (!$alternate_found) {
136 $alternate_index = $k;
137 $alternate_found = true;
138 } elseif (!$alternate2_found){
139 $alternate2_index = $k;
140 $alternate2_found = true;
144 if ($primary_found) {
145 $bean->email1 = $this->addresses[$primary_index]['email_address'];
146 $bean->email_opt_out = $this->addresses[$primary_index]['opt_out'];
147 $bean->invalid_email = $this->addresses[$primary_index]['invalid_email'];
148 if ($alternate_found) {
149 $bean->email2 = $this->addresses[$alternate_index]['email_address'];
151 } elseif ($alternate_found) {
152 // Use the first found alternate as email1.
153 $bean->email1 = $this->addresses[$alternate_index]['email_address'];
154 $bean->email_opt_out = $this->addresses[$alternate_index]['opt_out'];
155 $bean->invalid_email = $this->addresses[$alternate_index]['invalid_email'];
156 if ($alternate2_found) {
157 $bean->email2 = $this->addresses[$alternate2_index]['email_address'];
163 * Saves email addresses for a parent bean
164 * @param string $id Parent bean ID
165 * @param string $module Parent bean's module
166 * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
167 * @param string $primary GUID of primary address
168 * @param string $replyTo GUID of reply-to address
169 * @param string $invalid GUID of invalid address
171 function save($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='', $in_workflow=false) {
172 if(empty($this->addresses) || $in_workflow){
173 $this->populateAddresses($id, $module, $new_addrs,$primary);
176 //find all email addresses..
177 $current_links=array();
178 // Need to correct this to handle the Employee/User split
179 $module = $this->getCorrectedModule($module);
180 $q2="select * from email_addr_bean_rel eabr WHERE eabr.bean_id = '".$this->db->quote($id)."' AND eabr.bean_module = '".$this->db->quote($module)."' and eabr.deleted=0";
181 $r2 = $this->db->query($q2);
182 while(($row2=$this->db->fetchByAssoc($r2)) != null ) {
183 $current_links[$row2['email_address_id']]=$row2;
186 $isConversion = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? true : false;
188 if (!empty($this->addresses)) {
189 // insert new relationships and create email address record, if they don't exist
190 foreach($this->addresses as $address) {
191 if(!empty($address['email_address'])) {
192 $guid = create_guid();
193 $emailId = isset($address['email_address_id'])
194 && isset($current_links[$address['email_address_id']])
195 ? $address['email_address_id'] : null;
196 $emailId = $this->AddUpdateEmailAddress($address['email_address'],
197 $address['invalid_email'],
199 $emailId);// this will save the email address if not found
201 //verify linkage and flags.
203 if (isset($current_links[$emailId])) {
204 if (!$isConversion) { // do not update anything if this is for lead conversion
205 if ($address['primary_address'] != $current_links[$emailId]['primary_address'] or $address['reply_to_address'] != $current_links[$emailId]['reply_to_address'] ) {
206 $upd_eabr="UPDATE email_addr_bean_rel SET primary_address='".$this->db->quote($address['primary_address'])."', reply_to_address='".$this->db->quote($address['reply_to_address'])."' WHERE id='".$this->db->quote($current_links[$emailId]['id'])."'";
209 unset($current_links[$emailId]);
212 $primary = $address['primary_address'];
213 if (!empty($current_links) && $isConversion) {
214 foreach ($current_links as $eabr) {
215 if ($eabr['primary_address'] == 1) {
216 // for lead conversion, if there is already a primary email, do not insert another primary email
222 $now = $this->db->now();
223 $upd_eabr = "INSERT INTO email_addr_bean_rel (id, email_address_id,bean_id, bean_module,primary_address,reply_to_address,date_created,date_modified,deleted) VALUES('".$this->db->quote($guid)."', '".$this->db->quote($emailId)."', '".$this->db->quote($id)."', '".$this->db->quote($module)."', ".intval($primary).", ".intval($address['reply_to_address']).", $now, $now, 0)";
226 if (!empty($upd_eabr)) {
227 $r2 = $this->db->query($upd_eabr);
233 //delete link to dropped email address.
234 // for lead conversion, do not delete email addresses
235 if (!empty($current_links) && !$isConversion) {
238 foreach ($current_links as $eabr) {
240 $delete.=empty($delete) ? "'".$this->db->quote($eabr['id']) . "' " : ",'" . $this->db->quote($eabr['id']) . "'";
243 $eabr_unlink="update email_addr_bean_rel set deleted=1 where id in ({$delete})";
244 $this->db->query($eabr_unlink);
246 $this->stateBeforeWorkflow = null;
251 * returns the number of email addresses found for a specifed bean
253 * @param string $email Address to match
254 * @param object $bean Bean to query against
255 * @param string $addresstype Optional, pass a 1 to query against the primary address, 0 for the other addresses
256 * @return int Count of records found
258 function getCountEmailAddressByBean(
264 $emailCaps = strtoupper(trim($email));
265 if(empty($emailCaps))
269 FROM email_addr_bean_rel eabl JOIN email_addresses ea
270 ON (ea.id = eabl.email_address_id)
271 JOIN {$bean->table_name} bean
272 ON (eabl.bean_id = bean.id)
273 WHERE ea.email_address_caps = '".$this->db->quote($emailCaps)."'
274 and eabl.bean_module = '".$this->db->quote($bean->module_dir)."'
275 and eabl.primary_address = '".$this->db->quote($addresstype)."'
276 and eabl.deleted=0 ";
278 $r = $this->db->query($q);
280 // do it this way to make the count accurate in oracle
282 while ($this->db->fetchByAssoc($r)) ++$i;
288 * This function returns a contact or user ID if a matching email is found
289 * @param $email the email address to match
290 * @param $table which table to query
292 function getRelatedId($email, $module) {
293 $email = $this->db->quote(trim(strtoupper($email)));
294 $module = $this->db->quote(ucfirst($module));
296 $q = "SELECT bean_id FROM email_addr_bean_rel eabr
297 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
298 WHERE bean_module = '$module' AND ea.email_address_caps = '$email' AND eabr.deleted=0";
300 $r = $this->db->query($q, true);
303 while($a = $this->db->fetchByAssoc($r)) {
304 $retArr[] = $a['bean_id'];
306 if(count($retArr) > 0) {
314 * returns a collection of beans matching the email address
315 * @param string $email Address to match
318 function getBeansByEmailAddress($email) {
324 $email = trim($email);
330 $emailCaps = "'".$this->db->quote(strtoupper($email))."'";
331 $q = "SELECT * FROM email_addr_bean_rel eabl JOIN email_addresses ea ON (ea.id = eabl.email_address_id)
332 WHERE ea.email_address_caps = $emailCaps and eabl.deleted=0 ";
333 $r = $this->db->query($q);
335 while($a = $this->db->fetchByAssoc($r)) {
336 if(isset($beanList[$a['bean_module']]) && !empty($beanList[$a['bean_module']])) {
337 $className = $beanList[$a['bean_module']];
339 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
340 if(!class_exists($className)) {
341 require_once($beanFiles[$className]);
344 $bean = new $className();
345 $bean->retrieve($a['bean_id']);
349 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class file for [ {$className} ]");
352 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class [ {$a['bean_module']} ]");
360 * Saves email addresses for a parent bean
361 * @param string $id Parent bean ID
362 * @param string $module Parent bean's module
363 * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
364 * @param string $primary GUID of primary address
365 * @param string $replyTo GUID of reply-to address
366 * @param string $invalid GUID of invalid address
368 function populateAddresses($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='') {
369 $module = $this->getCorrectedModule($module);
370 //One last check for the ConvertLead action in which case we need to change $module to 'Leads'
371 $module = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? 'Leads' : $module;
373 $post_from_email_address_widget = (isset($_REQUEST) && isset($_REQUEST['emailAddressWidget'])) ? true : false;
374 $primaryValue = $primary;
376 $hasEmailValue = false;
377 $email_ids = array();
379 if (isset($_REQUEST) && isset($_REQUEST[$module .'_email_widget_id'])) {
381 $fromRequest = false;
382 // determine which array to process
383 foreach($_REQUEST as $k => $v) {
384 if(strpos($k, 'emailAddress') !== false) {
388 $widget_id = $_REQUEST[$module .'_email_widget_id'];
391 //Iterate over the widgets for this module, in case there are multiple email widgets for this module
392 while(isset($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount]))
394 if (empty($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount])) {
399 $hasEmailValue = true;
401 $eId = $module . $widget_id;
402 if(isset($_REQUEST[$eId . 'emailAddressPrimaryFlag'])) {
403 $primaryValue = $_REQUEST[$eId . 'emailAddressPrimaryFlag'];
404 } else if(isset($_REQUEST[$module . 'emailAddressPrimaryFlag'])) {
405 $primaryValue = $_REQUEST[$module . 'emailAddressPrimaryFlag'];
408 $optOutValues = array();
409 if(isset($_REQUEST[$eId .'emailAddressOptOutFlag'])) {
410 $optOutValues = $_REQUEST[$eId .'emailAddressOptOutFlag'];
411 } else if(isset($_REQUEST[$module . 'emailAddressOptOutFlag'])) {
412 $optOutValues = $_REQUEST[$module . 'emailAddressOptOutFlag'];
415 $invalidValues = array();
416 if(isset($_REQUEST[$eId .'emailAddressInvalidFlag'])) {
417 $invalidValues = $_REQUEST[$eId .'emailAddressInvalidFlag'];
418 } else if(isset($_REQUEST[$module . 'emailAddressInvalidFlag'])) {
419 $invalidValues = $_REQUEST[$module . 'emailAddressInvalidFlag'];
422 $deleteValues = array();
423 if(isset($_REQUEST[$eId .'emailAddressDeleteFlag'])) {
424 $deleteValues = $_REQUEST[$eId .'emailAddressDeleteFlag'];
425 } else if(isset($_REQUEST[$module . 'emailAddressDeleteFlag'])) {
426 $deleteValues = $_REQUEST[$module . 'emailAddressDeleteFlag'];
429 // prep from form save
430 $primaryField = $primary;
434 if($fromRequest && empty($primary) && isset($primaryValue)) {
435 $primaryField = $primaryValue;
438 if($fromRequest && empty($replyTo)) {
439 if(isset($_REQUEST[$eId .'emailAddressReplyToFlag'])) {
440 $replyToField = $_REQUEST[$eId .'emailAddressReplyToFlag'];
441 } else if(isset($_REQUEST[$module . 'emailAddressReplyToFlag'])) {
442 $replyToField = $_REQUEST[$module . 'emailAddressReplyToFlag'];
445 if($fromRequest && empty($new_addrs)) {
446 foreach($_REQUEST as $k => $v) {
447 if(preg_match('/'.$eId.'emailAddress[0-9]+$/i', $k) && !empty($v)) {
452 if($fromRequest && empty($email_ids)) {
453 foreach($_REQUEST as $k => $v) {
454 if(preg_match('/'.$eId.'emailAddressId[0-9]+$/i', $k) && !empty($v)) {
455 $key = str_replace('emailAddressId', 'emailAddress', $k);
456 $email_ids[$key] = $v;
461 if($fromRequest && empty($new_addrs)) {
462 foreach($_REQUEST as $k => $v) {
463 if(preg_match('/'.$eId.'emailAddressVerifiedValue[0-9]+$/i', $k) && !empty($v)) {
464 $validateFlag = str_replace("Value", "Flag", $k);
465 if (isset($_REQUEST[$validateFlag]) && $_REQUEST[$validateFlag] == "true")
471 //empty the addresses array if the post happened from email address widget.
472 if($post_from_email_address_widget) {
473 $this->addresses=array(); //this gets populated during retrieve of the contact bean.
475 $optOutValues = array();
476 $invalidValues = array();
477 foreach($new_addrs as $k=>$email) {
478 preg_match('/emailAddress([0-9])+$/', $k, $matches);
479 $count = $matches[1];
480 $result = $this->db->query("SELECT opt_out, invalid_email from email_addresses where email_address_caps = '" . $this->db->quote(strtoupper($email)) . "'");
481 if(!empty($result)) {
482 $row=$this->db->fetchByAssoc($result);
483 if(!empty($row['opt_out'])) {
484 $optOutValues[$k] = "emailAddress$count";
486 if(!empty($row['invalid_email'])) {
487 $invalidValues[$k] = "emailAddress$count";
492 // Re-populate the addresses class variable if we have new address(es).
493 if (!empty($new_addrs)) {
494 foreach($new_addrs as $k => $reqVar) {
495 //$key = preg_match("/^$eId/s", $k) ? substr($k, strlen($eId)) : $k;
496 $reqVar = trim($reqVar);
497 if(strpos($k, 'emailAddress') !== false) {
498 if(!empty($reqVar) && !in_array($k, $deleteValues)) {
499 $email_id = (array_key_exists($k, $email_ids)) ? $email_ids[$k] : null;
500 $primary = ($k == $primaryValue) ? true : false;
501 $replyTo = ($k == $replyToField) ? true : false;
502 $invalid = (in_array($k, $invalidValues)) ? true : false;
503 $optOut = (in_array($k, $optOutValues)) ? true : false;
504 $this->addAddress(trim($new_addrs[$k]), $primary, $replyTo, $invalid, $optOut, $email_id);
511 }//End of Widget for loop
514 //If no widgets, set addresses array to empty
515 if($post_from_email_address_widget && !$hasEmailValue) {
516 $this->addresses = array();
521 * Preps internal array structure for email addresses
522 * @param string $addr Email address
523 * @param bool $primary Default false
524 * @param bool $replyTo Default false
526 function addAddress($addr, $primary=false, $replyTo=false, $invalid=false, $optOut=false, $email_id = null) {
527 $addr = html_entity_decode($addr, ENT_QUOTES);
528 if(preg_match($this->regex, $addr)) {
529 $primaryFlag = ($primary) ? '1' : '0';
530 $replyToFlag = ($replyTo) ? '1' : '0';
531 $invalidFlag = ($invalid) ? '1' : '0';
532 $optOutFlag = ($optOut) ? '1' : '0';
536 // If we have such address already, remove it and add new one in.
537 foreach ($this->addresses as $k=>$address) {
538 if ($address['email_address'] == $addr) {
539 unset($this->addresses[$k]);
540 } elseif ($primary && $address['primary_address'] == '1') {
541 // We should only have one primary. If we are adding a primary but
542 // we find an existing primary, reset this one's primary flag.
543 $address['primary_address'] = '0';
547 $this->addresses[] = array(
548 'email_address' => $addr,
549 'primary_address' => $primaryFlag,
550 'reply_to_address' => $replyToFlag,
551 'invalid_email' => $invalidFlag,
552 'opt_out' => $optOutFlag,
553 'email_address_id' => $email_id,
556 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: address did not validate [ {$addr} ]");
561 * Updates invalid_email and opt_out flags for each address
563 function updateFlags() {
564 if(!empty($this->addresses)) {
565 foreach($this->addresses as $addressMeta) {
566 if(isset($addressMeta['email_address']) && !empty($addressMeta['email_address'])) {
567 $address = $this->db->quote($this->_cleanAddress($addressMeta['email_address']));
569 $q = "SELECT * FROM email_addresses WHERE email_address = '{$address}'";
570 $r = $this->db->query($q);
571 $a = $this->db->fetchByAssoc($r);
574 if(isset($a['invalid_email']) && isset($addressMeta['invalid_email']) && isset($addressMeta['opt_out']) && $a['invalid_email'] != $addressMeta['invalid_email'] || $a['opt_out'] != $addressMeta['opt_out']) {
575 $qUpdate = "UPDATE email_addresses SET invalid_email = ".intval($addressMeta['invalid_email']).", opt_out = ".intval($addressMeta['opt_out']).", date_modified = '".TimeDate::getInstance()->nowDb()."' WHERE id = '".$this->db->quote($a['id'])."'";
576 $rUpdate = $this->db->query($qUpdate);
584 public function splitEmailAddress($addr)
586 $email = $this->_cleanAddress($addr);
587 if(!preg_match($this->regex, $email)) {
588 $email = ''; // remove bad email addr
590 $name = trim(str_replace(array($email, '<', '>', '"', "'"), '', $addr));
591 return array("name" => $name, "email" => strtolower($email));
596 * Normalizes an RFC-clean email address, returns a string that is the email address only
597 * @param string $addr Dirty email address
598 * @return string clean email address
600 function _cleanAddress($addr) {
601 $addr = trim(from_html($addr));
603 if(strpos($addr, "<") !== false && strpos($addr, ">") !== false) {
604 $address = trim(substr($addr, strrpos($addr, "<") +1, strrpos($addr, ">") - strrpos($addr, "<") -1));
606 $address = trim($addr);
613 * preps a passed email address for email address storage
614 * @param array $addr Address in focus, must be RFC compliant
615 * @return string $id email_addresses ID
617 function getEmailGUID($addr) {
618 $address = $this->db->quote($this->_cleanAddress($addr));
619 $addressCaps = strtoupper($address);
621 $q = "SELECT id FROM email_addresses WHERE email_address_caps = '{$addressCaps}'";
622 $r = $this->db->query($q);
623 $a = $this->db->fetchByAssoc($r);
625 if(!empty($a) && !empty($a['id'])) {
629 if(!empty($address)){
630 $guid = create_guid();
631 $now = TimeDate::getInstance()->nowDb();
632 $qa = "INSERT INTO email_addresses (id, email_address, email_address_caps, date_created, date_modified, deleted)
633 VALUES('{$guid}', '{$address}', '{$addressCaps}', '$now', '$now', 0)";
634 $ra = $this->db->query($qa);
641 * Creates or Updates an entry in the email_addresses table, depending
642 * on if the email address submitted matches a previous entry (case-insensitive)
643 * @param String $addr - email address
644 * @param int $invalid - is the email address marked as Invalid?
645 * @param int $opt_out - is the email address marked as Opt-Out?
646 * @param String $id - the GUID of the original SugarEmailAddress bean,
647 * in case a "email has changed" WorkFlow has triggered - hack to allow workflow-induced changes
648 * to propagate to the new SugarEmailAddress - see bug 39188
649 * @return String GUID of Email Address or '' if cleaned address was empty.
651 public function AddUpdateEmailAddress($addr,$invalid=0,$opt_out=0,$id=null)
653 // sanity checks to avoid SQL injection.
654 $invalid = intval($invalid);
655 $opt_out = intval($opt_out);
657 $address = $this->db->quote($this->_cleanAddress($addr));
658 $addressCaps = strtoupper($address);
660 // determine if we have a matching email address
661 $q = "SELECT * FROM email_addresses WHERE email_address_caps = '{$addressCaps}' and deleted=0";
662 $r = $this->db->query($q);
663 $duplicate_email = $this->db->fetchByAssoc($r);
665 // check if we are changing an email address, where workflow might be in play
667 $r = $this->db->query("SELECT * FROM email_addresses WHERE id='".$this->db->quote($id)."'");
668 $current_email = $this->db->fetchByAssoc($r);
671 $current_email = null;
674 // unless workflow made changes, assume parameters are what to use.
675 $new_opt_out = $opt_out;
676 $new_invalid = $invalid;
677 if (!empty($current_email['id']) && isset($this->stateBeforeWorkflow[$current_email['id']])) {
678 if ($current_email['invalid_email'] != $invalid ||
679 $current_email['opt_out'] != $opt_out) {
681 // workflow could be in play
682 $before_email = $this->stateBeforeWorkflow[$current_email['id']];
684 // our logic is as follows: choose from parameter, unless workflow made a change to the value, then choose final value
685 if (intval($before_email['opt_out']) != intval($current_email['opt_out'])) {
686 $new_opt_out = intval($current_email['opt_out']);
688 if (intval($before_email['invalid_email']) != intval($current_email['invalid_email'])) {
689 $new_invalid = intval($current_email['invalid_email']);
694 // determine how we are going to put in this address - UPDATE or INSERT
695 if (!empty($duplicate_email['id'])) {
697 // address_caps matches - see if we're changing fields
698 if ($duplicate_email['invalid_email'] != $new_invalid ||
699 $duplicate_email['opt_out'] != $new_opt_out ||
700 (trim($duplicate_email['email_address']) != $address)) {
701 $upd_q = 'UPDATE ' . $this->table_name . ' ' .
702 'SET email_address=\'' . $address . '\', ' .
703 'invalid_email=' . $new_invalid . ', ' .
704 'opt_out=' . $new_opt_out . ', ' .
705 'date_modified=' . $this->db->now() . ' ' .
706 'WHERE id=\'' . $this->db->quote($duplicate_email['id']) . '\'';
707 $upd_r = $this->db->query($upd_q);
709 return $duplicate_email['id'];
712 // no case-insensitive address match - it's new, or undeleted.
714 if(!empty($address)){
715 $guid = create_guid();
716 $now = TimeDate::getInstance()->nowDb();
717 $qa = "INSERT INTO email_addresses (id, email_address, email_address_caps, date_created, date_modified, deleted, invalid_email, opt_out)
718 VALUES('{$guid}', '{$address}', '{$addressCaps}', '$now', '$now', 0 , $new_invalid, $new_opt_out)";
719 $this->db->query($qa);
726 * Returns Primary or newest email address
727 * @param object $focus Object in focus
728 * @return string email
730 function getPrimaryAddress($focus,$parent_id=null,$parent_type=null) {
732 $parent_type=empty($parent_type) ? $focus->module_dir : $parent_type;
733 $parent_id=empty($parent_id) ? $focus->id : $parent_id;
735 $q = "SELECT ea.email_address FROM email_addresses ea
736 LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
737 WHERE ear.bean_module = '".$this->db->quote($parent_type)."'
738 AND ear.bean_id = '".$this->db->quote($parent_id)."'
740 AND ea.invalid_email = 0
741 ORDER BY ear.primary_address DESC";
742 $r = $this->db->limitQuery($q, 0, 1);
743 $a = $this->db->fetchByAssoc($r);
745 if(isset($a['email_address'])) {
746 return $a['email_address'];
752 * As long as this function is used not only to retrieve user's Reply-To
753 * address, but also notification address and so on, there were added
754 * $replyToOnly optional parameter used to retrieve only address marked as
755 * Reply-To (bug #43643).
757 * @param SugarBean $focus
758 * @param bool $replyToOnly
761 function getReplyToAddress($focus, $replyToOnly = false) {
762 $q = "SELECT ea.email_address FROM email_addresses ea
763 LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
764 WHERE ear.bean_module = '".$this->db->quote($focus->module_dir)."'
765 AND ear.bean_id = '".$this->db->quote($focus->id)."'
767 AND ea.invalid_email = 0";
771 // retrieve reply-to address if it exists or any other address
774 ORDER BY ear.reply_to_address DESC";
778 // retrieve reply-to address only
780 AND ear.reply_to_address = 1";
783 $r = $this->db->query($q);
784 $a = $this->db->fetchByAssoc($r);
786 if(isset($a['email_address'])) {
787 return $a['email_address'];
793 * Returns all email addresses by parent's GUID
794 * @param string $id Parent's GUID
795 * @param string $module Parent's module
798 function getAddressesByGUID($id, $module) {
800 $module = $this->getCorrectedModule($module);
802 $q = "SELECT ea.email_address, ea.email_address_caps, ea.invalid_email, ea.opt_out, ea.date_created, ea.date_modified,
803 ear.id, ear.email_address_id, ear.bean_id, ear.bean_module, ear.primary_address, ear.reply_to_address, ear.deleted
804 FROM email_addresses ea LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
805 WHERE ear.bean_module = '".$this->db->quote($module)."'
806 AND ear.bean_id = '".$this->db->quote($id)."'
808 ORDER BY ear.reply_to_address, ear.primary_address DESC";
809 $r = $this->db->query($q);
811 while($a = $this->db->fetchByAssoc($r, FALSE)) {
819 * Returns the HTML/JS for the EmailAddress widget
820 * @param string $parent_id ID of parent bean, generally $focus
821 * @param string $module $focus' module
822 * @param bool asMetadata Default false
823 * @return string HTML/JS for widget
825 function getEmailAddressWidgetEditView($id, $module, $asMetadata=false, $tpl='',$tabindex='0')
827 if ( !($this->smarty instanceOf Sugar_Smarty ) )
828 $this->smarty = new Sugar_Smarty();
830 global $app_strings, $dictionary, $beanList;
834 $prefillData = 'new Object()';
835 $passedModule = $module;
836 $module = $this->getCorrectedModule($module);
837 $saveModule = $module;
838 if(isset($_POST['is_converted']) && $_POST['is_converted']==true){
839 $id=$_POST['return_id'];
840 $module=$_POST['return_module'];
842 $prefillDataArr = array();
844 $prefillDataArr = $this->getAddressesByGUID($id, $module);
845 //When coming from convert leads, sometimes module is Contacts while the id is for a lead.
846 if (empty($prefillDataArr) && $module == "Contacts")
847 $prefillDataArr = $this->getAddressesByGUID($id, "Leads");
848 } else if(isset($_REQUEST['full_form']) && !empty($_REQUEST['emailAddressWidget'])){
849 $widget_id = isset($_REQUEST[$module . '_email_widget_id']) ? $_REQUEST[$module . '_email_widget_id'] : '0';
851 $key = $module . $widget_id . 'emailAddress'.$count;
852 while(isset($_REQUEST[$key])) {
853 $email = $_REQUEST[$key];
854 $prefillDataArr[] = array('email_address'=>$email,
855 'primary_address'=>isset($_REQUEST['emailAddressPrimaryFlag']) && $_REQUEST['emailAddressPrimaryFlag'] == $key,
856 'invalid_email'=>isset($_REQUEST['emailAddressInvalidFlag']) && in_array($key, $_REQUEST['emailAddressInvalidFlag']),
857 'opt_out'=>isset($_REQUEST['emailAddressOptOutFlag']) && in_array($key, $_REQUEST['emailAddressOptOutFlag']),
858 'reply_to_address'=>false
860 $key = $module . $widget_id . 'emailAddress' . ++$count;
864 if(!empty($prefillDataArr)) {
865 $json = new JSON(JSON_LOOSE_TYPE);
866 $prefillData = $json->encode($prefillDataArr);
867 $prefill = !empty($prefillDataArr) ? 'true' : 'false';
871 $vardefs = $dictionary[$beanList[$passedModule]]['fields'];
872 if (!empty($vardefs['email1']) && isset($vardefs['email1']['required']) && $vardefs['email1']['required'])
874 $this->smarty->assign('required', $required);
876 $this->smarty->assign('module', $saveModule);
877 $this->smarty->assign('index', $this->index);
878 $this->smarty->assign('app_strings', $app_strings);
879 $this->smarty->assign('prefillEmailAddresses', $prefill);
880 $this->smarty->assign('prefillData', $prefillData);
881 $this->smarty->assign('tabindex', $tabindex);
882 //Set addDefaultAddress flag (do not add if it's from the Email module)
883 $this->smarty->assign('addDefaultAddress', (isset($_REQUEST['module']) && $_REQUEST['module'] == 'Emails') ? 'false' : 'true');
886 //determine if this should be a quickcreate form, or a quick create form under subpanels
887 if ($this->view == "QuickCreate"){
888 $form = 'form_DC'.$this->view .'_'.$module;
889 if(isset($_REQUEST['action']) && $_REQUEST['action']=='SubpanelCreates' || $_REQUEST['action']=='SubpanelEdits'){
890 $form = 'form_Subpanel'.$this->view .'_'.$module;
894 $this->smarty->assign('emailView', $form);
896 if($module == 'Users') {
897 $this->smarty->assign('useReplyTo', true);
899 $this->smarty->assign('useOptOut', true);
900 $this->smarty->assign('useInvalid', true);
903 $template = empty($tpl) ? "include/SugarEmailAddress/templates/forEditView.tpl" : $tpl;
904 $newEmail = $this->smarty->fetch($template);
910 $ret['prefillData'] = $prefillDataArr;
911 $ret['html'] = $newEmail;
921 * Returns the HTML/JS for the EmailAddress widget
922 * @param object $focus Bean in focus
923 * @return string HTML/JS for widget
925 function getEmailAddressWidgetDetailView($focus, $tpl='')
927 if ( !($this->smarty instanceOf Sugar_Smarty ) )
928 $this->smarty = new Sugar_Smarty();
931 global $current_user;
933 if(empty($focus->id))return '';
934 $prefillData = $this->getAddressesByGUID($focus->id, $focus->module_dir);
936 foreach($prefillData as $addressItem) {
937 $key = ($addressItem['primary_address'] == 1) ? 'primary' : "";
938 $key = ($addressItem['reply_to_address'] == 1) ? 'reply_to' : $key;
939 $key = ($addressItem['opt_out'] == 1) ? 'opt_out' : $key;
940 $key = ($addressItem['invalid_email'] == 1) ? 'invalid' : $key;
941 $key = ($addressItem['opt_out'] == 1) && ($addressItem['invalid_email'] == 1) ? 'opt_out_invalid' : $key;
943 $assign[] = array('key' => $key, 'address' => $current_user->getEmailLink2($addressItem['email_address'], $focus).$addressItem['email_address']."</a>");
947 $this->smarty->assign('app_strings', $app_strings);
948 $this->smarty->assign('emailAddresses', $assign);
949 $templateFile = empty($tpl) ? "include/SugarEmailAddress/templates/forDetailView.tpl" : $tpl;
950 $return = $this->smarty->fetch($templateFile);
956 * getEmailAddressWidgetDuplicatesView($focus)
957 * @param object $focus Bean in focus
958 * @return string HTML that contains hidden input values based off of HTML request
960 function getEmailAddressWidgetDuplicatesView($focus)
962 if ( !($this->smarty instanceOf Sugar_Smarty ) )
963 $this->smarty = new Sugar_Smarty();
970 $mod = isset($focus) ? $focus->module_dir : "";
972 $widget_id = $_POST[$mod .'_email_widget_id'];
973 $this->smarty->assign('email_widget_id',$widget_id);
974 $this->smarty->assign('emailAddressWidget',$_POST['emailAddressWidget']);
976 if(isset($_POST[$mod . $widget_id . 'emailAddressPrimaryFlag'])) {
977 $primary = $_POST[$mod . $widget_id . 'emailAddressPrimaryFlag'];
980 while(isset($_POST[$mod . $widget_id . "emailAddress" . $count])) {
981 $emails[] = $_POST[$mod . $widget_id . 'emailAddress' . $count];
989 if(isset($_POST[$mod . $widget_id . 'emailAddressOptOutFlag'])) {
990 foreach($_POST[$mod . $widget_id . 'emailAddressOptOutFlag'] as $v) {
995 if(isset($_POST[$mod . $widget_id . 'emailAddressInvalidFlag'])) {
996 foreach($_POST[$mod . $widget_id . 'emailAddressInvalidFlag'] as $v) {
1001 if(isset($_POST[$mod . $widget_id . 'emailAddressReplyToFlag'])) {
1002 foreach($_POST[$mod . $widget_id . 'emailAddressReplyToFlag'] as $v) {
1007 if(isset($_POST[$mod . $widget_id . 'emailAddressDeleteFlag'])) {
1008 foreach($_POST[$mod . $widget_id . 'emailAddressDeleteFlag'] as $v) {
1013 while(isset($_POST[$mod . $widget_id . "emailAddressVerifiedValue" . $count])) {
1014 $verified[] = $_POST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count];
1018 $this->smarty->assign('emails', $emails);
1019 $this->smarty->assign('primary', $primary);
1020 $this->smarty->assign('optOut', $optOut);
1021 $this->smarty->assign('invalid', $invalid);
1022 $this->smarty->assign('replyTo', $invalid);
1023 $this->smarty->assign('delete', $invalid);
1024 $this->smarty->assign('verified', $invalid);
1025 $this->smarty->assign('moduleDir', $mod);
1027 return $this->smarty->fetch("include/SugarEmailAddress/templates/forDuplicatesView.tpl");
1034 function getFormBaseURL($focus) {
1037 $mod = isset($focus) ? $focus->module_dir : "";
1039 $widget_id = $_POST[$mod .'_email_widget_id'];
1040 $get .= '&' . $mod . '_email_widget_id='. $widget_id;
1041 $get .= '&emailAddressWidget='.$_POST['emailAddressWidget'];
1043 while(isset($_REQUEST[$mod . $widget_id . 'emailAddress' . $count])) {
1044 $get .= "&" . $mod . $widget_id . "emailAddress" . $count . "=" . urlencode($_REQUEST[$mod . $widget_id . 'emailAddress' . $count]);
1048 while(isset($_REQUEST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count])) {
1049 $get .= "&" . $mod . $widget_id . "emailAddressVerifiedValue" . $count . "=" . urlencode($_REQUEST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count]);
1053 $options = array('emailAddressPrimaryFlag', 'emailAddressOptOutFlag', 'emailAddressInvalidFlag', 'emailAddressDeleteFlag', 'emailAddressReplyToFlag');
1055 foreach($options as $option) {
1057 $optionIdentifier = $mod.$widget_id.$option;
1058 if(isset($_REQUEST[$optionIdentifier])) {
1059 if(is_array($_REQUEST[$optionIdentifier])) {
1060 foreach($_REQUEST[$optionIdentifier] as $optOut) {
1061 $get .= "&" . $optionIdentifier . "[" . $count . "]=" . $optOut;
1065 $get .= "&" . $optionIdentifier . "=" . $_REQUEST[$optionIdentifier];
1073 function setView($view) {
1074 $this->view = $view;
1078 * This function is here so the Employees/Users division can be handled cleanly in one place
1079 * @param object $focus SugarBean
1080 * @return string The value for the bean_module column in the email_addr_bean_rel table
1082 function getCorrectedModule(&$module) {
1083 return ($module == "Employees")? "Users" : $module;
1086 public function stash($parentBeanId, $moduleName)
1088 $result = $this->db->query("select email_address_id from email_addr_bean_rel eabr WHERE eabr.bean_id = '".$this->db->quote($parentBeanId)."' AND eabr.bean_module = '".$this->db->quote($moduleName)."' and eabr.deleted=0");
1089 $this->stateBeforeWorkflow = array();
1091 while ($row = $this->db->fetchByAssoc($result, false))
1093 $ids[] =$this->db->quote($row['email_address_id']); // avoid 2nd order SQL Injection
1097 $ids = implode("', '", $ids);
1098 $queryEmailData = "SELECT id, email_address, invalid_email, opt_out FROM {$this->table_name} WHERE id IN ('$ids') AND deleted=0";
1099 $result = $this->db->query($queryEmailData);
1100 while ($row = $this->db->fetchByAssoc($result, false))
1102 $this->stateBeforeWorkflow[$row['id']] = array_diff_key($row, array('id' => null));
1110 * Convenience function for MVC (Mystique)
1111 * @param object $focus SugarBean
1112 * @param string $field unused
1113 * @param string $value unused
1114 * @param string $view DetailView or EditView
1117 function getEmailAddressWidget($focus, $field, $value, $view, $tabindex='0') {
1118 $sea = new SugarEmailAddress();
1119 $sea->setView($view);
1121 if($view == 'EditView' || $view == 'QuickCreate' || $view == 'ConvertLead') {
1122 $module = $focus->module_dir;
1123 if ($view == 'ConvertLead' && $module == "Contacts") $module = "Leads";
1125 return $sea->getEmailAddressWidgetEditView($focus->id, $module, false,'',$tabindex);
1128 return $sea->getEmailAddressWidgetDetailView($focus);