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();
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);
130 static function buildQuickForm(&$form) {
131 $toArray = $ccArray = $bccArray = array();
132 $suppressedEmails = 0;
133 //here we are getting logged in user id as array but we need target contact id. CRM-5988
134 $cid = $form->get('cid');
136 $form->_contactIds
= explode(',', $cid);
138 if (count($form->_contactIds
) > 1) {
139 $form->_single
= FALSE;
142 $emailAttributes = array(
145 $to = $form->add('text', 'to', ts('To'), $emailAttributes, TRUE);
146 $cc = $form->add('text', 'cc_id', ts('CC'), $emailAttributes);
147 $bcc = $form->add('text', 'bcc_id', ts('BCC'), $emailAttributes);
150 if (property_exists($form, '_context') && $form->_context
== 'standalone') {
151 $setDefaults = FALSE;
154 $elements = array('to', 'cc', 'bcc');
155 $form->_allContactIds
= $form->_toContactIds
= $form->_contactIds
;
156 foreach ($elements as $element) {
157 if ($
$element->getValue()) {
158 $allEmails = explode(',', $
$element->getValue());
159 if ($element == 'to') {
160 $form->_toContactIds
= $form->_contactIds
= array();
163 foreach ($allEmails as $value) {
164 list($contactId, $email) = explode('::', $value);
168 $form->_contactIds
[] = $form->_toContactIds
[] = $contactId;
169 $form->_toContactEmails
[] = $email;
172 $form->_ccContactIds
[] = $contactId;
175 $form->_bccContactIds
[] = $contactId;
179 $form->_allContactIds
[] = $contactId;
187 //get the group of contacts as per selected by user in case of Find Activities
188 if (!empty($form->_activityHolderIds
)) {
189 $contact = $form->get('contacts');
190 $form->_allContactIds
= $form->_contactIds
= $contact;
193 // check if we need to setdefaults and check for valid contact emails / communication preferences
194 if (is_array($form->_allContactIds
) && $setDefaults) {
195 $returnProperties = array(
202 'preferred_mail_format' => 1,
205 // get the details for all selected contacts ( to, cc and bcc contacts )
206 list($form->_contactDetails
) = CRM_Utils_Token
::getTokenDetails($form->_allContactIds
,
212 // make a copy of all contact details
213 $form->_allContactDetails
= $form->_contactDetails
;
215 // perform all validations
216 foreach ($form->_allContactIds
as $key => $contactId) {
217 $value = $form->_contactDetails
[$contactId];
218 if ($value['do_not_email'] ||
empty($value['email']) ||
!empty($value['is_deceased']) ||
$value['on_hold']) {
221 // unset contact details for contacts that we won't be sending email. This is prevent extra computation
222 // during token evaluation etc.
223 unset($form->_contactDetails
[$contactId]);
226 $email = $value['email'];
228 // build array's which are used to setdefaults
229 if (in_array($contactId, $form->_toContactIds
)) {
230 $form->_toContactDetails
[$contactId] = $form->_contactDetails
[$contactId];
231 // If a particular address has been specified as the default, use that instead of contact's primary email
232 if (!empty($form->_toEmail
) && $form->_toEmail
['contact_id'] == $contactId) {
233 $email = $form->_toEmail
['email'];
236 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
237 'id' => "$contactId::{$email}",
240 elseif (in_array($contactId, $form->_ccContactIds
)) {
242 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
243 'id' => "$contactId::{$email}",
246 elseif (in_array($contactId, $form->_bccContactIds
)) {
248 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
249 'id' => "$contactId::{$email}",
255 if (empty($toArray)) {
256 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.'));
260 $form->assign('toContact', json_encode($toArray));
261 $form->assign('ccContact', json_encode($ccArray));
262 $form->assign('bccContact', json_encode($bccArray));
264 $form->assign('suppressedEmails', $suppressedEmails);
266 $form->assign('totalSelectedContacts', count($form->_contactIds
));
268 $form->add('text', 'subject', ts('Subject'), 'size=50 maxlength=254', TRUE);
270 $form->add('select', 'fromEmailAddress', ts('From'), $form->_fromEmails
, TRUE, array('class' => 'crm-select2 huge'));
272 CRM_Mailing_BAO_Mailing
::commonCompose($form);
275 CRM_Core_BAO_File
::buildAttachment($form, NULL);
277 if ($form->_single
) {
278 // also fix the user context stack
279 if ($form->_caseId
) {
280 $ccid = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseContact', $form->_caseId
,
281 'contact_id', 'case_id'
283 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
284 "&reset=1&action=view&cid={$ccid}&id={$form->_caseId}"
287 elseif ($form->_context
) {
288 $url = CRM_Utils_System
::url('civicrm/dashboard', 'reset=1');
291 $url = CRM_Utils_System
::url('civicrm/contact/view',
292 "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"
296 $session = CRM_Core_Session
::singleton();
297 $session->replaceUserContext($url);
298 $form->addDefaultButtons(ts('Send Email'), 'upload', 'cancel');
301 $form->addDefaultButtons(ts('Send Email'), 'upload');
304 $form->addFormRule(array('CRM_Contact_Form_Task_EmailCommon', 'formRule'), $form);
305 CRM_Core_Resources
::singleton()->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Task/EmailCommon.js');
311 * @param array $fields the input form values
312 * @param array $dontCare
313 * @param array $self additional values form 'this'
315 * @return true if no errors, else array of errors
319 static function formRule($fields, $dontCare, $self) {
321 $template = CRM_Core_Smarty
::singleton();
323 if (isset($fields['html_message'])) {
324 $htmlMessage = str_replace(array("\n", "\r"), ' ', $fields['html_message']);
325 $htmlMessage = str_replace('"', '\"', $htmlMessage);
326 $template->assign('htmlContent', $htmlMessage);
330 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
331 $errors['saveTemplateName'] = ts("Enter name to save message template");
334 return empty($errors) ?
TRUE : $errors;
338 * process the form after the input has been submitted and validated
346 static function postProcess(&$form) {
347 if (count($form->_contactIds
) > self
::MAX_EMAILS_KILL_SWITCH
) {
348 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.',
349 array(1 => self
::MAX_EMAILS_KILL_SWITCH
)
353 // check and ensure that
354 $formValues = $form->controller
->exportValues($form->getName());
356 $fromEmail = $formValues['fromEmailAddress'];
357 $from = CRM_Utils_Array
::value($fromEmail, $form->_emails
);
358 $subject = $formValues['subject'];
360 // CRM-13378: Append CC and BCC information at the end of Activity Details and format cc and bcc fields
361 $elements = array('cc_id', 'bcc_id');
362 $additionalDetails = NULL;
363 $ccValues = $bccValues = array();
364 foreach ($elements as $element) {
365 if (!empty($formValues[$element])) {
366 $allEmails = explode(',', $formValues[$element]);
367 foreach ($allEmails as $value) {
368 list($contactId, $email) = explode('::', $value);
369 $contactURL = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&force=1&cid={$contactId}", true);
372 $ccValues['email'][] = '"' . $form->_contactDetails
[$contactId]['sort_name'] . '" <' . $email . '>';
373 $ccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails
[$contactId]['display_name'] . "</a>";
376 $bccValues['email'][]= '"' . $form->_contactDetails
[$contactId]['sort_name'] . '" <' . $email . '>';
377 $bccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails
[$contactId]['display_name'] . "</a>";
385 if (!empty($ccValues)) {
386 $cc = implode(',', $ccValues['email']);
387 $additionalDetails .= "\ncc : " . implode(", ", $ccValues['details']);
389 if (!empty($bccValues)) {
390 $bcc = implode(',', $bccValues['email']);
391 $additionalDetails .= "\nbcc : " . implode(", ", $bccValues['details']);
394 // CRM-5916: prepend case id hash to CiviCase-originating emails’ subjects
395 if (isset($form->_caseId
) && is_numeric($form->_caseId
)) {
396 $hash = substr(sha1(CIVICRM_SITE_KEY
. $form->_caseId
), 0, 7);
397 $subject = "[case #$hash] $subject";
400 // process message template
401 if (!empty($formValues['saveTemplate']) ||
!empty($formValues['updateTemplate'])) {
402 $messageTemplate = array(
403 'msg_text' => $formValues['text_message'],
404 'msg_html' => $formValues['html_message'],
405 'msg_subject' => $formValues['subject'],
409 if (!empty($formValues['saveTemplate'])) {
410 $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
411 CRM_Core_BAO_MessageTemplate
::add($messageTemplate);
414 if (!empty($formValues['template']) && !empty($formValues['updateTemplate'])) {
415 $messageTemplate['id'] = $formValues['template'];
416 unset($messageTemplate['msg_title']);
417 CRM_Core_BAO_MessageTemplate
::add($messageTemplate);
421 $attachments = array();
422 CRM_Core_BAO_File
::formatAttachment($formValues,
427 // format contact details array to handle multiple emails from same contact
428 $formattedContactDetails = array();
429 $tempEmails = array();
431 foreach ($form->_contactIds
as $key => $contactId) {
432 // if we dont have details on this contactID, we should ignore
433 // potentially this is due to the contact not wanting to receive email
434 if (!isset($form->_contactDetails
[$contactId])) {
437 $email = $form->_toContactEmails
[$key];
438 // prevent duplicate emails if same email address is selected CRM-4067
439 // we should allow same emails for different contacts
440 $emailKey = "{$contactId}::{$email}";
441 if (!in_array($emailKey, $tempEmails)) {
442 $tempEmails[] = $emailKey;
443 $details = $form->_contactDetails
[$contactId];
444 $details['email'] = $email;
445 unset($details['email_id']);
446 $formattedContactDetails[] = $details;
451 list($sent, $activityId) = CRM_Activity_BAO_Activity
::sendEmail(
452 $formattedContactDetails,
454 $formValues['text_message'],
455 $formValues['html_message'],
462 array_keys($form->_toContactDetails
),
467 $count_success = count($form->_toContactDetails
);
468 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');
471 // Display the name and number of contacts for those email is not sent.
472 // php 5.4 throws out a notice since the values of these below arrays are arrays.
473 // the behavior is not documented in the php manual, but it does the right thing
474 // suppressing the notices to get things in good shape going forward
475 $emailsNotSent = @array_diff_assoc
($form->_allContactDetails
, $form->_contactDetails
);
477 if ($emailsNotSent) {
479 foreach ($emailsNotSent as $contactId => $values) {
480 $displayName = $values['display_name'];
481 $email = $values['email'];
482 $contactViewUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid=$contactId");
483 $not_sent[] = "<a href='$contactViewUrl' title='$email'>$displayName</a>" . ($values['on_hold'] ?
'(' . ts('on hold') . ')' : '');
485 $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>';
486 CRM_Core_Session
::setStatus($status, ts('One Message Not Sent', array('count' => count($emailsNotSent), 'plural' => '%count Messages Not Sent')), 'info');
489 if (isset($form->_caseId
)) {
490 // if case-id is found in the url, create case activity record
491 $cases = explode(',', $form->_caseId
);
492 foreach($cases as $key => $val) {
493 if (is_numeric($val)) {
495 'activity_id' => $activityId,
498 CRM_Case_BAO_Case
::processCaseActivity($caseParams);