CRM-15278 - Fix email signature on itinial form load
[civicrm-core.git] / CRM / Contact / Form / Task / EmailCommon.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
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 {
42 CONST MAX_EMAILS_KILL_SWITCH = 50;
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 */
6a488035
TO
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'
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 /**
133 * Build the form
134 *
135 * @access public
136 *
da6b46f4
EM
137 * @param $form
138 *
6a488035
TO
139 * @return void
140 */
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');
146 if ($cid) {
b3dbca23 147 $form->_contactIds = explode(',', $cid);
9cb404b4
N
148 }
149 if (count($form->_contactIds) > 1) {
150 $form->_single = FALSE;
6a488035 151 }
a03d5ab9 152
cac1236c
M
153 $emailAttributes = array(
154 'class' => 'huge',
155 );
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);
6a488035 159
3f77636a 160 $setDefaults = TRUE;
161 if (property_exists($form, '_context') && $form->_context == 'standalone') {
162 $setDefaults = FALSE;
163 }
164
165 $elements = array('to', 'cc', 'bcc');
16947fa6 166 $form->_allContactIds = $form->_toContactIds = $form->_contactIds;
6a488035
TO
167 foreach ($elements as $element) {
168 if ($$element->getValue()) {
3f77636a 169 $allEmails = explode(',', $$element->getValue());
170 if ($element == 'to') {
16947fa6 171 $form->_toContactIds = $form->_contactIds = array();
6a488035 172 }
6a488035 173
3f77636a 174 foreach ($allEmails as $value) {
175 list($contactId, $email) = explode('::', $value);
176 if ($contactId) {
177 switch ($element) {
178 case 'to':
179 $form->_contactIds[] = $form->_toContactIds[] = $contactId;
180 $form->_toContactEmails[] = $email;
181 break;
182 case 'cc':
183 $form->_ccContactIds[] = $contactId;
184 break;
185 case 'bcc':
186 $form->_bccContactIds[] = $contactId;
187 break;
188 }
189
190 $form->_allContactIds[] = $contactId;
191 }
6a488035 192 }
3f77636a 193
194 $setDefaults = TRUE;
6a488035 195 }
6a488035
TO
196 }
197
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');
16947fa6 201 $form->_allContactIds = $form->_contactIds = $contact;
6a488035
TO
202 }
203
3f77636a 204 // check if we need to setdefaults and check for valid contact emails / communication preferences
16947fa6 205 if (is_array($form->_allContactIds) && $setDefaults) {
6a488035
TO
206 $returnProperties = array(
207 'sort_name' => 1,
208 'email' => 1,
209 'do_not_email' => 1,
210 'is_deceased' => 1,
211 'on_hold' => 1,
212 'display_name' => 1,
213 'preferred_mail_format' => 1,
214 );
215
3f77636a 216 // get the details for all selected contacts ( to, cc and bcc contacts )
217 list($form->_contactDetails) = CRM_Utils_Token::getTokenDetails($form->_allContactIds,
6a488035
TO
218 $returnProperties,
219 FALSE,
220 FALSE
221 );
222
223 // make a copy of all contact details
224 $form->_allContactDetails = $form->_contactDetails;
225
3f77636a 226 // perform all validations
227 foreach ($form->_allContactIds as $key => $contactId) {
6a488035 228 $value = $form->_contactDetails[$contactId];
8cc574cf 229 if ($value['do_not_email'] || empty($value['email']) || !empty($value['is_deceased']) || $value['on_hold']) {
6a488035
TO
230 $suppressedEmails++;
231
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]);
235 }
236 else {
3f77636a 237 $email = $value['email'];
238
239 // build array's which are used to setdefaults
240 if (in_array($contactId, $form->_toContactIds)) {
241 $form->_toContactDetails[$contactId] = $form->_contactDetails[$contactId];
8e4aa90c
CW
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'];
245 }
3f77636a 246 $toArray[] = array(
a03d5ab9 247 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
3f77636a 248 'id' => "$contactId::{$email}",
249 );
250 }
251 elseif (in_array($contactId, $form->_ccContactIds)) {
252 $ccArray[] = array(
a03d5ab9 253 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
3f77636a 254 'id' => "$contactId::{$email}",
255 );
6a488035 256 }
3f77636a 257 elseif (in_array($contactId, $form->_bccContactIds)) {
258 $bccArray[] = array(
a03d5ab9 259 'text' => '"' . $value['sort_name'] . '" <' . $email . '>',
3f77636a 260 'id' => "$contactId::{$email}",
261 );
6a488035 262 }
6a488035
TO
263 }
264 }
265
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.'));
268 }
269 }
270
271 $form->assign('toContact', json_encode($toArray));
3f77636a 272 $form->assign('ccContact', json_encode($ccArray));
273 $form->assign('bccContact', json_encode($bccArray));
274
6a488035
TO
275 $form->assign('suppressedEmails', $suppressedEmails);
276
277 $form->assign('totalSelectedContacts', count($form->_contactIds));
278
279 $form->add('text', 'subject', ts('Subject'), 'size=50 maxlength=254', TRUE);
280
f7305cbc 281 $form->add('select', 'fromEmailAddress', ts('From'), $form->_fromEmails, TRUE, array('class' => 'crm-select2 huge'));
6a488035
TO
282
283 CRM_Mailing_BAO_Mailing::commonCompose($form);
284
285 // add attachments
286 CRM_Core_BAO_File::buildAttachment($form, NULL);
287
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'
293 );
294 $url = CRM_Utils_System::url('civicrm/contact/view/case',
295 "&reset=1&action=view&cid={$ccid}&id={$form->_caseId}"
296 );
297 }
298 elseif ($form->_context) {
299 $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
300 }
301 else {
302 $url = CRM_Utils_System::url('civicrm/contact/view',
303 "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"
304 );
305 }
306
307 $session = CRM_Core_Session::singleton();
308 $session->replaceUserContext($url);
309 $form->addDefaultButtons(ts('Send Email'), 'upload', 'cancel');
310 }
311 else {
312 $form->addDefaultButtons(ts('Send Email'), 'upload');
313 }
314
315 $form->addFormRule(array('CRM_Contact_Form_Task_EmailCommon', 'formRule'), $form);
28530b98 316 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'templates/CRM/Contact/Form/Task/EmailCommon.js');
6a488035
TO
317 }
318
319 /**
320 * form rule
321 *
322 * @param array $fields the input form values
323 * @param array $dontCare
324 * @param array $self additional values form 'this'
325 *
326 * @return true if no errors, else array of errors
327 * @access public
328 *
329 */
330 static function formRule($fields, $dontCare, $self) {
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 /**
349 * process the form after the input has been submitted and validated
350 *
351 * @access public
352 *
fd31fa4c
EM
353 * @param $form
354 *
355ba699 355 * @return void
6a488035
TO
356 */
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)
361 ));
362 }
363
364 // check and ensure that
365 $formValues = $form->controller->exportValues($form->getName());
366
367 $fromEmail = $formValues['fromEmailAddress'];
368 $from = CRM_Utils_Array::value($fromEmail, $form->_emails);
6a488035
TO
369 $subject = $formValues['subject'];
370
3f77636a 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');
c1d26519 373 $additionalDetails = NULL;
3f77636a 374 $ccValues = $bccValues = array();
c1d26519 375 foreach ($elements as $element) {
a7488080 376 if (!empty($formValues[$element])) {
3f77636a 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);
381 switch ($element) {
382 case 'cc_id':
383 $ccValues['email'][] = '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>';
384 $ccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>";
385 break;
386 case 'bcc_id':
387 $bccValues['email'][]= '"' . $form->_contactDetails[$contactId]['sort_name'] . '" <' . $email . '>';
388 $bccValues['details'][] = "<a href='{$contactURL}'>" . $form->_contactDetails[$contactId]['display_name'] . "</a>";
389 break;
390 }
c1d26519 391 }
c1d26519 392 }
393 }
394
3f77636a 395 $cc = $bcc = '';
396 if (!empty($ccValues)) {
397 $cc = implode(',', $ccValues['email']);
398 $additionalDetails .= "\ncc : " . implode(", ", $ccValues['details']);
399 }
400 if (!empty($bccValues)) {
401 $bcc = implode(',', $bccValues['email']);
402 $additionalDetails .= "\nbcc : " . implode(", ", $bccValues['details']);
403 }
404
6a488035
TO
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";
409 }
410
411 // process message template
8cc574cf 412 if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) {
6a488035
TO
413 $messageTemplate = array(
414 'msg_text' => $formValues['text_message'],
415 'msg_html' => $formValues['html_message'],
416 'msg_subject' => $formValues['subject'],
417 'is_active' => TRUE,
418 );
419
a7488080 420 if (!empty($formValues['saveTemplate'])) {
6a488035 421 $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
c6327d7d 422 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
6a488035
TO
423 }
424
8cc574cf 425 if (!empty($formValues['template']) && !empty($formValues['updateTemplate'])) {
6a488035
TO
426 $messageTemplate['id'] = $formValues['template'];
427 unset($messageTemplate['msg_title']);
c6327d7d 428 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
6a488035
TO
429 }
430 }
431
432 $attachments = array();
433 CRM_Core_BAO_File::formatAttachment($formValues,
434 $attachments,
435 NULL, NULL
436 );
437
438 // format contact details array to handle multiple emails from same contact
439 $formattedContactDetails = array();
440 $tempEmails = array();
441
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 // send the mail
462 list($sent, $activityId) = CRM_Activity_BAO_Activity::sendEmail(
463 $formattedContactDetails,
464 $subject,
465 $formValues['text_message'],
466 $formValues['html_message'],
467 NULL,
468 NULL,
469 $from,
470 $attachments,
471 $cc,
472 $bcc,
3f77636a 473 array_keys($form->_toContactDetails),
c1d26519 474 $additionalDetails
6a488035
TO
475 );
476
477 if ($sent) {
3f77636a 478 $count_success = count($form->_toContactDetails);
6a488035
TO
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');
480 }
481
a5611c8e
DL
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);
6a488035
TO
487
488 if ($emailsNotSent) {
489 $not_sent = array();
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') . ')' : '');
495 }
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');
498 }
499
9cb404b4 500 if (isset($form->_caseId)) {
6a488035 501 // if case-id is found in the url, create case activity record
9cb404b4
N
502 $cases = explode(',', $form->_caseId);
503 foreach($cases as $key => $val) {
504 if (is_numeric($val)) {
505 $caseParams = array(
506 'activity_id' => $activityId,
507 'case_id' => $val,
508 );
509 CRM_Case_BAO_Case::processCaseActivity($caseParams);
510 }
511 }
6a488035
TO
512 }
513 }
514 //end of function
515}