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->convert_to_gmt_datetime('now');
870 $this->date_sent = $timedate->to_display_date_time($this->date_sent);
871 ///////////////////////////////////////////////////////////////////
872 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
874 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
875 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) ) {
876 $this->parent_id = $_REQUEST['parent_id'];
877 $this->parent_type = $_REQUEST['parent_type'];
878 $q = "SELECT count(*) c FROM emails_beans WHERE email_id = '{$this->id}' AND bean_id = '{$_REQUEST['parent_id']}' AND bean_module = '{$_REQUEST['parent_type']}'";
879 $r = $this->db->query($q);
880 $a = $this->db->fetchByAssoc($r);
882 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
883 $className = $beanList[$_REQUEST['parent_type']];
884 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
885 if(!class_exists($className)) {
886 require_once($beanFiles[$className]);
888 $bean = new $className();
889 $bean->retrieve($_REQUEST['parent_id']);
890 if($bean->load_relationship('emails')) {
891 $bean->emails->add($this->id);
901 if(!class_exists('aCase')) {
906 if($caseId = InboundEmail::getCaseIdFromCaseNumber($mail->Subject, $c)) {
907 $c->retrieve($caseId);
908 $c->load_relationship('emails');
909 $c->emails->add($this->id);
910 $this->parent_type = "Cases";
911 $this->parent_id = $caseId;
917 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
918 ///////////////////////////////////////////////////////////////////
922 if(!empty($request['fromAccount'])) {
923 if (isset($ie->id) && !$ie->isPop3Protocol()) {
924 $sentFolder = $ie->get_stored_options("sentFolder");
925 if (!empty($sentFolder)) {
926 $data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n";
927 $ie->mailbox = $sentFolder;
928 if ($ie->connectMailserver() == 'true') {
929 $connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox);
930 $returnData = imap_append($ie->conn,$connectString, $data, "\\Seen");
932 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}");
935 $GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}");
938 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty");
946 * Generates a comma sperated name and addresses to be used in compose email screen for contacts or leads
949 function getNamePlusEmailAddressesForCompose($table, $idsArray) {
952 $table = strtolower($table);
953 $returndata = array();
955 foreach($idsArray as $id) {
956 if ($idsString != "") {
957 $idsString = $idsString . ",";
959 $idsString = $idsString . "'" . $id . "'";
961 $where = "({$table}.deleted = 0 AND {$table}.id in ({$idsString}))";
963 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.salutation, {$table}.title";
964 if ($table == 'accounts') {
965 $selectColumn = "{$table}.name";
967 $query = "SELECT {$table}.id, {$selectColumn}, eabr.primary_address, ea.email_address";
968 $query .= " FROM {$table} ";
969 $query .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
970 $query .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
971 $query .= " WHERE ({$where}) ORDER BY eabr.primary_address DESC";
972 $r = $this->db->query($query);
974 while($a = $this->db->fetchByAssoc($r)) {
975 if (!isset($returndata[$a['id']])) {
976 if ($table == 'accounts') {
977 $returndata[$a['id']] = from_html($a['name']) . " <".from_html($a['email_address']).">";
979 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], $a['salutation'], $a['title']));
980 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
985 return join(",", array_values($returndata));
991 ///////////////////////////////////////////////////////////////////////////
993 function save($check_notify = false) {
994 if($this->isDuplicate) {
995 $GLOBALS['log']->debug("EMAIL - tried to save a duplicate Email record");
998 if(empty($this->id)) {
999 $this->id = create_guid();
1000 $this->new_with_id = true;
1002 $this->saveEmailText();
1003 $this->saveEmailAddresses();
1005 $GLOBALS['log']->debug('-------------------------------> Email called save()');
1007 // handle legacy concatenation of date and time fields
1008 if(empty($this->date_sent)) $this->date_sent = $this->date_start." ".$this->time_start;
1009 parent::save($check_notify);
1014 * Helper function to save temporary attachments assocaited to an email as note.
1016 * @param string $filename
1017 * @param string $fileLocation
1018 * @param string $mimeType
1020 function saveTempNoteAttachments($filename,$fileLocation, $mimeType)
1022 global $sugar_config;
1024 $tmpNote = new Note();
1025 $tmpNote->id = create_guid();
1026 $tmpNote->new_with_id = true;
1027 $tmpNote->parent_id = $this->id;
1028 $tmpNote->parent_type = $this->module_dir;
1029 $tmpNote->name = $filename;
1030 $tmpNote->filename = $filename;
1031 $tmpNote->file_mime_type = $mimeType;
1032 $noteFile = "{$sugar_config['upload_dir']}{$tmpNote->id}";
1033 if(!copy($fileLocation, $noteFile))
1034 $GLOBALS['log']->fatal("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
1038 * Handles normalization of Email Addressess
1040 function saveEmailAddresses() {
1041 // from, single address
1042 $fromId = $this->emailAddress->getEmailGUID(from_html($this->from_addr));
1043 if(!empty($fromId)){
1044 $this->linkEmailToAddress($fromId, 'from');
1048 $replace = array(",",";");
1049 $toaddrs = str_replace($replace, "::", from_html($this->to_addrs));
1050 $exToAddrs = explode("::", $toaddrs);
1052 if(!empty($exToAddrs)) {
1053 foreach($exToAddrs as $toaddr) {
1054 $toaddr = trim($toaddr);
1055 if(!empty($toaddr)) {
1056 $toId = $this->emailAddress->getEmailGUID($toaddr);
1057 $this->linkEmailToAddress($toId, 'to');
1063 $ccAddrs = str_replace($replace, "::", from_html($this->cc_addrs));
1064 $exccAddrs = explode("::", $ccAddrs);
1066 if(!empty($exccAddrs)) {
1067 foreach($exccAddrs as $ccAddr) {
1068 $ccAddr = trim($ccAddr);
1069 if(!empty($ccAddr)) {
1070 $ccId = $this->emailAddress->getEmailGUID($ccAddr);
1071 $this->linkEmailToAddress($ccId, 'cc');
1077 $bccAddrs = str_replace($replace, "::", from_html($this->bcc_addrs));
1078 $exbccAddrs = explode("::", $bccAddrs);
1079 if(!empty($exbccAddrs)) {
1080 foreach($exbccAddrs as $bccAddr) {
1081 $bccAddr = trim($bccAddr);
1082 if(!empty($bccAddr)) {
1083 $bccId = $this->emailAddress->getEmailGUID($bccAddr);
1084 $this->linkEmailToAddress($bccId, 'bcc');
1090 function linkEmailToAddress($id, $type) {
1091 // TODO: make this update?
1092 $q1 = "SELECT * FROM emails_email_addr_rel WHERE email_id = '{$this->id}' AND email_address_id = '{$id}' AND address_type = '{$type}' AND deleted = 0";
1093 $r1 = $this->db->query($q1);
1094 $a1 = $this->db->fetchByAssoc($r1);
1096 if(!empty($a1) && !empty($a1['id'])) {
1099 $guid = create_guid();
1100 $q2 = "INSERT INTO emails_email_addr_rel VALUES('{$guid}', '{$this->id}', '{$type}', '{$id}', 0)";
1101 $r2 = $this->db->query($q2);
1108 function saveEmailText() {
1109 $isOracle = ($this->db->dbType == "oci8") ? true : false;
1112 $description = $this->db->quote(trim($this->description));
1113 $description_html = $this->db->quoteForEmail(trim($this->description_html));
1114 $raw_source = $this->db->quote(trim($this->raw_source));
1115 $fromAddressName = $this->db->helper->escape_quote($this->from_addr_name);
1116 $toAddressName = $this->db->helper->escape_quote($this->to_addrs_names);
1117 $ccAddressName = $this->db->helper->escape_quote($this->cc_addrs_names);
1118 $bccAddressName = $this->db->helper->escape_quote($this->bcc_addrs_names);
1119 $replyToAddrName = $this->db->helper->escape_quote($this->reply_to_addr);
1121 if(!$this->new_with_id) {
1122 $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}'";
1124 $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)";
1126 $this->db->query($q);
1132 ///////////////////////////////////////////////////////////////////////////
1134 function retrieve($id, $encoded=true, $deleted=true) {
1135 // cn: bug 11915, return SugarBean's retrieve() call bean instead of $this
1136 $ret = parent::retrieve($id, $encoded, $deleted);
1139 $ret->raw_source = to_html($ret->safeText(from_html($ret->raw_source)));
1140 $ret->description = to_html($ret->safeText(from_html($ret->description)));
1141 $ret->description_html = $ret->safeText($ret->description_html);
1142 $ret->retrieveEmailText();
1143 $ret->retrieveEmailAddresses();
1145 $ret->date_start = '';
1146 $ret->time_start = '';
1147 $dateSent = explode(' ', $ret->date_sent);
1148 if (!empty($dateSent)) {
1149 $ret->date_start = $dateSent[0];
1150 if ( isset($dateSent[1]) )
1151 $ret->time_start = $dateSent[1];
1154 foreach($ret as $k => $v) {
1163 * Retrieves email addresses from GUIDs
1165 function retrieveEmailAddresses() {
1168 $q = "SELECT email_address, address_type
1169 FROM emails_email_addr_rel eam
1170 JOIN email_addresses ea ON ea.id = eam.email_address_id
1171 WHERE eam.email_id = '{$this->id}' AND eam.deleted=0";
1172 $r = $this->db->query($q);
1174 while($a = $this->db->fetchByAssoc($r)) {
1175 if(!isset($return[$a['address_type']])) {
1176 $return[$a['address_type']] = array();
1178 $return[$a['address_type']][] = $a['email_address'];
1181 if(count($return) > 0) {
1182 if(isset($return['from'])) {
1183 $this->from_addr = implode(", ", $return['from']);
1185 if(isset($return['to'])) {
1186 $this->to_addrs = implode(", ", $return['to']);
1188 if(isset($return['cc'])) {
1189 $this->cc_addrs = implode(", ", $return['cc']);
1191 if(isset($return['bcc'])) {
1192 $this->bcc_addrs = implode(", ", $return['bcc']);
1198 * Handles longtext fields
1200 function retrieveEmailText() {
1201 $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}'";
1202 $r = $this->db->query($q);
1203 $a = $this->db->fetchByAssoc($r, -1, false);
1205 $this->description = $a['description'];
1206 $this->description_html = $a['description_html'];
1207 $this->raw_source = $a['raw_source'];
1208 $this->from_addr_name = $a['from_addr'];
1209 $this->reply_to_addr = $a['reply_to_addr'];
1210 $this->to_addrs_names = $a['to_addrs'];
1211 $this->cc_addrs_names = $a['cc_addrs'];
1212 $this->bcc_addrs_names = $a['bcc_addrs'];
1215 function delete($id='') {
1219 $q = "UPDATE emails SET deleted = 1 WHERE id = '{$id}'";
1220 $qt = "UPDATE emails_text SET deleted = 1 WHERE email_id = '{$id}'";
1221 $r = $this->db->query($q);
1222 $rt = $this->db->query($qt);
1226 * creates the standard "Forward" info at the top of the forwarded message
1229 function getForwardHeader() {
1230 global $mod_strings;
1231 global $current_user;
1233 //$from = str_replace(array(">","<"), array(")","("), $this->from_name);
1234 $from = to_html($this->from_name);
1235 $subject = to_html($this->name);
1236 $ret = "<br /><br />";
1237 $ret .= $this->replyDelimiter."{$mod_strings['LBL_FROM']} {$from}<br />";
1238 $ret .= $this->replyDelimiter."{$mod_strings['LBL_DATE_SENT']} {$this->date_sent}<br />";
1239 $ret .= $this->replyDelimiter."{$mod_strings['LBL_TO']} {$this->to_addrs}<br />";
1240 $ret .= $this->replyDelimiter."{$mod_strings['LBL_CC']} {$this->cc_addrs}<br />";
1241 $ret .= $this->replyDelimiter."{$mod_strings['LBL_SUBJECT']} {$subject}<br />";
1242 $ret .= $this->replyDelimiter."<br />";
1245 //return from_html($ret);
1249 * retrieves Notes that belong to this Email and stuffs them into the "attachments" attribute
1251 function getNotes($id, $duplicate=false) {
1252 if(!class_exists('Note')) {
1256 $exRemoved = array();
1257 if(isset($_REQUEST['removeAttachment'])) {
1258 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1261 $noteArray = array();
1262 $q = "SELECT id FROM notes WHERE parent_id = '".$id."'";
1263 $r = $this->db->query($q);
1265 while($a = $this->db->fetchByAssoc($r)) {
1266 if(!in_array($a['id'], $exRemoved)) {
1268 $note->retrieve($a['id']);
1270 // duplicate actual file when creating forwards
1272 if(!class_exists('UploadFile')) {
1273 require_once('include/upload_file.php');
1275 // save a brand new Note
1276 $noteDupe->id = create_guid();
1277 $noteDupe->new_with_id = true;
1278 $noteDupe->parent_id = $this->id;
1279 $noteDupe->parent_type = $this->module_dir;
1281 $noteFile = new UploadFile('none');
1282 $noteFile->duplicate_file($a['id'], $note->id, $note->filename);
1286 // add Note to attachments array
1287 $this->attachments[] = $note;
1293 * creates the standard "Reply" info at the top of the forwarded message
1296 function getReplyHeader() {
1297 global $mod_strings;
1298 global $current_user;
1300 $from = str_replace(array(">","<", ">","<"), array(")","(",")","("), $this->from_name);
1301 $ret = "<br>{$mod_strings['LBL_REPLY_HEADER_1']} {$this->date_start}, {$this->time_start}, {$from} {$mod_strings['LBL_REPLY_HEADER_2']}";
1303 return from_html($ret);
1307 * Quotes plain-text email text
1308 * @param string $text
1311 function quotePlainTextEmail($text) {
1315 $desc = nl2br(trim($text));
1316 $exDesc = explode('<br />', $desc);
1318 foreach($exDesc as $k => $line) {
1319 $quoted .= '> '.trim($line)."\r";
1326 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1327 * @param string $text HTML text to quote
1330 function quoteHtmlEmail($text) {
1331 $text = trim(from_html($text));
1336 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1342 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1343 * @param string $text HTML text to quote
1346 function quoteHtmlEmailForNewEmailUI($text) {
1347 $text = trim($text);
1352 $text = str_replace("\n", "\n<BR/>", $text);
1353 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1360 ///////////////////////////////////////////////////////////////////////////
1363 * Safes description text (both HTML and Plain Text) for display
1364 * @param string str The text to safe
1365 * @return string Safed text
1367 function safeText($str) {
1369 $this->safe->clear();
1370 $ret = $this->safe->parse($str);
1372 // Julian's XSS cleaner
1373 $potentials = clean_xss($str, false);
1375 if(is_array($potentials) && !empty($potentials)) {
1376 //_ppl($potentials);
1377 foreach($potentials as $bad) {
1378 $ret = str_replace($bad, "", $ret);
1382 // clean <HTML> and <BODY> tags
1383 $html = '#<\\\\\?HTML[\w =\'\"\&]*>#sim';
1384 $body = '#<\\\\\?BODY[\w =\'\"\&]*>#sim';
1386 $ret = preg_replace($html, "", $ret);
1387 $ret = preg_replace($body, "", $ret);
1393 * Ensures that the user is able to send outbound emails
1395 function check_email_settings() {
1396 global $current_user;
1398 $mail_fromaddress = $current_user->emailAddress->getPrimaryAddress($current_user);
1399 $replyToName = $current_user->getPreference('mail_fromname');
1400 $mail_fromname = (!empty($replyToName)) ? $current_user->getPreference('mail_fromname') : $current_user->full_name;
1402 if(empty($mail_fromaddress)) {
1405 if(empty($mail_fromname)) {
1409 $send_type = $current_user->getPreference('mail_sendtype') ;
1410 if (!empty($send_type) && $send_type == "SMTP") {
1411 $mail_smtpserver = $current_user->getPreference('mail_smtpserver');
1412 $mail_smtpport = $current_user->getPreference('mail_smtpport');
1413 $mail_smtpauth_req = $current_user->getPreference('mail_smtpauth_req');
1414 $mail_smtpuser = $current_user->getPreference('mail_smtpuser');
1415 $mail_smtppass = $current_user->getPreference('mail_smtppass');
1416 if (empty($mail_smtpserver) ||
1417 empty($mail_smtpport) ||
1418 (!empty($mail_smtpauth_req) && ( empty($mail_smtpuser) || empty($mail_smtppass)))
1427 * outputs JS to set fields in the MassUpdate form in the "My Inbox" view
1429 function js_set_archived() {
1430 global $mod_strings;
1432 <script type="text/javascript" language="JavaScript"><!-- Begin
1433 function setArchived() {
1434 var form = document.getElementById("MassUpdate");
1435 var status = document.getElementById("mass_status");
1438 for(var i=0; i < form.elements.length; i++) {
1439 if(form.elements[i].name == "mass[]") {
1440 if(form.elements[i].checked == true) {
1447 var user = document.getElementById("mass_assigned_user_name");
1448 var team = document.getElementById("team");
1451 for(var j=0; j<status.length; j++) {
1452 if(status.options[j].value == "archived") {
1453 status.options[j].selected = true;
1454 status.selectedIndex = j; // for IE
1460 alert("'.$mod_strings['ERR_ARCHIVE_EMAIL'].'");
1464 // End --></script>';
1469 * replaces the javascript in utils.php - more specialized
1471 function u_get_clear_form_js($type='', $group='', $assigned_user_id='') {
1474 $uAssigned_user_id = '';
1476 if(!empty($type)) { $uType = '&type='.$type; }
1477 if(!empty($group)) { $uGroup = '&group='.$group; }
1478 if(!empty($assigned_user_id)) { $uAssigned_user_id = '&assigned_user_id='.$assigned_user_id; }
1481 <script type="text/javascript" language="JavaScript"><!-- Begin
1482 function clear_form(form) {
1483 var newLoc = "index.php?action=" + form.action.value + "&module=" + form.module.value + "&query=true&clear_query=true'.$uType.$uGroup.$uAssigned_user_id.'";
1484 if(typeof(form.advanced) != "undefined"){
1485 newLoc += "&advanced=" + form.advanced.value;
1487 document.location.href= newLoc;
1489 // End --></script>';
1493 function pickOneButton() {
1495 global $mod_strings;
1496 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_GRAB_TITLE'].'"
1497 accessKey="'.$mod_strings['LBL_BUTTON_GRAB_KEY'].'"
1499 type="button" name="button"
1500 onClick="window.location=\'index.php?module=Emails&action=Grab\';"
1501 style="margin-bottom:2px"
1502 value=" '.$mod_strings['LBL_BUTTON_GRAB'].' "></div>';
1507 * Determines what Editor (HTML or Plain-text) the current_user uses;
1508 * @return string Editor type
1510 function getUserEditorPreference() {
1511 global $sugar_config;
1512 global $current_user;
1516 if(!isset($sugar_config['email_default_editor'])) {
1517 $sugar_config = $current_user->setDefaultsInConfig();
1520 $userEditor = $current_user->getPreference('email_editor_option');
1521 $systemEditor = $sugar_config['email_default_editor'];
1523 if($userEditor != '') {
1524 $editor = $userEditor;
1526 $editor = $systemEditor;
1533 * takes the mess we pass from EditView and tries to create some kind of order
1534 * @param array addrs
1535 * @param array addrs_ids (from contacts)
1536 * @param array addrs_names (from contacts);
1537 * @param array addrs_emails (from contacts);
1538 * @return array Parsed assoc array to feed to PHPMailer
1540 function parse_addrs($addrs, $addrs_ids, $addrs_names, $addrs_emails) {
1541 // cn: bug 9406 - enable commas to separate email addresses
1542 $addrs = str_replace(",", ";", $addrs);
1544 $ltgt = array('<','>');
1545 $gtlt = array('<','>');
1548 $addrs = str_replace($ltgt, '', $addrs);
1549 $addrs_arr = explode(";",$addrs);
1550 $addrs_arr = $this->remove_empty_fields($addrs_arr);
1551 $addrs_ids_arr = explode(";",$addrs_ids);
1552 $addrs_ids_arr = $this->remove_empty_fields($addrs_ids_arr);
1553 $addrs_emails_arr = explode(";",$addrs_emails);
1554 $addrs_emails_arr = $this->remove_empty_fields($addrs_emails_arr);
1555 $addrs_names_arr = explode(";",$addrs_names);
1556 $addrs_names_arr = $this->remove_empty_fields($addrs_names_arr);
1558 ///////////////////////////////////////////////////////////////////////
1559 //// HANDLE EMAILS HAND-WRITTEN
1560 $contactRecipients = array();
1561 $knownEmails = array();
1563 foreach($addrs_arr as $i => $v) {
1565 continue; // skip any "blanks" - will always have 1
1567 $recipient = array();
1569 //// get the email to see if we're dealing with a dupe
1570 //// what crappy coding
1571 preg_match("/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i",$v, $match);
1573 if(!empty($match[0]) && !in_array(trim($match[0]), $knownEmails)) {
1574 $knownEmails[] = $match[0];
1575 $recipient['email'] = $match[0];
1577 //// handle the Display name
1578 $display = trim(str_replace($match[0], '', $v));
1580 //// only trigger a "displayName" <email@address> when necessary
1581 if(isset($addrs_names_arr[$i])){
1582 $recipient['display'] = $addrs_names_arr[$i];
1584 else if(!empty($display)) {
1585 $recipient['display'] = $display;
1587 if(isset($addrs_ids_arr[$i]) && $addrs_emails_arr[$i] == $match[0]){
1588 $recipient['contact_id'] = $addrs_ids_arr[$i];
1590 $return[] = $recipient;
1597 function remove_empty_fields(&$arr) {
1600 foreach($arr as $field) {
1601 $field = trim($field);
1605 array_push($newarr,$field);
1611 * handles attachments of various kinds when sending email
1613 function handleAttachments() {
1618 global $mod_strings;
1620 ///////////////////////////////////////////////////////////////////////////
1621 //// ATTACHMENTS FROM DRAFTS
1622 if(($this->type == 'out' || $this->type == 'draft') && $this->status == 'draft' && isset($_REQUEST['record'])) {
1623 $this->getNotes($_REQUEST['record']); // cn: get notes from OLD email for use in new email
1625 //// END ATTACHMENTS FROM DRAFTS
1626 ///////////////////////////////////////////////////////////////////////////
1628 ///////////////////////////////////////////////////////////////////////////
1629 //// ATTACHMENTS FROM FORWARDS
1630 // Bug 8034 Jenny - Need the check for type 'draft' here to handle cases where we want to save
1631 // forwarded messages as drafts. We still need to save the original message's attachments.
1632 if(($this->type == 'out' || $this->type == 'draft') &&
1633 isset($_REQUEST['origType']) && $_REQUEST['origType'] == 'forward' &&
1634 isset($_REQUEST['return_id']) && !empty($_REQUEST['return_id'])
1636 $this->getNotes($_REQUEST['return_id'], true);
1639 // cn: bug 8034 - attachments from forward/replies lost when saving in draft
1640 if(isset($_REQUEST['prior_attachments']) && !empty($_REQUEST['prior_attachments']) && $this->new_with_id == true) {
1641 $exIds = explode(",", $_REQUEST['prior_attachments']);
1642 if(!isset($_REQUEST['template_attachment'])) {
1643 $_REQUEST['template_attachment'] = array();
1645 $_REQUEST['template_attachment'] = array_merge($_REQUEST['template_attachment'], $exIds);
1647 //// END ATTACHMENTS FROM FORWARDS
1648 ///////////////////////////////////////////////////////////////////////////
1650 ///////////////////////////////////////////////////////////////////////////
1651 //// ATTACHMENTS FROM TEMPLATES
1652 // to preserve individual email integrity, we must dupe Notes and associated files
1653 // for each outbound email - good for integrity, bad for filespace
1654 if(isset($_REQUEST['template_attachment']) && !empty($_REQUEST['template_attachment'])) {
1655 $removeArr = array();
1656 $noteArray = array();
1658 if(isset($_REQUEST['temp_remove_attachment']) && !empty($_REQUEST['temp_remove_attachment'])) {
1659 $removeArr = $_REQUEST['temp_remove_attachment'];
1663 foreach($_REQUEST['template_attachment'] as $noteId) {
1664 if(in_array($noteId, $removeArr)) {
1667 $noteTemplate = new Note();
1668 $noteTemplate->retrieve($noteId);
1669 $noteTemplate->id = create_guid();
1670 $noteTemplate->new_with_id = true; // duplicating the note with files
1671 $noteTemplate->parent_id = $this->id;
1672 $noteTemplate->parent_type = $this->module_dir;
1673 $noteTemplate->date_entered = '';
1674 $noteTemplate->save();
1676 $noteFile = new UploadFile('none');
1677 $noteFile->duplicate_file($noteId, $noteTemplate->id, $noteTemplate->filename);
1678 $noteArray[] = $noteTemplate;
1680 $this->attachments = array_merge($this->attachments, $noteArray);
1682 //// END ATTACHMENTS FROM TEMPLATES
1683 ///////////////////////////////////////////////////////////////////////////
1685 ///////////////////////////////////////////////////////////////////////////
1686 //// ADDING NEW ATTACHMENTS
1687 $max_files_upload = 10;
1688 // Jenny - Bug 8211 Since attachments for drafts have already been processed,
1689 // we don't need to re-process them.
1690 if($this->status != "draft") {
1691 $notes_list = array();
1692 if(!empty($this->id) && !$this->new_with_id) {
1694 $where = "notes.parent_id='{$this->id}'";
1695 $notes_list = $note->get_full_list("", $where, true);
1697 $this->attachments = array_merge($this->attachments, $notes_list);
1699 // cn: Bug 5995 - rudimentary error checking
1700 $filesError = array(
1701 0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
1702 1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
1703 2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
1704 3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
1705 4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
1706 5 => 'UNKNOWN ERROR',
1707 6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
1708 7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
1711 for($i = 0; $i < $max_files_upload; $i++) {
1712 // cn: Bug 5995 - rudimentary error checking
1713 if (!isset($_FILES["email_attachment{$i}"])) {
1714 $GLOBALS['log']->debug("Email Attachment {$i} does not exist.");
1717 if($_FILES['email_attachment'.$i]['error'] != 0 && $_FILES['email_attachment'.$i]['error'] != 4) {
1718 $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment'.$i]['error']]);
1723 $note->parent_id = $this->id;
1724 $note->parent_type = $this->module_dir;
1725 $upload_file = new UploadFile('email_attachment'.$i);
1727 if(empty($upload_file)) {
1731 if(isset($_FILES['email_attachment'.$i]) && $upload_file->confirm_upload()) {
1732 $note->filename = $upload_file->get_stored_file_name();
1733 $note->file = $upload_file;
1734 $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$note->file->original_file_name;
1736 $this->attachments[] = $note;
1740 $this->saved_attachments = array();
1741 foreach($this->attachments as $note) {
1742 if(!empty($note->id)) {
1743 array_push($this->saved_attachments, $note);
1746 $note->parent_id = $this->id;
1747 $note->parent_type = 'Emails';
1748 $note->file_mime_type = $note->file->mime_type;
1749 $note_id = $note->save();
1751 $this->saved_attachments[] = $note;
1753 $note->id = $note_id;
1754 $note->file->final_move($note->id);
1756 //// END NEW ATTACHMENTS
1757 ///////////////////////////////////////////////////////////////////////////
1759 ///////////////////////////////////////////////////////////////////////////
1760 //// ATTACHMENTS FROM DOCUMENTS
1761 for($i=0; $i<10; $i++) {
1762 if(isset($_REQUEST['documentId'.$i]) && !empty($_REQUEST['documentId'.$i])) {
1763 $doc = new Document();
1764 $docRev = new DocumentRevision();
1765 $docNote = new Note();
1766 $noteFile = new UploadFile('none');
1768 $doc->retrieve($_REQUEST['documentId'.$i]);
1769 $docRev->retrieve($doc->document_revision_id);
1771 $this->saved_attachments[] = $docRev;
1773 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
1774 $docNote->name = $docRev->getDocumentRevisionNameForDisplay();
1775 $docNote->filename = $docRev->filename;
1776 $docNote->description = $doc->description;
1777 $docNote->parent_id = $this->id;
1778 $docNote->parent_type = 'Emails';
1779 $docNote->file_mime_type = $docRev->file_mime_type;
1780 $docId = $docNote = $docNote->save();
1782 $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
1786 //// END ATTACHMENTS FROM DOCUMENTS
1787 ///////////////////////////////////////////////////////////////////////////
1789 ///////////////////////////////////////////////////////////////////////////
1790 //// REMOVE ATTACHMENTS
1791 if(isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
1792 foreach($_REQUEST['remove_attachment'] as $noteId) {
1793 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1794 $this->db->query($q);
1798 //this will remove attachments that have been selected to be removed from drafts.
1799 if(isset($_REQUEST['removeAttachment']) && !empty($_REQUEST['removeAttachment'])) {
1800 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1801 foreach($exRemoved as $noteId) {
1802 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1803 $this->db->query($q);
1806 //// END REMOVE ATTACHMENTS
1807 ///////////////////////////////////////////////////////////////////////////
1812 * Determines if an email body (HTML or Plain) has a User signature already in the content
1813 * @param array Array of signatures
1816 function hasSignatureInBody($sig) {
1817 // strpos can't handle line breaks - normalize
1818 $html = $this->removeAllNewlines($this->description_html);
1819 $htmlSig = $this->removeAllNewlines($sig['signature_html']);
1820 $plain = $this->removeAllNewlines($this->description);
1821 $plainSig = $this->removeAllNewlines($sig['signature']);
1823 // cn: bug 11621 - empty sig triggers notice error
1824 if(!empty($htmlSig) && false !== strpos($html, $htmlSig)) {
1826 } elseif(!empty($plainSig) && false !== strpos($plain, $plainSig)) {
1835 * @param string String to be normalized
1838 function removeAllNewlines($str) {
1839 $bad = array("\r\n", "\n\r", "\n", "\r");
1840 $good = array('', '', '', '');
1842 return str_replace($bad, $good, strip_tags(br2nl(from_html($str))));
1848 * Set navigation anchors to aid DetailView record navigation (VCR buttons)
1849 * @param string uri The URI from the referring page (always ListView)
1850 * @return array start Array of the URI broken down with a special "current_view" for My Inbox Navs
1852 function getStartPage($uri) {
1853 if(strpos($uri, '&')) { // "&" to ensure that we can explode the GET vars - else we're gonna trigger a Notice error
1854 $serial = substr($uri, (strpos($uri, '?')+1), strlen($uri));
1855 $exUri = explode('&', $serial);
1856 $start = array('module' => '', 'action' => '', 'group' => '', 'record' => '', 'type' => '');
1858 foreach($exUri as $k => $pair) {
1859 $exPair = explode('=', $pair);
1860 $start[$exPair[0]] = $exPair[1];
1863 // specific views for current_user
1864 if(isset($start['assigned_user_id'])) {
1865 $start['current_view'] = "{$start['action']}&module={$start['module']}&assigned_user_id={$start['assigned_user_id']}&type={$start['type']}";
1875 * preps SMTP info for email transmission
1876 * @param object mail SugarPHPMailer object
1877 * @param string mailer_id
1878 * @param string ieId
1879 * @return object mail SugarPHPMailer object
1881 function setMailer($mail, $mailer_id='', $ieId='') {
1882 global $current_user;
1884 require_once("include/OutboundEmail/OutboundEmail.php");
1885 $oe = new OutboundEmail();
1886 $oe = $oe->getInboundMailerSettings($current_user, $mailer_id, $ieId);
1888 // ssl or tcp - keeping outside isSMTP b/c a default may inadvertantly set ssl://
1889 $mail->protocol = ($oe->mail_smtpssl) ? "ssl://" : "tcp://";
1890 if($oe->mail_sendtype == "SMTP")
1892 //Set mail send type information
1893 $mail->Mailer = "smtp";
1894 $mail->Host = $oe->mail_smtpserver;
1895 $mail->Port = $oe->mail_smtpport;
1896 if ($oe->mail_smtpssl == 1) {
1897 $mail->SMTPSecure = 'ssl';
1899 if ($oe->mail_smtpssl == 2) {
1900 $mail->SMTPSecure = 'tls';
1903 if($oe->mail_smtpauth_req) {
1904 $mail->SMTPAuth = TRUE;
1905 $mail->Username = $oe->mail_smtpuser;
1906 $mail->Password = $oe->mail_smtppass;
1910 $mail->Mailer = "sendmail";
1917 * preps SugarPHPMailer object for HTML or Plain text sends
1918 * @param object SugarPHPMailer instance
1920 function handleBody($mail) {
1921 global $current_user;
1922 global $sugar_config;
1923 ///////////////////////////////////////////////////////////////////////
1924 //// HANDLE EMAIL FORMAT PREFERENCE
1925 // the if() below is HIGHLY dependent on the Javascript unchecking the Send HTML Email box
1927 if( (isset($_REQUEST['setEditor']) /* from Email EditView navigation */
1928 && $_REQUEST['setEditor'] == 1
1929 && trim($_REQUEST['description_html']) != '')
1930 || trim($this->description_html) != '' /* from email templates */
1931 && $current_user->getPreference('email_editor_option', 'global') !== 'plain' //user preference is not set to plain text
1933 $this->handleBodyInHTMLformat($mail);
1936 $this->description_html = '';
1937 $mail->IsHTML(false);
1938 $plainText = from_html($this->description);
1939 $plainText = str_replace(" ", " ", $plainText);
1940 $plainText = str_replace("</p>", "</p><br />", $plainText);
1941 $plainText = strip_tags(br2nl($plainText));
1942 $plainText = str_replace("&", "&", $plainText);
1943 $plainText = str_replace("'", "'", $plainText);
1944 $mail->Body = wordwrap($plainText, 996);
1945 $mail->Body = $this->decodeDuringSend($mail->Body);
1946 $this->description = $mail->Body;
1949 // wp: if plain text version has lines greater than 998, use base64 encoding
1950 foreach(explode("\n", ($mail->ContentType == "text/html") ? $mail->AltBody : $mail->Body) as $line) {
1951 if(strlen($line) > 998) {
1952 $mail->Encoding = 'base64';
1956 //// HANDLE EMAIL FORMAT PREFERENCE
1957 ///////////////////////////////////////////////////////////////////////
1963 * Retrieve function from handlebody() to unit test easily
1965 * @return formatted $mail body
1967 function handleBodyInHTMLformat($mail) {
1968 global $current_user;
1969 global $sugar_config;
1970 // wp: if body is html, then insert new lines at 996 characters. no effect on client side
1971 // due to RFC 2822 which limits email lines to 998
1972 $mail->IsHTML(true);
1973 $body = from_html(wordwrap($this->description_html, 996));
1974 $mail->Body = $body;
1977 // new plan is to use the selected type (html or plain) to fill the other
1978 $plainText = from_html($this->description_html);
1979 $plainText = strip_tags(br2nl($plainText));
1980 $mail->AltBody = $plainText;
1981 $this->description = $plainText;
1983 $fileBasePath = "{$sugar_config['cache_dir']}images/";
1984 $filePatternSearch = "{$sugar_config['cache_dir']}";
1985 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
1986 $filePatternSearch = $filePatternSearch . "images\/";
1987 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
1990 preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
1991 foreach($matches[0] as $match) {
1992 $filename = str_replace($fileBasePath, '', $match);
1993 $filename = urldecode(substr($filename, 0, -1));
1995 $file_location = clean_path(getcwd()."/{$sugar_config['cache_dir']}images/{$filename}");
1996 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
1998 if(file_exists($file_location)) {
1999 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2003 //replace references to cache with cid tag
2004 $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2005 $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2006 // remove bad img line from outbound email
2007 $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2008 $mail->Body = preg_replace($regex, '', $mail->Body);
2010 $fileBasePath = "{$sugar_config['upload_dir']}";
2011 $filePatternSearch = "{$sugar_config['upload_dir']}";
2012 $filePatternSearch = str_replace("/", "\/", $filePatternSearch);
2013 if(strpos($mail->Body, "\"{$fileBasePath}") !== FALSE)
2016 preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
2017 foreach($matches[0] as $match) {
2018 $filename = str_replace($fileBasePath, '', $match);
2019 $filename = urldecode(substr($filename, 0, -1));
2021 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$filename}");
2022 $mime_type = "image/".strtolower(substr($filename, strrpos($filename, ".")+1, strlen($filename)));
2024 if(file_exists($file_location)) {
2025 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
2029 //replace references to cache with cid tag
2030 $mail->Body = str_replace("/" . $fileBasePath,'cid:',$mail->Body);
2031 $mail->Body = str_replace($fileBasePath,'cid:',$mail->Body);
2033 // remove bad img line from outbound email
2034 $regex = '#<img[^>]+src[^=]*=\"\/([^>]*?[^>]*)>#sim';
2035 $mail->Body = preg_replace($regex, '', $mail->Body);
2038 //Replace any embeded images using the secure entryPoint for src url.
2039 $noteImgRegex = "/<img[^>]*[\s]+src[^=]*=\"index.php\?entryPoint=download\&id=([^\&]*)[^>]*>/im";
2040 $embededImageMatches = array();
2041 preg_match_all($noteImgRegex, $mail->Body, $embededImageMatches,PREG_SET_ORDER);
2043 foreach ($embededImageMatches as $singleMatch )
2045 $fullMatch = $singleMatch[0];
2046 $noteId = $singleMatch[1];
2048 $filename = $noteId;
2050 //Retrieve note for mimetype
2051 $tmpNote = new Note();
2052 $tmpNote->retrieve($noteId);
2053 //Replace the src part of img tag with new cid tag
2054 $cidRegex = "/src=\"([^\"]*)\"/im";
2055 $replaceMatch = preg_replace($cidRegex, "src=\"cid:$noteId\"", $fullMatch);
2057 //Replace the body, old tag for new tag
2058 $mail->Body = str_replace($fullMatch, $replaceMatch, $mail->Body);
2061 $file_location = clean_path(getcwd()."/{$sugar_config['upload_dir']}{$noteId}");
2063 if(file_exists($file_location))
2064 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $tmpNote->file_mime_type);
2069 $mail->Body = from_html($mail->Body);
2074 * @return bool True on success
2077 global $mod_strings,$app_strings;
2078 global $current_user;
2079 global $sugar_config;
2081 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
2082 $mail = new SugarPHPMailer();
2084 foreach ($this->to_addrs_arr as $addr_arr) {
2085 if ( empty($addr_arr['display'])) {
2086 $mail->AddAddress($addr_arr['email'], "");
2088 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
2091 foreach ($this->cc_addrs_arr as $addr_arr) {
2092 if ( empty($addr_arr['display'])) {
2093 $mail->AddCC($addr_arr['email'], "");
2095 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2099 foreach ($this->bcc_addrs_arr as $addr_arr) {
2100 if ( empty($addr_arr['display'])) {
2101 $mail->AddBCC($addr_arr['email'], "");
2103 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2107 $mail = $this->setMailer($mail);
2110 if(!empty($this->from_addr)) {
2111 $mail->From = $this->from_addr;
2113 $mail->From = $current_user->getPreference('mail_fromaddress');
2114 $this->from_addr = $mail->From;
2117 if(!empty($this->from_name)) {
2118 $mail->FromName = $this->from_name;
2120 $mail->FromName = $current_user->getPreference('mail_fromname');
2121 $this->from_name = $mail->FromName;
2124 //Reply to information for case create and autoreply.
2125 if(!empty($this->reply_to_name)) {
2126 $ReplyToName = $this->reply_to_name;
2128 $ReplyToName = $mail->FromName;
2130 if(!empty($this->reply_to_addr)) {
2131 $ReplyToAddr = $this->reply_to_addr;
2133 $ReplyToAddr = $mail->From;
2135 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
2136 $mail->AddReplyTo($ReplyToAddr,$locale->translateCharsetMIME(trim($ReplyToName), 'UTF-8', $OBCharset));
2138 //$mail->Subject = html_entity_decode($this->name, ENT_QUOTES, 'UTF-8');
2139 $mail->Subject = $this->name;
2141 ///////////////////////////////////////////////////////////////////////
2143 foreach($this->saved_attachments as $note) {
2144 $mime_type = 'text/plain';
2145 if($note->object_name == 'Note') {
2146 if(!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) { // brandy-new file upload/attachment
2147 $file_location = $sugar_config['upload_dir'].$note->id;
2148 $filename = $note->file->original_file_name;
2149 $mime_type = $note->file->mime_type;
2150 } else { // attachment coming from template/forward
2151 $file_location = rawurldecode(UploadFile::get_file_path($note->filename,$note->id));
2152 // cn: bug 9723 - documents from EmailTemplates sent with Doc Name, not file name.
2153 $filename = !empty($note->filename) ? $note->filename : $note->name;
2154 $mime_type = $note->file_mime_type;
2156 } elseif($note->object_name == 'DocumentRevision') { // from Documents
2157 $filePathName = $note->id;
2158 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
2159 $filename = $note->getDocumentRevisionNameForDisplay();
2160 $file_location = getcwd().'/'.$GLOBALS['sugar_config']['upload_dir'].$filePathName;
2161 $mime_type = $note->file_mime_type;
2164 // strip out the "Email attachment label if exists
2165 $filename = str_replace($mod_strings['LBL_EMAIL_ATTACHMENT'].': ', '', $filename);
2167 //is attachment in our list of bad files extensions? If so, append .txt to file location
2168 //get position of last "." in file name
2169 $file_ext_beg = strrpos($file_location,".");
2171 //get file extension
2172 if($file_ext_beg >0){
2173 $file_ext = substr($file_location, $file_ext_beg+1 );
2175 //check to see if this is a file with extension located in "badext"
2176 foreach($sugar_config['upload_badext'] as $badExt) {
2177 if(strtolower($file_ext) == strtolower($badExt)) {
2178 //if found, then append with .txt to filename and break out of lookup
2179 //this will make sure that the file goes out with right extension, but is stored
2181 $file_location = $file_location . ".txt";
2182 break; // no need to look for more
2185 $mail->AddAttachment($file_location,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
2188 if($note->embed_flag == true) {
2190 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64',$mime_type);
2193 //// END ATTACHMENTS
2194 ///////////////////////////////////////////////////////////////////////
2196 $mail = $this->handleBody($mail);
2198 $GLOBALS['log']->debug('Email sending --------------------- ');
2200 ///////////////////////////////////////////////////////////////////////
2201 //// I18N TRANSLATION
2202 $mail->prepForOutbound();
2203 //// END I18N TRANSLATION
2204 ///////////////////////////////////////////////////////////////////////
2207 ///////////////////////////////////////////////////////////////////
2208 //// INBOUND EMAIL HANDLING
2210 if(!empty($_REQUEST['inbound_email_id'])) {
2211 $ieMail = new Email();
2212 $ieMail->retrieve($_REQUEST['inbound_email_id']);
2213 $ieMail->status = 'replied';
2216 $GLOBALS['log']->debug(' --------------------- buh bye -- sent successful');
2217 //// END INBOUND EMAIL HANDLING
2218 ///////////////////////////////////////////////////////////////////
2221 $GLOBALS['log']->debug($app_strings['LBL_EMAIL_ERROR_PREPEND'].$mail->ErrorInfo);
2226 function listviewACLHelper(){
2227 $array_assign = parent::listviewACLHelper();
2229 if(!empty($this->parent_name)){
2231 if(!empty($this->parent_name_owner)){
2232 global $current_user;
2233 $is_owner = $current_user->id == $this->parent_name_owner;
2236 if(!ACLController::moduleSupportsACL($this->parent_type) || ACLController::checkAccess($this->parent_type, 'view', $is_owner)){
2237 $array_assign['PARENT'] = 'a';
2239 $array_assign['PARENT'] = 'span';
2242 if(!empty($this->contact_name)) {
2243 if(!empty($this->contact_name_owner)) {
2244 global $current_user;
2245 $is_owner = $current_user->id == $this->contact_name_owner;
2248 if(ACLController::checkAccess('Contacts', 'view', $is_owner)) {
2249 $array_assign['CONTACT'] = 'a';
2251 $array_assign['CONTACT'] = 'span';
2254 return $array_assign;
2257 function getSystemDefaultEmail() {
2260 $r1 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromaddress\'');
2261 $r2 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromname\'');
2262 $a1 = $this->db->fetchByAssoc($r1);
2263 $a2 = $this->db->fetchByAssoc($r2);
2265 $email['email'] = $a1['value'];
2266 $email['name'] = $a2['value'];
2272 function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false) {
2274 if ($return_array) {
2275 return parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, $return_array,$parentbean, $singleSelect);
2277 $custom_join = $this->custom_fields->getJOIN();
2279 $query = "SELECT ".$this->table_name.".*, users.user_name as assigned_user_name\n";
2282 $query .= $custom_join['select'];
2284 $query .= " FROM emails\n";
2285 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2286 $query .= " LEFT JOIN emails_beans ON emails.id = emails_beans.email_id\n";
2289 $query .= " LEFT JOIN users ON emails.assigned_user_id=users.id \n";
2290 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2292 $query .= " JOIN contacts ON contacts.id= emails_beans.bean_id AND emails_beans.bean_module='Contacts' and contacts.deleted=0 \n";
2296 $query .= $custom_join['join'];
2299 if($show_deleted == 0) {
2300 $where_auto = " emails.deleted=0 \n";
2301 }else if($show_deleted == 1){
2302 $where_auto = " emails.deleted=1 \n";
2306 $query .= "WHERE $where AND ".$where_auto;
2308 $query .= "WHERE ".$where_auto;
2311 $query .= " ORDER BY $order_by";
2313 $query .= " ORDER BY date_sent DESC";
2319 function fill_in_additional_list_fields() {
2321 $this->fill_in_additional_detail_fields();
2323 $this->link_action = 'DetailView';
2324 ///////////////////////////////////////////////////////////////////////
2325 //populate attachment_image, used to display attachment icon.
2326 $query = "select 1 from notes where notes.parent_id = '$this->id' and notes.deleted = 0";
2327 $result =$this->db->query($query,true," Error filling in additional list fields: ");
2329 $row = $this->db->fetchByAssoc($result);
2332 $this->attachment_image = SugarThemeRegistry::current()->getImage('attachment',"","","");
2334 $this->attachment_image = SugarThemeRegistry::current()->getImage('blank',"","","");
2336 ///////////////////////////////////////////////////////////////////////
2337 if(empty($this->contact_id) && !empty($this->parent_id) && !empty($this->parent_type) && $this->parent_type === 'Contacts' && !empty($this->parent_name) ){
2338 $this->contact_id = $this->parent_id;
2339 $this->contact_name = $this->parent_name;
2343 function fill_in_additional_detail_fields() {
2344 global $app_list_strings,$mod_strings;
2345 // Fill in the assigned_user_name
2346 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id, '');
2347 //if ($this->parent_type == 'Contacts') {
2348 $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 ";
2349 $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";
2350 if(!empty($this->parent_id)){
2351 $query .= " AND contacts.id= '".$this->parent_id."' ";
2352 }else if(!empty($_REQUEST['record'])){
2353 $query .= " AND contacts.id= '".$_REQUEST['record']."' ";
2355 $result =$this->db->query($query,true," Error filling in additional detail fields: ");
2357 // Get the id and the name.
2358 $row = $this->db->fetchByAssoc($result);
2362 $contact = new Contact();
2363 $contact->retrieve($row['id']);
2364 $this->contact_name = $contact->full_name;
2365 $this->contact_phone = $row['phone_work'];
2366 $this->contact_id = $row['id'];
2367 $this->contact_email = $contact->emailAddress->getPrimaryAddress($contact);
2368 $this->contact_name_owner = $row['contact_name_owner'];
2369 $this->contact_name_mod = $row['contact_name_mod'];
2370 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2371 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2372 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2373 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2376 $this->contact_name = '';
2377 $this->contact_phone = '';
2378 $this->contact_id = '';
2379 $this->contact_email = '';
2380 $this->contact_name_owner = '';
2381 $this->contact_name_mod = '';
2382 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2383 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2384 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2385 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2388 $this->created_by_name = get_assigned_user_name($this->created_by);
2389 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
2391 $this->link_action = 'DetailView';
2393 if(!empty($this->type)) {
2394 if($this->type == 'out' && $this->status == 'send_error') {
2395 $this->type_name = $mod_strings['LBL_NOT_SENT'];
2397 $this->type_name = $app_list_strings['dom_email_types'][$this->type];
2400 if(($this->type == 'out' && $this->status == 'send_error') || $this->type == 'draft') {
2401 $this->link_action = 'EditView';
2405 //todo this isset( $app_list_strings['dom_email_status'][$this->status]) is hack for 3261.
2406 if(!empty($this->status) && isset( $app_list_strings['dom_email_status'][$this->status])) {
2407 $this->status_name = $app_list_strings['dom_email_status'][$this->status];
2410 if ( empty($this->name ) && empty($_REQUEST['record'])) {
2411 $this->name = $mod_strings['LBL_NO_SUBJECT'];
2414 $this->fill_in_additional_parent_fields();
2419 function create_export_query(&$order_by, &$where) {
2420 $contact_required = stristr($where, "contacts");
2421 $custom_join = $this->custom_fields->getJOIN(true, true,$where);
2423 if($contact_required) {
2424 $query = "SELECT emails.*, contacts.first_name, contacts.last_name";
2426 $query .= $custom_join['select'];
2429 $query .= " FROM contacts, emails, emails_contacts ";
2430 $where_auto = "emails_contacts.contact_id = contacts.id AND emails_contacts.email_id = emails.id AND emails.deleted=0 AND contacts.deleted=0";
2432 $query = 'SELECT emails.*';
2434 $query .= $custom_join['select'];
2437 $query .= ' FROM emails ';
2438 $where_auto = "emails.deleted=0";
2442 $query .= $custom_join['join'];
2446 $query .= "where $where AND ".$where_auto;
2448 $query .= "where ".$where_auto;
2451 $query .= " ORDER BY $order_by";
2453 $query .= " ORDER BY emails.name";
2457 function get_list_view_data() {
2458 global $app_list_strings;
2460 global $current_user;
2462 global $mod_strings;
2464 $email_fields = $this->get_list_view_array();
2465 $this->retrieveEmailText();
2466 $email_fields['FROM_ADDR'] = $this->from_addr_name;
2467 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); // hard-coding for Home screen ListView
2469 if($this->status != 'replied') {
2470 $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>';
2471 $email_fields['STATUS'] = ($email_fields['REPLY_TO_STATUS'] == 1 ? $mod_strings['LBL_REPLIED'] : $email_fields['STATUS']);
2473 $email_fields['QUICK_REPLY'] = $mod_strings['LBL_REPLIED'];
2475 if(!empty($this->parent_type)) {
2476 $email_fields['PARENT_MODULE'] = $this->parent_type;
2478 switch($this->intent) {
2480 $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>';
2484 $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>';
2488 $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>';
2492 $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>';
2496 $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>';
2509 $email_fields['CREATE_RELATED'] = $this->quickCreateForm();
2515 //BUG 17098 - MFH changed $this->from_addr to $this->to_addrs
2516 $email_fields['CONTACT_NAME'] = empty($this->contact_name) ? '</a>'.$this->trimLongTo($this->to_addrs).'<a>' : $this->contact_name;
2517 $email_fields['CONTACT_ID'] = empty($this->contact_id) ? '' : $this->contact_id;
2518 $email_fields['ATTACHMENT_IMAGE'] = $this->attachment_image;
2519 $email_fields['LINK_ACTION'] = $this->link_action;
2521 if(isset($this->type_name))
2522 $email_fields['TYPE_NAME'] = $this->type_name;
2524 return $email_fields;
2527 function quickCreateForm() {
2528 global $mod_strings, $app_strings, $currentModule, $current_language;
2530 // Coming from the home page via Dashlets
2531 if($currentModule != 'Email')
2532 $mod_strings = return_module_language($current_language, 'Emails');
2533 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>";
2537 * Searches all imported emails and returns the result set as an array.
2540 function searchImportedEmails($sort = '', $direction='')
2542 require_once('include/TimeDate.php');
2544 global $current_user;
2546 global $sugar_config;
2547 global $app_strings;
2549 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
2550 // cn: default to a low number until user specifies otherwise
2551 if(empty($emailSettings['showNumInList']))
2554 $pageSize = $emailSettings['showNumInList'];
2556 if( isset($_REQUEST['start']) && isset($_REQUEST['limit']) )
2557 $page = ceil($_REQUEST['start'] / $_REQUEST['limit']) + 1;
2561 //Determine sort ordering
2563 //Sort ordering parameters in the request do not coincide with actual column names
2564 //so we need to remap them.
2565 $hrSortLocal = array(
2566 'flagged' => 'type',
2567 'status' => 'reply_to_status',
2568 'from' => 'emails_text.from_addr',
2569 'subject' => 'name',
2570 'date' => 'date_sent',
2571 'AssignedTo' => 'assigned_user_id',
2572 'flagged' => 'flagged'
2575 $sort = !empty($_REQUEST['sort']) ? $_REQUEST['sort'] : "";
2576 $direction = !empty($_REQUEST['dir']) ? $_REQUEST['dir'] : "";
2578 $order = ( !empty($sort) && !empty($direction) ) ? " ORDER BY {$hrSortLocal[$sort]} {$direction}" : "";
2580 //Get our main query.
2581 $fullQuery = $this->_genereateSearchImportedEmailsQuery();
2583 //Perform a count query needed for pagination.
2584 $countQuery = $this->create_list_count_query($fullQuery);
2585 $count_rs = $this->db->query($countQuery, false, 'Error executing count query for imported emails search');
2586 $count_row = $this->db->fetchByAssoc($count_rs);
2587 $total_count = ($count_row != null) ? $count_row['c'] : 0;
2589 $start = ($page - 1) * $pageSize;
2592 $rs = $this->db->limitQuery($fullQuery . $order, $start, $pageSize);
2596 while($a = $this->db->fetchByAssoc($rs)) {
2598 $temp['flagged'] = (is_null($a['flagged']) || $a['flagged'] == '0') ? '' : 1;
2599 $temp['status'] = (is_null($a['reply_to_status']) || $a['reply_to_status'] == '0') ? '' : 1;
2600 $temp['subject'] = $a['name'];
2601 $temp['date'] = $timedate->to_display_date_time($a['date_sent']);
2602 $temp['uid'] = $a['id'];
2603 $temp['ieId'] = $a['mailbox_id'];
2604 $temp['site_url'] = $sugar_config['site_url'];
2605 $temp['seen'] = ($a['status'] == 'unread') ? 0 : 1;
2606 $temp['type'] = $a['type'];
2607 $temp['mbox'] = 'sugar::Emails';
2608 $temp['hasAttach'] = $this->doesImportedEmailHaveAttachment($a['id']);
2609 //To and from addresses may be stored in emails_text, if nothing is found, revert to
2610 //regular email addresses.
2611 $temp['to_addrs'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['to_addrs']);
2612 $temp['from'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['from_addr']);
2613 if( empty($temp['from']) || empty($temp['to_addrs']) )
2615 //Retrieve email addresses seperatly.
2616 $tmpEmail = new Email();
2617 $tmpEmail->id = $a['id'];
2618 $tmpEmail->retrieveEmailAddresses();
2619 $temp['from'] = $tmpEmail->from_addr;
2620 $temp['to_addrs'] = $tmpEmail->to_addrs;
2626 $metadata = array();
2627 $metadata['totalCount'] = $total_count;
2628 $metadata['out'] = $return;
2634 * Determine if an imported email has an attachment by examining the relationship to notes.
2639 function doesImportedEmailHaveAttachment($id)
2641 $hasAttachment = FALSE;
2642 $query = "SELECT id FROM notes where parent_id='$id' AND parent_type='Emails' AND file_mime_type is not null AND deleted=0";
2643 $rs = $this->db->limitQuery($query, 0, 1);
2644 $row = $this->db->fetchByAssoc($rs);
2645 if( !empty($row['id']) )
2646 $hasAttachment = TRUE;
2648 return (int) $hasAttachment;
2652 * Generate the query used for searching imported emails.
2654 * @return String Query to be executed.
2656 function _genereateSearchImportedEmailsQuery()
2660 $additionalWhereClause = $this->_generateSearchImportWhereClause();
2664 $query['select'] = "emails.id , emails.mailbox_id, emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status,
2665 emails_text.from_addr, emails_text.to_addrs FROM emails ";
2667 $query['joins'] = " JOIN emails_text on emails.id = emails_text.email_id ";
2669 //Handle from and to addr joins
2670 if( !empty($_REQUEST['from_addr']) )
2672 $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
2673 AND er_from.address_type='from' AND ea_from.email_address='" . strtolower($_REQUEST['from_addr']) . "'";
2676 if( !empty($_REQUEST['to_addrs']) )
2678 $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
2679 AND er_to.address_type='to' AND ea_to.email_address='" . strtolower($_REQUEST['to_addrs']) . "'";
2682 $query['where'] = " WHERE (emails.type= 'inbound' OR emails.type='archived' OR emails.type='out') AND emails.deleted = 0 ";
2683 if( !empty($additionalWhereClause) )
2684 $query['where'] .= "AND $additionalWhereClause";
2686 //If we are explicitly looking for attachments. Do not use a distinct query as the to_addr is defined
2687 //as a text which equals clob in oracle and the distinct query can not be executed correctly.
2688 $addDistinctKeyword = "";
2689 if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 1) //1 indicates yes
2690 $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 )";
2691 else if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 2 )
2692 $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 )";
2694 $fullQuery = "SELECT " . $query['select'] . " " . $query['joins'] . " " . $query['where'];
2699 * Generate the where clause for searching imported emails.
2702 function _generateSearchImportWhereClause()
2706 //The clear button was removed so if a user removes the asisgned user name, do not process the id.
2707 if( empty($_REQUEST['assigned_user_name']) && !empty($_REQUEST['assigned_user_id']) )
2708 unset($_REQUEST['assigned_user_id']);
2710 $availableSearchParam = array('name' => array('table_name' =>'emails'),
2711 'data_parent_id_search' => array('table_name' =>'emails','db_key' => 'parent_id','opp' => '='),
2712 'assigned_user_id' => array('table_name' => 'emails', 'opp' => '=') );
2714 $additionalWhereClause = array();
2715 foreach ($availableSearchParam as $key => $properties)
2717 if( !empty($_REQUEST[$key]) )
2719 $db_key = isset($properties['db_key']) ? $properties['db_key'] : $key;
2720 $searchValue = $_REQUEST[$key];
2722 $opp = isset($properties['opp']) ? $properties['opp'] : 'like';
2724 $searchValue = $searchValue . "%";
2726 $additionalWhereClause[] = "{$properties['table_name']}.$db_key $opp '$searchValue' ";
2730 $isDateFromSearchSet = !empty($_REQUEST['dateFrom']);
2731 $isdateToSearchSet = !empty($_REQUEST['dateTo']);
2732 $bothDateRangesSet = $isDateFromSearchSet & $isdateToSearchSet;
2734 //Hanlde date from and to seperately
2735 if($bothDateRangesSet)
2737 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['dateFrom'], false);
2738 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2740 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['dateTo'], false);
2741 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2743 $additionalWhereClause[] = "( emails.date_sent >= $dbFormatDateFrom AND
2744 emails.date_sent <= $dbFormatDateTo )";
2746 elseif ($isdateToSearchSet)
2748 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['dateTo'], false);
2749 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2750 $additionalWhereClause[] = "emails.date_sent <= $dbFormatDateTo ";
2752 elseif ($isDateFromSearchSet)
2754 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['dateFrom'], false);
2755 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2756 $additionalWhereClause[] = "emails.date_sent >= $dbFormatDateFrom ";
2759 $additionalWhereClause = implode(" AND ", $additionalWhereClause);
2761 return $additionalWhereClause;
2767 * takes a long TO: string of emails and returns the first appended by an
2770 function trimLongTo($str) {
2771 if(strpos($str, ',')) {
2772 $exStr = explode(',', $str);
2773 return $exStr[0].'...';
2774 } elseif(strpos($str, ';')) {
2775 $exStr = explode(';', $str);
2776 return $exStr[0].'...';
2782 function get_summary_text() {
2788 function distributionForm($where) {
2789 global $app_list_strings;
2790 global $app_strings;
2791 global $mod_strings;
2793 global $current_user;
2795 $distribution = get_select_options_with_id($app_list_strings['dom_email_distribution'], '');
2796 $_SESSION['distribute_where'] = $where;
2799 $out = '<form name="Distribute" id="Distribute">';
2800 $out .= get_form_header($mod_strings['LBL_DIST_TITLE'], '', false);
2807 <table cellpadding="0" cellspacing="0" width="100%" border="0">
2810 <script type="text/javascript">
2813 function checkDeps(form) {
2817 function mySubmit() {
2818 var assform = document.getElementById("Distribute");
2819 var select = document.getElementById("userSelect");
2820 var assign1 = assform.r1.checked;
2821 var assign2 = assform.r2.checked;
2822 var dist = assform.dm.value;
2826 var warn1 = "'.$mod_strings['LBL_WARN_NO_USERS'].'";
2829 if(assign1 || assign2) {
2834 for(i=0; i<select.options.length; i++) {
2835 if(select.options[i].selected == true) {
2844 warn2 = "'.$mod_strings['LBL_WARN_NO_DIST'].'";
2847 if(assign && users && rules) {
2849 if(document.getElementById("r1").checked) {
2850 var mu = document.getElementById("MassUpdate");
2853 for(i=0; i<mu.elements.length; i++) {
2854 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name.value != "massall") {
2855 if(grabbed != "") { grabbed += "::"; }
2856 grabbed += mu.elements[i].value;
2859 var formgrab = document.getElementById("grabbed");
2860 formgrab.value = grabbed;
2864 alert("'.$mod_strings['LBL_ASSIGN_WARN'].'" + "\n" + warn1 + "\n" + warn2);
2868 function submitDelete() {
2869 if(document.getElementById("r1").checked) {
2870 var mu = document.getElementById("MassUpdate");
2873 for(i=0; i<mu.elements.length; i++) {
2874 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name != "massall") {
2875 if(grabbed != "") { grabbed += "::"; }
2876 grabbed += mu.elements[i].value;
2879 var formgrab = document.getElementById("grabbed");
2880 formgrab.value = grabbed;
2883 alert("'.$mod_strings['LBL_MASS_DELETE_ERROR'].'");
2885 document.getElementById("Distribute").submit();
2890 <input type="hidden" name="module" value="Emails">
2891 <input type="hidden" name="action" id="action">
2892 <input type="hidden" name="grabbed" id="grabbed">
2894 <table cellpadding="1" cellspacing="0" width="100%" border="0" class="edit view">
2896 <td scope="col" scope="row" NOWRAP align="center">
2897 '.$mod_strings['LBL_ASSIGN_SELECTED_RESULTS_TO'].' ';
2898 $out .= $this->userSelectTable();
2900 <td scope="col" scope="row" NOWRAP align="left">
2901 '.$mod_strings['LBL_USING_RULES'].'
2902 <select name="distribute_method" id="dm" onChange="checkDeps(this.form);">'.$distribution.'</select>
2911 <td scope="col" width="50%" scope="row" NOWRAP align="right" colspan="2">
2912 <input title="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_TITLE'].'"
2914 accessKey="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_KEY'].'"
2915 class="button" onClick="AjaxObject.detailView.handleAssignmentDialogAssignAction();"
2916 type="button" name="button"
2917 value=" '.$mod_strings['LBL_BUTTON_DISTRIBUTE'].' ">';
2927 function userSelectTable() {
2929 global $mod_strings;
2932 $setTeamUserFunction = '';
2936 $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");
2938 $userTable = '<table cellpadding="0" cellspacing="0" border="0">';
2939 $userTable .= '<tr><td colspan="2"><b>'.$mod_strings['LBL_USER_SELECT'].'</b></td></tr>';
2940 $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>';
2941 $userTable .= '<tr><td colspan="2"><select style="visibility:hidden;" name="users[]" id="userSelect" multiple size="12">';
2943 while($a = $this->db->fetchByAssoc($r)) {
2944 $userTable .= '<option value="'.$a['id'].'" id="'.$a['id'].'">'.$a['first_name'].' '.$a['last_name'].'</option>';
2946 $userTable .= '</select></td></tr>';
2947 $userTable .= '</table>';
2949 $out = '<script type="text/javascript">';
2950 $out .= $setTeamUserFunction;
2952 function setCheckMark() {
2953 var select = document.getElementById("userSelect");
2955 for(i=0 ; i<select.options.length; i++) {
2956 if(select.options[i].selected == true) {
2957 document.getElementById("checkMark").style.display="";
2962 document.getElementById("checkMark").style.display="none";
2966 function showUserSelect() {
2967 var targetTable = document.getElementById("user_select");
2968 targetTable.style.visibility="visible";
2969 var userSelectTable = document.getElementById("userSelect");
2970 userSelectTable.style.visibility="visible";
2973 function hideUserSelect() {
2974 var targetTable = document.getElementById("user_select");
2975 targetTable.style.visibility="hidden";
2976 var userSelectTable = document.getElementById("userSelect");
2977 userSelectTable.style.visibility="hidden";
2980 function toggleAll(toggle) {
2981 if(toggle.checked) {
2986 var form = document.getElementById("userSelect");
2987 for(i=0; i<form.options.length; i++) {
2988 form.options[i].selected = stat;
2994 <span id="showUsersDiv" style="position:relative;">
2995 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
2996 <img border="0" src="'.SugarThemeRegistry::current()->getImageURL('Users.gif').'"></a>
2997 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
2998 <span style="display:none;" id="checkMark"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('check_inline.gif').'"></span>
3002 <div id="user_select" style="width:200px;position:absolute;left:2;top:2;visibility:hidden;z-index:1000;">
3003 <table cellpadding="0" cellspacing="0" border="0" class="list view">
3005 <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\';">
3006 <a href="#" onClick="javascript:hideUserSelect();"><img border="0" src="'.SugarThemeRegistry::current()->getImageURL('close.gif').'"></a>
3007 '.$mod_strings['LBL_USER_SELECT'].'
3011 //<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\';">
3012 $out .= ' <td style="padding:5px" class="oddListRowS1" bgcolor="#fdfdfd" valign="top" align="left" style="left:0;top:0;">
3021 function checkInbox($type) {
3023 global $mod_strings;
3024 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_CHECK_TITLE'].'"
3025 accessKey="'.$mod_strings['LBL_BUTTON_CHECK_KEY'].'"
3027 type="button" name="button"
3028 onClick="window.location=\'index.php?module=Emails&action=Check&type='.$type.'\';"
3029 style="margin-bottom:2px"
3030 value=" '.$mod_strings['LBL_BUTTON_CHECK'].' "></div>';
3035 * Guesses Primary Parent id from From: email address. Cascades guesses from Accounts to Contacts to Leads to
3036 * Users. This will not affect the many-to-many relationships already constructed as this is, at best,
3037 * informational linking.
3039 function fillPrimaryParentFields() {
3040 if(empty($this->from_addr))
3043 $GLOBALS['log']->debug("*** Email trying to guess Primary Parent from address [ {$this->from_addr} ]");
3045 $tables = array('accounts');
3047 // loop through types to get hits
3048 foreach($tables as $table) {
3049 $q = "SELECT name, id FROM {$table} WHERE email1 = '{$this->from_addr}' OR email2 = '{$this->from_addr}' AND deleted = 0";
3050 $r = $this->db->query($q);
3051 while($a = $this->db->fetchByAssoc($r)) {
3052 if(!empty($a['name']) && !empty($a['id'])) {
3053 $this->parent_type = ucwords($table);
3054 $this->parent_id = $a['id'];
3055 $this->parent_name = $a['name'];