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