Merge pull request #17008 from ivan-compucorp/CPS-70-fix-radio-value
[civicrm-core.git] / CRM / Core / BAO / Email.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class contains functions for email handling.
20 */
21 class CRM_Core_BAO_Email extends CRM_Core_DAO_Email {
22
23 /**
24 * Create email address.
25 *
26 * Note that the create function calls 'add' but has more business logic.
27 *
28 * @param array $params
29 * Input parameters.
30 *
31 * @return object
32 */
33 public static function create($params) {
34 // if id is set & is_primary isn't we can assume no change
35 if (is_numeric(CRM_Utils_Array::value('is_primary', $params)) || empty($params['id'])) {
36 CRM_Core_BAO_Block::handlePrimary($params, get_class());
37 }
38
39 $email = CRM_Core_BAO_Email::add($params);
40
41 return $email;
42 }
43
44 /**
45 * Takes an associative array and adds email.
46 *
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
49 *
50 * @return object
51 * CRM_Core_BAO_Email object on success, null otherwise
52 */
53 public static function add(&$params) {
54 $hook = empty($params['id']) ? 'create' : 'edit';
55 CRM_Utils_Hook::pre($hook, 'Email', CRM_Utils_Array::value('id', $params), $params);
56
57 if (isset($params['is_bulkmail']) && $params['is_bulkmail'] === 'null') {
58 CRM_Core_Error::deprecatedFunctionWarning('It is not valid to set bulkmail to null, it is boolean');
59 $params['bulkmail'] = 0;
60 }
61 $email = new CRM_Core_DAO_Email();
62 $email->copyValues($params);
63 if (!empty($email->email)) {
64 // lower case email field to optimize queries
65 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
66 $email->email = $strtolower($email->email);
67 }
68
69 /*
70 * since we're setting bulkmail for 1 of this contact's emails, first reset all their other emails to is_bulkmail false
71 * We shouldn't set the current email to false even though we
72 * are about to reset it to avoid contaminating the changelog if logging is enabled.
73 * (only 1 email address can have is_bulkmail = true)
74 */
75 if ($email->is_bulkmail && !empty($params['contact_id']) && !self::isMultipleBulkMail()) {
76 $sql = "
77 UPDATE civicrm_email
78 SET is_bulkmail = 0
79 WHERE contact_id = {$params['contact_id']}
80 ";
81 if ($hook === 'edit') {
82 $sql .= " AND id <> {$params['id']}";
83 }
84 CRM_Core_DAO::executeQuery($sql);
85 }
86
87 // handle if email is on hold
88 self::holdEmail($email);
89
90 $email->save();
91
92 if ($email->is_primary) {
93 // update the UF user email if that has changed
94 CRM_Core_BAO_UFMatch::updateUFName($email->contact_id);
95 }
96
97 CRM_Utils_Hook::post($hook, 'Email', $email->id, $email);
98 return $email;
99 }
100
101 /**
102 * Given the list of params in the params array, fetch the object
103 * and store the values in the values array
104 *
105 * @param array $entityBlock
106 * Input parameters to find object.
107 *
108 * @return array
109 */
110 public static function getValues($entityBlock) {
111 return CRM_Core_BAO_Block::getValues('email', $entityBlock);
112 }
113
114 /**
115 * Get all the emails for a specified contact_id, with the primary email being first
116 *
117 * @param int $id
118 * The contact id.
119 *
120 * @param bool $updateBlankLocInfo
121 *
122 * @return array
123 * the array of email id's
124 */
125 public static function allEmails($id, $updateBlankLocInfo = FALSE) {
126 if (!$id) {
127 return NULL;
128 }
129
130 $query = "
131 SELECT email,
132 civicrm_location_type.name as locationType,
133 civicrm_email.is_primary as is_primary,
134 civicrm_email.on_hold as on_hold,
135 civicrm_email.id as email_id,
136 civicrm_email.location_type_id as locationTypeId
137 FROM civicrm_contact
138 LEFT JOIN civicrm_email ON ( civicrm_email.contact_id = civicrm_contact.id )
139 LEFT JOIN civicrm_location_type ON ( civicrm_email.location_type_id = civicrm_location_type.id )
140 WHERE civicrm_contact.id = %1
141 ORDER BY civicrm_email.is_primary DESC, email_id ASC ";
142 $params = [
143 1 => [
144 $id,
145 'Integer',
146 ],
147 ];
148
149 $emails = $values = [];
150 $dao = CRM_Core_DAO::executeQuery($query, $params);
151 $count = 1;
152 while ($dao->fetch()) {
153 $values = [
154 'locationType' => $dao->locationType,
155 'is_primary' => $dao->is_primary,
156 'on_hold' => $dao->on_hold,
157 'id' => $dao->email_id,
158 'email' => $dao->email,
159 'locationTypeId' => $dao->locationTypeId,
160 ];
161
162 if ($updateBlankLocInfo) {
163 $emails[$count++] = $values;
164 }
165 else {
166 $emails[$dao->email_id] = $values;
167 }
168 }
169 return $emails;
170 }
171
172 /**
173 * Get all the emails for a specified location_block id, with the primary email being first
174 *
175 * @param array $entityElements
176 * The array containing entity_id and.
177 * entity_table name
178 *
179 * @return array
180 * the array of email id's
181 */
182 public static function allEntityEmails(&$entityElements) {
183 if (empty($entityElements)) {
184 return NULL;
185 }
186
187 $entityId = $entityElements['entity_id'];
188 $entityTable = $entityElements['entity_table'];
189
190 $sql = " SELECT email, ltype.name as locationType, e.is_primary as is_primary, e.on_hold as on_hold,e.id as email_id, e.location_type_id as locationTypeId
191 FROM civicrm_loc_block loc, civicrm_email e, civicrm_location_type ltype, {$entityTable} ev
192 WHERE ev.id = %1
193 AND loc.id = ev.loc_block_id
194 AND e.id IN (loc.email_id, loc.email_2_id)
195 AND ltype.id = e.location_type_id
196 ORDER BY e.is_primary DESC, email_id ASC ";
197
198 $params = [
199 1 => [
200 $entityId,
201 'Integer',
202 ],
203 ];
204
205 $emails = [];
206 $dao = CRM_Core_DAO::executeQuery($sql, $params);
207 while ($dao->fetch()) {
208 $emails[$dao->email_id] = [
209 'locationType' => $dao->locationType,
210 'is_primary' => $dao->is_primary,
211 'on_hold' => $dao->on_hold,
212 'id' => $dao->email_id,
213 'email' => $dao->email,
214 'locationTypeId' => $dao->locationTypeId,
215 ];
216 }
217
218 return $emails;
219 }
220
221 /**
222 * Set / reset hold status for an email
223 *
224 * @param object $email
225 * Email object.
226 */
227 public static function holdEmail(&$email) {
228 if ($email->id && $email->on_hold === NULL) {
229 // email is being updated but no change to on_hold.
230 return;
231 }
232 if ($email->on_hold === 'null' || $email->on_hold === NULL) {
233 // legacy handling, deprecated.
234 $email->on_hold = 0;
235 }
236 $email->on_hold = (int) $email->on_hold;
237
238 //check for update mode
239 if ($email->id) {
240 $params = [1 => [$email->id, 'Integer']];
241 if ($email->on_hold) {
242 $sql = "
243 SELECT id
244 FROM civicrm_email
245 WHERE id = %1
246 AND hold_date IS NULL
247 ";
248 if (CRM_Core_DAO::singleValueQuery($sql, $params)) {
249 $email->hold_date = date('YmdHis');
250 $email->reset_date = 'null';
251 }
252 }
253 elseif ($email->on_hold === 0) {
254 // we do this lookup to see if reset_date should be changed.
255 $sql = "
256 SELECT id
257 FROM civicrm_email
258 WHERE id = %1
259 AND hold_date IS NOT NULL
260 AND reset_date IS NULL
261 ";
262 if (CRM_Core_DAO::singleValueQuery($sql, $params)) {
263 //set reset date only if it is not set and if hold date is set
264 $email->on_hold = FALSE;
265 $email->hold_date = 'null';
266 $email->reset_date = date('YmdHis');
267 }
268 }
269 }
270 else {
271 if ($email->on_hold) {
272 $email->hold_date = date('YmdHis');
273 }
274 }
275 }
276
277 /**
278 * Generate an array of Domain email addresses.
279 * @return array $domainEmails;
280 */
281 public static function domainEmails() {
282 $domainEmails = [];
283 $domainFrom = (array) CRM_Core_OptionGroup::values('from_email_address');
284 foreach (array_keys($domainFrom) as $k) {
285 $domainEmail = $domainFrom[$k];
286 $domainEmails[$domainEmail] = htmlspecialchars($domainEmail);
287 }
288 return $domainEmails;
289 }
290
291 /**
292 * Build From Email as the combination of all the email ids of the logged in user and
293 * the domain email id
294 *
295 * @return array
296 * an array of email ids
297 */
298 public static function getFromEmail() {
299 // add all configured FROM email addresses
300 $fromEmailValues = self::domainEmails();
301
302 if (!Civi::settings()->get('allow_mail_from_logged_in_contact')) {
303 return $fromEmailValues;
304 }
305
306 $contactFromEmails = [];
307 // add logged in user's active email ids
308 $contactID = CRM_Core_Session::singleton()->getLoggedInContactID();
309 if ($contactID) {
310 $contactEmails = self::allEmails($contactID);
311 $fromDisplayName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
312
313 foreach ($contactEmails as $emailId => $emailVal) {
314 $email = trim($emailVal['email']);
315 if (!$email || $emailVal['on_hold']) {
316 continue;
317 }
318 $fromEmail = "$fromDisplayName <$email>";
319 $fromEmailHtml = htmlspecialchars($fromEmail) . ' ' . $emailVal['locationType'];
320
321 if (!empty($emailVal['is_primary'])) {
322 $fromEmailHtml .= ' ' . ts('(preferred)');
323 }
324 $contactFromEmails[$emailId] = $fromEmailHtml;
325 }
326 }
327 return CRM_Utils_Array::crmArrayMerge($contactFromEmails, $fromEmailValues);
328 }
329
330 /**
331 * @return object
332 */
333 public static function isMultipleBulkMail() {
334 return Civi::settings()->get('civimail_multiple_bulk_emails');
335 }
336
337 /**
338 * Call common delete function.
339 *
340 * @param int $id
341 *
342 * @return bool
343 */
344 public static function del($id) {
345 return CRM_Contact_BAO_Contact::deleteObjectWithPrimary('Email', $id);
346 }
347
348 /**
349 * Get filters for entity reference fields.
350 *
351 * @return array
352 */
353 public static function getEntityRefFilters() {
354 $contactFields = CRM_Contact_BAO_Contact::getEntityRefFilters();
355 foreach ($contactFields as $index => &$contactField) {
356 if (!empty($contactField['entity'])) {
357 // For now email_getlist can't parse state, country etc.
358 unset($contactFields[$index]);
359 }
360 elseif ($contactField['key'] !== 'contact_id') {
361 $contactField['entity'] = 'Contact';
362 $contactField['key'] = 'contact_id.' . $contactField['key'];
363 }
364 }
365 return $contactFields;
366 }
367
368 }