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 $object_name = 'Email';
117 /* private attributes */
118 var $rolloverStyle = "<style>div#rollover {position: relative;float: left;margin: none;text-decoration: none;}div#rollover a:hover {padding: 0;text-decoration: none;}div#rollover a span {display: none;}div#rollover a:hover span {text-decoration: none;display: block;width: 250px;margin-top: 5px;margin-left: 5px;position: absolute;padding: 10px;color: #333; border: 1px solid #ccc; background-color: #fff; font-size: 12px;z-index: 1000;}</style>\n";
120 var $cacheFile = 'robin.cache.php';
121 var $replyDelimiter = "> ";
122 var $emailDescription;
123 var $emailDescriptionHTML;
127 var $attachments = array();
129 /* to support Email 2.0 */
137 var $relationshipMap = array(
138 'Contacts' => 'emails_contacts_rel',
139 'Accounts' => 'emails_accounts_rel',
140 'Leads' => 'emails_leads_rel',
141 'Users' => 'emails_users_rel',
142 'Prospects' => 'emails_prospects_rel',
146 var $et; // EmailUI object
154 $this->cachePath = $GLOBALS['sugar_config']['cache_dir'].'modules/Emails';
157 $this->safe = new HTML_Safe();
158 $this->safe->clear();
159 $this->emailAddress = new SugarEmailAddress();
162 function email2init() {
163 require_once('modules/Emails/EmailUI.php');
164 $this->et = new EmailUI();
166 function bean_implements($interface){
168 case 'ACL': return true;
169 default: return false;
175 * Presaves one attachment for new email 2.0 spec
176 * DOES NOT CREATE A NOTE
177 * @return string ID of note associated with the attachment
179 function email2saveAttachment() {
180 global $sugar_config;
183 0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
184 1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
185 2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
186 3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
187 4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
188 5 => 'UNKNOWN ERROR',
189 6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
190 7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
193 // cn: Bug 5995 - rudimentary error checking
194 if($_FILES['email_attachment']['error'] != 0 && $_FILES['email_attachment']['error'] != 4) {
195 $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment']['error']]);
199 if(isset($_FILES['email_attachment']) && is_uploaded_file($_FILES['email_attachment']['tmp_name'])) {
200 $guid = create_guid();
201 $cleanAttachmentFileName = from_html($_FILES['email_attachment']['name']);
202 $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] ");
203 $cleanAttachmentFileName = str_replace("\\", "", $cleanAttachmentFileName);
204 $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] ");
205 //$destination = clean_path("{$this->et->userCacheDir}/{$guid}{$cleanAttachmentFileName}");
206 $destination = clean_path("{$this->et->userCacheDir}/{$guid}");
207 $badExt = $this->safeAttachmentName($cleanAttachmentFileName);
209 //$destination = $destination . ".txt";
211 $fileName = $badExt ? $cleanAttachmentFileName . ".txt" : $cleanAttachmentFileName;
212 if(move_uploaded_file($_FILES['email_attachment']['tmp_name'], $destination)) {
215 'name' => $GLOBALS['db']->helper->escape_quote($fileName),
216 'nameForDisplay' => $fileName
219 $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] could not be moved to cache dir");
225 function safeAttachmentName($filename) {
226 global $sugar_config;
227 $badExtension = false;
228 //get position of last "." in file name
229 $file_ext_beg = strrpos($filename, ".");
233 if($file_ext_beg !== false) {
234 $file_ext = substr($filename, $file_ext_beg + 1);
237 //check to see if this is a file with extension located in "badext"
238 foreach($sugar_config['upload_badext'] as $badExt) {
239 if(strtolower($file_ext) == strtolower($badExt)) {
240 //if found, then append with .txt and break out of lookup
241 $filename = $filename . ".txt";
242 $badExtension = true;
243 break; // no need to look for more
247 return $badExtension;
251 * takes output from email 2.0 to/cc/bcc fields and returns appropriate arrays for usage by PHPMailer
252 * @param string addresses
255 function email2ParseAddresses($addresses) {
256 $addresses = from_html($addresses);
257 $addresses = $this->et->unifyEmailString($addresses);
259 $pattern = '/@.*,/U';
260 preg_match_all($pattern, $addresses, $matchs);
261 if (!empty($matchs[0])){
263 foreach ($total as $match) {
264 $convertedPattern = str_replace(',', '::;::', $match);
265 $addresses = str_replace($match, $convertedPattern, $addresses);
269 $exAddr = explode("::;::", $addresses);
272 $clean = array("<", ">");
273 $dirty = array("<", ">");
275 foreach($exAddr as $addr) {
278 $addr = str_replace($dirty, $clean, $addr);
280 if((strpos($addr, "<") === false) && (strpos($addr, ">") === false)) {
283 $address = substr($addr, strpos($addr, "<") + 1, strpos($addr, ">") - 1 - strpos($addr, "<"));
284 $name = substr($addr, 0, strpos($addr, "<"));
288 $addrTemp['email'] = trim($address);
289 $addrTemp['display'] = trim($name);
297 * takes output from email 2.0 to/cc/bcc fields and returns appropriate arrays for usage by PHPMailer
298 * @param string addresses
301 function email2ParseAddressesForAddressesOnly($addresses) {
302 $addresses = from_html($addresses);
303 $pattern = '/@.*,/U';
304 preg_match_all($pattern, $addresses, $matchs);
305 if (!empty($matchs[0])){
307 foreach ($total as $match) {
308 $convertedPattern = str_replace(',', '::;::', $match);
309 $addresses = str_replace($match, $convertedPattern, $addresses);
313 $exAddr = explode("::;::", $addresses);
316 $clean = array("<", ">");
317 $dirty = array("<", ">");
319 foreach($exAddr as $addr) {
322 $addr = str_replace($dirty, $clean, $addr);
324 if(strpos($addr, "<") && strpos($addr, ">")) {
325 $address = substr($addr, strpos($addr, "<") + 1, strpos($addr, ">") - 1 - strpos($addr, "<"));
330 $ret[] = trim($address);
337 * Determines MIME-type encoding as possible.
338 * @param string $fileLocation relative path to file
339 * @return string MIME-type
341 function email2GetMime($fileLocation) {
342 if(!is_readable($fileLocation)) {
343 return 'application/octet-stream';
345 if(function_exists('mime_content_type')) {
346 $mime = mime_content_type($fileLocation);
347 } elseif(function_exists('ext2mime')) {
348 $mime = ext2mime($fileLocation);
350 $mime = 'application/octet-stream';
356 function sendEmailTest($mailserver_url, $port, $ssltls, $smtp_auth_req, $smtp_username, $smtppassword, $fromaddress, $toaddress, $mail_sendtype = 'smtp') {
357 global $current_user,$app_strings;
358 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); //Called from EmailMan as well.
359 $mail = new SugarPHPMailer();
360 $mail->Mailer = strtolower($mail_sendtype);
361 if($mail->Mailer == 'smtp')
363 $mail->Host = $mailserver_url;
365 if (isset($ssltls) && !empty($ssltls)) {
366 $mail->protocol = "ssl://";
368 $mail->SMTPSecure = 'ssl';
371 $mail->SMTPSecure = 'tls';
374 $mail->protocol = "tcp://";
376 if ($smtp_auth_req) {
377 $mail->SMTPAuth = TRUE;
378 $mail->Username = $smtp_username;
379 $mail->Password = $smtppassword;
383 $mail->Mailer = 'sendmail';
385 $mail->Subject = from_html($mod_strings['LBL_TEST_EMAIL_SUBJECT']);
386 $mail->From = $fromaddress;
387 $mail->FromName = $current_user->name;
388 $mail->Sender = $mail->From;
389 $mail->AddAddress($toaddress);
390 $mail->Body = $mod_strings['LBL_TEST_EMAIL_BODY'];
396 $return['status'] = false;
397 $return['errorMessage'] = $app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo;
400 $return['status'] = true;
404 function decodeDuringSend($htmlData) {
405 $htmlData = str_replace("sugarLessThan", "<", $htmlData);
406 $htmlData = str_replace("sugarGreaterThan", ">", $htmlData);
411 * Returns true or false if this email is a draft.
413 * @param array $request
414 * @return bool True indicates this email is a draft.
416 function isDraftEmail($request)
418 return ( isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft') );
422 * Sends Email for Email 2.0
424 function email2Send($request) {
427 global $current_user;
428 global $sugar_config;
433 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
435 /**********************************************************************
441 if(!empty($this->id)) {
442 $orignialId = $this->id;
445 if(empty($this->id)) {
446 $this->id = create_guid();
447 $this->new_with_id = true;
450 /* satisfy basic HTML email requirements */
451 $this->name = $request['sendSubject'];
452 $this->description_html = '<html><body>'.$request['sendDescription'].'</body></html>';
454 /**********************************************************************
457 $mail = new SugarPHPMailer();
458 $mail = $this->setMailer($mail, '', $_REQUEST['fromAccount']);
459 if (empty($mail->Host) && !$this->isDraftEmail($request))
461 $this->status = 'send_error';
463 if ($mail->oe->type == 'system')
464 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_SYSTEM_OUTBOUND']);
466 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_PERSONAL_OUTBOUND']);
471 $subject = $this->name;
472 $mail->Subject = from_html($this->name);
474 // work-around legacy code in SugarPHPMailer
475 if($_REQUEST['setEditor'] == 1) {
476 $_REQUEST['description_html'] = $_REQUEST['sendDescription'];
477 $this->description_html = $_REQUEST['description_html'];
479 $this->description_html = '';
480 $this->description = $_REQUEST['sendDescription'];
484 if ( $this->isDraftEmail($request) )
486 if($this->type != 'draft' && $this->status != 'draft') {
487 $this->id = create_guid();
488 $this->new_with_id = true;
489 $this->date_entered = "";
491 $q1 = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$this->id}'";
492 $r1 = $this->db->query($q1);
495 if (isset($request['saveDraft'])) {
496 $this->type = 'draft';
497 $this->status = 'draft';
500 /* Apply Email Templates */
501 // do not parse email templates if the email is being saved as draft....
502 $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']);
503 $sea = new SugarEmailAddress();
504 $object_arr = array();
506 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
507 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) &&
508 ($_REQUEST['parent_type'] == 'Accounts' ||
509 $_REQUEST['parent_type'] == 'Contacts' ||
510 $_REQUEST['parent_type'] == 'Leads' ||
511 $_REQUEST['parent_type'] == 'Users' ||
512 $_REQUEST['parent_type'] == 'Prospects')) {
513 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
514 $className = $beanList[$_REQUEST['parent_type']];
515 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
516 if(!class_exists($className)) {
517 require_once($beanFiles[$className]);
519 $bean = new $className();
520 $bean->retrieve($_REQUEST['parent_id']);
521 $object_arr[$bean->module_dir] = $bean->id;
525 foreach($toAddresses as $addrMeta) {
526 $addr = $addrMeta['email'];
527 $beans = $sea->getBeansByEmailAddress($addr);
528 foreach($beans as $bean) {
529 if (!isset($object_arr[$bean->module_dir])) {
530 $object_arr[$bean->module_dir] = $bean->id;
535 /* template parsing */
536 if (empty($object_arr)) {
537 $object_arr= array('Contacts' => '123');
539 $object_arr['Users'] = $current_user->id;
540 $this->description_html = EmailTemplate::parse_template($this->description_html, $object_arr);
541 $this->name = EmailTemplate::parse_template($this->name, $object_arr);
542 $this->description = EmailTemplate::parse_template($this->description, $object_arr);
543 $this->description = html_entity_decode($this->description,ENT_COMPAT,'UTF-8');
544 if($this->type != 'draft' && $this->status != 'draft') {
545 $this->id = create_guid();
546 $this->date_entered = "";
547 $this->new_with_id = true;
549 $this->status = 'sent';
553 if(isset($_REQUEST['parent_type']) && empty($_REQUEST['parent_type']) &&
554 isset($_REQUEST['parent_id']) && empty($_REQUEST['parent_id']) ) {
555 $this->parent_id = "";
556 $this->parent_type = "";
560 $mail->Subject = $this->name;
561 $mail = $this->handleBody($mail);
562 $mail->Subject = $this->name;
563 $this->description_html = from_html($this->description_html);
564 $this->description_html = $this->decodeDuringSend($this->description_html);
565 $this->description = $this->decodeDuringSend($this->description);
568 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
570 if(empty($request['fromAccount'])) {
571 $defaults = $current_user->getPreferredEmail();
572 $mail->From = $defaults['email'];
573 $mail->FromName = $defaults['name'];
574 $replyToName = $mail->FromName;
575 //$replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
577 // passed -> user -> system default
578 $ie = new InboundEmail();
579 $ie->retrieve($request['fromAccount']);
580 $storedOptions = unserialize(base64_decode($ie->stored_options));
584 //$replyToAddress = "";
585 if (!empty($storedOptions)) {
586 $fromAddress = $storedOptions['from_addr'];
587 $fromName = from_html($storedOptions['from_name']);
588 $replyToAddress = (isset($storedOptions['reply_to_addr']) ? $storedOptions['reply_to_addr'] : "");
589 $replyToName = (isset($storedOptions['reply_to_name']) ? from_html($storedOptions['reply_to_name']) : "");
591 $defaults = $current_user->getPreferredEmail();
592 // Personal Account doesn't have reply To Name and Reply To Address. So add those columns on UI
593 // After adding remove below code
596 if ($ie->is_personal)
598 if (empty($replyToAddress))
600 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
602 if (empty($replyToName))
604 $replyToName = $defaults['name'];
606 //Personal accounts can have a reply_address, which should
607 //overwrite the users set default.
608 if( !empty($storedOptions['reply_to_addr']) )
609 $replyToAddress = $storedOptions['reply_to_addr'];
612 // end of code to remove
613 $mail->From = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
614 $mail->FromName = (!empty($fromName)) ? $fromName : $defaults['name'];
615 $replyToName = (!empty($replyToName)) ? $replyToName : $mail->FromName;
618 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
620 if (!empty($replyToAddress)) {
621 $mail->AddReplyTo($replyToAddress,$locale->translateCharsetMIME(trim( $replyToName), 'UTF-8', $OBCharset));
623 $mail->AddReplyTo($mail->From,$locale->translateCharsetMIME(trim( $mail->FromName), 'UTF-8', $OBCharset));
625 $emailAddressCollection = array(); // used in linking to beans below
627 foreach($this->email2ParseAddresses($request['sendTo']) as $addr_arr) {
628 if(empty($addr_arr['email'])) continue;
630 if(empty($addr_arr['display'])) {
631 $mail->AddAddress($addr_arr['email'], "");
633 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
635 $emailAddressCollection[] = $addr_arr['email'];
637 foreach($this->email2ParseAddresses($request['sendCc']) as $addr_arr) {
638 if(empty($addr_arr['email'])) continue;
640 if(empty($addr_arr['display'])) {
641 $mail->AddCC($addr_arr['email'], "");
643 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
645 $emailAddressCollection[] = $addr_arr['email'];
648 foreach($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) {
649 if(empty($addr_arr['email'])) continue;
651 if(empty($addr_arr['display'])) {
652 $mail->AddBCC($addr_arr['email'], "");
654 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
656 $emailAddressCollection[] = $addr_arr['email'];
660 /* parse remove attachments array */
661 $removeAttachments = array();
662 if(!empty($request['templateAttachmentsRemove'])) {
663 $exRemove = explode("::", $request['templateAttachmentsRemove']);
665 foreach($exRemove as $file) {
666 $removeAttachments = substr($file, 0, 36);
670 /* handle attachments */
671 if(!empty($request['attachments'])) {
672 $exAttachments = explode("::", $request['attachments']);
674 foreach($exAttachments as $file) {
675 $file = trim(from_html($file));
676 $file = str_replace("\\", "", $file);
678 //$fileLocation = $this->et->userCacheDir."/{$file}";
679 $fileGUID = substr($file, 0, 36);
680 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
681 $filename = substr($file, 36, strlen($file)); // strip GUID for PHPMailer class to name outbound file
683 $mail->AddAttachment($fileLocation,$filename, 'base64', $this->email2GetMime($fileLocation));
684 //$mail->AddAttachment($fileLocation, $filename, 'base64');
686 // only save attachments if we're archiving or drafting
687 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
689 $note->id = create_guid();
690 $note->new_with_id = true; // duplicating the note with files
691 $note->parent_id = $this->id;
692 $note->parent_type = $this->module_dir;
693 $note->name = $filename;
694 $note->filename = $filename;
695 $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
696 $note->file_mime_type = $this->email2GetMime($fileLocation);
698 if(!copy($fileLocation, $noteFile)) {
699 $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to cache/upload [ {$fileLocation} ]");
708 /* handle sugar documents */
709 if(!empty($request['documents'])) {
710 $exDocs = explode("::", $request['documents']);
715 foreach($exDocs as $docId) {
716 $docId = trim($docId);
718 $doc = new Document();
719 $docRev = new DocumentRevision();
720 $doc->retrieve($docId);
721 $docRev->retrieve($doc->document_revision_id);
723 $filename = $docRev->filename;
724 $fileLocation = "{$sugar_config['upload_dir']}{$docRev->id}";
725 $mime_type = $docRev->file_mime_type;
726 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
728 // only save attachments if we're archiving or drafting
729 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
731 $note->id = create_guid();
732 $note->new_with_id = true; // duplicating the note with files
733 $note->parent_id = $this->id;
734 $note->parent_type = $this->module_dir;
735 $note->name = $filename;
736 $note->filename = $filename;
737 $note->file_mime_type = $mime_type;
738 $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
740 if(!copy($fileLocation, $noteFile)) {
741 $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
750 /* handle template attachments */
751 if(!empty($request['templateAttachments'])) {
753 $exNotes = explode("::", $request['templateAttachments']);
754 foreach($exNotes as $noteId) {
755 $noteId = trim($noteId);
756 if(!empty($noteId)) {
758 $note->retrieve($noteId);
759 if (!empty($note->id)) {
760 $filename = $note->filename;
761 $fileLocation = "{$sugar_config['upload_dir']}{$note->id}";
762 $mime_type = $note->file_mime_type;
763 if (!$note->embed_flag) {
764 $mail->AddAttachment($fileLocation,$filename, 'base64', $mime_type);
765 // only save attachments if we're archiving or drafting
766 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
768 if ($note->parent_id != $this->id)
769 $this->saveTempNoteAttachments($filename,$fileLocation, $mime_type);
774 //$fileLocation = $this->et->userCacheDir."/{$file}";
775 $fileGUID = substr($noteId, 0, 36);
776 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
777 //$fileLocation = $this->et->userCacheDir."/{$noteId}";
778 $filename = substr($noteId, 36, strlen($noteId)); // strip GUID for PHPMailer class to name outbound file
780 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $this->email2GetMime($fileLocation));
782 //If we are saving an email we were going to forward we need to save the attachments as well.
783 if( (($this->type == 'draft') && !empty($this->id))
784 || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1))
786 $mimeType = $this->email2GetMime($fileLocation);
787 $this->saveTempNoteAttachments($filename,$fileLocation, $mimeType);
796 /**********************************************************************
799 /* save email to sugar? */
802 if($this->type == 'draft' && !isset($request['saveDraft'])) {
803 // sending a draft email
805 $this->status = 'sent';
807 } elseif(isset($request['saveDraft'])) {
808 $this->type = 'draft';
809 $this->status = 'draft';
813 /**********************************************************************
814 * SEND EMAIL (finally!)
817 if ($this->type != 'draft') {
818 $mail->prepForOutbound();
819 $mail->Body = $this->decodeDuringSend($mail->Body);
820 $mail->AltBody = $this->decodeDuringSend($mail->AltBody);
821 if (!$mail->Send()) {
822 $this->status = 'send_error';
824 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo);
829 if ((!(empty($orignialId) || isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft'))) &&
830 (($_REQUEST['composeType'] == 'reply') || ($_REQUEST['composeType'] == 'replyAll') || ($_REQUEST['composeType'] == 'replyCase')) && ($orignialId != $this->id)) {
831 $originalEmail = new Email();
832 $originalEmail->retrieve($orignialId);
833 $originalEmail->reply_to_status = 1;
834 $originalEmail->save();
835 $this->reply_to_status = 0;
838 if ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase') {
839 if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) {
840 $emailFromIe = new InboundEmail();
841 $emailFromIe->retrieve($_REQUEST['ieId']);
842 $emailFromIe->mailbox = $_REQUEST['mbox'];
843 if (isset($emailFromIe->id) && $emailFromIe->is_personal) {
844 if ($emailFromIe->isPop3Protocol()) {
845 $emailFromIe->mark_answered($this->uid, 'pop3');
847 elseif ($emailFromIe->connectMailserver() == 'true') {
848 $emailFromIe->markEmails($this->uid, 'answered');
849 $emailFromIe->mark_answered($this->uid);
857 $this->type == 'draft' ||
858 (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
860 // saving a draft OR saving a sent email
861 $decodedFromName = mb_decode_mimeheader($mail->FromName);
862 $this->from_addr = "{$decodedFromName} <{$mail->From}>";
863 $this->from_addr_name = $this->from_addr;
864 $this->to_addrs = $_REQUEST['sendTo'];
865 $this->to_addrs_names = $_REQUEST['sendTo'];
866 $this->cc_addrs = $_REQUEST['sendCc'];
867 $this->cc_addrs_names = $_REQUEST['sendCc'];
868 $this->bcc_addrs = $_REQUEST['sendBcc'];
869 $this->bcc_addrs_names = $_REQUEST['sendBcc'];
870 $this->assigned_user_id = $current_user->id;
872 $this->date_sent = $timedate->now();
873 ///////////////////////////////////////////////////////////////////
874 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
876 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
877 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) ) {
878 $this->parent_id = $_REQUEST['parent_id'];
879 $this->parent_type = $_REQUEST['parent_type'];
880 $q = "SELECT count(*) c FROM emails_beans WHERE email_id = '{$this->id}' AND bean_id = '{$_REQUEST['parent_id']}' AND bean_module = '{$_REQUEST['parent_type']}'";
881 $r = $this->db->query($q);
882 $a = $this->db->fetchByAssoc($r);
884 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
885 $className = $beanList[$_REQUEST['parent_type']];
886 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
887 if(!class_exists($className)) {
888 require_once($beanFiles[$className]);
890 $bean = new $className();
891 $bean->retrieve($_REQUEST['parent_id']);
892 if($bean->load_relationship('emails')) {
893 $bean->emails->add($this->id);
903 if(!class_exists('aCase')) {
908 if($caseId = InboundEmail::getCaseIdFromCaseNumber($mail->Subject, $c)) {
909 $c->retrieve($caseId);
910 $c->load_relationship('emails');
911 $c->emails->add($this->id);
912 $this->parent_type = "Cases";
913 $this->parent_id = $caseId;
919 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
920 ///////////////////////////////////////////////////////////////////
924 if(!empty($request['fromAccount'])) {
925 if (isset($ie->id) && !$ie->isPop3Protocol()) {
926 $sentFolder = $ie->get_stored_options("sentFolder");
927 if (!empty($sentFolder)) {
928 $data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n";
929 $ie->mailbox = $sentFolder;
930 if ($ie->connectMailserver() == 'true') {
931 $connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox);
932 $returnData = imap_append($ie->conn,$connectString, $data, "\\Seen");
934 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}");
937 $GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}");
940 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty");
948 * Generates a comma sperated name and addresses to be used in compose email screen for contacts or leads
951 * @param $module string module name
952 * @param $idsArray array of record ids to get the email address for
953 * @return string comma delimited list of email addresses
955 public function getNamePlusEmailAddressesForCompose($module, $idsArray)
959 $table = SugarModule::get($module)->loadBean()->table_name;
960 $returndata = array();
962 foreach($idsArray as $id) {
963 if ($idsString != "") {
964 $idsString = $idsString . ",";
966 $idsString = $idsString . "'" . $id . "'";
968 $where = "({$table}.deleted = 0 AND {$table}.id in ({$idsString}))";
970 if ($module == 'Users' || $module == 'Employees') {
971 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.title";
973 elseif (SugarModule::get($module)->moduleImplements('Person')) {
974 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.salutation, {$table}.title";
977 $selectColumn = "{$table}.name";
979 $query = "SELECT {$table}.id, {$selectColumn}, eabr.primary_address, ea.email_address";
980 $query .= " FROM {$table} ";
981 $query .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
982 $query .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
983 $query .= " WHERE ({$where}) ORDER BY eabr.primary_address DESC";
984 $r = $this->db->query($query);
986 while($a = $this->db->fetchByAssoc($r)) {
987 if (!isset($returndata[$a['id']])) {
988 if ($module == 'Users' || $module == 'Employees') {
989 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], '', $a['title']));
990 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
992 elseif (SugarModule::get($module)->moduleImplements('Person')) {
993 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], $a['salutation'], $a['title']));
994 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
997 $returndata[$a['id']] = from_html($a['name']) . " <".from_html($a['email_address']).">";
1002 return join(",", array_values($returndata));
1008 ///////////////////////////////////////////////////////////////////////////
1010 function save($check_notify = false) {
1011 if($this->isDuplicate) {
1012 $GLOBALS['log']->debug("EMAIL - tried to save a duplicate Email record");
1015 if(empty($this->id)) {
1016 $this->id = create_guid();
1017 $this->new_with_id = true;
1019 $this->from_addr_name = $this->cleanEmails($this->from_addr_name);
1020 $this->to_addrs_names = $this->cleanEmails($this->to_addrs_names);
1021 $this->cc_addrs_names = $this->cleanEmails($this->cc_addrs_names);
1022 $this->bcc_addrs_names = $this->cleanEmails($this->bcc_addrs_names);
1023 $this->reply_to_addr = $this->cleanEmails($this->reply_to_addr);
1024 $this->description = to_html($this->safeText(from_html($this->description)));
1025 $this->description_html = $this->safeText($this->description_html);
1026 $this->saveEmailText();
1027 $this->saveEmailAddresses();
1029 $GLOBALS['log']->debug('-------------------------------> Email called save()');
1031 // handle legacy concatenation of date and time fields
1032 if(empty($this->date_sent)) $this->date_sent = $this->date_start." ".$this->time_start;
1034 parent::save($check_notify);
1036 if(!empty($this->parent_type) && !empty($this->parent_id)) {
1037 if(!empty($this->fetched_row) && !empty($this->fetched_row['parent_id']) && !empty($this->fetched_row['parent_type'])) {
1038 if($this->fetched_row['parent_id'] != $this->parent_id || $this->fetched_row['parent_type'] != $this->parent_type) {
1039 $mod = strtolower($this->fetched_row['parent_type']);
1040 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1041 if($this->load_relationship($rel) ) {
1042 $this->$rel->delete($this->id, $this->fetched_row['parent_id']);
1045 // we already have this relationship, don't add it
1049 $mod = strtolower($this->parent_type);
1050 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1051 if($this->load_relationship($rel) ) {
1052 $this->$rel->add($this->parent_id);
1059 * Helper function to save temporary attachments assocaited to an email as note.
1061 * @param string $filename
1062 * @param string $fileLocation
1063 * @param string $mimeType
1065 function saveTempNoteAttachments($filename,$fileLocation, $mimeType)
1067 global $sugar_config;
1069 $tmpNote = new Note();
1070 $tmpNote->id = create_guid();
1071 $tmpNote->new_with_id = true;
1072 $tmpNote->parent_id = $this->id;
1073 $tmpNote->parent_type = $this->module_dir;
1074 $tmpNote->name = $filename;
1075 $tmpNote->filename = $filename;
1076 $tmpNote->file_mime_type = $mimeType;
1077 $noteFile = "{$sugar_config['upload_dir']}{$tmpNote->id}";
1078 if(!copy($fileLocation, $noteFile))
1079 $GLOBALS['log']->fatal("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
1083 * Handles normalization of Email Addressess
1085 function saveEmailAddresses() {
1086 // from, single address
1087 $fromId = $this->emailAddress->getEmailGUID(from_html($this->from_addr));
1088 if(!empty($fromId)){
1089 $this->linkEmailToAddress($fromId, 'from');
1093 $replace = array(",",";");
1094 $toaddrs = str_replace($replace, "::", from_html($this->to_addrs));
1095 $exToAddrs = explode("::", $toaddrs);
1097 if(!empty($exToAddrs)) {
1098 foreach($exToAddrs as $toaddr) {
1099 $toaddr = trim($toaddr);
1100 if(!empty($toaddr)) {
1101 $toId = $this->emailAddress->getEmailGUID($toaddr);
1102 $this->linkEmailToAddress($toId, 'to');
1108 $ccAddrs = str_replace($replace, "::", from_html($this->cc_addrs));
1109 $exccAddrs = explode("::", $ccAddrs);
1111 if(!empty($exccAddrs)) {
1112 foreach($exccAddrs as $ccAddr) {
1113 $ccAddr = trim($ccAddr);
1114 if(!empty($ccAddr)) {
1115 $ccId = $this->emailAddress->getEmailGUID($ccAddr);
1116 $this->linkEmailToAddress($ccId, 'cc');
1122 $bccAddrs = str_replace($replace, "::", from_html($this->bcc_addrs));
1123 $exbccAddrs = explode("::", $bccAddrs);
1124 if(!empty($exbccAddrs)) {
1125 foreach($exbccAddrs as $bccAddr) {
1126 $bccAddr = trim($bccAddr);
1127 if(!empty($bccAddr)) {
1128 $bccId = $this->emailAddress->getEmailGUID($bccAddr);
1129 $this->linkEmailToAddress($bccId, 'bcc');
1135 function linkEmailToAddress($id, $type) {
1136 // TODO: make this update?
1137 $q1 = "SELECT * FROM emails_email_addr_rel WHERE email_id = '{$this->id}' AND email_address_id = '{$id}' AND address_type = '{$type}' AND deleted = 0";
1138 $r1 = $this->db->query($q1);
1139 $a1 = $this->db->fetchByAssoc($r1);
1141 if(!empty($a1) && !empty($a1['id'])) {
1144 $guid = create_guid();
1145 $q2 = "INSERT INTO emails_email_addr_rel VALUES('{$guid}', '{$this->id}', '{$type}', '{$id}', 0)";
1146 $r2 = $this->db->query($q2);
1152 function cleanEmails($emails)
1154 $emails = str_replace(array(",",";"), "::", from_html($emails));
1155 $addrs = explode("::", $emails);
1157 foreach($addrs as $addr) {
1158 $parts = $this->emailAddress->splitEmailAddress($addr);
1159 if(empty($parts["email"])) {
1162 if(!empty($parts["name"])) {
1163 $res[] = "{$parts["name"]} <{$parts["email"]}>";
1165 $res[] .= $parts["email"];
1168 return join(", ", $res);
1171 function saveEmailText() {
1172 $isOracle = ($this->db->dbType == "oci8") ? true : false;
1175 $description = $this->db->quote(trim($this->description));
1176 $description_html = $this->db->quoteForEmail(trim($this->description_html));
1177 $raw_source = $this->db->quote(trim($this->raw_source));
1178 $fromAddressName = $this->db->helper->escape_quote($this->from_addr_name);
1179 $toAddressName = $this->db->helper->escape_quote($this->to_addrs_names);
1180 $ccAddressName = $this->db->helper->escape_quote($this->cc_addrs_names);
1181 $bccAddressName = $this->db->helper->escape_quote($this->bcc_addrs_names);
1182 $replyToAddrName = $this->db->helper->escape_quote($this->reply_to_addr);
1184 if(!$this->new_with_id) {
1185 $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}'";
1187 $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)";
1189 $this->db->query($q);
1195 ///////////////////////////////////////////////////////////////////////////
1197 function retrieve($id, $encoded=true, $deleted=true) {
1198 // cn: bug 11915, return SugarBean's retrieve() call bean instead of $this
1199 $ret = parent::retrieve($id, $encoded, $deleted);
1202 $ret->retrieveEmailText();
1203 $ret->retrieveEmailAddresses();
1204 $ret->raw_source = to_html($ret->safeText(from_html($ret->raw_source)));
1205 $ret->description = to_html($ret->safeText(from_html($ret->description)));
1206 $ret->description_html = $ret->safeText($ret->description_html);
1208 $ret->date_start = '';
1209 $ret->time_start = '';
1210 $dateSent = explode(' ', $ret->date_sent);
1211 if (!empty($dateSent)) {
1212 $ret->date_start = $dateSent[0];
1213 if ( isset($dateSent[1]) )
1214 $ret->time_start = $dateSent[1];
1217 foreach($ret as $k => $v) {
1226 * Retrieves email addresses from GUIDs
1228 function retrieveEmailAddresses() {
1231 $q = "SELECT email_address, address_type
1232 FROM emails_email_addr_rel eam
1233 JOIN email_addresses ea ON ea.id = eam.email_address_id
1234 WHERE eam.email_id = '{$this->id}' AND eam.deleted=0";
1235 $r = $this->db->query($q);
1237 while($a = $this->db->fetchByAssoc($r)) {
1238 if(!isset($return[$a['address_type']])) {
1239 $return[$a['address_type']] = array();
1241 $return[$a['address_type']][] = $a['email_address'];
1244 if(count($return) > 0) {
1245 if(isset($return['from'])) {
1246 $this->from_addr = implode(", ", $return['from']);
1248 if(isset($return['to'])) {
1249 $this->to_addrs = implode(", ", $return['to']);
1251 if(isset($return['cc'])) {
1252 $this->cc_addrs = implode(", ", $return['cc']);
1254 if(isset($return['bcc'])) {
1255 $this->bcc_addrs = implode(", ", $return['bcc']);
1261 * Handles longtext fields
1263 function retrieveEmailText() {
1264 $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}'";
1265 $r = $this->db->query($q);
1266 $a = $this->db->fetchByAssoc($r, -1, false);
1268 $this->description = $a['description'];
1269 $this->description_html = $a['description_html'];
1270 $this->raw_source = $a['raw_source'];
1271 $this->from_addr_name = $a['from_addr'];
1272 $this->reply_to_addr = $a['reply_to_addr'];
1273 $this->to_addrs_names = $a['to_addrs'];
1274 $this->cc_addrs_names = $a['cc_addrs'];
1275 $this->bcc_addrs_names = $a['bcc_addrs'];
1278 function delete($id='') {
1282 $q = "UPDATE emails SET deleted = 1 WHERE id = '{$id}'";
1283 $qt = "UPDATE emails_text SET deleted = 1 WHERE email_id = '{$id}'";
1284 $r = $this->db->query($q);
1285 $rt = $this->db->query($qt);
1289 * creates the standard "Forward" info at the top of the forwarded message
1292 function getForwardHeader() {
1293 global $mod_strings;
1294 global $current_user;
1296 //$from = str_replace(array(">","<"), array(")","("), $this->from_name);
1297 $from = to_html($this->from_name);
1298 $subject = to_html($this->name);
1299 $ret = "<br /><br />";
1300 $ret .= $this->replyDelimiter."{$mod_strings['LBL_FROM']} {$from}<br />";
1301 $ret .= $this->replyDelimiter."{$mod_strings['LBL_DATE_SENT']} {$this->date_sent}<br />";
1302 $ret .= $this->replyDelimiter."{$mod_strings['LBL_TO']} {$this->to_addrs}<br />";
1303 $ret .= $this->replyDelimiter."{$mod_strings['LBL_CC']} {$this->cc_addrs}<br />";
1304 $ret .= $this->replyDelimiter."{$mod_strings['LBL_SUBJECT']} {$subject}<br />";
1305 $ret .= $this->replyDelimiter."<br />";
1308 //return from_html($ret);
1312 * retrieves Notes that belong to this Email and stuffs them into the "attachments" attribute
1314 function getNotes($id, $duplicate=false) {
1315 if(!class_exists('Note')) {
1319 $exRemoved = array();
1320 if(isset($_REQUEST['removeAttachment'])) {
1321 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1324 $noteArray = array();
1325 $q = "SELECT id FROM notes WHERE parent_id = '".$id."'";
1326 $r = $this->db->query($q);
1328 while($a = $this->db->fetchByAssoc($r)) {
1329 if(!in_array($a['id'], $exRemoved)) {
1331 $note->retrieve($a['id']);
1333 // duplicate actual file when creating forwards
1335 if(!class_exists('UploadFile')) {
1336 require_once('include/upload_file.php');
1338 // save a brand new Note
1339 $noteDupe->id = create_guid();
1340 $noteDupe->new_with_id = true;
1341 $noteDupe->parent_id = $this->id;
1342 $noteDupe->parent_type = $this->module_dir;
1344 $noteFile = new UploadFile('none');
1345 $noteFile->duplicate_file($a['id'], $note->id, $note->filename);
1349 // add Note to attachments array
1350 $this->attachments[] = $note;
1356 * creates the standard "Reply" info at the top of the forwarded message
1359 function getReplyHeader() {
1360 global $mod_strings;
1361 global $current_user;
1363 $from = str_replace(array(">","<", ">","<"), array(")","(",")","("), $this->from_name);
1364 $ret = "<br>{$mod_strings['LBL_REPLY_HEADER_1']} {$this->date_start}, {$this->time_start}, {$from} {$mod_strings['LBL_REPLY_HEADER_2']}";
1366 return from_html($ret);
1370 * Quotes plain-text email text
1371 * @param string $text
1374 function quotePlainTextEmail($text) {
1378 $desc = nl2br(trim($text));
1379 $exDesc = explode('<br />', $desc);
1381 foreach($exDesc as $k => $line) {
1382 $quoted .= '> '.trim($line)."\r";
1389 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1390 * @param string $text HTML text to quote
1393 function quoteHtmlEmail($text) {
1394 $text = trim(from_html($text));
1399 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1405 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1406 * @param string $text HTML text to quote
1409 function quoteHtmlEmailForNewEmailUI($text) {
1410 $text = trim($text);
1415 $text = str_replace("\n", "\n<BR/>", $text);
1416 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1423 ///////////////////////////////////////////////////////////////////////////
1426 * Safes description text (both HTML and Plain Text) for display
1427 * @param string str The text to safe
1428 * @return string Safed text
1430 function safeText($str) {
1432 $this->safe->clear();
1433 $ret = $this->safe->parse($str);
1435 // Julian's XSS cleaner
1436 $potentials = clean_xss($str, false);
1438 if(is_array($potentials) && !empty($potentials)) {
1439 //_ppl($potentials);
1440 foreach($potentials as $bad) {
1441 $ret = str_replace($bad, "", $ret);
1445 // clean <HTML> and <BODY> tags
1446 $html = '#<\\\\\?HTML[\w =\'\"\&]*>#sim';
1447 $body = '#<\\\\\?BODY[\w =\'\"\&]*>#sim';
1449 $ret = preg_replace($html, "", $ret);
1450 $ret = preg_replace($body, "", $ret);
1456 * Ensures that the user is able to send outbound emails
1458 function check_email_settings() {
1459 global $current_user;
1461 $mail_fromaddress = $current_user->emailAddress->getPrimaryAddress($current_user);
1462 $replyToName = $current_user->getPreference('mail_fromname');
1463 $mail_fromname = (!empty($replyToName)) ? $current_user->getPreference('mail_fromname') : $current_user->full_name;
1465 if(empty($mail_fromaddress)) {
1468 if(empty($mail_fromname)) {
1472 $send_type = $current_user->getPreference('mail_sendtype') ;
1473 if (!empty($send_type) && $send_type == "SMTP") {
1474 $mail_smtpserver = $current_user->getPreference('mail_smtpserver');
1475 $mail_smtpport = $current_user->getPreference('mail_smtpport');
1476 $mail_smtpauth_req = $current_user->getPreference('mail_smtpauth_req');
1477 $mail_smtpuser = $current_user->getPreference('mail_smtpuser');
1478 $mail_smtppass = $current_user->getPreference('mail_smtppass');
1479 if (empty($mail_smtpserver) ||
1480 empty($mail_smtpport) ||
1481 (!empty($mail_smtpauth_req) && ( empty($mail_smtpuser) || empty($mail_smtppass)))
1490 * outputs JS to set fields in the MassUpdate form in the "My Inbox" view
1492 function js_set_archived() {
1493 global $mod_strings;
1495 <script type="text/javascript" language="JavaScript"><!-- Begin
1496 function setArchived() {
1497 var form = document.getElementById("MassUpdate");
1498 var status = document.getElementById("mass_status");
1501 for(var i=0; i < form.elements.length; i++) {
1502 if(form.elements[i].name == "mass[]") {
1503 if(form.elements[i].checked == true) {
1510 var user = document.getElementById("mass_assigned_user_name");
1511 var team = document.getElementById("team");
1514 for(var j=0; j<status.length; j++) {
1515 if(status.options[j].value == "archived") {
1516 status.options[j].selected = true;
1517 status.selectedIndex = j; // for IE
1523 alert("'.$mod_strings['ERR_ARCHIVE_EMAIL'].'");
1527 // End --></script>';
1532 * replaces the javascript in utils.php - more specialized
1534 function u_get_clear_form_js($type='', $group='', $assigned_user_id='') {
1537 $uAssigned_user_id = '';
1539 if(!empty($type)) { $uType = '&type='.$type; }
1540 if(!empty($group)) { $uGroup = '&group='.$group; }
1541 if(!empty($assigned_user_id)) { $uAssigned_user_id = '&assigned_user_id='.$assigned_user_id; }
1544 <script type="text/javascript" language="JavaScript"><!-- Begin
1545 function clear_form(form) {
1546 var newLoc = "index.php?action=" + form.action.value + "&module=" + form.module.value + "&query=true&clear_query=true'.$uType.$uGroup.$uAssigned_user_id.'";
1547 if(typeof(form.advanced) != "undefined"){
1548 newLoc += "&advanced=" + form.advanced.value;
1550 document.location.href= newLoc;
1552 // End --></script>';
1556 function pickOneButton() {
1558 global $mod_strings;
1559 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_GRAB_TITLE'].'"
1560 accessKey="'.$mod_strings['LBL_BUTTON_GRAB_KEY'].'"
1562 type="button" name="button"
1563 onClick="window.location=\'index.php?module=Emails&action=Grab\';"
1564 style="margin-bottom:2px"
1565 value=" '.$mod_strings['LBL_BUTTON_GRAB'].' "></div>';
1570 * Determines what Editor (HTML or Plain-text) the current_user uses;
1571 * @return string Editor type
1573 function getUserEditorPreference() {
1574 global $sugar_config;
1575 global $current_user;
1579 if(!isset($sugar_config['email_default_editor'])) {
1580 $sugar_config = $current_user->setDefaultsInConfig();
1583 $userEditor = $current_user->getPreference('email_editor_option');
1584 $systemEditor = $sugar_config['email_default_editor'];
1586 if($userEditor != '') {
1587 $editor = $userEditor;
1589 $editor = $systemEditor;
1596 * takes the mess we pass from EditView and tries to create some kind of order
1597 * @param array addrs
1598 * @param array addrs_ids (from contacts)
1599 * @param array addrs_names (from contacts);
1600 * @param array addrs_emails (from contacts);
1601 * @return array Parsed assoc array to feed to PHPMailer
1603 function parse_addrs($addrs, $addrs_ids, $addrs_names, $addrs_emails) {
1604 // cn: bug 9406 - enable commas to separate email addresses
1605 $addrs = str_replace(",", ";", $addrs);
1607 $ltgt = array('<','>');
1608 $gtlt = array('<','>');
1611 $addrs = str_replace($ltgt, '', $addrs);
1612 $addrs_arr = explode(";",$addrs);
1613 $addrs_arr = $this->remove_empty_fields($addrs_arr);
1614 $addrs_ids_arr = explode(";",$addrs_ids);
1615 $addrs_ids_arr = $this->remove_empty_fields($addrs_ids_arr);
1616 $addrs_emails_arr = explode(";",$addrs_emails);
1617 $addrs_emails_arr = $this->remove_empty_fields($addrs_emails_arr);
1618 $addrs_names_arr = explode(";",$addrs_names);
1619 $addrs_names_arr = $this->remove_empty_fields($addrs_names_arr);
1621 ///////////////////////////////////////////////////////////////////////
1622 //// HANDLE EMAILS HAND-WRITTEN
1623 $contactRecipients = array();
1624 $knownEmails = array();
1626 foreach($addrs_arr as $i => $v) {
1628 continue; // skip any "blanks" - will always have 1
1630 $recipient = array();
1632 //// get the email to see if we're dealing with a dupe
1633 //// what crappy coding
1634 preg_match("/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i",$v, $match);
1636 if(!empty($match[0]) && !in_array(trim($match[0]), $knownEmails)) {
1637 $knownEmails[] = $match[0];
1638 $recipient['email'] = $match[0];
1640 //// handle the Display name
1641 $display = trim(str_replace($match[0], '', $v));
1643 //// only trigger a "displayName" <email@address> when necessary
1644 if(isset($addrs_names_arr[$i])){
1645 $recipient['display'] = $addrs_names_arr[$i];
1647 else if(!empty($display)) {
1648 $recipient['display'] = $display;
1650 if(isset($addrs_ids_arr[$i]) && $addrs_emails_arr[$i] == $match[0]){
1651 $recipient['contact_id'] = $addrs_ids_arr[$i];
1653 $return[] = $recipient;
1660 function remove_empty_fields(&$arr) {
1663 foreach($arr as $field) {
1664 $field = trim($field);
1668 array_push($newarr,$field);
1674 * handles attachments of various kinds when sending email
1676 function handleAttachments() {
1681 global $mod_strings;
1683 ///////////////////////////////////////////////////////////////////////////
1684 //// ATTACHMENTS FROM DRAFTS
1685 if(($this->type == 'out' || $this->type == 'draft') && $this->status == 'draft' && isset($_REQUEST['record'])) {
1686 $this->getNotes($_REQUEST['record']); // cn: get notes from OLD email for use in new email
1688 //// END ATTACHMENTS FROM DRAFTS
1689 ///////////////////////////////////////////////////////////////////////////
1691 ///////////////////////////////////////////////////////////////////////////
1692 //// ATTACHMENTS FROM FORWARDS
1693 // Bug 8034 Jenny - Need the check for type 'draft' here to handle cases where we want to save
1694 // forwarded messages as drafts. We still need to save the original message's attachments.
1695 if(($this->type == 'out' || $this->type == 'draft') &&
1696 isset($_REQUEST['origType']) && $_REQUEST['origType'] == 'forward' &&
1697 isset($_REQUEST['return_id']) && !empty($_REQUEST['return_id'])
1699 $this->getNotes($_REQUEST['return_id'], true);
1702 // cn: bug 8034 - attachments from forward/replies lost when saving in draft
1703 if(isset($_REQUEST['prior_attachments']) && !empty($_REQUEST['prior_attachments']) && $this->new_with_id == true) {
1704 $exIds = explode(",", $_REQUEST['prior_attachments']);
1705 if(!isset($_REQUEST['template_attachment'])) {
1706 $_REQUEST['template_attachment'] = array();
1708 $_REQUEST['template_attachment'] = array_merge($_REQUEST['template_attachment'], $exIds);
1710 //// END ATTACHMENTS FROM FORWARDS
1711 ///////////////////////////////////////////////////////////////////////////
1713 ///////////////////////////////////////////////////////////////////////////
1714 //// ATTACHMENTS FROM TEMPLATES
1715 // to preserve individual email integrity, we must dupe Notes and associated files
1716 // for each outbound email - good for integrity, bad for filespace
1717 if(isset($_REQUEST['template_attachment']) && !empty($_REQUEST['template_attachment'])) {
1718 $removeArr = array();
1719 $noteArray = array();
1721 if(isset($_REQUEST['temp_remove_attachment']) && !empty($_REQUEST['temp_remove_attachment'])) {
1722 $removeArr = $_REQUEST['temp_remove_attachment'];
1726 foreach($_REQUEST['template_attachment'] as $noteId) {
1727 if(in_array($noteId, $removeArr)) {
1730 $noteTemplate = new Note();
1731 $noteTemplate->retrieve($noteId);
1732 $noteTemplate->id = create_guid();
1733 $noteTemplate->new_with_id = true; // duplicating the note with files
1734 $noteTemplate->parent_id = $this->id;
1735 $noteTemplate->parent_type = $this->module_dir;
1736 $noteTemplate->date_entered = '';
1737 $noteTemplate->save();
1739 $noteFile = new UploadFile('none');
1740 $noteFile->duplicate_file($noteId, $noteTemplate->id, $noteTemplate->filename);
1741 $noteArray[] = $noteTemplate;
1743 $this->attachments = array_merge($this->attachments, $noteArray);
1745 //// END ATTACHMENTS FROM TEMPLATES
1746 ///////////////////////////////////////////////////////////////////////////
1748 ///////////////////////////////////////////////////////////////////////////
1749 //// ADDING NEW ATTACHMENTS
1750 $max_files_upload = 10;
1751 // Jenny - Bug 8211 Since attachments for drafts have already been processed,
1752 // we don't need to re-process them.
1753 if($this->status != "draft") {
1754 $notes_list = array();
1755 if(!empty($this->id) && !$this->new_with_id) {
1757 $where = "notes.parent_id='{$this->id}'";
1758 $notes_list = $note->get_full_list("", $where, true);
1760 $this->attachments = array_merge($this->attachments, $notes_list);
1762 // cn: Bug 5995 - rudimentary error checking
1763 $filesError = array(
1764 0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
1765 1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
1766 2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
1767 3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
1768 4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
1769 5 => 'UNKNOWN ERROR',
1770 6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
1771 7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
1774 for($i = 0; $i < $max_files_upload; $i++) {
1775 // cn: Bug 5995 - rudimentary error checking
1776 if (!isset($_FILES["email_attachment{$i}"])) {
1777 $GLOBALS['log']->debug("Email Attachment {$i} does not exist.");
1780 if($_FILES['email_attachment'.$i]['error'] != 0 && $_FILES['email_attachment'.$i]['error'] != 4) {
1781 $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment'.$i]['error']]);
1786 $note->parent_id = $this->id;
1787 $note->parent_type = $this->module_dir;
1788 $upload_file = new UploadFile('email_attachment'.$i);
1790 if(empty($upload_file)) {
1794 if(isset($_FILES['email_attachment'.$i]) && $upload_file->confirm_upload()) {
1795 $note->filename = $upload_file->get_stored_file_name();
1796 $note->file = $upload_file;
1797 $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$note->file->original_file_name;
1799 $this->attachments[] = $note;
1803 $this->saved_attachments = array();
1804 foreach($this->attachments as $note) {
1805 if(!empty($note->id)) {
1806 array_push($this->saved_attachments, $note);
1809 $note->parent_id = $this->id;
1810 $note->parent_type = 'Emails';
1811 $note->file_mime_type = $note->file->mime_type;
1812 $note_id = $note->save();
1814 $this->saved_attachments[] = $note;
1816 $note->id = $note_id;
1817 $note->file->final_move($note->id);
1819 //// END NEW ATTACHMENTS
1820 ///////////////////////////////////////////////////////////////////////////
1822 ///////////////////////////////////////////////////////////////////////////
1823 //// ATTACHMENTS FROM DOCUMENTS
1824 for($i=0; $i<10; $i++) {
1825 if(isset($_REQUEST['documentId'.$i]) && !empty($_REQUEST['documentId'.$i])) {
1826 $doc = new Document();
1827 $docRev = new DocumentRevision();
1828 $docNote = new Note();
1829 $noteFile = new UploadFile('none');
1831 $doc->retrieve($_REQUEST['documentId'.$i]);
1832 $docRev->retrieve($doc->document_revision_id);
1834 $this->saved_attachments[] = $docRev;
1836 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
1837 $docNote->name = $docRev->getDocumentRevisionNameForDisplay();
1838 $docNote->filename = $docRev->filename;
1839 $docNote->description = $doc->description;
1840 $docNote->parent_id = $this->id;
1841 $docNote->parent_type = 'Emails';
1842 $docNote->file_mime_type = $docRev->file_mime_type;
1843 $docId = $docNote = $docNote->save();
1845 $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
1849 //// END ATTACHMENTS FROM DOCUMENTS
1850 ///////////////////////////////////////////////////////////////////////////
1852 ///////////////////////////////////////////////////////////////////////////
1853 //// REMOVE ATTACHMENTS
1854 if(isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
1855 foreach($_REQUEST['remove_attachment'] as $noteId) {
1856 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1857 $this->db->query($q);
1861 //this will remove attachments that have been selected to be removed from drafts.
1862 if(isset($_REQUEST['removeAttachment']) && !empty($_REQUEST['removeAttachment'])) {
1863 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1864 foreach($exRemoved as $noteId) {
1865 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1866 $this->db->query($q);
1869 //// END REMOVE ATTACHMENTS
1870 ///////////////////////////////////////////////////////////////////////////
1875 * Determines if an email body (HTML or Plain) has a User signature already in the content
1876 * @param array Array of signatures
1879 function hasSignatureInBody($sig) {
1880 // strpos can't handle line breaks - normalize
1881 $html = $this->removeAllNewlines($this->description_html);
1882 $htmlSig = $this->removeAllNewlines($sig['signature_html']);
1883 $plain = $this->removeAllNewlines($this->description);
1884 $plainSig = $this->removeAllNewlines($sig['signature']);
1886 // cn: bug 11621 - empty sig triggers notice error
1887 if(!empty($htmlSig) && false !== strpos($html, $htmlSig)) {
1889 } elseif(!empty($plainSig) && false !== strpos($plain, $plainSig)) {
1898 * @param string String to be normalized
1901 function removeAllNewlines($str) {
1902 $bad = array("\r\n", "\n\r", "\n", "\r");
1903 $good = array('', '', '', '');
1905 return str_replace($bad, $good, strip_tags(br2nl(from_html($str))));
1911 * Set navigation anchors to aid DetailView record navigation (VCR buttons)
1912 * @param string uri The URI from the referring page (always ListView)
1913 * @return array start Array of the URI broken down with a special "current_view" for My Inbox Navs
1915 function getStartPage($uri) {
1916 if(strpos($uri, '&')) { // "&" to ensure that we can explode the GET vars - else we're gonna trigger a Notice error
1917 $serial = substr($uri, (strpos($uri, '?')+1), strlen($uri));
1918 $exUri = explode('&', $serial);
1919 $start = array('module' => '', 'action' => '', 'group' => '', 'record' => '', 'type' => '');
1921 foreach($exUri as $k => $pair) {
1922 $exPair = explode('=', $pair);
1923 $start[$exPair[0]] = $exPair[1];
1926 // specific views for current_user
1927 if(isset($start['assigned_user_id'])) {
1928 $start['current_view'] = "{$start['action']}&module={$start['module']}&assigned_user_id={$start['assigned_user_id']}&type={$start['type']}";
1938 * preps SMTP info for email transmission
1939 * @param object mail SugarPHPMailer object
1940 * @param string mailer_id
1941 * @param string ieId
1942 * @return object mail SugarPHPMailer object
1944 function setMailer($mail, $mailer_id='', $ieId='') {
1945 global $current_user;
1947 require_once("include/OutboundEmail/OutboundEmail.php");
1948 $oe = new OutboundEmail();
1949 $oe = $oe->getInboundMailerSettings($current_user, $mailer_id, $ieId);
1951 // ssl or tcp - keeping outside isSMTP b/c a default may inadvertantly set ssl://
1952 $mail->protocol = ($oe->mail_smtpssl) ? "ssl://" : "tcp://";
1953 if($oe->mail_sendtype == "SMTP")
1955 //Set mail send type information
1956 $mail->Mailer = "smtp";
1957 $mail->Host = $oe->mail_smtpserver;
1958 $mail->Port = $oe->mail_smtpport;
1959 if ($oe->mail_smtpssl == 1) {
1960 $mail->SMTPSecure = 'ssl';
1962 if ($oe->mail_smtpssl == 2) {
1963 $mail->SMTPSecure = 'tls';
1966 if($oe->mail_smtpauth_req) {
1967 $mail->SMTPAuth = TRUE;
1968 $mail->Username = $oe->mail_smtpuser;
1969 $mail->Password = $oe->mail_smtppass;
1973 $mail->Mailer = "sendmail";
1980 * preps SugarPHPMailer object for HTML or Plain text sends
1981 * @param object SugarPHPMailer instance
1983 function handleBody($mail) {
1984 global $current_user;
1985 global $sugar_config;
1986 ///////////////////////////////////////////////////////////////////////
1987 //// HANDLE EMAIL FORMAT PREFERENCE
1988 // the if() below is HIGHLY dependent on the Javascript unchecking the Send HTML Email box
1990 if( (isset($_REQUEST['setEditor']) /* from Email EditView navigation */
1991 && $_REQUEST['setEditor'] == 1
1992 && trim($_REQUEST['description_html']) != '')
1993 || trim($this->description_html) != '' /* from email templates */
1994 && $current_user->getPreference('email_editor_option', 'global') !== 'plain' //user preference is not set to plain text
1996 $this->handleBodyInHTMLformat($mail);
1999 $this->description_html = '';
2000 $mail->IsHTML(false);
2001 $plainText = from_html($this->description);
2002 $plainText = str_replace(" ", " ", $plainText);
2003 $plainText = str_replace("</p>", "</p><br />", $plainText);
2004 $plainText = strip_tags(br2nl($plainText));
2005 $plainText = str_replace("&", "&", $plainText);
2006 $plainText = str_replace("'", "'", $plainText);
2007 $mail->Body = wordwrap($plainText, 996);
2008 $mail->Body = $this->decodeDuringSend($mail->Body);
2009 $this->description = $mail->Body;
2012 // wp: if plain text version has lines greater than 998, use base64 encoding
2013 foreach(explode("\n", ($mail->ContentType == "text/html") ? $mail->AltBody : $mail->Body) as $line) {
2014 if(strlen($line) > 998) {
2015 $mail->Encoding = 'base64';
2019 //// HANDLE EMAIL FORMAT PREFERENCE
2020 ///////////////////////////////////////////////////////////////////////
2026 * Retrieve function from handlebody() to unit test easily
2028 * @return formatted $mail body
2030 function handleBodyInHTMLformat($mail) {
2031 global $current_user;
2032 global $sugar_config;
2033 // wp: if body is html, then insert new lines at 996 characters. no effect on client side
2034 // due to RFC 2822 which limits email lines to 998
2035 $mail->IsHTML(true);
2036 $body = from_html(wordwrap($this->description_html, 996));
2037 $mail->Body = $body;
2040 // new plan is to use the selected type (html or plain) to fill the other
2041 $plainText = from_html($this->description_html);
2042 $plainText = strip_tags(br2nl($plainText));
2043 $mail->AltBody = $plainText;
2044 $this->description = $plainText;
2046 $fileBasePath = "{$sugar_config['cache_dir']}images/";
2047 $filePatternSearch = "{$sugar_config['cache_dir']}";
2048 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2049 $filePatternSearch = $filePatternSearch . "images\/";
2050 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2053 preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2054 foreach($matches[0] as $match) {
2055 $filename = str_replace($fileBasePath, '', $match);
2056 $filename = urldecode(substr($filename, 0, -1));
2058 $file_location = clean_path(getcwd()."/{$sugar_config['cache_dir']}images/{$filename}");
2059 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2061 if(file_exists($file_location)) {
2062 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2066 //replace references to cache with cid tag
2067 $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2068 $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2069 // remove bad img line from outbound email
2070 $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2071 $mail->Body = preg_replace($regex, '', $mail->Body);
2073 $fileBasePath = "{$sugar_config['upload_dir']}";
2074 $filePatternSearch = "{$sugar_config['upload_dir']}";
2075 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2076 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2079 preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2080 foreach($matches[0] as $match) {
2081 $filename = str_replace($fileBasePath, '', $match);
2082 $filename = urldecode(substr($filename, 0, -1));
2084 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$filename}");
2085 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2087 if(file_exists($file_location)) {
2088 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2092 //replace references to cache with cid tag
2093 $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2094 $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2096 // remove bad img line from outbound email
2097 $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2098 $mail->Body = preg_replace($regex, '', $mail->Body);
2101 //Replace any embeded images using the secure entryPoint for src url.
2102 $noteImgRegex = "/<img[^>]*[\s]+src[^=]*=\"index.php\?entryPoint=download\&id=([^\&]*)[^>]*>/im";
2103 $embededImageMatches = array();
2104 preg_match_all($noteImgRegex, $mail->Body, $embededImageMatches,PREG_SET_ORDER);
2106 foreach ($embededImageMatches as $singleMatch )
2108 $fullMatch = $singleMatch[0];
2109 $noteId = $singleMatch[1];
2111 $filename = $noteId;
2113 //Retrieve note for mimetype
2114 $tmpNote = new Note();
2115 $tmpNote->retrieve($noteId);
2116 //Replace the src part of img tag with new cid tag
2117 $cidRegex = "/src=\"([^\"]*)\"/im";
2118 $replaceMatch = preg_replace($cidRegex, "src=\"cid:$noteId\"", $fullMatch);
2120 //Replace the body, old tag for new tag
2121 $mail->Body = str_replace($fullMatch, $replaceMatch, $mail->Body);
2124 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$noteId}");
2126 if(file_exists($file_location))
2127 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $tmpNote->file_mime_type);
2132 $mail->Body = from_html($mail->Body);
2137 * @return bool True on success
2140 global $mod_strings,$app_strings;
2141 global $current_user;
2142 global $sugar_config;
2144 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
2145 $mail = new SugarPHPMailer();
2147 foreach ($this->to_addrs_arr as $addr_arr) {
2148 if ( empty($addr_arr['display'])) {
2149 $mail->AddAddress($addr_arr['email'], "");
2151 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
2154 foreach ($this->cc_addrs_arr as $addr_arr) {
2155 if ( empty($addr_arr['display'])) {
2156 $mail->AddCC($addr_arr['email'], "");
2158 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2162 foreach ($this->bcc_addrs_arr as $addr_arr) {
2163 if ( empty($addr_arr['display'])) {
2164 $mail->AddBCC($addr_arr['email'], "");
2166 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2170 $mail = $this->setMailer($mail);
2173 if(!empty($this->from_addr)) {
2174 $mail->From = $this->from_addr;
2176 $mail->From = $current_user->getPreference('mail_fromaddress');
2177 $this->from_addr = $mail->From;
2180 if(!empty($this->from_name)) {
2181 $mail->FromName = $this->from_name;
2183 $mail->FromName = $current_user->getPreference('mail_fromname');
2184 $this->from_name = $mail->FromName;
2187 //Reply to information for case create and autoreply.
2188 if(!empty($this->reply_to_name)) {
2189 $ReplyToName = $this->reply_to_name;
2191 $ReplyToName = $mail->FromName;
2193 if(!empty($this->reply_to_addr)) {
2194 $ReplyToAddr = $this->reply_to_addr;
2196 $ReplyToAddr = $mail->From;
2198 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
2199 $mail->AddReplyTo($ReplyToAddr,$locale->translateCharsetMIME(trim($ReplyToName), 'UTF-8', $OBCharset));
2201 //$mail->Subject = html_entity_decode($this->name, ENT_QUOTES, 'UTF-8');
2202 $mail->Subject = $this->name;
2204 ///////////////////////////////////////////////////////////////////////
2206 foreach($this->saved_attachments as $note) {
2207 $mime_type = 'text/plain';
2208 if($note->object_name == 'Note') {
2209 if(!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) { // brandy-new file upload/attachment
2210 $file_location = $sugar_config['upload_dir'].$note->id;
2211 $filename = $note->file->original_file_name;
2212 $mime_type = $note->file->mime_type;
2213 } else { // attachment coming from template/forward
2214 $file_location = rawurldecode(UploadFile::get_file_path($note->filename,$note->id));
2215 // cn: bug 9723 - documents from EmailTemplates sent with Doc Name, not file name.
2216 $filename = !empty($note->filename) ? $note->filename : $note->name;
2217 $mime_type = $note->file_mime_type;
2219 } elseif($note->object_name == 'DocumentRevision') { // from Documents
2220 $filePathName = $note->id;
2221 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
2222 $filename = $note->getDocumentRevisionNameForDisplay();
2223 $file_location = getcwd().'/'.$GLOBALS['sugar_config']['upload_dir'].$filePathName;
2224 $mime_type = $note->file_mime_type;
2227 // strip out the "Email attachment label if exists
2228 $filename = str_replace($mod_strings['LBL_EMAIL_ATTACHMENT'].': ', '', $filename);
2230 //is attachment in our list of bad files extensions? If so, append .txt to file location
2231 //get position of last "." in file name
2232 $file_ext_beg = strrpos($file_location,".");
2234 //get file extension
2235 if($file_ext_beg >0){
2236 $file_ext = substr($file_location, $file_ext_beg+1 );
2238 //check to see if this is a file with extension located in "badext"
2239 foreach($sugar_config['upload_badext'] as $badExt) {
2240 if(strtolower($file_ext) == strtolower($badExt)) {
2241 //if found, then append with .txt to filename and break out of lookup
2242 //this will make sure that the file goes out with right extension, but is stored
2244 $file_location = $file_location . ".txt";
2245 break; // no need to look for more
2248 $mail->AddAttachment($file_location,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
2251 if($note->embed_flag == true) {
2253 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64',$mime_type);
2256 //// END ATTACHMENTS
2257 ///////////////////////////////////////////////////////////////////////
2259 $mail = $this->handleBody($mail);
2261 $GLOBALS['log']->debug('Email sending --------------------- ');
2263 ///////////////////////////////////////////////////////////////////////
2264 //// I18N TRANSLATION
2265 $mail->prepForOutbound();
2266 //// END I18N TRANSLATION
2267 ///////////////////////////////////////////////////////////////////////
2270 ///////////////////////////////////////////////////////////////////
2271 //// INBOUND EMAIL HANDLING
2273 if(!empty($_REQUEST['inbound_email_id'])) {
2274 $ieMail = new Email();
2275 $ieMail->retrieve($_REQUEST['inbound_email_id']);
2276 $ieMail->status = 'replied';
2279 $GLOBALS['log']->debug(' --------------------- buh bye -- sent successful');
2280 //// END INBOUND EMAIL HANDLING
2281 ///////////////////////////////////////////////////////////////////
2284 $GLOBALS['log']->debug($app_strings['LBL_EMAIL_ERROR_PREPEND'].$mail->ErrorInfo);
2289 function listviewACLHelper(){
2290 $array_assign = parent::listviewACLHelper();
2292 if(!empty($this->parent_name)){
2294 if(!empty($this->parent_name_owner)){
2295 global $current_user;
2296 $is_owner = $current_user->id == $this->parent_name_owner;
2299 if(!ACLController::moduleSupportsACL($this->parent_type) || ACLController::checkAccess($this->parent_type, 'view', $is_owner)){
2300 $array_assign['PARENT'] = 'a';
2302 $array_assign['PARENT'] = 'span';
2305 if(!empty($this->contact_name)) {
2306 if(!empty($this->contact_name_owner)) {
2307 global $current_user;
2308 $is_owner = $current_user->id == $this->contact_name_owner;
2311 if(ACLController::checkAccess('Contacts', 'view', $is_owner)) {
2312 $array_assign['CONTACT'] = 'a';
2314 $array_assign['CONTACT'] = 'span';
2317 return $array_assign;
2320 function getSystemDefaultEmail() {
2323 $r1 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromaddress\'');
2324 $r2 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromname\'');
2325 $a1 = $this->db->fetchByAssoc($r1);
2326 $a2 = $this->db->fetchByAssoc($r2);
2328 $email['email'] = $a1['value'];
2329 $email['name'] = $a2['value'];
2335 function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false) {
2337 if ($return_array) {
2338 return parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, $return_array,$parentbean, $singleSelect);
2340 $custom_join = $this->custom_fields->getJOIN();
2342 $query = "SELECT ".$this->table_name.".*, users.user_name as assigned_user_name\n";
2345 $query .= $custom_join['select'];
2347 $query .= " FROM emails\n";
2348 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2349 $query .= " LEFT JOIN emails_beans ON emails.id = emails_beans.email_id\n";
2352 $query .= " LEFT JOIN users ON emails.assigned_user_id=users.id \n";
2353 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2355 $query .= " JOIN contacts ON contacts.id= emails_beans.bean_id AND emails_beans.bean_module='Contacts' and contacts.deleted=0 \n";
2359 $query .= $custom_join['join'];
2362 if($show_deleted == 0) {
2363 $where_auto = " emails.deleted=0 \n";
2364 }else if($show_deleted == 1){
2365 $where_auto = " emails.deleted=1 \n";
2369 $query .= "WHERE $where AND ".$where_auto;
2371 $query .= "WHERE ".$where_auto;
2374 $query .= " ORDER BY $order_by";
2376 $query .= " ORDER BY date_sent DESC";
2382 function fill_in_additional_list_fields() {
2384 $this->fill_in_additional_detail_fields();
2386 $this->link_action = 'DetailView';
2387 ///////////////////////////////////////////////////////////////////////
2388 //populate attachment_image, used to display attachment icon.
2389 $query = "select 1 from notes where notes.parent_id = '$this->id' and notes.deleted = 0";
2390 $result =$this->db->query($query,true," Error filling in additional list fields: ");
2392 $row = $this->db->fetchByAssoc($result);
2395 $this->attachment_image = SugarThemeRegistry::current()->getImage('attachment',"","","");
2397 $this->attachment_image = SugarThemeRegistry::current()->getImage('blank',"","","");
2399 ///////////////////////////////////////////////////////////////////////
2400 if(empty($this->contact_id) && !empty($this->parent_id) && !empty($this->parent_type) && $this->parent_type === 'Contacts' && !empty($this->parent_name) ){
2401 $this->contact_id = $this->parent_id;
2402 $this->contact_name = $this->parent_name;
2406 function fill_in_additional_detail_fields() {
2407 global $app_list_strings,$mod_strings;
2408 // Fill in the assigned_user_name
2409 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id, '');
2410 //if ($this->parent_type == 'Contacts') {
2411 $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 ";
2412 $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";
2413 if(!empty($this->parent_id)){
2414 $query .= " AND contacts.id= '".$this->parent_id."' ";
2415 }else if(!empty($_REQUEST['record'])){
2416 $query .= " AND contacts.id= '".$_REQUEST['record']."' ";
2418 $result =$this->db->query($query,true," Error filling in additional detail fields: ");
2420 // Get the id and the name.
2421 $row = $this->db->fetchByAssoc($result);
2425 $contact = new Contact();
2426 $contact->retrieve($row['id']);
2427 $this->contact_name = $contact->full_name;
2428 $this->contact_phone = $row['phone_work'];
2429 $this->contact_id = $row['id'];
2430 $this->contact_email = $contact->emailAddress->getPrimaryAddress($contact);
2431 $this->contact_name_owner = $row['contact_name_owner'];
2432 $this->contact_name_mod = $row['contact_name_mod'];
2433 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2434 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2435 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2436 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2439 $this->contact_name = '';
2440 $this->contact_phone = '';
2441 $this->contact_id = '';
2442 $this->contact_email = '';
2443 $this->contact_name_owner = '';
2444 $this->contact_name_mod = '';
2445 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2446 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2447 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2448 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2451 $this->created_by_name = get_assigned_user_name($this->created_by);
2452 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
2454 $this->link_action = 'DetailView';
2456 if(!empty($this->type)) {
2457 if($this->type == 'out' && $this->status == 'send_error') {
2458 $this->type_name = $mod_strings['LBL_NOT_SENT'];
2460 $this->type_name = $app_list_strings['dom_email_types'][$this->type];
2463 if(($this->type == 'out' && $this->status == 'send_error') || $this->type == 'draft') {
2464 $this->link_action = 'EditView';
2468 //todo this isset( $app_list_strings['dom_email_status'][$this->status]) is hack for 3261.
2469 if(!empty($this->status) && isset( $app_list_strings['dom_email_status'][$this->status])) {
2470 $this->status_name = $app_list_strings['dom_email_status'][$this->status];
2473 if ( empty($this->name ) && empty($_REQUEST['record'])) {
2474 $this->name = $mod_strings['LBL_NO_SUBJECT'];
2477 $this->fill_in_additional_parent_fields();
2482 function create_export_query(&$order_by, &$where) {
2483 $contact_required = stristr($where, "contacts");
2484 $custom_join = $this->custom_fields->getJOIN(true, true,$where);
2486 if($contact_required) {
2487 $query = "SELECT emails.*, contacts.first_name, contacts.last_name";
2489 $query .= $custom_join['select'];
2492 $query .= " FROM contacts, emails, emails_contacts ";
2493 $where_auto = "emails_contacts.contact_id = contacts.id AND emails_contacts.email_id = emails.id AND emails.deleted=0 AND contacts.deleted=0";
2495 $query = 'SELECT emails.*';
2497 $query .= $custom_join['select'];
2500 $query .= ' FROM emails ';
2501 $where_auto = "emails.deleted=0";
2505 $query .= $custom_join['join'];
2509 $query .= "where $where AND ".$where_auto;
2511 $query .= "where ".$where_auto;
2514 $query .= " ORDER BY $order_by";
2516 $query .= " ORDER BY emails.name";
2520 function get_list_view_data() {
2521 global $app_list_strings;
2523 global $current_user;
2525 global $mod_strings;
2527 $email_fields = $this->get_list_view_array();
2528 $this->retrieveEmailText();
2529 $email_fields['FROM_ADDR'] = $this->from_addr_name;
2530 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); // hard-coding for Home screen ListView
2532 if($this->status != 'replied') {
2533 $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>';
2534 $email_fields['STATUS'] = ($email_fields['REPLY_TO_STATUS'] == 1 ? $mod_strings['LBL_REPLIED'] : $email_fields['STATUS']);
2536 $email_fields['QUICK_REPLY'] = $mod_strings['LBL_REPLIED'];
2538 if(!empty($this->parent_type)) {
2539 $email_fields['PARENT_MODULE'] = $this->parent_type;
2541 switch($this->intent) {
2543 $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>';
2547 $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>';
2551 $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>';
2555 $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>';
2559 $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>';
2572 $email_fields['CREATE_RELATED'] = $this->quickCreateForm();
2578 //BUG 17098 - MFH changed $this->from_addr to $this->to_addrs
2579 $email_fields['CONTACT_NAME'] = empty($this->contact_name) ? '</a>'.$this->trimLongTo($this->to_addrs).'<a>' : $this->contact_name;
2580 $email_fields['CONTACT_ID'] = empty($this->contact_id) ? '' : $this->contact_id;
2581 $email_fields['ATTACHMENT_IMAGE'] = $this->attachment_image;
2582 $email_fields['LINK_ACTION'] = $this->link_action;
2584 if(isset($this->type_name))
2585 $email_fields['TYPE_NAME'] = $this->type_name;
2587 return $email_fields;
2590 function quickCreateForm() {
2591 global $mod_strings, $app_strings, $currentModule, $current_language;
2593 // Coming from the home page via Dashlets
2594 if($currentModule != 'Email')
2595 $mod_strings = return_module_language($current_language, 'Emails');
2596 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>";
2600 * Searches all imported emails and returns the result set as an array.
2603 function searchImportedEmails($sort = '', $direction='')
2605 require_once('include/TimeDate.php');
2607 global $current_user;
2609 global $sugar_config;
2610 global $app_strings;
2612 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
2613 // cn: default to a low number until user specifies otherwise
2614 if(empty($emailSettings['showNumInList']))
2617 $pageSize = $emailSettings['showNumInList'];
2619 if( isset($_REQUEST['start']) && isset($_REQUEST['limit']) )
2620 $page = ceil($_REQUEST['start'] / $_REQUEST['limit']) + 1;
2624 //Determine sort ordering
2626 //Sort ordering parameters in the request do not coincide with actual column names
2627 //so we need to remap them.
2628 $hrSortLocal = array(
2629 'flagged' => 'type',
2630 'status' => 'reply_to_status',
2631 'from' => 'emails_text.from_addr',
2632 'subject' => 'name',
2633 'date' => 'date_sent',
2634 'AssignedTo' => 'assigned_user_id',
2635 'flagged' => 'flagged'
2638 $sort = !empty($_REQUEST['sort']) ? $_REQUEST['sort'] : "";
2639 $direction = !empty($_REQUEST['dir']) ? $_REQUEST['dir'] : "";
2641 $order = ( !empty($sort) && !empty($direction) ) ? " ORDER BY {$hrSortLocal[$sort]} {$direction}" : "";
2643 //Get our main query.
2644 $fullQuery = $this->_genereateSearchImportedEmailsQuery();
2646 //Perform a count query needed for pagination.
2647 $countQuery = $this->create_list_count_query($fullQuery);
2648 $count_rs = $this->db->query($countQuery, false, 'Error executing count query for imported emails search');
2649 $count_row = $this->db->fetchByAssoc($count_rs);
2650 $total_count = ($count_row != null) ? $count_row['c'] : 0;
2652 $start = ($page - 1) * $pageSize;
2655 $rs = $this->db->limitQuery($fullQuery . $order, $start, $pageSize);
2659 while($a = $this->db->fetchByAssoc($rs)) {
2661 $temp['flagged'] = (is_null($a['flagged']) || $a['flagged'] == '0') ? '' : 1;
2662 $temp['status'] = (is_null($a['reply_to_status']) || $a['reply_to_status'] == '0') ? '' : 1;
2663 $temp['subject'] = $a['name'];
2664 $temp['date'] = $timedate->to_display_date_time($a['date_sent']);
2665 $temp['uid'] = $a['id'];
2666 $temp['ieId'] = $a['mailbox_id'];
2667 $temp['site_url'] = $sugar_config['site_url'];
2668 $temp['seen'] = ($a['status'] == 'unread') ? 0 : 1;
2669 $temp['type'] = $a['type'];
2670 $temp['mbox'] = 'sugar::Emails';
2671 $temp['hasAttach'] = $this->doesImportedEmailHaveAttachment($a['id']);
2672 //To and from addresses may be stored in emails_text, if nothing is found, revert to
2673 //regular email addresses.
2674 $temp['to_addrs'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['to_addrs']);
2675 $temp['from'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['from_addr']);
2676 if( empty($temp['from']) || empty($temp['to_addrs']) )
2678 //Retrieve email addresses seperatly.
2679 $tmpEmail = new Email();
2680 $tmpEmail->id = $a['id'];
2681 $tmpEmail->retrieveEmailAddresses();
2682 $temp['from'] = $tmpEmail->from_addr;
2683 $temp['to_addrs'] = $tmpEmail->to_addrs;
2689 $metadata = array();
2690 $metadata['totalCount'] = $total_count;
2691 $metadata['out'] = $return;
2697 * Determine if an imported email has an attachment by examining the relationship to notes.
2702 function doesImportedEmailHaveAttachment($id)
2704 $hasAttachment = FALSE;
2705 $query = "SELECT id FROM notes where parent_id='$id' AND parent_type='Emails' AND file_mime_type is not null AND deleted=0";
2706 $rs = $this->db->limitQuery($query, 0, 1);
2707 $row = $this->db->fetchByAssoc($rs);
2708 if( !empty($row['id']) )
2709 $hasAttachment = TRUE;
2711 return (int) $hasAttachment;
2715 * Generate the query used for searching imported emails.
2717 * @return String Query to be executed.
2719 function _genereateSearchImportedEmailsQuery()
2723 $additionalWhereClause = $this->_generateSearchImportWhereClause();
2727 $query['select'] = "emails.id , emails.mailbox_id, emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status,
2728 emails_text.from_addr, emails_text.to_addrs FROM emails ";
2730 $query['joins'] = " JOIN emails_text on emails.id = emails_text.email_id ";
2732 //Handle from and to addr joins
2733 if( !empty($_REQUEST['from_addr']) )
2735 $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
2736 AND er_from.address_type='from' AND ea_from.email_address='" . strtolower($_REQUEST['from_addr']) . "'";
2739 if( !empty($_REQUEST['to_addrs']) )
2741 $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
2742 AND er_to.address_type='to' AND ea_to.email_address='" . strtolower($_REQUEST['to_addrs']) . "'";
2745 $query['where'] = " WHERE (emails.type= 'inbound' OR emails.type='archived' OR emails.type='out') AND emails.deleted = 0 ";
2746 if( !empty($additionalWhereClause) )
2747 $query['where'] .= "AND $additionalWhereClause";
2749 //If we are explicitly looking for attachments. Do not use a distinct query as the to_addr is defined
2750 //as a text which equals clob in oracle and the distinct query can not be executed correctly.
2751 $addDistinctKeyword = "";
2752 if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 1) //1 indicates yes
2753 $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 )";
2754 else if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 2 )
2755 $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 )";
2757 $fullQuery = "SELECT " . $query['select'] . " " . $query['joins'] . " " . $query['where'];
2762 * Generate the where clause for searching imported emails.
2765 function _generateSearchImportWhereClause()
2769 //The clear button was removed so if a user removes the asisgned user name, do not process the id.
2770 if( empty($_REQUEST['assigned_user_name']) && !empty($_REQUEST['assigned_user_id']) )
2771 unset($_REQUEST['assigned_user_id']);
2773 $availableSearchParam = array('name' => array('table_name' =>'emails'),
2774 'data_parent_id_search' => array('table_name' =>'emails','db_key' => 'parent_id','opp' => '='),
2775 'assigned_user_id' => array('table_name' => 'emails', 'opp' => '=') );
2777 $additionalWhereClause = array();
2778 foreach ($availableSearchParam as $key => $properties)
2780 if( !empty($_REQUEST[$key]) )
2782 $db_key = isset($properties['db_key']) ? $properties['db_key'] : $key;
2783 $searchValue = $_REQUEST[$key];
2785 $opp = isset($properties['opp']) ? $properties['opp'] : 'like';
2787 $searchValue = $searchValue . "%";
2789 $additionalWhereClause[] = "{$properties['table_name']}.$db_key $opp '$searchValue' ";
2793 $isDateFromSearchSet = !empty($_REQUEST['searchDateFrom']);
2794 $isdateToSearchSet = !empty($_REQUEST['searchDateTo']);
2796 $bothDateRangesSet = $isDateFromSearchSet & $isdateToSearchSet;
2798 //Hanlde date from and to seperately
2799 if($bothDateRangesSet)
2801 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2802 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2804 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2805 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2807 $additionalWhereClause[] = "( emails.date_sent >= $dbFormatDateFrom AND
2808 emails.date_sent <= $dbFormatDateTo )";
2810 elseif ($isdateToSearchSet)
2812 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2813 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2814 $additionalWhereClause[] = "emails.date_sent <= $dbFormatDateTo ";
2816 elseif ($isDateFromSearchSet)
2818 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2819 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2820 $additionalWhereClause[] = "emails.date_sent >= $dbFormatDateFrom ";
2823 $additionalWhereClause = implode(" AND ", $additionalWhereClause);
2825 return $additionalWhereClause;
2831 * takes a long TO: string of emails and returns the first appended by an
2834 function trimLongTo($str) {
2835 if(strpos($str, ',')) {
2836 $exStr = explode(',', $str);
2837 return $exStr[0].'...';
2838 } elseif(strpos($str, ';')) {
2839 $exStr = explode(';', $str);
2840 return $exStr[0].'...';
2846 function get_summary_text() {
2852 function distributionForm($where) {
2853 global $app_list_strings;
2854 global $app_strings;
2855 global $mod_strings;
2857 global $current_user;
2859 $distribution = get_select_options_with_id($app_list_strings['dom_email_distribution'], '');
2860 $_SESSION['distribute_where'] = $where;
2863 $out = '<form name="Distribute" id="Distribute">';
2864 $out .= get_form_header($mod_strings['LBL_DIST_TITLE'], '', false);
2871 <table cellpadding="0" cellspacing="0" width="100%" border="0">
2874 <script type="text/javascript">
2877 function checkDeps(form) {
2881 function mySubmit() {
2882 var assform = document.getElementById("Distribute");
2883 var select = document.getElementById("userSelect");
2884 var assign1 = assform.r1.checked;
2885 var assign2 = assform.r2.checked;
2886 var dist = assform.dm.value;
2890 var warn1 = "'.$mod_strings['LBL_WARN_NO_USERS'].'";
2893 if(assign1 || assign2) {
2898 for(i=0; i<select.options.length; i++) {
2899 if(select.options[i].selected == true) {
2908 warn2 = "'.$mod_strings['LBL_WARN_NO_DIST'].'";
2911 if(assign && users && rules) {
2913 if(document.getElementById("r1").checked) {
2914 var mu = document.getElementById("MassUpdate");
2917 for(i=0; i<mu.elements.length; i++) {
2918 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name.value != "massall") {
2919 if(grabbed != "") { grabbed += "::"; }
2920 grabbed += mu.elements[i].value;
2923 var formgrab = document.getElementById("grabbed");
2924 formgrab.value = grabbed;
2928 alert("'.$mod_strings['LBL_ASSIGN_WARN'].'" + "\n" + warn1 + "\n" + warn2);
2932 function submitDelete() {
2933 if(document.getElementById("r1").checked) {
2934 var mu = document.getElementById("MassUpdate");
2937 for(i=0; i<mu.elements.length; i++) {
2938 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name != "massall") {
2939 if(grabbed != "") { grabbed += "::"; }
2940 grabbed += mu.elements[i].value;
2943 var formgrab = document.getElementById("grabbed");
2944 formgrab.value = grabbed;
2947 alert("'.$mod_strings['LBL_MASS_DELETE_ERROR'].'");
2949 document.getElementById("Distribute").submit();
2954 <input type="hidden" name="module" value="Emails">
2955 <input type="hidden" name="action" id="action">
2956 <input type="hidden" name="grabbed" id="grabbed">
2958 <table cellpadding="1" cellspacing="0" width="100%" border="0" class="edit view">
2960 <td scope="col" scope="row" NOWRAP align="center">
2961 '.$mod_strings['LBL_ASSIGN_SELECTED_RESULTS_TO'].' ';
2962 $out .= $this->userSelectTable();
2964 <td scope="col" scope="row" NOWRAP align="left">
2965 '.$mod_strings['LBL_USING_RULES'].'
2966 <select name="distribute_method" id="dm" onChange="checkDeps(this.form);">'.$distribution.'</select>
2975 <td scope="col" width="50%" scope="row" NOWRAP align="right" colspan="2">
2976 <input title="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_TITLE'].'"
2978 accessKey="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_KEY'].'"
2979 class="button" onClick="AjaxObject.detailView.handleAssignmentDialogAssignAction();"
2980 type="button" name="button"
2981 value=" '.$mod_strings['LBL_BUTTON_DISTRIBUTE'].' ">';
2991 function userSelectTable() {
2993 global $mod_strings;
2996 $setTeamUserFunction = '';
3000 $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");
3002 $userTable = '<table cellpadding="0" cellspacing="0" border="0">';
3003 $userTable .= '<tr><td colspan="2"><b>'.$mod_strings['LBL_USER_SELECT'].'</b></td></tr>';
3004 $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>';
3005 $userTable .= '<tr><td colspan="2"><select style="visibility:hidden;" name="users[]" id="userSelect" multiple size="12">';
3007 while($a = $this->db->fetchByAssoc($r)) {
3008 $userTable .= '<option value="'.$a['id'].'" id="'.$a['id'].'">'.$a['first_name'].' '.$a['last_name'].'</option>';
3010 $userTable .= '</select></td></tr>';
3011 $userTable .= '</table>';
3013 $out = '<script type="text/javascript">';
3014 $out .= $setTeamUserFunction;
3016 function setCheckMark() {
3017 var select = document.getElementById("userSelect");
3019 for(i=0 ; i<select.options.length; i++) {
3020 if(select.options[i].selected == true) {
3021 document.getElementById("checkMark").style.display="";
3026 document.getElementById("checkMark").style.display="none";
3030 function showUserSelect() {
3031 var targetTable = document.getElementById("user_select");
3032 targetTable.style.visibility="visible";
3033 var userSelectTable = document.getElementById("userSelect");
3034 userSelectTable.style.visibility="visible";
3037 function hideUserSelect() {
3038 var targetTable = document.getElementById("user_select");
3039 targetTable.style.visibility="hidden";
3040 var userSelectTable = document.getElementById("userSelect");
3041 userSelectTable.style.visibility="hidden";
3044 function toggleAll(toggle) {
3045 if(toggle.checked) {
3050 var form = document.getElementById("userSelect");
3051 for(i=0; i<form.options.length; i++) {
3052 form.options[i].selected = stat;
3058 <span id="showUsersDiv" style="position:relative;">
3059 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
3060 <img border="0" src="'.SugarThemeRegistry::current()->getImageURL('Users.gif').'"></a>
3061 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
3062 <span style="display:none;" id="checkMark"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('check_inline.gif').'"></span>
3066 <div id="user_select" style="width:200px;position:absolute;left:2;top:2;visibility:hidden;z-index:1000;">
3067 <table cellpadding="0" cellspacing="0" border="0" class="list view">
3069 <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\';">
3070 <a href="#" onClick="javascript:hideUserSelect();"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('close.gif').'"></a>
3071 '.$mod_strings['LBL_USER_SELECT'].'
3075 //<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\';">
3076 $out .= ' <td style="padding:5px" class="oddListRowS1" bgcolor="#fdfdfd" valign="top" align="left" style="left:0;top:0;">
3085 function checkInbox($type) {
3087 global $mod_strings;
3088 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_CHECK_TITLE'].'"
3089 accessKey="'.$mod_strings['LBL_BUTTON_CHECK_KEY'].'"
3091 type="button" name="button"
3092 onClick="window.location=\'index.php?module=Emails&action=Check&type='.$type.'\';"
3093 style="margin-bottom:2px"
3094 value=" '.$mod_strings['LBL_BUTTON_CHECK'].' "></div>';
3099 * Guesses Primary Parent id from From: email address. Cascades guesses from Accounts to Contacts to Leads to
3100 * Users. This will not affect the many-to-many relationships already constructed as this is, at best,
3101 * informational linking.
3103 function fillPrimaryParentFields() {
3104 if(empty($this->from_addr))
3107 $GLOBALS['log']->debug("*** Email trying to guess Primary Parent from address [ {$this->from_addr} ]");
3109 $tables = array('accounts');
3111 // loop through types to get hits
3112 foreach($tables as $table) {
3113 $q = "SELECT name, id FROM {$table} WHERE email1 = '{$this->from_addr}' OR email2 = '{$this->from_addr}' AND deleted = 0";
3114 $r = $this->db->query($q);
3115 while($a = $this->db->fetchByAssoc($r)) {
3116 if(!empty($a['name']) && !empty($a['id'])) {
3117 $this->parent_type = ucwords($table);
3118 $this->parent_id = $a['id'];
3119 $this->parent_name = $a['name'];