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