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 $isConversion = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? true : false;
184 if (!empty($this->addresses)) {
185 // insert new relationships and create email address record, if they don't exist
186 foreach($this->addresses as $address) {
187 if(!empty($address['email_address'])) {
188 $guid = create_guid();
189 $emailId = $this->AddUpdateEmailAddress($address['email_address'],$address['invalid_email'],$address['opt_out']);// this will save the email address if not found
191 //verify linkage and flags.
193 if (isset($current_links[$emailId])) {
194 if (!$isConversion) { // do not update anything if this is for lead conversion
195 if ($address['primary_address'] != $current_links[$emailId]['primary_address'] or $address['reply_to_address'] != $current_links[$emailId]['reply_to_address'] ) {
196 $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']}'";
199 unset($current_links[$emailId]);
202 $primary = $address['primary_address'];
203 if (!empty($current_links) && $isConversion) {
204 foreach ($current_links as $eabr) {
205 if ($eabr['primary_address'] == 1) {
206 // for lead conversion, if there is already a primary email, do not insert another primary email
212 $now = TimeDate::getInstance()->nowDb();
213 $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)";
216 if (!empty($upd_eabr)) {
217 $r2 = $this->db->query($upd_eabr);
223 //delete link to dropped email address.
224 // for lead conversion, do not delete email addresses
225 if (!empty($current_links) && !$isConversion) {
228 foreach ($current_links as $eabr) {
230 $delete.=empty($delete) ? "'".$eabr['id'] . "' " : ",'" . $eabr['id'] . "'";
233 $eabr_unlink="update email_addr_bean_rel set deleted=1 where id in ({$delete})";
234 $this->db->query($eabr_unlink);
240 * returns the number of email addresses found for a specifed bean
242 * @param string $email Address to match
243 * @param object $bean Bean to query against
244 * @param string $addresstype Optional, pass a 1 to query against the primary address, 0 for the other addresses
245 * @return int Count of records found
247 function getCountEmailAddressByBean(
253 $emailCaps = strtoupper(trim($email));
254 if(empty($emailCaps))
258 FROM email_addr_bean_rel eabl JOIN email_addresses ea
259 ON (ea.id = eabl.email_address_id)
260 JOIN {$bean->table_name} bean
261 ON (eabl.bean_id = bean.id)
262 WHERE ea.email_address_caps = '{$emailCaps}'
263 and eabl.bean_module = '{$bean->module_dir}'
264 and eabl.primary_address = '{$addresstype}'
265 and eabl.deleted=0 ";
267 $r = $this->db->query($q);
269 // do it this way to make the count accurate in oracle
271 while ($this->db->fetchByAssoc($r)) ++$i;
277 * This function returns a contact or user ID if a matching email is found
278 * @param $email the email address to match
279 * @param $table which table to query
281 function getRelatedId($email, $module) {
282 $email = trim(strtoupper($email));
283 $module = ucfirst($module);
285 $q = "SELECT bean_id FROM email_addr_bean_rel eabr
286 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
287 WHERE bean_module = '{$module}' AND ea.email_address_caps = '{$email}' AND eabr.deleted=0";
289 $r = $this->db->query($q, true);
292 while($a = $this->db->fetchByAssoc($r)) {
293 $retArr[] = $a['bean_id'];
295 if(count($retArr) > 0) {
303 * returns a collection of beans matching the email address
304 * @param string $email Address to match
307 function getBeansByEmailAddress($email) {
313 $email = trim($email);
319 $emailCaps = strtoupper($email);
320 $q = "SELECT * FROM email_addr_bean_rel eabl JOIN email_addresses ea ON (ea.id = eabl.email_address_id)
321 WHERE ea.email_address_caps = '{$emailCaps}' and eabl.deleted=0 ";
322 $r = $this->db->query($q);
324 while($a = $this->db->fetchByAssoc($r)) {
325 if(isset($beanList[$a['bean_module']]) && !empty($beanList[$a['bean_module']])) {
326 $className = $beanList[$a['bean_module']];
328 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
329 if(!class_exists($className)) {
330 require_once($beanFiles[$className]);
333 $bean = new $className();
334 $bean->retrieve($a['bean_id']);
338 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class file for [ {$className} ]");
341 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class [ {$a['bean_module']} ]");
349 * Saves email addresses for a parent bean
350 * @param string $id Parent bean ID
351 * @param string $module Parent bean's module
352 * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
353 * @param string $primary GUID of primary address
354 * @param string $replyTo GUID of reply-to address
355 * @param string $invalid GUID of invalid address
357 function populateAddresses($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='') {
358 $module = $this->getCorrectedModule($module);
359 //One last check for the ConvertLead action in which case we need to change $module to 'Leads'
360 $module = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? 'Leads' : $module;
362 $post_from_email_address_widget = (isset($_REQUEST) && isset($_REQUEST['emailAddressWidget'])) ? true : false;
363 $primaryValue = $primary;
365 $hasEmailValue = false;
367 if (isset($_REQUEST) && isset($_REQUEST[$module .'_email_widget_id'])) {
369 $fromRequest = false;
370 // determine which array to process
371 foreach($_REQUEST as $k => $v) {
372 if(strpos($k, 'emailAddress') !== false) {
376 $widget_id = $_REQUEST[$module .'_email_widget_id'];
379 //Iterate over the widgets for this module, in case there are multiple email widgets for this module
380 while(isset($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount]))
382 if (empty($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount])) {
387 $hasEmailValue = true;
389 $eId = $module . $widget_id;
390 if(isset($_REQUEST[$eId . 'emailAddressPrimaryFlag'])) {
391 $primaryValue = $_REQUEST[$eId . 'emailAddressPrimaryFlag'];
392 } else if(isset($_REQUEST[$module . 'emailAddressPrimaryFlag'])) {
393 $primaryValue = $_REQUEST[$module . 'emailAddressPrimaryFlag'];
396 $optOutValues = array();
397 if(isset($_REQUEST[$eId .'emailAddressOptOutFlag'])) {
398 $optOutValues = $_REQUEST[$eId .'emailAddressOptOutFlag'];
399 } else if(isset($_REQUEST[$module . 'emailAddressOptOutFlag'])) {
400 $optOutValues = $_REQUEST[$module . 'emailAddressOptOutFlag'];
403 $invalidValues = array();
404 if(isset($_REQUEST[$eId .'emailAddressInvalidFlag'])) {
405 $invalidValues = $_REQUEST[$eId .'emailAddressInvalidFlag'];
406 } else if(isset($_REQUEST[$module . 'emailAddressInvalidFlag'])) {
407 $invalidValues = $_REQUEST[$module . 'emailAddressInvalidFlag'];
410 $deleteValues = array();
411 if(isset($_REQUEST[$eId .'emailAddressDeleteFlag'])) {
412 $deleteValues = $_REQUEST[$eId .'emailAddressDeleteFlag'];
413 } else if(isset($_REQUEST[$module . 'emailAddressDeleteFlag'])) {
414 $deleteValues = $_REQUEST[$module . 'emailAddressDeleteFlag'];
417 // prep from form save
418 $primaryField = $primary;
422 if($fromRequest && empty($primary) && isset($primaryValue)) {
423 $primaryField = $primaryValue;
426 if($fromRequest && empty($replyTo)) {
427 if(isset($_REQUEST[$eId .'emailAddressReplyToFlag'])) {
428 $replyToField = $_REQUEST[$eId .'emailAddressReplyToFlag'];
429 } else if(isset($_REQUEST[$module . 'emailAddressReplyToFlag'])) {
430 $replyToField = $_REQUEST[$module . 'emailAddressReplyToFlag'];
433 if($fromRequest && empty($new_addrs)) {
434 foreach($_REQUEST as $k => $v) {
435 if(preg_match('/'.$eId.'emailAddress[0-9]+$/i', $k) && !empty($v)) {
441 if($fromRequest && empty($new_addrs)) {
442 foreach($_REQUEST as $k => $v) {
443 if(preg_match('/'.$eId.'emailAddressVerifiedValue[0-9]+$/i', $k) && !empty($v)) {
444 $validateFlag = str_replace("Value", "Flag", $k);
445 if (isset($_REQUEST[$validateFlag]) && $_REQUEST[$validateFlag] == "true")
451 //empty the addresses array if the post happened from email address widget.
452 if($post_from_email_address_widget) {
453 $this->addresses=array(); //this gets populated during retrieve of the contact bean.
455 $optOutValues = array();
456 $invalidValues = array();
457 foreach($new_addrs as $k=>$email) {
458 preg_match('/emailAddress([0-9])+$/', $k, $matches);
459 $count = $matches[1];
460 $result = $this->db->query("SELECT opt_out, invalid_email from email_addresses where email_address_caps = '" . strtoupper($email) . "'");
461 if(!empty($result)) {
462 $row=$this->db->fetchByAssoc($result);
463 if(!empty($row['opt_out'])) {
464 $optOutValues[$k] = "emailAddress$count";
466 if(!empty($row['invalid_email'])) {
467 $invalidValues[$k] = "emailAddress$count";
472 // Re-populate the addresses class variable if we have new address(es).
473 if (!empty($new_addrs)) {
474 foreach($new_addrs as $k => $reqVar) {
475 //$key = preg_match("/^$eId/s", $k) ? substr($k, strlen($eId)) : $k;
476 $reqVar = trim($reqVar);
477 if(strpos($k, 'emailAddress') !== false) {
478 if(!empty($reqVar) && !in_array($k, $deleteValues)) {
479 $primary = ($k == $primaryValue) ? true : false;
480 $replyTo = ($k == $replyToField) ? true : false;
481 $invalid = (in_array($k, $invalidValues)) ? true : false;
482 $optOut = (in_array($k, $optOutValues)) ? true : false;
483 $this->addAddress(trim($new_addrs[$k]), $primary, $replyTo, $invalid, $optOut);
490 }//End of Widget for loop
493 //If no widgets, set addresses array to empty
494 if($post_from_email_address_widget && !$hasEmailValue) {
495 $this->addresses = array();
500 * Preps internal array structure for email addresses
501 * @param string $addr Email address
502 * @param bool $primary Default false
503 * @param bool $replyTo Default false
505 function addAddress($addr, $primary=false, $replyTo=false, $invalid=false, $optOut=false) {
506 $addr = html_entity_decode($addr, ENT_QUOTES);
507 if(preg_match($this->regex, $addr)) {
508 $primaryFlag = ($primary) ? '1' : '0';
509 $replyToFlag = ($replyTo) ? '1' : '0';
510 $invalidFlag = ($invalid) ? '1' : '0';
511 $optOutFlag = ($optOut) ? '1' : '0';
515 // If we have such address already, remove it and add new one in.
516 foreach ($this->addresses as $k=>$address) {
517 if ($address['email_address'] == $addr) {
518 unset($this->addresses[$k]);
519 } elseif ($primary && $address['primary_address'] == '1') {
520 // We should only have one primary. If we are adding a primary but
521 // we find an existing primary, reset this one's primary flag.
522 $address['primary_address'] = '0';
526 $this->addresses[] = array(
527 'email_address' => $addr,
528 'primary_address' => $primaryFlag,
529 'reply_to_address' => $replyToFlag,
530 'invalid_email' => $invalidFlag,
531 'opt_out' => $optOutFlag,
534 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: address did not validate [ {$addr} ]");
539 * Updates invalid_email and opt_out flags for each address
541 function updateFlags() {
542 if(!empty($this->addresses)) {
543 foreach($this->addresses as $addressMeta) {
544 if(isset($addressMeta['email_address']) && !empty($addressMeta['email_address'])) {
545 $address = $this->_cleanAddress($addressMeta['email_address']);
547 $q = "SELECT * FROM email_addresses WHERE email_address = '{$address}'";
548 $r = $this->db->query($q);
549 $a = $this->db->fetchByAssoc($r);
552 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']) {
553 $qUpdate = "UPDATE email_addresses SET invalid_email = {$addressMeta['invalid_email']}, opt_out = {$addressMeta['opt_out']}, date_modified = '".TimeDate::getInstance()->nowDb()."' WHERE id = '{$a['id']}'";
554 $rUpdate = $this->db->query($qUpdate);
562 public function splitEmailAddress($addr)
564 $email = $this->_cleanAddress($addr);
565 if(!preg_match($this->regex, $email)) {
566 $email = ''; // remove bad email addr
568 $name = trim(str_replace(array($email, '<', '>', '"', "'"), '', $addr));
569 return array("name" => $name, "email" => strtolower($email));
574 * Normalizes an RFC-clean email address, returns a string that is the email address only
575 * @param string $addr Dirty email address
576 * @return string clean email address
578 function _cleanAddress($addr) {
579 $addr = trim(from_html($addr));
581 if(strpos($addr, "<") !== false && strpos($addr, ">") !== false) {
582 $address = trim(substr($addr, strrpos($addr, "<") +1, strrpos($addr, ">") - strrpos($addr, "<") -1));
584 $address = trim($addr);
591 * preps a passed email address for email address storage
592 * @param array $addr Address in focus, must be RFC compliant
593 * @return string $id email_addresses ID
595 function getEmailGUID($addr) {
596 $address = $this->_cleanAddress($addr);
597 $addressCaps = strtoupper($address);
599 $q = "SELECT id FROM email_addresses WHERE email_address_caps = '{$addressCaps}'";
600 $r = $this->db->query($q);
601 $a = $this->db->fetchByAssoc($r);
603 if(!empty($a) && !empty($a['id'])) {
607 if(!empty($address)){
608 $guid = create_guid();
609 $address = $GLOBALS['db']->quote($address);
610 $addressCaps = $GLOBALS['db']->quote($addressCaps);
611 $now = TimeDate::getInstance()->nowDb();
612 $qa = "INSERT INTO email_addresses (id, email_address, email_address_caps, date_created, date_modified, deleted)
613 VALUES('{$guid}', '{$address}', '{$addressCaps}', '$now', '$now', 0)";
614 $ra = $this->db->query($qa);
620 function AddUpdateEmailAddress($addr,$invalid=0,$opt_out=0) {
622 $address = $this->_cleanAddress($addr);
623 $addressCaps = strtoupper($this->db->quote($address));
625 $q = "SELECT * FROM email_addresses WHERE email_address_caps = '{$addressCaps}' and deleted=0";
626 $r = $this->db->query($q);
627 $a = $this->db->fetchByAssoc($r);
628 if(!empty($a) && !empty($a['id'])) {
629 //verify the opt out and invalid flags.
630 //bug# 39378- did not allow change of case of an email address
631 if ($a['invalid_email'] != $invalid or $a['opt_out'] != $opt_out or strcasecmp(trim($a['email_address']), trim($address))==0) {
632 $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']}'";
633 $upd_r= $this->db->query($upd_q);
638 if(!empty($address)){
639 $guid = create_guid();
640 $address = $GLOBALS['db']->quote($address);
641 $addressCaps = $GLOBALS['db']->quote($addressCaps);
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='')
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='') {
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);