Merge branch 4.5 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-2014 |
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-2014
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 object
52 * @static
53 */
54 public static function retrieve(&$params, &$defaults) {
55 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
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 /**
65 * Update the is_active flag in the db
66 *
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.
71 *
72 * @return Object
73 * DAO object on sucess, NULL otherwise
74 * @static
75 */
76 public static function setIsActive($id, $is_active) {
77 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
78 }
79
80 /**
81 * Add the Message Templates
82 *
83 * @param array $params
84 * Reference array contains the values submitted by the form.
85 *
86 * @static
87 *
88 * @return object
89 */
90 public static function add(&$params) {
91 $hook = empty($params['id']) ? 'create' : 'edit';
92 CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
93
94 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
95 $messageTemplates->copyValues($params);
96 $messageTemplates->save();
97
98 CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
99 return $messageTemplates;
100 }
101
102 /**
103 * Delete the Message Templates
104 *
105 * @static
106 *
107 * @param int $messageTemplatesID
108 *
109 * @return object
110 */
111 public static function del($messageTemplatesID) {
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";
121
122 $params = array(1 => array($messageTemplatesID, 'Integer'));
123 CRM_Core_DAO::executeQuery($query, $params);
124
125 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
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 /**
132 * Get the Message Templates
133 *
134 * @static
135 *
136 * @param bool $all
137 *
138 * @return object
139 */
140 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
141 $msgTpls = array();
142
143 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
144 $messageTemplates->is_active = 1;
145 $messageTemplates->is_sms = $isSMS;
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
158 /**
159 * @param int $contactId
160 * @param $email
161 * @param int $messageTemplateID
162 * @param $from
163 *
164 * @return bool|NULL
165 */
166 public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
167
168 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
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);
202 if (isset($tokens['contact'])) {
203 foreach ($tokens['contact'] as $key => $value) {
204 $returnProperties[$value] = 1;
205 }
206 }
207 list($details) = CRM_Utils_Token::getTokenDetails(array($contactId),
208 $returnProperties,
209 NULL, NULL, FALSE,
210 $tokens,
211 'CRM_Core_BAO_MessageTemplate');
212 $contact = reset($details);
213
214 // call token hook
215 $hookTokens = array();
216 CRM_Utils_Hook::tokens($hookTokens);
217 $categories = array_keys($hookTokens);
218
219 // do replacements in text and html body
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']);
225 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens, TRUE);
226 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
227 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens, TRUE);
228 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
229 }
230 }
231 $html = $body_html;
232 $text = $body_text;
233
234 $smarty = CRM_Core_Smarty::singleton();
235 foreach (array(
236 'text', 'html') as $elem) {
237 $$elem = $smarty->fetch("string:{$$elem}");
238 }
239
240 // do replacements in message subject
241 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
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);
245
246 $messageSubject = $smarty->fetch("string:{$messageSubject}");
247
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 *
279 * @param int id id of the template
280 *
281 * @return void
282 */
283 public static function revert($id) {
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 *
311 * @param array $params
312 * A string-keyed array of function params, see function body for details.
313 *
314 * @return array
315 * of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
316 */
317 public static function sendTemplate($params) {
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
445 $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, FALSE, $tokens['text'], TRUE);
446 $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text'], TRUE);
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
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
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();
508 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
509 $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
510 if (empty($params['attachments'])) {
511 $params['attachments'] = array();
512 }
513 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $format);
514 }
515 $pdf_filename = '';
516 if ($config->doNotAttachPDFReceipt &&
517 $params['PDFFilename'] &&
518 $params['html']
519 ) {
520 if (empty($params['attachments'])) {
521 $params['attachments'] = array();
522 }
523 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $format);
524 if (isset($params['tplParams']['email_comment'])) {
525 $params['html'] = $params['tplParams']['email_comment'];
526 $params['text'] = strip_tags($params['tplParams']['email_comment']);
527 }
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 }