Merge remote branch 'canonical/master' into merge-forward
[civicrm-core.git] / CRM / Core / BAO / MessageTemplate.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 * 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 *
53 * @return object CRM_Core_BAO_MessageTemplate object
54 * @access public
55 * @static
56 */
57 static function retrieve(&$params, &$defaults) {
58 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
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) {
77 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
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) {
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 * function to delete the Message Templates
104 *
105 * @access public
106 * @static
107 *
108 * @param $messageTemplatesID
109 *
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";
122
123 $params = array(1 => array($messageTemplatesID, 'Integer'));
124 CRM_Core_DAO::executeQuery($query, $params);
125
126 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
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 *
138 * @param bool $all
139 *
140 * @return object
141 */
142 static function getMessageTemplates($all = TRUE) {
143 $msgTpls = array();
144
145 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
146 $messageTemplates->is_active = 1;
147
148 if (!$all) {
149 $messageTemplates->workflow_id = 'NULL';
150 }
151 $messageTemplates->find();
152 while ($messageTemplates->fetch()) {
153 $msgTpls[$messageTemplates->id] = $messageTemplates->msg_title;
154 }
155 asort($msgTpls);
156 return $msgTpls;
157 }
158
159 /**
160 * @param $contactId
161 * @param $email
162 * @param $messageTemplateID
163 * @param $from
164 *
165 * @return bool|null
166 */
167 static function sendReminder($contactId, $email, $messageTemplateID, $from) {
168
169 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
170 $messageTemplates->id = $messageTemplateID;
171
172 $domain = CRM_Core_BAO_Domain::getDomain();
173 $result = NULL;
174 $hookTokens = array();
175
176 if ($messageTemplates->find(TRUE)) {
177 $body_text = $messageTemplates->msg_text;
178 $body_html = $messageTemplates->msg_html;
179 $body_subject = $messageTemplates->msg_subject;
180 if (!$body_text) {
181 $body_text = CRM_Utils_String::htmlToText($body_html);
182 }
183
184 $params = array(array('contact_id', '=', $contactId, 0, 0));
185 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
186
187 //CRM-4524
188 $contact = reset($contact);
189
190 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
191 return NULL;
192 }
193
194 //CRM-5734
195
196 // get tokens to be replaced
197 $tokens = array_merge(CRM_Utils_Token::getTokens($body_text),
198 CRM_Utils_Token::getTokens($body_html),
199 CRM_Utils_Token::getTokens($body_subject));
200
201 // get replacement text for these tokens
202 $returnProperties = array("preferred_mail_format" => 1);
203 if (isset($tokens['contact'])) {
204 foreach ($tokens['contact'] as $key => $value) {
205 $returnProperties[$value] = 1;
206 }
207 }
208 list($details) = CRM_Utils_Token::getTokenDetails(array($contactId),
209 $returnProperties,
210 null, null, false,
211 $tokens,
212 'CRM_Core_BAO_MessageTemplate');
213 $contact = reset( $details );
214
215 // call token hook
216 $hookTokens = array();
217 CRM_Utils_Hook::tokens($hookTokens);
218 $categories = array_keys($hookTokens);
219
220 // do replacements in text and html body
221 $type = array('html', 'text');
222 foreach ($type as $key => $value) {
223 $bodyType = "body_{$value}";
224 if ($$bodyType) {
225 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
226 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, true, $tokens, true);
227 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, false, $tokens, false, true);
228 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens, true);
229 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact , $categories, true);
230 }
231 }
232 $html = $body_html;
233 $text = $body_text;
234
235 $smarty = CRM_Core_Smarty::singleton();
236 foreach (array(
237 'text', 'html') as $elem) {
238 $$elem = $smarty->fetch("string:{$$elem}");
239 }
240
241 // do replacements in message subject
242 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, false, $tokens);
243 $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, true, $tokens);
244 $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens, true);
245 $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, true);
246
247 $messageSubject = $smarty->fetch("string:{$messageSubject}");
248
249 // set up the parameters for CRM_Utils_Mail::send
250 $mailParams = array(
251 'groupName' => 'Scheduled Reminder Sender',
252 'from' => $from,
253 'toName' => $contact['display_name'],
254 'toEmail' => $email,
255 'subject' => $messageSubject,
256 );
257 if (!$html || $contact['preferred_mail_format'] == 'Text' ||
258 $contact['preferred_mail_format'] == 'Both'
259 ) {
260 // render the &amp; entities in text mode, so that the links work
261 $mailParams['text'] = str_replace('&amp;', '&', $text);
262 }
263 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
264 $contact['preferred_mail_format'] == 'Both'
265 )) {
266 $mailParams['html'] = $html;
267 }
268
269 $result = CRM_Utils_Mail::send($mailParams);
270 }
271
272 $messageTemplates->free();
273
274 return $result;
275 }
276
277 /**
278 * Revert a message template to its default subject+text+HTML state
279 *
280 * @param integer id id of the template
281 *
282 * @return void
283 */
284 static function revert($id) {
285 $diverted = new self;
286 $diverted->id = (int) $id;
287 $diverted->find(1);
288
289 if ($diverted->N != 1) {
290 CRM_Core_Error::fatal(ts('Did not find a message template with id of %1.', array(1 => $id)));
291 }
292
293 $orig = new self;
294 $orig->workflow_id = $diverted->workflow_id;
295 $orig->is_reserved = 1;
296 $orig->find(1);
297
298 if ($orig->N != 1) {
299 CRM_Core_Error::fatal(ts('Message template with id of %1 does not have a default to revert to.', array(1 => $id)));
300 }
301
302 $diverted->msg_subject = $orig->msg_subject;
303 $diverted->msg_text = $orig->msg_text;
304 $diverted->msg_html = $orig->msg_html;
305 $diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
306 $diverted->save();
307 }
308
309 /**
310 * Send an email from the specified template based on an array of params
311 *
312 * @param array $params a string-keyed array of function params, see function body for details
313 *
314 * @return array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
315 */
316 static function sendTemplate($params) {
317 $defaults = array(
318 // option group name of the template
319 'groupName' => NULL,
320 // option value name of the template
321 'valueName' => NULL,
322 // ID of the template
323 'messageTemplateID' => NULL,
324 // contact id if contact tokens are to be replaced
325 'contactId' => NULL,
326 // additional template params (other than the ones already set in the template singleton)
327 'tplParams' => array(),
328 // the From: header
329 'from' => NULL,
330 // the recipient’s name
331 'toName' => NULL,
332 // the recipient’s email - mail is sent only if set
333 'toEmail' => NULL,
334 // the Cc: header
335 'cc' => NULL,
336 // the Bcc: header
337 'bcc' => NULL,
338 // the Reply-To: header
339 'replyTo' => NULL,
340 // email attachments
341 'attachments' => NULL,
342 // whether this is a test email (and hence should include the test banner)
343 'isTest' => FALSE,
344 // filename of optional PDF version to add as attachment (do not include path)
345 'PDFFilename' => NULL,
346 );
347 $params = array_merge($defaults, $params);
348
349 if ((!$params['groupName'] ||
350 !$params['valueName']
351 ) &&
352 !$params['messageTemplateID']
353 ) {
354 CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing."));
355 }
356
357 if ($params['messageTemplateID']) {
358 // fetch the three elements from the db based on id
359 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
360 FROM civicrm_msg_template mt
361 WHERE mt.id = %1 AND mt.is_default = 1';
362 $sqlParams = array(1 => array($params['messageTemplateID'], 'String'));
363 }
364 else {
365 // fetch the three elements from the db based on option_group and option_value names
366 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
367 FROM civicrm_msg_template mt
368 JOIN civicrm_option_value ov ON workflow_id = ov.id
369 JOIN civicrm_option_group og ON ov.option_group_id = og.id
370 WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
371 $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String'));
372 }
373 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
374 $dao->fetch();
375
376 if (!$dao->N) {
377 if ($params['messageTemplateID']) {
378 CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID'])));
379 }
380 else {
381 CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName'])));
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
454 $contactArray = array($contactID => $contact);
455 CRM_Utils_Hook::tokenValues($contactArray,
456 array($contactID),
457 NULL,
458 CRM_Utils_Token::flattenTokens($tokens),
459 // we should consider adding groupName and valueName here
460 'CRM_Core_BAO_MessageTemplate'
461 );
462 $contact = $contactArray[$contactID];
463
464 $subject = CRM_Utils_Token::replaceHookTokens($subject, $contact, $categories, TRUE);
465 $text = CRM_Utils_Token::replaceHookTokens($text, $contact, $categories, TRUE);
466 $html = CRM_Utils_Token::replaceHookTokens($html, $contact, $categories, TRUE);
467 }
468
469 // strip whitespace from ends and turn into a single line
470 $subject = "{strip}$subject{/strip}";
471
472 // parse the three elements with Smarty
473
474
475 $smarty = CRM_Core_Smarty::singleton();
476 foreach ($params['tplParams'] as $name => $value) {
477 $smarty->assign($name, $value);
478 }
479 foreach (array(
480 'subject', 'text', 'html') 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 }