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