2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
38 /*********************************************************************************
41 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42 * Reserved. Contributor(s): ______________________________________..
43 *********************************************************************************/
44 require_once('include/SugarPHPMailer.php');
46 require_once('include/Pear/HTML_Safe/Safe.php');
48 class Email extends SugarBean {
49 /* SugarBean schema */
53 var $assigned_user_id;
54 var $assigned_user_name;
55 var $modified_user_id;
67 var $type = 'archived';
78 var $description_html;
88 var $date_start; // legacy
89 var $time_start; // legacy
101 var $bcc_addrs_names;
102 var $bcc_addrs_emails;
106 /* Archive Email attrs */
111 var $new_schema = true;
112 var $table_name = 'emails';
113 var $module_dir = 'Emails';
114 var $module_name = 'Emails';
115 var $object_name = 'Email';
118 /* private attributes */
119 var $rolloverStyle = "<style>div#rollover {position: relative;float: left;margin: none;text-decoration: none;}div#rollover a:hover {padding: 0;text-decoration: none;}div#rollover a span {display: none;}div#rollover a:hover span {text-decoration: none;display: block;width: 250px;margin-top: 5px;margin-left: 5px;position: absolute;padding: 10px;color: #333; border: 1px solid #ccc; background-color: #fff; font-size: 12px;z-index: 1000;}</style>\n";
121 var $cacheFile = 'robin.cache.php';
122 var $replyDelimiter = "> ";
123 var $emailDescription;
124 var $emailDescriptionHTML;
128 var $attachments = array();
130 /* to support Email 2.0 */
138 var $relationshipMap = array(
139 'Contacts' => 'emails_contacts_rel',
140 'Accounts' => 'emails_accounts_rel',
141 'Leads' => 'emails_leads_rel',
142 'Users' => 'emails_users_rel',
143 'Prospects' => 'emails_prospects_rel',
147 var $et; // EmailUI object
155 $this->cachePath = $GLOBALS['sugar_config']['cache_dir'].'modules/Emails';
158 $this->safe = new HTML_Safe();
159 $this->safe->clear();
160 $this->emailAddress = new SugarEmailAddress();
163 function email2init() {
164 require_once('modules/Emails/EmailUI.php');
165 $this->et = new EmailUI();
167 function bean_implements($interface){
169 case 'ACL': return true;
170 default: return false;
176 * Presaves one attachment for new email 2.0 spec
177 * DOES NOT CREATE A NOTE
178 * @return string ID of note associated with the attachment
180 function email2saveAttachment() {
181 global $sugar_config;
184 0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
185 1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
186 2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
187 3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
188 4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
189 5 => 'UNKNOWN ERROR',
190 6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
191 7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
194 // cn: Bug 5995 - rudimentary error checking
195 if($_FILES['email_attachment']['error'] != 0 && $_FILES['email_attachment']['error'] != 4) {
196 $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment']['error']]);
200 if(isset($_FILES['email_attachment']) && is_uploaded_file($_FILES['email_attachment']['tmp_name'])) {
201 $guid = create_guid();
202 $cleanAttachmentFileName = from_html($_FILES['email_attachment']['name']);
203 $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] ");
204 $cleanAttachmentFileName = str_replace("\\", "", $cleanAttachmentFileName);
205 $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] ");
206 //$destination = clean_path("{$this->et->userCacheDir}/{$guid}{$cleanAttachmentFileName}");
207 $destination = clean_path("{$this->et->userCacheDir}/{$guid}");
208 $badExt = $this->safeAttachmentName($cleanAttachmentFileName);
210 //$destination = $destination . ".txt";
212 $fileName = $badExt ? $cleanAttachmentFileName . ".txt" : $cleanAttachmentFileName;
213 if(move_uploaded_file($_FILES['email_attachment']['tmp_name'], $destination)) {
216 'name' => $GLOBALS['db']->helper->escape_quote($fileName),
217 'nameForDisplay' => $fileName
220 $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] could not be moved to cache dir");
226 function safeAttachmentName($filename) {
227 global $sugar_config;
228 $badExtension = false;
229 //get position of last "." in file name
230 $file_ext_beg = strrpos($filename, ".");
234 if($file_ext_beg !== false) {
235 $file_ext = substr($filename, $file_ext_beg + 1);
238 //check to see if this is a file with extension located in "badext"
239 foreach($sugar_config['upload_badext'] as $badExt) {
240 if(strtolower($file_ext) == strtolower($badExt)) {
241 //if found, then append with .txt and break out of lookup
242 $filename = $filename . ".txt";
243 $badExtension = true;
244 break; // no need to look for more
248 return $badExtension;
252 * takes output from email 2.0 to/cc/bcc fields and returns appropriate arrays for usage by PHPMailer
253 * @param string addresses
256 function email2ParseAddresses($addresses) {
257 $addresses = from_html($addresses);
258 $addresses = $this->et->unifyEmailString($addresses);
260 $pattern = '/@.*,/U';
261 preg_match_all($pattern, $addresses, $matchs);
262 if (!empty($matchs[0])){
264 foreach ($total as $match) {
265 $convertedPattern = str_replace(',', '::;::', $match);
266 $addresses = str_replace($match, $convertedPattern, $addresses);
270 $exAddr = explode("::;::", $addresses);
273 $clean = array("<", ">");
274 $dirty = array("<", ">");
276 foreach($exAddr as $addr) {
279 $addr = str_replace($dirty, $clean, $addr);
281 if((strpos($addr, "<") === false) && (strpos($addr, ">") === false)) {
284 $address = substr($addr, strpos($addr, "<") + 1, strpos($addr, ">") - 1 - strpos($addr, "<"));
285 $name = substr($addr, 0, strpos($addr, "<"));
289 $addrTemp['email'] = trim($address);
290 $addrTemp['display'] = trim($name);
298 * takes output from email 2.0 to/cc/bcc fields and returns appropriate arrays for usage by PHPMailer
299 * @param string addresses
302 function email2ParseAddressesForAddressesOnly($addresses) {
303 $addresses = from_html($addresses);
304 $pattern = '/@.*,/U';
305 preg_match_all($pattern, $addresses, $matchs);
306 if (!empty($matchs[0])){
308 foreach ($total as $match) {
309 $convertedPattern = str_replace(',', '::;::', $match);
310 $addresses = str_replace($match, $convertedPattern, $addresses);
314 $exAddr = explode("::;::", $addresses);
317 $clean = array("<", ">");
318 $dirty = array("<", ">");
320 foreach($exAddr as $addr) {
323 $addr = str_replace($dirty, $clean, $addr);
325 if(strpos($addr, "<") && strpos($addr, ">")) {
326 $address = substr($addr, strpos($addr, "<") + 1, strpos($addr, ">") - 1 - strpos($addr, "<"));
331 $ret[] = trim($address);
338 * Determines MIME-type encoding as possible.
339 * @param string $fileLocation relative path to file
340 * @return string MIME-type
342 function email2GetMime($fileLocation) {
343 if(!is_readable($fileLocation)) {
344 return 'application/octet-stream';
346 if(function_exists('mime_content_type')) {
347 $mime = mime_content_type($fileLocation);
348 } elseif(function_exists('ext2mime')) {
349 $mime = ext2mime($fileLocation);
351 $mime = 'application/octet-stream';
357 function sendEmailTest($mailserver_url, $port, $ssltls, $smtp_auth_req, $smtp_username, $smtppassword, $fromaddress, $toaddress, $mail_sendtype = 'smtp', $fromname = '') {
358 global $current_user,$app_strings;
359 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); //Called from EmailMan as well.
360 $mail = new SugarPHPMailer();
361 $mail->Mailer = strtolower($mail_sendtype);
362 if($mail->Mailer == 'smtp')
364 $mail->Host = $mailserver_url;
366 if (isset($ssltls) && !empty($ssltls)) {
367 $mail->protocol = "ssl://";
369 $mail->SMTPSecure = 'ssl';
372 $mail->SMTPSecure = 'tls';
375 $mail->protocol = "tcp://";
377 if ($smtp_auth_req) {
378 $mail->SMTPAuth = TRUE;
379 $mail->Username = $smtp_username;
380 $mail->Password = $smtppassword;
384 $mail->Mailer = 'sendmail';
386 $mail->Subject = from_html($mod_strings['LBL_TEST_EMAIL_SUBJECT']);
387 $mail->From = $fromaddress;
389 if ($fromname != '') {
390 $mail->FromName = html_entity_decode($fromname,ENT_QUOTES);
392 $mail->FromName = $current_user->name;
395 $mail->Sender = $mail->From;
396 $mail->AddAddress($toaddress);
397 $mail->Body = $mod_strings['LBL_TEST_EMAIL_BODY'];
403 $return['status'] = false;
404 $return['errorMessage'] = $app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo;
407 $return['status'] = true;
411 function decodeDuringSend($htmlData) {
412 $htmlData = str_replace("sugarLessThan", "<", $htmlData);
413 $htmlData = str_replace("sugarGreaterThan", ">", $htmlData);
418 * Returns true or false if this email is a draft.
420 * @param array $request
421 * @return bool True indicates this email is a draft.
423 function isDraftEmail($request)
425 return ( isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft') );
429 * Sends Email for Email 2.0
431 function email2Send($request) {
434 global $current_user;
435 global $sugar_config;
440 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
442 /**********************************************************************
448 if(!empty($this->id)) {
449 $orignialId = $this->id;
452 if(empty($this->id)) {
453 $this->id = create_guid();
454 $this->new_with_id = true;
457 /* satisfy basic HTML email requirements */
458 $this->name = $request['sendSubject'];
459 $this->description_html = '<html><body>'.$request['sendDescription'].'</body></html>';
461 /**********************************************************************
464 $mail = new SugarPHPMailer();
465 $mail = $this->setMailer($mail, '', $_REQUEST['fromAccount']);
466 if (empty($mail->Host) && !$this->isDraftEmail($request))
468 $this->status = 'send_error';
470 if ($mail->oe->type == 'system')
471 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_SYSTEM_OUTBOUND']);
473 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_PERSONAL_OUTBOUND']);
478 $subject = $this->name;
479 $mail->Subject = from_html($this->name);
481 // work-around legacy code in SugarPHPMailer
482 if($_REQUEST['setEditor'] == 1) {
483 $_REQUEST['description_html'] = $_REQUEST['sendDescription'];
484 $this->description_html = $_REQUEST['description_html'];
486 $this->description_html = '';
487 $this->description = $_REQUEST['sendDescription'];
491 if ( $this->isDraftEmail($request) )
493 if($this->type != 'draft' && $this->status != 'draft') {
494 $this->id = create_guid();
495 $this->new_with_id = true;
496 $this->date_entered = "";
498 $q1 = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$this->id}'";
499 $r1 = $this->db->query($q1);
502 if (isset($request['saveDraft'])) {
503 $this->type = 'draft';
504 $this->status = 'draft';
507 /* Apply Email Templates */
508 // do not parse email templates if the email is being saved as draft....
509 $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']);
510 $sea = new SugarEmailAddress();
511 $object_arr = array();
513 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
514 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) &&
515 ($_REQUEST['parent_type'] == 'Accounts' ||
516 $_REQUEST['parent_type'] == 'Contacts' ||
517 $_REQUEST['parent_type'] == 'Leads' ||
518 $_REQUEST['parent_type'] == 'Users' ||
519 $_REQUEST['parent_type'] == 'Prospects')) {
520 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
521 $className = $beanList[$_REQUEST['parent_type']];
522 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
523 if(!class_exists($className)) {
524 require_once($beanFiles[$className]);
526 $bean = new $className();
527 $bean->retrieve($_REQUEST['parent_id']);
528 $object_arr[$bean->module_dir] = $bean->id;
532 foreach($toAddresses as $addrMeta) {
533 $addr = $addrMeta['email'];
534 $beans = $sea->getBeansByEmailAddress($addr);
535 foreach($beans as $bean) {
536 if (!isset($object_arr[$bean->module_dir])) {
537 $object_arr[$bean->module_dir] = $bean->id;
542 /* template parsing */
543 if (empty($object_arr)) {
544 $object_arr= array('Contacts' => '123');
546 $object_arr['Users'] = $current_user->id;
547 $this->description_html = EmailTemplate::parse_template($this->description_html, $object_arr);
548 $this->name = EmailTemplate::parse_template($this->name, $object_arr);
549 $this->description = EmailTemplate::parse_template($this->description, $object_arr);
550 $this->description = html_entity_decode($this->description,ENT_COMPAT,'UTF-8');
551 if($this->type != 'draft' && $this->status != 'draft') {
552 $this->id = create_guid();
553 $this->date_entered = "";
554 $this->new_with_id = true;
556 $this->status = 'sent';
560 if(isset($_REQUEST['parent_type']) && empty($_REQUEST['parent_type']) &&
561 isset($_REQUEST['parent_id']) && empty($_REQUEST['parent_id']) ) {
562 $this->parent_id = "";
563 $this->parent_type = "";
567 $mail->Subject = $this->name;
568 $mail = $this->handleBody($mail);
569 $mail->Subject = $this->name;
570 $this->description_html = from_html($this->description_html);
571 $this->description_html = $this->decodeDuringSend($this->description_html);
572 $this->description = $this->decodeDuringSend($this->description);
575 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
577 if(empty($request['fromAccount'])) {
578 $defaults = $current_user->getPreferredEmail();
579 $mail->From = $defaults['email'];
580 $mail->FromName = $defaults['name'];
581 $replyToName = $mail->FromName;
582 //$replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
584 // passed -> user -> system default
585 $ie = new InboundEmail();
586 $ie->retrieve($request['fromAccount']);
587 $storedOptions = unserialize(base64_decode($ie->stored_options));
591 //$replyToAddress = "";
592 if (!empty($storedOptions)) {
593 $fromAddress = $storedOptions['from_addr'];
594 $fromName = from_html($storedOptions['from_name']);
595 $replyToAddress = (isset($storedOptions['reply_to_addr']) ? $storedOptions['reply_to_addr'] : "");
596 $replyToName = (isset($storedOptions['reply_to_name']) ? from_html($storedOptions['reply_to_name']) : "");
598 $defaults = $current_user->getPreferredEmail();
599 // Personal Account doesn't have reply To Name and Reply To Address. So add those columns on UI
600 // After adding remove below code
603 if ($ie->is_personal)
605 if (empty($replyToAddress))
607 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
609 if (empty($replyToName))
611 $replyToName = $defaults['name'];
613 //Personal accounts can have a reply_address, which should
614 //overwrite the users set default.
615 if( !empty($storedOptions['reply_to_addr']) )
616 $replyToAddress = $storedOptions['reply_to_addr'];
619 // end of code to remove
620 $mail->From = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
621 $mail->FromName = (!empty($fromName)) ? $fromName : $defaults['name'];
622 $replyToName = (!empty($replyToName)) ? $replyToName : $mail->FromName;
625 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
627 if (!empty($replyToAddress)) {
628 $mail->AddReplyTo($replyToAddress,$locale->translateCharsetMIME(trim( $replyToName), 'UTF-8', $OBCharset));
630 $mail->AddReplyTo($mail->From,$locale->translateCharsetMIME(trim( $mail->FromName), 'UTF-8', $OBCharset));
632 $emailAddressCollection = array(); // used in linking to beans below
634 foreach($this->email2ParseAddresses($request['sendTo']) as $addr_arr) {
635 if(empty($addr_arr['email'])) continue;
637 if(empty($addr_arr['display'])) {
638 $mail->AddAddress($addr_arr['email'], "");
640 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
642 $emailAddressCollection[] = $addr_arr['email'];
644 foreach($this->email2ParseAddresses($request['sendCc']) as $addr_arr) {
645 if(empty($addr_arr['email'])) continue;
647 if(empty($addr_arr['display'])) {
648 $mail->AddCC($addr_arr['email'], "");
650 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
652 $emailAddressCollection[] = $addr_arr['email'];
655 foreach($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) {
656 if(empty($addr_arr['email'])) continue;
658 if(empty($addr_arr['display'])) {
659 $mail->AddBCC($addr_arr['email'], "");
661 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
663 $emailAddressCollection[] = $addr_arr['email'];
667 /* parse remove attachments array */
668 $removeAttachments = array();
669 if(!empty($request['templateAttachmentsRemove'])) {
670 $exRemove = explode("::", $request['templateAttachmentsRemove']);
672 foreach($exRemove as $file) {
673 $removeAttachments = substr($file, 0, 36);
677 /* handle attachments */
678 if(!empty($request['attachments'])) {
679 $exAttachments = explode("::", $request['attachments']);
681 foreach($exAttachments as $file) {
682 $file = trim(from_html($file));
683 $file = str_replace("\\", "", $file);
685 //$fileLocation = $this->et->userCacheDir."/{$file}";
686 $fileGUID = substr($file, 0, 36);
687 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
688 $filename = substr($file, 36, strlen($file)); // strip GUID for PHPMailer class to name outbound file
690 $mail->AddAttachment($fileLocation,$filename, 'base64', $this->email2GetMime($fileLocation));
691 //$mail->AddAttachment($fileLocation, $filename, 'base64');
693 // only save attachments if we're archiving or drafting
694 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
696 $note->id = create_guid();
697 $note->new_with_id = true; // duplicating the note with files
698 $note->parent_id = $this->id;
699 $note->parent_type = $this->module_dir;
700 $note->name = $filename;
701 $note->filename = $filename;
702 $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
703 $note->file_mime_type = $this->email2GetMime($fileLocation);
705 if(!copy($fileLocation, $noteFile)) {
706 $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to cache/upload [ {$fileLocation} ]");
715 /* handle sugar documents */
716 if(!empty($request['documents'])) {
717 $exDocs = explode("::", $request['documents']);
722 foreach($exDocs as $docId) {
723 $docId = trim($docId);
725 $doc = new Document();
726 $docRev = new DocumentRevision();
727 $doc->retrieve($docId);
728 $docRev->retrieve($doc->document_revision_id);
730 $filename = $docRev->filename;
731 $fileLocation = "{$sugar_config['upload_dir']}{$docRev->id}";
732 $mime_type = $docRev->file_mime_type;
733 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
735 // only save attachments if we're archiving or drafting
736 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
738 $note->id = create_guid();
739 $note->new_with_id = true; // duplicating the note with files
740 $note->parent_id = $this->id;
741 $note->parent_type = $this->module_dir;
742 $note->name = $filename;
743 $note->filename = $filename;
744 $note->file_mime_type = $mime_type;
745 $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
747 if(!copy($fileLocation, $noteFile)) {
748 $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
757 /* handle template attachments */
758 if(!empty($request['templateAttachments'])) {
760 $exNotes = explode("::", $request['templateAttachments']);
761 foreach($exNotes as $noteId) {
762 $noteId = trim($noteId);
763 if(!empty($noteId)) {
765 $note->retrieve($noteId);
766 if (!empty($note->id)) {
767 $filename = $note->filename;
768 $fileLocation = "{$sugar_config['upload_dir']}{$note->id}";
769 $mime_type = $note->file_mime_type;
770 if (!$note->embed_flag) {
771 $mail->AddAttachment($fileLocation,$filename, 'base64', $mime_type);
772 // only save attachments if we're archiving or drafting
773 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
775 if ($note->parent_id != $this->id)
776 $this->saveTempNoteAttachments($filename,$fileLocation, $mime_type);
781 //$fileLocation = $this->et->userCacheDir."/{$file}";
782 $fileGUID = substr($noteId, 0, 36);
783 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
784 //$fileLocation = $this->et->userCacheDir."/{$noteId}";
785 $filename = substr($noteId, 36, strlen($noteId)); // strip GUID for PHPMailer class to name outbound file
787 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $this->email2GetMime($fileLocation));
789 //If we are saving an email we were going to forward we need to save the attachments as well.
790 if( (($this->type == 'draft') && !empty($this->id))
791 || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1))
793 $mimeType = $this->email2GetMime($fileLocation);
794 $this->saveTempNoteAttachments($filename,$fileLocation, $mimeType);
803 /**********************************************************************
806 /* save email to sugar? */
809 if($this->type == 'draft' && !isset($request['saveDraft'])) {
810 // sending a draft email
812 $this->status = 'sent';
814 } elseif(isset($request['saveDraft'])) {
815 $this->type = 'draft';
816 $this->status = 'draft';
820 /**********************************************************************
821 * SEND EMAIL (finally!)
824 if ($this->type != 'draft') {
825 $mail->prepForOutbound();
826 $mail->Body = $this->decodeDuringSend($mail->Body);
827 $mail->AltBody = $this->decodeDuringSend($mail->AltBody);
828 if (!$mail->Send()) {
829 $this->status = 'send_error';
831 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo);
836 if ((!(empty($orignialId) || isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft'))) &&
837 (($_REQUEST['composeType'] == 'reply') || ($_REQUEST['composeType'] == 'replyAll') || ($_REQUEST['composeType'] == 'replyCase')) && ($orignialId != $this->id)) {
838 $originalEmail = new Email();
839 $originalEmail->retrieve($orignialId);
840 $originalEmail->reply_to_status = 1;
841 $originalEmail->save();
842 $this->reply_to_status = 0;
845 if ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase') {
846 if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) {
847 $emailFromIe = new InboundEmail();
848 $emailFromIe->retrieve($_REQUEST['ieId']);
849 $emailFromIe->mailbox = $_REQUEST['mbox'];
850 if (isset($emailFromIe->id) && $emailFromIe->is_personal) {
851 if ($emailFromIe->isPop3Protocol()) {
852 $emailFromIe->mark_answered($this->uid, 'pop3');
854 elseif ($emailFromIe->connectMailserver() == 'true') {
855 $emailFromIe->markEmails($this->uid, 'answered');
856 $emailFromIe->mark_answered($this->uid);
864 $this->type == 'draft' ||
865 (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
867 // saving a draft OR saving a sent email
868 $decodedFromName = mb_decode_mimeheader($mail->FromName);
869 $this->from_addr = "{$decodedFromName} <{$mail->From}>";
870 $this->from_addr_name = $this->from_addr;
871 $this->to_addrs = $_REQUEST['sendTo'];
872 $this->to_addrs_names = $_REQUEST['sendTo'];
873 $this->cc_addrs = $_REQUEST['sendCc'];
874 $this->cc_addrs_names = $_REQUEST['sendCc'];
875 $this->bcc_addrs = $_REQUEST['sendBcc'];
876 $this->bcc_addrs_names = $_REQUEST['sendBcc'];
877 $this->assigned_user_id = $current_user->id;
879 $this->date_sent = $timedate->now();
880 ///////////////////////////////////////////////////////////////////
881 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
883 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
884 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) ) {
885 $this->parent_id = $_REQUEST['parent_id'];
886 $this->parent_type = $_REQUEST['parent_type'];
887 $q = "SELECT count(*) c FROM emails_beans WHERE email_id = '{$this->id}' AND bean_id = '{$_REQUEST['parent_id']}' AND bean_module = '{$_REQUEST['parent_type']}'";
888 $r = $this->db->query($q);
889 $a = $this->db->fetchByAssoc($r);
891 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
892 $className = $beanList[$_REQUEST['parent_type']];
893 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
894 if(!class_exists($className)) {
895 require_once($beanFiles[$className]);
897 $bean = new $className();
898 $bean->retrieve($_REQUEST['parent_id']);
899 if($bean->load_relationship('emails')) {
900 $bean->emails->add($this->id);
910 if(!class_exists('aCase')) {
915 if($caseId = InboundEmail::getCaseIdFromCaseNumber($mail->Subject, $c)) {
916 $c->retrieve($caseId);
917 $c->load_relationship('emails');
918 $c->emails->add($this->id);
919 $this->parent_type = "Cases";
920 $this->parent_id = $caseId;
926 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
927 ///////////////////////////////////////////////////////////////////
931 if(!empty($request['fromAccount'])) {
932 if (isset($ie->id) && !$ie->isPop3Protocol()) {
933 $sentFolder = $ie->get_stored_options("sentFolder");
934 if (!empty($sentFolder)) {
935 $data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n";
936 $ie->mailbox = $sentFolder;
937 if ($ie->connectMailserver() == 'true') {
938 $connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox);
939 $returnData = imap_append($ie->conn,$connectString, $data, "\\Seen");
941 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}");
944 $GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}");
947 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty");
955 * Generates a comma sperated name and addresses to be used in compose email screen for contacts or leads
958 * @param $module string module name
959 * @param $idsArray array of record ids to get the email address for
960 * @return string comma delimited list of email addresses
962 public function getNamePlusEmailAddressesForCompose($module, $idsArray)
966 $table = SugarModule::get($module)->loadBean()->table_name;
967 $returndata = array();
969 foreach($idsArray as $id) {
970 if ($idsString != "") {
971 $idsString = $idsString . ",";
973 $idsString = $idsString . "'" . $id . "'";
975 $where = "({$table}.deleted = 0 AND {$table}.id in ({$idsString}))";
977 if ($module == 'Users' || $module == 'Employees') {
978 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.title";
980 elseif (SugarModule::get($module)->moduleImplements('Person')) {
981 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.salutation, {$table}.title";
984 $selectColumn = "{$table}.name";
986 $query = "SELECT {$table}.id, {$selectColumn}, eabr.primary_address, ea.email_address";
987 $query .= " FROM {$table} ";
988 $query .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
989 $query .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
990 $query .= " WHERE ({$where}) ORDER BY eabr.primary_address DESC";
991 $r = $this->db->query($query);
993 while($a = $this->db->fetchByAssoc($r)) {
994 if (!isset($returndata[$a['id']])) {
995 if ($module == 'Users' || $module == 'Employees') {
996 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], '', $a['title']));
997 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
999 elseif (SugarModule::get($module)->moduleImplements('Person')) {
1000 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], $a['salutation'], $a['title']));
1001 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
1004 $returndata[$a['id']] = from_html($a['name']) . " <".from_html($a['email_address']).">";
1009 return join(",", array_values($returndata));
1015 ///////////////////////////////////////////////////////////////////////////
1017 function save($check_notify = false) {
1018 if($this->isDuplicate) {
1019 $GLOBALS['log']->debug("EMAIL - tried to save a duplicate Email record");
1022 if(empty($this->id)) {
1023 $this->id = create_guid();
1024 $this->new_with_id = true;
1026 $this->from_addr_name = $this->cleanEmails($this->from_addr_name);
1027 $this->to_addrs_names = $this->cleanEmails($this->to_addrs_names);
1028 $this->cc_addrs_names = $this->cleanEmails($this->cc_addrs_names);
1029 $this->bcc_addrs_names = $this->cleanEmails($this->bcc_addrs_names);
1030 $this->reply_to_addr = $this->cleanEmails($this->reply_to_addr);
1031 $this->description = to_html($this->safeText(from_html($this->description)));
1032 $this->description_html = $this->safeText($this->description_html);
1033 $this->saveEmailText();
1034 $this->saveEmailAddresses();
1036 $GLOBALS['log']->debug('-------------------------------> Email called save()');
1038 // handle legacy concatenation of date and time fields
1039 if(empty($this->date_sent)) $this->date_sent = $this->date_start." ".$this->time_start;
1041 parent::save($check_notify);
1043 if(!empty($this->parent_type) && !empty($this->parent_id)) {
1044 if(!empty($this->fetched_row) && !empty($this->fetched_row['parent_id']) && !empty($this->fetched_row['parent_type'])) {
1045 if($this->fetched_row['parent_id'] != $this->parent_id || $this->fetched_row['parent_type'] != $this->parent_type) {
1046 $mod = strtolower($this->fetched_row['parent_type']);
1047 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1048 if($this->load_relationship($rel) ) {
1049 $this->$rel->delete($this->id, $this->fetched_row['parent_id']);
1053 $mod = strtolower($this->parent_type);
1054 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1055 if($this->load_relationship($rel) ) {
1056 $this->$rel->add($this->parent_id);
1060 $GLOBALS['log']->debug('-------------------------------> Email save() done');
1064 * Helper function to save temporary attachments assocaited to an email as note.
1066 * @param string $filename
1067 * @param string $fileLocation
1068 * @param string $mimeType
1070 function saveTempNoteAttachments($filename,$fileLocation, $mimeType)
1072 global $sugar_config;
1074 $tmpNote = new Note();
1075 $tmpNote->id = create_guid();
1076 $tmpNote->new_with_id = true;
1077 $tmpNote->parent_id = $this->id;
1078 $tmpNote->parent_type = $this->module_dir;
1079 $tmpNote->name = $filename;
1080 $tmpNote->filename = $filename;
1081 $tmpNote->file_mime_type = $mimeType;
1082 $noteFile = "{$sugar_config['upload_dir']}{$tmpNote->id}";
1083 if(!copy($fileLocation, $noteFile))
1084 $GLOBALS['log']->fatal("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
1088 * Handles normalization of Email Addressess
1090 function saveEmailAddresses() {
1091 // from, single address
1092 $fromId = $this->emailAddress->getEmailGUID(from_html($this->from_addr));
1093 if(!empty($fromId)){
1094 $this->linkEmailToAddress($fromId, 'from');
1098 $replace = array(",",";");
1099 $toaddrs = str_replace($replace, "::", from_html($this->to_addrs));
1100 $exToAddrs = explode("::", $toaddrs);
1102 if(!empty($exToAddrs)) {
1103 foreach($exToAddrs as $toaddr) {
1104 $toaddr = trim($toaddr);
1105 if(!empty($toaddr)) {
1106 $toId = $this->emailAddress->getEmailGUID($toaddr);
1107 $this->linkEmailToAddress($toId, 'to');
1113 $ccAddrs = str_replace($replace, "::", from_html($this->cc_addrs));
1114 $exccAddrs = explode("::", $ccAddrs);
1116 if(!empty($exccAddrs)) {
1117 foreach($exccAddrs as $ccAddr) {
1118 $ccAddr = trim($ccAddr);
1119 if(!empty($ccAddr)) {
1120 $ccId = $this->emailAddress->getEmailGUID($ccAddr);
1121 $this->linkEmailToAddress($ccId, 'cc');
1127 $bccAddrs = str_replace($replace, "::", from_html($this->bcc_addrs));
1128 $exbccAddrs = explode("::", $bccAddrs);
1129 if(!empty($exbccAddrs)) {
1130 foreach($exbccAddrs as $bccAddr) {
1131 $bccAddr = trim($bccAddr);
1132 if(!empty($bccAddr)) {
1133 $bccId = $this->emailAddress->getEmailGUID($bccAddr);
1134 $this->linkEmailToAddress($bccId, 'bcc');
1140 function linkEmailToAddress($id, $type) {
1141 // TODO: make this update?
1142 $q1 = "SELECT * FROM emails_email_addr_rel WHERE email_id = '{$this->id}' AND email_address_id = '{$id}' AND address_type = '{$type}' AND deleted = 0";
1143 $r1 = $this->db->query($q1);
1144 $a1 = $this->db->fetchByAssoc($r1);
1146 if(!empty($a1) && !empty($a1['id'])) {
1149 $guid = create_guid();
1150 $q2 = "INSERT INTO emails_email_addr_rel VALUES('{$guid}', '{$this->id}', '{$type}', '{$id}', 0)";
1151 $r2 = $this->db->query($q2);
1157 function cleanEmails($emails)
1159 $emails = str_replace(array(",",";"), "::", from_html($emails));
1160 $addrs = explode("::", $emails);
1162 foreach($addrs as $addr) {
1163 $parts = $this->emailAddress->splitEmailAddress($addr);
1164 if(empty($parts["email"])) {
1167 if(!empty($parts["name"])) {
1168 $res[] = "{$parts["name"]} <{$parts["email"]}>";
1170 $res[] .= $parts["email"];
1173 return join(", ", $res);
1176 function saveEmailText() {
1177 $isOracle = ($this->db->dbType == "oci8") ? true : false;
1180 $description = $this->db->quote(trim($this->description));
1181 $description_html = $this->db->quoteForEmail(trim($this->description_html));
1182 $raw_source = $this->db->quote(trim($this->raw_source));
1183 $fromAddressName = $this->db->helper->escape_quote($this->from_addr_name);
1184 $toAddressName = $this->db->helper->escape_quote($this->to_addrs_names);
1185 $ccAddressName = $this->db->helper->escape_quote($this->cc_addrs_names);
1186 $bccAddressName = $this->db->helper->escape_quote($this->bcc_addrs_names);
1187 $replyToAddrName = $this->db->helper->escape_quote($this->reply_to_addr);
1189 if(!$this->new_with_id) {
1190 $q = "UPDATE emails_text SET from_addr = '{$fromAddressName}', to_addrs = '{$toAddressName}', cc_addrs = '{$ccAddressName}', bcc_addrs = '{$bccAddressName}', reply_to_addr = '{$replyToAddrName}', description = '{$description}', description_html = '{$description_html}', raw_source = '{$raw_source}' WHERE email_id = '{$this->id}'";
1192 $q = "INSERT INTO emails_text (email_id, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to_addr, description, description_html, raw_source, deleted) VALUES('{$this->id}', '{$fromAddressName}', '{$toAddressName}', '{$ccAddressName}', '{$bccAddressName}', '{$replyToAddrName}', '{$description}', '{$description_html}', '{$raw_source}', 0)";
1194 $this->db->query($q);
1200 ///////////////////////////////////////////////////////////////////////////
1202 function retrieve($id, $encoded=true, $deleted=true) {
1203 // cn: bug 11915, return SugarBean's retrieve() call bean instead of $this
1204 $ret = parent::retrieve($id, $encoded, $deleted);
1207 $ret->retrieveEmailText();
1208 $ret->retrieveEmailAddresses();
1209 $ret->raw_source = to_html($ret->safeText(from_html($ret->raw_source)));
1210 $ret->description = to_html($ret->safeText(from_html($ret->description)));
1211 $ret->description_html = $ret->safeText($ret->description_html);
1213 $ret->date_start = '';
1214 $ret->time_start = '';
1215 $dateSent = explode(' ', $ret->date_sent);
1216 if (!empty($dateSent)) {
1217 $ret->date_start = $dateSent[0];
1218 if ( isset($dateSent[1]) )
1219 $ret->time_start = $dateSent[1];
1222 foreach($ret as $k => $v) {
1231 * Retrieves email addresses from GUIDs
1233 function retrieveEmailAddresses() {
1236 $q = "SELECT email_address, address_type
1237 FROM emails_email_addr_rel eam
1238 JOIN email_addresses ea ON ea.id = eam.email_address_id
1239 WHERE eam.email_id = '{$this->id}' AND eam.deleted=0";
1240 $r = $this->db->query($q);
1242 while($a = $this->db->fetchByAssoc($r)) {
1243 if(!isset($return[$a['address_type']])) {
1244 $return[$a['address_type']] = array();
1246 $return[$a['address_type']][] = $a['email_address'];
1249 if(count($return) > 0) {
1250 if(isset($return['from'])) {
1251 $this->from_addr = implode(", ", $return['from']);
1253 if(isset($return['to'])) {
1254 $this->to_addrs = implode(", ", $return['to']);
1256 if(isset($return['cc'])) {
1257 $this->cc_addrs = implode(", ", $return['cc']);
1259 if(isset($return['bcc'])) {
1260 $this->bcc_addrs = implode(", ", $return['bcc']);
1266 * Handles longtext fields
1268 function retrieveEmailText() {
1269 $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}'";
1270 $r = $this->db->query($q);
1271 $a = $this->db->fetchByAssoc($r, -1, false);
1273 $this->description = $a['description'];
1274 $this->description_html = $a['description_html'];
1275 $this->raw_source = $a['raw_source'];
1276 $this->from_addr_name = $a['from_addr'];
1277 $this->reply_to_addr = $a['reply_to_addr'];
1278 $this->to_addrs_names = $a['to_addrs'];
1279 $this->cc_addrs_names = $a['cc_addrs'];
1280 $this->bcc_addrs_names = $a['bcc_addrs'];
1283 function delete($id='') {
1287 $q = "UPDATE emails SET deleted = 1 WHERE id = '{$id}'";
1288 $qt = "UPDATE emails_text SET deleted = 1 WHERE email_id = '{$id}'";
1289 $r = $this->db->query($q);
1290 $rt = $this->db->query($qt);
1294 * creates the standard "Forward" info at the top of the forwarded message
1297 function getForwardHeader() {
1298 global $mod_strings;
1299 global $current_user;
1301 //$from = str_replace(array(">","<"), array(")","("), $this->from_name);
1302 $from = to_html($this->from_name);
1303 $subject = to_html($this->name);
1304 $ret = "<br /><br />";
1305 $ret .= $this->replyDelimiter."{$mod_strings['LBL_FROM']} {$from}<br />";
1306 $ret .= $this->replyDelimiter."{$mod_strings['LBL_DATE_SENT']} {$this->date_sent}<br />";
1307 $ret .= $this->replyDelimiter."{$mod_strings['LBL_TO']} {$this->to_addrs}<br />";
1308 $ret .= $this->replyDelimiter."{$mod_strings['LBL_CC']} {$this->cc_addrs}<br />";
1309 $ret .= $this->replyDelimiter."{$mod_strings['LBL_SUBJECT']} {$subject}<br />";
1310 $ret .= $this->replyDelimiter."<br />";
1313 //return from_html($ret);
1317 * retrieves Notes that belong to this Email and stuffs them into the "attachments" attribute
1319 function getNotes($id, $duplicate=false) {
1320 if(!class_exists('Note')) {
1324 $exRemoved = array();
1325 if(isset($_REQUEST['removeAttachment'])) {
1326 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1329 $noteArray = array();
1330 $q = "SELECT id FROM notes WHERE parent_id = '".$id."'";
1331 $r = $this->db->query($q);
1333 while($a = $this->db->fetchByAssoc($r)) {
1334 if(!in_array($a['id'], $exRemoved)) {
1336 $note->retrieve($a['id']);
1338 // duplicate actual file when creating forwards
1340 if(!class_exists('UploadFile')) {
1341 require_once('include/upload_file.php');
1343 // save a brand new Note
1344 $noteDupe->id = create_guid();
1345 $noteDupe->new_with_id = true;
1346 $noteDupe->parent_id = $this->id;
1347 $noteDupe->parent_type = $this->module_dir;
1349 $noteFile = new UploadFile('none');
1350 $noteFile->duplicate_file($a['id'], $note->id, $note->filename);
1354 // add Note to attachments array
1355 $this->attachments[] = $note;
1361 * creates the standard "Reply" info at the top of the forwarded message
1364 function getReplyHeader() {
1365 global $mod_strings;
1366 global $current_user;
1368 $from = str_replace(array(">","<", ">","<"), array(")","(",")","("), $this->from_name);
1369 $ret = "<br>{$mod_strings['LBL_REPLY_HEADER_1']} {$this->date_start}, {$this->time_start}, {$from} {$mod_strings['LBL_REPLY_HEADER_2']}";
1371 return from_html($ret);
1375 * Quotes plain-text email text
1376 * @param string $text
1379 function quotePlainTextEmail($text) {
1383 $desc = nl2br(trim($text));
1384 $exDesc = explode('<br />', $desc);
1386 foreach($exDesc as $k => $line) {
1387 $quoted .= '> '.trim($line)."\r";
1394 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1395 * @param string $text HTML text to quote
1398 function quoteHtmlEmail($text) {
1399 $text = trim(from_html($text));
1404 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1410 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1411 * @param string $text HTML text to quote
1414 function quoteHtmlEmailForNewEmailUI($text) {
1415 $text = trim($text);
1420 $text = str_replace("\n", "\n<BR/>", $text);
1421 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1428 ///////////////////////////////////////////////////////////////////////////
1431 * Safes description text (both HTML and Plain Text) for display
1432 * @param string str The text to safe
1433 * @return string Safed text
1435 function safeText($str)
1437 if(empty($str)) return $str;
1439 if(!strchr($str, "<")) {
1443 $this->safe->clear();
1444 $ret = $this->safe->parse($str);
1446 // Julian's XSS cleaner
1447 $potentials = clean_xss($ret, false);
1449 if(is_array($potentials) && !empty($potentials)) {
1450 //_ppl($potentials);
1451 foreach($potentials as $bad) {
1452 $ret = str_replace($bad, "", $ret);
1456 // clean <HTML> and <BODY> tags
1457 $html = '#<\\\\\?HTML[\w =\'\"\&]*>#sim';
1458 $body = '#<\\\\\?BODY[\w =\'\"\&]*>#sim';
1460 $ret = preg_replace($html, "", $ret);
1461 $ret = preg_replace($body, "", $ret);
1467 * Ensures that the user is able to send outbound emails
1469 function check_email_settings() {
1470 global $current_user;
1472 $mail_fromaddress = $current_user->emailAddress->getPrimaryAddress($current_user);
1473 $replyToName = $current_user->getPreference('mail_fromname');
1474 $mail_fromname = (!empty($replyToName)) ? $current_user->getPreference('mail_fromname') : $current_user->full_name;
1476 if(empty($mail_fromaddress)) {
1479 if(empty($mail_fromname)) {
1483 $send_type = $current_user->getPreference('mail_sendtype') ;
1484 if (!empty($send_type) && $send_type == "SMTP") {
1485 $mail_smtpserver = $current_user->getPreference('mail_smtpserver');
1486 $mail_smtpport = $current_user->getPreference('mail_smtpport');
1487 $mail_smtpauth_req = $current_user->getPreference('mail_smtpauth_req');
1488 $mail_smtpuser = $current_user->getPreference('mail_smtpuser');
1489 $mail_smtppass = $current_user->getPreference('mail_smtppass');
1490 if (empty($mail_smtpserver) ||
1491 empty($mail_smtpport) ||
1492 (!empty($mail_smtpauth_req) && ( empty($mail_smtpuser) || empty($mail_smtppass)))
1501 * outputs JS to set fields in the MassUpdate form in the "My Inbox" view
1503 function js_set_archived() {
1504 global $mod_strings;
1506 <script type="text/javascript" language="JavaScript"><!-- Begin
1507 function setArchived() {
1508 var form = document.getElementById("MassUpdate");
1509 var status = document.getElementById("mass_status");
1512 for(var i=0; i < form.elements.length; i++) {
1513 if(form.elements[i].name == "mass[]") {
1514 if(form.elements[i].checked == true) {
1521 var user = document.getElementById("mass_assigned_user_name");
1522 var team = document.getElementById("team");
1525 for(var j=0; j<status.length; j++) {
1526 if(status.options[j].value == "archived") {
1527 status.options[j].selected = true;
1528 status.selectedIndex = j; // for IE
1534 alert("'.$mod_strings['ERR_ARCHIVE_EMAIL'].'");
1538 // End --></script>';
1543 * replaces the javascript in utils.php - more specialized
1545 function u_get_clear_form_js($type='', $group='', $assigned_user_id='') {
1548 $uAssigned_user_id = '';
1550 if(!empty($type)) { $uType = '&type='.$type; }
1551 if(!empty($group)) { $uGroup = '&group='.$group; }
1552 if(!empty($assigned_user_id)) { $uAssigned_user_id = '&assigned_user_id='.$assigned_user_id; }
1555 <script type="text/javascript" language="JavaScript"><!-- Begin
1556 function clear_form(form) {
1557 var newLoc = "index.php?action=" + form.action.value + "&module=" + form.module.value + "&query=true&clear_query=true'.$uType.$uGroup.$uAssigned_user_id.'";
1558 if(typeof(form.advanced) != "undefined"){
1559 newLoc += "&advanced=" + form.advanced.value;
1561 document.location.href= newLoc;
1563 // End --></script>';
1567 function pickOneButton() {
1569 global $mod_strings;
1570 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_GRAB_TITLE'].'"
1571 accessKey="'.$mod_strings['LBL_BUTTON_GRAB_KEY'].'"
1573 type="button" name="button"
1574 onClick="window.location=\'index.php?module=Emails&action=Grab\';"
1575 style="margin-bottom:2px"
1576 value=" '.$mod_strings['LBL_BUTTON_GRAB'].' "></div>';
1581 * Determines what Editor (HTML or Plain-text) the current_user uses;
1582 * @return string Editor type
1584 function getUserEditorPreference() {
1585 global $sugar_config;
1586 global $current_user;
1590 if(!isset($sugar_config['email_default_editor'])) {
1591 $sugar_config = $current_user->setDefaultsInConfig();
1594 $userEditor = $current_user->getPreference('email_editor_option');
1595 $systemEditor = $sugar_config['email_default_editor'];
1597 if($userEditor != '') {
1598 $editor = $userEditor;
1600 $editor = $systemEditor;
1607 * takes the mess we pass from EditView and tries to create some kind of order
1608 * @param array addrs
1609 * @param array addrs_ids (from contacts)
1610 * @param array addrs_names (from contacts);
1611 * @param array addrs_emails (from contacts);
1612 * @return array Parsed assoc array to feed to PHPMailer
1614 function parse_addrs($addrs, $addrs_ids, $addrs_names, $addrs_emails) {
1615 // cn: bug 9406 - enable commas to separate email addresses
1616 $addrs = str_replace(",", ";", $addrs);
1618 $ltgt = array('<','>');
1619 $gtlt = array('<','>');
1622 $addrs = str_replace($ltgt, '', $addrs);
1623 $addrs_arr = explode(";",$addrs);
1624 $addrs_arr = $this->remove_empty_fields($addrs_arr);
1625 $addrs_ids_arr = explode(";",$addrs_ids);
1626 $addrs_ids_arr = $this->remove_empty_fields($addrs_ids_arr);
1627 $addrs_emails_arr = explode(";",$addrs_emails);
1628 $addrs_emails_arr = $this->remove_empty_fields($addrs_emails_arr);
1629 $addrs_names_arr = explode(";",$addrs_names);
1630 $addrs_names_arr = $this->remove_empty_fields($addrs_names_arr);
1632 ///////////////////////////////////////////////////////////////////////
1633 //// HANDLE EMAILS HAND-WRITTEN
1634 $contactRecipients = array();
1635 $knownEmails = array();
1637 foreach($addrs_arr as $i => $v) {
1639 continue; // skip any "blanks" - will always have 1
1641 $recipient = array();
1643 //// get the email to see if we're dealing with a dupe
1644 //// what crappy coding
1645 preg_match("/[A-Z0-9._%-\']+@[A-Z0-9.-]+\.[A-Z]{2,}/i",$v, $match);
1648 if(!empty($match[0]) && !in_array(trim($match[0]), $knownEmails)) {
1649 $knownEmails[] = $match[0];
1650 $recipient['email'] = $match[0];
1652 //// handle the Display name
1653 $display = trim(str_replace($match[0], '', $v));
1655 //// only trigger a "displayName" <email@address> when necessary
1656 if(isset($addrs_names_arr[$i])){
1657 $recipient['display'] = $addrs_names_arr[$i];
1659 else if(!empty($display)) {
1660 $recipient['display'] = $display;
1662 if(isset($addrs_ids_arr[$i]) && $addrs_emails_arr[$i] == $match[0]){
1663 $recipient['contact_id'] = $addrs_ids_arr[$i];
1665 $return[] = $recipient;
1672 function remove_empty_fields(&$arr) {
1675 foreach($arr as $field) {
1676 $field = trim($field);
1680 array_push($newarr,$field);
1686 * handles attachments of various kinds when sending email
1688 function handleAttachments() {
1693 global $mod_strings;
1695 ///////////////////////////////////////////////////////////////////////////
1696 //// ATTACHMENTS FROM DRAFTS
1697 if(($this->type == 'out' || $this->type == 'draft') && $this->status == 'draft' && isset($_REQUEST['record'])) {
1698 $this->getNotes($_REQUEST['record']); // cn: get notes from OLD email for use in new email
1700 //// END ATTACHMENTS FROM DRAFTS
1701 ///////////////////////////////////////////////////////////////////////////
1703 ///////////////////////////////////////////////////////////////////////////
1704 //// ATTACHMENTS FROM FORWARDS
1705 // Bug 8034 Jenny - Need the check for type 'draft' here to handle cases where we want to save
1706 // forwarded messages as drafts. We still need to save the original message's attachments.
1707 if(($this->type == 'out' || $this->type == 'draft') &&
1708 isset($_REQUEST['origType']) && $_REQUEST['origType'] == 'forward' &&
1709 isset($_REQUEST['return_id']) && !empty($_REQUEST['return_id'])
1711 $this->getNotes($_REQUEST['return_id'], true);
1714 // cn: bug 8034 - attachments from forward/replies lost when saving in draft
1715 if(isset($_REQUEST['prior_attachments']) && !empty($_REQUEST['prior_attachments']) && $this->new_with_id == true) {
1716 $exIds = explode(",", $_REQUEST['prior_attachments']);
1717 if(!isset($_REQUEST['template_attachment'])) {
1718 $_REQUEST['template_attachment'] = array();
1720 $_REQUEST['template_attachment'] = array_merge($_REQUEST['template_attachment'], $exIds);
1722 //// END ATTACHMENTS FROM FORWARDS
1723 ///////////////////////////////////////////////////////////////////////////
1725 ///////////////////////////////////////////////////////////////////////////
1726 //// ATTACHMENTS FROM TEMPLATES
1727 // to preserve individual email integrity, we must dupe Notes and associated files
1728 // for each outbound email - good for integrity, bad for filespace
1729 if(isset($_REQUEST['template_attachment']) && !empty($_REQUEST['template_attachment'])) {
1730 $removeArr = array();
1731 $noteArray = array();
1733 if(isset($_REQUEST['temp_remove_attachment']) && !empty($_REQUEST['temp_remove_attachment'])) {
1734 $removeArr = $_REQUEST['temp_remove_attachment'];
1738 foreach($_REQUEST['template_attachment'] as $noteId) {
1739 if(in_array($noteId, $removeArr)) {
1742 $noteTemplate = new Note();
1743 $noteTemplate->retrieve($noteId);
1744 $noteTemplate->id = create_guid();
1745 $noteTemplate->new_with_id = true; // duplicating the note with files
1746 $noteTemplate->parent_id = $this->id;
1747 $noteTemplate->parent_type = $this->module_dir;
1748 $noteTemplate->date_entered = '';
1749 $noteTemplate->save();
1751 $noteFile = new UploadFile('none');
1752 $noteFile->duplicate_file($noteId, $noteTemplate->id, $noteTemplate->filename);
1753 $noteArray[] = $noteTemplate;
1755 $this->attachments = array_merge($this->attachments, $noteArray);
1757 //// END ATTACHMENTS FROM TEMPLATES
1758 ///////////////////////////////////////////////////////////////////////////
1760 ///////////////////////////////////////////////////////////////////////////
1761 //// ADDING NEW ATTACHMENTS
1762 $max_files_upload = 10;
1763 // Jenny - Bug 8211 Since attachments for drafts have already been processed,
1764 // we don't need to re-process them.
1765 if($this->status != "draft") {
1766 $notes_list = array();
1767 if(!empty($this->id) && !$this->new_with_id) {
1769 $where = "notes.parent_id='{$this->id}'";
1770 $notes_list = $note->get_full_list("", $where, true);
1772 $this->attachments = array_merge($this->attachments, $notes_list);
1774 // cn: Bug 5995 - rudimentary error checking
1775 $filesError = array(
1776 0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
1777 1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
1778 2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
1779 3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
1780 4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
1781 5 => 'UNKNOWN ERROR',
1782 6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
1783 7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
1786 for($i = 0; $i < $max_files_upload; $i++) {
1787 // cn: Bug 5995 - rudimentary error checking
1788 if (!isset($_FILES["email_attachment{$i}"])) {
1789 $GLOBALS['log']->debug("Email Attachment {$i} does not exist.");
1792 if($_FILES['email_attachment'.$i]['error'] != 0 && $_FILES['email_attachment'.$i]['error'] != 4) {
1793 $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment'.$i]['error']]);
1798 $note->parent_id = $this->id;
1799 $note->parent_type = $this->module_dir;
1800 $upload_file = new UploadFile('email_attachment'.$i);
1802 if(empty($upload_file)) {
1806 if(isset($_FILES['email_attachment'.$i]) && $upload_file->confirm_upload()) {
1807 $note->filename = $upload_file->get_stored_file_name();
1808 $note->file = $upload_file;
1809 $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$note->file->original_file_name;
1811 $this->attachments[] = $note;
1815 $this->saved_attachments = array();
1816 foreach($this->attachments as $note) {
1817 if(!empty($note->id)) {
1818 array_push($this->saved_attachments, $note);
1821 $note->parent_id = $this->id;
1822 $note->parent_type = 'Emails';
1823 $note->file_mime_type = $note->file->mime_type;
1824 $note_id = $note->save();
1826 $this->saved_attachments[] = $note;
1828 $note->id = $note_id;
1829 $note->file->final_move($note->id);
1831 //// END NEW ATTACHMENTS
1832 ///////////////////////////////////////////////////////////////////////////
1834 ///////////////////////////////////////////////////////////////////////////
1835 //// ATTACHMENTS FROM DOCUMENTS
1836 for($i=0; $i<10; $i++) {
1837 if(isset($_REQUEST['documentId'.$i]) && !empty($_REQUEST['documentId'.$i])) {
1838 $doc = new Document();
1839 $docRev = new DocumentRevision();
1840 $docNote = new Note();
1841 $noteFile = new UploadFile('none');
1843 $doc->retrieve($_REQUEST['documentId'.$i]);
1844 $docRev->retrieve($doc->document_revision_id);
1846 $this->saved_attachments[] = $docRev;
1848 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
1849 $docNote->name = $docRev->getDocumentRevisionNameForDisplay();
1850 $docNote->filename = $docRev->filename;
1851 $docNote->description = $doc->description;
1852 $docNote->parent_id = $this->id;
1853 $docNote->parent_type = 'Emails';
1854 $docNote->file_mime_type = $docRev->file_mime_type;
1855 $docId = $docNote = $docNote->save();
1857 $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
1861 //// END ATTACHMENTS FROM DOCUMENTS
1862 ///////////////////////////////////////////////////////////////////////////
1864 ///////////////////////////////////////////////////////////////////////////
1865 //// REMOVE ATTACHMENTS
1866 if(isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
1867 foreach($_REQUEST['remove_attachment'] as $noteId) {
1868 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1869 $this->db->query($q);
1873 //this will remove attachments that have been selected to be removed from drafts.
1874 if(isset($_REQUEST['removeAttachment']) && !empty($_REQUEST['removeAttachment'])) {
1875 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1876 foreach($exRemoved as $noteId) {
1877 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1878 $this->db->query($q);
1881 //// END REMOVE ATTACHMENTS
1882 ///////////////////////////////////////////////////////////////////////////
1887 * Determines if an email body (HTML or Plain) has a User signature already in the content
1888 * @param array Array of signatures
1891 function hasSignatureInBody($sig) {
1892 // strpos can't handle line breaks - normalize
1893 $html = $this->removeAllNewlines($this->description_html);
1894 $htmlSig = $this->removeAllNewlines($sig['signature_html']);
1895 $plain = $this->removeAllNewlines($this->description);
1896 $plainSig = $this->removeAllNewlines($sig['signature']);
1898 // cn: bug 11621 - empty sig triggers notice error
1899 if(!empty($htmlSig) && false !== strpos($html, $htmlSig)) {
1901 } elseif(!empty($plainSig) && false !== strpos($plain, $plainSig)) {
1910 * @param string String to be normalized
1913 function removeAllNewlines($str) {
1914 $bad = array("\r\n", "\n\r", "\n", "\r");
1915 $good = array('', '', '', '');
1917 return str_replace($bad, $good, strip_tags(br2nl(from_html($str))));
1923 * Set navigation anchors to aid DetailView record navigation (VCR buttons)
1924 * @param string uri The URI from the referring page (always ListView)
1925 * @return array start Array of the URI broken down with a special "current_view" for My Inbox Navs
1927 function getStartPage($uri) {
1928 if(strpos($uri, '&')) { // "&" to ensure that we can explode the GET vars - else we're gonna trigger a Notice error
1929 $serial = substr($uri, (strpos($uri, '?')+1), strlen($uri));
1930 $exUri = explode('&', $serial);
1931 $start = array('module' => '', 'action' => '', 'group' => '', 'record' => '', 'type' => '');
1933 foreach($exUri as $k => $pair) {
1934 $exPair = explode('=', $pair);
1935 $start[$exPair[0]] = $exPair[1];
1938 // specific views for current_user
1939 if(isset($start['assigned_user_id'])) {
1940 $start['current_view'] = "{$start['action']}&module={$start['module']}&assigned_user_id={$start['assigned_user_id']}&type={$start['type']}";
1950 * preps SMTP info for email transmission
1951 * @param object mail SugarPHPMailer object
1952 * @param string mailer_id
1953 * @param string ieId
1954 * @return object mail SugarPHPMailer object
1956 function setMailer($mail, $mailer_id='', $ieId='') {
1957 global $current_user;
1959 require_once("include/OutboundEmail/OutboundEmail.php");
1960 $oe = new OutboundEmail();
1961 $oe = $oe->getInboundMailerSettings($current_user, $mailer_id, $ieId);
1963 // ssl or tcp - keeping outside isSMTP b/c a default may inadvertantly set ssl://
1964 $mail->protocol = ($oe->mail_smtpssl) ? "ssl://" : "tcp://";
1965 if($oe->mail_sendtype == "SMTP")
1967 //Set mail send type information
1968 $mail->Mailer = "smtp";
1969 $mail->Host = $oe->mail_smtpserver;
1970 $mail->Port = $oe->mail_smtpport;
1971 if ($oe->mail_smtpssl == 1) {
1972 $mail->SMTPSecure = 'ssl';
1974 if ($oe->mail_smtpssl == 2) {
1975 $mail->SMTPSecure = 'tls';
1978 if($oe->mail_smtpauth_req) {
1979 $mail->SMTPAuth = TRUE;
1980 $mail->Username = $oe->mail_smtpuser;
1981 $mail->Password = $oe->mail_smtppass;
1985 $mail->Mailer = "sendmail";
1992 * preps SugarPHPMailer object for HTML or Plain text sends
1993 * @param object SugarPHPMailer instance
1995 function handleBody($mail) {
1996 global $current_user;
1997 global $sugar_config;
1998 ///////////////////////////////////////////////////////////////////////
1999 //// HANDLE EMAIL FORMAT PREFERENCE
2000 // the if() below is HIGHLY dependent on the Javascript unchecking the Send HTML Email box
2002 if( (isset($_REQUEST['setEditor']) /* from Email EditView navigation */
2003 && $_REQUEST['setEditor'] == 1
2004 && trim($_REQUEST['description_html']) != '')
2005 || trim($this->description_html) != '' /* from email templates */
2006 && $current_user->getPreference('email_editor_option', 'global') !== 'plain' //user preference is not set to plain text
2008 $this->handleBodyInHTMLformat($mail);
2011 $this->description_html = '';
2012 $mail->IsHTML(false);
2013 $plainText = from_html($this->description);
2014 $plainText = str_replace(" ", " ", $plainText);
2015 $plainText = str_replace("</p>", "</p><br />", $plainText);
2016 $plainText = strip_tags(br2nl($plainText));
2017 $plainText = str_replace("&", "&", $plainText);
2018 $plainText = str_replace("'", "'", $plainText);
2019 $mail->Body = wordwrap($plainText, 996);
2020 $mail->Body = $this->decodeDuringSend($mail->Body);
2021 $this->description = $mail->Body;
2024 // wp: if plain text version has lines greater than 998, use base64 encoding
2025 foreach(explode("\n", ($mail->ContentType == "text/html") ? $mail->AltBody : $mail->Body) as $line) {
2026 if(strlen($line) > 998) {
2027 $mail->Encoding = 'base64';
2031 //// HANDLE EMAIL FORMAT PREFERENCE
2032 ///////////////////////////////////////////////////////////////////////
2038 * Retrieve function from handlebody() to unit test easily
2040 * @return formatted $mail body
2042 function handleBodyInHTMLformat($mail) {
2043 global $current_user;
2044 global $sugar_config;
2045 // wp: if body is html, then insert new lines at 996 characters. no effect on client side
2046 // due to RFC 2822 which limits email lines to 998
2047 $mail->IsHTML(true);
2048 $body = from_html(wordwrap($this->description_html, 996));
2049 $mail->Body = $body;
2052 // new plan is to use the selected type (html or plain) to fill the other
2053 $plainText = from_html($this->description_html);
2054 $plainText = strip_tags(br2nl($plainText));
2055 $mail->AltBody = $plainText;
2056 $this->description = $plainText;
2058 $fileBasePath = "{$sugar_config['cache_dir']}images/";
2059 $filePatternSearch = "{$sugar_config['cache_dir']}";
2060 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2061 $filePatternSearch = $filePatternSearch . "images\/";
2062 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2065 preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2066 foreach($matches[0] as $match) {
2067 $filename = str_replace($fileBasePath, '', $match);
2068 $filename = urldecode(substr($filename, 0, -1));
2070 $file_location = clean_path(getcwd()."/{$sugar_config['cache_dir']}images/{$filename}");
2071 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2073 if(file_exists($file_location)) {
2074 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2078 //replace references to cache with cid tag
2079 $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2080 $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2081 // remove bad img line from outbound email
2082 $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2083 $mail->Body = preg_replace($regex, '', $mail->Body);
2085 $fileBasePath = "{$sugar_config['upload_dir']}";
2086 $filePatternSearch = "{$sugar_config['upload_dir']}";
2087 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2088 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2091 preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2092 foreach($matches[0] as $match) {
2093 $filename = str_replace($fileBasePath, '', $match);
2094 $filename = urldecode(substr($filename, 0, -1));
2096 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$filename}");
2097 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2099 if(file_exists($file_location)) {
2100 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2104 //replace references to cache with cid tag
2105 $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2106 $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2108 // remove bad img line from outbound email
2109 $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2110 $mail->Body = preg_replace($regex, '', $mail->Body);
2113 //Replace any embeded images using the secure entryPoint for src url.
2114 $noteImgRegex = "/<img[^>]*[\s]+src[^=]*=\"index.php\?entryPoint=download\&id=([^\&]*)[^>]*>/im";
2115 $embededImageMatches = array();
2116 preg_match_all($noteImgRegex, $mail->Body, $embededImageMatches,PREG_SET_ORDER);
2118 foreach ($embededImageMatches as $singleMatch )
2120 $fullMatch = $singleMatch[0];
2121 $noteId = $singleMatch[1];
2123 $filename = $noteId;
2125 //Retrieve note for mimetype
2126 $tmpNote = new Note();
2127 $tmpNote->retrieve($noteId);
2128 //Replace the src part of img tag with new cid tag
2129 $cidRegex = "/src=\"([^\"]*)\"/im";
2130 $replaceMatch = preg_replace($cidRegex, "src=\"cid:$noteId\"", $fullMatch);
2132 //Replace the body, old tag for new tag
2133 $mail->Body = str_replace($fullMatch, $replaceMatch, $mail->Body);
2136 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$noteId}");
2138 if(file_exists($file_location))
2139 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $tmpNote->file_mime_type);
2144 $mail->Body = from_html($mail->Body);
2149 * @return bool True on success
2152 global $mod_strings,$app_strings;
2153 global $current_user;
2154 global $sugar_config;
2156 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
2157 $mail = new SugarPHPMailer();
2159 foreach ($this->to_addrs_arr as $addr_arr) {
2160 if ( empty($addr_arr['display'])) {
2161 $mail->AddAddress($addr_arr['email'], "");
2163 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
2166 foreach ($this->cc_addrs_arr as $addr_arr) {
2167 if ( empty($addr_arr['display'])) {
2168 $mail->AddCC($addr_arr['email'], "");
2170 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2174 foreach ($this->bcc_addrs_arr as $addr_arr) {
2175 if ( empty($addr_arr['display'])) {
2176 $mail->AddBCC($addr_arr['email'], "");
2178 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2182 $mail = $this->setMailer($mail);
2185 if(!empty($this->from_addr)) {
2186 $mail->From = $this->from_addr;
2188 $mail->From = $current_user->getPreference('mail_fromaddress');
2189 $this->from_addr = $mail->From;
2192 if(!empty($this->from_name)) {
2193 $mail->FromName = $this->from_name;
2195 $mail->FromName = $current_user->getPreference('mail_fromname');
2196 $this->from_name = $mail->FromName;
2199 //Reply to information for case create and autoreply.
2200 if(!empty($this->reply_to_name)) {
2201 $ReplyToName = $this->reply_to_name;
2203 $ReplyToName = $mail->FromName;
2205 if(!empty($this->reply_to_addr)) {
2206 $ReplyToAddr = $this->reply_to_addr;
2208 $ReplyToAddr = $mail->From;
2210 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
2211 $mail->AddReplyTo($ReplyToAddr,$locale->translateCharsetMIME(trim($ReplyToName), 'UTF-8', $OBCharset));
2213 //$mail->Subject = html_entity_decode($this->name, ENT_QUOTES, 'UTF-8');
2214 $mail->Subject = $this->name;
2216 ///////////////////////////////////////////////////////////////////////
2218 foreach($this->saved_attachments as $note) {
2219 $mime_type = 'text/plain';
2220 if($note->object_name == 'Note') {
2221 if(!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) { // brandy-new file upload/attachment
2222 $file_location = $sugar_config['upload_dir'].$note->id;
2223 $filename = $note->file->original_file_name;
2224 $mime_type = $note->file->mime_type;
2225 } else { // attachment coming from template/forward
2226 $file_location = rawurldecode(UploadFile::get_file_path($note->filename,$note->id));
2227 // cn: bug 9723 - documents from EmailTemplates sent with Doc Name, not file name.
2228 $filename = !empty($note->filename) ? $note->filename : $note->name;
2229 $mime_type = $note->file_mime_type;
2231 } elseif($note->object_name == 'DocumentRevision') { // from Documents
2232 $filePathName = $note->id;
2233 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
2234 $filename = $note->getDocumentRevisionNameForDisplay();
2235 $file_location = getcwd().'/'.$GLOBALS['sugar_config']['upload_dir'].$filePathName;
2236 $mime_type = $note->file_mime_type;
2239 // strip out the "Email attachment label if exists
2240 $filename = str_replace($mod_strings['LBL_EMAIL_ATTACHMENT'].': ', '', $filename);
2242 //is attachment in our list of bad files extensions? If so, append .txt to file location
2243 //get position of last "." in file name
2244 $file_ext_beg = strrpos($file_location,".");
2246 //get file extension
2247 if($file_ext_beg >0){
2248 $file_ext = substr($file_location, $file_ext_beg+1 );
2250 //check to see if this is a file with extension located in "badext"
2251 foreach($sugar_config['upload_badext'] as $badExt) {
2252 if(strtolower($file_ext) == strtolower($badExt)) {
2253 //if found, then append with .txt to filename and break out of lookup
2254 //this will make sure that the file goes out with right extension, but is stored
2256 $file_location = $file_location . ".txt";
2257 break; // no need to look for more
2260 $mail->AddAttachment($file_location,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
2263 if($note->embed_flag == true) {
2265 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64',$mime_type);
2268 //// END ATTACHMENTS
2269 ///////////////////////////////////////////////////////////////////////
2271 $mail = $this->handleBody($mail);
2273 $GLOBALS['log']->debug('Email sending --------------------- ');
2275 ///////////////////////////////////////////////////////////////////////
2276 //// I18N TRANSLATION
2277 $mail->prepForOutbound();
2278 //// END I18N TRANSLATION
2279 ///////////////////////////////////////////////////////////////////////
2282 ///////////////////////////////////////////////////////////////////
2283 //// INBOUND EMAIL HANDLING
2285 if(!empty($_REQUEST['inbound_email_id'])) {
2286 $ieMail = new Email();
2287 $ieMail->retrieve($_REQUEST['inbound_email_id']);
2288 $ieMail->status = 'replied';
2291 $GLOBALS['log']->debug(' --------------------- buh bye -- sent successful');
2292 //// END INBOUND EMAIL HANDLING
2293 ///////////////////////////////////////////////////////////////////
2296 $GLOBALS['log']->debug($app_strings['LBL_EMAIL_ERROR_PREPEND'].$mail->ErrorInfo);
2301 function listviewACLHelper(){
2302 $array_assign = parent::listviewACLHelper();
2304 if(!empty($this->parent_name)){
2306 if(!empty($this->parent_name_owner)){
2307 global $current_user;
2308 $is_owner = $current_user->id == $this->parent_name_owner;
2311 if(!ACLController::moduleSupportsACL($this->parent_type) || ACLController::checkAccess($this->parent_type, 'view', $is_owner)){
2312 $array_assign['PARENT'] = 'a';
2314 $array_assign['PARENT'] = 'span';
2317 if(!empty($this->contact_name)) {
2318 if(!empty($this->contact_name_owner)) {
2319 global $current_user;
2320 $is_owner = $current_user->id == $this->contact_name_owner;
2323 if(ACLController::checkAccess('Contacts', 'view', $is_owner)) {
2324 $array_assign['CONTACT'] = 'a';
2326 $array_assign['CONTACT'] = 'span';
2329 return $array_assign;
2332 function getSystemDefaultEmail() {
2335 $r1 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromaddress\'');
2336 $r2 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromname\'');
2337 $a1 = $this->db->fetchByAssoc($r1);
2338 $a2 = $this->db->fetchByAssoc($r2);
2340 $email['email'] = $a1['value'];
2341 $email['name'] = $a2['value'];
2347 function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false) {
2349 if ($return_array) {
2350 return parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, $return_array,$parentbean, $singleSelect);
2352 $custom_join = $this->custom_fields->getJOIN();
2354 $query = "SELECT ".$this->table_name.".*, users.user_name as assigned_user_name\n";
2357 $query .= $custom_join['select'];
2359 $query .= " FROM emails\n";
2360 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2361 $query .= " LEFT JOIN emails_beans ON emails.id = emails_beans.email_id\n";
2364 $query .= " LEFT JOIN users ON emails.assigned_user_id=users.id \n";
2365 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2367 $query .= " JOIN contacts ON contacts.id= emails_beans.bean_id AND emails_beans.bean_module='Contacts' and contacts.deleted=0 \n";
2371 $query .= $custom_join['join'];
2374 if($show_deleted == 0) {
2375 $where_auto = " emails.deleted=0 \n";
2376 }else if($show_deleted == 1){
2377 $where_auto = " emails.deleted=1 \n";
2381 $query .= "WHERE $where AND ".$where_auto;
2383 $query .= "WHERE ".$where_auto;
2386 $query .= " ORDER BY $order_by";
2388 $query .= " ORDER BY date_sent DESC";
2394 function fill_in_additional_list_fields() {
2396 $this->fill_in_additional_detail_fields();
2398 $this->link_action = 'DetailView';
2399 ///////////////////////////////////////////////////////////////////////
2400 //populate attachment_image, used to display attachment icon.
2401 $query = "select 1 from notes where notes.parent_id = '$this->id' and notes.deleted = 0";
2402 $result =$this->db->query($query,true," Error filling in additional list fields: ");
2404 $row = $this->db->fetchByAssoc($result);
2405 $this->attachment_image = ($row !=null) ? SugarThemeRegistry::current()->getImage('attachment',"","","") : "";
2407 ///////////////////////////////////////////////////////////////////////
2408 if(empty($this->contact_id) && !empty($this->parent_id) && !empty($this->parent_type) && $this->parent_type === 'Contacts' && !empty($this->parent_name) ){
2409 $this->contact_id = $this->parent_id;
2410 $this->contact_name = $this->parent_name;
2414 function fill_in_additional_detail_fields() {
2415 global $app_list_strings,$mod_strings;
2416 // Fill in the assigned_user_name
2417 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id, '');
2418 //if ($this->parent_type == 'Contacts') {
2419 $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 ";
2420 $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";
2421 if(!empty($this->parent_id)){
2422 $query .= " AND contacts.id= '".$this->parent_id."' ";
2423 }else if(!empty($_REQUEST['record'])){
2424 $query .= " AND contacts.id= '".$_REQUEST['record']."' ";
2426 $result =$this->db->query($query,true," Error filling in additional detail fields: ");
2428 // Get the id and the name.
2429 $row = $this->db->fetchByAssoc($result);
2433 $contact = new Contact();
2434 $contact->retrieve($row['id']);
2435 $this->contact_name = $contact->full_name;
2436 $this->contact_phone = $row['phone_work'];
2437 $this->contact_id = $row['id'];
2438 $this->contact_email = $contact->emailAddress->getPrimaryAddress($contact);
2439 $this->contact_name_owner = $row['contact_name_owner'];
2440 $this->contact_name_mod = $row['contact_name_mod'];
2441 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2442 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2443 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2444 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2447 $this->contact_name = '';
2448 $this->contact_phone = '';
2449 $this->contact_id = '';
2450 $this->contact_email = '';
2451 $this->contact_name_owner = '';
2452 $this->contact_name_mod = '';
2453 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2454 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2455 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2456 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2459 $this->created_by_name = get_assigned_user_name($this->created_by);
2460 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
2462 $this->link_action = 'DetailView';
2464 if(!empty($this->type)) {
2465 if($this->type == 'out' && $this->status == 'send_error') {
2466 $this->type_name = $mod_strings['LBL_NOT_SENT'];
2468 $this->type_name = $app_list_strings['dom_email_types'][$this->type];
2471 if(($this->type == 'out' && $this->status == 'send_error') || $this->type == 'draft') {
2472 $this->link_action = 'EditView';
2476 //todo this isset( $app_list_strings['dom_email_status'][$this->status]) is hack for 3261.
2477 if(!empty($this->status) && isset( $app_list_strings['dom_email_status'][$this->status])) {
2478 $this->status_name = $app_list_strings['dom_email_status'][$this->status];
2481 if ( empty($this->name ) && empty($_REQUEST['record'])) {
2482 $this->name = $mod_strings['LBL_NO_SUBJECT'];
2485 $this->fill_in_additional_parent_fields();
2490 function create_export_query(&$order_by, &$where) {
2491 $contact_required = stristr($where, "contacts");
2492 $custom_join = $this->custom_fields->getJOIN(true, true,$where);
2494 if($contact_required) {
2495 $query = "SELECT emails.*, contacts.first_name, contacts.last_name";
2497 $query .= $custom_join['select'];
2500 $query .= " FROM contacts, emails, emails_contacts ";
2501 $where_auto = "emails_contacts.contact_id = contacts.id AND emails_contacts.email_id = emails.id AND emails.deleted=0 AND contacts.deleted=0";
2503 $query = 'SELECT emails.*';
2505 $query .= $custom_join['select'];
2508 $query .= ' FROM emails ';
2509 $where_auto = "emails.deleted=0";
2513 $query .= $custom_join['join'];
2517 $query .= "where $where AND ".$where_auto;
2519 $query .= "where ".$where_auto;
2522 $query .= " ORDER BY $order_by";
2524 $query .= " ORDER BY emails.name";
2528 function get_list_view_data() {
2529 global $app_list_strings;
2531 global $current_user;
2533 global $mod_strings;
2535 $email_fields = $this->get_list_view_array();
2536 $this->retrieveEmailText();
2537 $email_fields['FROM_ADDR'] = $this->from_addr_name;
2538 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); // hard-coding for Home screen ListView
2540 if($this->status != 'replied') {
2541 $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>';
2542 $email_fields['STATUS'] = ($email_fields['REPLY_TO_STATUS'] == 1 ? $mod_strings['LBL_REPLIED'] : $email_fields['STATUS']);
2544 $email_fields['QUICK_REPLY'] = $mod_strings['LBL_REPLIED'];
2546 if(!empty($this->parent_type)) {
2547 $email_fields['PARENT_MODULE'] = $this->parent_type;
2549 switch($this->intent) {
2551 $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Cases&action=EditView&inbound_email_id='.$this->id.'" ><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('CreateCases.gif').'">'.$mod_strings['LBL_CREATE_CASE'].'</a>';
2555 $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Leads&action=EditView&inbound_email_id='.$this->id.'" ><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('CreateLeads.gif').'">'.$mod_strings['LBL_CREATE_LEAD'].'</a>';
2559 $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Contacts&action=EditView&inbound_email_id='.$this->id.'" ><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('CreateContacts.gif').'">'.$mod_strings['LBL_CREATE_CONTACT'].'</a>';
2563 $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Bugs&action=EditView&inbound_email_id='.$this->id.'" ><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('CreateBugs.gif').'">'.$mod_strings['LBL_CREATE_BUG'].'</a>';
2567 $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Tasks&action=EditView&inbound_email_id='.$this->id.'" ><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('CreateTasks.gif').'">'.$mod_strings['LBL_CREATE_TASK'].'</a>';
2580 $email_fields['CREATE_RELATED'] = $this->quickCreateForm();
2586 //BUG 17098 - MFH changed $this->from_addr to $this->to_addrs
2587 $email_fields['CONTACT_NAME'] = empty($this->contact_name) ? '</a>'.$this->trimLongTo($this->to_addrs).'<a>' : $this->contact_name;
2588 $email_fields['CONTACT_ID'] = empty($this->contact_id) ? '' : $this->contact_id;
2589 $email_fields['ATTACHMENT_IMAGE'] = $this->attachment_image;
2590 $email_fields['LINK_ACTION'] = $this->link_action;
2592 if(isset($this->type_name))
2593 $email_fields['TYPE_NAME'] = $this->type_name;
2595 return $email_fields;
2598 function quickCreateForm() {
2599 global $mod_strings, $app_strings, $currentModule, $current_language;
2601 // Coming from the home page via Dashlets
2602 if($currentModule != 'Email')
2603 $mod_strings = return_module_language($current_language, 'Emails');
2604 return $mod_strings['LBL_QUICK_CREATE']." <a id='$this->id' onclick='return quick_create_overlib(\"{$this->id}\", \"".SugarThemeRegistry::current()->__toString()."\");' href=\"#\" >".SugarThemeRegistry::current()->getImage("advanced_search","alt='".$mod_strings['LBL_QUICK_CREATE']."' border='0' align='absmiddle'")."</a>";
2608 * Searches all imported emails and returns the result set as an array.
2611 function searchImportedEmails($sort = '', $direction='')
2613 require_once('include/TimeDate.php');
2615 global $current_user;
2617 global $sugar_config;
2618 global $app_strings;
2620 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
2621 // cn: default to a low number until user specifies otherwise
2622 if(empty($emailSettings['showNumInList']))
2625 $pageSize = $emailSettings['showNumInList'];
2627 if( isset($_REQUEST['start']) && isset($_REQUEST['limit']) )
2628 $page = ceil($_REQUEST['start'] / $_REQUEST['limit']) + 1;
2632 //Determine sort ordering
2634 //Sort ordering parameters in the request do not coincide with actual column names
2635 //so we need to remap them.
2636 $hrSortLocal = array(
2637 'flagged' => 'type',
2638 'status' => 'reply_to_status',
2639 'from' => 'emails_text.from_addr',
2640 'subject' => 'name',
2641 'date' => 'date_sent',
2642 'AssignedTo' => 'assigned_user_id',
2643 'flagged' => 'flagged'
2646 $sort = !empty($_REQUEST['sort']) ? $_REQUEST['sort'] : "";
2647 $direction = !empty($_REQUEST['dir']) ? $_REQUEST['dir'] : "";
2649 $order = ( !empty($sort) && !empty($direction) ) ? " ORDER BY {$hrSortLocal[$sort]} {$direction}" : "";
2651 //Get our main query.
2652 $fullQuery = $this->_genereateSearchImportedEmailsQuery();
2654 //Perform a count query needed for pagination.
2655 $countQuery = $this->create_list_count_query($fullQuery);
2656 $count_rs = $this->db->query($countQuery, false, 'Error executing count query for imported emails search');
2657 $count_row = $this->db->fetchByAssoc($count_rs);
2658 $total_count = ($count_row != null) ? $count_row['c'] : 0;
2660 $start = ($page - 1) * $pageSize;
2663 $rs = $this->db->limitQuery($fullQuery . $order, $start, $pageSize);
2667 while($a = $this->db->fetchByAssoc($rs)) {
2669 $temp['flagged'] = (is_null($a['flagged']) || $a['flagged'] == '0') ? '' : 1;
2670 $temp['status'] = (is_null($a['reply_to_status']) || $a['reply_to_status'] == '0') ? '' : 1;
2671 $temp['subject'] = $a['name'];
2672 $temp['date'] = $timedate->to_display_date_time($a['date_sent']);
2673 $temp['uid'] = $a['id'];
2674 $temp['ieId'] = $a['mailbox_id'];
2675 $temp['site_url'] = $sugar_config['site_url'];
2676 $temp['seen'] = ($a['status'] == 'unread') ? 0 : 1;
2677 $temp['type'] = $a['type'];
2678 $temp['mbox'] = 'sugar::Emails';
2679 $temp['hasAttach'] = $this->doesImportedEmailHaveAttachment($a['id']);
2680 //To and from addresses may be stored in emails_text, if nothing is found, revert to
2681 //regular email addresses.
2682 $temp['to_addrs'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['to_addrs']);
2683 $temp['from'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['from_addr']);
2684 if( empty($temp['from']) || empty($temp['to_addrs']) )
2686 //Retrieve email addresses seperatly.
2687 $tmpEmail = new Email();
2688 $tmpEmail->id = $a['id'];
2689 $tmpEmail->retrieveEmailAddresses();
2690 $temp['from'] = $tmpEmail->from_addr;
2691 $temp['to_addrs'] = $tmpEmail->to_addrs;
2697 $metadata = array();
2698 $metadata['totalCount'] = $total_count;
2699 $metadata['out'] = $return;
2705 * Determine if an imported email has an attachment by examining the relationship to notes.
2710 function doesImportedEmailHaveAttachment($id)
2712 $hasAttachment = FALSE;
2713 $query = "SELECT id FROM notes where parent_id='$id' AND parent_type='Emails' AND file_mime_type is not null AND deleted=0";
2714 $rs = $this->db->limitQuery($query, 0, 1);
2715 $row = $this->db->fetchByAssoc($rs);
2716 if( !empty($row['id']) )
2717 $hasAttachment = TRUE;
2719 return (int) $hasAttachment;
2723 * Generate the query used for searching imported emails.
2725 * @return String Query to be executed.
2727 function _genereateSearchImportedEmailsQuery()
2731 $additionalWhereClause = $this->_generateSearchImportWhereClause();
2735 $query['select'] = "emails.id , emails.mailbox_id, emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status,
2736 emails_text.from_addr, emails_text.to_addrs FROM emails ";
2738 $query['joins'] = " JOIN emails_text on emails.id = emails_text.email_id ";
2740 //Handle from and to addr joins
2741 if( !empty($_REQUEST['from_addr']) )
2743 $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
2744 AND er_from.address_type='from' AND ea_from.email_address='" . strtolower($_REQUEST['from_addr']) . "'";
2747 if( !empty($_REQUEST['to_addrs']) )
2749 $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
2750 AND er_to.address_type='to' AND ea_to.email_address='" . strtolower($_REQUEST['to_addrs']) . "'";
2753 $query['where'] = " WHERE (emails.type= 'inbound' OR emails.type='archived' OR emails.type='out') AND emails.deleted = 0 ";
2754 if( !empty($additionalWhereClause) )
2755 $query['where'] .= "AND $additionalWhereClause";
2757 //If we are explicitly looking for attachments. Do not use a distinct query as the to_addr is defined
2758 //as a text which equals clob in oracle and the distinct query can not be executed correctly.
2759 $addDistinctKeyword = "";
2760 if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 1) //1 indicates yes
2761 $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 )";
2762 else if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 2 )
2763 $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 )";
2765 $fullQuery = "SELECT " . $query['select'] . " " . $query['joins'] . " " . $query['where'];
2770 * Generate the where clause for searching imported emails.
2773 function _generateSearchImportWhereClause()
2777 //The clear button was removed so if a user removes the asisgned user name, do not process the id.
2778 if( empty($_REQUEST['assigned_user_name']) && !empty($_REQUEST['assigned_user_id']) )
2779 unset($_REQUEST['assigned_user_id']);
2781 $availableSearchParam = array('name' => array('table_name' =>'emails'),
2782 'data_parent_id_search' => array('table_name' =>'emails','db_key' => 'parent_id','opp' => '='),
2783 'assigned_user_id' => array('table_name' => 'emails', 'opp' => '=') );
2785 $additionalWhereClause = array();
2786 foreach ($availableSearchParam as $key => $properties)
2788 if( !empty($_REQUEST[$key]) )
2790 $db_key = isset($properties['db_key']) ? $properties['db_key'] : $key;
2791 $searchValue = $_REQUEST[$key];
2793 $opp = isset($properties['opp']) ? $properties['opp'] : 'like';
2795 $searchValue = $searchValue . "%";
2797 $additionalWhereClause[] = "{$properties['table_name']}.$db_key $opp '$searchValue' ";
2801 $isDateFromSearchSet = !empty($_REQUEST['searchDateFrom']);
2802 $isdateToSearchSet = !empty($_REQUEST['searchDateTo']);
2804 $bothDateRangesSet = $isDateFromSearchSet & $isdateToSearchSet;
2806 //Hanlde date from and to seperately
2807 if($bothDateRangesSet)
2809 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2810 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2812 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2813 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2815 $additionalWhereClause[] = "( emails.date_sent >= $dbFormatDateFrom AND
2816 emails.date_sent <= $dbFormatDateTo )";
2818 elseif ($isdateToSearchSet)
2820 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2821 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2822 $additionalWhereClause[] = "emails.date_sent <= $dbFormatDateTo ";
2824 elseif ($isDateFromSearchSet)
2826 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2827 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2828 $additionalWhereClause[] = "emails.date_sent >= $dbFormatDateFrom ";
2831 $additionalWhereClause = implode(" AND ", $additionalWhereClause);
2833 return $additionalWhereClause;
2839 * takes a long TO: string of emails and returns the first appended by an
2842 function trimLongTo($str) {
2843 if(strpos($str, ',')) {
2844 $exStr = explode(',', $str);
2845 return $exStr[0].'...';
2846 } elseif(strpos($str, ';')) {
2847 $exStr = explode(';', $str);
2848 return $exStr[0].'...';
2854 function get_summary_text() {
2860 function distributionForm($where) {
2861 global $app_list_strings;
2862 global $app_strings;
2863 global $mod_strings;
2865 global $current_user;
2867 $distribution = get_select_options_with_id($app_list_strings['dom_email_distribution'], '');
2868 $_SESSION['distribute_where'] = $where;
2871 $out = '<form name="Distribute" id="Distribute">';
2872 $out .= get_form_header($mod_strings['LBL_DIST_TITLE'], '', false);
2879 <table cellpadding="0" cellspacing="0" width="100%" border="0">
2882 <script type="text/javascript">
2885 function checkDeps(form) {
2889 function mySubmit() {
2890 var assform = document.getElementById("Distribute");
2891 var select = document.getElementById("userSelect");
2892 var assign1 = assform.r1.checked;
2893 var assign2 = assform.r2.checked;
2894 var dist = assform.dm.value;
2898 var warn1 = "'.$mod_strings['LBL_WARN_NO_USERS'].'";
2901 if(assign1 || assign2) {
2906 for(i=0; i<select.options.length; i++) {
2907 if(select.options[i].selected == true) {
2916 warn2 = "'.$mod_strings['LBL_WARN_NO_DIST'].'";
2919 if(assign && users && rules) {
2921 if(document.getElementById("r1").checked) {
2922 var mu = document.getElementById("MassUpdate");
2925 for(i=0; i<mu.elements.length; i++) {
2926 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name.value != "massall") {
2927 if(grabbed != "") { grabbed += "::"; }
2928 grabbed += mu.elements[i].value;
2931 var formgrab = document.getElementById("grabbed");
2932 formgrab.value = grabbed;
2936 alert("'.$mod_strings['LBL_ASSIGN_WARN'].'" + "\n" + warn1 + "\n" + warn2);
2940 function submitDelete() {
2941 if(document.getElementById("r1").checked) {
2942 var mu = document.getElementById("MassUpdate");
2945 for(i=0; i<mu.elements.length; i++) {
2946 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name != "massall") {
2947 if(grabbed != "") { grabbed += "::"; }
2948 grabbed += mu.elements[i].value;
2951 var formgrab = document.getElementById("grabbed");
2952 formgrab.value = grabbed;
2955 alert("'.$mod_strings['LBL_MASS_DELETE_ERROR'].'");
2957 document.getElementById("Distribute").submit();
2962 <input type="hidden" name="module" value="Emails">
2963 <input type="hidden" name="action" id="action">
2964 <input type="hidden" name="grabbed" id="grabbed">
2966 <table cellpadding="1" cellspacing="0" width="100%" border="0" class="edit view">
2968 <td scope="col" scope="row" NOWRAP align="center">
2969 '.$mod_strings['LBL_ASSIGN_SELECTED_RESULTS_TO'].' ';
2970 $out .= $this->userSelectTable();
2972 <td scope="col" scope="row" NOWRAP align="left">
2973 '.$mod_strings['LBL_USING_RULES'].'
2974 <select name="distribute_method" id="dm" onChange="checkDeps(this.form);">'.$distribution.'</select>
2983 <td scope="col" width="50%" scope="row" NOWRAP align="right" colspan="2">
2984 <input title="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_TITLE'].'"
2986 accessKey="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_KEY'].'"
2987 class="button" onClick="AjaxObject.detailView.handleAssignmentDialogAssignAction();"
2988 type="button" name="button"
2989 value=" '.$mod_strings['LBL_BUTTON_DISTRIBUTE'].' ">';
2999 function userSelectTable() {
3001 global $mod_strings;
3004 $setTeamUserFunction = '';
3008 $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");
3010 $userTable = '<table cellpadding="0" cellspacing="0" border="0">';
3011 $userTable .= '<tr><td colspan="2"><b>'.$mod_strings['LBL_USER_SELECT'].'</b></td></tr>';
3012 $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>';
3013 $userTable .= '<tr><td colspan="2"><select style="visibility:hidden;" name="users[]" id="userSelect" multiple size="12">';
3015 while($a = $this->db->fetchByAssoc($r)) {
3016 $userTable .= '<option value="'.$a['id'].'" id="'.$a['id'].'">'.$a['first_name'].' '.$a['last_name'].'</option>';
3018 $userTable .= '</select></td></tr>';
3019 $userTable .= '</table>';
3021 $out = '<script type="text/javascript">';
3022 $out .= $setTeamUserFunction;
3024 function setCheckMark() {
3025 var select = document.getElementById("userSelect");
3027 for(i=0 ; i<select.options.length; i++) {
3028 if(select.options[i].selected == true) {
3029 document.getElementById("checkMark").style.display="";
3034 document.getElementById("checkMark").style.display="none";
3038 function showUserSelect() {
3039 var targetTable = document.getElementById("user_select");
3040 targetTable.style.visibility="visible";
3041 var userSelectTable = document.getElementById("userSelect");
3042 userSelectTable.style.visibility="visible";
3045 function hideUserSelect() {
3046 var targetTable = document.getElementById("user_select");
3047 targetTable.style.visibility="hidden";
3048 var userSelectTable = document.getElementById("userSelect");
3049 userSelectTable.style.visibility="hidden";
3052 function toggleAll(toggle) {
3053 if(toggle.checked) {
3058 var form = document.getElementById("userSelect");
3059 for(i=0; i<form.options.length; i++) {
3060 form.options[i].selected = stat;
3066 <span id="showUsersDiv" style="position:relative;">
3067 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
3068 <img border="0" src="'.SugarThemeRegistry::current()->getImageURL('Users.gif').'"></a>
3069 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
3070 <span style="display:none;" id="checkMark"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('check_inline.gif').'"></span>
3074 <div id="user_select" style="width:200px;position:absolute;left:2;top:2;visibility:hidden;z-index:1000;">
3075 <table cellpadding="0" cellspacing="0" border="0" class="list view">
3077 <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\';">
3078 <a href="#" onClick="javascript:hideUserSelect();"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('close.gif').'"></a>
3079 '.$mod_strings['LBL_USER_SELECT'].'
3083 //<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\';">
3084 $out .= ' <td style="padding:5px" class="oddListRowS1" bgcolor="#fdfdfd" valign="top" align="left" style="left:0;top:0;">
3093 function checkInbox($type) {
3095 global $mod_strings;
3096 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_CHECK_TITLE'].'"
3097 accessKey="'.$mod_strings['LBL_BUTTON_CHECK_KEY'].'"
3099 type="button" name="button"
3100 onClick="window.location=\'index.php?module=Emails&action=Check&type='.$type.'\';"
3101 style="margin-bottom:2px"
3102 value=" '.$mod_strings['LBL_BUTTON_CHECK'].' "></div>';
3107 * Guesses Primary Parent id from From: email address. Cascades guesses from Accounts to Contacts to Leads to
3108 * Users. This will not affect the many-to-many relationships already constructed as this is, at best,
3109 * informational linking.
3111 function fillPrimaryParentFields() {
3112 if(empty($this->from_addr))
3115 $GLOBALS['log']->debug("*** Email trying to guess Primary Parent from address [ {$this->from_addr} ]");
3117 $tables = array('accounts');
3119 // loop through types to get hits
3120 foreach($tables as $table) {
3121 $q = "SELECT name, id FROM {$table} WHERE email1 = '{$this->from_addr}' OR email2 = '{$this->from_addr}' AND deleted = 0";
3122 $r = $this->db->query($q);
3123 while($a = $this->db->fetchByAssoc($r)) {
3124 if(!empty($a['name']) && !empty($a['id'])) {
3125 $this->parent_type = ucwords($table);
3126 $this->parent_id = $a['id'];
3127 $this->parent_name = $a['name'];