]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SugarEmailAddress/SugarEmailAddress.php
Release 6.4.0
[Github/sugarcrm.git] / include / SugarEmailAddress / SugarEmailAddress.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description:
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42  * Reserved. Contributor(s): ______________________________________..
43  *********************************************************************************/
44
45
46 require_once("include/JSON.php");
47
48
49 class SugarEmailAddress extends SugarBean {
50     var $table_name = 'email_addresses';
51     var $module_name = "EmailAddresses";
52     var $module_dir = 'EmailAddresses';
53     var $object_name = 'EmailAddress';
54
55     //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
56         //allowed special characters ! # $ % & ' * + - / = ?  ^ _ ` . { | } ~ in local part
57     var $regex = "/^(?:['\.\-\+&#!\$\*=\?\^_`\{\}~\/\w]+)@(?:(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|\w+(?:[\.-]*\w+)*(?:\.[\w-]{2,})+)\$/";
58     var $disable_custom_fields = true;
59     var $db;
60     var $smarty;
61     var $addresses = array(); // array of emails
62     var $view = '';
63
64     static $count = 0;
65
66     /**
67      * Sole constructor
68      */
69     function SugarEmailAddress() {
70         parent::SugarBean();
71         $this->index = self::$count;
72         self::$count++;
73     }
74
75     /**
76      * Legacy email address handling.  This is to allow support for SOAP or customizations
77      * @param string $id
78      * @param string $module
79      */
80     function handleLegacySave($bean, $prefix = "") {
81         if(!isset($_REQUEST) || !isset($_REQUEST['useEmailWidget'])) {
82             if (empty($this->addresses) || !isset($_REQUEST['massupdate'])) {
83                 $this->addresses = array();
84                 $optOut = (isset($bean->email_opt_out) && $bean->email_opt_out == "1") ? true : false;
85                 $invalid = (isset($bean->invalid_email) && $bean->invalid_email == "1") ? true : false;
86
87                 $isPrimary = true;
88                 for($i = 1; $i <= 10; $i++){
89                     $email = 'email'.$i;
90                     if(isset($bean->$email) && !empty($bean->$email)){
91                         $opt_out_field = $email.'_opt_out';
92                         $invalid_field = $email.'_invalid';
93                         $field_optOut = (isset($bean->$opt_out_field)) ? $bean->$opt_out_field : $optOut;
94                         $field_invalid = (isset($bean->$invalid_field)) ? $bean->$invalid_field : $invalid;
95                         $this->addAddress($bean->$email, $isPrimary, false, $field_invalid, $field_optOut);
96                         $isPrimary = false;
97                     }
98                 }
99             }
100         }
101         $this->populateAddresses($bean->id, $bean->module_dir, array(),'');
102         if(isset($_REQUEST) && isset($_REQUEST['useEmailWidget'])) {
103             $this->populateLegacyFields($bean);
104         }
105     }
106
107     /**
108      * Fills standard email1 legacy fields
109      * @param string id
110      * @param string module
111      * @return object
112      */
113     function handleLegacyRetrieve(&$bean) {
114         $module_dir = $this->getCorrectedModule($bean->module_dir);
115         $this->addresses = $this->getAddressesByGUID($bean->id, $module_dir);
116         $this->populateLegacyFields($bean);
117         if (isset($bean->email1) && !isset($bean->fetched_row['email1'])) {
118             $bean->fetched_row['email1'] = $bean->email1;
119         }
120
121         return;
122     }
123
124     function populateLegacyFields(&$bean){
125         $primary_found = false;
126         $alternate_found = false;
127         $alternate2_found = false;
128         foreach($this->addresses as $k=>$address) {
129             if ($primary_found && $alternate_found)
130                 break;
131             if ($address['primary_address'] == 1 && !$primary_found) {
132                 $primary_index = $k;
133                 $primary_found = true;
134             } elseif (!$alternate_found) {
135                 $alternate_index = $k;
136                 $alternate_found = true;
137             } elseif (!$alternate2_found){
138                 $alternate2_index = $k;
139                 $alternate2_found = true;
140             }
141         }
142
143         if ($primary_found) {
144             $bean->email1 = $this->addresses[$primary_index]['email_address'];
145             $bean->email_opt_out = $this->addresses[$primary_index]['opt_out'];
146             $bean->invalid_email = $this->addresses[$primary_index]['invalid_email'];
147             if ($alternate_found) {
148                 $bean->email2 = $this->addresses[$alternate_index]['email_address'];
149             }
150         } elseif ($alternate_found) {
151             // Use the first found alternate as email1.
152             $bean->email1 = $this->addresses[$alternate_index]['email_address'];
153             $bean->email_opt_out = $this->addresses[$alternate_index]['opt_out'];
154             $bean->invalid_email = $this->addresses[$alternate_index]['invalid_email'];
155             if ($alternate2_found) {
156                 $bean->email2 = $this->addresses[$alternate2_index]['email_address'];
157             }
158         }
159     }
160
161     /**
162      * Saves email addresses for a parent bean
163      * @param string $id Parent bean ID
164      * @param string $module Parent bean's module
165      * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
166      * @param string $primary GUID of primary address
167      * @param string $replyTo GUID of reply-to address
168      * @param string $invalid GUID of invalid address
169      */
170     function save($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='', $in_workflow=false) {
171         if(empty($this->addresses) || $in_workflow){
172             $this->populateAddresses($id, $module, $new_addrs,$primary);
173         }
174
175         //find all email addresses..
176         $current_links=array();
177         // Need to correct this to handle the Employee/User split
178         $module = $this->getCorrectedModule($module);
179         $q2="select *  from email_addr_bean_rel eabr WHERE eabr.bean_id = '{$id}' AND eabr.bean_module = '{$module}' and eabr.deleted=0";
180         $r2 = $this->db->query($q2);
181         while(($row2=$this->db->fetchByAssoc($r2)) != null ) {
182             $current_links[$row2['email_address_id']]=$row2;
183         }
184
185         $isConversion = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? true : false;
186
187         if (!empty($this->addresses)) {
188             // insert new relationships and create email address record, if they don't exist
189             foreach($this->addresses as $address) {
190                 if(!empty($address['email_address'])) {
191                     $guid = create_guid();
192                     $emailId = $this->AddUpdateEmailAddress($address['email_address'],$address['invalid_email'],$address['opt_out']);// this will save the email address if not found
193
194                     //verify linkage and flags.
195                     $upd_eabr="";
196                     if (isset($current_links[$emailId])) {
197                         if (!$isConversion) { // do not update anything if this is for lead conversion
198                         if ($address['primary_address'] != $current_links[$emailId]['primary_address'] or $address['reply_to_address'] != $current_links[$emailId]['reply_to_address'] ) {
199                             $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']}'";
200                         }
201
202                         unset($current_links[$emailId]);
203                         }
204                     } else {
205                         $primary = $address['primary_address'];
206                         if (!empty($current_links) && $isConversion) {
207                             foreach ($current_links as $eabr) {
208                                 if ($eabr['primary_address'] == 1) {
209                                     // for lead conversion, if there is already a primary email, do not insert another primary email
210                                     $primary = 0;
211                                     break;
212                                 }
213                             }
214                         }
215                         $now = $this->db->now();
216                         $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)";
217                     }
218
219                     if (!empty($upd_eabr)) {
220                         $r2 = $this->db->query($upd_eabr);
221                     }
222                 }
223             }
224         }
225
226         //delete link to dropped email address.
227         // for lead conversion, do not delete email addresses
228         if (!empty($current_links) && !$isConversion) {
229
230             $delete="";
231             foreach ($current_links as $eabr) {
232
233                 $delete.=empty($delete) ? "'".$eabr['id'] . "' " : ",'" . $eabr['id'] . "'";
234             }
235
236             $eabr_unlink="update email_addr_bean_rel set deleted=1 where id in ({$delete})";
237             $this->db->query($eabr_unlink);
238         }
239         return;
240     }
241
242     /**
243      * returns the number of email addresses found for a specifed bean
244      *
245      * @param  string $email       Address to match
246      * @param  object $bean        Bean to query against
247      * @param  string $addresstype Optional, pass a 1 to query against the primary address, 0 for the other addresses
248      * @return int                 Count of records found
249      */
250     function getCountEmailAddressByBean(
251         $email,
252         $bean,
253         $addresstype
254         )
255     {
256         $emailCaps = strtoupper(trim($email));
257         if(empty($emailCaps))
258             return 0;
259
260         $q = "SELECT *
261                 FROM email_addr_bean_rel eabl JOIN email_addresses ea
262                         ON (ea.id = eabl.email_address_id)
263                     JOIN {$bean->table_name} bean
264                         ON (eabl.bean_id = bean.id)
265                 WHERE ea.email_address_caps = '{$emailCaps}'
266                     and eabl.bean_module = '{$bean->module_dir}'
267                     and eabl.primary_address = '{$addresstype}'
268                     and eabl.deleted=0 ";
269
270         $r = $this->db->query($q);
271
272         // do it this way to make the count accurate in oracle
273         $i = 0;
274         while ($this->db->fetchByAssoc($r)) ++$i;
275
276         return $i;
277     }
278
279     /**
280      * This function returns a contact or user ID if a matching email is found
281      * @param   $email      the email address to match
282      * @param   $table      which table to query
283      */
284     function getRelatedId($email, $module) {
285         $email = trim(strtoupper($email));
286         $module = ucfirst($module);
287
288         $q = "SELECT bean_id FROM email_addr_bean_rel eabr
289                 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
290                 WHERE bean_module = '{$module}' AND ea.email_address_caps = '{$email}' AND eabr.deleted=0";
291
292         $r = $this->db->query($q, true);
293
294         $retArr = array();
295         while($a = $this->db->fetchByAssoc($r)) {
296             $retArr[] = $a['bean_id'];
297         }
298         if(count($retArr) > 0) {
299             return $retArr;
300         } else {
301             return false;
302         }
303     }
304
305     /**
306      * returns a collection of beans matching the email address
307      * @param string $email Address to match
308      * @return array
309      */
310     function getBeansByEmailAddress($email) {
311         global $beanList;
312         global $beanFiles;
313
314         $ret = array();
315
316         $email = trim($email);
317
318         if(empty($email)) {
319             return array();
320         }
321
322         $emailCaps = strtoupper($email);
323         $q = "SELECT * FROM email_addr_bean_rel eabl JOIN email_addresses ea ON (ea.id = eabl.email_address_id)
324                 WHERE ea.email_address_caps = '{$emailCaps}' and eabl.deleted=0 ";
325         $r = $this->db->query($q);
326
327         while($a = $this->db->fetchByAssoc($r)) {
328             if(isset($beanList[$a['bean_module']]) && !empty($beanList[$a['bean_module']])) {
329                 $className = $beanList[$a['bean_module']];
330
331                 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
332                     if(!class_exists($className)) {
333                         require_once($beanFiles[$className]);
334                     }
335
336                     $bean = new $className();
337                     $bean->retrieve($a['bean_id']);
338
339                     $ret[] = $bean;
340                 } else {
341                     $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class file for [ {$className} ]");
342                 }
343             } else {
344                 $GLOBALS['log']->fatal("SUGAREMAILADDRESS: could not find valid class [ {$a['bean_module']} ]");
345             }
346         }
347
348         return $ret;
349     }
350
351     /**
352      * Saves email addresses for a parent bean
353      * @param string $id Parent bean ID
354      * @param string $module Parent bean's module
355      * @param array $addresses Override of $_REQUEST vars, used to handle non-standard bean saves
356      * @param string $primary GUID of primary address
357      * @param string $replyTo GUID of reply-to address
358      * @param string $invalid GUID of invalid address
359      */
360     function populateAddresses($id, $module, $new_addrs=array(), $primary='', $replyTo='', $invalid='', $optOut='') {
361         $module = $this->getCorrectedModule($module);
362         //One last check for the ConvertLead action in which case we need to change $module to 'Leads'
363         $module = (isset($_REQUEST) && isset($_REQUEST['action']) && $_REQUEST['action'] == 'ConvertLead') ? 'Leads' : $module;
364
365         $post_from_email_address_widget = (isset($_REQUEST) && isset($_REQUEST['emailAddressWidget'])) ? true : false;
366         $primaryValue = $primary;
367         $widgetCount = 0;
368         $hasEmailValue = false;
369
370         if (isset($_REQUEST) && isset($_REQUEST[$module .'_email_widget_id'])) {
371
372             $fromRequest = false;
373             // determine which array to process
374             foreach($_REQUEST as $k => $v) {
375                 if(strpos($k, 'emailAddress') !== false) {
376                    $fromRequest = true;
377                    break;
378                 }
379             $widget_id = $_REQUEST[$module .'_email_widget_id'];
380     }
381
382             //Iterate over the widgets for this module, in case there are multiple email widgets for this module
383             while(isset($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount]))
384             {
385                 if (empty($_REQUEST[$module . $widget_id . "emailAddress" . $widgetCount])) {
386                     $widgetCount++;
387                     continue;
388                 }
389
390                 $hasEmailValue = true;
391
392                 $eId = $module . $widget_id;
393                 if(isset($_REQUEST[$eId . 'emailAddressPrimaryFlag'])) {
394                    $primaryValue = $_REQUEST[$eId . 'emailAddressPrimaryFlag'];
395                 } else if(isset($_REQUEST[$module . 'emailAddressPrimaryFlag'])) {
396                    $primaryValue = $_REQUEST[$module . 'emailAddressPrimaryFlag'];
397                 }
398
399                 $optOutValues = array();
400                 if(isset($_REQUEST[$eId .'emailAddressOptOutFlag'])) {
401                    $optOutValues = $_REQUEST[$eId .'emailAddressOptOutFlag'];
402                 } else if(isset($_REQUEST[$module . 'emailAddressOptOutFlag'])) {
403                    $optOutValues = $_REQUEST[$module . 'emailAddressOptOutFlag'];
404                 }
405
406                 $invalidValues = array();
407                 if(isset($_REQUEST[$eId .'emailAddressInvalidFlag'])) {
408                    $invalidValues = $_REQUEST[$eId .'emailAddressInvalidFlag'];
409                 } else if(isset($_REQUEST[$module . 'emailAddressInvalidFlag'])) {
410                    $invalidValues = $_REQUEST[$module . 'emailAddressInvalidFlag'];
411                 }
412
413                 $deleteValues = array();
414                 if(isset($_REQUEST[$eId .'emailAddressDeleteFlag'])) {
415                    $deleteValues = $_REQUEST[$eId .'emailAddressDeleteFlag'];
416                 } else if(isset($_REQUEST[$module . 'emailAddressDeleteFlag'])) {
417                    $deleteValues = $_REQUEST[$module . 'emailAddressDeleteFlag'];
418                 }
419
420                 // prep from form save
421                 $primaryField = $primary;
422                 $replyToField = '';
423                 $invalidField = '';
424                 $optOutField = '';
425                 if($fromRequest && empty($primary) && isset($primaryValue)) {
426                     $primaryField = $primaryValue;
427                 }
428
429                 if($fromRequest && empty($replyTo)) {
430                     if(isset($_REQUEST[$eId .'emailAddressReplyToFlag'])) {
431                        $replyToField = $_REQUEST[$eId .'emailAddressReplyToFlag'];
432                     } else if(isset($_REQUEST[$module . 'emailAddressReplyToFlag'])) {
433                        $replyToField = $_REQUEST[$module . 'emailAddressReplyToFlag'];
434                     }
435                 }
436                 if($fromRequest && empty($new_addrs)) {
437                     foreach($_REQUEST as $k => $v) {
438                         if(preg_match('/'.$eId.'emailAddress[0-9]+$/i', $k) && !empty($v)) {
439                             $new_addrs[$k] = $v;
440                         }
441                     }
442                 }
443
444                 if($fromRequest && empty($new_addrs)) {
445                     foreach($_REQUEST as $k => $v) {
446                         if(preg_match('/'.$eId.'emailAddressVerifiedValue[0-9]+$/i', $k) && !empty($v)) {
447                             $validateFlag = str_replace("Value", "Flag", $k);
448                             if (isset($_REQUEST[$validateFlag]) && $_REQUEST[$validateFlag] == "true")
449                               $new_addrs[$k] = $v;
450                         }
451                     }
452                 }
453
454                 //empty the addresses array if the post happened from email address widget.
455                 if($post_from_email_address_widget) {
456                     $this->addresses=array();  //this gets populated during retrieve of the contact bean.
457                 } else {
458                     $optOutValues = array();
459                     $invalidValues = array();
460                     foreach($new_addrs as $k=>$email) {
461                        preg_match('/emailAddress([0-9])+$/', $k, $matches);
462                        $count = $matches[1];
463                        $result = $this->db->query("SELECT opt_out, invalid_email from email_addresses where email_address_caps = '" . strtoupper($email) . "'");
464                        if(!empty($result)) {
465                           $row=$this->db->fetchByAssoc($result);
466                           if(!empty($row['opt_out'])) {
467                              $optOutValues[$k] = "emailAddress$count";
468                           }
469                           if(!empty($row['invalid_email'])) {
470                              $invalidValues[$k] = "emailAddress$count";
471                           }
472                        }
473                     }
474                 }
475                 // Re-populate the addresses class variable if we have new address(es).
476                 if (!empty($new_addrs)) {
477                     foreach($new_addrs as $k => $reqVar) {
478                         //$key = preg_match("/^$eId/s", $k) ? substr($k, strlen($eId)) : $k;
479                         $reqVar = trim($reqVar);
480                         if(strpos($k, 'emailAddress') !== false) {
481                             if(!empty($reqVar) && !in_array($k, $deleteValues)) {
482                                 $primary    = ($k == $primaryValue) ? true : false;
483                                 $replyTo    = ($k == $replyToField) ? true : false;
484                                 $invalid    = (in_array($k, $invalidValues)) ? true : false;
485                                 $optOut     = (in_array($k, $optOutValues)) ? true : false;
486                                 $this->addAddress(trim($new_addrs[$k]), $primary, $replyTo, $invalid, $optOut);
487                             }
488                         }
489                     } //foreach
490                 }
491
492                 $widgetCount++;
493             }//End of Widget for loop
494         }
495
496         //If no widgets, set addresses array to empty
497         if($post_from_email_address_widget && !$hasEmailValue) {
498            $this->addresses = array();
499         }
500     }
501
502     /**
503      * Preps internal array structure for email addresses
504      * @param string $addr Email address
505      * @param bool $primary Default false
506      * @param bool $replyTo Default false
507      */
508     function addAddress($addr, $primary=false, $replyTo=false, $invalid=false, $optOut=false) {
509         $addr = html_entity_decode($addr, ENT_QUOTES);
510         if(preg_match($this->regex, $addr)) {
511             $primaryFlag = ($primary) ? '1' : '0';
512             $replyToFlag = ($replyTo) ? '1' : '0';
513             $invalidFlag = ($invalid) ? '1' : '0';
514             $optOutFlag = ($optOut) ? '1' : '0';
515
516             $addr = trim($addr);
517
518             // If we have such address already, remove it and add new one in.
519             foreach ($this->addresses as $k=>$address) {
520                 if ($address['email_address'] == $addr) {
521                     unset($this->addresses[$k]);
522                 } elseif ($primary && $address['primary_address'] == '1') {
523                     // We should only have one primary. If we are adding a primary but
524                     // we find an existing primary, reset this one's primary flag.
525                     $address['primary_address'] = '0';
526                 }
527             }
528
529             $this->addresses[] = array(
530                 'email_address' => $addr,
531                 'primary_address' => $primaryFlag,
532                 'reply_to_address' => $replyToFlag,
533                 'invalid_email' => $invalidFlag,
534                 'opt_out' => $optOutFlag,
535             );
536         } else {
537             $GLOBALS['log']->fatal("SUGAREMAILADDRESS: address did not validate [ {$addr} ]");
538         }
539     }
540
541     /**
542      * Updates invalid_email and opt_out flags for each address
543      */
544     function updateFlags() {
545         if(!empty($this->addresses)) {
546             foreach($this->addresses as $addressMeta) {
547                 if(isset($addressMeta['email_address']) && !empty($addressMeta['email_address'])) {
548                     $address = $this->_cleanAddress($addressMeta['email_address']);
549
550                     $q = "SELECT * FROM email_addresses WHERE email_address = '{$address}'";
551                     $r = $this->db->query($q);
552                     $a = $this->db->fetchByAssoc($r);
553
554                     if(!empty($a)) {
555                         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']) {
556                             $qUpdate = "UPDATE email_addresses SET invalid_email = {$addressMeta['invalid_email']}, opt_out = {$addressMeta['opt_out']}, date_modified = '".TimeDate::getInstance()->nowDb()."' WHERE id = '{$a['id']}'";
557                             $rUpdate = $this->db->query($qUpdate);
558                         }
559                     }
560                 }
561             }
562         }
563     }
564
565     public function splitEmailAddress($addr)
566     {
567         $email = $this->_cleanAddress($addr);
568         if(!preg_match($this->regex, $email)) {
569             $email = ''; // remove bad email addr
570         }
571         $name = trim(str_replace(array($email, '<', '>', '"', "'"), '', $addr));
572         return array("name" => $name, "email" => strtolower($email));
573     }
574
575     /**
576      * PRIVATE UTIL
577      * Normalizes an RFC-clean email address, returns a string that is the email address only
578      * @param string $addr Dirty email address
579      * @return string clean email address
580      */
581     function _cleanAddress($addr) {
582         $addr = trim(from_html($addr));
583
584         if(strpos($addr, "<") !== false && strpos($addr, ">") !== false) {
585             $address = trim(substr($addr, strrpos($addr, "<") +1, strrpos($addr, ">") - strrpos($addr, "<") -1));
586         } else {
587             $address = trim($addr);
588         }
589
590         return $address;
591     }
592
593     /**
594      * preps a passed email address for email address storage
595      * @param array $addr Address in focus, must be RFC compliant
596      * @return string $id email_addresses ID
597      */
598     function getEmailGUID($addr) {
599         $address = $this->db->quote($this->_cleanAddress($addr));
600         $addressCaps = strtoupper($address);
601
602         $q = "SELECT id FROM email_addresses WHERE email_address_caps = '{$addressCaps}'";
603         $r = $this->db->query($q);
604         $a = $this->db->fetchByAssoc($r);
605
606         if(!empty($a) && !empty($a['id'])) {
607             return $a['id'];
608         } else {
609             $guid = '';
610             if(!empty($address)){
611                 $guid = create_guid();
612                 $address = $GLOBALS['db']->quote($address);
613                 $now = TimeDate::getInstance()->nowDb();
614                 $qa = "INSERT INTO email_addresses (id, email_address, email_address_caps, date_created, date_modified, deleted)
615                         VALUES('{$guid}', '{$address}', '{$addressCaps}', '$now', '$now', 0)";
616                 $ra = $this->db->query($qa);
617             }
618             return $guid;
619         }
620     }
621
622     function AddUpdateEmailAddress($addr,$invalid=0,$opt_out=0)
623     {
624         $address = $this->db->quote($this->_cleanAddress($addr));
625         $addressCaps = strtoupper($address);
626
627         $q = "SELECT * FROM email_addresses WHERE email_address_caps = '{$addressCaps}' and deleted=0";
628         $r = $this->db->query($q);
629         $a = $this->db->fetchByAssoc($r);
630         if(!empty($a) && !empty($a['id'])) {
631             //verify the opt out and invalid flags.
632            //bug# 39378- did not allow change of case of an email address
633             if ($a['invalid_email'] != $invalid or $a['opt_out'] != $opt_out or strcasecmp(trim($a['email_address']), trim($address))==0) {
634                 $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']}'";
635                 $upd_r= $this->db->query($upd_q);
636             }
637             return $a['id'];
638         } else {
639             $guid = '';
640             if(!empty($address)){
641                 $guid = create_guid();
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='0')
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='0') {
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 }