d8ba0e606523c66b24ae94abfdf9b96a8d581f9d
[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',
237 'html'
238 ) as $elem) {
239 $$elem = $smarty->fetch("string:{$$elem}");
240 }
241
242 // do replacements in message subject
243 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
244 $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens);
245 $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens, TRUE);
246 $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE);
247
248 $messageSubject = $smarty->fetch("string:{$messageSubject}");
249
250 // set up the parameters for CRM_Utils_Mail::send
251 $mailParams = array(
252 'groupName' => 'Scheduled Reminder Sender',
253 'from' => $from,
254 'toName' => $contact['display_name'],
255 'toEmail' => $email,
256 'subject' => $messageSubject,
257 );
258 if (!$html || $contact['preferred_mail_format'] == 'Text' ||
259 $contact['preferred_mail_format'] == 'Both'
260 ) {
261 // render the &amp; entities in text mode, so that the links work
262 $mailParams['text'] = str_replace('&amp;', '&', $text);
263 }
264 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
265 $contact['preferred_mail_format'] == 'Both'
266 )
267 ) {
268 $mailParams['html'] = $html;
269 }
270
271 $result = CRM_Utils_Mail::send($mailParams);
272 }
273
274 $messageTemplates->free();
275
276 return $result;
277 }
278
279 /**
280 * Revert a message template to its default subject+text+HTML state
281 *
282 * @param int id id of the template
283 *
284 * @return void
285 */
286 public static function revert($id) {
287 $diverted = new self;
288 $diverted->id = (int) $id;
289 $diverted->find(1);
290
291 if ($diverted->N != 1) {
292 CRM_Core_Error::fatal(ts('Did not find a message template with id of %1.', array(1 => $id)));
293 }
294
295 $orig = new self;
296 $orig->workflow_id = $diverted->workflow_id;
297 $orig->is_reserved = 1;
298 $orig->find(1);
299
300 if ($orig->N != 1) {
301 CRM_Core_Error::fatal(ts('Message template with id of %1 does not have a default to revert to.', array(1 => $id)));
302 }
303
304 $diverted->msg_subject = $orig->msg_subject;
305 $diverted->msg_text = $orig->msg_text;
306 $diverted->msg_html = $orig->msg_html;
307 $diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
308 $diverted->save();
309 }
310
311 /**
312 * Send an email from the specified template based on an array of params
313 *
314 * @param array $params
315 * A string-keyed array of function params, see function body for details.
316 *
317 * @return array
318 * of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
319 */
320 public static function sendTemplate($params) {
321 $defaults = array(
322 // option group name of the template
323 'groupName' => NULL,
324 // option value name of the template
325 'valueName' => NULL,
326 // ID of the template
327 'messageTemplateID' => NULL,
328 // contact id if contact tokens are to be replaced
329 'contactId' => NULL,
330 // additional template params (other than the ones already set in the template singleton)
331 'tplParams' => array(),
332 // the From: header
333 'from' => NULL,
334 // the recipient’s name
335 'toName' => NULL,
336 // the recipient’s email - mail is sent only if set
337 'toEmail' => NULL,
338 // the Cc: header
339 'cc' => NULL,
340 // the Bcc: header
341 'bcc' => NULL,
342 // the Reply-To: header
343 'replyTo' => NULL,
344 // email attachments
345 'attachments' => NULL,
346 // whether this is a test email (and hence should include the test banner)
347 'isTest' => FALSE,
348 // filename of optional PDF version to add as attachment (do not include path)
349 'PDFFilename' => NULL,
350 );
351 $params = array_merge($defaults, $params);
352
353 if ((!$params['groupName'] ||
354 !$params['valueName']
355 ) &&
356 !$params['messageTemplateID']
357 ) {
358 CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing."));
359 }
360
361 if ($params['messageTemplateID']) {
362 // fetch the three elements from the db based on id
363 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
364 FROM civicrm_msg_template mt
365 WHERE mt.id = %1 AND mt.is_default = 1';
366 $sqlParams = array(1 => array($params['messageTemplateID'], 'String'));
367 }
368 else {
369 // fetch the three elements from the db based on option_group and option_value names
370 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
371 FROM civicrm_msg_template mt
372 JOIN civicrm_option_value ov ON workflow_id = ov.id
373 JOIN civicrm_option_group og ON ov.option_group_id = og.id
374 WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
375 $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String'));
376 }
377 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
378 $dao->fetch();
379
380 if (!$dao->N) {
381 if ($params['messageTemplateID']) {
382 CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID'])));
383 }
384 else {
385 CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(
386 1 => $params['groupName'],
387 2 => $params['valueName']
388 )));
389 }
390 }
391
392 $subject = $dao->subject;
393 $text = $dao->text;
394 $html = $dao->html;
395 $format = $dao->format;
396 $dao->free();
397
398 // add the test banner (if requested)
399 if ($params['isTest']) {
400 $query = "SELECT msg_subject subject, msg_text text, msg_html html
401 FROM civicrm_msg_template mt
402 JOIN civicrm_option_value ov ON workflow_id = ov.id
403 JOIN civicrm_option_group og ON ov.option_group_id = og.id
404 WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1";
405 $testDao = CRM_Core_DAO::executeQuery($query);
406 $testDao->fetch();
407
408 $subject = $testDao->subject . $subject;
409 $text = $testDao->text . $text;
410 $html = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $html);
411 $testDao->free();
412 }
413
414 // replace tokens in the three elements (in subject as if it was the text body)
415 $domain = CRM_Core_BAO_Domain::getDomain();
416 $hookTokens = array();
417 $mailing = new CRM_Mailing_BAO_Mailing;
418 $mailing->body_text = $text;
419 $mailing->body_html = $html;
420 $tokens = $mailing->getTokens();
421 CRM_Utils_Hook::tokens($hookTokens);
422 $categories = array_keys($hookTokens);
423
424 $contactID = CRM_Utils_Array::value('contactId', $params);
425
426 if ($contactID) {
427 $contactParams = array('contact_id' => $contactID);
428 $returnProperties = array();
429
430 if (isset($tokens['text']['contact'])) {
431 foreach ($tokens['text']['contact'] as $name) {
432 $returnProperties[$name] = 1;
433 }
434 }
435
436 if (isset($tokens['html']['contact'])) {
437 foreach ($tokens['html']['contact'] as $name) {
438 $returnProperties[$name] = 1;
439 }
440 }
441 list($contact) = CRM_Utils_Token::getTokenDetails($contactParams,
442 $returnProperties,
443 FALSE, FALSE, NULL,
444 CRM_Utils_Token::flattenTokens($tokens),
445 // we should consider adding groupName and valueName here
446 'CRM_Core_BAO_MessageTemplate'
447 );
448 $contact = $contact[$contactID];
449 }
450
451 $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, FALSE, $tokens['text'], TRUE);
452 $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text'], TRUE);
453 $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html'], TRUE);
454
455 if ($contactID) {
456 $subject = CRM_Utils_Token::replaceContactTokens($subject, $contact, FALSE, $tokens['text'], FALSE, TRUE);
457 $text = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $tokens['text'], FALSE, TRUE);
458 $html = CRM_Utils_Token::replaceContactTokens($html, $contact, FALSE, $tokens['html'], FALSE, TRUE);
459
460
461 $contactArray = array($contactID => $contact);
462 CRM_Utils_Hook::tokenValues($contactArray,
463 array($contactID),
464 NULL,
465 CRM_Utils_Token::flattenTokens($tokens),
466 // we should consider adding groupName and valueName here
467 'CRM_Core_BAO_MessageTemplate'
468 );
469 $contact = $contactArray[$contactID];
470
471 $subject = CRM_Utils_Token::replaceHookTokens($subject, $contact, $categories, TRUE);
472 $text = CRM_Utils_Token::replaceHookTokens($text, $contact, $categories, TRUE);
473 $html = CRM_Utils_Token::replaceHookTokens($html, $contact, $categories, TRUE);
474 }
475
476 // strip whitespace from ends and turn into a single line
477 $subject = "{strip}$subject{/strip}";
478
479 // parse the three elements with Smarty
480
481
482 $smarty = CRM_Core_Smarty::singleton();
483 foreach ($params['tplParams'] as $name => $value) {
484 $smarty->assign($name, $value);
485 }
486 foreach (array(
487 'subject',
488 'text',
489 'html'
490 ) as $elem) {
491 $$elem = $smarty->fetch("string:{$$elem}");
492 }
493
494 // send the template, honouring the target user’s preferences (if any)
495 $sent = FALSE;
496
497 // create the params array
498 $params['subject'] = $subject;
499 $params['text'] = $text;
500 $params['html'] = $html;
501
502 if ($params['toEmail']) {
503 $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1));
504 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams);
505
506 $prefs = array_pop($contact);
507
508 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') {
509 $params['text'] = NULL;
510 }
511
512 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') {
513 $params['html'] = NULL;
514 }
515
516 $config = CRM_Core_Config::singleton();
517 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
518 $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
519 if (empty($params['attachments'])) {
520 $params['attachments'] = array();
521 }
522 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $format);
523 }
524 $pdf_filename = '';
525 if ($config->doNotAttachPDFReceipt &&
526 $params['PDFFilename'] &&
527 $params['html']
528 ) {
529 if (empty($params['attachments'])) {
530 $params['attachments'] = array();
531 }
532 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $format);
533 if (isset($params['tplParams']['email_comment'])) {
534 $params['html'] = $params['tplParams']['email_comment'];
535 $params['text'] = strip_tags($params['tplParams']['email_comment']);
536 }
537 }
538
539 $sent = CRM_Utils_Mail::send($params);
540
541 if ($pdf_filename) {
542 unlink($pdf_filename);
543 }
544 }
545
546 return array($sent, $subject, $text, $html);
547 }
548 }