INFRA-132 - Put space after flow-control (if/switch/for/foreach/while)
[civicrm-core.git] / CRM / Contact / Form / Task / EmailCommon.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
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 */
41class CRM_Contact_Form_Task_EmailCommon {
7da04cde 42 const MAX_EMAILS_KILL_SWITCH = 50;
6a488035
TO
43
44 public $_contactDetails = array();
45 public $_allContactDetails = array();
46 public $_toContactEmails = array();
47
86538308 48 /**
20b22300 49 * @param CRM_Core_Form $form
86538308 50 */
00be9182 51 public static function preProcessFromAddress(&$form) {
6a488035
TO
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'];
3d41f850
DL
77 if (!$email && (count($emails) < 1)) {
78 // set it if no emails are present at all
6a488035
TO
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'];
3d41f850 90 $form->_noEmails = FALSE;
6a488035
TO
91 }
92 }
93
94 $form->_emails[$emailId] = $emails[$emailId];
6a488035
TO
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();
cbf48754 111 $domainFrom = CRM_Core_OptionGroup::values('from_email_address');
6a488035
TO
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);
20b22300
CW
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);
6a488035
TO
130 }
131
132 /**
c490a46a 133 * Build the form object
6a488035 134 *
6a488035 135 *
c490a46a 136 * @param CRM_Core_Form $form
da6b46f4 137 *
6a488035
TO
138 * @return void
139 */
00be9182 140 public static function buildQuickForm(&$form) {
6a488035
TO
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) {
b3dbca23 146 $form->_contactIds = explode(',', $cid);
9cb404b4
N
147 }
148 if (count($form->_contactIds) > 1) {
149 $form->_single = FALSE;
6a488035 150 }
a03d5ab9 151
cac1236c
M
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);
6a488035 158
3f77636a 159 $setDefaults = TRUE;
160 if (property_exists($form, '_context') && $form->_context == 'standalone') {
161 $setDefaults = FALSE;
162 }
163
164 $elements = array('to', 'cc', 'bcc');
16947fa6 165 $form->_allContactIds = $form->_toContactIds = $form->_contactIds;
6a488035
TO
166 foreach ($elements as $element) {
167 if ($$element->getValue()) {
3f77636a 168 $allEmails = explode(',', $$element->getValue());
169 if ($element == 'to') {
16947fa6 170 $form->_toContactIds = $form->_contactIds = array();
6a488035 171 }
6a488035 172
3f77636a 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 case 'cc':
182 $form->_ccContactIds[] = $contactId;
183 break;
184 case 'bcc':
185 $form->_bccContactIds[] = $contactId;
186 break;
187 }
188
189 $form->_allContactIds[] = $contactId;
190 }
6a488035 191 }
3f77636a 192
193 $setDefaults = TRUE;
6a488035 194 }
6a488035
TO
195 }
196
197 //get the group of contacts as per selected by user in case of Find Activities
198 if (!empty($form->_activityHolderIds)) {
199 $contact = $form->get('contacts');
16947fa6 200 $form->_allContactIds = $form->_contactIds = $contact;
6a488035
TO
201 }
202
3f77636a 203 // check if we need to setdefaults and check for valid contact emails / communication preferences
16947fa6 204 if (is_array($form->_allContactIds) && $setDefaults) {
6a488035
TO
205 $returnProperties = array(
206 'sort_name' => 1,
207 'email' => 1,
208 'do_not_email' => 1,
209 'is_deceased' => 1,
210 'on_hold' => 1,
211 'display_name' => 1,
212 'preferred_mail_format' => 1,
213 );
214
3f77636a 215 // get the details for all selected contacts ( to, cc and bcc contacts )
216 list($form->_contactDetails) = CRM_Utils_Token::getTokenDetails($form->_allContactIds,
6a488035
TO
217 $returnProperties,
218 FALSE,
219 FALSE
220 );
221
222 // make a copy of all contact details
223 $form->_allContactDetails = $form->_contactDetails;
224
3f77636a 225 // perform all validations
226 foreach ($form->_allContactIds as $key => $contactId) {
6a488035 227 $value = $form->_contactDetails[$contactId];
8cc574cf 228 if ($value['do_not_email'] || empty($value['email']) || !empty($value['is_deceased']) || $value['on_hold']) {
6a488035
TO
229 $suppressedEmails++;
230
231 // unset contact details for contacts that we won't be sending email. This is prevent extra computation
232 // during token evaluation etc.
233 unset($form->_contactDetails[$contactId]);
234 }
235 else {
3f77636a 236 $email = $value['email'];
237
238 // build array's which are used to setdefaults
239 if (in_array($contactId, $form->_toContactIds)) {
240 $form->_toContactDetails[$contactId] = $form->_contactDetails[$contactId];
8e4aa90c
CW
241 // If a particular address has been specified as the default, use that instead of contact's primary email
242 if (!empty($form->_toEmail) && $form->_toEmail['contact_id'] == $contactId) {
243 $email = $form->_toEmail['email'];
244 }
3f77636a 245 $toArray[] = array(
a03d5ab9 246 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
3f77636a 247 'id' => "$contactId::{$email}",
248 );
249 }
250 elseif (in_array($contactId, $form->_ccContactIds)) {
251 $ccArray[] = array(
a03d5ab9 252 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
3f77636a 253 'id' => "$contactId::{$email}",
254 );
6a488035 255 }
3f77636a 256 elseif (in_array($contactId, $form->_bccContactIds)) {
257 $bccArray[] = array(
a03d5ab9 258 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
3f77636a 259 'id' => "$contactId::{$email}",
260 );
6a488035 261 }
6a488035
TO
262 }
263 }
264
265 if (empty($toArray)) {
266 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.'));
267 }
268 }
269
270 $form->assign('toContact', json_encode($toArray));
3f77636a 271 $form->assign('ccContact', json_encode($ccArray));
272 $form->assign('bccContact', json_encode($bccArray));
273
6a488035
TO
274 $form->assign('suppressedEmails', $suppressedEmails);
275
276 $form->assign('totalSelectedContacts', count($form->_contactIds));
277
278 $form->add('text', 'subject', ts('Subject'), 'size=50 maxlength=254', TRUE);
279
f7305cbc 280 $form->add('select', 'fromEmailAddress', ts('From'), $form->_fromEmails, TRUE, array('class' => 'crm-select2 huge'));
6a488035
TO
281
282 CRM_Mailing_BAO_Mailing::commonCompose($form);
283
284 // add attachments
285 CRM_Core_BAO_File::buildAttachment($form, NULL);
286
287 if ($form->_single) {
288 // also fix the user context stack
289 if ($form->_caseId) {
290 $ccid = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $form->_caseId,
291 'contact_id', 'case_id'
292 );
293 $url = CRM_Utils_System::url('civicrm/contact/view/case',
294 "&reset=1&action=view&cid={$ccid}&id={$form->_caseId}"
295 );
296 }
297 elseif ($form->_context) {
298 $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
299 }
300 else {
301 $url = CRM_Utils_System::url('civicrm/contact/view',
302 "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"
303 );
304 }
305
306 $session = CRM_Core_Session::singleton();
307 $session->replaceUserContext($url);
308 $form->addDefaultButtons(ts('Send Email'), 'upload', 'cancel');
309 }
310 else {
311 $form->addDefaultButtons(ts('Send Email'), 'upload');
312 }
313
314 $form->addFormRule(array('CRM_Contact_Form_Task_EmailCommon', 'formRule'), $form);
28530b98 315 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Task/EmailCommon.js');
6a488035
TO
316 }
317
318 /**
100fef9d 319 * Form rule
6a488035 320 *
77c5b619
TO
321 * @param array $fields
322 * The input form values.
6a488035 323 * @param array $dontCare
77c5b619
TO
324 * @param array $self
325 * Additional values form 'this'.
6a488035
TO
326 *
327 * @return true if no errors, else array of errors
6a488035
TO
328 *
329 */
00be9182 330 public static function formRule($fields, $dontCare, $self) {
6a488035
TO
331 $errors = array();
332 $template = CRM_Core_Smarty::singleton();
333
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);
338 }
339
340 //Added for CRM-1393
a7488080 341 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
6a488035
TO
342 $errors['saveTemplateName'] = ts("Enter name to save message template");
343 }
344
345 return empty($errors) ? TRUE : $errors;
346 }
347
348 /**
100fef9d 349 * Process the form after the input has been submitted and validated
6a488035 350 *
6a488035 351 *
c490a46a 352 * @param CRM_Core_Form $form
fd31fa4c 353 *
355ba699 354 * @return void
6a488035 355 */
00be9182 356 public static function postProcess(&$form) {
6a488035
TO
357 if (count($form->_contactIds) > self::MAX_EMAILS_KILL_SWITCH) {
358 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.',
359 array(1 => self::MAX_EMAILS_KILL_SWITCH)
360 ));
361 }
362
363 // check and ensure that
364 $formValues = $form->controller->exportValues($form->getName());
365
366 $fromEmail = $formValues['fromEmailAddress'];
367 $from = CRM_Utils_Array::value($fromEmail, $form->_emails);
6a488035
TO
368 $subject = $formValues['subject'];
369
3f77636a 370 // CRM-13378: Append CC and BCC information at the end of Activity Details and format cc and bcc fields
371 $elements = array('cc_id', 'bcc_id');
c1d26519 372 $additionalDetails = NULL;
3f77636a 373 $ccValues = $bccValues = array();
c1d26519 374 foreach ($elements as $element) {
a7488080 375 if (!empty($formValues[$element])) {
3f77636a 376 $allEmails = explode(',', $formValues[$element]);
377 foreach ($allEmails as $value) {
378 list($contactId, $email) = explode('::', $value);
379 $contactURL = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$contactId}", true);
380 switch ($element) {
381 case 'cc_id':
382 $ccValues['email'][] = '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>';
383 $ccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>";
384 break;
385 case 'bcc_id':
386 $bccValues['email'][]= '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>';
387 $bccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>";
388 break;
389 }
c1d26519 390 }
c1d26519 391 }
392 }
393
3f77636a 394 $cc = $bcc = '';
395 if (!empty($ccValues)) {
396 $cc = implode(',', $ccValues['email']);
397 $additionalDetails .= "\ncc : " . implode(", ", $ccValues['details']);
398 }
399 if (!empty($bccValues)) {
400 $bcc = implode(',', $bccValues['email']);
401 $additionalDetails .= "\nbcc : " . implode(", ", $bccValues['details']);
402 }
403
6a488035
TO
404 // CRM-5916: prepend case id hash to CiviCase-originating emails’ subjects
405 if (isset($form->_caseId) && is_numeric($form->_caseId)) {
406 $hash = substr(sha1(CIVICRM_SITE_KEY . $form->_caseId), 0, 7);
407 $subject = "[case #$hash] $subject";
408 }
409
410 // process message template
8cc574cf 411 if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) {
6a488035
TO
412 $messageTemplate = array(
413 'msg_text' => $formValues['text_message'],
414 'msg_html' => $formValues['html_message'],
415 'msg_subject' => $formValues['subject'],
416 'is_active' => TRUE,
417 );
418
a7488080 419 if (!empty($formValues['saveTemplate'])) {
6a488035 420 $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
c6327d7d 421 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
6a488035
TO
422 }
423
8cc574cf 424 if (!empty($formValues['template']) && !empty($formValues['updateTemplate'])) {
6a488035
TO
425 $messageTemplate['id'] = $formValues['template'];
426 unset($messageTemplate['msg_title']);
c6327d7d 427 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
6a488035
TO
428 }
429 }
430
431 $attachments = array();
432 CRM_Core_BAO_File::formatAttachment($formValues,
433 $attachments,
434 NULL, NULL
435 );
436
437 // format contact details array to handle multiple emails from same contact
438 $formattedContactDetails = array();
439 $tempEmails = array();
440
441 foreach ($form->_contactIds as $key => $contactId) {
442 // if we dont have details on this contactID, we should ignore
443 // potentially this is due to the contact not wanting to receive email
444 if (!isset($form->_contactDetails[$contactId])) {
445 continue;
446 }
447 $email = $form->_toContactEmails[$key];
448 // prevent duplicate emails if same email address is selected CRM-4067
449 // we should allow same emails for different contacts
450 $emailKey = "{$contactId}::{$email}";
451 if (!in_array($emailKey, $tempEmails)) {
452 $tempEmails[] = $emailKey;
453 $details = $form->_contactDetails[$contactId];
454 $details['email'] = $email;
455 unset($details['email_id']);
456 $formattedContactDetails[] = $details;
457 }
458 }
459
460 // send the mail
461 list($sent, $activityId) = CRM_Activity_BAO_Activity::sendEmail(
462 $formattedContactDetails,
463 $subject,
464 $formValues['text_message'],
465 $formValues['html_message'],
466 NULL,
467 NULL,
468 $from,
469 $attachments,
470 $cc,
471 $bcc,
3f77636a 472 array_keys($form->_toContactDetails),
c1d26519 473 $additionalDetails
6a488035
TO
474 );
475
476 if ($sent) {
3f77636a 477 $count_success = count($form->_toContactDetails);
6a488035
TO
478 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');
479 }
480
a5611c8e
DL
481 // Display the name and number of contacts for those email is not sent.
482 // php 5.4 throws out a notice since the values of these below arrays are arrays.
483 // the behavior is not documented in the php manual, but it does the right thing
484 // suppressing the notices to get things in good shape going forward
485 $emailsNotSent = @array_diff_assoc($form->_allContactDetails, $form->_contactDetails);
6a488035
TO
486
487 if ($emailsNotSent) {
488 $not_sent = array();
489 foreach ($emailsNotSent as $contactId => $values) {
490 $displayName = $values['display_name'];
491 $email = $values['email'];
492 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=$contactId");
493 $not_sent[] = "<a href='$contactViewUrl' title='$email'>$displayName</a>" . ($values['on_hold'] ? '(' . ts('on hold') . ')' : '');
494 }
495 $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>';
496 CRM_Core_Session::setStatus($status, ts('One Message Not Sent', array('count' => count($emailsNotSent), 'plural' => '%count Messages Not Sent')), 'info');
497 }
498
9cb404b4 499 if (isset($form->_caseId)) {
6a488035 500 // if case-id is found in the url, create case activity record
9cb404b4 501 $cases = explode(',', $form->_caseId);
22e263ad 502 foreach ($cases as $key => $val) {
9cb404b4
N
503 if (is_numeric($val)) {
504 $caseParams = array(
505 'activity_id' => $activityId,
506 'case_id' => $val,
507 );
508 CRM_Case_BAO_Case::processCaseActivity($caseParams);
509 }
510 }
6a488035
TO
511 }
512 }
6a488035 513}