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