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);
121 function populateLegacyFields(&$bean){
122 $primary_found = false;
123 $alternate_found = false;
124 $alternate2_found = false;
125 foreach($this->addresses as $k=>$address) {
126 if ($primary_found && $alternate_found)
128 if ($address['primary_address'] == 1 && !$primary_found) {
130 $primary_found = true;
131 } elseif (!$alternate_found) {
132 $alternate_index = $k;
133 $alternate_found = true;
134 } elseif (!$alternate2_found){
135 $alternate2_index = $k;
136 $alternate2_found = true;
140 if ($primary_found) {
141 $bean->email1 = $this->addresses[$primary_index]['email_address'];
142 $bean->email_opt_out = $this->addresses[$primary_index]['opt_out'];
143 $bean->invalid_email = $this->addresses[$primary_index]['invalid_email'];
144 if ($alternate_found) {
145 $bean->email2 = $this->addresses[$alternate_index]['email_address'];
147 } elseif ($alternate_found) {
148 // Use the first found alternate as email1.
149 $bean->email1 = $this->addresses[$alternate_index]['email_address'];
150 $bean->email_opt_out = $this->addresses[$alternate_index]['opt_out'];
151 $bean->invalid_email = $this->addresses[$alternate_index]['invalid_email'];
152 if ($alternate2_found) {
153 $bean->email2 = $this->addresses[$alternate2_index]['email_address'];
159 * Saves email addresses for a parent bean
160 * @param string $id Parent bean ID
161 * @param string $module Parent bean's module
162 * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
163 * @param string $primary GUID of primary address
164 * @param string $replyTo GUID of reply-to address
165 * @param string $invalid GUID of invalid address
167 function save($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='', $in_workflow=false) {
168 if(empty($this->addresses) || $in_workflow){
169 $this->populateAddresses($id, $module, $new_addrs,$primary);
172 //find all email addresses..
173 $current_links=array();
174 // Need to correct this to handle the Employee/User split
175 $module = $this->getCorrectedModule($module);
176 $q2="select * from email_addr_bean_rel eabr WHERE eabr.bean_id = '{$id}' AND eabr.bean_module = '{$module}' and eabr.deleted=0";
177 $r2 = $this->db->query($q2);
178 while(($row2=$this->db->fetchByAssoc($r2)) != null ) {
179 $current_links[$row2['email_address_id']]=$row2;
182 if (!empty($this->addresses)) {
183 // insert new relationships and create email address record, if they don't exist
184 foreach($this->addresses as $address) {
185 if(!empty($address['email_address'])) {
186 $guid = create_guid();
187 $emailId = $this->AddUpdateEmailAddress($address['email_address'],$address['invalid_email'],$address['opt_out']);// this will save the email address if not found
189 //verify linkage and flags.
191 if (isset($current_links[$emailId])) {
192 if ($address['primary_address'] != $current_links[$emailId]['primary_address'] or $address['reply_to_address'] != $current_links[$emailId]['reply_to_address'] ) {
193 $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']}'";
196 unset($current_links[$emailId]);
198 $now = TimeDate::getInstance()->nowDb();
199 $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}', {$address['primary_address']}, {$address['reply_to_address']}, '$now', '$now', 0)";
202 if (!empty($upd_eabr)) {
203 $r2 = $this->db->query($upd_eabr);
209 //delete link to dropped email address.
210 if (!empty($current_links)) {
213 foreach ($current_links as $eabr) {
215 $delete.=empty($delete) ? "'".$eabr['id'] . "' " : ",'" . $eabr['id'] . "'";
218 $eabr_unlink="update email_addr_bean_rel set deleted=1 where id in ({$delete})";
219 $this->db->query($eabr_unlink);
225 * returns the number of email addresses found for a specifed bean
227 * @param string $email Address to match
228 * @param object $bean Bean to query against
229 * @param string $addresstype Optional, pass a 1 to query against the primary address, 0 for the other addresses
230 * @return int Count of records found
232 function getCountEmailAddressByBean(
238 $emailCaps = strtoupper(trim($email));
239 if(empty($emailCaps))
243 FROM email_addr_bean_rel eabl JOIN email_addresses ea
244 ON (ea.id = eabl.email_address_id)
245 JOIN {$bean->table_name} bean
246 ON (eabl.bean_id = bean.id)
247 WHERE ea.email_address_caps = '{$emailCaps}'
248 and eabl.bean_module = '{$bean->module_dir}'
249 and eabl.primary_address = '{$addresstype}'
250 and eabl.deleted=0 ";
252 $r = $this->db->query($q);
254 // do it this way to make the count accurate in oracle
256 while ($this->db->fetchByAssoc($r)) ++$i;
262 * This function returns a contact or user ID if a matching email is found
263 * @param $email the email address to match
264 * @param $table which table to query
266 function getRelatedId($email, $module) {
267 $email = trim(strtoupper($email));
268 $module = ucfirst($module);
270 $q = "SELECT bean_id FROM email_addr_bean_rel eabr
271 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
272 WHERE bean_module = '{$module}' AND ea.email_address_caps = '{$email}' AND eabr.deleted=0";
274 $r = $this->db->query($q, true);
277 while($a = $this->db->fetchByAssoc($r)) {
278 $retArr[] = $a['bean_id'];
280 if(count($retArr) > 0) {
288 * returns a collection of beans matching the email address
289 * @param string $email Address to match
292 function getBeansByEmailAddress($email) {
298 $email = trim($email);
304 $emailCaps = strtoupper($email);
305 $q = "SELECT * FROM email_addr_bean_rel eabl JOIN email_addresses ea ON (ea.id = eabl.email_address_id)
306 WHERE ea.email_address_caps = '{$emailCaps}' and eabl.deleted=0 ";
307 $r = $this->db->query($q);
309 while($a = $this->db->fetchByAssoc($r)) {
310 if(isset($beanList[$a['bean_module']]) && !empty($beanList[$a['bean_module']])) {
311 $className = $beanList[$a['bean_module']];
313 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
314 if(!class_exists($className)) {
315 require_once($beanFiles[$className]);
318 $bean = new $className();
319 $bean->retrieve($a['bean_id']);
323 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class file for [ {$className} ]");
326 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class [ {$a['bean_module']} ]");
334 * Saves email addresses for a parent bean
335 * @param string $id Parent bean ID
336 * @param string $module Parent bean's module
337 * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
338 * @param string $primary GUID of primary address
339 * @param string $replyTo GUID of reply-to address
340 * @param string $invalid GUID of invalid address
342 function populateAddresses($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='') {
343 $module = $this->getCorrectedModule($module);
344 //One last check for the ConvertLead action in which case we need to change $module to 'Leads'
345 $module = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? 'Leads' : $module;
347 $post_from_email_address_widget = (isset($_REQUEST) && isset($_REQUEST['emailAddressWidget'])) ? true : false;
348 $primaryValue = $primary;
350 $hasEmailValue = false;
352 if (isset($_REQUEST) && isset($_REQUEST[$module .'_email_widget_id'])) {
354 $fromRequest = false;
355 // determine which array to process
356 foreach($_REQUEST as $k => $v) {
357 if(strpos($k, 'emailAddress') !== false) {
362 $widget_id = $_REQUEST[$module .'_email_widget_id'];
365 //Iterate over the widgets for this module, in case there are multiple email widgets for this module
366 while(isset($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount]))
368 if (empty($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount])) {
373 $hasEmailValue = true;
375 $eId = $module . $widget_id;
376 if(isset($_REQUEST[$eId . 'emailAddressPrimaryFlag'])) {
377 $primaryValue = $_REQUEST[$eId . 'emailAddressPrimaryFlag'];
378 } else if(isset($_REQUEST[$module . 'emailAddressPrimaryFlag'])) {
379 $primaryValue = $_REQUEST[$module . 'emailAddressPrimaryFlag'];
382 $optOutValues = array();
383 if(isset($_REQUEST[$eId .'emailAddressOptOutFlag'])) {
384 $optOutValues = $_REQUEST[$eId .'emailAddressOptOutFlag'];
385 } else if(isset($_REQUEST[$module . 'emailAddressOptOutFlag'])) {
386 $optOutValues = $_REQUEST[$module . 'emailAddressOptOutFlag'];
389 $invalidValues = array();
390 if(isset($_REQUEST[$eId .'emailAddressInvalidFlag'])) {
391 $invalidValues = $_REQUEST[$eId .'emailAddressInvalidFlag'];
392 } else if(isset($_REQUEST[$module . 'emailAddressInvalidFlag'])) {
393 $invalidValues = $_REQUEST[$module . 'emailAddressInvalidFlag'];
396 $deleteValues = array();
397 if(isset($_REQUEST[$eId .'emailAddressDeleteFlag'])) {
398 $deleteValues = $_REQUEST[$eId .'emailAddressDeleteFlag'];
399 } else if(isset($_REQUEST[$module . 'emailAddressDeleteFlag'])) {
400 $deleteValues = $_REQUEST[$module . 'emailAddressDeleteFlag'];
403 // prep from form save
404 $primaryField = $primary;
408 if($fromRequest && empty($primary) && isset($primaryValue)) {
409 $primaryField = $primaryValue;
412 if($fromRequest && empty($replyTo)) {
413 if(isset($_REQUEST[$eId .'emailAddressReplyToFlag'])) {
414 $replyToField = $_REQUEST[$eId .'emailAddressReplyToFlag'];
415 } else if(isset($_REQUEST[$module . 'emailAddressReplyToFlag'])) {
416 $replyToField = $_REQUEST[$module . 'emailAddressReplyToFlag'];
419 if($fromRequest && empty($new_addrs)) {
420 foreach($_REQUEST as $k => $v) {
421 if(preg_match('/'.$eId.'emailAddress[0-9]+$/i', $k) && !empty($v)) {
427 if($fromRequest && empty($new_addrs)) {
428 foreach($_REQUEST as $k => $v) {
429 if(preg_match('/'.$eId.'emailAddressVerifiedValue[0-9]+$/i', $k) && !empty($v)) {
430 $validateFlag = str_replace("Value", "Flag", $k);
431 if (isset($_REQUEST[$validateFlag]) && $_REQUEST[$validateFlag] == "true")
437 //empty the addresses array if the post happened from email address widget.
438 if($post_from_email_address_widget) {
439 $this->addresses=array(); //this gets populated during retrieve of the contact bean.
441 $optOutValues = array();
442 $invalidValues = array();
443 foreach($new_addrs as $k=>$email) {
444 preg_match('/emailAddress([0-9])+$/', $k, $matches);
445 $count = $matches[1];
446 $result = $this->db->query("SELECT opt_out, invalid_email from email_addresses where email_address_caps = '" . strtoupper($email) . "'");
447 if(!empty($result)) {
448 $row=$this->db->fetchByAssoc($result);
449 if(!empty($row['opt_out'])) {
450 $optOutValues[$k] = "emailAddress$count";
452 if(!empty($row['invalid_email'])) {
453 $invalidValues[$k] = "emailAddress$count";
458 // Re-populate the addresses class variable if we have new address(es).
459 if (!empty($new_addrs)) {
460 foreach($new_addrs as $k => $reqVar) {
461 //$key = preg_match("/^$eId/s", $k) ? substr($k, strlen($eId)) : $k;
462 $reqVar = trim($reqVar);
463 if(strpos($k, 'emailAddress') !== false) {
464 if(!empty($reqVar) && !in_array($k, $deleteValues)) {
465 $primary = ($k == $primaryValue) ? true : false;
466 $replyTo = ($k == $replyToField) ? true : false;
467 $invalid = (in_array($k, $invalidValues)) ? true : false;
468 $optOut = (in_array($k, $optOutValues)) ? true : false;
469 $this->addAddress(trim($new_addrs[$k]), $primary, $replyTo, $invalid, $optOut);
476 }//End of Widget for loop
479 //If no widgets, set addresses array to empty
480 if($post_from_email_address_widget && !$hasEmailValue) {
481 $this->addresses = array();
486 * Preps internal array structure for email addresses
487 * @param string $addr Email address
488 * @param bool $primary Default false
489 * @param bool $replyTo Default false
491 function addAddress($addr, $primary=false, $replyTo=false, $invalid=false, $optOut=false) {
492 $addr = html_entity_decode($addr, ENT_QUOTES);
493 if(preg_match($this->regex, $addr)) {
494 $primaryFlag = ($primary) ? '1' : '0';
495 $replyToFlag = ($replyTo) ? '1' : '0';
496 $invalidFlag = ($invalid) ? '1' : '0';
497 $optOutFlag = ($optOut) ? '1' : '0';
501 // If we have such address already, remove it and add new one in.
502 foreach ($this->addresses as $k=>$address) {
503 if ($address['email_address'] == $addr) {
504 unset($this->addresses[$k]);
505 } elseif ($primary && $address['primary_address'] == '1') {
506 // We should only have one primary. If we are adding a primary but
507 // we find an existing primary, reset this one's primary flag.
508 $address['primary_address'] = '0';
512 $this->addresses[] = array(
513 'email_address' => $addr,
514 'primary_address' => $primaryFlag,
515 'reply_to_address' => $replyToFlag,
516 'invalid_email' => $invalidFlag,
517 'opt_out' => $optOutFlag,
520 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: address did not validate [ {$addr} ]");
525 * Updates invalid_email and opt_out flags for each address
527 function updateFlags() {
528 if(!empty($this->addresses)) {
529 foreach($this->addresses as $addressMeta) {
530 if(isset($addressMeta['email_address']) && !empty($addressMeta['email_address'])) {
531 $address = $this->_cleanAddress($addressMeta['email_address']);
533 $q = "SELECT * FROM email_addresses WHERE email_address = '{$address}'";
534 $r = $this->db->query($q);
535 $a = $this->db->fetchByAssoc($r);
538 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']) {
539 $qUpdate = "UPDATE email_addresses SET invalid_email = {$addressMeta['invalid_email']}, opt_out = {$addressMeta['opt_out']}, date_modified = '".TimeDate::getInstance()->nowDb()."' WHERE id = '{$a['id']}'";
540 $rUpdate = $this->db->query($qUpdate);
548 public function splitEmailAddress($addr)
550 $email = $this->_cleanAddress($addr);
551 if(!preg_match($this->regex, $email)) {
552 $email = ''; // remove bad email addr
554 $name = trim(str_replace(array($email, '<', '>', '"', "'"), '', $addr));
555 return array("name" => $name, "email" => strtolower($email));
560 * Normalizes an RFC-clean email address, returns a string that is the email address only
561 * @param string $addr Dirty email address
562 * @return string clean email address
564 function _cleanAddress($addr) {
565 $addr = trim(from_html($addr));
567 if(strpos($addr, "<") !== false && strpos($addr, ">") !== false) {
568 $address = trim(substr($addr, strrpos($addr, "<") +1, strrpos($addr, ">") - strrpos($addr, "<") -1));
570 $address = trim($addr);
577 * preps a passed email address for email address storage
578 * @param array $addr Address in focus, must be RFC compliant
579 * @return string $id email_addresses ID
581 function getEmailGUID($addr) {
582 $address = $this->_cleanAddress($addr);
583 $addressCaps = strtoupper($address);
585 $q = "SELECT id FROM email_addresses WHERE email_address_caps = '{$addressCaps}'";
586 $r = $this->db->query($q);
587 $a = $this->db->fetchByAssoc($r);
589 if(!empty($a) && !empty($a['id'])) {
593 if(!empty($address)){
594 $guid = create_guid();
595 $address = $GLOBALS['db']->quote($address);
596 $addressCaps = $GLOBALS['db']->quote($addressCaps);
597 $now = TimeDate::getInstance()->nowDb();
598 $qa = "INSERT INTO email_addresses (id, email_address, email_address_caps, date_created, date_modified, deleted)
599 VALUES('{$guid}', '{$address}', '{$addressCaps}', '$now', '$now', 0)";
600 $ra = $this->db->query($qa);
606 function AddUpdateEmailAddress($addr,$invalid=0,$opt_out=0) {
608 $address = $this->_cleanAddress($addr);
609 $addressCaps = strtoupper($this->db->quoteForEmail($address));
611 $q = "SELECT * FROM email_addresses WHERE email_address_caps = '{$addressCaps}' and deleted=0";
612 $r = $this->db->query($q);
613 $a = $this->db->fetchByAssoc($r);
614 if(!empty($a) && !empty($a['id'])) {
615 //verify the opt out and invalid flags.
616 //bug# 39378- did not allow change of case of an email address
617 if ($a['invalid_email'] != $invalid or $a['opt_out'] != $opt_out or strcasecmp(trim($a['email_address']), trim($address))==0) {
618 $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']}'";
619 $upd_r= $this->db->query($upd_q);
624 if(!empty($address)){
625 $guid = create_guid();
626 $address = $GLOBALS['db']->quote($address);
627 $addressCaps = $GLOBALS['db']->quote($addressCaps);
628 $now = TimeDate::getInstance()->nowDb();
629 $qa = "INSERT INTO email_addresses (id, email_address, email_address_caps, date_created, date_modified, deleted, invalid_email, opt_out)
630 VALUES('{$guid}', '{$address}', '{$addressCaps}', '$now', '$now', 0 , $invalid, $opt_out)";
631 $this->db->query($qa);
638 * Returns Primary or newest email address
639 * @param object $focus Object in focus
640 * @return string email
642 function getPrimaryAddress($focus,$parent_id=null,$parent_type=null) {
644 $parent_type=empty($parent_type) ? $focus->module_dir : $parent_type;
645 $parent_id=empty($parent_id) ? $focus->id : $parent_id;
647 $q = "SELECT ea.email_address FROM email_addresses ea
648 LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
649 WHERE ear.bean_module = '{$parent_type}'
650 AND ear.bean_id = '{$parent_id}'
652 ORDER BY ear.primary_address DESC";
653 $r = $this->db->limitQuery($q, 0, 1);
654 $a = $this->db->fetchByAssoc($r);
656 if(isset($a['email_address'])) {
657 return $a['email_address'];
662 function getReplyToAddress($focus) {
663 $q = "SELECT ea.email_address FROM email_addresses ea
664 LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
665 WHERE ear.bean_module = '{$focus->module_dir}'
666 AND ear.bean_id = '{$focus->id}'
668 ORDER BY ear.reply_to_address DESC";
669 $r = $this->db->query($q);
670 $a = $this->db->fetchByAssoc($r);
672 if(isset($a['email_address'])) {
673 return $a['email_address'];
679 * Returns all email addresses by parent's GUID
680 * @param string $id Parent's GUID
681 * @param string $module Parent's module
684 function getAddressesByGUID($id, $module) {
686 $module = $this->getCorrectedModule($module);
688 $q = "SELECT ea.email_address, ea.email_address_caps, ea.invalid_email, ea.opt_out, ea.date_created, ea.date_modified,
689 ear.id, ear.email_address_id, ear.bean_id, ear.bean_module, ear.primary_address, ear.reply_to_address, ear.deleted
690 FROM email_addresses ea LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
691 WHERE ear.bean_module = '{$module}'
692 AND ear.bean_id = '{$id}'
694 ORDER BY ear.reply_to_address, ear.primary_address DESC";
695 $r = $this->db->query($q);
697 while($a = $this->db->fetchByAssoc($r)) {
705 * Returns the HTML/JS for the EmailAddress widget
706 * @param string $parent_id ID of parent bean, generally $focus
707 * @param string $module $focus' module
708 * @param bool asMetadata Default false
709 * @return string HTML/JS for widget
711 function getEmailAddressWidgetEditView($id, $module, $asMetadata=false, $tpl='',$tabindex='')
713 if ( !($this->smarty instanceOf Sugar_Smarty ) )
714 $this->smarty = new Sugar_Smarty();
716 global $app_strings, $dictionary, $beanList;
720 $prefillData = 'new Object()';
721 $passedModule = $module;
722 $module = $this->getCorrectedModule($module);
723 $saveModule = $module;
724 if(isset($_POST['is_converted']) && $_POST['is_converted']==true){
725 $id=$_POST['return_id'];
726 $module=$_POST['return_module'];
728 $prefillDataArr = array();
730 $prefillDataArr = $this->getAddressesByGUID($id, $module);
731 //When coming from convert leads, sometimes module is Contacts while the id is for a lead.
732 if (empty($prefillDataArr) && $module == "Contacts")
733 $prefillDataArr = $this->getAddressesByGUID($id, "Leads");
734 } else if(isset($_REQUEST['full_form']) && !empty($_REQUEST['emailAddressWidget'])){
735 $widget_id = isset($_REQUEST[$module . '_email_widget_id']) ? $_REQUEST[$module . '_email_widget_id'] : '0';
737 $key = $module . $widget_id . 'emailAddress'.$count;
738 while(isset($_REQUEST[$key])) {
739 $email = $_REQUEST[$key];
740 $prefillDataArr[] = array('email_address'=>$email,
741 'primary_address'=>isset($_REQUEST['emailAddressPrimaryFlag']) && $_REQUEST['emailAddressPrimaryFlag'] == $key,
742 'invalid_email'=>isset($_REQUEST['emailAddressInvalidFlag']) && in_array($key, $_REQUEST['emailAddressInvalidFlag']),
743 'opt_out'=>isset($_REQUEST['emailAddressOptOutFlag']) && in_array($key, $_REQUEST['emailAddressOptOutFlag']),
744 'reply_to_address'=>false
746 $key = $module . $widget_id . 'emailAddress' . ++$count;
750 if(!empty($prefillDataArr)) {
751 $json = new JSON(JSON_LOOSE_TYPE);
752 $prefillData = $json->encode($prefillDataArr);
753 $prefill = !empty($prefillDataArr) ? 'true' : 'false';
757 $vardefs = $dictionary[$beanList[$passedModule]]['fields'];
758 if (!empty($vardefs['email1']) && isset($vardefs['email1']['required']) && $vardefs['email1']['required'])
760 $this->smarty->assign('required', $required);
762 $this->smarty->assign('module', $saveModule);
763 $this->smarty->assign('index', $this->index);
764 $this->smarty->assign('app_strings', $app_strings);
765 $this->smarty->assign('prefillEmailAddresses', $prefill);
766 $this->smarty->assign('prefillData', $prefillData);
767 $this->smarty->assign('tabindex', $tabindex);
768 //Set addDefaultAddress flag (do not add if it's from the Email module)
769 $this->smarty->assign('addDefaultAddress', (isset($_REQUEST['module']) && $_REQUEST['module'] == 'Emails') ? 'false' : 'true');
772 if ($this->view == "QuickCreate")
773 $form = 'form_'.$this->view .'_'.$module;
774 $this->smarty->assign('emailView', $form);
776 if($module == 'Users') {
777 $this->smarty->assign('useReplyTo', true);
779 $this->smarty->assign('useOptOut', true);
780 $this->smarty->assign('useInvalid', true);
783 $template = empty($tpl) ? "include/SugarEmailAddress/templates/forEditView.tpl" : $tpl;
784 $newEmail = $this->smarty->fetch($template);
790 $ret['prefillData'] = $prefillDataArr;
791 $ret['html'] = $newEmail;
801 * Returns the HTML/JS for the EmailAddress widget
802 * @param object $focus Bean in focus
803 * @return string HTML/JS for widget
805 function getEmailAddressWidgetDetailView($focus, $tpl='')
807 if ( !($this->smarty instanceOf Sugar_Smarty ) )
808 $this->smarty = new Sugar_Smarty();
811 global $current_user;
813 if(empty($focus->id))return '';
814 $prefillData = $this->getAddressesByGUID($focus->id, $focus->module_dir);
816 foreach($prefillData as $addressItem) {
817 $key = ($addressItem['primary_address'] == 1) ? 'primary' : "";
818 $key = ($addressItem['reply_to_address'] == 1) ? 'reply_to' : $key;
819 $key = ($addressItem['opt_out'] == 1) ? 'opt_out' : $key;
820 $key = ($addressItem['invalid_email'] == 1) ? 'invalid' : $key;
821 $key = ($addressItem['opt_out'] == 1) && ($addressItem['invalid_email'] == 1) ? 'opt_out_invalid' : $key;
823 $assign[] = array('key' => $key, 'address' => $current_user->getEmailLink2($addressItem['email_address'], $focus).$addressItem['email_address']."</a>");
827 $this->smarty->assign('app_strings', $app_strings);
828 $this->smarty->assign('emailAddresses', $assign);
829 $templateFile = empty($tpl) ? "include/SugarEmailAddress/templates/forDetailView.tpl" : $tpl;
830 $return = $this->smarty->fetch($templateFile);
836 * getEmailAddressWidgetDuplicatesView($focus)
837 * @param object $focus Bean in focus
838 * @return string HTML that contains hidden input values based off of HTML request
840 function getEmailAddressWidgetDuplicatesView($focus)
842 if ( !($this->smarty instanceOf Sugar_Smarty ) )
843 $this->smarty = new Sugar_Smarty();
850 $mod = isset($focus) ? $focus->module_dir : "";
852 $widget_id = $_POST[$mod .'_email_widget_id'];
853 $this->smarty->assign('email_widget_id',$widget_id);
854 $this->smarty->assign('emailAddressWidget',$_POST['emailAddressWidget']);
856 if(isset($_POST[$mod . $widget_id . 'emailAddressPrimaryFlag'])) {
857 $primary = $_POST[$mod . $widget_id . 'emailAddressPrimaryFlag'];
860 while(isset($_POST[$mod . $widget_id . "emailAddress" . $count])) {
861 $emails[] = $_POST[$mod . $widget_id . 'emailAddress' . $count];
869 if(isset($_POST[$mod . $widget_id . 'emailAddressOptOutFlag'])) {
870 foreach($_POST[$mod . $widget_id . 'emailAddressOptOutFlag'] as $v) {
875 if(isset($_POST[$mod . $widget_id . 'emailAddressInvalidFlag'])) {
876 foreach($_POST[$mod . $widget_id . 'emailAddressInvalidFlag'] as $v) {
881 if(isset($_POST[$mod . $widget_id . 'emailAddressReplyToFlag'])) {
882 foreach($_POST[$mod . $widget_id . 'emailAddressReplyToFlag'] as $v) {
887 if(isset($_POST[$mod . $widget_id . 'emailAddressDeleteFlag'])) {
888 foreach($_POST[$mod . $widget_id . 'emailAddressDeleteFlag'] as $v) {
893 while(isset($_POST[$mod . $widget_id . "emailAddressVerifiedValue" . $count])) {
894 $verified[] = $_POST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count];
898 $this->smarty->assign('emails', $emails);
899 $this->smarty->assign('primary', $primary);
900 $this->smarty->assign('optOut', $optOut);
901 $this->smarty->assign('invalid', $invalid);
902 $this->smarty->assign('replyTo', $invalid);
903 $this->smarty->assign('delete', $invalid);
904 $this->smarty->assign('verified', $invalid);
905 $this->smarty->assign('moduleDir', $mod);
907 return $this->smarty->fetch("include/SugarEmailAddress/templates/forDuplicatesView.tpl");
914 function getFormBaseURL($focus) {
917 $mod = isset($focus) ? $focus->module_dir : "";
919 $widget_id = $_POST[$mod .'_email_widget_id'];
920 $get .= '&' . $mod . '_email_widget_id='. $widget_id;
921 $get .= '&emailAddressWidget='.$_POST['emailAddressWidget'];
923 while(isset($_REQUEST[$mod . $widget_id . 'emailAddress' . $count])) {
924 $get .= "&" . $mod . $widget_id . "emailAddress" . $count . "=" . urlencode($_REQUEST[$mod . $widget_id . 'emailAddress' . $count]);
928 while(isset($_REQUEST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count])) {
929 $get .= "&" . $mod . $widget_id . "emailAddressVerifiedValue" . $count . "=" . urlencode($_REQUEST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count]);
933 $options = array('emailAddressPrimaryFlag', 'emailAddressOptOutFlag', 'emailAddressInvalidFlag', 'emailAddressDeleteFlag', 'emailAddressReplyToFlag');
935 foreach($options as $option) {
937 $optionIdentifier = $mod.$widget_id.$option;
938 if(isset($_REQUEST[$optionIdentifier])) {
939 if(is_array($_REQUEST[$optionIdentifier])) {
940 foreach($_REQUEST[$optionIdentifier] as $optOut) {
941 $get .= "&" . $optionIdentifier . "[" . $count . "]=" . $optOut;
945 $get .= "&" . $optionIdentifier . "=" . $_REQUEST[$optionIdentifier];
953 function setView($view) {
958 * This function is here so the Employees/Users division can be handled cleanly in one place
959 * @param object $focus SugarBean
960 * @return string The value for the bean_module column in the email_addr_bean_rel table
962 function getCorrectedModule(&$module) {
963 return ($module == "Employees")? "Users" : $module;
969 * Convenience function for MVC (Mystique)
970 * @param object $focus SugarBean
971 * @param string $field unused
972 * @param string $value unused
973 * @param string $view DetailView or EditView
976 function getEmailAddressWidget($focus, $field, $value, $view, $tabindex='') {
977 $sea = new SugarEmailAddress();
978 $sea->setView($view);
980 if($view == 'EditView' || $view == 'QuickCreate' || $view == 'ConvertLead') {
981 $module = $focus->module_dir;
982 if ($view == 'ConvertLead' && $module == "Contacts") $module = "Leads";
984 return $sea->getEmailAddressWidgetEditView($focus->id, $module, false,'',$tabindex);
987 return $sea->getEmailAddressWidgetDetailView($focus);