Merge pull request #18360 from colemanw/fixMultiInProfile
[civicrm-core.git] / CRM / Contact / Form / Task / EmailCommon.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class provides the common functionality for sending email to
20 * one or a group of contact ids. This class is reused by all the search
21 * components in CiviCRM (since they all have send email as a task)
22 */
23 class CRM_Contact_Form_Task_EmailCommon {
24
25 const MAX_EMAILS_KILL_SWITCH = 50;
26
27 public $_contactDetails = [];
28
29 public $_allContactDetails = [];
30
31 public $_toContactEmails = [];
32
33 /**
34 * Pre Process Form Addresses to be used in Quickform
35 *
36 * @param CRM_Core_Form $form
37 * @param bool $bounce determine if we want to throw a status bounce.
38 *
39 * @throws \CiviCRM_API3_Exception
40 */
41 public static function preProcessFromAddress(&$form, $bounce = TRUE) {
42 if (!isset($form->_single)) {
43 // @todo ensure this is already set.
44 $form->_single = FALSE;
45 }
46
47 $form->_emails = [];
48
49 // @TODO remove these line and to it somewhere more appropriate. Currently some classes (e.g Case
50 // are having to re-write contactIds afterwards due to this inappropriate variable setting
51 // If we don't have any contact IDs, use the logged in contact ID
52 $form->_contactIds = $form->_contactIds ?: [CRM_Core_Session::getLoggedInContactID()];
53
54 $fromEmailValues = CRM_Core_BAO_Email::getFromEmail();
55
56 if ($bounce) {
57 if (empty($fromEmailValues)) {
58 CRM_Core_Error::statusBounce(ts('Your user record does not have a valid email address and no from addresses have been configured.'));
59 }
60 }
61
62 $form->_emails = $fromEmailValues;
63 $defaults = [];
64 $form->_fromEmails = $fromEmailValues;
65 if (!Civi::settings()->get('allow_mail_from_logged_in_contact')) {
66 $defaults['from_email_address'] = current(CRM_Core_BAO_Domain::getNameAndEmail(FALSE, TRUE));
67 }
68 if (is_numeric(key($form->_fromEmails))) {
69 // Add signature
70 $defaultEmail = civicrm_api3('email', 'getsingle', ['id' => key($form->_fromEmails)]);
71 $defaults = [];
72 if (!empty($defaultEmail['signature_html'])) {
73 $defaults['html_message'] = '<br/><br/>--' . $defaultEmail['signature_html'];
74 }
75 if (!empty($defaultEmail['signature_text'])) {
76 $defaults['text_message'] = "\n\n--\n" . $defaultEmail['signature_text'];
77 }
78 }
79 $form->setDefaults($defaults);
80 }
81
82 /**
83 * Build the form object.
84 *
85 * @param CRM_Core_Form $form
86 *
87 * @throws \CRM_Core_Exception
88 */
89 public static function buildQuickForm(&$form) {
90 CRM_Core_Error::deprecatedFunctionWarning('This code is no longer used in core and will be removed');
91 $toArray = $ccArray = $bccArray = [];
92 $suppressedEmails = 0;
93 //here we are getting logged in user id as array but we need target contact id. CRM-5988
94 $cid = $form->get('cid');
95 if ($cid) {
96 $form->_contactIds = explode(',', $cid);
97 }
98 if (count($form->_contactIds) > 1) {
99 $form->_single = FALSE;
100 }
101 CRM_Contact_Form_Task_EmailCommon::bounceIfSimpleMailLimitExceeded(count($form->_contactIds));
102
103 $emailAttributes = [
104 'class' => 'huge',
105 ];
106 $to = $form->add('text', 'to', ts('To'), $emailAttributes, TRUE);
107 $cc = $form->add('text', 'cc_id', ts('CC'), $emailAttributes);
108 $bcc = $form->add('text', 'bcc_id', ts('BCC'), $emailAttributes);
109
110 if ($to->getValue()) {
111 $form->_toContactIds = $form->_contactIds = [];
112 }
113 $setDefaults = TRUE;
114 if (property_exists($form, '_context') && $form->_context == 'standalone') {
115 $setDefaults = FALSE;
116 }
117
118 $elements = ['to', 'cc', 'bcc'];
119 $form->_allContactIds = $form->_toContactIds = $form->_contactIds;
120 foreach ($elements as $element) {
121 if ($$element->getValue()) {
122
123 foreach (self::getEmails($$element) as $value) {
124 $contactId = $value['contact_id'];
125 $email = $value['email'];
126 if ($contactId) {
127 switch ($element) {
128 case 'to':
129 $form->_contactIds[] = $form->_toContactIds[] = $contactId;
130 $form->_toContactEmails[] = $email;
131 break;
132
133 case 'cc':
134 $form->_ccContactIds[] = $contactId;
135 break;
136
137 case 'bcc':
138 $form->_bccContactIds[] = $contactId;
139 break;
140 }
141
142 $form->_allContactIds[] = $contactId;
143 }
144 }
145
146 $setDefaults = TRUE;
147 }
148 }
149
150 //get the group of contacts as per selected by user in case of Find Activities
151 if (!empty($form->_activityHolderIds)) {
152 $contact = $form->get('contacts');
153 $form->_allContactIds = $form->_contactIds = $contact;
154 }
155
156 // check if we need to setdefaults and check for valid contact emails / communication preferences
157 if (is_array($form->_allContactIds) && $setDefaults) {
158 $returnProperties = [
159 'sort_name' => 1,
160 'email' => 1,
161 'do_not_email' => 1,
162 'is_deceased' => 1,
163 'on_hold' => 1,
164 'display_name' => 1,
165 'preferred_mail_format' => 1,
166 ];
167
168 // get the details for all selected contacts ( to, cc and bcc contacts )
169 list($form->_contactDetails) = CRM_Utils_Token::getTokenDetails($form->_allContactIds,
170 $returnProperties,
171 FALSE,
172 FALSE
173 );
174
175 // make a copy of all contact details
176 $form->_allContactDetails = $form->_contactDetails;
177
178 // perform all validations on unique contact Ids
179 foreach (array_unique($form->_allContactIds) as $key => $contactId) {
180 $value = $form->_contactDetails[$contactId];
181 if ($value['do_not_email'] || empty($value['email']) || !empty($value['is_deceased']) || $value['on_hold']) {
182 $suppressedEmails++;
183
184 // unset contact details for contacts that we won't be sending email. This is prevent extra computation
185 // during token evaluation etc.
186 unset($form->_contactDetails[$contactId]);
187 }
188 else {
189 $email = $value['email'];
190
191 // build array's which are used to setdefaults
192 if (in_array($contactId, $form->_toContactIds)) {
193 $form->_toContactDetails[$contactId] = $form->_contactDetails[$contactId];
194 // If a particular address has been specified as the default, use that instead of contact's primary email
195 if (!empty($form->_toEmail) && $form->_toEmail['contact_id'] == $contactId) {
196 $email = $form->_toEmail['email'];
197 }
198 $toArray[] = [
199 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
200 'id' => "$contactId::{$email}",
201 ];
202 }
203 elseif (in_array($contactId, $form->_ccContactIds)) {
204 $ccArray[] = [
205 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
206 'id' => "$contactId::{$email}",
207 ];
208 }
209 elseif (in_array($contactId, $form->_bccContactIds)) {
210 $bccArray[] = [
211 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
212 'id' => "$contactId::{$email}",
213 ];
214 }
215 }
216 }
217
218 if (empty($toArray)) {
219 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.'));
220 }
221 }
222
223 $form->assign('toContact', json_encode($toArray));
224 $form->assign('ccContact', json_encode($ccArray));
225 $form->assign('bccContact', json_encode($bccArray));
226
227 $form->assign('suppressedEmails', $suppressedEmails);
228
229 $form->assign('totalSelectedContacts', count($form->_contactIds));
230
231 $form->add('text', 'subject', ts('Subject'), 'size=50 maxlength=254', TRUE);
232
233 $form->add('select', 'from_email_address', ts('From'), $form->_fromEmails, TRUE);
234
235 CRM_Mailing_BAO_Mailing::commonCompose($form);
236
237 // add attachments
238 CRM_Core_BAO_File::buildAttachment($form, NULL);
239
240 if ($form->_single) {
241 // also fix the user context stack
242 if ($form->_caseId) {
243 $ccid = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $form->_caseId,
244 'contact_id', 'case_id'
245 );
246 $url = CRM_Utils_System::url('civicrm/contact/view/case',
247 "&reset=1&action=view&cid={$ccid}&id={$form->_caseId}"
248 );
249 }
250 elseif ($form->_context) {
251 $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
252 }
253 else {
254 $url = CRM_Utils_System::url('civicrm/contact/view',
255 "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"
256 );
257 }
258
259 $session = CRM_Core_Session::singleton();
260 $session->replaceUserContext($url);
261 $form->addDefaultButtons(ts('Send Email'), 'upload', 'cancel');
262 }
263 else {
264 $form->addDefaultButtons(ts('Send Email'), 'upload');
265 }
266
267 $fields = [
268 'followup_assignee_contact_id' => [
269 'type' => 'entityRef',
270 'label' => ts('Assigned to'),
271 'attributes' => [
272 'multiple' => TRUE,
273 'create' => TRUE,
274 'api' => ['params' => ['is_deceased' => 0]],
275 ],
276 ],
277 'followup_activity_type_id' => [
278 'type' => 'select',
279 'label' => ts('Followup Activity'),
280 'attributes' => ['' => '- ' . ts('select activity') . ' -'] + CRM_Core_PseudoConstant::ActivityType(FALSE),
281 'extra' => ['class' => 'crm-select2'],
282 ],
283 'followup_activity_subject' => [
284 'type' => 'text',
285 'label' => ts('Subject'),
286 'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity',
287 'subject'
288 ),
289 ],
290 ];
291
292 //add followup date
293 $form->add('datepicker', 'followup_date', ts('in'));
294
295 foreach ($fields as $field => $values) {
296 if (!empty($fields[$field])) {
297 $attribute = $values['attributes'] ?? NULL;
298 $required = !empty($values['required']);
299
300 if ($values['type'] == 'select' && empty($attribute)) {
301 $form->addSelect($field, ['entity' => 'activity'], $required);
302 }
303 elseif ($values['type'] == 'entityRef') {
304 $form->addEntityRef($field, $values['label'], $attribute, $required);
305 }
306 else {
307 $form->add($values['type'], $field, $values['label'], $attribute, $required, CRM_Utils_Array::value('extra', $values));
308 }
309 }
310 }
311
312 //Added for CRM-15984: Add campaign field
313 CRM_Campaign_BAO_Campaign::addCampaign($form);
314
315 $form->addFormRule(['CRM_Contact_Form_Task_EmailCommon', 'formRule'], $form);
316 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Task/EmailCommon.js', 0, 'html-header');
317 }
318
319 /**
320 * Form rule.
321 *
322 * @param array $fields
323 * The input form values.
324 * @param array $dontCare
325 * @param array $self
326 * Additional values form 'this'.
327 *
328 * @return bool|array
329 * true if no errors, else array of errors
330 */
331 public static function formRule($fields, $dontCare, $self) {
332 $errors = [];
333 $template = CRM_Core_Smarty::singleton();
334
335 if (isset($fields['html_message'])) {
336 $htmlMessage = str_replace(["\n", "\r"], ' ', $fields['html_message']);
337 $htmlMessage = str_replace('"', '\"', $htmlMessage);
338 $template->assign('htmlContent', $htmlMessage);
339 }
340
341 //Added for CRM-1393
342 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
343 $errors['saveTemplateName'] = ts("Enter name to save message template");
344 }
345
346 return empty($errors) ? TRUE : $errors;
347 }
348
349 /**
350 * Process the form after the input has been submitted and validated.
351 *
352 * @param CRM_Core_Form $form
353 *
354 * @throws \CRM_Core_Exception
355 * @throws \CiviCRM_API3_Exception
356 * @throws \Civi\API\Exception\UnauthorizedException
357 */
358 public static function postProcess(&$form) {
359 CRM_Core_Error::deprecatedFunctionWarning('This code is no longer used in core and will be removed');
360
361 self::bounceIfSimpleMailLimitExceeded(count($form->_contactIds));
362
363 // check and ensure that
364 $formValues = $form->controller->exportValues($form->getName());
365 self::submit($form, $formValues);
366 }
367
368 /**
369 * Submit the form values.
370 *
371 * This is also accessible for testing.
372 *
373 * @param CRM_Core_Form $form
374 * @param array $formValues
375 *
376 * @throws \CRM_Core_Exception
377 * @throws \CiviCRM_API3_Exception
378 * @throws \Civi\API\Exception\UnauthorizedException
379 */
380 public static function submit(&$form, $formValues) {
381 CRM_Core_Error::deprecatedFunctionWarning('This code is no longer used in core and will be removed');
382
383 self::saveMessageTemplate($formValues);
384
385 $from = $formValues['from_email_address'] ?? NULL;
386 // dev/core#357 User Emails are keyed by their id so that the Signature is able to be added
387 // If we have had a contact email used here the value returned from the line above will be the
388 // numerical key where as $from for use in the sendEmail in Activity needs to be of format of "To Name" <toemailaddress>
389 $from = CRM_Utils_Mail::formatFromAddress($from);
390 $subject = $formValues['subject'];
391
392 // CRM-13378: Append CC and BCC information at the end of Activity Details and format cc and bcc fields
393 $elements = ['cc_id', 'bcc_id'];
394 $additionalDetails = NULL;
395 $ccValues = $bccValues = [];
396 foreach ($elements as $element) {
397 if (!empty($formValues[$element])) {
398 $allEmails = explode(',', $formValues[$element]);
399 foreach ($allEmails as $value) {
400 list($contactId, $email) = explode('::', $value);
401 $contactURL = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$contactId}", TRUE);
402 switch ($element) {
403 case 'cc_id':
404 $ccValues['email'][] = '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>';
405 $ccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>";
406 break;
407
408 case 'bcc_id':
409 $bccValues['email'][] = '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>';
410 $bccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>";
411 break;
412 }
413 }
414 }
415 }
416
417 $cc = $bcc = '';
418 if (!empty($ccValues)) {
419 $cc = implode(',', $ccValues['email']);
420 $additionalDetails .= "\ncc : " . implode(", ", $ccValues['details']);
421 }
422 if (!empty($bccValues)) {
423 $bcc = implode(',', $bccValues['email']);
424 $additionalDetails .= "\nbcc : " . implode(", ", $bccValues['details']);
425 }
426
427 // CRM-5916: prepend case id hash to CiviCase-originating emails’ subjects
428 if (isset($form->_caseId) && is_numeric($form->_caseId)) {
429 $hash = substr(sha1(CIVICRM_SITE_KEY . $form->_caseId), 0, 7);
430 $subject = "[case #$hash] $subject";
431 }
432
433 $attachments = [];
434 CRM_Core_BAO_File::formatAttachment($formValues,
435 $attachments,
436 NULL, NULL
437 );
438
439 // format contact details array to handle multiple emails from same contact
440 $formattedContactDetails = [];
441 $tempEmails = [];
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])) {
446 continue;
447 }
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;
458 }
459 }
460
461 $contributionIds = [];
462 if ($form->getVar('_contributionIds')) {
463 $contributionIds = $form->getVar('_contributionIds');
464 }
465
466 // send the mail
467 list($sent, $activityId) = CRM_Activity_BAO_Activity::sendEmail(
468 $formattedContactDetails,
469 $subject,
470 $formValues['text_message'],
471 $formValues['html_message'],
472 NULL,
473 NULL,
474 $from,
475 $attachments,
476 $cc,
477 $bcc,
478 array_keys($form->_toContactDetails),
479 $additionalDetails,
480 $contributionIds,
481 CRM_Utils_Array::value('campaign_id', $formValues),
482 $form->getVar('_caseId')
483 );
484
485 $followupStatus = '';
486 if ($sent) {
487 $followupActivity = NULL;
488 if (!empty($formValues['followup_activity_type_id'])) {
489 $params['followup_activity_type_id'] = $formValues['followup_activity_type_id'];
490 $params['followup_activity_subject'] = $formValues['followup_activity_subject'];
491 $params['followup_date'] = $formValues['followup_date'];
492 $params['target_contact_id'] = $form->_contactIds;
493 $params['followup_assignee_contact_id'] = explode(',', $formValues['followup_assignee_contact_id']);
494 $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activityId, $params);
495 $followupStatus = ts('A followup activity has been scheduled.');
496
497 if (Civi::settings()->get('activity_assignee_notification')) {
498 if ($followupActivity) {
499 $mailToFollowupContacts = [];
500 $assignee = [$followupActivity->id];
501 $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($assignee, TRUE, FALSE);
502 foreach ($assigneeContacts as $values) {
503 $mailToFollowupContacts[$values['email']] = $values;
504 }
505
506 $sentFollowup = CRM_Activity_BAO_Activity::sendToAssignee($followupActivity, $mailToFollowupContacts);
507 if ($sentFollowup) {
508 $followupStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s).");
509 }
510 }
511 }
512 }
513
514 $count_success = count($form->_toContactDetails);
515 CRM_Core_Session::setStatus(ts('One message was sent successfully. ', [
516 'plural' => '%count messages were sent successfully. ',
517 'count' => $count_success,
518 ]) . $followupStatus, ts('Message Sent', ['plural' => 'Messages Sent', 'count' => $count_success]), 'success');
519 }
520
521 // Display the name and number of contacts for those email is not sent.
522 // php 5.4 throws out a notice since the values of these below arrays are arrays.
523 // the behavior is not documented in the php manual, but it does the right thing
524 // suppressing the notices to get things in good shape going forward
525 $emailsNotSent = @array_diff_assoc($form->_allContactDetails, $form->_contactDetails);
526
527 if ($emailsNotSent) {
528 $not_sent = [];
529 foreach ($emailsNotSent as $contactId => $values) {
530 $displayName = $values['display_name'];
531 $email = $values['email'];
532 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=$contactId");
533 $not_sent[] = "<a href='$contactViewUrl' title='$email'>$displayName</a>" . ($values['on_hold'] ? '(' . ts('on hold') . ')' : '');
534 }
535 $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>';
536 CRM_Core_Session::setStatus($status, ts('One Message Not Sent', [
537 'count' => count($emailsNotSent),
538 'plural' => '%count Messages Not Sent',
539 ]), 'info');
540 }
541
542 if (isset($form->_caseId)) {
543 // if case-id is found in the url, create case activity record
544 $cases = explode(',', $form->_caseId);
545 foreach ($cases as $key => $val) {
546 if (is_numeric($val)) {
547 $caseParams = [
548 'activity_id' => $activityId,
549 'case_id' => $val,
550 ];
551 CRM_Case_BAO_Case::processCaseActivity($caseParams);
552 }
553 }
554 }
555 }
556
557 /**
558 * Save the template if update selected.
559 *
560 * @param array $formValues
561 *
562 * @throws \CiviCRM_API3_Exception
563 * @throws \Civi\API\Exception\UnauthorizedException
564 */
565 protected static function saveMessageTemplate($formValues) {
566 CRM_Core_Error::deprecatedFunctionWarning('This code is no longer used in core and will be removed');
567
568 if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) {
569 $messageTemplate = [
570 'msg_text' => $formValues['text_message'],
571 'msg_html' => $formValues['html_message'],
572 'msg_subject' => $formValues['subject'],
573 'is_active' => TRUE,
574 ];
575
576 if (!empty($formValues['saveTemplate'])) {
577 $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
578 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
579 }
580
581 if (!empty($formValues['template']) && !empty($formValues['updateTemplate'])) {
582 $messageTemplate['id'] = $formValues['template'];
583 unset($messageTemplate['msg_title']);
584 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
585 }
586 }
587 }
588
589 /**
590 * Bounce if there are more emails than permitted.
591 *
592 * @param int $count
593 * The number of emails the user is attempting to send
594 */
595 public static function bounceIfSimpleMailLimitExceeded($count) {
596 CRM_Core_Error::deprecatedFunctionWarning('This code is no longer used in core and will be removed');
597
598 $limit = Civi::settings()->get('simple_mail_limit');
599 if ($count > $limit) {
600 CRM_Core_Error::statusBounce(ts('Please do not use this task to send a lot of emails (greater than %1). Many countries have legal requirements when sending bulk emails and the CiviMail framework has opt out functionality and domain tokens to help meet these.',
601 [1 => $limit]
602 ));
603 }
604 }
605
606 /**
607 * Get the emails from the added element.
608 *
609 * @param HTML_QuickForm_Element $element
610 *
611 * @return array
612 */
613 protected static function getEmails($element): array {
614 CRM_Core_Error::deprecatedFunctionWarning('This code is no longer used in core and will be removed');
615
616 $allEmails = explode(',', $element->getValue());
617 $return = [];
618 foreach ($allEmails as $value) {
619 $values = explode('::', $value);
620 $return[] = ['contact_id' => $values[0], 'email' => $values[1]];
621 }
622 return $return;
623 }
624
625 }