CRM-15603 - Standardize punctuation of 'Event templates are not meant to be registered.'
[civicrm-core.git] / CRM / Utils / Mail.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 class CRM_Utils_Mail {
36
37 /**
38 * Wrapper function to send mail in CiviCRM. Hooks are called from this function. The input parameter
39 * is an associateive array which holds the values of field needed to send an email. These are:
40 *
41 * from : complete from envelope
42 * toName : name of person to send email
43 * toEmail : email address to send to
44 * cc : email addresses to cc
45 * bcc : email addresses to bcc
46 * subject : subject of the email
47 * text : text of the message
48 * html : html version of the message
49 * replyTo : reply-to header in the email
50 * attachments: an associative array of
51 * fullPath : complete pathname to the file
52 * mime_type: mime type of the attachment
53 * cleanName: the user friendly name of the attachmment
54 *
55 * @param array $params (by reference)
56 *
57 * @access public
58 *
59 * @return boolean true if a mail was sent, else false
60 */
61 static function send(&$params) {
62 $returnPath = CRM_Core_BAO_MailSettings::defaultReturnPath();
63 $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
64 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
65 $from = CRM_Utils_Array::value('from', $params);
66 if (!$returnPath) {
67 $returnPath = self::pluckEmailFromHeader($from);
68 }
69 $params['returnPath'] = $returnPath;
70
71 // first call the mail alter hook
72 CRM_Utils_Hook::alterMailParams($params);
73
74 // check if any module has aborted mail sending
75 if (!empty($params['abortMailSend']) || empty($params['toEmail'])) {
76 return FALSE;
77 }
78
79 $textMessage = CRM_Utils_Array::value('text', $params);
80 $htmlMessage = CRM_Utils_Array::value('html', $params);
81 $attachments = CRM_Utils_Array::value('attachments', $params);
82
83 // CRM-6224
84 if (trim(CRM_Utils_String::htmlToText($htmlMessage)) == '') {
85 $htmlMessage = FALSE;
86 }
87
88 $headers = array();
89 // CRM-10699 support custom email headers
90 if (!empty($params['headers'])) {
91 $headers = array_merge($headers, $params['headers']);
92 }
93 $headers['From'] = $params['from'];
94 $headers['To'] =
95 self::formatRFC822Email(
96 CRM_Utils_Array::value('toName', $params),
97 CRM_Utils_Array::value('toEmail', $params),
98 FALSE
99 );
100 $headers['Cc'] = CRM_Utils_Array::value('cc', $params);
101 $headers['Bcc'] = CRM_Utils_Array::value('bcc', $params);
102 $headers['Subject'] = CRM_Utils_Array::value('subject', $params);
103 $headers['Content-Type'] = $htmlMessage ? 'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
104 $headers['Content-Disposition'] = 'inline';
105 $headers['Content-Transfer-Encoding'] = '8bit';
106 $headers['Return-Path'] = CRM_Utils_Array::value('returnPath', $params);
107
108 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
109 $replyTo = CRM_Utils_Array::value('replyTo', $params, $from);
110
111 if (!empty($replyTo)) {
112 $headers['Reply-To'] = $replyTo;
113 }
114 $headers['Date'] = date('r');
115 if ($includeMessageId) {
116 $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@$emailDomain>";
117 }
118 if (!empty($params['autoSubmitted'])) {
119 $headers['Auto-Submitted'] = "Auto-Generated";
120 }
121
122 //make sure we has to have space, CRM-6977
123 foreach (array('From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path') as $fld) {
124 if (isset($headers[$fld])) {
125 $headers[$fld] = str_replace('"<', '" <', $headers[$fld]);
126 }
127 }
128
129 // quote FROM, if comma is detected AND is not already quoted. CRM-7053
130 if (strpos($headers['From'], ',') !== FALSE) {
131 $from = explode(' <', $headers['From']);
132 $headers['From'] = self::formatRFC822Email(
133 $from[0],
134 substr(trim($from[1]), 0, -1),
135 TRUE
136 );
137 }
138
139 require_once 'Mail/mime.php';
140 $msg = new Mail_mime("\n");
141 if ($textMessage) {
142 $msg->setTxtBody($textMessage);
143 }
144
145 if ($htmlMessage) {
146 $msg->setHTMLBody($htmlMessage);
147 }
148
149 if (!empty($attachments)) {
150 foreach ($attachments as $fileID => $attach) {
151 $msg->addAttachment(
152 $attach['fullPath'],
153 $attach['mime_type'],
154 $attach['cleanName']
155 );
156 }
157 }
158
159 $message = self::setMimeParams($msg);
160 $headers = &$msg->headers($headers);
161
162 $to = array($params['toEmail']);
163 $result = null;
164 $mailer =& CRM_Core_Config::getMailer( );
165
166 // Mail_smtp and Mail_sendmail mailers require Bcc anc Cc emails
167 // be included in both $to and $headers['Cc', 'Bcc']
168 if (get_class($mailer) != "Mail_mail") {
169 //get emails from headers, since these are
170 //combination of name and email addresses.
171 if (!empty($headers['Cc'])) {
172 $to[] = CRM_Utils_Array::value( 'Cc', $headers );
173 }
174 if (!empty($headers['Bcc'])) {
175 $to[] = CRM_Utils_Array::value( 'Bcc', $headers );
176 }
177 }
178 if (is_object($mailer)) {
179 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
180 $result = $mailer->send($to, $headers, $message);
181 if (is_a($result, 'PEAR_Error')) {
182 $message = self::errorMessage($mailer, $result);
183 // append error message in case multiple calls are being made to
184 // this method in the course of sending a batch of messages.
185 CRM_Core_Session::setStatus($message, ts('Mailing Error'), 'error');
186 return FALSE;
187 }
188 // CRM-10699
189 CRM_Utils_Hook::postEmailSend($params);
190 return TRUE;
191 }
192 return FALSE;
193 }
194
195 /**
196 * @param $mailer
197 * @param $result
198 *
199 * @return string
200 */
201 static function errorMessage($mailer, $result) {
202 $message = '<p>' . ts('An error occurred when CiviCRM attempted to send an email (via %1). If you received this error after submitting on online contribution or event registration - the transaction was completed, but we were unable to send the email receipt.', array(
203 1 => 'SMTP')) . '</p>' . '<p>' . ts('The mail library returned the following error message:') . '<br /><span class="font-red"><strong>' . $result->getMessage() . '</strong></span></p>' . '<p>' . ts('This is probably related to a problem in your Outbound Email Settings (Administer CiviCRM &raquo; System Settings &raquo; Outbound Email), OR the FROM email address specifically configured for your contribution page or event. Possible causes are:') . '</p>';
204
205 if (is_a($mailer, 'Mail_smtp')) {
206 $message .= '<ul>' . '<li>' . ts('Your SMTP Username or Password are incorrect.') . '</li>' . '<li>' . ts('Your SMTP Server (machine) name is incorrect.') . '</li>' . '<li>' . ts('You need to use a Port other than the default port 25 in your environment.') . '</li>' . '<li>' . ts('Your SMTP server is just not responding right now (it is down for some reason).') . '</li>';
207 }
208 else {
209 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
210 }
211
212 $message .= '<li>' . ts('The FROM Email Address configured for this feature may not be a valid sender based on your email service provider rules.') . '</li>' . '</ul>' . '<p>' . ts('Check <a href="%1">this page</a> for more information.', array(
213 1 => CRM_Utils_System::docURL2('user/advanced-configuration/email-system-configuration', TRUE))) . '</p>';
214
215 return $message;
216 }
217
218 /**
219 * @param $to
220 * @param $headers
221 * @param $message
222 */
223 static function logger(&$to, &$headers, &$message) {
224 if (is_array($to)) {
225 $toString = implode(', ', $to);
226 $fileName = $to[0];
227 }
228 else {
229 $toString = $fileName = $to;
230 }
231 $content = "To: " . $toString . "\n";
232 foreach ($headers as $key => $val) {
233 $content .= "$key: $val\n";
234 }
235 $content .= "\n" . $message . "\n";
236
237 if (is_numeric(CIVICRM_MAIL_LOG)) {
238 $config = CRM_Core_Config::singleton();
239 // create the directory if not there
240 $dirName = $config->configAndLogDir . 'mail' . DIRECTORY_SEPARATOR;
241 CRM_Utils_File::createDir($dirName);
242 $fileName = md5(uniqid(CRM_Utils_String::munge($fileName))) . '.txt';
243 file_put_contents($dirName . $fileName,
244 $content
245 );
246 }
247 else {
248 file_put_contents(CIVICRM_MAIL_LOG, $content, FILE_APPEND);
249 }
250 }
251
252 /**
253 * Get the email address itself from a formatted full name + address string
254 *
255 * Ugly but working.
256 *
257 * @param string $header the full name + email address string
258 *
259 * @return string the plucked email address
260 * @static
261 */
262 static function pluckEmailFromHeader($header) {
263 preg_match('/<([^<]*)>$/', $header, $matches);
264
265 if (isset($matches[1])) {
266 return $matches[1];
267 }
268 return NULL;
269 }
270
271 /**
272 * Get the Active outBound email
273 *
274 * @return boolean true if valid outBound email configuration found, false otherwise
275 * @access public
276 * @static
277 */
278 static function validOutBoundMail() {
279 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
280 'mailing_backend'
281 );
282 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
283 return TRUE;
284 }
285 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
286 if (!isset($mailingInfo['smtpServer']) || $mailingInfo['smtpServer'] == '' ||
287 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
288 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' || $mailingInfo['smtpPassword'] == ''))
289 ) {
290 return FALSE;
291 }
292 return TRUE;
293 }
294 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
295 if (!$mailingInfo['sendmail_path'] || !$mailingInfo['sendmail_args']) {
296 return FALSE;
297 }
298 return TRUE;
299 }
300 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB) {
301 return TRUE;
302 }
303 return FALSE;
304 }
305
306 /**
307 * @param $message
308 * @param null $params
309 *
310 * @return mixed
311 */
312 static function &setMimeParams(&$message, $params = NULL) {
313 static $mimeParams = NULL;
314 if (!$params) {
315 if (!$mimeParams) {
316 $mimeParams = array(
317 'text_encoding' => '8bit',
318 'html_encoding' => '8bit',
319 'head_charset' => 'utf-8',
320 'text_charset' => 'utf-8',
321 'html_charset' => 'utf-8',
322 );
323 }
324 $params = $mimeParams;
325 }
326 return $message->get($params);
327 }
328
329 /**
330 * @param $name
331 * @param $email
332 * @param bool $useQuote
333 *
334 * @return null|string
335 */
336 static function formatRFC822Email($name, $email, $useQuote = FALSE) {
337 $result = NULL;
338
339 $name = trim($name);
340
341 // strip out double quotes if present at the beginning AND end
342 if (substr($name, 0, 1) == '"' &&
343 substr($name, -1, 1) == '"'
344 ) {
345 $name = substr($name, 1, -1);
346 }
347
348 if (!empty($name)) {
349 // escape the special characters
350 $name = str_replace(array('<', '"', '>'),
351 array('\<', '\"', '\>'),
352 $name
353 );
354 if (strpos($name, ',') !== FALSE ||
355 $useQuote
356 ) {
357 // quote the string if it has a comma
358 $name = '"' . $name . '"';
359 }
360
361 $result = "$name ";
362 }
363
364 $result .= "<{$email}>";
365 return $result;
366 }
367
368 /**
369 * Takes a string and checks to see if it needs to be escaped / double quoted
370 * and if so does the needful and return the formatted name
371 *
372 * This code has been copied and adapted from ezc/Mail/src/tools.php
373 */
374 static function formatRFC2822Name($name) {
375 $name = trim($name);
376 if (!empty($name)) {
377 // remove the quotes around the name part if they are already there
378 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
379 $name = substr($name, 1, -1);
380 }
381
382 // add slashes to " and \ and surround the name part with quotes
383 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
384 $name = '"' . addcslashes($name, '\\"') . '"';
385 }
386 }
387
388 return $name;
389 }
390
391 /**
392 *
393 * @param string $fileName
394 * @param string $html
395 * @param string $format
396 *
397 * @return array $attachments
398 */
399 static function appendPDF($fileName, $html, $format = NULL) {
400 $pdf_filename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($fileName);
401
402 //FIXME : CRM-7894
403 //xmlns attribute is required in XHTML but it is invalid in HTML,
404 //Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
405 //and will be added to the <html> tag even if you do not include it.
406 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
407
408 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html,
409 $fileName,
410 TRUE,
411 $format)
412 );
413 return array(
414 'fullPath' => $pdf_filename,
415 'mime_type' => 'application/pdf',
416 'cleanName' => $fileName,
417 );
418 }
419 }
420