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