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