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', $fromname = '') {
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;
388 if ($fromname != '') {
389 $mail->FromName = html_entity_decode($fromname,ENT_QUOTES);
391 $mail->FromName = $current_user->name;
394 $mail->Sender = $mail->From;
395 $mail->AddAddress($toaddress);
396 $mail->Body = $mod_strings['LBL_TEST_EMAIL_BODY'];
402 $return['status'] = false;
403 $return['errorMessage'] = $app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo;
406 $return['status'] = true;
410 function decodeDuringSend($htmlData) {
411 $htmlData = str_replace("sugarLessThan", "<", $htmlData);
412 $htmlData = str_replace("sugarGreaterThan", ">", $htmlData);
417 * Returns true or false if this email is a draft.
419 * @param array $request
420 * @return bool True indicates this email is a draft.
422 function isDraftEmail($request)
424 return ( isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft') );
428 * Sends Email for Email 2.0
430 function email2Send($request) {
433 global $current_user;
434 global $sugar_config;
439 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
441 /**********************************************************************
447 if(!empty($this->id)) {
448 $orignialId = $this->id;
451 if(empty($this->id)) {
452 $this->id = create_guid();
453 $this->new_with_id = true;
456 /* satisfy basic HTML email requirements */
457 $this->name = $request['sendSubject'];
458 $this->description_html = '<html><body>'.$request['sendDescription'].'</body></html>';
460 /**********************************************************************
463 $mail = new SugarPHPMailer();
464 $mail = $this->setMailer($mail, '', $_REQUEST['fromAccount']);
465 if (empty($mail->Host) && !$this->isDraftEmail($request))
467 $this->status = 'send_error';
469 if ($mail->oe->type == 'system')
470 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_SYSTEM_OUTBOUND']);
472 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_PERSONAL_OUTBOUND']);
477 $subject = $this->name;
478 $mail->Subject = from_html($this->name);
480 // work-around legacy code in SugarPHPMailer
481 if($_REQUEST['setEditor'] == 1) {
482 $_REQUEST['description_html'] = $_REQUEST['sendDescription'];
483 $this->description_html = $_REQUEST['description_html'];
485 $this->description_html = '';
486 $this->description = $_REQUEST['sendDescription'];
490 if ( $this->isDraftEmail($request) )
492 if($this->type != 'draft' && $this->status != 'draft') {
493 $this->id = create_guid();
494 $this->new_with_id = true;
495 $this->date_entered = "";
497 $q1 = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$this->id}'";
498 $r1 = $this->db->query($q1);
501 if (isset($request['saveDraft'])) {
502 $this->type = 'draft';
503 $this->status = 'draft';
506 /* Apply Email Templates */
507 // do not parse email templates if the email is being saved as draft....
508 $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']);
509 $sea = new SugarEmailAddress();
510 $object_arr = array();
512 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
513 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) &&
514 ($_REQUEST['parent_type'] == 'Accounts' ||
515 $_REQUEST['parent_type'] == 'Contacts' ||
516 $_REQUEST['parent_type'] == 'Leads' ||
517 $_REQUEST['parent_type'] == 'Users' ||
518 $_REQUEST['parent_type'] == 'Prospects')) {
519 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
520 $className = $beanList[$_REQUEST['parent_type']];
521 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
522 if(!class_exists($className)) {
523 require_once($beanFiles[$className]);
525 $bean = new $className();
526 $bean->retrieve($_REQUEST['parent_id']);
527 $object_arr[$bean->module_dir] = $bean->id;
531 foreach($toAddresses as $addrMeta) {
532 $addr = $addrMeta['email'];
533 $beans = $sea->getBeansByEmailAddress($addr);
534 foreach($beans as $bean) {
535 if (!isset($object_arr[$bean->module_dir])) {
536 $object_arr[$bean->module_dir] = $bean->id;
541 /* template parsing */
542 if (empty($object_arr)) {
543 $object_arr= array('Contacts' => '123');
545 $object_arr['Users'] = $current_user->id;
546 $this->description_html = EmailTemplate::parse_template($this->description_html, $object_arr);
547 $this->name = EmailTemplate::parse_template($this->name, $object_arr);
548 $this->description = EmailTemplate::parse_template($this->description, $object_arr);
549 $this->description = html_entity_decode($this->description,ENT_COMPAT,'UTF-8');
550 if($this->type != 'draft' && $this->status != 'draft') {
551 $this->id = create_guid();
552 $this->date_entered = "";
553 $this->new_with_id = true;
555 $this->status = 'sent';
559 if(isset($_REQUEST['parent_type']) && empty($_REQUEST['parent_type']) &&
560 isset($_REQUEST['parent_id']) && empty($_REQUEST['parent_id']) ) {
561 $this->parent_id = "";
562 $this->parent_type = "";
566 $mail->Subject = $this->name;
567 $mail = $this->handleBody($mail);
568 $mail->Subject = $this->name;
569 $this->description_html = from_html($this->description_html);
570 $this->description_html = $this->decodeDuringSend($this->description_html);
571 $this->description = $this->decodeDuringSend($this->description);
574 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
576 if(empty($request['fromAccount'])) {
577 $defaults = $current_user->getPreferredEmail();
578 $mail->From = $defaults['email'];
579 $mail->FromName = $defaults['name'];
580 $replyToName = $mail->FromName;
581 //$replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
583 // passed -> user -> system default
584 $ie = new InboundEmail();
585 $ie->retrieve($request['fromAccount']);
586 $storedOptions = unserialize(base64_decode($ie->stored_options));
590 //$replyToAddress = "";
591 if (!empty($storedOptions)) {
592 $fromAddress = $storedOptions['from_addr'];
593 $fromName = from_html($storedOptions['from_name']);
594 $replyToAddress = (isset($storedOptions['reply_to_addr']) ? $storedOptions['reply_to_addr'] : "");
595 $replyToName = (isset($storedOptions['reply_to_name']) ? from_html($storedOptions['reply_to_name']) : "");
597 $defaults = $current_user->getPreferredEmail();
598 // Personal Account doesn't have reply To Name and Reply To Address. So add those columns on UI
599 // After adding remove below code
602 if ($ie->is_personal)
604 if (empty($replyToAddress))
606 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
608 if (empty($replyToName))
610 $replyToName = $defaults['name'];
612 //Personal accounts can have a reply_address, which should
613 //overwrite the users set default.
614 if( !empty($storedOptions['reply_to_addr']) )
615 $replyToAddress = $storedOptions['reply_to_addr'];
618 // end of code to remove
619 $mail->From = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
620 $mail->FromName = (!empty($fromName)) ? $fromName : $defaults['name'];
621 $replyToName = (!empty($replyToName)) ? $replyToName : $mail->FromName;
624 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
626 if (!empty($replyToAddress)) {
627 $mail->AddReplyTo($replyToAddress,$locale->translateCharsetMIME(trim( $replyToName), 'UTF-8', $OBCharset));
629 $mail->AddReplyTo($mail->From,$locale->translateCharsetMIME(trim( $mail->FromName), 'UTF-8', $OBCharset));
631 $emailAddressCollection = array(); // used in linking to beans below
633 foreach($this->email2ParseAddresses($request['sendTo']) as $addr_arr) {
634 if(empty($addr_arr['email'])) continue;
636 if(empty($addr_arr['display'])) {
637 $mail->AddAddress($addr_arr['email'], "");
639 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
641 $emailAddressCollection[] = $addr_arr['email'];
643 foreach($this->email2ParseAddresses($request['sendCc']) as $addr_arr) {
644 if(empty($addr_arr['email'])) continue;
646 if(empty($addr_arr['display'])) {
647 $mail->AddCC($addr_arr['email'], "");
649 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
651 $emailAddressCollection[] = $addr_arr['email'];
654 foreach($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) {
655 if(empty($addr_arr['email'])) continue;
657 if(empty($addr_arr['display'])) {
658 $mail->AddBCC($addr_arr['email'], "");
660 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
662 $emailAddressCollection[] = $addr_arr['email'];
666 /* parse remove attachments array */
667 $removeAttachments = array();
668 if(!empty($request['templateAttachmentsRemove'])) {
669 $exRemove = explode("::", $request['templateAttachmentsRemove']);
671 foreach($exRemove as $file) {
672 $removeAttachments = substr($file, 0, 36);
676 /* handle attachments */
677 if(!empty($request['attachments'])) {
678 $exAttachments = explode("::", $request['attachments']);
680 foreach($exAttachments as $file) {
681 $file = trim(from_html($file));
682 $file = str_replace("\\", "", $file);
684 //$fileLocation = $this->et->userCacheDir."/{$file}";
685 $fileGUID = substr($file, 0, 36);
686 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
687 $filename = substr($file, 36, strlen($file)); // strip GUID for PHPMailer class to name outbound file
689 $mail->AddAttachment($fileLocation,$filename, 'base64', $this->email2GetMime($fileLocation));
690 //$mail->AddAttachment($fileLocation, $filename, 'base64');
692 // only save attachments if we're archiving or drafting
693 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
695 $note->id = create_guid();
696 $note->new_with_id = true; // duplicating the note with files
697 $note->parent_id = $this->id;
698 $note->parent_type = $this->module_dir;
699 $note->name = $filename;
700 $note->filename = $filename;
701 $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
702 $note->file_mime_type = $this->email2GetMime($fileLocation);
704 if(!copy($fileLocation, $noteFile)) {
705 $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to cache/upload [ {$fileLocation} ]");
714 /* handle sugar documents */
715 if(!empty($request['documents'])) {
716 $exDocs = explode("::", $request['documents']);
721 foreach($exDocs as $docId) {
722 $docId = trim($docId);
724 $doc = new Document();
725 $docRev = new DocumentRevision();
726 $doc->retrieve($docId);
727 $docRev->retrieve($doc->document_revision_id);
729 $filename = $docRev->filename;
730 $fileLocation = "{$sugar_config['upload_dir']}{$docRev->id}";
731 $mime_type = $docRev->file_mime_type;
732 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
734 // only save attachments if we're archiving or drafting
735 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
737 $note->id = create_guid();
738 $note->new_with_id = true; // duplicating the note with files
739 $note->parent_id = $this->id;
740 $note->parent_type = $this->module_dir;
741 $note->name = $filename;
742 $note->filename = $filename;
743 $note->file_mime_type = $mime_type;
744 $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
746 if(!copy($fileLocation, $noteFile)) {
747 $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
756 /* handle template attachments */
757 if(!empty($request['templateAttachments'])) {
759 $exNotes = explode("::", $request['templateAttachments']);
760 foreach($exNotes as $noteId) {
761 $noteId = trim($noteId);
762 if(!empty($noteId)) {
764 $note->retrieve($noteId);
765 if (!empty($note->id)) {
766 $filename = $note->filename;
767 $fileLocation = "{$sugar_config['upload_dir']}{$note->id}";
768 $mime_type = $note->file_mime_type;
769 if (!$note->embed_flag) {
770 $mail->AddAttachment($fileLocation,$filename, 'base64', $mime_type);
771 // only save attachments if we're archiving or drafting
772 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
774 if ($note->parent_id != $this->id)
775 $this->saveTempNoteAttachments($filename,$fileLocation, $mime_type);
780 //$fileLocation = $this->et->userCacheDir."/{$file}";
781 $fileGUID = substr($noteId, 0, 36);
782 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
783 //$fileLocation = $this->et->userCacheDir."/{$noteId}";
784 $filename = substr($noteId, 36, strlen($noteId)); // strip GUID for PHPMailer class to name outbound file
786 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $this->email2GetMime($fileLocation));
788 //If we are saving an email we were going to forward we need to save the attachments as well.
789 if( (($this->type == 'draft') && !empty($this->id))
790 || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1))
792 $mimeType = $this->email2GetMime($fileLocation);
793 $this->saveTempNoteAttachments($filename,$fileLocation, $mimeType);
802 /**********************************************************************
805 /* save email to sugar? */
808 if($this->type == 'draft' && !isset($request['saveDraft'])) {
809 // sending a draft email
811 $this->status = 'sent';
813 } elseif(isset($request['saveDraft'])) {
814 $this->type = 'draft';
815 $this->status = 'draft';
819 /**********************************************************************
820 * SEND EMAIL (finally!)
823 if ($this->type != 'draft') {
824 $mail->prepForOutbound();
825 $mail->Body = $this->decodeDuringSend($mail->Body);
826 $mail->AltBody = $this->decodeDuringSend($mail->AltBody);
827 if (!$mail->Send()) {
828 $this->status = 'send_error';
830 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo);
835 if ((!(empty($orignialId) || isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft'))) &&
836 (($_REQUEST['composeType'] == 'reply') || ($_REQUEST['composeType'] == 'replyAll') || ($_REQUEST['composeType'] == 'replyCase')) && ($orignialId != $this->id)) {
837 $originalEmail = new Email();
838 $originalEmail->retrieve($orignialId);
839 $originalEmail->reply_to_status = 1;
840 $originalEmail->save();
841 $this->reply_to_status = 0;
844 if ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase') {
845 if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) {
846 $emailFromIe = new InboundEmail();
847 $emailFromIe->retrieve($_REQUEST['ieId']);
848 $emailFromIe->mailbox = $_REQUEST['mbox'];
849 if (isset($emailFromIe->id) && $emailFromIe->is_personal) {
850 if ($emailFromIe->isPop3Protocol()) {
851 $emailFromIe->mark_answered($this->uid, 'pop3');
853 elseif ($emailFromIe->connectMailserver() == 'true') {
854 $emailFromIe->markEmails($this->uid, 'answered');
855 $emailFromIe->mark_answered($this->uid);
863 $this->type == 'draft' ||
864 (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
866 // saving a draft OR saving a sent email
867 $decodedFromName = mb_decode_mimeheader($mail->FromName);
868 $this->from_addr = "{$decodedFromName} <{$mail->From}>";
869 $this->from_addr_name = $this->from_addr;
870 $this->to_addrs = $_REQUEST['sendTo'];
871 $this->to_addrs_names = $_REQUEST['sendTo'];
872 $this->cc_addrs = $_REQUEST['sendCc'];
873 $this->cc_addrs_names = $_REQUEST['sendCc'];
874 $this->bcc_addrs = $_REQUEST['sendBcc'];
875 $this->bcc_addrs_names = $_REQUEST['sendBcc'];
876 $this->assigned_user_id = $current_user->id;
878 $this->date_sent = $timedate->now();
879 ///////////////////////////////////////////////////////////////////
880 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
882 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
883 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) ) {
884 $this->parent_id = $_REQUEST['parent_id'];
885 $this->parent_type = $_REQUEST['parent_type'];
886 $q = "SELECT count(*) c FROM emails_beans WHERE email_id = '{$this->id}' AND bean_id = '{$_REQUEST['parent_id']}' AND bean_module = '{$_REQUEST['parent_type']}'";
887 $r = $this->db->query($q);
888 $a = $this->db->fetchByAssoc($r);
890 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
891 $className = $beanList[$_REQUEST['parent_type']];
892 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
893 if(!class_exists($className)) {
894 require_once($beanFiles[$className]);
896 $bean = new $className();
897 $bean->retrieve($_REQUEST['parent_id']);
898 if($bean->load_relationship('emails')) {
899 $bean->emails->add($this->id);
909 if(!class_exists('aCase')) {
914 if($caseId = InboundEmail::getCaseIdFromCaseNumber($mail->Subject, $c)) {
915 $c->retrieve($caseId);
916 $c->load_relationship('emails');
917 $c->emails->add($this->id);
918 $this->parent_type = "Cases";
919 $this->parent_id = $caseId;
925 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
926 ///////////////////////////////////////////////////////////////////
930 if(!empty($request['fromAccount'])) {
931 if (isset($ie->id) && !$ie->isPop3Protocol()) {
932 $sentFolder = $ie->get_stored_options("sentFolder");
933 if (!empty($sentFolder)) {
934 $data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n";
935 $ie->mailbox = $sentFolder;
936 if ($ie->connectMailserver() == 'true') {
937 $connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox);
938 $returnData = imap_append($ie->conn,$connectString, $data, "\\Seen");
940 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}");
943 $GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}");
946 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty");
954 * Generates a comma sperated name and addresses to be used in compose email screen for contacts or leads
957 * @param $module string module name
958 * @param $idsArray array of record ids to get the email address for
959 * @return string comma delimited list of email addresses
961 public function getNamePlusEmailAddressesForCompose($module, $idsArray)
965 $table = SugarModule::get($module)->loadBean()->table_name;
966 $returndata = array();
968 foreach($idsArray as $id) {
969 if ($idsString != "") {
970 $idsString = $idsString . ",";
972 $idsString = $idsString . "'" . $id . "'";
974 $where = "({$table}.deleted = 0 AND {$table}.id in ({$idsString}))";
976 if ($module == 'Users' || $module == 'Employees') {
977 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.title";
979 elseif (SugarModule::get($module)->moduleImplements('Person')) {
980 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.salutation, {$table}.title";
983 $selectColumn = "{$table}.name";
985 $query = "SELECT {$table}.id, {$selectColumn}, eabr.primary_address, ea.email_address";
986 $query .= " FROM {$table} ";
987 $query .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
988 $query .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
989 $query .= " WHERE ({$where}) ORDER BY eabr.primary_address DESC";
990 $r = $this->db->query($query);
992 while($a = $this->db->fetchByAssoc($r)) {
993 if (!isset($returndata[$a['id']])) {
994 if ($module == 'Users' || $module == 'Employees') {
995 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], '', $a['title']));
996 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
998 elseif (SugarModule::get($module)->moduleImplements('Person')) {
999 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], $a['salutation'], $a['title']));
1000 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
1003 $returndata[$a['id']] = from_html($a['name']) . " <".from_html($a['email_address']).">";
1008 return join(",", array_values($returndata));
1014 ///////////////////////////////////////////////////////////////////////////
1016 function save($check_notify = false) {
1017 if($this->isDuplicate) {
1018 $GLOBALS['log']->debug("EMAIL - tried to save a duplicate Email record");
1021 if(empty($this->id)) {
1022 $this->id = create_guid();
1023 $this->new_with_id = true;
1025 $this->from_addr_name = $this->cleanEmails($this->from_addr_name);
1026 $this->to_addrs_names = $this->cleanEmails($this->to_addrs_names);
1027 $this->cc_addrs_names = $this->cleanEmails($this->cc_addrs_names);
1028 $this->bcc_addrs_names = $this->cleanEmails($this->bcc_addrs_names);
1029 $this->reply_to_addr = $this->cleanEmails($this->reply_to_addr);
1030 $this->description = to_html($this->safeText(from_html($this->description)));
1031 $this->description_html = $this->safeText($this->description_html);
1032 $this->saveEmailText();
1033 $this->saveEmailAddresses();
1035 $GLOBALS['log']->debug('-------------------------------> Email called save()');
1037 // handle legacy concatenation of date and time fields
1038 if(empty($this->date_sent)) $this->date_sent = $this->date_start." ".$this->time_start;
1040 parent::save($check_notify);
1042 if(!empty($this->parent_type) && !empty($this->parent_id)) {
1043 if(!empty($this->fetched_row) && !empty($this->fetched_row['parent_id']) && !empty($this->fetched_row['parent_type'])) {
1044 if($this->fetched_row['parent_id'] != $this->parent_id || $this->fetched_row['parent_type'] != $this->parent_type) {
1045 $mod = strtolower($this->fetched_row['parent_type']);
1046 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1047 if($this->load_relationship($rel) ) {
1048 $this->$rel->delete($this->id, $this->fetched_row['parent_id']);
1051 // we already have this relationship, don't add it
1055 $mod = strtolower($this->parent_type);
1056 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1057 if($this->load_relationship($rel) ) {
1058 $this->$rel->add($this->parent_id);
1065 * Helper function to save temporary attachments assocaited to an email as note.
1067 * @param string $filename
1068 * @param string $fileLocation
1069 * @param string $mimeType
1071 function saveTempNoteAttachments($filename,$fileLocation, $mimeType)
1073 global $sugar_config;
1075 $tmpNote = new Note();
1076 $tmpNote->id = create_guid();
1077 $tmpNote->new_with_id = true;
1078 $tmpNote->parent_id = $this->id;
1079 $tmpNote->parent_type = $this->module_dir;
1080 $tmpNote->name = $filename;
1081 $tmpNote->filename = $filename;
1082 $tmpNote->file_mime_type = $mimeType;
1083 $noteFile = "{$sugar_config['upload_dir']}{$tmpNote->id}";
1084 if(!copy($fileLocation, $noteFile))
1085 $GLOBALS['log']->fatal("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
1089 * Handles normalization of Email Addressess
1091 function saveEmailAddresses() {
1092 // from, single address
1093 $fromId = $this->emailAddress->getEmailGUID(from_html($this->from_addr));
1094 if(!empty($fromId)){
1095 $this->linkEmailToAddress($fromId, 'from');
1099 $replace = array(",",";");
1100 $toaddrs = str_replace($replace, "::", from_html($this->to_addrs));
1101 $exToAddrs = explode("::", $toaddrs);
1103 if(!empty($exToAddrs)) {
1104 foreach($exToAddrs as $toaddr) {
1105 $toaddr = trim($toaddr);
1106 if(!empty($toaddr)) {
1107 $toId = $this->emailAddress->getEmailGUID($toaddr);
1108 $this->linkEmailToAddress($toId, 'to');
1114 $ccAddrs = str_replace($replace, "::", from_html($this->cc_addrs));
1115 $exccAddrs = explode("::", $ccAddrs);
1117 if(!empty($exccAddrs)) {
1118 foreach($exccAddrs as $ccAddr) {
1119 $ccAddr = trim($ccAddr);
1120 if(!empty($ccAddr)) {
1121 $ccId = $this->emailAddress->getEmailGUID($ccAddr);
1122 $this->linkEmailToAddress($ccId, 'cc');
1128 $bccAddrs = str_replace($replace, "::", from_html($this->bcc_addrs));
1129 $exbccAddrs = explode("::", $bccAddrs);
1130 if(!empty($exbccAddrs)) {
1131 foreach($exbccAddrs as $bccAddr) {
1132 $bccAddr = trim($bccAddr);
1133 if(!empty($bccAddr)) {
1134 $bccId = $this->emailAddress->getEmailGUID($bccAddr);
1135 $this->linkEmailToAddress($bccId, 'bcc');
1141 function linkEmailToAddress($id, $type) {
1142 // TODO: make this update?
1143 $q1 = "SELECT * FROM emails_email_addr_rel WHERE email_id = '{$this->id}' AND email_address_id = '{$id}' AND address_type = '{$type}' AND deleted = 0";
1144 $r1 = $this->db->query($q1);
1145 $a1 = $this->db->fetchByAssoc($r1);
1147 if(!empty($a1) && !empty($a1['id'])) {
1150 $guid = create_guid();
1151 $q2 = "INSERT INTO emails_email_addr_rel VALUES('{$guid}', '{$this->id}', '{$type}', '{$id}', 0)";
1152 $r2 = $this->db->query($q2);
1158 function cleanEmails($emails)
1160 $emails = str_replace(array(",",";"), "::", from_html($emails));
1161 $addrs = explode("::", $emails);
1163 foreach($addrs as $addr) {
1164 $parts = $this->emailAddress->splitEmailAddress($addr);
1165 if(empty($parts["email"])) {
1168 if(!empty($parts["name"])) {
1169 $res[] = "{$parts["name"]} <{$parts["email"]}>";
1171 $res[] .= $parts["email"];
1174 return join(", ", $res);
1177 function saveEmailText() {
1178 $isOracle = ($this->db->dbType == "oci8") ? true : false;
1181 $description = $this->db->quote(trim($this->description));
1182 $description_html = $this->db->quoteForEmail(trim($this->description_html));
1183 $raw_source = $this->db->quote(trim($this->raw_source));
1184 $fromAddressName = $this->db->helper->escape_quote($this->from_addr_name);
1185 $toAddressName = $this->db->helper->escape_quote($this->to_addrs_names);
1186 $ccAddressName = $this->db->helper->escape_quote($this->cc_addrs_names);
1187 $bccAddressName = $this->db->helper->escape_quote($this->bcc_addrs_names);
1188 $replyToAddrName = $this->db->helper->escape_quote($this->reply_to_addr);
1190 if(!$this->new_with_id) {
1191 $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}'";
1193 $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)";
1195 $this->db->query($q);
1201 ///////////////////////////////////////////////////////////////////////////
1203 function retrieve($id, $encoded=true, $deleted=true) {
1204 // cn: bug 11915, return SugarBean's retrieve() call bean instead of $this
1205 $ret = parent::retrieve($id, $encoded, $deleted);
1208 $ret->retrieveEmailText();
1209 $ret->retrieveEmailAddresses();
1210 $ret->raw_source = to_html($ret->safeText(from_html($ret->raw_source)));
1211 $ret->description = to_html($ret->safeText(from_html($ret->description)));
1212 $ret->description_html = $ret->safeText($ret->description_html);
1214 $ret->date_start = '';
1215 $ret->time_start = '';
1216 $dateSent = explode(' ', $ret->date_sent);
1217 if (!empty($dateSent)) {
1218 $ret->date_start = $dateSent[0];
1219 if ( isset($dateSent[1]) )
1220 $ret->time_start = $dateSent[1];
1223 foreach($ret as $k => $v) {
1232 * Retrieves email addresses from GUIDs
1234 function retrieveEmailAddresses() {
1237 $q = "SELECT email_address, address_type
1238 FROM emails_email_addr_rel eam
1239 JOIN email_addresses ea ON ea.id = eam.email_address_id
1240 WHERE eam.email_id = '{$this->id}' AND eam.deleted=0";
1241 $r = $this->db->query($q);
1243 while($a = $this->db->fetchByAssoc($r)) {
1244 if(!isset($return[$a['address_type']])) {
1245 $return[$a['address_type']] = array();
1247 $return[$a['address_type']][] = $a['email_address'];
1250 if(count($return) > 0) {
1251 if(isset($return['from'])) {
1252 $this->from_addr = implode(", ", $return['from']);
1254 if(isset($return['to'])) {
1255 $this->to_addrs = implode(", ", $return['to']);
1257 if(isset($return['cc'])) {
1258 $this->cc_addrs = implode(", ", $return['cc']);
1260 if(isset($return['bcc'])) {
1261 $this->bcc_addrs = implode(", ", $return['bcc']);
1267 * Handles longtext fields
1269 function retrieveEmailText() {
1270 $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}'";
1271 $r = $this->db->query($q);
1272 $a = $this->db->fetchByAssoc($r, -1, false);
1274 $this->description = $a['description'];
1275 $this->description_html = $a['description_html'];
1276 $this->raw_source = $a['raw_source'];
1277 $this->from_addr_name = $a['from_addr'];
1278 $this->reply_to_addr = $a['reply_to_addr'];
1279 $this->to_addrs_names = $a['to_addrs'];
1280 $this->cc_addrs_names = $a['cc_addrs'];
1281 $this->bcc_addrs_names = $a['bcc_addrs'];
1284 function delete($id='') {
1288 $q = "UPDATE emails SET deleted = 1 WHERE id = '{$id}'";
1289 $qt = "UPDATE emails_text SET deleted = 1 WHERE email_id = '{$id}'";
1290 $r = $this->db->query($q);
1291 $rt = $this->db->query($qt);
1295 * creates the standard "Forward" info at the top of the forwarded message
1298 function getForwardHeader() {
1299 global $mod_strings;
1300 global $current_user;
1302 //$from = str_replace(array(">","<"), array(")","("), $this->from_name);
1303 $from = to_html($this->from_name);
1304 $subject = to_html($this->name);
1305 $ret = "<br /><br />";
1306 $ret .= $this->replyDelimiter."{$mod_strings['LBL_FROM']} {$from}<br />";
1307 $ret .= $this->replyDelimiter."{$mod_strings['LBL_DATE_SENT']} {$this->date_sent}<br />";
1308 $ret .= $this->replyDelimiter."{$mod_strings['LBL_TO']} {$this->to_addrs}<br />";
1309 $ret .= $this->replyDelimiter."{$mod_strings['LBL_CC']} {$this->cc_addrs}<br />";
1310 $ret .= $this->replyDelimiter."{$mod_strings['LBL_SUBJECT']} {$subject}<br />";
1311 $ret .= $this->replyDelimiter."<br />";
1314 //return from_html($ret);
1318 * retrieves Notes that belong to this Email and stuffs them into the "attachments" attribute
1320 function getNotes($id, $duplicate=false) {
1321 if(!class_exists('Note')) {
1325 $exRemoved = array();
1326 if(isset($_REQUEST['removeAttachment'])) {
1327 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1330 $noteArray = array();
1331 $q = "SELECT id FROM notes WHERE parent_id = '".$id."'";
1332 $r = $this->db->query($q);
1334 while($a = $this->db->fetchByAssoc($r)) {
1335 if(!in_array($a['id'], $exRemoved)) {
1337 $note->retrieve($a['id']);
1339 // duplicate actual file when creating forwards
1341 if(!class_exists('UploadFile')) {
1342 require_once('include/upload_file.php');
1344 // save a brand new Note
1345 $noteDupe->id = create_guid();
1346 $noteDupe->new_with_id = true;
1347 $noteDupe->parent_id = $this->id;
1348 $noteDupe->parent_type = $this->module_dir;
1350 $noteFile = new UploadFile('none');
1351 $noteFile->duplicate_file($a['id'], $note->id, $note->filename);
1355 // add Note to attachments array
1356 $this->attachments[] = $note;
1362 * creates the standard "Reply" info at the top of the forwarded message
1365 function getReplyHeader() {
1366 global $mod_strings;
1367 global $current_user;
1369 $from = str_replace(array(">","<", ">","<"), array(")","(",")","("), $this->from_name);
1370 $ret = "<br>{$mod_strings['LBL_REPLY_HEADER_1']} {$this->date_start}, {$this->time_start}, {$from} {$mod_strings['LBL_REPLY_HEADER_2']}";
1372 return from_html($ret);
1376 * Quotes plain-text email text
1377 * @param string $text
1380 function quotePlainTextEmail($text) {
1384 $desc = nl2br(trim($text));
1385 $exDesc = explode('<br />', $desc);
1387 foreach($exDesc as $k => $line) {
1388 $quoted .= '> '.trim($line)."\r";
1395 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1396 * @param string $text HTML text to quote
1399 function quoteHtmlEmail($text) {
1400 $text = trim(from_html($text));
1405 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1411 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1412 * @param string $text HTML text to quote
1415 function quoteHtmlEmailForNewEmailUI($text) {
1416 $text = trim($text);
1421 $text = str_replace("\n", "\n<BR/>", $text);
1422 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1429 ///////////////////////////////////////////////////////////////////////////
1432 * Safes description text (both HTML and Plain Text) for display
1433 * @param string str The text to safe
1434 * @return string Safed text
1436 function safeText($str) {
1438 $this->safe->clear();
1439 $ret = $this->safe->parse($str);
1441 // Julian's XSS cleaner
1442 $potentials = clean_xss($str, false);
1444 if(is_array($potentials) && !empty($potentials)) {
1445 //_ppl($potentials);
1446 foreach($potentials as $bad) {
1447 $ret = str_replace($bad, "", $ret);
1451 // clean <HTML> and <BODY> tags
1452 $html = '#<\\\\\?HTML[\w =\'\"\&]*>#sim';
1453 $body = '#<\\\\\?BODY[\w =\'\"\&]*>#sim';
1455 $ret = preg_replace($html, "", $ret);
1456 $ret = preg_replace($body, "", $ret);
1462 * Ensures that the user is able to send outbound emails
1464 function check_email_settings() {
1465 global $current_user;
1467 $mail_fromaddress = $current_user->emailAddress->getPrimaryAddress($current_user);
1468 $replyToName = $current_user->getPreference('mail_fromname');
1469 $mail_fromname = (!empty($replyToName)) ? $current_user->getPreference('mail_fromname') : $current_user->full_name;
1471 if(empty($mail_fromaddress)) {
1474 if(empty($mail_fromname)) {
1478 $send_type = $current_user->getPreference('mail_sendtype') ;
1479 if (!empty($send_type) && $send_type == "SMTP") {
1480 $mail_smtpserver = $current_user->getPreference('mail_smtpserver');
1481 $mail_smtpport = $current_user->getPreference('mail_smtpport');
1482 $mail_smtpauth_req = $current_user->getPreference('mail_smtpauth_req');
1483 $mail_smtpuser = $current_user->getPreference('mail_smtpuser');
1484 $mail_smtppass = $current_user->getPreference('mail_smtppass');
1485 if (empty($mail_smtpserver) ||
1486 empty($mail_smtpport) ||
1487 (!empty($mail_smtpauth_req) && ( empty($mail_smtpuser) || empty($mail_smtppass)))
1496 * outputs JS to set fields in the MassUpdate form in the "My Inbox" view
1498 function js_set_archived() {
1499 global $mod_strings;
1501 <script type="text/javascript" language="JavaScript"><!-- Begin
1502 function setArchived() {
1503 var form = document.getElementById("MassUpdate");
1504 var status = document.getElementById("mass_status");
1507 for(var i=0; i < form.elements.length; i++) {
1508 if(form.elements[i].name == "mass[]") {
1509 if(form.elements[i].checked == true) {
1516 var user = document.getElementById("mass_assigned_user_name");
1517 var team = document.getElementById("team");
1520 for(var j=0; j<status.length; j++) {
1521 if(status.options[j].value == "archived") {
1522 status.options[j].selected = true;
1523 status.selectedIndex = j; // for IE
1529 alert("'.$mod_strings['ERR_ARCHIVE_EMAIL'].'");
1533 // End --></script>';
1538 * replaces the javascript in utils.php - more specialized
1540 function u_get_clear_form_js($type='', $group='', $assigned_user_id='') {
1543 $uAssigned_user_id = '';
1545 if(!empty($type)) { $uType = '&type='.$type; }
1546 if(!empty($group)) { $uGroup = '&group='.$group; }
1547 if(!empty($assigned_user_id)) { $uAssigned_user_id = '&assigned_user_id='.$assigned_user_id; }
1550 <script type="text/javascript" language="JavaScript"><!-- Begin
1551 function clear_form(form) {
1552 var newLoc = "index.php?action=" + form.action.value + "&module=" + form.module.value + "&query=true&clear_query=true'.$uType.$uGroup.$uAssigned_user_id.'";
1553 if(typeof(form.advanced) != "undefined"){
1554 newLoc += "&advanced=" + form.advanced.value;
1556 document.location.href= newLoc;
1558 // End --></script>';
1562 function pickOneButton() {
1564 global $mod_strings;
1565 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_GRAB_TITLE'].'"
1566 accessKey="'.$mod_strings['LBL_BUTTON_GRAB_KEY'].'"
1568 type="button" name="button"
1569 onClick="window.location=\'index.php?module=Emails&action=Grab\';"
1570 style="margin-bottom:2px"
1571 value=" '.$mod_strings['LBL_BUTTON_GRAB'].' "></div>';
1576 * Determines what Editor (HTML or Plain-text) the current_user uses;
1577 * @return string Editor type
1579 function getUserEditorPreference() {
1580 global $sugar_config;
1581 global $current_user;
1585 if(!isset($sugar_config['email_default_editor'])) {
1586 $sugar_config = $current_user->setDefaultsInConfig();
1589 $userEditor = $current_user->getPreference('email_editor_option');
1590 $systemEditor = $sugar_config['email_default_editor'];
1592 if($userEditor != '') {
1593 $editor = $userEditor;
1595 $editor = $systemEditor;
1602 * takes the mess we pass from EditView and tries to create some kind of order
1603 * @param array addrs
1604 * @param array addrs_ids (from contacts)
1605 * @param array addrs_names (from contacts);
1606 * @param array addrs_emails (from contacts);
1607 * @return array Parsed assoc array to feed to PHPMailer
1609 function parse_addrs($addrs, $addrs_ids, $addrs_names, $addrs_emails) {
1610 // cn: bug 9406 - enable commas to separate email addresses
1611 $addrs = str_replace(",", ";", $addrs);
1613 $ltgt = array('<','>');
1614 $gtlt = array('<','>');
1617 $addrs = str_replace($ltgt, '', $addrs);
1618 $addrs_arr = explode(";",$addrs);
1619 $addrs_arr = $this->remove_empty_fields($addrs_arr);
1620 $addrs_ids_arr = explode(";",$addrs_ids);
1621 $addrs_ids_arr = $this->remove_empty_fields($addrs_ids_arr);
1622 $addrs_emails_arr = explode(";",$addrs_emails);
1623 $addrs_emails_arr = $this->remove_empty_fields($addrs_emails_arr);
1624 $addrs_names_arr = explode(";",$addrs_names);
1625 $addrs_names_arr = $this->remove_empty_fields($addrs_names_arr);
1627 ///////////////////////////////////////////////////////////////////////
1628 //// HANDLE EMAILS HAND-WRITTEN
1629 $contactRecipients = array();
1630 $knownEmails = array();
1632 foreach($addrs_arr as $i => $v) {
1634 continue; // skip any "blanks" - will always have 1
1636 $recipient = array();
1638 //// get the email to see if we're dealing with a dupe
1639 //// what crappy coding
1640 preg_match("/[A-Z0-9._%-\']+@[A-Z0-9.-]+\.[A-Z]{2,}/i",$v, $match);
1643 if(!empty($match[0]) && !in_array(trim($match[0]), $knownEmails)) {
1644 $knownEmails[] = $match[0];
1645 $recipient['email'] = $match[0];
1647 //// handle the Display name
1648 $display = trim(str_replace($match[0], '', $v));
1650 //// only trigger a "displayName" <email@address> when necessary
1651 if(isset($addrs_names_arr[$i])){
1652 $recipient['display'] = $addrs_names_arr[$i];
1654 else if(!empty($display)) {
1655 $recipient['display'] = $display;
1657 if(isset($addrs_ids_arr[$i]) && $addrs_emails_arr[$i] == $match[0]){
1658 $recipient['contact_id'] = $addrs_ids_arr[$i];
1660 $return[] = $recipient;
1667 function remove_empty_fields(&$arr) {
1670 foreach($arr as $field) {
1671 $field = trim($field);
1675 array_push($newarr,$field);
1681 * handles attachments of various kinds when sending email
1683 function handleAttachments() {
1688 global $mod_strings;
1690 ///////////////////////////////////////////////////////////////////////////
1691 //// ATTACHMENTS FROM DRAFTS
1692 if(($this->type == 'out' || $this->type == 'draft') && $this->status == 'draft' && isset($_REQUEST['record'])) {
1693 $this->getNotes($_REQUEST['record']); // cn: get notes from OLD email for use in new email
1695 //// END ATTACHMENTS FROM DRAFTS
1696 ///////////////////////////////////////////////////////////////////////////
1698 ///////////////////////////////////////////////////////////////////////////
1699 //// ATTACHMENTS FROM FORWARDS
1700 // Bug 8034 Jenny - Need the check for type 'draft' here to handle cases where we want to save
1701 // forwarded messages as drafts. We still need to save the original message's attachments.
1702 if(($this->type == 'out' || $this->type == 'draft') &&
1703 isset($_REQUEST['origType']) && $_REQUEST['origType'] == 'forward' &&
1704 isset($_REQUEST['return_id']) && !empty($_REQUEST['return_id'])
1706 $this->getNotes($_REQUEST['return_id'], true);
1709 // cn: bug 8034 - attachments from forward/replies lost when saving in draft
1710 if(isset($_REQUEST['prior_attachments']) && !empty($_REQUEST['prior_attachments']) && $this->new_with_id == true) {
1711 $exIds = explode(",", $_REQUEST['prior_attachments']);
1712 if(!isset($_REQUEST['template_attachment'])) {
1713 $_REQUEST['template_attachment'] = array();
1715 $_REQUEST['template_attachment'] = array_merge($_REQUEST['template_attachment'], $exIds);
1717 //// END ATTACHMENTS FROM FORWARDS
1718 ///////////////////////////////////////////////////////////////////////////
1720 ///////////////////////////////////////////////////////////////////////////
1721 //// ATTACHMENTS FROM TEMPLATES
1722 // to preserve individual email integrity, we must dupe Notes and associated files
1723 // for each outbound email - good for integrity, bad for filespace
1724 if(isset($_REQUEST['template_attachment']) && !empty($_REQUEST['template_attachment'])) {
1725 $removeArr = array();
1726 $noteArray = array();
1728 if(isset($_REQUEST['temp_remove_attachment']) && !empty($_REQUEST['temp_remove_attachment'])) {
1729 $removeArr = $_REQUEST['temp_remove_attachment'];
1733 foreach($_REQUEST['template_attachment'] as $noteId) {
1734 if(in_array($noteId, $removeArr)) {
1737 $noteTemplate = new Note();
1738 $noteTemplate->retrieve($noteId);
1739 $noteTemplate->id = create_guid();
1740 $noteTemplate->new_with_id = true; // duplicating the note with files
1741 $noteTemplate->parent_id = $this->id;
1742 $noteTemplate->parent_type = $this->module_dir;
1743 $noteTemplate->date_entered = '';
1744 $noteTemplate->save();
1746 $noteFile = new UploadFile('none');
1747 $noteFile->duplicate_file($noteId, $noteTemplate->id, $noteTemplate->filename);
1748 $noteArray[] = $noteTemplate;
1750 $this->attachments = array_merge($this->attachments, $noteArray);
1752 //// END ATTACHMENTS FROM TEMPLATES
1753 ///////////////////////////////////////////////////////////////////////////
1755 ///////////////////////////////////////////////////////////////////////////
1756 //// ADDING NEW ATTACHMENTS
1757 $max_files_upload = 10;
1758 // Jenny - Bug 8211 Since attachments for drafts have already been processed,
1759 // we don't need to re-process them.
1760 if($this->status != "draft") {
1761 $notes_list = array();
1762 if(!empty($this->id) && !$this->new_with_id) {
1764 $where = "notes.parent_id='{$this->id}'";
1765 $notes_list = $note->get_full_list("", $where, true);
1767 $this->attachments = array_merge($this->attachments, $notes_list);
1769 // cn: Bug 5995 - rudimentary error checking
1770 $filesError = array(
1771 0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
1772 1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
1773 2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
1774 3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
1775 4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
1776 5 => 'UNKNOWN ERROR',
1777 6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
1778 7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
1781 for($i = 0; $i < $max_files_upload; $i++) {
1782 // cn: Bug 5995 - rudimentary error checking
1783 if (!isset($_FILES["email_attachment{$i}"])) {
1784 $GLOBALS['log']->debug("Email Attachment {$i} does not exist.");
1787 if($_FILES['email_attachment'.$i]['error'] != 0 && $_FILES['email_attachment'.$i]['error'] != 4) {
1788 $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment'.$i]['error']]);
1793 $note->parent_id = $this->id;
1794 $note->parent_type = $this->module_dir;
1795 $upload_file = new UploadFile('email_attachment'.$i);
1797 if(empty($upload_file)) {
1801 if(isset($_FILES['email_attachment'.$i]) && $upload_file->confirm_upload()) {
1802 $note->filename = $upload_file->get_stored_file_name();
1803 $note->file = $upload_file;
1804 $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$note->file->original_file_name;
1806 $this->attachments[] = $note;
1810 $this->saved_attachments = array();
1811 foreach($this->attachments as $note) {
1812 if(!empty($note->id)) {
1813 array_push($this->saved_attachments, $note);
1816 $note->parent_id = $this->id;
1817 $note->parent_type = 'Emails';
1818 $note->file_mime_type = $note->file->mime_type;
1819 $note_id = $note->save();
1821 $this->saved_attachments[] = $note;
1823 $note->id = $note_id;
1824 $note->file->final_move($note->id);
1826 //// END NEW ATTACHMENTS
1827 ///////////////////////////////////////////////////////////////////////////
1829 ///////////////////////////////////////////////////////////////////////////
1830 //// ATTACHMENTS FROM DOCUMENTS
1831 for($i=0; $i<10; $i++) {
1832 if(isset($_REQUEST['documentId'.$i]) && !empty($_REQUEST['documentId'.$i])) {
1833 $doc = new Document();
1834 $docRev = new DocumentRevision();
1835 $docNote = new Note();
1836 $noteFile = new UploadFile('none');
1838 $doc->retrieve($_REQUEST['documentId'.$i]);
1839 $docRev->retrieve($doc->document_revision_id);
1841 $this->saved_attachments[] = $docRev;
1843 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
1844 $docNote->name = $docRev->getDocumentRevisionNameForDisplay();
1845 $docNote->filename = $docRev->filename;
1846 $docNote->description = $doc->description;
1847 $docNote->parent_id = $this->id;
1848 $docNote->parent_type = 'Emails';
1849 $docNote->file_mime_type = $docRev->file_mime_type;
1850 $docId = $docNote = $docNote->save();
1852 $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
1856 //// END ATTACHMENTS FROM DOCUMENTS
1857 ///////////////////////////////////////////////////////////////////////////
1859 ///////////////////////////////////////////////////////////////////////////
1860 //// REMOVE ATTACHMENTS
1861 if(isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
1862 foreach($_REQUEST['remove_attachment'] as $noteId) {
1863 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1864 $this->db->query($q);
1868 //this will remove attachments that have been selected to be removed from drafts.
1869 if(isset($_REQUEST['removeAttachment']) && !empty($_REQUEST['removeAttachment'])) {
1870 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1871 foreach($exRemoved as $noteId) {
1872 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1873 $this->db->query($q);
1876 //// END REMOVE ATTACHMENTS
1877 ///////////////////////////////////////////////////////////////////////////
1882 * Determines if an email body (HTML or Plain) has a User signature already in the content
1883 * @param array Array of signatures
1886 function hasSignatureInBody($sig) {
1887 // strpos can't handle line breaks - normalize
1888 $html = $this->removeAllNewlines($this->description_html);
1889 $htmlSig = $this->removeAllNewlines($sig['signature_html']);
1890 $plain = $this->removeAllNewlines($this->description);
1891 $plainSig = $this->removeAllNewlines($sig['signature']);
1893 // cn: bug 11621 - empty sig triggers notice error
1894 if(!empty($htmlSig) && false !== strpos($html, $htmlSig)) {
1896 } elseif(!empty($plainSig) && false !== strpos($plain, $plainSig)) {
1905 * @param string String to be normalized
1908 function removeAllNewlines($str) {
1909 $bad = array("\r\n", "\n\r", "\n", "\r");
1910 $good = array('', '', '', '');
1912 return str_replace($bad, $good, strip_tags(br2nl(from_html($str))));
1918 * Set navigation anchors to aid DetailView record navigation (VCR buttons)
1919 * @param string uri The URI from the referring page (always ListView)
1920 * @return array start Array of the URI broken down with a special "current_view" for My Inbox Navs
1922 function getStartPage($uri) {
1923 if(strpos($uri, '&')) { // "&" to ensure that we can explode the GET vars - else we're gonna trigger a Notice error
1924 $serial = substr($uri, (strpos($uri, '?')+1), strlen($uri));
1925 $exUri = explode('&', $serial);
1926 $start = array('module' => '', 'action' => '', 'group' => '', 'record' => '', 'type' => '');
1928 foreach($exUri as $k => $pair) {
1929 $exPair = explode('=', $pair);
1930 $start[$exPair[0]] = $exPair[1];
1933 // specific views for current_user
1934 if(isset($start['assigned_user_id'])) {
1935 $start['current_view'] = "{$start['action']}&module={$start['module']}&assigned_user_id={$start['assigned_user_id']}&type={$start['type']}";
1945 * preps SMTP info for email transmission
1946 * @param object mail SugarPHPMailer object
1947 * @param string mailer_id
1948 * @param string ieId
1949 * @return object mail SugarPHPMailer object
1951 function setMailer($mail, $mailer_id='', $ieId='') {
1952 global $current_user;
1954 require_once("include/OutboundEmail/OutboundEmail.php");
1955 $oe = new OutboundEmail();
1956 $oe = $oe->getInboundMailerSettings($current_user, $mailer_id, $ieId);
1958 // ssl or tcp - keeping outside isSMTP b/c a default may inadvertantly set ssl://
1959 $mail->protocol = ($oe->mail_smtpssl) ? "ssl://" : "tcp://";
1960 if($oe->mail_sendtype == "SMTP")
1962 //Set mail send type information
1963 $mail->Mailer = "smtp";
1964 $mail->Host = $oe->mail_smtpserver;
1965 $mail->Port = $oe->mail_smtpport;
1966 if ($oe->mail_smtpssl == 1) {
1967 $mail->SMTPSecure = 'ssl';
1969 if ($oe->mail_smtpssl == 2) {
1970 $mail->SMTPSecure = 'tls';
1973 if($oe->mail_smtpauth_req) {
1974 $mail->SMTPAuth = TRUE;
1975 $mail->Username = $oe->mail_smtpuser;
1976 $mail->Password = $oe->mail_smtppass;
1980 $mail->Mailer = "sendmail";
1987 * preps SugarPHPMailer object for HTML or Plain text sends
1988 * @param object SugarPHPMailer instance
1990 function handleBody($mail) {
1991 global $current_user;
1992 global $sugar_config;
1993 ///////////////////////////////////////////////////////////////////////
1994 //// HANDLE EMAIL FORMAT PREFERENCE
1995 // the if() below is HIGHLY dependent on the Javascript unchecking the Send HTML Email box
1997 if( (isset($_REQUEST['setEditor']) /* from Email EditView navigation */
1998 && $_REQUEST['setEditor'] == 1
1999 && trim($_REQUEST['description_html']) != '')
2000 || trim($this->description_html) != '' /* from email templates */
2001 && $current_user->getPreference('email_editor_option', 'global') !== 'plain' //user preference is not set to plain text
2003 $this->handleBodyInHTMLformat($mail);
2006 $this->description_html = '';
2007 $mail->IsHTML(false);
2008 $plainText = from_html($this->description);
2009 $plainText = str_replace(" ", " ", $plainText);
2010 $plainText = str_replace("</p>", "</p><br />", $plainText);
2011 $plainText = strip_tags(br2nl($plainText));
2012 $plainText = str_replace("&", "&", $plainText);
2013 $plainText = str_replace("'", "'", $plainText);
2014 $mail->Body = wordwrap($plainText, 996);
2015 $mail->Body = $this->decodeDuringSend($mail->Body);
2016 $this->description = $mail->Body;
2019 // wp: if plain text version has lines greater than 998, use base64 encoding
2020 foreach(explode("\n", ($mail->ContentType == "text/html") ? $mail->AltBody : $mail->Body) as $line) {
2021 if(strlen($line) > 998) {
2022 $mail->Encoding = 'base64';
2026 //// HANDLE EMAIL FORMAT PREFERENCE
2027 ///////////////////////////////////////////////////////////////////////
2033 * Retrieve function from handlebody() to unit test easily
2035 * @return formatted $mail body
2037 function handleBodyInHTMLformat($mail) {
2038 global $current_user;
2039 global $sugar_config;
2040 // wp: if body is html, then insert new lines at 996 characters. no effect on client side
2041 // due to RFC 2822 which limits email lines to 998
2042 $mail->IsHTML(true);
2043 $body = from_html(wordwrap($this->description_html, 996));
2044 $mail->Body = $body;
2047 // new plan is to use the selected type (html or plain) to fill the other
2048 $plainText = from_html($this->description_html);
2049 $plainText = strip_tags(br2nl($plainText));
2050 $mail->AltBody = $plainText;
2051 $this->description = $plainText;
2053 $fileBasePath = "{$sugar_config['cache_dir']}images/";
2054 $filePatternSearch = "{$sugar_config['cache_dir']}";
2055 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2056 $filePatternSearch = $filePatternSearch . "images\/";
2057 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2060 preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2061 foreach($matches[0] as $match) {
2062 $filename = str_replace($fileBasePath, '', $match);
2063 $filename = urldecode(substr($filename, 0, -1));
2065 $file_location = clean_path(getcwd()."/{$sugar_config['cache_dir']}images/{$filename}");
2066 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2068 if(file_exists($file_location)) {
2069 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2073 //replace references to cache with cid tag
2074 $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2075 $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2076 // remove bad img line from outbound email
2077 $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2078 $mail->Body = preg_replace($regex, '', $mail->Body);
2080 $fileBasePath = "{$sugar_config['upload_dir']}";
2081 $filePatternSearch = "{$sugar_config['upload_dir']}";
2082 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2083 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2086 preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2087 foreach($matches[0] as $match) {
2088 $filename = str_replace($fileBasePath, '', $match);
2089 $filename = urldecode(substr($filename, 0, -1));
2091 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$filename}");
2092 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2094 if(file_exists($file_location)) {
2095 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2099 //replace references to cache with cid tag
2100 $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2101 $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2103 // remove bad img line from outbound email
2104 $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2105 $mail->Body = preg_replace($regex, '', $mail->Body);
2108 //Replace any embeded images using the secure entryPoint for src url.
2109 $noteImgRegex = "/<img[^>]*[\s]+src[^=]*=\"index.php\?entryPoint=download\&id=([^\&]*)[^>]*>/im";
2110 $embededImageMatches = array();
2111 preg_match_all($noteImgRegex, $mail->Body, $embededImageMatches,PREG_SET_ORDER);
2113 foreach ($embededImageMatches as $singleMatch )
2115 $fullMatch = $singleMatch[0];
2116 $noteId = $singleMatch[1];
2118 $filename = $noteId;
2120 //Retrieve note for mimetype
2121 $tmpNote = new Note();
2122 $tmpNote->retrieve($noteId);
2123 //Replace the src part of img tag with new cid tag
2124 $cidRegex = "/src=\"([^\"]*)\"/im";
2125 $replaceMatch = preg_replace($cidRegex, "src=\"cid:$noteId\"", $fullMatch);
2127 //Replace the body, old tag for new tag
2128 $mail->Body = str_replace($fullMatch, $replaceMatch, $mail->Body);
2131 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$noteId}");
2133 if(file_exists($file_location))
2134 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $tmpNote->file_mime_type);
2139 $mail->Body = from_html($mail->Body);
2144 * @return bool True on success
2147 global $mod_strings,$app_strings;
2148 global $current_user;
2149 global $sugar_config;
2151 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
2152 $mail = new SugarPHPMailer();
2154 foreach ($this->to_addrs_arr as $addr_arr) {
2155 if ( empty($addr_arr['display'])) {
2156 $mail->AddAddress($addr_arr['email'], "");
2158 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
2161 foreach ($this->cc_addrs_arr as $addr_arr) {
2162 if ( empty($addr_arr['display'])) {
2163 $mail->AddCC($addr_arr['email'], "");
2165 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2169 foreach ($this->bcc_addrs_arr as $addr_arr) {
2170 if ( empty($addr_arr['display'])) {
2171 $mail->AddBCC($addr_arr['email'], "");
2173 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2177 $mail = $this->setMailer($mail);
2180 if(!empty($this->from_addr)) {
2181 $mail->From = $this->from_addr;
2183 $mail->From = $current_user->getPreference('mail_fromaddress');
2184 $this->from_addr = $mail->From;
2187 if(!empty($this->from_name)) {
2188 $mail->FromName = $this->from_name;
2190 $mail->FromName = $current_user->getPreference('mail_fromname');
2191 $this->from_name = $mail->FromName;
2194 //Reply to information for case create and autoreply.
2195 if(!empty($this->reply_to_name)) {
2196 $ReplyToName = $this->reply_to_name;
2198 $ReplyToName = $mail->FromName;
2200 if(!empty($this->reply_to_addr)) {
2201 $ReplyToAddr = $this->reply_to_addr;
2203 $ReplyToAddr = $mail->From;
2205 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
2206 $mail->AddReplyTo($ReplyToAddr,$locale->translateCharsetMIME(trim($ReplyToName), 'UTF-8', $OBCharset));
2208 //$mail->Subject = html_entity_decode($this->name, ENT_QUOTES, 'UTF-8');
2209 $mail->Subject = $this->name;
2211 ///////////////////////////////////////////////////////////////////////
2213 foreach($this->saved_attachments as $note) {
2214 $mime_type = 'text/plain';
2215 if($note->object_name == 'Note') {
2216 if(!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) { // brandy-new file upload/attachment
2217 $file_location = $sugar_config['upload_dir'].$note->id;
2218 $filename = $note->file->original_file_name;
2219 $mime_type = $note->file->mime_type;
2220 } else { // attachment coming from template/forward
2221 $file_location = rawurldecode(UploadFile::get_file_path($note->filename,$note->id));
2222 // cn: bug 9723 - documents from EmailTemplates sent with Doc Name, not file name.
2223 $filename = !empty($note->filename) ? $note->filename : $note->name;
2224 $mime_type = $note->file_mime_type;
2226 } elseif($note->object_name == 'DocumentRevision') { // from Documents
2227 $filePathName = $note->id;
2228 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
2229 $filename = $note->getDocumentRevisionNameForDisplay();
2230 $file_location = getcwd().'/'.$GLOBALS['sugar_config']['upload_dir'].$filePathName;
2231 $mime_type = $note->file_mime_type;
2234 // strip out the "Email attachment label if exists
2235 $filename = str_replace($mod_strings['LBL_EMAIL_ATTACHMENT'].': ', '', $filename);
2237 //is attachment in our list of bad files extensions? If so, append .txt to file location
2238 //get position of last "." in file name
2239 $file_ext_beg = strrpos($file_location,".");
2241 //get file extension
2242 if($file_ext_beg >0){
2243 $file_ext = substr($file_location, $file_ext_beg+1 );
2245 //check to see if this is a file with extension located in "badext"
2246 foreach($sugar_config['upload_badext'] as $badExt) {
2247 if(strtolower($file_ext) == strtolower($badExt)) {
2248 //if found, then append with .txt to filename and break out of lookup
2249 //this will make sure that the file goes out with right extension, but is stored
2251 $file_location = $file_location . ".txt";
2252 break; // no need to look for more
2255 $mail->AddAttachment($file_location,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
2258 if($note->embed_flag == true) {
2260 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64',$mime_type);
2263 //// END ATTACHMENTS
2264 ///////////////////////////////////////////////////////////////////////
2266 $mail = $this->handleBody($mail);
2268 $GLOBALS['log']->debug('Email sending --------------------- ');
2270 ///////////////////////////////////////////////////////////////////////
2271 //// I18N TRANSLATION
2272 $mail->prepForOutbound();
2273 //// END I18N TRANSLATION
2274 ///////////////////////////////////////////////////////////////////////
2277 ///////////////////////////////////////////////////////////////////
2278 //// INBOUND EMAIL HANDLING
2280 if(!empty($_REQUEST['inbound_email_id'])) {
2281 $ieMail = new Email();
2282 $ieMail->retrieve($_REQUEST['inbound_email_id']);
2283 $ieMail->status = 'replied';
2286 $GLOBALS['log']->debug(' --------------------- buh bye -- sent successful');
2287 //// END INBOUND EMAIL HANDLING
2288 ///////////////////////////////////////////////////////////////////
2291 $GLOBALS['log']->debug($app_strings['LBL_EMAIL_ERROR_PREPEND'].$mail->ErrorInfo);
2296 function listviewACLHelper(){
2297 $array_assign = parent::listviewACLHelper();
2299 if(!empty($this->parent_name)){
2301 if(!empty($this->parent_name_owner)){
2302 global $current_user;
2303 $is_owner = $current_user->id == $this->parent_name_owner;
2306 if(!ACLController::moduleSupportsACL($this->parent_type) || ACLController::checkAccess($this->parent_type, 'view', $is_owner)){
2307 $array_assign['PARENT'] = 'a';
2309 $array_assign['PARENT'] = 'span';
2312 if(!empty($this->contact_name)) {
2313 if(!empty($this->contact_name_owner)) {
2314 global $current_user;
2315 $is_owner = $current_user->id == $this->contact_name_owner;
2318 if(ACLController::checkAccess('Contacts', 'view', $is_owner)) {
2319 $array_assign['CONTACT'] = 'a';
2321 $array_assign['CONTACT'] = 'span';
2324 return $array_assign;
2327 function getSystemDefaultEmail() {
2330 $r1 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromaddress\'');
2331 $r2 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromname\'');
2332 $a1 = $this->db->fetchByAssoc($r1);
2333 $a2 = $this->db->fetchByAssoc($r2);
2335 $email['email'] = $a1['value'];
2336 $email['name'] = $a2['value'];
2342 function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false) {
2344 if ($return_array) {
2345 return parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, $return_array,$parentbean, $singleSelect);
2347 $custom_join = $this->custom_fields->getJOIN();
2349 $query = "SELECT ".$this->table_name.".*, users.user_name as assigned_user_name\n";
2352 $query .= $custom_join['select'];
2354 $query .= " FROM emails\n";
2355 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2356 $query .= " LEFT JOIN emails_beans ON emails.id = emails_beans.email_id\n";
2359 $query .= " LEFT JOIN users ON emails.assigned_user_id=users.id \n";
2360 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2362 $query .= " JOIN contacts ON contacts.id= emails_beans.bean_id AND emails_beans.bean_module='Contacts' and contacts.deleted=0 \n";
2366 $query .= $custom_join['join'];
2369 if($show_deleted == 0) {
2370 $where_auto = " emails.deleted=0 \n";
2371 }else if($show_deleted == 1){
2372 $where_auto = " emails.deleted=1 \n";
2376 $query .= "WHERE $where AND ".$where_auto;
2378 $query .= "WHERE ".$where_auto;
2381 $query .= " ORDER BY $order_by";
2383 $query .= " ORDER BY date_sent DESC";
2389 function fill_in_additional_list_fields() {
2391 $this->fill_in_additional_detail_fields();
2393 $this->link_action = 'DetailView';
2394 ///////////////////////////////////////////////////////////////////////
2395 //populate attachment_image, used to display attachment icon.
2396 $query = "select 1 from notes where notes.parent_id = '$this->id' and notes.deleted = 0";
2397 $result =$this->db->query($query,true," Error filling in additional list fields: ");
2399 $row = $this->db->fetchByAssoc($result);
2402 $this->attachment_image = SugarThemeRegistry::current()->getImage('attachment',"","","");
2404 $this->attachment_image = SugarThemeRegistry::current()->getImage('blank',"","","");
2406 ///////////////////////////////////////////////////////////////////////
2407 if(empty($this->contact_id) && !empty($this->parent_id) && !empty($this->parent_type) && $this->parent_type === 'Contacts' && !empty($this->parent_name) ){
2408 $this->contact_id = $this->parent_id;
2409 $this->contact_name = $this->parent_name;
2413 function fill_in_additional_detail_fields() {
2414 global $app_list_strings,$mod_strings;
2415 // Fill in the assigned_user_name
2416 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id, '');
2417 //if ($this->parent_type == 'Contacts') {
2418 $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 ";
2419 $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";
2420 if(!empty($this->parent_id)){
2421 $query .= " AND contacts.id= '".$this->parent_id."' ";
2422 }else if(!empty($_REQUEST['record'])){
2423 $query .= " AND contacts.id= '".$_REQUEST['record']."' ";
2425 $result =$this->db->query($query,true," Error filling in additional detail fields: ");
2427 // Get the id and the name.
2428 $row = $this->db->fetchByAssoc($result);
2432 $contact = new Contact();
2433 $contact->retrieve($row['id']);
2434 $this->contact_name = $contact->full_name;
2435 $this->contact_phone = $row['phone_work'];
2436 $this->contact_id = $row['id'];
2437 $this->contact_email = $contact->emailAddress->getPrimaryAddress($contact);
2438 $this->contact_name_owner = $row['contact_name_owner'];
2439 $this->contact_name_mod = $row['contact_name_mod'];
2440 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2441 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2442 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2443 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2446 $this->contact_name = '';
2447 $this->contact_phone = '';
2448 $this->contact_id = '';
2449 $this->contact_email = '';
2450 $this->contact_name_owner = '';
2451 $this->contact_name_mod = '';
2452 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2453 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2454 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2455 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2458 $this->created_by_name = get_assigned_user_name($this->created_by);
2459 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
2461 $this->link_action = 'DetailView';
2463 if(!empty($this->type)) {
2464 if($this->type == 'out' && $this->status == 'send_error') {
2465 $this->type_name = $mod_strings['LBL_NOT_SENT'];
2467 $this->type_name = $app_list_strings['dom_email_types'][$this->type];
2470 if(($this->type == 'out' && $this->status == 'send_error') || $this->type == 'draft') {
2471 $this->link_action = 'EditView';
2475 //todo this isset( $app_list_strings['dom_email_status'][$this->status]) is hack for 3261.
2476 if(!empty($this->status) && isset( $app_list_strings['dom_email_status'][$this->status])) {
2477 $this->status_name = $app_list_strings['dom_email_status'][$this->status];
2480 if ( empty($this->name ) && empty($_REQUEST['record'])) {
2481 $this->name = $mod_strings['LBL_NO_SUBJECT'];
2484 $this->fill_in_additional_parent_fields();
2489 function create_export_query(&$order_by, &$where) {
2490 $contact_required = stristr($where, "contacts");
2491 $custom_join = $this->custom_fields->getJOIN(true, true,$where);
2493 if($contact_required) {
2494 $query = "SELECT emails.*, contacts.first_name, contacts.last_name";
2496 $query .= $custom_join['select'];
2499 $query .= " FROM contacts, emails, emails_contacts ";
2500 $where_auto = "emails_contacts.contact_id = contacts.id AND emails_contacts.email_id = emails.id AND emails.deleted=0 AND contacts.deleted=0";
2502 $query = 'SELECT emails.*';
2504 $query .= $custom_join['select'];
2507 $query .= ' FROM emails ';
2508 $where_auto = "emails.deleted=0";
2512 $query .= $custom_join['join'];
2516 $query .= "where $where AND ".$where_auto;
2518 $query .= "where ".$where_auto;
2521 $query .= " ORDER BY $order_by";
2523 $query .= " ORDER BY emails.name";
2527 function get_list_view_data() {
2528 global $app_list_strings;
2530 global $current_user;
2532 global $mod_strings;
2534 $email_fields = $this->get_list_view_array();
2535 $this->retrieveEmailText();
2536 $email_fields['FROM_ADDR'] = $this->from_addr_name;
2537 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); // hard-coding for Home screen ListView
2539 if($this->status != 'replied') {
2540 $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>';
2541 $email_fields['STATUS'] = ($email_fields['REPLY_TO_STATUS'] == 1 ? $mod_strings['LBL_REPLIED'] : $email_fields['STATUS']);
2543 $email_fields['QUICK_REPLY'] = $mod_strings['LBL_REPLIED'];
2545 if(!empty($this->parent_type)) {
2546 $email_fields['PARENT_MODULE'] = $this->parent_type;
2548 switch($this->intent) {
2550 $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>';
2554 $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>';
2558 $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>';
2562 $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>';
2566 $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>';
2579 $email_fields['CREATE_RELATED'] = $this->quickCreateForm();
2585 //BUG 17098 - MFH changed $this->from_addr to $this->to_addrs
2586 $email_fields['CONTACT_NAME'] = empty($this->contact_name) ? '</a>'.$this->trimLongTo($this->to_addrs).'<a>' : $this->contact_name;
2587 $email_fields['CONTACT_ID'] = empty($this->contact_id) ? '' : $this->contact_id;
2588 $email_fields['ATTACHMENT_IMAGE'] = $this->attachment_image;
2589 $email_fields['LINK_ACTION'] = $this->link_action;
2591 if(isset($this->type_name))
2592 $email_fields['TYPE_NAME'] = $this->type_name;
2594 return $email_fields;
2597 function quickCreateForm() {
2598 global $mod_strings, $app_strings, $currentModule, $current_language;
2600 // Coming from the home page via Dashlets
2601 if($currentModule != 'Email')
2602 $mod_strings = return_module_language($current_language, 'Emails');
2603 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>";
2607 * Searches all imported emails and returns the result set as an array.
2610 function searchImportedEmails($sort = '', $direction='')
2612 require_once('include/TimeDate.php');
2614 global $current_user;
2616 global $sugar_config;
2617 global $app_strings;
2619 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
2620 // cn: default to a low number until user specifies otherwise
2621 if(empty($emailSettings['showNumInList']))
2624 $pageSize = $emailSettings['showNumInList'];
2626 if( isset($_REQUEST['start']) && isset($_REQUEST['limit']) )
2627 $page = ceil($_REQUEST['start'] / $_REQUEST['limit']) + 1;
2631 //Determine sort ordering
2633 //Sort ordering parameters in the request do not coincide with actual column names
2634 //so we need to remap them.
2635 $hrSortLocal = array(
2636 'flagged' => 'type',
2637 'status' => 'reply_to_status',
2638 'from' => 'emails_text.from_addr',
2639 'subject' => 'name',
2640 'date' => 'date_sent',
2641 'AssignedTo' => 'assigned_user_id',
2642 'flagged' => 'flagged'
2645 $sort = !empty($_REQUEST['sort']) ? $_REQUEST['sort'] : "";
2646 $direction = !empty($_REQUEST['dir']) ? $_REQUEST['dir'] : "";
2648 $order = ( !empty($sort) && !empty($direction) ) ? " ORDER BY {$hrSortLocal[$sort]} {$direction}" : "";
2650 //Get our main query.
2651 $fullQuery = $this->_genereateSearchImportedEmailsQuery();
2653 //Perform a count query needed for pagination.
2654 $countQuery = $this->create_list_count_query($fullQuery);
2655 $count_rs = $this->db->query($countQuery, false, 'Error executing count query for imported emails search');
2656 $count_row = $this->db->fetchByAssoc($count_rs);
2657 $total_count = ($count_row != null) ? $count_row['c'] : 0;
2659 $start = ($page - 1) * $pageSize;
2662 $rs = $this->db->limitQuery($fullQuery . $order, $start, $pageSize);
2666 while($a = $this->db->fetchByAssoc($rs)) {
2668 $temp['flagged'] = (is_null($a['flagged']) || $a['flagged'] == '0') ? '' : 1;
2669 $temp['status'] = (is_null($a['reply_to_status']) || $a['reply_to_status'] == '0') ? '' : 1;
2670 $temp['subject'] = $a['name'];
2671 $temp['date'] = $timedate->to_display_date_time($a['date_sent']);
2672 $temp['uid'] = $a['id'];
2673 $temp['ieId'] = $a['mailbox_id'];
2674 $temp['site_url'] = $sugar_config['site_url'];
2675 $temp['seen'] = ($a['status'] == 'unread') ? 0 : 1;
2676 $temp['type'] = $a['type'];
2677 $temp['mbox'] = 'sugar::Emails';
2678 $temp['hasAttach'] = $this->doesImportedEmailHaveAttachment($a['id']);
2679 //To and from addresses may be stored in emails_text, if nothing is found, revert to
2680 //regular email addresses.
2681 $temp['to_addrs'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['to_addrs']);
2682 $temp['from'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['from_addr']);
2683 if( empty($temp['from']) || empty($temp['to_addrs']) )
2685 //Retrieve email addresses seperatly.
2686 $tmpEmail = new Email();
2687 $tmpEmail->id = $a['id'];
2688 $tmpEmail->retrieveEmailAddresses();
2689 $temp['from'] = $tmpEmail->from_addr;
2690 $temp['to_addrs'] = $tmpEmail->to_addrs;
2696 $metadata = array();
2697 $metadata['totalCount'] = $total_count;
2698 $metadata['out'] = $return;
2704 * Determine if an imported email has an attachment by examining the relationship to notes.
2709 function doesImportedEmailHaveAttachment($id)
2711 $hasAttachment = FALSE;
2712 $query = "SELECT id FROM notes where parent_id='$id' AND parent_type='Emails' AND file_mime_type is not null AND deleted=0";
2713 $rs = $this->db->limitQuery($query, 0, 1);
2714 $row = $this->db->fetchByAssoc($rs);
2715 if( !empty($row['id']) )
2716 $hasAttachment = TRUE;
2718 return (int) $hasAttachment;
2722 * Generate the query used for searching imported emails.
2724 * @return String Query to be executed.
2726 function _genereateSearchImportedEmailsQuery()
2730 $additionalWhereClause = $this->_generateSearchImportWhereClause();
2734 $query['select'] = "emails.id , emails.mailbox_id, emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status,
2735 emails_text.from_addr, emails_text.to_addrs FROM emails ";
2737 $query['joins'] = " JOIN emails_text on emails.id = emails_text.email_id ";
2739 //Handle from and to addr joins
2740 if( !empty($_REQUEST['from_addr']) )
2742 $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
2743 AND er_from.address_type='from' AND ea_from.email_address='" . strtolower($_REQUEST['from_addr']) . "'";
2746 if( !empty($_REQUEST['to_addrs']) )
2748 $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
2749 AND er_to.address_type='to' AND ea_to.email_address='" . strtolower($_REQUEST['to_addrs']) . "'";
2752 $query['where'] = " WHERE (emails.type= 'inbound' OR emails.type='archived' OR emails.type='out') AND emails.deleted = 0 ";
2753 if( !empty($additionalWhereClause) )
2754 $query['where'] .= "AND $additionalWhereClause";
2756 //If we are explicitly looking for attachments. Do not use a distinct query as the to_addr is defined
2757 //as a text which equals clob in oracle and the distinct query can not be executed correctly.
2758 $addDistinctKeyword = "";
2759 if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 1) //1 indicates yes
2760 $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 )";
2761 else if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 2 )
2762 $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 )";
2764 $fullQuery = "SELECT " . $query['select'] . " " . $query['joins'] . " " . $query['where'];
2769 * Generate the where clause for searching imported emails.
2772 function _generateSearchImportWhereClause()
2776 //The clear button was removed so if a user removes the asisgned user name, do not process the id.
2777 if( empty($_REQUEST['assigned_user_name']) && !empty($_REQUEST['assigned_user_id']) )
2778 unset($_REQUEST['assigned_user_id']);
2780 $availableSearchParam = array('name' => array('table_name' =>'emails'),
2781 'data_parent_id_search' => array('table_name' =>'emails','db_key' => 'parent_id','opp' => '='),
2782 'assigned_user_id' => array('table_name' => 'emails', 'opp' => '=') );
2784 $additionalWhereClause = array();
2785 foreach ($availableSearchParam as $key => $properties)
2787 if( !empty($_REQUEST[$key]) )
2789 $db_key = isset($properties['db_key']) ? $properties['db_key'] : $key;
2790 $searchValue = $_REQUEST[$key];
2792 $opp = isset($properties['opp']) ? $properties['opp'] : 'like';
2794 $searchValue = $searchValue . "%";
2796 $additionalWhereClause[] = "{$properties['table_name']}.$db_key $opp '$searchValue' ";
2800 $isDateFromSearchSet = !empty($_REQUEST['searchDateFrom']);
2801 $isdateToSearchSet = !empty($_REQUEST['searchDateTo']);
2803 $bothDateRangesSet = $isDateFromSearchSet & $isdateToSearchSet;
2805 //Hanlde date from and to seperately
2806 if($bothDateRangesSet)
2808 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2809 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2811 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2812 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2814 $additionalWhereClause[] = "( emails.date_sent >= $dbFormatDateFrom AND
2815 emails.date_sent <= $dbFormatDateTo )";
2817 elseif ($isdateToSearchSet)
2819 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2820 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2821 $additionalWhereClause[] = "emails.date_sent <= $dbFormatDateTo ";
2823 elseif ($isDateFromSearchSet)
2825 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2826 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2827 $additionalWhereClause[] = "emails.date_sent >= $dbFormatDateFrom ";
2830 $additionalWhereClause = implode(" AND ", $additionalWhereClause);
2832 return $additionalWhereClause;
2838 * takes a long TO: string of emails and returns the first appended by an
2841 function trimLongTo($str) {
2842 if(strpos($str, ',')) {
2843 $exStr = explode(',', $str);
2844 return $exStr[0].'...';
2845 } elseif(strpos($str, ';')) {
2846 $exStr = explode(';', $str);
2847 return $exStr[0].'...';
2853 function get_summary_text() {
2859 function distributionForm($where) {
2860 global $app_list_strings;
2861 global $app_strings;
2862 global $mod_strings;
2864 global $current_user;
2866 $distribution = get_select_options_with_id($app_list_strings['dom_email_distribution'], '');
2867 $_SESSION['distribute_where'] = $where;
2870 $out = '<form name="Distribute" id="Distribute">';
2871 $out .= get_form_header($mod_strings['LBL_DIST_TITLE'], '', false);
2878 <table cellpadding="0" cellspacing="0" width="100%" border="0">
2881 <script type="text/javascript">
2884 function checkDeps(form) {
2888 function mySubmit() {
2889 var assform = document.getElementById("Distribute");
2890 var select = document.getElementById("userSelect");
2891 var assign1 = assform.r1.checked;
2892 var assign2 = assform.r2.checked;
2893 var dist = assform.dm.value;
2897 var warn1 = "'.$mod_strings['LBL_WARN_NO_USERS'].'";
2900 if(assign1 || assign2) {
2905 for(i=0; i<select.options.length; i++) {
2906 if(select.options[i].selected == true) {
2915 warn2 = "'.$mod_strings['LBL_WARN_NO_DIST'].'";
2918 if(assign && users && rules) {
2920 if(document.getElementById("r1").checked) {
2921 var mu = document.getElementById("MassUpdate");
2924 for(i=0; i<mu.elements.length; i++) {
2925 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name.value != "massall") {
2926 if(grabbed != "") { grabbed += "::"; }
2927 grabbed += mu.elements[i].value;
2930 var formgrab = document.getElementById("grabbed");
2931 formgrab.value = grabbed;
2935 alert("'.$mod_strings['LBL_ASSIGN_WARN'].'" + "\n" + warn1 + "\n" + warn2);
2939 function submitDelete() {
2940 if(document.getElementById("r1").checked) {
2941 var mu = document.getElementById("MassUpdate");
2944 for(i=0; i<mu.elements.length; i++) {
2945 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name != "massall") {
2946 if(grabbed != "") { grabbed += "::"; }
2947 grabbed += mu.elements[i].value;
2950 var formgrab = document.getElementById("grabbed");
2951 formgrab.value = grabbed;
2954 alert("'.$mod_strings['LBL_MASS_DELETE_ERROR'].'");
2956 document.getElementById("Distribute").submit();
2961 <input type="hidden" name="module" value="Emails">
2962 <input type="hidden" name="action" id="action">
2963 <input type="hidden" name="grabbed" id="grabbed">
2965 <table cellpadding="1" cellspacing="0" width="100%" border="0" class="edit view">
2967 <td scope="col" scope="row" NOWRAP align="center">
2968 '.$mod_strings['LBL_ASSIGN_SELECTED_RESULTS_TO'].' ';
2969 $out .= $this->userSelectTable();
2971 <td scope="col" scope="row" NOWRAP align="left">
2972 '.$mod_strings['LBL_USING_RULES'].'
2973 <select name="distribute_method" id="dm" onChange="checkDeps(this.form);">'.$distribution.'</select>
2982 <td scope="col" width="50%" scope="row" NOWRAP align="right" colspan="2">
2983 <input title="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_TITLE'].'"
2985 accessKey="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_KEY'].'"
2986 class="button" onClick="AjaxObject.detailView.handleAssignmentDialogAssignAction();"
2987 type="button" name="button"
2988 value=" '.$mod_strings['LBL_BUTTON_DISTRIBUTE'].' ">';
2998 function userSelectTable() {
3000 global $mod_strings;
3003 $setTeamUserFunction = '';
3007 $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");
3009 $userTable = '<table cellpadding="0" cellspacing="0" border="0">';
3010 $userTable .= '<tr><td colspan="2"><b>'.$mod_strings['LBL_USER_SELECT'].'</b></td></tr>';
3011 $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>';
3012 $userTable .= '<tr><td colspan="2"><select style="visibility:hidden;" name="users[]" id="userSelect" multiple size="12">';
3014 while($a = $this->db->fetchByAssoc($r)) {
3015 $userTable .= '<option value="'.$a['id'].'" id="'.$a['id'].'">'.$a['first_name'].' '.$a['last_name'].'</option>';
3017 $userTable .= '</select></td></tr>';
3018 $userTable .= '</table>';
3020 $out = '<script type="text/javascript">';
3021 $out .= $setTeamUserFunction;
3023 function setCheckMark() {
3024 var select = document.getElementById("userSelect");
3026 for(i=0 ; i<select.options.length; i++) {
3027 if(select.options[i].selected == true) {
3028 document.getElementById("checkMark").style.display="";
3033 document.getElementById("checkMark").style.display="none";
3037 function showUserSelect() {
3038 var targetTable = document.getElementById("user_select");
3039 targetTable.style.visibility="visible";
3040 var userSelectTable = document.getElementById("userSelect");
3041 userSelectTable.style.visibility="visible";
3044 function hideUserSelect() {
3045 var targetTable = document.getElementById("user_select");
3046 targetTable.style.visibility="hidden";
3047 var userSelectTable = document.getElementById("userSelect");
3048 userSelectTable.style.visibility="hidden";
3051 function toggleAll(toggle) {
3052 if(toggle.checked) {
3057 var form = document.getElementById("userSelect");
3058 for(i=0; i<form.options.length; i++) {
3059 form.options[i].selected = stat;
3065 <span id="showUsersDiv" style="position:relative;">
3066 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
3067 <img border="0" src="'.SugarThemeRegistry::current()->getImageURL('Users.gif').'"></a>
3068 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
3069 <span style="display:none;" id="checkMark"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('check_inline.gif').'"></span>
3073 <div id="user_select" style="width:200px;position:absolute;left:2;top:2;visibility:hidden;z-index:1000;">
3074 <table cellpadding="0" cellspacing="0" border="0" class="list view">
3076 <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\';">
3077 <a href="#" onClick="javascript:hideUserSelect();"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('close.gif').'"></a>
3078 '.$mod_strings['LBL_USER_SELECT'].'
3082 //<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\';">
3083 $out .= ' <td style="padding:5px" class="oddListRowS1" bgcolor="#fdfdfd" valign="top" align="left" style="left:0;top:0;">
3092 function checkInbox($type) {
3094 global $mod_strings;
3095 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_CHECK_TITLE'].'"
3096 accessKey="'.$mod_strings['LBL_BUTTON_CHECK_KEY'].'"
3098 type="button" name="button"
3099 onClick="window.location=\'index.php?module=Emails&action=Check&type='.$type.'\';"
3100 style="margin-bottom:2px"
3101 value=" '.$mod_strings['LBL_BUTTON_CHECK'].' "></div>';
3106 * Guesses Primary Parent id from From: email address. Cascades guesses from Accounts to Contacts to Leads to
3107 * Users. This will not affect the many-to-many relationships already constructed as this is, at best,
3108 * informational linking.
3110 function fillPrimaryParentFields() {
3111 if(empty($this->from_addr))
3114 $GLOBALS['log']->debug("*** Email trying to guess Primary Parent from address [ {$this->from_addr} ]");
3116 $tables = array('accounts');
3118 // loop through types to get hits
3119 foreach($tables as $table) {
3120 $q = "SELECT name, id FROM {$table} WHERE email1 = '{$this->from_addr}' OR email2 = '{$this->from_addr}' AND deleted = 0";
3121 $r = $this->db->query($q);
3122 while($a = $this->db->fetchByAssoc($r)) {
3123 if(!empty($a['name']) && !empty($a['id'])) {
3124 $this->parent_type = ucwords($table);
3125 $this->parent_id = $a['id'];
3126 $this->parent_name = $a['name'];