Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-11-23-22-46-27
[civicrm-core.git] / CRM / Core / BAO / MessageTemplate.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 */
33
34 require_once 'Mail/mime.php';
35
36 /**
37 * Class CRM_Core_BAO_MessageTemplate.
38 */
39 class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate {
40
41 /**
42 * Fetch object based on array of properties.
43 *
44 * @param array $params
45 * (reference ) an assoc array of name/value pairs.
46 * @param array $defaults
47 * (reference ) an assoc array to hold the flattened values.
48 *
49 * @return CRM_Core_BAO_MessageTemplate
50 */
51 public static function retrieve(&$params, &$defaults) {
52 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
53 $messageTemplates->copyValues($params);
54 if ($messageTemplates->find(TRUE)) {
55 CRM_Core_DAO::storeValues($messageTemplates, $defaults);
56 return $messageTemplates;
57 }
58 return NULL;
59 }
60
61 /**
62 * Update the is_active flag in the db.
63 *
64 * @param int $id
65 * Id of the database record.
66 * @param bool $is_active
67 * Value we want to set the is_active field.
68 *
69 * @return Object
70 * DAO object on success, NULL otherwise
71 */
72 public static function setIsActive($id, $is_active) {
73 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_MessageTemplate', $id, 'is_active', $is_active);
74 }
75
76 /**
77 * Add the Message Templates.
78 *
79 * @param array $params
80 * Reference array contains the values submitted by the form.
81 *
82 *
83 * @return object
84 */
85 public static function add(&$params) {
86 $hook = empty($params['id']) ? 'create' : 'edit';
87 CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
88
89 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
90 $messageTemplates->copyValues($params);
91 $messageTemplates->save();
92
93 CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
94 return $messageTemplates;
95 }
96
97 /**
98 * Delete the Message Templates.
99 *
100 * @param int $messageTemplatesID
101 */
102 public static function del($messageTemplatesID) {
103 // make sure messageTemplatesID is an integer
104 if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
105 CRM_Core_Error::fatal(ts('Invalid Message template'));
106 }
107
108 // Set mailing msg template col to NULL
109 $query = "UPDATE civicrm_mailing
110 SET msg_template_id = NULL
111 WHERE msg_template_id = %1";
112
113 $params = array(1 => array($messageTemplatesID, 'Integer'));
114 CRM_Core_DAO::executeQuery($query, $params);
115
116 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
117 $messageTemplates->id = $messageTemplatesID;
118 $messageTemplates->delete();
119 CRM_Core_Session::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
120 }
121
122 /**
123 * Get the Message Templates.
124 *
125 *
126 * @param bool $all
127 *
128 * @param bool $isSMS
129 *
130 * @return object
131 */
132 public static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
133 $msgTpls = array();
134
135 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
136 $messageTemplates->is_active = 1;
137 $messageTemplates->is_sms = $isSMS;
138
139 if (!$all) {
140 $messageTemplates->workflow_id = 'NULL';
141 }
142 $messageTemplates->find();
143 while ($messageTemplates->fetch()) {
144 $msgTpls[$messageTemplates->id] = $messageTemplates->msg_title;
145 }
146 asort($msgTpls);
147 return $msgTpls;
148 }
149
150 /**
151 * @param int $contactId
152 * @param $email
153 * @param int $messageTemplateID
154 * @param $from
155 *
156 * @return bool|NULL
157 */
158 public static function sendReminder($contactId, $email, $messageTemplateID, $from) {
159
160 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
161 $messageTemplates->id = $messageTemplateID;
162
163 $domain = CRM_Core_BAO_Domain::getDomain();
164 $result = NULL;
165 $hookTokens = array();
166
167 if ($messageTemplates->find(TRUE)) {
168 $body_text = $messageTemplates->msg_text;
169 $body_html = $messageTemplates->msg_html;
170 $body_subject = $messageTemplates->msg_subject;
171 if (!$body_text) {
172 $body_text = CRM_Utils_String::htmlToText($body_html);
173 }
174
175 $params = array(array('contact_id', '=', $contactId, 0, 0));
176 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
177
178 //CRM-4524
179 $contact = reset($contact);
180
181 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
182 return NULL;
183 }
184
185 //CRM-5734
186
187 // get tokens to be replaced
188 $tokens = array_merge(CRM_Utils_Token::getTokens($body_text),
189 CRM_Utils_Token::getTokens($body_html),
190 CRM_Utils_Token::getTokens($body_subject));
191
192 // get replacement text for these tokens
193 $returnProperties = array("preferred_mail_format" => 1);
194 if (isset($tokens['contact'])) {
195 foreach ($tokens['contact'] as $key => $value) {
196 $returnProperties[$value] = 1;
197 }
198 }
199 list($details) = CRM_Utils_Token::getTokenDetails(array($contactId),
200 $returnProperties,
201 NULL, NULL, FALSE,
202 $tokens,
203 'CRM_Core_BAO_MessageTemplate');
204 $contact = reset($details);
205
206 // call token hook
207 $hookTokens = array();
208 CRM_Utils_Hook::tokens($hookTokens);
209 $categories = array_keys($hookTokens);
210
211 // do replacements in text and html body
212 $type = array('html', 'text');
213 foreach ($type as $key => $value) {
214 $bodyType = "body_{$value}";
215 if ($$bodyType) {
216 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
217 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, TRUE, $tokens, TRUE);
218 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, FALSE, $tokens, FALSE, TRUE);
219 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens, TRUE);
220 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact, $categories, TRUE);
221 }
222 }
223 $html = $body_html;
224 $text = $body_text;
225
226 $smarty = CRM_Core_Smarty::singleton();
227 foreach (array(
228 'text',
229 'html',
230 ) 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 ) {
260 $mailParams['html'] = $html;
261 }
262
263 $result = CRM_Utils_Mail::send($mailParams);
264 }
265
266 $messageTemplates->free();
267
268 return $result;
269 }
270
271 /**
272 * Revert a message template to its default subject+text+HTML state.
273 *
274 * @param int $id id of the template
275 */
276 public static function revert($id) {
277 $diverted = new CRM_Core_BAO_MessageTemplate();
278 $diverted->id = (int) $id;
279 $diverted->find(1);
280
281 if ($diverted->N != 1) {
282 CRM_Core_Error::fatal(ts('Did not find a message template with id of %1.', array(1 => $id)));
283 }
284
285 $orig = new CRM_Core_BAO_MessageTemplate();
286 $orig->workflow_id = $diverted->workflow_id;
287 $orig->is_reserved = 1;
288 $orig->find(1);
289
290 if ($orig->N != 1) {
291 CRM_Core_Error::fatal(ts('Message template with id of %1 does not have a default to revert to.', array(1 => $id)));
292 }
293
294 $diverted->msg_subject = $orig->msg_subject;
295 $diverted->msg_text = $orig->msg_text;
296 $diverted->msg_html = $orig->msg_html;
297 $diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
298 $diverted->save();
299 }
300
301 /**
302 * Send an email from the specified template based on an array of params.
303 *
304 * @param array $params
305 * A string-keyed array of function params, see function body for details.
306 *
307 * @return array
308 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
309 */
310 public static function sendTemplate($params) {
311 $defaults = array(
312 // option group name of the template
313 'groupName' => NULL,
314 // option value name of the template
315 'valueName' => NULL,
316 // ID of the template
317 'messageTemplateID' => NULL,
318 // contact id if contact tokens are to be replaced
319 'contactId' => NULL,
320 // additional template params (other than the ones already set in the template singleton)
321 'tplParams' => array(),
322 // the From: header
323 'from' => NULL,
324 // the recipient’s name
325 'toName' => NULL,
326 // the recipient’s email - mail is sent only if set
327 'toEmail' => NULL,
328 // the Cc: header
329 'cc' => NULL,
330 // the Bcc: header
331 'bcc' => NULL,
332 // the Reply-To: header
333 'replyTo' => NULL,
334 // email attachments
335 'attachments' => NULL,
336 // whether this is a test email (and hence should include the test banner)
337 'isTest' => FALSE,
338 // filename of optional PDF version to add as attachment (do not include path)
339 'PDFFilename' => NULL,
340 );
341 $params = array_merge($defaults, $params);
342
343 if ((!$params['groupName'] ||
344 !$params['valueName']
345 ) &&
346 !$params['messageTemplateID']
347 ) {
348 CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing."));
349 }
350
351 if ($params['messageTemplateID']) {
352 // fetch the three elements from the db based on id
353 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
354 FROM civicrm_msg_template mt
355 WHERE mt.id = %1 AND mt.is_default = 1';
356 $sqlParams = array(1 => array($params['messageTemplateID'], 'String'));
357 }
358 else {
359 // fetch the three elements from the db based on option_group and option_value names
360 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
361 FROM civicrm_msg_template mt
362 JOIN civicrm_option_value ov ON workflow_id = ov.id
363 JOIN civicrm_option_group og ON ov.option_group_id = og.id
364 WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
365 $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String'));
366 }
367 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
368 $dao->fetch();
369
370 if (!$dao->N) {
371 if ($params['messageTemplateID']) {
372 CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID'])));
373 }
374 else {
375 CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(
376 1 => $params['groupName'],
377 2 => $params['valueName'],
378 )));
379 }
380 }
381
382 $subject = $dao->subject;
383 $text = $dao->text;
384 $html = $dao->html;
385 $format = $dao->format;
386 $dao->free();
387
388 // add the test banner (if requested)
389 if ($params['isTest']) {
390 $query = "SELECT msg_subject subject, msg_text text, msg_html html
391 FROM civicrm_msg_template mt
392 JOIN civicrm_option_value ov ON workflow_id = ov.id
393 JOIN civicrm_option_group og ON ov.option_group_id = og.id
394 WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1";
395 $testDao = CRM_Core_DAO::executeQuery($query);
396 $testDao->fetch();
397
398 $subject = $testDao->subject . $subject;
399 $text = $testDao->text . $text;
400 $html = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $html);
401 $testDao->free();
402 }
403
404 // replace tokens in the three elements (in subject as if it was the text body)
405 $domain = CRM_Core_BAO_Domain::getDomain();
406 $hookTokens = array();
407 $mailing = new CRM_Mailing_BAO_Mailing();
408 $mailing->body_text = $text;
409 $mailing->body_html = $html;
410 $tokens = $mailing->getTokens();
411 CRM_Utils_Hook::tokens($hookTokens);
412 $categories = array_keys($hookTokens);
413
414 $contactID = CRM_Utils_Array::value('contactId', $params);
415
416 if ($contactID) {
417 $contactParams = array('contact_id' => $contactID);
418 $returnProperties = array();
419
420 if (isset($tokens['text']['contact'])) {
421 foreach ($tokens['text']['contact'] as $name) {
422 $returnProperties[$name] = 1;
423 }
424 }
425
426 if (isset($tokens['html']['contact'])) {
427 foreach ($tokens['html']['contact'] as $name) {
428 $returnProperties[$name] = 1;
429 }
430 }
431
432 // @todo CRM-17253 don't resolve contact details if there are no tokens
433 // effectively comment out this next (performance-expensive) line
434 // but unfortunately testing is a bit think on the ground to that needs to
435 // be added.
436 list($contact) = CRM_Utils_Token::getTokenDetails($contactParams,
437 $returnProperties,
438 FALSE, FALSE, NULL,
439 CRM_Utils_Token::flattenTokens($tokens),
440 // we should consider adding groupName and valueName here
441 'CRM_Core_BAO_MessageTemplate'
442 );
443 $contact = $contact[$contactID];
444 }
445
446 $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, FALSE, $tokens['text'], TRUE);
447 $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text'], TRUE);
448 $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html'], TRUE);
449
450 if ($contactID) {
451 $subject = CRM_Utils_Token::replaceContactTokens($subject, $contact, FALSE, $tokens['text'], FALSE, TRUE);
452 $text = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $tokens['text'], FALSE, TRUE);
453 $html = CRM_Utils_Token::replaceContactTokens($html, $contact, FALSE, $tokens['html'], FALSE, TRUE);
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 $smarty = CRM_Core_Smarty::singleton();
475 foreach ($params['tplParams'] as $name => $value) {
476 $smarty->assign($name, $value);
477 }
478 foreach (array(
479 'subject',
480 'text',
481 'html',
482 ) as $elem) {
483 $$elem = $smarty->fetch("string:{$$elem}");
484 }
485
486 // send the template, honouring the target user’s preferences (if any)
487 $sent = FALSE;
488
489 // create the params array
490 $params['subject'] = $subject;
491 $params['text'] = $text;
492 $params['html'] = $html;
493
494 if ($params['toEmail']) {
495 $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1));
496 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams);
497
498 $prefs = array_pop($contact);
499
500 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') {
501 $params['text'] = NULL;
502 }
503
504 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') {
505 $params['html'] = NULL;
506 }
507
508 $config = CRM_Core_Config::singleton();
509 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
510 $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
511 if (empty($params['attachments'])) {
512 $params['attachments'] = array();
513 }
514 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $format);
515 }
516 $pdf_filename = '';
517 if ($config->doNotAttachPDFReceipt &&
518 $params['PDFFilename'] &&
519 $params['html']
520 ) {
521 if (empty($params['attachments'])) {
522 $params['attachments'] = array();
523 }
524 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $format);
525 if (isset($params['tplParams']['email_comment'])) {
526 $params['html'] = $params['tplParams']['email_comment'];
527 $params['text'] = strip_tags($params['tplParams']['email_comment']);
528 }
529 }
530
531 $sent = CRM_Utils_Mail::send($params);
532
533 if ($pdf_filename) {
534 unlink($pdf_filename);
535 }
536 }
537
538 return array($sent, $subject, $text, $html);
539 }
540
541 }