Merge pull request #6531 from samuelsov/CRM-16561-bis
[civicrm-core.git] / CRM / Contact / Form / Task / EmailCommon.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35
36 /**
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)
40 */
41 class CRM_Contact_Form_Task_EmailCommon {
42 const MAX_EMAILS_KILL_SWITCH = 50;
43
44 public $_contactDetails = array();
45 public $_allContactDetails = array();
46 public $_toContactEmails = array();
47
48 /**
49 * @param CRM_Core_Form $form
50 */
51 public 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'
57 ) {
58 $form->_single = TRUE;
59 }
60
61 $form->_emails = $emails = array();
62
63 $session = CRM_Core_Session::singleton();
64 $contactID = $session->get('userID');
65
66 $form->_contactIds = array($contactID);
67 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
68
69 $form->_onHold = array();
70
71 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
72 $contactID, 'display_name'
73 );
74
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;
80 }
81 else {
82 if ($email) {
83 if (in_array($email, $emails)) {
84 // CRM-3624
85 continue;
86 }
87
88 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
89 $form->_onHold[$emailId] = $item['on_hold'];
90 $form->_noEmails = FALSE;
91 }
92 }
93
94 $form->_emails[$emailId] = $emails[$emailId];
95 $emails[$emailId] .= $item['locationType'];
96
97 if ($item['is_primary']) {
98 $emails[$emailId] .= ' ' . ts('(preferred)');
99 }
100 $emails[$emailId] = htmlspecialchars($emails[$emailId]);
101 }
102
103 $form->assign('noEmails', $form->_noEmails);
104
105 if ($form->_noEmails) {
106 CRM_Core_Error::statusBounce(ts('Your user record does not have a valid email address'));
107 }
108
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;
116 }
117
118 $form->_fromEmails = CRM_Utils_Array::crmArrayMerge($emails, $domainEmails);
119
120 // Add signature
121 $defaultEmail = civicrm_api3('email', 'getsingle', array('id' => key($form->_fromEmails)));
122 $defaults = array();
123 if (!empty($defaultEmail['signature_html'])) {
124 $defaults['html_message'] = '<br/><br/>--' . $defaultEmail['signature_html'];
125 }
126 if (!empty($defaultEmail['signature_text'])) {
127 $defaults['text_message'] = "\n\n--\n" . $defaultEmail['signature_text'];
128 }
129 $form->setDefaults($defaults);
130 }
131
132 /**
133 * Build the form object.
134 *
135 *
136 * @param CRM_Core_Form $form
137 *
138 * @return void
139 */
140 public static function buildQuickForm(&$form) {
141 $toArray = $ccArray = $bccArray = array();
142 $suppressedEmails = 0;
143 //here we are getting logged in user id as array but we need target contact id. CRM-5988
144 $cid = $form->get('cid');
145 if ($cid) {
146 $form->_contactIds = explode(',', $cid);
147 }
148 if (count($form->_contactIds) > 1) {
149 $form->_single = FALSE;
150 }
151
152 $emailAttributes = array(
153 'class' => 'huge',
154 );
155 $to = $form->add('text', 'to', ts('To'), $emailAttributes, TRUE);
156 $cc = $form->add('text', 'cc_id', ts('CC'), $emailAttributes);
157 $bcc = $form->add('text', 'bcc_id', ts('BCC'), $emailAttributes);
158
159 $setDefaults = TRUE;
160 if (property_exists($form, '_context') && $form->_context == 'standalone') {
161 $setDefaults = FALSE;
162 }
163
164 $elements = array('to', 'cc', 'bcc');
165 $form->_allContactIds = $form->_toContactIds = $form->_contactIds;
166 foreach ($elements as $element) {
167 if ($$element->getValue()) {
168 $allEmails = explode(',', $$element->getValue());
169 if ($element == 'to') {
170 $form->_toContactIds = $form->_contactIds = array();
171 }
172
173 foreach ($allEmails as $value) {
174 list($contactId, $email) = explode('::', $value);
175 if ($contactId) {
176 switch ($element) {
177 case 'to':
178 $form->_contactIds[] = $form->_toContactIds[] = $contactId;
179 $form->_toContactEmails[] = $email;
180 break;
181
182 case 'cc':
183 $form->_ccContactIds[] = $contactId;
184 break;
185
186 case 'bcc':
187 $form->_bccContactIds[] = $contactId;
188 break;
189 }
190
191 $form->_allContactIds[] = $contactId;
192 }
193 }
194
195 $setDefaults = TRUE;
196 }
197 }
198
199 //get the group of contacts as per selected by user in case of Find Activities
200 if (!empty($form->_activityHolderIds)) {
201 $contact = $form->get('contacts');
202 $form->_allContactIds = $form->_contactIds = $contact;
203 }
204
205 // check if we need to setdefaults and check for valid contact emails / communication preferences
206 if (is_array($form->_allContactIds) && $setDefaults) {
207 $returnProperties = array(
208 'sort_name' => 1,
209 'email' => 1,
210 'do_not_email' => 1,
211 'is_deceased' => 1,
212 'on_hold' => 1,
213 'display_name' => 1,
214 'preferred_mail_format' => 1,
215 );
216
217 // get the details for all selected contacts ( to, cc and bcc contacts )
218 list($form->_contactDetails) = CRM_Utils_Token::getTokenDetails($form->_allContactIds,
219 $returnProperties,
220 FALSE,
221 FALSE
222 );
223
224 // make a copy of all contact details
225 $form->_allContactDetails = $form->_contactDetails;
226
227 // perform all validations
228 foreach ($form->_allContactIds as $key => $contactId) {
229 $value = $form->_contactDetails[$contactId];
230 if ($value['do_not_email'] || empty($value['email']) || !empty($value['is_deceased']) || $value['on_hold']) {
231 $suppressedEmails++;
232
233 // unset contact details for contacts that we won't be sending email. This is prevent extra computation
234 // during token evaluation etc.
235 unset($form->_contactDetails[$contactId]);
236 }
237 else {
238 $email = $value['email'];
239
240 // build array's which are used to setdefaults
241 if (in_array($contactId, $form->_toContactIds)) {
242 $form->_toContactDetails[$contactId] = $form->_contactDetails[$contactId];
243 // If a particular address has been specified as the default, use that instead of contact's primary email
244 if (!empty($form->_toEmail) && $form->_toEmail['contact_id'] == $contactId) {
245 $email = $form->_toEmail['email'];
246 }
247 $toArray[] = array(
248 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
249 'id' => "$contactId::{$email}",
250 );
251 }
252 elseif (in_array($contactId, $form->_ccContactIds)) {
253 $ccArray[] = array(
254 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
255 'id' => "$contactId::{$email}",
256 );
257 }
258 elseif (in_array($contactId, $form->_bccContactIds)) {
259 $bccArray[] = array(
260 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
261 'id' => "$contactId::{$email}",
262 );
263 }
264 }
265 }
266
267 if (empty($toArray)) {
268 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.'));
269 }
270 }
271
272 $form->assign('toContact', json_encode($toArray));
273 $form->assign('ccContact', json_encode($ccArray));
274 $form->assign('bccContact', json_encode($bccArray));
275
276 $form->assign('suppressedEmails', $suppressedEmails);
277
278 $form->assign('totalSelectedContacts', count($form->_contactIds));
279
280 $form->add('text', 'subject', ts('Subject'), 'size=50 maxlength=254', TRUE);
281
282 $form->add('select', 'fromEmailAddress', ts('From'), $form->_fromEmails, TRUE, array('class' => 'crm-select2 huge'));
283
284 CRM_Mailing_BAO_Mailing::commonCompose($form);
285
286 // add attachments
287 CRM_Core_BAO_File::buildAttachment($form, NULL);
288
289 if ($form->_single) {
290 // also fix the user context stack
291 if ($form->_caseId) {
292 $ccid = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $form->_caseId,
293 'contact_id', 'case_id'
294 );
295 $url = CRM_Utils_System::url('civicrm/contact/view/case',
296 "&reset=1&action=view&cid={$ccid}&id={$form->_caseId}"
297 );
298 }
299 elseif ($form->_context) {
300 $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
301 }
302 else {
303 $url = CRM_Utils_System::url('civicrm/contact/view',
304 "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"
305 );
306 }
307
308 $session = CRM_Core_Session::singleton();
309 $session->replaceUserContext($url);
310 $form->addDefaultButtons(ts('Send Email'), 'upload', 'cancel');
311 }
312 else {
313 $form->addDefaultButtons(ts('Send Email'), 'upload');
314 }
315
316 $fields = array(
317 'followup_assignee_contact_id' => array(
318 'type' => 'entityRef',
319 'label' => ts('Assigned to'),
320 'attributes' => array(
321 'multiple' => TRUE,
322 'create' => TRUE,
323 'api' => array('params' => array('is_deceased' => 0)),
324 ),
325 ),
326 'followup_activity_type_id' => array(
327 'type' => 'select',
328 'label' => ts('Followup Activity'),
329 'attributes' => array('' => '- ' . ts('select activity') . ' -') + CRM_Core_PseudoConstant::ActivityType(FALSE),
330 'extra' => array('class' => 'crm-select2'),
331 ),
332 'followup_activity_subject' => array(
333 'type' => 'text',
334 'label' => ts('Subject'),
335 'attributes' => CRM_Core_DAO::getAttribute('CRM_Activity_DAO_Activity',
336 'subject'
337 ),
338 ),
339 );
340
341 //add followup date
342 $form->addDateTime('followup_date', ts('in'), FALSE, array('formatType' => 'activityDateTime'));
343
344 foreach ($fields as $field => $values) {
345 if (!empty($fields[$field])) {
346 $attribute = CRM_Utils_Array::value('attributes', $values);
347 $required = !empty($values['required']);
348
349 if ($values['type'] == 'select' && empty($attribute)) {
350 $form->addSelect($field, array('entity' => 'activity'), $required);
351 }
352 elseif ($values['type'] == 'entityRef') {
353 $form->addEntityRef($field, $values['label'], $attribute, $required);
354 }
355 else {
356 $form->add($values['type'], $field, $values['label'], $attribute, $required, CRM_Utils_Array::value('extra', $values));
357 }
358 }
359 }
360
361 $form->addFormRule(array('CRM_Contact_Form_Task_EmailCommon', 'formRule'), $form);
362 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Task/EmailCommon.js', 0, 'html-header');
363 }
364
365 /**
366 * Form rule.
367 *
368 * @param array $fields
369 * The input form values.
370 * @param array $dontCare
371 * @param array $self
372 * Additional values form 'this'.
373 *
374 * @return bool|array
375 * true if no errors, else array of errors
376 */
377 public static function formRule($fields, $dontCare, $self) {
378 $errors = array();
379 $template = CRM_Core_Smarty::singleton();
380
381 if (isset($fields['html_message'])) {
382 $htmlMessage = str_replace(array("\n", "\r"), ' ', $fields['html_message']);
383 $htmlMessage = str_replace('"', '\"', $htmlMessage);
384 $template->assign('htmlContent', $htmlMessage);
385 }
386
387 //Added for CRM-1393
388 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
389 $errors['saveTemplateName'] = ts("Enter name to save message template");
390 }
391
392 return empty($errors) ? TRUE : $errors;
393 }
394
395 /**
396 * Process the form after the input has been submitted and validated.
397 *
398 *
399 * @param CRM_Core_Form $form
400 *
401 * @return void
402 */
403 public static function postProcess(&$form) {
404 if (count($form->_contactIds) > self::MAX_EMAILS_KILL_SWITCH) {
405 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.',
406 array(1 => self::MAX_EMAILS_KILL_SWITCH)
407 ));
408 }
409
410 // check and ensure that
411 $formValues = $form->controller->exportValues($form->getName());
412 $fromEmail = $formValues['fromEmailAddress'];
413 $from = CRM_Utils_Array::value($fromEmail, $form->_emails);
414 $subject = $formValues['subject'];
415
416 // CRM-13378: Append CC and BCC information at the end of Activity Details and format cc and bcc fields
417 $elements = array('cc_id', 'bcc_id');
418 $additionalDetails = NULL;
419 $ccValues = $bccValues = array();
420 foreach ($elements as $element) {
421 if (!empty($formValues[$element])) {
422 $allEmails = explode(',', $formValues[$element]);
423 foreach ($allEmails as $value) {
424 list($contactId, $email) = explode('::', $value);
425 $contactURL = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$contactId}", TRUE);
426 switch ($element) {
427 case 'cc_id':
428 $ccValues['email'][] = '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>';
429 $ccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>";
430 break;
431
432 case 'bcc_id':
433 $bccValues['email'][] = '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>';
434 $bccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>";
435 break;
436 }
437 }
438 }
439 }
440
441 $cc = $bcc = '';
442 if (!empty($ccValues)) {
443 $cc = implode(',', $ccValues['email']);
444 $additionalDetails .= "\ncc : " . implode(", ", $ccValues['details']);
445 }
446 if (!empty($bccValues)) {
447 $bcc = implode(',', $bccValues['email']);
448 $additionalDetails .= "\nbcc : " . implode(", ", $bccValues['details']);
449 }
450
451 // CRM-5916: prepend case id hash to CiviCase-originating emails’ subjects
452 if (isset($form->_caseId) && is_numeric($form->_caseId)) {
453 $hash = substr(sha1(CIVICRM_SITE_KEY . $form->_caseId), 0, 7);
454 $subject = "[case #$hash] $subject";
455 }
456
457 // process message template
458 if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) {
459 $messageTemplate = array(
460 'msg_text' => $formValues['text_message'],
461 'msg_html' => $formValues['html_message'],
462 'msg_subject' => $formValues['subject'],
463 'is_active' => TRUE,
464 );
465
466 if (!empty($formValues['saveTemplate'])) {
467 $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
468 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
469 }
470
471 if (!empty($formValues['template']) && !empty($formValues['updateTemplate'])) {
472 $messageTemplate['id'] = $formValues['template'];
473 unset($messageTemplate['msg_title']);
474 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
475 }
476 }
477
478 $attachments = array();
479 CRM_Core_BAO_File::formatAttachment($formValues,
480 $attachments,
481 NULL, NULL
482 );
483
484 // format contact details array to handle multiple emails from same contact
485 $formattedContactDetails = array();
486 $tempEmails = array();
487 foreach ($form->_contactIds as $key => $contactId) {
488 // if we dont have details on this contactID, we should ignore
489 // potentially this is due to the contact not wanting to receive email
490 if (!isset($form->_contactDetails[$contactId])) {
491 continue;
492 }
493 $email = $form->_toContactEmails[$key];
494 // prevent duplicate emails if same email address is selected CRM-4067
495 // we should allow same emails for different contacts
496 $emailKey = "{$contactId}::{$email}";
497 if (!in_array($emailKey, $tempEmails)) {
498 $tempEmails[] = $emailKey;
499 $details = $form->_contactDetails[$contactId];
500 $details['email'] = $email;
501 unset($details['email_id']);
502 $formattedContactDetails[] = $details;
503 }
504 }
505
506 // send the mail
507 list($sent, $activityId) = CRM_Activity_BAO_Activity::sendEmail(
508 $formattedContactDetails,
509 $subject,
510 $formValues['text_message'],
511 $formValues['html_message'],
512 NULL,
513 NULL,
514 $from,
515 $attachments,
516 $cc,
517 $bcc,
518 array_keys($form->_toContactDetails),
519 $additionalDetails
520 );
521
522 $followupStatus = '';
523 if ($sent) {
524 $followupActivity = NULL;
525 if (!empty($formValues['followup_activity_type_id'])) {
526 $params['followup_activity_type_id'] = $formValues['followup_activity_type_id'];
527 $params['followup_activity_subject'] = $formValues['followup_activity_subject'];
528 $params['followup_date'] = $formValues['followup_date'];
529 $params['followup_date_time'] = $formValues['followup_date_time'];
530 $params['target_contact_id'] = $form->_contactIds;
531 $params['followup_assignee_contact_id'] = explode(',', $formValues['followup_assignee_contact_id']);
532 $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activityId, $params);
533 $followupStatus = ts('A followup activity has been scheduled.');
534
535 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'activity_assignee_notification')) {
536 if ($followupActivity) {
537 $mailToFollowupContacts = array();
538 $assignee = array($followupActivity->id);
539 $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($assignee, TRUE, FALSE);
540 foreach ($assigneeContacts as $values) {
541 $mailToFollowupContacts[$values['email']] = $values;
542 }
543
544 $sentFollowup = CRM_Activity_BAO_Activity::sendToAssignee($followupActivity, $mailToFollowupContacts);
545 if ($sentFollowup) {
546 $followupStatus .= '<br />' . ts("A copy of the follow-up activity has also been sent to follow-up assignee contacts(s).");
547 }
548 }
549 }
550 }
551
552 $count_success = count($form->_toContactDetails);
553 CRM_Core_Session::setStatus(ts('One message was sent successfully. ', array(
554 'plural' => '%count messages were sent successfully. ',
555 'count' => $count_success,
556 )) . $followupStatus, ts('Message Sent', array('plural' => 'Messages Sent', 'count' => $count_success)), 'success');
557 }
558
559 // Display the name and number of contacts for those email is not sent.
560 // php 5.4 throws out a notice since the values of these below arrays are arrays.
561 // the behavior is not documented in the php manual, but it does the right thing
562 // suppressing the notices to get things in good shape going forward
563 $emailsNotSent = @array_diff_assoc($form->_allContactDetails, $form->_contactDetails);
564
565 if ($emailsNotSent) {
566 $not_sent = array();
567 foreach ($emailsNotSent as $contactId => $values) {
568 $displayName = $values['display_name'];
569 $email = $values['email'];
570 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=$contactId");
571 $not_sent[] = "<a href='$contactViewUrl' title='$email'>$displayName</a>" . ($values['on_hold'] ? '(' . ts('on hold') . ')' : '');
572 }
573 $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>';
574 CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array(
575 'count' => count($emailsNotSent),
576 'plural' => '%count Messages Not Sent',
577 )), 'info');
578 }
579
580 if (isset($form->_caseId)) {
581 // if case-id is found in the url, create case activity record
582 $cases = explode(',', $form->_caseId);
583 foreach ($cases as $key => $val) {
584 if (is_numeric($val)) {
585 $caseParams = array(
586 'activity_id' => $activityId,
587 'case_id' => $val,
588 );
589 CRM_Case_BAO_Case::processCaseActivity($caseParams);
590 }
591 }
592 }
593 }
594
595 }