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