2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM 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(function_exists('mime_content_type')) {
343 $mime = mime_content_type($fileLocation);
344 } elseif(function_exists('ext2mime')) {
345 $mime = ext2mime($fileLocation);
347 $mime = 'application/octet-stream';
353 function sendEmailTest($mailserver_url, $port, $ssltls, $smtp_auth_req, $smtp_username, $smtppassword, $fromaddress, $toaddress, $mail_sendtype = 'smtp') {
354 global $current_user,$app_strings;
355 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); //Called from EmailMan as well.
356 $mail = new SugarPHPMailer();
357 $mail->Mailer = strtolower($mail_sendtype);
358 if($mail->Mailer == 'smtp')
360 $mail->Host = $mailserver_url;
362 if (isset($ssltls) && !empty($ssltls)) {
363 $mail->protocol = "ssl://";
365 $mail->SMTPSecure = 'ssl';
368 $mail->SMTPSecure = 'tls';
371 $mail->protocol = "tcp://";
373 if ($smtp_auth_req) {
374 $mail->SMTPAuth = TRUE;
375 $mail->Username = $smtp_username;
376 $mail->Password = $smtppassword;
380 $mail->Mailer = 'sendmail';
382 $mail->Subject = from_html($mod_strings['LBL_TEST_EMAIL_SUBJECT']);
383 $mail->From = $fromaddress;
384 $mail->FromName = $current_user->name;
385 $mail->Sender = $mail->From;
386 $mail->AddAddress($toaddress);
387 $mail->Body = $mod_strings['LBL_TEST_EMAIL_BODY'];
393 $return['status'] = false;
394 $return['errorMessage'] = $app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo;
397 $return['status'] = true;
401 function decodeDuringSend($htmlData) {
402 $htmlData = str_replace("sugarLessThan", "<", $htmlData);
403 $htmlData = str_replace("sugarGreaterThan", ">", $htmlData);
408 * Returns true or false if this email is a draft.
410 * @param array $request
411 * @return bool True indicates this email is a draft.
413 function isDraftEmail($request)
415 return ( isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft') );
419 * Sends Email for Email 2.0
421 function email2Send($request) {
424 global $current_user;
425 global $sugar_config;
430 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
432 /**********************************************************************
438 if(!empty($this->id)) {
439 $orignialId = $this->id;
442 if(empty($this->id)) {
443 $this->id = create_guid();
444 $this->new_with_id = true;
447 /* satisfy basic HTML email requirements */
448 $this->name = $request['sendSubject'];
449 $this->description_html = '<html><body>'.$request['sendDescription'].'</body></html>';
451 /**********************************************************************
454 $mail = new SugarPHPMailer();
455 $mail = $this->setMailer($mail, '', $_REQUEST['fromAccount']);
456 if (empty($mail->Host) && !$this->isDraftEmail($request))
458 $this->status = 'send_error';
460 if ($mail->oe->type == 'system')
461 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_SYSTEM_OUTBOUND']);
463 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_PERSONAL_OUTBOUND']);
468 $subject = $this->name;
469 $mail->Subject = from_html($this->name);
471 // work-around legacy code in SugarPHPMailer
472 if($_REQUEST['setEditor'] == 1) {
473 $_REQUEST['description_html'] = $_REQUEST['sendDescription'];
474 $this->description_html = $_REQUEST['description_html'];
476 $this->description_html = '';
477 $this->description = $_REQUEST['sendDescription'];
481 if ( $this->isDraftEmail($request) )
483 if($this->type != 'draft' && $this->status != 'draft') {
484 $this->id = create_guid();
485 $this->new_with_id = true;
486 $this->date_entered = "";
488 $q1 = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$this->id}'";
489 $r1 = $this->db->query($q1);
492 if (isset($request['saveDraft'])) {
493 $this->type = 'draft';
494 $this->status = 'draft';
497 /* Apply Email Templates */
498 // do not parse email templates if the email is being saved as draft....
499 $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']);
500 $sea = new SugarEmailAddress();
501 $object_arr = array();
503 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
504 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) &&
505 ($_REQUEST['parent_type'] == 'Accounts' ||
506 $_REQUEST['parent_type'] == 'Contacts' ||
507 $_REQUEST['parent_type'] == 'Leads' ||
508 $_REQUEST['parent_type'] == 'Users' ||
509 $_REQUEST['parent_type'] == 'Prospects')) {
510 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
511 $className = $beanList[$_REQUEST['parent_type']];
512 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
513 if(!class_exists($className)) {
514 require_once($beanFiles[$className]);
516 $bean = new $className();
517 $bean->retrieve($_REQUEST['parent_id']);
518 $object_arr[$bean->module_dir] = $bean->id;
522 foreach($toAddresses as $addrMeta) {
523 $addr = $addrMeta['email'];
524 $beans = $sea->getBeansByEmailAddress($addr);
525 foreach($beans as $bean) {
526 if (!isset($object_arr[$bean->module_dir])) {
527 $object_arr[$bean->module_dir] = $bean->id;
532 /* template parsing */
533 if (empty($object_arr)) {
534 $object_arr= array('Contacts' => '123');
536 $object_arr['Users'] = $current_user->id;
537 $this->description_html = EmailTemplate::parse_template($this->description_html, $object_arr);
538 $this->name = EmailTemplate::parse_template($this->name, $object_arr);
539 $this->description = EmailTemplate::parse_template($this->description, $object_arr);
540 $this->description = html_entity_decode($this->description,ENT_COMPAT,'UTF-8');
541 if($this->type != 'draft' && $this->status != 'draft') {
542 $this->id = create_guid();
543 $this->date_entered = "";
544 $this->new_with_id = true;
546 $this->status = 'sent';
550 if(isset($_REQUEST['parent_type']) && empty($_REQUEST['parent_type']) &&
551 isset($_REQUEST['parent_id']) && empty($_REQUEST['parent_id']) ) {
552 $this->parent_id = "";
553 $this->parent_type = "";
557 $mail->Subject = $this->name;
558 $mail = $this->handleBody($mail);
559 $mail->Subject = $this->name;
560 $this->description_html = from_html($this->description_html);
561 $this->description_html = $this->decodeDuringSend($this->description_html);
562 $this->description = $this->decodeDuringSend($this->description);
565 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
567 if(empty($request['fromAccount'])) {
568 $defaults = $current_user->getPreferredEmail();
569 $mail->From = $defaults['email'];
570 $mail->FromName = $defaults['name'];
571 $replyToName = $mail->FromName;
572 //$replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
574 // passed -> user -> system default
575 $ie = new InboundEmail();
576 $ie->retrieve($request['fromAccount']);
577 $storedOptions = unserialize(base64_decode($ie->stored_options));
581 //$replyToAddress = "";
582 if (!empty($storedOptions)) {
583 $fromAddress = $storedOptions['from_addr'];
584 $fromName = from_html($storedOptions['from_name']);
585 $replyToAddress = (isset($storedOptions['reply_to_addr']) ? $storedOptions['reply_to_addr'] : "");
586 $replyToName = (isset($storedOptions['reply_to_name']) ? from_html($storedOptions['reply_to_name']) : "");
588 $defaults = $current_user->getPreferredEmail();
589 // Personal Account doesn't have reply To Name and Reply To Address. So add those columns on UI
590 // After adding remove below code
593 if ($ie->is_personal)
595 if (empty($replyToAddress))
597 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
599 if (empty($replyToName))
601 $replyToName = $defaults['name'];
603 //Personal accounts can have a reply_address, which should
604 //overwrite the users set default.
605 if( !empty($storedOptions['reply_to_addr']) )
606 $replyToAddress = $storedOptions['reply_to_addr'];
609 // end of code to remove
610 $mail->From = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
611 $mail->FromName = (!empty($fromName)) ? $fromName : $defaults['name'];
612 $replyToName = (!empty($replyToName)) ? $replyToName : $mail->FromName;
615 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
617 if (!empty($replyToAddress)) {
618 $mail->AddReplyTo($replyToAddress,$locale->translateCharsetMIME(trim( $replyToName), 'UTF-8', $OBCharset));
620 $mail->AddReplyTo($mail->From,$locale->translateCharsetMIME(trim( $mail->FromName), 'UTF-8', $OBCharset));
622 $emailAddressCollection = array(); // used in linking to beans below
624 foreach($this->email2ParseAddresses($request['sendTo']) as $addr_arr) {
625 if(empty($addr_arr['email'])) continue;
627 if(empty($addr_arr['display'])) {
628 $mail->AddAddress($addr_arr['email'], "");
630 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
632 $emailAddressCollection[] = $addr_arr['email'];
634 foreach($this->email2ParseAddresses($request['sendCc']) as $addr_arr) {
635 if(empty($addr_arr['email'])) continue;
637 if(empty($addr_arr['display'])) {
638 $mail->AddCC($addr_arr['email'], "");
640 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
642 $emailAddressCollection[] = $addr_arr['email'];
645 foreach($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) {
646 if(empty($addr_arr['email'])) continue;
648 if(empty($addr_arr['display'])) {
649 $mail->AddBCC($addr_arr['email'], "");
651 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
653 $emailAddressCollection[] = $addr_arr['email'];
657 /* parse remove attachments array */
658 $removeAttachments = array();
659 if(!empty($request['templateAttachmentsRemove'])) {
660 $exRemove = explode("::", $request['templateAttachmentsRemove']);
662 foreach($exRemove as $file) {
663 $removeAttachments = substr($file, 0, 36);
667 /* handle attachments */
668 if(!empty($request['attachments'])) {
669 $exAttachments = explode("::", $request['attachments']);
671 foreach($exAttachments as $file) {
672 $file = trim(from_html($file));
673 $file = str_replace("\\", "", $file);
675 //$fileLocation = $this->et->userCacheDir."/{$file}";
676 $fileGUID = substr($file, 0, 36);
677 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
678 $filename = substr($file, 36, strlen($file)); // strip GUID for PHPMailer class to name outbound file
680 $mail->AddAttachment($fileLocation,$filename, 'base64', $this->email2GetMime($fileLocation));
681 //$mail->AddAttachment($fileLocation, $filename, 'base64');
683 // only save attachments if we're archiving or drafting
684 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
686 $note->id = create_guid();
687 $note->new_with_id = true; // duplicating the note with files
688 $note->parent_id = $this->id;
689 $note->parent_type = $this->module_dir;
690 $note->name = $filename;
691 $note->filename = $filename;
692 $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
693 $note->file_mime_type = $this->email2GetMime($fileLocation);
695 if(!copy($fileLocation, $noteFile)) {
696 $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to cache/upload [ {$fileLocation} ]");
705 /* handle sugar documents */
706 if(!empty($request['documents'])) {
707 $exDocs = explode("::", $request['documents']);
712 foreach($exDocs as $docId) {
713 $docId = trim($docId);
715 $doc = new Document();
716 $docRev = new DocumentRevision();
717 $doc->retrieve($docId);
718 $docRev->retrieve($doc->document_revision_id);
720 $filename = $docRev->filename;
721 $fileLocation = "{$sugar_config['upload_dir']}{$docRev->id}";
722 $mime_type = $docRev->file_mime_type;
723 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
725 // only save attachments if we're archiving or drafting
726 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
728 $note->id = create_guid();
729 $note->new_with_id = true; // duplicating the note with files
730 $note->parent_id = $this->id;
731 $note->parent_type = $this->module_dir;
732 $note->name = $filename;
733 $note->filename = $filename;
734 $note->file_mime_type = $mime_type;
735 $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
737 if(!copy($fileLocation, $noteFile)) {
738 $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
747 /* handle template attachments */
748 if(!empty($request['templateAttachments'])) {
750 $exNotes = explode("::", $request['templateAttachments']);
751 foreach($exNotes as $noteId) {
752 $noteId = trim($noteId);
753 if(!empty($noteId)) {
755 $note->retrieve($noteId);
756 if (!empty($note->id)) {
757 $filename = $note->filename;
758 $fileLocation = "{$sugar_config['upload_dir']}{$note->id}";
759 $mime_type = $note->file_mime_type;
760 if (!$note->embed_flag) {
761 $mail->AddAttachment($fileLocation,$filename, 'base64', $mime_type);
762 // only save attachments if we're archiving or drafting
763 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
765 if ($note->parent_id != $this->id)
766 $this->saveTempNoteAttachments($filename,$fileLocation, $mime_type);
771 //$fileLocation = $this->et->userCacheDir."/{$file}";
772 $fileGUID = substr($noteId, 0, 36);
773 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
774 //$fileLocation = $this->et->userCacheDir."/{$noteId}";
775 $filename = substr($noteId, 36, strlen($noteId)); // strip GUID for PHPMailer class to name outbound file
777 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $this->email2GetMime($fileLocation));
779 //If we are saving an email we were going to forward we need to save the attachments as well.
780 if( (($this->type == 'draft') && !empty($this->id))
781 || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1))
783 $mimeType = $this->email2GetMime($fileLocation);
784 $this->saveTempNoteAttachments($filename,$fileLocation, $mimeType);
793 /**********************************************************************
796 /* save email to sugar? */
799 if($this->type == 'draft' && !isset($request['saveDraft'])) {
800 // sending a draft email
802 $this->status = 'sent';
804 } elseif(isset($request['saveDraft'])) {
805 $this->type = 'draft';
806 $this->status = 'draft';
810 /**********************************************************************
811 * SEND EMAIL (finally!)
814 if ($this->type != 'draft') {
815 $mail->prepForOutbound();
816 $mail->Body = $this->decodeDuringSend($mail->Body);
817 $mail->AltBody = $this->decodeDuringSend($mail->AltBody);
818 if (!$mail->Send()) {
819 $this->status = 'send_error';
821 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo);
826 if ((!(empty($orignialId) || isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft'))) &&
827 (($_REQUEST['composeType'] == 'reply') || ($_REQUEST['composeType'] == 'replyAll') || ($_REQUEST['composeType'] == 'replyCase')) && ($orignialId != $this->id)) {
828 $originalEmail = new Email();
829 $originalEmail->retrieve($orignialId);
830 $originalEmail->reply_to_status = 1;
831 $originalEmail->save();
832 $this->reply_to_status = 0;
835 if ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase') {
836 if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) {
837 $emailFromIe = new InboundEmail();
838 $emailFromIe->retrieve($_REQUEST['ieId']);
839 $emailFromIe->mailbox = $_REQUEST['mbox'];
840 if (isset($emailFromIe->id) && $emailFromIe->is_personal) {
841 if ($emailFromIe->isPop3Protocol()) {
842 $emailFromIe->mark_answered($this->uid, 'pop3');
844 elseif ($emailFromIe->connectMailserver() == 'true') {
845 $emailFromIe->markEmails($this->uid, 'answered');
846 $emailFromIe->mark_answered($this->uid);
854 $this->type == 'draft' ||
855 (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
857 // saving a draft OR saving a sent email
858 $decodedFromName = mb_decode_mimeheader($mail->FromName);
859 $this->from_addr = "{$decodedFromName} <{$mail->From}>";
860 $this->from_addr_name = $this->from_addr;
861 $this->to_addrs = $_REQUEST['sendTo'];
862 $this->to_addrs_names = $_REQUEST['sendTo'];
863 $this->cc_addrs = $_REQUEST['sendCc'];
864 $this->cc_addrs_names = $_REQUEST['sendCc'];
865 $this->bcc_addrs = $_REQUEST['sendBcc'];
866 $this->bcc_addrs_names = $_REQUEST['sendBcc'];
867 $this->assigned_user_id = $current_user->id;
869 $this->date_sent = $timedate->now();
870 ///////////////////////////////////////////////////////////////////
871 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
873 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
874 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) ) {
875 $this->parent_id = $_REQUEST['parent_id'];
876 $this->parent_type = $_REQUEST['parent_type'];
877 $q = "SELECT count(*) c FROM emails_beans WHERE email_id = '{$this->id}' AND bean_id = '{$_REQUEST['parent_id']}' AND bean_module = '{$_REQUEST['parent_type']}'";
878 $r = $this->db->query($q);
879 $a = $this->db->fetchByAssoc($r);
881 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
882 $className = $beanList[$_REQUEST['parent_type']];
883 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
884 if(!class_exists($className)) {
885 require_once($beanFiles[$className]);
887 $bean = new $className();
888 $bean->retrieve($_REQUEST['parent_id']);
889 if($bean->load_relationship('emails')) {
890 $bean->emails->add($this->id);
900 if(!class_exists('aCase')) {
905 if($caseId = InboundEmail::getCaseIdFromCaseNumber($mail->Subject, $c)) {
906 $c->retrieve($caseId);
907 $c->load_relationship('emails');
908 $c->emails->add($this->id);
909 $this->parent_type = "Cases";
910 $this->parent_id = $caseId;
916 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
917 ///////////////////////////////////////////////////////////////////
921 if(!empty($request['fromAccount'])) {
922 if (isset($ie->id) && !$ie->isPop3Protocol()) {
923 $sentFolder = $ie->get_stored_options("sentFolder");
924 if (!empty($sentFolder)) {
925 $data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n";
926 $ie->mailbox = $sentFolder;
927 if ($ie->connectMailserver() == 'true') {
928 $connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox);
929 $returnData = imap_append($ie->conn,$connectString, $data, "\\Seen");
931 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}");
934 $GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}");
937 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty");
945 * Generates a comma sperated name and addresses to be used in compose email screen for contacts or leads
948 * @param $module string module name
949 * @param $idsArray array of record ids to get the email address for
950 * @return string comma delimited list of email addresses
952 public function getNamePlusEmailAddressesForCompose($module, $idsArray)
956 $table = SugarModule::get($module)->loadBean()->table_name;
957 $returndata = array();
959 foreach($idsArray as $id) {
960 if ($idsString != "") {
961 $idsString = $idsString . ",";
963 $idsString = $idsString . "'" . $id . "'";
965 $where = "({$table}.deleted = 0 AND {$table}.id in ({$idsString}))";
967 if ($module == 'Users' || $module == 'Employees') {
968 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.title";
970 elseif (SugarModule::get($module)->moduleImplements('Person')) {
971 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.salutation, {$table}.title";
974 $selectColumn = "{$table}.name";
976 $query = "SELECT {$table}.id, {$selectColumn}, eabr.primary_address, ea.email_address";
977 $query .= " FROM {$table} ";
978 $query .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
979 $query .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
980 $query .= " WHERE ({$where}) ORDER BY eabr.primary_address DESC";
981 $r = $this->db->query($query);
983 while($a = $this->db->fetchByAssoc($r)) {
984 if (!isset($returndata[$a['id']])) {
985 if ($module == 'Users' || $module == 'Employees') {
986 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], '', $a['title']));
987 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
989 elseif (SugarModule::get($module)->moduleImplements('Person')) {
990 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], $a['salutation'], $a['title']));
991 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
994 $returndata[$a['id']] = from_html($a['name']) . " <".from_html($a['email_address']).">";
999 return join(",", array_values($returndata));
1005 ///////////////////////////////////////////////////////////////////////////
1007 function save($check_notify = false) {
1008 if($this->isDuplicate) {
1009 $GLOBALS['log']->debug("EMAIL - tried to save a duplicate Email record");
1012 if(empty($this->id)) {
1013 $this->id = create_guid();
1014 $this->new_with_id = true;
1016 $this->from_addr_name = $this->cleanEmails($this->from_addr_name);
1017 $this->to_addrs_names = $this->cleanEmails($this->to_addrs_names);
1018 $this->cc_addrs_names = $this->cleanEmails($this->cc_addrs_names);
1019 $this->bcc_addrs_names = $this->cleanEmails($this->bcc_addrs_names);
1020 $this->reply_to_addr = $this->cleanEmails($this->reply_to_addr);
1021 $this->description = to_html($this->safeText(from_html($this->description)));
1022 $this->description_html = $this->safeText($this->description_html);
1023 $this->saveEmailText();
1024 $this->saveEmailAddresses();
1026 $GLOBALS['log']->debug('-------------------------------> Email called save()');
1028 // handle legacy concatenation of date and time fields
1029 if(empty($this->date_sent)) $this->date_sent = $this->date_start." ".$this->time_start;
1031 parent::save($check_notify);
1033 if(!empty($this->parent_type) && !empty($this->parent_id)) {
1034 if(!empty($this->fetched_row) && !empty($this->fetched_row['parent_id']) && !empty($this->fetched_row['parent_type'])) {
1035 if($this->fetched_row['parent_id'] != $this->parent_id || $this->fetched_row['parent_type'] != $this->parent_type) {
1036 $mod = strtolower($this->fetched_row['parent_type']);
1037 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1038 if($this->load_relationship($rel) ) {
1039 $this->$rel->delete($this->id, $this->fetched_row['parent_id']);
1042 // we already have this relationship, don't add it
1046 $mod = strtolower($this->parent_type);
1047 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1048 if($this->load_relationship($rel) ) {
1049 $this->$rel->add($this->parent_id);
1056 * Helper function to save temporary attachments assocaited to an email as note.
1058 * @param string $filename
1059 * @param string $fileLocation
1060 * @param string $mimeType
1062 function saveTempNoteAttachments($filename,$fileLocation, $mimeType)
1064 global $sugar_config;
1066 $tmpNote = new Note();
1067 $tmpNote->id = create_guid();
1068 $tmpNote->new_with_id = true;
1069 $tmpNote->parent_id = $this->id;
1070 $tmpNote->parent_type = $this->module_dir;
1071 $tmpNote->name = $filename;
1072 $tmpNote->filename = $filename;
1073 $tmpNote->file_mime_type = $mimeType;
1074 $noteFile = "{$sugar_config['upload_dir']}{$tmpNote->id}";
1075 if(!copy($fileLocation, $noteFile))
1076 $GLOBALS['log']->fatal("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
1080 * Handles normalization of Email Addressess
1082 function saveEmailAddresses() {
1083 // from, single address
1084 $fromId = $this->emailAddress->getEmailGUID(from_html($this->from_addr));
1085 if(!empty($fromId)){
1086 $this->linkEmailToAddress($fromId, 'from');
1090 $replace = array(",",";");
1091 $toaddrs = str_replace($replace, "::", from_html($this->to_addrs));
1092 $exToAddrs = explode("::", $toaddrs);
1094 if(!empty($exToAddrs)) {
1095 foreach($exToAddrs as $toaddr) {
1096 $toaddr = trim($toaddr);
1097 if(!empty($toaddr)) {
1098 $toId = $this->emailAddress->getEmailGUID($toaddr);
1099 $this->linkEmailToAddress($toId, 'to');
1105 $ccAddrs = str_replace($replace, "::", from_html($this->cc_addrs));
1106 $exccAddrs = explode("::", $ccAddrs);
1108 if(!empty($exccAddrs)) {
1109 foreach($exccAddrs as $ccAddr) {
1110 $ccAddr = trim($ccAddr);
1111 if(!empty($ccAddr)) {
1112 $ccId = $this->emailAddress->getEmailGUID($ccAddr);
1113 $this->linkEmailToAddress($ccId, 'cc');
1119 $bccAddrs = str_replace($replace, "::", from_html($this->bcc_addrs));
1120 $exbccAddrs = explode("::", $bccAddrs);
1121 if(!empty($exbccAddrs)) {
1122 foreach($exbccAddrs as $bccAddr) {
1123 $bccAddr = trim($bccAddr);
1124 if(!empty($bccAddr)) {
1125 $bccId = $this->emailAddress->getEmailGUID($bccAddr);
1126 $this->linkEmailToAddress($bccId, 'bcc');
1132 function linkEmailToAddress($id, $type) {
1133 // TODO: make this update?
1134 $q1 = "SELECT * FROM emails_email_addr_rel WHERE email_id = '{$this->id}' AND email_address_id = '{$id}' AND address_type = '{$type}' AND deleted = 0";
1135 $r1 = $this->db->query($q1);
1136 $a1 = $this->db->fetchByAssoc($r1);
1138 if(!empty($a1) && !empty($a1['id'])) {
1141 $guid = create_guid();
1142 $q2 = "INSERT INTO emails_email_addr_rel VALUES('{$guid}', '{$this->id}', '{$type}', '{$id}', 0)";
1143 $r2 = $this->db->query($q2);
1149 function cleanEmails($emails)
1151 $emails = str_replace(array(",",";"), "::", from_html($emails));
1152 $addrs = explode("::", $emails);
1154 foreach($addrs as $addr) {
1155 $parts = $this->emailAddress->splitEmailAddress($addr);
1156 if(empty($parts["email"])) {
1159 if(!empty($parts["name"])) {
1160 $res[] = "{$parts["name"]} <{$parts["email"]}>";
1162 $res[] .= $parts["email"];
1165 return join(", ", $res);
1168 function saveEmailText() {
1169 $isOracle = ($this->db->dbType == "oci8") ? true : false;
1172 $description = $this->db->quote(trim($this->description));
1173 $description_html = $this->db->quoteForEmail(trim($this->description_html));
1174 $raw_source = $this->db->quote(trim($this->raw_source));
1175 $fromAddressName = $this->db->helper->escape_quote($this->from_addr_name);
1176 $toAddressName = $this->db->helper->escape_quote($this->to_addrs_names);
1177 $ccAddressName = $this->db->helper->escape_quote($this->cc_addrs_names);
1178 $bccAddressName = $this->db->helper->escape_quote($this->bcc_addrs_names);
1179 $replyToAddrName = $this->db->helper->escape_quote($this->reply_to_addr);
1181 if(!$this->new_with_id) {
1182 $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}'";
1184 $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)";
1186 $this->db->query($q);
1192 ///////////////////////////////////////////////////////////////////////////
1194 function retrieve($id, $encoded=true, $deleted=true) {
1195 // cn: bug 11915, return SugarBean's retrieve() call bean instead of $this
1196 $ret = parent::retrieve($id, $encoded, $deleted);
1199 $ret->retrieveEmailText();
1200 $ret->retrieveEmailAddresses();
1201 $ret->raw_source = to_html($ret->safeText(from_html($ret->raw_source)));
1202 $ret->description = to_html($ret->safeText(from_html($ret->description)));
1203 $ret->description_html = $ret->safeText($ret->description_html);
1205 $ret->date_start = '';
1206 $ret->time_start = '';
1207 $dateSent = explode(' ', $ret->date_sent);
1208 if (!empty($dateSent)) {
1209 $ret->date_start = $dateSent[0];
1210 if ( isset($dateSent[1]) )
1211 $ret->time_start = $dateSent[1];
1214 foreach($ret as $k => $v) {
1223 * Retrieves email addresses from GUIDs
1225 function retrieveEmailAddresses() {
1228 $q = "SELECT email_address, address_type
1229 FROM emails_email_addr_rel eam
1230 JOIN email_addresses ea ON ea.id = eam.email_address_id
1231 WHERE eam.email_id = '{$this->id}' AND eam.deleted=0";
1232 $r = $this->db->query($q);
1234 while($a = $this->db->fetchByAssoc($r)) {
1235 if(!isset($return[$a['address_type']])) {
1236 $return[$a['address_type']] = array();
1238 $return[$a['address_type']][] = $a['email_address'];
1241 if(count($return) > 0) {
1242 if(isset($return['from'])) {
1243 $this->from_addr = implode(", ", $return['from']);
1245 if(isset($return['to'])) {
1246 $this->to_addrs = implode(", ", $return['to']);
1248 if(isset($return['cc'])) {
1249 $this->cc_addrs = implode(", ", $return['cc']);
1251 if(isset($return['bcc'])) {
1252 $this->bcc_addrs = implode(", ", $return['bcc']);
1258 * Handles longtext fields
1260 function retrieveEmailText() {
1261 $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}'";
1262 $r = $this->db->query($q);
1263 $a = $this->db->fetchByAssoc($r, -1, false);
1265 $this->description = $a['description'];
1266 $this->description_html = $a['description_html'];
1267 $this->raw_source = $a['raw_source'];
1268 $this->from_addr_name = $a['from_addr'];
1269 $this->reply_to_addr = $a['reply_to_addr'];
1270 $this->to_addrs_names = $a['to_addrs'];
1271 $this->cc_addrs_names = $a['cc_addrs'];
1272 $this->bcc_addrs_names = $a['bcc_addrs'];
1275 function delete($id='') {
1279 $q = "UPDATE emails SET deleted = 1 WHERE id = '{$id}'";
1280 $qt = "UPDATE emails_text SET deleted = 1 WHERE email_id = '{$id}'";
1281 $r = $this->db->query($q);
1282 $rt = $this->db->query($qt);
1286 * creates the standard "Forward" info at the top of the forwarded message
1289 function getForwardHeader() {
1290 global $mod_strings;
1291 global $current_user;
1293 //$from = str_replace(array(">","<"), array(")","("), $this->from_name);
1294 $from = to_html($this->from_name);
1295 $subject = to_html($this->name);
1296 $ret = "<br /><br />";
1297 $ret .= $this->replyDelimiter."{$mod_strings['LBL_FROM']} {$from}<br />";
1298 $ret .= $this->replyDelimiter."{$mod_strings['LBL_DATE_SENT']} {$this->date_sent}<br />";
1299 $ret .= $this->replyDelimiter."{$mod_strings['LBL_TO']} {$this->to_addrs}<br />";
1300 $ret .= $this->replyDelimiter."{$mod_strings['LBL_CC']} {$this->cc_addrs}<br />";
1301 $ret .= $this->replyDelimiter."{$mod_strings['LBL_SUBJECT']} {$subject}<br />";
1302 $ret .= $this->replyDelimiter."<br />";
1305 //return from_html($ret);
1309 * retrieves Notes that belong to this Email and stuffs them into the "attachments" attribute
1311 function getNotes($id, $duplicate=false) {
1312 if(!class_exists('Note')) {
1316 $exRemoved = array();
1317 if(isset($_REQUEST['removeAttachment'])) {
1318 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1321 $noteArray = array();
1322 $q = "SELECT id FROM notes WHERE parent_id = '".$id."'";
1323 $r = $this->db->query($q);
1325 while($a = $this->db->fetchByAssoc($r)) {
1326 if(!in_array($a['id'], $exRemoved)) {
1328 $note->retrieve($a['id']);
1330 // duplicate actual file when creating forwards
1332 if(!class_exists('UploadFile')) {
1333 require_once('include/upload_file.php');
1335 // save a brand new Note
1336 $noteDupe->id = create_guid();
1337 $noteDupe->new_with_id = true;
1338 $noteDupe->parent_id = $this->id;
1339 $noteDupe->parent_type = $this->module_dir;
1341 $noteFile = new UploadFile('none');
1342 $noteFile->duplicate_file($a['id'], $note->id, $note->filename);
1346 // add Note to attachments array
1347 $this->attachments[] = $note;
1353 * creates the standard "Reply" info at the top of the forwarded message
1356 function getReplyHeader() {
1357 global $mod_strings;
1358 global $current_user;
1360 $from = str_replace(array(">","<", ">","<"), array(")","(",")","("), $this->from_name);
1361 $ret = "<br>{$mod_strings['LBL_REPLY_HEADER_1']} {$this->date_start}, {$this->time_start}, {$from} {$mod_strings['LBL_REPLY_HEADER_2']}";
1363 return from_html($ret);
1367 * Quotes plain-text email text
1368 * @param string $text
1371 function quotePlainTextEmail($text) {
1375 $desc = nl2br(trim($text));
1376 $exDesc = explode('<br />', $desc);
1378 foreach($exDesc as $k => $line) {
1379 $quoted .= '> '.trim($line)."\r";
1386 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1387 * @param string $text HTML text to quote
1390 function quoteHtmlEmail($text) {
1391 $text = trim(from_html($text));
1396 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1402 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1403 * @param string $text HTML text to quote
1406 function quoteHtmlEmailForNewEmailUI($text) {
1407 $text = trim($text);
1412 $text = str_replace("\n", "\n<BR/>", $text);
1413 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1420 ///////////////////////////////////////////////////////////////////////////
1423 * Safes description text (both HTML and Plain Text) for display
1424 * @param string str The text to safe
1425 * @return string Safed text
1427 function safeText($str) {
1429 $this->safe->clear();
1430 $ret = $this->safe->parse($str);
1432 // Julian's XSS cleaner
1433 $potentials = clean_xss($str, false);
1435 if(is_array($potentials) && !empty($potentials)) {
1436 //_ppl($potentials);
1437 foreach($potentials as $bad) {
1438 $ret = str_replace($bad, "", $ret);
1442 // clean <HTML> and <BODY> tags
1443 $html = '#<\\\\\?HTML[\w =\'\"\&]*>#sim';
1444 $body = '#<\\\\\?BODY[\w =\'\"\&]*>#sim';
1446 $ret = preg_replace($html, "", $ret);
1447 $ret = preg_replace($body, "", $ret);
1453 * Ensures that the user is able to send outbound emails
1455 function check_email_settings() {
1456 global $current_user;
1458 $mail_fromaddress = $current_user->emailAddress->getPrimaryAddress($current_user);
1459 $replyToName = $current_user->getPreference('mail_fromname');
1460 $mail_fromname = (!empty($replyToName)) ? $current_user->getPreference('mail_fromname') : $current_user->full_name;
1462 if(empty($mail_fromaddress)) {
1465 if(empty($mail_fromname)) {
1469 $send_type = $current_user->getPreference('mail_sendtype') ;
1470 if (!empty($send_type) && $send_type == "SMTP") {
1471 $mail_smtpserver = $current_user->getPreference('mail_smtpserver');
1472 $mail_smtpport = $current_user->getPreference('mail_smtpport');
1473 $mail_smtpauth_req = $current_user->getPreference('mail_smtpauth_req');
1474 $mail_smtpuser = $current_user->getPreference('mail_smtpuser');
1475 $mail_smtppass = $current_user->getPreference('mail_smtppass');
1476 if (empty($mail_smtpserver) ||
1477 empty($mail_smtpport) ||
1478 (!empty($mail_smtpauth_req) && ( empty($mail_smtpuser) || empty($mail_smtppass)))
1487 * outputs JS to set fields in the MassUpdate form in the "My Inbox" view
1489 function js_set_archived() {
1490 global $mod_strings;
1492 <script type="text/javascript" language="JavaScript"><!-- Begin
1493 function setArchived() {
1494 var form = document.getElementById("MassUpdate");
1495 var status = document.getElementById("mass_status");
1498 for(var i=0; i < form.elements.length; i++) {
1499 if(form.elements[i].name == "mass[]") {
1500 if(form.elements[i].checked == true) {
1507 var user = document.getElementById("mass_assigned_user_name");
1508 var team = document.getElementById("team");
1511 for(var j=0; j<status.length; j++) {
1512 if(status.options[j].value == "archived") {
1513 status.options[j].selected = true;
1514 status.selectedIndex = j; // for IE
1520 alert("'.$mod_strings['ERR_ARCHIVE_EMAIL'].'");
1524 // End --></script>';
1529 * replaces the javascript in utils.php - more specialized
1531 function u_get_clear_form_js($type='', $group='', $assigned_user_id='') {
1534 $uAssigned_user_id = '';
1536 if(!empty($type)) { $uType = '&type='.$type; }
1537 if(!empty($group)) { $uGroup = '&group='.$group; }
1538 if(!empty($assigned_user_id)) { $uAssigned_user_id = '&assigned_user_id='.$assigned_user_id; }
1541 <script type="text/javascript" language="JavaScript"><!-- Begin
1542 function clear_form(form) {
1543 var newLoc = "index.php?action=" + form.action.value + "&module=" + form.module.value + "&query=true&clear_query=true'.$uType.$uGroup.$uAssigned_user_id.'";
1544 if(typeof(form.advanced) != "undefined"){
1545 newLoc += "&advanced=" + form.advanced.value;
1547 document.location.href= newLoc;
1549 // End --></script>';
1553 function pickOneButton() {
1555 global $mod_strings;
1556 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_GRAB_TITLE'].'"
1557 accessKey="'.$mod_strings['LBL_BUTTON_GRAB_KEY'].'"
1559 type="button" name="button"
1560 onClick="window.location=\'index.php?module=Emails&action=Grab\';"
1561 style="margin-bottom:2px"
1562 value=" '.$mod_strings['LBL_BUTTON_GRAB'].' "></div>';
1567 * Determines what Editor (HTML or Plain-text) the current_user uses;
1568 * @return string Editor type
1570 function getUserEditorPreference() {
1571 global $sugar_config;
1572 global $current_user;
1576 if(!isset($sugar_config['email_default_editor'])) {
1577 $sugar_config = $current_user->setDefaultsInConfig();
1580 $userEditor = $current_user->getPreference('email_editor_option');
1581 $systemEditor = $sugar_config['email_default_editor'];
1583 if($userEditor != '') {
1584 $editor = $userEditor;
1586 $editor = $systemEditor;
1593 * takes the mess we pass from EditView and tries to create some kind of order
1594 * @param array addrs
1595 * @param array addrs_ids (from contacts)
1596 * @param array addrs_names (from contacts);
1597 * @param array addrs_emails (from contacts);
1598 * @return array Parsed assoc array to feed to PHPMailer
1600 function parse_addrs($addrs, $addrs_ids, $addrs_names, $addrs_emails) {
1601 // cn: bug 9406 - enable commas to separate email addresses
1602 $addrs = str_replace(",", ";", $addrs);
1604 $ltgt = array('<','>');
1605 $gtlt = array('<','>');
1608 $addrs = str_replace($ltgt, '', $addrs);
1609 $addrs_arr = explode(";",$addrs);
1610 $addrs_arr = $this->remove_empty_fields($addrs_arr);
1611 $addrs_ids_arr = explode(";",$addrs_ids);
1612 $addrs_ids_arr = $this->remove_empty_fields($addrs_ids_arr);
1613 $addrs_emails_arr = explode(";",$addrs_emails);
1614 $addrs_emails_arr = $this->remove_empty_fields($addrs_emails_arr);
1615 $addrs_names_arr = explode(";",$addrs_names);
1616 $addrs_names_arr = $this->remove_empty_fields($addrs_names_arr);
1618 ///////////////////////////////////////////////////////////////////////
1619 //// HANDLE EMAILS HAND-WRITTEN
1620 $contactRecipients = array();
1621 $knownEmails = array();
1623 foreach($addrs_arr as $i => $v) {
1625 continue; // skip any "blanks" - will always have 1
1627 $recipient = array();
1629 //// get the email to see if we're dealing with a dupe
1630 //// what crappy coding
1631 preg_match("/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i",$v, $match);
1633 if(!empty($match[0]) && !in_array(trim($match[0]), $knownEmails)) {
1634 $knownEmails[] = $match[0];
1635 $recipient['email'] = $match[0];
1637 //// handle the Display name
1638 $display = trim(str_replace($match[0], '', $v));
1640 //// only trigger a "displayName" <email@address> when necessary
1641 if(isset($addrs_names_arr[$i])){
1642 $recipient['display'] = $addrs_names_arr[$i];
1644 else if(!empty($display)) {
1645 $recipient['display'] = $display;
1647 if(isset($addrs_ids_arr[$i]) && $addrs_emails_arr[$i] == $match[0]){
1648 $recipient['contact_id'] = $addrs_ids_arr[$i];
1650 $return[] = $recipient;
1657 function remove_empty_fields(&$arr) {
1660 foreach($arr as $field) {
1661 $field = trim($field);
1665 array_push($newarr,$field);
1671 * handles attachments of various kinds when sending email
1673 function handleAttachments() {
1678 global $mod_strings;
1680 ///////////////////////////////////////////////////////////////////////////
1681 //// ATTACHMENTS FROM DRAFTS
1682 if(($this->type == 'out' || $this->type == 'draft') && $this->status == 'draft' && isset($_REQUEST['record'])) {
1683 $this->getNotes($_REQUEST['record']); // cn: get notes from OLD email for use in new email
1685 //// END ATTACHMENTS FROM DRAFTS
1686 ///////////////////////////////////////////////////////////////////////////
1688 ///////////////////////////////////////////////////////////////////////////
1689 //// ATTACHMENTS FROM FORWARDS
1690 // Bug 8034 Jenny - Need the check for type 'draft' here to handle cases where we want to save
1691 // forwarded messages as drafts. We still need to save the original message's attachments.
1692 if(($this->type == 'out' || $this->type == 'draft') &&
1693 isset($_REQUEST['origType']) && $_REQUEST['origType'] == 'forward' &&
1694 isset($_REQUEST['return_id']) && !empty($_REQUEST['return_id'])
1696 $this->getNotes($_REQUEST['return_id'], true);
1699 // cn: bug 8034 - attachments from forward/replies lost when saving in draft
1700 if(isset($_REQUEST['prior_attachments']) && !empty($_REQUEST['prior_attachments']) && $this->new_with_id == true) {
1701 $exIds = explode(",", $_REQUEST['prior_attachments']);
1702 if(!isset($_REQUEST['template_attachment'])) {
1703 $_REQUEST['template_attachment'] = array();
1705 $_REQUEST['template_attachment'] = array_merge($_REQUEST['template_attachment'], $exIds);
1707 //// END ATTACHMENTS FROM FORWARDS
1708 ///////////////////////////////////////////////////////////////////////////
1710 ///////////////////////////////////////////////////////////////////////////
1711 //// ATTACHMENTS FROM TEMPLATES
1712 // to preserve individual email integrity, we must dupe Notes and associated files
1713 // for each outbound email - good for integrity, bad for filespace
1714 if(isset($_REQUEST['template_attachment']) && !empty($_REQUEST['template_attachment'])) {
1715 $removeArr = array();
1716 $noteArray = array();
1718 if(isset($_REQUEST['temp_remove_attachment']) && !empty($_REQUEST['temp_remove_attachment'])) {
1719 $removeArr = $_REQUEST['temp_remove_attachment'];
1723 foreach($_REQUEST['template_attachment'] as $noteId) {
1724 if(in_array($noteId, $removeArr)) {
1727 $noteTemplate = new Note();
1728 $noteTemplate->retrieve($noteId);
1729 $noteTemplate->id = create_guid();
1730 $noteTemplate->new_with_id = true; // duplicating the note with files
1731 $noteTemplate->parent_id = $this->id;
1732 $noteTemplate->parent_type = $this->module_dir;
1733 $noteTemplate->date_entered = '';
1734 $noteTemplate->save();
1736 $noteFile = new UploadFile('none');
1737 $noteFile->duplicate_file($noteId, $noteTemplate->id, $noteTemplate->filename);
1738 $noteArray[] = $noteTemplate;
1740 $this->attachments = array_merge($this->attachments, $noteArray);
1742 //// END ATTACHMENTS FROM TEMPLATES
1743 ///////////////////////////////////////////////////////////////////////////
1745 ///////////////////////////////////////////////////////////////////////////
1746 //// ADDING NEW ATTACHMENTS
1747 $max_files_upload = 10;
1748 // Jenny - Bug 8211 Since attachments for drafts have already been processed,
1749 // we don't need to re-process them.
1750 if($this->status != "draft") {
1751 $notes_list = array();
1752 if(!empty($this->id) && !$this->new_with_id) {
1754 $where = "notes.parent_id='{$this->id}'";
1755 $notes_list = $note->get_full_list("", $where, true);
1757 $this->attachments = array_merge($this->attachments, $notes_list);
1759 // cn: Bug 5995 - rudimentary error checking
1760 $filesError = array(
1761 0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
1762 1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
1763 2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
1764 3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
1765 4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
1766 5 => 'UNKNOWN ERROR',
1767 6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
1768 7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
1771 for($i = 0; $i < $max_files_upload; $i++) {
1772 // cn: Bug 5995 - rudimentary error checking
1773 if (!isset($_FILES["email_attachment{$i}"])) {
1774 $GLOBALS['log']->debug("Email Attachment {$i} does not exist.");
1777 if($_FILES['email_attachment'.$i]['error'] != 0 && $_FILES['email_attachment'.$i]['error'] != 4) {
1778 $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment'.$i]['error']]);
1783 $note->parent_id = $this->id;
1784 $note->parent_type = $this->module_dir;
1785 $upload_file = new UploadFile('email_attachment'.$i);
1787 if(empty($upload_file)) {
1791 if(isset($_FILES['email_attachment'.$i]) && $upload_file->confirm_upload()) {
1792 $note->filename = $upload_file->get_stored_file_name();
1793 $note->file = $upload_file;
1794 $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$note->file->original_file_name;
1796 $this->attachments[] = $note;
1800 $this->saved_attachments = array();
1801 foreach($this->attachments as $note) {
1802 if(!empty($note->id)) {
1803 array_push($this->saved_attachments, $note);
1806 $note->parent_id = $this->id;
1807 $note->parent_type = 'Emails';
1808 $note->file_mime_type = $note->file->mime_type;
1809 $note_id = $note->save();
1811 $this->saved_attachments[] = $note;
1813 $note->id = $note_id;
1814 $note->file->final_move($note->id);
1816 //// END NEW ATTACHMENTS
1817 ///////////////////////////////////////////////////////////////////////////
1819 ///////////////////////////////////////////////////////////////////////////
1820 //// ATTACHMENTS FROM DOCUMENTS
1821 for($i=0; $i<10; $i++) {
1822 if(isset($_REQUEST['documentId'.$i]) && !empty($_REQUEST['documentId'.$i])) {
1823 $doc = new Document();
1824 $docRev = new DocumentRevision();
1825 $docNote = new Note();
1826 $noteFile = new UploadFile('none');
1828 $doc->retrieve($_REQUEST['documentId'.$i]);
1829 $docRev->retrieve($doc->document_revision_id);
1831 $this->saved_attachments[] = $docRev;
1833 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
1834 $docNote->name = $docRev->getDocumentRevisionNameForDisplay();
1835 $docNote->filename = $docRev->filename;
1836 $docNote->description = $doc->description;
1837 $docNote->parent_id = $this->id;
1838 $docNote->parent_type = 'Emails';
1839 $docNote->file_mime_type = $docRev->file_mime_type;
1840 $docId = $docNote = $docNote->save();
1842 $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
1846 //// END ATTACHMENTS FROM DOCUMENTS
1847 ///////////////////////////////////////////////////////////////////////////
1849 ///////////////////////////////////////////////////////////////////////////
1850 //// REMOVE ATTACHMENTS
1851 if(isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
1852 foreach($_REQUEST['remove_attachment'] as $noteId) {
1853 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1854 $this->db->query($q);
1858 //this will remove attachments that have been selected to be removed from drafts.
1859 if(isset($_REQUEST['removeAttachment']) && !empty($_REQUEST['removeAttachment'])) {
1860 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1861 foreach($exRemoved as $noteId) {
1862 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1863 $this->db->query($q);
1866 //// END REMOVE ATTACHMENTS
1867 ///////////////////////////////////////////////////////////////////////////
1872 * Determines if an email body (HTML or Plain) has a User signature already in the content
1873 * @param array Array of signatures
1876 function hasSignatureInBody($sig) {
1877 // strpos can't handle line breaks - normalize
1878 $html = $this->removeAllNewlines($this->description_html);
1879 $htmlSig = $this->removeAllNewlines($sig['signature_html']);
1880 $plain = $this->removeAllNewlines($this->description);
1881 $plainSig = $this->removeAllNewlines($sig['signature']);
1883 // cn: bug 11621 - empty sig triggers notice error
1884 if(!empty($htmlSig) && false !== strpos($html, $htmlSig)) {
1886 } elseif(!empty($plainSig) && false !== strpos($plain, $plainSig)) {
1895 * @param string String to be normalized
1898 function removeAllNewlines($str) {
1899 $bad = array("\r\n", "\n\r", "\n", "\r");
1900 $good = array('', '', '', '');
1902 return str_replace($bad, $good, strip_tags(br2nl(from_html($str))));
1908 * Set navigation anchors to aid DetailView record navigation (VCR buttons)
1909 * @param string uri The URI from the referring page (always ListView)
1910 * @return array start Array of the URI broken down with a special "current_view" for My Inbox Navs
1912 function getStartPage($uri) {
1913 if(strpos($uri, '&')) { // "&" to ensure that we can explode the GET vars - else we're gonna trigger a Notice error
1914 $serial = substr($uri, (strpos($uri, '?')+1), strlen($uri));
1915 $exUri = explode('&', $serial);
1916 $start = array('module' => '', 'action' => '', 'group' => '', 'record' => '', 'type' => '');
1918 foreach($exUri as $k => $pair) {
1919 $exPair = explode('=', $pair);
1920 $start[$exPair[0]] = $exPair[1];
1923 // specific views for current_user
1924 if(isset($start['assigned_user_id'])) {
1925 $start['current_view'] = "{$start['action']}&module={$start['module']}&assigned_user_id={$start['assigned_user_id']}&type={$start['type']}";
1935 * preps SMTP info for email transmission
1936 * @param object mail SugarPHPMailer object
1937 * @param string mailer_id
1938 * @param string ieId
1939 * @return object mail SugarPHPMailer object
1941 function setMailer($mail, $mailer_id='', $ieId='') {
1942 global $current_user;
1944 require_once("include/OutboundEmail/OutboundEmail.php");
1945 $oe = new OutboundEmail();
1946 $oe = $oe->getInboundMailerSettings($current_user, $mailer_id, $ieId);
1948 // ssl or tcp - keeping outside isSMTP b/c a default may inadvertantly set ssl://
1949 $mail->protocol = ($oe->mail_smtpssl) ? "ssl://" : "tcp://";
1950 if($oe->mail_sendtype == "SMTP")
1952 //Set mail send type information
1953 $mail->Mailer = "smtp";
1954 $mail->Host = $oe->mail_smtpserver;
1955 $mail->Port = $oe->mail_smtpport;
1956 if ($oe->mail_smtpssl == 1) {
1957 $mail->SMTPSecure = 'ssl';
1959 if ($oe->mail_smtpssl == 2) {
1960 $mail->SMTPSecure = 'tls';
1963 if($oe->mail_smtpauth_req) {
1964 $mail->SMTPAuth = TRUE;
1965 $mail->Username = $oe->mail_smtpuser;
1966 $mail->Password = $oe->mail_smtppass;
1970 $mail->Mailer = "sendmail";
1977 * preps SugarPHPMailer object for HTML or Plain text sends
1978 * @param object SugarPHPMailer instance
1980 function handleBody($mail) {
1981 global $current_user;
1982 global $sugar_config;
1983 ///////////////////////////////////////////////////////////////////////
1984 //// HANDLE EMAIL FORMAT PREFERENCE
1985 // the if() below is HIGHLY dependent on the Javascript unchecking the Send HTML Email box
1987 if( (isset($_REQUEST['setEditor']) /* from Email EditView navigation */
1988 && $_REQUEST['setEditor'] == 1
1989 && trim($_REQUEST['description_html']) != '')
1990 || trim($this->description_html) != '' /* from email templates */
1991 && $current_user->getPreference('email_editor_option', 'global') !== 'plain' //user preference is not set to plain text
1993 $this->handleBodyInHTMLformat($mail);
1996 $this->description_html = '';
1997 $mail->IsHTML(false);
1998 $plainText = from_html($this->description);
1999 $plainText = str_replace(" ", " ", $plainText);
2000 $plainText = str_replace("</p>", "</p><br />", $plainText);
2001 $plainText = strip_tags(br2nl($plainText));
2002 $plainText = str_replace("&", "&", $plainText);
2003 $plainText = str_replace("'", "'", $plainText);
2004 $mail->Body = wordwrap($plainText, 996);
2005 $mail->Body = $this->decodeDuringSend($mail->Body);
2006 $this->description = $mail->Body;
2009 // wp: if plain text version has lines greater than 998, use base64 encoding
2010 foreach(explode("\n", ($mail->ContentType == "text/html") ? $mail->AltBody : $mail->Body) as $line) {
2011 if(strlen($line) > 998) {
2012 $mail->Encoding = 'base64';
2016 //// HANDLE EMAIL FORMAT PREFERENCE
2017 ///////////////////////////////////////////////////////////////////////
2023 * Retrieve function from handlebody() to unit test easily
2025 * @return formatted $mail body
2027 function handleBodyInHTMLformat($mail) {
2028 global $current_user;
2029 global $sugar_config;
2030 // wp: if body is html, then insert new lines at 996 characters. no effect on client side
2031 // due to RFC 2822 which limits email lines to 998
2032 $mail->IsHTML(true);
2033 $body = from_html(wordwrap($this->description_html, 996));
2034 $mail->Body = $body;
2037 // new plan is to use the selected type (html or plain) to fill the other
2038 $plainText = from_html($this->description_html);
2039 $plainText = strip_tags(br2nl($plainText));
2040 $mail->AltBody = $plainText;
2041 $this->description = $plainText;
2043 $fileBasePath = "{$sugar_config['cache_dir']}images/";
2044 $filePatternSearch = "{$sugar_config['cache_dir']}";
2045 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2046 $filePatternSearch = $filePatternSearch . "images\/";
2047 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2050 preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2051 foreach($matches[0] as $match) {
2052 $filename = str_replace($fileBasePath, '', $match);
2053 $filename = urldecode(substr($filename, 0, -1));
2055 $file_location = clean_path(getcwd()."/{$sugar_config['cache_dir']}images/{$filename}");
2056 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2058 if(file_exists($file_location)) {
2059 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2063 //replace references to cache with cid tag
2064 $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2065 $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2066 // remove bad img line from outbound email
2067 $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2068 $mail->Body = preg_replace($regex, '', $mail->Body);
2070 $fileBasePath = "{$sugar_config['upload_dir']}";
2071 $filePatternSearch = "{$sugar_config['upload_dir']}";
2072 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2073 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2076 preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2077 foreach($matches[0] as $match) {
2078 $filename = str_replace($fileBasePath, '', $match);
2079 $filename = urldecode(substr($filename, 0, -1));
2081 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$filename}");
2082 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2084 if(file_exists($file_location)) {
2085 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2089 //replace references to cache with cid tag
2090 $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2091 $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2093 // remove bad img line from outbound email
2094 $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2095 $mail->Body = preg_replace($regex, '', $mail->Body);
2098 //Replace any embeded images using the secure entryPoint for src url.
2099 $noteImgRegex = "/<img[^>]*[\s]+src[^=]*=\"index.php\?entryPoint=download\&id=([^\&]*)[^>]*>/im";
2100 $embededImageMatches = array();
2101 preg_match_all($noteImgRegex, $mail->Body, $embededImageMatches,PREG_SET_ORDER);
2103 foreach ($embededImageMatches as $singleMatch )
2105 $fullMatch = $singleMatch[0];
2106 $noteId = $singleMatch[1];
2108 $filename = $noteId;
2110 //Retrieve note for mimetype
2111 $tmpNote = new Note();
2112 $tmpNote->retrieve($noteId);
2113 //Replace the src part of img tag with new cid tag
2114 $cidRegex = "/src=\"([^\"]*)\"/im";
2115 $replaceMatch = preg_replace($cidRegex, "src=\"cid:$noteId\"", $fullMatch);
2117 //Replace the body, old tag for new tag
2118 $mail->Body = str_replace($fullMatch, $replaceMatch, $mail->Body);
2121 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$noteId}");
2123 if(file_exists($file_location))
2124 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $tmpNote->file_mime_type);
2129 $mail->Body = from_html($mail->Body);
2134 * @return bool True on success
2137 global $mod_strings,$app_strings;
2138 global $current_user;
2139 global $sugar_config;
2141 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
2142 $mail = new SugarPHPMailer();
2144 foreach ($this->to_addrs_arr as $addr_arr) {
2145 if ( empty($addr_arr['display'])) {
2146 $mail->AddAddress($addr_arr['email'], "");
2148 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
2151 foreach ($this->cc_addrs_arr as $addr_arr) {
2152 if ( empty($addr_arr['display'])) {
2153 $mail->AddCC($addr_arr['email'], "");
2155 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2159 foreach ($this->bcc_addrs_arr as $addr_arr) {
2160 if ( empty($addr_arr['display'])) {
2161 $mail->AddBCC($addr_arr['email'], "");
2163 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2167 $mail = $this->setMailer($mail);
2170 if(!empty($this->from_addr)) {
2171 $mail->From = $this->from_addr;
2173 $mail->From = $current_user->getPreference('mail_fromaddress');
2174 $this->from_addr = $mail->From;
2177 if(!empty($this->from_name)) {
2178 $mail->FromName = $this->from_name;
2180 $mail->FromName = $current_user->getPreference('mail_fromname');
2181 $this->from_name = $mail->FromName;
2184 //Reply to information for case create and autoreply.
2185 if(!empty($this->reply_to_name)) {
2186 $ReplyToName = $this->reply_to_name;
2188 $ReplyToName = $mail->FromName;
2190 if(!empty($this->reply_to_addr)) {
2191 $ReplyToAddr = $this->reply_to_addr;
2193 $ReplyToAddr = $mail->From;
2195 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
2196 $mail->AddReplyTo($ReplyToAddr,$locale->translateCharsetMIME(trim($ReplyToName), 'UTF-8', $OBCharset));
2198 //$mail->Subject = html_entity_decode($this->name, ENT_QUOTES, 'UTF-8');
2199 $mail->Subject = $this->name;
2201 ///////////////////////////////////////////////////////////////////////
2203 foreach($this->saved_attachments as $note) {
2204 $mime_type = 'text/plain';
2205 if($note->object_name == 'Note') {
2206 if(!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) { // brandy-new file upload/attachment
2207 $file_location = $sugar_config['upload_dir'].$note->id;
2208 $filename = $note->file->original_file_name;
2209 $mime_type = $note->file->mime_type;
2210 } else { // attachment coming from template/forward
2211 $file_location = rawurldecode(UploadFile::get_file_path($note->filename,$note->id));
2212 // cn: bug 9723 - documents from EmailTemplates sent with Doc Name, not file name.
2213 $filename = !empty($note->filename) ? $note->filename : $note->name;
2214 $mime_type = $note->file_mime_type;
2216 } elseif($note->object_name == 'DocumentRevision') { // from Documents
2217 $filePathName = $note->id;
2218 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
2219 $filename = $note->getDocumentRevisionNameForDisplay();
2220 $file_location = getcwd().'/'.$GLOBALS['sugar_config']['upload_dir'].$filePathName;
2221 $mime_type = $note->file_mime_type;
2224 // strip out the "Email attachment label if exists
2225 $filename = str_replace($mod_strings['LBL_EMAIL_ATTACHMENT'].': ', '', $filename);
2227 //is attachment in our list of bad files extensions? If so, append .txt to file location
2228 //get position of last "." in file name
2229 $file_ext_beg = strrpos($file_location,".");
2231 //get file extension
2232 if($file_ext_beg >0){
2233 $file_ext = substr($file_location, $file_ext_beg+1 );
2235 //check to see if this is a file with extension located in "badext"
2236 foreach($sugar_config['upload_badext'] as $badExt) {
2237 if(strtolower($file_ext) == strtolower($badExt)) {
2238 //if found, then append with .txt to filename and break out of lookup
2239 //this will make sure that the file goes out with right extension, but is stored
2241 $file_location = $file_location . ".txt";
2242 break; // no need to look for more
2245 $mail->AddAttachment($file_location,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
2248 if($note->embed_flag == true) {
2250 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64',$mime_type);
2253 //// END ATTACHMENTS
2254 ///////////////////////////////////////////////////////////////////////
2256 $mail = $this->handleBody($mail);
2258 $GLOBALS['log']->debug('Email sending --------------------- ');
2260 ///////////////////////////////////////////////////////////////////////
2261 //// I18N TRANSLATION
2262 $mail->prepForOutbound();
2263 //// END I18N TRANSLATION
2264 ///////////////////////////////////////////////////////////////////////
2267 ///////////////////////////////////////////////////////////////////
2268 //// INBOUND EMAIL HANDLING
2270 if(!empty($_REQUEST['inbound_email_id'])) {
2271 $ieMail = new Email();
2272 $ieMail->retrieve($_REQUEST['inbound_email_id']);
2273 $ieMail->status = 'replied';
2276 $GLOBALS['log']->debug(' --------------------- buh bye -- sent successful');
2277 //// END INBOUND EMAIL HANDLING
2278 ///////////////////////////////////////////////////////////////////
2281 $GLOBALS['log']->debug($app_strings['LBL_EMAIL_ERROR_PREPEND'].$mail->ErrorInfo);
2286 function listviewACLHelper(){
2287 $array_assign = parent::listviewACLHelper();
2289 if(!empty($this->parent_name)){
2291 if(!empty($this->parent_name_owner)){
2292 global $current_user;
2293 $is_owner = $current_user->id == $this->parent_name_owner;
2296 if(!ACLController::moduleSupportsACL($this->parent_type) || ACLController::checkAccess($this->parent_type, 'view', $is_owner)){
2297 $array_assign['PARENT'] = 'a';
2299 $array_assign['PARENT'] = 'span';
2302 if(!empty($this->contact_name)) {
2303 if(!empty($this->contact_name_owner)) {
2304 global $current_user;
2305 $is_owner = $current_user->id == $this->contact_name_owner;
2308 if(ACLController::checkAccess('Contacts', 'view', $is_owner)) {
2309 $array_assign['CONTACT'] = 'a';
2311 $array_assign['CONTACT'] = 'span';
2314 return $array_assign;
2317 function getSystemDefaultEmail() {
2320 $r1 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromaddress\'');
2321 $r2 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromname\'');
2322 $a1 = $this->db->fetchByAssoc($r1);
2323 $a2 = $this->db->fetchByAssoc($r2);
2325 $email['email'] = $a1['value'];
2326 $email['name'] = $a2['value'];
2332 function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false) {
2334 if ($return_array) {
2335 return parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, $return_array,$parentbean, $singleSelect);
2337 $custom_join = $this->custom_fields->getJOIN();
2339 $query = "SELECT ".$this->table_name.".*, users.user_name as assigned_user_name\n";
2342 $query .= $custom_join['select'];
2344 $query .= " FROM emails\n";
2345 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2346 $query .= " LEFT JOIN emails_beans ON emails.id = emails_beans.email_id\n";
2349 $query .= " LEFT JOIN users ON emails.assigned_user_id=users.id \n";
2350 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2352 $query .= " JOIN contacts ON contacts.id= emails_beans.bean_id AND emails_beans.bean_module='Contacts' and contacts.deleted=0 \n";
2356 $query .= $custom_join['join'];
2359 if($show_deleted == 0) {
2360 $where_auto = " emails.deleted=0 \n";
2361 }else if($show_deleted == 1){
2362 $where_auto = " emails.deleted=1 \n";
2366 $query .= "WHERE $where AND ".$where_auto;
2368 $query .= "WHERE ".$where_auto;
2371 $query .= " ORDER BY $order_by";
2373 $query .= " ORDER BY date_sent DESC";
2379 function fill_in_additional_list_fields() {
2381 $this->fill_in_additional_detail_fields();
2383 $this->link_action = 'DetailView';
2384 ///////////////////////////////////////////////////////////////////////
2385 //populate attachment_image, used to display attachment icon.
2386 $query = "select 1 from notes where notes.parent_id = '$this->id' and notes.deleted = 0";
2387 $result =$this->db->query($query,true," Error filling in additional list fields: ");
2389 $row = $this->db->fetchByAssoc($result);
2392 $this->attachment_image = SugarThemeRegistry::current()->getImage('attachment',"","","");
2394 $this->attachment_image = SugarThemeRegistry::current()->getImage('blank',"","","");
2396 ///////////////////////////////////////////////////////////////////////
2397 if(empty($this->contact_id) && !empty($this->parent_id) && !empty($this->parent_type) && $this->parent_type === 'Contacts' && !empty($this->parent_name) ){
2398 $this->contact_id = $this->parent_id;
2399 $this->contact_name = $this->parent_name;
2403 function fill_in_additional_detail_fields() {
2404 global $app_list_strings,$mod_strings;
2405 // Fill in the assigned_user_name
2406 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id, '');
2407 //if ($this->parent_type == 'Contacts') {
2408 $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 ";
2409 $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";
2410 if(!empty($this->parent_id)){
2411 $query .= " AND contacts.id= '".$this->parent_id."' ";
2412 }else if(!empty($_REQUEST['record'])){
2413 $query .= " AND contacts.id= '".$_REQUEST['record']."' ";
2415 $result =$this->db->query($query,true," Error filling in additional detail fields: ");
2417 // Get the id and the name.
2418 $row = $this->db->fetchByAssoc($result);
2422 $contact = new Contact();
2423 $contact->retrieve($row['id']);
2424 $this->contact_name = $contact->full_name;
2425 $this->contact_phone = $row['phone_work'];
2426 $this->contact_id = $row['id'];
2427 $this->contact_email = $contact->emailAddress->getPrimaryAddress($contact);
2428 $this->contact_name_owner = $row['contact_name_owner'];
2429 $this->contact_name_mod = $row['contact_name_mod'];
2430 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2431 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2432 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2433 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2436 $this->contact_name = '';
2437 $this->contact_phone = '';
2438 $this->contact_id = '';
2439 $this->contact_email = '';
2440 $this->contact_name_owner = '';
2441 $this->contact_name_mod = '';
2442 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2443 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2444 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2445 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2448 $this->created_by_name = get_assigned_user_name($this->created_by);
2449 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
2451 $this->link_action = 'DetailView';
2453 if(!empty($this->type)) {
2454 if($this->type == 'out' && $this->status == 'send_error') {
2455 $this->type_name = $mod_strings['LBL_NOT_SENT'];
2457 $this->type_name = $app_list_strings['dom_email_types'][$this->type];
2460 if(($this->type == 'out' && $this->status == 'send_error') || $this->type == 'draft') {
2461 $this->link_action = 'EditView';
2465 //todo this isset( $app_list_strings['dom_email_status'][$this->status]) is hack for 3261.
2466 if(!empty($this->status) && isset( $app_list_strings['dom_email_status'][$this->status])) {
2467 $this->status_name = $app_list_strings['dom_email_status'][$this->status];
2470 if ( empty($this->name ) && empty($_REQUEST['record'])) {
2471 $this->name = $mod_strings['LBL_NO_SUBJECT'];
2474 $this->fill_in_additional_parent_fields();
2479 function create_export_query(&$order_by, &$where) {
2480 $contact_required = stristr($where, "contacts");
2481 $custom_join = $this->custom_fields->getJOIN(true, true,$where);
2483 if($contact_required) {
2484 $query = "SELECT emails.*, contacts.first_name, contacts.last_name";
2486 $query .= $custom_join['select'];
2489 $query .= " FROM contacts, emails, emails_contacts ";
2490 $where_auto = "emails_contacts.contact_id = contacts.id AND emails_contacts.email_id = emails.id AND emails.deleted=0 AND contacts.deleted=0";
2492 $query = 'SELECT emails.*';
2494 $query .= $custom_join['select'];
2497 $query .= ' FROM emails ';
2498 $where_auto = "emails.deleted=0";
2502 $query .= $custom_join['join'];
2506 $query .= "where $where AND ".$where_auto;
2508 $query .= "where ".$where_auto;
2511 $query .= " ORDER BY $order_by";
2513 $query .= " ORDER BY emails.name";
2517 function get_list_view_data() {
2518 global $app_list_strings;
2520 global $current_user;
2522 global $mod_strings;
2524 $email_fields = $this->get_list_view_array();
2525 $this->retrieveEmailText();
2526 $email_fields['FROM_ADDR'] = $this->from_addr_name;
2527 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); // hard-coding for Home screen ListView
2529 if($this->status != 'replied') {
2530 $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>';
2531 $email_fields['STATUS'] = ($email_fields['REPLY_TO_STATUS'] == 1 ? $mod_strings['LBL_REPLIED'] : $email_fields['STATUS']);
2533 $email_fields['QUICK_REPLY'] = $mod_strings['LBL_REPLIED'];
2535 if(!empty($this->parent_type)) {
2536 $email_fields['PARENT_MODULE'] = $this->parent_type;
2538 switch($this->intent) {
2540 $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>';
2544 $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>';
2548 $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>';
2552 $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>';
2556 $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>';
2569 $email_fields['CREATE_RELATED'] = $this->quickCreateForm();
2575 //BUG 17098 - MFH changed $this->from_addr to $this->to_addrs
2576 $email_fields['CONTACT_NAME'] = empty($this->contact_name) ? '</a>'.$this->trimLongTo($this->to_addrs).'<a>' : $this->contact_name;
2577 $email_fields['CONTACT_ID'] = empty($this->contact_id) ? '' : $this->contact_id;
2578 $email_fields['ATTACHMENT_IMAGE'] = $this->attachment_image;
2579 $email_fields['LINK_ACTION'] = $this->link_action;
2581 if(isset($this->type_name))
2582 $email_fields['TYPE_NAME'] = $this->type_name;
2584 return $email_fields;
2587 function quickCreateForm() {
2588 global $mod_strings, $app_strings, $currentModule, $current_language;
2590 // Coming from the home page via Dashlets
2591 if($currentModule != 'Email')
2592 $mod_strings = return_module_language($current_language, 'Emails');
2593 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>";
2597 * Searches all imported emails and returns the result set as an array.
2600 function searchImportedEmails($sort = '', $direction='')
2602 require_once('include/TimeDate.php');
2604 global $current_user;
2606 global $sugar_config;
2607 global $app_strings;
2609 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
2610 // cn: default to a low number until user specifies otherwise
2611 if(empty($emailSettings['showNumInList']))
2614 $pageSize = $emailSettings['showNumInList'];
2616 if( isset($_REQUEST['start']) && isset($_REQUEST['limit']) )
2617 $page = ceil($_REQUEST['start'] / $_REQUEST['limit']) + 1;
2621 //Determine sort ordering
2623 //Sort ordering parameters in the request do not coincide with actual column names
2624 //so we need to remap them.
2625 $hrSortLocal = array(
2626 'flagged' => 'type',
2627 'status' => 'reply_to_status',
2628 'from' => 'emails_text.from_addr',
2629 'subject' => 'name',
2630 'date' => 'date_sent',
2631 'AssignedTo' => 'assigned_user_id',
2632 'flagged' => 'flagged'
2635 $sort = !empty($_REQUEST['sort']) ? $_REQUEST['sort'] : "";
2636 $direction = !empty($_REQUEST['dir']) ? $_REQUEST['dir'] : "";
2638 $order = ( !empty($sort) && !empty($direction) ) ? " ORDER BY {$hrSortLocal[$sort]} {$direction}" : "";
2640 //Get our main query.
2641 $fullQuery = $this->_genereateSearchImportedEmailsQuery();
2643 //Perform a count query needed for pagination.
2644 $countQuery = $this->create_list_count_query($fullQuery);
2645 $count_rs = $this->db->query($countQuery, false, 'Error executing count query for imported emails search');
2646 $count_row = $this->db->fetchByAssoc($count_rs);
2647 $total_count = ($count_row != null) ? $count_row['c'] : 0;
2649 $start = ($page - 1) * $pageSize;
2652 $rs = $this->db->limitQuery($fullQuery . $order, $start, $pageSize);
2656 while($a = $this->db->fetchByAssoc($rs)) {
2658 $temp['flagged'] = (is_null($a['flagged']) || $a['flagged'] == '0') ? '' : 1;
2659 $temp['status'] = (is_null($a['reply_to_status']) || $a['reply_to_status'] == '0') ? '' : 1;
2660 $temp['subject'] = $a['name'];
2661 $temp['date'] = $timedate->to_display_date_time($a['date_sent']);
2662 $temp['uid'] = $a['id'];
2663 $temp['ieId'] = $a['mailbox_id'];
2664 $temp['site_url'] = $sugar_config['site_url'];
2665 $temp['seen'] = ($a['status'] == 'unread') ? 0 : 1;
2666 $temp['type'] = $a['type'];
2667 $temp['mbox'] = 'sugar::Emails';
2668 $temp['hasAttach'] = $this->doesImportedEmailHaveAttachment($a['id']);
2669 //To and from addresses may be stored in emails_text, if nothing is found, revert to
2670 //regular email addresses.
2671 $temp['to_addrs'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['to_addrs']);
2672 $temp['from'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['from_addr']);
2673 if( empty($temp['from']) || empty($temp['to_addrs']) )
2675 //Retrieve email addresses seperatly.
2676 $tmpEmail = new Email();
2677 $tmpEmail->id = $a['id'];
2678 $tmpEmail->retrieveEmailAddresses();
2679 $temp['from'] = $tmpEmail->from_addr;
2680 $temp['to_addrs'] = $tmpEmail->to_addrs;
2686 $metadata = array();
2687 $metadata['totalCount'] = $total_count;
2688 $metadata['out'] = $return;
2694 * Determine if an imported email has an attachment by examining the relationship to notes.
2699 function doesImportedEmailHaveAttachment($id)
2701 $hasAttachment = FALSE;
2702 $query = "SELECT id FROM notes where parent_id='$id' AND parent_type='Emails' AND file_mime_type is not null AND deleted=0";
2703 $rs = $this->db->limitQuery($query, 0, 1);
2704 $row = $this->db->fetchByAssoc($rs);
2705 if( !empty($row['id']) )
2706 $hasAttachment = TRUE;
2708 return (int) $hasAttachment;
2712 * Generate the query used for searching imported emails.
2714 * @return String Query to be executed.
2716 function _genereateSearchImportedEmailsQuery()
2720 $additionalWhereClause = $this->_generateSearchImportWhereClause();
2724 $query['select'] = "emails.id , emails.mailbox_id, emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status,
2725 emails_text.from_addr, emails_text.to_addrs FROM emails ";
2727 $query['joins'] = " JOIN emails_text on emails.id = emails_text.email_id ";
2729 //Handle from and to addr joins
2730 if( !empty($_REQUEST['from_addr']) )
2732 $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
2733 AND er_from.address_type='from' AND ea_from.email_address='" . strtolower($_REQUEST['from_addr']) . "'";
2736 if( !empty($_REQUEST['to_addrs']) )
2738 $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
2739 AND er_to.address_type='to' AND ea_to.email_address='" . strtolower($_REQUEST['to_addrs']) . "'";
2742 $query['where'] = " WHERE (emails.type= 'inbound' OR emails.type='archived' OR emails.type='out') AND emails.deleted = 0 ";
2743 if( !empty($additionalWhereClause) )
2744 $query['where'] .= "AND $additionalWhereClause";
2746 //If we are explicitly looking for attachments. Do not use a distinct query as the to_addr is defined
2747 //as a text which equals clob in oracle and the distinct query can not be executed correctly.
2748 $addDistinctKeyword = "";
2749 if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 1) //1 indicates yes
2750 $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 )";
2751 else if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 2 )
2752 $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 )";
2754 $fullQuery = "SELECT " . $query['select'] . " " . $query['joins'] . " " . $query['where'];
2759 * Generate the where clause for searching imported emails.
2762 function _generateSearchImportWhereClause()
2766 //The clear button was removed so if a user removes the asisgned user name, do not process the id.
2767 if( empty($_REQUEST['assigned_user_name']) && !empty($_REQUEST['assigned_user_id']) )
2768 unset($_REQUEST['assigned_user_id']);
2770 $availableSearchParam = array('name' => array('table_name' =>'emails'),
2771 'data_parent_id_search' => array('table_name' =>'emails','db_key' => 'parent_id','opp' => '='),
2772 'assigned_user_id' => array('table_name' => 'emails', 'opp' => '=') );
2774 $additionalWhereClause = array();
2775 foreach ($availableSearchParam as $key => $properties)
2777 if( !empty($_REQUEST[$key]) )
2779 $db_key = isset($properties['db_key']) ? $properties['db_key'] : $key;
2780 $searchValue = $_REQUEST[$key];
2782 $opp = isset($properties['opp']) ? $properties['opp'] : 'like';
2784 $searchValue = $searchValue . "%";
2786 $additionalWhereClause[] = "{$properties['table_name']}.$db_key $opp '$searchValue' ";
2790 $isDateFromSearchSet = !empty($_REQUEST['searchDateFrom']);
2791 $isdateToSearchSet = !empty($_REQUEST['searchDateTo']);
2793 $bothDateRangesSet = $isDateFromSearchSet & $isdateToSearchSet;
2795 //Hanlde date from and to seperately
2796 if($bothDateRangesSet)
2798 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2799 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2801 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2802 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2804 $additionalWhereClause[] = "( emails.date_sent >= $dbFormatDateFrom AND
2805 emails.date_sent <= $dbFormatDateTo )";
2807 elseif ($isdateToSearchSet)
2809 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2810 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2811 $additionalWhereClause[] = "emails.date_sent <= $dbFormatDateTo ";
2813 elseif ($isDateFromSearchSet)
2815 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2816 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2817 $additionalWhereClause[] = "emails.date_sent >= $dbFormatDateFrom ";
2820 $additionalWhereClause = implode(" AND ", $additionalWhereClause);
2822 return $additionalWhereClause;
2828 * takes a long TO: string of emails and returns the first appended by an
2831 function trimLongTo($str) {
2832 if(strpos($str, ',')) {
2833 $exStr = explode(',', $str);
2834 return $exStr[0].'...';
2835 } elseif(strpos($str, ';')) {
2836 $exStr = explode(';', $str);
2837 return $exStr[0].'...';
2843 function get_summary_text() {
2849 function distributionForm($where) {
2850 global $app_list_strings;
2851 global $app_strings;
2852 global $mod_strings;
2854 global $current_user;
2856 $distribution = get_select_options_with_id($app_list_strings['dom_email_distribution'], '');
2857 $_SESSION['distribute_where'] = $where;
2860 $out = '<form name="Distribute" id="Distribute">';
2861 $out .= get_form_header($mod_strings['LBL_DIST_TITLE'], '', false);
2868 <table cellpadding="0" cellspacing="0" width="100%" border="0">
2871 <script type="text/javascript">
2874 function checkDeps(form) {
2878 function mySubmit() {
2879 var assform = document.getElementById("Distribute");
2880 var select = document.getElementById("userSelect");
2881 var assign1 = assform.r1.checked;
2882 var assign2 = assform.r2.checked;
2883 var dist = assform.dm.value;
2887 var warn1 = "'.$mod_strings['LBL_WARN_NO_USERS'].'";
2890 if(assign1 || assign2) {
2895 for(i=0; i<select.options.length; i++) {
2896 if(select.options[i].selected == true) {
2905 warn2 = "'.$mod_strings['LBL_WARN_NO_DIST'].'";
2908 if(assign && users && rules) {
2910 if(document.getElementById("r1").checked) {
2911 var mu = document.getElementById("MassUpdate");
2914 for(i=0; i<mu.elements.length; i++) {
2915 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name.value != "massall") {
2916 if(grabbed != "") { grabbed += "::"; }
2917 grabbed += mu.elements[i].value;
2920 var formgrab = document.getElementById("grabbed");
2921 formgrab.value = grabbed;
2925 alert("'.$mod_strings['LBL_ASSIGN_WARN'].'" + "\n" + warn1 + "\n" + warn2);
2929 function submitDelete() {
2930 if(document.getElementById("r1").checked) {
2931 var mu = document.getElementById("MassUpdate");
2934 for(i=0; i<mu.elements.length; i++) {
2935 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name != "massall") {
2936 if(grabbed != "") { grabbed += "::"; }
2937 grabbed += mu.elements[i].value;
2940 var formgrab = document.getElementById("grabbed");
2941 formgrab.value = grabbed;
2944 alert("'.$mod_strings['LBL_MASS_DELETE_ERROR'].'");
2946 document.getElementById("Distribute").submit();
2951 <input type="hidden" name="module" value="Emails">
2952 <input type="hidden" name="action" id="action">
2953 <input type="hidden" name="grabbed" id="grabbed">
2955 <table cellpadding="1" cellspacing="0" width="100%" border="0" class="edit view">
2957 <td scope="col" scope="row" NOWRAP align="center">
2958 '.$mod_strings['LBL_ASSIGN_SELECTED_RESULTS_TO'].' ';
2959 $out .= $this->userSelectTable();
2961 <td scope="col" scope="row" NOWRAP align="left">
2962 '.$mod_strings['LBL_USING_RULES'].'
2963 <select name="distribute_method" id="dm" onChange="checkDeps(this.form);">'.$distribution.'</select>
2972 <td scope="col" width="50%" scope="row" NOWRAP align="right" colspan="2">
2973 <input title="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_TITLE'].'"
2975 accessKey="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_KEY'].'"
2976 class="button" onClick="AjaxObject.detailView.handleAssignmentDialogAssignAction();"
2977 type="button" name="button"
2978 value=" '.$mod_strings['LBL_BUTTON_DISTRIBUTE'].' ">';
2988 function userSelectTable() {
2990 global $mod_strings;
2993 $setTeamUserFunction = '';
2997 $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");
2999 $userTable = '<table cellpadding="0" cellspacing="0" border="0">';
3000 $userTable .= '<tr><td colspan="2"><b>'.$mod_strings['LBL_USER_SELECT'].'</b></td></tr>';
3001 $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>';
3002 $userTable .= '<tr><td colspan="2"><select style="visibility:hidden;" name="users[]" id="userSelect" multiple size="12">';
3004 while($a = $this->db->fetchByAssoc($r)) {
3005 $userTable .= '<option value="'.$a['id'].'" id="'.$a['id'].'">'.$a['first_name'].' '.$a['last_name'].'</option>';
3007 $userTable .= '</select></td></tr>';
3008 $userTable .= '</table>';
3010 $out = '<script type="text/javascript">';
3011 $out .= $setTeamUserFunction;
3013 function setCheckMark() {
3014 var select = document.getElementById("userSelect");
3016 for(i=0 ; i<select.options.length; i++) {
3017 if(select.options[i].selected == true) {
3018 document.getElementById("checkMark").style.display="";
3023 document.getElementById("checkMark").style.display="none";
3027 function showUserSelect() {
3028 var targetTable = document.getElementById("user_select");
3029 targetTable.style.visibility="visible";
3030 var userSelectTable = document.getElementById("userSelect");
3031 userSelectTable.style.visibility="visible";
3034 function hideUserSelect() {
3035 var targetTable = document.getElementById("user_select");
3036 targetTable.style.visibility="hidden";
3037 var userSelectTable = document.getElementById("userSelect");
3038 userSelectTable.style.visibility="hidden";
3041 function toggleAll(toggle) {
3042 if(toggle.checked) {
3047 var form = document.getElementById("userSelect");
3048 for(i=0; i<form.options.length; i++) {
3049 form.options[i].selected = stat;
3055 <span id="showUsersDiv" style="position:relative;">
3056 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
3057 <img border="0" src="'.SugarThemeRegistry::current()->getImageURL('Users.gif').'"></a>
3058 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
3059 <span style="display:none;" id="checkMark"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('check_inline.gif').'"></span>
3063 <div id="user_select" style="width:200px;position:absolute;left:2;top:2;visibility:hidden;z-index:1000;">
3064 <table cellpadding="0" cellspacing="0" border="0" class="list view">
3066 <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\';">
3067 <a href="#" onClick="javascript:hideUserSelect();"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('close.gif').'"></a>
3068 '.$mod_strings['LBL_USER_SELECT'].'
3072 //<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\';">
3073 $out .= ' <td style="padding:5px" class="oddListRowS1" bgcolor="#fdfdfd" valign="top" align="left" style="left:0;top:0;">
3082 function checkInbox($type) {
3084 global $mod_strings;
3085 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_CHECK_TITLE'].'"
3086 accessKey="'.$mod_strings['LBL_BUTTON_CHECK_KEY'].'"
3088 type="button" name="button"
3089 onClick="window.location=\'index.php?module=Emails&action=Check&type='.$type.'\';"
3090 style="margin-bottom:2px"
3091 value=" '.$mod_strings['LBL_BUTTON_CHECK'].' "></div>';
3096 * Guesses Primary Parent id from From: email address. Cascades guesses from Accounts to Contacts to Leads to
3097 * Users. This will not affect the many-to-many relationships already constructed as this is, at best,
3098 * informational linking.
3100 function fillPrimaryParentFields() {
3101 if(empty($this->from_addr))
3104 $GLOBALS['log']->debug("*** Email trying to guess Primary Parent from address [ {$this->from_addr} ]");
3106 $tables = array('accounts');
3108 // loop through types to get hits
3109 foreach($tables as $table) {
3110 $q = "SELECT name, id FROM {$table} WHERE email1 = '{$this->from_addr}' OR email2 = '{$this->from_addr}' AND deleted = 0";
3111 $r = $this->db->query($q);
3112 while($a = $this->db->fetchByAssoc($r)) {
3113 if(!empty($a['name']) && !empty($a['id'])) {
3114 $this->parent_type = ucwords($table);
3115 $this->parent_id = $a['id'];
3116 $this->parent_name = $a['name'];