]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Emails/Email.php
Release 6.5.11
[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-2013 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 delimiters 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         $result = array();
948
949         foreach ($idsArray as $id)
950         {
951             // Load bean
952             $bean = BeanFactory::getBean($module, $id);
953
954             // Got a bean
955             if (!empty($bean))
956             {
957                 // For CE, just get primary e-mail address
958                 $emailAddress = $bean->email1;
959
960
961                 // If we have an e-mail address loaded
962                 if (!empty($emailAddress))
963                 {
964                     // Use bean name by default
965                     $fullName = $bean->name;
966
967                     // Depending on module, format the name
968                     if (in_array($module, array('Users', 'Employees')))
969                     {
970                         $fullName = from_html(
971                             $locale->getLocaleFormattedName(
972                                 $bean->first_name,
973                                 $bean->last_name,
974                                 '',
975                                 $bean->title
976                             )
977                         );
978                     }
979                     else if (SugarModule::get($module)->moduleImplements('Person'))
980                     {
981                         $fullName = from_html(
982                             $locale->getLocaleFormattedName(
983                                 $bean->first_name,
984                                 $bean->last_name,
985                                 $bean->salutation,
986                                 $bean->title
987                             )
988                         );
989                     }
990
991                     // Make e-mail address in format "Name <@email>"
992                     $result[$bean->id] = $fullName . " <" . from_html($emailAddress) . ">";
993                 }
994             }
995         }
996
997         // Broken out of method to facilitate unit testing
998         return $this->_arrayToDelimitedString($result);
999     }
1000
1001     /**
1002      * @param Array $arr - list of strings
1003      * @return string the list of strings delimited by email_address_separator
1004      */
1005     function _arrayToDelimitedString($arr)
1006     {
1007         // bug 51804: outlook does not respect the correct email address separator (',') , so let
1008         // clients override the default.
1009         $separator = (isset($GLOBALS['sugar_config']['email_address_separator']) &&
1010                         !empty($GLOBALS['sugar_config']['email_address_separator'])) ?
1011                      $GLOBALS['sugar_config']['email_address_separator'] :
1012                      ',';
1013
1014                 return join($separator, array_values($arr));
1015     }
1016
1017         /**
1018          * Overrides
1019          */
1020         ///////////////////////////////////////////////////////////////////////////
1021         ////    SAVERS
1022         function save($check_notify = false) {
1023         global $current_user;
1024
1025                 if($this->isDuplicate) {
1026                         $GLOBALS['log']->debug("EMAIL - tried to save a duplicate Email record");
1027                 } else {
1028
1029                         if(empty($this->id)) {
1030                                 $this->id = create_guid();
1031                                 $this->new_with_id = true;
1032                         }
1033                         $this->from_addr_name = $this->cleanEmails($this->from_addr_name);
1034                         $this->to_addrs_names = $this->cleanEmails($this->to_addrs_names);
1035                         $this->cc_addrs_names = $this->cleanEmails($this->cc_addrs_names);
1036                         $this->bcc_addrs_names = $this->cleanEmails($this->bcc_addrs_names);
1037                         $this->reply_to_addr = $this->cleanEmails($this->reply_to_addr);
1038                         $this->description = SugarCleaner::cleanHtml($this->description);
1039             $this->description_html = SugarCleaner::cleanHtml($this->description_html, true);
1040             $this->raw_source = SugarCleaner::cleanHtml($this->raw_source, true);
1041                         $this->saveEmailText();
1042                         $this->saveEmailAddresses();
1043
1044                         $GLOBALS['log']->debug('-------------------------------> Email called save()');
1045
1046                         // handle legacy concatenation of date and time fields
1047                         //Bug 39503 - SugarBean is not setting date_sent when seconds missing
1048                         if(empty($this->date_sent)) {
1049                                 global $timedate;
1050                                 $date_sent_obj = $timedate->fromUser($timedate->merge_date_time($this->date_start, $this->time_start), $current_user);
1051                  if (!empty($date_sent_obj) && ($date_sent_obj instanceof SugarDateTime)) {
1052                                     $this->date_sent = $date_sent_obj->asDb();
1053                  }
1054                         } else {
1055                                 //set date_entered to date_sent if this is a new email being archived
1056                                 //that way emails archived to sugar by plugins like opacus mail will
1057                                 //have the correct ordering according to email incoming date.
1058                                 if ($this->new_with_id) {
1059                                         $this->date_entered = $this->date_sent;
1060                                 }
1061                         }
1062
1063                         parent::save($check_notify);
1064
1065                         if(!empty($this->parent_type) && !empty($this->parent_id)) {
1066                 if(!empty($this->fetched_row) && !empty($this->fetched_row['parent_id']) && !empty($this->fetched_row['parent_type'])) {
1067                     if($this->fetched_row['parent_id'] != $this->parent_id || $this->fetched_row['parent_type'] != $this->parent_type) {
1068                         $mod = strtolower($this->fetched_row['parent_type']);
1069                         $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1070                         if($this->load_relationship($rel) ) {
1071                             $this->$rel->delete($this->id, $this->fetched_row['parent_id']);
1072                         }
1073                     }
1074                 }
1075                 $mod = strtolower($this->parent_type);
1076                 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1077                 if($this->load_relationship($rel) ) {
1078                     $this->$rel->add($this->parent_id);
1079                 }
1080                         }
1081                 }
1082                 $GLOBALS['log']->debug('-------------------------------> Email save() done');
1083         }
1084
1085         /**
1086          * Helper function to save temporary attachments assocaited to an email as note.
1087          *
1088          * @param string $filename
1089          * @param string $fileLocation
1090          * @param string $mimeType
1091          */
1092         function saveTempNoteAttachments($filename,$fileLocation, $mimeType)
1093         {
1094             $tmpNote = new Note();
1095             $tmpNote->id = create_guid();
1096             $tmpNote->new_with_id = true;
1097             $tmpNote->parent_id = $this->id;
1098             $tmpNote->parent_type = $this->module_dir;
1099             $tmpNote->name = $filename;
1100             $tmpNote->filename = $filename;
1101             $tmpNote->file_mime_type = $mimeType;
1102             $noteFile = "upload://{$tmpNote->id}";
1103             if(!copy($fileLocation, $noteFile)) {
1104             $GLOBALS['log']->fatal("EMAIL 2.0: could not copy SugarDocument revision file $fileLocation => $noteFile");
1105             }
1106             $tmpNote->save();
1107         }
1108         /**
1109          * Handles normalization of Email Addressess
1110          */
1111         function saveEmailAddresses() {
1112                 // from, single address
1113                 $fromId = $this->emailAddress->getEmailGUID(from_html($this->from_addr));
1114         if(!empty($fromId)){
1115                   $this->linkEmailToAddress($fromId, 'from');
1116         }
1117
1118                 // to, multiple
1119                 $replace = array(",",";");
1120                 $toaddrs = str_replace($replace, "::", from_html($this->to_addrs));
1121                 $exToAddrs = explode("::", $toaddrs);
1122
1123                 if(!empty($exToAddrs)) {
1124                         foreach($exToAddrs as $toaddr) {
1125                                 $toaddr = trim($toaddr);
1126                                 if(!empty($toaddr)) {
1127                                         $toId = $this->emailAddress->getEmailGUID($toaddr);
1128                                         $this->linkEmailToAddress($toId, 'to');
1129                                 }
1130                         }
1131                 }
1132
1133                 // cc, multiple
1134                 $ccAddrs = str_replace($replace, "::", from_html($this->cc_addrs));
1135                 $exccAddrs = explode("::", $ccAddrs);
1136
1137                 if(!empty($exccAddrs)) {
1138                         foreach($exccAddrs as $ccAddr) {
1139                                 $ccAddr = trim($ccAddr);
1140                                 if(!empty($ccAddr)) {
1141                                         $ccId = $this->emailAddress->getEmailGUID($ccAddr);
1142                                         $this->linkEmailToAddress($ccId, 'cc');
1143                                 }
1144                         }
1145                 }
1146
1147                 // bcc, multiple
1148                 $bccAddrs = str_replace($replace, "::", from_html($this->bcc_addrs));
1149                 $exbccAddrs = explode("::", $bccAddrs);
1150                 if(!empty($exbccAddrs)) {
1151                         foreach($exbccAddrs as $bccAddr) {
1152                                 $bccAddr = trim($bccAddr);
1153                                 if(!empty($bccAddr)) {
1154                                         $bccId = $this->emailAddress->getEmailGUID($bccAddr);
1155                                         $this->linkEmailToAddress($bccId, 'bcc');
1156                                 }
1157                         }
1158                 }
1159         }
1160
1161         function linkEmailToAddress($id, $type) {
1162                 // TODO: make this update?
1163                 $q1 = "SELECT * FROM emails_email_addr_rel WHERE email_id = '{$this->id}' AND email_address_id = '{$id}' AND address_type = '{$type}' AND deleted = 0";
1164                 $r1 = $this->db->query($q1);
1165                 $a1 = $this->db->fetchByAssoc($r1);
1166
1167                 if(!empty($a1) && !empty($a1['id'])) {
1168                         return $a1['id'];
1169                 } else {
1170                         $guid = create_guid();
1171                         $q2 = "INSERT INTO emails_email_addr_rel VALUES('{$guid}', '{$this->id}', '{$type}', '{$id}', 0)";
1172                         $r2 = $this->db->query($q2);
1173                 }
1174
1175                 return $guid;
1176         }
1177
1178     protected $email_to_text = array(
1179         "email_id" => "id",
1180         "description" => "description",
1181         "description_html" => "description_html",
1182         "raw_source" => "raw_source",
1183         "from_addr" => "from_addr_name",
1184         "reply_to_addr" => "reply_to_addr",
1185         "to_addrs" => "to_addrs_names",
1186         "cc_addrs" => "cc_addrs_names",
1187         "bcc_addrs" => "bcc_addrs_names",
1188     );
1189
1190         function cleanEmails($emails)
1191         {
1192             if(empty($emails)) return '';
1193                 $emails = str_replace(array(",",";"), "::", from_html($emails));
1194                 $addrs = explode("::", $emails);
1195                 $res = array();
1196                 foreach($addrs as $addr) {
1197             $parts = $this->emailAddress->splitEmailAddress($addr);
1198             if(empty($parts["email"])) {
1199                 continue;
1200             }
1201             if(!empty($parts["name"])) {
1202                 $res[] = "{$parts['name']} <{$parts['email']}>";
1203             } else {
1204                 $res[] .= $parts["email"];
1205             }
1206                 }
1207                 return join(", ", $res);
1208         }
1209
1210         protected function saveEmailText()
1211         {
1212         $text = SugarModule::get("EmailText")->loadBean();
1213         foreach($this->email_to_text as $textfield=>$mailfield) {
1214             $text->$textfield = $this->$mailfield;
1215         }
1216         $text->email_id = $this->id;
1217                 if(!$this->new_with_id) {
1218             $this->db->update($text);
1219                 } else {
1220                     $this->db->insert($text);
1221                 }
1222         }
1223
1224         ///////////////////////////////////////////////////////////////////////////
1225         ////    RETRIEVERS
1226         function retrieve($id, $encoded=true, $deleted=true) {
1227                 // cn: bug 11915, return SugarBean's retrieve() call bean instead of $this
1228                 $ret = parent::retrieve($id, $encoded, $deleted);
1229
1230                 if($ret) {
1231                         $ret->retrieveEmailText();
1232             //$ret->raw_source = SugarCleaner::cleanHtml($ret->raw_source);
1233                         $ret->description = to_html($ret->description);
1234             //$ret->description_html = SugarCleaner::cleanHtml($ret->description_html);
1235                         $ret->retrieveEmailAddresses();
1236
1237                         $ret->date_start = '';
1238                         $ret->time_start = '';
1239                         $dateSent = explode(' ', $ret->date_sent);
1240                         if (!empty($dateSent)) {
1241                             $ret->date_start = $dateSent[0];
1242                             if ( isset($dateSent[1]) )
1243                                 $ret->time_start = $dateSent[1];
1244                         }
1245                         // for Email 2.0
1246                         foreach($ret as $k => $v) {
1247                                 $this->$k = $v;
1248                         }
1249                 }
1250                 return $ret;
1251         }
1252
1253
1254         /**
1255          * Retrieves email addresses from GUIDs
1256          */
1257         function retrieveEmailAddresses() {
1258                 $return = array();
1259
1260                 $q = "SELECT email_address, address_type
1261                                 FROM emails_email_addr_rel eam
1262                                 JOIN email_addresses ea ON ea.id = eam.email_address_id
1263                                 WHERE eam.email_id = '{$this->id}' AND eam.deleted=0";
1264                 $r = $this->db->query($q);
1265
1266                 while($a = $this->db->fetchByAssoc($r)) {
1267                         if(!isset($return[$a['address_type']])) {
1268                                 $return[$a['address_type']] = array();
1269                         }
1270                         $return[$a['address_type']][] = $a['email_address'];
1271                 }
1272
1273                 if(count($return) > 0) {
1274                         if(isset($return['from'])) {
1275                                 $this->from_addr = implode(", ", $return['from']);
1276                         }
1277                         if(isset($return['to'])) {
1278                                 $this->to_addrs = implode(", ", $return['to']);
1279                         }
1280                         if(isset($return['cc'])) {
1281                                 $this->cc_addrs = implode(", ", $return['cc']);
1282                         }
1283                         if(isset($return['bcc'])) {
1284                                 $this->bcc_addrs = implode(", ", $return['bcc']);
1285                         }
1286                 }
1287         }
1288
1289         /**
1290          * Handles longtext fields
1291          */
1292         function retrieveEmailText() {
1293                 $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}'";
1294                 $r = $this->db->query($q);
1295                 $a = $this->db->fetchByAssoc($r, false);
1296
1297                 $this->description = $a['description'];
1298                 $this->description_html = $a['description_html'];
1299                 $this->raw_source = $a['raw_source'];
1300                 $this->from_addr_name = $a['from_addr'];
1301                 $this->reply_to_addr  = $a['reply_to_addr'];
1302                 $this->to_addrs_names = $a['to_addrs'];
1303                 $this->cc_addrs_names = $a['cc_addrs'];
1304                 $this->bcc_addrs_names = $a['bcc_addrs'];
1305         }
1306
1307         function delete($id='') {
1308                 if(empty($id))
1309                         $id = $this->id;
1310
1311                 $q  = "UPDATE emails SET deleted = 1 WHERE id = '{$id}'";
1312                 $qt = "UPDATE emails_text SET deleted = 1 WHERE email_id = '{$id}'";
1313                 $r  = $this->db->query($q);
1314                 $rt = $this->db->query($qt);
1315         }
1316
1317         /**
1318          * creates the standard "Forward" info at the top of the forwarded message
1319          * @return string
1320          */
1321         function getForwardHeader() {
1322                 global $mod_strings;
1323                 global $current_user;
1324
1325                 //$from = str_replace(array("&gt;","&lt;"), array(")","("), $this->from_name);
1326                 $from = to_html($this->from_name);
1327                 $subject = to_html($this->name);
1328                 $ret  = "<br /><br />";
1329                 $ret .= $this->replyDelimiter."{$mod_strings['LBL_FROM']} {$from}<br />";
1330                 $ret .= $this->replyDelimiter."{$mod_strings['LBL_DATE_SENT']} {$this->date_sent}<br />";
1331                 $ret .= $this->replyDelimiter."{$mod_strings['LBL_TO']} {$this->to_addrs}<br />";
1332                 $ret .= $this->replyDelimiter."{$mod_strings['LBL_CC']} {$this->cc_addrs}<br />";
1333                 $ret .= $this->replyDelimiter."{$mod_strings['LBL_SUBJECT']} {$subject}<br />";
1334                 $ret .= $this->replyDelimiter."<br />";
1335
1336                 return $ret;
1337                 //return from_html($ret);
1338         }
1339
1340     /**
1341      * retrieves Notes that belong to this Email and stuffs them into the "attachments" attribute
1342      */
1343     function getNotes($id, $duplicate=false) {
1344         if(!class_exists('Note')) {
1345
1346         }
1347
1348         $exRemoved = array();
1349                 if(isset($_REQUEST['removeAttachment'])) {
1350                         $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1351                 }
1352
1353         $noteArray = array();
1354         $q = "SELECT id FROM notes WHERE parent_id = '".$id."'";
1355         $r = $this->db->query($q);
1356
1357         while($a = $this->db->fetchByAssoc($r)) {
1358                 if(!in_array($a['id'], $exRemoved)) {
1359                     $note = new Note();
1360                     $note->retrieve($a['id']);
1361
1362                     // duplicate actual file when creating forwards
1363                         if($duplicate) {
1364                                 if(!class_exists('UploadFile')) {
1365                                         require_once('include/upload_file.php');
1366                                 }
1367                                 // save a brand new Note
1368                                 $noteDupe->id = create_guid();
1369                                 $noteDupe->new_with_id = true;
1370                                         $noteDupe->parent_id = $this->id;
1371                                         $noteDupe->parent_type = $this->module_dir;
1372
1373                                         $noteFile = new UploadFile();
1374                                         $noteFile->duplicate_file($a['id'], $note->id, $note->filename);
1375
1376                                         $note->save();
1377                         }
1378                         // add Note to attachments array
1379                     $this->attachments[] = $note;
1380                 }
1381         }
1382     }
1383
1384         /**
1385          * creates the standard "Reply" info at the top of the forwarded message
1386          * @return string
1387          */
1388         function getReplyHeader() {
1389                 global $mod_strings;
1390                 global $current_user;
1391
1392                 $from = str_replace(array("&gt;","&lt;", ">","<"), array(")","(",")","("), $this->from_name);
1393                 $ret  = "<br>{$mod_strings['LBL_REPLY_HEADER_1']} {$this->date_start}, {$this->time_start}, {$from} {$mod_strings['LBL_REPLY_HEADER_2']}";
1394
1395                 return from_html($ret);
1396         }
1397
1398         /**
1399          * Quotes plain-text email text
1400          * @param string $text
1401          * @return string
1402          */
1403         function quotePlainTextEmail($text) {
1404                 $quoted = "\n";
1405
1406                 // plain-text
1407                 $desc = nl2br(trim($text));
1408                 $exDesc = explode('<br />', $desc);
1409
1410                 foreach($exDesc as $k => $line) {
1411                         $quoted .= '> '.trim($line)."\r";
1412                 }
1413
1414                 return $quoted;
1415         }
1416
1417         /**
1418          * "quotes" (i.e., "> my text yadda" the HTML part of an email
1419          * @param string $text HTML text to quote
1420          * @return string
1421          */
1422         function quoteHtmlEmail($text) {
1423                 $text = trim(from_html($text));
1424
1425                 if(empty($text)) {
1426                         return '';
1427                 }
1428                 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1429
1430                 return $out;
1431         }
1432
1433         /**
1434          * "quotes" (i.e., "> my text yadda" the HTML part of an email
1435          * @param string $text HTML text to quote
1436          * @return string
1437          */
1438         function quoteHtmlEmailForNewEmailUI($text) {
1439                 $text = trim($text);
1440
1441                 if(empty($text)) {
1442                         return '';
1443                 }
1444                 $text = str_replace("\n", "<BR/>", $text);
1445                 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1446
1447                 return $out;
1448         }
1449
1450         /**
1451          * Ensures that the user is able to send outbound emails
1452          */
1453         function check_email_settings() {
1454                 global $current_user;
1455
1456                 $mail_fromaddress = $current_user->emailAddress->getPrimaryAddress($current_user);
1457                 $replyToName = $current_user->getPreference('mail_fromname');
1458                 $mail_fromname = (!empty($replyToName)) ? $current_user->getPreference('mail_fromname') : $current_user->full_name;
1459
1460                 if(empty($mail_fromaddress)) {
1461                         return false;
1462                 }
1463                 if(empty($mail_fromname)) {
1464                         return false;
1465                 }
1466
1467         $send_type = $current_user->getPreference('mail_sendtype') ;
1468                 if (!empty($send_type) && $send_type == "SMTP") {
1469                         $mail_smtpserver = $current_user->getPreference('mail_smtpserver');
1470                         $mail_smtpport = $current_user->getPreference('mail_smtpport');
1471                         $mail_smtpauth_req = $current_user->getPreference('mail_smtpauth_req');
1472                         $mail_smtpuser = $current_user->getPreference('mail_smtpuser');
1473                         $mail_smtppass = $current_user->getPreference('mail_smtppass');
1474                         if (empty($mail_smtpserver) ||
1475                                 empty($mail_smtpport) ||
1476                 (!empty($mail_smtpauth_req) && ( empty($mail_smtpuser) || empty($mail_smtppass)))
1477                         ) {
1478                                 return false;
1479                         }
1480                 }
1481                 return true;
1482         }
1483
1484         /**
1485          * outputs JS to set fields in the MassUpdate form in the "My Inbox" view
1486          */
1487         function js_set_archived() {
1488                 global $mod_strings;
1489                 $script = '
1490                 <script type="text/javascript" language="JavaScript"><!-- Begin
1491                         function setArchived() {
1492                                 var form = document.getElementById("MassUpdate");
1493                                 var status = document.getElementById("mass_status");
1494                                 var ok = false;
1495
1496                                 for(var i=0; i < form.elements.length; i++) {
1497                                         if(form.elements[i].name == "mass[]") {
1498                                                 if(form.elements[i].checked == true) {
1499                                                         ok = true;
1500                                                 }
1501                                         }
1502                                 }
1503
1504                                 if(ok == true) {
1505                                         var user = document.getElementById("mass_assigned_user_name");
1506                                         var team = document.getElementById("team");
1507
1508                                         user.value = "";
1509                                         for(var j=0; j<status.length; j++) {
1510                                                 if(status.options[j].value == "archived") {
1511                                                         status.options[j].selected = true;
1512                                                         status.selectedIndex = j; // for IE
1513                                                 }
1514                                         }
1515
1516                                         form.submit();
1517                                 } else {
1518                                         alert("'.$mod_strings['ERR_ARCHIVE_EMAIL'].'");
1519                                 }
1520
1521                         }
1522                 //  End --></script>';
1523                 return $script;
1524         }
1525
1526         /**
1527          * replaces the javascript in utils.php - more specialized
1528          */
1529         function u_get_clear_form_js($type='', $group='', $assigned_user_id='') {
1530                 $uType                          = '';
1531                 $uGroup                         = '';
1532                 $uAssigned_user_id      = '';
1533
1534                 if(!empty($type)) { $uType = '&type='.$type; }
1535                 if(!empty($group)) { $uGroup = '&group='.$group; }
1536                 if(!empty($assigned_user_id)) { $uAssigned_user_id = '&assigned_user_id='.$assigned_user_id; }
1537
1538                 $the_script = '
1539                 <script type="text/javascript" language="JavaScript"><!-- Begin
1540                         function clear_form(form) {
1541                                 var newLoc = "index.php?action=" + form.action.value + "&module=" + form.module.value + "&query=true&clear_query=true'.$uType.$uGroup.$uAssigned_user_id.'";
1542                                 if(typeof(form.advanced) != "undefined"){
1543                                         newLoc += "&advanced=" + form.advanced.value;
1544                                 }
1545                                 document.location.href= newLoc;
1546                         }
1547                 //  End --></script>';
1548                 return $the_script;
1549         }
1550
1551         function pickOneButton() {
1552                 global $theme;
1553                 global $mod_strings;
1554                 $out = '<div><input     title="'.$mod_strings['LBL_BUTTON_GRAB_TITLE'].'"
1555                                                 class="button"
1556                                                 type="button" name="button"
1557                                                 onClick="window.location=\'index.php?module=Emails&action=Grab\';"
1558                                                 style="margin-bottom:2px"
1559                                                 value="  '.$mod_strings['LBL_BUTTON_GRAB'].'  "></div>';
1560                 return $out;
1561         }
1562
1563         /**
1564          * Determines what Editor (HTML or Plain-text) the current_user uses;
1565          * @return string Editor type
1566          */
1567         function getUserEditorPreference() {
1568                 global $sugar_config;
1569                 global $current_user;
1570
1571                 $editor = '';
1572
1573                 if(!isset($sugar_config['email_default_editor'])) {
1574                         $sugar_config = $current_user->setDefaultsInConfig();
1575                 }
1576
1577                 $userEditor = $current_user->getPreference('email_editor_option');
1578                 $systemEditor = $sugar_config['email_default_editor'];
1579
1580                 if($userEditor != '') {
1581                         $editor = $userEditor;
1582                 } else {
1583                         $editor = $systemEditor;
1584                 }
1585
1586                 return $editor;
1587         }
1588
1589         /**
1590          * takes the mess we pass from EditView and tries to create some kind of order
1591          * @param array addrs
1592          * @param array addrs_ids (from contacts)
1593          * @param array addrs_names (from contacts);
1594          * @param array addrs_emails (from contacts);
1595          * @return array Parsed assoc array to feed to PHPMailer
1596          */
1597         function parse_addrs($addrs, $addrs_ids, $addrs_names, $addrs_emails) {
1598                 // cn: bug 9406 - enable commas to separate email addresses
1599                 $addrs = str_replace(",", ";", $addrs);
1600
1601                 $ltgt = array('&lt;','&gt;');
1602                 $gtlt = array('<','>');
1603
1604                 $return                         = array();
1605                 $addrs                          = str_replace($ltgt, '', $addrs);
1606                 $addrs_arr                      = explode(";",$addrs);
1607                 $addrs_arr                      = $this->remove_empty_fields($addrs_arr);
1608                 $addrs_ids_arr          = explode(";",$addrs_ids);
1609                 $addrs_ids_arr          = $this->remove_empty_fields($addrs_ids_arr);
1610                 $addrs_emails_arr       = explode(";",$addrs_emails);
1611                 $addrs_emails_arr       = $this->remove_empty_fields($addrs_emails_arr);
1612                 $addrs_names_arr        = explode(";",$addrs_names);
1613                 $addrs_names_arr        = $this->remove_empty_fields($addrs_names_arr);
1614
1615                 ///////////////////////////////////////////////////////////////////////
1616                 ////    HANDLE EMAILS HAND-WRITTEN
1617                 $contactRecipients = array();
1618                 $knownEmails = array();
1619
1620                 foreach($addrs_arr as $i => $v) {
1621                         if(trim($v) == "")
1622                                 continue; // skip any "blanks" - will always have 1
1623
1624                         $recipient = array();
1625
1626                         //// get the email to see if we're dealing with a dupe
1627                         //// what crappy coding
1628                         preg_match("/[A-Z0-9._%-\']+@[A-Z0-9.-]+\.[A-Z]{2,}/i",$v, $match);
1629
1630
1631                         if(!empty($match[0]) && !in_array(trim($match[0]), $knownEmails)) {
1632                                 $knownEmails[] = $match[0];
1633                                 $recipient['email'] = $match[0];
1634
1635                                 //// handle the Display name
1636                                 $display = trim(str_replace($match[0], '', $v));
1637
1638                                 //// only trigger a "displayName" <email@address> when necessary
1639                                 if(isset($addrs_names_arr[$i])){
1640                                                 $recipient['display'] = $addrs_names_arr[$i];
1641                                 }
1642                                 else if(!empty($display)) {
1643                                         $recipient['display'] = $display;
1644                                 }
1645                                 if(isset($addrs_ids_arr[$i]) && $addrs_emails_arr[$i] == $match[0]){
1646                                         $recipient['contact_id'] = $addrs_ids_arr[$i];
1647                                 }
1648                                 $return[] = $recipient;
1649                         }
1650                 }
1651
1652                 return $return;
1653         }
1654
1655         function remove_empty_fields(&$arr) {
1656                 $newarr = array();
1657
1658                 foreach($arr as $field) {
1659                         $field = trim($field);
1660                         if(empty($field)) {
1661                                 continue;
1662                         }
1663                         array_push($newarr,$field);
1664                 }
1665                 return $newarr;
1666         }
1667
1668         /**
1669          * handles attachments of various kinds when sending email
1670          */
1671         function handleAttachments() {
1672
1673
1674
1675
1676                 global $mod_strings;
1677
1678         ///////////////////////////////////////////////////////////////////////////
1679         ////    ATTACHMENTS FROM DRAFTS
1680         if(($this->type == 'out' || $this->type == 'draft') && $this->status == 'draft' && isset($_REQUEST['record'])) {
1681             $this->getNotes($_REQUEST['record']); // cn: get notes from OLD email for use in new email
1682         }
1683         ////    END ATTACHMENTS FROM DRAFTS
1684         ///////////////////////////////////////////////////////////////////////////
1685
1686         ///////////////////////////////////////////////////////////////////////////
1687         ////    ATTACHMENTS FROM FORWARDS
1688         // Bug 8034 Jenny - Need the check for type 'draft' here to handle cases where we want to save
1689         // forwarded messages as drafts.  We still need to save the original message's attachments.
1690         if(($this->type == 'out' || $this->type == 'draft') &&
1691                 isset($_REQUEST['origType']) && $_REQUEST['origType'] == 'forward' &&
1692                 isset($_REQUEST['return_id']) && !empty($_REQUEST['return_id'])
1693         ) {
1694             $this->getNotes($_REQUEST['return_id'], true);
1695         }
1696
1697         // cn: bug 8034 - attachments from forward/replies lost when saving in draft
1698         if(isset($_REQUEST['prior_attachments']) && !empty($_REQUEST['prior_attachments']) && $this->new_with_id == true) {
1699                 $exIds = explode(",", $_REQUEST['prior_attachments']);
1700                 if(!isset($_REQUEST['template_attachment'])) {
1701                         $_REQUEST['template_attachment'] = array();
1702                 }
1703                 $_REQUEST['template_attachment'] = array_merge($_REQUEST['template_attachment'], $exIds);
1704         }
1705         ////    END ATTACHMENTS FROM FORWARDS
1706         ///////////////////////////////////////////////////////////////////////////
1707
1708                 ///////////////////////////////////////////////////////////////////////////
1709                 ////    ATTACHMENTS FROM TEMPLATES
1710                 // to preserve individual email integrity, we must dupe Notes and associated files
1711                 // for each outbound email - good for integrity, bad for filespace
1712                 if(isset($_REQUEST['template_attachment']) && !empty($_REQUEST['template_attachment'])) {
1713                         $removeArr = array();
1714                         $noteArray = array();
1715
1716                         if(isset($_REQUEST['temp_remove_attachment']) && !empty($_REQUEST['temp_remove_attachment'])) {
1717                                 $removeArr = $_REQUEST['temp_remove_attachment'];
1718                         }
1719
1720
1721                         foreach($_REQUEST['template_attachment'] as $noteId) {
1722                                 if(in_array($noteId, $removeArr)) {
1723                                         continue;
1724                                 }
1725                                 $noteTemplate = new Note();
1726                                 $noteTemplate->retrieve($noteId);
1727                                 $noteTemplate->id = create_guid();
1728                                 $noteTemplate->new_with_id = true; // duplicating the note with files
1729                                 $noteTemplate->parent_id = $this->id;
1730                                 $noteTemplate->parent_type = $this->module_dir;
1731                                 $noteTemplate->date_entered = '';
1732                                 $noteTemplate->save();
1733
1734                                 $noteFile = new UploadFile();
1735                                 $noteFile->duplicate_file($noteId, $noteTemplate->id, $noteTemplate->filename);
1736                                 $noteArray[] = $noteTemplate;
1737                         }
1738                         $this->attachments = array_merge($this->attachments, $noteArray);
1739                 }
1740                 ////    END ATTACHMENTS FROM TEMPLATES
1741                 ///////////////////////////////////////////////////////////////////////////
1742
1743                 ///////////////////////////////////////////////////////////////////////////
1744                 ////    ADDING NEW ATTACHMENTS
1745                 $max_files_upload = 10;
1746         // Jenny - Bug 8211 Since attachments for drafts have already been processed,
1747         // we don't need to re-process them.
1748         if($this->status != "draft") {
1749                 $notes_list = array();
1750                 if(!empty($this->id) && !$this->new_with_id) {
1751                         $note = new Note();
1752                         $where = "notes.parent_id='{$this->id}'";
1753                         $notes_list = $note->get_full_list("", $where, true);
1754                 }
1755                 $this->attachments = array_merge($this->attachments, $notes_list);
1756         }
1757                 // cn: Bug 5995 - rudimentary error checking
1758                 $filesError = array(
1759                         0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
1760                         1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
1761                         2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
1762                         3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
1763                         4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
1764                         5 => 'UNKNOWN ERROR',
1765                         6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
1766                         7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
1767                 );
1768
1769                 for($i = 0; $i < $max_files_upload; $i++) {
1770                         // cn: Bug 5995 - rudimentary error checking
1771                         if (!isset($_FILES["email_attachment{$i}"])) {
1772                                 $GLOBALS['log']->debug("Email Attachment {$i} does not exist.");
1773                                 continue;
1774                         }
1775                         if($_FILES['email_attachment'.$i]['error'] != 0 && $_FILES['email_attachment'.$i]['error'] != 4) {
1776                                 $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment'.$i]['error']]);
1777                                 continue;
1778                         }
1779
1780                         $note = new Note();
1781                         $note->parent_id = $this->id;
1782                         $note->parent_type = $this->module_dir;
1783                         $upload_file = new UploadFile('email_attachment'.$i);
1784
1785                         if(empty($upload_file)) {
1786                                 continue;
1787                         }
1788
1789                         if(isset($_FILES['email_attachment'.$i]) && $upload_file->confirm_upload()) {
1790                                 $note->filename = $upload_file->get_stored_file_name();
1791                                 $note->file = $upload_file;
1792                                 $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$note->file->original_file_name;
1793
1794                                 $this->attachments[] = $note;
1795                         }
1796                 }
1797
1798                 $this->saved_attachments = array();
1799                 foreach($this->attachments as $note) {
1800                         if(!empty($note->id)) {
1801                                 array_push($this->saved_attachments, $note);
1802                                 continue;
1803                         }
1804                         $note->parent_id = $this->id;
1805                         $note->parent_type = 'Emails';
1806                         $note->file_mime_type = $note->file->mime_type;
1807                         $note_id = $note->save();
1808
1809                         $this->saved_attachments[] = $note;
1810
1811                         $note->id = $note_id;
1812                         $note->file->final_move($note->id);
1813                 }
1814                 ////    END NEW ATTACHMENTS
1815                 ///////////////////////////////////////////////////////////////////////////
1816
1817                 ///////////////////////////////////////////////////////////////////////////
1818                 ////    ATTACHMENTS FROM DOCUMENTS
1819                 for($i=0; $i<10; $i++) {
1820                         if(isset($_REQUEST['documentId'.$i]) && !empty($_REQUEST['documentId'.$i])) {
1821                                 $doc = new Document();
1822                                 $docRev = new DocumentRevision();
1823                                 $docNote = new Note();
1824                                 $noteFile = new UploadFile();
1825
1826                                 $doc->retrieve($_REQUEST['documentId'.$i]);
1827                                 $docRev->retrieve($doc->document_revision_id);
1828
1829                                 $this->saved_attachments[] = $docRev;
1830
1831                                 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
1832                                 $docNote->name = $docRev->getDocumentRevisionNameForDisplay();
1833                                 $docNote->filename = $docRev->filename;
1834                                 $docNote->description = $doc->description;
1835                                 $docNote->parent_id = $this->id;
1836                                 $docNote->parent_type = 'Emails';
1837                                 $docNote->file_mime_type = $docRev->file_mime_type;
1838                                 $docId = $docNote = $docNote->save();
1839
1840                                 $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
1841                         }
1842                 }
1843
1844                 ////    END ATTACHMENTS FROM DOCUMENTS
1845                 ///////////////////////////////////////////////////////////////////////////
1846
1847                 ///////////////////////////////////////////////////////////////////////////
1848                 ////    REMOVE ATTACHMENTS
1849         if(isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
1850             foreach($_REQUEST['remove_attachment'] as $noteId) {
1851                 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1852                 $this->db->query($q);
1853             }
1854         }
1855
1856         //this will remove attachments that have been selected to be removed from drafts.
1857         if(isset($_REQUEST['removeAttachment']) && !empty($_REQUEST['removeAttachment'])) {
1858             $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1859             foreach($exRemoved as $noteId) {
1860                 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1861                 $this->db->query($q);
1862             }
1863         }
1864                 ////    END REMOVE ATTACHMENTS
1865                 ///////////////////////////////////////////////////////////////////////////
1866         }
1867
1868
1869         /**
1870          * Determines if an email body (HTML or Plain) has a User signature already in the content
1871          * @param array Array of signatures
1872          * @return bool
1873          */
1874         function hasSignatureInBody($sig) {
1875                 // strpos can't handle line breaks - normalize
1876                 $html = $this->removeAllNewlines($this->description_html);
1877                 $htmlSig = $this->removeAllNewlines($sig['signature_html']);
1878                 $plain = $this->removeAllNewlines($this->description);
1879                 $plainSig = $this->removeAllNewlines($sig['signature']);
1880
1881                 // cn: bug 11621 - empty sig triggers notice error
1882                 if(!empty($htmlSig) && false !== strpos($html, $htmlSig)) {
1883                         return true;
1884                 } elseif(!empty($plainSig) && false !== strpos($plain, $plainSig)) {
1885                         return true;
1886                 } else {
1887                         return false;
1888                 }
1889         }
1890
1891         /**
1892          * internal helper
1893          * @param string String to be normalized
1894          * @return string
1895          */
1896         function removeAllNewlines($str) {
1897                 $bad = array("\r\n", "\n\r", "\n", "\r");
1898                 $good = array('', '', '', '');
1899
1900                 return str_replace($bad, $good, strip_tags(br2nl(from_html($str))));
1901         }
1902
1903
1904
1905         /**
1906          * Set navigation anchors to aid DetailView record navigation (VCR buttons)
1907          * @param string uri The URI from the referring page (always ListView)
1908          * @return array start Array of the URI broken down with a special "current_view" for My Inbox Navs
1909          */
1910         function getStartPage($uri) {
1911                 if(strpos($uri, '&')) { // "&" to ensure that we can explode the GET vars - else we're gonna trigger a Notice error
1912                         $serial = substr($uri, (strpos($uri, '?')+1), strlen($uri));
1913                         $exUri = explode('&', $serial);
1914                         $start = array('module' => '', 'action' => '', 'group' => '', 'record' => '', 'type' => '');
1915
1916                         foreach($exUri as $k => $pair) {
1917                                 $exPair = explode('=', $pair);
1918                                 $start[$exPair[0]] = $exPair[1];
1919                         }
1920
1921                         // specific views for current_user
1922                         if(isset($start['assigned_user_id'])) {
1923                                 $start['current_view'] = "{$start['action']}&module={$start['module']}&assigned_user_id={$start['assigned_user_id']}&type={$start['type']}";
1924                         }
1925
1926                         return $start;
1927                 } else {
1928                         return array();
1929                 }
1930         }
1931
1932         /**
1933          * preps SMTP info for email transmission
1934          * @param object mail SugarPHPMailer object
1935          * @param string mailer_id
1936          * @param string ieId
1937          * @return object mail SugarPHPMailer object
1938          */
1939         function setMailer($mail, $mailer_id='', $ieId='') {
1940                 global $current_user;
1941
1942                 require_once("include/OutboundEmail/OutboundEmail.php");
1943                 $oe = new OutboundEmail();
1944                 $oe = $oe->getInboundMailerSettings($current_user, $mailer_id, $ieId);
1945
1946                 // ssl or tcp - keeping outside isSMTP b/c a default may inadvertantly set ssl://
1947                 $mail->protocol = ($oe->mail_smtpssl) ? "ssl://" : "tcp://";
1948         if($oe->mail_sendtype == "SMTP")
1949         {
1950                 //Set mail send type information
1951                 $mail->Mailer = "smtp";
1952                 $mail->Host = $oe->mail_smtpserver;
1953                 $mail->Port = $oe->mail_smtpport;
1954             if ($oe->mail_smtpssl == 1) {
1955                 $mail->SMTPSecure = 'ssl';
1956             } // if
1957             if ($oe->mail_smtpssl == 2) {
1958                 $mail->SMTPSecure = 'tls';
1959             } // if
1960
1961                 if($oe->mail_smtpauth_req) {
1962                         $mail->SMTPAuth = TRUE;
1963                         $mail->Username = $oe->mail_smtpuser;
1964                         $mail->Password = $oe->mail_smtppass;
1965                 }
1966         }
1967         else
1968                         $mail->Mailer = "sendmail";
1969
1970                 $mail->oe = $oe;
1971                 return $mail;
1972         }
1973
1974         /**
1975          * preps SugarPHPMailer object for HTML or Plain text sends
1976          * @param SugarPHPMailer $mail SugarPHPMailer instance
1977          */
1978         function handleBody($mail) {
1979                 global $current_user;
1980                 global $sugar_config;
1981                 ///////////////////////////////////////////////////////////////////////
1982                 ////    HANDLE EMAIL FORMAT PREFERENCE
1983                 // the if() below is HIGHLY dependent on the Javascript unchecking the Send HTML Email box
1984                 // HTML email
1985                 if( (isset($_REQUEST['setEditor']) /* from Email EditView navigation */
1986                         && $_REQUEST['setEditor'] == 1
1987                         && trim($_REQUEST['description_html']) != '')
1988                         || trim($this->description_html) != '' /* from email templates */
1989             && $current_user->getPreference('email_editor_option', 'global') !== 'plain' //user preference is not set to plain text
1990                 ) {
1991                     $this->handleBodyInHTMLformat($mail);
1992                 } else {
1993                         // plain text only
1994                         $this->description_html = '';
1995                         $mail->IsHTML(false);
1996                         $plainText = from_html($this->description);
1997                         $plainText = str_replace("&nbsp;", " ", $plainText);
1998                         $plainText = str_replace("</p>", "</p><br />", $plainText);
1999                         $plainText = strip_tags(br2nl($plainText));
2000                         $plainText = str_replace("&amp;", "&", $plainText);
2001             $plainText = str_replace("&#39;", "'", $plainText);
2002                         $mail->Body = wordwrap($plainText, 996);
2003                         $mail->Body = $this->decodeDuringSend($mail->Body);
2004                         $this->description = $mail->Body;
2005                 }
2006
2007                 // wp: if plain text version has lines greater than 998, use base64 encoding
2008                 foreach(explode("\n", ($mail->ContentType == "text/html") ? $mail->AltBody : $mail->Body) as $line) {
2009                         if(strlen($line) > 998) {
2010                                 $mail->Encoding = 'base64';
2011                                 break;
2012                         }
2013                 }
2014                 ////    HANDLE EMAIL FORMAT PREFERENCE
2015                 ///////////////////////////////////////////////////////////////////////
2016
2017                 return $mail;
2018         }
2019
2020         /**
2021          * Retrieve function from handlebody() to unit test easily
2022          * @param SugarPHPMailer $mail SugarPHPMailer instance
2023          * @return formatted $mail body
2024          */
2025         function handleBodyInHTMLformat($mail) {
2026                 global $sugar_config;
2027                 // wp: if body is html, then insert new lines at 996 characters. no effect on client side
2028                 // due to RFC 2822 which limits email lines to 998
2029                 $mail->IsHTML(true);
2030                 $body = from_html(wordwrap($this->description_html, 996));
2031                 $mail->Body = $body;
2032
2033                 // cn: bug 9725
2034                 // new plan is to use the selected type (html or plain) to fill the other
2035                 $plainText = from_html($this->description_html);
2036                 $plainText = strip_tags(br2nl($plainText));
2037                 $mail->AltBody = $plainText;
2038                 $this->description = $plainText;
2039
2040                 $mail->replaceImageByRegex("(?:{$sugar_config['site_url']})?/?cache/images/", sugar_cached("images/"));
2041
2042                 //Replace any embeded images using the secure entryPoint for src url.
2043                 $mail->replaceImageByRegex("(?:{$sugar_config['site_url']})?/?index.php[?]entryPoint=download&(?:amp;)?[^\"]+?id=", "upload://", true);
2044
2045                 $mail->Body = from_html($mail->Body);
2046         }
2047
2048         /**
2049          * Sends Email
2050          * @return bool True on success
2051          */
2052         function send() {
2053                 global $mod_strings,$app_strings;
2054                 global $current_user;
2055                 global $sugar_config;
2056                 global $locale;
2057         $OBCharset = $locale->getPrecedentPreference('default_email_charset');
2058                 $mail = new SugarPHPMailer();
2059
2060                 foreach ($this->to_addrs_arr as $addr_arr) {
2061                         if ( empty($addr_arr['display'])) {
2062                                 $mail->AddAddress($addr_arr['email'], "");
2063                         } else {
2064                                 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
2065                         }
2066                 }
2067                 foreach ($this->cc_addrs_arr as $addr_arr) {
2068                         if ( empty($addr_arr['display'])) {
2069                                 $mail->AddCC($addr_arr['email'], "");
2070                         } else {
2071                                 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2072                         }
2073                 }
2074
2075                 foreach ($this->bcc_addrs_arr as $addr_arr) {
2076                         if ( empty($addr_arr['display'])) {
2077                                 $mail->AddBCC($addr_arr['email'], "");
2078                         } else {
2079                                 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2080                         }
2081                 }
2082
2083                 $mail = $this->setMailer($mail);
2084
2085                 // FROM ADDRESS
2086                 if(!empty($this->from_addr)) {
2087                         $mail->From = $this->from_addr;
2088                 } else {
2089                         $mail->From = $current_user->getPreference('mail_fromaddress');
2090                         $this->from_addr = $mail->From;
2091                 }
2092                 // FROM NAME
2093                 if(!empty($this->from_name)) {
2094                         $mail->FromName = $this->from_name;
2095                 } else {
2096                         $mail->FromName =  $current_user->getPreference('mail_fromname');
2097                         $this->from_name = $mail->FromName;
2098                 }
2099
2100                 //Reply to information for case create and autoreply.
2101                 if(!empty($this->reply_to_name)) {
2102                         $ReplyToName = $this->reply_to_name;
2103                 } else {
2104                         $ReplyToName = $mail->FromName;
2105                 }
2106                 if(!empty($this->reply_to_addr)) {
2107                         $ReplyToAddr = $this->reply_to_addr;
2108                 } else {
2109                         $ReplyToAddr = $mail->From;
2110                 }
2111                 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
2112                 $mail->AddReplyTo($ReplyToAddr,$locale->translateCharsetMIME(trim($ReplyToName), 'UTF-8', $OBCharset));
2113
2114                 //$mail->Subject = html_entity_decode($this->name, ENT_QUOTES, 'UTF-8');
2115                 $mail->Subject = $this->name;
2116
2117                 ///////////////////////////////////////////////////////////////////////
2118                 ////    ATTACHMENTS
2119                 foreach($this->saved_attachments as $note) {
2120                         $mime_type = 'text/plain';
2121                         if($note->object_name == 'Note') {
2122                                 if(!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) { // brandy-new file upload/attachment
2123                                         $file_location = "upload://$note->id";
2124                                         $filename = $note->file->original_file_name;
2125                                         $mime_type = $note->file->mime_type;
2126                                 } else { // attachment coming from template/forward
2127                                         $file_location = "upload://{$note->id}";
2128                                         // cn: bug 9723 - documents from EmailTemplates sent with Doc Name, not file name.
2129                                         $filename = !empty($note->filename) ? $note->filename : $note->name;
2130                                         $mime_type = $note->file_mime_type;
2131                                 }
2132                         } elseif($note->object_name == 'DocumentRevision') { // from Documents
2133                                 $filePathName = $note->id;
2134                                 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
2135                                 $filename = $note->getDocumentRevisionNameForDisplay();
2136                                 $file_location = "upload://$note->id";
2137                                 $mime_type = $note->file_mime_type;
2138                         }
2139
2140                         // strip out the "Email attachment label if exists
2141                         $filename = str_replace($mod_strings['LBL_EMAIL_ATTACHMENT'].': ', '', $filename);
2142             $file_ext = pathinfo($filename, PATHINFO_EXTENSION);
2143                         //is attachment in our list of bad files extensions?  If so, append .txt to file location
2144                         //check to see if this is a file with extension located in "badext"
2145                         foreach($sugar_config['upload_badext'] as $badExt) {
2146                         if(strtolower($file_ext) == strtolower($badExt)) {
2147                                 //if found, then append with .txt to filename and break out of lookup
2148                                 //this will make sure that the file goes out with right extension, but is stored
2149                                 //as a text in db.
2150                                 $file_location = $file_location . ".txt";
2151                                 break; // no need to look for more
2152                         }
2153                 }
2154                         $mail->AddAttachment($file_location,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
2155
2156                         // embedded Images
2157                         if($note->embed_flag == true) {
2158                                 $cid = $filename;
2159                                 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64',$mime_type);
2160                         }
2161                 }
2162                 ////    END ATTACHMENTS
2163                 ///////////////////////////////////////////////////////////////////////
2164
2165                 $mail = $this->handleBody($mail);
2166
2167                 $GLOBALS['log']->debug('Email sending --------------------- ');
2168
2169                 ///////////////////////////////////////////////////////////////////////
2170                 ////    I18N TRANSLATION
2171                 $mail->prepForOutbound();
2172                 ////    END I18N TRANSLATION
2173                 ///////////////////////////////////////////////////////////////////////
2174
2175                 if($mail->Send()) {
2176                         ///////////////////////////////////////////////////////////////////
2177                         ////    INBOUND EMAIL HANDLING
2178                         // mark replied
2179                         if(!empty($_REQUEST['inbound_email_id'])) {
2180                                 $ieMail = new Email();
2181                                 $ieMail->retrieve($_REQUEST['inbound_email_id']);
2182                                 $ieMail->status = 'replied';
2183                                 $ieMail->save();
2184                         }
2185                         $GLOBALS['log']->debug(' --------------------- buh bye -- sent successful');
2186                         ////    END INBOUND EMAIL HANDLING
2187                         ///////////////////////////////////////////////////////////////////
2188                         return true;
2189                 }
2190             $GLOBALS['log']->debug($app_strings['LBL_EMAIL_ERROR_PREPEND'].$mail->ErrorInfo);
2191                 return false;
2192         }
2193
2194
2195         function listviewACLHelper(){
2196                 $array_assign = parent::listviewACLHelper();
2197                 $is_owner = false;
2198                 if(!empty($this->parent_name)){
2199
2200                         if(!empty($this->parent_name_owner)){
2201                                 global $current_user;
2202                                 $is_owner = $current_user->id == $this->parent_name_owner;
2203                         }
2204                 }
2205                 if(!ACLController::moduleSupportsACL($this->parent_type) || ACLController::checkAccess($this->parent_type, 'view', $is_owner)){
2206                         $array_assign['PARENT'] = 'a';
2207                 } else {
2208                         $array_assign['PARENT'] = 'span';
2209                 }
2210                 $is_owner = false;
2211                 if(!empty($this->contact_name)) {
2212                         if(!empty($this->contact_name_owner)) {
2213                                 global $current_user;
2214                                 $is_owner = $current_user->id == $this->contact_name_owner;
2215                         }
2216                 }
2217                 if(ACLController::checkAccess('Contacts', 'view', $is_owner)) {
2218                         $array_assign['CONTACT'] = 'a';
2219                 } else {
2220                         $array_assign['CONTACT'] = 'span';
2221                 }
2222
2223                 return $array_assign;
2224         }
2225
2226         function getSystemDefaultEmail() {
2227                 $email = array();
2228
2229                 $r1 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromaddress\'');
2230                 $r2 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromname\'');
2231                 $a1 = $this->db->fetchByAssoc($r1);
2232                 $a2 = $this->db->fetchByAssoc($r2);
2233
2234                 $email['email'] = $a1['value'];
2235                 $email['name']  = $a2['value'];
2236
2237                 return $email;
2238         }
2239
2240
2241     function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false) {
2242
2243                 if ($return_array) {
2244                         return parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, $return_array,$parentbean, $singleSelect);
2245                 }
2246         $custom_join = $this->getCustomJoin();
2247
2248                 $query = "SELECT ".$this->table_name.".*, users.user_name as assigned_user_name\n";
2249
2250         $query .= $custom_join['select'];
2251         $query .= " FROM emails\n";
2252         if ($where != "" && (strpos($where, "contacts.first_name") > 0))  {
2253                         $query .= " LEFT JOIN emails_beans ON emails.id = emails_beans.email_id\n";
2254         }
2255
2256         $query .= " LEFT JOIN users ON emails.assigned_user_id=users.id \n";
2257         if ($where != "" && (strpos($where, "contacts.first_name") > 0))  {
2258
2259         $query .= " JOIN contacts ON contacts.id= emails_beans.bean_id AND emails_beans.bean_module='Contacts' and contacts.deleted=0 \n";
2260         }
2261
2262         $query .= $custom_join['join'];
2263
2264                 if($show_deleted == 0) {
2265                         $where_auto = " emails.deleted=0 \n";
2266                 }else if($show_deleted == 1){
2267                         $where_auto = " emails.deleted=1 \n";
2268                 }
2269
2270         if($where != "")
2271                         $query .= "WHERE $where AND ".$where_auto;
2272                 else
2273                         $query .= "WHERE ".$where_auto;
2274
2275                 if($order_by != "")
2276                         $query .= " ORDER BY $order_by";
2277                 else
2278                         $query .= " ORDER BY date_sent DESC";
2279
2280                 return $query;
2281     } // fn
2282
2283
2284         function fill_in_additional_list_fields() {
2285                 global $timedate, $mod_strings;
2286                 $this->fill_in_additional_detail_fields();
2287
2288                 $this->link_action = 'DetailView';
2289                 ///////////////////////////////////////////////////////////////////////
2290                 //populate attachment_image, used to display attachment icon.
2291                 $query =  "select 1 from notes where notes.parent_id = '$this->id' and notes.deleted = 0";
2292                 $result =$this->db->query($query,true," Error filling in additional list fields: ");
2293
2294                 $row = $this->db->fetchByAssoc($result);
2295         $this->attachment_image = ($row !=null) ? SugarThemeRegistry::current()->getImage('attachment',"","","") : "";
2296
2297                 if ($row !=null) {
2298                         $this->attachment_image = SugarThemeRegistry::current()->getImage('attachment',"","","",'.gif',translate('LBL_ATTACHMENT', 'Emails'));
2299                 }
2300
2301                 ///////////////////////////////////////////////////////////////////////
2302                 if(empty($this->contact_id) && !empty($this->parent_id) && !empty($this->parent_type) && $this->parent_type === 'Contacts' && !empty($this->parent_name) ){
2303                         $this->contact_id = $this->parent_id;
2304                         $this->contact_name = $this->parent_name;
2305                 }
2306         }
2307
2308         function fill_in_additional_detail_fields() {
2309                 global $app_list_strings,$mod_strings;
2310                 // Fill in the assigned_user_name
2311                 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id, '');
2312                 //if ($this->parent_type == 'Contacts') {
2313                         $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 ";
2314                         $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";
2315                         if(!empty($this->parent_id)){
2316                                 $query .= " AND contacts.id= '".$this->parent_id."' ";
2317                         }else if(!empty($_REQUEST['record'])){
2318                                 $query .= " AND contacts.id= '".$_REQUEST['record']."' ";
2319                         }
2320                         $result =$this->db->query($query,true," Error filling in additional detail fields: ");
2321
2322                         // Get the id and the name.
2323                         $row = $this->db->fetchByAssoc($result);
2324                         if($row != null)
2325                         {
2326
2327                                 $contact = new Contact();
2328                                 $contact->retrieve($row['id']);
2329                                 $this->contact_name = $contact->full_name;
2330                                 $this->contact_phone = $row['phone_work'];
2331                                 $this->contact_id = $row['id'];
2332                                 $this->contact_email = $contact->emailAddress->getPrimaryAddress($contact);
2333                                 $this->contact_name_owner = $row['contact_name_owner'];
2334                                 $this->contact_name_mod = $row['contact_name_mod'];
2335                                 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2336                                 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2337                                 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2338                                 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2339                         }
2340                         else {
2341                                 $this->contact_name = '';
2342                                 $this->contact_phone = '';
2343                                 $this->contact_id = '';
2344                                 $this->contact_email = '';
2345                                 $this->contact_name_owner = '';
2346                                 $this->contact_name_mod = '';
2347                                 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2348                                 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2349                                 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2350                                 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2351                         }
2352                 //}
2353                 $this->created_by_name = get_assigned_user_name($this->created_by);
2354                 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
2355
2356                 $this->link_action = 'DetailView';
2357
2358                 if(!empty($this->type)) {
2359                         if($this->type == 'out' && $this->status == 'send_error') {
2360                                 $this->type_name = $mod_strings['LBL_NOT_SENT'];
2361                         } else {
2362                                 $this->type_name = $app_list_strings['dom_email_types'][$this->type];
2363                         }
2364
2365                         if(($this->type == 'out' && $this->status == 'send_error') || $this->type == 'draft') {
2366                                 $this->link_action = 'EditView';
2367                         }
2368                 }
2369
2370                 //todo this  isset( $app_list_strings['dom_email_status'][$this->status]) is hack for 3261.
2371                 if(!empty($this->status) && isset( $app_list_strings['dom_email_status'][$this->status])) {
2372                         $this->status_name = $app_list_strings['dom_email_status'][$this->status];
2373                 }
2374
2375                 if ( empty($this->name ) &&  empty($_REQUEST['record'])) {
2376                         $this->name = $mod_strings['LBL_NO_SUBJECT'];
2377                 }
2378
2379                 $this->fill_in_additional_parent_fields();
2380         }
2381
2382
2383
2384         function create_export_query(&$order_by, &$where)
2385     {
2386                 $contact_required = stristr($where, "contacts");
2387                 $custom_join = $this->getCustomJoin(true, true, $where);
2388
2389                 if($contact_required) {
2390                         $query = "SELECT emails.*, contacts.first_name, contacts.last_name";
2391             $query .= $custom_join['select'];
2392
2393                         $query .= " FROM contacts, emails, emails_contacts ";
2394                         $where_auto = "emails_contacts.contact_id = contacts.id AND emails_contacts.email_id = emails.id AND emails.deleted=0 AND contacts.deleted=0";
2395                 } else {
2396                         $query = 'SELECT emails.*';
2397             $query .= $custom_join['select'];
2398
2399             $query .= ' FROM emails ';
2400             $where_auto = "emails.deleted=0";
2401                 }
2402
2403         $query .= $custom_join['join'];
2404
2405                 if($where != "")
2406                         $query .= "where $where AND ".$where_auto;
2407         else
2408                         $query .= "where ".$where_auto;
2409
2410         if($order_by != "")
2411                         $query .= " ORDER BY $order_by";
2412         else
2413                         $query .= " ORDER BY emails.name";
2414         return $query;
2415     }
2416
2417         function get_list_view_data() {
2418                 global $app_list_strings;
2419                 global $theme;
2420                 global $current_user;
2421                 global $timedate;
2422                 global $mod_strings;
2423
2424                 $email_fields = $this->get_list_view_array();
2425                 $this->retrieveEmailText();
2426                 $email_fields['FROM_ADDR'] = $this->from_addr_name;
2427                 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); // hard-coding for Home screen ListView
2428
2429                 if($this->status != 'replied') {
2430                         $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>';
2431                         $email_fields['STATUS'] = ($email_fields['REPLY_TO_STATUS'] == 1 ? $mod_strings['LBL_REPLIED'] : $email_fields['STATUS']);
2432                 } else {
2433                         $email_fields['QUICK_REPLY'] = $mod_strings['LBL_REPLIED'];
2434                 }
2435                 if(!empty($this->parent_type)) {
2436                         $email_fields['PARENT_MODULE'] = $this->parent_type;
2437                 } else {
2438                         switch($this->intent) {
2439                                 case 'support':
2440                                         $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>';
2441                                 break;
2442
2443                                 case 'sales':
2444                                         $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>';
2445                                 break;
2446
2447                                 case 'contact':
2448                                         $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>';
2449                                 break;
2450
2451                                 case 'bug':
2452                                         $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>';
2453                                 break;
2454
2455                                 case 'task':
2456                                         $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>';
2457                                 break;
2458
2459                                 case 'bounce':
2460                                 break;
2461
2462                                 case 'pick':
2463                                 // break;
2464
2465                                 case 'info':
2466                                 //break;
2467
2468                                 default:
2469                                         $email_fields['CREATE_RELATED'] = $this->quickCreateForm();
2470                                 break;
2471                         }
2472
2473                 }
2474
2475                 //BUG 17098 - MFH changed $this->from_addr to $this->to_addrs
2476                 $email_fields['CONTACT_NAME']           = empty($this->contact_name) ? '</a>'.$this->trimLongTo($this->to_addrs).'<a>' : $this->contact_name;
2477                 $email_fields['CONTACT_ID']             = empty($this->contact_id) ? '' : $this->contact_id;
2478                 $email_fields['ATTACHMENT_IMAGE']       = $this->attachment_image;
2479                 $email_fields['LINK_ACTION']            = $this->link_action;
2480
2481         if(isset($this->type_name))
2482                 $email_fields['TYPE_NAME'] = $this->type_name;
2483
2484                 return $email_fields;
2485         }
2486
2487     function quickCreateForm() {
2488         global $mod_strings, $app_strings, $currentModule, $current_language;
2489
2490         // Coming from the home page via Dashlets
2491         if($currentModule != 'Email')
2492                 $mod_strings = return_module_language($current_language, 'Emails');
2493         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>";
2494     }
2495
2496     /**
2497      * Searches all imported emails and returns the result set as an array.
2498      *
2499      */
2500     function searchImportedEmails($sort = '', $direction='')
2501     {
2502         require_once('include/TimeDate.php');
2503                 global $timedate;
2504                 global $current_user;
2505                 global $beanList;
2506                 global $sugar_config;
2507                 global $app_strings;
2508
2509                 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
2510                 // cn: default to a low number until user specifies otherwise
2511                 if(empty($emailSettings['showNumInList']))
2512                         $pageSize = 20;
2513         else
2514             $pageSize = $emailSettings['showNumInList'];
2515
2516         if( isset($_REQUEST['start']) && isset($_REQUEST['limit']) )
2517                $page = ceil($_REQUEST['start'] / $_REQUEST['limit']) + 1;
2518             else
2519                $page = 1;
2520
2521              //Determine sort ordering
2522
2523              //Sort ordering parameters in the request do not coincide with actual column names
2524              //so we need to remap them.
2525              $hrSortLocal = array(
2526             'flagged' => 'type',
2527             'status'  => 'reply_to_status',
2528             'from'    => 'emails_text.from_addr',
2529             'subject' => 'name',
2530             'date'    => 'date_sent',
2531             'AssignedTo' => 'assigned_user_id',
2532             'flagged' => 'flagged'
2533         );
2534
2535              $sort = !empty($_REQUEST['sort']) ? $this->db->getValidDBName($_REQUEST['sort']) : "";
2536          $direction = !empty($_REQUEST['dir'])  && in_array(strtolower($_REQUEST['dir']), array("asc", "desc")) ? $_REQUEST['dir'] : "";
2537
2538          $order = ( !empty($sort) && !empty($direction) ) ? " ORDER BY {$hrSortLocal[$sort]} {$direction}" : "";
2539
2540          //Get our main query.
2541                 $fullQuery = $this->_genereateSearchImportedEmailsQuery();
2542
2543                 //Perform a count query needed for pagination.
2544                 $countQuery = $this->create_list_count_query($fullQuery);
2545                 
2546                 $count_rs = $this->db->query($countQuery, false, 'Error executing count query for imported emails search');
2547                 $count_row = $this->db->fetchByAssoc($count_rs);
2548                 $total_count = ($count_row != null) ? $count_row['c'] : 0;
2549
2550         $start = ($page - 1) * $pageSize;
2551
2552         //Execute the query
2553                 $rs = $this->db->limitQuery($fullQuery . $order, $start, $pageSize);
2554
2555                 $return = array();
2556
2557                 while($a = $this->db->fetchByAssoc($rs)) {
2558                         $temp = array();
2559                         $temp['flagged'] = (is_null($a['flagged']) || $a['flagged'] == '0') ? '' : 1;
2560                         $temp['status'] = (is_null($a['reply_to_status']) || $a['reply_to_status'] == '0') ? '' : 1;
2561                         $temp['subject'] = $a['name'];
2562                         $temp['date']   = $timedate->to_display_date_time($a['date_sent']);
2563                         $temp['uid'] = $a['id'];
2564                         $temp['ieId'] = $a['mailbox_id'];
2565                         $temp['site_url'] = $sugar_config['site_url'];
2566                         $temp['seen'] = ($a['status'] == 'unread') ? 0 : 1;
2567                         $temp['type'] = $a['type'];
2568                         $temp['mbox'] = 'sugar::Emails';
2569                         $temp['hasAttach'] =  $this->doesImportedEmailHaveAttachment($a['id']);
2570                         //To and from addresses may be stored in emails_text, if nothing is found, revert to
2571                         //regular email addresses.
2572                         $temp['to_addrs'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['to_addrs']);
2573                         $temp['from']   = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['from_addr']);
2574                         if( empty($temp['from']) || empty($temp['to_addrs']) )
2575                         {
2576                         //Retrieve email addresses seperatly.
2577                         $tmpEmail = new Email();
2578                         $tmpEmail->id = $a['id'];
2579                         $tmpEmail->retrieveEmailAddresses();
2580                         $temp['from'] = $tmpEmail->from_addr;
2581                         $temp['to_addrs'] = $tmpEmail->to_addrs;
2582                         }
2583
2584                         $return[] = $temp;
2585                 }
2586
2587                 $metadata = array();
2588                 $metadata['totalCount'] = $total_count;
2589                 $metadata['out'] = $return;
2590
2591                 return $metadata;
2592     }
2593
2594     /**
2595      * Determine if an imported email has an attachment by examining the relationship to notes.
2596      *
2597      * @param string $id
2598      * @return boolean
2599      */
2600     function doesImportedEmailHaveAttachment($id)
2601         {
2602            $hasAttachment = FALSE;
2603            $query = "SELECT id FROM notes where parent_id='$id' AND parent_type='Emails' AND file_mime_type is not null AND deleted=0";
2604            $rs = $this->db->limitQuery($query, 0, 1);
2605            $row = $this->db->fetchByAssoc($rs);
2606            if( !empty($row['id']) )
2607                $hasAttachment = TRUE;
2608
2609            return (int) $hasAttachment;
2610         }
2611
2612     /**
2613      * Generate the query used for searching imported emails.
2614      *
2615      * @return String Query to be executed.
2616      */
2617     function _genereateSearchImportedEmailsQuery()
2618     {
2619                 global $timedate;
2620
2621         $additionalWhereClause = $this->_generateSearchImportWhereClause();
2622
2623         $query = array();
2624         $fullQuery = "";
2625         $query['select'] = "emails.id , emails.mailbox_id, emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status,
2626                                       emails_text.from_addr, emails_text.to_addrs  FROM emails ";
2627
2628         $query['joins'] = " JOIN emails_text on emails.id = emails_text.email_id ";
2629
2630         //Handle from and to addr joins
2631         if( !empty($_REQUEST['from_addr']) )
2632         {
2633             $from_addr = $this->db->quote(strtolower($_REQUEST['from_addr']));
2634             $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
2635                                 AND er_from.address_type='from' AND emails_text.from_addr LIKE '%" . $from_addr . "%'";
2636         }
2637
2638         if( !empty($_REQUEST['to_addrs'])  )
2639         {
2640             $to_addrs = $this->db->quote(strtolower($_REQUEST['to_addrs']));
2641             $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
2642                                     AND er_to.address_type='to' AND ea_to.email_address LIKE '%" . $to_addrs . "%'";
2643         }
2644
2645         $query['where'] = " WHERE (emails.type= 'inbound' OR emails.type='archived' OR emails.type='out') AND emails.deleted = 0 ";
2646                 if( !empty($additionalWhereClause) )
2647             $query['where'] .= "AND $additionalWhereClause";
2648
2649         //If we are explicitly looking for attachments.  Do not use a distinct query as the to_addr is defined
2650         //as a text which equals clob in oracle and the distinct query can not be executed correctly.
2651         $addDistinctKeyword = "";
2652         if( !empty($_REQUEST['attachmentsSearch']) &&  $_REQUEST['attachmentsSearch'] == 1) //1 indicates yes
2653             $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 )";
2654         else if( !empty($_REQUEST['attachmentsSearch']) &&  $_REQUEST['attachmentsSearch'] == 2 )
2655              $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 )";
2656
2657         $fullQuery = "SELECT " . $query['select'] . " " . $query['joins'] . " " . $query['where'];
2658         
2659         return $fullQuery;
2660     }
2661         /**
2662      * Generate the where clause for searching imported emails.
2663      *
2664      */
2665     function _generateSearchImportWhereClause()
2666     {
2667         global $timedate;
2668
2669         //The clear button was removed so if a user removes the asisgned user name, do not process the id.
2670         if( empty($_REQUEST['assigned_user_name']) && !empty($_REQUEST['assigned_user_id'])  )
2671             unset($_REQUEST['assigned_user_id']);
2672
2673         $availableSearchParam = array('name' => array('table_name' =>'emails'),
2674                                       'data_parent_id_search' => array('table_name' =>'emails','db_key' => 'parent_id','opp' => '='),
2675                                       'assigned_user_id' => array('table_name' => 'emails', 'opp' => '=') );
2676
2677                 $additionalWhereClause = array();
2678                 foreach ($availableSearchParam as $key => $properties)
2679                 {
2680                       if( !empty($_REQUEST[$key]) )
2681                       {
2682                           $db_key =  isset($properties['db_key']) ? $properties['db_key'] : $key;
2683                   $searchValue = $this->db->quote($_REQUEST[$key]);
2684
2685                           $opp = isset($properties['opp']) ? $properties['opp'] : 'like';
2686                           if($opp == 'like')
2687                               $searchValue = "%" . $searchValue . "%";
2688
2689                           $additionalWhereClause[] = "{$properties['table_name']}.$db_key $opp '$searchValue' ";
2690                       }
2691         }
2692         
2693         
2694
2695         $isDateFromSearchSet = !empty($_REQUEST['searchDateFrom']);
2696         $isdateToSearchSet = !empty($_REQUEST['searchDateTo']);
2697         $bothDateRangesSet = $isDateFromSearchSet & $isdateToSearchSet;
2698
2699         //Hanlde date from and to separately
2700         if($bothDateRangesSet)
2701         {
2702             $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2703             $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2704
2705             $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2706             $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2707
2708             $additionalWhereClause[] = "( emails.date_sent >= $dbFormatDateFrom AND
2709                                           emails.date_sent <= $dbFormatDateTo )";
2710         }
2711         elseif ($isdateToSearchSet)
2712         {
2713             $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2714             $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2715             $additionalWhereClause[] = "emails.date_sent <= $dbFormatDateTo ";
2716         }
2717         elseif ($isDateFromSearchSet)
2718         {
2719             $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2720             $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2721             $additionalWhereClause[] = "emails.date_sent >= $dbFormatDateFrom ";
2722         }
2723
2724         $additionalWhereClause = implode(" AND ", $additionalWhereClause);
2725
2726         return $additionalWhereClause;
2727     }
2728
2729
2730
2731         /**
2732          * takes a long TO: string of emails and returns the first appended by an
2733          * elipse
2734          */
2735         function trimLongTo($str) {
2736                 if(strpos($str, ',')) {
2737                         $exStr = explode(',', $str);
2738                         return $exStr[0].'...';
2739                 } elseif(strpos($str, ';')) {
2740                         $exStr = explode(';', $str);
2741                         return $exStr[0].'...';
2742                 } else {
2743                         return $str;
2744                 }
2745         }
2746
2747         function get_summary_text() {
2748                 return $this->name;
2749         }
2750
2751
2752
2753         function distributionForm($where) {
2754                 global $app_list_strings;
2755                 global $app_strings;
2756                 global $mod_strings;
2757                 global $theme;
2758                 global $current_user;
2759
2760                 $distribution   = get_select_options_with_id($app_list_strings['dom_email_distribution'], '');
2761                 $_SESSION['distribute_where'] = $where;
2762
2763
2764                 $out = '<form name="Distribute" id="Distribute">';
2765                 $out .= get_form_header($mod_strings['LBL_DIST_TITLE'], '', false);
2766                 $out .=<<<eoq
2767                 <script>
2768                         enableQS(true);
2769                 </script>
2770 eoq;
2771                 $out .= '
2772                 <table cellpadding="0" cellspacing="0" width="100%" border="0">
2773                         <tr>
2774                                 <td>
2775                                         <script type="text/javascript">
2776
2777
2778                                                 function checkDeps(form) {
2779                                                         return;
2780                                                 }
2781
2782                                                 function mySubmit() {
2783                                                         var assform = document.getElementById("Distribute");
2784                                                         var select = document.getElementById("userSelect");
2785                                                         var assign1 = assform.r1.checked;
2786                                                         var assign2 = assform.r2.checked;
2787                                                         var dist = assform.dm.value;
2788                                                         var assign = false;
2789                                                         var users = false;
2790                                                         var rules = false;
2791                                                         var warn1 = "'.$mod_strings['LBL_WARN_NO_USERS'].'";
2792                                                         var warn2 = "";
2793
2794                                                         if(assign1 || assign2) {
2795                                                                 assign = true;
2796
2797                                                         }
2798
2799                                                         for(i=0; i<select.options.length; i++) {
2800                                                                 if(select.options[i].selected == true) {
2801                                                                         users = true;
2802                                                                         warn1 = "";
2803                                                                 }
2804                                                         }
2805
2806                                                         if(dist != "") {
2807                                                                 rules = true;
2808                                                         } else {
2809                                                                 warn2 = "'.$mod_strings['LBL_WARN_NO_DIST'].'";
2810                                                         }
2811
2812                                                         if(assign && users && rules) {
2813
2814                                                                 if(document.getElementById("r1").checked) {
2815                                                                         var mu = document.getElementById("MassUpdate");
2816                                                                         var grabbed = "";
2817
2818                                                                         for(i=0; i<mu.elements.length; i++) {
2819                                                                                 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name.value != "massall") {
2820                                                                                         if(grabbed != "") { grabbed += "::"; }
2821                                                                                         grabbed += mu.elements[i].value;
2822                                                                                 }
2823                                                                         }
2824                                                                         var formgrab = document.getElementById("grabbed");
2825                                                                         formgrab.value = grabbed;
2826                                                                 }
2827                                                                 assform.submit();
2828                                                         } else {
2829                                                                 alert("'.$mod_strings['LBL_ASSIGN_WARN'].'" + "\n" + warn1 + "\n" + warn2);
2830                                                         }
2831                                                 }
2832
2833                                                 function submitDelete() {
2834                                                         if(document.getElementById("r1").checked) {
2835                                                                 var mu = document.getElementById("MassUpdate");
2836                                                                 var grabbed = "";
2837
2838                                                                 for(i=0; i<mu.elements.length; i++) {
2839                                                                         if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name != "massall") {
2840                                                                                 if(grabbed != "") { grabbed += "::"; }
2841                                                                                 grabbed += mu.elements[i].value;
2842                                                                         }
2843                                                                 }
2844                                                                 var formgrab = document.getElementById("grabbed");
2845                                                                 formgrab.value = grabbed;
2846                                                         }
2847                                                         if(grabbed == "") {
2848                                                                 alert("'.$mod_strings['LBL_MASS_DELETE_ERROR'].'");
2849                                                         } else {
2850                                                                 document.getElementById("Distribute").submit();
2851                                                         }
2852                                                 }
2853
2854                                         </script>
2855                                                 <input type="hidden" name="module" value="Emails">
2856                                                 <input type="hidden" name="action" id="action">
2857                                                 <input type="hidden" name="grabbed" id="grabbed">
2858
2859                                         <table cellpadding="1" cellspacing="0" width="100%" border="0" class="edit view">
2860                                                 <tr height="20">
2861                                                         <td scope="col" scope="row" NOWRAP align="center">
2862                                                                 &nbsp;'.$mod_strings['LBL_ASSIGN_SELECTED_RESULTS_TO'].'&nbsp;';
2863                                         $out .= $this->userSelectTable();
2864                                         $out .= '</td>
2865                                                         <td scope="col" scope="row" NOWRAP align="left">
2866                                                                 &nbsp;'.$mod_strings['LBL_USING_RULES'].'&nbsp;
2867                                                                 <select name="distribute_method" id="dm" onChange="checkDeps(this.form);">'.$distribution.'</select>
2868                                                         </td>';
2869
2870
2871                                         $out .= '</td>
2872                                                         </tr>';
2873
2874
2875                                         $out .= '<tr>
2876                                                                 <td scope="col" width="50%" scope="row" NOWRAP align="right" colspan="2">
2877                                                                 <input title="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_TITLE'].'"
2878                                                                         id="dist_button"
2879                                                                         class="button" onClick="AjaxObject.detailView.handleAssignmentDialogAssignAction();"
2880                                                                         type="button" name="button"
2881                                                                         value="  '.$mod_strings['LBL_BUTTON_DISTRIBUTE'].'  ">';
2882                                         $out .= '</tr>
2883                                         </table>
2884                                 </td>
2885                         </tr>
2886                 </table>
2887                 </form>';
2888         return $out;
2889         }
2890
2891         function userSelectTable() {
2892                 global $theme;
2893                 global $mod_strings;
2894
2895                 $colspan = 1;
2896                 $setTeamUserFunction = '';
2897
2898
2899                 // get users
2900                 $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");
2901
2902                 $userTable = '<table cellpadding="0" cellspacing="0" border="0">';
2903                 $userTable .= '<tr><td colspan="2"><b>'.$mod_strings['LBL_USER_SELECT'].'</b></td></tr>';
2904                 $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>';
2905                 $userTable .= '<tr><td colspan="2"><select style="visibility:hidden;" name="users[]" id="userSelect" multiple size="12">';
2906
2907                 while($a = $this->db->fetchByAssoc($r)) {
2908                         $userTable .= '<option value="'.$a['id'].'" id="'.$a['id'].'">'.$a['first_name'].' '.$a['last_name'].'</option>';
2909                 }
2910                 $userTable .= '</select></td></tr>';
2911                 $userTable .= '</table>';
2912
2913                 $out  = '<script type="text/javascript">';
2914                 $out .= $setTeamUserFunction;
2915                 $out .= '
2916                                         function setCheckMark() {
2917                                                 var select = document.getElementById("userSelect");
2918
2919                                                 for(i=0 ; i<select.options.length; i++) {
2920                                                         if(select.options[i].selected == true) {
2921                                                                 document.getElementById("checkMark").style.display="";
2922                                                                 return;
2923                                                         }
2924                                                 }
2925
2926                                                 document.getElementById("checkMark").style.display="none";
2927                                                 return;
2928                                         }
2929
2930                                         function showUserSelect() {
2931                                                 var targetTable = document.getElementById("user_select");
2932                                                 targetTable.style.visibility="visible";
2933                                                 var userSelectTable = document.getElementById("userSelect");
2934                                                 userSelectTable.style.visibility="visible";
2935                                                 return;
2936                                         }
2937                                         function hideUserSelect() {
2938                                                 var targetTable = document.getElementById("user_select");
2939                                                 targetTable.style.visibility="hidden";
2940                                                 var userSelectTable = document.getElementById("userSelect");
2941                                                 userSelectTable.style.visibility="hidden";
2942                                                 return;
2943                                         }
2944                                         function toggleAll(toggle) {
2945                                                 if(toggle.checked) {
2946                                                         var stat = true;
2947                                                 } else {
2948                                                         var stat = false;
2949                                                 }
2950                                                 var form = document.getElementById("userSelect");
2951                                                 for(i=0; i<form.options.length; i++) {
2952                                                         form.options[i].selected = stat;
2953                                                 }
2954                                         }
2955
2956
2957                                 </script>
2958                         <span id="showUsersDiv" style="position:relative;">
2959                                 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
2960                                         '.SugarThemeRegistry::current()->getImage('Users', '', null, null, ".gif", $mod_strings['LBL_USERS']).'</a>&nbsp;
2961                                 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
2962                                         <span style="display:none;" id="checkMark">'.SugarThemeRegistry::current()->getImage('check_inline', 'border="0"', null, null, ".gif", $mod_strings['LBL_CHECK_INLINE']).'</span>
2963                                 </a>
2964
2965
2966                                 <div id="user_select" style="width:200px;position:absolute;left:2;top:2;visibility:hidden;z-index:1000;">
2967                                 <table cellpadding="0" cellspacing="0" border="0" class="list view">
2968                                         <tr height="20">
2969                                                 <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\';">
2970                                                         <a href="#" onClick="javascript:hideUserSelect();">'.SugarThemeRegistry::current()->getImage('close', 'border="0"', null, null, ".gif", $mod_strings['LBL_CLOSE']).'</a>
2971                                                         '.$mod_strings['LBL_USER_SELECT'].'
2972                                                 </td>
2973                                         </tr>
2974                                         <tr>';
2975 //<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\';">
2976                 $out .= '               <td style="padding:5px" class="oddListRowS1" bgcolor="#fdfdfd" valign="top" align="left" style="left:0;top:0;">
2977                                                         '.$userTable.'
2978                                                 </td>
2979                                         </tr>
2980                                 </table></div>
2981                         </span>';
2982                 return $out;
2983         }
2984
2985         function checkInbox($type) {
2986                 global $theme;
2987                 global $mod_strings;
2988                 $out = '<div><input     title="'.$mod_strings['LBL_BUTTON_CHECK_TITLE'].'"
2989                                                 class="button"
2990                                                 type="button" name="button"
2991                                                 onClick="window.location=\'index.php?module=Emails&action=Check&type='.$type.'\';"
2992                                                 style="margin-bottom:2px"
2993                                                 value="  '.$mod_strings['LBL_BUTTON_CHECK'].'  "></div>';
2994                 return $out;
2995         }
2996
2997         /**
2998          * Guesses Primary Parent id from From: email address.  Cascades guesses from Accounts to Contacts to Leads to
2999          * Users.  This will not affect the many-to-many relationships already constructed as this is, at best,
3000          * informational linking.
3001          */
3002         function fillPrimaryParentFields() {
3003                 if(empty($this->from_addr))
3004                         return;
3005
3006                 $GLOBALS['log']->debug("*** Email trying to guess Primary Parent from address [ {$this->from_addr} ]");
3007
3008                 $tables = array('accounts');
3009                 $ret = array();
3010                 // loop through types to get hits
3011                 foreach($tables as $table) {
3012                         $q = "SELECT name, id FROM {$table} WHERE email1 = '{$this->from_addr}' OR email2 = '{$this->from_addr}' AND deleted = 0";
3013                         $r = $this->db->query($q);
3014                         while($a = $this->db->fetchByAssoc($r)) {
3015                                 if(!empty($a['name']) && !empty($a['id'])) {
3016                                         $this->parent_type      = ucwords($table);
3017                                         $this->parent_id        = $a['id'];
3018                                         $this->parent_name      = $a['name'];
3019                                         return;
3020                                 }
3021                         }
3022                 }
3023         }
3024
3025         /**
3026          * Convert reference to inline image (stored as Note) to URL link
3027          * Enter description here ...
3028          * @param string $note ID of the note
3029          * @param string $ext type of the note
3030          */
3031         public function cid2Link($noteId, $noteType)
3032         {
3033             if(empty($this->description_html)) return;
3034                         list($type, $subtype) = explode('/', $noteType);
3035                         if(strtolower($type) != 'image') {
3036                             return;
3037                         }
3038             $upload = new UploadFile();
3039                         $this->description_html = preg_replace("#class=\"image\" src=\"cid:$noteId\.(.+?)\"#", "class=\"image\" src=\"{$this->imagePrefix}{$noteId}.\\1\"", $this->description_html);
3040                 // ensure the image is in the cache
3041                         $imgfilename = sugar_cached("images/")."$noteId.".strtolower($subtype);
3042                         $src = "upload://$noteId";
3043                         if(!file_exists($imgfilename) && file_exists($src)) {
3044                                 copy($src, $imgfilename);
3045                         }
3046         }
3047
3048         /**
3049          * Convert all cid: links in this email into URLs
3050          */
3051         function cids2Links()
3052         {
3053             if(empty($this->description_html)) return;
3054             $q = "SELECT id, file_mime_type FROM notes WHERE parent_id = '{$this->id}' AND deleted = 0";
3055                 $r = $this->db->query($q);
3056             while($a = $this->db->fetchByAssoc($r)) {
3057                 $this->cid2Link($a['id'], $a['file_mime_type']);
3058             }
3059         }
3060
3061     /**
3062      * Bugs 50972, 50973
3063      * Sets the field def for a field to allow null values
3064      *
3065      * @todo Consider moving to SugarBean to allow other models to set fields to NULL
3066      * @param string $field The field name to modify
3067      * @return void
3068      */
3069     public function setFieldNullable($field)
3070     {
3071         if (isset($this->field_defs[$field]) && is_array($this->field_defs[$field]))
3072         {
3073             if (empty($this->modifiedFieldDefs[$field]))
3074             {
3075                 if (
3076                     isset($this->field_defs[$field]['isnull']) &&
3077                     (strtolower($this->field_defs[$field]['isnull']) == 'false' || $this->field_defs[$field]['isnull'] === false)
3078                 )
3079                 {
3080                     $this->modifiedFieldDefs[$field]['isnull'] = $this->field_defs[$field]['isnull'];
3081                     unset($this->field_defs[$field]['isnull']);
3082                 }
3083
3084                 if (isset($this->field_defs[$field]['dbType']) && $this->field_defs[$field]['dbType'] == 'id')
3085                 {
3086                     $this->modifiedFieldDefs[$field]['dbType'] = $this->field_defs[$field]['dbType'];
3087                     unset($this->field_defs[$field]['dbType']);
3088                 }
3089             }
3090         }
3091     }
3092
3093     /**
3094      * Bugs 50972, 50973
3095      * Set the field def back to the way it was prior to modification
3096      *
3097      * @param $field
3098      * @return void
3099      */
3100     public function revertFieldNullable($field)
3101     {
3102         if (!empty($this->modifiedFieldDefs[$field]) && is_array($this->modifiedFieldDefs[$field]))
3103         {
3104             foreach ($this->modifiedFieldDefs[$field] as $k => $v)
3105             {
3106                 $this->field_defs[$field][$k] = $v;
3107             }
3108
3109             unset($this->modifiedFieldDefs[$field]);
3110             }
3111         }
3112 } // end class def