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