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