3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
implements Civi\Core\HookInterface
{
20 * SQL function used to format the phone_numeric field via trigger.
22 * @see self::triggerInfo()
24 * Note that this is also used by the 4.3 upgrade script.
25 * @see CRM_Upgrade_Incremental_php_FourThree
27 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
29 const CREATE_STRIP_FUNCTION_43
= "
30 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255))
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));
41 SET iterator = iterator + 1;
47 * The types of communication preferences.
51 public static $_commPrefs = [
64 public static $_greetingTypes = [
71 * Static field for all the contact information that we can potentially import.
75 public static $_importableFields = [];
78 * Static field for all the contact information that we can potentially export.
82 public static $_exportableFields = NULL;
85 * Takes an associative array and creates a contact object.
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
91 * @param array $params
92 * (reference) an assoc array of name/value pairs.
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
99 public static function add(&$params) {
100 $contact = new CRM_Contact_DAO_Contact();
101 $contactID = $params['contact_id'] ??
NULL;
102 if (empty($params)) {
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';
111 elseif ($params['contact_sub_type'] !== 'null') {
112 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
113 $params['contact_type'], TRUE
116 // we'll need to fix tests to handle this
118 throw new CRM_Core_Exception(ts('The Contact Sub Type does not match the Contact type for this record'));
120 $params['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
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']);
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'];
138 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
139 $defaults['display_name'] = $params['household_name'];
140 $defaults['sort_name'] = $params['household_name'];
142 $params = array_merge($defaults, $params);
144 if (!empty($params['deceased_date']) && $params['deceased_date'] !== 'null') {
145 $params['is_deceased'] = TRUE;
147 $allNull = $contact->copyValues($params);
149 $contact->id
= $contactID;
151 if ($contact->contact_type
=== 'Individual') {
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);
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
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');
169 if (mb_strlen($contact->sort_name
, 'UTF-8') > 128) {
170 $contact->sort_name
= mb_substr($contact->sort_name
, 0, 128, 'UTF-8');
173 $privacy = $params['privacy'] ??
NULL;
174 if ($privacy && is_array($privacy)) {
176 foreach (self
::$_commPrefs as $name) {
177 $contact->$name = $privacy[$name] ??
FALSE;
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
) {
186 $contact->hash
= md5(uniqid(rand(), TRUE));
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');
197 CRM_Core_BAO_Log
::register($contact->id
,
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;
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);
211 elseif ($employerId) {
212 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
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
);
227 * takes an associative array and creates a contact object and all the associated
228 * derived objects (i.e. individual, location, email, phone etc)
230 * This function is invoked from within the web form layer and also from the api layer
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.
239 * @param bool $skipDelete
240 * Unclear parameter, passed to website create
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
246 * @throws \CRM_Core_Exception
247 * @throws \CiviCRM_API3_Exception
248 * @throws \Civi\API\Exception\UnauthorizedException
250 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
252 if (empty($params['contact_type']) && empty($params['contact_id'])) {
256 $isEdit = !empty($params['contact_id']);
258 if ($isEdit && empty($params['contact_type'])) {
259 $params['contact_type'] = self
::getContactType($params['contact_id']);
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())
266 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify api key');
270 if (!empty($params['contact_id'])) {
271 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
274 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
278 self
::ensureGreetingParamsAreSet($params);
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;
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);
294 $transaction = new CRM_Core_Transaction();
296 $contact = self
::add($params);
298 $params['contact_id'] = $contact->id
;
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;
308 $params['group'] = [$domainGroupID => 1];
313 if (!empty($params['group'])) {
314 $contactIds = [$params['contact_id']];
315 foreach ($params['group'] as $groupId => $flag) {
317 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
319 elseif ($flag == -1) {
320 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
325 // Add location Block data.
326 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
327 foreach ($blocks as $name => $value) {
328 $contact->$name = $value;
330 if (!empty($params['updateBlankLocInfo'])) {
334 if (isset($params['website'])) {
335 CRM_Core_BAO_Website
::process($params['website'], $contact->id
, $skipDelete);
338 $userID = CRM_Core_Session
::singleton()->get('userID');
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'];
347 //if logged in user, overwrite contactId
349 $contactId = $userID;
353 'entity_id' => $contact->id
,
354 'entity_table' => 'civicrm_contact',
355 'note' => $note['note'],
356 'subject' => $note['subject'] ??
NULL,
357 'contact_id' => $contactId,
359 CRM_Core_BAO_Note
::add($noteParams);
363 $contactId = $contact->id
;
364 //if logged in user, overwrite contactId
366 $contactId = $userID;
370 'entity_id' => $contact->id
,
371 'entity_table' => 'civicrm_contact',
372 'note' => $params['note'],
373 'subject' => $params['subject'] ??
NULL,
374 'contact_id' => $contactId,
376 CRM_Core_BAO_Note
::add($noteParams);
380 if (!empty($params['custom']) &&
381 is_array($params['custom'])
383 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
, $isEdit ?
'edit' : 'create');
386 $transaction->commit();
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
,
396 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
400 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
403 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
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);
414 if (!empty($params['check_permissions'])) {
415 $contacts = [&$contact];
416 self
::unsetProtectedFields($contacts);
419 if (!empty($params['is_deceased'])) {
420 // Edit Membership Status
422 'contact_id' => $contact->id
,
423 'is_deceased' => $params['is_deceased'],
424 'deceased_date' => $params['deceased_date'] ??
NULL,
426 CRM_Member_BAO_Membership
::updateMembershipStatus($deceasedParams, $params['contact_type']);
433 * Check if a contact has a name.
435 * - Individuals need a first_name or last_name
436 * - Organizations need organization_name
437 * - Households need household_name
439 * @param array $contact
442 public static function hasName(array $contact): bool {
444 'Individual' => ['first_name', 'last_name'],
445 'Organization' => ['organization_name'],
446 'Household' => ['household_name'],
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');
454 if (!$contactType ||
!isset($nameFields[$contactType])) {
455 throw new CRM_Core_Exception('No contact_type given to ' . __CLASS__
. '::' . __FUNCTION__
);
457 foreach ($nameFields[$contactType] as $field) {
458 if (isset($contact[$field]) && is_string($contact[$field]) && $contact[$field] !== '') {
462 // For existing contacts, look up name from database
464 foreach ($nameFields[$contactType] as $field) {
465 $value = $contact[$field] ?? CRM_Core_DAO
::getFieldValue(__CLASS__
, $cid, $field);
466 if (isset($value) && $value !== '') {
475 * Format the output of the create contact function
477 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
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
);
490 unset($contact['api_key']);
498 * Ensure greeting parameters are set.
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.)
503 * @param array $params
505 * @throws \CiviCRM_API3_Exception
507 public static function ensureGreetingParamsAreSet(&$params) {
508 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
509 $missingGreetingParams = [];
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');
515 // An empty string means NULL
516 if (($params[$greetingParam] ??
NULL) === '') {
517 $params[$greetingParam] = 'null';
519 if (empty($params[$greetingParam])) {
520 $missingGreetingParams[$greetingIndex] = $greetingParam;
524 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
525 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
526 'id' => $params['contact_id'],
527 'return' => array_keys($missingGreetingParams),
530 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
531 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
532 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
535 // Filter out other fields.
536 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
537 $params = array_merge($params, $savedGreetings);
540 foreach ($missingGreetingParams as $greetingName => $greeting) {
541 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
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';
550 if ((int) $params[$greetingParam] != CRM_Core_PseudoConstant
::getKey('CRM_Contact_BAO_Contact', $greetingParam, 'Customized')) {
551 $params[$greetingIndex . '_custom'] = 'null';
558 * Get the display name and image of a contact.
563 * @param bool $includeTypeInReturnParameters
564 * Should type be part of the returned array?
567 * the displayName and contactImage for this contact
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
572 SELECT civicrm_contact.*,
573 civicrm_email.email as email
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();
581 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
582 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
584 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
585 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
588 // use email if display_name is empty
589 if (empty($dao->display_name
)) {
590 $displayName = $dao->email
;
593 $displayName = $dao->display_name
;
596 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
598 return $includeTypeInReturnParameters ?
[
602 $dao->contact_sub_type
,
604 ] : [$displayName, $image, $imageUrl];
610 * Add billing fields to the params if appropriate.
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.
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.
619 * @param array $params
621 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
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])) {
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];
635 $params['preserveDBName'] = TRUE;
641 * Resolve a state province string (UT or Utah) to an ID.
643 * If country has been passed in we should select a state belonging to that country.
645 * Alternatively we should choose from enabled countries, prioritising the default country.
647 * @param array $values
648 * @param int|null $countryID
652 * @throws \CRM_Core_Exception
654 protected static function resolveStateProvinceID($values, $countryID) {
657 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
658 if (CRM_Utils_Array
::lookupValue($values,
663 return $values['state_province_id'];
665 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
666 if (CRM_Utils_Array
::lookupValue($values,
671 return $values['state_province_id'];
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,
685 return $values['state_province_id'];
688 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
689 if (CRM_Utils_Array
::lookupValue($values,
694 return $values['state_province_id'];
697 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
698 if (CRM_Utils_Array
::lookupValue($values,
703 return $values['state_province_id'];
705 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
706 if (CRM_Utils_Array
::lookupValue($values,
711 return $values['state_province_id'];
719 * Get the relevant location entity for the array key.
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).
725 * @param string $fieldName
729 protected static function getLocationEntityForKey($fieldName) {
730 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
733 if ($fieldName === 'phone_ext') {
740 * Soft delete a contact.
742 * Call this via the api, not directly.
744 * @param \CRM_Contact_BAO_Contact $contact
747 * @throws \CRM_Core_Exception
749 protected static function contactTrash($contact): bool {
751 'id' => $contact->id
,
754 CRM_Utils_Hook
::pre('edit', $contact->contact_type
, $contact->id
, $updateParams);
756 $params = [1 => [$contact->id
, 'Integer']];
757 $query = 'DELETE FROM civicrm_uf_match WHERE contact_id = %1';
758 CRM_Core_DAO
::executeQuery($query, $params);
760 $contact->copyValues($updateParams);
762 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
764 CRM_Utils_Hook
::post('edit', $contact->contact_type
, $contact->id
, $contact);
770 * Get the values for pseudoconstants for name->value and reverse.
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..
779 * This is called specifically from the contact import parser & should be moved there
780 * as it is not truly a generic function.
783 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
787 * Fetch object based on array of properties.
789 * @deprecated This is called from a few places but creates rather than solves
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.
800 * @return CRM_Contact_BAO_Contact
802 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
803 if (array_key_exists('contact_id', $params)) {
804 $params['id'] = $params['contact_id'];
806 elseif (array_key_exists('id', $params)) {
807 $params['contact_id'] = $params['id'];
810 $contact = self
::getValues($params, $defaults);
812 unset($params['id']);
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);
821 if (!isset($params['noNotes'])) {
822 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
825 if (!isset($params['noRelationships'])) {
826 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
829 if (!isset($params['noGroups'])) {
830 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
837 * Get the display name of a contact.
842 * @return null|string
843 * display name of the contact if found
845 public static function displayName($id) {
848 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
855 * Delete a contact and all its associated records.
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
866 * Was contact deleted?
868 * @throws \CRM_Core_Exception
869 * @throws \CiviCRM_API3_Exception
871 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
873 if (!$id ||
!is_numeric($id)) {
874 CRM_Core_Error
::deprecatedFunctionWarning('calling delete contact without a valid contact ID is deprecated.');
877 // If trash is disabled in system settings then we always skip
878 if (!Civi
::settings()->get('contact_undelete')) {
879 $skipUndelete = TRUE;
882 // make sure we have edit permission for this contact
884 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
885 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
891 // Restrict contact to be delete if contact has financial trxns
893 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent([$id], $error)) {
897 // make sure this contact_id does not have any membership types
898 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
901 'member_of_contact_id'
903 if ($membershipTypeID) {
907 $contact = new CRM_Contact_DAO_Contact();
909 if (!$contact->find(TRUE)) {
913 $contactType = $contact->contact_type
;
915 // @todo deprecate calling contactDelete with the intention to restore.
917 'id' => $contact->id
,
918 'is_deleted' => FALSE,
920 self
::create($updateParams);
924 // start a new transaction
925 $transaction = new CRM_Core_Transaction();
928 $hookParams = ['check_permissions' => $checkPermissions];
929 CRM_Utils_Hook
::pre('delete', $contactType, $id, $hookParams);
931 //delete billing address if exists.
932 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
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;
940 // delete contact participants CRM-12155
941 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
943 // delete contact contributions CRM-12155
944 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
946 // do activity cleanup, CRM-5604
947 CRM_Activity_BAO_Activity
::cleanupActivity($id);
949 // delete all notes related to contact
950 CRM_Core_BAO_Note
::cleanContactNotes($id);
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);
967 self
::contactTrash($contact);
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);
979 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
982 //delete the contact id from recently view
983 CRM_Utils_Recent
::del(['contact_id' => $id]);
984 self
::updateContactCache($id, empty($restore));
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);
992 $transaction->commit();
995 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1002 * Action to update any caches relating to a recently update contact.
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.
1009 * @param int $contactID
1010 * @param bool $isTrashed
1012 public static function updateContactCache($contactID, $isTrashed = FALSE) {
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']]);
1023 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1028 * Delete the image of a contact.
1031 * Id of the contact.
1034 * Was contact image deleted?
1036 public static function deleteContactImage($id) {
1041 $contact = new self();
1043 $contact->image_URL
= 'null';
1050 * Return proportional height and width of the image.
1052 * @param int $imageWidth
1055 * @param int $imageHeight
1059 * Thumb dimension of image
1061 public static function getThumbSize($imageWidth, $imageHeight) {
1063 if ($imageWidth && $imageHeight) {
1064 $imageRatio = $imageWidth / $imageHeight;
1069 if ($imageRatio > 1) {
1070 $imageThumbWidth = $thumbWidth;
1071 $imageThumbHeight = round($thumbWidth / $imageRatio);
1074 $imageThumbHeight = $thumbWidth;
1075 $imageThumbWidth = round($thumbWidth * $imageRatio);
1078 return [$imageThumbWidth, $imageThumbHeight];
1082 * Validate type of contact image.
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.
1093 * true if valid image extension
1095 public static function processImageParams(
1097 $imageIndex = 'image_URL',
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);
1117 unset($params[$imageIndex]);
1119 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1121 if ($opType == 'status') {
1122 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1124 // FIXME: additional support for fatal, bounce etc could be added.
1130 * Extract contact id from url for deleting contact image.
1132 public static function processImage() {
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);
1151 * Function to set is_delete true or restore deleted contact.
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
1162 * @throws \CRM_Core_Exception
1164 public static function contactTrashRestore($contact, $restore = FALSE) {
1165 CRM_Core_Error
::deprecatedFunctionWarning('Use the api');
1168 CRM_Core_Error
::deprecatedFunctionWarning('Use contact.create to restore - this does nothing much');
1169 // @todo deprecate calling contactDelete with the intention to restore.
1171 'id' => $contact->id
,
1172 'is_deleted' => FALSE,
1174 self
::create($updateParams);
1177 return self
::contactTrash($contact);
1181 * Get contact type for a contact.
1184 * Id of the contact whose contact type is needed.
1187 * contact_type if $id found else null ""
1189 public static function getContactType($id) {
1190 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1194 * Get contact sub type for a contact.
1197 * Id of the contact whose contact sub type is needed.
1199 * @param string $implodeDelimiter
1202 * contact_sub_type if $id found else null ""
1204 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1205 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1207 return $implodeDelimiter ?
NULL : [];
1210 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1212 if ($implodeDelimiter) {
1213 $subtype = implode($implodeDelimiter, $subtype);
1219 * Get pair of contact-type and sub-type for a contact.
1222 * Id of the contact whose contact sub/contact type is needed.
1226 public static function getContactTypes($id) {
1227 $params = ['id' => $id];
1229 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1232 ['contact_type', 'contact_sub_type']
1237 if ($contact->contact_sub_type
) {
1238 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1240 array_unshift($contactTypes, $contact->contact_type
);
1242 return $contactTypes;
1245 throw new CRM_Core_Exception('Cannot proceed without a valid contact');
1250 * Combine all the importable fields from the lower levels object.
1252 * The ordering is important, since currently we do not have a weight
1253 * scheme. Adding weight is super important
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).
1265 * @param bool $withMultiCustomFields
1268 * array of importable Fields
1270 public static function importableFields(
1271 $contactType = 'Individual',
1275 $checkPermission = TRUE,
1276 $withMultiCustomFields = FALSE
1278 if (empty($contactType)) {
1279 $contactType = 'All';
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() . '_';
1289 $fields = self
::$_importableFields[$cacheKeyString] ?? Civi
::cache('fields')->get($cacheKeyString);
1292 $fields = CRM_Contact_DAO_Contact
::import();
1294 // get the fields thar are meant for contact types
1295 if (in_array($contactType, [
1301 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
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()
1311 $locationFields = array_merge($locationFields,
1312 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1320 foreach ($locationFields as $key => $field) {
1321 $locationFields[$key]['hasLocationType'] = TRUE;
1324 $fields = array_merge($fields, $locationFields);
1326 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1327 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1330 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1331 $fields['url']['hasWebsiteType'] = TRUE;
1333 if ($contactType != 'All') {
1334 $fields = array_merge($fields,
1335 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1340 $withMultiCustomFields
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]);
1351 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1352 $fields = array_merge($fields,
1353 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1358 $withMultiCustomFields
1365 $fields = array_merge($fields, [
1367 'title' => ts('Group(s)'),
1371 'title' => ts('Tag(s)'),
1375 'title' => ts('Note'),
1378 'communication_style_id' => [
1379 'title' => ts('Communication Style'),
1380 'name' => 'communication_style_id',
1385 //Sorting fields in alphabetical order(CRM-1507)
1386 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1388 Civi
::cache('fields')->set($cacheKeyString, $fields);
1391 self
::$_importableFields[$cacheKeyString] = $fields;
1395 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1396 self
::$_importableFields[$cacheKeyString]
1400 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1401 self
::$_importableFields[$cacheKeyString]
1409 * Combine all the exportable fields from the lower levels object.
1411 * Currently we are using importable fields as exportable fields
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?.
1421 * @param bool $withMultiRecord
1422 * @param bool $checkPermissions
1425 * array of exportable Fields
1427 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1428 if (empty($contactType)) {
1429 $contactType = 'All';
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();
1442 if (!self
::$_exportableFields ||
empty(self
::$_exportableFields[$cacheKeyString])) {
1443 if (!self
::$_exportableFields) {
1444 self
::$_exportableFields = [];
1447 // check if we can retrieve from database cache
1448 $fields = Civi
::cache('fields')->get($cacheKeyString);
1451 $fields = CRM_Contact_DAO_Contact
::export();
1453 // The fields are meant for contact types.
1454 if (in_array($contactType, [
1460 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1462 // add current employer for individuals
1463 $fields = array_merge($fields, [
1464 'current_employer' =>
1466 'name' => 'organization_name',
1467 'title' => ts('Current Employer'),
1468 'type' => CRM_Utils_Type
::T_STRING
,
1472 // This probably would be added anyway by appendPseudoConstantsToFields.
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
,
1484 'name' => 'im_provider',
1485 'where' => 'civicrm_im.provider_id',
1486 'title' => ts('IM Provider'),
1487 'type' => CRM_Utils_Type
::T_STRING
,
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(),
1498 CRM_Core_DAO_Email
::export(),
1500 CRM_Core_DAO_IM
::export(TRUE),
1501 CRM_Core_DAO_OpenID
::export()
1504 $locationFields = array_merge($locationFields,
1505 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1508 foreach ($locationFields as $key => $field) {
1509 $locationFields[$key]['hasLocationType'] = TRUE;
1512 $fields = array_merge($fields, $locationFields);
1515 $fields = array_merge($fields,
1516 CRM_Core_DAO_Worldregion
::export()
1519 $fields = array_merge($fields,
1520 CRM_Contact_DAO_Contact
::export()
1524 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1526 if ($contactType != 'All') {
1527 $fields = array_merge($fields,
1528 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
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)
1540 $fields = array_merge($fields, [
1542 'title' => ts('Group(s)'),
1546 'title' => ts('Tag(s)'),
1550 'title' => ts('Note(s)'),
1556 $fields = array_merge($fields, [
1558 'title' => ts('Group(s)'),
1562 'title' => ts('Tag(s)'),
1566 'title' => ts('Note(s)'),
1572 //Sorting fields in alphabetical order(CRM-1507)
1573 foreach ($fields as $k => $v) {
1574 $sortArray[$k] = $v['title'] ??
NULL;
1577 $fields = array_merge($sortArray, $fields);
1578 //unset the field which are not related to their contact type.
1579 if ($contactType != 'All') {
1585 'organization_name',
1586 'email_greeting_custom',
1587 'postal_greeting_custom',
1600 'organization_name',
1608 'email_greeting_custom',
1609 'postal_greeting_custom',
1625 'email_greeting_custom',
1626 'postal_greeting_custom',
1636 foreach ($commonValues[$contactType] as $value) {
1637 unset($fields[$value]);
1641 Civi
::cache('fields')->set($cacheKeyString, $fields);
1643 self
::$_exportableFields[$cacheKeyString] = $fields;
1647 $fields = self
::$_exportableFields[$cacheKeyString];
1650 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1651 self
::$_exportableFields[$cacheKeyString]
1659 * Get the all contact details (Hierarchical).
1661 * @param int $contactId
1663 * @param array $fields
1669 public static function getHierContactDetails($contactId, $fields) {
1670 $params = [['contact_id', '=', $contactId, 0, 0]];
1672 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
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);
1686 * Given a set of flat profile style field names, create a hierarchy.
1688 * This is for the query to use, create the right sql.
1690 * @param array $fields
1691 * @param int $contactId
1695 * A hierarchical property tree if appropriate
1697 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1698 $locationTypes = CRM_Core_BAO_Address
::buildOptions('location_type_id', 'validate');
1700 $returnProperties = [];
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);
1707 if (!in_array($fieldName, $multipleFields)) {
1708 if ($id == 'Primary') {
1709 $locationTypeName = 1;
1712 $locationTypeName = $locationTypes[$id] ??
NULL;
1713 if (!$locationTypeName) {
1718 if (empty($returnProperties['location'])) {
1719 $returnProperties['location'] = [];
1721 if (empty($returnProperties['location'][$locationTypeName])) {
1722 $returnProperties['location'][$locationTypeName] = [];
1723 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1725 if (in_array($fieldName, [
1733 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1736 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1739 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1740 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1743 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1747 $returnProperties['website'][$id][$fieldName] = 1;
1751 $returnProperties[$name] = 1;
1755 return $returnProperties;
1759 * Return the primary location type of a contact.
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
1765 * @param int $contactId
1766 * @param bool $skipDefaultPrimary
1767 * @param string|null $block
1770 * $locationType location_type_id
1772 public static function getPrimaryLocationType($contactId, $skipDefaultPrimary = FALSE, $block = NULL) {
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;
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 ";
1802 $params = [1 => [$contactId, 'Integer']];
1804 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1806 $locationType = NULL;
1807 if ($dao->fetch()) {
1808 $locationType = $dao->locationType
;
1811 if (isset($locationType)) {
1812 return $locationType;
1814 elseif ($skipDefaultPrimary) {
1815 // if there is no primary contact location then return null
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
;
1827 * Get the display name, primary email and location type of a contact.
1830 * Id of the contact.
1833 * Array of display_name, email if found, do_not_email or (null,null,null)
1835 public static function getContactDetails($id) {
1836 // check if the contact type
1837 $contactType = self
::getContactType($id);
1839 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
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);
1849 if ($dao->fetch()) {
1850 if ($contactType == 'Individual') {
1851 if ($dao->first_name ||
$dao->last_name
) {
1852 $name = "{$dao->first_name} {$dao->last_name}";
1855 $name = $dao->display_name
;
1859 $name = $dao->display_name
;
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];
1867 return [NULL, NULL, NULL, NULL, NULL];
1871 * Add/edit/register contacts through profile.
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
1889 * contact id created/edited
1891 * @throws \CRM_Core_Exception
1892 * @throws \CiviCRM_API3_Exception
1893 * @throws \Civi\API\Exception\UnauthorizedException
1895 public static function createProfileContact(
1899 $addToGroupID = NULL,
1904 // add ufGroupID to params array ( CRM-2012 )
1906 $params['uf_group_id'] = $ufGroupId;
1908 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
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;
1920 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1924 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1927 [$data, $contactDetails] = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
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'])) {
1937 'contact_id' => $contactDetails['contact_id'],
1938 'status' => $isOptOut ?
'Removed' : 'Added',
1941 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1945 $contact = self
::create($data);
1947 // contact is null if the profile does not have any contact fields
1949 $contactID = $contact->id
;
1952 if (empty($contactID)) {
1953 throw new CRM_Core_Exception('Cannot proceed without a valid contact id');
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'])) {
1961 // this for sure means we are coming in via profile since i added it to fix
1962 // removing contacts from user groups -- lobo
1966 $groupParams = $params['group'] ??
[];
1967 $contactIds = [$contactID];
1971 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($contactID, 'Added',
1972 NULL, FALSE, $visibility
1974 if (is_array($contactGroupList)) {
1975 foreach ($contactGroupList as $key) {
1976 $groupId = $key['group_id'];
1977 $contactGroup[$groupId] = $groupId;
1981 // get the list of all the groups
1982 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
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);
1990 elseif (empty($groupParams[$key]) && array_key_exists($key, $contactGroup)) {
1991 // remove contact from group
1992 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
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);
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);
2011 elseif ($addToGroupID) {
2012 $contactIds = [$contactID];
2013 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2017 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2020 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2026 * Format profile contact parameters.
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
2037 public static function formatProfileContactParams(
2046 $data = $contactDetails = [];
2048 // get the contact details (hier)
2050 $details = self
::getHierContactDetails($contactID, $fields);
2052 $contactDetails = $details[$contactID];
2053 $data['contact_type'] = $contactDetails['contact_type'] ??
NULL;
2054 $data['contact_sub_type'] = $contactDetails['contact_sub_type'] ??
NULL;
2057 //we should get contact type only if contact
2059 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId, TRUE, FALSE, TRUE);
2061 //special case to handle profile with only contact fields
2062 if ($data['contact_type'] == 'Contact') {
2063 $data['contact_type'] = 'Individual';
2065 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2066 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2070 $data['contact_type'] = $ctype;
2073 $data['contact_type'] = 'Individual';
2077 //fix contact sub type CRM-5125
2078 if (array_key_exists('contact_sub_type', $params) &&
2079 !empty($params['contact_sub_type'])
2081 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2083 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2084 !empty($params['contact_sub_type_hidden'])
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']);
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']);
2102 if ($ctype == 'Organization') {
2103 $data['organization_name'] = $contactDetails['organization_name'] ??
NULL;
2105 elseif ($ctype == 'Household') {
2106 $data['household_name'] = $contactDetails['household_name'] ??
NULL;
2114 $data['contact_id'] = $contactID;
2115 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2118 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2119 $defaultLocationId = $defaultLocation->id
;
2122 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2124 $blocks = ['email', 'phone', 'im', 'openid'];
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])
2133 unset($params[$blk]);
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);
2142 if ($locTypeId == 'Primary') {
2144 if (in_array($fieldName, $blocks)) {
2145 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2148 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2150 $primaryLocationType = $locTypeId;
2153 $locTypeId = $defaultLocationId;
2157 if (is_numeric($locTypeId) &&
2158 !in_array($fieldName, $multiplFields) &&
2159 substr($fieldName, 0, 7) != 'custom_'
2161 $index = $locTypeId;
2163 if (is_numeric($typeId)) {
2164 $index .= '-' . $typeId;
2166 if (!in_array($index, $locationType)) {
2167 $locationType[$count] = $index;
2171 $loc = CRM_Utils_Array
::key($index, $locationType);
2173 $blockName = self
::getLocationEntityForKey($fieldName);
2175 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2177 //set is_billing true, for location type "Billing"
2178 if ($locTypeId == $billingLocationTypeId) {
2179 $data[$blockName][$loc]['is_billing'] = 1;
2183 //get the primary location type
2184 if ($locTypeId == $primaryLocationType) {
2185 $data[$blockName][$loc]['is_primary'] = 1;
2188 elseif ($locTypeId == $defaultLocationId) {
2189 $data[$blockName][$loc]['is_primary'] = 1;
2192 if (in_array($fieldName, ['phone'])) {
2194 $data['phone'][$loc]['phone_type_id'] = $typeId;
2197 $data['phone'][$loc]['phone_type_id'] = '';
2199 $data['phone'][$loc]['phone'] = $value;
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;
2207 if ($loc != $primaryPhoneLoc) {
2208 unset($data['phone'][$loc]['is_primary']);
2211 elseif ($fieldName == 'email') {
2212 $data['email'][$loc]['email'] = $value;
2213 if (empty($contactID)) {
2214 $data['email'][$loc]['is_primary'] = 1;
2217 elseif ($fieldName == 'im') {
2218 if (isset($params[$key . '-provider_id'])) {
2219 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2221 if (strpos($key, '-provider_id') !== FALSE) {
2222 $data['im'][$loc]['provider_id'] = $params[$key];
2225 $data['im'][$loc]['name'] = $value;
2228 elseif ($fieldName == 'openid') {
2229 $data['openid'][$loc]['openid'] = $value;
2232 if ($fieldName === 'state_province') {
2234 if (is_numeric($value) && ((int ) $value) >= 1000) {
2235 $data['address'][$loc]['state_province_id'] = $value;
2237 elseif (empty($value)) {
2238 $data['address'][$loc]['state_province_id'] = '';
2241 $data['address'][$loc]['state_province'] = $value;
2244 elseif ($fieldName === 'country') {
2246 if (is_numeric($value) && ((int ) $value) >= 1000
2248 $data['address'][$loc]['country_id'] = $value;
2250 elseif (empty($value)) {
2251 $data['address'][$loc]['country_id'] = '';
2254 $data['address'][$loc]['country'] = $value;
2257 elseif ($fieldName === 'county') {
2258 $data['address'][$loc]['county_id'] = $value;
2260 elseif ($fieldName == 'address_name') {
2261 $data['address'][$loc]['name'] = $value;
2263 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2264 $data['address'][$loc][substr($fieldName, 8)] = $value;
2267 $data[$blockName][$loc][$fieldName] = $value;
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;
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;
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'];
2287 // we need to append time with date
2288 if ($params[$key] && isset($params[$key . '_time'])) {
2289 $value .= ' ' . $params[$key . '_time'];
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))
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) {
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'];
2320 $type = $data['contact_type'];
2321 if (!empty($data['contact_sub_type'])) {
2322 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2326 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2336 elseif ($key === 'edit') {
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'];
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');
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
2366 $data[$key] = $value;
2372 if (!isset($data['contact_type'])) {
2373 $data['contact_type'] = 'Individual';
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])) {
2387 elseif (!$contactID) {
2393 return [$data, $contactDetails];
2397 * Find the get contact details.
2399 * This function does not respect ACLs for now, which might need to be rectified at some
2400 * stage based on how its used.
2402 * @param string $mail
2403 * Primary email address of the contact.
2404 * @param string $ctype
2407 * @return object|null
2408 * $dao contact details
2410 public static function matchContactOnEmail($mail, $ctype = NULL) {
2411 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2412 $mail = $strtolower(trim($mail));
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 )";
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)) {
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) . "))";
2432 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2433 $p = [1 => [$mail, 'String']];
2436 $query .= " AND civicrm_contact.contact_type = %3";
2437 $p[3] = [$ctype, 'String'];
2440 $query .= " ORDER BY civicrm_email.is_primary DESC";
2442 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2444 if ($dao->fetch()) {
2451 * Find the contact details associated with an OpenID.
2453 * @param string $openId
2454 * OpenId of the contact.
2455 * @param string $ctype
2458 * @return object|null
2459 * $dao contact details
2461 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2462 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2463 $openId = $strtolower(trim($openId));
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']];
2475 $query .= " AND civicrm_contact.contact_type = %3";
2476 $p[3] = [$ctype, 'String'];
2479 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2481 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2483 if ($dao->fetch()) {
2490 * Get primary email of the contact.
2492 * @param int $contactID
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.
2499 * Email address if present else null
2501 public static function getPrimaryEmail($contactID, $polite = FALSE) {
2502 // fetch the primary email
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";
2511 AND civicrm_contact.do_not_email = 0
2512 AND civicrm_email.on_hold = 0';
2514 $p = [1 => [$contactID, 'Integer']];
2515 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2518 if ($dao->fetch()) {
2519 $email = $dao->email
;
2525 * Fetch the object and store the values in the values array.
2527 * @param array $params
2528 * Input parameters to find object.
2529 * @param array $values
2530 * Output values of the object.
2532 * @return CRM_Contact_BAO_Contact|null
2533 * The found object or null
2535 public static function getValues($params, &$values) {
2536 $contact = new CRM_Contact_BAO_Contact();
2538 $contact->copyValues($params);
2540 if ($contact->find(TRUE)) {
2542 CRM_Core_DAO
::storeValues($contact, $values);
2545 foreach (self
::$_commPrefs as $name) {
2546 if (isset($contact->$name)) {
2547 $privacy[$name] = $contact->$name;
2551 if (!empty($privacy)) {
2552 $values['privacy'] = $privacy;
2555 // communication Prefferance
2556 $preffComm = $comm = [];
2557 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2558 $contact->preferred_communication_method
2560 foreach ($comm as $value) {
2561 $preffComm[$value] = 1;
2563 $temp = ['preferred_communication_method' => $contact->preferred_communication_method
];
2566 'preferred_communication_method' => [
2567 'newName' => 'preferred_communication_method_display',
2568 'groupName' => 'preferred_communication_method',
2572 // @todo This can be figured out from metadata & we can avoid the uncached query.
2573 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2575 $values['preferred_communication_method'] = $preffComm;
2576 $values['preferred_communication_method_display'] = $temp['preferred_communication_method_display'] ??
NULL;
2578 if ($contact->preferred_mail_format
) {
2579 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2580 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
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
);
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
;
2596 $age = CRM_Utils_Date
::calculateAge($birthDate, $deceasedDate);
2597 $values['age']['y'] = $age['years'] ??
NULL;
2598 $values['age']['m'] = $age['months'] ??
NULL;
2602 $contact->contact_id
= $contact->id
;
2610 * Provides counts for the contact summary tabs.
2612 * @param string $type
2613 * Type of record to count.
2614 * @param int $contactId
2616 * @param string|null $tableName
2617 * Deprecated - do not use
2620 * total number in database
2622 public static function getCountComponent(string $type, int $contactId, ?
string $tableName = NULL) {
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__);
2629 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2632 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2633 CRM_Contact_BAO_Relationship
::CURRENT
,
2641 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2644 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2647 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2650 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2652 case 'contribution':
2653 if (CRM_Core_Component
::isEnabled('CiviContribute')) {
2654 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2659 if (CRM_Core_Component
::isEnabled('CiviMember')) {
2660 return CRM_Member_BAO_Membership
::getContactMembershipCount((int) $contactId, TRUE);
2665 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2668 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2671 return CRM_Case_BAO_Case
::caseCount($contactId);
2675 'contact_id' => $contactId,
2678 'context' => 'activity',
2680 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2683 $params = ['contact_id' => $contactId];
2684 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2688 $custom = explode('_', $type);
2689 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom[1], 'table_name');
2691 $queryString = "SELECT count(id) FROM $tableName WHERE entity_id = $contactId";
2692 return (int) CRM_Core_DAO
::singleValueQuery($queryString);
2697 * Update contact greetings if an update has resulted in a custom field change.
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).
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);
2723 * Process greetings and cache.
2725 * @param \CRM_Contact_DAO_Contact $contact
2726 * Contact object after save.
2728 public static function processGreetings(&$contact) {
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.
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);
2745 // store object values to an array
2746 $contactDetails = [];
2747 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2748 $contactDetails = [[$contact->id
=> $contactDetails]];
2750 $updateQueryString = [];
2752 if ($emailGreetingString) {
2753 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2756 'CRM_Contact_BAO_Contact'
2758 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2759 $updateQueryString[] = " email_greeting_display = '$emailGreetingString'";
2762 if ($postalGreetingString) {
2763 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2766 'CRM_Contact_BAO_Contact'
2768 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2769 $updateQueryString[] = " postal_greeting_display = '$postalGreetingString'";
2772 if ($addresseeString) {
2773 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2776 'CRM_Contact_BAO_Contact'
2778 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2779 $updateQueryString[] = " addressee_display = '$addresseeString'";
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);
2790 * Retrieve loc block ids w/ given condition.
2792 * @param int $contactId
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.
2801 * loc block ids which fulfill condition.
2803 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2806 return $locBlockIds;
2809 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2810 $name = strtolower($block);
2811 $className = "CRM_Core_DAO_$block";
2812 $blockDAO = new $className();
2814 // build the condition.
2815 if (is_array($criteria)) {
2816 $fields = $blockDAO->fields();
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 )";
2825 $conditions[] = $cond;
2828 if (!empty($conditions)) {
2829 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2833 $blockDAO->contact_id
= $contactId;
2835 while ($blockDAO->fetch()) {
2836 $locBlockIds[$name][] = $blockDAO->id
;
2840 return $locBlockIds;
2844 * Build context menu items.
2846 * @param int $contactId
2849 * Array of context menu for logged in user.
2851 public static function contextMenu($contactId = NULL) {
2854 'title' => ts('View Contact'),
2856 'ref' => 'view-contact',
2857 'class' => 'no-popup',
2859 'permissions' => ['view all contacts'],
2862 'title' => ts('Edit Contact'),
2864 'ref' => 'edit-contact',
2865 'class' => 'no-popup',
2867 'permissions' => ['edit all contacts'],
2870 'title' => ts('Delete Contact'),
2872 'ref' => 'delete-contact',
2874 'permissions' => ['access deleted contacts', 'delete contacts'],
2877 'title' => ts('Add Contribution'),
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'
2887 'access CiviContribute',
2888 'edit contributions',
2892 'title' => ts('Register for Event'),
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'),
2901 'edit event participants',
2905 'title' => ts('Record Activity'),
2907 'ref' => 'new-activity',
2908 'key' => 'activity',
2909 'permissions' => ['edit all contacts'],
2912 'title' => ts('Add Pledge'),
2914 'ref' => 'new-pledge',
2917 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2918 'reset=1&action=add&context=pledge'
2920 'component' => 'CiviPledge',
2922 'access CiviPledge',
2927 'title' => ts('Add Membership'),
2929 'ref' => 'new-membership',
2930 'key' => 'membership',
2932 'component' => 'CiviMember',
2933 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2934 'reset=1&action=add&context=membership'
2937 'access CiviMember',
2942 'title' => ts('Add Case'),
2944 'ref' => 'new-case',
2947 'component' => 'CiviCase',
2948 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
2949 'permissions' => ['add cases'],
2952 'title' => ts('Add Relationship'),
2954 'ref' => 'new-relationship',
2957 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
2958 'reset=1&action=add'
2960 'permissions' => ['edit all contacts'],
2963 'title' => ts('Add Note'),
2965 'ref' => 'new-note',
2968 'class' => 'medium-popup',
2969 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
2970 'reset=1&action=add'
2972 'permissions' => ['edit all contacts'],
2975 'title' => ts('Send an Email'),
2977 'ref' => 'new-email',
2979 'permissions' => ['view all contacts'],
2982 'title' => ts('Add to Group'),
2984 'ref' => 'group-add-contact',
2987 'permissions' => ['edit groups'],
2990 'title' => ts('Tag Contact'),
2992 'ref' => 'tag-contact',
2995 'permissions' => ['edit all contacts'],
2999 $menu['otherActions'] = [
3001 'title' => ts('Print Summary'),
3002 'description' => ts('Printer-friendly view of this page.'),
3004 'ref' => 'crm-contact-print',
3007 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3011 'icon' => 'crm-i fa-print',
3014 'title' => ts('vCard'),
3015 'description' => ts('vCard record for this contact.'),
3017 'ref' => 'crm-contact-vcard',
3020 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3024 'icon' => 'crm-i fa-list-alt',
3028 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3029 $menu['otherActions']['dashboard'] = [
3030 'title' => ts('Contact Dashboard'),
3031 'description' => ts('Contact Dashboard'),
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',
3044 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3046 $menu['otherActions']['user-record'] = [
3047 'title' => ts('User Record'),
3048 'description' => ts('User Record'),
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',
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'),
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',
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.
3078 $aclPermissionedTasks = [
3083 'group-add-contact',
3087 $corePermission = CRM_Core_Permission
::getPermission();
3090 foreach ($menu as $key => $values) {
3091 if ($key !== 'otherActions') {
3093 // user does not have necessary permissions.
3094 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3097 // build directly accessible action menu.
3098 if (in_array($values['ref'], [
3102 $contextMenu['primaryActions'][$key] = [
3103 'title' => $values['title'],
3104 'ref' => $values['ref'],
3105 'class' => $values['class'] ??
NULL,
3106 'key' => $values['key'],
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']++
;
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'],
3127 foreach ($values as $value) {
3128 // user does not have necessary permissions.
3129 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
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.
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'],
3152 ksort($contextMenu['moreActions']);
3153 ksort($contextMenu['otherActions']);
3155 return $contextMenu;
3159 * Check if user has permissions to access items in action menu.
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).
3169 * TRUE if user has all permissions, FALSE if otherwise.
3171 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3172 $componentName = $menuOptions['component'] ??
NULL;
3174 // if component action - make sure component is enable.
3175 if ($componentName && !CRM_Core_Component
::isEnabled($componentName)) {
3179 // make sure user has all required permissions.
3180 $hasAllPermissions = FALSE;
3182 $permissions = $menuOptions['permissions'] ??
NULL;
3183 if (!is_array($permissions) ||
empty($permissions)) {
3184 $hasAllPermissions = TRUE;
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)) {
3196 if (count($permissions) == $hasPermissions) {
3197 $hasAllPermissions = TRUE;
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
3205 $hasAllPermissions = TRUE;
3207 elseif (in_array($menuOptions['ref'], [
3210 // grant permissions for these tasks.
3211 $hasAllPermissions = TRUE;
3216 return $hasAllPermissions;
3220 * Retrieve display name of contact that address is shared.
3222 * This is based on $masterAddressId or $contactId .
3224 * @param int $masterAddressId
3226 * @param int $contactId
3227 * Contact id. (deprecated - do not use)
3229 * @return string|null
3230 * the found display name or null.
3232 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3233 $masterDisplayName = NULL;
3234 if (!$masterAddressId) {
3235 return $masterDisplayName;
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;
3243 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3244 return $masterDisplayName;
3248 * Get the creation/modification times for a contact.
3250 * @param int $contactId
3253 * Dates - ('created_date' => $, 'modified_date' => $)
3255 public static function getTimestamps($contactId) {
3256 $timestamps = CRM_Core_DAO
::executeQuery(
3257 'SELECT created_date, modified_date
3258 FROM civicrm_contact
3261 1 => [$contactId, 'Integer'],
3264 if ($timestamps->fetch()) {
3266 'created_date' => $timestamps->created_date
,
3267 'modified_date' => $timestamps->modified_date
,
3276 * Get a list of triggers for the contact table.
3278 * @param array $info
3279 * @param string|null $tableName
3281 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3283 * @see hook_civicrm_triggerInfo
3284 * @see CRM_Core_DAO::triggerRebuild
3286 public static function triggerInfo(&$info, $tableName = NULL) {
3288 // Modifications to these records should update the contact timestamps.
3289 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
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'],
3297 ->alterTriggerInfo($info, $tableName);
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
);
3306 'table' => ['civicrm_phone'],
3308 'event' => ['INSERT', 'UPDATE'],
3309 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3315 * Check if contact is being used in civicrm_domain based on $contactId.
3317 * @param int $contactId
3321 * true if present else false.
3323 public static function checkDomainContact($contactId) {
3327 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3338 * Get options for a given contact field.
3340 * @param string $fieldName
3341 * @param string $context
3342 * @param array $props
3343 * whatever is known about this dao object.
3345 * @return array|bool
3346 * @see CRM_Core_DAO::buildOptions
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?
3351 * @see CRM_Core_DAO::buildOptionsContext
3353 public static function buildOptions($fieldName, $context = NULL, $props = []) {
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']}')";
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();
3371 // The contact api supports some related entities so we'll honor that by fetching their options
3374 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3378 $props['entity_table'] = 'civicrm_contact';
3379 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3381 case 'state_province_id':
3382 case 'state_province':
3383 case 'state_province_name':
3388 case 'worldregion_id':
3389 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3392 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3396 * Event fired after modifying any entity.
3397 * @param \Civi\Core\Event\PostEvent $event
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'];
3403 $event->action
=== 'delete' && $event->id
&&
3404 in_array($event->entity
, $hasPrimary) &&
3405 !empty($event->object->is_primary
) &&
3406 !empty($event->object->contact_id
)
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]);
3424 * Get the template string for the given greeting.
3426 * @param string $greetingType
3427 * @param CRM_Contact_DAO_Contact $contact
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;
3436 $idField = $greetingType . '_id';
3437 if (!is_numeric($contact->$idField)) {
3441 'contact_type' => $contact->contact_type
,
3442 'greeting_type' => $greetingType,
3444 return CRM_Core_PseudoConstant
::greeting($filter)[$contact->$idField] ??
'';
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
3454 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3455 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
[] : ['!= 1'],
3457 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3462 * Get any existing duplicate contacts based on the input parameters.
3464 * @param array $input
3465 * Input parameters to be matched.
3466 * @param string $contactType
3467 * @param string $rule
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]
3479 * @throws \CRM_Core_Exception
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);
3494 return $dedupeResults['ids'] ??
[];
3498 * Get the first duplicate contacts based on the input parameters.
3500 * @param array $input
3501 * Input parameters to be matched.
3502 * @param string $contactType
3503 * @param string $rule
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]
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);
3525 * Check if a field is associated with an entity that has a location type.
3527 * (ie. is an address, phone, email etc field).
3529 * @param string $fieldTitle
3530 * Title of the field (not the name - create a new function for that if required).
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;
3544 * @param array $appendProfiles
3545 * Name of profile(s) to append to each link.
3547 * @return array|false
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']])) {
3556 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3557 $profiles[] = 'new_' . strtolower($contactType);
3559 $retrieved = civicrm_api3('uf_group', 'get', [
3560 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3563 $links = $append = [];
3564 if (!empty($retrieved['values'])) {
3566 'individual' => 'fa-user',
3567 'organization' => 'fa-building',
3568 'household' => 'fa-home',
3570 foreach ($retrieved['values'] as $id => $profile) {
3571 if (in_array($profile['name'], $profiles)) {
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,
3584 foreach ($append as $id) {
3585 foreach ($links as &$link) {
3586 $link['url'] .= ",$id";
3596 public static function getEntityRefFilters() {
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'],
3617 * @param string $entityName
3618 * @param string $action
3619 * @param array $record
3622 * @see CRM_Core_DAO::checkAccess
3624 public static function _checkAccess(string $entityName, string $action, array $record, $userID): bool {
3627 return CRM_Core_Permission
::check('add contacts', $userID);
3630 $actionType = CRM_Core_Permission
::VIEW
;
3634 $actionType = CRM_Core_Permission
::DELETE
;
3638 $actionType = CRM_Core_Permission
::EDIT
;
3642 return CRM_Contact_BAO_Contact_Permission
::allow($record['id'], $actionType, $userID);
3646 * Get icon for a particular contact.
3648 * Example: `CRM_Contact_BAO_Contact::getIcon('Contact', 123)`
3650 * @param string $entityName
3652 * @param int $entityId
3653 * Id of the contact.
3654 * @throws CRM_Core_Exception
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'];
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;