Merge pull request #4627 from colemanw/docblocks
[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 * Fetch object based on array of properties
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 CRM_Core_BAO_MessageTemplate object
50 * @access public
51 * @static
52 */
53 static function retrieve(&$params, &$defaults) {
54 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
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_MessageTemplate', $id, 'is_active', $is_active);
74 }
75
76 /**
77 * 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 $hook = empty($params['id']) ? 'create' : 'edit';
88 CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
89
90 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
91 $messageTemplates->copyValues($params);
92 $messageTemplates->save();
93
94 CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
95 return $messageTemplates;
96 }
97
98 /**
99 * delete the Message Templates
100 *
101 * @access public
102 * @static
103 *
104 * @param $messageTemplatesID
105 *
106 * @return object
107 */
108 static function del($messageTemplatesID) {
109 // make sure messageTemplatesID is an integer
110 if (!CRM_Utils_Rule::positiveInteger($messageTemplatesID)) {
111 CRM_Core_Error::fatal(ts('Invalid Message template'));
112 }
113
114 // Set mailing msg template col to NULL
115 $query = "UPDATE civicrm_mailing
116 SET msg_template_id = NULL
117 WHERE msg_template_id = %1";
118
119 $params = array(1 => array($messageTemplatesID, 'Integer'));
120 CRM_Core_DAO::executeQuery($query, $params);
121
122 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
123 $messageTemplates->id = $messageTemplatesID;
124 $messageTemplates->delete();
125 CRM_Core_Session::setStatus(ts('Selected message template has been deleted.'), ts('Deleted'), 'success');
126 }
127
128 /**
129 * get the Message Templates
130 *
131 * @access public
132 * @static
133 *
134 * @param bool $all
135 *
136 * @return object
137 */
138 static function getMessageTemplates($all = TRUE, $isSMS = FALSE) {
139 $msgTpls = array();
140
141 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
142 $messageTemplates->is_active = 1;
143 $messageTemplates->is_sms = $isSMS;
144
145 if (!$all) {
146 $messageTemplates->workflow_id = 'NULL';
147 }
148 $messageTemplates->find();
149 while ($messageTemplates->fetch()) {
150 $msgTpls[$messageTemplates->id] = $messageTemplates->msg_title;
151 }
152 asort($msgTpls);
153 return $msgTpls;
154 }
155
156 /**
157 * @param $contactId
158 * @param $email
159 * @param $messageTemplateID
160 * @param $from
161 *
162 * @return bool|null
163 */
164 static function sendReminder($contactId, $email, $messageTemplateID, $from) {
165
166 $messageTemplates = new CRM_Core_DAO_MessageTemplate();
167 $messageTemplates->id = $messageTemplateID;
168
169 $domain = CRM_Core_BAO_Domain::getDomain();
170 $result = NULL;
171 $hookTokens = array();
172
173 if ($messageTemplates->find(TRUE)) {
174 $body_text = $messageTemplates->msg_text;
175 $body_html = $messageTemplates->msg_html;
176 $body_subject = $messageTemplates->msg_subject;
177 if (!$body_text) {
178 $body_text = CRM_Utils_String::htmlToText($body_html);
179 }
180
181 $params = array(array('contact_id', '=', $contactId, 0, 0));
182 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
183
184 //CRM-4524
185 $contact = reset($contact);
186
187 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
188 return NULL;
189 }
190
191 //CRM-5734
192
193 // get tokens to be replaced
194 $tokens = array_merge(CRM_Utils_Token::getTokens($body_text),
195 CRM_Utils_Token::getTokens($body_html),
196 CRM_Utils_Token::getTokens($body_subject));
197
198 // get replacement text for these tokens
199 $returnProperties = array("preferred_mail_format" => 1);
200 if (isset($tokens['contact'])) {
201 foreach ($tokens['contact'] as $key => $value) {
202 $returnProperties[$value] = 1;
203 }
204 }
205 list($details) = CRM_Utils_Token::getTokenDetails(array($contactId),
206 $returnProperties,
207 null, null, false,
208 $tokens,
209 'CRM_Core_BAO_MessageTemplate');
210 $contact = reset( $details );
211
212 // call token hook
213 $hookTokens = array();
214 CRM_Utils_Hook::tokens($hookTokens);
215 $categories = array_keys($hookTokens);
216
217 // do replacements in text and html body
218 $type = array('html', 'text');
219 foreach ($type as $key => $value) {
220 $bodyType = "body_{$value}";
221 if ($$bodyType) {
222 CRM_Utils_Token::replaceGreetingTokens($$bodyType, NULL, $contact['contact_id']);
223 $$bodyType = CRM_Utils_Token::replaceDomainTokens($$bodyType, $domain, true, $tokens, true);
224 $$bodyType = CRM_Utils_Token::replaceContactTokens($$bodyType, $contact, false, $tokens, false, true);
225 $$bodyType = CRM_Utils_Token::replaceComponentTokens($$bodyType, $contact, $tokens, true);
226 $$bodyType = CRM_Utils_Token::replaceHookTokens($$bodyType, $contact , $categories, true);
227 }
228 }
229 $html = $body_html;
230 $text = $body_text;
231
232 $smarty = CRM_Core_Smarty::singleton();
233 foreach (array(
234 'text', 'html') as $elem) {
235 $$elem = $smarty->fetch("string:{$$elem}");
236 }
237
238 // do replacements in message subject
239 $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, false, $tokens);
240 $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, true, $tokens);
241 $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens, true);
242 $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, true);
243
244 $messageSubject = $smarty->fetch("string:{$messageSubject}");
245
246 // set up the parameters for CRM_Utils_Mail::send
247 $mailParams = array(
248 'groupName' => 'Scheduled Reminder Sender',
249 'from' => $from,
250 'toName' => $contact['display_name'],
251 'toEmail' => $email,
252 'subject' => $messageSubject,
253 );
254 if (!$html || $contact['preferred_mail_format'] == 'Text' ||
255 $contact['preferred_mail_format'] == 'Both'
256 ) {
257 // render the &amp; entities in text mode, so that the links work
258 $mailParams['text'] = str_replace('&amp;', '&', $text);
259 }
260 if ($html && ($contact['preferred_mail_format'] == 'HTML' ||
261 $contact['preferred_mail_format'] == 'Both'
262 )) {
263 $mailParams['html'] = $html;
264 }
265
266 $result = CRM_Utils_Mail::send($mailParams);
267 }
268
269 $messageTemplates->free();
270
271 return $result;
272 }
273
274 /**
275 * Revert a message template to its default subject+text+HTML state
276 *
277 * @param integer id id of the template
278 *
279 * @return void
280 */
281 static function revert($id) {
282 $diverted = new self;
283 $diverted->id = (int) $id;
284 $diverted->find(1);
285
286 if ($diverted->N != 1) {
287 CRM_Core_Error::fatal(ts('Did not find a message template with id of %1.', array(1 => $id)));
288 }
289
290 $orig = new self;
291 $orig->workflow_id = $diverted->workflow_id;
292 $orig->is_reserved = 1;
293 $orig->find(1);
294
295 if ($orig->N != 1) {
296 CRM_Core_Error::fatal(ts('Message template with id of %1 does not have a default to revert to.', array(1 => $id)));
297 }
298
299 $diverted->msg_subject = $orig->msg_subject;
300 $diverted->msg_text = $orig->msg_text;
301 $diverted->msg_html = $orig->msg_html;
302 $diverted->pdf_format_id = is_null($orig->pdf_format_id) ? 'null' : $orig->pdf_format_id;
303 $diverted->save();
304 }
305
306 /**
307 * Send an email from the specified template based on an array of params
308 *
309 * @param array $params a string-keyed array of function params, see function body for details
310 *
311 * @return array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
312 */
313 static function sendTemplate($params) {
314 $defaults = array(
315 // option group name of the template
316 'groupName' => NULL,
317 // option value name of the template
318 'valueName' => NULL,
319 // ID of the template
320 'messageTemplateID' => NULL,
321 // contact id if contact tokens are to be replaced
322 'contactId' => NULL,
323 // additional template params (other than the ones already set in the template singleton)
324 'tplParams' => array(),
325 // the From: header
326 'from' => NULL,
327 // the recipient’s name
328 'toName' => NULL,
329 // the recipient’s email - mail is sent only if set
330 'toEmail' => NULL,
331 // the Cc: header
332 'cc' => NULL,
333 // the Bcc: header
334 'bcc' => NULL,
335 // the Reply-To: header
336 'replyTo' => NULL,
337 // email attachments
338 'attachments' => NULL,
339 // whether this is a test email (and hence should include the test banner)
340 'isTest' => FALSE,
341 // filename of optional PDF version to add as attachment (do not include path)
342 'PDFFilename' => NULL,
343 );
344 $params = array_merge($defaults, $params);
345
346 if ((!$params['groupName'] ||
347 !$params['valueName']
348 ) &&
349 !$params['messageTemplateID']
350 ) {
351 CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing."));
352 }
353
354 if ($params['messageTemplateID']) {
355 // fetch the three elements from the db based on id
356 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
357 FROM civicrm_msg_template mt
358 WHERE mt.id = %1 AND mt.is_default = 1';
359 $sqlParams = array(1 => array($params['messageTemplateID'], 'String'));
360 }
361 else {
362 // fetch the three elements from the db based on option_group and option_value names
363 $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format
364 FROM civicrm_msg_template mt
365 JOIN civicrm_option_value ov ON workflow_id = ov.id
366 JOIN civicrm_option_group og ON ov.option_group_id = og.id
367 WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
368 $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String'));
369 }
370 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
371 $dao->fetch();
372
373 if (!$dao->N) {
374 if ($params['messageTemplateID']) {
375 CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID'])));
376 }
377 else {
378 CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName'])));
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 list($contact) = CRM_Utils_Token::getTokenDetails($contactParams,
432 $returnProperties,
433 FALSE, FALSE, NULL,
434 CRM_Utils_Token::flattenTokens($tokens),
435 // we should consider adding groupName and valueName here
436 'CRM_Core_BAO_MessageTemplate'
437 );
438 $contact = $contact[$contactID];
439 }
440
441 $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, FALSE, $tokens['text'], TRUE);
442 $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text'], TRUE);
443 $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html'], TRUE);
444
445 if ($contactID) {
446 $subject = CRM_Utils_Token::replaceContactTokens($subject, $contact, FALSE, $tokens['text'], FALSE, TRUE);
447 $text = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $tokens['text'], FALSE, TRUE);
448 $html = CRM_Utils_Token::replaceContactTokens($html, $contact, FALSE, $tokens['html'], FALSE, TRUE);
449
450
451 $contactArray = array($contactID => $contact);
452 CRM_Utils_Hook::tokenValues($contactArray,
453 array($contactID),
454 NULL,
455 CRM_Utils_Token::flattenTokens($tokens),
456 // we should consider adding groupName and valueName here
457 'CRM_Core_BAO_MessageTemplate'
458 );
459 $contact = $contactArray[$contactID];
460
461 $subject = CRM_Utils_Token::replaceHookTokens($subject, $contact, $categories, TRUE);
462 $text = CRM_Utils_Token::replaceHookTokens($text, $contact, $categories, TRUE);
463 $html = CRM_Utils_Token::replaceHookTokens($html, $contact, $categories, TRUE);
464 }
465
466 // strip whitespace from ends and turn into a single line
467 $subject = "{strip}$subject{/strip}";
468
469 // parse the three elements with Smarty
470
471
472 $smarty = CRM_Core_Smarty::singleton();
473 foreach ($params['tplParams'] as $name => $value) {
474 $smarty->assign($name, $value);
475 }
476 foreach (array(
477 'subject', 'text', 'html') as $elem) {
478 $$elem = $smarty->fetch("string:{$$elem}");
479 }
480
481 // send the template, honouring the target user’s preferences (if any)
482 $sent = FALSE;
483
484 // create the params array
485 $params['subject'] = $subject;
486 $params['text'] = $text;
487 $params['html'] = $html;
488
489 if ($params['toEmail']) {
490 $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1));
491 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams);
492
493 $prefs = array_pop($contact);
494
495 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') {
496 $params['text'] = NULL;
497 }
498
499 if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') {
500 $params['html'] = NULL;
501 }
502
503 $config = CRM_Core_Config::singleton();
504 if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) {
505 $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']);
506 if (empty($params['attachments'])) {
507 $params['attachments'] = array();
508 }
509 $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $format) ;
510 }
511 $pdf_filename = '';
512 if ($config->doNotAttachPDFReceipt &&
513 $params['PDFFilename'] &&
514 $params['html']
515 ) {
516 if (empty($params['attachments'])) {
517 $params['attachments'] = array();
518 }
519 $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $format);
520 if (isset($params['tplParams']['email_comment'])) {
521 $params['html'] = $params['tplParams']['email_comment'];
522 $params['text'] = strip_tags($params['tplParams']['email_comment']);
523 }
524 }
525
526 $sent = CRM_Utils_Mail::send($params);
527
528 if ($pdf_filename) {
529 unlink($pdf_filename);
530 }
531 }
532
533 return array($sent, $subject, $text, $html);
534 }
535 }