[NFC] comment fixes relating to doc blocks, spelling
[civicrm-core.git] / CRM / Core / BAO / MessageTemplate.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
32 */
33
34 require_once 'Mail/mime.php';
35
36 /**
37 * Class CRM_Core_BAO_MessageTemplate.
38 */
39 class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate {
40
41 /**
42 * Fetch object based on array of properties.
43 *
44 * @param array $params
45 * (reference ) an assoc array of name/value pairs.
46 * @param array $defaults
47 * (reference ) an assoc array to hold the flattened values.
48 *
49 * @return CRM_Core_BAO_MessageTemplate
50 */
51 public static function retrieve(&$params, &$defaults) {
52 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
53 $messageTemplates->copyValues($params);
54 if ($messageTemplates->find(TRUE)) {
55 CRM_Core_DAO::storeValues($messageTemplates, $defaults);
56 return $messageTemplates;
57 }
58 return NULL;
59 }
60
61 /**
62 * Update the is_active flag in the db.
63 *
64 * @param int $id
65 * Id of the database record.
66 * @param bool $is_active
67 * Value we want to set the is_active field.
68 *
69 * @return bool
70 * true if we found and updated the object, else false
71 */
72 public static function setIsActive($id, $is_active) {
73 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
74 }
75
76 /**
77 * Add the Message Templates.
78 *
79 * @param array $params
80 * Reference array contains the values submitted by the form.
81 *
82 *
83 * @return object
84 */
85 public static function add(&$params) {
86 $hook = empty($params['id']) ? 'create' : 'edit';
87 CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
88
89 if (!empty($params['file_id']) && is_array($params['file_id']) && count($params['file_id'])) {
90 $fileParams = $params['file_id'];
91 unset($params['file_id']);
92 }
93
94 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
95 $messageTemplates->copyValues($params);
96 $messageTemplates->save();
97
98 if (!empty($fileParams)) {
99 $params['file_id'] = $fileParams;
100 CRM_Core_BAO_File::filePostProcess(
101 $params['file_id']['location'],
102 NULL,
103 'civicrm_msg_template',
104 $messageTemplates->id,
105 NULL,
106 TRUE,
107 $params['file_id'],
108 'file_id',
109 $params['file_id']['type']
110 );
111 }
112
113 CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
114 return $messageTemplates;
115 }
116
117 /**
118 * Delete the Message Templates.
119 *
120 * @param int $messageTemplatesID
121 */
122 public static function del($messageTemplatesID) {
123 // make sure messageTemplatesID is an integer
124 if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
125 CRM_Core_Error::fatal(ts('Invalid Message template'));
126 }
127
128 // Set mailing msg template col to NULL
129 $query = "UPDATE civicrm_mailing
130 SET msg_template_id = NULL
131 WHERE msg_template_id = %1";
132
133 $params = array(1 => array($messageTemplatesID, 'Integer'));
134 CRM_Core_DAO::executeQuery($query, $params);
135
136 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
137 $messageTemplates->id = $messageTemplatesID;
138 $messageTemplates->delete();
139 CRM_Core_Session::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
140 }
141
142 /**
143 * Get the Message Templates.
144 *
145 *
146 * @param bool $all
147 *
148 * @param bool $isSMS
149 *
150 * @return object
151 */
152 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
153 $msgTpls = array();
154
155 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
156 $messageTemplates->is_active = 1;
157 $messageTemplates->is_sms = $isSMS;
158
159 if (!$all) {
160 $messageTemplates->workflow_id = 'NULL';
161 }
162 $messageTemplates->find();
163 while ($messageTemplates->fetch()) {
164 $msgTpls[$messageTemplates->id] = $messageTemplates->msg_title;
165 }
166 asort($msgTpls);
167 return $msgTpls;
168 }
169
170 /**
171 * @param int $contactId
172 * @param $email
173 * @param int $messageTemplateID
174 * @param $from
175 *
176 * @return bool|NULL
177 */
178 public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
179
180 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
181 $messageTemplates->id = $messageTemplateID;
182
183 $domain = CRM_Core_BAO_Domain::getDomain();
184 $result = NULL;
185 $hookTokens = array();
186
187 if ($messageTemplates->find(TRUE)) {
188 $body_text = $messageTemplates->msg_text;
189 $body_html = $messageTemplates->msg_html;
190 $body_subject = $messageTemplates->msg_subject;
191 if (!$body_text) {
192 $body_text = CRM_Utils_String::htmlToText($body_html);
193 }
194
195 $params = array(array('contact_id', '=', $contactId, 0, 0));
196 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
197
198 //CRM-4524
199 $contact = reset($contact);
200
201 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
202 return NULL;
203 }
204
205 //CRM-5734
206
207 // get tokens to be replaced
208 $tokens = array_merge(CRM_Utils_Token::getTokens($body_text),
209 CRM_Utils_Token::getTokens($body_html),
210 CRM_Utils_Token::getTokens($body_subject));
211
212 // get replacement text for these tokens
213 $returnProperties = array("preferred_mail_format" => 1);
214 if (isset($tokens['contact'])) {
215 foreach ($tokens['contact'] as $key => $value) {
216 $returnProperties[$value] = 1;
217 }
218 }
219 list($details) = CRM_Utils_Token::getTokenDetails(array($contactId),
220 $returnProperties,
221 NULL, NULL, FALSE,
222 $tokens,
223 'CRM_Core_BAO_MessageTemplate');
224 $contact = reset($details);
225
226 // call token hook
227 $hookTokens = array();
228 CRM_Utils_Hook::tokens($hookTokens);
229 $categories = array_keys($hookTokens);
230
231 // do replacements in text and html body
232 $type = array('html', 'text');
233 foreach ($type as $key => $value) {
234 $bodyType = "body_{$value}";
235 if ($$bodyType) {
236 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
237 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens, TRUE);
238 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
239 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens, TRUE);
240 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
241 }
242 }
243 $html = $body_html;
244 $text = $body_text;
245
246 $smarty = CRM_Core_Smarty::singleton();
247 foreach (array(
248 'text',
249 'html',
250 ) as $elem) {
251 $$elem = $smarty->fetch("string:{$$elem}");
252 }
253
254 // do replacements in message subject
255 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
256 $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens);
257 $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens, TRUE);
258 $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
259
260 $messageSubject = $smarty->fetch("string:{$messageSubject}");
261
262 // set up the parameters for CRM_Utils_Mail::send
263 $mailParams = array(
264 'groupName' => 'Scheduled Reminder Sender',
265 'from' => $from,
266 'toName' => $contact['display_name'],
267 'toEmail' => $email,
268 'subject' => $messageSubject,
269 );
270 if (!$html || $contact['preferred_mail_format'] == 'Text' ||
271 $contact['preferred_mail_format'] == 'Both'
272 ) {
273 // render the &amp; entities in text mode, so that the links work
274 $mailParams['text'] = str_replace('&amp;', '&', $text);
275 }
276 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
277 $contact['preferred_mail_format'] == 'Both'
278 )
279 ) {
280 $mailParams['html'] = $html;
281 }
282
283 $result = CRM_Utils_Mail::send($mailParams);
284 }
285
286 $messageTemplates->free();
287
288 return $result;
289 }
290
291 /**
292 * Revert a message template to its default subject+text+HTML state.
293 *
294 * @param int $id id of the template
295 */
296 public static function revert($id) {
297 $diverted = new CRM_Core_BAO_MessageTemplate();
298 $diverted->id = (int) $id;
299 $diverted->find(1);
300
301 if ($diverted->N != 1) {
302 CRM_Core_Error::fatal(ts('Did not find a message template with id of %1.', array(1 => $id)));
303 }
304
305 $orig = new CRM_Core_BAO_MessageTemplate();
306 $orig->workflow_id = $diverted->workflow_id;
307 $orig->is_reserved = 1;
308 $orig->find(1);
309
310 if ($orig->N != 1) {
311 CRM_Core_Error::fatal(ts('Message template with id of %1 does not have a default to revert to.', array(1 => $id)));
312 }
313
314 $diverted->msg_subject = $orig->msg_subject;
315 $diverted->msg_text = $orig->msg_text;
316 $diverted->msg_html = $orig->msg_html;
317 $diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
318 $diverted->save();
319 }
320
321 /**
322 * Send an email from the specified template based on an array of params.
323 *
324 * @param array $params
325 * A string-keyed array of function params, see function body for details.
326 *
327 * @return array
328 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
329 */
330 public static function sendTemplate($params) {
331 $defaults = array(
332 // option group name of the template
333 'groupName' => NULL,
334 // option value name of the template
335 'valueName' => NULL,
336 // ID of the template
337 'messageTemplateID' => NULL,
338 // contact id if contact tokens are to be replaced
339 'contactId' => NULL,
340 // additional template params (other than the ones already set in the template singleton)
341 'tplParams' => array(),
342 // the From: header
343 'from' => NULL,
344 // the recipient’s name
345 'toName' => NULL,
346 // the recipient’s email - mail is sent only if set
347 'toEmail' => NULL,
348 // the Cc: header
349 'cc' => NULL,
350 // the Bcc: header
351 'bcc' => NULL,
352 // the Reply-To: header
353 'replyTo' => NULL,
354 // email attachments
355 'attachments' => NULL,
356 // whether this is a test email (and hence should include the test banner)
357 'isTest' => FALSE,
358 // filename of optional PDF version to add as attachment (do not include path)
359 'PDFFilename' => NULL,
360 );
361 $params = array_merge($defaults, $params);
362
363 CRM_Utils_Hook::alterMailParams($params, 'messageTemplate');
364
365 if ((!$params['groupName'] ||
366 !$params['valueName']
367 ) &&
368 !$params['messageTemplateID']
369 ) {
370 CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing."));
371 }
372
373 if ($params['messageTemplateID']) {
374 // fetch the three elements from the db based on id
375 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
376 FROM civicrm_msg_template mt
377 WHERE mt.id = %1 AND mt.is_default = 1';
378 $sqlParams = array(1 => array($params['messageTemplateID'], 'String'));
379 }
380 else {
381 // fetch the three elements from the db based on option_group and option_value names
382 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
383 FROM civicrm_msg_template mt
384 JOIN civicrm_option_value ov ON workflow_id = ov.id
385 JOIN civicrm_option_group og ON ov.option_group_id = og.id
386 WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
387 $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String'));
388 }
389 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
390 $dao->fetch();
391
392 if (!$dao->N) {
393 if ($params['messageTemplateID']) {
394 CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID'])));
395 }
396 else {
397 CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(
398 1 => $params['groupName'],
399 2 => $params['valueName'],
400 )));
401 }
402 }
403
404 $mailContent = array(
405 'subject' => $dao->subject,
406 'text' => $dao->text,
407 'html' => $dao->html,
408 'format' => $dao->format,
409 'groupName' => $params['groupName'],
410 'valueName' => $params['valueName'],
411 'messageTemplateID' => $params['messageTemplateID'],
412 );
413 $dao->free();
414
415 CRM_Utils_Hook::alterMailContent($mailContent);
416
417 // add the test banner (if requested)
418 if ($params['isTest']) {
419 $query = "SELECT msg_subject subject, msg_text text, msg_html html
420 FROM civicrm_msg_template mt
421 JOIN civicrm_option_value ov ON workflow_id = ov.id
422 JOIN civicrm_option_group og ON ov.option_group_id = og.id
423 WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1";
424 $testDao = CRM_Core_DAO::executeQuery($query);
425 $testDao->fetch();
426
427 $mailContent['subject'] = $testDao->subject . $mailContent['subject'];
428 $mailContent['text'] = $testDao->text . $mailContent['text'];
429 $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $mailContent['html']);
430 $testDao->free();
431 }
432
433 // replace tokens in the three elements (in subject as if it was the text body)
434 $domain = CRM_Core_BAO_Domain::getDomain();
435 $hookTokens = array();
436 $mailing = new CRM_Mailing_BAO_Mailing();
437 $mailing->subject = $mailContent['subject'];
438 $mailing->body_text = $mailContent['text'];
439 $mailing->body_html = $mailContent['html'];
440 $tokens = $mailing->getTokens();
441 CRM_Utils_Hook::tokens($hookTokens);
442 $categories = array_keys($hookTokens);
443
444 $contactID = CRM_Utils_Array::value('contactId', $params);
445
446 if ($contactID) {
447 $contactParams = array('contact_id' => $contactID);
448 $returnProperties = array();
449
450 if (isset($tokens['subject']['contact'])) {
451 foreach ($tokens['subject']['contact'] as $name) {
452 $returnProperties[$name] = 1;
453 }
454 }
455
456 if (isset($tokens['text']['contact'])) {
457 foreach ($tokens['text']['contact'] as $name) {
458 $returnProperties[$name] = 1;
459 }
460 }
461
462 if (isset($tokens['html']['contact'])) {
463 foreach ($tokens['html']['contact'] as $name) {
464 $returnProperties[$name] = 1;
465 }
466 }
467
468 // @todo CRM-17253 don't resolve contact details if there are no tokens
469 // effectively comment out this next (performance-expensive) line
470 // but unfortunately testing is a bit think on the ground to that needs to
471 // be added.
472 list($contact) = CRM_Utils_Token::getTokenDetails($contactParams,
473 $returnProperties,
474 FALSE, FALSE, NULL,
475 CRM_Utils_Token::flattenTokens($tokens),
476 // we should consider adding groupName and valueName here
477 'CRM_Core_BAO_MessageTemplate'
478 );
479 $contact = $contact[$contactID];
480 }
481
482 $mailContent['subject'] = CRM_Utils_Token::replaceDomainTokens($mailContent['subject'], $domain, FALSE, $tokens['subject'], TRUE);
483 $mailContent['text'] = CRM_Utils_Token::replaceDomainTokens($mailContent['text'], $domain, FALSE, $tokens['text'], TRUE);
484 $mailContent['html'] = CRM_Utils_Token::replaceDomainTokens($mailContent['html'], $domain, TRUE, $tokens['html'], TRUE);
485
486 if ($contactID) {
487 $mailContent['subject'] = CRM_Utils_Token::replaceContactTokens($mailContent['subject'], $contact, FALSE, $tokens['subject'], FALSE, TRUE);
488 $mailContent['text'] = CRM_Utils_Token::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, TRUE);
489 $mailContent['html'] = CRM_Utils_Token::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, TRUE);
490
491 $contactArray = array($contactID => $contact);
492 CRM_Utils_Hook::tokenValues($contactArray,
493 array($contactID),
494 NULL,
495 CRM_Utils_Token::flattenTokens($tokens),
496 // we should consider adding groupName and valueName here
497 'CRM_Core_BAO_MessageTemplate'
498 );
499 $contact = $contactArray[$contactID];
500
501 $mailContent['subject'] = CRM_Utils_Token::replaceHookTokens($mailContent['subject'], $contact, $categories, TRUE);
502 $mailContent['text'] = CRM_Utils_Token::replaceHookTokens($mailContent['text'], $contact, $categories, TRUE);
503 $mailContent['html'] = CRM_Utils_Token::replaceHookTokens($mailContent['html'], $contact, $categories, TRUE);
504 }
505
506 // strip whitespace from ends and turn into a single line
507 $mailContent['subject'] = "{strip}{$mailContent['subject']}{/strip}";
508
509 // parse the three elements with Smarty
510 $smarty = CRM_Core_Smarty::singleton();
511 foreach ($params['tplParams'] as $name => $value) {
512 $smarty->assign($name, $value);
513 }
514 foreach (array(
515 'subject',
516 'text',
517 'html',
518 ) as $elem) {
519 $mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}");
520 }
521
522 // send the template, honouring the target user’s preferences (if any)
523 $sent = FALSE;
524
525 // create the params array
526 $params['subject'] = $mailContent['subject'];
527 $params['text'] = $mailContent['text'];
528 $params['html'] = $mailContent['html'];
529
530 if ($params['toEmail']) {
531 $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1));
532 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams);
533
534 $prefs = array_pop($contact);
535
536 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') {
537 $params['text'] = NULL;
538 }
539
540 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') {
541 $params['html'] = NULL;
542 }
543
544 $config = CRM_Core_Config::singleton();
545 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
546 $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
547 if (empty($params['attachments'])) {
548 $params['attachments'] = array();
549 }
550 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']);
551 }
552 $pdf_filename = '';
553 if ($config->doNotAttachPDFReceipt &&
554 $params['PDFFilename'] &&
555 $params['html']
556 ) {
557 if (empty($params['attachments'])) {
558 $params['attachments'] = array();
559 }
560 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']);
561 if (isset($params['tplParams']['email_comment'])) {
562 $params['html'] = $params['tplParams']['email_comment'];
563 $params['text'] = strip_tags($params['tplParams']['email_comment']);
564 }
565 }
566
567 $sent = CRM_Utils_Mail::send($params);
568
569 if ($pdf_filename) {
570 unlink($pdf_filename);
571 }
572 }
573
574 return array($sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']);
575 }
576
577 }