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-2011 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
69 function SugarEmailAddress() {
71 $this->index = self::$count;
76 * Legacy email address handling. This is to allow support for SOAP or customizations
78 * @param string $module
80 function handleLegacySave($bean, $prefix = "") {
81 if(!isset($_REQUEST) || !isset($_REQUEST['useEmailWidget'])) {
82 if (empty($this->addresses) || !isset($_REQUEST['massupdate'])) {
83 $this->addresses = array();
84 $optOut = (isset($bean->email_opt_out) && $bean->email_opt_out == "1") ? true : false;
85 $invalid = (isset($bean->invalid_email) && $bean->invalid_email == "1") ? true : false;
88 for($i = 1; $i <= 10; $i++){
90 if(isset($bean->$email) && !empty($bean->$email)){
91 $opt_out_field = $email.'_opt_out';
92 $invalid_field = $email.'_invalid';
93 $field_optOut = (isset($bean->$opt_out_field)) ? $bean->$opt_out_field : $optOut;
94 $field_invalid = (isset($bean->$invalid_field)) ? $bean->$invalid_field : $invalid;
95 $this->addAddress($bean->$email, $isPrimary, false, $field_invalid, $field_optOut);
101 $this->populateAddresses($bean->id, $bean->module_dir, array(),'');
102 if(isset($_REQUEST) && isset($_REQUEST['useEmailWidget'])) {
103 $this->populateLegacyFields($bean);
108 * Fills standard email1 legacy fields
110 * @param string module
113 function handleLegacyRetrieve(&$bean) {
114 $module_dir = $this->getCorrectedModule($bean->module_dir);
115 $this->addresses = $this->getAddressesByGUID($bean->id, $module_dir);
116 $this->populateLegacyFields($bean);
117 if (isset($bean->email1) && !isset($bean->fetched_row['email1'])) {
118 $bean->fetched_row['email1'] = $bean->email1;
124 function populateLegacyFields(&$bean){
125 $primary_found = false;
126 $alternate_found = false;
127 $alternate2_found = false;
128 foreach($this->addresses as $k=>$address) {
129 if ($primary_found && $alternate_found)
131 if ($address['primary_address'] == 1 && !$primary_found) {
133 $primary_found = true;
134 } elseif (!$alternate_found) {
135 $alternate_index = $k;
136 $alternate_found = true;
137 } elseif (!$alternate2_found){
138 $alternate2_index = $k;
139 $alternate2_found = true;
143 if ($primary_found) {
144 $bean->email1 = $this->addresses[$primary_index]['email_address'];
145 $bean->email_opt_out = $this->addresses[$primary_index]['opt_out'];
146 $bean->invalid_email = $this->addresses[$primary_index]['invalid_email'];
147 if ($alternate_found) {
148 $bean->email2 = $this->addresses[$alternate_index]['email_address'];
150 } elseif ($alternate_found) {
151 // Use the first found alternate as email1.
152 $bean->email1 = $this->addresses[$alternate_index]['email_address'];
153 $bean->email_opt_out = $this->addresses[$alternate_index]['opt_out'];
154 $bean->invalid_email = $this->addresses[$alternate_index]['invalid_email'];
155 if ($alternate2_found) {
156 $bean->email2 = $this->addresses[$alternate2_index]['email_address'];
162 * Saves email addresses for a parent bean
163 * @param string $id Parent bean ID
164 * @param string $module Parent bean's module
165 * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
166 * @param string $primary GUID of primary address
167 * @param string $replyTo GUID of reply-to address
168 * @param string $invalid GUID of invalid address
170 function save($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='', $in_workflow=false) {
171 if(empty($this->addresses) || $in_workflow){
172 $this->populateAddresses($id, $module, $new_addrs,$primary);
175 //find all email addresses..
176 $current_links=array();
177 // Need to correct this to handle the Employee/User split
178 $module = $this->getCorrectedModule($module);
179 $q2="select * from email_addr_bean_rel eabr WHERE eabr.bean_id = '{$id}' AND eabr.bean_module = '{$module}' and eabr.deleted=0";
180 $r2 = $this->db->query($q2);
181 while(($row2=$this->db->fetchByAssoc($r2)) != null ) {
182 $current_links[$row2['email_address_id']]=$row2;
185 $isConversion = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? true : false;
187 if (!empty($this->addresses)) {
188 // insert new relationships and create email address record, if they don't exist
189 foreach($this->addresses as $address) {
190 if(!empty($address['email_address'])) {
191 $guid = create_guid();
192 $emailId = $this->AddUpdateEmailAddress($address['email_address'],$address['invalid_email'],$address['opt_out']);// this will save the email address if not found
194 //verify linkage and flags.
196 if (isset($current_links[$emailId])) {
197 if (!$isConversion) { // do not update anything if this is for lead conversion
198 if ($address['primary_address'] != $current_links[$emailId]['primary_address'] or $address['reply_to_address'] != $current_links[$emailId]['reply_to_address'] ) {
199 $upd_eabr="UPDATE email_addr_bean_rel SET primary_address='{$address['primary_address']}', reply_to_address='{$address['reply_to_address']}' WHERE id='{$current_links[$emailId]['id']}'";
202 unset($current_links[$emailId]);
205 $primary = $address['primary_address'];
206 if (!empty($current_links) && $isConversion) {
207 foreach ($current_links as $eabr) {
208 if ($eabr['primary_address'] == 1) {
209 // for lead conversion, if there is already a primary email, do not insert another primary email
215 $now = $this->db->now();
216 $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('{$guid}', '{$emailId}', '{$id}', '{$module}', {$primary}, {$address['reply_to_address']}, $now, $now, 0)";
219 if (!empty($upd_eabr)) {
220 $r2 = $this->db->query($upd_eabr);
226 //delete link to dropped email address.
227 // for lead conversion, do not delete email addresses
228 if (!empty($current_links) && !$isConversion) {
231 foreach ($current_links as $eabr) {
233 $delete.=empty($delete) ? "'".$eabr['id'] . "' " : ",'" . $eabr['id'] . "'";
236 $eabr_unlink="update email_addr_bean_rel set deleted=1 where id in ({$delete})";
237 $this->db->query($eabr_unlink);
243 * returns the number of email addresses found for a specifed bean
245 * @param string $email Address to match
246 * @param object $bean Bean to query against
247 * @param string $addresstype Optional, pass a 1 to query against the primary address, 0 for the other addresses
248 * @return int Count of records found
250 function getCountEmailAddressByBean(
256 $emailCaps = strtoupper(trim($email));
257 if(empty($emailCaps))
261 FROM email_addr_bean_rel eabl JOIN email_addresses ea
262 ON (ea.id = eabl.email_address_id)
263 JOIN {$bean->table_name} bean
264 ON (eabl.bean_id = bean.id)
265 WHERE ea.email_address_caps = '{$emailCaps}'
266 and eabl.bean_module = '{$bean->module_dir}'
267 and eabl.primary_address = '{$addresstype}'
268 and eabl.deleted=0 ";
270 $r = $this->db->query($q);
272 // do it this way to make the count accurate in oracle
274 while ($this->db->fetchByAssoc($r)) ++$i;
280 * This function returns a contact or user ID if a matching email is found
281 * @param $email the email address to match
282 * @param $table which table to query
284 function getRelatedId($email, $module) {
285 $email = trim(strtoupper($email));
286 $module = ucfirst($module);
288 $q = "SELECT bean_id FROM email_addr_bean_rel eabr
289 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
290 WHERE bean_module = '{$module}' AND ea.email_address_caps = '{$email}' AND eabr.deleted=0";
292 $r = $this->db->query($q, true);
295 while($a = $this->db->fetchByAssoc($r)) {
296 $retArr[] = $a['bean_id'];
298 if(count($retArr) > 0) {
306 * returns a collection of beans matching the email address
307 * @param string $email Address to match
310 function getBeansByEmailAddress($email) {
316 $email = trim($email);
322 $emailCaps = strtoupper($email);
323 $q = "SELECT * FROM email_addr_bean_rel eabl JOIN email_addresses ea ON (ea.id = eabl.email_address_id)
324 WHERE ea.email_address_caps = '{$emailCaps}' and eabl.deleted=0 ";
325 $r = $this->db->query($q);
327 while($a = $this->db->fetchByAssoc($r)) {
328 if(isset($beanList[$a['bean_module']]) && !empty($beanList[$a['bean_module']])) {
329 $className = $beanList[$a['bean_module']];
331 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
332 if(!class_exists($className)) {
333 require_once($beanFiles[$className]);
336 $bean = new $className();
337 $bean->retrieve($a['bean_id']);
341 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class file for [ {$className} ]");
344 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class [ {$a['bean_module']} ]");
352 * Saves email addresses for a parent bean
353 * @param string $id Parent bean ID
354 * @param string $module Parent bean's module
355 * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
356 * @param string $primary GUID of primary address
357 * @param string $replyTo GUID of reply-to address
358 * @param string $invalid GUID of invalid address
360 function populateAddresses($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='') {
361 $module = $this->getCorrectedModule($module);
362 //One last check for the ConvertLead action in which case we need to change $module to 'Leads'
363 $module = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? 'Leads' : $module;
365 $post_from_email_address_widget = (isset($_REQUEST) && isset($_REQUEST['emailAddressWidget'])) ? true : false;
366 $primaryValue = $primary;
368 $hasEmailValue = false;
370 if (isset($_REQUEST) && isset($_REQUEST[$module .'_email_widget_id'])) {
372 $fromRequest = false;
373 // determine which array to process
374 foreach($_REQUEST as $k => $v) {
375 if(strpos($k, 'emailAddress') !== false) {
379 $widget_id = $_REQUEST[$module .'_email_widget_id'];
382 //Iterate over the widgets for this module, in case there are multiple email widgets for this module
383 while(isset($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount]))
385 if (empty($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount])) {
390 $hasEmailValue = true;
392 $eId = $module . $widget_id;
393 if(isset($_REQUEST[$eId . 'emailAddressPrimaryFlag'])) {
394 $primaryValue = $_REQUEST[$eId . 'emailAddressPrimaryFlag'];
395 } else if(isset($_REQUEST[$module . 'emailAddressPrimaryFlag'])) {
396 $primaryValue = $_REQUEST[$module . 'emailAddressPrimaryFlag'];
399 $optOutValues = array();
400 if(isset($_REQUEST[$eId .'emailAddressOptOutFlag'])) {
401 $optOutValues = $_REQUEST[$eId .'emailAddressOptOutFlag'];
402 } else if(isset($_REQUEST[$module . 'emailAddressOptOutFlag'])) {
403 $optOutValues = $_REQUEST[$module . 'emailAddressOptOutFlag'];
406 $invalidValues = array();
407 if(isset($_REQUEST[$eId .'emailAddressInvalidFlag'])) {
408 $invalidValues = $_REQUEST[$eId .'emailAddressInvalidFlag'];
409 } else if(isset($_REQUEST[$module . 'emailAddressInvalidFlag'])) {
410 $invalidValues = $_REQUEST[$module . 'emailAddressInvalidFlag'];
413 $deleteValues = array();
414 if(isset($_REQUEST[$eId .'emailAddressDeleteFlag'])) {
415 $deleteValues = $_REQUEST[$eId .'emailAddressDeleteFlag'];
416 } else if(isset($_REQUEST[$module . 'emailAddressDeleteFlag'])) {
417 $deleteValues = $_REQUEST[$module . 'emailAddressDeleteFlag'];
420 // prep from form save
421 $primaryField = $primary;
425 if($fromRequest && empty($primary) && isset($primaryValue)) {
426 $primaryField = $primaryValue;
429 if($fromRequest && empty($replyTo)) {
430 if(isset($_REQUEST[$eId .'emailAddressReplyToFlag'])) {
431 $replyToField = $_REQUEST[$eId .'emailAddressReplyToFlag'];
432 } else if(isset($_REQUEST[$module . 'emailAddressReplyToFlag'])) {
433 $replyToField = $_REQUEST[$module . 'emailAddressReplyToFlag'];
436 if($fromRequest && empty($new_addrs)) {
437 foreach($_REQUEST as $k => $v) {
438 if(preg_match('/'.$eId.'emailAddress[0-9]+$/i', $k) && !empty($v)) {
444 if($fromRequest && empty($new_addrs)) {
445 foreach($_REQUEST as $k => $v) {
446 if(preg_match('/'.$eId.'emailAddressVerifiedValue[0-9]+$/i', $k) && !empty($v)) {
447 $validateFlag = str_replace("Value", "Flag", $k);
448 if (isset($_REQUEST[$validateFlag]) && $_REQUEST[$validateFlag] == "true")
454 //empty the addresses array if the post happened from email address widget.
455 if($post_from_email_address_widget) {
456 $this->addresses=array(); //this gets populated during retrieve of the contact bean.
458 $optOutValues = array();
459 $invalidValues = array();
460 foreach($new_addrs as $k=>$email) {
461 preg_match('/emailAddress([0-9])+$/', $k, $matches);
462 $count = $matches[1];
463 $result = $this->db->query("SELECT opt_out, invalid_email from email_addresses where email_address_caps = '" . strtoupper($email) . "'");
464 if(!empty($result)) {
465 $row=$this->db->fetchByAssoc($result);
466 if(!empty($row['opt_out'])) {
467 $optOutValues[$k] = "emailAddress$count";
469 if(!empty($row['invalid_email'])) {
470 $invalidValues[$k] = "emailAddress$count";
475 // Re-populate the addresses class variable if we have new address(es).
476 if (!empty($new_addrs)) {
477 foreach($new_addrs as $k => $reqVar) {
478 //$key = preg_match("/^$eId/s", $k) ? substr($k, strlen($eId)) : $k;
479 $reqVar = trim($reqVar);
480 if(strpos($k, 'emailAddress') !== false) {
481 if(!empty($reqVar) && !in_array($k, $deleteValues)) {
482 $primary = ($k == $primaryValue) ? true : false;
483 $replyTo = ($k == $replyToField) ? true : false;
484 $invalid = (in_array($k, $invalidValues)) ? true : false;
485 $optOut = (in_array($k, $optOutValues)) ? true : false;
486 $this->addAddress(trim($new_addrs[$k]), $primary, $replyTo, $invalid, $optOut);
493 }//End of Widget for loop
496 //If no widgets, set addresses array to empty
497 if($post_from_email_address_widget && !$hasEmailValue) {
498 $this->addresses = array();
503 * Preps internal array structure for email addresses
504 * @param string $addr Email address
505 * @param bool $primary Default false
506 * @param bool $replyTo Default false
508 function addAddress($addr, $primary=false, $replyTo=false, $invalid=false, $optOut=false) {
509 $addr = html_entity_decode($addr, ENT_QUOTES);
510 if(preg_match($this->regex, $addr)) {
511 $primaryFlag = ($primary) ? '1' : '0';
512 $replyToFlag = ($replyTo) ? '1' : '0';
513 $invalidFlag = ($invalid) ? '1' : '0';
514 $optOutFlag = ($optOut) ? '1' : '0';
518 // If we have such address already, remove it and add new one in.
519 foreach ($this->addresses as $k=>$address) {
520 if ($address['email_address'] == $addr) {
521 unset($this->addresses[$k]);
522 } elseif ($primary && $address['primary_address'] == '1') {
523 // We should only have one primary. If we are adding a primary but
524 // we find an existing primary, reset this one's primary flag.
525 $address['primary_address'] = '0';
529 $this->addresses[] = array(
530 'email_address' => $addr,
531 'primary_address' => $primaryFlag,
532 'reply_to_address' => $replyToFlag,
533 'invalid_email' => $invalidFlag,
534 'opt_out' => $optOutFlag,
537 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: address did not validate [ {$addr} ]");
542 * Updates invalid_email and opt_out flags for each address
544 function updateFlags() {
545 if(!empty($this->addresses)) {
546 foreach($this->addresses as $addressMeta) {
547 if(isset($addressMeta['email_address']) && !empty($addressMeta['email_address'])) {
548 $address = $this->_cleanAddress($addressMeta['email_address']);
550 $q = "SELECT * FROM email_addresses WHERE email_address = '{$address}'";
551 $r = $this->db->query($q);
552 $a = $this->db->fetchByAssoc($r);
555 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']) {
556 $qUpdate = "UPDATE email_addresses SET invalid_email = {$addressMeta['invalid_email']}, opt_out = {$addressMeta['opt_out']}, date_modified = '".TimeDate::getInstance()->nowDb()."' WHERE id = '{$a['id']}'";
557 $rUpdate = $this->db->query($qUpdate);
565 public function splitEmailAddress($addr)
567 $email = $this->_cleanAddress($addr);
568 if(!preg_match($this->regex, $email)) {
569 $email = ''; // remove bad email addr
571 $name = trim(str_replace(array($email, '<', '>', '"', "'"), '', $addr));
572 return array("name" => $name, "email" => strtolower($email));
577 * Normalizes an RFC-clean email address, returns a string that is the email address only
578 * @param string $addr Dirty email address
579 * @return string clean email address
581 function _cleanAddress($addr) {
582 $addr = trim(from_html($addr));
584 if(strpos($addr, "<") !== false && strpos($addr, ">") !== false) {
585 $address = trim(substr($addr, strrpos($addr, "<") +1, strrpos($addr, ">") - strrpos($addr, "<") -1));
587 $address = trim($addr);
594 * preps a passed email address for email address storage
595 * @param array $addr Address in focus, must be RFC compliant
596 * @return string $id email_addresses ID
598 function getEmailGUID($addr) {
599 $address = $this->db->quote($this->_cleanAddress($addr));
600 $addressCaps = strtoupper($address);
602 $q = "SELECT id FROM email_addresses WHERE email_address_caps = '{$addressCaps}'";
603 $r = $this->db->query($q);
604 $a = $this->db->fetchByAssoc($r);
606 if(!empty($a) && !empty($a['id'])) {
610 if(!empty($address)){
611 $guid = create_guid();
612 $address = $GLOBALS['db']->quote($address);
613 $now = TimeDate::getInstance()->nowDb();
614 $qa = "INSERT INTO email_addresses (id, email_address, email_address_caps, date_created, date_modified, deleted)
615 VALUES('{$guid}', '{$address}', '{$addressCaps}', '$now', '$now', 0)";
616 $ra = $this->db->query($qa);
622 function AddUpdateEmailAddress($addr,$invalid=0,$opt_out=0)
624 $address = $this->db->quote($this->_cleanAddress($addr));
625 $addressCaps = strtoupper($address);
627 $q = "SELECT * FROM email_addresses WHERE email_address_caps = '{$addressCaps}' and deleted=0";
628 $r = $this->db->query($q);
629 $a = $this->db->fetchByAssoc($r);
630 if(!empty($a) && !empty($a['id'])) {
631 //verify the opt out and invalid flags.
632 //bug# 39378- did not allow change of case of an email address
633 if ($a['invalid_email'] != $invalid or $a['opt_out'] != $opt_out or strcasecmp(trim($a['email_address']), trim($address))==0) {
634 $upd_q="update email_addresses set email_address='{$address}', invalid_email={$invalid}, opt_out={$opt_out},date_modified = '".gmdate($GLOBALS['timedate']->get_db_date_time_format())."' where id='{$a['id']}'";
635 $upd_r= $this->db->query($upd_q);
640 if(!empty($address)){
641 $guid = create_guid();
642 $now = TimeDate::getInstance()->nowDb();
643 $qa = "INSERT INTO email_addresses (id, email_address, email_address_caps, date_created, date_modified, deleted, invalid_email, opt_out)
644 VALUES('{$guid}', '{$address}', '{$addressCaps}', '$now', '$now', 0 , $invalid, $opt_out)";
645 $this->db->query($qa);
652 * Returns Primary or newest email address
653 * @param object $focus Object in focus
654 * @return string email
656 function getPrimaryAddress($focus,$parent_id=null,$parent_type=null) {
658 $parent_type=empty($parent_type) ? $focus->module_dir : $parent_type;
659 $parent_id=empty($parent_id) ? $focus->id : $parent_id;
661 $q = "SELECT ea.email_address FROM email_addresses ea
662 LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
663 WHERE ear.bean_module = '{$parent_type}'
664 AND ear.bean_id = '{$parent_id}'
666 AND ea.invalid_email = 0
667 ORDER BY ear.primary_address DESC";
668 $r = $this->db->limitQuery($q, 0, 1);
669 $a = $this->db->fetchByAssoc($r);
671 if(isset($a['email_address'])) {
672 return $a['email_address'];
677 function getReplyToAddress($focus) {
678 $q = "SELECT ea.email_address FROM email_addresses ea
679 LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
680 WHERE ear.bean_module = '{$focus->module_dir}'
681 AND ear.bean_id = '{$focus->id}'
683 AND ea.invalid_email = 0
684 ORDER BY ear.reply_to_address DESC";
685 $r = $this->db->query($q);
686 $a = $this->db->fetchByAssoc($r);
688 if(isset($a['email_address'])) {
689 return $a['email_address'];
695 * Returns all email addresses by parent's GUID
696 * @param string $id Parent's GUID
697 * @param string $module Parent's module
700 function getAddressesByGUID($id, $module) {
702 $module = $this->getCorrectedModule($module);
704 $q = "SELECT ea.email_address, ea.email_address_caps, ea.invalid_email, ea.opt_out, ea.date_created, ea.date_modified,
705 ear.id, ear.email_address_id, ear.bean_id, ear.bean_module, ear.primary_address, ear.reply_to_address, ear.deleted
706 FROM email_addresses ea LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
707 WHERE ear.bean_module = '{$module}'
708 AND ear.bean_id = '{$id}'
710 ORDER BY ear.reply_to_address, ear.primary_address DESC";
711 $r = $this->db->query($q);
713 while($a = $this->db->fetchByAssoc($r)) {
721 * Returns the HTML/JS for the EmailAddress widget
722 * @param string $parent_id ID of parent bean, generally $focus
723 * @param string $module $focus' module
724 * @param bool asMetadata Default false
725 * @return string HTML/JS for widget
727 function getEmailAddressWidgetEditView($id, $module, $asMetadata=false, $tpl='',$tabindex='0')
729 if ( !($this->smarty instanceOf Sugar_Smarty ) )
730 $this->smarty = new Sugar_Smarty();
732 global $app_strings, $dictionary, $beanList;
736 $prefillData = 'new Object()';
737 $passedModule = $module;
738 $module = $this->getCorrectedModule($module);
739 $saveModule = $module;
740 if(isset($_POST['is_converted']) && $_POST['is_converted']==true){
741 $id=$_POST['return_id'];
742 $module=$_POST['return_module'];
744 $prefillDataArr = array();
746 $prefillDataArr = $this->getAddressesByGUID($id, $module);
747 //When coming from convert leads, sometimes module is Contacts while the id is for a lead.
748 if (empty($prefillDataArr) && $module == "Contacts")
749 $prefillDataArr = $this->getAddressesByGUID($id, "Leads");
750 } else if(isset($_REQUEST['full_form']) && !empty($_REQUEST['emailAddressWidget'])){
751 $widget_id = isset($_REQUEST[$module . '_email_widget_id']) ? $_REQUEST[$module . '_email_widget_id'] : '0';
753 $key = $module . $widget_id . 'emailAddress'.$count;
754 while(isset($_REQUEST[$key])) {
755 $email = $_REQUEST[$key];
756 $prefillDataArr[] = array('email_address'=>$email,
757 'primary_address'=>isset($_REQUEST['emailAddressPrimaryFlag']) && $_REQUEST['emailAddressPrimaryFlag'] == $key,
758 'invalid_email'=>isset($_REQUEST['emailAddressInvalidFlag']) && in_array($key, $_REQUEST['emailAddressInvalidFlag']),
759 'opt_out'=>isset($_REQUEST['emailAddressOptOutFlag']) && in_array($key, $_REQUEST['emailAddressOptOutFlag']),
760 'reply_to_address'=>false
762 $key = $module . $widget_id . 'emailAddress' . ++$count;
766 if(!empty($prefillDataArr)) {
767 $json = new JSON(JSON_LOOSE_TYPE);
768 $prefillData = $json->encode($prefillDataArr);
769 $prefill = !empty($prefillDataArr) ? 'true' : 'false';
773 $vardefs = $dictionary[$beanList[$passedModule]]['fields'];
774 if (!empty($vardefs['email1']) && isset($vardefs['email1']['required']) && $vardefs['email1']['required'])
776 $this->smarty->assign('required', $required);
778 $this->smarty->assign('module', $saveModule);
779 $this->smarty->assign('index', $this->index);
780 $this->smarty->assign('app_strings', $app_strings);
781 $this->smarty->assign('prefillEmailAddresses', $prefill);
782 $this->smarty->assign('prefillData', $prefillData);
783 $this->smarty->assign('tabindex', $tabindex);
784 //Set addDefaultAddress flag (do not add if it's from the Email module)
785 $this->smarty->assign('addDefaultAddress', (isset($_REQUEST['module']) && $_REQUEST['module'] == 'Emails') ? 'false' : 'true');
788 //determine if this should be a quickcreate form, or a quick create form under subpanels
789 if ($this->view == "QuickCreate"){
790 $form = 'form_DC'.$this->view .'_'.$module;
791 if(isset($_REQUEST['action']) && $_REQUEST['action']=='SubpanelCreates' || $_REQUEST['action']=='SubpanelEdits'){
792 $form = 'form_Subpanel'.$this->view .'_'.$module;
796 $this->smarty->assign('emailView', $form);
798 if($module == 'Users') {
799 $this->smarty->assign('useReplyTo', true);
801 $this->smarty->assign('useOptOut', true);
802 $this->smarty->assign('useInvalid', true);
805 $template = empty($tpl) ? "include/SugarEmailAddress/templates/forEditView.tpl" : $tpl;
806 $newEmail = $this->smarty->fetch($template);
812 $ret['prefillData'] = $prefillDataArr;
813 $ret['html'] = $newEmail;
823 * Returns the HTML/JS for the EmailAddress widget
824 * @param object $focus Bean in focus
825 * @return string HTML/JS for widget
827 function getEmailAddressWidgetDetailView($focus, $tpl='')
829 if ( !($this->smarty instanceOf Sugar_Smarty ) )
830 $this->smarty = new Sugar_Smarty();
833 global $current_user;
835 if(empty($focus->id))return '';
836 $prefillData = $this->getAddressesByGUID($focus->id, $focus->module_dir);
838 foreach($prefillData as $addressItem) {
839 $key = ($addressItem['primary_address'] == 1) ? 'primary' : "";
840 $key = ($addressItem['reply_to_address'] == 1) ? 'reply_to' : $key;
841 $key = ($addressItem['opt_out'] == 1) ? 'opt_out' : $key;
842 $key = ($addressItem['invalid_email'] == 1) ? 'invalid' : $key;
843 $key = ($addressItem['opt_out'] == 1) && ($addressItem['invalid_email'] == 1) ? 'opt_out_invalid' : $key;
845 $assign[] = array('key' => $key, 'address' => $current_user->getEmailLink2($addressItem['email_address'], $focus).$addressItem['email_address']."</a>");
849 $this->smarty->assign('app_strings', $app_strings);
850 $this->smarty->assign('emailAddresses', $assign);
851 $templateFile = empty($tpl) ? "include/SugarEmailAddress/templates/forDetailView.tpl" : $tpl;
852 $return = $this->smarty->fetch($templateFile);
858 * getEmailAddressWidgetDuplicatesView($focus)
859 * @param object $focus Bean in focus
860 * @return string HTML that contains hidden input values based off of HTML request
862 function getEmailAddressWidgetDuplicatesView($focus)
864 if ( !($this->smarty instanceOf Sugar_Smarty ) )
865 $this->smarty = new Sugar_Smarty();
872 $mod = isset($focus) ? $focus->module_dir : "";
874 $widget_id = $_POST[$mod .'_email_widget_id'];
875 $this->smarty->assign('email_widget_id',$widget_id);
876 $this->smarty->assign('emailAddressWidget',$_POST['emailAddressWidget']);
878 if(isset($_POST[$mod . $widget_id . 'emailAddressPrimaryFlag'])) {
879 $primary = $_POST[$mod . $widget_id . 'emailAddressPrimaryFlag'];
882 while(isset($_POST[$mod . $widget_id . "emailAddress" . $count])) {
883 $emails[] = $_POST[$mod . $widget_id . 'emailAddress' . $count];
891 if(isset($_POST[$mod . $widget_id . 'emailAddressOptOutFlag'])) {
892 foreach($_POST[$mod . $widget_id . 'emailAddressOptOutFlag'] as $v) {
897 if(isset($_POST[$mod . $widget_id . 'emailAddressInvalidFlag'])) {
898 foreach($_POST[$mod . $widget_id . 'emailAddressInvalidFlag'] as $v) {
903 if(isset($_POST[$mod . $widget_id . 'emailAddressReplyToFlag'])) {
904 foreach($_POST[$mod . $widget_id . 'emailAddressReplyToFlag'] as $v) {
909 if(isset($_POST[$mod . $widget_id . 'emailAddressDeleteFlag'])) {
910 foreach($_POST[$mod . $widget_id . 'emailAddressDeleteFlag'] as $v) {
915 while(isset($_POST[$mod . $widget_id . "emailAddressVerifiedValue" . $count])) {
916 $verified[] = $_POST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count];
920 $this->smarty->assign('emails', $emails);
921 $this->smarty->assign('primary', $primary);
922 $this->smarty->assign('optOut', $optOut);
923 $this->smarty->assign('invalid', $invalid);
924 $this->smarty->assign('replyTo', $invalid);
925 $this->smarty->assign('delete', $invalid);
926 $this->smarty->assign('verified', $invalid);
927 $this->smarty->assign('moduleDir', $mod);
929 return $this->smarty->fetch("include/SugarEmailAddress/templates/forDuplicatesView.tpl");
936 function getFormBaseURL($focus) {
939 $mod = isset($focus) ? $focus->module_dir : "";
941 $widget_id = $_POST[$mod .'_email_widget_id'];
942 $get .= '&' . $mod . '_email_widget_id='. $widget_id;
943 $get .= '&emailAddressWidget='.$_POST['emailAddressWidget'];
945 while(isset($_REQUEST[$mod . $widget_id . 'emailAddress' . $count])) {
946 $get .= "&" . $mod . $widget_id . "emailAddress" . $count . "=" . urlencode($_REQUEST[$mod . $widget_id . 'emailAddress' . $count]);
950 while(isset($_REQUEST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count])) {
951 $get .= "&" . $mod . $widget_id . "emailAddressVerifiedValue" . $count . "=" . urlencode($_REQUEST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count]);
955 $options = array('emailAddressPrimaryFlag', 'emailAddressOptOutFlag', 'emailAddressInvalidFlag', 'emailAddressDeleteFlag', 'emailAddressReplyToFlag');
957 foreach($options as $option) {
959 $optionIdentifier = $mod.$widget_id.$option;
960 if(isset($_REQUEST[$optionIdentifier])) {
961 if(is_array($_REQUEST[$optionIdentifier])) {
962 foreach($_REQUEST[$optionIdentifier] as $optOut) {
963 $get .= "&" . $optionIdentifier . "[" . $count . "]=" . $optOut;
967 $get .= "&" . $optionIdentifier . "=" . $_REQUEST[$optionIdentifier];
975 function setView($view) {
980 * This function is here so the Employees/Users division can be handled cleanly in one place
981 * @param object $focus SugarBean
982 * @return string The value for the bean_module column in the email_addr_bean_rel table
984 function getCorrectedModule(&$module) {
985 return ($module == "Employees")? "Users" : $module;
991 * Convenience function for MVC (Mystique)
992 * @param object $focus SugarBean
993 * @param string $field unused
994 * @param string $value unused
995 * @param string $view DetailView or EditView
998 function getEmailAddressWidget($focus, $field, $value, $view, $tabindex='0') {
999 $sea = new SugarEmailAddress();
1000 $sea->setView($view);
1002 if($view == 'EditView' || $view == 'QuickCreate' || $view == 'ConvertLead') {
1003 $module = $focus->module_dir;
1004 if ($view == 'ConvertLead' && $module == "Contacts") $module = "Leads";
1006 return $sea->getEmailAddressWidgetEditView($focus->id, $module, false,'',$tabindex);
1009 return $sea->getEmailAddressWidgetDetailView($focus);