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