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