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