Merge remote-tracking branch 'upstream/4.4' into 4.4-4.5-2014-10-14-11-16-10
[civicrm-core.git] / CRM / Core / BAO / MessageTemplate.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36require_once 'Mail/mime.php';
b5c2afd0
EM
37
38/**
39 * Class CRM_Core_BAO_MessageTemplate
40 */
c6327d7d 41class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate {
6a488035
TO
42
43 /**
44 * Takes a bunch of params that are needed to match certain criteria and
45 * retrieves the relevant objects. Typically the valid params are only
46 * contact_id. We'll tweak this function to be more full featured over a period
47 * of time. This is the inverse function of create. It also stores all the retrieved
48 * values in the default array
49 *
50 * @param array $params (reference ) an assoc array of name/value pairs
51 * @param array $defaults (reference ) an assoc array to hold the flattened values
52 *
c6327d7d 53 * @return object CRM_Core_BAO_MessageTemplate object
6a488035
TO
54 * @access public
55 * @static
56 */
57 static function retrieve(&$params, &$defaults) {
c6327d7d 58 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
6a488035
TO
59 $messageTemplates->copyValues($params);
60 if ($messageTemplates->find(TRUE)) {
61 CRM_Core_DAO::storeValues($messageTemplates, $defaults);
62 return $messageTemplates;
63 }
64 return NULL;
65 }
66
67 /**
68 * update the is_active flag in the db
69 *
70 * @param int $id id of the database record
71 * @param boolean $is_active value we want to set the is_active field
72 *
73 * @return Object DAO object on sucess, null otherwise
74 * @static
75 */
76 static function setIsActive($id, $is_active) {
c6327d7d 77 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
6a488035
TO
78 }
79
80 /**
81 * function to add the Message Templates
82 *
83 * @param array $params reference array contains the values submitted by the form
84 *
85 * @access public
86 * @static
87 *
88 * @return object
89 */
90 static function add(&$params) {
3c8059c8
KM
91 $hook = empty($params['id']) ? 'create' : 'edit';
92 CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
c39c0aa1 93
c6327d7d 94 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
6a488035 95 $messageTemplates->copyValues($params);
6a488035 96 $messageTemplates->save();
c39c0aa1 97
c9606a53 98 CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
6a488035
TO
99 return $messageTemplates;
100 }
101
102 /**
103 * function to delete the Message Templates
104 *
105 * @access public
106 * @static
107 *
77b97be7
EM
108 * @param $messageTemplatesID
109 *
6a488035
TO
110 * @return object
111 */
112 static function del($messageTemplatesID) {
113 // make sure messageTemplatesID is an integer
114 if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
115 CRM_Core_Error::fatal(ts('Invalid Message template'));
116 }
117
118 // Set mailing msg template col to NULL
119 $query = "UPDATE civicrm_mailing
120 SET msg_template_id = NULL
121 WHERE msg_template_id = %1";
5f351616 122
123 $params = array(1 => array($messageTemplatesID, 'Integer'));
6a488035
TO
124 CRM_Core_DAO::executeQuery($query, $params);
125
c6327d7d 126 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
6a488035
TO
127 $messageTemplates->id = $messageTemplatesID;
128 $messageTemplates->delete();
129 CRM_Core_Session::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
130 }
131
132 /**
133 * function to get the Message Templates
134 *
135 * @access public
136 * @static
137 *
dd244018
EM
138 * @param bool $all
139 *
6a488035
TO
140 * @return object
141 */
1e035d58 142 static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
6a488035
TO
143 $msgTpls = array();
144
c6327d7d 145 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
6a488035 146 $messageTemplates->is_active = 1;
1e035d58 147 $messageTemplates->is_sms = $isSMS;
6a488035
TO
148
149 if (!$all) {
150 $messageTemplates->workflow_id = 'NULL';
151 }
152 $messageTemplates->find();
153 while ($messageTemplates->fetch()) {
154 $msgTpls[$messageTemplates->id] = $messageTemplates->msg_title;
155 }
156 asort($msgTpls);
157 return $msgTpls;
158 }
159
b5c2afd0
EM
160 /**
161 * @param $contactId
162 * @param $email
163 * @param $messageTemplateID
164 * @param $from
165 *
166 * @return bool|null
167 */
6a488035
TO
168 static function sendReminder($contactId, $email, $messageTemplateID, $from) {
169
c6327d7d 170 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
6a488035
TO
171 $messageTemplates->id = $messageTemplateID;
172
173 $domain = CRM_Core_BAO_Domain::getDomain();
174 $result = NULL;
175 $hookTokens = array();
176
177 if ($messageTemplates->find(TRUE)) {
178 $body_text = $messageTemplates->msg_text;
179 $body_html = $messageTemplates->msg_html;
180 $body_subject = $messageTemplates->msg_subject;
181 if (!$body_text) {
182 $body_text = CRM_Utils_String::htmlToText($body_html);
183 }
184
185 $params = array(array('contact_id', '=', $contactId, 0, 0));
186 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
187
188 //CRM-4524
189 $contact = reset($contact);
190
191 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
192 return NULL;
193 }
194
195 //CRM-5734
196
197 // get tokens to be replaced
198 $tokens = array_merge(CRM_Utils_Token::getTokens($body_text),
199 CRM_Utils_Token::getTokens($body_html),
200 CRM_Utils_Token::getTokens($body_subject));
201
202 // get replacement text for these tokens
203 $returnProperties = array("preferred_mail_format" => 1);
c39c0aa1 204 if (isset($tokens['contact'])) {
6a488035 205 foreach ($tokens['contact'] as $key => $value) {
c39c0aa1 206 $returnProperties[$value] = 1;
6a488035
TO
207 }
208 }
209 list($details) = CRM_Utils_Token::getTokenDetails(array($contactId),
210 $returnProperties,
211 null, null, false,
212 $tokens,
c6327d7d 213 'CRM_Core_BAO_MessageTemplate');
6a488035
TO
214 $contact = reset( $details );
215
216 // call token hook
c39c0aa1 217 $hookTokens = array();
6a488035
TO
218 CRM_Utils_Hook::tokens($hookTokens);
219 $categories = array_keys($hookTokens);
220
c39c0aa1 221 // do replacements in text and html body
6a488035
TO
222 $type = array('html', 'text');
223 foreach ($type as $key => $value) {
224 $bodyType = "body_{$value}";
225 if ($$bodyType) {
226 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
227 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, true, $tokens, true);
228 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, false, $tokens, false, true);
229 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens, true);
230 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact , $categories, true);
231 }
232 }
233 $html = $body_html;
234 $text = $body_text;
235
4ee279f4 236 $smarty = CRM_Core_Smarty::singleton();
237 foreach (array(
238 'text', 'html') as $elem) {
239 $$elem = $smarty->fetch("string:{$$elem}");
240 }
241
6a488035
TO
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
4ee279f4 248 $messageSubject = $smarty->fetch("string:{$messageSubject}");
249
6a488035
TO
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 $mailParams['html'] = $html;
268 }
269
270 $result = CRM_Utils_Mail::send($mailParams);
271 }
272
273 $messageTemplates->free();
274
275 return $result;
276 }
277
278 /**
279 * Revert a message template to its default subject+text+HTML state
280 *
281 * @param integer id id of the template
282 *
283 * @return void
284 */
285 static function revert($id) {
286 $diverted = new self;
287 $diverted->id = (int) $id;
288 $diverted->find(1);
289
290 if ($diverted->N != 1) {
291 CRM_Core_Error::fatal(ts('Did not find a message template with id of %1.', array(1 => $id)));
292 }
293
294 $orig = new self;
295 $orig->workflow_id = $diverted->workflow_id;
296 $orig->is_reserved = 1;
297 $orig->find(1);
298
299 if ($orig->N != 1) {
300 CRM_Core_Error::fatal(ts('Message template with id of %1 does not have a default to revert to.', array(1 => $id)));
301 }
302
303 $diverted->msg_subject = $orig->msg_subject;
304 $diverted->msg_text = $orig->msg_text;
305 $diverted->msg_html = $orig->msg_html;
306 $diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
307 $diverted->save();
308 }
309
310 /**
311 * Send an email from the specified template based on an array of params
312 *
313 * @param array $params a string-keyed array of function params, see function body for details
314 *
315 * @return array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
316 */
317 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
d8ea987e
SG
445 $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, FALSE, $tokens['text'], TRUE);
446 $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text'], TRUE);
6a488035
TO
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
4ee279f4 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
6a488035
TO
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 $pdf_filename = '';
509 if ($config->doNotAttachPDFReceipt &&
510 $params['PDFFilename'] &&
511 $params['html']
512 ) {
6a488035
TO
513 if (empty($params['attachments'])) {
514 $params['attachments'] = array();
515 }
383c047b 516 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $format);
6a488035
TO
517 }
518
519 $sent = CRM_Utils_Mail::send($params);
520
521 if ($pdf_filename) {
522 unlink($pdf_filename);
523 }
524 }
525
526 return array($sent, $subject, $text, $html);
527 }
528}