]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Emails/Email.php
Release 6.2.3
[Github/sugarcrm.git] / modules / Emails / Email.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 require_once('include/SugarPHPMailer.php');
45
46 require_once('include/Pear/HTML_Safe/Safe.php');
47
48 class Email extends SugarBean {
49         /* SugarBean schema */
50         var $id;
51         var $date_entered;
52         var $date_modified;
53         var $assigned_user_id;
54         var $assigned_user_name;
55         var $modified_user_id;
56         var $created_by;
57         var $deleted;
58         var $from_addr;
59         var $reply_to_addr;
60         var $to_addrs;
61     var $cc_addrs;
62     var $bcc_addrs;
63         var $message_id;
64
65         /* Bean Attributes */
66         var $name;
67     var $type = 'archived';
68     var $date_sent;
69         var $status;
70         var $intent;
71         var $mailbox_id;
72         var $from_name;
73
74         var $reply_to_status;
75         var $reply_to_name;
76         var $reply_to_email;
77         var $description;
78         var $description_html;
79         var $raw_source;
80         var $parent_id;
81         var $parent_type;
82
83         /* link attributes */
84         var $parent_name;
85
86
87         /* legacy */
88         var $date_start; // legacy
89         var $time_start; // legacy
90         var $from_addr_name;
91         var $to_addrs_arr;
92     var $cc_addrs_arr;
93     var $bcc_addrs_arr;
94         var $to_addrs_ids;
95         var $to_addrs_names;
96         var $to_addrs_emails;
97         var $cc_addrs_ids;
98         var $cc_addrs_names;
99         var $cc_addrs_emails;
100         var $bcc_addrs_ids;
101         var $bcc_addrs_names;
102         var $bcc_addrs_emails;
103         var $contact_id;
104         var $contact_name;
105
106         /* Archive Email attrs */
107         var $duration_hours;
108
109
110
111         var $new_schema = true;
112         var $table_name = 'emails';
113         var $module_dir = 'Emails';
114         var $object_name = 'Email';
115         var $db;
116
117         /* private attributes */
118         var $rolloverStyle              = "<style>div#rollover {position: relative;float: left;margin: none;text-decoration: none;}div#rollover a:hover {padding: 0;text-decoration: none;}div#rollover a span {display: none;}div#rollover a:hover span {text-decoration: none;display: block;width: 250px;margin-top: 5px;margin-left: 5px;position: absolute;padding: 10px;color: #333;      border: 1px solid #ccc; background-color: #fff; font-size: 12px;z-index: 1000;}</style>\n";
119         var $cachePath;
120         var $cacheFile                  = 'robin.cache.php';
121         var $replyDelimiter     = "> ";
122         var $emailDescription;
123         var $emailDescriptionHTML;
124         var $emailRawSource;
125         var $link_action;
126         var $emailAddress;
127         var $attachments = array();
128
129         /* to support Email 2.0 */
130         var $isDuplicate;
131         var $uid;
132         var $to;
133         var $flagged;
134         var $answered;
135         var $seen;
136         var $draft;
137         var $relationshipMap = array(
138                 'Contacts'      => 'emails_contacts_rel',
139                 'Accounts'      => 'emails_accounts_rel',
140                 'Leads'         => 'emails_leads_rel',
141                 'Users'         => 'emails_users_rel',
142                 'Prospects'     => 'emails_prospects_rel',
143         );
144
145         /* public */
146         var $et;                // EmailUI object
147
148
149
150         /**
151          * sole constructor
152          */
153         function Email() {
154             $this->cachePath = $GLOBALS['sugar_config']['cache_dir'].'modules/Emails';
155                 parent::SugarBean();
156
157                 $this->safe = new HTML_Safe();
158                 $this->safe->clear();
159                 $this->emailAddress = new SugarEmailAddress();
160         }
161
162         function email2init() {
163                 require_once('modules/Emails/EmailUI.php');
164                 $this->et = new EmailUI();
165         }
166         function bean_implements($interface){
167                 switch($interface){
168                         case 'ACL': return true;
169                         default: return false;
170                 }
171
172         }
173
174         /**
175          * Presaves one attachment for new email 2.0 spec
176          * DOES NOT CREATE A NOTE
177          * @return string ID of note associated with the attachment
178          */
179         function email2saveAttachment() {
180                 global $sugar_config;
181
182                 $filesError = array(
183                         0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
184                         1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
185                         2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
186                         3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
187                         4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
188                         5 => 'UNKNOWN ERROR',
189                         6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
190                         7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
191                 );
192
193                 // cn: Bug 5995 - rudimentary error checking
194                 if($_FILES['email_attachment']['error'] != 0 && $_FILES['email_attachment']['error'] != 4) {
195                         $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment']['error']]);
196                         return array();
197                 }
198
199                 if(isset($_FILES['email_attachment']) && is_uploaded_file($_FILES['email_attachment']['tmp_name'])) {
200                         $guid = create_guid();
201                         $cleanAttachmentFileName = from_html($_FILES['email_attachment']['name']);
202                         $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] ");
203                         $cleanAttachmentFileName = str_replace("\\", "", $cleanAttachmentFileName);
204                         $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] ");
205                         //$destination = clean_path("{$this->et->userCacheDir}/{$guid}{$cleanAttachmentFileName}");
206                         $destination = clean_path("{$this->et->userCacheDir}/{$guid}");
207                         $badExt = $this->safeAttachmentName($cleanAttachmentFileName);
208                         if ($badExt) {
209                                 //$destination = $destination . ".txt";
210                         } // if
211                         $fileName = $badExt ? $cleanAttachmentFileName . ".txt" : $cleanAttachmentFileName;
212                         if(move_uploaded_file($_FILES['email_attachment']['tmp_name'], $destination)) {
213                                 return array(
214                                         'guid' => $guid,
215                                         'name' => $GLOBALS['db']->helper->escape_quote($fileName),
216                                         'nameForDisplay' => $fileName
217                                 );
218                         } else {
219                                 $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] could not be moved to cache dir");
220                                 return array();
221                         }
222                 }
223         }
224
225         function safeAttachmentName($filename) {
226                 global $sugar_config;
227                 $badExtension = false;
228                 //get position of last "." in file name
229                 $file_ext_beg = strrpos($filename, ".");
230                 $file_ext = "";
231
232                 //get file extension
233                 if($file_ext_beg !== false) {
234                         $file_ext = substr($filename, $file_ext_beg + 1);
235                 }
236
237                 //check to see if this is a file with extension located in "badext"
238                 foreach($sugar_config['upload_badext'] as $badExt) {
239                         if(strtolower($file_ext) == strtolower($badExt)) {
240                                 //if found, then append with .txt and break out of lookup
241                                 $filename = $filename . ".txt";
242                                 $badExtension = true;
243                                 break; // no need to look for more
244                         } // if
245                 } // foreach
246
247                 return $badExtension;
248         } // fn
249
250         /**
251          * takes output from email 2.0 to/cc/bcc fields and returns appropriate arrays for usage by PHPMailer
252          * @param string addresses
253          * @return array
254          */
255         function email2ParseAddresses($addresses) {
256                 $addresses = from_html($addresses);
257         $addresses = $this->et->unifyEmailString($addresses);
258
259                 $pattern = '/@.*,/U';
260                 preg_match_all($pattern, $addresses, $matchs);
261                 if (!empty($matchs[0])){
262                         $total = $matchs[0];
263                         foreach ($total as $match) {
264                                 $convertedPattern = str_replace(',', '::;::', $match);
265                                 $addresses = str_replace($match, $convertedPattern, $addresses);
266                         } //foreach
267                 }
268
269                 $exAddr = explode("::;::", $addresses);
270
271                 $ret = array();
272                 $clean = array("<", ">");
273                 $dirty = array("&lt;", "&gt;");
274
275                 foreach($exAddr as $addr) {
276                         $name = '';
277
278                         $addr = str_replace($dirty, $clean, $addr);
279
280                         if((strpos($addr, "<") === false) && (strpos($addr, ">") === false)) {
281                                 $address = $addr;
282                         } else {
283                                 $address = substr($addr, strpos($addr, "<") + 1, strpos($addr, ">") - 1 - strpos($addr, "<"));
284                                 $name = substr($addr, 0, strpos($addr, "<"));
285                         }
286
287                         $addrTemp = array();
288                         $addrTemp['email'] = trim($address);
289                         $addrTemp['display'] = trim($name);
290                         $ret[] = $addrTemp;
291                 }
292
293                 return $ret;
294         }
295
296         /**
297          * takes output from email 2.0 to/cc/bcc fields and returns appropriate arrays for usage by PHPMailer
298          * @param string addresses
299          * @return array
300          */
301         function email2ParseAddressesForAddressesOnly($addresses) {
302                 $addresses = from_html($addresses);
303                 $pattern = '/@.*,/U';
304                 preg_match_all($pattern, $addresses, $matchs);
305                 if (!empty($matchs[0])){
306                         $total = $matchs[0];
307                         foreach ($total as $match) {
308                                 $convertedPattern = str_replace(',', '::;::', $match);
309                                 $addresses = str_replace($match, $convertedPattern, $addresses);
310                         } //foreach
311                 }
312
313                 $exAddr = explode("::;::", $addresses);
314
315                 $ret = array();
316                 $clean = array("<", ">");
317                 $dirty = array("&lt;", "&gt;");
318
319                 foreach($exAddr as $addr) {
320                         $name = '';
321
322                         $addr = str_replace($dirty, $clean, $addr);
323
324                         if(strpos($addr, "<") && strpos($addr, ">")) {
325                                 $address = substr($addr, strpos($addr, "<") + 1, strpos($addr, ">") - 1 - strpos($addr, "<"));
326                         } else {
327                                 $address = $addr;
328                         }
329
330                         $ret[] = trim($address);
331                 }
332
333                 return $ret;
334         }
335
336         /**
337          * Determines MIME-type encoding as possible.
338          * @param string $fileLocation relative path to file
339          * @return string MIME-type
340          */
341         function email2GetMime($fileLocation) {
342             if(!is_readable($fileLocation)) {
343                 return 'application/octet-stream';
344             }
345                 if(function_exists('mime_content_type')) {
346                         $mime = mime_content_type($fileLocation);
347                 } elseif(function_exists('ext2mime')) {
348                         $mime = ext2mime($fileLocation);
349                 } else {
350                         $mime = 'application/octet-stream';
351                 }
352                 return $mime;
353         }
354
355
356         function sendEmailTest($mailserver_url, $port, $ssltls, $smtp_auth_req, $smtp_username, $smtppassword, $fromaddress, $toaddress, $mail_sendtype = 'smtp', $fromname = '') {
357                 global $current_user,$app_strings;
358                 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); //Called from EmailMan as well.
359             $mail = new SugarPHPMailer();
360                 $mail->Mailer = strtolower($mail_sendtype);
361                 if($mail->Mailer == 'smtp')
362                 {
363                 $mail->Host = $mailserver_url;
364                 $mail->Port = $port;
365                 if (isset($ssltls) && !empty($ssltls)) {
366                         $mail->protocol = "ssl://";
367                 if ($ssltls == 1) {
368                     $mail->SMTPSecure = 'ssl';
369                 } // if
370                 if ($ssltls == 2) {
371                     $mail->SMTPSecure = 'tls';
372                 } // if
373                 } else {
374                         $mail->protocol = "tcp://";
375                 }
376                 if ($smtp_auth_req) {
377                         $mail->SMTPAuth = TRUE;
378                         $mail->Username = $smtp_username;
379                         $mail->Password = $smtppassword;
380                 }
381                 }
382                 else
383                     $mail->Mailer = 'sendmail';
384
385                 $mail->Subject = from_html($mod_strings['LBL_TEST_EMAIL_SUBJECT']);
386                 $mail->From = $fromaddress;
387
388         if ($fromname != '') {
389             $mail->FromName = html_entity_decode($fromname,ENT_QUOTES);
390         } else {
391             $mail->FromName = $current_user->name;
392         }
393
394         $mail->Sender = $mail->From;
395                 $mail->AddAddress($toaddress);
396                 $mail->Body = $mod_strings['LBL_TEST_EMAIL_BODY'];
397
398                 $return = array();
399
400                 if(!$mail->Send()) {
401                 ob_clean();
402                 $return['status'] = false;
403                 $return['errorMessage'] = $app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo;
404                 return $return;
405                 } // if
406                 $return['status'] = true;
407         return $return;
408         } // fn
409
410         function decodeDuringSend($htmlData) {
411             $htmlData = str_replace("sugarLessThan", "&lt;", $htmlData);
412             $htmlData = str_replace("sugarGreaterThan", "&gt;", $htmlData);
413                 return $htmlData;
414         }
415
416         /**
417          * Returns true or false if this email is a draft.
418          *
419          * @param array $request
420          * @return bool True indicates this email is a draft.
421          */
422         function isDraftEmail($request)
423         {
424             return ( isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft') );
425         }
426
427         /**
428          * Sends Email for Email 2.0
429          */
430         function email2Send($request) {
431                 global $mod_strings;
432                 global $app_strings;
433                 global $current_user;
434                 global $sugar_config;
435                 global $locale;
436                 global $timedate;
437                 global $beanList;
438                 global $beanFiles;
439         $OBCharset = $locale->getPrecedentPreference('default_email_charset');
440
441                 /**********************************************************************
442                  * Sugar Email PREP
443                  */
444                 /* preset GUID */
445
446                 $orignialId = "";
447                 if(!empty($this->id)) {
448                         $orignialId =   $this->id;
449                 } // if
450
451                 if(empty($this->id)) {
452                         $this->id = create_guid();
453                         $this->new_with_id = true;
454                 }
455
456                 /* satisfy basic HTML email requirements */
457                 $this->name = $request['sendSubject'];
458                 $this->description_html = '&lt;html&gt;&lt;body&gt;'.$request['sendDescription'].'&lt;/body&gt;&lt;/html&gt;';
459
460                 /**********************************************************************
461                  * PHPMAILER PREP
462                  */
463                 $mail = new SugarPHPMailer();
464                 $mail = $this->setMailer($mail, '', $_REQUEST['fromAccount']);
465                 if (empty($mail->Host) && !$this->isDraftEmail($request))
466                 {
467             $this->status = 'send_error';
468
469             if ($mail->oe->type == 'system')
470                 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_SYSTEM_OUTBOUND']);
471              else
472                 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_PERSONAL_OUTBOUND']);
473
474             return false;
475                 }
476
477                 $subject = $this->name;
478                 $mail->Subject = from_html($this->name);
479
480                 // work-around legacy code in SugarPHPMailer
481                 if($_REQUEST['setEditor'] == 1) {
482                         $_REQUEST['description_html'] = $_REQUEST['sendDescription'];
483                         $this->description_html = $_REQUEST['description_html'];
484                 } else {
485                         $this->description_html = '';
486                         $this->description = $_REQUEST['sendDescription'];
487                 }
488                 // end work-around
489
490                 if ( $this->isDraftEmail($request) )
491                 {
492                         if($this->type != 'draft' && $this->status != 'draft') {
493                         $this->id = create_guid();
494                         $this->new_with_id = true;
495                         $this->date_entered = "";
496                         } // if
497                         $q1 = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$this->id}'";
498                         $r1 = $this->db->query($q1);
499                 } // if
500
501                 if (isset($request['saveDraft'])) {
502                         $this->type = 'draft';
503                         $this->status = 'draft';
504                         $forceSave = true;
505                 } else {
506                         /* Apply Email Templates */
507                         // do not parse email templates if the email is being saved as draft....
508                     $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']);
509                 $sea = new SugarEmailAddress();
510                 $object_arr = array();
511
512                         if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
513                                 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) &&
514                                 ($_REQUEST['parent_type'] == 'Accounts' ||
515                                 $_REQUEST['parent_type'] == 'Contacts' ||
516                                 $_REQUEST['parent_type'] == 'Leads' ||
517                                 $_REQUEST['parent_type'] == 'Users' ||
518                                 $_REQUEST['parent_type'] == 'Prospects')) {
519                                         if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
520                                                 $className = $beanList[$_REQUEST['parent_type']];
521                                                 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
522                                                         if(!class_exists($className)) {
523                                                                 require_once($beanFiles[$className]);
524                                                         }
525                                                         $bean = new $className();
526                                                         $bean->retrieve($_REQUEST['parent_id']);
527                                         $object_arr[$bean->module_dir] = $bean->id;
528                                                 } // if
529                                         } // if
530                         }
531                         foreach($toAddresses as $addrMeta) {
532                                 $addr = $addrMeta['email'];
533                                 $beans = $sea->getBeansByEmailAddress($addr);
534                                 foreach($beans as $bean) {
535                                         if (!isset($object_arr[$bean->module_dir])) {
536                                                 $object_arr[$bean->module_dir] = $bean->id;
537                                         }
538                                 }
539                         }
540
541                 /* template parsing */
542                 if (empty($object_arr)) {
543                   $object_arr= array('Contacts' => '123');
544                 }
545                 $object_arr['Users'] = $current_user->id;
546                 $this->description_html = EmailTemplate::parse_template($this->description_html, $object_arr);
547                 $this->name = EmailTemplate::parse_template($this->name, $object_arr);
548                 $this->description = EmailTemplate::parse_template($this->description, $object_arr);
549                 $this->description = html_entity_decode($this->description,ENT_COMPAT,'UTF-8');
550                         if($this->type != 'draft' && $this->status != 'draft') {
551                         $this->id = create_guid();
552                         $this->date_entered = "";
553                         $this->new_with_id = true;
554                         $this->type = 'out';
555                         $this->status = 'sent';
556                         }
557         }
558
559         if(isset($_REQUEST['parent_type']) && empty($_REQUEST['parent_type']) &&
560                         isset($_REQUEST['parent_id']) && empty($_REQUEST['parent_id']) ) {
561                                 $this->parent_id = "";
562                                 $this->parent_type = "";
563                 } // if
564
565
566         $mail->Subject = $this->name;
567         $mail = $this->handleBody($mail);
568         $mail->Subject = $this->name;
569         $this->description_html = from_html($this->description_html);
570         $this->description_html = $this->decodeDuringSend($this->description_html);
571                 $this->description = $this->decodeDuringSend($this->description);
572
573                 /* from account */
574                 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
575                 $replyToName = "";
576                 if(empty($request['fromAccount'])) {
577                         $defaults = $current_user->getPreferredEmail();
578                         $mail->From = $defaults['email'];
579                         $mail->FromName = $defaults['name'];
580                         $replyToName = $mail->FromName;
581                         //$replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
582                 } else {
583                         // passed -> user -> system default
584                         $ie = new InboundEmail();
585                         $ie->retrieve($request['fromAccount']);
586                         $storedOptions = unserialize(base64_decode($ie->stored_options));
587                         $fromName = "";
588                         $fromAddress = "";
589                         $replyToName = "";
590                         //$replyToAddress = "";
591                         if (!empty($storedOptions)) {
592                                 $fromAddress = $storedOptions['from_addr'];
593                                 $fromName = from_html($storedOptions['from_name']);
594                                 $replyToAddress = (isset($storedOptions['reply_to_addr']) ? $storedOptions['reply_to_addr'] : "");
595                                 $replyToName = (isset($storedOptions['reply_to_name']) ? from_html($storedOptions['reply_to_name']) : "");
596                         } // if
597                         $defaults = $current_user->getPreferredEmail();
598                         // Personal Account doesn't have reply To Name and Reply To Address. So add those columns on UI
599                         // After adding remove below code
600
601                         // code to remove
602                         if ($ie->is_personal)
603                         {
604                                 if (empty($replyToAddress))
605                                 {
606                                         $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
607                                 } // if
608                                 if (empty($replyToName))
609                                 {
610                                         $replyToName = $defaults['name'];
611                                 } // if
612                                 //Personal accounts can have a reply_address, which should
613                                 //overwrite the users set default.
614                                 if( !empty($storedOptions['reply_to_addr']) )
615                                         $replyToAddress = $storedOptions['reply_to_addr'];
616
617                         }
618                         // end of code to remove
619                         $mail->From = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
620                         $mail->FromName = (!empty($fromName)) ? $fromName : $defaults['name'];
621                         $replyToName = (!empty($replyToName)) ? $replyToName : $mail->FromName;
622                 }
623
624                 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
625
626                 if (!empty($replyToAddress)) {
627                         $mail->AddReplyTo($replyToAddress,$locale->translateCharsetMIME(trim( $replyToName), 'UTF-8', $OBCharset));
628                 } else {
629                         $mail->AddReplyTo($mail->From,$locale->translateCharsetMIME(trim( $mail->FromName), 'UTF-8', $OBCharset));
630                 } // else
631         $emailAddressCollection = array(); // used in linking to beans below
632                 // handle to/cc/bcc
633                 foreach($this->email2ParseAddresses($request['sendTo']) as $addr_arr) {
634                         if(empty($addr_arr['email'])) continue;
635
636                         if(empty($addr_arr['display'])) {
637                                 $mail->AddAddress($addr_arr['email'], "");
638                         } else {
639                                 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
640                         }
641                         $emailAddressCollection[] = $addr_arr['email'];
642                 }
643                 foreach($this->email2ParseAddresses($request['sendCc']) as $addr_arr) {
644                         if(empty($addr_arr['email'])) continue;
645
646                         if(empty($addr_arr['display'])) {
647                                 $mail->AddCC($addr_arr['email'], "");
648                         } else {
649                                 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
650                         }
651                         $emailAddressCollection[] = $addr_arr['email'];
652                 }
653
654                 foreach($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) {
655                         if(empty($addr_arr['email'])) continue;
656
657                         if(empty($addr_arr['display'])) {
658                                 $mail->AddBCC($addr_arr['email'], "");
659                         } else {
660                                 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
661                         }
662                         $emailAddressCollection[] = $addr_arr['email'];
663                 }
664
665
666                 /* parse remove attachments array */
667                 $removeAttachments = array();
668                 if(!empty($request['templateAttachmentsRemove'])) {
669                         $exRemove = explode("::", $request['templateAttachmentsRemove']);
670
671                         foreach($exRemove as $file) {
672                                 $removeAttachments = substr($file, 0, 36);
673                         }
674                 }
675
676                 /* handle attachments */
677                 if(!empty($request['attachments'])) {
678                         $exAttachments = explode("::", $request['attachments']);
679
680                         foreach($exAttachments as $file) {
681                                 $file = trim(from_html($file));
682                                 $file = str_replace("\\", "", $file);
683                                 if(!empty($file)) {
684                                         //$fileLocation = $this->et->userCacheDir."/{$file}";
685                                         $fileGUID = substr($file, 0, 36);
686                                         $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
687                                         $filename = substr($file, 36, strlen($file)); // strip GUID     for PHPMailer class to name outbound file
688
689                                         $mail->AddAttachment($fileLocation,$filename, 'base64', $this->email2GetMime($fileLocation));
690                                         //$mail->AddAttachment($fileLocation, $filename, 'base64');
691
692                                         // only save attachments if we're archiving or drafting
693                                         if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
694                                                 $note = new Note();
695                                                 $note->id = create_guid();
696                                                 $note->new_with_id = true; // duplicating the note with files
697                                                 $note->parent_id = $this->id;
698                                                 $note->parent_type = $this->module_dir;
699                                                 $note->name = $filename;
700                                                 $note->filename = $filename;
701                                                 $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
702                                                 $note->file_mime_type = $this->email2GetMime($fileLocation);
703
704                                                 if(!copy($fileLocation, $noteFile)) {
705                                                         $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to cache/upload [ {$fileLocation} ]");
706                                                 }
707
708                                                 $note->save();
709                                         }
710                                 }
711                         }
712                 }
713
714                 /* handle sugar documents */
715                 if(!empty($request['documents'])) {
716                         $exDocs = explode("::", $request['documents']);
717
718
719
720
721                         foreach($exDocs as $docId) {
722                                 $docId = trim($docId);
723                                 if(!empty($docId)) {
724                                         $doc = new Document();
725                                         $docRev = new DocumentRevision();
726                                         $doc->retrieve($docId);
727                                         $docRev->retrieve($doc->document_revision_id);
728
729                                         $filename = $docRev->filename;
730                                         $fileLocation = "{$sugar_config['upload_dir']}{$docRev->id}";
731                                         $mime_type = $docRev->file_mime_type;
732                                         $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
733
734                                         // only save attachments if we're archiving or drafting
735                                         if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
736                                                 $note = new Note();
737                                                 $note->id = create_guid();
738                                                 $note->new_with_id = true; // duplicating the note with files
739                                                 $note->parent_id = $this->id;
740                                                 $note->parent_type = $this->module_dir;
741                                                 $note->name = $filename;
742                                                 $note->filename = $filename;
743                                                 $note->file_mime_type = $mime_type;
744                                                 $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
745
746                                                 if(!copy($fileLocation, $noteFile)) {
747                                                         $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
748                                                 }
749
750                                                 $note->save();
751                                         }
752                                 }
753                         }
754                 }
755
756                 /* handle template attachments */
757                 if(!empty($request['templateAttachments'])) {
758
759                         $exNotes = explode("::", $request['templateAttachments']);
760                         foreach($exNotes as $noteId) {
761                                 $noteId = trim($noteId);
762                                 if(!empty($noteId)) {
763                                         $note = new Note();
764                                         $note->retrieve($noteId);
765                                         if (!empty($note->id)) {
766                                                 $filename = $note->filename;
767                                                 $fileLocation = "{$sugar_config['upload_dir']}{$note->id}";
768                                                 $mime_type = $note->file_mime_type;
769                                                 if (!$note->embed_flag) {
770                                                         $mail->AddAttachment($fileLocation,$filename, 'base64', $mime_type);
771                                                         // only save attachments if we're archiving or drafting
772                                                         if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
773
774                                                                 if ($note->parent_id != $this->id)
775                                                                     $this->saveTempNoteAttachments($filename,$fileLocation, $mime_type);
776                                                         } // if
777
778                                                 } // if
779                                         } else {
780                                                 //$fileLocation = $this->et->userCacheDir."/{$file}";
781                                                 $fileGUID = substr($noteId, 0, 36);
782                                                 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
783                                                 //$fileLocation = $this->et->userCacheDir."/{$noteId}";
784                                                 $filename = substr($noteId, 36, strlen($noteId)); // strip GUID for PHPMailer class to name outbound file
785
786                                                 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $this->email2GetMime($fileLocation));
787
788                                                 //If we are saving an email we were going to forward we need to save the attachments as well.
789                                                 if( (($this->type == 'draft') && !empty($this->id))
790                                                       || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1))
791                                                   {
792                                                       $mimeType = $this->email2GetMime($fileLocation);
793                                                       $this->saveTempNoteAttachments($filename,$fileLocation, $mimeType);
794                                                  } // if
795                                         }
796                                 }
797                         }
798                 }
799
800
801
802                 /**********************************************************************
803                  * Final Touches
804                  */
805                 /* save email to sugar? */
806                 $forceSave = false;
807
808                 if($this->type == 'draft' && !isset($request['saveDraft'])) {
809                         // sending a draft email
810                         $this->type = 'out';
811                         $this->status = 'sent';
812                         $forceSave = true;
813                 } elseif(isset($request['saveDraft'])) {
814                         $this->type = 'draft';
815                         $this->status = 'draft';
816                         $forceSave = true;
817                 }
818
819                       /**********************************************************************
820          * SEND EMAIL (finally!)
821          */
822         $mailSent = false;
823         if ($this->type != 'draft') {
824             $mail->prepForOutbound();
825             $mail->Body = $this->decodeDuringSend($mail->Body);
826             $mail->AltBody = $this->decodeDuringSend($mail->AltBody);
827             if (!$mail->Send()) {
828                 $this->status = 'send_error';
829                 ob_clean();
830                 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo);
831                 return false;
832             }
833         }
834
835                 if ((!(empty($orignialId) || isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft'))) &&
836                         (($_REQUEST['composeType'] == 'reply') || ($_REQUEST['composeType'] == 'replyAll') || ($_REQUEST['composeType'] == 'replyCase')) && ($orignialId != $this->id)) {
837                         $originalEmail = new Email();
838                         $originalEmail->retrieve($orignialId);
839                         $originalEmail->reply_to_status = 1;
840                         $originalEmail->save();
841                         $this->reply_to_status = 0;
842                 } // if
843
844                 if ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase') {
845                         if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) {
846                                 $emailFromIe = new InboundEmail();
847                                 $emailFromIe->retrieve($_REQUEST['ieId']);
848                                 $emailFromIe->mailbox = $_REQUEST['mbox'];
849                                 if (isset($emailFromIe->id) && $emailFromIe->is_personal) {
850                                         if ($emailFromIe->isPop3Protocol()) {
851                                                 $emailFromIe->mark_answered($this->uid, 'pop3');
852                                         }
853                                         elseif ($emailFromIe->connectMailserver() == 'true') {
854                                                 $emailFromIe->markEmails($this->uid, 'answered');
855                                                 $emailFromIe->mark_answered($this->uid);
856                                         }
857                                 }
858                         }
859                 }
860
861
862                 if(     $forceSave ||
863                         $this->type == 'draft' ||
864                         (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
865
866                         // saving a draft OR saving a sent email
867                         $decodedFromName = mb_decode_mimeheader($mail->FromName);
868                         $this->from_addr = "{$decodedFromName} <{$mail->From}>";
869                         $this->from_addr_name = $this->from_addr;
870                         $this->to_addrs = $_REQUEST['sendTo'];
871                         $this->to_addrs_names = $_REQUEST['sendTo'];
872                         $this->cc_addrs = $_REQUEST['sendCc'];
873                         $this->cc_addrs_names = $_REQUEST['sendCc'];
874                         $this->bcc_addrs = $_REQUEST['sendBcc'];
875                         $this->bcc_addrs_names = $_REQUEST['sendBcc'];
876                         $this->assigned_user_id = $current_user->id;
877
878                         $this->date_sent = $timedate->now();
879                         ///////////////////////////////////////////////////////////////////
880                         ////    LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
881
882                         if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
883                                 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) ) {
884                         $this->parent_id = $_REQUEST['parent_id'];
885                         $this->parent_type = $_REQUEST['parent_type'];
886                                         $q = "SELECT count(*) c FROM emails_beans WHERE  email_id = '{$this->id}' AND bean_id = '{$_REQUEST['parent_id']}' AND bean_module = '{$_REQUEST['parent_type']}'";
887                                         $r = $this->db->query($q);
888                                         $a = $this->db->fetchByAssoc($r);
889                                         if($a['c'] <= 0) {
890                                                 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
891                                                         $className = $beanList[$_REQUEST['parent_type']];
892                                                         if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
893                                                                 if(!class_exists($className)) {
894                                                                         require_once($beanFiles[$className]);
895                                                                 }
896                                                                 $bean = new $className();
897                                                                 $bean->retrieve($_REQUEST['parent_id']);
898                                                                 if($bean->load_relationship('emails')) {
899                                                                         $bean->emails->add($this->id);
900                                                                 } // if
901
902                                                         } // if
903
904                                                 } // if
905
906                                         } // if
907
908                                 } else {
909                                         if(!class_exists('aCase')) {
910
911                                         }
912                                         else{
913                                                 $c = new aCase();
914                                                 if($caseId = InboundEmail::getCaseIdFromCaseNumber($mail->Subject, $c)) {
915                                                         $c->retrieve($caseId);
916                                                         $c->load_relationship('emails');
917                                                         $c->emails->add($this->id);
918                                                         $this->parent_type = "Cases";
919                                                         $this->parent_id = $caseId;
920                                                 } // if
921                                         }
922
923                                 } // else
924
925                         ////    LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
926                         ///////////////////////////////////////////////////////////////////
927                         $this->save();
928                 }
929
930                 if(!empty($request['fromAccount'])) {
931                         if (isset($ie->id) && !$ie->isPop3Protocol()) {
932                                 $sentFolder = $ie->get_stored_options("sentFolder");
933                                 if (!empty($sentFolder)) {
934                                         $data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n";
935                                         $ie->mailbox = $sentFolder;
936                                         if ($ie->connectMailserver() == 'true') {
937                                                 $connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox);
938                                                 $returnData = imap_append($ie->conn,$connectString, $data, "\\Seen");
939                                                 if (!$returnData) {
940                                                         $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}");
941                                                 } // if
942                                         } else {
943                                                 $GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}");
944                                         } // else
945                                 } else {
946                                         $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty");
947                                 } // else
948                         } // if
949                 } // if
950                 return true;
951         } // end email2send
952
953         /**
954          * Generates a comma sperated name and addresses to be used in compose email screen for contacts or leads
955          * from listview
956          *
957          * @param $module string module name
958          * @param $idsArray array of record ids to get the email address for
959          * @return string comma delimited list of email addresses
960          */
961         public function getNamePlusEmailAddressesForCompose($module, $idsArray)
962         {
963                 global $locale;
964                 global $db;
965                 $table = SugarModule::get($module)->loadBean()->table_name;
966                 $returndata = array();
967                 $idsString = "";
968                 foreach($idsArray as $id) {
969                         if ($idsString != "") {
970                                 $idsString = $idsString . ",";
971                         } // if
972                         $idsString = $idsString . "'" . $id . "'";
973                 } // foreach
974                 $where = "({$table}.deleted = 0 AND {$table}.id in ({$idsString}))";
975
976                 if ($module == 'Users' || $module == 'Employees') {
977                         $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.title";
978                 }
979                 elseif (SugarModule::get($module)->moduleImplements('Person')) {
980                         $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.salutation, {$table}.title";
981                 }
982                 else {
983                     $selectColumn = "{$table}.name";
984                 }
985                 $query = "SELECT {$table}.id, {$selectColumn}, eabr.primary_address, ea.email_address";
986                 $query .= " FROM {$table} ";
987                 $query .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
988                 $query .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
989                 $query .= " WHERE ({$where}) ORDER BY eabr.primary_address DESC";
990                 $r = $this->db->query($query);
991
992                 while($a = $this->db->fetchByAssoc($r)) {
993                         if (!isset($returndata[$a['id']])) {
994                                 if ($module == 'Users' || $module == 'Employees') {
995                                     $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], '', $a['title']));
996                                         $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
997                                 }
998                                 elseif (SugarModule::get($module)->moduleImplements('Person')) {
999                                         $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], $a['salutation'], $a['title']));
1000                                         $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
1001                                 }
1002                                 else {
1003                                         $returndata[$a['id']] = from_html($a['name']) . " <".from_html($a['email_address']).">";
1004                                 } // else
1005                         }
1006                 }
1007
1008                 return join(",", array_values($returndata));
1009     }
1010
1011         /**
1012          * Overrides
1013          */
1014         ///////////////////////////////////////////////////////////////////////////
1015         ////    SAVERS
1016         function save($check_notify = false) {
1017                 if($this->isDuplicate) {
1018                         $GLOBALS['log']->debug("EMAIL - tried to save a duplicate Email record");
1019                 } else {
1020
1021                         if(empty($this->id)) {
1022                                 $this->id = create_guid();
1023                                 $this->new_with_id = true;
1024                         }
1025                         $this->from_addr_name = $this->cleanEmails($this->from_addr_name);
1026                         $this->to_addrs_names = $this->cleanEmails($this->to_addrs_names);
1027                         $this->cc_addrs_names = $this->cleanEmails($this->cc_addrs_names);
1028                         $this->bcc_addrs_names = $this->cleanEmails($this->bcc_addrs_names);
1029                         $this->reply_to_addr = $this->cleanEmails($this->reply_to_addr);
1030                         $this->description = to_html($this->safeText(from_html($this->description)));
1031                         $this->description_html = $this->safeText($this->description_html);
1032                         $this->saveEmailText();
1033                         $this->saveEmailAddresses();
1034
1035                         $GLOBALS['log']->debug('-------------------------------> Email called save()');
1036
1037                         // handle legacy concatenation of date and time fields
1038                         if(empty($this->date_sent)) $this->date_sent = $this->date_start." ".$this->time_start;
1039
1040                         parent::save($check_notify);
1041
1042                         if(!empty($this->parent_type) && !empty($this->parent_id)) {
1043                 if(!empty($this->fetched_row) && !empty($this->fetched_row['parent_id']) && !empty($this->fetched_row['parent_type'])) {
1044                     if($this->fetched_row['parent_id'] != $this->parent_id || $this->fetched_row['parent_type'] != $this->parent_type) {
1045                         $mod = strtolower($this->fetched_row['parent_type']);
1046                         $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1047                         if($this->load_relationship($rel) ) {
1048                             $this->$rel->delete($this->id, $this->fetched_row['parent_id']);
1049                         }
1050                     } else {
1051                         // we already have this relationship, don't add it
1052                         return;
1053                     }
1054                 }
1055                 $mod = strtolower($this->parent_type);
1056                 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1057                 if($this->load_relationship($rel) ) {
1058                     $this->$rel->add($this->parent_id);
1059                 }
1060                         }
1061                 }
1062         }
1063
1064         /**
1065          * Helper function to save temporary attachments assocaited to an email as note.
1066          *
1067          * @param string $filename
1068          * @param string $fileLocation
1069          * @param string $mimeType
1070          */
1071         function saveTempNoteAttachments($filename,$fileLocation, $mimeType)
1072         {
1073             global $sugar_config;
1074
1075             $tmpNote = new Note();
1076             $tmpNote->id = create_guid();
1077             $tmpNote->new_with_id = true;
1078             $tmpNote->parent_id = $this->id;
1079             $tmpNote->parent_type = $this->module_dir;
1080             $tmpNote->name = $filename;
1081             $tmpNote->filename = $filename;
1082             $tmpNote->file_mime_type = $mimeType;
1083             $noteFile = "{$sugar_config['upload_dir']}{$tmpNote->id}";
1084             if(!copy($fileLocation, $noteFile))
1085             $GLOBALS['log']->fatal("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
1086             $tmpNote->save();
1087         }
1088         /**
1089          * Handles normalization of Email Addressess
1090          */
1091         function saveEmailAddresses() {
1092                 // from, single address
1093                 $fromId = $this->emailAddress->getEmailGUID(from_html($this->from_addr));
1094         if(!empty($fromId)){
1095                   $this->linkEmailToAddress($fromId, 'from');
1096         }
1097
1098                 // to, multiple
1099                 $replace = array(",",";");
1100                 $toaddrs = str_replace($replace, "::", from_html($this->to_addrs));
1101                 $exToAddrs = explode("::", $toaddrs);
1102
1103                 if(!empty($exToAddrs)) {
1104                         foreach($exToAddrs as $toaddr) {
1105                                 $toaddr = trim($toaddr);
1106                                 if(!empty($toaddr)) {
1107                                         $toId = $this->emailAddress->getEmailGUID($toaddr);
1108                                         $this->linkEmailToAddress($toId, 'to');
1109                                 }
1110                         }
1111                 }
1112
1113                 // cc, multiple
1114                 $ccAddrs = str_replace($replace, "::", from_html($this->cc_addrs));
1115                 $exccAddrs = explode("::", $ccAddrs);
1116
1117                 if(!empty($exccAddrs)) {
1118                         foreach($exccAddrs as $ccAddr) {
1119                                 $ccAddr = trim($ccAddr);
1120                                 if(!empty($ccAddr)) {
1121                                         $ccId = $this->emailAddress->getEmailGUID($ccAddr);
1122                                         $this->linkEmailToAddress($ccId, 'cc');
1123                                 }
1124                         }
1125                 }
1126
1127                 // bcc, multiple
1128                 $bccAddrs = str_replace($replace, "::", from_html($this->bcc_addrs));
1129                 $exbccAddrs = explode("::", $bccAddrs);
1130                 if(!empty($exbccAddrs)) {
1131                         foreach($exbccAddrs as $bccAddr) {
1132                                 $bccAddr = trim($bccAddr);
1133                                 if(!empty($bccAddr)) {
1134                                         $bccId = $this->emailAddress->getEmailGUID($bccAddr);
1135                                         $this->linkEmailToAddress($bccId, 'bcc');
1136                                 }
1137                         }
1138                 }
1139         }
1140
1141         function linkEmailToAddress($id, $type) {
1142                 // TODO: make this update?
1143                 $q1 = "SELECT * FROM emails_email_addr_rel WHERE email_id = '{$this->id}' AND email_address_id = '{$id}' AND address_type = '{$type}' AND deleted = 0";
1144                 $r1 = $this->db->query($q1);
1145                 $a1 = $this->db->fetchByAssoc($r1);
1146
1147                 if(!empty($a1) && !empty($a1['id'])) {
1148                         return $a1['id'];
1149                 } else {
1150                         $guid = create_guid();
1151                         $q2 = "INSERT INTO emails_email_addr_rel VALUES('{$guid}', '{$this->id}', '{$type}', '{$id}', 0)";
1152                         $r2 = $this->db->query($q2);
1153                 }
1154
1155                 return $guid;
1156         }
1157
1158         function cleanEmails($emails)
1159         {
1160                 $emails = str_replace(array(",",";"), "::", from_html($emails));
1161                 $addrs = explode("::", $emails);
1162                 $res = array();
1163                 foreach($addrs as $addr) {
1164             $parts = $this->emailAddress->splitEmailAddress($addr);
1165             if(empty($parts["email"])) {
1166                 continue;
1167             }
1168             if(!empty($parts["name"])) {
1169                 $res[] = "{$parts["name"]} <{$parts["email"]}>";
1170             } else {
1171                 $res[] .= $parts["email"];
1172             }
1173                 }
1174         return join(", ", $res);
1175         }
1176
1177         function saveEmailText() {
1178                 $isOracle = ($this->db->dbType == "oci8") ? true : false;
1179                 if ($isOracle) {
1180                 } else {
1181                         $description = $this->db->quote(trim($this->description));
1182                         $description_html = $this->db->quoteForEmail(trim($this->description_html));
1183                         $raw_source = $this->db->quote(trim($this->raw_source));
1184                         $fromAddressName = $this->db->helper->escape_quote($this->from_addr_name);
1185                         $toAddressName = $this->db->helper->escape_quote($this->to_addrs_names);
1186                         $ccAddressName = $this->db->helper->escape_quote($this->cc_addrs_names);
1187                         $bccAddressName = $this->db->helper->escape_quote($this->bcc_addrs_names);
1188                         $replyToAddrName = $this->db->helper->escape_quote($this->reply_to_addr);
1189
1190                         if(!$this->new_with_id) {
1191                                 $q = "UPDATE emails_text SET from_addr = '{$fromAddressName}', to_addrs = '{$toAddressName}', cc_addrs = '{$ccAddressName}', bcc_addrs = '{$bccAddressName}', reply_to_addr = '{$replyToAddrName}', description = '{$description}', description_html = '{$description_html}', raw_source = '{$raw_source}' WHERE email_id = '{$this->id}'";
1192                         } else {
1193                                 $q = "INSERT INTO emails_text (email_id, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to_addr, description, description_html, raw_source, deleted) VALUES('{$this->id}', '{$fromAddressName}', '{$toAddressName}', '{$ccAddressName}', '{$bccAddressName}', '{$replyToAddrName}', '{$description}', '{$description_html}', '{$raw_source}', 0)";
1194                         }
1195                         $this->db->query($q);
1196
1197                 } // else
1198         }
1199
1200
1201         ///////////////////////////////////////////////////////////////////////////
1202         ////    RETRIEVERS
1203         function retrieve($id, $encoded=true, $deleted=true) {
1204                 // cn: bug 11915, return SugarBean's retrieve() call bean instead of $this
1205                 $ret = parent::retrieve($id, $encoded, $deleted);
1206
1207                 if($ret) {
1208                         $ret->retrieveEmailText();
1209                         $ret->retrieveEmailAddresses();
1210                         $ret->raw_source = to_html($ret->safeText(from_html($ret->raw_source)));
1211                         $ret->description = to_html($ret->safeText(from_html($ret->description)));
1212                         $ret->description_html = $ret->safeText($ret->description_html);
1213
1214                         $ret->date_start = '';
1215                         $ret->time_start = '';
1216                         $dateSent = explode(' ', $ret->date_sent);
1217                         if (!empty($dateSent)) {
1218                             $ret->date_start = $dateSent[0];
1219                             if ( isset($dateSent[1]) )
1220                                 $ret->time_start = $dateSent[1];
1221                         }
1222                         // for Email 2.0
1223                         foreach($ret as $k => $v) {
1224                                 $this->$k = $v;
1225                         }
1226                 }
1227                 return $ret;
1228         }
1229
1230
1231         /**
1232          * Retrieves email addresses from GUIDs
1233          */
1234         function retrieveEmailAddresses() {
1235                 $return = array();
1236
1237                 $q = "SELECT email_address, address_type
1238                                 FROM emails_email_addr_rel eam
1239                                 JOIN email_addresses ea ON ea.id = eam.email_address_id
1240                                 WHERE eam.email_id = '{$this->id}' AND eam.deleted=0";
1241                 $r = $this->db->query($q);
1242
1243                 while($a = $this->db->fetchByAssoc($r)) {
1244                         if(!isset($return[$a['address_type']])) {
1245                                 $return[$a['address_type']] = array();
1246                         }
1247                         $return[$a['address_type']][] = $a['email_address'];
1248                 }
1249
1250                 if(count($return) > 0) {
1251                         if(isset($return['from'])) {
1252                                 $this->from_addr = implode(", ", $return['from']);
1253                         }
1254                         if(isset($return['to'])) {
1255                                 $this->to_addrs = implode(", ", $return['to']);
1256                         }
1257                         if(isset($return['cc'])) {
1258                                 $this->cc_addrs = implode(", ", $return['cc']);
1259                         }
1260                         if(isset($return['bcc'])) {
1261                                 $this->bcc_addrs = implode(", ", $return['bcc']);
1262                         }
1263                 }
1264         }
1265
1266         /**
1267          * Handles longtext fields
1268          */
1269         function retrieveEmailText() {
1270                 $q = "SELECT from_addr, reply_to_addr, to_addrs, cc_addrs, bcc_addrs, description, description_html, raw_source FROM emails_text WHERE email_id = '{$this->id}'";
1271                 $r = $this->db->query($q);
1272                 $a = $this->db->fetchByAssoc($r, -1, false);
1273
1274                 $this->description = $a['description'];
1275                 $this->description_html = $a['description_html'];
1276                 $this->raw_source = $a['raw_source'];
1277                 $this->from_addr_name = $a['from_addr'];
1278                 $this->reply_to_addr  = $a['reply_to_addr'];
1279                 $this->to_addrs_names = $a['to_addrs'];
1280                 $this->cc_addrs_names = $a['cc_addrs'];
1281                 $this->bcc_addrs_names = $a['bcc_addrs'];
1282         }
1283
1284         function delete($id='') {
1285                 if(empty($id))
1286                         $id = $this->id;
1287
1288                 $q  = "UPDATE emails SET deleted = 1 WHERE id = '{$id}'";
1289                 $qt = "UPDATE emails_text SET deleted = 1 WHERE email_id = '{$id}'";
1290                 $r  = $this->db->query($q);
1291                 $rt = $this->db->query($qt);
1292         }
1293
1294         /**
1295          * creates the standard "Forward" info at the top of the forwarded message
1296          * @return string
1297          */
1298         function getForwardHeader() {
1299                 global $mod_strings;
1300                 global $current_user;
1301
1302                 //$from = str_replace(array("&gt;","&lt;"), array(")","("), $this->from_name);
1303                 $from = to_html($this->from_name);
1304                 $subject = to_html($this->name);
1305                 $ret  = "<br /><br />";
1306                 $ret .= $this->replyDelimiter."{$mod_strings['LBL_FROM']} {$from}<br />";
1307                 $ret .= $this->replyDelimiter."{$mod_strings['LBL_DATE_SENT']} {$this->date_sent}<br />";
1308                 $ret .= $this->replyDelimiter."{$mod_strings['LBL_TO']} {$this->to_addrs}<br />";
1309                 $ret .= $this->replyDelimiter."{$mod_strings['LBL_CC']} {$this->cc_addrs}<br />";
1310                 $ret .= $this->replyDelimiter."{$mod_strings['LBL_SUBJECT']} {$subject}<br />";
1311                 $ret .= $this->replyDelimiter."<br />";
1312
1313                 return $ret;
1314                 //return from_html($ret);
1315         }
1316
1317     /**
1318      * retrieves Notes that belong to this Email and stuffs them into the "attachments" attribute
1319      */
1320     function getNotes($id, $duplicate=false) {
1321         if(!class_exists('Note')) {
1322
1323         }
1324
1325         $exRemoved = array();
1326                 if(isset($_REQUEST['removeAttachment'])) {
1327                         $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1328                 }
1329
1330         $noteArray = array();
1331         $q = "SELECT id FROM notes WHERE parent_id = '".$id."'";
1332         $r = $this->db->query($q);
1333
1334         while($a = $this->db->fetchByAssoc($r)) {
1335                 if(!in_array($a['id'], $exRemoved)) {
1336                     $note = new Note();
1337                     $note->retrieve($a['id']);
1338
1339                     // duplicate actual file when creating forwards
1340                         if($duplicate) {
1341                                 if(!class_exists('UploadFile')) {
1342                                         require_once('include/upload_file.php');
1343                                 }
1344                                 // save a brand new Note
1345                                 $noteDupe->id = create_guid();
1346                                 $noteDupe->new_with_id = true;
1347                                         $noteDupe->parent_id = $this->id;
1348                                         $noteDupe->parent_type = $this->module_dir;
1349
1350                                         $noteFile = new UploadFile('none');
1351                                         $noteFile->duplicate_file($a['id'], $note->id, $note->filename);
1352
1353                                         $note->save();
1354                         }
1355                         // add Note to attachments array
1356                     $this->attachments[] = $note;
1357                 }
1358         }
1359     }
1360
1361         /**
1362          * creates the standard "Reply" info at the top of the forwarded message
1363          * @return string
1364          */
1365         function getReplyHeader() {
1366                 global $mod_strings;
1367                 global $current_user;
1368
1369                 $from = str_replace(array("&gt;","&lt;", ">","<"), array(")","(",")","("), $this->from_name);
1370                 $ret  = "<br>{$mod_strings['LBL_REPLY_HEADER_1']} {$this->date_start}, {$this->time_start}, {$from} {$mod_strings['LBL_REPLY_HEADER_2']}";
1371
1372                 return from_html($ret);
1373         }
1374
1375         /**
1376          * Quotes plain-text email text
1377          * @param string $text
1378          * @return string
1379          */
1380         function quotePlainTextEmail($text) {
1381                 $quoted = "\n";
1382
1383                 // plain-text
1384                 $desc = nl2br(trim($text));
1385                 $exDesc = explode('<br />', $desc);
1386
1387                 foreach($exDesc as $k => $line) {
1388                         $quoted .= '> '.trim($line)."\r";
1389                 }
1390
1391                 return $quoted;
1392         }
1393
1394         /**
1395          * "quotes" (i.e., "> my text yadda" the HTML part of an email
1396          * @param string $text HTML text to quote
1397          * @return string
1398          */
1399         function quoteHtmlEmail($text) {
1400                 $text = trim(from_html($text));
1401
1402                 if(empty($text)) {
1403                         return '';
1404                 }
1405                 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1406
1407                 return $out;
1408         }
1409
1410         /**
1411          * "quotes" (i.e., "> my text yadda" the HTML part of an email
1412          * @param string $text HTML text to quote
1413          * @return string
1414          */
1415         function quoteHtmlEmailForNewEmailUI($text) {
1416                 $text = trim($text);
1417
1418                 if(empty($text)) {
1419                         return '';
1420                 }
1421                 $text = str_replace("\n", "\n<BR/>", $text);
1422                 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1423
1424                 return $out;
1425         }
1426
1427
1428
1429         ///////////////////////////////////////////////////////////////////////////
1430         ////    LEGACY CODE
1431         /**
1432          * Safes description text (both HTML and Plain Text) for display
1433          * @param string str The text to safe
1434          * @return string Safed text
1435          */
1436         function safeText($str) {
1437                 // Safe_HTML
1438                 $this->safe->clear();
1439                 $ret = $this->safe->parse($str);
1440
1441                 // Julian's XSS cleaner
1442                 $potentials = clean_xss($str, false);
1443
1444                 if(is_array($potentials) && !empty($potentials)) {
1445                         //_ppl($potentials);
1446                         foreach($potentials as $bad) {
1447                                 $ret = str_replace($bad, "", $ret);
1448                         }
1449                 }
1450
1451                 // clean <HTML> and <BODY> tags
1452                 $html = '#<\\\\\?HTML[\w =\'\"\&]*>#sim';
1453                 $body = '#<\\\\\?BODY[\w =\'\"\&]*>#sim';
1454
1455                 $ret = preg_replace($html, "", $ret);
1456                 $ret = preg_replace($body, "", $ret);
1457
1458                 return $ret;
1459         }
1460
1461         /**
1462          * Ensures that the user is able to send outbound emails
1463          */
1464         function check_email_settings() {
1465                 global $current_user;
1466
1467                 $mail_fromaddress = $current_user->emailAddress->getPrimaryAddress($current_user);
1468                 $replyToName = $current_user->getPreference('mail_fromname');
1469                 $mail_fromname = (!empty($replyToName)) ? $current_user->getPreference('mail_fromname') : $current_user->full_name;
1470
1471                 if(empty($mail_fromaddress)) {
1472                         return false;
1473                 }
1474                 if(empty($mail_fromname)) {
1475                         return false;
1476                 }
1477
1478         $send_type = $current_user->getPreference('mail_sendtype') ;
1479                 if (!empty($send_type) && $send_type == "SMTP") {
1480                         $mail_smtpserver = $current_user->getPreference('mail_smtpserver');
1481                         $mail_smtpport = $current_user->getPreference('mail_smtpport');
1482                         $mail_smtpauth_req = $current_user->getPreference('mail_smtpauth_req');
1483                         $mail_smtpuser = $current_user->getPreference('mail_smtpuser');
1484                         $mail_smtppass = $current_user->getPreference('mail_smtppass');
1485                         if (empty($mail_smtpserver) ||
1486                                 empty($mail_smtpport) ||
1487                 (!empty($mail_smtpauth_req) && ( empty($mail_smtpuser) || empty($mail_smtppass)))
1488                         ) {
1489                                 return false;
1490                         }
1491                 }
1492                 return true;
1493         }
1494
1495         /**
1496          * outputs JS to set fields in the MassUpdate form in the "My Inbox" view
1497          */
1498         function js_set_archived() {
1499                 global $mod_strings;
1500                 $script = '
1501                 <script type="text/javascript" language="JavaScript"><!-- Begin
1502                         function setArchived() {
1503                                 var form = document.getElementById("MassUpdate");
1504                                 var status = document.getElementById("mass_status");
1505                                 var ok = false;
1506
1507                                 for(var i=0; i < form.elements.length; i++) {
1508                                         if(form.elements[i].name == "mass[]") {
1509                                                 if(form.elements[i].checked == true) {
1510                                                         ok = true;
1511                                                 }
1512                                         }
1513                                 }
1514
1515                                 if(ok == true) {
1516                                         var user = document.getElementById("mass_assigned_user_name");
1517                                         var team = document.getElementById("team");
1518
1519                                         user.value = "";
1520                                         for(var j=0; j<status.length; j++) {
1521                                                 if(status.options[j].value == "archived") {
1522                                                         status.options[j].selected = true;
1523                                                         status.selectedIndex = j; // for IE
1524                                                 }
1525                                         }
1526
1527                                         form.submit();
1528                                 } else {
1529                                         alert("'.$mod_strings['ERR_ARCHIVE_EMAIL'].'");
1530                                 }
1531
1532                         }
1533                 //  End --></script>';
1534                 return $script;
1535         }
1536
1537         /**
1538          * replaces the javascript in utils.php - more specialized
1539          */
1540         function u_get_clear_form_js($type='', $group='', $assigned_user_id='') {
1541                 $uType                          = '';
1542                 $uGroup                         = '';
1543                 $uAssigned_user_id      = '';
1544
1545                 if(!empty($type)) { $uType = '&type='.$type; }
1546                 if(!empty($group)) { $uGroup = '&group='.$group; }
1547                 if(!empty($assigned_user_id)) { $uAssigned_user_id = '&assigned_user_id='.$assigned_user_id; }
1548
1549                 $the_script = '
1550                 <script type="text/javascript" language="JavaScript"><!-- Begin
1551                         function clear_form(form) {
1552                                 var newLoc = "index.php?action=" + form.action.value + "&module=" + form.module.value + "&query=true&clear_query=true'.$uType.$uGroup.$uAssigned_user_id.'";
1553                                 if(typeof(form.advanced) != "undefined"){
1554                                         newLoc += "&advanced=" + form.advanced.value;
1555                                 }
1556                                 document.location.href= newLoc;
1557                         }
1558                 //  End --></script>';
1559                 return $the_script;
1560         }
1561
1562         function pickOneButton() {
1563                 global $theme;
1564                 global $mod_strings;
1565                 $out = '<div><input     title="'.$mod_strings['LBL_BUTTON_GRAB_TITLE'].'"
1566                                                 accessKey="'.$mod_strings['LBL_BUTTON_GRAB_KEY'].'"
1567                                                 class="button"
1568                                                 type="button" name="button"
1569                                                 onClick="window.location=\'index.php?module=Emails&action=Grab\';"
1570                                                 style="margin-bottom:2px"
1571                                                 value="  '.$mod_strings['LBL_BUTTON_GRAB'].'  "></div>';
1572                 return $out;
1573         }
1574
1575         /**
1576          * Determines what Editor (HTML or Plain-text) the current_user uses;
1577          * @return string Editor type
1578          */
1579         function getUserEditorPreference() {
1580                 global $sugar_config;
1581                 global $current_user;
1582
1583                 $editor = '';
1584
1585                 if(!isset($sugar_config['email_default_editor'])) {
1586                         $sugar_config = $current_user->setDefaultsInConfig();
1587                 }
1588
1589                 $userEditor = $current_user->getPreference('email_editor_option');
1590                 $systemEditor = $sugar_config['email_default_editor'];
1591
1592                 if($userEditor != '') {
1593                         $editor = $userEditor;
1594                 } else {
1595                         $editor = $systemEditor;
1596                 }
1597
1598                 return $editor;
1599         }
1600
1601         /**
1602          * takes the mess we pass from EditView and tries to create some kind of order
1603          * @param array addrs
1604          * @param array addrs_ids (from contacts)
1605          * @param array addrs_names (from contacts);
1606          * @param array addrs_emails (from contacts);
1607          * @return array Parsed assoc array to feed to PHPMailer
1608          */
1609         function parse_addrs($addrs, $addrs_ids, $addrs_names, $addrs_emails) {
1610                 // cn: bug 9406 - enable commas to separate email addresses
1611                 $addrs = str_replace(",", ";", $addrs);
1612
1613                 $ltgt = array('&lt;','&gt;');
1614                 $gtlt = array('<','>');
1615
1616                 $return                         = array();
1617                 $addrs                          = str_replace($ltgt, '', $addrs);
1618                 $addrs_arr                      = explode(";",$addrs);
1619                 $addrs_arr                      = $this->remove_empty_fields($addrs_arr);
1620                 $addrs_ids_arr          = explode(";",$addrs_ids);
1621                 $addrs_ids_arr          = $this->remove_empty_fields($addrs_ids_arr);
1622                 $addrs_emails_arr       = explode(";",$addrs_emails);
1623                 $addrs_emails_arr       = $this->remove_empty_fields($addrs_emails_arr);
1624                 $addrs_names_arr        = explode(";",$addrs_names);
1625                 $addrs_names_arr        = $this->remove_empty_fields($addrs_names_arr);
1626
1627                 ///////////////////////////////////////////////////////////////////////
1628                 ////    HANDLE EMAILS HAND-WRITTEN
1629                 $contactRecipients = array();
1630                 $knownEmails = array();
1631
1632                 foreach($addrs_arr as $i => $v) {
1633                         if(trim($v) == "")
1634                                 continue; // skip any "blanks" - will always have 1
1635
1636                         $recipient = array();
1637
1638                         //// get the email to see if we're dealing with a dupe
1639                         //// what crappy coding
1640                         preg_match("/[A-Z0-9._%-\']+@[A-Z0-9.-]+\.[A-Z]{2,}/i",$v, $match);
1641                         
1642
1643                         if(!empty($match[0]) && !in_array(trim($match[0]), $knownEmails)) {
1644                                 $knownEmails[] = $match[0];
1645                                 $recipient['email'] = $match[0];
1646
1647                                 //// handle the Display name
1648                                 $display = trim(str_replace($match[0], '', $v));
1649
1650                                 //// only trigger a "displayName" <email@address> when necessary
1651                                 if(isset($addrs_names_arr[$i])){
1652                                                 $recipient['display'] = $addrs_names_arr[$i];
1653                                 }
1654                                 else if(!empty($display)) {
1655                                         $recipient['display'] = $display;
1656                                 }
1657                                 if(isset($addrs_ids_arr[$i]) && $addrs_emails_arr[$i] == $match[0]){
1658                                         $recipient['contact_id'] = $addrs_ids_arr[$i];
1659                                 }
1660                                 $return[] = $recipient;
1661                         }
1662                 }
1663
1664                 return $return;
1665         }
1666
1667         function remove_empty_fields(&$arr) {
1668                 $newarr = array();
1669
1670                 foreach($arr as $field) {
1671                         $field = trim($field);
1672                         if(empty($field)) {
1673                                 continue;
1674                         }
1675                         array_push($newarr,$field);
1676                 }
1677                 return $newarr;
1678         }
1679
1680         /**
1681          * handles attachments of various kinds when sending email
1682          */
1683         function handleAttachments() {
1684
1685
1686
1687
1688                 global $mod_strings;
1689
1690         ///////////////////////////////////////////////////////////////////////////
1691         ////    ATTACHMENTS FROM DRAFTS
1692         if(($this->type == 'out' || $this->type == 'draft') && $this->status == 'draft' && isset($_REQUEST['record'])) {
1693             $this->getNotes($_REQUEST['record']); // cn: get notes from OLD email for use in new email
1694         }
1695         ////    END ATTACHMENTS FROM DRAFTS
1696         ///////////////////////////////////////////////////////////////////////////
1697
1698         ///////////////////////////////////////////////////////////////////////////
1699         ////    ATTACHMENTS FROM FORWARDS
1700         // Bug 8034 Jenny - Need the check for type 'draft' here to handle cases where we want to save
1701         // forwarded messages as drafts.  We still need to save the original message's attachments.
1702         if(($this->type == 'out' || $this->type == 'draft') &&
1703                 isset($_REQUEST['origType']) && $_REQUEST['origType'] == 'forward' &&
1704                 isset($_REQUEST['return_id']) && !empty($_REQUEST['return_id'])
1705         ) {
1706             $this->getNotes($_REQUEST['return_id'], true);
1707         }
1708
1709         // cn: bug 8034 - attachments from forward/replies lost when saving in draft
1710         if(isset($_REQUEST['prior_attachments']) && !empty($_REQUEST['prior_attachments']) && $this->new_with_id == true) {
1711                 $exIds = explode(",", $_REQUEST['prior_attachments']);
1712                 if(!isset($_REQUEST['template_attachment'])) {
1713                         $_REQUEST['template_attachment'] = array();
1714                 }
1715                 $_REQUEST['template_attachment'] = array_merge($_REQUEST['template_attachment'], $exIds);
1716         }
1717         ////    END ATTACHMENTS FROM FORWARDS
1718         ///////////////////////////////////////////////////////////////////////////
1719
1720                 ///////////////////////////////////////////////////////////////////////////
1721                 ////    ATTACHMENTS FROM TEMPLATES
1722                 // to preserve individual email integrity, we must dupe Notes and associated files
1723                 // for each outbound email - good for integrity, bad for filespace
1724                 if(isset($_REQUEST['template_attachment']) && !empty($_REQUEST['template_attachment'])) {
1725                         $removeArr = array();
1726                         $noteArray = array();
1727
1728                         if(isset($_REQUEST['temp_remove_attachment']) && !empty($_REQUEST['temp_remove_attachment'])) {
1729                                 $removeArr = $_REQUEST['temp_remove_attachment'];
1730                         }
1731
1732
1733                         foreach($_REQUEST['template_attachment'] as $noteId) {
1734                                 if(in_array($noteId, $removeArr)) {
1735                                         continue;
1736                                 }
1737                                 $noteTemplate = new Note();
1738                                 $noteTemplate->retrieve($noteId);
1739                                 $noteTemplate->id = create_guid();
1740                                 $noteTemplate->new_with_id = true; // duplicating the note with files
1741                                 $noteTemplate->parent_id = $this->id;
1742                                 $noteTemplate->parent_type = $this->module_dir;
1743                                 $noteTemplate->date_entered = '';
1744                                 $noteTemplate->save();
1745
1746                                 $noteFile = new UploadFile('none');
1747                                 $noteFile->duplicate_file($noteId, $noteTemplate->id, $noteTemplate->filename);
1748                                 $noteArray[] = $noteTemplate;
1749                         }
1750                         $this->attachments = array_merge($this->attachments, $noteArray);
1751                 }
1752                 ////    END ATTACHMENTS FROM TEMPLATES
1753                 ///////////////////////////////////////////////////////////////////////////
1754
1755                 ///////////////////////////////////////////////////////////////////////////
1756                 ////    ADDING NEW ATTACHMENTS
1757                 $max_files_upload = 10;
1758         // Jenny - Bug 8211 Since attachments for drafts have already been processed,
1759         // we don't need to re-process them.
1760         if($this->status != "draft") {
1761                 $notes_list = array();
1762                 if(!empty($this->id) && !$this->new_with_id) {
1763                         $note = new Note();
1764                         $where = "notes.parent_id='{$this->id}'";
1765                         $notes_list = $note->get_full_list("", $where, true);
1766                 }
1767                 $this->attachments = array_merge($this->attachments, $notes_list);
1768         }
1769                 // cn: Bug 5995 - rudimentary error checking
1770                 $filesError = array(
1771                         0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
1772                         1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
1773                         2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
1774                         3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
1775                         4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
1776                         5 => 'UNKNOWN ERROR',
1777                         6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
1778                         7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
1779                 );
1780
1781                 for($i = 0; $i < $max_files_upload; $i++) {
1782                         // cn: Bug 5995 - rudimentary error checking
1783                         if (!isset($_FILES["email_attachment{$i}"])) {
1784                                 $GLOBALS['log']->debug("Email Attachment {$i} does not exist.");
1785                                 continue;
1786                         }
1787                         if($_FILES['email_attachment'.$i]['error'] != 0 && $_FILES['email_attachment'.$i]['error'] != 4) {
1788                                 $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment'.$i]['error']]);
1789                                 continue;
1790                         }
1791
1792                         $note = new Note();
1793                         $note->parent_id = $this->id;
1794                         $note->parent_type = $this->module_dir;
1795                         $upload_file = new UploadFile('email_attachment'.$i);
1796
1797                         if(empty($upload_file)) {
1798                                 continue;
1799                         }
1800
1801                         if(isset($_FILES['email_attachment'.$i]) && $upload_file->confirm_upload()) {
1802                                 $note->filename = $upload_file->get_stored_file_name();
1803                                 $note->file = $upload_file;
1804                                 $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$note->file->original_file_name;
1805
1806                                 $this->attachments[] = $note;
1807                         }
1808                 }
1809
1810                 $this->saved_attachments = array();
1811                 foreach($this->attachments as $note) {
1812                         if(!empty($note->id)) {
1813                                 array_push($this->saved_attachments, $note);
1814                                 continue;
1815                         }
1816                         $note->parent_id = $this->id;
1817                         $note->parent_type = 'Emails';
1818                         $note->file_mime_type = $note->file->mime_type;
1819                         $note_id = $note->save();
1820
1821                         $this->saved_attachments[] = $note;
1822
1823                         $note->id = $note_id;
1824                         $note->file->final_move($note->id);
1825                 }
1826                 ////    END NEW ATTACHMENTS
1827                 ///////////////////////////////////////////////////////////////////////////
1828
1829                 ///////////////////////////////////////////////////////////////////////////
1830                 ////    ATTACHMENTS FROM DOCUMENTS
1831                 for($i=0; $i<10; $i++) {
1832                         if(isset($_REQUEST['documentId'.$i]) && !empty($_REQUEST['documentId'.$i])) {
1833                                 $doc = new Document();
1834                                 $docRev = new DocumentRevision();
1835                                 $docNote = new Note();
1836                                 $noteFile = new UploadFile('none');
1837
1838                                 $doc->retrieve($_REQUEST['documentId'.$i]);
1839                                 $docRev->retrieve($doc->document_revision_id);
1840
1841                                 $this->saved_attachments[] = $docRev;
1842
1843                                 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
1844                                 $docNote->name = $docRev->getDocumentRevisionNameForDisplay();
1845                                 $docNote->filename = $docRev->filename;
1846                                 $docNote->description = $doc->description;
1847                                 $docNote->parent_id = $this->id;
1848                                 $docNote->parent_type = 'Emails';
1849                                 $docNote->file_mime_type = $docRev->file_mime_type;
1850                                 $docId = $docNote = $docNote->save();
1851
1852                                 $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
1853                         }
1854                 }
1855
1856                 ////    END ATTACHMENTS FROM DOCUMENTS
1857                 ///////////////////////////////////////////////////////////////////////////
1858
1859                 ///////////////////////////////////////////////////////////////////////////
1860                 ////    REMOVE ATTACHMENTS
1861         if(isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
1862             foreach($_REQUEST['remove_attachment'] as $noteId) {
1863                 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1864                 $this->db->query($q);
1865             }
1866         }
1867
1868         //this will remove attachments that have been selected to be removed from drafts.
1869         if(isset($_REQUEST['removeAttachment']) && !empty($_REQUEST['removeAttachment'])) {
1870             $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1871             foreach($exRemoved as $noteId) {
1872                 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1873                 $this->db->query($q);
1874             }
1875         }
1876                 ////    END REMOVE ATTACHMENTS
1877                 ///////////////////////////////////////////////////////////////////////////
1878         }
1879
1880
1881         /**
1882          * Determines if an email body (HTML or Plain) has a User signature already in the content
1883          * @param array Array of signatures
1884          * @return bool
1885          */
1886         function hasSignatureInBody($sig) {
1887                 // strpos can't handle line breaks - normalize
1888                 $html = $this->removeAllNewlines($this->description_html);
1889                 $htmlSig = $this->removeAllNewlines($sig['signature_html']);
1890                 $plain = $this->removeAllNewlines($this->description);
1891                 $plainSig = $this->removeAllNewlines($sig['signature']);
1892
1893                 // cn: bug 11621 - empty sig triggers notice error
1894                 if(!empty($htmlSig) && false !== strpos($html, $htmlSig)) {
1895                         return true;
1896                 } elseif(!empty($plainSig) && false !== strpos($plain, $plainSig)) {
1897                         return true;
1898                 } else {
1899                         return false;
1900                 }
1901         }
1902
1903         /**
1904          * internal helper
1905          * @param string String to be normalized
1906          * @return string
1907          */
1908         function removeAllNewlines($str) {
1909                 $bad = array("\r\n", "\n\r", "\n", "\r");
1910                 $good = array('', '', '', '');
1911
1912                 return str_replace($bad, $good, strip_tags(br2nl(from_html($str))));
1913         }
1914
1915
1916
1917         /**
1918          * Set navigation anchors to aid DetailView record navigation (VCR buttons)
1919          * @param string uri The URI from the referring page (always ListView)
1920          * @return array start Array of the URI broken down with a special "current_view" for My Inbox Navs
1921          */
1922         function getStartPage($uri) {
1923                 if(strpos($uri, '&')) { // "&" to ensure that we can explode the GET vars - else we're gonna trigger a Notice error
1924                         $serial = substr($uri, (strpos($uri, '?')+1), strlen($uri));
1925                         $exUri = explode('&', $serial);
1926                         $start = array('module' => '', 'action' => '', 'group' => '', 'record' => '', 'type' => '');
1927
1928                         foreach($exUri as $k => $pair) {
1929                                 $exPair = explode('=', $pair);
1930                                 $start[$exPair[0]] = $exPair[1];
1931                         }
1932
1933                         // specific views for current_user
1934                         if(isset($start['assigned_user_id'])) {
1935                                 $start['current_view'] = "{$start['action']}&module={$start['module']}&assigned_user_id={$start['assigned_user_id']}&type={$start['type']}";
1936                         }
1937
1938                         return $start;
1939                 } else {
1940                         return array();
1941                 }
1942         }
1943
1944         /**
1945          * preps SMTP info for email transmission
1946          * @param object mail SugarPHPMailer object
1947          * @param string mailer_id
1948          * @param string ieId
1949          * @return object mail SugarPHPMailer object
1950          */
1951         function setMailer($mail, $mailer_id='', $ieId='') {
1952                 global $current_user;
1953
1954                 require_once("include/OutboundEmail/OutboundEmail.php");
1955                 $oe = new OutboundEmail();
1956                 $oe = $oe->getInboundMailerSettings($current_user, $mailer_id, $ieId);
1957
1958                 // ssl or tcp - keeping outside isSMTP b/c a default may inadvertantly set ssl://
1959                 $mail->protocol = ($oe->mail_smtpssl) ? "ssl://" : "tcp://";
1960         if($oe->mail_sendtype == "SMTP")
1961         {
1962                 //Set mail send type information
1963                 $mail->Mailer = "smtp";
1964                 $mail->Host = $oe->mail_smtpserver;
1965                 $mail->Port = $oe->mail_smtpport;
1966             if ($oe->mail_smtpssl == 1) {
1967                 $mail->SMTPSecure = 'ssl';
1968             } // if
1969             if ($oe->mail_smtpssl == 2) {
1970                 $mail->SMTPSecure = 'tls';
1971             } // if
1972
1973                 if($oe->mail_smtpauth_req) {
1974                         $mail->SMTPAuth = TRUE;
1975                         $mail->Username = $oe->mail_smtpuser;
1976                         $mail->Password = $oe->mail_smtppass;
1977                 }
1978         }
1979         else
1980                         $mail->Mailer = "sendmail";
1981
1982                 $mail->oe = $oe;
1983                 return $mail;
1984         }
1985
1986         /**
1987          * preps SugarPHPMailer object for HTML or Plain text sends
1988          * @param object SugarPHPMailer instance
1989          */
1990         function handleBody($mail) {
1991                 global $current_user;
1992                 global $sugar_config;
1993                 ///////////////////////////////////////////////////////////////////////
1994                 ////    HANDLE EMAIL FORMAT PREFERENCE
1995                 // the if() below is HIGHLY dependent on the Javascript unchecking the Send HTML Email box
1996                 // HTML email
1997                 if( (isset($_REQUEST['setEditor']) /* from Email EditView navigation */
1998                         && $_REQUEST['setEditor'] == 1
1999                         && trim($_REQUEST['description_html']) != '')
2000                         || trim($this->description_html) != '' /* from email templates */
2001             && $current_user->getPreference('email_editor_option', 'global') !== 'plain' //user preference is not set to plain text
2002                 ) {
2003                     $this->handleBodyInHTMLformat($mail);
2004                 } else {
2005                         // plain text only
2006                         $this->description_html = '';
2007                         $mail->IsHTML(false);
2008                         $plainText = from_html($this->description);
2009                         $plainText = str_replace("&nbsp;", " ", $plainText);
2010                         $plainText = str_replace("</p>", "</p><br />", $plainText);
2011                         $plainText = strip_tags(br2nl($plainText));
2012                         $plainText = str_replace("&amp;", "&", $plainText);
2013             $plainText = str_replace("&#39;", "'", $plainText);
2014                         $mail->Body = wordwrap($plainText, 996);
2015                         $mail->Body = $this->decodeDuringSend($mail->Body);
2016                         $this->description = $mail->Body;
2017                 }
2018
2019                 // wp: if plain text version has lines greater than 998, use base64 encoding
2020                 foreach(explode("\n", ($mail->ContentType == "text/html") ? $mail->AltBody : $mail->Body) as $line) {
2021                         if(strlen($line) > 998) {
2022                                 $mail->Encoding = 'base64';
2023                                 break;
2024                         }
2025                 }
2026                 ////    HANDLE EMAIL FORMAT PREFERENCE
2027                 ///////////////////////////////////////////////////////////////////////
2028
2029                 return $mail;
2030         }
2031
2032         /**
2033          * Retrieve function from handlebody() to unit test easily
2034          * @param $mail
2035          * @return formatted $mail body
2036          */
2037         function handleBodyInHTMLformat($mail) {
2038                 global $current_user;
2039                 global $sugar_config;
2040                 // wp: if body is html, then insert new lines at 996 characters. no effect on client side
2041                 // due to RFC 2822 which limits email lines to 998
2042                 $mail->IsHTML(true);
2043                 $body = from_html(wordwrap($this->description_html, 996));
2044                 $mail->Body = $body;
2045
2046                 // cn: bug 9725
2047                 // new plan is to use the selected type (html or plain) to fill the other
2048                 $plainText = from_html($this->description_html);
2049                 $plainText = strip_tags(br2nl($plainText));
2050                 $mail->AltBody = $plainText;
2051                 $this->description = $plainText;
2052
2053                 $fileBasePath = "{$sugar_config['cache_dir']}images/";
2054                 $filePatternSearch = "{$sugar_config['cache_dir']}";
2055                 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2056                 $filePatternSearch = $filePatternSearch . "images\/";
2057                 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2058                 {  //cache/images
2059                         $matches = array();
2060                         preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2061                         foreach($matches[0] as $match) {
2062                                 $filename = str_replace($fileBasePath, '', $match);
2063                                 $filename = urldecode(substr($filename, 0, -1));
2064                                 $cid = $filename;
2065                                 $file_location = clean_path(getcwd()."/{$sugar_config['cache_dir']}images/{$filename}");
2066                                 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2067
2068                                 if(file_exists($file_location)) {
2069                                         $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2070                                 }
2071                         }
2072
2073                         //replace references to cache with cid tag
2074                         $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2075                         $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2076                         // remove bad img line from outbound email
2077                         $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2078                         $mail->Body = preg_replace($regex, '', $mail->Body);
2079                 }
2080                 $fileBasePath = "{$sugar_config['upload_dir']}";
2081                 $filePatternSearch = "{$sugar_config['upload_dir']}";
2082                 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2083                 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2084                 {
2085                         $matches = array();
2086                         preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2087                         foreach($matches[0] as $match) {
2088                                 $filename = str_replace($fileBasePath, '', $match);
2089                                 $filename = urldecode(substr($filename, 0, -1));
2090                                 $cid = $filename;
2091                                 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$filename}");
2092                                 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2093
2094                                 if(file_exists($file_location)) {
2095                                         $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2096                                 }
2097                         }
2098
2099                         //replace references to cache with cid tag
2100                         $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2101                         $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2102
2103                         // remove bad img line from outbound email
2104                         $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2105                         $mail->Body = preg_replace($regex, '', $mail->Body);
2106                 }
2107
2108                 //Replace any embeded images using the secure entryPoint for src url.
2109                 $noteImgRegex = "/<img[^>]*[\s]+src[^=]*=\"index.php\?entryPoint=download\&amp;id=([^\&]*)[^>]*>/im";
2110         $embededImageMatches = array();
2111         preg_match_all($noteImgRegex, $mail->Body, $embededImageMatches,PREG_SET_ORDER);
2112
2113         foreach ($embededImageMatches as $singleMatch )
2114         {
2115             $fullMatch = $singleMatch[0];
2116             $noteId = $singleMatch[1];
2117             $cid = $noteId;
2118             $filename = $noteId;
2119
2120             //Retrieve note for mimetype
2121             $tmpNote = new Note();
2122             $tmpNote->retrieve($noteId);
2123             //Replace the src part of img tag with new cid tag
2124             $cidRegex = "/src=\"([^\"]*)\"/im";
2125             $replaceMatch = preg_replace($cidRegex, "src=\"cid:$noteId\"", $fullMatch);
2126
2127             //Replace the body, old tag for new tag
2128             $mail->Body = str_replace($fullMatch, $replaceMatch, $mail->Body);
2129
2130             //Attach the file
2131             $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$noteId}");
2132
2133             if(file_exists($file_location))
2134                                         $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $tmpNote->file_mime_type);
2135         }
2136         //End Replace
2137
2138
2139                 $mail->Body = from_html($mail->Body);
2140         }
2141
2142         /**
2143          * Sends Email
2144          * @return bool True on success
2145          */
2146         function send() {
2147                 global $mod_strings,$app_strings;
2148                 global $current_user;
2149                 global $sugar_config;
2150                 global $locale;
2151         $OBCharset = $locale->getPrecedentPreference('default_email_charset');
2152                 $mail = new SugarPHPMailer();
2153
2154                 foreach ($this->to_addrs_arr as $addr_arr) {
2155                         if ( empty($addr_arr['display'])) {
2156                                 $mail->AddAddress($addr_arr['email'], "");
2157                         } else {
2158                                 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
2159                         }
2160                 }
2161                 foreach ($this->cc_addrs_arr as $addr_arr) {
2162                         if ( empty($addr_arr['display'])) {
2163                                 $mail->AddCC($addr_arr['email'], "");
2164                         } else {
2165                                 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2166                         }
2167                 }
2168
2169                 foreach ($this->bcc_addrs_arr as $addr_arr) {
2170                         if ( empty($addr_arr['display'])) {
2171                                 $mail->AddBCC($addr_arr['email'], "");
2172                         } else {
2173                                 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2174                         }
2175                 }
2176
2177                 $mail = $this->setMailer($mail);
2178
2179                 // FROM ADDRESS
2180                 if(!empty($this->from_addr)) {
2181                         $mail->From = $this->from_addr;
2182                 } else {
2183                         $mail->From = $current_user->getPreference('mail_fromaddress');
2184                         $this->from_addr = $mail->From;
2185                 }
2186                 // FROM NAME
2187                 if(!empty($this->from_name)) {
2188                         $mail->FromName = $this->from_name;
2189                 } else {
2190                         $mail->FromName =  $current_user->getPreference('mail_fromname');
2191                         $this->from_name = $mail->FromName;
2192                 }
2193
2194                 //Reply to information for case create and autoreply.
2195                 if(!empty($this->reply_to_name)) {
2196                         $ReplyToName = $this->reply_to_name;
2197                 } else {
2198                         $ReplyToName = $mail->FromName;
2199                 }
2200                 if(!empty($this->reply_to_addr)) {
2201                         $ReplyToAddr = $this->reply_to_addr;
2202                 } else {
2203                         $ReplyToAddr = $mail->From;
2204                 }
2205                 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
2206                 $mail->AddReplyTo($ReplyToAddr,$locale->translateCharsetMIME(trim($ReplyToName), 'UTF-8', $OBCharset));
2207
2208                 //$mail->Subject = html_entity_decode($this->name, ENT_QUOTES, 'UTF-8');
2209                 $mail->Subject = $this->name;
2210
2211                 ///////////////////////////////////////////////////////////////////////
2212                 ////    ATTACHMENTS
2213                 foreach($this->saved_attachments as $note) {
2214                         $mime_type = 'text/plain';
2215                         if($note->object_name == 'Note') {
2216                                 if(!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) { // brandy-new file upload/attachment
2217                                         $file_location = $sugar_config['upload_dir'].$note->id;
2218                                         $filename = $note->file->original_file_name;
2219                                         $mime_type = $note->file->mime_type;
2220                                 } else { // attachment coming from template/forward
2221                                         $file_location = rawurldecode(UploadFile::get_file_path($note->filename,$note->id));
2222                                         // cn: bug 9723 - documents from EmailTemplates sent with Doc Name, not file name.
2223                                         $filename = !empty($note->filename) ? $note->filename : $note->name;
2224                                         $mime_type = $note->file_mime_type;
2225                                 }
2226                         } elseif($note->object_name == 'DocumentRevision') { // from Documents
2227                                 $filePathName = $note->id;
2228                                 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
2229                                 $filename = $note->getDocumentRevisionNameForDisplay();
2230                                 $file_location = getcwd().'/'.$GLOBALS['sugar_config']['upload_dir'].$filePathName;
2231                                 $mime_type = $note->file_mime_type;
2232                         }
2233
2234                         // strip out the "Email attachment label if exists
2235                         $filename = str_replace($mod_strings['LBL_EMAIL_ATTACHMENT'].': ', '', $filename);
2236
2237                         //is attachment in our list of bad files extensions?  If so, append .txt to file location
2238                         //get position of last "." in file name
2239                         $file_ext_beg = strrpos($file_location,".");
2240                         $file_ext = "";
2241                         //get file extension
2242                         if($file_ext_beg >0){
2243                                 $file_ext = substr($file_location, $file_ext_beg+1 );
2244                         }
2245                         //check to see if this is a file with extension located in "badext"
2246                         foreach($sugar_config['upload_badext'] as $badExt) {
2247                         if(strtolower($file_ext) == strtolower($badExt)) {
2248                                 //if found, then append with .txt to filename and break out of lookup
2249                                 //this will make sure that the file goes out with right extension, but is stored
2250                                 //as a text in db.
2251                                 $file_location = $file_location . ".txt";
2252                                 break; // no need to look for more
2253                         }
2254                 }
2255                         $mail->AddAttachment($file_location,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
2256
2257                         // embedded Images
2258                         if($note->embed_flag == true) {
2259                                 $cid = $filename;
2260                                 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64',$mime_type);
2261                         }
2262                 }
2263                 ////    END ATTACHMENTS
2264                 ///////////////////////////////////////////////////////////////////////
2265
2266                 $mail = $this->handleBody($mail);
2267
2268                 $GLOBALS['log']->debug('Email sending --------------------- ');
2269
2270                 ///////////////////////////////////////////////////////////////////////
2271                 ////    I18N TRANSLATION
2272                 $mail->prepForOutbound();
2273                 ////    END I18N TRANSLATION
2274                 ///////////////////////////////////////////////////////////////////////
2275
2276                 if($mail->Send()) {
2277                         ///////////////////////////////////////////////////////////////////
2278                         ////    INBOUND EMAIL HANDLING
2279                         // mark replied
2280                         if(!empty($_REQUEST['inbound_email_id'])) {
2281                                 $ieMail = new Email();
2282                                 $ieMail->retrieve($_REQUEST['inbound_email_id']);
2283                                 $ieMail->status = 'replied';
2284                                 $ieMail->save();
2285                         }
2286                         $GLOBALS['log']->debug(' --------------------- buh bye -- sent successful');
2287                         ////    END INBOUND EMAIL HANDLING
2288                         ///////////////////////////////////////////////////////////////////
2289                         return true;
2290                 }
2291             $GLOBALS['log']->debug($app_strings['LBL_EMAIL_ERROR_PREPEND'].$mail->ErrorInfo);
2292                 return false;
2293         }
2294
2295
2296         function listviewACLHelper(){
2297                 $array_assign = parent::listviewACLHelper();
2298                 $is_owner = false;
2299                 if(!empty($this->parent_name)){
2300
2301                         if(!empty($this->parent_name_owner)){
2302                                 global $current_user;
2303                                 $is_owner = $current_user->id == $this->parent_name_owner;
2304                         }
2305                 }
2306                 if(!ACLController::moduleSupportsACL($this->parent_type) || ACLController::checkAccess($this->parent_type, 'view', $is_owner)){
2307                         $array_assign['PARENT'] = 'a';
2308                 } else {
2309                         $array_assign['PARENT'] = 'span';
2310                 }
2311                 $is_owner = false;
2312                 if(!empty($this->contact_name)) {
2313                         if(!empty($this->contact_name_owner)) {
2314                                 global $current_user;
2315                                 $is_owner = $current_user->id == $this->contact_name_owner;
2316                         }
2317                 }
2318                 if(ACLController::checkAccess('Contacts', 'view', $is_owner)) {
2319                         $array_assign['CONTACT'] = 'a';
2320                 } else {
2321                         $array_assign['CONTACT'] = 'span';
2322                 }
2323
2324                 return $array_assign;
2325         }
2326
2327         function getSystemDefaultEmail() {
2328                 $email = array();
2329
2330                 $r1 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromaddress\'');
2331                 $r2 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromname\'');
2332                 $a1 = $this->db->fetchByAssoc($r1);
2333                 $a2 = $this->db->fetchByAssoc($r2);
2334
2335                 $email['email'] = $a1['value'];
2336                 $email['name']  = $a2['value'];
2337
2338                 return $email;
2339         }
2340
2341
2342     function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false) {
2343
2344                 if ($return_array) {
2345                         return parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, $return_array,$parentbean, $singleSelect);
2346                 }
2347         $custom_join = $this->custom_fields->getJOIN();
2348
2349                 $query = "SELECT ".$this->table_name.".*, users.user_name as assigned_user_name\n";
2350
2351         if($custom_join){
2352                         $query .= $custom_join['select'];
2353                 }
2354         $query .= " FROM emails\n";
2355         if ($where != "" && (strpos($where, "contacts.first_name") > 0))  {
2356                         $query .= " LEFT JOIN emails_beans ON emails.id = emails_beans.email_id\n";
2357         }
2358
2359         $query .= " LEFT JOIN users ON emails.assigned_user_id=users.id \n";
2360         if ($where != "" && (strpos($where, "contacts.first_name") > 0))  {
2361
2362         $query .= " JOIN contacts ON contacts.id= emails_beans.bean_id AND emails_beans.bean_module='Contacts' and contacts.deleted=0 \n";
2363         }
2364
2365                 if($custom_join){
2366                         $query .= $custom_join['join'];
2367                 }
2368
2369                 if($show_deleted == 0) {
2370                         $where_auto = " emails.deleted=0 \n";
2371                 }else if($show_deleted == 1){
2372                         $where_auto = " emails.deleted=1 \n";
2373                 }
2374
2375         if($where != "")
2376                         $query .= "WHERE $where AND ".$where_auto;
2377                 else
2378                         $query .= "WHERE ".$where_auto;
2379
2380                 if($order_by != "")
2381                         $query .= " ORDER BY $order_by";
2382                 else
2383                         $query .= " ORDER BY date_sent DESC";
2384
2385                 return $query;
2386     } // fn
2387
2388
2389         function fill_in_additional_list_fields() {
2390                 global $timedate;
2391                 $this->fill_in_additional_detail_fields();
2392
2393                 $this->link_action = 'DetailView';
2394                 ///////////////////////////////////////////////////////////////////////
2395                 //populate attachment_image, used to display attachment icon.
2396                 $query =  "select 1 from notes where notes.parent_id = '$this->id' and notes.deleted = 0";
2397                 $result =$this->db->query($query,true," Error filling in additional list fields: ");
2398
2399                 $row = $this->db->fetchByAssoc($result);
2400
2401                 if ($row !=null) {
2402                         $this->attachment_image = SugarThemeRegistry::current()->getImage('attachment',"","","");
2403                 } else {
2404                         $this->attachment_image = SugarThemeRegistry::current()->getImage('blank',"","","");
2405                 }
2406                 ///////////////////////////////////////////////////////////////////////
2407                 if(empty($this->contact_id) && !empty($this->parent_id) && !empty($this->parent_type) && $this->parent_type === 'Contacts' && !empty($this->parent_name) ){
2408                         $this->contact_id = $this->parent_id;
2409                         $this->contact_name = $this->parent_name;
2410                 }
2411         }
2412
2413         function fill_in_additional_detail_fields() {
2414                 global $app_list_strings,$mod_strings;
2415                 // Fill in the assigned_user_name
2416                 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id, '');
2417                 //if ($this->parent_type == 'Contacts') {
2418                         $query  = "SELECT contacts.first_name, contacts.last_name, contacts.phone_work, contacts.id, contacts.assigned_user_id contact_name_owner, 'Contacts' contact_name_mod FROM contacts, emails_beans ";
2419                         $query .= "WHERE emails_beans.email_id='$this->id' AND emails_beans.bean_id=contacts.id AND emails_beans.bean_module = 'Contacts' AND emails_beans.deleted=0 AND contacts.deleted=0";
2420                         if(!empty($this->parent_id)){
2421                                 $query .= " AND contacts.id= '".$this->parent_id."' ";
2422                         }else if(!empty($_REQUEST['record'])){
2423                                 $query .= " AND contacts.id= '".$_REQUEST['record']."' ";
2424                         }
2425                         $result =$this->db->query($query,true," Error filling in additional detail fields: ");
2426
2427                         // Get the id and the name.
2428                         $row = $this->db->fetchByAssoc($result);
2429                         if($row != null)
2430                         {
2431
2432                                 $contact = new Contact();
2433                                 $contact->retrieve($row['id']);
2434                                 $this->contact_name = $contact->full_name;
2435                                 $this->contact_phone = $row['phone_work'];
2436                                 $this->contact_id = $row['id'];
2437                                 $this->contact_email = $contact->emailAddress->getPrimaryAddress($contact);
2438                                 $this->contact_name_owner = $row['contact_name_owner'];
2439                                 $this->contact_name_mod = $row['contact_name_mod'];
2440                                 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2441                                 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2442                                 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2443                                 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2444                         }
2445                         else {
2446                                 $this->contact_name = '';
2447                                 $this->contact_phone = '';
2448                                 $this->contact_id = '';
2449                                 $this->contact_email = '';
2450                                 $this->contact_name_owner = '';
2451                                 $this->contact_name_mod = '';
2452                                 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2453                                 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2454                                 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2455                                 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2456                         }
2457                 //}
2458                 $this->created_by_name = get_assigned_user_name($this->created_by);
2459                 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
2460
2461                 $this->link_action = 'DetailView';
2462
2463                 if(!empty($this->type)) {
2464                         if($this->type == 'out' && $this->status == 'send_error') {
2465                                 $this->type_name = $mod_strings['LBL_NOT_SENT'];
2466                         } else {
2467                                 $this->type_name = $app_list_strings['dom_email_types'][$this->type];
2468                         }
2469
2470                         if(($this->type == 'out' && $this->status == 'send_error') || $this->type == 'draft') {
2471                                 $this->link_action = 'EditView';
2472                         }
2473                 }
2474
2475                 //todo this  isset( $app_list_strings['dom_email_status'][$this->status]) is hack for 3261.
2476                 if(!empty($this->status) && isset( $app_list_strings['dom_email_status'][$this->status])) {
2477                         $this->status_name = $app_list_strings['dom_email_status'][$this->status];
2478                 }
2479
2480                 if ( empty($this->name ) &&  empty($_REQUEST['record'])) {
2481                         $this->name = $mod_strings['LBL_NO_SUBJECT'];
2482                 }
2483
2484                 $this->fill_in_additional_parent_fields();
2485         }
2486
2487
2488
2489         function create_export_query(&$order_by, &$where) {
2490                 $contact_required = stristr($where, "contacts");
2491                 $custom_join = $this->custom_fields->getJOIN(true, true,$where);
2492
2493                 if($contact_required) {
2494                         $query = "SELECT emails.*, contacts.first_name, contacts.last_name";
2495                         if($custom_join) {
2496                                 $query .= $custom_join['select'];
2497                         }
2498
2499                         $query .= " FROM contacts, emails, emails_contacts ";
2500                         $where_auto = "emails_contacts.contact_id = contacts.id AND emails_contacts.email_id = emails.id AND emails.deleted=0 AND contacts.deleted=0";
2501                 } else {
2502                         $query = 'SELECT emails.*';
2503                         if($custom_join) {
2504                                 $query .= $custom_join['select'];
2505                         }
2506
2507             $query .= ' FROM emails ';
2508             $where_auto = "emails.deleted=0";
2509                 }
2510
2511                 if($custom_join){
2512                         $query .= $custom_join['join'];
2513                 }
2514
2515                 if($where != "")
2516                         $query .= "where $where AND ".$where_auto;
2517         else
2518                         $query .= "where ".$where_auto;
2519
2520         if($order_by != "")
2521                         $query .= " ORDER BY $order_by";
2522         else
2523                         $query .= " ORDER BY emails.name";
2524         return $query;
2525     }
2526
2527         function get_list_view_data() {
2528                 global $app_list_strings;
2529                 global $theme;
2530                 global $current_user;
2531                 global $timedate;
2532                 global $mod_strings;
2533
2534                 $email_fields = $this->get_list_view_array();
2535                 $this->retrieveEmailText();
2536                 $email_fields['FROM_ADDR'] = $this->from_addr_name;
2537                 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); // hard-coding for Home screen ListView
2538
2539                 if($this->status != 'replied') {
2540                         $email_fields['QUICK_REPLY'] = '<a  href="index.php?module=Emails&action=Compose&replyForward=true&reply=reply&record='.$this->id.'&inbound_email_id='.$this->id.'">'.$mod_strings['LNK_QUICK_REPLY'].'</a>';
2541                         $email_fields['STATUS'] = ($email_fields['REPLY_TO_STATUS'] == 1 ? $mod_strings['LBL_REPLIED'] : $email_fields['STATUS']);
2542                 } else {
2543                         $email_fields['QUICK_REPLY'] = $mod_strings['LBL_REPLIED'];
2544                 }
2545                 if(!empty($this->parent_type)) {
2546                         $email_fields['PARENT_MODULE'] = $this->parent_type;
2547                 } else {
2548                         switch($this->intent) {
2549                                 case 'support':
2550                                         $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Cases&action=EditView&inbound_email_id='.$this->id.'" ><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('CreateCases.gif').'">'.$mod_strings['LBL_CREATE_CASE'].'</a>';
2551                                 break;
2552
2553                                 case 'sales':
2554                                         $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Leads&action=EditView&inbound_email_id='.$this->id.'" ><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('CreateLeads.gif').'">'.$mod_strings['LBL_CREATE_LEAD'].'</a>';
2555                                 break;
2556
2557                                 case 'contact':
2558                                         $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Contacts&action=EditView&inbound_email_id='.$this->id.'" ><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('CreateContacts.gif').'">'.$mod_strings['LBL_CREATE_CONTACT'].'</a>';
2559                                 break;
2560
2561                                 case 'bug':
2562                                         $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Bugs&action=EditView&inbound_email_id='.$this->id.'" ><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('CreateBugs.gif').'">'.$mod_strings['LBL_CREATE_BUG'].'</a>';
2563                                 break;
2564
2565                                 case 'task':
2566                                         $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Tasks&action=EditView&inbound_email_id='.$this->id.'" ><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('CreateTasks.gif').'">'.$mod_strings['LBL_CREATE_TASK'].'</a>';
2567                                 break;
2568
2569                                 case 'bounce':
2570                                 break;
2571
2572                                 case 'pick':
2573                                 // break;
2574
2575                                 case 'info':
2576                                 //break;
2577
2578                                 default:
2579                                         $email_fields['CREATE_RELATED'] = $this->quickCreateForm();
2580                                 break;
2581                         }
2582
2583                 }
2584
2585                 //BUG 17098 - MFH changed $this->from_addr to $this->to_addrs
2586                 $email_fields['CONTACT_NAME']           = empty($this->contact_name) ? '</a>'.$this->trimLongTo($this->to_addrs).'<a>' : $this->contact_name;
2587                 $email_fields['CONTACT_ID']             = empty($this->contact_id) ? '' : $this->contact_id;
2588                 $email_fields['ATTACHMENT_IMAGE']       = $this->attachment_image;
2589                 $email_fields['LINK_ACTION']            = $this->link_action;
2590
2591         if(isset($this->type_name))
2592                 $email_fields['TYPE_NAME'] = $this->type_name;
2593
2594                 return $email_fields;
2595         }
2596
2597     function quickCreateForm() {
2598         global $mod_strings, $app_strings, $currentModule, $current_language;
2599
2600         // Coming from the home page via Dashlets
2601         if($currentModule != 'Email')
2602                 $mod_strings = return_module_language($current_language, 'Emails');
2603         return $mod_strings['LBL_QUICK_CREATE']."&nbsp;<a id='$this->id' onclick='return quick_create_overlib(\"{$this->id}\", \"".SugarThemeRegistry::current()->__toString()."\");' href=\"#\" >".SugarThemeRegistry::current()->getImage("advanced_search","alt='".$mod_strings['LBL_QUICK_CREATE']."'  border='0' align='absmiddle'")."</a>";
2604     }
2605
2606     /**
2607      * Searches all imported emails and returns the result set as an array.
2608      *
2609      */
2610     function searchImportedEmails($sort = '', $direction='')
2611     {
2612         require_once('include/TimeDate.php');
2613                 global $timedate;
2614                 global $current_user;
2615                 global $beanList;
2616                 global $sugar_config;
2617                 global $app_strings;
2618
2619                 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
2620                 // cn: default to a low number until user specifies otherwise
2621                 if(empty($emailSettings['showNumInList']))
2622                         $pageSize = 20;
2623         else
2624             $pageSize = $emailSettings['showNumInList'];
2625
2626         if( isset($_REQUEST['start']) && isset($_REQUEST['limit']) )
2627                $page = ceil($_REQUEST['start'] / $_REQUEST['limit']) + 1;
2628             else
2629                $page = 1;
2630
2631              //Determine sort ordering
2632
2633              //Sort ordering parameters in the request do not coincide with actual column names
2634              //so we need to remap them.
2635              $hrSortLocal = array(
2636             'flagged' => 'type',
2637             'status'  => 'reply_to_status',
2638             'from'    => 'emails_text.from_addr',
2639             'subject' => 'name',
2640             'date'    => 'date_sent',
2641             'AssignedTo' => 'assigned_user_id',
2642             'flagged' => 'flagged'
2643         );
2644
2645              $sort = !empty($_REQUEST['sort']) ? $_REQUEST['sort'] : "";
2646          $direction = !empty($_REQUEST['dir']) ? $_REQUEST['dir'] : "";
2647
2648          $order = ( !empty($sort) && !empty($direction) ) ? " ORDER BY {$hrSortLocal[$sort]} {$direction}" : "";
2649
2650          //Get our main query.
2651                 $fullQuery = $this->_genereateSearchImportedEmailsQuery();
2652
2653                 //Perform a count query needed for pagination.
2654                 $countQuery = $this->create_list_count_query($fullQuery);
2655                 $count_rs = $this->db->query($countQuery, false, 'Error executing count query for imported emails search');
2656                 $count_row = $this->db->fetchByAssoc($count_rs);
2657                 $total_count = ($count_row != null) ? $count_row['c'] : 0;
2658
2659         $start = ($page - 1) * $pageSize;
2660
2661         //Execute the query
2662                 $rs = $this->db->limitQuery($fullQuery . $order, $start, $pageSize);
2663
2664                 $return = array();
2665
2666                 while($a = $this->db->fetchByAssoc($rs)) {
2667                         $temp = array();
2668                         $temp['flagged'] = (is_null($a['flagged']) || $a['flagged'] == '0') ? '' : 1;
2669                         $temp['status'] = (is_null($a['reply_to_status']) || $a['reply_to_status'] == '0') ? '' : 1;
2670                         $temp['subject'] = $a['name'];
2671                         $temp['date']   = $timedate->to_display_date_time($a['date_sent']);
2672                         $temp['uid'] = $a['id'];
2673                         $temp['ieId'] = $a['mailbox_id'];
2674                         $temp['site_url'] = $sugar_config['site_url'];
2675                         $temp['seen'] = ($a['status'] == 'unread') ? 0 : 1;
2676                         $temp['type'] = $a['type'];
2677                         $temp['mbox'] = 'sugar::Emails';
2678                         $temp['hasAttach'] =  $this->doesImportedEmailHaveAttachment($a['id']);
2679                         //To and from addresses may be stored in emails_text, if nothing is found, revert to
2680                         //regular email addresses.
2681                         $temp['to_addrs'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['to_addrs']);
2682                         $temp['from']   = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['from_addr']);
2683                         if( empty($temp['from']) || empty($temp['to_addrs']) )
2684                         {
2685                         //Retrieve email addresses seperatly.
2686                         $tmpEmail = new Email();
2687                         $tmpEmail->id = $a['id'];
2688                         $tmpEmail->retrieveEmailAddresses();
2689                         $temp['from'] = $tmpEmail->from_addr;
2690                         $temp['to_addrs'] = $tmpEmail->to_addrs;
2691                         }
2692
2693                         $return[] = $temp;
2694                 }
2695
2696                 $metadata = array();
2697                 $metadata['totalCount'] = $total_count;
2698                 $metadata['out'] = $return;
2699
2700                 return $metadata;
2701     }
2702
2703     /**
2704      * Determine if an imported email has an attachment by examining the relationship to notes.
2705      *
2706      * @param string $id
2707      * @return boolean
2708      */
2709     function doesImportedEmailHaveAttachment($id)
2710         {
2711            $hasAttachment = FALSE;
2712            $query = "SELECT id FROM notes where parent_id='$id' AND parent_type='Emails' AND file_mime_type is not null AND deleted=0";
2713            $rs = $this->db->limitQuery($query, 0, 1);
2714            $row = $this->db->fetchByAssoc($rs);
2715            if( !empty($row['id']) )
2716                $hasAttachment = TRUE;
2717
2718            return (int) $hasAttachment;
2719         }
2720
2721     /**
2722      * Generate the query used for searching imported emails.
2723      *
2724      * @return String Query to be executed.
2725      */
2726     function _genereateSearchImportedEmailsQuery()
2727     {
2728                 global $timedate;
2729
2730         $additionalWhereClause = $this->_generateSearchImportWhereClause();
2731
2732         $query = array();
2733         $fullQuery = "";
2734         $query['select'] = "emails.id , emails.mailbox_id, emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status,
2735                                       emails_text.from_addr, emails_text.to_addrs  FROM emails ";
2736
2737         $query['joins'] = " JOIN emails_text on emails.id = emails_text.email_id ";
2738
2739         //Handle from and to addr joins
2740         if( !empty($_REQUEST['from_addr']) )
2741         {
2742             $query['joins'] .= "INNER JOIN emails_email_addr_rel er_from ON er_from.email_id = emails.id AND er_from.deleted = 0 INNER JOIN email_addresses ea_from ON ea_from.id = er_from.email_address_id
2743                                 AND er_from.address_type='from' AND ea_from.email_address='" . strtolower($_REQUEST['from_addr']) . "'";
2744         }
2745
2746         if( !empty($_REQUEST['to_addrs'])  )
2747         {
2748             $query['joins'] .= "INNER JOIN emails_email_addr_rel er_to ON er_to.email_id = emails.id AND er_to.deleted = 0 INNER JOIN email_addresses ea_to ON ea_to.id = er_to.email_address_id
2749                                     AND er_to.address_type='to' AND ea_to.email_address='" . strtolower($_REQUEST['to_addrs']) . "'";
2750         }
2751
2752         $query['where'] = " WHERE (emails.type= 'inbound' OR emails.type='archived' OR emails.type='out') AND emails.deleted = 0 ";
2753                 if( !empty($additionalWhereClause) )
2754             $query['where'] .= "AND $additionalWhereClause";
2755
2756         //If we are explicitly looking for attachments.  Do not use a distinct query as the to_addr is defined
2757         //as a text which equals clob in oracle and the distinct query can not be executed correctly.
2758         $addDistinctKeyword = "";
2759         if( !empty($_REQUEST['attachmentsSearch']) &&  $_REQUEST['attachmentsSearch'] == 1) //1 indicates yes
2760             $query['where'] .= " AND EXISTS ( SELECT id FROM notes n WHERE n.parent_id = emails.id AND n.deleted = 0 AND n.filename is not null )";
2761         else if( !empty($_REQUEST['attachmentsSearch']) &&  $_REQUEST['attachmentsSearch'] == 2 )
2762              $query['where'] .= " AND NOT EXISTS ( SELECT id FROM notes n WHERE n.parent_id = emails.id AND n.deleted = 0 AND n.filename is not null )";
2763
2764         $fullQuery = "SELECT " . $query['select'] . " " . $query['joins'] . " " . $query['where'];
2765
2766         return $fullQuery;
2767     }
2768         /**
2769      * Generate the where clause for searching imported emails.
2770      *
2771      */
2772     function _generateSearchImportWhereClause()
2773     {
2774         global $timedate;
2775
2776         //The clear button was removed so if a user removes the asisgned user name, do not process the id.
2777         if( empty($_REQUEST['assigned_user_name']) && !empty($_REQUEST['assigned_user_id'])  )
2778             unset($_REQUEST['assigned_user_id']);
2779
2780         $availableSearchParam = array('name' => array('table_name' =>'emails'),
2781                                         'data_parent_id_search' => array('table_name' =>'emails','db_key' => 'parent_id','opp' => '='),
2782                                         'assigned_user_id' => array('table_name' => 'emails', 'opp' => '=') );
2783
2784                 $additionalWhereClause = array();
2785                 foreach ($availableSearchParam as $key => $properties)
2786                 {
2787                       if( !empty($_REQUEST[$key]) )
2788                       {
2789                           $db_key =  isset($properties['db_key']) ? $properties['db_key'] : $key;
2790                           $searchValue = $_REQUEST[$key];
2791
2792                           $opp = isset($properties['opp']) ? $properties['opp'] : 'like';
2793                           if($opp == 'like')
2794                               $searchValue = $searchValue . "%";
2795
2796                           $additionalWhereClause[] = "{$properties['table_name']}.$db_key $opp '$searchValue' ";
2797                       }
2798         }
2799
2800         $isDateFromSearchSet = !empty($_REQUEST['searchDateFrom']);
2801         $isdateToSearchSet = !empty($_REQUEST['searchDateTo']);
2802
2803         $bothDateRangesSet = $isDateFromSearchSet & $isdateToSearchSet;
2804
2805         //Hanlde date from and to seperately
2806         if($bothDateRangesSet)
2807         {
2808             $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2809             $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2810
2811             $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2812             $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2813
2814             $additionalWhereClause[] = "( emails.date_sent >= $dbFormatDateFrom AND
2815                                           emails.date_sent <= $dbFormatDateTo )";
2816         }
2817         elseif ($isdateToSearchSet)
2818         {
2819             $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2820             $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2821             $additionalWhereClause[] = "emails.date_sent <= $dbFormatDateTo ";
2822         }
2823         elseif ($isDateFromSearchSet)
2824         {
2825             $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2826             $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2827             $additionalWhereClause[] = "emails.date_sent >= $dbFormatDateFrom ";
2828         }
2829
2830         $additionalWhereClause = implode(" AND ", $additionalWhereClause);
2831
2832         return $additionalWhereClause;
2833     }
2834
2835
2836
2837         /**
2838          * takes a long TO: string of emails and returns the first appended by an
2839          * elipse
2840          */
2841         function trimLongTo($str) {
2842                 if(strpos($str, ',')) {
2843                         $exStr = explode(',', $str);
2844                         return $exStr[0].'...';
2845                 } elseif(strpos($str, ';')) {
2846                         $exStr = explode(';', $str);
2847                         return $exStr[0].'...';
2848                 } else {
2849                         return $str;
2850                 }
2851         }
2852
2853         function get_summary_text() {
2854                 return $this->name;
2855         }
2856
2857
2858
2859         function distributionForm($where) {
2860                 global $app_list_strings;
2861                 global $app_strings;
2862                 global $mod_strings;
2863                 global $theme;
2864                 global $current_user;
2865
2866                 $distribution   = get_select_options_with_id($app_list_strings['dom_email_distribution'], '');
2867                 $_SESSION['distribute_where'] = $where;
2868
2869
2870                 $out = '<form name="Distribute" id="Distribute">';
2871                 $out .= get_form_header($mod_strings['LBL_DIST_TITLE'], '', false);
2872                 $out .=<<<eoq
2873                 <script>
2874                         enableQS(true);
2875                 </script>
2876 eoq;
2877                 $out .= '
2878                 <table cellpadding="0" cellspacing="0" width="100%" border="0">
2879                         <tr>
2880                                 <td>
2881                                         <script type="text/javascript">
2882
2883
2884                                                 function checkDeps(form) {
2885                                                         return;
2886                                                 }
2887
2888                                                 function mySubmit() {
2889                                                         var assform = document.getElementById("Distribute");
2890                                                         var select = document.getElementById("userSelect");
2891                                                         var assign1 = assform.r1.checked;
2892                                                         var assign2 = assform.r2.checked;
2893                                                         var dist = assform.dm.value;
2894                                                         var assign = false;
2895                                                         var users = false;
2896                                                         var rules = false;
2897                                                         var warn1 = "'.$mod_strings['LBL_WARN_NO_USERS'].'";
2898                                                         var warn2 = "";
2899
2900                                                         if(assign1 || assign2) {
2901                                                                 assign = true;
2902
2903                                                         }
2904
2905                                                         for(i=0; i<select.options.length; i++) {
2906                                                                 if(select.options[i].selected == true) {
2907                                                                         users = true;
2908                                                                         warn1 = "";
2909                                                                 }
2910                                                         }
2911
2912                                                         if(dist != "") {
2913                                                                 rules = true;
2914                                                         } else {
2915                                                                 warn2 = "'.$mod_strings['LBL_WARN_NO_DIST'].'";
2916                                                         }
2917
2918                                                         if(assign && users && rules) {
2919
2920                                                                 if(document.getElementById("r1").checked) {
2921                                                                         var mu = document.getElementById("MassUpdate");
2922                                                                         var grabbed = "";
2923
2924                                                                         for(i=0; i<mu.elements.length; i++) {
2925                                                                                 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name.value != "massall") {
2926                                                                                         if(grabbed != "") { grabbed += "::"; }
2927                                                                                         grabbed += mu.elements[i].value;
2928                                                                                 }
2929                                                                         }
2930                                                                         var formgrab = document.getElementById("grabbed");
2931                                                                         formgrab.value = grabbed;
2932                                                                 }
2933                                                                 assform.submit();
2934                                                         } else {
2935                                                                 alert("'.$mod_strings['LBL_ASSIGN_WARN'].'" + "\n" + warn1 + "\n" + warn2);
2936                                                         }
2937                                                 }
2938
2939                                                 function submitDelete() {
2940                                                         if(document.getElementById("r1").checked) {
2941                                                                 var mu = document.getElementById("MassUpdate");
2942                                                                 var grabbed = "";
2943
2944                                                                 for(i=0; i<mu.elements.length; i++) {
2945                                                                         if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name != "massall") {
2946                                                                                 if(grabbed != "") { grabbed += "::"; }
2947                                                                                 grabbed += mu.elements[i].value;
2948                                                                         }
2949                                                                 }
2950                                                                 var formgrab = document.getElementById("grabbed");
2951                                                                 formgrab.value = grabbed;
2952                                                         }
2953                                                         if(grabbed == "") {
2954                                                                 alert("'.$mod_strings['LBL_MASS_DELETE_ERROR'].'");
2955                                                         } else {
2956                                                                 document.getElementById("Distribute").submit();
2957                                                         }
2958                                                 }
2959
2960                                         </script>
2961                                                 <input type="hidden" name="module" value="Emails">
2962                                                 <input type="hidden" name="action" id="action">
2963                                                 <input type="hidden" name="grabbed" id="grabbed">
2964
2965                                         <table cellpadding="1" cellspacing="0" width="100%" border="0" class="edit view">
2966                                                 <tr height="20">
2967                                                         <td scope="col" scope="row" NOWRAP align="center">
2968                                                                 &nbsp;'.$mod_strings['LBL_ASSIGN_SELECTED_RESULTS_TO'].'&nbsp;';
2969                                         $out .= $this->userSelectTable();
2970                                         $out .= '</td>
2971                                                         <td scope="col" scope="row" NOWRAP align="left">
2972                                                                 &nbsp;'.$mod_strings['LBL_USING_RULES'].'&nbsp;
2973                                                                 <select name="distribute_method" id="dm" onChange="checkDeps(this.form);">'.$distribution.'</select>
2974                                                         </td>';
2975
2976
2977                                         $out .= '</td>
2978                                                         </tr>';
2979
2980
2981                                         $out .= '<tr>
2982                                                                 <td scope="col" width="50%" scope="row" NOWRAP align="right" colspan="2">
2983                                                                 <input title="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_TITLE'].'"
2984                                                                         id="dist_button"
2985                                                                         accessKey="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_KEY'].'"
2986                                                                         class="button" onClick="AjaxObject.detailView.handleAssignmentDialogAssignAction();"
2987                                                                         type="button" name="button"
2988                                                                         value="  '.$mod_strings['LBL_BUTTON_DISTRIBUTE'].'  ">';
2989                                         $out .= '</tr>
2990                                         </table>
2991                                 </td>
2992                         </tr>
2993                 </table>
2994                 </form>';
2995         return $out;
2996         }
2997
2998         function userSelectTable() {
2999                 global $theme;
3000                 global $mod_strings;
3001
3002                 $colspan = 1;
3003                 $setTeamUserFunction = '';
3004
3005
3006                 // get users
3007                 $r = $this->db->query("SELECT users.id, users.user_name, users.first_name, users.last_name FROM users WHERE deleted=0 AND status = 'Active' AND is_group=0 ORDER BY users.last_name, users.first_name");
3008
3009                 $userTable = '<table cellpadding="0" cellspacing="0" border="0">';
3010                 $userTable .= '<tr><td colspan="2"><b>'.$mod_strings['LBL_USER_SELECT'].'</b></td></tr>';
3011                 $userTable .= '<tr><td><input type="checkbox" style="border:0px solid #000000" onClick="toggleAll(this); setCheckMark(); checkDeps(this.form);"></td> <td>'.$mod_strings['LBL_TOGGLE_ALL'].'</td></tr>';
3012                 $userTable .= '<tr><td colspan="2"><select style="visibility:hidden;" name="users[]" id="userSelect" multiple size="12">';
3013
3014                 while($a = $this->db->fetchByAssoc($r)) {
3015                         $userTable .= '<option value="'.$a['id'].'" id="'.$a['id'].'">'.$a['first_name'].' '.$a['last_name'].'</option>';
3016                 }
3017                 $userTable .= '</select></td></tr>';
3018                 $userTable .= '</table>';
3019
3020                 $out  = '<script type="text/javascript">';
3021                 $out .= $setTeamUserFunction;
3022                 $out .= '
3023                                         function setCheckMark() {
3024                                                 var select = document.getElementById("userSelect");
3025
3026                                                 for(i=0 ; i<select.options.length; i++) {
3027                                                         if(select.options[i].selected == true) {
3028                                                                 document.getElementById("checkMark").style.display="";
3029                                                                 return;
3030                                                         }
3031                                                 }
3032
3033                                                 document.getElementById("checkMark").style.display="none";
3034                                                 return;
3035                                         }
3036
3037                                         function showUserSelect() {
3038                                                 var targetTable = document.getElementById("user_select");
3039                                                 targetTable.style.visibility="visible";
3040                                                 var userSelectTable = document.getElementById("userSelect");
3041                                                 userSelectTable.style.visibility="visible";
3042                                                 return;
3043                                         }
3044                                         function hideUserSelect() {
3045                                                 var targetTable = document.getElementById("user_select");
3046                                                 targetTable.style.visibility="hidden";
3047                                                 var userSelectTable = document.getElementById("userSelect");
3048                                                 userSelectTable.style.visibility="hidden";
3049                                                 return;
3050                                         }
3051                                         function toggleAll(toggle) {
3052                                                 if(toggle.checked) {
3053                                                         var stat = true;
3054                                                 } else {
3055                                                         var stat = false;
3056                                                 }
3057                                                 var form = document.getElementById("userSelect");
3058                                                 for(i=0; i<form.options.length; i++) {
3059                                                         form.options[i].selected = stat;
3060                                                 }
3061                                         }
3062
3063
3064                                 </script>
3065                         <span id="showUsersDiv" style="position:relative;">
3066                                 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
3067                                         <img border="0" src="'.SugarThemeRegistry::current()->getImageURL('Users.gif').'"></a>&nbsp;
3068                                 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
3069                                         <span style="display:none;" id="checkMark"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('check_inline.gif').'"></span>
3070                                 </a>
3071
3072
3073                                 <div id="user_select" style="width:200px;position:absolute;left:2;top:2;visibility:hidden;z-index:1000;">
3074                                 <table cellpadding="0" cellspacing="0" border="0" class="list view">
3075                                         <tr height="20">
3076                                                 <td  colspan="'.$colspan.'" id="hiddenhead" onClick="hideUserSelect();" onMouseOver="this.style.border = \'outset red 1px\';" onMouseOut="this.style.border = \'inset white 0px\';this.style.borderBottom = \'inset red 1px\';">
3077                                                         <a href="#" onClick="javascript:hideUserSelect();"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('close.gif').'"></a>
3078                                                         '.$mod_strings['LBL_USER_SELECT'].'
3079                                                 </td>
3080                                         </tr>
3081                                         <tr>';
3082 //<td valign="middle" height="30"  colspan="'.$colspan.'" id="hiddenhead" onClick="hideUserSelect();" onMouseOver="this.style.border = \'outset red 1px\';" onMouseOut="this.style.border = \'inset white 0px\';this.style.borderBottom = \'inset red 1px\';">
3083                 $out .= '               <td style="padding:5px" class="oddListRowS1" bgcolor="#fdfdfd" valign="top" align="left" style="left:0;top:0;">
3084                                                         '.$userTable.'
3085                                                 </td>
3086                                         </tr>
3087                                 </table></div>
3088                         </span>';
3089                 return $out;
3090         }
3091
3092         function checkInbox($type) {
3093                 global $theme;
3094                 global $mod_strings;
3095                 $out = '<div><input     title="'.$mod_strings['LBL_BUTTON_CHECK_TITLE'].'"
3096                                                 accessKey="'.$mod_strings['LBL_BUTTON_CHECK_KEY'].'"
3097                                                 class="button"
3098                                                 type="button" name="button"
3099                                                 onClick="window.location=\'index.php?module=Emails&action=Check&type='.$type.'\';"
3100                                                 style="margin-bottom:2px"
3101                                                 value="  '.$mod_strings['LBL_BUTTON_CHECK'].'  "></div>';
3102                 return $out;
3103         }
3104
3105         /**
3106          * Guesses Primary Parent id from From: email address.  Cascades guesses from Accounts to Contacts to Leads to
3107          * Users.  This will not affect the many-to-many relationships already constructed as this is, at best,
3108          * informational linking.
3109          */
3110         function fillPrimaryParentFields() {
3111                 if(empty($this->from_addr))
3112                         return;
3113
3114                 $GLOBALS['log']->debug("*** Email trying to guess Primary Parent from address [ {$this->from_addr} ]");
3115
3116                 $tables = array('accounts');
3117                 $ret = array();
3118                 // loop through types to get hits
3119                 foreach($tables as $table) {
3120                         $q = "SELECT name, id FROM {$table} WHERE email1 = '{$this->from_addr}' OR email2 = '{$this->from_addr}' AND deleted = 0";
3121                         $r = $this->db->query($q);
3122                         while($a = $this->db->fetchByAssoc($r)) {
3123                                 if(!empty($a['name']) && !empty($a['id'])) {
3124                                         $this->parent_type      = ucwords($table);
3125                                         $this->parent_id        = $a['id'];
3126                                         $this->parent_name      = $a['name'];
3127                                         return;
3128                                 }
3129                         }
3130                 }
3131         }
3132
3133
3134
3135 } // end class def