]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SugarEmailAddress/SugarEmailAddress.php
Release 6.5.5
[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-2012 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     private $stateBeforeWorkflow;
64
65     static $count = 0;
66
67     /**
68      * Sole constructor
69      */
70     function SugarEmailAddress() {
71         parent::SugarBean();
72         $this->index = self::$count;
73         self::$count++;
74     }
75
76     /**
77      * Legacy email address handling.  This is to allow support for SOAP or customizations
78      * @param string $id
79      * @param string $module
80      */
81     function handleLegacySave($bean, $prefix = "") {
82         if(!isset($_REQUEST) || !isset($_REQUEST['useEmailWidget'])) {
83             if (empty($this->addresses) || !isset($_REQUEST['massupdate'])) {
84                 $this->addresses = array();
85                 $optOut = (isset($bean->email_opt_out) && $bean->email_opt_out == "1") ? true : false;
86                 $invalid = (isset($bean->invalid_email) && $bean->invalid_email == "1") ? true : false;
87
88                 $isPrimary = true;
89                 for($i = 1; $i <= 10; $i++){
90                     $email = 'email'.$i;
91                     if(isset($bean->$email) && !empty($bean->$email)){
92                         $opt_out_field = $email.'_opt_out';
93                         $invalid_field = $email.'_invalid';
94                         $field_optOut = (isset($bean->$opt_out_field)) ? $bean->$opt_out_field : $optOut;
95                         $field_invalid = (isset($bean->$invalid_field)) ? $bean->$invalid_field : $invalid;
96                         $this->addAddress($bean->$email, $isPrimary, false, $field_invalid, $field_optOut);
97                         $isPrimary = false;
98                     }
99                 }
100             }
101         }
102         $this->populateAddresses($bean->id, $bean->module_dir, array(),'');
103         if(isset($_REQUEST) && isset($_REQUEST['useEmailWidget'])) {
104             $this->populateLegacyFields($bean);
105         }
106     }
107
108     /**
109      * Fills standard email1 legacy fields
110      * @param string id
111      * @param string module
112      * @return object
113      */
114     function handleLegacyRetrieve(&$bean) {
115         $module_dir = $this->getCorrectedModule($bean->module_dir);
116         $this->addresses = $this->getAddressesByGUID($bean->id, $module_dir);
117         $this->populateLegacyFields($bean);
118         if (isset($bean->email1) && !isset($bean->fetched_row['email1'])) {
119             $bean->fetched_row['email1'] = $bean->email1;
120         }
121
122         return;
123     }
124
125     function populateLegacyFields(&$bean){
126         $primary_found = false;
127         $alternate_found = false;
128         $alternate2_found = false;
129         foreach($this->addresses as $k=>$address) {
130             if ($primary_found && $alternate_found)
131                 break;
132             if ($address['primary_address'] == 1 && !$primary_found) {
133                 $primary_index = $k;
134                 $primary_found = true;
135             } elseif (!$alternate_found) {
136                 $alternate_index = $k;
137                 $alternate_found = true;
138             } elseif (!$alternate2_found){
139                 $alternate2_index = $k;
140                 $alternate2_found = true;
141             }
142         }
143
144         if ($primary_found) {
145             $bean->email1 = $this->addresses[$primary_index]['email_address'];
146             $bean->email_opt_out = $this->addresses[$primary_index]['opt_out'];
147             $bean->invalid_email = $this->addresses[$primary_index]['invalid_email'];
148             if ($alternate_found) {
149                 $bean->email2 = $this->addresses[$alternate_index]['email_address'];
150             }
151         } elseif ($alternate_found) {
152             // Use the first found alternate as email1.
153             $bean->email1 = $this->addresses[$alternate_index]['email_address'];
154             $bean->email_opt_out = $this->addresses[$alternate_index]['opt_out'];
155             $bean->invalid_email = $this->addresses[$alternate_index]['invalid_email'];
156             if ($alternate2_found) {
157                 $bean->email2 = $this->addresses[$alternate2_index]['email_address'];
158             }
159         }
160     }
161
162     /**
163      * Saves email addresses for a parent bean
164      * @param string $id Parent bean ID
165      * @param string $module Parent bean's module
166      * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
167      * @param string $primary GUID of primary address
168      * @param string $replyTo GUID of reply-to address
169      * @param string $invalid GUID of invalid address
170      */
171     function save($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='', $in_workflow=false) {
172         if(empty($this->addresses) || $in_workflow){
173             $this->populateAddresses($id, $module, $new_addrs,$primary);
174         }
175
176         //find all email addresses..
177         $current_links=array();
178         // Need to correct this to handle the Employee/User split
179         $module = $this->getCorrectedModule($module);
180         $q2="select *  from email_addr_bean_rel eabr WHERE eabr.bean_id = '".$this->db->quote($id)."' AND eabr.bean_module = '".$this->db->quote($module)."' and eabr.deleted=0";
181         $r2 = $this->db->query($q2);
182         while(($row2=$this->db->fetchByAssoc($r2)) != null ) {
183             $current_links[$row2['email_address_id']]=$row2;
184         }
185
186         $isConversion = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? true : false;
187
188         if (!empty($this->addresses)) {
189             // insert new relationships and create email address record, if they don't exist
190             foreach($this->addresses as $address) {
191                 if(!empty($address['email_address'])) {
192                     $guid = create_guid();
193                     $emailId = $this->AddUpdateEmailAddress($address['email_address'],
194                                                             $address['invalid_email'],
195                                                             $address['opt_out'],
196                                                             isset($address['email_address_id']) ? 
197                                                                 $address['email_address_id'] : 
198                                                                 null);// this will save the email address if not found
199
200                     //verify linkage and flags.
201                     $upd_eabr="";
202                     if (isset($current_links[$emailId])) {
203                         if (!$isConversion) { // do not update anything if this is for lead conversion
204                         if ($address['primary_address'] != $current_links[$emailId]['primary_address'] or $address['reply_to_address'] != $current_links[$emailId]['reply_to_address'] ) {
205                             $upd_eabr="UPDATE email_addr_bean_rel SET primary_address='".$this->db->quote($address['primary_address'])."', reply_to_address='".$this->db->quote($address['reply_to_address'])."' WHERE id='".$this->db->quote($current_links[$emailId]['id'])."'";
206                         }
207
208                         unset($current_links[$emailId]);
209                         }
210                     } else {
211                         $primary = $address['primary_address'];
212                         if (!empty($current_links) && $isConversion) {
213                             foreach ($current_links as $eabr) {
214                                 if ($eabr['primary_address'] == 1) {
215                                     // for lead conversion, if there is already a primary email, do not insert another primary email
216                                     $primary = 0;
217                                     break;
218                                 }
219                             }
220                         }
221                         $now = $this->db->now();
222                         $upd_eabr = "INSERT INTO email_addr_bean_rel (id, email_address_id,bean_id, bean_module,primary_address,reply_to_address,date_created,date_modified,deleted) VALUES('".$this->db->quote($guid)."', '".$this->db->quote($emailId)."', '".$this->db->quote($id)."', '".$this->db->quote($module)."', ".intval($primary).", ".intval($address['reply_to_address']).", $now, $now, 0)";
223                     }
224
225                     if (!empty($upd_eabr)) {
226                         $r2 = $this->db->query($upd_eabr);
227                     }
228                 }
229             }
230         }
231
232         //delete link to dropped email address.
233         // for lead conversion, do not delete email addresses
234         if (!empty($current_links) && !$isConversion) {
235
236             $delete="";
237             foreach ($current_links as $eabr) {
238
239                 $delete.=empty($delete) ? "'".$this->db->quote($eabr['id']) . "' " : ",'" . $this->db->quote($eabr['id']) . "'";
240             }
241
242             $eabr_unlink="update email_addr_bean_rel set deleted=1 where id in ({$delete})";
243             $this->db->query($eabr_unlink);
244         }
245         $this->stateBeforeWorkflow = null;
246         return;
247     }
248
249     /**
250      * returns the number of email addresses found for a specifed bean
251      *
252      * @param  string $email       Address to match
253      * @param  object $bean        Bean to query against
254      * @param  string $addresstype Optional, pass a 1 to query against the primary address, 0 for the other addresses
255      * @return int                 Count of records found
256      */
257     function getCountEmailAddressByBean(
258         $email,
259         $bean,
260         $addresstype
261         )
262     {
263         $emailCaps = strtoupper(trim($email));
264         if(empty($emailCaps))
265             return 0;
266
267         $q = "SELECT *
268                 FROM email_addr_bean_rel eabl JOIN email_addresses ea
269                         ON (ea.id = eabl.email_address_id)
270                     JOIN {$bean->table_name} bean
271                         ON (eabl.bean_id = bean.id)
272                 WHERE ea.email_address_caps = '".$this->db->quote($emailCaps)."'
273                     and eabl.bean_module = '".$this->db->quote($bean->module_dir)."'
274                     and eabl.primary_address = '".$this->db->quote($addresstype)."'
275                     and eabl.deleted=0 ";
276
277         $r = $this->db->query($q);
278
279         // do it this way to make the count accurate in oracle
280         $i = 0;
281         while ($this->db->fetchByAssoc($r)) ++$i;
282
283         return $i;
284     }
285
286     /**
287      * This function returns a contact or user ID if a matching email is found
288      * @param   $email      the email address to match
289      * @param   $table      which table to query
290      */
291     function getRelatedId($email, $module) {
292         $email = $this->db->quote(trim(strtoupper($email)));
293         $module = $this->db->quote(ucfirst($module));
294
295         $q = "SELECT bean_id FROM email_addr_bean_rel eabr
296                 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
297                 WHERE bean_module = '$module' AND ea.email_address_caps = '$email' AND eabr.deleted=0";
298
299         $r = $this->db->query($q, true);
300
301         $retArr = array();
302         while($a = $this->db->fetchByAssoc($r)) {
303             $retArr[] = $a['bean_id'];
304         }
305         if(count($retArr) > 0) {
306             return $retArr;
307         } else {
308             return false;
309         }
310     }
311
312     /**
313      * returns a collection of beans matching the email address
314      * @param string $email Address to match
315      * @return array
316      */
317     function getBeansByEmailAddress($email) {
318         global $beanList;
319         global $beanFiles;
320
321         $ret = array();
322
323         $email = trim($email);
324
325         if(empty($email)) {
326             return array();
327         }
328
329         $emailCaps = "'".$this->db->quote(strtoupper($email))."'";
330         $q = "SELECT * FROM email_addr_bean_rel eabl JOIN email_addresses ea ON (ea.id = eabl.email_address_id)
331                 WHERE ea.email_address_caps = $emailCaps and eabl.deleted=0 ";
332         $r = $this->db->query($q);
333
334         while($a = $this->db->fetchByAssoc($r)) {
335             if(isset($beanList[$a['bean_module']]) && !empty($beanList[$a['bean_module']])) {
336                 $className = $beanList[$a['bean_module']];
337
338                 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
339                     if(!class_exists($className)) {
340                         require_once($beanFiles[$className]);
341                     }
342
343                     $bean = new $className();
344                     $bean->retrieve($a['bean_id']);
345
346                     $ret[] = $bean;
347                 } else {
348                     $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class file for [ {$className} ]");
349                 }
350             } else {
351                 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class [ {$a['bean_module']} ]");
352             }
353         }
354
355         return $ret;
356     }
357
358     /**
359      * Saves email addresses for a parent bean
360      * @param string $id Parent bean ID
361      * @param string $module Parent bean's module
362      * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
363      * @param string $primary GUID of primary address
364      * @param string $replyTo GUID of reply-to address
365      * @param string $invalid GUID of invalid address
366      */
367     function populateAddresses($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='') {
368         $module = $this->getCorrectedModule($module);
369         //One last check for the ConvertLead action in which case we need to change $module to 'Leads'
370         $module = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? 'Leads' : $module;
371
372         $post_from_email_address_widget = (isset($_REQUEST) && isset($_REQUEST['emailAddressWidget'])) ? true : false;
373         $primaryValue = $primary;
374         $widgetCount = 0;
375         $hasEmailValue = false;
376         $email_ids = array();
377
378         if (isset($_REQUEST) && isset($_REQUEST[$module .'_email_widget_id'])) {
379
380             $fromRequest = false;
381             // determine which array to process
382             foreach($_REQUEST as $k => $v) {
383                 if(strpos($k, 'emailAddress') !== false) {
384                    $fromRequest = true;
385                    break;
386                 }
387             $widget_id = $_REQUEST[$module .'_email_widget_id'];
388     }
389
390             //Iterate over the widgets for this module, in case there are multiple email widgets for this module
391             while(isset($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount]))
392             {
393                 if (empty($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount])) {
394                     $widgetCount++;
395                     continue;
396                 }
397
398                 $hasEmailValue = true;
399
400                 $eId = $module . $widget_id;
401                 if(isset($_REQUEST[$eId . 'emailAddressPrimaryFlag'])) {
402                    $primaryValue = $_REQUEST[$eId . 'emailAddressPrimaryFlag'];
403                 } else if(isset($_REQUEST[$module . 'emailAddressPrimaryFlag'])) {
404                    $primaryValue = $_REQUEST[$module . 'emailAddressPrimaryFlag'];
405                 }
406
407                 $optOutValues = array();
408                 if(isset($_REQUEST[$eId .'emailAddressOptOutFlag'])) {
409                    $optOutValues = $_REQUEST[$eId .'emailAddressOptOutFlag'];
410                 } else if(isset($_REQUEST[$module . 'emailAddressOptOutFlag'])) {
411                    $optOutValues = $_REQUEST[$module . 'emailAddressOptOutFlag'];
412                 }
413
414                 $invalidValues = array();
415                 if(isset($_REQUEST[$eId .'emailAddressInvalidFlag'])) {
416                    $invalidValues = $_REQUEST[$eId .'emailAddressInvalidFlag'];
417                 } else if(isset($_REQUEST[$module . 'emailAddressInvalidFlag'])) {
418                    $invalidValues = $_REQUEST[$module . 'emailAddressInvalidFlag'];
419                 }
420
421                 $deleteValues = array();
422                 if(isset($_REQUEST[$eId .'emailAddressDeleteFlag'])) {
423                    $deleteValues = $_REQUEST[$eId .'emailAddressDeleteFlag'];
424                 } else if(isset($_REQUEST[$module . 'emailAddressDeleteFlag'])) {
425                    $deleteValues = $_REQUEST[$module . 'emailAddressDeleteFlag'];
426                 }
427
428                 // prep from form save
429                 $primaryField = $primary;
430                 $replyToField = '';
431                 $invalidField = '';
432                 $optOutField = '';
433                 if($fromRequest && empty($primary) && isset($primaryValue)) {
434                     $primaryField = $primaryValue;
435                 }
436
437                 if($fromRequest && empty($replyTo)) {
438                     if(isset($_REQUEST[$eId .'emailAddressReplyToFlag'])) {
439                        $replyToField = $_REQUEST[$eId .'emailAddressReplyToFlag'];
440                     } else if(isset($_REQUEST[$module . 'emailAddressReplyToFlag'])) {
441                        $replyToField = $_REQUEST[$module . 'emailAddressReplyToFlag'];
442                     }
443                 }
444                 if($fromRequest && empty($new_addrs)) {
445                     foreach($_REQUEST as $k => $v) {
446                         if(preg_match('/'.$eId.'emailAddress[0-9]+$/i', $k) && !empty($v)) {
447                             $new_addrs[$k] = $v;
448                         }
449                     }
450                 }
451                 if($fromRequest && empty($email_ids)) {
452                     foreach($_REQUEST as $k => $v) {
453                         if(preg_match('/'.$eId.'emailAddressId[0-9]+$/i', $k) && !empty($v)) {
454                             $key = str_replace('emailAddressId', 'emailAddress', $k);
455                             $email_ids[$key] = $v;
456                         }
457                     }
458                 }
459
460                 if($fromRequest && empty($new_addrs)) {
461                     foreach($_REQUEST as $k => $v) {
462                         if(preg_match('/'.$eId.'emailAddressVerifiedValue[0-9]+$/i', $k) && !empty($v)) {
463                             $validateFlag = str_replace("Value", "Flag", $k);
464                             if (isset($_REQUEST[$validateFlag]) && $_REQUEST[$validateFlag] == "true")
465                               $new_addrs[$k] = $v;
466                         }
467                     }
468                 }
469
470                 //empty the addresses array if the post happened from email address widget.
471                 if($post_from_email_address_widget) {
472                     $this->addresses=array();  //this gets populated during retrieve of the contact bean.
473                 } else {
474                     $optOutValues = array();
475                     $invalidValues = array();
476                     foreach($new_addrs as $k=>$email) {
477                        preg_match('/emailAddress([0-9])+$/', $k, $matches);
478                        $count = $matches[1];
479                        $result = $this->db->query("SELECT opt_out, invalid_email from email_addresses where email_address_caps = '" . $this->db->quote(strtoupper($email)) . "'");
480                        if(!empty($result)) {
481                           $row=$this->db->fetchByAssoc($result);
482                           if(!empty($row['opt_out'])) {
483                              $optOutValues[$k] = "emailAddress$count";
484                           }
485                           if(!empty($row['invalid_email'])) {
486                              $invalidValues[$k] = "emailAddress$count";
487                           }
488                        }
489                     }
490                 }
491                 // Re-populate the addresses class variable if we have new address(es).
492                 if (!empty($new_addrs)) {
493                     foreach($new_addrs as $k => $reqVar) {
494                         //$key = preg_match("/^$eId/s", $k) ? substr($k, strlen($eId)) : $k;
495                         $reqVar = trim($reqVar);
496                         if(strpos($k, 'emailAddress') !== false) {
497                             if(!empty($reqVar) && !in_array($k, $deleteValues)) {
498                                 $email_id   = (array_key_exists($k, $email_ids)) ? $email_ids[$k] : null;
499                                 $primary    = ($k == $primaryValue) ? true : false;
500                                 $replyTo    = ($k == $replyToField) ? true : false;
501                                 $invalid    = (in_array($k, $invalidValues)) ? true : false;
502                                 $optOut     = (in_array($k, $optOutValues)) ? true : false;
503                                 $this->addAddress(trim($new_addrs[$k]), $primary, $replyTo, $invalid, $optOut, $email_id);
504                             }
505                         }
506                     } //foreach
507                 }
508
509                 $widgetCount++;
510             }//End of Widget for loop
511         }
512
513         //If no widgets, set addresses array to empty
514         if($post_from_email_address_widget && !$hasEmailValue) {
515            $this->addresses = array();
516         }
517     }
518
519     /**
520      * Preps internal array structure for email addresses
521      * @param string $addr Email address
522      * @param bool $primary Default false
523      * @param bool $replyTo Default false
524      */
525     function addAddress($addr, $primary=false, $replyTo=false, $invalid=false, $optOut=false, $email_id = null) {
526         $addr = html_entity_decode($addr, ENT_QUOTES);
527         if(preg_match($this->regex, $addr)) {
528             $primaryFlag = ($primary) ? '1' : '0';
529             $replyToFlag = ($replyTo) ? '1' : '0';
530             $invalidFlag = ($invalid) ? '1' : '0';
531             $optOutFlag = ($optOut) ? '1' : '0';
532
533             $addr = trim($addr);
534
535             // If we have such address already, remove it and add new one in.
536             foreach ($this->addresses as $k=>$address) {
537                 if ($address['email_address'] == $addr) {
538                     unset($this->addresses[$k]);
539                 } elseif ($primary && $address['primary_address'] == '1') {
540                     // We should only have one primary. If we are adding a primary but
541                     // we find an existing primary, reset this one's primary flag.
542                     $address['primary_address'] = '0';
543                 }
544             }
545
546             $this->addresses[] = array(
547                 'email_address' => $addr,
548                 'primary_address' => $primaryFlag,
549                 'reply_to_address' => $replyToFlag,
550                 'invalid_email' => $invalidFlag,
551                 'opt_out' => $optOutFlag,
552                 'email_address_id' => $email_id,
553             );
554         } else {
555             $GLOBALS['log']->fatal("SUGAREMAILADDRESS: address did not validate [ {$addr} ]");
556         }
557     }
558
559     /**
560      * Updates invalid_email and opt_out flags for each address
561      */
562     function updateFlags() {
563         if(!empty($this->addresses)) {
564             foreach($this->addresses as $addressMeta) {
565                 if(isset($addressMeta['email_address']) && !empty($addressMeta['email_address'])) {
566                     $address = $this->db->quote($this->_cleanAddress($addressMeta['email_address']));
567
568                     $q = "SELECT * FROM email_addresses WHERE email_address = '{$address}'";
569                     $r = $this->db->query($q);
570                     $a = $this->db->fetchByAssoc($r);
571
572                     if(!empty($a)) {
573                         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']) {
574                             $qUpdate = "UPDATE email_addresses SET invalid_email = ".intval($addressMeta['invalid_email']).", opt_out = ".intval($addressMeta['opt_out']).", date_modified = '".TimeDate::getInstance()->nowDb()."' WHERE id = '".$this->db->quote($a['id'])."'";
575                             $rUpdate = $this->db->query($qUpdate);
576                         }
577                     }
578                 }
579             }
580         }
581     }
582
583     public function splitEmailAddress($addr)
584     {
585         $email = $this->_cleanAddress($addr);
586         if(!preg_match($this->regex, $email)) {
587             $email = ''; // remove bad email addr
588         }
589         $name = trim(str_replace(array($email, '<', '>', '"', "'"), '', $addr));
590         return array("name" => $name, "email" => strtolower($email));
591     }
592
593     /**
594      * PRIVATE UTIL
595      * Normalizes an RFC-clean email address, returns a string that is the email address only
596      * @param string $addr Dirty email address
597      * @return string clean email address
598      */
599     function _cleanAddress($addr) {
600         $addr = trim(from_html($addr));
601
602         if(strpos($addr, "<") !== false && strpos($addr, ">") !== false) {
603             $address = trim(substr($addr, strrpos($addr, "<") +1, strrpos($addr, ">") - strrpos($addr, "<") -1));
604         } else {
605             $address = trim($addr);
606         }
607
608         return $address;
609     }
610
611     /**
612      * preps a passed email address for email address storage
613      * @param array $addr Address in focus, must be RFC compliant
614      * @return string $id email_addresses ID
615      */
616     function getEmailGUID($addr) {
617         $address = $this->db->quote($this->_cleanAddress($addr));
618         $addressCaps = strtoupper($address);
619
620         $q = "SELECT id FROM email_addresses WHERE email_address_caps = '{$addressCaps}'";
621         $r = $this->db->query($q);
622         $a = $this->db->fetchByAssoc($r);
623
624         if(!empty($a) && !empty($a['id'])) {
625             return $a['id'];
626         } else {
627             $guid = '';
628             if(!empty($address)){
629                 $guid = create_guid();
630                 $now = TimeDate::getInstance()->nowDb();
631                 $qa = "INSERT INTO email_addresses (id, email_address, email_address_caps, date_created, date_modified, deleted)
632                         VALUES('{$guid}', '{$address}', '{$addressCaps}', '$now', '$now', 0)";
633                 $ra = $this->db->query($qa);
634             }
635             return $guid;
636         }
637     }
638
639     function AddUpdateEmailAddress($addr,$invalid=0,$opt_out=0,$id=null)
640     {
641         // sanity checks to avoid SQL injection.
642         $invalid = intval($invalid);
643         $opt_out = intval($opt_out);
644
645         $address = $this->db->quote($this->_cleanAddress($addr));
646         $addressCaps = strtoupper($address);
647
648         if ($id)
649         {
650             $r = $this->db->query("SELECT * FROM email_addresses WHERE id='".$this->db->quote($id)."'");
651             $a = $this->db->fetchByAssoc($r);
652         }
653         else
654         {
655             $a = null;
656         }
657
658         if(!empty($a) && !empty($a['id'])) {
659             if ($a['invalid_email'] != $invalid ||
660                 $a['opt_out']       != $opt_out ||
661                 // bug #39378 - did not allow change of case of an email address
662                 strnatcmp(trim($a['email_address']), trim($address)) != 0)
663             {
664                 if (isset($this->stateBeforeWorkflow[$a['id']]))
665                 {
666                     $data = $this->stateBeforeWorkflow[$a['id']];
667                 }
668                 else
669                 {
670                     $data = array();
671                 }
672
673                 $upd_q = 'UPDATE ' . $this->table_name . ' ' . 
674                          'SET email_address=\'' . $address . '\', '. 
675                          (isset($data['invalid_email']) && $data['invalid_email'] == $a['invalid_email'] ? ('invalid_email=' . $invalid . ', ') : '') .
676                          (isset($data['opt_out']) && $data['opt_out'] == $a['opt_out'] ? ('opt_out=' . $opt_out . ', ') : '') .
677                          'date_modified=\'' . gmdate($GLOBALS['timedate']->get_db_date_time_format()) . '\' ' .
678                          'WHERE id=\'' . $this->db->quote($a['id']) . '\'';
679                 $upd_r = $this->db->query($upd_q);
680             }
681             return $a['id'];
682         } else {
683             $guid = '';
684             if(!empty($address)){
685                 $guid = create_guid();
686                 $now = TimeDate::getInstance()->nowDb();
687                 $qa = "INSERT INTO email_addresses (id, email_address, email_address_caps, date_created, date_modified, deleted, invalid_email, opt_out)
688                         VALUES('{$guid}', '{$address}', '{$addressCaps}', '$now', '$now', 0 , $invalid, $opt_out)";
689                 $this->db->query($qa);
690             }
691             return $guid;
692         }
693     }
694
695     /**
696      * Returns Primary or newest email address
697      * @param object $focus Object in focus
698      * @return string email
699      */
700     function getPrimaryAddress($focus,$parent_id=null,$parent_type=null) {
701
702         $parent_type=empty($parent_type) ? $focus->module_dir : $parent_type;
703         $parent_id=empty($parent_id) ? $focus->id : $parent_id;
704
705         $q = "SELECT ea.email_address FROM email_addresses ea
706                 LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
707                 WHERE ear.bean_module = '".$this->db->quote($parent_type)."'
708                 AND ear.bean_id = '".$this->db->quote($parent_id)."'
709                 AND ear.deleted = 0
710                 AND ea.invalid_email = 0
711                 ORDER BY ear.primary_address DESC";
712         $r = $this->db->limitQuery($q, 0, 1);
713         $a = $this->db->fetchByAssoc($r);
714
715         if(isset($a['email_address'])) {
716             return $a['email_address'];
717         }
718         return '';
719     }
720
721     /**
722      * As long as this function is used not only to retrieve user's Reply-To
723      * address, but also notification address and so on, there were added
724      * $replyToOnly optional parameter used to retrieve only address marked as
725      * Reply-To (bug #43643).
726      *
727      * @param SugarBean $focus
728      * @param bool $replyToOnly
729      * @return string
730      */
731     function getReplyToAddress($focus, $replyToOnly = false) {
732         $q = "SELECT ea.email_address FROM email_addresses ea
733                 LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
734                 WHERE ear.bean_module = '".$this->db->quote($focus->module_dir)."'
735                 AND ear.bean_id = '".$this->db->quote($focus->id)."'
736                 AND ear.deleted = 0
737                 AND ea.invalid_email = 0";
738
739         if (!$replyToOnly)
740         {
741             // retrieve reply-to address if it exists or any other address
742             // otherwise
743             $q .= "
744                 ORDER BY ear.reply_to_address DESC";
745         }
746         else
747         {
748             // retrieve reply-to address only
749             $q .= "
750                 AND ear.reply_to_address = 1";
751         }
752
753         $r = $this->db->query($q);
754         $a = $this->db->fetchByAssoc($r);
755
756         if(isset($a['email_address'])) {
757             return $a['email_address'];
758         }
759         return '';
760     }
761
762     /**
763      * Returns all email addresses by parent's GUID
764      * @param string $id Parent's GUID
765      * @param string $module Parent's module
766      * @return array
767      */
768     function getAddressesByGUID($id, $module) {
769         $return = array();
770         $module = $this->getCorrectedModule($module);
771
772         $q = "SELECT ea.email_address, ea.email_address_caps, ea.invalid_email, ea.opt_out, ea.date_created, ea.date_modified,
773                 ear.id, ear.email_address_id, ear.bean_id, ear.bean_module, ear.primary_address, ear.reply_to_address, ear.deleted
774                 FROM email_addresses ea LEFT JOIN email_addr_bean_rel ear ON ea.id = ear.email_address_id
775                 WHERE ear.bean_module = '".$this->db->quote($module)."'
776                 AND ear.bean_id = '".$this->db->quote($id)."'
777                 AND ear.deleted = 0
778                 ORDER BY ear.reply_to_address, ear.primary_address DESC";
779         $r = $this->db->query($q);
780
781         while($a = $this->db->fetchByAssoc($r, FALSE)) {
782             $return[] = $a;
783         }
784
785         return $return;
786     }
787
788     /**
789      * Returns the HTML/JS for the EmailAddress widget
790      * @param string $parent_id ID of parent bean, generally $focus
791      * @param string $module $focus' module
792      * @param bool asMetadata Default false
793      * @return string HTML/JS for widget
794      */
795     function getEmailAddressWidgetEditView($id, $module, $asMetadata=false, $tpl='',$tabindex='0')
796     {
797         if ( !($this->smarty instanceOf Sugar_Smarty ) )
798             $this->smarty = new Sugar_Smarty();
799
800         global $app_strings, $dictionary, $beanList;
801
802         $prefill = 'false';
803
804         $prefillData = 'new Object()';
805         $passedModule = $module;
806         $module = $this->getCorrectedModule($module);
807         $saveModule = $module;
808         if(isset($_POST['is_converted']) && $_POST['is_converted']==true){
809             $id=$_POST['return_id'];
810             $module=$_POST['return_module'];
811         }
812         $prefillDataArr = array();
813         if(!empty($id)) {
814             $prefillDataArr = $this->getAddressesByGUID($id, $module);
815             //When coming from convert leads, sometimes module is Contacts while the id is for a lead.
816             if (empty($prefillDataArr) && $module == "Contacts")
817                 $prefillDataArr = $this->getAddressesByGUID($id, "Leads");
818         } else if(isset($_REQUEST['full_form']) && !empty($_REQUEST['emailAddressWidget'])){
819             $widget_id = isset($_REQUEST[$module . '_email_widget_id']) ? $_REQUEST[$module . '_email_widget_id'] : '0';
820             $count = 0;
821             $key = $module . $widget_id . 'emailAddress'.$count;
822             while(isset($_REQUEST[$key])) {
823                    $email = $_REQUEST[$key];
824                    $prefillDataArr[] =  array('email_address'=>$email,
825                                              'primary_address'=>isset($_REQUEST['emailAddressPrimaryFlag']) && $_REQUEST['emailAddressPrimaryFlag'] == $key,
826                                              'invalid_email'=>isset($_REQUEST['emailAddressInvalidFlag']) && in_array($key, $_REQUEST['emailAddressInvalidFlag']),
827                                              'opt_out'=>isset($_REQUEST['emailAddressOptOutFlag']) && in_array($key, $_REQUEST['emailAddressOptOutFlag']),
828                                              'reply_to_address'=>false
829                                         );
830                    $key = $module . $widget_id . 'emailAddress' . ++$count;
831             } //while
832         }
833
834         if(!empty($prefillDataArr)) {
835             $json = new JSON(JSON_LOOSE_TYPE);
836             $prefillData = $json->encode($prefillDataArr);
837             $prefill = !empty($prefillDataArr) ? 'true' : 'false';
838         }
839
840         $required = false;
841         $vardefs = $dictionary[$beanList[$passedModule]]['fields'];
842         if (!empty($vardefs['email1']) && isset($vardefs['email1']['required']) && $vardefs['email1']['required'])
843             $required = true;
844         $this->smarty->assign('required', $required);
845
846         $this->smarty->assign('module', $saveModule);
847         $this->smarty->assign('index', $this->index);
848         $this->smarty->assign('app_strings', $app_strings);
849         $this->smarty->assign('prefillEmailAddresses', $prefill);
850         $this->smarty->assign('prefillData', $prefillData);
851         $this->smarty->assign('tabindex', $tabindex);
852         //Set addDefaultAddress flag (do not add if it's from the Email module)
853         $this->smarty->assign('addDefaultAddress', (isset($_REQUEST['module']) && $_REQUEST['module'] == 'Emails') ? 'false' : 'true');
854         $form = $this->view;
855
856         //determine if this should be a quickcreate form, or a quick create form under subpanels
857         if ($this->view == "QuickCreate"){
858             $form = 'form_DC'.$this->view .'_'.$module;
859             if(isset($_REQUEST['action']) && $_REQUEST['action']=='SubpanelCreates' ||  $_REQUEST['action']=='SubpanelEdits'){
860                 $form = 'form_Subpanel'.$this->view .'_'.$module;
861             }
862         }
863
864         $this->smarty->assign('emailView', $form);
865
866         if($module == 'Users') {
867             $this->smarty->assign('useReplyTo', true);
868         } else {
869             $this->smarty->assign('useOptOut', true);
870             $this->smarty->assign('useInvalid', true);
871         }
872
873         $template = empty($tpl) ? "include/SugarEmailAddress/templates/forEditView.tpl" : $tpl;
874         $newEmail = $this->smarty->fetch($template);
875
876
877         if($asMetadata) {
878             // used by Email 2.0
879             $ret = array();
880             $ret['prefillData'] = $prefillDataArr;
881             $ret['html'] = $newEmail;
882
883             return $ret;
884         }
885
886         return $newEmail;
887     }
888
889
890     /**
891      * Returns the HTML/JS for the EmailAddress widget
892      * @param object $focus Bean in focus
893      * @return string HTML/JS for widget
894      */
895     function getEmailAddressWidgetDetailView($focus, $tpl='')
896     {
897         if ( !($this->smarty instanceOf Sugar_Smarty ) )
898             $this->smarty = new Sugar_Smarty();
899
900         global $app_strings;
901         global $current_user;
902         $assign = array();
903         if(empty($focus->id))return '';
904         $prefillData = $this->getAddressesByGUID($focus->id, $focus->module_dir);
905
906         foreach($prefillData as $addressItem) {
907             $key = ($addressItem['primary_address'] == 1) ? 'primary' : "";
908             $key = ($addressItem['reply_to_address'] == 1) ? 'reply_to' : $key;
909             $key = ($addressItem['opt_out'] == 1) ? 'opt_out' : $key;
910             $key = ($addressItem['invalid_email'] == 1) ? 'invalid' : $key;
911             $key = ($addressItem['opt_out'] == 1) && ($addressItem['invalid_email'] == 1) ? 'opt_out_invalid' : $key;
912
913             $assign[] = array('key' => $key, 'address' => $current_user->getEmailLink2($addressItem['email_address'], $focus).$addressItem['email_address']."</a>");
914         }
915
916
917         $this->smarty->assign('app_strings', $app_strings);
918         $this->smarty->assign('emailAddresses', $assign);
919         $templateFile = empty($tpl) ? "include/SugarEmailAddress/templates/forDetailView.tpl" : $tpl;
920         $return = $this->smarty->fetch($templateFile);
921         return $return;
922     }
923
924
925     /**
926      * getEmailAddressWidgetDuplicatesView($focus)
927      * @param object $focus Bean in focus
928      * @return string HTML that contains hidden input values based off of HTML request
929      */
930     function getEmailAddressWidgetDuplicatesView($focus)
931     {
932         if ( !($this->smarty instanceOf Sugar_Smarty ) )
933             $this->smarty = new Sugar_Smarty();
934
935         $count = 0;
936         $emails = array();
937         $primary = null;
938         $optOut = array();
939         $invalid = array();
940         $mod = isset($focus) ? $focus->module_dir : "";
941
942         $widget_id = $_POST[$mod .'_email_widget_id'];
943         $this->smarty->assign('email_widget_id',$widget_id);
944         $this->smarty->assign('emailAddressWidget',$_POST['emailAddressWidget']);
945
946         if(isset($_POST[$mod . $widget_id . 'emailAddressPrimaryFlag'])) {
947            $primary = $_POST[$mod . $widget_id . 'emailAddressPrimaryFlag'];
948         }
949
950         while(isset($_POST[$mod . $widget_id . "emailAddress" . $count])) {
951             $emails[] = $_POST[$mod . $widget_id . 'emailAddress' . $count];
952             $count++;
953         }
954
955         if($count == 0) {
956            return "";
957         }
958
959         if(isset($_POST[$mod . $widget_id . 'emailAddressOptOutFlag'])) {
960            foreach($_POST[$mod . $widget_id . 'emailAddressOptOutFlag'] as $v) {
961               $optOut[] = $v;
962            }
963         }
964
965         if(isset($_POST[$mod . $widget_id . 'emailAddressInvalidFlag'])) {
966            foreach($_POST[$mod . $widget_id . 'emailAddressInvalidFlag'] as $v) {
967               $invalid[] = $v;
968            }
969         }
970
971         if(isset($_POST[$mod . $widget_id . 'emailAddressReplyToFlag'])) {
972            foreach($_POST[$mod . $widget_id . 'emailAddressReplyToFlag'] as $v) {
973               $replyTo[] = $v;
974            }
975         }
976
977         if(isset($_POST[$mod . $widget_id . 'emailAddressDeleteFlag'])) {
978            foreach($_POST[$mod . $widget_id . 'emailAddressDeleteFlag'] as $v) {
979               $delete[] = $v;
980            }
981         }
982
983         while(isset($_POST[$mod . $widget_id . "emailAddressVerifiedValue" . $count])) {
984             $verified[] = $_POST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count];
985             $count++;
986         }
987
988         $this->smarty->assign('emails', $emails);
989         $this->smarty->assign('primary', $primary);
990         $this->smarty->assign('optOut', $optOut);
991         $this->smarty->assign('invalid', $invalid);
992         $this->smarty->assign('replyTo', $invalid);
993         $this->smarty->assign('delete', $invalid);
994         $this->smarty->assign('verified', $invalid);
995         $this->smarty->assign('moduleDir', $mod);
996
997         return $this->smarty->fetch("include/SugarEmailAddress/templates/forDuplicatesView.tpl");
998     }
999
1000     /**
1001      * getFormBaseURL
1002      *
1003      */
1004     function getFormBaseURL($focus) {
1005         $get = "";
1006         $count = 0;
1007         $mod = isset($focus) ? $focus->module_dir : "";
1008
1009         $widget_id = $_POST[$mod .'_email_widget_id'];
1010         $get .= '&' . $mod . '_email_widget_id='. $widget_id;
1011         $get .= '&emailAddressWidget='.$_POST['emailAddressWidget'];
1012
1013         while(isset($_REQUEST[$mod . $widget_id . 'emailAddress' . $count])) {
1014               $get .= "&" . $mod . $widget_id . "emailAddress" . $count . "=" . urlencode($_REQUEST[$mod . $widget_id . 'emailAddress' . $count]);
1015               $count++;
1016         } //while
1017
1018         while(isset($_REQUEST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count])) {
1019               $get .= "&" . $mod . $widget_id . "emailAddressVerifiedValue" . $count . "=" . urlencode($_REQUEST[$mod . $widget_id . 'emailAddressVerifiedValue' . $count]);
1020               $count++;
1021         } //while
1022
1023         $options = array('emailAddressPrimaryFlag', 'emailAddressOptOutFlag', 'emailAddressInvalidFlag', 'emailAddressDeleteFlag', 'emailAddressReplyToFlag');
1024
1025         foreach($options as $option) {
1026             $count = 0;
1027             $optionIdentifier = $mod.$widget_id.$option;
1028             if(isset($_REQUEST[$optionIdentifier])) {
1029                if(is_array($_REQUEST[$optionIdentifier])) {
1030                    foreach($_REQUEST[$optionIdentifier] as $optOut) {
1031                       $get .= "&" . $optionIdentifier . "[" . $count . "]=" . $optOut;
1032                       $count++;
1033                    } //foreach
1034                } else {
1035                    $get .= "&" . $optionIdentifier . "=" . $_REQUEST[$optionIdentifier];
1036                }
1037             } //if
1038         } //foreach
1039         return $get;
1040
1041     }
1042
1043     function setView($view) {
1044        $this->view = $view;
1045     }
1046
1047 /**
1048  * This function is here so the Employees/Users division can be handled cleanly in one place
1049  * @param object $focus SugarBean
1050  * @return string The value for the bean_module column in the email_addr_bean_rel table
1051  */
1052     function getCorrectedModule(&$module) {
1053         return ($module == "Employees")? "Users" : $module;
1054     }
1055
1056     public function stash($parentBeanId, $moduleName)
1057     {
1058         $result = $this->db->query("select email_address_id from email_addr_bean_rel eabr WHERE eabr.bean_id = '".$this->db->quote($parentBeanId)."' AND eabr.bean_module = '".$this->db->quote($moduleName)."' and eabr.deleted=0");
1059         $this->stateBeforeWorkflow = array();
1060         $ids = array();
1061         while ($row = $this->db->fetchByAssoc($result, false))
1062         {
1063             $ids[] =$this->db->quote($row['email_address_id']); // avoid 2nd order SQL Injection
1064         }
1065         if (!empty($ids))
1066         {
1067             $ids = implode("', '", $ids);
1068             $queryEmailData = "SELECT id, email_address, invalid_email, opt_out FROM {$this->table_name} WHERE id IN ('$ids') AND deleted=0";
1069             $result = $this->db->query($queryEmailData);
1070             while ($row = $this->db->fetchByAssoc($result, false))
1071             {
1072                 $this->stateBeforeWorkflow[$row['id']] = array_diff_key($row, array('id' => null));
1073             }
1074         }
1075     }
1076 } // end class def
1077
1078
1079 /**
1080  * Convenience function for MVC (Mystique)
1081  * @param object $focus SugarBean
1082  * @param string $field unused
1083  * @param string $value unused
1084  * @param string $view DetailView or EditView
1085  * @return string
1086  */
1087 function getEmailAddressWidget($focus, $field, $value, $view, $tabindex='0') {
1088     $sea = new SugarEmailAddress();
1089     $sea->setView($view);
1090
1091         if($view == 'EditView' || $view == 'QuickCreate' || $view == 'ConvertLead') {
1092             $module = $focus->module_dir;
1093             if ($view == 'ConvertLead' && $module == "Contacts")  $module = "Leads";
1094
1095             return $sea->getEmailAddressWidgetEditView($focus->id, $module, false,'',$tabindex);
1096         }
1097
1098     return $sea->getEmailAddressWidgetDetailView($focus);
1099 }