/modules/Emails/Email.php
PHP | 3135 lines | 2274 code | 430 blank | 431 comment | 498 complexity | 41d07af157ef12df023cee3d06209145 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1, BSD-3-Clause, AGPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
- /*********************************************************************************
- * SugarCRM Community Edition is a customer relationship management program developed by
- * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
- *
- * This program is free software; you can redistribute it and/or modify it under
- * the terms of the GNU Affero General Public License version 3 as published by the
- * Free Software Foundation with the addition of the following permission added
- * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
- * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
- * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
- *
- * This program is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
- * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
- * details.
- *
- * You should have received a copy of the GNU Affero General Public License along with
- * this program; if not, see http://www.gnu.org/licenses or write to the Free
- * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- *
- * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
- * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
- *
- * The interactive user interfaces in modified source and object code versions
- * of this program must display Appropriate Legal Notices, as required under
- * Section 5 of the GNU Affero General Public License version 3.
- *
- * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
- * these Appropriate Legal Notices must retain the display of the "Powered by
- * SugarCRM" logo. If the display of the logo is not reasonably feasible for
- * technical reasons, the Appropriate Legal Notices must display the words
- * "Powered by SugarCRM".
- ********************************************************************************/
- /*********************************************************************************
- * Description:
- * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
- * Reserved. Contributor(s): ______________________________________..
- *********************************************************************************/
- require_once('include/SugarPHPMailer.php');
- require_once('include/Pear/HTML_Safe/Safe.php');
- class Email extends SugarBean {
- /* SugarBean schema */
- var $id;
- var $date_entered;
- var $date_modified;
- var $assigned_user_id;
- var $assigned_user_name;
- var $modified_user_id;
- var $created_by;
- var $deleted;
- var $from_addr;
- var $reply_to_addr;
- var $to_addrs;
- var $cc_addrs;
- var $bcc_addrs;
- var $message_id;
- /* Bean Attributes */
- var $name;
- var $type = 'archived';
- var $date_sent;
- var $status;
- var $intent;
- var $mailbox_id;
- var $from_name;
- var $reply_to_status;
- var $reply_to_name;
- var $reply_to_email;
- var $description;
- var $description_html;
- var $raw_source;
- var $parent_id;
- var $parent_type;
- /* link attributes */
- var $parent_name;
- /* legacy */
- var $date_start; // legacy
- var $time_start; // legacy
- var $from_addr_name;
- var $to_addrs_arr;
- var $cc_addrs_arr;
- var $bcc_addrs_arr;
- var $to_addrs_ids;
- var $to_addrs_names;
- var $to_addrs_emails;
- var $cc_addrs_ids;
- var $cc_addrs_names;
- var $cc_addrs_emails;
- var $bcc_addrs_ids;
- var $bcc_addrs_names;
- var $bcc_addrs_emails;
- var $contact_id;
- var $contact_name;
- /* Archive Email attrs */
- var $duration_hours;
- var $new_schema = true;
- var $table_name = 'emails';
- var $module_dir = 'Emails';
- var $object_name = 'Email';
- var $db;
- /* private attributes */
- 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";
- var $cachePath;
- var $cacheFile = 'robin.cache.php';
- var $replyDelimiter = "> ";
- var $emailDescription;
- var $emailDescriptionHTML;
- var $emailRawSource;
- var $link_action;
- var $emailAddress;
- var $attachments = array();
- /* to support Email 2.0 */
- var $isDuplicate;
- var $uid;
- var $to;
- var $flagged;
- var $answered;
- var $seen;
- var $draft;
- var $relationshipMap = array(
- 'Contacts' => 'emails_contacts_rel',
- 'Accounts' => 'emails_accounts_rel',
- 'Leads' => 'emails_leads_rel',
- 'Users' => 'emails_users_rel',
- 'Prospects' => 'emails_prospects_rel',
- );
- /* public */
- var $et; // EmailUI object
- /**
- * sole constructor
- */
- function Email() {
- $this->cachePath = $GLOBALS['sugar_config']['cache_dir'].'modules/Emails';
- parent::SugarBean();
- $this->safe = new HTML_Safe();
- $this->safe->clear();
- $this->emailAddress = new SugarEmailAddress();
- }
- function email2init() {
- require_once('modules/Emails/EmailUI.php');
- $this->et = new EmailUI();
- }
- function bean_implements($interface){
- switch($interface){
- case 'ACL': return true;
- default: return false;
- }
- }
- /**
- * Presaves one attachment for new email 2.0 spec
- * DOES NOT CREATE A NOTE
- * @return string ID of note associated with the attachment
- */
- function email2saveAttachment() {
- global $sugar_config;
- $filesError = array(
- 0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
- 1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
- 2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
- 3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
- 4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
- 5 => 'UNKNOWN ERROR',
- 6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
- 7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.',
- );
- // cn: Bug 5995 - rudimentary error checking
- if($_FILES['email_attachment']['error'] != 0 && $_FILES['email_attachment']['error'] != 4) {
- $GLOBALS['log']->debug('Email Attachment could not be attach due to error: '.$filesError[$_FILES['email_attachment']['error']]);
- return array();
- }
- if(isset($_FILES['email_attachment']) && is_uploaded_file($_FILES['email_attachment']['tmp_name'])) {
- $guid = create_guid();
- $cleanAttachmentFileName = from_html($_FILES['email_attachment']['name']);
- $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] ");
- $cleanAttachmentFileName = str_replace("\\", "", $cleanAttachmentFileName);
- $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] ");
- //$destination = clean_path("{$this->et->userCacheDir}/{$guid}{$cleanAttachmentFileName}");
- $destination = clean_path("{$this->et->userCacheDir}/{$guid}");
- $badExt = $this->safeAttachmentName($cleanAttachmentFileName);
- if ($badExt) {
- //$destination = $destination . ".txt";
- } // if
- $fileName = $badExt ? $cleanAttachmentFileName . ".txt" : $cleanAttachmentFileName;
- if(move_uploaded_file($_FILES['email_attachment']['tmp_name'], $destination)) {
- return array(
- 'guid' => $guid,
- 'name' => $GLOBALS['db']->helper->escape_quote($fileName),
- 'nameForDisplay' => $fileName
- );
- } else {
- $GLOBALS['log']->debug("Email Attachment [ {$cleanAttachmentFileName} ] could not be moved to cache dir");
- return array();
- }
- }
- }
- function safeAttachmentName($filename) {
- global $sugar_config;
- $badExtension = false;
- //get position of last "." in file name
- $file_ext_beg = strrpos($filename, ".");
- $file_ext = "";
- //get file extension
- if($file_ext_beg !== false) {
- $file_ext = substr($filename, $file_ext_beg + 1);
- }
- //check to see if this is a file with extension located in "badext"
- foreach($sugar_config['upload_badext'] as $badExt) {
- if(strtolower($file_ext) == strtolower($badExt)) {
- //if found, then append with .txt and break out of lookup
- $filename = $filename . ".txt";
- $badExtension = true;
- break; // no need to look for more
- } // if
- } // foreach
- return $badExtension;
- } // fn
- /**
- * takes output from email 2.0 to/cc/bcc fields and returns appropriate arrays for usage by PHPMailer
- * @param string addresses
- * @return array
- */
- function email2ParseAddresses($addresses) {
- $addresses = from_html($addresses);
- $addresses = $this->et->unifyEmailString($addresses);
- $pattern = '/@.*,/U';
- preg_match_all($pattern, $addresses, $matchs);
- if (!empty($matchs[0])){
- $total = $matchs[0];
- foreach ($total as $match) {
- $convertedPattern = str_replace(',', '::;::', $match);
- $addresses = str_replace($match, $convertedPattern, $addresses);
- } //foreach
- }
- $exAddr = explode("::;::", $addresses);
- $ret = array();
- $clean = array("<", ">");
- $dirty = array("<", ">");
- foreach($exAddr as $addr) {
- $name = '';
- $addr = str_replace($dirty, $clean, $addr);
- if((strpos($addr, "<") === false) && (strpos($addr, ">") === false)) {
- $address = $addr;
- } else {
- $address = substr($addr, strpos($addr, "<") + 1, strpos($addr, ">") - 1 - strpos($addr, "<"));
- $name = substr($addr, 0, strpos($addr, "<"));
- }
- $addrTemp = array();
- $addrTemp['email'] = trim($address);
- $addrTemp['display'] = trim($name);
- $ret[] = $addrTemp;
- }
- return $ret;
- }
- /**
- * takes output from email 2.0 to/cc/bcc fields and returns appropriate arrays for usage by PHPMailer
- * @param string addresses
- * @return array
- */
- function email2ParseAddressesForAddressesOnly($addresses) {
- $addresses = from_html($addresses);
- $pattern = '/@.*,/U';
- preg_match_all($pattern, $addresses, $matchs);
- if (!empty($matchs[0])){
- $total = $matchs[0];
- foreach ($total as $match) {
- $convertedPattern = str_replace(',', '::;::', $match);
- $addresses = str_replace($match, $convertedPattern, $addresses);
- } //foreach
- }
- $exAddr = explode("::;::", $addresses);
- $ret = array();
- $clean = array("<", ">");
- $dirty = array("<", ">");
- foreach($exAddr as $addr) {
- $name = '';
- $addr = str_replace($dirty, $clean, $addr);
- if(strpos($addr, "<") && strpos($addr, ">")) {
- $address = substr($addr, strpos($addr, "<") + 1, strpos($addr, ">") - 1 - strpos($addr, "<"));
- } else {
- $address = $addr;
- }
- $ret[] = trim($address);
- }
- return $ret;
- }
- /**
- * Determines MIME-type encoding as possible.
- * @param string $fileLocation relative path to file
- * @return string MIME-type
- */
- function email2GetMime($fileLocation) {
- if(!is_readable($fileLocation)) {
- return 'application/octet-stream';
- }
- if(function_exists('mime_content_type')) {
- $mime = mime_content_type($fileLocation);
- } elseif(function_exists('ext2mime')) {
- $mime = ext2mime($fileLocation);
- } else {
- $mime = 'application/octet-stream';
- }
- return $mime;
- }
- function sendEmailTest($mailserver_url, $port, $ssltls, $smtp_auth_req, $smtp_username, $smtppassword, $fromaddress, $toaddress, $mail_sendtype = 'smtp', $fromname = '') {
- global $current_user,$app_strings;
- $mod_strings = return_module_language($GLOBALS['current_language'], 'Emails'); //Called from EmailMan as well.
- $mail = new SugarPHPMailer();
- $mail->Mailer = strtolower($mail_sendtype);
- if($mail->Mailer == 'smtp')
- {
- $mail->Host = $mailserver_url;
- $mail->Port = $port;
- if (isset($ssltls) && !empty($ssltls)) {
- $mail->protocol = "ssl://";
- if ($ssltls == 1) {
- $mail->SMTPSecure = 'ssl';
- } // if
- if ($ssltls == 2) {
- $mail->SMTPSecure = 'tls';
- } // if
- } else {
- $mail->protocol = "tcp://";
- }
- if ($smtp_auth_req) {
- $mail->SMTPAuth = TRUE;
- $mail->Username = $smtp_username;
- $mail->Password = $smtppassword;
- }
- }
- else
- $mail->Mailer = 'sendmail';
- $mail->Subject = from_html($mod_strings['LBL_TEST_EMAIL_SUBJECT']);
- $mail->From = $fromaddress;
- if ($fromname != '') {
- $mail->FromName = html_entity_decode($fromname,ENT_QUOTES);
- } else {
- $mail->FromName = $current_user->name;
- }
- $mail->Sender = $mail->From;
- $mail->AddAddress($toaddress);
- $mail->Body = $mod_strings['LBL_TEST_EMAIL_BODY'];
- $return = array();
- if(!$mail->Send()) {
- ob_clean();
- $return['status'] = false;
- $return['errorMessage'] = $app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo;
- return $return;
- } // if
- $return['status'] = true;
- return $return;
- } // fn
- function decodeDuringSend($htmlData) {
- $htmlData = str_replace("sugarLessThan", "<", $htmlData);
- $htmlData = str_replace("sugarGreaterThan", ">", $htmlData);
- return $htmlData;
- }
- /**
- * Returns true or false if this email is a draft.
- *
- * @param array $request
- * @return bool True indicates this email is a draft.
- */
- function isDraftEmail($request)
- {
- return ( isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft') );
- }
- /**
- * Sends Email for Email 2.0
- */
- function email2Send($request) {
- global $mod_strings;
- global $app_strings;
- global $current_user;
- global $sugar_config;
- global $locale;
- global $timedate;
- global $beanList;
- global $beanFiles;
- $OBCharset = $locale->getPrecedentPreference('default_email_charset');
- /**********************************************************************
- * Sugar Email PREP
- */
- /* preset GUID */
- $orignialId = "";
- if(!empty($this->id)) {
- $orignialId = $this->id;
- } // if
- if(empty($this->id)) {
- $this->id = create_guid();
- $this->new_with_id = true;
- }
- /* satisfy basic HTML email requirements */
- $this->name = $request['sendSubject'];
- $this->description_html = '<html><body>'.$request['sendDescription'].'</body></html>';
- /**********************************************************************
- * PHPMAILER PREP
- */
- $mail = new SugarPHPMailer();
- $mail = $this->setMailer($mail, '', $_REQUEST['fromAccount']);
- if (empty($mail->Host) && !$this->isDraftEmail($request))
- {
- $this->status = 'send_error';
- if ($mail->oe->type == 'system')
- echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_SYSTEM_OUTBOUND']);
- else
- echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $app_strings['LBL_EMAIL_INVALID_PERSONAL_OUTBOUND']);
- return false;
- }
- $subject = $this->name;
- $mail->Subject = from_html($this->name);
- // work-around legacy code in SugarPHPMailer
- if($_REQUEST['setEditor'] == 1) {
- $_REQUEST['description_html'] = $_REQUEST['sendDescription'];
- $this->description_html = $_REQUEST['description_html'];
- } else {
- $this->description_html = '';
- $this->description = $_REQUEST['sendDescription'];
- }
- // end work-around
- if ( $this->isDraftEmail($request) )
- {
- if($this->type != 'draft' && $this->status != 'draft') {
- $this->id = create_guid();
- $this->new_with_id = true;
- $this->date_entered = "";
- } // if
- $q1 = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$this->id}'";
- $r1 = $this->db->query($q1);
- } // if
- if (isset($request['saveDraft'])) {
- $this->type = 'draft';
- $this->status = 'draft';
- $forceSave = true;
- } else {
- /* Apply Email Templates */
- // do not parse email templates if the email is being saved as draft....
- $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']);
- $sea = new SugarEmailAddress();
- $object_arr = array();
- if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
- isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) &&
- ($_REQUEST['parent_type'] == 'Accounts' ||
- $_REQUEST['parent_type'] == 'Contacts' ||
- $_REQUEST['parent_type'] == 'Leads' ||
- $_REQUEST['parent_type'] == 'Users' ||
- $_REQUEST['parent_type'] == 'Prospects')) {
- if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
- $className = $beanList[$_REQUEST['parent_type']];
- if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
- if(!class_exists($className)) {
- require_once($beanFiles[$className]);
- }
- $bean = new $className();
- $bean->retrieve($_REQUEST['parent_id']);
- $object_arr[$bean->module_dir] = $bean->id;
- } // if
- } // if
- }
- foreach($toAddresses as $addrMeta) {
- $addr = $addrMeta['email'];
- $beans = $sea->getBeansByEmailAddress($addr);
- foreach($beans as $bean) {
- if (!isset($object_arr[$bean->module_dir])) {
- $object_arr[$bean->module_dir] = $bean->id;
- }
- }
- }
- /* template parsing */
- if (empty($object_arr)) {
- $object_arr= array('Contacts' => '123');
- }
- $object_arr['Users'] = $current_user->id;
- $this->description_html = EmailTemplate::parse_template($this->description_html, $object_arr);
- $this->name = EmailTemplate::parse_template($this->name, $object_arr);
- $this->description = EmailTemplate::parse_template($this->description, $object_arr);
- $this->description = html_entity_decode($this->description,ENT_COMPAT,'UTF-8');
- if($this->type != 'draft' && $this->status != 'draft') {
- $this->id = create_guid();
- $this->date_entered = "";
- $this->new_with_id = true;
- $this->type = 'out';
- $this->status = 'sent';
- }
- }
- if(isset($_REQUEST['parent_type']) && empty($_REQUEST['parent_type']) &&
- isset($_REQUEST['parent_id']) && empty($_REQUEST['parent_id']) ) {
- $this->parent_id = "";
- $this->parent_type = "";
- } // if
- $mail->Subject = $this->name;
- $mail = $this->handleBody($mail);
- $mail->Subject = $this->name;
- $this->description_html = from_html($this->description_html);
- $this->description_html = $this->decodeDuringSend($this->description_html);
- $this->description = $this->decodeDuringSend($this->description);
- /* from account */
- $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
- $replyToName = "";
- if(empty($request['fromAccount'])) {
- $defaults = $current_user->getPreferredEmail();
- $mail->From = $defaults['email'];
- $mail->FromName = $defaults['name'];
- $replyToName = $mail->FromName;
- //$replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
- } else {
- // passed -> user -> system default
- $ie = new InboundEmail();
- $ie->retrieve($request['fromAccount']);
- $storedOptions = unserialize(base64_decode($ie->stored_options));
- $fromName = "";
- $fromAddress = "";
- $replyToName = "";
- //$replyToAddress = "";
- if (!empty($storedOptions)) {
- $fromAddress = $storedOptions['from_addr'];
- $fromName = from_html($storedOptions['from_name']);
- $replyToAddress = (isset($storedOptions['reply_to_addr']) ? $storedOptions['reply_to_addr'] : "");
- $replyToName = (isset($storedOptions['reply_to_name']) ? from_html($storedOptions['reply_to_name']) : "");
- } // if
- $defaults = $current_user->getPreferredEmail();
- // Personal Account doesn't have reply To Name and Reply To Address. So add those columns on UI
- // After adding remove below code
- // code to remove
- if ($ie->is_personal)
- {
- if (empty($replyToAddress))
- {
- $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user);
- } // if
- if (empty($replyToName))
- {
- $replyToName = $defaults['name'];
- } // if
- //Personal accounts can have a reply_address, which should
- //overwrite the users set default.
- if( !empty($storedOptions['reply_to_addr']) )
- $replyToAddress = $storedOptions['reply_to_addr'];
- }
- // end of code to remove
- $mail->From = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
- $mail->FromName = (!empty($fromName)) ? $fromName : $defaults['name'];
- $replyToName = (!empty($replyToName)) ? $replyToName : $mail->FromName;
- }
- $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
- if (!empty($replyToAddress)) {
- $mail->AddReplyTo($replyToAddress,$locale->translateCharsetMIME(trim( $replyToName), 'UTF-8', $OBCharset));
- } else {
- $mail->AddReplyTo($mail->From,$locale->translateCharsetMIME(trim( $mail->FromName), 'UTF-8', $OBCharset));
- } // else
- $emailAddressCollection = array(); // used in linking to beans below
- // handle to/cc/bcc
- foreach($this->email2ParseAddresses($request['sendTo']) as $addr_arr) {
- if(empty($addr_arr['email'])) continue;
- if(empty($addr_arr['display'])) {
- $mail->AddAddress($addr_arr['email'], "");
- } else {
- $mail->AddAddress($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
- }
- $emailAddressCollection[] = $addr_arr['email'];
- }
- foreach($this->email2ParseAddresses($request['sendCc']) as $addr_arr) {
- if(empty($addr_arr['email'])) continue;
- if(empty($addr_arr['display'])) {
- $mail->AddCC($addr_arr['email'], "");
- } else {
- $mail->AddCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
- }
- $emailAddressCollection[] = $addr_arr['email'];
- }
- foreach($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) {
- if(empty($addr_arr['email'])) continue;
- if(empty($addr_arr['display'])) {
- $mail->AddBCC($addr_arr['email'], "");
- } else {
- $mail->AddBCC($addr_arr['email'],$locale->translateCharsetMIME(trim( $addr_arr['display']), 'UTF-8', $OBCharset));
- }
- $emailAddressCollection[] = $addr_arr['email'];
- }
- /* parse remove attachments array */
- $removeAttachments = array();
- if(!empty($request['templateAttachmentsRemove'])) {
- $exRemove = explode("::", $request['templateAttachmentsRemove']);
- foreach($exRemove as $file) {
- $removeAttachments = substr($file, 0, 36);
- }
- }
- /* handle attachments */
- if(!empty($request['attachments'])) {
- $exAttachments = explode("::", $request['attachments']);
- foreach($exAttachments as $file) {
- $file = trim(from_html($file));
- $file = str_replace("\\", "", $file);
- if(!empty($file)) {
- //$fileLocation = $this->et->userCacheDir."/{$file}";
- $fileGUID = substr($file, 0, 36);
- $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
- $filename = substr($file, 36, strlen($file)); // strip GUID for PHPMailer class to name outbound file
- $mail->AddAttachment($fileLocation,$filename, 'base64', $this->email2GetMime($fileLocation));
- //$mail->AddAttachment($fileLocation, $filename, 'base64');
- // only save attachments if we're archiving or drafting
- if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
- $note = new Note();
- $note->id = create_guid();
- $note->new_with_id = true; // duplicating the note with files
- $note->parent_id = $this->id;
- $note->parent_type = $this->module_dir;
- $note->name = $filename;
- $note->filename = $filename;
- $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
- $note->file_mime_type = $this->email2GetMime($fileLocation);
- if(!copy($fileLocation, $noteFile)) {
- $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to cache/upload [ {$fileLocation} ]");
- }
- $note->save();
- }
- }
- }
- }
- /* handle sugar documents */
- if(!empty($request['documents'])) {
- $exDocs = explode("::", $request['documents']);
- foreach($exDocs as $docId) {
- $docId = trim($docId);
- if(!empty($docId)) {
- $doc = new Document();
- $docRev = new DocumentRevision();
- $doc->retrieve($docId);
- $docRev->retrieve($doc->document_revision_id);
- $filename = $docRev->filename;
- $fileLocation = "{$sugar_config['upload_dir']}{$docRev->id}";
- $mime_type = $docRev->file_mime_type;
- $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
- // only save attachments if we're archiving or drafting
- if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
- $note = new Note();
- $note->id = create_guid();
- $note->new_with_id = true; // duplicating the note with files
- $note->parent_id = $this->id;
- $note->parent_type = $this->module_dir;
- $note->name = $filename;
- $note->filename = $filename;
- $note->file_mime_type = $mime_type;
- $noteFile = "{$sugar_config['upload_dir']}{$note->id}";
- if(!copy($fileLocation, $noteFile)) {
- $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
- }
- $note->save();
- }
- }
- }
- }
- /* handle template attachments */
- if(!empty($request['templateAttachments'])) {
- $exNotes = explode("::", $request['templateAttachments']);
- foreach($exNotes as $noteId) {
- $noteId = trim($noteId);
- if(!empty($noteId)) {
- $note = new Note();
- $note->retrieve($noteId);
- if (!empty($note->id)) {
- $filename = $note->filename;
- $fileLocation = "{$sugar_config['upload_dir']}{$note->id}";
- $mime_type = $note->file_mime_type;
- if (!$note->embed_flag) {
- $mail->AddAttachment($fileLocation,$filename, 'base64', $mime_type);
- // only save attachments if we're archiving or drafting
- if((($this->type == 'draft') && !empty($this->id)) || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
- if ($note->parent_id != $this->id)
- $this->saveTempNoteAttachments($filename,$fileLocation, $mime_type);
- } // if
- } // if
- } else {
- //$fileLocation = $this->et->userCacheDir."/{$file}";
- $fileGUID = substr($noteId, 0, 36);
- $fileLocation = $this->et->userCacheDir."/{$fileGUID}";
- //$fileLocation = $this->et->userCacheDir."/{$noteId}";
- $filename = substr($noteId, 36, strlen($noteId)); // strip GUID for PHPMailer class to name outbound file
- $mail->AddAttachment($fileLocation,$locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $this->email2GetMime($fileLocation));
- //If we are saving an email we were going to forward we need to save the attachments as well.
- if( (($this->type == 'draft') && !empty($this->id))
- || (isset($request['saveToSugar']) && $request['saveToSugar'] == 1))
- {
- $mimeType = $this->email2GetMime($fileLocation);
- $this->saveTempNoteAttachments($filename,$fileLocation, $mimeType);
- } // if
- }
- }
- }
- }
- /**********************************************************************
- * Final Touches
- */
- /* save email to sugar? */
- $forceSave = false;
- if($this->type == 'draft' && !isset($request['saveDraft'])) {
- // sending a draft email
- $this->type = 'out';
- $this->status = 'sent';
- $forceSave = true;
- } elseif(isset($request['saveDraft'])) {
- $this->type = 'draft';
- $this->status = 'draft';
- $forceSave = true;
- }
- /**********************************************************************
- * SEND EMAIL (finally!)
- */
- $mailSent = false;
- if ($this->type != 'draft') {
- $mail->prepForOutbound();
- $mail->Body = $this->decodeDuringSend($mail->Body);
- $mail->AltBody = $this->decodeDuringSend($mail->AltBody);
- if (!$mail->Send()) {
- $this->status = 'send_error';
- ob_clean();
- echo($app_strings['LBL_EMAIL_ERROR_PREPEND']. $mail->ErrorInfo);
- return false;
- }
- }
- if ((!(empty($orignialId) || isset($request['saveDraft']) || ($this->type == 'draft' && $this->status == 'draft'))) &&
- (($_REQUEST['composeType'] == 'reply') || ($_REQUEST['composeType'] == 'replyAll') || ($_REQUEST['composeType'] == 'replyCase')) && ($orignialId != $this->id)) {
- $originalEmail = new Email();
- $originalEmail->retrieve($orignialId);
- $originalEmail->reply_to_status = 1;
- $originalEmail->save();
- $this->reply_to_status = 0;
- } // if
- if ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase') {
- if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) {
- $emailFromIe = new InboundEmail();
- $emailFromIe->retrieve($_REQUEST['ieId']);
- $emailFromIe->mailbox = $_REQUEST['mbox'];
- if (isset($emailFromIe->id) && $emailFromIe->is_personal) {
- if ($emailFromIe->isPop3Protocol()) {
- $emailFromIe->mark_answered($this->uid, 'pop3');
- }
- elseif ($emailFromIe->connectMailserver() == 'true') {
- $emailFromIe->markEmails($this->uid, 'answered');
- $emailFromIe->mark_answered($this->uid);
- }
- }
- }
- }
- if( $forceSave ||
- $this->type == 'draft' ||
- (isset($request['saveToSugar']) && $request['saveToSugar'] == 1)) {
- // saving a draft OR saving a sent email
- $decodedFromName = mb_decode_mimeheader($mail->FromName);
- $this->from_addr = "{$decodedFromName} <{$mail->From}>";
- $this->from_addr_name = $this->from_addr;
- $this->to_addrs = $_REQUEST['sendTo'];
- $this->to_addrs_names = $_REQUEST['sendTo'];
- $this->cc_addrs = $_REQUEST['sendCc'];
- $this->cc_addrs_names = $_REQUEST['sendCc'];
- $this->bcc_addrs = $_REQUEST['sendBcc'];
- $this->bcc_addrs_names = $_REQUEST['sendBcc'];
- $this->assigned_user_id = $current_user->id;
- $this->date_sent = $timedate->now();
- ///////////////////////////////////////////////////////////////////
- //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
- if( isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) &&
- isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) ) {
- $this->parent_id = $_REQUEST['parent_id'];
- $this->parent_type = $_REQUEST['parent_type'];
- $q = "SELECT count(*) c FROM emails_beans WHERE email_id = '{$this->id}' AND bean_id = '{$_REQUEST['parent_id']}' AND bean_module = '{$_REQUEST['parent_type']}'";
- $r = $this->db->query($q);
- $a = $this->db->fetchByAssoc($r);
- if($a['c'] <= 0) {
- if(isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) {
- $className = $beanList[$_REQUEST['parent_type']];
- if(isset($beanFiles[$className]) && !empty($beanFiles[$className])) {
- if(!class_exists($className)) {
- require_once($beanFiles[$className]);
- }
- $bean = new $className();
- $bean->retrieve($_REQUEST['parent_id']);
- if($bean->load_relationship('emails')) {
- $bean->emails->add($this->id);
- } // if
- } // if
- } // if
- } // if
- } else {
- if(!class_exists('aCase')) {
- }
- else{
- $c = new aCase();
- if($caseId = InboundEmail::getCaseIdFromCaseNumber($mail->Subject, $c)) {
- $c->retrieve($caseId);
- $c->load_relationship('emails');
- $c->emails->add($this->id);
- $this->parent_type = "Cases";
- $this->parent_id = $caseId;
- } // if
- }
- } // else
- //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
- ///////////////////////////////////////////////////////////////////
- $this->save();
- }
- if(!empty($request['fromAccount'])) {
- if (isset($ie->id) && !$ie->isPop3Protocol()) {
- $sentFolder = $ie->get_stored_options("sentFolder");
- if (!empty($sentFolder)) {
- $data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n";
- $ie->mailbox = $sentFolder;
- if ($ie->connectMailserver() == 'true') {
- $connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox);
- $returnData = imap_append($ie->conn,$connectString, $data, "\\Seen");
- if (!$returnData) {
- $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}");
- } // if
- } else {
- $GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}");
- } // else
- } else {
- $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty");
- } // else
- } // if
- } // if
- return true;
- } // end email2send
- /**
- * Generates a comma sperated name and addresses to be used in compose email screen for contacts or leads
- * from listview
- *
- * @param $module string module name
- * @param $idsArray array of record ids to get the email address for
- * @return string comma delimited list of email addresses
- */
- public function getNamePlusEmailAddressesForCompose($module, $idsArray)
- {
- global $locale;
- global $db;
- $table = SugarModule::get($module)->loadBean()->table_name;
- $returndata = array();
- $idsString = "";
- foreach($idsArray as $id) {
- if ($idsString != "") {
- $idsString = $idsString . ",";
- } // if
- $idsString = $idsString . "'" . $id . "'";
- } // foreach
- $where = "({$table}.deleted = 0 AND {$table}.id in ({$idsString}))";
- if ($module == 'Users' || $module == 'Employees') {
- $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.title";
- }
- elseif (SugarModule::get($module)->moduleImplements('Person')) {
- $selectColumn = "{$table}.first_name, {$table}.last_name, {$table}.salutation, {$table}.title";
- }
- else {
- $selectColumn = "{$table}.name";
- }
- $query = "SELECT {$table}.id, {$selectColumn}, eabr.primary_address, ea.email_address";
- $query .= " FROM {$table} ";
- $query .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
- $query .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
- $query .= " WHERE ({$where}) ORDER BY eabr.primary_address DESC";
- $r = $this->db->query($query);
- while($a = $this->db->fetchByAssoc($r)) {
- if (!isset($returndata[$a['id']])) {
- if ($module == 'Users' || $module == 'Employees') {
- $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], '', $a['title']));
- $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
- }
- elseif (SugarModule::get($module)->moduleImplements('Person')) {
- $full_name = from_html($locale->getLocaleFormattedName($a['first_name'], $a['last_name'], $a['salutation'], $a['title']));
- $returndata[$a['id']] = "{$full_name} <".from_html($a['email_address']).">";
- }
- else {
- $returndata[$a['id']] = from_html($a['name']) . " <".from_html($a['email_address']).">";
- } // else
- }
- }
- return join(",", array_values($returndata));
- }
- /**
- * Overrides
- */
- ///////////////////////////////////////////////////////////////////////////
- //// SAVERS
- function save($check_notify = false) {
- if($this->isDuplicate) {
- $GLOBALS['log']->debug("EMAIL - tried to save a duplicate Email record");
- } else {
- if(empty($this->id)) {
- $this->id = create_guid();
- $this->new_with_id = true;
- }
- $this->from_addr_name = $this->cleanEmails($this->from_addr_name);
- $this->to_addrs_names = $this->cleanEmails($this->to_addrs_names);
- $this->cc_addrs_names = $this->cleanEmails($this->cc_addrs_names);
- $this->bcc_addrs_names = $this->cleanEmails($this->bcc_addrs_names);
- $this->reply_to_addr = $this->cleanEmails($this->reply_to_addr);
- $this->description = to_html($this->safeText(from_html($this->description)));
- $this->description_html = $this->safeText($this->description_html);
- $this->saveEmailText();
- $this->saveEmailAddresses();
- $GLOBALS['log']->debug('-------------------------------> Email called save()');
- // handle legacy concatenation of date and time fields
- if(empty($this->date_sent)) $this->date_sent = $this->date_start." ".$this->time_start;
- parent::save($check_notify);
- if(!empty($this->parent_type) && !empty($this->parent_id)) {
- if(!empty($this->fetched_row) && !empty($this->fetched_row['parent_id']) && !empty($this->fetched_row['parent_type'])) {
- if($this->fetched_row['parent_id'] != $this->parent_id || $this->fetched_row['parent_type'] != $this->parent_type) {
- $mod = strtolower($this->fetched_row['parent_type']);
- $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
- if($this->load_relationship($rel) ) {
- $this->$rel->delete($this->id, $this->fetched_row['parent_id']);
- }
- } else {
- // we already have this relationship, don't add it
- return;
- }
- }
- $mod = strtolower($this->parent_type);
- $rel = array_key_exists($mod, $this->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
- if($this->load_relationship($rel) ) {
- $this->$rel->add($this->parent_id);
- }
- }
- }
- }
- /**
- * Helper function to save temporary attachments assocaited to an email as note.
- *
- * @param string $filename
- * @param string $fileLocation
- * @param string $mimeType
- */
- function saveTempNoteAttachments($filename,$fileLocation, $mimeType)
- {
- global $sugar_config;
- $tmpNote = new Note();
- $tmpNote->id = create_guid();
- $tmpNote->new_with_id = true;
- $tmpNote->parent_id = $this->id;
- $tmpNote->parent_type = $this->module_dir;
- $tmpNote->name = $filename;
- $tmpNote->filename = $filename;
- $tmpNote->file_mime_type = $mimeType;
- $noteFile = "{$sugar_config['upload_dir']}{$tmpNote->id}";
- if(!copy($fileLocation, $noteFile))
- $GLOBALS['log']->fatal("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]");
- $tmpNote->save();
- }
- /**
- * Handles normalization of Email Addressess
- */
- function saveEmailAddresses() {
- // from, single address
- $fromId = $this->emailAddress->getEmailGUID(from_html($this->from_addr));
- if(!empty($fromId)){
- $this->linkEmailToAddress($fromId, 'from');
- }
- // to, multiple
- $replace = array(",",";");
- $toaddrs = str_replace($replace, "::", from_html($this->to_addrs));
- $exToAddrs = explode("::", $toaddrs);
- if(!empty($exToAddrs)) {
- foreach($exToAddrs as $toaddr) {
- $toaddr = trim($toaddr);
- if(!empty($toaddr)) {
- $toId = $this->emailAddress->getEmailGUID($toaddr);
- $this->linkEmailToAddress($toId, 'to');
- }
- }
- }
- // cc, multiple
- $ccAddrs = str_replace($replace, "::", from_html($this->cc_addrs));
- $exccAddrs = explode("::", $ccAddrs);
- if(!empty($exccAddrs)) {
- foreach($exccAddrs as $ccAddr) {
- $ccAddr = trim($ccAddr);
- if(!empty($ccAddr)) {
- $ccId = $this->emailAddress->getEmailGUID($ccAddr);
- $this->linkEmailToAddress($ccId, 'cc');
- }
- }
- }
- // bcc, multiple
- $bccAddrs = str_replace($replace, "::", from_html($this->bcc_addrs));
- $exbccAddrs = explode("::", $bccAddrs);
- if(!empty($exbccAddrs)) {
- foreach($exbccAddrs as $bccAddr) {
- $bccAddr = trim($bccAddr);
- if(!empty($bccAddr)) {
- $bccId = $this->emailAddress->getEmailGUID($bccAddr);
- $this->linkEmailToAddress($bccId, 'bcc');
- }
- }
- }
- }
- function linkEmailToAddress($id, $type) {
- // TODO: make this update?
- $q1 = "SELECT * FROM emails_email_addr_rel WHERE email_id = '{$this->id}' AND email_address_id = '{$id}' AND address_type = '{$type}' AND deleted = 0";
- $r1 = $this->db->query($q1);
- $a1 = $this->db->fetchByAssoc($r1);
- if(!empty($a1) && !empty($a1['id'])) {
- return $a1['id'];
- } else {
- $guid = create_guid();
- $q2 = "INSERT INTO emails_email_addr_rel VALUES('{$guid}', '{$this->id}', '{$type}', '{$id}', 0)";
- $r2 = $this->db->query($q2);
- }
- return $guid;
- }
- function cleanEmails($emails)
- {
- $emails = str_replace(array(",",";"), "::", from_html($emails));
- $addrs = explode("::", $emails);
- $res = array();
- foreach($addrs as $addr) {
- $parts = $this->emailAddress->splitEmailAddress($addr);
- if(empty($parts["email"])) {
- continue;
- }
- if(!empty($parts["name"])) {
- $res[] = "{$parts["name"]} <{$parts["email"]}>";
- } else {
- $res[] .= $parts["email"];
- }
- }
- return join(", ", $res);
- }
- function saveEmailText() {
- $isOracle = ($this->db->dbType == "oci8") ? true : false;
- if ($isOracle) {
- } else {
- $description = $this->db->quote(trim($this->description));
- $description_html = $this->db->quoteForEmail(trim($this->description_html));
- $raw_source = $this->db->quote(trim($this->raw_source));
- $fromAddressName = $this->db->helper->escape_quote($this->from_addr_name);
- $toAddressName = $this->db->helper->escape_quote($this->to_addrs_names);
- $ccAddressName = $this->db->helper->escape_quote($this->cc_addrs_names);
- $bccAddressName = $this->db->helper->escape_quote($this->bcc_addrs_names);
- $replyToAddrName = $this->db->helper->escape_quote($this->reply_to_addr);
- if(!$this->new_with_id) {
- $q = "UPDATE emails_text SET from_addr = '{$fromAddressName}', to_addrs = '{$toAddressName}', cc_addrs = '{$ccAddressName}', bcc_addrs = '{$bccAddressName}', reply_to_addr = '{$replyToAddrName}', description = '{$description}', description_html = '{$description_html}', raw_source = '{$raw_source}' WHERE email_id = '{$this->id}'";
- } else {
- $q = "INSERT INTO emails_text (email_id, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to_addr, description, description_html, raw_source, deleted) VALUES('{$this->id}', '{$fromAddressName}', '{$toAddressName}', '{$ccAddressName}', '{$bccAddressName}', '{$replyToAddrName}', '{$description}', '{$description_html}', '{$raw_source}', 0)";
- }
- $this->db->query($q);
- } // else
- }
- ///////////////////////////////////////////////////////////////////////////
- //// RETRIEVERS
- function retrieve($id, $encoded=true, $deleted=true) {
- // cn: bug 11915, return SugarBean's retrieve() call bean instead of $this
- $ret = parent::retrieve($id, $encoded, $deleted);
- if($ret) {
- $ret->retrieveEmailText();
- $ret->retrieveEmailAddresses();
- $ret->raw_source = to_html($ret->safeText(from_html($ret->raw_source)));
- $ret->description = to_html($ret->safeText(from_html($ret->description)));
- $ret->description_html = $ret->safeText($ret->description_html);
- $ret->date_start = '';
- $ret->time_start = '';
- $dateSent = explode(' ', $ret->date_sent);
- if (!empty($dateSent)) {
- $ret->date_start = $dateSent[0];
- if ( isset($dateSent[1]) )
- $ret->time_start = $dateSent[1];
- }
- // for Email 2.0
- foreach($ret as $k => $v) {
- $this->$k = $v;
- }
- }
- return $ret;
- }
- /**
- * Retrieves email addresses from GUIDs
- */
- function retrieveEmailAddresses() {
- $return = array();
- $q = "SELECT email_address, address_type
- FROM emails_email_addr_rel eam
- JOIN email_addresses ea ON ea.id = eam.email_address_id
- WHERE eam.email_id = '{$this->id}' AND eam.deleted=0";
- $r = $this->db->query($q);
- while($a = $this->db->fetchByAssoc($r)) {
- if(!isset($return[$a['address_type']])) {
- $return[$a['address_type']] = array();
- }
- $return[$a['address_type']][] = $a['email_address'];
- }
- if(count($return) > 0) {
- if(isset($return['from'])) {
- $this->from_addr = implode(", ", $return['from']);
- }
- if(isset($return['to'])) {
- $this->to_addrs = implode(", ", $return['to']);
- }
- if(isset($return['cc'])) {
- $this->cc_addrs = implode(", ", $return['cc']);
- }
- if(isset($return['bcc'])) {
- $this->bcc_addrs = implode(", ", $return['bcc']);
- }
- }
- }
- /**
- * Handles longtext fields
- */
- function retrieveEmailText() {
- $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}'";
- $r = $this->db->query($q);
- $a = $this->db->fetchByAssoc($r, -1, false);
- $this->description = $a['description'];
- $this->description_html = $a['description_html'];
- $this->raw_source = $a['raw_source'];
- $this->from_addr_name = $a['from_addr'];
- $this->reply_to_addr = $a['reply_to_addr'];
- $this->to_addrs_names = $a['to_addrs'];
- $this->cc_addrs_names = $a['cc_addrs'];
- $this->bcc_addrs_names = $a['bcc_addrs'];
- }
- function delete($id='') {
- if(empty($id))
- $id = $this->id;
- $q = "UPDATE emails SET deleted = 1 WHERE id = '{$id}'";
- $qt = "UPDATE emails_text SET deleted = 1 WHERE email_id = '{$id}'";
- $r = $this->db->query($q);
- $rt = $this->db->query($qt);
- }
- /**
- * creates the standard "Forward" info at the top of the forwarded message
- * @return string
- */
- function getForwardHeader() {
- global $mod_strings;
- global $current_user;
- //$from = str_replace(array(">","<"), array(")","("), $this->from_name);
- $from = to_html($this->from_name);
- $subject = to_html($this->name);
- $ret = "<br /><br />";
- $ret .= $this->replyDelimiter."{$mod_strings['LBL_FROM']} {$from}<br />";
- $ret .= $this->replyDelimiter."{$mod_strings['LBL_DATE_SENT']} {$this->date_sent}<br />";
- $ret .= $this->replyDelimiter."{$mod_strings['LBL_TO']} {$this->to_addrs}<br />";
- $ret .= $this->replyDelimiter."{$mod_strings['LBL_CC']} {$this->cc_addrs}<br />";
- $ret .= $this->replyDelimiter."{$mod_strings['LBL_SUBJECT']} {$subject}<br />";
- $ret .= $this->replyDelimiter."<br />";
- return $ret;
- //return from_html($ret);
- }
- /**
- * retrieves Notes that belong to this Email and stuffs them into the "attachments" attribute
- */
- function getNotes($id, $duplicate=false) {
- if(!class_exists('Note')) {
- }
- $exRemoved = array();
- if(isset($_REQUEST['removeAttachment'])) {
- $exRemoved = explode('::', $_REQUEST['removeAttachment']);
- }
- $noteArray = array();
- $q = "SELECT id FROM notes WHERE parent_id = '".$id."'";
- $r = $this->db->query($q);
- while($a = $this->db->fetchByAssoc($r)) {
- if(!in_array($a['id'], $exRemoved)) {
- $note = new Note();
- $note->retrieve($a['id']);
- // duplicate actual file when creating forwards
- if($duplicate) {
- if(!class_exists('UploadFile')) {
- require_once('include/upload_file.php');
- }
- // save a brand new Note
- $noteDupe->id = create_guid();
- $noteDupe->new_with_id = true;
- $noteDupe->parent_id = $this->id;
- $noteDupe->parent_type = $this->module_dir;
- $noteFile = new UploadFile('none');
- $noteFile->duplicate_file($a['id'], $note->id, $note->filename);
- $note->save();
- }
- // add Note to attachments array
- $this->attachments[] = $note;
- }
- }
- }
- /**
- * creates the standard "Reply" info at the top of the forwarded message
- * @return string
- */
- function getReplyHeader() {
- global $mod_strings;
- global $current_user;
- $from = str_replace(array(">","<", ">","<"), array(")","(",")","("), $this->from_name);
- $ret = "<br>{$mod_strings['LBL_REPLY_HEADER_1']} {$this->date_start}, {$this->time_start}, {$from} {$mod_strings['LBL_REPLY_HEADER_2']}";
- return from_html($ret);
- }
- /**
- * Quotes plain-text email text
- * @param string $text
- * @return string
- */
- function quotePlainTextEmail($text) {
- $quoted = "\n";
- // plain-text
- $desc = nl2br(trim($text));
- $exDesc = explode('<br />', $desc);
- foreach($exDesc as $k => $line) {
- $quoted .= '> '.trim($line)."\r";
- }
- return $quoted;
- }
- /**
- * "quotes" (i.e., "> my text yadda" the HTML part of an email
- * @param string $text HTML text to quote
- * @return string
- */
- function quoteHtmlEmail($text) {
- $text = trim(from_html($text));
- if(empty($text)) {
- return '';
- }
- $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
- return $out;
- }
- /**
- * "quotes" (i.e., "> my text yadda" the HTML part of an email
- * @param string $text HTML text to quote
- * @return string
- */
- function quoteHtmlEmailForNewEmailUI($text) {
- $text = trim($text);
- if(empty($text)) {
- return '';
- }
- $text = str_replace("\n", "\n<BR/>", $text);
- $out = "<div style='border-left:1px solid #00c; padding:5px; margin-left:10px;'>{$text}</div>";
- return $out;
- }
- ///////////////////////////////////////////////////////////////////////////
- //// LEGACY CODE
- /**
- * Safes description text (both HTML and Plain Text) for display
- * @param string str The text to safe
- * @return string Safed text
- */
- function safeText($str) {
- // Safe_HTML
- $this->safe->clear();
- $ret = $this->safe->parse($str);
- // Julian's XSS cleaner
- $potentials = clean_xss($str, false);
- if(is_array($potentials) && !empty($potentials)) {
- //_ppl($potentials);
- foreach($potentials as $bad) {
- $ret = str_replace($bad, "", $ret);
- }
- }
- // clean <HTML> and <BODY> tags
- $html = '#<\\\\\?HTML[\w =\'\"\&]*>#sim';
- $body = '#<\\\\\?BODY[\w =\'\"\&]*>#sim';
- $ret = preg_replace($html, "", $ret);
- $ret = preg_replace($body, "", $ret);
- return $ret;
- }
- /**
- * Ensures that the user is able to send outbound emails
- */
- function check_email_settings() {
- global $current_user;
- $mail_fromaddress = $current_user->emailAddre…
Large files files are truncated, but you can click here to view the full file