define format at one place
[civicrm-core.git] / CRM / Contact / BAO / Contact.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 class CRM_Contact_BAO_Contact extends CRM_Contact_DAO_Contact implements Civi\Core\HookInterface {
18
19 /**
20 * SQL function used to format the phone_numeric field via trigger.
21 *
22 * @see self::triggerInfo()
23 *
24 * Note that this is also used by the 4.3 upgrade script.
25 * @see CRM_Upgrade_Incremental_php_FourThree
26 */
27 const DROP_STRIP_FUNCTION_43 = "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
28
29 const CREATE_STRIP_FUNCTION_43 = "
30 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255))
31 RETURNS VARCHAR(255)
32 DETERMINISTIC
33 NO SQL
34 BEGIN
35 DECLARE output VARCHAR(255) DEFAULT '';
36 DECLARE iterator INT DEFAULT 1;
37 WHILE iterator < (LENGTH(input) + 1) DO
38 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
39 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
40 END IF;
41 SET iterator = iterator + 1;
42 END WHILE;
43 RETURN output;
44 END";
45
46 /**
47 * The types of communication preferences.
48 *
49 * @var array
50 */
51 public static $_commPrefs = [
52 'do_not_phone',
53 'do_not_email',
54 'do_not_mail',
55 'do_not_sms',
56 'do_not_trade',
57 ];
58
59 /**
60 * Types of greetings.
61 *
62 * @var array
63 */
64 public static $_greetingTypes = [
65 'addressee',
66 'email_greeting',
67 'postal_greeting',
68 ];
69
70 /**
71 * Static field for all the contact information that we can potentially import.
72 *
73 * @var array
74 */
75 public static $_importableFields = [];
76
77 /**
78 * Static field for all the contact information that we can potentially export.
79 *
80 * @var array
81 */
82 public static $_exportableFields = NULL;
83
84 /**
85 * Takes an associative array and creates a contact object.
86 *
87 * The function extracts all the params it needs to initialize the create a
88 * contact object. the params array could contain additional unused name/value
89 * pairs
90 *
91 * @param array $params
92 * (reference) an assoc array of name/value pairs.
93 *
94 * @return CRM_Contact_DAO_Contact|CRM_Core_Error|NULL
95 * Created or updated contact object or error object.
96 * (error objects are being phased out in favour of exceptions)
97 * @throws \CRM_Core_Exception
98 */
99 public static function add(&$params) {
100 $contact = new CRM_Contact_DAO_Contact();
101 $contactID = $params['contact_id'] ?? NULL;
102 if (empty($params)) {
103 return NULL;
104 }
105
106 // Fix for validate contact sub type CRM-5143.
107 if (isset($params['contact_sub_type'])) {
108 if (empty($params['contact_sub_type'])) {
109 $params['contact_sub_type'] = 'null';
110 }
111 elseif ($params['contact_sub_type'] !== 'null') {
112 if (!CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'],
113 $params['contact_type'], TRUE
114 )
115 ) {
116 // we'll need to fix tests to handle this
117 // CRM-7925
118 throw new CRM_Core_Exception(ts('The Contact Sub Type does not match the Contact type for this record'));
119 }
120 $params['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
121 }
122 }
123
124 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
125 if (!empty($params['preferred_communication_method']) && empty($params['preferred_communication_method'][0])) {
126 CRM_Core_Error::deprecatedWarning(' Form layer formatting should never get to the BAO');
127 CRM_Utils_Array::formatArrayKeys($params['preferred_communication_method']);
128 $contact->preferred_communication_method = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
129 unset($params['preferred_communication_method']);
130 }
131 }
132
133 $defaults = ['source' => $params['contact_source'] ?? NULL];
134 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
135 $defaults['display_name'] = $params['organization_name'];
136 $defaults['sort_name'] = $params['organization_name'];
137 }
138 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
139 $defaults['display_name'] = $params['household_name'];
140 $defaults['sort_name'] = $params['household_name'];
141 }
142 $params = array_merge($defaults, $params);
143
144 if (!empty($params['deceased_date']) && $params['deceased_date'] !== 'null') {
145 $params['is_deceased'] = TRUE;
146 }
147 $allNull = $contact->copyValues($params);
148
149 $contact->id = $contactID;
150
151 if ($contact->contact_type === 'Individual') {
152 $allNull = FALSE;
153 // @todo get rid of this - most of this formatting should
154 // be done by time we get here - maybe start with some
155 // deprecation notices.
156 CRM_Contact_BAO_Individual::format($params, $contact);
157 }
158
159 // Note that copyValues() above might already call this, via
160 // CRM_Utils_String::ellipsify(), but e.g. for Individual it gets put
161 // back or altered by Individual::format() just above, so we need to
162 // check again.
163 // Note also orgs will get ellipsified, but if we do that here then
164 // some existing tests on individual fail.
165 // Also api v3 will enforce org naming length by failing, v4 will truncate.
166 if (mb_strlen(($contact->display_name ?? ''), 'UTF-8') > 128) {
167 $contact->display_name = mb_substr($contact->display_name, 0, 128, 'UTF-8');
168 }
169 if (mb_strlen(($contact->sort_name ?? ''), 'UTF-8') > 128) {
170 $contact->sort_name = mb_substr($contact->sort_name, 0, 128, 'UTF-8');
171 }
172
173 $privacy = $params['privacy'] ?? NULL;
174 if ($privacy && is_array($privacy)) {
175 $allNull = FALSE;
176 foreach (self::$_commPrefs as $name) {
177 $contact->$name = $privacy[$name] ?? FALSE;
178 }
179 }
180
181 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
182 // @todo - does this mean we can remove this block?
183 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
184 if ((!isset($contact->hash) || !$contact->hash) && !$contact->id) {
185 $allNull = FALSE;
186 $contact->hash = md5(uniqid(rand(), TRUE));
187 }
188
189 // Even if we don't need $employerId, it's important to call getFieldValue() before
190 // the contact is saved because we want the existing value to be cached.
191 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
192 $employerId = (!$contactID || $contact->contact_type !== 'Individual') ? NULL : CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contact->id, 'employer_id');
193
194 if (!$allNull) {
195 $contact->save();
196
197 CRM_Core_BAO_Log::register($contact->id,
198 'civicrm_contact',
199 $contact->id
200 );
201 }
202
203 if ($contact->contact_type === 'Individual' && (isset($params['current_employer']) || isset($params['employer_id']))) {
204 // Create current employer.
205 $newEmployer = !empty($params['employer_id']) ? $params['employer_id'] : $params['current_employer'] ?? NULL;
206
207 $newContact = empty($params['contact_id']);
208 if (!CRM_Utils_System::isNull($newEmployer)) {
209 CRM_Contact_BAO_Contact_Utils::createCurrentEmployerRelationship($contact->id, $newEmployer, $employerId, $newContact);
210 }
211 elseif ($employerId) {
212 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($contact->id, $employerId);
213 }
214 }
215
216 // Update cached employer name if the name of an existing organization is being updated.
217 if ($contact->contact_type === 'Organization' && !empty($params['organization_name']) && $contactID) {
218 CRM_Contact_BAO_Contact_Utils::updateCurrentEmployer($contact->id);
219 }
220
221 return $contact;
222 }
223
224 /**
225 * Create contact.
226 *
227 * takes an associative array and creates a contact object and all the associated
228 * derived objects (i.e. individual, location, email, phone etc)
229 *
230 * This function is invoked from within the web form layer and also from the api layer
231 *
232 * @param array $params
233 * (reference ) an assoc array of name/value pairs.
234 * @param bool $fixAddress
235 * If we need to fix address.
236 * @param bool $invokeHooks
237 * If we need to invoke hooks.
238 *
239 * @param bool $skipDelete
240 * Unclear parameter, passed to website create
241 *
242 * @return CRM_Contact_BAO_Contact|CRM_Core_Error|NULL
243 * Created or updated contribution object. We are deprecating returning an error in
244 * favour of exceptions
245 *
246 * @throws \CRM_Core_Exception
247 * @throws \CiviCRM_API3_Exception
248 * @throws \Civi\API\Exception\UnauthorizedException
249 */
250 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
251 $contact = NULL;
252 if (empty($params['contact_type']) && empty($params['contact_id'])) {
253 return $contact;
254 }
255
256 $isEdit = !empty($params['contact_id']);
257
258 if ($isEdit && empty($params['contact_type'])) {
259 $params['contact_type'] = self::getContactType($params['contact_id']);
260 }
261
262 if (!empty($params['check_permissions']) && isset($params['api_key'])
263 && !CRM_Core_Permission::check([['edit api keys', 'administer CiviCRM']])
264 && !($isEdit && CRM_Core_Permission::check('edit own api keys') && $params['contact_id'] == CRM_Core_Session::getLoggedInContactID())
265 ) {
266 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify api key');
267 }
268
269 if ($invokeHooks) {
270 if (!empty($params['contact_id'])) {
271 CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
272 }
273 else {
274 CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
275 }
276 }
277
278 self::ensureGreetingParamsAreSet($params);
279
280 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
281 if (empty($params['contact_id'])) {
282 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
283 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n::getContactDefaultLanguage()) != FALSE) {
284 $params['preferred_language'] = $language;
285 }
286
287 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
288 if (empty($params['communication_style_id'])) {
289 $defaultCommunicationStyleId = CRM_Core_OptionGroup::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
290 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
291 }
292 }
293
294 $transaction = new CRM_Core_Transaction();
295
296 $contact = self::add($params);
297
298 $params['contact_id'] = $contact->id;
299
300 if (Civi::settings()->get('is_enabled')) {
301 // Enabling multisite causes the contact to be added to the domain group.
302 $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
303 if (!empty($domainGroupID)) {
304 if (!empty($params['group']) && is_array($params['group'])) {
305 $params['group'][$domainGroupID] = 1;
306 }
307 else {
308 $params['group'] = [$domainGroupID => 1];
309 }
310 }
311 }
312
313 if (!empty($params['group'])) {
314 $contactIds = [$params['contact_id']];
315 foreach ($params['group'] as $groupId => $flag) {
316 if ($flag == 1) {
317 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
318 }
319 elseif ($flag == -1) {
320 CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $groupId);
321 }
322 }
323 }
324
325 // Add location Block data.
326 $blocks = CRM_Core_BAO_Location::create($params, $fixAddress);
327 foreach ($blocks as $name => $value) {
328 $contact->$name = $value;
329 }
330 if (!empty($params['updateBlankLocInfo'])) {
331 $skipDelete = TRUE;
332 }
333
334 if (isset($params['website'])) {
335 CRM_Core_BAO_Website::process($params['website'], $contact->id, $skipDelete);
336 }
337
338 $userID = CRM_Core_Session::singleton()->get('userID');
339 // add notes
340 if (!empty($params['note'])) {
341 if (is_array($params['note'])) {
342 foreach ($params['note'] as $note) {
343 $contactId = $contact->id;
344 if (isset($note['contact_id'])) {
345 $contactId = $note['contact_id'];
346 }
347 //if logged in user, overwrite contactId
348 if ($userID) {
349 $contactId = $userID;
350 }
351
352 $noteParams = [
353 'entity_id' => $contact->id,
354 'entity_table' => 'civicrm_contact',
355 'note' => $note['note'],
356 'subject' => $note['subject'] ?? NULL,
357 'contact_id' => $contactId,
358 ];
359 CRM_Core_BAO_Note::add($noteParams);
360 }
361 }
362 else {
363 $contactId = $contact->id;
364 //if logged in user, overwrite contactId
365 if ($userID) {
366 $contactId = $userID;
367 }
368
369 $noteParams = [
370 'entity_id' => $contact->id,
371 'entity_table' => 'civicrm_contact',
372 'note' => $params['note'],
373 'subject' => $params['subject'] ?? NULL,
374 'contact_id' => $contactId,
375 ];
376 CRM_Core_BAO_Note::add($noteParams);
377 }
378 }
379
380 if (!empty($params['custom']) &&
381 is_array($params['custom'])
382 ) {
383 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contact', $contact->id, $isEdit ? 'edit' : 'create');
384 }
385
386 $transaction->commit();
387
388 // CRM-6367: fetch the right label for contact type’s display
389 $contact->contact_type_display = CRM_Core_DAO::getFieldValue(
390 'CRM_Contact_DAO_ContactType',
391 $contact->contact_type,
392 'label',
393 'name'
394 );
395
396 CRM_Contact_BAO_Contact_Utils::clearContactCaches();
397
398 if ($invokeHooks) {
399 if ($isEdit) {
400 CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
401 }
402 else {
403 CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
404 }
405 }
406
407 // In order to prevent a series of expensive queries in intensive batch processing
408 // api calls may pass in skip_greeting_processing, probably doing it later via the
409 // scheduled job. CRM-21551
410 if (empty($params['skip_greeting_processing'])) {
411 self::processGreetings($contact);
412 }
413
414 if (!empty($params['check_permissions'])) {
415 $contacts = [&$contact];
416 self::unsetProtectedFields($contacts);
417 }
418
419 if (!empty($params['is_deceased'])) {
420 // Edit Membership Status
421 $deceasedParams = [
422 'contact_id' => $contact->id,
423 'is_deceased' => $params['is_deceased'],
424 'deceased_date' => $params['deceased_date'] ?? NULL,
425 ];
426 CRM_Member_BAO_Membership::updateMembershipStatus($deceasedParams, $params['contact_type']);
427 }
428
429 return $contact;
430 }
431
432 /**
433 * Check if a contact has a name.
434 *
435 * - Individuals need a first_name or last_name
436 * - Organizations need organization_name
437 * - Households need household_name
438 *
439 * @param array $contact
440 * @return bool
441 */
442 public static function hasName(array $contact): bool {
443 $nameFields = [
444 'Individual' => ['first_name', 'last_name'],
445 'Organization' => ['organization_name'],
446 'Household' => ['household_name'],
447 ];
448 // Casting to int filters out the string 'null'
449 $cid = (int) ($contact['id'] ?? NULL);
450 $contactType = $contact['contact_type'] ?? NULL;
451 if (!$contactType && $cid) {
452 $contactType = CRM_Core_DAO::getFieldValue(__CLASS__, $cid, 'contact_type');
453 }
454 if (!$contactType || !isset($nameFields[$contactType])) {
455 throw new CRM_Core_Exception('No contact_type given to ' . __CLASS__ . '::' . __FUNCTION__);
456 }
457 foreach ($nameFields[$contactType] as $field) {
458 if (isset($contact[$field]) && is_string($contact[$field]) && $contact[$field] !== '') {
459 return TRUE;
460 }
461 }
462 // For existing contacts, look up name from database
463 if ($cid) {
464 foreach ($nameFields[$contactType] as $field) {
465 $value = $contact[$field] ?? CRM_Core_DAO::getFieldValue(__CLASS__, $cid, $field);
466 if (isset($value) && $value !== '') {
467 return TRUE;
468 }
469 }
470 }
471 return FALSE;
472 }
473
474 /**
475 * Format the output of the create contact function
476 *
477 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
478 */
479 public static function unsetProtectedFields(&$contacts) {
480 if (!CRM_Core_Permission::check([['edit api keys', 'administer CiviCRM']])) {
481 $currentUser = CRM_Core_Session::getLoggedInContactID();
482 $editOwn = $currentUser && CRM_Core_Permission::check('edit own api keys');
483 foreach ($contacts as &$contact) {
484 $cid = is_object($contact) ? $contact->id : $contact['id'] ?? NULL;
485 if (!($editOwn && $cid == $currentUser)) {
486 if (is_object($contact)) {
487 unset($contact->api_key);
488 }
489 else {
490 unset($contact['api_key']);
491 }
492 }
493 }
494 }
495 }
496
497 /**
498 * Ensure greeting parameters are set.
499 *
500 * By always populating greetings here we can be sure they are set if required & avoid a call later.
501 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
502 *
503 * @param array $params
504 *
505 * @throws \CiviCRM_API3_Exception
506 */
507 public static function ensureGreetingParamsAreSet(&$params) {
508 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
509 $missingGreetingParams = [];
510
511 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
512 if (!empty($params[$greetingIndex . '_custom']) && empty($params[$greetingParam])) {
513 $params[$greetingParam] = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greetingParam, 'Customized');
514 }
515 // An empty string means NULL
516 if (($params[$greetingParam] ?? NULL) === '') {
517 $params[$greetingParam] = 'null';
518 }
519 if (empty($params[$greetingParam])) {
520 $missingGreetingParams[$greetingIndex] = $greetingParam;
521 }
522 }
523
524 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
525 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
526 'id' => $params['contact_id'],
527 'return' => array_keys($missingGreetingParams),
528 ]);
529
530 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
531 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
532 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
533 }
534 }
535 // Filter out other fields.
536 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
537 $params = array_merge($params, $savedGreetings);
538 }
539 else {
540 foreach ($missingGreetingParams as $greetingName => $greeting) {
541 $params[$greeting] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($params['contact_type'], $greetingName);
542 }
543 }
544
545 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
546 if ($params[$greetingParam] === 'null') {
547 // If we are setting it to null then null out the display field.
548 $params[$greetingIndex . '_display'] = 'null';
549 }
550 if ((int) $params[$greetingParam] != CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greetingParam, 'Customized')) {
551 $params[$greetingIndex . '_custom'] = 'null';
552 }
553
554 }
555 }
556
557 /**
558 * Get the display name and image of a contact.
559 *
560 * @param int $id
561 * The contactId.
562 *
563 * @param bool $includeTypeInReturnParameters
564 * Should type be part of the returned array?
565 *
566 * @return array|null
567 * the displayName and contactImage for this contact
568 */
569 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
570 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
571 $sql = "
572 SELECT civicrm_contact.*,
573 civicrm_email.email as email
574 FROM civicrm_contact
575 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
576 AND civicrm_email.is_primary = 1
577 WHERE civicrm_contact.id = " . CRM_Utils_Type::escape($id, 'Integer');
578 $dao = new CRM_Core_DAO();
579 $dao->query($sql);
580 if ($dao->fetch()) {
581 $image = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
582 $dao->contact_sub_type : $dao->contact_type, FALSE, $id
583 );
584 $imageUrl = CRM_Contact_BAO_Contact_Utils::getImage($dao->contact_sub_type ?
585 $dao->contact_sub_type : $dao->contact_type, TRUE, $id
586 );
587
588 // use email if display_name is empty
589 if (empty($dao->display_name)) {
590 $displayName = $dao->email;
591 }
592 else {
593 $displayName = $dao->display_name;
594 }
595
596 CRM_Utils_Hook::alterDisplayName($displayName, $id, $dao);
597
598 return $includeTypeInReturnParameters ? [
599 $displayName,
600 $image,
601 $dao->contact_type,
602 $dao->contact_sub_type,
603 $imageUrl,
604 ] : [$displayName, $image, $imageUrl];
605 }
606 return NULL;
607 }
608
609 /**
610 * Add billing fields to the params if appropriate.
611 *
612 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
613 * don't then we should set the name fields to the billing fields AND add the preserveDBName
614 * parameter (which will tell the BAO only to set those fields if none already exist.
615 *
616 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
617 * matching is best done by hipsters.
618 *
619 * @param array $params
620 *
621 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
622 */
623 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
624 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
625 foreach ($nameFields as $field) {
626 if (!empty($params[$field])) {
627 return;
628 }
629 }
630 // There are only 3 - we can iterate through them twice :-)
631 foreach ($nameFields as $field) {
632 if (!empty($params['billing_' . $field])) {
633 $params[$field] = $params['billing_' . $field];
634 }
635 $params['preserveDBName'] = TRUE;
636 }
637
638 }
639
640 /**
641 * Resolve a state province string (UT or Utah) to an ID.
642 *
643 * If country has been passed in we should select a state belonging to that country.
644 *
645 * Alternatively we should choose from enabled countries, prioritising the default country.
646 *
647 * @param array $values
648 * @param int|null $countryID
649 *
650 * @return int|null
651 *
652 * @throws \CRM_Core_Exception
653 */
654 protected static function resolveStateProvinceID($values, $countryID) {
655
656 if ($countryID) {
657 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($countryID);
658 if (CRM_Utils_Array::lookupValue($values,
659 'state_province',
660 $stateProvinceList,
661 TRUE
662 )) {
663 return $values['state_province_id'];
664 }
665 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($countryID, 'abbreviation');
666 if (CRM_Utils_Array::lookupValue($values,
667 'state_province',
668 $stateProvinceList,
669 TRUE
670 )) {
671 return $values['state_province_id'];
672 }
673 return NULL;
674 }
675 else {
676 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
677 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
678 // prefer matching country..
679 $stateProvinceList = CRM_Core_BAO_Address::buildOptions('state_province_id', NULL, ['country_id' => Civi::settings()->get('defaultContactCountry')]);
680 if (CRM_Utils_Array::lookupValue($values,
681 'state_province',
682 $stateProvinceList,
683 TRUE
684 )) {
685 return $values['state_province_id'];
686 }
687
688 $stateProvinceList = CRM_Core_PseudoConstant::stateProvince();
689 if (CRM_Utils_Array::lookupValue($values,
690 'state_province',
691 $stateProvinceList,
692 TRUE
693 )) {
694 return $values['state_province_id'];
695 }
696
697 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviationForDefaultCountry();
698 if (CRM_Utils_Array::lookupValue($values,
699 'state_province',
700 $stateProvinceList,
701 TRUE
702 )) {
703 return $values['state_province_id'];
704 }
705 $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
706 if (CRM_Utils_Array::lookupValue($values,
707 'state_province',
708 $stateProvinceList,
709 TRUE
710 )) {
711 return $values['state_province_id'];
712 }
713 }
714
715 return NULL;
716 }
717
718 /**
719 * Get the relevant location entity for the array key.
720 *
721 * Based on the field name we determine which location entity
722 * we are dealing with. Apart from a few specific ones they
723 * are mostly 'address' (the default).
724 *
725 * @param string $fieldName
726 *
727 * @return string
728 */
729 protected static function getLocationEntityForKey($fieldName) {
730 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
731 return $fieldName;
732 }
733 if ($fieldName === 'phone_ext') {
734 return 'phone';
735 }
736 return 'address';
737 }
738
739 /**
740 * Soft delete a contact.
741 *
742 * Call this via the api, not directly.
743 *
744 * @param \CRM_Contact_BAO_Contact $contact
745 *
746 * @return bool
747 * @throws \CRM_Core_Exception
748 */
749 protected static function contactTrash($contact): bool {
750 $updateParams = [
751 'id' => $contact->id,
752 'is_deleted' => 1,
753 ];
754 CRM_Utils_Hook::pre('edit', $contact->contact_type, $contact->id, $updateParams);
755
756 $params = [1 => [$contact->id, 'Integer']];
757 $query = 'DELETE FROM civicrm_uf_match WHERE contact_id = %1';
758 CRM_Core_DAO::executeQuery($query, $params);
759
760 $contact->copyValues($updateParams);
761 $contact->save();
762 CRM_Core_BAO_Log::register($contact->id, 'civicrm_contact', $contact->id);
763
764 CRM_Utils_Hook::post('edit', $contact->contact_type, $contact->id, $contact);
765
766 return TRUE;
767 }
768
769 /**
770 * Get the values for pseudoconstants for name->value and reverse.
771 *
772 * @param array $defaults
773 * (reference) the default values, some of which need to be resolved.
774 * @param bool $reverse
775 * Always true as this function is only called from one place..
776 *
777 * @deprecated
778 *
779 * This is called specifically from the contact import parser & should be moved there
780 * as it is not truly a generic function.
781 *
782 */
783 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
784 }
785
786 /**
787 * Fetch object based on array of properties.
788 *
789 * @deprecated This is called from a few places but creates rather than solves
790 * complexity.
791 *
792 * @param array $params
793 * (reference ) an assoc array of name/value pairs.
794 * @param array $defaults
795 * (reference ) an assoc array to hold the name / value pairs.
796 * in a hierarchical manner
797 * @param bool $microformat
798 * For location in microformat.
799 *
800 * @return CRM_Contact_BAO_Contact
801 */
802 public static function &retrieve(&$params, &$defaults = [], $microformat = FALSE) {
803 if (array_key_exists('contact_id', $params)) {
804 $params['id'] = $params['contact_id'];
805 }
806 elseif (array_key_exists('id', $params)) {
807 $params['contact_id'] = $params['id'];
808 }
809
810 $contact = self::getValues($params, $defaults);
811
812 unset($params['id']);
813
814 $contact->im = $defaults['im'] = CRM_Core_BAO_IM::getValues(['contact_id' => $params['contact_id']]);
815 $contact->email = $defaults['email'] = CRM_Core_BAO_Email::getValues(['contact_id' => $params['contact_id']]);
816 $contact->openid = $defaults['openid'] = CRM_Core_BAO_OpenID::getValues(['contact_id' => $params['contact_id']]);
817 $contact->phone = $defaults['phone'] = CRM_Core_BAO_Phone::getValues(['contact_id' => $params['contact_id']]);
818 $contact->address = $defaults['address'] = CRM_Core_BAO_Address::getValues(['contact_id' => $params['contact_id']], $microformat);
819 $contact->website = CRM_Core_BAO_Website::getValues($params, $defaults);
820
821 if (!isset($params['noNotes'])) {
822 $contact->notes = CRM_Core_BAO_Note::getValues($params, $defaults);
823 }
824
825 if (!isset($params['noRelationships'])) {
826 $contact->relationship = CRM_Contact_BAO_Relationship::getValues($params, $defaults);
827 }
828
829 if (!isset($params['noGroups'])) {
830 $contact->groupContact = CRM_Contact_BAO_GroupContact::getValues($params, $defaults);
831 }
832
833 return $contact;
834 }
835
836 /**
837 * Get the display name of a contact.
838 *
839 * @param int $id
840 * Id of the contact.
841 *
842 * @return null|string
843 * display name of the contact if found
844 */
845 public static function displayName($id) {
846 $displayName = NULL;
847 if ($id) {
848 $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
849 }
850
851 return $displayName;
852 }
853
854 /**
855 * Delete a contact and all its associated records.
856 *
857 * @param int $id
858 * Id of the contact to delete.
859 * @param bool $restore
860 * Whether to actually restore, not delete.
861 * @param bool $skipUndelete
862 * Whether to force contact delete or not.
863 * @param bool $checkPermissions
864 *
865 * @return bool
866 * Was contact deleted?
867 *
868 * @throws \CRM_Core_Exception
869 * @throws \CiviCRM_API3_Exception
870 */
871 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
872
873 if (!$id || !is_numeric($id)) {
874 CRM_Core_Error::deprecatedFunctionWarning('calling delete contact without a valid contact ID is deprecated.');
875 return FALSE;
876 }
877 // If trash is disabled in system settings then we always skip
878 if (!Civi::settings()->get('contact_undelete')) {
879 $skipUndelete = TRUE;
880 }
881
882 // make sure we have edit permission for this contact
883 // before we delete
884 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission::check('delete contacts')) ||
885 ($restore && !CRM_Core_Permission::check('access deleted contacts')))
886 ) {
887 return FALSE;
888 }
889
890 // CRM-12929
891 // Restrict contact to be delete if contact has financial trxns
892 $error = NULL;
893 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent([$id], $error)) {
894 return FALSE;
895 }
896
897 // make sure this contact_id does not have any membership types
898 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
899 $id,
900 'id',
901 'member_of_contact_id'
902 );
903 if ($membershipTypeID) {
904 return FALSE;
905 }
906
907 $contact = new CRM_Contact_DAO_Contact();
908 $contact->id = $id;
909 if (!$contact->find(TRUE)) {
910 return FALSE;
911 }
912
913 $contactType = $contact->contact_type;
914 if ($restore) {
915 // @todo deprecate calling contactDelete with the intention to restore.
916 $updateParams = [
917 'id' => $contact->id,
918 'is_deleted' => FALSE,
919 ];
920 self::create($updateParams);
921 return TRUE;
922 }
923
924 // start a new transaction
925 $transaction = new CRM_Core_Transaction();
926
927 if ($skipUndelete) {
928 $hookParams = ['check_permissions' => $checkPermissions];
929 CRM_Utils_Hook::pre('delete', $contactType, $id, $hookParams);
930
931 //delete billing address if exists.
932 CRM_Contribute_BAO_Contribution::deleteAddress(NULL, $id);
933
934 // delete the log entries since we dont have triggers enabled as yet
935 $logDAO = new CRM_Core_DAO_Log();
936 $logDAO->entity_table = 'civicrm_contact';
937 $logDAO->entity_id = $id;
938 $logDAO->delete();
939
940 // delete contact participants CRM-12155
941 CRM_Event_BAO_Participant::deleteContactParticipant($id);
942
943 // delete contact contributions CRM-12155
944 CRM_Contribute_BAO_Contribution::deleteContactContribution($id);
945
946 // do activity cleanup, CRM-5604
947 CRM_Activity_BAO_Activity::cleanupActivity($id);
948
949 // delete all notes related to contact
950 CRM_Core_BAO_Note::cleanContactNotes($id);
951
952 // delete cases related to contact
953 $contactCases = CRM_Case_BAO_Case::retrieveCaseIdsByContactId($id);
954 if (!empty($contactCases)) {
955 foreach ($contactCases as $caseId) {
956 //check if case is associate with other contact or not.
957 $caseContactId = CRM_Case_BAO_Case::getCaseClients($caseId);
958 if (count($caseContactId) <= 1) {
959 CRM_Case_BAO_Case::deleteCase($caseId);
960 }
961 }
962 }
963
964 $contact->delete();
965 }
966 else {
967 self::contactTrash($contact);
968 }
969 // currently we only clear employer cache.
970 // we are now deleting inherited membership if any.
971 if ($contact->contact_type == 'Organization') {
972 $action = $restore ? CRM_Core_Action::ENABLE : CRM_Core_Action::DISABLE;
973 $relationshipDtls = CRM_Contact_BAO_Relationship::getRelationship($id);
974 if (!empty($relationshipDtls)) {
975 foreach ($relationshipDtls as $rId => $details) {
976 CRM_Contact_BAO_Relationship::disableEnableRelationship($rId, $action);
977 }
978 }
979 CRM_Contact_BAO_Contact_Utils::clearAllEmployee($id);
980 }
981
982 //delete the contact id from recently view
983 CRM_Utils_Recent::del(['contact_id' => $id]);
984 self::updateContactCache($id, empty($restore));
985
986 // delete any prevnext/dupe cache entry
987 // These two calls are redundant in default deployments, but they're
988 // meaningful if "prevnext" is memory-backed.
989 Civi::service('prevnext')->deleteItem($id);
990 CRM_Core_BAO_PrevNextCache::deleteItem($id);
991
992 $transaction->commit();
993
994 if ($skipUndelete) {
995 CRM_Utils_Hook::post('delete', $contactType, $contact->id, $contact);
996 }
997
998 return TRUE;
999 }
1000
1001 /**
1002 * Action to update any caches relating to a recently update contact.
1003 *
1004 * I was going to call this from delete as well as from create to ensure the delete is being
1005 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1006 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1007 * where the call involved a subquery that was locking the table.
1008 *
1009 * @param int $contactID
1010 * @param bool $isTrashed
1011 */
1012 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1013
1014 if ($isTrashed) {
1015 CRM_Contact_BAO_GroupContactCache::removeContact($contactID);
1016 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1017 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1018 // but this should not cause any change as long as contacts are not being trashed outside the
1019 // main functions for that.
1020 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1021 }
1022 else {
1023 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
1024 }
1025 }
1026
1027 /**
1028 * Delete the image of a contact.
1029 *
1030 * @param int $id
1031 * Id of the contact.
1032 *
1033 * @return bool
1034 * Was contact image deleted?
1035 */
1036 public static function deleteContactImage($id) {
1037 if (!$id) {
1038 return FALSE;
1039 }
1040
1041 $contact = new self();
1042 $contact->id = $id;
1043 $contact->image_URL = 'null';
1044 $contact->save();
1045
1046 return TRUE;
1047 }
1048
1049 /**
1050 * Return proportional height and width of the image.
1051 *
1052 * @param int $imageWidth
1053 * Width of image.
1054 *
1055 * @param int $imageHeight
1056 * Height of image.
1057 *
1058 * @return array
1059 * Thumb dimension of image
1060 */
1061 public static function getThumbSize($imageWidth, $imageHeight) {
1062 $thumbWidth = 100;
1063 if ($imageWidth && $imageHeight) {
1064 $imageRatio = $imageWidth / $imageHeight;
1065 }
1066 else {
1067 $imageRatio = 1;
1068 }
1069 if ($imageRatio > 1) {
1070 $imageThumbWidth = $thumbWidth;
1071 $imageThumbHeight = round($thumbWidth / $imageRatio);
1072 }
1073 else {
1074 $imageThumbHeight = $thumbWidth;
1075 $imageThumbWidth = round($thumbWidth * $imageRatio);
1076 }
1077
1078 return [$imageThumbWidth, $imageThumbHeight];
1079 }
1080
1081 /**
1082 * Validate type of contact image.
1083 *
1084 * @param array $params
1085 * @param string $imageIndex
1086 * Index of image field.
1087 * @param string $statusMsg
1088 * Status message to be set after operation.
1089 * @param string $opType
1090 * Type of operation like fatal, bounce etc.
1091 *
1092 * @return bool
1093 * true if valid image extension
1094 */
1095 public static function processImageParams(
1096 &$params,
1097 $imageIndex = 'image_URL',
1098 $statusMsg = NULL,
1099 $opType = 'status'
1100 ) {
1101 $mimeType = [
1102 'image/jpeg',
1103 'image/jpg',
1104 'image/png',
1105 'image/bmp',
1106 'image/p-jpeg',
1107 'image/gif',
1108 'image/x-png',
1109 ];
1110
1111 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1112 $photo = basename($params[$imageIndex]['name']);
1113 $params[$imageIndex] = CRM_Utils_System::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1114 return TRUE;
1115 }
1116 else {
1117 unset($params[$imageIndex]);
1118 if (!$statusMsg) {
1119 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1120 }
1121 if ($opType == 'status') {
1122 CRM_Core_Session::setStatus($statusMsg, ts('Error'), 'error');
1123 }
1124 // FIXME: additional support for fatal, bounce etc could be added.
1125 return FALSE;
1126 }
1127 }
1128
1129 /**
1130 * Extract contact id from url for deleting contact image.
1131 */
1132 public static function processImage() {
1133
1134 $action = CRM_Utils_Request::retrieve('action', 'String');
1135 $cid = CRM_Utils_Request::retrieve('cid', 'Positive');
1136 // retrieve contact id in case of Profile context
1137 $id = CRM_Utils_Request::retrieve('id', 'Positive');
1138 $cid = $cid ? $cid : $id;
1139 if ($action & CRM_Core_Action::DELETE) {
1140 if (CRM_Utils_Request::retrieve('confirmed', 'Boolean')) {
1141 CRM_Contact_BAO_Contact::deleteContactImage($cid);
1142 CRM_Core_Session::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1143 $session = CRM_Core_Session::singleton();
1144 $toUrl = $session->popUserContext();
1145 CRM_Utils_System::redirect($toUrl);
1146 }
1147 }
1148 }
1149
1150 /**
1151 * Function to set is_delete true or restore deleted contact.
1152 *
1153 * @param CRM_Contact_DAO_Contact $contact
1154 * Contact DAO object.
1155 * @param bool $restore
1156 * True to set the is_delete = 1 else false to restore deleted contact,
1157 * i.e. is_delete = 0
1158 *
1159 * @deprecated
1160 *
1161 * @return bool
1162 * @throws \CRM_Core_Exception
1163 */
1164 public static function contactTrashRestore($contact, $restore = FALSE) {
1165 CRM_Core_Error::deprecatedFunctionWarning('Use the api');
1166
1167 if ($restore) {
1168 CRM_Core_Error::deprecatedFunctionWarning('Use contact.create to restore - this does nothing much');
1169 // @todo deprecate calling contactDelete with the intention to restore.
1170 $updateParams = [
1171 'id' => $contact->id,
1172 'is_deleted' => FALSE,
1173 ];
1174 self::create($updateParams);
1175 return TRUE;
1176 }
1177 return self::contactTrash($contact);
1178 }
1179
1180 /**
1181 * Get contact type for a contact.
1182 *
1183 * @param int $id
1184 * Id of the contact whose contact type is needed.
1185 *
1186 * @return string
1187 * contact_type if $id found else null ""
1188 */
1189 public static function getContactType($id) {
1190 return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1191 }
1192
1193 /**
1194 * Get contact sub type for a contact.
1195 *
1196 * @param int $id
1197 * Id of the contact whose contact sub type is needed.
1198 *
1199 * @param string $implodeDelimiter
1200 *
1201 * @return string
1202 * contact_sub_type if $id found else null ""
1203 */
1204 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1205 $subtype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1206 if (!$subtype) {
1207 return $implodeDelimiter ? NULL : [];
1208 }
1209
1210 $subtype = CRM_Utils_Array::explodePadded($subtype);
1211
1212 if ($implodeDelimiter) {
1213 $subtype = implode($implodeDelimiter, $subtype);
1214 }
1215 return $subtype;
1216 }
1217
1218 /**
1219 * Get pair of contact-type and sub-type for a contact.
1220 *
1221 * @param int $id
1222 * Id of the contact whose contact sub/contact type is needed.
1223 *
1224 * @return array
1225 */
1226 public static function getContactTypes($id) {
1227 $params = ['id' => $id];
1228 $details = [];
1229 $contact = CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact',
1230 $params,
1231 $details,
1232 ['contact_type', 'contact_sub_type']
1233 );
1234
1235 if ($contact) {
1236 $contactTypes = [];
1237 if ($contact->contact_sub_type) {
1238 $contactTypes = CRM_Utils_Array::explodePadded($contact->contact_sub_type);
1239 }
1240 array_unshift($contactTypes, $contact->contact_type);
1241
1242 return $contactTypes;
1243 }
1244 else {
1245 throw new CRM_Core_Exception('Cannot proceed without a valid contact');
1246 }
1247 }
1248
1249 /**
1250 * Combine all the importable fields from the lower levels object.
1251 *
1252 * The ordering is important, since currently we do not have a weight
1253 * scheme. Adding weight is super important
1254 *
1255 * @param int|string $contactType contact Type
1256 * @param bool $status
1257 * Status is used to manipulate first title.
1258 * @param bool $showAll
1259 * If true returns all fields (includes disabled fields).
1260 * @param bool $isProfile
1261 * If its profile mode.
1262 * @param bool $checkPermission
1263 * If false, do not include permissioning clause (for custom data).
1264 *
1265 * @param bool $withMultiCustomFields
1266 *
1267 * @return array
1268 * array of importable Fields
1269 */
1270 public static function importableFields(
1271 $contactType = 'Individual',
1272 $status = FALSE,
1273 $showAll = FALSE,
1274 $isProfile = FALSE,
1275 $checkPermission = TRUE,
1276 $withMultiCustomFields = FALSE
1277 ) {
1278 if (empty($contactType)) {
1279 $contactType = 'All';
1280 }
1281
1282 $cacheKeyString = "importableFields $contactType";
1283 $cacheKeyString .= $status ? '_1' : '_0';
1284 $cacheKeyString .= $showAll ? '_1' : '_0';
1285 $cacheKeyString .= $isProfile ? '_1' : '_0';
1286 $cacheKeyString .= $checkPermission ? '_1' : '_0';
1287 $cacheKeyString .= '_' . CRM_Core_Config::domainID() . '_';
1288
1289 $fields = self::$_importableFields[$cacheKeyString] ?? Civi::cache('fields')->get($cacheKeyString);
1290
1291 if (!$fields) {
1292 $fields = CRM_Contact_DAO_Contact::import();
1293
1294 // get the fields thar are meant for contact types
1295 if (in_array($contactType, [
1296 'Individual',
1297 'Household',
1298 'Organization',
1299 'All',
1300 ])) {
1301 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
1302 }
1303
1304 $locationFields = array_merge(CRM_Core_DAO_Address::import(),
1305 CRM_Core_DAO_Phone::import(),
1306 CRM_Core_DAO_Email::import(),
1307 CRM_Core_DAO_IM::import(TRUE),
1308 CRM_Core_DAO_OpenID::import()
1309 );
1310
1311 $locationFields = array_merge($locationFields,
1312 CRM_Core_BAO_CustomField::getFieldsForImport('Address',
1313 FALSE,
1314 FALSE,
1315 FALSE,
1316 FALSE
1317 )
1318 );
1319
1320 foreach ($locationFields as $key => $field) {
1321 $locationFields[$key]['hasLocationType'] = TRUE;
1322 }
1323
1324 $fields = array_merge($fields, $locationFields);
1325
1326 $fields = array_merge($fields, CRM_Contact_DAO_Contact::import());
1327 $fields = array_merge($fields, CRM_Core_DAO_Note::import());
1328
1329 //website fields
1330 $fields = array_merge($fields, CRM_Core_DAO_Website::import());
1331 $fields['url']['hasWebsiteType'] = TRUE;
1332
1333 if ($contactType != 'All') {
1334 $fields = array_merge($fields,
1335 CRM_Core_BAO_CustomField::getFieldsForImport($contactType,
1336 $showAll,
1337 TRUE,
1338 FALSE,
1339 FALSE,
1340 $withMultiCustomFields
1341 )
1342 );
1343 // Unset the fields which are not related to their contact type.
1344 foreach (CRM_Contact_DAO_Contact::import() as $name => $value) {
1345 if (!empty($value['contactType']) && $value['contactType'] !== $contactType) {
1346 unset($fields[$name]);
1347 }
1348 }
1349 }
1350 else {
1351 foreach (CRM_Contact_BAO_ContactType::basicTypes() as $type) {
1352 $fields = array_merge($fields,
1353 CRM_Core_BAO_CustomField::getFieldsForImport($type,
1354 $showAll,
1355 FALSE,
1356 FALSE,
1357 FALSE,
1358 $withMultiCustomFields
1359 )
1360 );
1361 }
1362 }
1363
1364 if ($isProfile) {
1365 $fields = array_merge($fields, [
1366 'group' => [
1367 'title' => ts('Group(s)'),
1368 'name' => 'group',
1369 ],
1370 'tag' => [
1371 'title' => ts('Tag(s)'),
1372 'name' => 'tag',
1373 ],
1374 'note' => [
1375 'title' => ts('Note'),
1376 'name' => 'note',
1377 ],
1378 'communication_style_id' => [
1379 'title' => ts('Communication Style'),
1380 'name' => 'communication_style_id',
1381 ],
1382 ]);
1383 }
1384
1385 //Sorting fields in alphabetical order(CRM-1507)
1386 $fields = CRM_Utils_Array::crmArraySortByField($fields, 'title');
1387
1388 Civi::cache('fields')->set($cacheKeyString, $fields);
1389 }
1390
1391 self::$_importableFields[$cacheKeyString] = $fields;
1392
1393 if (!$isProfile) {
1394 if (!$status) {
1395 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1396 self::$_importableFields[$cacheKeyString]
1397 );
1398 }
1399 else {
1400 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1401 self::$_importableFields[$cacheKeyString]
1402 );
1403 }
1404 }
1405 return $fields;
1406 }
1407
1408 /**
1409 * Combine all the exportable fields from the lower levels object.
1410 *
1411 * Currently we are using importable fields as exportable fields
1412 *
1413 * @param int|string $contactType contact Type
1414 * @param bool $status
1415 * True while exporting primary contacts.
1416 * @param bool $export
1417 * True when used during export.
1418 * @param bool $search
1419 * True when used during search, might conflict with export param?.
1420 *
1421 * @param bool $withMultiRecord
1422 * @param bool $checkPermissions
1423 *
1424 * @return array
1425 * array of exportable Fields
1426 */
1427 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1428 if (empty($contactType)) {
1429 $contactType = 'All';
1430 }
1431
1432 $cacheKeyString = "exportableFields $contactType";
1433 $cacheKeyString .= $export ? '_1' : '_0';
1434 $cacheKeyString .= $status ? '_1' : '_0';
1435 $cacheKeyString .= $search ? '_1' : '_0';
1436 $cacheKeyString .= '_' . (bool) $checkPermissions;
1437 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1438 //calculates custom fields takes into account the logged in user & caches that for all users
1439 //as an interim fix we will cache the fields by contact
1440 $cacheKeyString .= '_' . CRM_Core_Session::getLoggedInContactID();
1441
1442 if (!self::$_exportableFields || empty(self::$_exportableFields[$cacheKeyString])) {
1443 if (!self::$_exportableFields) {
1444 self::$_exportableFields = [];
1445 }
1446
1447 // check if we can retrieve from database cache
1448 $fields = Civi::cache('fields')->get($cacheKeyString);
1449
1450 if (!$fields) {
1451 $fields = CRM_Contact_DAO_Contact::export();
1452
1453 // The fields are meant for contact types.
1454 if (in_array($contactType, [
1455 'Individual',
1456 'Household',
1457 'Organization',
1458 'All',
1459 ])) {
1460 $fields = array_merge($fields, CRM_Core_OptionValue::getFields('', $contactType));
1461 }
1462 // add current employer for individuals
1463 $fields = array_merge($fields, [
1464 'current_employer' =>
1465 [
1466 'name' => 'organization_name',
1467 'title' => ts('Current Employer'),
1468 'type' => CRM_Utils_Type::T_STRING,
1469 ],
1470 ]);
1471
1472 // This probably would be added anyway by appendPseudoConstantsToFields.
1473 $locationType = [
1474 'location_type' => [
1475 'name' => 'location_type',
1476 'where' => 'civicrm_location_type.name',
1477 'title' => ts('Location Type'),
1478 'type' => CRM_Utils_Type::T_STRING,
1479 ],
1480 ];
1481
1482 $IMProvider = [
1483 'im_provider' => [
1484 'name' => 'im_provider',
1485 'where' => 'civicrm_im.provider_id',
1486 'title' => ts('IM Provider'),
1487 'type' => CRM_Utils_Type::T_STRING,
1488 ],
1489 ];
1490
1491 $phoneFields = CRM_Core_DAO_Phone::export();
1492 // This adds phone_type to the exportable fields and make it available for export.
1493 // with testing the same can be done to the other entities.
1494 CRM_Core_DAO::appendPseudoConstantsToFields($phoneFields);
1495 $locationFields = array_merge($locationType,
1496 CRM_Core_DAO_Address::export(),
1497 $phoneFields,
1498 CRM_Core_DAO_Email::export(),
1499 $IMProvider,
1500 CRM_Core_DAO_IM::export(TRUE),
1501 CRM_Core_DAO_OpenID::export()
1502 );
1503
1504 $locationFields = array_merge($locationFields,
1505 CRM_Core_BAO_CustomField::getFieldsForImport('Address')
1506 );
1507
1508 foreach ($locationFields as $key => $field) {
1509 $locationFields[$key]['hasLocationType'] = TRUE;
1510 }
1511
1512 $fields = array_merge($fields, $locationFields);
1513
1514 //add world region
1515 $fields = array_merge($fields,
1516 CRM_Core_DAO_Worldregion::export()
1517 );
1518
1519 $fields = array_merge($fields,
1520 CRM_Contact_DAO_Contact::export()
1521 );
1522
1523 //website fields
1524 $fields = array_merge($fields, CRM_Core_DAO_Website::export());
1525
1526 if ($contactType != 'All') {
1527 $fields = array_merge($fields,
1528 CRM_Core_BAO_CustomField::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1529 );
1530 }
1531 else {
1532 foreach (CRM_Contact_BAO_ContactType::basicTypes() as $type) {
1533 $fields = array_merge($fields,
1534 CRM_Core_BAO_CustomField::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions ? CRM_Core_Permission::VIEW : FALSE, $withMultiRecord)
1535 );
1536 }
1537 }
1538 //fix for CRM-791
1539 if ($export) {
1540 $fields = array_merge($fields, [
1541 'groups' => [
1542 'title' => ts('Group(s)'),
1543 'name' => 'groups',
1544 ],
1545 'tags' => [
1546 'title' => ts('Tag(s)'),
1547 'name' => 'tags',
1548 ],
1549 'notes' => [
1550 'title' => ts('Note(s)'),
1551 'name' => 'notes',
1552 ],
1553 ]);
1554 }
1555 else {
1556 $fields = array_merge($fields, [
1557 'group' => [
1558 'title' => ts('Group(s)'),
1559 'name' => 'group',
1560 ],
1561 'tag' => [
1562 'title' => ts('Tag(s)'),
1563 'name' => 'tag',
1564 ],
1565 'note' => [
1566 'title' => ts('Note(s)'),
1567 'name' => 'note',
1568 ],
1569 ]);
1570 }
1571
1572 //Sorting fields in alphabetical order(CRM-1507)
1573 foreach ($fields as $k => $v) {
1574 $sortArray[$k] = $v['title'] ?? NULL;
1575 }
1576
1577 $fields = array_merge($sortArray, $fields);
1578 //unset the field which are not related to their contact type.
1579 if ($contactType != 'All') {
1580 $commonValues = [
1581 'Individual' => [
1582 'household_name',
1583 'legal_name',
1584 'sic_code',
1585 'organization_name',
1586 'email_greeting_custom',
1587 'postal_greeting_custom',
1588 'addressee_custom',
1589 ],
1590 'Household' => [
1591 'first_name',
1592 'middle_name',
1593 'last_name',
1594 'formal_title',
1595 'job_title',
1596 'gender_id',
1597 'prefix_id',
1598 'suffix_id',
1599 'birth_date',
1600 'organization_name',
1601 'legal_name',
1602 'legal_identifier',
1603 'sic_code',
1604 'home_URL',
1605 'is_deceased',
1606 'deceased_date',
1607 'current_employer',
1608 'email_greeting_custom',
1609 'postal_greeting_custom',
1610 'addressee_custom',
1611 'prefix_id',
1612 'suffix_id',
1613 ],
1614 'Organization' => [
1615 'first_name',
1616 'middle_name',
1617 'last_name',
1618 'formal_title',
1619 'job_title',
1620 'gender_id',
1621 'prefix_id',
1622 'suffix_id',
1623 'birth_date',
1624 'household_name',
1625 'email_greeting_custom',
1626 'postal_greeting_custom',
1627 'prefix_id',
1628 'suffix_id',
1629 'gender_id',
1630 'addressee_custom',
1631 'is_deceased',
1632 'deceased_date',
1633 'current_employer',
1634 ],
1635 ];
1636 foreach ($commonValues[$contactType] as $value) {
1637 unset($fields[$value]);
1638 }
1639 }
1640
1641 Civi::cache('fields')->set($cacheKeyString, $fields);
1642 }
1643 self::$_exportableFields[$cacheKeyString] = $fields;
1644 }
1645
1646 if (!$status) {
1647 $fields = self::$_exportableFields[$cacheKeyString];
1648 }
1649 else {
1650 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1651 self::$_exportableFields[$cacheKeyString]
1652 );
1653 }
1654
1655 return $fields;
1656 }
1657
1658 /**
1659 * Get the all contact details (Hierarchical).
1660 *
1661 * @param int $contactId
1662 * Contact id.
1663 * @param array $fields
1664 * Fields array.
1665 *
1666 * @return array
1667 * Contact details
1668 */
1669 public static function getHierContactDetails($contactId, $fields) {
1670 $params = [['contact_id', '=', $contactId, 0, 0]];
1671
1672 $returnProperties = self::makeHierReturnProperties($fields, $contactId);
1673
1674 // We don't know the contents of return properties, but we need the lower
1675 // level ids of the contact so add a few fields.
1676 $returnProperties['first_name'] = 1;
1677 $returnProperties['organization_name'] = 1;
1678 $returnProperties['household_name'] = 1;
1679 $returnProperties['contact_type'] = 1;
1680 $returnProperties['contact_sub_type'] = 1;
1681 [$query] = CRM_Contact_BAO_Query::apiQuery($params, $returnProperties);
1682 return $query;
1683 }
1684
1685 /**
1686 * Given a set of flat profile style field names, create a hierarchy.
1687 *
1688 * This is for the query to use, create the right sql.
1689 *
1690 * @param array $fields
1691 * @param int $contactId
1692 * Contact id.
1693 *
1694 * @return array
1695 * A hierarchical property tree if appropriate
1696 */
1697 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1698 $locationTypes = CRM_Core_BAO_Address::buildOptions('location_type_id', 'validate');
1699
1700 $returnProperties = [];
1701
1702 $multipleFields = ['website' => 'url'];
1703 foreach ($fields as $name => $dontCare) {
1704 if (strpos($name, '-') !== FALSE) {
1705 [$fieldName, $id, $type] = CRM_Utils_System::explode('-', $name, 3);
1706
1707 if (!in_array($fieldName, $multipleFields)) {
1708 if ($id == 'Primary') {
1709 $locationTypeName = 1;
1710 }
1711 else {
1712 $locationTypeName = $locationTypes[$id] ?? NULL;
1713 if (!$locationTypeName) {
1714 continue;
1715 }
1716 }
1717
1718 if (empty($returnProperties['location'])) {
1719 $returnProperties['location'] = [];
1720 }
1721 if (empty($returnProperties['location'][$locationTypeName])) {
1722 $returnProperties['location'][$locationTypeName] = [];
1723 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1724 }
1725 if (in_array($fieldName, [
1726 'phone',
1727 'im',
1728 'email',
1729 'openid',
1730 'phone_ext',
1731 ])) {
1732 if ($type) {
1733 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1734 }
1735 else {
1736 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1737 }
1738 }
1739 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1740 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1741 }
1742 else {
1743 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1744 }
1745 }
1746 else {
1747 $returnProperties['website'][$id][$fieldName] = 1;
1748 }
1749 }
1750 else {
1751 $returnProperties[$name] = 1;
1752 }
1753 }
1754
1755 return $returnProperties;
1756 }
1757
1758 /**
1759 * Return the primary location type of a contact.
1760 *
1761 * $params int $contactId contact_id
1762 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1763 * $params boolean $skipDefaultPrimary if true, return primary contact location type otherwise null
1764 *
1765 * @param int $contactId
1766 * @param bool $skipDefaultPrimary
1767 * @param string|null $block
1768 *
1769 * @return int|NULL
1770 * $locationType location_type_id
1771 */
1772 public static function getPrimaryLocationType($contactId, $skipDefaultPrimary = FALSE, $block = NULL) {
1773 if ($block) {
1774 $entityBlock = ['contact_id' => $contactId];
1775 $blocks = CRM_Core_BAO_Location::getValues($entityBlock);
1776 foreach ($blocks[$block] as $key => $value) {
1777 if (!empty($value['is_primary'])) {
1778 $locationType = $value['location_type_id'] ?? NULL;
1779 }
1780 }
1781 }
1782 else {
1783 $query = "
1784 SELECT
1785 IF ( civicrm_email.location_type_id IS NULL,
1786 IF ( civicrm_address.location_type_id IS NULL,
1787 IF ( civicrm_phone.location_type_id IS NULL,
1788 IF ( civicrm_im.location_type_id IS NULL,
1789 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1790 ,civicrm_im.location_type_id)
1791 ,civicrm_phone.location_type_id)
1792 ,civicrm_address.location_type_id)
1793 ,civicrm_email.location_type_id) as locationType
1794 FROM civicrm_contact
1795 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1796 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1797 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1798 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1799 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1800 WHERE civicrm_contact.id = %1 ";
1801
1802 $params = [1 => [$contactId, 'Integer']];
1803
1804 $dao = CRM_Core_DAO::executeQuery($query, $params);
1805
1806 $locationType = NULL;
1807 if ($dao->fetch()) {
1808 $locationType = $dao->locationType;
1809 }
1810 }
1811 if (isset($locationType)) {
1812 return $locationType;
1813 }
1814 elseif ($skipDefaultPrimary) {
1815 // if there is no primary contact location then return null
1816 return NULL;
1817 }
1818 else {
1819 // if there is no primart contact location, then return default
1820 // location type of the system
1821 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
1822 return $defaultLocationType->id;
1823 }
1824 }
1825
1826 /**
1827 * Get the display name, primary email and location type of a contact.
1828 *
1829 * @param int $id
1830 * Id of the contact.
1831 *
1832 * @return array
1833 * Array of display_name, email if found, do_not_email or (null,null,null)
1834 */
1835 public static function getContactDetails($id) {
1836 // check if the contact type
1837 $contactType = self::getContactType($id);
1838
1839 $nameFields = ($contactType == 'Individual') ? "civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1840
1841 $sql = "
1842 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1843 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1844 WHERE civicrm_contact.id = %1
1845 ORDER BY civicrm_email.is_primary DESC";
1846 $params = [1 => [$id, 'Integer']];
1847 $dao = CRM_Core_DAO::executeQuery($sql, $params);
1848
1849 if ($dao->fetch()) {
1850 if ($contactType == 'Individual') {
1851 if ($dao->first_name || $dao->last_name) {
1852 $name = "{$dao->first_name} {$dao->last_name}";
1853 }
1854 else {
1855 $name = $dao->display_name;
1856 }
1857 }
1858 else {
1859 $name = $dao->display_name;
1860 }
1861 $email = $dao->email;
1862 $doNotEmail = (bool) $dao->do_not_email;
1863 $onHold = (bool) $dao->on_hold;
1864 $isDeceased = (bool) $dao->is_deceased;
1865 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1866 }
1867 return [NULL, NULL, NULL, NULL, NULL];
1868 }
1869
1870 /**
1871 * Add/edit/register contacts through profile.
1872 *
1873 * @param array $params
1874 * Array of profile fields to be edited/added.
1875 * @param array $fields
1876 * Array of fields from UFGroup.
1877 * @param int $contactID
1878 * Id of the contact to be edited/added.
1879 * @param int $addToGroupID
1880 * Specifies the default group to which contact is added.
1881 * @param int $ufGroupId
1882 * Uf group id (profile id).
1883 * @param string $ctype
1884 * @param bool $visibility
1885 * Basically lets us know where this request is coming from.
1886 * if via a profile from web, we restrict what groups are changed
1887 *
1888 * @return int
1889 * contact id created/edited
1890 *
1891 * @throws \CRM_Core_Exception
1892 * @throws \CiviCRM_API3_Exception
1893 * @throws \Civi\API\Exception\UnauthorizedException
1894 */
1895 public static function createProfileContact(
1896 &$params,
1897 $fields = [],
1898 $contactID = NULL,
1899 $addToGroupID = NULL,
1900 $ufGroupId = NULL,
1901 $ctype = NULL,
1902 $visibility = FALSE
1903 ) {
1904 // add ufGroupID to params array ( CRM-2012 )
1905 if ($ufGroupId) {
1906 $params['uf_group_id'] = $ufGroupId;
1907 }
1908 self::addBillingNameFieldsIfOtherwiseNotSet($params);
1909
1910 // If a user has logged in, or accessed via a checksum
1911 // Then deliberately 'blanking' a value in the profile should remove it from their record
1912 $session = CRM_Core_Session::singleton();
1913 $params['updateBlankLocInfo'] = TRUE;
1914 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0) {
1915 $params['updateBlankLocInfo'] = FALSE;
1916 }
1917
1918 if ($contactID) {
1919 $editHook = TRUE;
1920 CRM_Utils_Hook::pre('edit', 'Profile', $contactID, $params);
1921 }
1922 else {
1923 $editHook = FALSE;
1924 CRM_Utils_Hook::pre('create', 'Profile', NULL, $params);
1925 }
1926
1927 [$data, $contactDetails] = self::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1928
1929 // manage is_opt_out
1930 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1931 $wasOptOut = $contactDetails['is_opt_out'] ?? FALSE;
1932 $isOptOut = $params['is_opt_out'];
1933 $data['is_opt_out'] = $isOptOut;
1934 // on change, create new civicrm_subscription_history entry
1935 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1936 $shParams = [
1937 'contact_id' => $contactDetails['contact_id'],
1938 'status' => $isOptOut ? 'Removed' : 'Added',
1939 'method' => 'Web',
1940 ];
1941 CRM_Contact_BAO_SubscriptionHistory::create($shParams);
1942 }
1943 }
1944
1945 $contact = self::create($data);
1946
1947 // contact is null if the profile does not have any contact fields
1948 if ($contact) {
1949 $contactID = $contact->id;
1950 }
1951
1952 if (empty($contactID)) {
1953 throw new CRM_Core_Exception('Cannot proceed without a valid contact id');
1954 }
1955
1956 // Process group and tag
1957 // @todo Contact::create also calls addContactsToGroup/removeContactsToGroup
1958 // Remove from here and use the existing functionality in Contact::create
1959 if (isset($params['group'])) {
1960 $method = 'Admin';
1961 // this for sure means we are coming in via profile since i added it to fix
1962 // removing contacts from user groups -- lobo
1963 if ($visibility) {
1964 $method = 'Web';
1965 }
1966 $groupParams = $params['group'] ?? [];
1967 $contactIds = [$contactID];
1968 $contactGroup = [];
1969
1970 if ($contactID) {
1971 $contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($contactID, 'Added',
1972 NULL, FALSE, $visibility
1973 );
1974 if (is_array($contactGroupList)) {
1975 foreach ($contactGroupList as $key) {
1976 $groupId = $key['group_id'];
1977 $contactGroup[$groupId] = $groupId;
1978 }
1979 }
1980 }
1981 // get the list of all the groups
1982 $allGroup = CRM_Contact_BAO_GroupContact::getGroupList(0, $visibility);
1983
1984 // check which values has to be add/remove contact from group
1985 foreach ($allGroup as $key => $varValue) {
1986 if (!empty($groupParams[$key]) && !array_key_exists($key, $contactGroup)) {
1987 // add contact to group
1988 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $key, $method);
1989 }
1990 elseif (empty($groupParams[$key]) && array_key_exists($key, $contactGroup)) {
1991 // remove contact from group
1992 CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $key, $method);
1993 }
1994 }
1995 }
1996
1997 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
1998 // Convert comma separated form values from select2 v3
1999 $tags = is_array($params['tag']) ? $params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2000 CRM_Core_BAO_EntityTag::create($tags, 'civicrm_contact', $contactID);
2001 }
2002
2003 // to add profile in default group
2004 // @todo merge this with code above which also calls addContactsToGroup
2005 if (is_array($addToGroupID)) {
2006 $contactIds = [$contactID];
2007 foreach ($addToGroupID as $groupId) {
2008 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
2009 }
2010 }
2011 elseif ($addToGroupID) {
2012 $contactIds = [$contactID];
2013 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $addToGroupID);
2014 }
2015
2016 if ($editHook) {
2017 CRM_Utils_Hook::post('edit', 'Profile', $contactID, $params);
2018 }
2019 else {
2020 CRM_Utils_Hook::post('create', 'Profile', $contactID, $params);
2021 }
2022 return $contactID;
2023 }
2024
2025 /**
2026 * Format profile contact parameters.
2027 *
2028 * @param array $params
2029 * @param array $fields
2030 * @param int|null $contactID
2031 * @param int|null $ufGroupId
2032 * @param string|null $ctype
2033 * @param bool $skipCustom
2034 *
2035 * @return array
2036 */
2037 public static function formatProfileContactParams(
2038 &$params,
2039 $fields,
2040 $contactID = NULL,
2041 $ufGroupId = NULL,
2042 $ctype = NULL,
2043 $skipCustom = FALSE
2044 ) {
2045
2046 $data = $contactDetails = [];
2047
2048 // get the contact details (hier)
2049 if ($contactID) {
2050 $details = self::getHierContactDetails($contactID, $fields);
2051
2052 $contactDetails = $details[$contactID];
2053 $data['contact_type'] = $contactDetails['contact_type'] ?? NULL;
2054 $data['contact_sub_type'] = $contactDetails['contact_sub_type'] ?? NULL;
2055 }
2056 else {
2057 //we should get contact type only if contact
2058 if ($ufGroupId) {
2059 $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId, TRUE, FALSE, TRUE);
2060
2061 //special case to handle profile with only contact fields
2062 if ($data['contact_type'] == 'Contact') {
2063 $data['contact_type'] = 'Individual';
2064 }
2065 elseif (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) {
2066 $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']);
2067 }
2068 }
2069 elseif ($ctype) {
2070 $data['contact_type'] = $ctype;
2071 }
2072 else {
2073 $data['contact_type'] = 'Individual';
2074 }
2075 }
2076
2077 //fix contact sub type CRM-5125
2078 if (array_key_exists('contact_sub_type', $params) &&
2079 !empty($params['contact_sub_type'])
2080 ) {
2081 $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
2082 }
2083 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2084 !empty($params['contact_sub_type_hidden'])
2085 ) {
2086 // if profile was used, and had any subtype, we obtain it from there
2087 //CRM-13596 - add to existing contact types, rather than overwriting
2088 if (empty($data['contact_sub_type'])) {
2089 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2090 $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
2091 }
2092 else {
2093 $data_contact_sub_type_arr = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
2094 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2095 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2096 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR);
2097 $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . $data['contact_sub_type'] . CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
2098 }
2099 }
2100 }
2101
2102 if ($ctype == 'Organization') {
2103 $data['organization_name'] = $contactDetails['organization_name'] ?? NULL;
2104 }
2105 elseif ($ctype == 'Household') {
2106 $data['household_name'] = $contactDetails['household_name'] ?? NULL;
2107 }
2108
2109 $locationType = [];
2110 $count = 1;
2111
2112 if ($contactID) {
2113 //add contact id
2114 $data['contact_id'] = $contactID;
2115 $primaryLocationType = self::getPrimaryLocationType($contactID);
2116 }
2117 else {
2118 $defaultLocation = CRM_Core_BAO_LocationType::getDefault();
2119 $defaultLocationId = $defaultLocation->id;
2120 }
2121
2122 $billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling();
2123
2124 $blocks = ['email', 'phone', 'im', 'openid'];
2125
2126 $multiplFields = ['url'];
2127 // prevent overwritten of formatted array, reset all block from
2128 // params if it is not in valid format (since import pass valid format)
2129 foreach ($blocks as $blk) {
2130 if (array_key_exists($blk, $params) &&
2131 !is_array($params[$blk])
2132 ) {
2133 unset($params[$blk]);
2134 }
2135 }
2136
2137 $primaryPhoneLoc = NULL;
2138 $session = CRM_Core_Session::singleton();
2139 foreach ($params as $key => $value) {
2140 [$fieldName, $locTypeId, $typeId] = CRM_Utils_System::explode('-', $key, 3);
2141
2142 if ($locTypeId == 'Primary') {
2143 if ($contactID) {
2144 if (in_array($fieldName, $blocks)) {
2145 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, $fieldName);
2146 }
2147 else {
2148 $locTypeId = self::getPrimaryLocationType($contactID, FALSE, 'address');
2149 }
2150 $primaryLocationType = $locTypeId;
2151 }
2152 else {
2153 $locTypeId = $defaultLocationId;
2154 }
2155 }
2156
2157 if (is_numeric($locTypeId) &&
2158 !in_array($fieldName, $multiplFields) &&
2159 substr($fieldName, 0, 7) != 'custom_'
2160 ) {
2161 $index = $locTypeId;
2162
2163 if (is_numeric($typeId)) {
2164 $index .= '-' . $typeId;
2165 }
2166 if (!in_array($index, $locationType)) {
2167 $locationType[$count] = $index;
2168 $count++;
2169 }
2170
2171 $loc = CRM_Utils_Array::key($index, $locationType);
2172
2173 $blockName = self::getLocationEntityForKey($fieldName);
2174
2175 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2176
2177 //set is_billing true, for location type "Billing"
2178 if ($locTypeId == $billingLocationTypeId) {
2179 $data[$blockName][$loc]['is_billing'] = 1;
2180 }
2181
2182 if ($contactID) {
2183 //get the primary location type
2184 if ($locTypeId == $primaryLocationType) {
2185 $data[$blockName][$loc]['is_primary'] = 1;
2186 }
2187 }
2188 elseif ($locTypeId == $defaultLocationId) {
2189 $data[$blockName][$loc]['is_primary'] = 1;
2190 }
2191
2192 if (in_array($fieldName, ['phone'])) {
2193 if ($typeId) {
2194 $data['phone'][$loc]['phone_type_id'] = $typeId;
2195 }
2196 else {
2197 $data['phone'][$loc]['phone_type_id'] = '';
2198 }
2199 $data['phone'][$loc]['phone'] = $value;
2200
2201 //special case to handle primary phone with different phone types
2202 // in this case we make first phone type as primary
2203 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2204 $primaryPhoneLoc = $loc;
2205 }
2206
2207 if ($loc != $primaryPhoneLoc) {
2208 unset($data['phone'][$loc]['is_primary']);
2209 }
2210 }
2211 elseif ($fieldName == 'email') {
2212 $data['email'][$loc]['email'] = $value;
2213 if (empty($contactID)) {
2214 $data['email'][$loc]['is_primary'] = 1;
2215 }
2216 }
2217 elseif ($fieldName == 'im') {
2218 if (isset($params[$key . '-provider_id'])) {
2219 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2220 }
2221 if (strpos($key, '-provider_id') !== FALSE) {
2222 $data['im'][$loc]['provider_id'] = $params[$key];
2223 }
2224 else {
2225 $data['im'][$loc]['name'] = $value;
2226 }
2227 }
2228 elseif ($fieldName == 'openid') {
2229 $data['openid'][$loc]['openid'] = $value;
2230 }
2231 else {
2232 if ($fieldName === 'state_province') {
2233 // CRM-3393
2234 if (is_numeric($value) && ((int ) $value) >= 1000) {
2235 $data['address'][$loc]['state_province_id'] = $value;
2236 }
2237 elseif (empty($value)) {
2238 $data['address'][$loc]['state_province_id'] = '';
2239 }
2240 else {
2241 $data['address'][$loc]['state_province'] = $value;
2242 }
2243 }
2244 elseif ($fieldName === 'country') {
2245 // CRM-3393
2246 if (is_numeric($value) && ((int ) $value) >= 1000
2247 ) {
2248 $data['address'][$loc]['country_id'] = $value;
2249 }
2250 elseif (empty($value)) {
2251 $data['address'][$loc]['country_id'] = '';
2252 }
2253 else {
2254 $data['address'][$loc]['country'] = $value;
2255 }
2256 }
2257 elseif ($fieldName === 'county') {
2258 $data['address'][$loc]['county_id'] = $value;
2259 }
2260 elseif ($fieldName == 'address_name') {
2261 $data['address'][$loc]['name'] = $value;
2262 }
2263 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2264 $data['address'][$loc][substr($fieldName, 8)] = $value;
2265 }
2266 else {
2267 $data[$blockName][$loc][$fieldName] = $value;
2268 }
2269 }
2270 }
2271 else {
2272 if (substr($key, 0, 4) === 'url-') {
2273 $websiteField = explode('-', $key);
2274 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2275 $data['website'][$websiteField[1]]['url'] = $value;
2276 }
2277 elseif (in_array($key, self::$_greetingTypes, TRUE)) {
2278 //save email/postal greeting and addressee values if any, CRM-4575
2279 $data[$key . '_id'] = $value;
2280 }
2281 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) {
2282 // for autocomplete transfer hidden value instead of label
2283 if ($params[$key] && isset($params[$key . '_id'])) {
2284 $value = $params[$key . '_id'];
2285 }
2286
2287 // we need to append time with date
2288 if ($params[$key] && isset($params[$key . '_time'])) {
2289 $value .= ' ' . $params[$key . '_time'];
2290 }
2291
2292 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2293 if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 &&
2294 ($value == '' || !isset($value))
2295 ) {
2296 continue;
2297 }
2298
2299 $valueId = NULL;
2300 if (!empty($params['customRecordValues'])) {
2301 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2302 foreach ($params['customRecordValues'] as $recId => $customFields) {
2303 if (is_array($customFields) && !empty($customFields)) {
2304 foreach ($customFields as $customFieldName) {
2305 if ($customFieldName == $key) {
2306 $valueId = $recId;
2307 break;
2308 }
2309 }
2310 }
2311 }
2312 }
2313 }
2314
2315 //CRM-13596 - check for contact_sub_type_hidden first
2316 if (array_key_exists('contact_sub_type_hidden', $params)) {
2317 $type = $params['contact_sub_type_hidden'];
2318 }
2319 else {
2320 $type = $data['contact_type'];
2321 if (!empty($data['contact_sub_type'])) {
2322 $type = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
2323 }
2324 }
2325
2326 CRM_Core_BAO_CustomField::formatCustomField($customFieldId,
2327 $data['custom'],
2328 $value,
2329 $type,
2330 $valueId,
2331 $contactID,
2332 FALSE,
2333 FALSE
2334 );
2335 }
2336 elseif ($key === 'edit') {
2337 continue;
2338 }
2339 else {
2340 if ($key === 'location') {
2341 foreach ($value as $locationTypeId => $field) {
2342 foreach ($field as $block => $val) {
2343 if ($block === 'address' && array_key_exists('address_name', $val)) {
2344 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2345 }
2346 }
2347 }
2348 }
2349 if ($key === 'phone' && isset($params['phone_ext'])) {
2350 $data[$key] = $value;
2351 foreach ($value as $cnt => $phoneBlock) {
2352 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2353 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2354 }
2355 }
2356 }
2357 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2358 && ($value == '' || !isset($value)) &&
2359 ($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 ||
2360 ($key === 'current_employer' && empty($params['current_employer']))) {
2361 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2362 // to avoid update with empty values
2363 continue;
2364 }
2365 else {
2366 $data[$key] = $value;
2367 }
2368 }
2369 }
2370 }
2371
2372 if (!isset($data['contact_type'])) {
2373 $data['contact_type'] = 'Individual';
2374 }
2375
2376 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2377 $privacy = CRM_Core_SelectValues::privacy();
2378 foreach ($privacy as $key => $value) {
2379 if (array_key_exists($key, $fields)) {
2380 // do not reset values for existing contacts, if fields are added to a profile
2381 if (array_key_exists($key, $params)) {
2382 $data[$key] = $params[$key];
2383 if (empty($params[$key])) {
2384 $data[$key] = 0;
2385 }
2386 }
2387 elseif (!$contactID) {
2388 $data[$key] = 0;
2389 }
2390 }
2391 }
2392
2393 return [$data, $contactDetails];
2394 }
2395
2396 /**
2397 * Find the get contact details.
2398 *
2399 * This function does not respect ACLs for now, which might need to be rectified at some
2400 * stage based on how its used.
2401 *
2402 * @param string $mail
2403 * Primary email address of the contact.
2404 * @param string $ctype
2405 * Contact type.
2406 *
2407 * @return object|null
2408 * $dao contact details
2409 */
2410 public static function matchContactOnEmail($mail, $ctype = NULL) {
2411 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2412 $mail = $strtolower(trim($mail));
2413 $query = "
2414 SELECT civicrm_contact.id as contact_id,
2415 civicrm_contact.hash as hash,
2416 civicrm_contact.contact_type as contact_type,
2417 civicrm_contact.contact_sub_type as contact_sub_type
2418 FROM civicrm_contact
2419 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2420
2421 if (Civi::settings()->get('uniq_email_per_site')) {
2422 // try to find a match within a site (multisite).
2423 $groups = CRM_Core_BAO_Domain::getChildGroupIds();
2424 if (!empty($groups)) {
2425 $query .= "
2426 INNER JOIN civicrm_group_contact gc ON
2427 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2428 }
2429 }
2430
2431 $query .= "
2432 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2433 $p = [1 => [$mail, 'String']];
2434
2435 if ($ctype) {
2436 $query .= " AND civicrm_contact.contact_type = %3";
2437 $p[3] = [$ctype, 'String'];
2438 }
2439
2440 $query .= " ORDER BY civicrm_email.is_primary DESC";
2441
2442 $dao = CRM_Core_DAO::executeQuery($query, $p);
2443
2444 if ($dao->fetch()) {
2445 return $dao;
2446 }
2447 return NULL;
2448 }
2449
2450 /**
2451 * Find the contact details associated with an OpenID.
2452 *
2453 * @param string $openId
2454 * OpenId of the contact.
2455 * @param string $ctype
2456 * Contact type.
2457 *
2458 * @return object|null
2459 * $dao contact details
2460 */
2461 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2462 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2463 $openId = $strtolower(trim($openId));
2464 $query = "
2465 SELECT civicrm_contact.id as contact_id,
2466 civicrm_contact.hash as hash,
2467 civicrm_contact.contact_type as contact_type,
2468 civicrm_contact.contact_sub_type as contact_sub_type
2469 FROM civicrm_contact
2470 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2471 WHERE civicrm_openid.openid = %1";
2472 $p = [1 => [$openId, 'String']];
2473
2474 if ($ctype) {
2475 $query .= " AND civicrm_contact.contact_type = %3";
2476 $p[3] = [$ctype, 'String'];
2477 }
2478
2479 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2480
2481 $dao = CRM_Core_DAO::executeQuery($query, $p);
2482
2483 if ($dao->fetch()) {
2484 return $dao;
2485 }
2486 return NULL;
2487 }
2488
2489 /**
2490 * Get primary email of the contact.
2491 *
2492 * @param int $contactID
2493 * Contact id.
2494 * @param bool $polite
2495 * Whether to only pull an email if it's okay to send to it--that is, if it
2496 * is not on_hold and the contact is not do_not_email.
2497 *
2498 * @return string
2499 * Email address if present else null
2500 */
2501 public static function getPrimaryEmail($contactID, $polite = FALSE) {
2502 // fetch the primary email
2503 $query = "
2504 SELECT civicrm_email.email as email
2505 FROM civicrm_contact
2506 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2507 WHERE civicrm_email.is_primary = 1
2508 AND civicrm_contact.id = %1";
2509 if ($polite) {
2510 $query .= '
2511 AND civicrm_contact.do_not_email = 0
2512 AND civicrm_email.on_hold = 0';
2513 }
2514 $p = [1 => [$contactID, 'Integer']];
2515 $dao = CRM_Core_DAO::executeQuery($query, $p);
2516
2517 $email = NULL;
2518 if ($dao->fetch()) {
2519 $email = $dao->email;
2520 }
2521 return $email;
2522 }
2523
2524 /**
2525 * Fetch the object and store the values in the values array.
2526 *
2527 * @param array $params
2528 * Input parameters to find object.
2529 * @param array $values
2530 * Output values of the object.
2531 *
2532 * @return CRM_Contact_BAO_Contact|null
2533 * The found object or null
2534 */
2535 public static function getValues($params, &$values) {
2536 $contact = new CRM_Contact_BAO_Contact();
2537
2538 $contact->copyValues($params);
2539
2540 if ($contact->find(TRUE)) {
2541
2542 CRM_Core_DAO::storeValues($contact, $values);
2543
2544 $privacy = [];
2545 foreach (self::$_commPrefs as $name) {
2546 if (isset($contact->$name)) {
2547 $privacy[$name] = $contact->$name;
2548 }
2549 }
2550
2551 if (!empty($privacy)) {
2552 $values['privacy'] = $privacy;
2553 }
2554
2555 // communication Prefferance
2556 $preffComm = $comm = [];
2557 $comm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2558 ($contact->preferred_communication_method ?? '')
2559 );
2560 foreach ($comm as $value) {
2561 $preffComm[$value] = 1;
2562 }
2563 $temp = ['preferred_communication_method' => $contact->preferred_communication_method];
2564
2565 $names = [
2566 'preferred_communication_method' => [
2567 'newName' => 'preferred_communication_method_display',
2568 'groupName' => 'preferred_communication_method',
2569 ],
2570 ];
2571
2572 // @todo This can be figured out from metadata & we can avoid the uncached query.
2573 CRM_Core_OptionGroup::lookupValues($temp, $names, FALSE);
2574
2575 $values['preferred_communication_method'] = $preffComm;
2576 $values['preferred_communication_method_display'] = $temp['preferred_communication_method_display'] ?? NULL;
2577
2578 if ($contact->preferred_mail_format) {
2579 $preferredMailingFormat = CRM_Core_SelectValues::pmf();
2580 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format];
2581 }
2582
2583 // get preferred languages
2584 if (!empty($contact->preferred_language)) {
2585 $values['preferred_language'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language);
2586 }
2587
2588 // Calculating Year difference
2589 if ($contact->birth_date) {
2590 $birthDate = CRM_Utils_Date::customFormat($contact->birth_date, '%Y%m%d');
2591 if ($birthDate < date('Ymd')) {
2592 $deceasedDate = NULL;
2593 if (!empty($contact->is_deceased) && !empty($contact->deceased_date)) {
2594 $deceasedDate = $contact->deceased_date;
2595 }
2596 $age = CRM_Utils_Date::calculateAge($birthDate, $deceasedDate);
2597 $values['age']['y'] = $age['years'] ?? NULL;
2598 $values['age']['m'] = $age['months'] ?? NULL;
2599 }
2600 }
2601
2602 $contact->contact_id = $contact->id;
2603
2604 return $contact;
2605 }
2606 return NULL;
2607 }
2608
2609 /**
2610 * Provides counts for the contact summary tabs.
2611 *
2612 * @param string $type
2613 * Type of record to count.
2614 * @param int $contactId
2615 * Input contact id.
2616 * @param string|null $tableName
2617 * Deprecated - do not use
2618 *
2619 * @return int|false
2620 * total number in database
2621 */
2622 public static function getCountComponent(string $type, int $contactId, ?string $tableName = NULL) {
2623 if ($tableName) {
2624 // TODO: Fix LineItemEditor extension to not use this function, then enable warning
2625 // CRM_Core_Error::deprecatedWarning('Deprecated argument $tableName passed to ' . __CLASS__ . '::' . __FUNCTION__);
2626 }
2627 switch ($type) {
2628 case 'tag':
2629 return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE);
2630
2631 case 'rel':
2632 $result = CRM_Contact_BAO_Relationship::getRelationship($contactId,
2633 CRM_Contact_BAO_Relationship::CURRENT,
2634 0, 1, 0,
2635 NULL, NULL,
2636 TRUE
2637 );
2638 return $result;
2639
2640 case 'group':
2641 return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2642
2643 case 'log':
2644 if (CRM_Core_BAO_Log::useLoggingReport()) {
2645 return FALSE;
2646 }
2647 return CRM_Core_BAO_Log::getContactLogCount($contactId);
2648
2649 case 'note':
2650 return CRM_Core_BAO_Note::getContactNoteCount($contactId);
2651
2652 case 'contribution':
2653 if (CRM_Core_Component::isEnabled('CiviContribute')) {
2654 return CRM_Contribute_BAO_Contribution::contributionCount($contactId);
2655 }
2656 return FALSE;
2657
2658 case 'membership':
2659 if (CRM_Core_Component::isEnabled('CiviMember')) {
2660 return CRM_Member_BAO_Membership::getContactMembershipCount((int) $contactId, TRUE);
2661 }
2662 return FALSE;
2663
2664 case 'participant':
2665 return CRM_Event_BAO_Participant::getContactParticipantCount($contactId);
2666
2667 case 'pledge':
2668 return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId);
2669
2670 case 'case':
2671 return CRM_Case_BAO_Case::caseCount($contactId);
2672
2673 case 'activity':
2674 $input = [
2675 'contact_id' => $contactId,
2676 'admin' => FALSE,
2677 'caseId' => NULL,
2678 'context' => 'activity',
2679 ];
2680 return CRM_Activity_BAO_Activity::getActivitiesCount($input);
2681
2682 case 'mailing':
2683 $params = ['contact_id' => $contactId];
2684 return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
2685
2686 default:
2687 if (!$tableName) {
2688 $custom = explode('_', $type);
2689 $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom[1], 'table_name');
2690 }
2691 $queryString = "SELECT count(id) FROM $tableName WHERE entity_id = $contactId";
2692 return (int) CRM_Core_DAO::singleValueQuery($queryString);
2693 }
2694 }
2695
2696 /**
2697 * Update contact greetings if an update has resulted in a custom field change.
2698 *
2699 * @param array $updatedFields
2700 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2701 * @param array $contactParams
2702 * Parameters known about the contact. At minimum array('contact_id' => x).
2703 * Fields in this array will take precedence over DB fields (so far only
2704 * in the case of greeting id fields).
2705 */
2706 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2707 $contactID = $contactParams['contact_id'];
2708 CRM_Contact_BAO_Contact::ensureGreetingParamsAreSet($contactParams);
2709 $tokens = CRM_Contact_BAO_Contact_Utils::getTokensRequiredForContactGreetings($contactParams);
2710 if (!empty($tokens['all']['contact'])) {
2711 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2712 if (!empty($affectedTokens)) {
2713 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2714 $contact = new CRM_Contact_BAO_Contact();
2715 $contact->id = $contactID;
2716 $contact->find(TRUE);
2717 CRM_Contact_BAO_Contact::processGreetings($contact);
2718 }
2719 }
2720 }
2721
2722 /**
2723 * Process greetings and cache.
2724 *
2725 * @param \CRM_Contact_DAO_Contact $contact
2726 * Contact object after save.
2727 */
2728 public static function processGreetings(&$contact) {
2729
2730 $emailGreetingString = self::getTemplateForGreeting('email_greeting', $contact);
2731 $postalGreetingString = self::getTemplateForGreeting('postal_greeting', $contact);
2732 $addresseeString = self::getTemplateForGreeting('addressee', $contact);
2733 //@todo this function does a lot of unnecessary loading.
2734 // ensureGreetingParamsAreSet now makes sure that the contact is
2735 // loaded and using updateGreetingsOnTokenFieldChange
2736 // allows us the possibility of only doing an update if required.
2737
2738 // The contact object has not always required the
2739 // fields that are required to calculate greetings
2740 // so we need to retrieve it again.
2741 if ($contact->_query !== FALSE) {
2742 $contact->find(TRUE);
2743 }
2744
2745 // store object values to an array
2746 $contactDetails = [];
2747 CRM_Core_DAO::storeValues($contact, $contactDetails);
2748 $contactDetails = [[$contact->id => $contactDetails]];
2749
2750 $updateQueryString = [];
2751
2752 if ($emailGreetingString) {
2753 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($emailGreetingString,
2754 $contactDetails,
2755 $contact->id,
2756 'CRM_Contact_BAO_Contact'
2757 );
2758 $emailGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($emailGreetingString));
2759 $updateQueryString[] = " email_greeting_display = '$emailGreetingString'";
2760 }
2761
2762 if ($postalGreetingString) {
2763 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($postalGreetingString,
2764 $contactDetails,
2765 $contact->id,
2766 'CRM_Contact_BAO_Contact'
2767 );
2768 $postalGreetingString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($postalGreetingString));
2769 $updateQueryString[] = " postal_greeting_display = '$postalGreetingString'";
2770 }
2771
2772 if ($addresseeString) {
2773 CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($addresseeString,
2774 $contactDetails,
2775 $contact->id,
2776 'CRM_Contact_BAO_Contact'
2777 );
2778 $addresseeString = CRM_Core_DAO::escapeString(CRM_Utils_String::stripSpaces($addresseeString));
2779 $updateQueryString[] = " addressee_display = '$addresseeString'";
2780 }
2781
2782 if (!empty($updateQueryString)) {
2783 $updateQueryString = implode(',', $updateQueryString);
2784 $queryString = "UPDATE civicrm_contact SET $updateQueryString WHERE id = {$contact->id}";
2785 CRM_Core_DAO::executeQuery($queryString);
2786 }
2787 }
2788
2789 /**
2790 * Retrieve loc block ids w/ given condition.
2791 *
2792 * @param int $contactId
2793 * Contact id.
2794 * @param array $criteria
2795 * Key => value pair which should be.
2796 * fulfill by return record ids.
2797 * @param string $condOperator
2798 * Operator use for grouping multiple conditions.
2799 *
2800 * @return array
2801 * loc block ids which fulfill condition.
2802 */
2803 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2804 $locBlockIds = [];
2805 if (!$contactId) {
2806 return $locBlockIds;
2807 }
2808
2809 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2810 $name = strtolower($block);
2811 $className = "CRM_Core_DAO_$block";
2812 $blockDAO = new $className();
2813
2814 // build the condition.
2815 if (is_array($criteria)) {
2816 $fields = $blockDAO->fields();
2817 $conditions = [];
2818 foreach ($criteria as $field => $value) {
2819 if (array_key_exists($field, $fields)) {
2820 $cond = "( $field = $value )";
2821 // value might be zero or null.
2822 if (!$value || strtolower($value) === 'null') {
2823 $cond = "( $field = 0 OR $field IS NULL )";
2824 }
2825 $conditions[] = $cond;
2826 }
2827 }
2828 if (!empty($conditions)) {
2829 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2830 }
2831 }
2832
2833 $blockDAO->contact_id = $contactId;
2834 $blockDAO->find();
2835 while ($blockDAO->fetch()) {
2836 $locBlockIds[$name][] = $blockDAO->id;
2837 }
2838 }
2839
2840 return $locBlockIds;
2841 }
2842
2843 /**
2844 * Build context menu items.
2845 *
2846 * @param int $contactId
2847 *
2848 * @return array
2849 * Array of context menu for logged in user.
2850 */
2851 public static function contextMenu($contactId = NULL) {
2852 $menu = [
2853 'view' => [
2854 'title' => ts('View Contact'),
2855 'weight' => 0,
2856 'ref' => 'view-contact',
2857 'class' => 'no-popup',
2858 'key' => 'view',
2859 'permissions' => ['view all contacts'],
2860 ],
2861 'add' => [
2862 'title' => ts('Edit Contact'),
2863 'weight' => 0,
2864 'ref' => 'edit-contact',
2865 'class' => 'no-popup',
2866 'key' => 'add',
2867 'permissions' => ['edit all contacts'],
2868 ],
2869 'delete' => [
2870 'title' => ts('Delete Contact'),
2871 'weight' => 0,
2872 'ref' => 'delete-contact',
2873 'key' => 'delete',
2874 'permissions' => ['access deleted contacts', 'delete contacts'],
2875 ],
2876 'contribution' => [
2877 'title' => ts('Add Contribution'),
2878 'weight' => 5,
2879 'ref' => 'new-contribution',
2880 'key' => 'contribution',
2881 'tab' => 'contribute',
2882 'component' => 'CiviContribute',
2883 'href' => CRM_Utils_System::url('civicrm/contact/view/contribution',
2884 'reset=1&action=add&context=contribution'
2885 ),
2886 'permissions' => [
2887 'access CiviContribute',
2888 'edit contributions',
2889 ],
2890 ],
2891 'participant' => [
2892 'title' => ts('Register for Event'),
2893 'weight' => 10,
2894 'ref' => 'new-participant',
2895 'key' => 'participant',
2896 'tab' => 'participant',
2897 'component' => 'CiviEvent',
2898 'href' => CRM_Utils_System::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2899 'permissions' => [
2900 'access CiviEvent',
2901 'edit event participants',
2902 ],
2903 ],
2904 'activity' => [
2905 'title' => ts('Record Activity'),
2906 'weight' => 35,
2907 'ref' => 'new-activity',
2908 'key' => 'activity',
2909 'permissions' => ['edit all contacts'],
2910 ],
2911 'pledge' => [
2912 'title' => ts('Add Pledge'),
2913 'weight' => 15,
2914 'ref' => 'new-pledge',
2915 'key' => 'pledge',
2916 'tab' => 'pledge',
2917 'href' => CRM_Utils_System::url('civicrm/contact/view/pledge',
2918 'reset=1&action=add&context=pledge'
2919 ),
2920 'component' => 'CiviPledge',
2921 'permissions' => [
2922 'access CiviPledge',
2923 'edit pledges',
2924 ],
2925 ],
2926 'membership' => [
2927 'title' => ts('Add Membership'),
2928 'weight' => 20,
2929 'ref' => 'new-membership',
2930 'key' => 'membership',
2931 'tab' => 'member',
2932 'component' => 'CiviMember',
2933 'href' => CRM_Utils_System::url('civicrm/contact/view/membership',
2934 'reset=1&action=add&context=membership'
2935 ),
2936 'permissions' => [
2937 'access CiviMember',
2938 'edit memberships',
2939 ],
2940 ],
2941 'case' => [
2942 'title' => ts('Add Case'),
2943 'weight' => 25,
2944 'ref' => 'new-case',
2945 'key' => 'case',
2946 'tab' => 'case',
2947 'component' => 'CiviCase',
2948 'href' => CRM_Utils_System::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2949 'permissions' => ['add cases'],
2950 ],
2951 'rel' => [
2952 'title' => ts('Add Relationship'),
2953 'weight' => 30,
2954 'ref' => 'new-relationship',
2955 'key' => 'rel',
2956 'tab' => 'rel',
2957 'href' => CRM_Utils_System::url('civicrm/contact/view/rel',
2958 'reset=1&action=add'
2959 ),
2960 'permissions' => ['edit all contacts'],
2961 ],
2962 'note' => [
2963 'title' => ts('Add Note'),
2964 'weight' => 40,
2965 'ref' => 'new-note',
2966 'key' => 'note',
2967 'tab' => 'note',
2968 'class' => 'medium-popup',
2969 'href' => CRM_Utils_System::url('civicrm/contact/view/note',
2970 'reset=1&action=add'
2971 ),
2972 'permissions' => ['edit all contacts'],
2973 ],
2974 'email' => [
2975 'title' => ts('Send an Email'),
2976 'weight' => 45,
2977 'ref' => 'new-email',
2978 'key' => 'email',
2979 'permissions' => ['view all contacts'],
2980 ],
2981 'group' => [
2982 'title' => ts('Add to Group'),
2983 'weight' => 50,
2984 'ref' => 'group-add-contact',
2985 'key' => 'group',
2986 'tab' => 'group',
2987 'permissions' => ['edit groups'],
2988 ],
2989 'tag' => [
2990 'title' => ts('Tag Contact'),
2991 'weight' => 55,
2992 'ref' => 'tag-contact',
2993 'key' => 'tag',
2994 'tab' => 'tag',
2995 'permissions' => ['edit all contacts'],
2996 ],
2997 ];
2998
2999 $menu['otherActions'] = [
3000 'print' => [
3001 'title' => ts('Print Summary'),
3002 'description' => ts('Printer-friendly view of this page.'),
3003 'weight' => 5,
3004 'ref' => 'crm-contact-print',
3005 'key' => 'print',
3006 'tab' => 'print',
3007 'href' => CRM_Utils_System::url('civicrm/contact/view/print',
3008 "reset=1&print=1"
3009 ),
3010 'class' => 'print',
3011 'icon' => 'crm-i fa-print',
3012 ],
3013 'vcard' => [
3014 'title' => ts('vCard'),
3015 'description' => ts('vCard record for this contact.'),
3016 'weight' => 10,
3017 'ref' => 'crm-contact-vcard',
3018 'key' => 'vcard',
3019 'tab' => 'vcard',
3020 'href' => CRM_Utils_System::url('civicrm/contact/view/vcard',
3021 "reset=1"
3022 ),
3023 'class' => 'vcard',
3024 'icon' => 'crm-i fa-list-alt',
3025 ],
3026 ];
3027
3028 if (CRM_Core_Permission::check('access Contact Dashboard')) {
3029 $menu['otherActions']['dashboard'] = [
3030 'title' => ts('Contact Dashboard'),
3031 'description' => ts('Contact Dashboard'),
3032 'weight' => 15,
3033 'ref' => 'crm-contact-dashboard',
3034 'key' => 'dashboard',
3035 'tab' => 'dashboard',
3036 'class' => 'dashboard',
3037 // NOTE: As an alternative you can also build url on CMS specific way
3038 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3039 'href' => CRM_Utils_System::url('civicrm/user', "reset=1&id=$contactId"),
3040 'icon' => 'crm-i fa-tachometer',
3041 ];
3042 }
3043
3044 $uid = CRM_Core_BAO_UFMatch::getUFId($contactId);
3045 if ($uid) {
3046 $menu['otherActions']['user-record'] = [
3047 'title' => ts('User Record'),
3048 'description' => ts('User Record'),
3049 'weight' => 20,
3050 'ref' => 'crm-contact-user-record',
3051 'key' => 'user-record',
3052 'tab' => 'user-record',
3053 'class' => 'user-record',
3054 'href' => CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId),
3055 'icon' => 'crm-i fa-user',
3056 ];
3057 }
3058 elseif (CRM_Core_Config::singleton()->userSystem->checkPermissionAddUser()) {
3059 $menu['otherActions']['user-add'] = [
3060 'title' => ts('Create User Record'),
3061 'description' => ts('Create User Record'),
3062 'weight' => 25,
3063 'ref' => 'crm-contact-user-add',
3064 'key' => 'user-add',
3065 'tab' => 'user-add',
3066 'class' => 'user-add',
3067 'href' => CRM_Utils_System::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3068 'icon' => 'crm-i fa-user-plus',
3069 ];
3070 }
3071
3072 CRM_Utils_Hook::summaryActions($menu, $contactId);
3073 //1. check for component is active.
3074 //2. check for user permissions.
3075 //3. check for acls.
3076 //3. edit and view contact are directly accessible to user.
3077
3078 $aclPermissionedTasks = [
3079 'view-contact',
3080 'edit-contact',
3081 'new-activity',
3082 'new-email',
3083 'group-add-contact',
3084 'tag-contact',
3085 'delete-contact',
3086 ];
3087 $corePermission = CRM_Core_Permission::getPermission();
3088
3089 $contextMenu = [];
3090 foreach ($menu as $key => $values) {
3091 if ($key !== 'otherActions') {
3092
3093 // user does not have necessary permissions.
3094 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3095 continue;
3096 }
3097 // build directly accessible action menu.
3098 if (in_array($values['ref'], [
3099 'view-contact',
3100 'edit-contact',
3101 ])) {
3102 $contextMenu['primaryActions'][$key] = [
3103 'title' => $values['title'],
3104 'ref' => $values['ref'],
3105 'class' => $values['class'] ?? NULL,
3106 'key' => $values['key'],
3107 ];
3108 continue;
3109 }
3110
3111 // finally get menu item for -more- action widget.
3112 while (!empty($contextMenu['moreActions'][$values['weight']])) {
3113 // Quick & dirty way of handling 2 items with the same weight
3114 // without clobbering one.
3115 $values['weight']++;
3116 }
3117 $contextMenu['moreActions'][$values['weight']] = [
3118 'title' => $values['title'],
3119 'ref' => $values['ref'],
3120 'href' => $values['href'] ?? NULL,
3121 'tab' => $values['tab'] ?? NULL,
3122 'class' => $values['class'] ?? NULL,
3123 'key' => $values['key'],
3124 ];
3125 }
3126 else {
3127 foreach ($values as $value) {
3128 // user does not have necessary permissions.
3129 if (!self::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3130 continue;
3131 }
3132
3133 // finally get menu item for -more- action widget.
3134 while (!empty($contextMenu['otherActions'][$value['weight']])) {
3135 // Quick & dirty way of handling 2 items with the same weight
3136 // without clobbering one.
3137 $value['weight']++;
3138 }
3139 $contextMenu['otherActions'][$value['weight']] = [
3140 'title' => $value['title'],
3141 'ref' => $value['ref'],
3142 'href' => $value['href'] ?? NULL,
3143 'tab' => $value['tab'] ?? NULL,
3144 'class' => $value['class'] ?? NULL,
3145 'icon' => $value['icon'] ?? NULL,
3146 'key' => $value['key'],
3147 ];
3148 }
3149 }
3150 }
3151
3152 ksort($contextMenu['moreActions']);
3153 ksort($contextMenu['otherActions']);
3154
3155 return $contextMenu;
3156 }
3157
3158 /**
3159 * Check if user has permissions to access items in action menu.
3160 *
3161 * @param array $aclPermissionedTasks
3162 * Array containing ACL related tasks.
3163 * @param string $corePermission
3164 * The permission of the user (edit or view or null).
3165 * @param array $menuOptions
3166 * Array containing params of the menu (title, href, etc).
3167 *
3168 * @return bool
3169 * TRUE if user has all permissions, FALSE if otherwise.
3170 */
3171 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3172 $componentName = $menuOptions['component'] ?? NULL;
3173
3174 // if component action - make sure component is enable.
3175 if ($componentName && !CRM_Core_Component::isEnabled($componentName)) {
3176 return FALSE;
3177 }
3178
3179 // make sure user has all required permissions.
3180 $hasAllPermissions = FALSE;
3181
3182 $permissions = $menuOptions['permissions'] ?? NULL;
3183 if (!is_array($permissions) || empty($permissions)) {
3184 $hasAllPermissions = TRUE;
3185 }
3186
3187 // iterate for required permissions in given permissions array.
3188 if (!$hasAllPermissions) {
3189 $hasPermissions = 0;
3190 foreach ($permissions as $permission) {
3191 if (CRM_Core_Permission::check($permission)) {
3192 $hasPermissions++;
3193 }
3194 }
3195
3196 if (count($permissions) == $hasPermissions) {
3197 $hasAllPermissions = TRUE;
3198 }
3199
3200 // if still user does not have required permissions, check acl.
3201 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3202 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3203 $corePermission == CRM_Core_Permission::EDIT
3204 ) {
3205 $hasAllPermissions = TRUE;
3206 }
3207 elseif (in_array($menuOptions['ref'], [
3208 'new-email',
3209 ])) {
3210 // grant permissions for these tasks.
3211 $hasAllPermissions = TRUE;
3212 }
3213 }
3214 }
3215
3216 return $hasAllPermissions;
3217 }
3218
3219 /**
3220 * Retrieve display name of contact that address is shared.
3221 *
3222 * This is based on $masterAddressId or $contactId .
3223 *
3224 * @param int $masterAddressId
3225 * Master id.
3226 * @param int $contactId
3227 * Contact id. (deprecated - do not use)
3228 *
3229 * @return string|null
3230 * the found display name or null.
3231 */
3232 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3233 $masterDisplayName = NULL;
3234 if (!$masterAddressId) {
3235 return $masterDisplayName;
3236 }
3237
3238 $sql = "
3239 SELECT display_name from civicrm_contact
3240 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3241 WHERE civicrm_address.id = " . $masterAddressId;
3242
3243 $masterDisplayName = CRM_Core_DAO::singleValueQuery($sql);
3244 return $masterDisplayName;
3245 }
3246
3247 /**
3248 * Get the creation/modification times for a contact.
3249 *
3250 * @param int $contactId
3251 *
3252 * @return array
3253 * Dates - ('created_date' => $, 'modified_date' => $)
3254 */
3255 public static function getTimestamps($contactId) {
3256 $timestamps = CRM_Core_DAO::executeQuery(
3257 'SELECT created_date, modified_date
3258 FROM civicrm_contact
3259 WHERE id = %1',
3260 [
3261 1 => [$contactId, 'Integer'],
3262 ]
3263 );
3264 if ($timestamps->fetch()) {
3265 return [
3266 'created_date' => $timestamps->created_date,
3267 'modified_date' => $timestamps->modified_date,
3268 ];
3269 }
3270 else {
3271 return NULL;
3272 }
3273 }
3274
3275 /**
3276 * Get a list of triggers for the contact table.
3277 *
3278 * @param array $info
3279 * @param string|null $tableName
3280 *
3281 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3282 *
3283 * @see hook_civicrm_triggerInfo
3284 * @see CRM_Core_DAO::triggerRebuild
3285 */
3286 public static function triggerInfo(&$info, $tableName = NULL) {
3287
3288 // Modifications to these records should update the contact timestamps.
3289 \Civi\Core\SqlTrigger\TimestampTriggers::create('civicrm_contact', 'Contact')
3290 ->setRelations([
3291 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3292 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3293 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3294 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3295 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3296 ])
3297 ->alterTriggerInfo($info, $tableName);
3298
3299 // Update phone table to populate phone_numeric field
3300 if (!$tableName || $tableName == 'civicrm_phone') {
3301 // Define stored sql function needed for phones
3302 $sqlTriggers = Civi::service('sql_triggers');
3303 $sqlTriggers->enqueueQuery(self::DROP_STRIP_FUNCTION_43);
3304 $sqlTriggers->enqueueQuery(self::CREATE_STRIP_FUNCTION_43);
3305 $info[] = [
3306 'table' => ['civicrm_phone'],
3307 'when' => 'BEFORE',
3308 'event' => ['INSERT', 'UPDATE'],
3309 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3310 ];
3311 }
3312 }
3313
3314 /**
3315 * Check if contact is being used in civicrm_domain based on $contactId.
3316 *
3317 * @param int $contactId
3318 * Contact id.
3319 *
3320 * @return bool
3321 * true if present else false.
3322 */
3323 public static function checkDomainContact($contactId) {
3324 if (!$contactId) {
3325 return FALSE;
3326 }
3327 $domainId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3328
3329 if ($domainId) {
3330 return TRUE;
3331 }
3332 else {
3333 return FALSE;
3334 }
3335 }
3336
3337 /**
3338 * Get options for a given contact field.
3339 *
3340 * @param string $fieldName
3341 * @param string $context
3342 * @param array $props
3343 * whatever is known about this dao object.
3344 *
3345 * @return array|bool
3346 * @see CRM_Core_DAO::buildOptions
3347 *
3348 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3349 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3350 *
3351 * @see CRM_Core_DAO::buildOptionsContext
3352 */
3353 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3354 $params = [];
3355 // Special logic for fields whose options depend on context or properties
3356 switch ($fieldName) {
3357 case 'contact_sub_type':
3358 if (!empty($props['contact_type'])) {
3359 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3360 }
3361 break;
3362
3363 case 'contact_type':
3364 if ($context == 'search') {
3365 // CRM-15495 - EntityRef filters and basic search forms expect this format
3366 // FIXME: Search builder does not
3367 return CRM_Contact_BAO_ContactType::getSelectElements();
3368 }
3369 break;
3370
3371 // The contact api supports some related entities so we'll honor that by fetching their options
3372 case 'group_id':
3373 case 'group':
3374 return CRM_Contact_BAO_GroupContact::buildOptions('group_id', $context, $props);
3375
3376 case 'tag_id':
3377 case 'tag':
3378 $props['entity_table'] = 'civicrm_contact';
3379 return CRM_Core_BAO_EntityTag::buildOptions('tag_id', $context, $props);
3380
3381 case 'state_province_id':
3382 case 'state_province':
3383 case 'state_province_name':
3384 case 'country_id':
3385 case 'country':
3386 case 'county_id':
3387 case 'worldregion':
3388 case 'worldregion_id':
3389 return CRM_Core_BAO_Address::buildOptions($fieldName, 'get', $props);
3390
3391 }
3392 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
3393 }
3394
3395 /**
3396 * Event fired after modifying any entity.
3397 * @param \Civi\Core\Event\PostEvent $event
3398 */
3399 public static function on_hook_civicrm_post(\Civi\Core\Event\PostEvent $event) {
3400 // Handle deleting a related entity with is_primary
3401 $hasPrimary = ['Address', 'Email', 'IM', 'OpenID', 'Phone'];
3402 if (
3403 $event->action === 'delete' && $event->id &&
3404 in_array($event->entity, $hasPrimary) &&
3405 !empty($event->object->is_primary) &&
3406 !empty($event->object->contact_id)
3407 ) {
3408 $daoClass = CRM_Core_DAO_AllCoreTables::getFullName($event->entity);
3409 $dao = new $daoClass();
3410 $dao->contact_id = $event->object->contact_id;
3411 $dao->is_primary = 1;
3412 // Pick another record to be primary (if one isn't already)
3413 if (!$dao->find(TRUE)) {
3414 $dao->is_primary = 0;
3415 if ($dao->find(TRUE)) {
3416 $baoClass = CRM_Core_DAO_AllCoreTables::getBAOClassName($daoClass);
3417 $baoClass::writeRecord(['id' => $dao->id, 'is_primary' => 1]);
3418 }
3419 }
3420 }
3421 }
3422
3423 /**
3424 * Get the template string for the given greeting.
3425 *
3426 * @param string $greetingType
3427 * @param CRM_Contact_DAO_Contact $contact
3428 *
3429 * @return string
3430 */
3431 private static function getTemplateForGreeting(string $greetingType, CRM_Contact_DAO_Contact $contact): string {
3432 $customFieldName = $greetingType . '_custom';
3433 if (!CRM_Utils_System::isNull($contact->$customFieldName)) {
3434 return $contact->$customFieldName;
3435 }
3436 $idField = $greetingType . '_id';
3437 if (!is_numeric($contact->$idField)) {
3438 return '';
3439 }
3440 $filter = [
3441 'contact_type' => $contact->contact_type,
3442 'greeting_type' => $greetingType,
3443 ];
3444 return CRM_Core_PseudoConstant::greeting($filter)[$contact->$idField] ?? '';
3445 }
3446
3447 /**
3448 * @inheritDoc
3449 */
3450 public function addSelectWhereClause() {
3451 // We always return an array with these keys, even if they are empty,
3452 // because this tells the query builder that we have considered these fields for acls
3453 $clauses = [
3454 'id' => (array) CRM_Contact_BAO_Contact_Permission::cacheSubquery(),
3455 'is_deleted' => CRM_Core_Permission::check('access deleted contacts') ? [] : ['!= 1'],
3456 ];
3457 CRM_Utils_Hook::selectWhereClause($this, $clauses);
3458 return $clauses;
3459 }
3460
3461 /**
3462 * Get any existing duplicate contacts based on the input parameters.
3463 *
3464 * @param array $input
3465 * Input parameters to be matched.
3466 * @param string $contactType
3467 * @param string $rule
3468 * - Supervised
3469 * - Unsupervised
3470 * @param $excludedContactIDs
3471 * An array of ids not to be included in the results.
3472 * @param bool $checkPermissions
3473 * @param int $ruleGroupID
3474 * ID of the rule group to be used if an override is desirable.
3475 * @param array $contextParams
3476 * The context if relevant, eg. ['event_id' => X]
3477 *
3478 * @return array
3479 * @throws \CRM_Core_Exception
3480 */
3481 public static function getDuplicateContacts(array $input, string $contactType, string $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []): array {
3482 $dedupeParams = CRM_Dedupe_Finder::formatParams($input, $contactType);
3483 $dedupeParams['check_permission'] = $checkPermissions;
3484 $dedupeParams['contact_type'] = $contactType;
3485 $dedupeParams['rule'] = $rule;
3486 $dedupeParams['rule_group_id'] = $ruleGroupID;
3487 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3488 $dedupeResults['ids'] = [];
3489 $dedupeResults['handled'] = FALSE;
3490 CRM_Utils_Hook::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3491 if (!$dedupeResults['handled']) {
3492 $dedupeResults['ids'] = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3493 }
3494 return $dedupeResults['ids'] ?? [];
3495 }
3496
3497 /**
3498 * Get the first duplicate contacts based on the input parameters.
3499 *
3500 * @param array $input
3501 * Input parameters to be matched.
3502 * @param string $contactType
3503 * @param string $rule
3504 * - Supervised
3505 * - Unsupervised
3506 * @param $excludedContactIDs
3507 * An array of ids not to be included in the results.
3508 * @param bool $checkPermissions
3509 * @param int $ruleGroupID
3510 * ID of the rule group to be used if an override is desirable.
3511 * @param array $contextParams
3512 * The context if relevant, eg. ['event_id' => X]
3513 *
3514 * @return int|null
3515 */
3516 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3517 $ids = self::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3518 if (empty($ids)) {
3519 return NULL;
3520 }
3521 return $ids[0];
3522 }
3523
3524 /**
3525 * Check if a field is associated with an entity that has a location type.
3526 *
3527 * (ie. is an address, phone, email etc field).
3528 *
3529 * @param string $fieldTitle
3530 * Title of the field (not the name - create a new function for that if required).
3531 *
3532 * @return bool
3533 */
3534 public static function isFieldHasLocationType($fieldTitle) {
3535 foreach (CRM_Contact_BAO_Contact::importableFields() as $key => $field) {
3536 if ($field['title'] === $fieldTitle) {
3537 return $field['hasLocationType'] ?? NULL;
3538 }
3539 }
3540 return FALSE;
3541 }
3542
3543 /**
3544 * @param array $appendProfiles
3545 * Name of profile(s) to append to each link.
3546 *
3547 * @return array|false
3548 */
3549 public static function getEntityRefCreateLinks($appendProfiles = []) {
3550 // You'd think that "create contacts" would be the permission to check,
3551 // But new contact popups are profile forms and those use their own permissions.
3552 if (!CRM_Core_Permission::check([['profile create', 'profile listings and forms']])) {
3553 return FALSE;
3554 }
3555 $profiles = [];
3556 foreach (CRM_Contact_BAO_ContactType::basicTypes() as $contactType) {
3557 $profiles[] = 'new_' . strtolower($contactType);
3558 }
3559 $retrieved = civicrm_api3('uf_group', 'get', [
3560 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3561 'is_active' => 1,
3562 ]);
3563 $links = $append = [];
3564 if (!empty($retrieved['values'])) {
3565 $icons = [
3566 'individual' => 'fa-user',
3567 'organization' => 'fa-building',
3568 'household' => 'fa-home',
3569 ];
3570 foreach ($retrieved['values'] as $id => $profile) {
3571 if (in_array($profile['name'], $profiles)) {
3572 $links[] = [
3573 'label' => $profile['title'],
3574 'url' => CRM_Utils_System::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3575 NULL, NULL, FALSE, FALSE, TRUE),
3576 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3577 'icon' => $icons[str_replace('new_', '', $profile['name'])] ?? NULL,
3578 ];
3579 }
3580 else {
3581 $append[] = $id;
3582 }
3583 }
3584 foreach ($append as $id) {
3585 foreach ($links as &$link) {
3586 $link['url'] .= ",$id";
3587 }
3588 }
3589 }
3590 return $links;
3591 }
3592
3593 /**
3594 * @return array
3595 */
3596 public static function getEntityRefFilters() {
3597 return [
3598 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3599 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3600 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3601 ['key' => 'city', 'value' => ts('City'), 'type' => 'text', 'entity' => 'Address'],
3602 ['key' => 'postal_code', 'value' => ts('Postal Code'), 'type' => 'text', 'entity' => 'Address'],
3603 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3604 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3605 ['key' => 'first_name', 'value' => ts('First Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3606 ['key' => 'last_name', 'value' => ts('Last Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3607 ['key' => 'nick_name', 'value' => ts('Nick Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3608 ['key' => 'organization_name', 'value' => ts('Employer name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3609 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3610 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3611 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3612 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],
3613 ];
3614 }
3615
3616 /**
3617 * @param string $entityName
3618 * @param string $action
3619 * @param array $record
3620 * @param $userID
3621 * @return bool
3622 * @see CRM_Core_DAO::checkAccess
3623 */
3624 public static function _checkAccess(string $entityName, string $action, array $record, $userID): bool {
3625 switch ($action) {
3626 case 'create':
3627 return CRM_Core_Permission::check('add contacts', $userID);
3628
3629 case 'get':
3630 $actionType = CRM_Core_Permission::VIEW;
3631 break;
3632
3633 case 'delete':
3634 $actionType = CRM_Core_Permission::DELETE;
3635 break;
3636
3637 default:
3638 $actionType = CRM_Core_Permission::EDIT;
3639 break;
3640 }
3641
3642 return CRM_Contact_BAO_Contact_Permission::allow($record['id'], $actionType, $userID);
3643 }
3644
3645 /**
3646 * Get icon for a particular contact.
3647 *
3648 * Example: `CRM_Contact_BAO_Contact::getIcon('Contact', 123)`
3649 *
3650 * @param string $entityName
3651 * Always "Contact".
3652 * @param int $entityId
3653 * Id of the contact.
3654 * @throws CRM_Core_Exception
3655 */
3656 public static function getEntityIcon(string $entityName, int $entityId) {
3657 $contactTypes = CRM_Contact_BAO_ContactType::getAllContactTypes();
3658 $subTypes = CRM_Utils_Array::explodePadded(CRM_Core_DAO::getFieldValue(parent::class, $entityId, 'contact_sub_type'));
3659 foreach ((array) $subTypes as $subType) {
3660 if (!empty($contactTypes[$subType]['icon'])) {
3661 return $contactTypes[$subType]['icon'];
3662 }
3663 }
3664 // If no sub-type icon, lookup contact type
3665 $contactType = CRM_Core_DAO::getFieldValue(parent::class, $entityId, 'contact_type');
3666 return $contactTypes[$contactType]['icon'] ?? self::$_icon;
3667 }
3668
3669 }