3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class provides the common functionality for sending email to
38 * one or a group of contact ids. This class is reused by all the search
39 * components in CiviCRM (since they all have send email as a task)
41 class CRM_Contact_Form_Task_EmailCommon
{
42 CONST MAX_EMAILS_KILL_SWITCH
= 50;
44 public $_contactDetails = array();
45 public $_allContactDetails = array();
46 public $_toContactEmails = array();
49 * @param CRM_Core_Form $form
51 static function preProcessFromAddress(&$form) {
52 $form->_single
= FALSE;
53 $className = CRM_Utils_System
::getClassName($form);
54 if (property_exists($form, '_context') &&
55 $form->_context
!= 'search' &&
56 $className == 'CRM_Contact_Form_Task_Email'
58 $form->_single
= TRUE;
61 $form->_emails
= $emails = array();
63 $session = CRM_Core_Session
::singleton();
64 $contactID = $session->get('userID');
66 $form->_contactIds
= array($contactID);
67 $contactEmails = CRM_Core_BAO_Email
::allEmails($contactID);
69 $form->_onHold
= array();
71 $fromDisplayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
72 $contactID, 'display_name'
75 foreach ($contactEmails as $emailId => $item) {
76 $email = $item['email'];
77 if (!$email && (count($emails) < 1)) {
78 // set it if no emails are present at all
79 $form->_noEmails
= TRUE;
83 if (in_array($email, $emails)) {
88 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
89 $form->_onHold
[$emailId] = $item['on_hold'];
90 $form->_noEmails
= FALSE;
94 $form->_emails
[$emailId] = $emails[$emailId];
95 $emails[$emailId] .= $item['locationType'];
97 if ($item['is_primary']) {
98 $emails[$emailId] .= ' ' . ts('(preferred)');
100 $emails[$emailId] = htmlspecialchars($emails[$emailId]);
103 $form->assign('noEmails', $form->_noEmails
);
105 if ($form->_noEmails
) {
106 CRM_Core_Error
::statusBounce(ts('Your user record does not have a valid email address'));
109 // now add domain from addresses
110 $domainEmails = array();
111 $domainFrom = CRM_Core_OptionGroup
::values('from_email_address');
112 foreach (array_keys($domainFrom) as $k) {
113 $domainEmail = $domainFrom[$k];
114 $domainEmails[$domainEmail] = htmlspecialchars($domainEmail);
115 $form->_emails
[$domainEmail] = $domainEmail;
118 $form->_fromEmails
= CRM_Utils_Array
::crmArrayMerge($emails, $domainEmails);
121 $defaultEmail = civicrm_api3('email', 'getsingle', array('id' => key($form->_fromEmails
)));
123 if (!empty($defaultEmail['signature_html'])) {
124 $defaults['html_message'] = '<br/><br/>--' . $defaultEmail['signature_html'];
126 if (!empty($defaultEmail['signature_text'])) {
127 $defaults['text_message'] = "\n\n--\n" . $defaultEmail['signature_text'];
129 $form->setDefaults($defaults);
133 * Build the form object
137 * @param CRM_Core_Form $form
141 static function buildQuickForm(&$form) {
142 $toArray = $ccArray = $bccArray = array();
143 $suppressedEmails = 0;
144 //here we are getting logged in user id as array but we need target contact id. CRM-5988
145 $cid = $form->get('cid');
147 $form->_contactIds
= explode(',', $cid);
149 if (count($form->_contactIds
) > 1) {
150 $form->_single
= FALSE;
153 $emailAttributes = array(
156 $to = $form->add('text', 'to', ts('To'), $emailAttributes, TRUE);
157 $cc = $form->add('text', 'cc_id', ts('CC'), $emailAttributes);
158 $bcc = $form->add('text', 'bcc_id', ts('BCC'), $emailAttributes);
161 if (property_exists($form, '_context') && $form->_context
== 'standalone') {
162 $setDefaults = FALSE;
165 $elements = array('to', 'cc', 'bcc');
166 $form->_allContactIds
= $form->_toContactIds
= $form->_contactIds
;
167 foreach ($elements as $element) {
168 if ($
$element->getValue()) {
169 $allEmails = explode(',', $
$element->getValue());
170 if ($element == 'to') {
171 $form->_toContactIds
= $form->_contactIds
= array();
174 foreach ($allEmails as $value) {
175 list($contactId, $email) = explode('::', $value);
179 $form->_contactIds
[] = $form->_toContactIds
[] = $contactId;
180 $form->_toContactEmails
[] = $email;
183 $form->_ccContactIds
[] = $contactId;
186 $form->_bccContactIds
[] = $contactId;
190 $form->_allContactIds
[] = $contactId;
198 //get the group of contacts as per selected by user in case of Find Activities
199 if (!empty($form->_activityHolderIds
)) {
200 $contact = $form->get('contacts');
201 $form->_allContactIds
= $form->_contactIds
= $contact;
204 // check if we need to setdefaults and check for valid contact emails / communication preferences
205 if (is_array($form->_allContactIds
) && $setDefaults) {
206 $returnProperties = array(
213 'preferred_mail_format' => 1,
216 // get the details for all selected contacts ( to, cc and bcc contacts )
217 list($form->_contactDetails
) = CRM_Utils_Token
::getTokenDetails($form->_allContactIds
,
223 // make a copy of all contact details
224 $form->_allContactDetails
= $form->_contactDetails
;
226 // perform all validations
227 foreach ($form->_allContactIds
as $key => $contactId) {
228 $value = $form->_contactDetails
[$contactId];
229 if ($value['do_not_email'] ||
empty($value['email']) ||
!empty($value['is_deceased']) ||
$value['on_hold']) {
232 // unset contact details for contacts that we won't be sending email. This is prevent extra computation
233 // during token evaluation etc.
234 unset($form->_contactDetails
[$contactId]);
237 $email = $value['email'];
239 // build array's which are used to setdefaults
240 if (in_array($contactId, $form->_toContactIds
)) {
241 $form->_toContactDetails
[$contactId] = $form->_contactDetails
[$contactId];
242 // If a particular address has been specified as the default, use that instead of contact's primary email
243 if (!empty($form->_toEmail
) && $form->_toEmail
['contact_id'] == $contactId) {
244 $email = $form->_toEmail
['email'];
247 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
248 'id' => "$contactId::{$email}",
251 elseif (in_array($contactId, $form->_ccContactIds
)) {
253 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
254 'id' => "$contactId::{$email}",
257 elseif (in_array($contactId, $form->_bccContactIds
)) {
259 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
260 'id' => "$contactId::{$email}",
266 if (empty($toArray)) {
267 CRM_Core_Error
::statusBounce(ts('Selected contact(s) do not have a valid email address, or communication preferences specify DO NOT EMAIL, or they are deceased or Primary email address is On Hold.'));
271 $form->assign('toContact', json_encode($toArray));
272 $form->assign('ccContact', json_encode($ccArray));
273 $form->assign('bccContact', json_encode($bccArray));
275 $form->assign('suppressedEmails', $suppressedEmails);
277 $form->assign('totalSelectedContacts', count($form->_contactIds
));
279 $form->add('text', 'subject', ts('Subject'), 'size=50 maxlength=254', TRUE);
281 $form->add('select', 'fromEmailAddress', ts('From'), $form->_fromEmails
, TRUE, array('class' => 'crm-select2 huge'));
283 CRM_Mailing_BAO_Mailing
::commonCompose($form);
286 CRM_Core_BAO_File
::buildAttachment($form, NULL);
288 if ($form->_single
) {
289 // also fix the user context stack
290 if ($form->_caseId
) {
291 $ccid = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $form->_caseId
,
292 'contact_id', 'case_id'
294 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
295 "&reset=1&action=view&cid={$ccid}&id={$form->_caseId}"
298 elseif ($form->_context
) {
299 $url = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
302 $url = CRM_Utils_System
::url('civicrm/contact/view',
303 "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"
307 $session = CRM_Core_Session
::singleton();
308 $session->replaceUserContext($url);
309 $form->addDefaultButtons(ts('Send Email'), 'upload', 'cancel');
312 $form->addDefaultButtons(ts('Send Email'), 'upload');
315 $form->addFormRule(array('CRM_Contact_Form_Task_EmailCommon', 'formRule'), $form);
316 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Task/EmailCommon.js');
322 * @param array $fields the input form values
323 * @param array $dontCare
324 * @param array $self additional values form 'this'
326 * @return true if no errors, else array of errors
330 static function formRule($fields, $dontCare, $self) {
332 $template = CRM_Core_Smarty
::singleton();
334 if (isset($fields['html_message'])) {
335 $htmlMessage = str_replace(array("\n", "\r"), ' ', $fields['html_message']);
336 $htmlMessage = str_replace('"', '\"', $htmlMessage);
337 $template->assign('htmlContent', $htmlMessage);
341 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
342 $errors['saveTemplateName'] = ts("Enter name to save message template");
345 return empty($errors) ?
TRUE : $errors;
349 * Process the form after the input has been submitted and validated
353 * @param CRM_Core_Form $form
357 static function postProcess(&$form) {
358 if (count($form->_contactIds
) > self
::MAX_EMAILS_KILL_SWITCH
) {
359 CRM_Core_Error
::fatal(ts('Please do not use this task to send a lot of emails (greater than %1). We recommend using CiviMail instead.',
360 array(1 => self
::MAX_EMAILS_KILL_SWITCH
)
364 // check and ensure that
365 $formValues = $form->controller
->exportValues($form->getName());
367 $fromEmail = $formValues['fromEmailAddress'];
368 $from = CRM_Utils_Array
::value($fromEmail, $form->_emails
);
369 $subject = $formValues['subject'];
371 // CRM-13378: Append CC and BCC information at the end of Activity Details and format cc and bcc fields
372 $elements = array('cc_id', 'bcc_id');
373 $additionalDetails = NULL;
374 $ccValues = $bccValues = array();
375 foreach ($elements as $element) {
376 if (!empty($formValues[$element])) {
377 $allEmails = explode(',', $formValues[$element]);
378 foreach ($allEmails as $value) {
379 list($contactId, $email) = explode('::', $value);
380 $contactURL = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&force=1&cid={$contactId}", true);
383 $ccValues['email'][] = '"' . $form->_contactDetails
[$contactId]['sort_name'] . '" <' . $email . '>';
384 $ccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails
[$contactId]['display_name'] . "</a>";
387 $bccValues['email'][]= '"' . $form->_contactDetails
[$contactId]['sort_name'] . '" <' . $email . '>';
388 $bccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails
[$contactId]['display_name'] . "</a>";
396 if (!empty($ccValues)) {
397 $cc = implode(',', $ccValues['email']);
398 $additionalDetails .= "\ncc : " . implode(", ", $ccValues['details']);
400 if (!empty($bccValues)) {
401 $bcc = implode(',', $bccValues['email']);
402 $additionalDetails .= "\nbcc : " . implode(", ", $bccValues['details']);
405 // CRM-5916: prepend case id hash to CiviCase-originating emails’ subjects
406 if (isset($form->_caseId
) && is_numeric($form->_caseId
)) {
407 $hash = substr(sha1(CIVICRM_SITE_KEY
. $form->_caseId
), 0, 7);
408 $subject = "[case #$hash] $subject";
411 // process message template
412 if (!empty($formValues['saveTemplate']) ||
!empty($formValues['updateTemplate'])) {
413 $messageTemplate = array(
414 'msg_text' => $formValues['text_message'],
415 'msg_html' => $formValues['html_message'],
416 'msg_subject' => $formValues['subject'],
420 if (!empty($formValues['saveTemplate'])) {
421 $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
422 CRM_Core_BAO_MessageTemplate
::add($messageTemplate);
425 if (!empty($formValues['template']) && !empty($formValues['updateTemplate'])) {
426 $messageTemplate['id'] = $formValues['template'];
427 unset($messageTemplate['msg_title']);
428 CRM_Core_BAO_MessageTemplate
::add($messageTemplate);
432 $attachments = array();
433 CRM_Core_BAO_File
::formatAttachment($formValues,
438 // format contact details array to handle multiple emails from same contact
439 $formattedContactDetails = array();
440 $tempEmails = array();
442 foreach ($form->_contactIds
as $key => $contactId) {
443 // if we dont have details on this contactID, we should ignore
444 // potentially this is due to the contact not wanting to receive email
445 if (!isset($form->_contactDetails
[$contactId])) {
448 $email = $form->_toContactEmails
[$key];
449 // prevent duplicate emails if same email address is selected CRM-4067
450 // we should allow same emails for different contacts
451 $emailKey = "{$contactId}::{$email}";
452 if (!in_array($emailKey, $tempEmails)) {
453 $tempEmails[] = $emailKey;
454 $details = $form->_contactDetails
[$contactId];
455 $details['email'] = $email;
456 unset($details['email_id']);
457 $formattedContactDetails[] = $details;
462 list($sent, $activityId) = CRM_Activity_BAO_Activity
::sendEmail(
463 $formattedContactDetails,
465 $formValues['text_message'],
466 $formValues['html_message'],
473 array_keys($form->_toContactDetails
),
478 $count_success = count($form->_toContactDetails
);
479 CRM_Core_Session
::setStatus(ts('One message was sent successfully.', array('plural' => '%count messages were sent successfully.', 'count' => $count_success)), ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $count_success)), 'success');
482 // Display the name and number of contacts for those email is not sent.
483 // php 5.4 throws out a notice since the values of these below arrays are arrays.
484 // the behavior is not documented in the php manual, but it does the right thing
485 // suppressing the notices to get things in good shape going forward
486 $emailsNotSent = @array_diff_assoc
($form->_allContactDetails
, $form->_contactDetails
);
488 if ($emailsNotSent) {
490 foreach ($emailsNotSent as $contactId => $values) {
491 $displayName = $values['display_name'];
492 $email = $values['email'];
493 $contactViewUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid=$contactId");
494 $not_sent[] = "<a href='$contactViewUrl' title='$email'>$displayName</a>" . ($values['on_hold'] ?
'(' . ts('on hold') . ')' : '');
496 $status = '(' . ts('because no email address on file or communication preferences specify DO NOT EMAIL or Contact is deceased or Primary email address is On Hold') . ')<ul><li>' . implode('</li><li>', $not_sent) . '</li></ul>';
497 CRM_Core_Session
::setStatus($status, ts('One Message Not Sent', array('count' => count($emailsNotSent), 'plural' => '%count Messages Not Sent')), 'info');
500 if (isset($form->_caseId
)) {
501 // if case-id is found in the url, create case activity record
502 $cases = explode(',', $form->_caseId
);
503 foreach($cases as $key => $val) {
504 if (is_numeric($val)) {
506 'activity_id' => $activityId,
509 CRM_Case_BAO_Case
::processCaseActivity($caseParams);