]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SugarEmailAddress/SugarEmailAddress.php
Release 6.2.0
[Github/sugarcrm.git] / include / SugarEmailAddress / SugarEmailAddress.php
1 <?php
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.
6  * 
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.
13  * 
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
17  * details.
18  * 
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
22  * 02110-1301 USA.
23  * 
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.
26  * 
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.
30  * 
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  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description:
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42  * Reserved. Contributor(s): ______________________________________..
43  *********************************************************************************/
44
45
46 require_once("include/JSON.php");
47
48
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';
54
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;
59     var $db;
60     var $smarty;
61     var $addresses = array(); // array of emails
62     var $view = '';
63
64     static $count = 0;
65
66     /**
67      * Sole constructor
68      */
69     function SugarEmailAddress() {
70         parent::SugarBean();
71         $this->index = self::$count;
72         self::$count++;
73     }
74
75     /**
76      * Legacy email address handling.  This is to allow support for SOAP or customizations
77      * @param string $id
78      * @param string $module
79      */
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;
86
87                 $isPrimary = true;
88                 for($i = 1; $i <= 10; $i++){
89                     $email = 'email'.$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);
96                         $isPrimary = false;
97                     }
98                 }
99             }
100         }
101         $this->populateAddresses($bean->id, $bean->module_dir, array(),'');
102         if(isset($_REQUEST) && isset($_REQUEST['useEmailWidget'])) {
103             $this->populateLegacyFields($bean);
104         }
105     }
106
107     /**
108      * Fills standard email1 legacy fields
109      * @param string id
110      * @param string module
111      * @return object
112      */
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
118         return;
119     }
120
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)
127                 break;
128             if ($address['primary_address'] == 1 && !$primary_found) {
129                 $primary_index = $k;
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;
137             }
138         }
139
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'];
146             }
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'];
154             }
155         }
156     }
157
158     /**
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
166      */
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);
170         }
171
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;
180         }
181
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
188
189                     //verify linkage and flags.
190                     $upd_eabr="";
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']}'";
194                         }
195
196                         unset($current_links[$emailId]);
197                     } else {
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)";
200                     }
201
202                     if (!empty($upd_eabr)) {
203                         $r2 = $this->db->query($upd_eabr);
204                     }
205                 }
206             }
207         }
208
209         //delete link to dropped email address.
210         if (!empty($current_links)) {
211
212             $delete="";
213             foreach ($current_links as $eabr) {
214
215                 $delete.=empty($delete) ? "'".$eabr['id'] . "' " : ",'" . $eabr['id'] . "'";
216             }
217
218             $eabr_unlink="update email_addr_bean_rel set deleted=1 where id in ({$delete})";
219             $this->db->query($eabr_unlink);
220         }
221         return;
222     }
223
224     /**
225      * returns the number of email addresses found for a specifed bean
226      *
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
231      */
232     function getCountEmailAddressByBean(
233         $email,
234         $bean,
235         $addresstype
236         )
237     {
238         $emailCaps = strtoupper(trim($email));
239         if(empty($emailCaps))
240             return 0;
241
242         $q = "SELECT *
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 ";
251
252         $r = $this->db->query($q);
253
254         // do it this way to make the count accurate in oracle
255         $i = 0;
256         while ($this->db->fetchByAssoc($r)) ++$i;
257
258         return $i;
259     }
260
261     /**
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
265      */
266     function getRelatedId($email, $module) {
267         $email = trim(strtoupper($email));
268         $module = ucfirst($module);
269
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";
273
274         $r = $this->db->query($q, true);
275
276         $retArr = array();
277         while($a = $this->db->fetchByAssoc($r)) {
278             $retArr[] = $a['bean_id'];
279         }
280         if(count($retArr) > 0) {
281             return $retArr;
282         } else {
283             return false;
284         }
285     }
286
287     /**
288      * returns a collection of beans matching the email address
289      * @param string $email Address to match
290      * @return array
291      */
292     function getBeansByEmailAddress($email) {
293         global $beanList;
294         global $beanFiles;
295
296         $ret = array();
297
298         $email = trim($email);
299
300         if(empty($email)) {
301             return array();
302         }
303
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);
308
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']];
312
313                 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
314                     if(!class_exists($className)) {
315                         require_once($beanFiles[$className]);
316                     }
317
318                     $bean = new $className();
319                     $bean->retrieve($a['bean_id']);
320
321                     $ret[] = $bean;
322                 } else {
323                     $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class file for [ {$className} ]");
324                 }
325             } else {
326                 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class [ {$a['bean_module']} ]");
327             }
328         }
329
330         return $ret;
331     }
332
333     /**
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
341      */
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;
346
347         $post_from_email_address_widget = (isset($_REQUEST) && isset($_REQUEST['emailAddressWidget'])) ? true : false;
348         $primaryValue = $primary;
349         $widgetCount = 0;
350         $hasEmailValue = false;
351
352         if (isset($_REQUEST) && isset($_REQUEST[$module .'_email_widget_id'])) {
353
354             $fromRequest = false;
355             // determine which array to process
356             foreach($_REQUEST as $k => $v) {
357                 if(strpos($k, 'emailAddress') !== false) {
358                    $fromRequest = true;
359                    break;
360                 }
361             }
362             $widget_id = $_REQUEST[$module .'_email_widget_id'];
363
364
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]))
367             {
368                 if (empty($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount])) {
369                     $widgetCount++;
370                     continue;
371                 }
372
373                 $hasEmailValue = true;
374
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'];
380                 }
381
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'];
387                 }
388
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'];
394                 }
395
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'];
401                 }
402
403                 // prep from form save
404                 $primaryField = $primary;
405                 $replyToField = '';
406                 $invalidField = '';
407                 $optOutField = '';
408                 if($fromRequest && empty($primary) && isset($primaryValue)) {
409                     $primaryField = $primaryValue;
410                 }
411
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'];
417                     }
418                 }
419                 if($fromRequest && empty($new_addrs)) {
420                     foreach($_REQUEST as $k => $v) {
421                         if(preg_match('/'.$eId.'emailAddress[0-9]+$/i', $k) && !empty($v)) {
422                             $new_addrs[$k] = $v;
423                         }
424                     }
425                 }
426
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")
432                               $new_addrs[$k] = $v;
433                         }
434                     }
435                 }
436
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.
440                 } else {
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";
451                           }
452                           if(!empty($row['invalid_email'])) {
453                              $invalidValues[$k] = "emailAddress$count";
454                           }
455                        }
456                     }
457                 }
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);
470                             }
471                         }
472                     } //foreach
473                 }
474
475                 $widgetCount++;
476             }//End of Widget for loop
477         }
478
479         //If no widgets, set addresses array to empty
480         if($post_from_email_address_widget && !$hasEmailValue) {
481            $this->addresses = array();
482         }
483     }
484
485     /**
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
490      */
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';
498
499             $addr = trim($addr);
500
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';
509                 }
510             }
511
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,
518             );
519         } else {
520             $GLOBALS['log']->fatal("SUGAREMAILADDRESS: address did not validate [ {$addr} ]");
521         }
522     }
523
524     /**
525      * Updates invalid_email and opt_out flags for each address
526      */
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']);
532
533                     $q = "SELECT * FROM email_addresses WHERE email_address = '{$address}'";
534                     $r = $this->db->query($q);
535                     $a = $this->db->fetchByAssoc($r);
536
537                     if(!empty($a)) {
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);
541                         }
542                     }
543                 }
544             }
545         }
546     }
547
548     public function splitEmailAddress($addr)
549     {
550         $email = $this->_cleanAddress($addr);
551         if(!preg_match($this->regex, $email)) {
552             $email = ''; // remove bad email addr
553         }
554         $name = trim(str_replace(array($email, '<', '>', '"', "'"), '', $addr));
555         return array("name" => $name, "email" => strtolower($email));
556     }
557
558     /**
559      * PRIVATE UTIL
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
563      */
564     function _cleanAddress($addr) {
565         $addr = trim(from_html($addr));
566
567         if(strpos($addr, "<") !== false && strpos($addr, ">") !== false) {
568             $address = trim(substr($addr, strrpos($addr, "<") +1, strrpos($addr, ">") - strrpos($addr, "<") -1));
569         } else {
570             $address = trim($addr);
571         }
572
573         return $address;
574     }
575
576     /**
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
580      */
581     function getEmailGUID($addr) {
582         $address = $this->_cleanAddress($addr);
583         $addressCaps = strtoupper($address);
584
585         $q = "SELECT id FROM email_addresses WHERE email_address_caps = '{$addressCaps}'";
586         $r = $this->db->query($q);
587         $a = $this->db->fetchByAssoc($r);
588
589         if(!empty($a) && !empty($a['id'])) {
590             return $a['id'];
591         } else {
592             $guid = '';
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);
601             }
602             return $guid;
603         }
604     }
605
606     function AddUpdateEmailAddress($addr,$invalid=0,$opt_out=0) {
607
608         $address = $this->_cleanAddress($addr);
609         $addressCaps = strtoupper($this->db->quoteForEmail($address));
610
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);
620             }
621             return $a['id'];
622         } else {
623             $guid = '';
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);
632             }
633             return $guid;
634         }
635     }
636
637     /**
638      * Returns Primary or newest email address
639      * @param object $focus Object in focus
640      * @return string email
641      */
642     function getPrimaryAddress($focus,$parent_id=null,$parent_type=null) {
643
644         $parent_type=empty($parent_type) ? $focus->module_dir : $parent_type;
645         $parent_id=empty($parent_id) ? $focus->id : $parent_id;
646
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}'
651                 AND ear.deleted = 0
652                 ORDER BY ear.primary_address DESC";
653         $r = $this->db->limitQuery($q, 0, 1);
654         $a = $this->db->fetchByAssoc($r);
655
656         if(isset($a['email_address'])) {
657             return $a['email_address'];
658         }
659         return '';
660     }
661
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}'
667                 AND ear.deleted = 0
668                 ORDER BY ear.reply_to_address DESC";
669         $r = $this->db->query($q);
670         $a = $this->db->fetchByAssoc($r);
671
672         if(isset($a['email_address'])) {
673             return $a['email_address'];
674         }
675         return '';
676     }
677
678     /**
679      * Returns all email addresses by parent's GUID
680      * @param string $id Parent's GUID
681      * @param string $module Parent's module
682      * @return array
683      */
684     function getAddressesByGUID($id, $module) {
685         $return = array();
686         $module = $this->getCorrectedModule($module);
687
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}'
693                 AND ear.deleted = 0
694                 ORDER BY ear.reply_to_address, ear.primary_address DESC";
695         $r = $this->db->query($q);
696
697         while($a = $this->db->fetchByAssoc($r)) {
698             $return[] = $a;
699         }
700
701         return $return;
702     }
703
704     /**
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
710      */
711     function getEmailAddressWidgetEditView($id, $module, $asMetadata=false, $tpl='',$tabindex='')
712     {
713         if ( !($this->smarty instanceOf Sugar_Smarty ) )
714             $this->smarty = new Sugar_Smarty();
715
716         global $app_strings, $dictionary, $beanList;
717
718         $prefill = 'false';
719
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'];
727         }
728         $prefillDataArr = array();
729         if(!empty($id)) {
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';
736             $count = 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
745                                         );
746                    $key = $module . $widget_id . 'emailAddress' . ++$count;
747             } //while
748         }
749
750         if(!empty($prefillDataArr)) {
751             $json = new JSON(JSON_LOOSE_TYPE);
752             $prefillData = $json->encode($prefillDataArr);
753             $prefill = !empty($prefillDataArr) ? 'true' : 'false';
754         }
755
756         $required = false;
757         $vardefs = $dictionary[$beanList[$passedModule]]['fields'];
758         if (!empty($vardefs['email1']) && isset($vardefs['email1']['required']) && $vardefs['email1']['required'])
759             $required = true;
760         $this->smarty->assign('required', $required);
761
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');
770         $form = $this->view;
771
772         if ($this->view == "QuickCreate")
773         $form = 'form_'.$this->view .'_'.$module;
774         $this->smarty->assign('emailView', $form);
775
776         if($module == 'Users') {
777             $this->smarty->assign('useReplyTo', true);
778         } else {
779             $this->smarty->assign('useOptOut', true);
780             $this->smarty->assign('useInvalid', true);
781         }
782
783         $template = empty($tpl) ? "include/SugarEmailAddress/templates/forEditView.tpl" : $tpl;
784         $newEmail = $this->smarty->fetch($template);
785
786
787         if($asMetadata) {
788             // used by Email 2.0
789             $ret = array();
790             $ret['prefillData'] = $prefillDataArr;
791             $ret['html'] = $newEmail;
792
793             return $ret;
794         }
795
796         return $newEmail;
797     }
798
799
800     /**
801      * Returns the HTML/JS for the EmailAddress widget
802      * @param object $focus Bean in focus
803      * @return string HTML/JS for widget
804      */
805     function getEmailAddressWidgetDetailView($focus, $tpl='')
806     {
807         if ( !($this->smarty instanceOf Sugar_Smarty ) )
808             $this->smarty = new Sugar_Smarty();
809
810         global $app_strings;
811         global $current_user;
812         $assign = array();
813         if(empty($focus->id))return '';
814         $prefillData = $this->getAddressesByGUID($focus->id, $focus->module_dir);
815
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;
822
823             $assign[] = array('key' => $key, 'address' => $current_user->getEmailLink2($addressItem['email_address'], $focus).$addressItem['email_address']."</a>");
824         }
825
826
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);
831         return $return;
832     }
833
834
835     /**
836      * getEmailAddressWidgetDuplicatesView($focus)
837      * @param object $focus Bean in focus
838      * @return string HTML that contains hidden input values based off of HTML request
839      */
840     function getEmailAddressWidgetDuplicatesView($focus)
841     {
842         if ( !($this->smarty instanceOf Sugar_Smarty ) )
843             $this->smarty = new Sugar_Smarty();
844
845         $count = 0;
846         $emails = array();
847         $primary = null;
848         $optOut = array();
849         $invalid = array();
850         $mod = isset($focus) ? $focus->module_dir : "";
851
852         $widget_id = $_POST[$mod .'_email_widget_id'];
853         $this->smarty->assign('email_widget_id',$widget_id);
854         $this->smarty->assign('emailAddressWidget',$_POST['emailAddressWidget']);
855
856         if(isset($_POST[$mod . $widget_id . 'emailAddressPrimaryFlag'])) {
857            $primary = $_POST[$mod . $widget_id . 'emailAddressPrimaryFlag'];
858         }
859
860         while(isset($_POST[$mod . $widget_id . "emailAddress" . $count])) {
861             $emails[] = $_POST[$mod . $widget_id . 'emailAddress' . $count];
862             $count++;
863         }
864
865         if($count == 0) {
866            return "";
867         }
868
869         if(isset($_POST[$mod . $widget_id . 'emailAddressOptOutFlag'])) {
870            foreach($_POST[$mod . $widget_id . 'emailAddressOptOutFlag'] as $v) {
871               $optOut[] = $v;
872            }
873         }
874
875         if(isset($_POST[$mod . $widget_id . 'emailAddressInvalidFlag'])) {
876            foreach($_POST[$mod . $widget_id . 'emailAddressInvalidFlag'] as $v) {
877               $invalid[] = $v;
878            }
879         }
880
881         if(isset($_POST[$mod . $widget_id . 'emailAddressReplyToFlag'])) {
882            foreach($_POST[$mod . $widget_id . 'emailAddressReplyToFlag'] as $v) {
883               $replyTo[] = $v;
884            }
885         }
886
887         if(isset($_POST[$mod . $widget_id . 'emailAddressDeleteFlag'])) {
888            foreach($_POST[$mod . $widget_id . 'emailAddressDeleteFlag'] as $v) {
889               $delete[] = $v;
890            }
891         }
892
893         while(isset($_POST[$mod . $widget_id . "emailAddressVerifiedValue" . $count])) {
894             $verified[] = $_POST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count];
895             $count++;
896         }
897
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);
906
907         return $this->smarty->fetch("include/SugarEmailAddress/templates/forDuplicatesView.tpl");
908     }
909
910     /**
911      * getFormBaseURL
912      *
913      */
914     function getFormBaseURL($focus) {
915         $get = "";
916         $count = 0;
917         $mod = isset($focus) ? $focus->module_dir : "";
918
919         $widget_id = $_POST[$mod .'_email_widget_id'];
920         $get .= '&' . $mod . '_email_widget_id='. $widget_id;
921         $get .= '&emailAddressWidget='.$_POST['emailAddressWidget'];
922
923         while(isset($_REQUEST[$mod . $widget_id . 'emailAddress' . $count])) {
924               $get .= "&" . $mod . $widget_id . "emailAddress" . $count . "=" . urlencode($_REQUEST[$mod . $widget_id . 'emailAddress' . $count]);
925               $count++;
926         } //while
927
928         while(isset($_REQUEST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count])) {
929               $get .= "&" . $mod . $widget_id . "emailAddressVerifiedValue" . $count . "=" . urlencode($_REQUEST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count]);
930               $count++;
931         } //while
932
933         $options = array('emailAddressPrimaryFlag', 'emailAddressOptOutFlag', 'emailAddressInvalidFlag', 'emailAddressDeleteFlag', 'emailAddressReplyToFlag');
934
935         foreach($options as $option) {
936             $count = 0;
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;
942                       $count++;
943                    } //foreach
944                } else {
945                    $get .= "&" . $optionIdentifier . "=" . $_REQUEST[$optionIdentifier];
946                }
947             } //if
948         } //foreach
949         return $get;
950
951     }
952
953     function setView($view) {
954        $this->view = $view;
955     }
956
957 /**
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
961  */
962     function getCorrectedModule(&$module) {
963         return ($module == "Employees")? "Users" : $module;
964     }
965 } // end class def
966
967
968 /**
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
974  * @return string
975  */
976 function getEmailAddressWidget($focus, $field, $value, $view, $tabindex='') {
977     $sea = new SugarEmailAddress();
978     $sea->setView($view);
979
980         if($view == 'EditView' || $view == 'QuickCreate' || $view == 'ConvertLead') {
981             $module = $focus->module_dir;
982             if ($view == 'ConvertLead' && $module == "Contacts")  $module = "Leads";
983
984             return $sea->getEmailAddressWidgetEditView($focus->id, $module, false,'',$tabindex);
985         }
986
987     return $sea->getEmailAddressWidgetDetailView($focus);
988 }
989
990 ?>