Пример #1
0
 function saveFile($note, $portal = false)
 {
     global $sugar_config;
     $focus = new Note();
     if (!empty($note['id'])) {
         $focus->retrieve($note['id']);
     } else {
         return '-1';
     }
     if (!empty($note['file'])) {
         $decodedFile = base64_decode($note['file']);
         $this->upload_file->set_for_soap($note['filename'], $decodedFile);
         $ext_pos = strrpos($this->upload_file->stored_file_name, ".");
         $this->upload_file->file_ext = substr($this->upload_file->stored_file_name, $ext_pos + 1);
         if (in_array($this->upload_file->file_ext, $sugar_config['upload_badext'])) {
             $this->upload_file->stored_file_name .= ".txt";
             $this->upload_file->file_ext = "txt";
         }
         $focus->filename = $this->upload_file->get_stored_file_name();
         $focus->file_mime_type = $this->upload_file->getMimeSoap($focus->filename);
         $focus->id = $note['id'];
         $return_id = $focus->save();
         $this->upload_file->final_move($focus->id);
     } else {
         return '-1';
     }
     return $return_id;
 }
Пример #2
0
 function newSaveFile($note, $portal = false)
 {
     global $sugar_config;
     $focus = new Note();
     if (!empty($note['id'])) {
         $focus->retrieve($note['id']);
         if (empty($focus->id)) {
             return '-1';
         }
     } else {
         return '-1';
     }
     if (!empty($note['file'])) {
         $decodedFile = base64_decode($note['file']);
         $this->upload_file->set_for_soap($note['filename'], $decodedFile);
         $ext_pos = strrpos($this->upload_file->stored_file_name, ".");
         $this->upload_file->file_ext = substr($this->upload_file->stored_file_name, $ext_pos + 1);
         if (in_array($this->upload_file->file_ext, $sugar_config['upload_badext'])) {
             $this->upload_file->stored_file_name .= ".txt";
             $this->upload_file->file_ext = "txt";
         }
         $focus->filename = $this->upload_file->get_stored_file_name();
         $focus->file_mime_type = $this->upload_file->getMimeSoap($focus->filename);
         $focus->save();
     }
     $return_id = $focus->id;
     if (!empty($note['file'])) {
         $this->upload_file->final_move($focus->id);
     }
     if (!empty($note['related_module_id']) && !empty($note['related_module_name'])) {
         $focus->process_save_dates = false;
         $module_name = $note['related_module_name'];
         $module_id = $note['related_module_id'];
         if ($module_name != 'Contacts') {
             $focus->parent_type = $module_name;
             $focus->parent_id = $module_id;
         } else {
             $focus->contact_id = $module_id;
         }
         $focus->save();
     }
     // if
     return $return_id;
 }
Пример #3
0
 function sendEmail($mail, $save_emails = 1, $testmode = false)
 {
     $this->test = $testmode;
     global $beanList, $beanFiles, $sugar_config;
     global $mod_strings;
     global $locale;
     $OBCharset = $locale->getPrecedentPreference('default_email_charset');
     $mod_strings = return_module_language($sugar_config['default_language'], 'EmailMan');
     //get tracking entities locations.
     if (!isset($this->tracking_url)) {
         if (!class_exists('Administration')) {
         }
         $admin = new Administration();
         $admin->retrieveSettings('massemailer');
         //retrieve all admin settings.
         if (isset($admin->settings['massemailer_tracking_entities_location_type']) and $admin->settings['massemailer_tracking_entities_location_type'] == '2' and isset($admin->settings['massemailer_tracking_entities_location'])) {
             $this->tracking_url = $admin->settings['massemailer_tracking_entities_location'];
         } else {
             $this->tracking_url = $sugar_config['site_url'];
         }
     }
     //make sure tracking url ends with '/' character
     $strLen = strlen($this->tracking_url);
     if ($this->tracking_url[$strLen - 1] != '/') {
         $this->tracking_url .= '/';
     }
     if (!isset($beanList[$this->related_type])) {
         return false;
     }
     $class = $beanList[$this->related_type];
     if (!class_exists($class)) {
         require_once $beanFiles[$class];
     }
     if (!class_exists('Email')) {
     }
     $module = new $class();
     $module->retrieve($this->related_id);
     $module->emailAddress->handleLegacyRetrieve($module);
     //check to see if bean has a primary email address
     if (!$this->is_primary_email_address($module)) {
         //no primary email address designated, do not send out email, create campaign log
         //of type send error to denote that this user was not emailed
         $this->set_as_sent($module->email1, true, null, null, 'send error');
         //create fatal logging for easy review of cause.
         $GLOBALS['log']->fatal('Email Address provided is not Primary Address for email with id ' . $module->email1 . "' Emailman id={$this->id}");
         return true;
     }
     if (!$this->valid_email_address($module->email1)) {
         $this->set_as_sent($module->email1, true, null, null, 'invalid email');
         $GLOBALS['log']->fatal('Encountered invalid email address' . $module->email1 . " Emailman id={$this->id}");
         return true;
     }
     if ((!isset($module->email_opt_out) || $module->email_opt_out !== 'on' && $module->email_opt_out !== 1 && $module->email_opt_out !== '1') && (!isset($module->invalid_email) || $module->invalid_email !== 'on' && $module->invalid_email !== 1 && $module->invalid_email !== '1')) {
         $lower_email_address = strtolower($module->email1);
         //test against indivdual address.
         if (isset($this->restricted_addresses) and isset($this->restricted_addresses[$lower_email_address])) {
             $this->set_as_sent($lower_email_address, true, null, null, 'blocked');
             return true;
         }
         //test against restricted domains
         $at_pos = strrpos($lower_email_address, '@');
         if ($at_pos !== false) {
             foreach ($this->restricted_domains as $domain => $value) {
                 $pos = strrpos($lower_email_address, $domain);
                 if ($pos !== false && $pos > $at_pos) {
                     //found
                     $this->set_as_sent($lower_email_address, true, null, null, 'blocked');
                     return true;
                 }
             }
         }
         //test for duplicate email address by marketing id.
         $dup_query = "select id from campaign_log where more_information='" . $module->email1 . "' and marketing_id='" . $this->marketing_id . "'";
         $dup = $this->db->query($dup_query);
         $dup_row = $this->db->fetchByAssoc($dup);
         if (!empty($dup_row)) {
             //we have seen this email address before
             $this->set_as_sent($module->email1, true, null, null, 'blocked');
             return true;
         }
         $this->target_tracker_key = create_guid();
         //fetch email marketing.
         if (empty($this->current_emailmarketing) or !isset($this->current_emailmarketing)) {
             if (!class_exists('EmailMarketing')) {
             }
             $this->current_emailmarketing = new EmailMarketing();
         }
         if (empty($this->current_emailmarketing->id) or $this->current_emailmarketing->id !== $this->marketing_id) {
             $this->current_emailmarketing->retrieve($this->marketing_id);
             $this->newmessage = true;
         }
         //fetch email template associate with the marketing message.
         if (empty($this->current_emailtemplate) or $this->current_emailtemplate->id !== $this->current_emailmarketing->template_id) {
             if (!class_exists('EmailTemplate')) {
             }
             $this->current_emailtemplate = new EmailTemplate();
             $this->current_emailtemplate->retrieve($this->current_emailmarketing->template_id);
             //escape email template contents.
             $this->current_emailtemplate->subject = from_html($this->current_emailtemplate->subject);
             $this->current_emailtemplate->body_html = from_html($this->current_emailtemplate->body_html);
             $this->current_emailtemplate->body = from_html($this->current_emailtemplate->body);
             $q = "SELECT * FROM notes WHERE parent_id = '" . $this->current_emailtemplate->id . "' AND deleted = 0";
             $r = $this->db->query($q);
             // cn: bug 4684 - initialize the notes array, else old data is still around for the next round
             $this->notes_array = array();
             if (!class_exists('Note')) {
                 require_once 'modules/Notes/Note.php';
             }
             while ($a = $this->db->fetchByAssoc($r)) {
                 $noteTemplate = new Note();
                 $noteTemplate->retrieve($a['id']);
                 $this->notes_array[] = $noteTemplate;
             }
         }
         // fetch mailbox details..
         if (empty($this->current_mailbox)) {
             if (!class_exists('InboundEmail')) {
             }
             $this->current_mailbox = new InboundEmail();
         }
         if (empty($this->current_mailbox->id) or $this->current_mailbox->id !== $this->current_emailmarketing->inbound_email_id) {
             $this->current_mailbox->retrieve($this->current_emailmarketing->inbound_email_id);
             //extract the email address.
             $this->mailbox_from_addr = $this->current_mailbox->get_stored_options('from_addr', '*****@*****.**', null);
         }
         // fetch campaign details..
         if (empty($this->current_campaign)) {
             if (!class_exists('Campaign')) {
             }
             $this->current_campaign = new Campaign();
         }
         if (empty($this->current_campaign->id) or $this->current_campaign->id !== $this->current_emailmarketing->campaign_id) {
             $this->current_campaign->retrieve($this->current_emailmarketing->campaign_id);
             //load defined tracked_urls
             $this->current_campaign->load_relationship('tracked_urls');
             $query_array = $this->current_campaign->tracked_urls->getQuery(true);
             $query_array['select'] = "SELECT tracker_name, tracker_key, id, is_optout ";
             $result = $this->current_campaign->db->query(implode(' ', $query_array));
             $this->has_optout_links = false;
             $this->tracker_urls = array();
             while (($row = $this->current_campaign->db->fetchByAssoc($result)) != null) {
                 $this->tracker_urls['{' . $row['tracker_name'] . '}'] = $row;
                 //has the user defined opt-out links for the campaign.
                 if ($row['is_optout'] == 1) {
                     $this->has_optout_links = true;
                 }
             }
         }
         $mail->ClearAllRecipients();
         $mail->ClearReplyTos();
         $mail->Sender = $this->mailbox_from_addr;
         $mail->From = $this->mailbox_from_addr;
         $mail->FromName = $this->current_emailmarketing->from_name;
         $mail->ClearCustomHeaders();
         $mail->AddCustomHeader('X-CampTrackID:' . $this->target_tracker_key);
         //CL - Bug 25256 Check if we have a reply_to_name/reply_to_addr value from the email marketing table.  If so use email marketing entry; otherwise current mailbox (inbound email) entry
         $replyToName = empty($this->current_emailmarketing->reply_to_name) ? $this->current_mailbox->get_stored_options('reply_to_name', $mail->FromName, null) : $this->current_emailmarketing->reply_to_name;
         $replyToAddr = empty($this->current_emailmarketing->reply_to_addr) ? $this->current_mailbox->get_stored_options('reply_to_addr', $mail->From, null) : $this->current_emailmarketing->reply_to_addr;
         $mail->AddReplyTo($replyToAddr, $locale->translateCharsetMIME(trim($replyToName), 'UTF-8', $OBCharset));
         //parse and replace bean variables.
         $macro_nv = array();
         $focus_name = 'Contacts';
         if ($module->module_dir == 'Accounts') {
             $focus_name = 'Accounts';
         }
         $template_data = $this->current_emailtemplate->parse_email_template(array('subject' => $this->current_emailtemplate->subject, 'body_html' => $this->current_emailtemplate->body_html, 'body' => $this->current_emailtemplate->body), $focus_name, $module, $macro_nv);
         //add email address to this list.
         $macro_nv['sugar_to_email_address'] = $module->email1;
         $macro_nv['email_template_id'] = $this->current_emailmarketing->template_id;
         //parse and replace urls.
         //this is new style of adding tracked urls to a campaign.
         $tracker_url_template = $this->tracking_url . 'index.php?entryPoint=campaign_trackerv2&track=%s' . '&identifier=' . $this->target_tracker_key;
         $removeme_url_template = $this->tracking_url . 'index.php?entryPoint=removeme&identifier=' . $this->target_tracker_key;
         $template_data = $this->current_emailtemplate->parse_tracker_urls($template_data, $tracker_url_template, $this->tracker_urls, $removeme_url_template);
         $mail->AddAddress($module->email1, $locale->translateCharsetMIME(trim($module->name), 'UTF-8', $OBCharset));
         //refetch strings in case they have been changed by creation of email templates or other beans.
         $mod_strings = return_module_language($sugar_config['default_language'], 'EmailMan');
         if ($this->test) {
             $mail->Subject = $mod_strings['LBL_PREPEND_TEST'] . $template_data['subject'];
         } else {
             $mail->Subject = $template_data['subject'];
         }
         //check if this template is meant to be used as "text only"
         $text_only = false;
         if (isset($this->current_emailtemplate->text_only) && $this->current_emailtemplate->text_only) {
             $text_only = true;
         }
         //if this template is textonly, then just send text body.  Do not add tracker, opt out,
         //or perform other processing as it will not show up in text only email
         if ($text_only) {
             $this->description_html = '';
             $mail->IsHTML(false);
             $mail->Body = $template_data['body'];
         } else {
             $mail->Body = wordwrap($template_data['body_html'], 900);
             //BEGIN:this code will trigger for only campaigns pending before upgrade to 4.2.0.
             //will be removed for the next release.
             if (!isset($btracker)) {
                 $btracker = false;
             }
             if ($btracker) {
                 $mail->Body .= "<br /><br /><a href='" . $tracker_url . "'>" . $tracker_text . "</a><br /><br />";
             } else {
                 if (!empty($tracker_url)) {
                     $mail->Body = str_replace('TRACKER_URL_START', "<a href='" . $tracker_url . "'>", $mail->Body);
                     $mail->Body = str_replace('TRACKER_URL_END', "</a>", $mail->Body);
                     $mail->AltBody = str_replace('TRACKER_URL_START', "<a href='" . $tracker_url . "'>", $mail->AltBody);
                     $mail->AltBody = str_replace('TRACKER_URL_END', "</a>", $mail->AltBody);
                 }
             }
             //END
             //do not add the default remove me link if the campaign has a trackerurl of the opotout link
             if ($this->has_optout_links == false) {
                 $mail->Body .= "<br /><span style='font-size:0.8em'>{$mod_strings['TXT_REMOVE_ME']} <a href='" . $this->tracking_url . "index.php?entryPoint=removeme&identifier={$this->target_tracker_key}'>{$mod_strings['TXT_REMOVE_ME_CLICK']}</a></span>";
             }
             // cn: bug 11979 - adding single quote to comform with HTML email RFC
             $mail->Body .= "<br /><img alt='' height='1' width='1' src='{$this->tracking_url}index.php?entryPoint=image&identifier={$this->target_tracker_key}' />";
             $mail->AltBody = $template_data['body'];
             if ($btracker) {
                 $mail->AltBody .= "\n" . $tracker_url;
             }
             if ($this->has_optout_links == false) {
                 $mail->AltBody .= "\n\n\n{$mod_strings['TXT_REMOVE_ME_ALT']} " . $this->tracking_url . "index.php?entryPoint=removeme&identifier={$this->target_tracker_key}";
             }
         }
         // cn: bug 4684, handle attachments in email templates.
         $mail->handleAttachments($this->notes_array);
         $tmp_Subject = $mail->Subject;
         $mail->prepForOutbound();
         $success = $mail->Send();
         //Do not save the encoded subject.
         $mail->Subject = $tmp_Subject;
         if ($success) {
             $email_id = null;
             if ($save_emails == 1) {
                 $email_id = $this->create_indiv_email($module, $mail);
             } else {
                 //find/create reference email record. all campaign targets reveiving this message will be linked with this message.
                 $email_id = $this->create_ref_email($this->marketing_id, $this->current_emailtemplate->subject, $this->current_emailtemplate->body, $this->current_emailtemplate->body_html, $this->current_campaign->name, $this->mailbox_from_addr, $this->user_id, $this->notes_array, $macro_nv, $this->newmessage);
                 $this->newmessage = false;
             }
         }
         if ($success) {
             $this->set_as_sent($module->email1, true, $email_id, 'Emails', 'targeted');
         } else {
             if (!empty($layout_def['parent_id'])) {
                 if (isset($layout_def['fields'][strtoupper($layout_def['parent_id'])])) {
                     $parent .= "&parent_id=" . $layout_def['fields'][strtoupper($layout_def['parent_id'])];
                 }
             }
             if (!empty($layout_def['parent_module'])) {
                 if (isset($layout_def['fields'][strtoupper($layout_def['parent_module'])])) {
                     $parent .= "&parent_module=" . $layout_def['fields'][strtoupper($layout_def['parent_module'])];
                 }
             }
             //log send error. save for next attempt after 24hrs. no campaign log entry will be created.
             $this->set_as_sent($module->email1, false, null, null, 'send error');
         }
     } else {
         $success = false;
         $this->target_tracker_key = create_guid();
         if (isset($module->email_opt_out) && ($module->email_opt_out === 'on' || $module->email_opt_out == '1' || $module->email_opt_out == 1)) {
             $this->set_as_sent($module->email1, true, null, null, 'removed');
         } else {
             if (isset($module->invalid_email) && ($module->invalid_email == 1 || $module->invalid_email == '1')) {
                 $this->set_as_sent($module->email1, true, null, null, 'invalid email');
             } else {
                 $this->set_as_sent($module->email1, true, null, null, 'send error');
             }
         }
     }
     return $success;
 }
 function handleSave($prefix, $redirect = true, $useRequired = false)
 {
     require_once 'include/formbase.php';
     require_once 'include/upload_file.php';
     global $upload_maxsize;
     global $mod_strings;
     global $sugar_config;
     $focus = new EmailTemplate();
     if ($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))) {
         return null;
     }
     $focus = populateFromPost($prefix, $focus);
     //process the text only flag
     if (isset($_POST['text_only']) && $_POST['text_only'] == '1') {
         $focus->text_only = 1;
     } else {
         $focus->text_only = 0;
     }
     if (!$focus->ACLAccess('Save')) {
         ACLController::displayNoAccess(true);
         sugar_cleanup(true);
     }
     if (!isset($_REQUEST['published'])) {
         $focus->published = 'off';
     }
     $preProcessedImages = array();
     $emailTemplateBodyHtml = from_html($focus->body_html);
     if (strpos($emailTemplateBodyHtml, '"cache/images/')) {
         $matches = array();
         preg_match_all('#<img[^>]*[\\s]+src[^=]*=[\\s]*["\']cache/images/(.+?)["\']#si', $emailTemplateBodyHtml, $matches);
         foreach ($matches[1] as $match) {
             $filename = urldecode($match);
             $file_location = sugar_cached("images/{$filename}");
             $mime_type = pathinfo($filename, PATHINFO_EXTENSION);
             if (file_exists($file_location)) {
                 $id = create_guid();
                 $newFileLocation = "upload://{$id}";
                 if (!copy($file_location, $newFileLocation)) {
                     $GLOBALS['log']->debug("EMAIL Template could not copy attachment to {$newFileLocation}");
                 } else {
                     $secureLink = "index.php?entryPoint=download&type=Notes&id={$id}";
                     $emailTemplateBodyHtml = str_replace("cache/images/{$match}", $secureLink, $emailTemplateBodyHtml);
                     unlink($file_location);
                     $preProcessedImages[$filename] = $id;
                 }
             }
             // if
         }
         // foreach
     }
     // if
     if (isset($GLOBALS['check_notify'])) {
         $check_notify = $GLOBALS['check_notify'];
     } else {
         $check_notify = FALSE;
     }
     $focus->body_html = $emailTemplateBodyHtml;
     $return_id = $focus->save($check_notify);
     ///////////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////
     ////	ADDING NEW ATTACHMENTS
     $max_files_upload = count($_FILES);
     if (!empty($focus->id)) {
         $note = new Note();
         $where = "notes.parent_id='{$focus->id}'";
         if (!empty($_REQUEST['old_id'])) {
             // to support duplication of email templates
             $where .= " OR notes.parent_id='" . $_REQUEST['old_id'] . "'";
         }
         $notes_list = $note->get_full_list("", $where, true);
     }
     if (!isset($notes_list)) {
         $notes_list = array();
     }
     if (!is_array($focus->attachments)) {
         // PHP5 does not auto-create arrays(). Need to initialize it here.
         $focus->attachments = array();
     }
     $focus->attachments = array_merge($focus->attachments, $notes_list);
     //for($i = 0; $i < $max_files_upload; $i++) {
     foreach ($_FILES as $key => $file) {
         $note = new Note();
         //Images are presaved above so we need to prevent duplicate files from being created.
         if (isset($preProcessedImages[$file['name']])) {
             $oldId = $preProcessedImages[$file['name']];
             $note->id = $oldId;
             $note->new_with_id = TRUE;
             $GLOBALS['log']->debug("Image {$file['name']} has already been processed.");
         }
         $i = preg_replace("/email_attachment(.+)/", '$1', $key);
         $upload_file = new UploadFile($key);
         if (isset($_FILES[$key]) && $upload_file->confirm_upload() && preg_match("/^email_attachment/", $key)) {
             $note->filename = $upload_file->get_stored_file_name();
             $note->file = $upload_file;
             $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ' . $note->file->original_file_name;
             if (isset($_REQUEST['embedded' . $i]) && !empty($_REQUEST['embedded' . $i])) {
                 if ($_REQUEST['embedded' . $i] == 'true') {
                     $note->embed_flag = true;
                 } else {
                     $note->embed_flag = false;
                 }
             }
             array_push($focus->attachments, $note);
         }
     }
     $focus->saved_attachments = array();
     foreach ($focus->attachments as $note) {
         if (!empty($note->id) && $note->new_with_id === FALSE) {
             if (empty($_REQUEST['old_id'])) {
                 array_push($focus->saved_attachments, $note);
             } else {
                 // we're duplicating a template with attachments
                 // dupe the file, create a new note, assign the note to the new template
                 $newNote = new Note();
                 $newNote->retrieve($note->id);
                 $newNote->id = create_guid();
                 $newNote->parent_id = $focus->id;
                 $newNote->new_with_id = true;
                 $newNote->date_modified = '';
                 $newNote->date_entered = '';
                 $newNoteId = $newNote->save();
                 UploadFile::duplicate_file($note->id, $newNoteId, $note->filename);
             }
             continue;
         }
         $note->parent_id = $focus->id;
         $note->parent_type = 'Emails';
         $note->file_mime_type = $note->file->mime_type;
         $note_id = $note->save();
         array_push($focus->saved_attachments, $note);
         $note->id = $note_id;
         if ($note->new_with_id === FALSE) {
             $note->file->final_move($note->id);
         } else {
             $GLOBALS['log']->debug("Not performing final move for note id {$note->id} as it has already been processed");
         }
     }
     ////	END NEW ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM DOCUMENTS
     $count = '';
     //_pp($_REQUEST);
     //_ppd(count($_REQUEST['document']));
     if (!empty($_REQUEST['document'])) {
         $count = count($_REQUEST['document']);
     } else {
         $count = 10;
     }
     for ($i = 0; $i < $count; $i++) {
         if (isset($_REQUEST['documentId' . $i]) && !empty($_REQUEST['documentId' . $i])) {
             $doc = new Document();
             $docRev = new DocumentRevision();
             $docNote = new Note();
             $doc->retrieve($_REQUEST['documentId' . $i]);
             $docRev->retrieve($doc->document_revision_id);
             array_push($focus->saved_attachments, $docRev);
             $docNote->name = $doc->document_name;
             $docNote->filename = $docRev->filename;
             $docNote->description = $doc->description;
             $docNote->parent_id = $focus->id;
             $docNote->parent_type = 'Emails';
             $docNote->file_mime_type = $docRev->file_mime_type;
             $docId = $docNote = $docNote->save();
             UploadFile::duplicate_file($docRev->id, $docId, $docRev->filename);
         }
     }
     ////	END ATTACHMENTS FROM DOCUMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	REMOVE ATTACHMENTS
     if (isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
         foreach ($_REQUEST['remove_attachment'] as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $focus->db->query($q);
         }
     }
     ////	END REMOVE ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ////	END ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////////
     clear_register_value('select_array', $focus->object_name);
     if ($redirect) {
         $GLOBALS['log']->debug("Saved record with id of " . $return_id);
         handleRedirect($return_id, "EmailTemplates");
     } else {
         return $focus;
     }
 }
Пример #5
0
/**
 * Retrieve an attachment from a note
 * @param String $session -- Session ID returned by a previous call to login.
 * @param Binary $note -- The flie contents of the attachment.
 * @return Array 'id' -- The ID of the new note or -1 on error
 *               'error' -- The SOAP error if any.
 *
 * @param String $session -- Session ID returned by a previous call to login.
 * @param String $id -- The ID of the appropriate Note.
 * @return Array 'note_attachment' -- Array String 'id' -- The ID of the Note containing the attachment
 *                                          String 'filename' -- The file name of the attachment
 *                                          Binary 'file' -- The binary contents of the file.
 *               'error' -- The SOAP error if any.
 */
function get_note_attachment($session, $id)
{
    $error = new SoapError();
    if (!validate_authenticated($session)) {
        $error->set_error('invalid_login');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    $note = new Note();
    $note->retrieve($id);
    if (!$note->ACLAccess('DetailView')) {
        $error->set_error('no_access');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    require_once 'modules/Notes/NoteSoap.php';
    $ns = new NoteSoap();
    if (!isset($note->filename)) {
        $note->filename = '';
    }
    $file = $ns->retrieveFile($id, $note->filename);
    if ($file == -1) {
        $error->set_error('no_file');
        $file = '';
    }
    return array('note_attachment' => array('id' => $id, 'filename' => $note->filename, 'file' => $file), 'error' => $error->get_soap_array());
}
Пример #6
0
 /**
  * handles attachments of various kinds when sending email
  */
 function handleAttachments()
 {
     require_once 'modules/Documents/Document.php';
     require_once 'modules/DocumentRevisions/DocumentRevision.php';
     require_once 'modules/Notes/Note.php';
     global $mod_strings;
     ///////////////////////////////////////////////////////////////////////////
     ////    ATTACHMENTS FROM DRAFTS
     if (($this->type == 'out' || $this->type == 'draft') && $this->status == 'draft' && isset($_REQUEST['record'])) {
         $this->getNotes($_REQUEST['record']);
         // cn: get notes from OLD email for use in new email
     }
     ////    END ATTACHMENTS FROM DRAFTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////    ATTACHMENTS FROM FORWARDS
     // Bug 8034 Jenny - Need the check for type 'draft' here to handle cases where we want to save
     // forwarded messages as drafts.  We still need to save the original message's attachments.
     if (($this->type == 'out' || $this->type == 'draft') && isset($_REQUEST['origType']) && $_REQUEST['origType'] == 'forward' && isset($_REQUEST['return_id']) && !empty($_REQUEST['return_id'])) {
         $this->getNotes($_REQUEST['return_id'], true);
     }
     ////    END ATTACHMENTS FROM FORWARDS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM TEMPLATES
     // to preserve individual email integrity, we must dupe Notes and associated files
     // for each outbound email - good for integrity, bad for filespace
     if (isset($_REQUEST['template_attachment']) && !empty($_REQUEST['template_attachment'])) {
         $removeArr = array();
         $noteArray = array();
         if (isset($_REQUEST['temp_remove_attachment']) && !empty($_REQUEST['temp_remove_attachment'])) {
             $removeArr = $_REQUEST['temp_remove_attachment'];
         }
         foreach ($_REQUEST['template_attachment'] as $noteId) {
             if (in_array($noteId, $removeArr)) {
                 continue;
             }
             $noteTemplate = new Note();
             $noteTemplate->retrieve($noteId);
             $noteTemplate->id = create_guid();
             $noteTemplate->new_with_id = true;
             // duplicating the note with files
             $noteTemplate->parent_id = $this->id;
             $noteTemplate->parent_type = $this->module_dir;
             $noteTemplate->save();
             $noteFile = new UploadFile('none');
             $noteFile->duplicate_file($noteId, $noteTemplate->id, $noteTemplate->filename);
             $noteArray[] = $noteTemplate;
         }
         $this->attachments = array_merge($this->attachments, $noteArray);
     }
     ////	END ATTACHMENTS FROM TEMPLATES
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ADDING NEW ATTACHMENTS
     $max_files_upload = 10;
     // Jenny - Bug 8211 Since attachments for drafts have already been processed,
     // we don't need to re-process them.
     if ($this->status != "draft") {
         $notes_list = array();
         if (!empty($this->id) && !$this->new_with_id) {
             $note = new Note();
             $where = "notes.parent_id='{$this->id}'";
             $notes_list = $note->get_full_list("", $where, true);
         }
         $this->attachments = array_merge($this->attachments, $notes_list);
     }
     // cn: Bug 5995 - rudimentary error checking
     $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.');
     for ($i = 0; $i < $max_files_upload; $i++) {
         // cn: Bug 5995 - rudimentary error checking
         if ($_FILES['email_attachment' . $i]['error'] != 0 && $_FILES['email_attachment' . $i]['error'] != 4) {
             $GLOBALS['log']->fatal('Email Attachment could not be attach due to error: ' . $filesError[$_FILES['email_attachment' . $i]['error']]);
             continue;
         }
         $note = new Note();
         $note->parent_id = $this->id;
         $note->parent_type = $this->module_dir;
         $upload_file = new UploadFile('email_attachment' . $i);
         if (empty($upload_file)) {
             continue;
         }
         if (isset($_FILES['email_attachment' . $i]) && $upload_file->confirm_upload()) {
             $note->filename = $upload_file->get_stored_file_name();
             $note->file = $upload_file;
             $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ' . $note->file->original_file_name;
             $this->attachments[] = $note;
         }
     }
     $this->saved_attachments = array();
     foreach ($this->attachments as $note) {
         if (!empty($note->id)) {
             array_push($this->saved_attachments, $note);
             continue;
         }
         $note->parent_id = $this->id;
         $note->parent_type = 'Emails';
         $note->file_mime_type = $note->file->mime_type;
         $note_id = $note->save();
         $this->saved_attachments[] = $note;
         $note->id = $note_id;
         $note->file->final_move($note->id);
     }
     ////	END NEW ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM DOCUMENTS
     for ($i = 0; $i < 10; $i++) {
         if (isset($_REQUEST['documentId' . $i]) && !empty($_REQUEST['documentId' . $i])) {
             $doc = new Document();
             $docRev = new DocumentRevision();
             $docNote = new Note();
             $noteFile = new UploadFile('none');
             $doc->retrieve($_REQUEST['documentId' . $i]);
             $docRev->retrieve($doc->document_revision_id);
             $this->saved_attachments[] = $docRev;
             $docNote->name = $doc->document_name;
             $docNote->filename = $docRev->filename;
             $docNote->description = $doc->description;
             $docNote->parent_id = $this->id;
             $docNote->parent_type = 'Emails';
             $docNote->file_mime_type = $docRev->file_mime_type;
             $docId = $docNote = $docNote->save();
             $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
         }
     }
     ////	END ATTACHMENTS FROM DOCUMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	REMOVE ATTACHMENTS
     if (isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
         foreach ($_REQUEST['remove_attachment'] as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $this->db->query($q);
         }
     }
     ////	END REMOVE ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
 }
function portal_get_note_attachment($session, $id)
{
    $error = new SoapError();
    if (!portal_validate_authenticated($session)) {
        $error->set_error('invalid_session');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    if ($_SESSION['type'] == 'lead' || !isset($_SESSION['viewable']['Notes'][$id])) {
        $error->set_error('no_access');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    $current_user = $seed_user;
    $note = new Note();
    $note->retrieve($id);
    require_once 'modules/Notes/NoteSoap.php';
    $ns = new NoteSoap();
    if (!isset($note->filename)) {
        $note->filename = '';
    }
    $file = $ns->retrieveFile($id, $note->filename);
    if ($file == -1) {
        $error->set_error('no_file');
        $file = '';
    }
    return array('note_attachment' => array('id' => $id, 'filename' => $note->filename, 'file' => $file), 'error' => $error->get_soap_array());
}
 function handleSave($prefix, $redirect = true, $useRequired = false)
 {
     require_once 'include/formbase.php';
     require_once 'include/upload_file.php';
     global $upload_maxsize, $upload_dir;
     global $mod_strings;
     global $sugar_config;
     $focus = new EmailTemplate();
     if ($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))) {
         return null;
     }
     $focus = populateFromPost($prefix, $focus);
     //process the text only flag
     if (isset($_POST['text_only']) && $_POST['text_only'] == '1') {
         $focus->text_only = 1;
     } else {
         $focus->text_only = 0;
     }
     if (!$focus->ACLAccess('Save')) {
         ACLController::displayNoAccess(true);
         sugar_cleanup(true);
     }
     if (!isset($_REQUEST['published'])) {
         $focus->published = 'off';
     }
     $emailTemplateBodyHtml = from_html($focus->body_html);
     $fileBasePath = "{$sugar_config['cache_dir']}images/";
     $filePatternSearch = "{$sugar_config['cache_dir']}";
     $filePatternSearch = str_replace("/", "\\/", $filePatternSearch);
     $filePatternSearch = $filePatternSearch . "images\\/";
     $fileBasePath1 = "\"" . $fileBasePath;
     if (strpos($emailTemplateBodyHtml, "\"{$fileBasePath}")) {
         $matches = array();
         preg_match_all("/{$filePatternSearch}.+?\"/i", $emailTemplateBodyHtml, $matches);
         foreach ($matches[0] as $match) {
             $filenameUndecoded = str_replace($fileBasePath, '', $match);
             $filename = urldecode(substr($filenameUndecoded, 0, -1));
             $filenameUndecoded = str_replace("\"", '', $filenameUndecoded);
             $cid = $filename;
             $file_location = clean_path(getcwd() . "/{$sugar_config['cache_dir']}images/{$filename}");
             $mime_type = strtolower(substr($filename, strrpos($filename, ".") + 1, strlen($filename)));
             if (file_exists($file_location)) {
                 $id = create_guid();
                 $newFileLocation = "{$sugar_config['upload_dir']}{$id}.{$mime_type}";
                 if (!copy($file_location, $newFileLocation)) {
                     $GLOBALS['log']->debug("EMAIL Template could not copy attachment to {$sugar_config['upload_dir']} [ {$newFileLocation} ]");
                 } else {
                     $emailTemplateBodyHtml = str_replace("{$sugar_config['cache_dir']}images/{$filenameUndecoded}", $newFileLocation, $emailTemplateBodyHtml);
                     unlink($file_location);
                 }
             }
             // if
         }
         // foreach
     }
     // if
     $focus->body_html = $emailTemplateBodyHtml;
     $return_id = $focus->save();
     ///////////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////
     ////	ADDING NEW ATTACHMENTS
     $max_files_upload = count($_FILES);
     if (!empty($focus->id)) {
         $note = new Note();
         $where = "notes.parent_id='{$focus->id}'";
         if (!empty($_REQUEST['old_id'])) {
             // to support duplication of email templates
             $where .= " OR notes.parent_id='" . $_REQUEST['old_id'] . "'";
         }
         $notes_list = $note->get_full_list("", $where, true);
     }
     if (!isset($notes_list)) {
         $notes_list = array();
     }
     if (!is_array($focus->attachments)) {
         // PHP5 does not auto-create arrays(). Need to initialize it here.
         $focus->attachments = array();
     }
     $focus->attachments = array_merge($focus->attachments, $notes_list);
     //for($i = 0; $i < $max_files_upload; $i++) {
     foreach ($_FILES as $key => $file) {
         $note = new Note();
         $i = preg_replace("/email_attachment(.+)/", '$1', $key);
         $upload_file = new UploadFile($key);
         if ($upload_file == -1) {
             continue;
         }
         if (isset($_FILES[$key]) && $upload_file->confirm_upload() && preg_match("/^email_attachment/", $key)) {
             $note->filename = $upload_file->get_stored_file_name();
             $note->file = $upload_file;
             $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ' . $note->file->original_file_name;
             if (isset($_REQUEST['embedded' . $i]) && !empty($_REQUEST['embedded' . $i])) {
                 if ($_REQUEST['embedded' . $i] == 'true') {
                     $note->embed_flag = true;
                 } else {
                     $note->embed_flag = false;
                 }
             }
             array_push($focus->attachments, $note);
         }
     }
     $focus->saved_attachments = array();
     foreach ($focus->attachments as $note) {
         if (!empty($note->id)) {
             if (empty($_REQUEST['old_id'])) {
                 // to support duplication of email templates
                 array_push($focus->saved_attachments, $note);
             } else {
                 // we're duplicating a template with attachments
                 // dupe the file, create a new note, assign the note to the new template
                 $newNote = new Note();
                 $newNote->retrieve($note->id);
                 $newNote->id = create_guid();
                 $newNote->parent_id = $focus->id;
                 $newNote->new_with_id = true;
                 $newNote->date_modified = '';
                 $newNote->date_entered = '';
                 $newNoteId = $newNote->save();
                 $dupeFile = new UploadFile('duplicate');
                 $dupeFile->duplicate_file($note->id, $newNoteId, $note->filename);
             }
             continue;
         }
         $note->parent_id = $focus->id;
         $note->parent_type = 'Emails';
         $note->file_mime_type = $note->file->mime_type;
         $note_id = $note->save();
         array_push($focus->saved_attachments, $note);
         $note->id = $note_id;
         $note->file->final_move($note->id);
     }
     ////	END NEW ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM DOCUMENTS
     $count = '';
     //_pp($_REQUEST);
     //_ppd(count($_REQUEST['document']));
     if (!empty($_REQUEST['document'])) {
         $count = count($_REQUEST['document']);
     } else {
         $count = 10;
     }
     for ($i = 0; $i < $count; $i++) {
         if (isset($_REQUEST['documentId' . $i]) && !empty($_REQUEST['documentId' . $i])) {
             $doc = new Document();
             $docRev = new DocumentRevision();
             $docNote = new Note();
             $noteFile = new UploadFile('none');
             $doc->retrieve($_REQUEST['documentId' . $i]);
             $docRev->retrieve($doc->document_revision_id);
             array_push($focus->saved_attachments, $docRev);
             $docNote->name = $doc->document_name;
             $docNote->filename = $docRev->filename;
             $docNote->description = $doc->description;
             $docNote->parent_id = $focus->id;
             $docNote->parent_type = 'Emails';
             $docNote->file_mime_type = $docRev->file_mime_type;
             $docId = $docNote = $docNote->save();
             $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
         }
     }
     ////	END ATTACHMENTS FROM DOCUMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	REMOVE ATTACHMENTS
     if (isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
         foreach ($_REQUEST['remove_attachment'] as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $focus->db->query($q);
         }
     }
     ////	END REMOVE ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ////	END ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////////
     if ($redirect) {
         $GLOBALS['log']->debug("Saved record with id of " . $return_id);
         handleRedirect($return_id, "EmailTemplates");
     } else {
         return $focus;
     }
 }
Пример #9
0
 function sendEmail($mail, $testmode = false)
 {
     $this->test = $testmode;
     global $beanList, $beanFiles, $sugar_config;
     global $mod_strings;
     $mod_strings = return_module_language($sugar_config['default_language'], 'EmailMan');
     //get tracking entities locations.
     if (!isset($this->tracking_url)) {
         if (!class_exists('Administration')) {
             require_once 'modules/Administration/Administration.php';
         }
         $admin = new Administration();
         $admin->retrieveSettings('massemailer');
         //retrieve all admin settings.
         if (isset($admin->settings['massemailer_tracking_entities_location_type']) and $admin->settings['massemailer_tracking_entities_location_type'] == '2' and isset($admin->settings['massemailer_tracking_entities_location'])) {
             $this->tracking_url = $admin->settings['massemailer_tracking_entities_location'];
         } else {
             $this->tracking_url = $sugar_config['site_url'];
         }
     }
     if (!isset($beanList[$this->related_type])) {
         return false;
     }
     $class = $beanList[$this->related_type];
     if (!class_exists($class)) {
         require_once $beanFiles[$class];
     }
     if (!class_exists('Email')) {
         require_once 'modules/Emails/Email.php';
     }
     $module = new $class();
     $module->retrieve($this->related_id);
     if ((!isset($module->email_opt_out) || $module->email_opt_out != 'on') && (!isset($module->invalid_email) || $module->invalid_email != 1)) {
         $lower_email_address = strtolower($module->email1);
         //test against indivdual address.
         if (isset($this->restricted_addresses) and isset($this->restricted_addresses[$lower_email_address])) {
             $this->set_as_sent($lower_email_address, true, true, null, null, null, true);
             return true;
         }
         //test against restricted domains
         $at_pos = strrpos($lower_email_address, '@');
         if ($at_pos !== false) {
             foreach ($this->restricted_domains as $domain => $value) {
                 $pos = strrpos($lower_email_address, $domain);
                 if ($pos !== false && $pos > $at_pos) {
                     //found
                     $this->set_as_sent($lower_email_address, true, true, null, null, null, true);
                     return true;
                 }
             }
         }
         //test for duplicate email address.
         if (!empty($module->email1) and !empty($this->campaign_id)) {
             $dup_query = "select id from campaign_log where more_information='" . $module->email1 . "' and campaign_id='" . $this->campaign_id . "'";
             $dup = $this->db->query($dup_query);
             $dup_row = $this->db->fetchByAssoc($dup);
             if (!empty($dup_row)) {
                 //email address was processed //silent delete this entry.
                 $this->set_as_sent($module->email1, true, true, null, null, null, true);
                 return true;
             }
         }
         $start = microtime();
         $this->target_tracker_key = create_guid();
         //fetch email marketing.
         if (empty($this->current_emailmarketing) or !isset($this->current_emailmarketing)) {
             if (!class_exists('EmailMarketing')) {
                 require_once 'modules/EmailMarketing/EmailMarketing.php';
             }
             $this->current_emailmarketing = new EmailMarketing();
         }
         if (empty($this->current_emailmarketing->id) or $this->current_emailmarketing->id !== $this->marketing_id) {
             $this->current_emailmarketing->retrieve($this->marketing_id);
         }
         //fetch email template associate with the marketing message.
         if (empty($this->current_emailtemplate) or $this->current_emailtemplate->id !== $this->current_emailmarketing->template_id) {
             if (!class_exists('EmailTemplate')) {
                 require_once 'modules/EmailTemplates/EmailTemplate.php';
             }
             $this->current_emailtemplate = new EmailTemplate();
             $this->current_emailtemplate->retrieve($this->current_emailmarketing->template_id);
             //escape email template contents.
             $this->current_emailtemplate->subject = from_html($this->current_emailtemplate->subject);
             $this->current_emailtemplate->body_html = from_html($this->current_emailtemplate->body_html);
             $this->current_emailtemplate->body = from_html($this->current_emailtemplate->body);
             $q = "SELECT * FROM notes WHERE parent_id = '" . $this->current_emailtemplate->id . "' AND deleted = 0";
             $r = $this->db->query($q);
             // cn: bug 4684 - initialize the notes array, else old data is still around for the next round
             $this->notes_array = array();
             while ($a = $this->db->fetchByAssoc($r)) {
                 $noteTemplate = new Note();
                 $noteTemplate->retrieve($a['id']);
                 $this->notes_array[] = $noteTemplate;
             }
         }
         //fetch mailbox details..
         if (empty($this->current_mailbox)) {
             if (!class_exists('InboundEmail')) {
                 require_once 'modules/InboundEmail/InboundEmail.php';
             }
             $this->current_mailbox = new InboundEmail();
         }
         if (empty($this->current_mailbox->id) or $this->current_mailbox->id !== $this->current_emailmarketing->inbound_email_id) {
             $this->current_mailbox->retrieve($this->current_emailmarketing->inbound_email_id);
             //extract the email address.
             $this->mailbox_from_addr = $this->current_mailbox->get_stored_options('from_addr', '*****@*****.**', null);
         }
         //fetch campaign  details..
         if (empty($this->current_campaign)) {
             if (!class_exists('Campaign')) {
                 require_once 'modules/Campaigns/Campaign.php';
             }
             $this->current_campaign = new Campaign();
         }
         if (empty($this->current_campaign->id) or $this->current_campaign->id !== $this->current_emailmarketing->campaign_id) {
             $this->current_campaign->retrieve($this->current_emailmarketing->campaign_id);
             //load defined tracked_urls
             $this->current_campaign->load_relationship('tracked_urls');
             $query_array = $this->current_campaign->tracked_urls->getQuery(true);
             $query_array['select'] = "SELECT tracker_name, tracker_key, id, is_optout ";
             $result = $this->current_campaign->db->query(implode(' ', $query_array));
             $this->has_optout_links = false;
             while (($row = $this->current_campaign->db->fetchByAssoc($result)) != null) {
                 $this->tracker_urls['{' . $row['tracker_name'] . '}'] = $row;
                 //has the user defined opt-out links for the campaign.
                 if ($row['is_optout'] == 1) {
                     $this->has_optout_links = true;
                 }
             }
         }
         //BEGIN:this code will trigger for only campaigns pending before upgrade to 4.2.0.
         //will be removed for the next release.
         $btracker = true;
         $tracker_url = $this->tracking_url . '/campaign_tracker.php?track=' . $this->current_campaign->tracker_key . '&identifier=' . $this->target_tracker_key;
         $tracker_text = $this->current_campaign->tracker_text;
         if (empty($tracker_text)) {
             $btracker = false;
         }
         //END
         $mail->ClearAllRecipients();
         $mail->ClearReplyTos();
         $mail->Sender = $this->mailbox_from_addr;
         $mail->From = $this->mailbox_from_addr;
         $mail->FromName = $this->current_emailmarketing->from_name;
         $mail->AddReplyTo($this->mailbox_from_addr, $this->current_emailmarketing->from_name);
         //parse and replace bean variables.
         $template_data = $this->current_emailtemplate->parse_email_template(array('subject' => $this->current_emailtemplate->subject, 'body_html' => $this->current_emailtemplate->body_html, 'body' => $this->current_emailtemplate->body), 'Contacts', $module);
         //parse and replace urls.
         //this is new style of adding tracked urls to a campaign.
         $tracker_url_template = $this->tracking_url . '/campaign_trackerv2.php?track=%s' . '&identifier=' . $this->target_tracker_key;
         $removeme_url_template = $this->tracking_url . '/removeme.php?identifier=' . $this->target_tracker_key;
         $template_data = $this->current_emailtemplate->parse_tracker_urls($template_data, $tracker_url_template, $this->tracker_urls, $removeme_url_template);
         $mail->AddAddress($module->email1, $module->first_name . ' ' . $module->last_name);
         $mail->Subject = $template_data['subject'];
         $mail->Body = wordwrap($template_data['body_html'], 900);
         //BEGIN:this code will trigger for only campaigns pending before upgrade to 4.2.0.
         //will be removed for the next release.
         if ($btracker) {
             $mail->Body .= "<br><br><a href='" . $tracker_url . "'>" . $tracker_text . "</a><br><br>";
         } else {
             if (!empty($tracker_url)) {
                 $mail->Body = str_replace('TRACKER_URL_START', "<a href='" . $tracker_url . "'>", $mail->Body);
                 $mail->Body = str_replace('TRACKER_URL_END', "</a>", $mail->Body);
                 $mail->AltBody = str_replace('TRACKER_URL_START', "<a href='" . $tracker_url . "'>", $mail->AltBody);
                 $mail->AltBody = str_replace('TRACKER_URL_END', "</a>", $mail->AltBody);
             }
         }
         //END
         //do not add the default remove me link if the campaign has a trackerurl of the opotout link
         if ($this->has_optout_links == false) {
             $mail->Body .= "<br><font size='2'>{$mod_strings['TXT_REMOVE_ME']}<a href='" . $this->tracking_url . "/removeme.php?identifier={$this->target_tracker_key}'>{$mod_strings['TXT_REMOVE_ME_CLICK']}</a></font>";
         }
         //add image reference to track opening of html emails.
         $mail->Body .= "<br><IMG HEIGHT=1 WIDTH=1 src={$this->tracking_url}/image.php?identifier={$this->target_tracker_key}>";
         $mail->AltBody = $template_data['body'];
         if ($btracker) {
             $mail->AltBody .= "\n" . $tracker_url;
         }
         if ($this->has_optout_links == false) {
             $mail->AltBody .= "\n\n\n{$mod_strings['TXT_REMOVE_ME_ALT']} " . $this->tracking_url . "/removeme.php?identifier={$this->target_tracker_key}";
         }
         // cn: bug 4684, handle attachments in email templates.
         $mail->handleAttachments($this->notes_array);
         $success = $mail->send();
         if ($success) {
             $email = new Email();
             $email->to_addrs = $module->first_name . ' ' . $module->last_name . '&lt;' . $module->email1 . '&gt;';
             $email->to_addrs_ids = $module->id . ';';
             $email->to_addrs_names = $module->first_name . ' ' . $module->last_name . ';';
             $email->to_addrs_emails = $module->email1 . ';';
             $email->type = 'archived';
             $email->deleted = '0';
             $email->name = $this->current_campaign->name . ': ' . $mail->Subject;
             $email->description_html = $mail->AltBody;
             $email->description = $mail->AltBody;
             $email->from_addr = $mail->From;
             $email->assigned_user_id = $this->user_id;
             $email->parent_type = $this->related_type;
             $email->parent_id = $this->related_id;
             $email->date_start = date('Y-m-d');
             $email->time_start = date('H:i:s');
             $email->status = 'sent';
             $retId = $email->save();
             foreach ($this->notes_array as $note) {
                 if (!class_exists('Note')) {
                     require_once 'modules/Notes/Note.php';
                 }
                 // create "audit" email without duping off the file to save on disk space
                 $noteAudit = new Note();
                 $noteAudit->parent_id = $retId;
                 $noteAudit->parent_type = $email->module_dir;
                 $noteAudit->description = "[" . $note->filename . "] " . $mod_strings['LBL_ATTACHMENT_AUDIT'];
                 $noteAudit->save();
             }
             if (!empty($this->related_id) && !empty($this->related_type)) {
                 //save relationships.
                 switch ($this->related_type) {
                     case 'Users':
                         $rel_name = "users";
                         break;
                     case 'Prospects':
                         $rel_name = "prospects";
                         break;
                     case 'Contacts':
                         $rel_name = "contacts";
                         break;
                     case 'Leads':
                         $rel_name = "leads";
                         break;
                 }
                 if (!empty($rel_name)) {
                     $email->load_relationship($rel_name);
                     $email->{$rel_name}->add($this->related_id);
                 }
             }
         }
         if ($success) {
             $this->set_as_sent($module->email1, $success, $success, $email->id, 'Emails', 'targeted');
         } else {
             //log send error.
             $this->set_as_sent($module->email1, $success, $success);
         }
     } else {
         $mail->ErrorInfo .= "\nRecipient Email Opt Out";
         $success = false;
         if (isset($module->email_opt_out) && $module->email_opt_out == 'on') {
             $this->set_as_sent($module->email1, $success, true, null, null, 'removed');
         } else {
             if (isset($module->invalid_email) && $module->invalid_email == 1) {
                 $this->set_as_sent($module->email1, $success, true, null, null, 'invalid email');
             } else {
                 $this->set_as_sent($module->email1, $success, true);
             }
         }
     }
     return $success;
 }
Пример #10
0
 public function handleAttachments($focus, $redirect, $return_id)
 {
     ///////////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////
     ////	ADDING NEW ATTACHMENTS
     global $mod_strings;
     $max_files_upload = count($_FILES);
     if (!empty($focus->id)) {
         $note = new Note();
         $where = "notes.parent_id='{$focus->id}'";
         if (!empty($_REQUEST['old_id'])) {
             // to support duplication of email templates
             $where .= " OR notes.parent_id='" . htmlspecialchars($_REQUEST['old_id'], ENT_QUOTES) . "'";
         }
         $notes_list = $note->get_full_list("", $where, true);
     }
     if (!isset($notes_list)) {
         $notes_list = array();
     }
     if (!is_array($focus->attachments)) {
         // PHP5 does not auto-create arrays(). Need to initialize it here.
         $focus->attachments = array();
     }
     $focus->attachments = array_merge($focus->attachments, $notes_list);
     //for($i = 0; $i < $max_files_upload; $i++) {
     foreach ($_FILES as $key => $file) {
         $note = new Note();
         //Images are presaved above so we need to prevent duplicate files from being created.
         if (isset($preProcessedImages[$file['name']])) {
             $oldId = $preProcessedImages[$file['name']];
             $note->id = $oldId;
             $note->new_with_id = TRUE;
             $GLOBALS['log']->debug("Image {$file['name']} has already been processed.");
         }
         $i = preg_replace("/email_attachment(.+)/", '$1', $key);
         $upload_file = new UploadFile($key);
         if (isset($_FILES[$key]) && $upload_file->confirm_upload() && preg_match("/^email_attachment/", $key)) {
             $note->filename = $upload_file->get_stored_file_name();
             $note->file = $upload_file;
             $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ' . $note->file->original_file_name;
             if (isset($_REQUEST['embedded' . $i]) && !empty($_REQUEST['embedded' . $i])) {
                 if ($_REQUEST['embedded' . $i] == 'true') {
                     $note->embed_flag = true;
                 } else {
                     $note->embed_flag = false;
                 }
             }
             array_push($focus->attachments, $note);
         }
     }
     $focus->saved_attachments = array();
     foreach ($focus->attachments as $note) {
         if (!empty($note->id) && $note->new_with_id === FALSE) {
             if (empty($_REQUEST['old_id'])) {
                 array_push($focus->saved_attachments, $note);
             } else {
                 // we're duplicating a template with attachments
                 // dupe the file, create a new note, assign the note to the new template
                 $newNote = new Note();
                 $newNote->retrieve($note->id);
                 $newNote->id = create_guid();
                 $newNote->parent_id = $focus->id;
                 $newNote->new_with_id = true;
                 $newNote->date_modified = '';
                 $newNote->date_entered = '';
                 /* BEGIN - SECURITY GROUPS */
                 //Need to do this so that attachments show under an EmailTemplate correctly for a normal user
                 global $current_user;
                 $newNote->assigned_user_id = $current_user->id;
                 /* END - SECURITY GROUPS */
                 $newNoteId = $newNote->save();
                 UploadFile::duplicate_file($note->id, $newNoteId, $note->filename);
             }
             continue;
         }
         $note->parent_id = $focus->id;
         $note->parent_type = 'Emails';
         $note->file_mime_type = $note->file->mime_type;
         /* BEGIN - SECURITY GROUPS */
         //Need to do this so that attachments show under an EmailTemplate correctly for a normal user
         global $current_user;
         $note->assigned_user_id = $current_user->id;
         /* END - SECURITY GROUPS */
         $note_id = $note->save();
         array_push($focus->saved_attachments, $note);
         $note->id = $note_id;
         if ($note->new_with_id === FALSE) {
             $note->file->final_move($note->id);
         } else {
             $GLOBALS['log']->debug("Not performing final move for note id {$note->id} as it has already been processed");
         }
     }
     ////	END NEW ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM DOCUMENTS
     $count = '';
     //_pp($_REQUEST);
     //_ppd(count($_REQUEST['document']));
     if (!empty($_REQUEST['document'])) {
         $count = count($_REQUEST['document']);
     } else {
         $count = 10;
     }
     for ($i = 0; $i < $count; $i++) {
         if (isset($_REQUEST['documentId' . $i]) && !empty($_REQUEST['documentId' . $i])) {
             $doc = new Document();
             $docRev = new DocumentRevision();
             $docNote = new Note();
             $doc->retrieve($_REQUEST['documentId' . $i]);
             $docRev->retrieve($doc->document_revision_id);
             array_push($focus->saved_attachments, $docRev);
             $docNote->name = $doc->document_name;
             $docNote->filename = $docRev->filename;
             $docNote->description = $doc->description;
             $docNote->parent_id = $focus->id;
             $docNote->parent_type = 'Emails';
             $docNote->file_mime_type = $docRev->file_mime_type;
             $docId = $docNote = $docNote->save();
             UploadFile::duplicate_file($docRev->id, $docId, $docRev->filename);
         }
     }
     ////	END ATTACHMENTS FROM DOCUMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	REMOVE ATTACHMENTS
     if (isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
         foreach ($_REQUEST['remove_attachment'] as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $focus->db->query($q);
         }
     }
     ////	END REMOVE ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ////	END ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////////
     clear_register_value('select_array', $focus->object_name);
     if ($redirect) {
         $GLOBALS['log']->debug("Saved record with id of " . $return_id);
         handleRedirect($return_id, "EmailTemplates");
     } else {
         return $focus;
     }
 }
 function handleSave($prefix, $redirect = true, $useRequired = false)
 {
     require_once 'modules/EmailTemplates/EmailTemplate.php';
     require_once 'modules/Documents/Document.php';
     require_once 'modules/DocumentRevisions/DocumentRevision.php';
     require_once 'modules/Notes/Note.php';
     require_once 'include/formbase.php';
     require_once 'include/upload_file.php';
     global $upload_maxsize, $upload_dir;
     global $mod_strings;
     $focus = new EmailTemplate();
     if ($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))) {
         return null;
     }
     $focus = populateFromPost($prefix, $focus);
     if (!$focus->ACLAccess('Save')) {
         ACLController::displayNoAccess(true);
         sugar_cleanup(true);
     }
     if (!isset($_REQUEST['published'])) {
         $focus->published = 'off';
     }
     $return_id = $focus->save();
     ///////////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////
     ////	ADDING NEW ATTACHMENTS
     $max_files_upload = 10;
     if (!empty($focus->id)) {
         $note = new Note();
         $where = "notes.parent_id='{$focus->id}'";
         if (!empty($_REQUEST['old_id'])) {
             // to support duplication of email templates
             $where .= " OR notes.parent_id='" . $_REQUEST['old_id'] . "'";
         }
         $notes_list = $note->get_full_list("", $where, true);
     }
     if (!isset($notes_list)) {
         $notes_list = array();
     }
     if (!is_array($focus->attachments)) {
         // PHP5 does not auto-create arrays(). Need to initialize it here.
         $focus->attachments = array();
     }
     $focus->attachments = array_merge($focus->attachments, $notes_list);
     for ($i = 0; $i < $max_files_upload; $i++) {
         $note = new Note();
         $upload_file = new UploadFile('email_attachment' . $i);
         if ($upload_file == -1) {
             continue;
         }
         if (isset($_FILES['email_attachment' . $i]) && $upload_file->confirm_upload()) {
             $note->filename = $upload_file->get_stored_file_name();
             $note->file = $upload_file;
             $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ' . $note->file->original_file_name;
             array_push($focus->attachments, $note);
         }
     }
     $focus->saved_attachments = array();
     foreach ($focus->attachments as $note) {
         if (!empty($note->id)) {
             if (empty($_REQUEST['old_id'])) {
                 // to support duplication of email templates
                 array_push($focus->saved_attachments, $note);
             } else {
                 // we're duplicating a template with attachments
                 // dupe the file, create a new note, assign the note to the new template
                 $newNote = new Note();
                 $newNote->retrieve($note->id);
                 $newNote->id = create_guid();
                 $newNote->parent_id = $focus->id;
                 $newNote->new_with_id = true;
                 $newNoteId = $newNote->save();
                 $dupeFile = new UploadFile('duplicate');
                 $dupeFile->duplicate_file($note->id, $newNoteId, $note->filename);
             }
             continue;
         }
         $note->parent_id = $focus->id;
         $note->parent_type = 'Emails';
         $note->file_mime_type = $note->file->mime_type;
         $note_id = $note->save();
         array_push($focus->saved_attachments, $note);
         $note->id = $note_id;
         $note->file->final_move($note->id);
     }
     ////	END NEW ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM DOCUMENTS
     for ($i = 0; $i < 10; $i++) {
         if (isset($_REQUEST['documentId' . $i]) && !empty($_REQUEST['documentId' . $i])) {
             $doc = new Document();
             $docRev = new DocumentRevision();
             $docNote = new Note();
             $noteFile = new UploadFile('none');
             $doc->retrieve($_REQUEST['documentId' . $i]);
             $docRev->retrieve($doc->document_revision_id);
             array_push($focus->saved_attachments, $docRev);
             $docNote->name = $doc->document_name;
             $docNote->filename = $docRev->filename;
             $docNote->description = $doc->description;
             $docNote->parent_id = $focus->id;
             $docNote->parent_type = 'Emails';
             $docNote->file_mime_type = $docRev->file_mime_type;
             $docId = $docNote = $docNote->save();
             $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
         }
     }
     ////	END ATTACHMENTS FROM DOCUMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	REMOVE ATTACHMENTS
     if (isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
         foreach ($_REQUEST['remove_attachment'] as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $focus->db->query($q);
         }
     }
     ////	END REMOVE ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ////	END ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////////
     if ($redirect) {
         $GLOBALS['log']->debug("Saved record with id of " . $return_id);
         handleRedirect($return_id, "EmailTemplates");
     } else {
         return $focus;
     }
 }
Пример #12
0
 /**
  * @param notes	array of note beans
  */
 function handleAttachments($notes)
 {
     global $sugar_config;
     //replace references to cache/images with cid tag
     $this->Body = str_replace($GLOBALS['sugar_config']['cache_dir'] . 'images/', 'cid:', $this->Body);
     if (empty($notes)) {
         return;
     }
     // cn: bug 4864 - reusing same SugarPHPMailer class, need to clear attachments
     $this->ClearAttachments();
     require_once 'include/upload_file.php';
     //Handle legacy attachments
     $fileBasePath = "{$sugar_config['upload_dir']}";
     $filePatternSearch = "{$sugar_config['upload_dir']}";
     $filePatternSearch = str_replace("/", "\\/", $filePatternSearch);
     if (strpos($this->Body, "\"{$fileBasePath}")) {
         $matches = array();
         preg_match_all("/{$filePatternSearch}.+?\"/i", $this->Body, $matches);
         foreach ($matches[0] as $match) {
             $filename = str_replace($fileBasePath, '', $match);
             $filename = urldecode(substr($filename, 0, -1));
             $cid = $filename;
             $file_location = clean_path(getcwd() . "/{$sugar_config['upload_dir']}{$filename}");
             $mime_type = "image/" . strtolower(substr($filename, strrpos($filename, ".") + 1, strlen($filename)));
             if (file_exists($file_location)) {
                 $this->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
             }
         }
         //replace references to cache with cid tag
         $this->Body = str_replace($fileBasePath, 'cid:', $this->Body);
     }
     //Handle secure embeded images.
     $noteImgRegex = "/<img[^>]*[\\s]+src[^=]*=\"index.php\\?entryPoint=download(\\&amp;|\\&)id=([^\\&]*)[^>]*>/im";
     $embededImageMatches = array();
     preg_match_all($noteImgRegex, $this->Body, $embededImageMatches, PREG_SET_ORDER);
     foreach ($embededImageMatches as $singleMatch) {
         $fullMatch = $singleMatch[0];
         $noteId = $singleMatch[2];
         $cid = $noteId;
         $filename = $noteId;
         //Retrieve note for mimetype
         $tmpNote = new Note();
         $tmpNote->retrieve($noteId);
         //Replace the src part of img tag with new cid tag
         $cidRegex = "/src=\"([^\"]*)\"/im";
         $replaceMatch = preg_replace($cidRegex, "src=\"cid:{$noteId}\"", $fullMatch);
         //Replace the body, old tag for new tag
         $this->Body = str_replace($fullMatch, $replaceMatch, $this->Body);
         //Attach the file
         $file_location = clean_path(getcwd() . "/{$sugar_config['upload_dir']}{$noteId}");
         if (file_exists($file_location)) {
             $this->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $tmpNote->file_mime_type);
         }
     }
     //Handle regular attachments.
     foreach ($notes as $note) {
         $mime_type = 'text/plain';
         $file_location = '';
         $filename = '';
         if ($note->object_name == 'Note') {
             if (!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) {
                 $file_location = $note->file->temp_file_location;
                 $filename = $note->file->original_file_name;
                 $mime_type = $note->file->mime_type;
             } else {
                 $file_location = rawurldecode(UploadFile::get_file_path($note->filename, $note->id));
                 $filename = $note->id . $note->filename;
                 $mime_type = $note->file_mime_type;
             }
         } elseif ($note->object_name == 'DocumentRevision') {
             // from Documents
             $filename = $note->id . $note->filename;
             $file_location = getcwd() . '/' . $GLOBALS['sugar_config']['upload_dir'] . $filename;
             $mime_type = $note->file_mime_type;
         }
         $filename = substr($filename, 36, strlen($filename));
         // strip GUID	for PHPMailer class to name outbound file
         if (!$note->embed_flag) {
             $this->AddAttachment($file_location, $filename, 'base64', $mime_type);
         }
         // else
     }
 }
/**
 * Retrieve an attachment from a note
 * @param String $session -- Session ID returned by a previous call to login.
 * @param String $id -- The ID of the appropriate Note.
 * @return Array 'note_attachment' -- Array String 'id' -- The ID of the Note containing the attachment
 *                                          String 'filename' -- The file name of the attachment
 *                                          Binary 'file' -- The binary contents of the file.
 * 											String 'related_module_id' -- module id to which this note is related
 * 											String 'related_module_name' - module name to which this note is related
 * @exception 'SoapFault' -- The SOAP error, if any
 */
function new_get_note_attachment($session, $id)
{
    $error = new SoapError();
    if (!checkSessionAndModuleAccess($session, 'invalid_session', '', '', '', $error)) {
        return;
    }
    // if
    $note = new Note();
    $note->retrieve($id);
    if (!checkACLAccess($note, 'DetailView', $error, 'no_access')) {
        return;
    }
    // if
    require_once 'modules/Notes/NoteSoap.php';
    $ns = new NoteSoap();
    if (!isset($note->filename)) {
        $note->filename = '';
    }
    $file = $ns->retrieveFile($id, $note->filename);
    if ($file == -1) {
        $file = '';
    }
    return array('note_attachment' => array('id' => $id, 'filename' => $note->filename, 'file' => $file, 'related_module_id' => $note->parent_id, 'related_module_name' => $note->parent_type));
}
Пример #14
0
 /**
  * Retrieve function from handlebody() to unit test easily
  * @param $mail
  * @return formatted $mail body
  */
 function handleBodyInHTMLformat($mail)
 {
     global $current_user;
     global $sugar_config;
     // wp: if body is html, then insert new lines at 996 characters. no effect on client side
     // due to RFC 2822 which limits email lines to 998
     $mail->IsHTML(true);
     $body = from_html(wordwrap($this->description_html, 996));
     $mail->Body = $body;
     // cn: bug 9725
     // new plan is to use the selected type (html or plain) to fill the other
     $plainText = from_html($this->description_html);
     $plainText = strip_tags(br2nl($plainText));
     $mail->AltBody = $plainText;
     $this->description = $plainText;
     $fileBasePath = "{$sugar_config['cache_dir']}images/";
     $filePatternSearch = "{$sugar_config['cache_dir']}";
     $filePatternSearch = str_replace("/", "\\/", $filePatternSearch);
     $filePatternSearch = $filePatternSearch . "images\\/";
     if (strpos($mail->Body, "\"{$fileBasePath}") !== FALSE) {
         //cache/images
         $matches = array();
         preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
         foreach ($matches[0] as $match) {
             $filename = str_replace($fileBasePath, '', $match);
             $filename = urldecode(substr($filename, 0, -1));
             $cid = $filename;
             $file_location = clean_path(getcwd() . "/{$sugar_config['cache_dir']}images/{$filename}");
             $mime_type = "image/" . strtolower(substr($filename, strrpos($filename, ".") + 1, strlen($filename)));
             if (file_exists($file_location)) {
                 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
             }
         }
         //replace references to cache with cid tag
         $mail->Body = str_replace("/" . $fileBasePath, 'cid:', $mail->Body);
         $mail->Body = str_replace($fileBasePath, 'cid:', $mail->Body);
         // remove bad img line from outbound email
         $regex = '#<img[^>]+src[^=]*=\\"\\/([^>]*?[^>]*)>#sim';
         $mail->Body = preg_replace($regex, '', $mail->Body);
     }
     $fileBasePath = "{$sugar_config['upload_dir']}";
     $filePatternSearch = "{$sugar_config['upload_dir']}";
     $filePatternSearch = str_replace("/", "\\/", $filePatternSearch);
     if (strpos($mail->Body, "\"{$fileBasePath}") !== FALSE) {
         $matches = array();
         preg_match_all("/{$filePatternSearch}.+?\"/i", $mail->Body, $matches);
         foreach ($matches[0] as $match) {
             $filename = str_replace($fileBasePath, '', $match);
             $filename = urldecode(substr($filename, 0, -1));
             $cid = $filename;
             $file_location = clean_path(getcwd() . "/{$sugar_config['upload_dir']}{$filename}");
             $mime_type = "image/" . strtolower(substr($filename, strrpos($filename, ".") + 1, strlen($filename)));
             if (file_exists($file_location)) {
                 $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
             }
         }
         //replace references to cache with cid tag
         $mail->Body = str_replace("/" . $fileBasePath, 'cid:', $mail->Body);
         $mail->Body = str_replace($fileBasePath, 'cid:', $mail->Body);
         // remove bad img line from outbound email
         $regex = '#<img[^>]+src[^=]*=\\"\\/([^>]*?[^>]*)>#sim';
         $mail->Body = preg_replace($regex, '', $mail->Body);
     }
     //Replace any embeded images using the secure entryPoint for src url.
     $noteImgRegex = "/<img[^>]*[\\s]+src[^=]*=\"index.php\\?entryPoint=download\\&amp;id=([^\\&]*)[^>]*>/im";
     $embededImageMatches = array();
     preg_match_all($noteImgRegex, $mail->Body, $embededImageMatches, PREG_SET_ORDER);
     foreach ($embededImageMatches as $singleMatch) {
         $fullMatch = $singleMatch[0];
         $noteId = $singleMatch[1];
         $cid = $noteId;
         $filename = $noteId;
         //Retrieve note for mimetype
         $tmpNote = new Note();
         $tmpNote->retrieve($noteId);
         //Replace the src part of img tag with new cid tag
         $cidRegex = "/src=\"([^\"]*)\"/im";
         $replaceMatch = preg_replace($cidRegex, "src=\"cid:{$noteId}\"", $fullMatch);
         //Replace the body, old tag for new tag
         $mail->Body = str_replace($fullMatch, $replaceMatch, $mail->Body);
         //Attach the file
         $file_location = clean_path(getcwd() . "/{$sugar_config['upload_dir']}{$noteId}");
         if (file_exists($file_location)) {
             $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $tmpNote->file_mime_type);
         }
     }
     //End Replace
     $mail->Body = from_html($mail->Body);
 }
Пример #15
0
 * Description: TODO:  To be written.
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 ********************************************************************************/
require_once 'XTemplate/xtpl.php';
require_once 'data/Tracker.php';
require_once 'modules/Notes/Note.php';
require_once 'modules/Notes/Forms.php';
global $app_strings;
global $app_list_strings;
global $mod_strings;
global $sugar_version, $sugar_config;
$focus = new Note();
if (isset($_REQUEST['record'])) {
    $focus->retrieve($_REQUEST['record']);
}
$old_id = '';
if (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
    if (!empty($focus->filename)) {
        $old_id = $focus->id;
    }
    $focus->id = "";
}
if (isset($_REQUEST['name'])) {
    $focus->name = $_REQUEST['name'];
}
if (isset($_REQUEST['description'])) {
    $focus->description = $_REQUEST['description'];
}
//setting default flag value so due date and time not required
Пример #16
0
 /**
  * Retrieve an attachment from a note
  * @param String $session -- Session ID returned by a previous call to login.
  * @param String $id -- The ID of the appropriate Note.
  * @return Array 'note_attachment' -- Array String 'id' -- The ID of the Note containing the attachment
  *                                          String 'filename' -- The file name of the attachment
  *                                          Binary 'file' -- The binary contents of the file.
  * 											String 'related_module_id' -- module id to which this note is related
  * 											String 'related_module_name' - module name to which this note is related
  * @exception 'SoapFault' -- The SOAP error, if any
  */
 function get_note_attachment($session, $id)
 {
     $GLOBALS['log']->info('Begin: SugarWebServiceImpl->get_note_attachment');
     $error = new SoapError();
     if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', '', '', $error)) {
         $GLOBALS['log']->info('End: SugarWebServiceImpl->get_note_attachment');
         return;
     }
     // if
     require_once 'modules/Notes/Note.php';
     $note = new Note();
     $note->retrieve($id);
     if (!self::$helperObject->checkACLAccess($note, 'DetailView', $error, 'no_access')) {
         $GLOBALS['log']->info('End: SugarWebServiceImpl->get_note_attachment');
         return;
     }
     // if
     require_once 'modules/Notes/NoteSoap.php';
     $ns = new NoteSoap();
     if (!isset($note->filename)) {
         $note->filename = '';
     }
     $file = $ns->retrieveFile($id, $note->filename);
     if ($file == -1) {
         $file = '';
     }
     $GLOBALS['log']->info('End: SugarWebServiceImpl->get_note_attachment');
     return array('note_attachment' => array('id' => $id, 'filename' => $note->filename, 'file' => $file, 'related_module_id' => $note->parent_id, 'related_module_name' => $note->parent_type));
 }
Пример #17
0
 /**
  * Sends Email for Email 2.0
  */
 function email2Send($request)
 {
     global $current_user;
     global $timedate;
     $saveAsDraft = !empty($request['saveDraft']);
     if (!$saveAsDraft && !empty($request["MAIL_RECORD_STATUS"]) && $request["MAIL_RECORD_STATUS"] == 'archived') {
         $archived = true;
         $this->type = 'archived';
     } else {
         $archived = false;
         if (!empty($request['MAIL_RECORD_STATUS']) && $request['MAIL_RECORD_STATUS'] === 'ready') {
             $this->type = 'out';
         }
     }
     /**********************************************************************
      * 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'];
     if (isset($_REQUEST['setEditor']) && $_REQUEST['setEditor'] == 1) {
         $_REQUEST['description_html'] = $_REQUEST['sendDescription'];
         $this->description_html = $_REQUEST['description_html'];
     } else {
         $this->description_html = '';
         $this->description = $_REQUEST['sendDescription'];
     }
     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}'";
         $this->db->query($q1);
     }
     // if
     if ($saveAsDraft) {
         $this->type = 'draft';
         $this->status = 'draft';
     } else {
         if ($archived) {
             $this->type = 'archived';
             $this->status = 'archived';
         }
         /* Apply Email Templates */
         // do not parse email templates if the email is being saved as draft....
         $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']);
         $sea = BeanFactory::getBean('EmailAddresses');
         $object_arr = array();
         if (!empty($_REQUEST['parent_type']) && !empty($_REQUEST['parent_id']) && ($_REQUEST['parent_type'] == 'Accounts' || $_REQUEST['parent_type'] == 'Contacts' || $_REQUEST['parent_type'] == 'Leads' || $_REQUEST['parent_type'] == 'Users' || $_REQUEST['parent_type'] == 'Prospects')) {
             $bean = BeanFactory::getBean($_REQUEST['parent_type'], $_REQUEST['parent_id']);
             if (!empty($bean->id)) {
                 $object_arr[$bean->module_dir] = $bean->id;
             }
         }
         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->type != 'archived' && $this->status != 'archived') {
             $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
     $forceSave = false;
     $subject = $this->name;
     $textBody = from_html($this->description);
     $htmlBody = from_html($this->description_html);
     //------------------- HANDLEBODY() ---------------------------------------------
     if (isset($_REQUEST['setEditor']) && $_REQUEST['setEditor'] == 1 && trim($_REQUEST['description_html']) != '' || trim($this->description_html) != '' && $current_user->getPreference('email_editor_option', 'global') !== 'plain') {
         $textBody = strip_tags(br2nl($htmlBody));
     } else {
         // plain-text only
         $textBody = str_replace("&nbsp;", " ", $textBody);
         $textBody = str_replace("</p>", "</p><br />", $textBody);
         $textBody = strip_tags(br2nl($textBody));
         $textBody = html_entity_decode($textBody, ENT_QUOTES, 'UTF-8');
         $this->description_html = "";
         // make sure it's blank to avoid any mishaps
         $htmlBody = $this->description_html;
     }
     $textBody = $this->decodeDuringSend($textBody);
     $htmlBody = $this->decodeDuringSend($htmlBody);
     $this->description = $textBody;
     $this->description_html = $htmlBody;
     $mailConfig = null;
     try {
         if (isset($request["fromAccount"]) && !empty($request["fromAccount"])) {
             $mailConfig = OutboundEmailConfigurationPeer::getMailConfigurationFromId($current_user, $request["fromAccount"]);
         } else {
             $mailConfig = OutboundEmailConfigurationPeer::getSystemMailConfiguration($current_user);
         }
     } catch (Exception $e) {
         if (!$saveAsDraft && !$archived) {
             throw $e;
         }
     }
     if (!$saveAsDraft && !$archived && is_null($mailConfig)) {
         throw new MailerException("No Valid Mail Configurations Found", MailerException::InvalidConfiguration);
     }
     try {
         $mailer = null;
         if (!$saveAsDraft && !$archived) {
             $mailerFactoryClass = $this->MockMailerFactoryClass;
             $mailer = $mailerFactoryClass::getMailer($mailConfig);
             $mailer->setSubject($subject);
             $mailer->setHtmlBody($htmlBody);
             $mailer->setTextBody($textBody);
             $replyTo = $mailConfig->getReplyTo();
             if (!empty($replyTo)) {
                 $replyToEmail = $replyTo->getEmail();
                 if (!empty($replyToEmail)) {
                     $mailer->setHeader(EmailHeaders::ReplyTo, new EmailIdentity($replyToEmail, $replyTo->getName()));
                 }
             }
         }
         if (!is_null($mailer)) {
             // Any individual Email Address that is not valid will be logged and skipped
             // If all email addresses in the request are skipped, an error "No Recipients" is reported for the request
             foreach ($this->email2ParseAddresses($request['sendTo']) as $addr_arr) {
                 try {
                     $mailer->addRecipientsTo(new EmailIdentity($addr_arr['email'], $addr_arr['display']));
                 } catch (MailerException $me) {
                     // Invalid Email Address - Log it and Skip
                     $GLOBALS["log"]->warning($me->getLogMessage());
                 }
             }
             foreach ($this->email2ParseAddresses($request['sendCc']) as $addr_arr) {
                 try {
                     $mailer->addRecipientsCc(new EmailIdentity($addr_arr['email'], $addr_arr['display']));
                 } catch (MailerException $me) {
                     // Invalid Email Address - Log it and Skip
                     $GLOBALS["log"]->warning($me->getLogMessage());
                 }
             }
             foreach ($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) {
                 try {
                     $mailer->addRecipientsBcc(new EmailIdentity($addr_arr['email'], $addr_arr['display']));
                 } catch (MailerException $me) {
                     // Invalid Email Address - Log it and Skip
                     $GLOBALS["log"]->warning($me->getLogMessage());
                 }
             }
         }
         /* 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)) {
                     $fileGUID = preg_replace('/[^a-z0-9\\-]/', "", substr($file, 0, 36));
                     $fileLocation = $this->et->userCacheDir . "/{$fileGUID}";
                     $filename = substr($file, 36, strlen($file));
                     // strip GUID	for PHPMailer class to name outbound file
                     // 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 = $this->email2GetMime($fileLocation);
                         $note->team_id = isset($_REQUEST['primaryteam']) ? $_REQUEST['primaryteam'] : $current_user->getPrivateTeamID();
                         $noteTeamSet = new TeamSet();
                         $noteteamIdsArray = isset($_REQUEST['teamIds']) ? explode(",", $_REQUEST['teamIds']) : array($current_user->getPrivateTeamID());
                         $note->team_set_id = $noteTeamSet->addTeams($noteteamIdsArray);
                         $dest = "upload://{$note->id}";
                         if (!file_exists($fileLocation) || !copy($fileLocation, $dest)) {
                             $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to {$fileLocation} => {$dest}");
                         } else {
                             $note->save();
                             $validNote = true;
                         }
                     } else {
                         $note = new Note();
                         $validNote = (bool) $note->retrieve($fileGUID);
                     }
                     if (isset($validNote) && $validNote === true) {
                         $attachment = AttachmentPeer::attachmentFromSugarBean($note);
                         if (!is_null($mailer)) {
                             $mailer->addAttachment($attachment);
                         }
                     }
                 }
             }
         }
         /* handle sugar documents */
         if (!empty($request['documents'])) {
             $exDocs = explode("::", $request['documents']);
             foreach ($exDocs as $docId) {
                 $docId = trim($docId);
                 if (!empty($docId)) {
                     $doc = new Document();
                     $doc->retrieve($docId);
                     if (empty($doc->id) || $doc->id != $docId) {
                         throw new Exception("Document Not Found: Id='" . $request['documents'] . "'");
                     }
                     $documentRevision = new DocumentRevision();
                     $documentRevision->retrieve($doc->document_revision_id);
                     //$documentRevision->x_file_name   = $documentRevision->filename;
                     //$documentRevision->x_file_path   = "upload/{$documentRevision->id}";
                     //$documentRevision->x_file_exists = (bool) file_exists($documentRevision->x_file_path);
                     //$documentRevision->x_mime_type   = $documentRevision->file_mime_type;
                     $filename = $documentRevision->filename;
                     $docGUID = preg_replace('/[^a-z0-9\\-]/', "", $documentRevision->id);
                     $fileLocation = "upload://{$docGUID}";
                     if (empty($documentRevision->id) || !file_exists($fileLocation)) {
                         throw new Exception("Document Revision Id Not Found");
                     }
                     // 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 = $documentRevision->file_mime_type;
                         $note->team_id = $this->team_id;
                         $note->team_set_id = $this->team_set_id;
                         $dest = "upload://{$note->id}";
                         if (!file_exists($fileLocation) || !copy($fileLocation, $dest)) {
                             $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file {$fileLocation} => {$dest}");
                         }
                         $note->save();
                     }
                     $attachment = AttachmentPeer::attachmentFromSugarBean($documentRevision);
                     //print_r($attachment);
                     if (!is_null($mailer)) {
                         $mailer->addAttachment($attachment);
                     }
                 }
             }
         }
         /* 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;
                         $noteGUID = preg_replace('/[^a-z0-9\\-]/', "", $note->id);
                         $fileLocation = "upload://{$noteGUID}";
                         $mime_type = $note->file_mime_type;
                         if (!$note->embed_flag) {
                             $attachment = AttachmentPeer::attachmentFromSugarBean($note);
                             //print_r($attachment);
                             if (!is_null($mailer)) {
                                 $mailer->addAttachment($attachment);
                             }
                             // 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 {
                         $fileGUID = preg_replace('/[^a-z0-9\\-]/', "", substr($noteId, 0, 36));
                         $fileLocation = $this->et->userCacheDir . "/{$fileGUID}";
                         $filename = substr($noteId, 36, strlen($noteId));
                         // strip GUID	for PHPMailer class to name outbound file
                         $mimeType = $this->email2GetMime($fileLocation);
                         $note = $this->saveTempNoteAttachments($filename, $fileLocation, $mimeType);
                         $attachment = AttachmentPeer::attachmentFromSugarBean($note);
                         //print_r($attachment);
                         if (!is_null($mailer)) {
                             $mailer->addAttachment($attachment);
                         }
                     }
                 }
             }
         }
         /**********************************************************************
          * Final Touches
          */
         if ($this->type == 'draft' && !$saveAsDraft) {
             // sending a draft email
             $this->type = 'out';
             $this->status = 'sent';
             $forceSave = true;
         } elseif ($saveAsDraft) {
             $this->type = 'draft';
             $this->status = 'draft';
             $forceSave = true;
         }
         if (!is_null($mailer)) {
             $mailer->send();
         }
     } catch (MailerException $me) {
         $GLOBALS["log"]->error($me->getLogMessage());
         throw $me;
     } catch (Exception $e) {
         // eat the phpmailerException but use it's message to provide context for the failure
         $me = new MailerException("Email2Send Failed: " . $e->getMessage(), MailerException::FailedToSend);
         $GLOBALS["log"]->error($me->getLogMessage());
         $GLOBALS["log"]->info($me->getTraceMessage());
         if (!empty($mailConfig)) {
             $GLOBALS["log"]->info($mailConfig->toArray(), true);
         }
         throw $me;
     }
     if (!(empty($orignialId) || $saveAsDraft || $this->type == 'draft' && $this->status == 'draft') && ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyAll' || $_REQUEST['composeType'] == 'replyCase') && $orignialId != $this->id) {
         $originalEmail = BeanFactory::getBean('Emails', $orignialId);
         $originalEmail->reply_to_status = 1;
         $originalEmail->save();
         $this->reply_to_status = 0;
     }
     // if
     if (isset($_REQUEST['composeType']) && ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase')) {
         if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) {
             $emailFromIe = BeanFactory::getBean('InboundEmail', $_REQUEST['ieId'], array('disable_row_level_security' => true));
             $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' || $this->type == 'archived' || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) {
         // Set Up From Name and Address Information
         if ($this->type == 'archived') {
             $this->from_addr = empty($request['archive_from_address']) ? '' : $request['archive_from_address'];
         } elseif (!empty($mailConfig)) {
             $sender = $mailConfig->getFrom();
             $decodedFromName = mb_decode_mimeheader($sender->getName());
             $this->from_addr = "{$decodedFromName} <" . $sender->getEmail() . ">";
         } else {
             $ret = $current_user->getUsersNameAndEmail();
             if (empty($ret['email'])) {
                 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
                 $ret['email'] = $systemReturn['email'];
                 $ret['name'] = $systemReturn['name'];
             }
             $decodedFromName = mb_decode_mimeheader($ret['name']);
             $this->from_addr = "{$decodedFromName} <" . $ret['email'] . ">";
         }
         $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->team_id = isset($_REQUEST['primaryteam']) ? $_REQUEST['primaryteam'] : $current_user->getPrivateTeamID();
         $teamSet = BeanFactory::getBean('TeamSets');
         $teamIdsArray = isset($_REQUEST['teamIds']) ? explode(",", $_REQUEST['teamIds']) : array($current_user->getPrivateTeamID());
         $this->team_set_id = $teamSet->addTeams($teamIdsArray);
         $this->assigned_user_id = $current_user->id;
         $this->date_sent = $timedate->now();
         ///////////////////////////////////////////////////////////////////
         ////	LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
         if (!empty($_REQUEST['parent_type']) && !empty($_REQUEST['parent_id'])) {
             $this->parent_id = $this->db->quote($_REQUEST['parent_id']);
             $this->parent_type = $this->db->quote($_REQUEST['parent_type']);
             $a = $this->db->fetchOne("SELECT count(*) c FROM emails_beans WHERE  email_id = '{$this->id}' AND bean_id = '{$this->parent_id}' AND bean_module = '{$this->parent_type}'");
             if ($a['c'] == 0) {
                 $bean = BeanFactory::getBean($_REQUEST['parent_type'], $_REQUEST['parent_id']);
                 if (!empty($bean)) {
                     if (!empty($bean->field_defs['emails']['type']) && $bean->field_defs['emails']['type'] == 'link') {
                         $email_link = "emails";
                     } else {
                         $email_link = $this->findEmailsLink($bean);
                     }
                     if ($email_link && $bean->load_relationship($email_link)) {
                         $bean->{$email_link}->add($this);
                     }
                 }
             }
             // if
         } else {
             $c = BeanFactory::getBean('Cases');
             if ($caseId = InboundEmail::getCaseIdFromCaseNumber($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'])) {
                 $ie = new InboundEmail();
                 $ie->retrieve($request['fromAccount']);
     			if (isset($ie->id) && !$ie->isPop3Protocol() && $mail->oe->mail_smtptype != 'gmail') {
     				$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;
 }