2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2012 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 ********************************************************************************/
39 require_once('include/SugarPHPMailer.php');
40 require_once 'include/upload_file.php';
42 class Email extends SugarBean {
43 /* SugarBean schema */
47 var $assigned_user_id;
48 var $assigned_user_name;
49 var $modified_user_id;
61 var $type = 'archived';
72 var $description_html;
82 var $date_start; // legacy
83 var $time_start; // legacy
96 var $bcc_addrs_emails;
100 /* Archive Email attrs */
105 var $new_schema = true;
106 var $table_name = 'emails';
107 var $module_dir = 'Emails';
108 var $module_name = 'Emails';
109 var $object_name = 'Email';
112 /* private attributes */
113 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";
115 var $cacheFile = 'robin.cache.php';
116 var $replyDelimiter = "> ";
117 var $emailDescription;
118 var $emailDescriptionHTML;
122 var $attachments = array();
124 /* to support Email 2.0 */
132 var $relationshipMap = array(
133 'Contacts' => 'emails_contacts_rel',
134 'Accounts' => 'emails_accounts_rel',
135 'Leads' => 'emails_leads_rel',
136 'Users' => 'emails_users_rel',
137 'Prospects' => 'emails_prospects_rel',
141 var $et; // EmailUI object
142 // prefix to use when importing inlinge images in emails
146 * Used for keeping track of field defs that have been modified
150 public $modifiedFieldDefs = array();
157 global $current_user;
158 $this->cachePath = sugar_cached('modules/Emails');
161 $this->emailAddress = new SugarEmailAddress();
163 $this->imagePrefix = rtrim($GLOBALS['sugar_config']['site_url'], "/")."/cache/images/";
166 function email2init() {
167 require_once('modules/Emails/EmailUI.php');
168 $this->et = new EmailUI();
171 function bean_implements($interface){
173 case 'ACL': return true;
174 default: return false;
180 * Presaves one attachment for new email 2.0 spec
181 * DOES NOT CREATE A NOTE
182 * @return string ID of note associated with the attachment
184 public function email2saveAttachment()
186 $email_uploads = "modules/Emails/{$GLOBALS['current_user']->id}";
187 $upload = new UploadFile('email_attachment');
188 if(!$upload->confirm_upload()) {
189 $err = $upload->get_upload_error();
191 $GLOBALS['log']->error("Email Attachment could not be attached due to error: $err");
196 $guid = create_guid();
197 $fileName = $upload->create_stored_filename();
198 $GLOBALS['log']->debug("Email Attachment [$fileName]");
199 if($upload->final_move($guid)) {
200 copy("upload://$guid", sugar_cached("$email_uploads/$guid"));
203 'name' => $GLOBALS['db']->quote($fileName),
204 'nameForDisplay' => $fileName
207 $GLOBALS['log']->debug("Email Attachment [$fileName] could not be moved to upload dir");
212 function safeAttachmentName($filename) {
213 global $sugar_config;
214 $badExtension = false;
215 //get position of last "." in file name
216 $file_ext_beg = strrpos($filename, ".");
220 if($file_ext_beg !== false) {
221 $file_ext = substr($filename, $file_ext_beg + 1);
224 //check to see if this is a file with extension located in "badext"
225 foreach($sugar_config['upload_badext'] as $badExt) {
226 if(strtolower($file_ext) == strtolower($badExt)) {
227 //if found, then append with .txt and break out of lookup
228 $filename = $filename . ".txt";
229 $badExtension = true;
230 break; // no need to look for more
234 return $badExtension;
238 * takes output from email 2.0 to/cc/bcc fields and returns appropriate arrays for usage by PHPMailer
239 * @param string addresses
242 function email2ParseAddresses($addresses) {
243 $addresses = from_html($addresses);
244 $addresses = $this->et->unifyEmailString($addresses);
246 $pattern = '/@.*,/U';
247 preg_match_all($pattern, $addresses, $matchs);
248 if (!empty($matchs[0])){
250 foreach ($total as $match) {
251 $convertedPattern = str_replace(',', '::;::', $match);
252 $addresses = str_replace($match, $convertedPattern, $addresses);
256 $exAddr = explode("::;::", $addresses);
259 $clean = array("<", ">");
260 $dirty = array("<", ">");
262 foreach($exAddr as $addr) {
265 $addr = str_replace($dirty, $clean, $addr);
267 if((strpos($addr, "<") === false) && (strpos($addr, ">") === false)) {
270 $address = substr($addr, strpos($addr, "<") + 1, strpos($addr, ">") - 1 - strpos($addr, "<"));
271 $name = substr($addr, 0, strpos($addr, "<"));
275 $addrTemp['email'] = trim($address);
276 $addrTemp['display'] = trim($name);
284 * takes output from email 2.0 to/cc/bcc fields and returns appropriate arrays for usage by PHPMailer
285 * @param string addresses
288 function email2ParseAddressesForAddressesOnly($addresses) {
289 $addresses = from_html($addresses);
290 $pattern = '/@.*,/U';
291 preg_match_all($pattern, $addresses, $matchs);
292 if (!empty($matchs[0])){
294 foreach ($total as $match) {
295 $convertedPattern = str_replace(',', '::;::', $match);
296 $addresses = str_replace($match, $convertedPattern, $addresses);
300 $exAddr = explode("::;::", $addresses);
303 $clean = array("<", ">");
304 $dirty = array("<", ">");
306 foreach($exAddr as $addr) {
309 $addr = str_replace($dirty, $clean, $addr);
311 if(strpos($addr, "<") && strpos($addr, ">")) {
312 $address = substr($addr, strpos($addr, "<") + 1, strpos($addr, ">") - 1 - strpos($addr, "<"));
317 $ret[] = trim($address);
324 * Determines MIME-type encoding as possible.
325 * @param string $fileLocation relative path to file
326 * @return string MIME-type
328 function email2GetMime($fileLocation) {
329 if(!is_readable($fileLocation)) {
330 return 'application/octet-stream';
332 if(function_exists('mime_content_type')) {
333 $mime = mime_content_type($fileLocation);
334 } elseif(function_exists('ext2mime')) {
335 $mime = ext2mime($fileLocation);
337 $mime = 'application/octet-stream';
343 function sendEmailTest($mailserver_url, $port, $ssltls, $smtp_auth_req, $smtp_username, $smtppassword, $fromaddress, $toaddress, $mail_sendtype = 'smtp', $fromname = '') {
344 global $current_user,$app_strings;
345 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); //Called from EmailMan as well.
346 $mail = new SugarPHPMailer();
347 $mail->Mailer = strtolower($mail_sendtype);
348 if($mail->Mailer == 'smtp')
350 $mail->Host = $mailserver_url;
352 if (isset($ssltls) && !empty($ssltls)) {
353 $mail->protocol = "ssl://";
355 $mail->SMTPSecure = 'ssl';
358 $mail->SMTPSecure = 'tls';
361 $mail->protocol = "tcp://";
363 if ($smtp_auth_req) {
364 $mail->SMTPAuth = TRUE;
365 $mail->Username = $smtp_username;
366 $mail->Password = $smtppassword;
370 $mail->Mailer = 'sendmail';
372 $mail->Subject = from_html($mod_strings['LBL_TEST_EMAIL_SUBJECT']);
373 $mail->From = $fromaddress;
375 if ($fromname != '') {
376 $mail->FromName = html_entity_decode($fromname,ENT_QUOTES);
378 $mail->FromName = $current_user->name;
381 $mail->Sender = $mail->From;
382 $mail->AddAddress($toaddress);
383 $mail->Body = $mod_strings['LBL_TEST_EMAIL_BODY'];
389 $return['status'] = false;
390 $return['errorMessage'] = $app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo;
393 $return['status'] = true;
397 function decodeDuringSend($htmlData) {
398 $htmlData = str_replace("sugarLessThan", "<", $htmlData);
399 $htmlData = str_replace("sugarGreaterThan", ">", $htmlData);
404 * Returns true or false if this email is a draft.
406 * @param array $request
407 * @return bool True indicates this email is a draft.
409 function isDraftEmail($request)
411 return ( isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft') );
415 * Sends Email for Email 2.0
417 function email2Send($request) {
420 global $current_user;
421 global $sugar_config;
426 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
428 /**********************************************************************
434 if(!empty($this->id)) {
435 $orignialId = $this->id;
438 if(empty($this->id)) {
439 $this->id = create_guid();
440 $this->new_with_id = true;
443 /* satisfy basic HTML email requirements */
444 $this->name = $request['sendSubject'];
445 $this->description_html = '<html><body>'.$request['sendDescription'].'</body></html>';
447 /**********************************************************************
450 $mail = new SugarPHPMailer();
451 $mail = $this->setMailer($mail, '', $_REQUEST['fromAccount']);
452 if (empty($mail->Host) && !$this->isDraftEmail($request))
454 $this->status = 'send_error';
456 if ($mail->oe->type == 'system')
457 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_SYSTEM_OUTBOUND']);
459 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_PERSONAL_OUTBOUND']);
464 $subject = $this->name;
465 $mail->Subject = from_html($this->name);
467 // work-around legacy code in SugarPHPMailer
468 if($_REQUEST['setEditor'] == 1) {
469 $_REQUEST['description_html'] = $_REQUEST['sendDescription'];
470 $this->description_html = $_REQUEST['description_html'];
472 $this->description_html = '';
473 $this->description = $_REQUEST['sendDescription'];
477 if ( $this->isDraftEmail($request) )
479 if($this->type != 'draft' && $this->status != 'draft') {
480 $this->id = create_guid();
481 $this->new_with_id = true;
482 $this->date_entered = "";
484 $q1 = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$this->id}'";
485 $r1 = $this->db->query($q1);
488 if (isset($request['saveDraft'])) {
489 $this->type = 'draft';
490 $this->status = 'draft';
493 /* Apply Email Templates */
494 // do not parse email templates if the email is being saved as draft....
495 $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']);
496 $sea = new SugarEmailAddress();
497 $object_arr = array();
499 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
500 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) &&
501 ($_REQUEST['parent_type'] == 'Accounts' ||
502 $_REQUEST['parent_type'] == 'Contacts' ||
503 $_REQUEST['parent_type'] == 'Leads' ||
504 $_REQUEST['parent_type'] == 'Users' ||
505 $_REQUEST['parent_type'] == 'Prospects')) {
506 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
507 $className = $beanList[$_REQUEST['parent_type']];
508 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
509 if(!class_exists($className)) {
510 require_once($beanFiles[$className]);
512 $bean = new $className();
513 $bean->retrieve($_REQUEST['parent_id']);
514 $object_arr[$bean->module_dir] = $bean->id;
518 foreach($toAddresses as $addrMeta) {
519 $addr = $addrMeta['email'];
520 $beans = $sea->getBeansByEmailAddress($addr);
521 foreach($beans as $bean) {
522 if (!isset($object_arr[$bean->module_dir])) {
523 $object_arr[$bean->module_dir] = $bean->id;
528 /* template parsing */
529 if (empty($object_arr)) {
530 $object_arr= array('Contacts' => '123');
532 $object_arr['Users'] = $current_user->id;
533 $this->description_html = EmailTemplate::parse_template($this->description_html, $object_arr);
534 $this->name = EmailTemplate::parse_template($this->name, $object_arr);
535 $this->description = EmailTemplate::parse_template($this->description, $object_arr);
536 $this->description = html_entity_decode($this->description,ENT_COMPAT,'UTF-8');
537 if($this->type != 'draft' && $this->status != 'draft') {
538 $this->id = create_guid();
539 $this->date_entered = "";
540 $this->new_with_id = true;
542 $this->status = 'sent';
546 if(isset($_REQUEST['parent_type']) && empty($_REQUEST['parent_type']) &&
547 isset($_REQUEST['parent_id']) && empty($_REQUEST['parent_id']) ) {
548 $this->parent_id = "";
549 $this->parent_type = "";
553 $mail->Subject = $this->name;
554 $mail = $this->handleBody($mail);
555 $mail->Subject = $this->name;
556 $this->description_html = from_html($this->description_html);
557 $this->description_html = $this->decodeDuringSend($this->description_html);
558 $this->description = $this->decodeDuringSend($this->description);
561 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user, true);
563 if(empty($request['fromAccount'])) {
564 $defaults = $current_user->getPreferredEmail();
565 $mail->From = $defaults['email'];
566 $mail->FromName = $defaults['name'];
567 $replyToName = $mail->FromName;
568 //$replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
570 // passed -> user -> system default
571 $ie = new InboundEmail();
572 $ie->retrieve($request['fromAccount']);
573 $storedOptions = unserialize(base64_decode($ie->stored_options));
577 //$replyToAddress = "";
578 if (!empty($storedOptions)) {
579 $fromAddress = $storedOptions['from_addr'];
580 $fromName = from_html($storedOptions['from_name']);
581 $replyToAddress = (isset($storedOptions['reply_to_addr']) ? $storedOptions['reply_to_addr'] : "");
582 $replyToName = (isset($storedOptions['reply_to_name']) ? from_html($storedOptions['reply_to_name']) : "");
584 $defaults = $current_user->getPreferredEmail();
585 // Personal Account doesn't have reply To Name and Reply To Address. So add those columns on UI
586 // After adding remove below code
589 if ($ie->is_personal)
591 if (empty($replyToAddress))
593 $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user, true);
595 if (empty($replyToName))
597 $replyToName = $defaults['name'];
599 //Personal accounts can have a reply_address, which should
600 //overwrite the users set default.
601 if( !empty($storedOptions['reply_to_addr']) )
602 $replyToAddress = $storedOptions['reply_to_addr'];
605 // end of code to remove
606 $mail->From = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
607 $mail->FromName = (!empty($fromName)) ? $fromName : $defaults['name'];
608 $replyToName = (!empty($replyToName)) ? $replyToName : $mail->FromName;
611 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
613 if (!empty($replyToAddress)) {
614 $mail->AddReplyTo($replyToAddress,$locale->translateCharsetMIME(trim( $replyToName), 'UTF-8', $OBCharset));
616 $mail->AddReplyTo($mail->From,$locale->translateCharsetMIME(trim( $mail->FromName), 'UTF-8', $OBCharset));
618 $emailAddressCollection = array(); // used in linking to beans below
620 foreach($this->email2ParseAddresses($request['sendTo']) as $addr_arr) {
621 if(empty($addr_arr['email'])) continue;
623 if(empty($addr_arr['display'])) {
624 $mail->AddAddress($addr_arr['email'], "");
626 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
628 $emailAddressCollection[] = $addr_arr['email'];
630 foreach($this->email2ParseAddresses($request['sendCc']) as $addr_arr) {
631 if(empty($addr_arr['email'])) continue;
633 if(empty($addr_arr['display'])) {
634 $mail->AddCC($addr_arr['email'], "");
636 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
638 $emailAddressCollection[] = $addr_arr['email'];
641 foreach($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) {
642 if(empty($addr_arr['email'])) continue;
644 if(empty($addr_arr['display'])) {
645 $mail->AddBCC($addr_arr['email'], "");
647 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
649 $emailAddressCollection[] = $addr_arr['email'];
653 /* parse remove attachments array */
654 $removeAttachments = array();
655 if(!empty($request['templateAttachmentsRemove'])) {
656 $exRemove = explode("::", $request['templateAttachmentsRemove']);
658 foreach($exRemove as $file) {
659 $removeAttachments = substr($file, 0, 36);
663 /* handle attachments */
664 if(!empty($request['attachments'])) {
665 $exAttachments = explode("::", $request['attachments']);
667 foreach($exAttachments as $file) {
668 $file = trim(from_html($file));
669 $file = str_replace("\\", "", $file);
671 //$fileLocation = $this->et->userCacheDir."/{$file}";
672 $fileGUID = substr($file, 0, 36);
673 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
674 $filename = substr($file, 36, strlen($file)); // strip GUID for PHPMailer class to name outbound file
676 $mail->AddAttachment($fileLocation,$filename, 'base64', $this->email2GetMime($fileLocation));
677 //$mail->AddAttachment($fileLocation, $filename, 'base64');
679 // only save attachments if we're archiving or drafting
680 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
682 $note->id = create_guid();
683 $note->new_with_id = true; // duplicating the note with files
684 $note->parent_id = $this->id;
685 $note->parent_type = $this->module_dir;
686 $note->name = $filename;
687 $note->filename = $filename;
688 $note->file_mime_type = $this->email2GetMime($fileLocation);
689 $dest = "upload://{$note->id}";
690 if(!copy($fileLocation, $dest)) {
691 $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to $fileLocation => $dest");
700 /* handle sugar documents */
701 if(!empty($request['documents'])) {
702 $exDocs = explode("::", $request['documents']);
704 foreach($exDocs as $docId) {
705 $docId = trim($docId);
707 $doc = new Document();
708 $docRev = new DocumentRevision();
709 $doc->retrieve($docId);
710 $docRev->retrieve($doc->document_revision_id);
712 $filename = $docRev->filename;
713 $fileLocation = "upload://{$docRev->id}";
714 $mime_type = $docRev->file_mime_type;
715 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
717 // only save attachments if we're archiving or drafting
718 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
720 $note->id = create_guid();
721 $note->new_with_id = true; // duplicating the note with files
722 $note->parent_id = $this->id;
723 $note->parent_type = $this->module_dir;
724 $note->name = $filename;
725 $note->filename = $filename;
726 $note->file_mime_type = $mime_type;
727 $dest = "upload://{$note->id}";
728 if(!copy($fileLocation, $dest)) {
729 $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file $fileLocation => $dest");
738 /* handle template attachments */
739 if(!empty($request['templateAttachments'])) {
741 $exNotes = explode("::", $request['templateAttachments']);
742 foreach($exNotes as $noteId) {
743 $noteId = trim($noteId);
744 if(!empty($noteId)) {
746 $note->retrieve($noteId);
747 if (!empty($note->id)) {
748 $filename = $note->filename;
749 $fileLocation = "upload://{$note->id}";
750 $mime_type = $note->file_mime_type;
751 if (!$note->embed_flag) {
752 $mail->AddAttachment($fileLocation,$filename, 'base64', $mime_type);
753 // only save attachments if we're archiving or drafting
754 if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
756 if ($note->parent_id != $this->id)
757 $this->saveTempNoteAttachments($filename,$fileLocation, $mime_type);
762 //$fileLocation = $this->et->userCacheDir."/{$file}";
763 $fileGUID = substr($noteId, 0, 36);
764 $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
765 //$fileLocation = $this->et->userCacheDir."/{$noteId}";
766 $filename = substr($noteId, 36, strlen($noteId)); // strip GUID for PHPMailer class to name outbound file
768 $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $this->email2GetMime($fileLocation));
770 //If we are saving an email we were going to forward we need to save the attachments as well.
771 if( (($this->type == 'draft') && !empty($this->id))
772 || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1))
774 $mimeType = $this->email2GetMime($fileLocation);
775 $this->saveTempNoteAttachments($filename,$fileLocation, $mimeType);
784 /**********************************************************************
787 /* save email to sugar? */
790 if($this->type == 'draft' && !isset($request['saveDraft'])) {
791 // sending a draft email
793 $this->status = 'sent';
795 } elseif(isset($request['saveDraft'])) {
796 $this->type = 'draft';
797 $this->status = 'draft';
801 /**********************************************************************
802 * SEND EMAIL (finally!)
805 if ($this->type != 'draft') {
806 $mail->prepForOutbound();
807 $mail->Body = $this->decodeDuringSend($mail->Body);
808 $mail->AltBody = $this->decodeDuringSend($mail->AltBody);
809 if (!$mail->Send()) {
810 $this->status = 'send_error';
812 echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo);
817 if ((!(empty($orignialId) || isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft'))) &&
818 (($_REQUEST['composeType'] == 'reply') || ($_REQUEST['composeType'] == 'replyAll') || ($_REQUEST['composeType'] == 'replyCase')) && ($orignialId != $this->id)) {
819 $originalEmail = new Email();
820 $originalEmail->retrieve($orignialId);
821 $originalEmail->reply_to_status = 1;
822 $originalEmail->save();
823 $this->reply_to_status = 0;
826 if ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase') {
827 if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) {
828 $emailFromIe = new InboundEmail();
829 $emailFromIe->retrieve($_REQUEST['ieId']);
830 $emailFromIe->mailbox = $_REQUEST['mbox'];
831 if (isset($emailFromIe->id) && $emailFromIe->is_personal) {
832 if ($emailFromIe->isPop3Protocol()) {
833 $emailFromIe->mark_answered($this->uid, 'pop3');
835 elseif ($emailFromIe->connectMailserver() == 'true') {
836 $emailFromIe->markEmails($this->uid, 'answered');
837 $emailFromIe->mark_answered($this->uid);
845 $this->type == 'draft' ||
846 (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
848 // saving a draft OR saving a sent email
849 $decodedFromName = mb_decode_mimeheader($mail->FromName);
850 $this->from_addr = "{$decodedFromName} <{$mail->From}>";
851 $this->from_addr_name = $this->from_addr;
852 $this->to_addrs = $_REQUEST['sendTo'];
853 $this->to_addrs_names = $_REQUEST['sendTo'];
854 $this->cc_addrs = $_REQUEST['sendCc'];
855 $this->cc_addrs_names = $_REQUEST['sendCc'];
856 $this->bcc_addrs = $_REQUEST['sendBcc'];
857 $this->bcc_addrs_names = $_REQUEST['sendBcc'];
858 $this->assigned_user_id = $current_user->id;
860 $this->date_sent = $timedate->now();
861 ///////////////////////////////////////////////////////////////////
862 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
864 if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
865 isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) ) {
866 $this->parent_id = $_REQUEST['parent_id'];
867 $this->parent_type = $_REQUEST['parent_type'];
868 $q = "SELECT count(*) c FROM emails_beans WHERE email_id = '{$this->id}' AND bean_id = '{$_REQUEST['parent_id']}' AND bean_module = '{$_REQUEST['parent_type']}'";
869 $r = $this->db->query($q);
870 $a = $this->db->fetchByAssoc($r);
872 if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
873 $className = $beanList[$_REQUEST['parent_type']];
874 if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
875 if(!class_exists($className)) {
876 require_once($beanFiles[$className]);
878 $bean = new $className();
879 $bean->retrieve($_REQUEST['parent_id']);
880 if($bean->load_relationship('emails')) {
881 $bean->emails->add($this->id);
891 if(!class_exists('aCase')) {
896 if($caseId = InboundEmail::getCaseIdFromCaseNumber($mail->Subject, $c)) {
897 $c->retrieve($caseId);
898 $c->load_relationship('emails');
899 $c->emails->add($this->id);
900 $this->parent_type = "Cases";
901 $this->parent_id = $caseId;
907 //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
908 ///////////////////////////////////////////////////////////////////
912 if(!empty($request['fromAccount'])) {
913 if (isset($ie->id) && !$ie->isPop3Protocol() && $mail->oe->mail_smtptype != 'gmail') {
914 $sentFolder = $ie->get_stored_options("sentFolder");
915 if (!empty($sentFolder)) {
916 $data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n";
917 $ie->mailbox = $sentFolder;
918 if ($ie->connectMailserver() == 'true') {
919 $connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox);
920 $returnData = imap_append($ie->conn,$connectString, $data, "\\Seen");
922 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}");
925 $GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}");
928 $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty");
936 * Generates a config-specified separated name and addresses to be used in compose email screen for
937 * contacts or leads from listview
938 * By default, use comma, but allow for non-standard delimeters as specified in email_address_separator
940 * @param $module string module name
941 * @param $idsArray array of record ids to get the email address for
942 * @return string (config-specified) delimited list of email addresses
944 public function getNamePlusEmailAddressesForCompose($module, $idsArray)
948 $table = SugarModule::get($module)->loadBean()->table_name;
949 $returndata = array();
951 foreach($idsArray as $id) {
952 if ($idsString != "") {
953 $idsString = $idsString . ",";
955 $idsString = $idsString . "'" . $id . "'";
957 $where = "({$table}.deleted = 0 AND {$table}.id in ({$idsString}))";
959 if ($module == 'Users' || $module == 'Employees') {
960 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.title";
962 elseif (SugarModule::get($module)->moduleImplements('Person')) {
963 $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.salutation, {$table}.title";
966 $selectColumn = "{$table}.name";
968 $query = "SELECT {$table}.id, {$selectColumn}, eabr.primary_address, ea.email_address";
969 $query .= " FROM {$table} ";
970 $query .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
971 $query .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
972 $query .= " WHERE ({$where}) ORDER BY eabr.primary_address DESC";
973 $r = $this->db->query($query);
975 while($a = $this->db->fetchByAssoc($r)) {
976 if (!isset($returndata[$a['id']])) {
977 if ($module == 'Users' || $module == 'Employees') {
978 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], '', $a['title']));
979 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
981 elseif (SugarModule::get($module)->moduleImplements('Person')) {
982 $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], $a['salutation'], $a['title']));
983 $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
986 $returndata[$a['id']] = from_html($a['name']) . " <".from_html($a['email_address']).">";
991 // broken out of method to facilitate unit testing
992 return $this->_arrayToDelimitedString($returndata);
996 * @param Array $arr - list of strings
997 * @return string the list of strings delimited by email_address_separator
999 function _arrayToDelimitedString($arr)
1001 // bug 51804: outlook does not respect the correct email address separator (',') , so let
1002 // clients override the default.
1003 $separator = (isset($GLOBALS['sugar_config']['email_address_separator']) &&
1004 !empty($GLOBALS['sugar_config']['email_address_separator'])) ?
1005 $GLOBALS['sugar_config']['email_address_separator'] :
1008 return join($separator, array_values($arr));
1014 ///////////////////////////////////////////////////////////////////////////
1016 function save($check_notify = false) {
1017 global $current_user;
1019 if($this->isDuplicate) {
1020 $GLOBALS['log']->debug("EMAIL - tried to save a duplicate Email record");
1023 if(empty($this->id)) {
1024 $this->id = create_guid();
1025 $this->new_with_id = true;
1027 $this->from_addr_name = $this->cleanEmails($this->from_addr_name);
1028 $this->to_addrs_names = $this->cleanEmails($this->to_addrs_names);
1029 $this->cc_addrs_names = $this->cleanEmails($this->cc_addrs_names);
1030 $this->bcc_addrs_names = $this->cleanEmails($this->bcc_addrs_names);
1031 $this->reply_to_addr = $this->cleanEmails($this->reply_to_addr);
1032 $this->description = SugarCleaner::cleanHtml($this->description);
1033 $this->description_html = SugarCleaner::cleanHtml($this->description_html, true);
1034 $this->raw_source = SugarCleaner::cleanHtml($this->raw_source, true);
1035 $this->saveEmailText();
1036 $this->saveEmailAddresses();
1038 $GLOBALS['log']->debug('-------------------------------> Email called save()');
1040 // handle legacy concatenation of date and time fields
1041 //Bug 39503 - SugarBean is not setting date_sent when seconds missing
1042 if(empty($this->date_sent)) {
1044 $date_sent_obj = $timedate->fromUser($timedate->merge_date_time($this->date_start, $this->time_start), $current_user);
1045 if (!empty($date_sent_obj) && ($date_sent_obj instanceof SugarDateTime)) {
1046 $this->date_sent = $date_sent_obj->asDb();
1050 parent::save($check_notify);
1052 if(!empty($this->parent_type) && !empty($this->parent_id)) {
1053 if(!empty($this->fetched_row) && !empty($this->fetched_row['parent_id']) && !empty($this->fetched_row['parent_type'])) {
1054 if($this->fetched_row['parent_id'] != $this->parent_id || $this->fetched_row['parent_type'] != $this->parent_type) {
1055 $mod = strtolower($this->fetched_row['parent_type']);
1056 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1057 if($this->load_relationship($rel) ) {
1058 $this->$rel->delete($this->id, $this->fetched_row['parent_id']);
1062 $mod = strtolower($this->parent_type);
1063 $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
1064 if($this->load_relationship($rel) ) {
1065 $this->$rel->add($this->parent_id);
1069 $GLOBALS['log']->debug('-------------------------------> Email save() done');
1073 * Helper function to save temporary attachments assocaited to an email as note.
1075 * @param string $filename
1076 * @param string $fileLocation
1077 * @param string $mimeType
1079 function saveTempNoteAttachments($filename,$fileLocation, $mimeType)
1081 $tmpNote = new Note();
1082 $tmpNote->id = create_guid();
1083 $tmpNote->new_with_id = true;
1084 $tmpNote->parent_id = $this->id;
1085 $tmpNote->parent_type = $this->module_dir;
1086 $tmpNote->name = $filename;
1087 $tmpNote->filename = $filename;
1088 $tmpNote->file_mime_type = $mimeType;
1089 $noteFile = "upload://{$tmpNote->id}";
1090 if(!copy($fileLocation, $noteFile)) {
1091 $GLOBALS['log']->fatal("EMAIL 2.0: could not copy SugarDocument revision file $fileLocation => $noteFile");
1096 * Handles normalization of Email Addressess
1098 function saveEmailAddresses() {
1099 // from, single address
1100 $fromId = $this->emailAddress->getEmailGUID(from_html($this->from_addr));
1101 if(!empty($fromId)){
1102 $this->linkEmailToAddress($fromId, 'from');
1106 $replace = array(",",";");
1107 $toaddrs = str_replace($replace, "::", from_html($this->to_addrs));
1108 $exToAddrs = explode("::", $toaddrs);
1110 if(!empty($exToAddrs)) {
1111 foreach($exToAddrs as $toaddr) {
1112 $toaddr = trim($toaddr);
1113 if(!empty($toaddr)) {
1114 $toId = $this->emailAddress->getEmailGUID($toaddr);
1115 $this->linkEmailToAddress($toId, 'to');
1121 $ccAddrs = str_replace($replace, "::", from_html($this->cc_addrs));
1122 $exccAddrs = explode("::", $ccAddrs);
1124 if(!empty($exccAddrs)) {
1125 foreach($exccAddrs as $ccAddr) {
1126 $ccAddr = trim($ccAddr);
1127 if(!empty($ccAddr)) {
1128 $ccId = $this->emailAddress->getEmailGUID($ccAddr);
1129 $this->linkEmailToAddress($ccId, 'cc');
1135 $bccAddrs = str_replace($replace, "::", from_html($this->bcc_addrs));
1136 $exbccAddrs = explode("::", $bccAddrs);
1137 if(!empty($exbccAddrs)) {
1138 foreach($exbccAddrs as $bccAddr) {
1139 $bccAddr = trim($bccAddr);
1140 if(!empty($bccAddr)) {
1141 $bccId = $this->emailAddress->getEmailGUID($bccAddr);
1142 $this->linkEmailToAddress($bccId, 'bcc');
1148 function linkEmailToAddress($id, $type) {
1149 // TODO: make this update?
1150 $q1 = "SELECT * FROM emails_email_addr_rel WHERE email_id = '{$this->id}' AND email_address_id = '{$id}' AND address_type = '{$type}' AND deleted = 0";
1151 $r1 = $this->db->query($q1);
1152 $a1 = $this->db->fetchByAssoc($r1);
1154 if(!empty($a1) && !empty($a1['id'])) {
1157 $guid = create_guid();
1158 $q2 = "INSERT INTO emails_email_addr_rel VALUES('{$guid}', '{$this->id}', '{$type}', '{$id}', 0)";
1159 $r2 = $this->db->query($q2);
1165 protected $email_to_text = array(
1167 "description" => "description",
1168 "description_html" => "description_html",
1169 "raw_source" => "raw_source",
1170 "from_addr" => "from_addr_name",
1171 "reply_to_addr" => "reply_to_addr",
1172 "to_addrs" => "to_addrs_names",
1173 "cc_addrs" => "cc_addrs_names",
1174 "bcc_addrs" => "bcc_addrs_names",
1177 function cleanEmails($emails)
1179 if(empty($emails)) return '';
1180 $emails = str_replace(array(",",";"), "::", from_html($emails));
1181 $addrs = explode("::", $emails);
1183 foreach($addrs as $addr) {
1184 $parts = $this->emailAddress->splitEmailAddress($addr);
1185 if(empty($parts["email"])) {
1188 if(!empty($parts["name"])) {
1189 $res[] = "{$parts['name']} <{$parts['email']}>";
1191 $res[] .= $parts["email"];
1194 return join(", ", $res);
1197 protected function saveEmailText()
1199 $text = SugarModule::get("EmailText")->loadBean();
1200 foreach($this->email_to_text as $textfield=>$mailfield) {
1201 $text->$textfield = $this->$mailfield;
1203 $text->email_id = $this->id;
1204 if(!$this->new_with_id) {
1205 $this->db->update($text);
1207 $this->db->insert($text);
1211 ///////////////////////////////////////////////////////////////////////////
1213 function retrieve($id, $encoded=true, $deleted=true) {
1214 // cn: bug 11915, return SugarBean's retrieve() call bean instead of $this
1215 $ret = parent::retrieve($id, $encoded, $deleted);
1218 $ret->retrieveEmailText();
1219 //$ret->raw_source = SugarCleaner::cleanHtml($ret->raw_source);
1220 $ret->description = to_html($ret->description);
1221 //$ret->description_html = SugarCleaner::cleanHtml($ret->description_html);
1222 $ret->retrieveEmailAddresses();
1224 $ret->date_start = '';
1225 $ret->time_start = '';
1226 $dateSent = explode(' ', $ret->date_sent);
1227 if (!empty($dateSent)) {
1228 $ret->date_start = $dateSent[0];
1229 if ( isset($dateSent[1]) )
1230 $ret->time_start = $dateSent[1];
1233 foreach($ret as $k => $v) {
1242 * Retrieves email addresses from GUIDs
1244 function retrieveEmailAddresses() {
1247 $q = "SELECT email_address, address_type
1248 FROM emails_email_addr_rel eam
1249 JOIN email_addresses ea ON ea.id = eam.email_address_id
1250 WHERE eam.email_id = '{$this->id}' AND eam.deleted=0";
1251 $r = $this->db->query($q);
1253 while($a = $this->db->fetchByAssoc($r)) {
1254 if(!isset($return[$a['address_type']])) {
1255 $return[$a['address_type']] = array();
1257 $return[$a['address_type']][] = $a['email_address'];
1260 if(count($return) > 0) {
1261 if(isset($return['from'])) {
1262 $this->from_addr = implode(", ", $return['from']);
1264 if(isset($return['to'])) {
1265 $this->to_addrs = implode(", ", $return['to']);
1267 if(isset($return['cc'])) {
1268 $this->cc_addrs = implode(", ", $return['cc']);
1270 if(isset($return['bcc'])) {
1271 $this->bcc_addrs = implode(", ", $return['bcc']);
1277 * Handles longtext fields
1279 function retrieveEmailText() {
1280 $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}'";
1281 $r = $this->db->query($q);
1282 $a = $this->db->fetchByAssoc($r, false);
1284 $this->description = $a['description'];
1285 $this->description_html = $a['description_html'];
1286 $this->raw_source = $a['raw_source'];
1287 $this->from_addr_name = $a['from_addr'];
1288 $this->reply_to_addr = $a['reply_to_addr'];
1289 $this->to_addrs_names = $a['to_addrs'];
1290 $this->cc_addrs_names = $a['cc_addrs'];
1291 $this->bcc_addrs_names = $a['bcc_addrs'];
1294 function delete($id='') {
1298 $q = "UPDATE emails SET deleted = 1 WHERE id = '{$id}'";
1299 $qt = "UPDATE emails_text SET deleted = 1 WHERE email_id = '{$id}'";
1300 $r = $this->db->query($q);
1301 $rt = $this->db->query($qt);
1305 * creates the standard "Forward" info at the top of the forwarded message
1308 function getForwardHeader() {
1309 global $mod_strings;
1310 global $current_user;
1312 //$from = str_replace(array(">","<"), array(")","("), $this->from_name);
1313 $from = to_html($this->from_name);
1314 $subject = to_html($this->name);
1315 $ret = "<br /><br />";
1316 $ret .= $this->replyDelimiter."{$mod_strings['LBL_FROM']} {$from}<br />";
1317 $ret .= $this->replyDelimiter."{$mod_strings['LBL_DATE_SENT']} {$this->date_sent}<br />";
1318 $ret .= $this->replyDelimiter."{$mod_strings['LBL_TO']} {$this->to_addrs}<br />";
1319 $ret .= $this->replyDelimiter."{$mod_strings['LBL_CC']} {$this->cc_addrs}<br />";
1320 $ret .= $this->replyDelimiter."{$mod_strings['LBL_SUBJECT']} {$subject}<br />";
1321 $ret .= $this->replyDelimiter."<br />";
1324 //return from_html($ret);
1328 * retrieves Notes that belong to this Email and stuffs them into the "attachments" attribute
1330 function getNotes($id, $duplicate=false) {
1331 if(!class_exists('Note')) {
1335 $exRemoved = array();
1336 if(isset($_REQUEST['removeAttachment'])) {
1337 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1340 $noteArray = array();
1341 $q = "SELECT id FROM notes WHERE parent_id = '".$id."'";
1342 $r = $this->db->query($q);
1344 while($a = $this->db->fetchByAssoc($r)) {
1345 if(!in_array($a['id'], $exRemoved)) {
1347 $note->retrieve($a['id']);
1349 // duplicate actual file when creating forwards
1351 if(!class_exists('UploadFile')) {
1352 require_once('include/upload_file.php');
1354 // save a brand new Note
1355 $noteDupe->id = create_guid();
1356 $noteDupe->new_with_id = true;
1357 $noteDupe->parent_id = $this->id;
1358 $noteDupe->parent_type = $this->module_dir;
1360 $noteFile = new UploadFile();
1361 $noteFile->duplicate_file($a['id'], $note->id, $note->filename);
1365 // add Note to attachments array
1366 $this->attachments[] = $note;
1372 * creates the standard "Reply" info at the top of the forwarded message
1375 function getReplyHeader() {
1376 global $mod_strings;
1377 global $current_user;
1379 $from = str_replace(array(">","<", ">","<"), array(")","(",")","("), $this->from_name);
1380 $ret = "<br>{$mod_strings['LBL_REPLY_HEADER_1']} {$this->date_start}, {$this->time_start}, {$from} {$mod_strings['LBL_REPLY_HEADER_2']}";
1382 return from_html($ret);
1386 * Quotes plain-text email text
1387 * @param string $text
1390 function quotePlainTextEmail($text) {
1394 $desc = nl2br(trim($text));
1395 $exDesc = explode('<br />', $desc);
1397 foreach($exDesc as $k => $line) {
1398 $quoted .= '> '.trim($line)."\r";
1405 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1406 * @param string $text HTML text to quote
1409 function quoteHtmlEmail($text) {
1410 $text = trim(from_html($text));
1415 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1421 * "quotes" (i.e., "> my text yadda" the HTML part of an email
1422 * @param string $text HTML text to quote
1425 function quoteHtmlEmailForNewEmailUI($text) {
1426 $text = trim($text);
1431 $text = str_replace("\n", "<BR/>", $text);
1432 $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
1438 * Ensures that the user is able to send outbound emails
1440 function check_email_settings() {
1441 global $current_user;
1443 $mail_fromaddress = $current_user->emailAddress->getPrimaryAddress($current_user);
1444 $replyToName = $current_user->getPreference('mail_fromname');
1445 $mail_fromname = (!empty($replyToName)) ? $current_user->getPreference('mail_fromname') : $current_user->full_name;
1447 if(empty($mail_fromaddress)) {
1450 if(empty($mail_fromname)) {
1454 $send_type = $current_user->getPreference('mail_sendtype') ;
1455 if (!empty($send_type) && $send_type == "SMTP") {
1456 $mail_smtpserver = $current_user->getPreference('mail_smtpserver');
1457 $mail_smtpport = $current_user->getPreference('mail_smtpport');
1458 $mail_smtpauth_req = $current_user->getPreference('mail_smtpauth_req');
1459 $mail_smtpuser = $current_user->getPreference('mail_smtpuser');
1460 $mail_smtppass = $current_user->getPreference('mail_smtppass');
1461 if (empty($mail_smtpserver) ||
1462 empty($mail_smtpport) ||
1463 (!empty($mail_smtpauth_req) && ( empty($mail_smtpuser) || empty($mail_smtppass)))
1472 * outputs JS to set fields in the MassUpdate form in the "My Inbox" view
1474 function js_set_archived() {
1475 global $mod_strings;
1477 <script type="text/javascript" language="JavaScript"><!-- Begin
1478 function setArchived() {
1479 var form = document.getElementById("MassUpdate");
1480 var status = document.getElementById("mass_status");
1483 for(var i=0; i < form.elements.length; i++) {
1484 if(form.elements[i].name == "mass[]") {
1485 if(form.elements[i].checked == true) {
1492 var user = document.getElementById("mass_assigned_user_name");
1493 var team = document.getElementById("team");
1496 for(var j=0; j<status.length; j++) {
1497 if(status.options[j].value == "archived") {
1498 status.options[j].selected = true;
1499 status.selectedIndex = j; // for IE
1505 alert("'.$mod_strings['ERR_ARCHIVE_EMAIL'].'");
1509 // End --></script>';
1514 * replaces the javascript in utils.php - more specialized
1516 function u_get_clear_form_js($type='', $group='', $assigned_user_id='') {
1519 $uAssigned_user_id = '';
1521 if(!empty($type)) { $uType = '&type='.$type; }
1522 if(!empty($group)) { $uGroup = '&group='.$group; }
1523 if(!empty($assigned_user_id)) { $uAssigned_user_id = '&assigned_user_id='.$assigned_user_id; }
1526 <script type="text/javascript" language="JavaScript"><!-- Begin
1527 function clear_form(form) {
1528 var newLoc = "index.php?action=" + form.action.value + "&module=" + form.module.value + "&query=true&clear_query=true'.$uType.$uGroup.$uAssigned_user_id.'";
1529 if(typeof(form.advanced) != "undefined"){
1530 newLoc += "&advanced=" + form.advanced.value;
1532 document.location.href= newLoc;
1534 // End --></script>';
1538 function pickOneButton() {
1540 global $mod_strings;
1541 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_GRAB_TITLE'].'"
1543 type="button" name="button"
1544 onClick="window.location=\'index.php?module=Emails&action=Grab\';"
1545 style="margin-bottom:2px"
1546 value=" '.$mod_strings['LBL_BUTTON_GRAB'].' "></div>';
1551 * Determines what Editor (HTML or Plain-text) the current_user uses;
1552 * @return string Editor type
1554 function getUserEditorPreference() {
1555 global $sugar_config;
1556 global $current_user;
1560 if(!isset($sugar_config['email_default_editor'])) {
1561 $sugar_config = $current_user->setDefaultsInConfig();
1564 $userEditor = $current_user->getPreference('email_editor_option');
1565 $systemEditor = $sugar_config['email_default_editor'];
1567 if($userEditor != '') {
1568 $editor = $userEditor;
1570 $editor = $systemEditor;
1577 * takes the mess we pass from EditView and tries to create some kind of order
1578 * @param array addrs
1579 * @param array addrs_ids (from contacts)
1580 * @param array addrs_names (from contacts);
1581 * @param array addrs_emails (from contacts);
1582 * @return array Parsed assoc array to feed to PHPMailer
1584 function parse_addrs($addrs, $addrs_ids, $addrs_names, $addrs_emails) {
1585 // cn: bug 9406 - enable commas to separate email addresses
1586 $addrs = str_replace(",", ";", $addrs);
1588 $ltgt = array('<','>');
1589 $gtlt = array('<','>');
1592 $addrs = str_replace($ltgt, '', $addrs);
1593 $addrs_arr = explode(";",$addrs);
1594 $addrs_arr = $this->remove_empty_fields($addrs_arr);
1595 $addrs_ids_arr = explode(";",$addrs_ids);
1596 $addrs_ids_arr = $this->remove_empty_fields($addrs_ids_arr);
1597 $addrs_emails_arr = explode(";",$addrs_emails);
1598 $addrs_emails_arr = $this->remove_empty_fields($addrs_emails_arr);
1599 $addrs_names_arr = explode(";",$addrs_names);
1600 $addrs_names_arr = $this->remove_empty_fields($addrs_names_arr);
1602 ///////////////////////////////////////////////////////////////////////
1603 //// HANDLE EMAILS HAND-WRITTEN
1604 $contactRecipients = array();
1605 $knownEmails = array();
1607 foreach($addrs_arr as $i => $v) {
1609 continue; // skip any "blanks" - will always have 1
1611 $recipient = array();
1613 //// get the email to see if we're dealing with a dupe
1614 //// what crappy coding
1615 preg_match("/[A-Z0-9._%-\']+@[A-Z0-9.-]+\.[A-Z]{2,}/i",$v, $match);
1618 if(!empty($match[0]) && !in_array(trim($match[0]), $knownEmails)) {
1619 $knownEmails[] = $match[0];
1620 $recipient['email'] = $match[0];
1622 //// handle the Display name
1623 $display = trim(str_replace($match[0], '', $v));
1625 //// only trigger a "displayName" <email@address> when necessary
1626 if(isset($addrs_names_arr[$i])){
1627 $recipient['display'] = $addrs_names_arr[$i];
1629 else if(!empty($display)) {
1630 $recipient['display'] = $display;
1632 if(isset($addrs_ids_arr[$i]) && $addrs_emails_arr[$i] == $match[0]){
1633 $recipient['contact_id'] = $addrs_ids_arr[$i];
1635 $return[] = $recipient;
1642 function remove_empty_fields(&$arr) {
1645 foreach($arr as $field) {
1646 $field = trim($field);
1650 array_push($newarr,$field);
1656 * handles attachments of various kinds when sending email
1658 function handleAttachments() {
1663 global $mod_strings;
1665 ///////////////////////////////////////////////////////////////////////////
1666 //// ATTACHMENTS FROM DRAFTS
1667 if(($this->type == 'out' || $this->type == 'draft') && $this->status == 'draft' && isset($_REQUEST['record'])) {
1668 $this->getNotes($_REQUEST['record']); // cn: get notes from OLD email for use in new email
1670 //// END ATTACHMENTS FROM DRAFTS
1671 ///////////////////////////////////////////////////////////////////////////
1673 ///////////////////////////////////////////////////////////////////////////
1674 //// ATTACHMENTS FROM FORWARDS
1675 // Bug 8034 Jenny - Need the check for type 'draft' here to handle cases where we want to save
1676 // forwarded messages as drafts. We still need to save the original message's attachments.
1677 if(($this->type == 'out' || $this->type == 'draft') &&
1678 isset($_REQUEST['origType']) && $_REQUEST['origType'] == 'forward' &&
1679 isset($_REQUEST['return_id']) && !empty($_REQUEST['return_id'])
1681 $this->getNotes($_REQUEST['return_id'], true);
1684 // cn: bug 8034 - attachments from forward/replies lost when saving in draft
1685 if(isset($_REQUEST['prior_attachments']) && !empty($_REQUEST['prior_attachments']) && $this->new_with_id == true) {
1686 $exIds = explode(",", $_REQUEST['prior_attachments']);
1687 if(!isset($_REQUEST['template_attachment'])) {
1688 $_REQUEST['template_attachment'] = array();
1690 $_REQUEST['template_attachment'] = array_merge($_REQUEST['template_attachment'], $exIds);
1692 //// END ATTACHMENTS FROM FORWARDS
1693 ///////////////////////////////////////////////////////////////////////////
1695 ///////////////////////////////////////////////////////////////////////////
1696 //// ATTACHMENTS FROM TEMPLATES
1697 // to preserve individual email integrity, we must dupe Notes and associated files
1698 // for each outbound email - good for integrity, bad for filespace
1699 if(isset($_REQUEST['template_attachment']) && !empty($_REQUEST['template_attachment'])) {
1700 $removeArr = array();
1701 $noteArray = array();
1703 if(isset($_REQUEST['temp_remove_attachment']) && !empty($_REQUEST['temp_remove_attachment'])) {
1704 $removeArr = $_REQUEST['temp_remove_attachment'];
1708 foreach($_REQUEST['template_attachment'] as $noteId) {
1709 if(in_array($noteId, $removeArr)) {
1712 $noteTemplate = new Note();
1713 $noteTemplate->retrieve($noteId);
1714 $noteTemplate->id = create_guid();
1715 $noteTemplate->new_with_id = true; // duplicating the note with files
1716 $noteTemplate->parent_id = $this->id;
1717 $noteTemplate->parent_type = $this->module_dir;
1718 $noteTemplate->date_entered = '';
1719 $noteTemplate->save();
1721 $noteFile = new UploadFile();
1722 $noteFile->duplicate_file($noteId, $noteTemplate->id, $noteTemplate->filename);
1723 $noteArray[] = $noteTemplate;
1725 $this->attachments = array_merge($this->attachments, $noteArray);
1727 //// END ATTACHMENTS FROM TEMPLATES
1728 ///////////////////////////////////////////////////////////////////////////
1730 ///////////////////////////////////////////////////////////////////////////
1731 //// ADDING NEW ATTACHMENTS
1732 $max_files_upload = 10;
1733 // Jenny - Bug 8211 Since attachments for drafts have already been processed,
1734 // we don't need to re-process them.
1735 if($this->status != "draft") {
1736 $notes_list = array();
1737 if(!empty($this->id) && !$this->new_with_id) {
1739 $where = "notes.parent_id='{$this->id}'";
1740 $notes_list = $note->get_full_list("", $where, true);
1742 $this->attachments = array_merge($this->attachments, $notes_list);
1744 // cn: Bug 5995 - rudimentary error checking
1745 $filesError = array(
1746 0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
1747 1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
1748 2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
1749 3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
1750 4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
1751 5 => 'UNKNOWN ERROR',
1752 6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
1753 7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
1756 for($i = 0; $i < $max_files_upload; $i++) {
1757 // cn: Bug 5995 - rudimentary error checking
1758 if (!isset($_FILES["email_attachment{$i}"])) {
1759 $GLOBALS['log']->debug("Email Attachment {$i} does not exist.");
1762 if($_FILES['email_attachment'.$i]['error'] != 0 && $_FILES['email_attachment'.$i]['error'] != 4) {
1763 $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment'.$i]['error']]);
1768 $note->parent_id = $this->id;
1769 $note->parent_type = $this->module_dir;
1770 $upload_file = new UploadFile('email_attachment'.$i);
1772 if(empty($upload_file)) {
1776 if(isset($_FILES['email_attachment'.$i]) && $upload_file->confirm_upload()) {
1777 $note->filename = $upload_file->get_stored_file_name();
1778 $note->file = $upload_file;
1779 $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$note->file->original_file_name;
1781 $this->attachments[] = $note;
1785 $this->saved_attachments = array();
1786 foreach($this->attachments as $note) {
1787 if(!empty($note->id)) {
1788 array_push($this->saved_attachments, $note);
1791 $note->parent_id = $this->id;
1792 $note->parent_type = 'Emails';
1793 $note->file_mime_type = $note->file->mime_type;
1794 $note_id = $note->save();
1796 $this->saved_attachments[] = $note;
1798 $note->id = $note_id;
1799 $note->file->final_move($note->id);
1801 //// END NEW ATTACHMENTS
1802 ///////////////////////////////////////////////////////////////////////////
1804 ///////////////////////////////////////////////////////////////////////////
1805 //// ATTACHMENTS FROM DOCUMENTS
1806 for($i=0; $i<10; $i++) {
1807 if(isset($_REQUEST['documentId'.$i]) && !empty($_REQUEST['documentId'.$i])) {
1808 $doc = new Document();
1809 $docRev = new DocumentRevision();
1810 $docNote = new Note();
1811 $noteFile = new UploadFile();
1813 $doc->retrieve($_REQUEST['documentId'.$i]);
1814 $docRev->retrieve($doc->document_revision_id);
1816 $this->saved_attachments[] = $docRev;
1818 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
1819 $docNote->name = $docRev->getDocumentRevisionNameForDisplay();
1820 $docNote->filename = $docRev->filename;
1821 $docNote->description = $doc->description;
1822 $docNote->parent_id = $this->id;
1823 $docNote->parent_type = 'Emails';
1824 $docNote->file_mime_type = $docRev->file_mime_type;
1825 $docId = $docNote = $docNote->save();
1827 $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
1831 //// END ATTACHMENTS FROM DOCUMENTS
1832 ///////////////////////////////////////////////////////////////////////////
1834 ///////////////////////////////////////////////////////////////////////////
1835 //// REMOVE ATTACHMENTS
1836 if(isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
1837 foreach($_REQUEST['remove_attachment'] as $noteId) {
1838 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1839 $this->db->query($q);
1843 //this will remove attachments that have been selected to be removed from drafts.
1844 if(isset($_REQUEST['removeAttachment']) && !empty($_REQUEST['removeAttachment'])) {
1845 $exRemoved = explode('::', $_REQUEST['removeAttachment']);
1846 foreach($exRemoved as $noteId) {
1847 $q = 'UPDATE notes SET deleted = 1 WHERE id = \''.$noteId.'\'';
1848 $this->db->query($q);
1851 //// END REMOVE ATTACHMENTS
1852 ///////////////////////////////////////////////////////////////////////////
1857 * Determines if an email body (HTML or Plain) has a User signature already in the content
1858 * @param array Array of signatures
1861 function hasSignatureInBody($sig) {
1862 // strpos can't handle line breaks - normalize
1863 $html = $this->removeAllNewlines($this->description_html);
1864 $htmlSig = $this->removeAllNewlines($sig['signature_html']);
1865 $plain = $this->removeAllNewlines($this->description);
1866 $plainSig = $this->removeAllNewlines($sig['signature']);
1868 // cn: bug 11621 - empty sig triggers notice error
1869 if(!empty($htmlSig) && false !== strpos($html, $htmlSig)) {
1871 } elseif(!empty($plainSig) && false !== strpos($plain, $plainSig)) {
1880 * @param string String to be normalized
1883 function removeAllNewlines($str) {
1884 $bad = array("\r\n", "\n\r", "\n", "\r");
1885 $good = array('', '', '', '');
1887 return str_replace($bad, $good, strip_tags(br2nl(from_html($str))));
1893 * Set navigation anchors to aid DetailView record navigation (VCR buttons)
1894 * @param string uri The URI from the referring page (always ListView)
1895 * @return array start Array of the URI broken down with a special "current_view" for My Inbox Navs
1897 function getStartPage($uri) {
1898 if(strpos($uri, '&')) { // "&" to ensure that we can explode the GET vars - else we're gonna trigger a Notice error
1899 $serial = substr($uri, (strpos($uri, '?')+1), strlen($uri));
1900 $exUri = explode('&', $serial);
1901 $start = array('module' => '', 'action' => '', 'group' => '', 'record' => '', 'type' => '');
1903 foreach($exUri as $k => $pair) {
1904 $exPair = explode('=', $pair);
1905 $start[$exPair[0]] = $exPair[1];
1908 // specific views for current_user
1909 if(isset($start['assigned_user_id'])) {
1910 $start['current_view'] = "{$start['action']}&module={$start['module']}&assigned_user_id={$start['assigned_user_id']}&type={$start['type']}";
1920 * preps SMTP info for email transmission
1921 * @param object mail SugarPHPMailer object
1922 * @param string mailer_id
1923 * @param string ieId
1924 * @return object mail SugarPHPMailer object
1926 function setMailer($mail, $mailer_id='', $ieId='') {
1927 global $current_user;
1929 require_once("include/OutboundEmail/OutboundEmail.php");
1930 $oe = new OutboundEmail();
1931 $oe = $oe->getInboundMailerSettings($current_user, $mailer_id, $ieId);
1933 // ssl or tcp - keeping outside isSMTP b/c a default may inadvertantly set ssl://
1934 $mail->protocol = ($oe->mail_smtpssl) ? "ssl://" : "tcp://";
1935 if($oe->mail_sendtype == "SMTP")
1937 //Set mail send type information
1938 $mail->Mailer = "smtp";
1939 $mail->Host = $oe->mail_smtpserver;
1940 $mail->Port = $oe->mail_smtpport;
1941 if ($oe->mail_smtpssl == 1) {
1942 $mail->SMTPSecure = 'ssl';
1944 if ($oe->mail_smtpssl == 2) {
1945 $mail->SMTPSecure = 'tls';
1948 if($oe->mail_smtpauth_req) {
1949 $mail->SMTPAuth = TRUE;
1950 $mail->Username = $oe->mail_smtpuser;
1951 $mail->Password = $oe->mail_smtppass;
1955 $mail->Mailer = "sendmail";
1962 * preps SugarPHPMailer object for HTML or Plain text sends
1963 * @param SugarPHPMailer $mail SugarPHPMailer instance
1965 function handleBody($mail) {
1966 global $current_user;
1967 global $sugar_config;
1968 ///////////////////////////////////////////////////////////////////////
1969 //// HANDLE EMAIL FORMAT PREFERENCE
1970 // the if() below is HIGHLY dependent on the Javascript unchecking the Send HTML Email box
1972 if( (isset($_REQUEST['setEditor']) /* from Email EditView navigation */
1973 && $_REQUEST['setEditor'] == 1
1974 && trim($_REQUEST['description_html']) != '')
1975 || trim($this->description_html) != '' /* from email templates */
1976 && $current_user->getPreference('email_editor_option', 'global') !== 'plain' //user preference is not set to plain text
1978 $this->handleBodyInHTMLformat($mail);
1981 $this->description_html = '';
1982 $mail->IsHTML(false);
1983 $plainText = from_html($this->description);
1984 $plainText = str_replace(" ", " ", $plainText);
1985 $plainText = str_replace("</p>", "</p><br />", $plainText);
1986 $plainText = strip_tags(br2nl($plainText));
1987 $plainText = str_replace("&", "&", $plainText);
1988 $plainText = str_replace("'", "'", $plainText);
1989 $mail->Body = wordwrap($plainText, 996);
1990 $mail->Body = $this->decodeDuringSend($mail->Body);
1991 $this->description = $mail->Body;
1994 // wp: if plain text version has lines greater than 998, use base64 encoding
1995 foreach(explode("\n", ($mail->ContentType == "text/html") ? $mail->AltBody : $mail->Body) as $line) {
1996 if(strlen($line) > 998) {
1997 $mail->Encoding = 'base64';
2001 //// HANDLE EMAIL FORMAT PREFERENCE
2002 ///////////////////////////////////////////////////////////////////////
2008 * Retrieve function from handlebody() to unit test easily
2009 * @param SugarPHPMailer $mail SugarPHPMailer instance
2010 * @return formatted $mail body
2012 function handleBodyInHTMLformat($mail) {
2013 global $sugar_config;
2014 // wp: if body is html, then insert new lines at 996 characters. no effect on client side
2015 // due to RFC 2822 which limits email lines to 998
2016 $mail->IsHTML(true);
2017 $body = from_html(wordwrap($this->description_html, 996));
2018 $mail->Body = $body;
2021 // new plan is to use the selected type (html or plain) to fill the other
2022 $plainText = from_html($this->description_html);
2023 $plainText = strip_tags(br2nl($plainText));
2024 $mail->AltBody = $plainText;
2025 $this->description = $plainText;
2027 $mail->replaceImageByRegex("(?:{$sugar_config['site_url']})?/?cache/images/", sugar_cached("images/"));
2029 //Replace any embeded images using the secure entryPoint for src url.
2030 $mail->replaceImageByRegex("(?:{$sugar_config['site_url']})?/?index.php[?]entryPoint=download&(?:amp;)?[^\"]+?id=", "upload://", true);
2032 $mail->Body = from_html($mail->Body);
2037 * @return bool True on success
2040 global $mod_strings,$app_strings;
2041 global $current_user;
2042 global $sugar_config;
2044 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
2045 $mail = new SugarPHPMailer();
2047 foreach ($this->to_addrs_arr as $addr_arr) {
2048 if ( empty($addr_arr['display'])) {
2049 $mail->AddAddress($addr_arr['email'], "");
2051 $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
2054 foreach ($this->cc_addrs_arr as $addr_arr) {
2055 if ( empty($addr_arr['display'])) {
2056 $mail->AddCC($addr_arr['email'], "");
2058 $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2062 foreach ($this->bcc_addrs_arr as $addr_arr) {
2063 if ( empty($addr_arr['display'])) {
2064 $mail->AddBCC($addr_arr['email'], "");
2066 $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
2070 $mail = $this->setMailer($mail);
2073 if(!empty($this->from_addr)) {
2074 $mail->From = $this->from_addr;
2076 $mail->From = $current_user->getPreference('mail_fromaddress');
2077 $this->from_addr = $mail->From;
2080 if(!empty($this->from_name)) {
2081 $mail->FromName = $this->from_name;
2083 $mail->FromName = $current_user->getPreference('mail_fromname');
2084 $this->from_name = $mail->FromName;
2087 //Reply to information for case create and autoreply.
2088 if(!empty($this->reply_to_name)) {
2089 $ReplyToName = $this->reply_to_name;
2091 $ReplyToName = $mail->FromName;
2093 if(!empty($this->reply_to_addr)) {
2094 $ReplyToAddr = $this->reply_to_addr;
2096 $ReplyToAddr = $mail->From;
2098 $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
2099 $mail->AddReplyTo($ReplyToAddr,$locale->translateCharsetMIME(trim($ReplyToName), 'UTF-8', $OBCharset));
2101 //$mail->Subject = html_entity_decode($this->name, ENT_QUOTES, 'UTF-8');
2102 $mail->Subject = $this->name;
2104 ///////////////////////////////////////////////////////////////////////
2106 foreach($this->saved_attachments as $note) {
2107 $mime_type = 'text/plain';
2108 if($note->object_name == 'Note') {
2109 if(!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) { // brandy-new file upload/attachment
2110 $file_location = "upload://$note->id";
2111 $filename = $note->file->original_file_name;
2112 $mime_type = $note->file->mime_type;
2113 } else { // attachment coming from template/forward
2114 $file_location = "upload://{$note->id}";
2115 // cn: bug 9723 - documents from EmailTemplates sent with Doc Name, not file name.
2116 $filename = !empty($note->filename) ? $note->filename : $note->name;
2117 $mime_type = $note->file_mime_type;
2119 } elseif($note->object_name == 'DocumentRevision') { // from Documents
2120 $filePathName = $note->id;
2121 // cn: bug 9723 - Emails with documents send GUID instead of Doc name
2122 $filename = $note->getDocumentRevisionNameForDisplay();
2123 $file_location = "upload://$note->id";
2124 $mime_type = $note->file_mime_type;
2127 // strip out the "Email attachment label if exists
2128 $filename = str_replace($mod_strings['LBL_EMAIL_ATTACHMENT'].': ', '', $filename);
2129 $file_ext = pathinfo($filename, PATHINFO_EXTENSION);
2130 //is attachment in our list of bad files extensions? If so, append .txt to file location
2131 //check to see if this is a file with extension located in "badext"
2132 foreach($sugar_config['upload_badext'] as $badExt) {
2133 if(strtolower($file_ext) == strtolower($badExt)) {
2134 //if found, then append with .txt to filename and break out of lookup
2135 //this will make sure that the file goes out with right extension, but is stored
2137 $file_location = $file_location . ".txt";
2138 break; // no need to look for more
2141 $mail->AddAttachment($file_location,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
2144 if($note->embed_flag == true) {
2146 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64',$mime_type);
2149 //// END ATTACHMENTS
2150 ///////////////////////////////////////////////////////////////////////
2152 $mail = $this->handleBody($mail);
2154 $GLOBALS['log']->debug('Email sending --------------------- ');
2156 ///////////////////////////////////////////////////////////////////////
2157 //// I18N TRANSLATION
2158 $mail->prepForOutbound();
2159 //// END I18N TRANSLATION
2160 ///////////////////////////////////////////////////////////////////////
2163 ///////////////////////////////////////////////////////////////////
2164 //// INBOUND EMAIL HANDLING
2166 if(!empty($_REQUEST['inbound_email_id'])) {
2167 $ieMail = new Email();
2168 $ieMail->retrieve($_REQUEST['inbound_email_id']);
2169 $ieMail->status = 'replied';
2172 $GLOBALS['log']->debug(' --------------------- buh bye -- sent successful');
2173 //// END INBOUND EMAIL HANDLING
2174 ///////////////////////////////////////////////////////////////////
2177 $GLOBALS['log']->debug($app_strings['LBL_EMAIL_ERROR_PREPEND'].$mail->ErrorInfo);
2182 function listviewACLHelper(){
2183 $array_assign = parent::listviewACLHelper();
2185 if(!empty($this->parent_name)){
2187 if(!empty($this->parent_name_owner)){
2188 global $current_user;
2189 $is_owner = $current_user->id == $this->parent_name_owner;
2192 if(!ACLController::moduleSupportsACL($this->parent_type) || ACLController::checkAccess($this->parent_type, 'view', $is_owner)){
2193 $array_assign['PARENT'] = 'a';
2195 $array_assign['PARENT'] = 'span';
2198 if(!empty($this->contact_name)) {
2199 if(!empty($this->contact_name_owner)) {
2200 global $current_user;
2201 $is_owner = $current_user->id == $this->contact_name_owner;
2204 if(ACLController::checkAccess('Contacts', 'view', $is_owner)) {
2205 $array_assign['CONTACT'] = 'a';
2207 $array_assign['CONTACT'] = 'span';
2210 return $array_assign;
2213 function getSystemDefaultEmail() {
2216 $r1 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromaddress\'');
2217 $r2 = $this->db->query('SELECT config.value FROM config WHERE name=\'fromname\'');
2218 $a1 = $this->db->fetchByAssoc($r1);
2219 $a2 = $this->db->fetchByAssoc($r2);
2221 $email['email'] = $a1['value'];
2222 $email['name'] = $a2['value'];
2228 function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false) {
2230 if ($return_array) {
2231 return parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, $return_array,$parentbean, $singleSelect);
2233 $custom_join = $this->custom_fields->getJOIN();
2235 $query = "SELECT ".$this->table_name.".*, users.user_name as assigned_user_name\n";
2238 $query .= $custom_join['select'];
2240 $query .= " FROM emails\n";
2241 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2242 $query .= " LEFT JOIN emails_beans ON emails.id = emails_beans.email_id\n";
2245 $query .= " LEFT JOIN users ON emails.assigned_user_id=users.id \n";
2246 if ($where != "" && (strpos($where, "contacts.first_name") > 0)) {
2248 $query .= " JOIN contacts ON contacts.id= emails_beans.bean_id AND emails_beans.bean_module='Contacts' and contacts.deleted=0 \n";
2252 $query .= $custom_join['join'];
2255 if($show_deleted == 0) {
2256 $where_auto = " emails.deleted=0 \n";
2257 }else if($show_deleted == 1){
2258 $where_auto = " emails.deleted=1 \n";
2262 $query .= "WHERE $where AND ".$where_auto;
2264 $query .= "WHERE ".$where_auto;
2267 $query .= " ORDER BY $order_by";
2269 $query .= " ORDER BY date_sent DESC";
2275 function fill_in_additional_list_fields() {
2276 global $timedate, $mod_strings;
2277 $this->fill_in_additional_detail_fields();
2279 $this->link_action = 'DetailView';
2280 ///////////////////////////////////////////////////////////////////////
2281 //populate attachment_image, used to display attachment icon.
2282 $query = "select 1 from notes where notes.parent_id = '$this->id' and notes.deleted = 0";
2283 $result =$this->db->query($query,true," Error filling in additional list fields: ");
2285 $row = $this->db->fetchByAssoc($result);
2286 $this->attachment_image = ($row !=null) ? SugarThemeRegistry::current()->getImage('attachment',"","","") : "";
2289 $this->attachment_image = SugarThemeRegistry::current()->getImage('attachment',"","","",'.gif',translate('LBL_ATTACHMENT', 'Emails'));
2292 ///////////////////////////////////////////////////////////////////////
2293 if(empty($this->contact_id) && !empty($this->parent_id) && !empty($this->parent_type) && $this->parent_type === 'Contacts' && !empty($this->parent_name) ){
2294 $this->contact_id = $this->parent_id;
2295 $this->contact_name = $this->parent_name;
2299 function fill_in_additional_detail_fields() {
2300 global $app_list_strings,$mod_strings;
2301 // Fill in the assigned_user_name
2302 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id, '');
2303 //if ($this->parent_type == 'Contacts') {
2304 $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 ";
2305 $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";
2306 if(!empty($this->parent_id)){
2307 $query .= " AND contacts.id= '".$this->parent_id."' ";
2308 }else if(!empty($_REQUEST['record'])){
2309 $query .= " AND contacts.id= '".$_REQUEST['record']."' ";
2311 $result =$this->db->query($query,true," Error filling in additional detail fields: ");
2313 // Get the id and the name.
2314 $row = $this->db->fetchByAssoc($result);
2318 $contact = new Contact();
2319 $contact->retrieve($row['id']);
2320 $this->contact_name = $contact->full_name;
2321 $this->contact_phone = $row['phone_work'];
2322 $this->contact_id = $row['id'];
2323 $this->contact_email = $contact->emailAddress->getPrimaryAddress($contact);
2324 $this->contact_name_owner = $row['contact_name_owner'];
2325 $this->contact_name_mod = $row['contact_name_mod'];
2326 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2327 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2328 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2329 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2332 $this->contact_name = '';
2333 $this->contact_phone = '';
2334 $this->contact_id = '';
2335 $this->contact_email = '';
2336 $this->contact_name_owner = '';
2337 $this->contact_name_mod = '';
2338 $GLOBALS['log']->debug("Call($this->id): contact_name = $this->contact_name");
2339 $GLOBALS['log']->debug("Call($this->id): contact_phone = $this->contact_phone");
2340 $GLOBALS['log']->debug("Call($this->id): contact_id = $this->contact_id");
2341 $GLOBALS['log']->debug("Call($this->id): contact_email1 = $this->contact_email");
2344 $this->created_by_name = get_assigned_user_name($this->created_by);
2345 $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
2347 $this->link_action = 'DetailView';
2349 if(!empty($this->type)) {
2350 if($this->type == 'out' && $this->status == 'send_error') {
2351 $this->type_name = $mod_strings['LBL_NOT_SENT'];
2353 $this->type_name = $app_list_strings['dom_email_types'][$this->type];
2356 if(($this->type == 'out' && $this->status == 'send_error') || $this->type == 'draft') {
2357 $this->link_action = 'EditView';
2361 //todo this isset( $app_list_strings['dom_email_status'][$this->status]) is hack for 3261.
2362 if(!empty($this->status) && isset( $app_list_strings['dom_email_status'][$this->status])) {
2363 $this->status_name = $app_list_strings['dom_email_status'][$this->status];
2366 if ( empty($this->name ) && empty($_REQUEST['record'])) {
2367 $this->name = $mod_strings['LBL_NO_SUBJECT'];
2370 $this->fill_in_additional_parent_fields();
2375 function create_export_query(&$order_by, &$where) {
2376 $contact_required = stristr($where, "contacts");
2377 $custom_join = $this->custom_fields->getJOIN(true, true,$where);
2379 if($contact_required) {
2380 $query = "SELECT emails.*, contacts.first_name, contacts.last_name";
2382 $query .= $custom_join['select'];
2385 $query .= " FROM contacts, emails, emails_contacts ";
2386 $where_auto = "emails_contacts.contact_id = contacts.id AND emails_contacts.email_id = emails.id AND emails.deleted=0 AND contacts.deleted=0";
2388 $query = 'SELECT emails.*';
2390 $query .= $custom_join['select'];
2393 $query .= ' FROM emails ';
2394 $where_auto = "emails.deleted=0";
2398 $query .= $custom_join['join'];
2402 $query .= "where $where AND ".$where_auto;
2404 $query .= "where ".$where_auto;
2407 $query .= " ORDER BY $order_by";
2409 $query .= " ORDER BY emails.name";
2413 function get_list_view_data() {
2414 global $app_list_strings;
2416 global $current_user;
2418 global $mod_strings;
2420 $email_fields = $this->get_list_view_array();
2421 $this->retrieveEmailText();
2422 $email_fields['FROM_ADDR'] = $this->from_addr_name;
2423 $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); // hard-coding for Home screen ListView
2425 if($this->status != 'replied') {
2426 $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>';
2427 $email_fields['STATUS'] = ($email_fields['REPLY_TO_STATUS'] == 1 ? $mod_strings['LBL_REPLIED'] : $email_fields['STATUS']);
2429 $email_fields['QUICK_REPLY'] = $mod_strings['LBL_REPLIED'];
2431 if(!empty($this->parent_type)) {
2432 $email_fields['PARENT_MODULE'] = $this->parent_type;
2434 switch($this->intent) {
2436 $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Cases&action=EditView&inbound_email_id='.$this->id.'" >' . SugarThemeRegistry::current()->getImage('CreateCases', 'border="0"', null, null, ".gif", $mod_strings['LBL_CREATE_CASES']).$mod_strings['LBL_CREATE_CASE'].'</a>';
2440 $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Leads&action=EditView&inbound_email_id='.$this->id.'" >'.SugarThemeRegistry::current()->getImage('CreateLeads', 'border="0"', null, null, ".gif", $mod_strings['LBL_CREATE_LEADS']).$mod_strings['LBL_CREATE_LEAD'].'</a>';
2444 $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Contacts&action=EditView&inbound_email_id='.$this->id.'" >'.SugarThemeRegistry::current()->getImage('CreateContacts', 'border="0"', null, null, ".gif", $mod_strings['LBL_CREATE_CONTACTS']).$mod_strings['LBL_CREATE_CONTACT'].'</a>';
2448 $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Bugs&action=EditView&inbound_email_id='.$this->id.'" >'.SugarThemeRegistry::current()->getImage('CreateBugs', 'border="0"', null, null, ".gif", $mod_strings['LBL_CREATE_BUGS']).$mod_strings['LBL_CREATE_BUG'].'</a>';
2452 $email_fields['CREATE_RELATED'] = '<a href="index.php?module=Tasks&action=EditView&inbound_email_id='.$this->id.'" >'.SugarThemeRegistry::current()->getImage('CreateTasks', 'border="0"', null, null, ".gif", $mod_strings['LBL_CREATE_TASKS']).$mod_strings['LBL_CREATE_TASK'].'</a>';
2465 $email_fields['CREATE_RELATED'] = $this->quickCreateForm();
2471 //BUG 17098 - MFH changed $this->from_addr to $this->to_addrs
2472 $email_fields['CONTACT_NAME'] = empty($this->contact_name) ? '</a>'.$this->trimLongTo($this->to_addrs).'<a>' : $this->contact_name;
2473 $email_fields['CONTACT_ID'] = empty($this->contact_id) ? '' : $this->contact_id;
2474 $email_fields['ATTACHMENT_IMAGE'] = $this->attachment_image;
2475 $email_fields['LINK_ACTION'] = $this->link_action;
2477 if(isset($this->type_name))
2478 $email_fields['TYPE_NAME'] = $this->type_name;
2480 return $email_fields;
2483 function quickCreateForm() {
2484 global $mod_strings, $app_strings, $currentModule, $current_language;
2486 // Coming from the home page via Dashlets
2487 if($currentModule != 'Email')
2488 $mod_strings = return_module_language($current_language, 'Emails');
2489 return $mod_strings['LBL_QUICK_CREATE']." <a id='$this->id' onclick='return quick_create_overlib(\"{$this->id}\", \"".SugarThemeRegistry::current()->__toString()."\", this);' href=\"#\" >".SugarThemeRegistry::current()->getImage("advanced_search","border='0' align='absmiddle'", null,null,'.gif',$mod_strings['LBL_QUICK_CREATE'])."</a>";
2493 * Searches all imported emails and returns the result set as an array.
2496 function searchImportedEmails($sort = '', $direction='')
2498 require_once('include/TimeDate.php');
2500 global $current_user;
2502 global $sugar_config;
2503 global $app_strings;
2505 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
2506 // cn: default to a low number until user specifies otherwise
2507 if(empty($emailSettings['showNumInList']))
2510 $pageSize = $emailSettings['showNumInList'];
2512 if( isset($_REQUEST['start']) && isset($_REQUEST['limit']) )
2513 $page = ceil($_REQUEST['start'] / $_REQUEST['limit']) + 1;
2517 //Determine sort ordering
2519 //Sort ordering parameters in the request do not coincide with actual column names
2520 //so we need to remap them.
2521 $hrSortLocal = array(
2522 'flagged' => 'type',
2523 'status' => 'reply_to_status',
2524 'from' => 'emails_text.from_addr',
2525 'subject' => 'name',
2526 'date' => 'date_sent',
2527 'AssignedTo' => 'assigned_user_id',
2528 'flagged' => 'flagged'
2531 $sort = !empty($_REQUEST['sort']) ? $this->db->getValidDBName($_REQUEST['sort']) : "";
2532 $direction = !empty($_REQUEST['dir']) && in_array(strtolower($_REQUEST['dir']), array("asc", "desc")) ? $_REQUEST['dir'] : "";
2534 $order = ( !empty($sort) && !empty($direction) ) ? " ORDER BY {$hrSortLocal[$sort]} {$direction}" : "";
2536 //Get our main query.
2537 $fullQuery = $this->_genereateSearchImportedEmailsQuery();
2539 //Perform a count query needed for pagination.
2540 $countQuery = $this->create_list_count_query($fullQuery);
2542 $count_rs = $this->db->query($countQuery, false, 'Error executing count query for imported emails search');
2543 $count_row = $this->db->fetchByAssoc($count_rs);
2544 $total_count = ($count_row != null) ? $count_row['c'] : 0;
2546 $start = ($page - 1) * $pageSize;
2549 $rs = $this->db->limitQuery($fullQuery . $order, $start, $pageSize);
2553 while($a = $this->db->fetchByAssoc($rs)) {
2555 $temp['flagged'] = (is_null($a['flagged']) || $a['flagged'] == '0') ? '' : 1;
2556 $temp['status'] = (is_null($a['reply_to_status']) || $a['reply_to_status'] == '0') ? '' : 1;
2557 $temp['subject'] = $a['name'];
2558 $temp['date'] = $timedate->to_display_date_time($a['date_sent']);
2559 $temp['uid'] = $a['id'];
2560 $temp['ieId'] = $a['mailbox_id'];
2561 $temp['site_url'] = $sugar_config['site_url'];
2562 $temp['seen'] = ($a['status'] == 'unread') ? 0 : 1;
2563 $temp['type'] = $a['type'];
2564 $temp['mbox'] = 'sugar::Emails';
2565 $temp['hasAttach'] = $this->doesImportedEmailHaveAttachment($a['id']);
2566 //To and from addresses may be stored in emails_text, if nothing is found, revert to
2567 //regular email addresses.
2568 $temp['to_addrs'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['to_addrs']);
2569 $temp['from'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['from_addr']);
2570 if( empty($temp['from']) || empty($temp['to_addrs']) )
2572 //Retrieve email addresses seperatly.
2573 $tmpEmail = new Email();
2574 $tmpEmail->id = $a['id'];
2575 $tmpEmail->retrieveEmailAddresses();
2576 $temp['from'] = $tmpEmail->from_addr;
2577 $temp['to_addrs'] = $tmpEmail->to_addrs;
2583 $metadata = array();
2584 $metadata['totalCount'] = $total_count;
2585 $metadata['out'] = $return;
2591 * Determine if an imported email has an attachment by examining the relationship to notes.
2596 function doesImportedEmailHaveAttachment($id)
2598 $hasAttachment = FALSE;
2599 $query = "SELECT id FROM notes where parent_id='$id' AND parent_type='Emails' AND file_mime_type is not null AND deleted=0";
2600 $rs = $this->db->limitQuery($query, 0, 1);
2601 $row = $this->db->fetchByAssoc($rs);
2602 if( !empty($row['id']) )
2603 $hasAttachment = TRUE;
2605 return (int) $hasAttachment;
2609 * Generate the query used for searching imported emails.
2611 * @return String Query to be executed.
2613 function _genereateSearchImportedEmailsQuery()
2617 $additionalWhereClause = $this->_generateSearchImportWhereClause();
2621 $query['select'] = "emails.id , emails.mailbox_id, emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status,
2622 emails_text.from_addr, emails_text.to_addrs FROM emails ";
2624 $query['joins'] = " JOIN emails_text on emails.id = emails_text.email_id ";
2626 //Handle from and to addr joins
2627 if( !empty($_REQUEST['from_addr']) )
2629 $from_addr = $this->db->quote(strtolower($_REQUEST['from_addr']));
2630 $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
2631 AND er_from.address_type='from' AND emails_text.from_addr LIKE '%" . $from_addr . "%'";
2634 if( !empty($_REQUEST['to_addrs']) )
2636 $to_addrs = $this->db->quote(strtolower($_REQUEST['to_addrs']));
2637 $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
2638 AND er_to.address_type='to' AND ea_to.email_address LIKE '%" . $to_addrs . "%'";
2641 $query['where'] = " WHERE (emails.type= 'inbound' OR emails.type='archived' OR emails.type='out') AND emails.deleted = 0 ";
2642 if( !empty($additionalWhereClause) )
2643 $query['where'] .= "AND $additionalWhereClause";
2645 //If we are explicitly looking for attachments. Do not use a distinct query as the to_addr is defined
2646 //as a text which equals clob in oracle and the distinct query can not be executed correctly.
2647 $addDistinctKeyword = "";
2648 if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 1) //1 indicates yes
2649 $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 )";
2650 else if( !empty($_REQUEST['attachmentsSearch']) && $_REQUEST['attachmentsSearch'] == 2 )
2651 $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 )";
2653 $fullQuery = "SELECT " . $query['select'] . " " . $query['joins'] . " " . $query['where'];
2658 * Generate the where clause for searching imported emails.
2661 function _generateSearchImportWhereClause()
2665 //The clear button was removed so if a user removes the asisgned user name, do not process the id.
2666 if( empty($_REQUEST['assigned_user_name']) && !empty($_REQUEST['assigned_user_id']) )
2667 unset($_REQUEST['assigned_user_id']);
2669 $availableSearchParam = array('name' => array('table_name' =>'emails'),
2670 'data_parent_id_search' => array('table_name' =>'emails','db_key' => 'parent_id','opp' => '='),
2671 'assigned_user_id' => array('table_name' => 'emails', 'opp' => '=') );
2673 $additionalWhereClause = array();
2674 foreach ($availableSearchParam as $key => $properties)
2676 if( !empty($_REQUEST[$key]) )
2678 $db_key = isset($properties['db_key']) ? $properties['db_key'] : $key;
2679 $searchValue = $this->db->quote($_REQUEST[$key]);
2681 $opp = isset($properties['opp']) ? $properties['opp'] : 'like';
2683 $searchValue = "%" . $searchValue . "%";
2685 $additionalWhereClause[] = "{$properties['table_name']}.$db_key $opp '$searchValue' ";
2691 $isDateFromSearchSet = !empty($_REQUEST['searchDateFrom']);
2692 $isdateToSearchSet = !empty($_REQUEST['searchDateTo']);
2693 $bothDateRangesSet = $isDateFromSearchSet & $isdateToSearchSet;
2695 //Hanlde date from and to separately
2696 if($bothDateRangesSet)
2698 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2699 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2701 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2702 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2704 $additionalWhereClause[] = "( emails.date_sent >= $dbFormatDateFrom AND
2705 emails.date_sent <= $dbFormatDateTo )";
2707 elseif ($isdateToSearchSet)
2709 $dbFormatDateTo = $timedate->to_db_date($_REQUEST['searchDateTo'], false);
2710 $dbFormatDateTo = db_convert("'" . $dbFormatDateTo . "'",'datetime');
2711 $additionalWhereClause[] = "emails.date_sent <= $dbFormatDateTo ";
2713 elseif ($isDateFromSearchSet)
2715 $dbFormatDateFrom = $timedate->to_db_date($_REQUEST['searchDateFrom'], false);
2716 $dbFormatDateFrom = db_convert("'" . $dbFormatDateFrom . "'",'datetime');
2717 $additionalWhereClause[] = "emails.date_sent >= $dbFormatDateFrom ";
2720 $additionalWhereClause = implode(" AND ", $additionalWhereClause);
2722 return $additionalWhereClause;
2728 * takes a long TO: string of emails and returns the first appended by an
2731 function trimLongTo($str) {
2732 if(strpos($str, ',')) {
2733 $exStr = explode(',', $str);
2734 return $exStr[0].'...';
2735 } elseif(strpos($str, ';')) {
2736 $exStr = explode(';', $str);
2737 return $exStr[0].'...';
2743 function get_summary_text() {
2749 function distributionForm($where) {
2750 global $app_list_strings;
2751 global $app_strings;
2752 global $mod_strings;
2754 global $current_user;
2756 $distribution = get_select_options_with_id($app_list_strings['dom_email_distribution'], '');
2757 $_SESSION['distribute_where'] = $where;
2760 $out = '<form name="Distribute" id="Distribute">';
2761 $out .= get_form_header($mod_strings['LBL_DIST_TITLE'], '', false);
2768 <table cellpadding="0" cellspacing="0" width="100%" border="0">
2771 <script type="text/javascript">
2774 function checkDeps(form) {
2778 function mySubmit() {
2779 var assform = document.getElementById("Distribute");
2780 var select = document.getElementById("userSelect");
2781 var assign1 = assform.r1.checked;
2782 var assign2 = assform.r2.checked;
2783 var dist = assform.dm.value;
2787 var warn1 = "'.$mod_strings['LBL_WARN_NO_USERS'].'";
2790 if(assign1 || assign2) {
2795 for(i=0; i<select.options.length; i++) {
2796 if(select.options[i].selected == true) {
2805 warn2 = "'.$mod_strings['LBL_WARN_NO_DIST'].'";
2808 if(assign && users && rules) {
2810 if(document.getElementById("r1").checked) {
2811 var mu = document.getElementById("MassUpdate");
2814 for(i=0; i<mu.elements.length; i++) {
2815 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name.value != "massall") {
2816 if(grabbed != "") { grabbed += "::"; }
2817 grabbed += mu.elements[i].value;
2820 var formgrab = document.getElementById("grabbed");
2821 formgrab.value = grabbed;
2825 alert("'.$mod_strings['LBL_ASSIGN_WARN'].'" + "\n" + warn1 + "\n" + warn2);
2829 function submitDelete() {
2830 if(document.getElementById("r1").checked) {
2831 var mu = document.getElementById("MassUpdate");
2834 for(i=0; i<mu.elements.length; i++) {
2835 if(mu.elements[i].type == "checkbox" && mu.elements[i].checked && mu.elements[i].name != "massall") {
2836 if(grabbed != "") { grabbed += "::"; }
2837 grabbed += mu.elements[i].value;
2840 var formgrab = document.getElementById("grabbed");
2841 formgrab.value = grabbed;
2844 alert("'.$mod_strings['LBL_MASS_DELETE_ERROR'].'");
2846 document.getElementById("Distribute").submit();
2851 <input type="hidden" name="module" value="Emails">
2852 <input type="hidden" name="action" id="action">
2853 <input type="hidden" name="grabbed" id="grabbed">
2855 <table cellpadding="1" cellspacing="0" width="100%" border="0" class="edit view">
2857 <td scope="col" scope="row" NOWRAP align="center">
2858 '.$mod_strings['LBL_ASSIGN_SELECTED_RESULTS_TO'].' ';
2859 $out .= $this->userSelectTable();
2861 <td scope="col" scope="row" NOWRAP align="left">
2862 '.$mod_strings['LBL_USING_RULES'].'
2863 <select name="distribute_method" id="dm" onChange="checkDeps(this.form);">'.$distribution.'</select>
2872 <td scope="col" width="50%" scope="row" NOWRAP align="right" colspan="2">
2873 <input title="'.$mod_strings['LBL_BUTTON_DISTRIBUTE_TITLE'].'"
2875 class="button" onClick="AjaxObject.detailView.handleAssignmentDialogAssignAction();"
2876 type="button" name="button"
2877 value=" '.$mod_strings['LBL_BUTTON_DISTRIBUTE'].' ">';
2887 function userSelectTable() {
2889 global $mod_strings;
2892 $setTeamUserFunction = '';
2896 $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");
2898 $userTable = '<table cellpadding="0" cellspacing="0" border="0">';
2899 $userTable .= '<tr><td colspan="2"><b>'.$mod_strings['LBL_USER_SELECT'].'</b></td></tr>';
2900 $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>';
2901 $userTable .= '<tr><td colspan="2"><select style="visibility:hidden;" name="users[]" id="userSelect" multiple size="12">';
2903 while($a = $this->db->fetchByAssoc($r)) {
2904 $userTable .= '<option value="'.$a['id'].'" id="'.$a['id'].'">'.$a['first_name'].' '.$a['last_name'].'</option>';
2906 $userTable .= '</select></td></tr>';
2907 $userTable .= '</table>';
2909 $out = '<script type="text/javascript">';
2910 $out .= $setTeamUserFunction;
2912 function setCheckMark() {
2913 var select = document.getElementById("userSelect");
2915 for(i=0 ; i<select.options.length; i++) {
2916 if(select.options[i].selected == true) {
2917 document.getElementById("checkMark").style.display="";
2922 document.getElementById("checkMark").style.display="none";
2926 function showUserSelect() {
2927 var targetTable = document.getElementById("user_select");
2928 targetTable.style.visibility="visible";
2929 var userSelectTable = document.getElementById("userSelect");
2930 userSelectTable.style.visibility="visible";
2933 function hideUserSelect() {
2934 var targetTable = document.getElementById("user_select");
2935 targetTable.style.visibility="hidden";
2936 var userSelectTable = document.getElementById("userSelect");
2937 userSelectTable.style.visibility="hidden";
2940 function toggleAll(toggle) {
2941 if(toggle.checked) {
2946 var form = document.getElementById("userSelect");
2947 for(i=0; i<form.options.length; i++) {
2948 form.options[i].selected = stat;
2954 <span id="showUsersDiv" style="position:relative;">
2955 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
2956 '.SugarThemeRegistry::current()->getImage('Users', '', null, null, ".gif", $mod_strings['LBL_USERS']).'</a>
2957 <a href="#" id="showUsers" onClick="javascript:showUserSelect();">
2958 <span style="display:none;" id="checkMark">'.SugarThemeRegistry::current()->getImage('check_inline', 'border="0"', null, null, ".gif", $mod_strings['LBL_CHECK_INLINE']).'</span>
2962 <div id="user_select" style="width:200px;position:absolute;left:2;top:2;visibility:hidden;z-index:1000;">
2963 <table cellpadding="0" cellspacing="0" border="0" class="list view">
2965 <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\';">
2966 <a href="#" onClick="javascript:hideUserSelect();">'.SugarThemeRegistry::current()->getImage('close', 'border="0"', null, null, ".gif", $mod_strings['LBL_CLOSE']).'</a>
2967 '.$mod_strings['LBL_USER_SELECT'].'
2971 //<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\';">
2972 $out .= ' <td style="padding:5px" class="oddListRowS1" bgcolor="#fdfdfd" valign="top" align="left" style="left:0;top:0;">
2981 function checkInbox($type) {
2983 global $mod_strings;
2984 $out = '<div><input title="'.$mod_strings['LBL_BUTTON_CHECK_TITLE'].'"
2986 type="button" name="button"
2987 onClick="window.location=\'index.php?module=Emails&action=Check&type='.$type.'\';"
2988 style="margin-bottom:2px"
2989 value=" '.$mod_strings['LBL_BUTTON_CHECK'].' "></div>';
2994 * Guesses Primary Parent id from From: email address. Cascades guesses from Accounts to Contacts to Leads to
2995 * Users. This will not affect the many-to-many relationships already constructed as this is, at best,
2996 * informational linking.
2998 function fillPrimaryParentFields() {
2999 if(empty($this->from_addr))
3002 $GLOBALS['log']->debug("*** Email trying to guess Primary Parent from address [ {$this->from_addr} ]");
3004 $tables = array('accounts');
3006 // loop through types to get hits
3007 foreach($tables as $table) {
3008 $q = "SELECT name, id FROM {$table} WHERE email1 = '{$this->from_addr}' OR email2 = '{$this->from_addr}' AND deleted = 0";
3009 $r = $this->db->query($q);
3010 while($a = $this->db->fetchByAssoc($r)) {
3011 if(!empty($a['name']) && !empty($a['id'])) {
3012 $this->parent_type = ucwords($table);
3013 $this->parent_id = $a['id'];
3014 $this->parent_name = $a['name'];
3022 * Convert reference to inline image (stored as Note) to URL link
3023 * Enter description here ...
3024 * @param string $note ID of the note
3025 * @param string $ext type of the note
3027 public function cid2Link($noteId, $noteType)
3029 if(empty($this->description_html)) return;
3030 list($type, $subtype) = explode('/', $noteType);
3031 if(strtolower($type) != 'image') {
3034 $upload = new UploadFile();
3035 $this->description_html = preg_replace("#class=\"image\" src=\"cid:$noteId\.(.+?)\"#", "class=\"image\" src=\"{$this->imagePrefix}{$noteId}.\\1\"", $this->description_html);
3036 // ensure the image is in the cache
3037 $imgfilename = sugar_cached("images/")."$noteId.".strtolower($subtype);
3038 $src = "upload://$noteId";
3039 if(!file_exists($imgfilename) && file_exists($src)) {
3040 copy($src, $imgfilename);
3045 * Convert all cid: links in this email into URLs
3047 function cids2Links()
3049 if(empty($this->description_html)) return;
3050 $q = "SELECT id, file_mime_type FROM notes WHERE parent_id = '{$this->id}' AND deleted = 0";
3051 $r = $this->db->query($q);
3052 while($a = $this->db->fetchByAssoc($r)) {
3053 $this->cid2Link($a['id'], $a['file_mime_type']);
3059 * Sets the field def for a field to allow null values
3061 * @todo Consider moving to SugarBean to allow other models to set fields to NULL
3062 * @param string $field The field name to modify
3065 public function setFieldNullable($field)
3067 if (isset($this->field_defs[$field]) && is_array($this->field_defs[$field]))
3069 if (empty($this->modifiedFieldDefs[$field]))
3072 isset($this->field_defs[$field]['isnull']) &&
3073 (strtolower($this->field_defs[$field]['isnull']) == 'false' || $this->field_defs[$field]['isnull'] === false)
3076 $this->modifiedFieldDefs[$field]['isnull'] = $this->field_defs[$field]['isnull'];
3077 unset($this->field_defs[$field]['isnull']);
3080 if (isset($this->field_defs[$field]['dbType']) && $this->field_defs[$field]['dbType'] == 'id')
3082 $this->modifiedFieldDefs[$field]['dbType'] = $this->field_defs[$field]['dbType'];
3083 unset($this->field_defs[$field]['dbType']);
3091 * Set the field def back to the way it was prior to modification
3096 public function revertFieldNullable($field)
3098 if (!empty($this->modifiedFieldDefs[$field]) && is_array($this->modifiedFieldDefs[$field]))
3100 foreach ($this->modifiedFieldDefs[$field] as $k => $v)
3102 $this->field_defs[$field][$k] = $v;
3105 unset($this->modifiedFieldDefs[$field]);