Merge pull request #13959 from mlutfy/setMessageError
[civicrm-core.git] / CRM / Admin / Form / Setting / Smtp.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
32 */
33
34 /**
35 * This class generates form components for Smtp Server.
36 */
37 class CRM_Admin_Form_Setting_Smtp extends CRM_Admin_Form_Setting {
38 protected $_testButtonName;
39 protected $_settings = [
40 'allow_mail_from_logged_in_contact' => CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME,
41 ];
42
43 /**
44 * Build the form object.
45 */
46 public function buildQuickForm() {
47
48 $outBoundOption = [
49 CRM_Mailing_Config::OUTBOUND_OPTION_MAIL => ts('mail()'),
50 CRM_Mailing_Config::OUTBOUND_OPTION_SMTP => ts('SMTP'),
51 CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL => ts('Sendmail'),
52 CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED => ts('Disable Outbound Email'),
53 CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB => ts('Redirect to Database'),
54 ];
55 $this->addRadio('outBound_option', ts('Select Mailer'), $outBoundOption);
56
57 CRM_Utils_System::setTitle(ts('Settings - Outbound Mail'));
58 $this->add('text', 'sendmail_path', ts('Sendmail Path'));
59 $this->add('text', 'sendmail_args', ts('Sendmail Argument'));
60 $this->add('text', 'smtpServer', ts('SMTP Server'));
61 $this->add('text', 'smtpPort', ts('SMTP Port'));
62 $this->addYesNo('smtpAuth', ts('Authentication?'));
63 $this->addElement('text', 'smtpUsername', ts('SMTP Username'));
64 $this->addElement('password', 'smtpPassword', ts('SMTP Password'));
65
66 $this->_testButtonName = $this->getButtonName('refresh', 'test');
67
68 $this->addFormRule(['CRM_Admin_Form_Setting_Smtp', 'formRule']);
69 parent::buildQuickForm();
70 $buttons = $this->getElement('buttons')->getElements();
71 $buttons[] = $this->createElement('submit', $this->_testButtonName, ts('Save & Send Test Email'), ['crm-icon' => 'fa-envelope-o']);
72 $this->getElement('buttons')->setElements($buttons);
73 }
74
75 /**
76 * Process the form submission.
77 *
78 * @throws \Exception
79 */
80 public function postProcess() {
81 // flush caches so we reload details for future requests
82 // CRM-11967
83 CRM_Utils_System::flushCache();
84
85 $formValues = $this->controller->exportValues($this->_name);
86
87 Civi::settings()->set('allow_mail_from_logged_in_contact', (!empty($formValues['allow_mail_from_logged_in_contact'])));
88 unset($formValues['allow_mail_from_logged_in_contact']);
89
90 $buttonName = $this->controller->getButtonName();
91 // check if test button
92 if ($buttonName == $this->_testButtonName) {
93 if ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED) {
94 CRM_Core_Session::setStatus(ts('You have selected "Disable Outbound Email". A test email can not be sent.'), ts("Email Disabled"), "error");
95 }
96 elseif ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB) {
97 CRM_Core_Session::setStatus(ts('You have selected "Redirect to Database". A test email can not be sent.'), ts("Email Disabled"), "error");
98 }
99 else {
100 $session = CRM_Core_Session::singleton();
101 $userID = $session->get('userID');
102 list($toDisplayName, $toEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
103
104 //get the default domain email address.CRM-4250
105 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
106
107 if (!$domainEmailAddress || $domainEmailAddress == 'info@EXAMPLE.ORG') {
108 $fixUrl = CRM_Utils_System::url("civicrm/admin/domain", 'action=update&reset=1');
109 CRM_Core_Error::statusBounce(ts('The site administrator needs to enter a valid email address in <a href="%1">Administer CiviCRM &raquo; Communications &raquo; Organization Address and Contact Info</a>. The email address used may need to be a valid mail account with your email service provider.', [1 => $fixUrl]));
110 }
111 if (!$toEmail) {
112 CRM_Core_Error::statusBounce(ts('Cannot send a test email because your user record does not have a valid email address.'));
113 }
114
115 if (!trim($toDisplayName)) {
116 $toDisplayName = $toEmail;
117 }
118
119 $to = '"' . $toDisplayName . '"' . "<$toEmail>";
120 $from = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
121 $testMailStatusMsg = ts('Sending test email') . ':<br />'
122 . ts('From: %1', [1 => $domainEmailAddress]) . '<br />'
123 . ts('To: %1', [1 => $toEmail]) . '<br />';
124
125 $params = [];
126 if ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
127 $subject = "Test for SMTP settings";
128 $message = "SMTP settings are correct.";
129
130 $params['host'] = $formValues['smtpServer'];
131 $params['port'] = $formValues['smtpPort'];
132
133 if ($formValues['smtpAuth']) {
134 $params['username'] = $formValues['smtpUsername'];
135 $params['password'] = $formValues['smtpPassword'];
136 $params['auth'] = TRUE;
137 }
138 else {
139 $params['auth'] = FALSE;
140 }
141
142 // set the localhost value, CRM-3153, CRM-9332
143 $params['localhost'] = $_SERVER['SERVER_NAME'];
144
145 // also set the timeout value, lets set it to 30 seconds
146 // CRM-7510, CRM-9332
147 $params['timeout'] = 30;
148
149 $mailerName = 'smtp';
150 }
151 elseif ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
152 $subject = "Test for Sendmail settings";
153 $message = "Sendmail settings are correct.";
154 $params['sendmail_path'] = $formValues['sendmail_path'];
155 $params['sendmail_args'] = $formValues['sendmail_args'];
156 $mailerName = 'sendmail';
157 }
158 elseif ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
159 $subject = "Test for PHP mail settings";
160 $message = "mail settings are correct.";
161 $mailerName = 'mail';
162 }
163
164 $headers = [
165 'From' => $from,
166 'To' => $to,
167 'Subject' => $subject,
168 ];
169
170 $mailer = Mail::factory($mailerName, $params);
171
172 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
173 $result = $mailer->send($toEmail, $headers, $message);
174 unset($errorScope);
175 if (defined('CIVICRM_MAIL_LOG') && defined('CIVICRM_MAIL_LOG_AND_SEND')) {
176 $testMailStatusMsg .= '<br />' . ts('You have defined CIVICRM_MAIL_LOG_AND_SEND - mail will be logged.') . '<br /><br />';
177 }
178 if (defined('CIVICRM_MAIL_LOG') && !defined('CIVICRM_MAIL_LOG_AND_SEND')) {
179 CRM_Core_Session::setStatus($testMailStatusMsg . ts('You have defined CIVICRM_MAIL_LOG - no mail will be sent. Your %1 settings have not been tested.', [1 => strtoupper($mailerName)]), ts("Mail not sent"), "warning");
180 }
181 elseif (!is_a($result, 'PEAR_Error')) {
182 CRM_Core_Session::setStatus($testMailStatusMsg . ts('Your %1 settings are correct. A test email has been sent to your email address.', [1 => strtoupper($mailerName)]), ts("Mail Sent"), "success");
183 }
184 else {
185 $message = CRM_Utils_Mail::errorMessage($mailer, $result);
186 CRM_Core_Session::setStatus($testMailStatusMsg . ts('Oops. Your %1 settings are incorrect. No test mail has been sent.', [1 => strtoupper($mailerName)]) . $message, ts("Mail Not Sent"), "error");
187 }
188 }
189 }
190
191 $mailingBackend = Civi::settings()->get('mailing_backend');
192
193 if (!empty($mailingBackend)) {
194 $formValues = array_merge($mailingBackend, $formValues);
195 }
196
197 // if password is present, encrypt it
198 if (!empty($formValues['smtpPassword'])) {
199 $formValues['smtpPassword'] = CRM_Utils_Crypt::encrypt($formValues['smtpPassword']);
200 }
201
202 Civi::settings()->set('mailing_backend', $formValues);
203 }
204
205 /**
206 * Global validation rules for the form.
207 *
208 * @param array $fields
209 * Posted values of the form.
210 *
211 * @return array|bool
212 * list of errors to be posted back to the form
213 */
214 public static function formRule($fields) {
215 if ($fields['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
216 if (empty($fields['smtpServer'])) {
217 $errors['smtpServer'] = 'SMTP Server name is a required field.';
218 }
219 if (empty($fields['smtpPort'])) {
220 $errors['smtpPort'] = 'SMTP Port is a required field.';
221 }
222 if (!empty($fields['smtpAuth'])) {
223 if (empty($fields['smtpUsername'])) {
224 $errors['smtpUsername'] = 'If your SMTP server requires authentication please provide a valid user name.';
225 }
226 if (empty($fields['smtpPassword'])) {
227 $errors['smtpPassword'] = 'If your SMTP server requires authentication, please provide a password.';
228 }
229 }
230 }
231 if ($fields['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
232 if (!$fields['sendmail_path']) {
233 $errors['sendmail_path'] = 'Sendmail Path is a required field.';
234 }
235 if (!$fields['sendmail_args']) {
236 $errors['sendmail_args'] = 'Sendmail Argument is a required field.';
237 }
238 }
239
240 return empty($errors) ? TRUE : $errors;
241 }
242
243 /**
244 * Set default values for the form.
245 */
246 public function setDefaultValues() {
247 if (!$this->_defaults) {
248 $this->_defaults = [];
249
250 $mailingBackend = Civi::settings()->get('mailing_backend');
251 if (!empty($mailingBackend)) {
252 $this->_defaults = $mailingBackend;
253
254 if (!empty($this->_defaults['smtpPassword'])) {
255 $this->_defaults['smtpPassword'] = CRM_Utils_Crypt::decrypt($this->_defaults['smtpPassword']);
256 }
257 }
258 else {
259 if (!isset($this->_defaults['smtpServer'])) {
260 $this->_defaults['smtpServer'] = 'localhost';
261 $this->_defaults['smtpPort'] = 25;
262 $this->_defaults['smtpAuth'] = 0;
263 }
264
265 if (!isset($this->_defaults['sendmail_path'])) {
266 $this->_defaults['sendmail_path'] = '/usr/sbin/sendmail';
267 $this->_defaults['sendmail_args'] = '-i';
268 }
269 }
270 }
271 $this->_defaults['allow_mail_from_logged_in_contact'] = Civi::settings()->get('allow_mail_from_logged_in_contact');
272 return $this->_defaults;
273 }
274
275 }