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
{
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;
87 public function __construct() {
88 parent
::__construct();
92 * Takes an associative array and creates a contact object.
94 * The function extracts all the params it needs to initialize the create a
95 * contact object. the params array could contain additional unused name/value
98 * @param array $params
99 * (reference) an assoc array of name/value pairs.
101 * @return CRM_Contact_DAO_Contact|CRM_Core_Error|NULL
102 * Created or updated contact object or error object.
103 * (error objects are being phased out in favour of exceptions)
104 * @throws \CRM_Core_Exception
106 public static function add(&$params) {
107 $contact = new CRM_Contact_DAO_Contact();
108 $contactID = $params['contact_id'] ??
NULL;
109 if (empty($params)) {
113 // Fix for validate contact sub type CRM-5143.
114 if (isset($params['contact_sub_type'])) {
115 if (empty($params['contact_sub_type'])) {
116 $params['contact_sub_type'] = 'null';
118 elseif ($params['contact_sub_type'] !== 'null') {
119 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
120 $params['contact_type'], TRUE
123 // we'll need to fix tests to handle this
125 throw new CRM_Core_Exception(ts('The Contact Sub Type does not match the Contact type for this record'));
127 $params['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
131 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
132 CRM_Utils_Array
::formatArrayKeys($params['preferred_communication_method']);
133 $contact->preferred_communication_method
= CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
134 unset($params['preferred_communication_method']);
137 $defaults = ['source' => $params['contact_source'] ??
NULL];
138 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
139 $defaults['display_name'] = $params['organization_name'];
140 $defaults['sort_name'] = $params['organization_name'];
142 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
143 $defaults['display_name'] = $params['household_name'];
144 $defaults['sort_name'] = $params['household_name'];
146 $params = array_merge($defaults, $params);
148 $allNull = $contact->copyValues($params);
150 $contact->id
= $contactID;
152 if ($contact->contact_type
=== 'Individual') {
154 // @todo allow the lines below to be overridden by input or hooks & add tests,
155 // as has been done for households and organizations.
156 // Format individual fields.
157 CRM_Contact_BAO_Individual
::format($params, $contact);
160 // Note that copyValues() above might already call this, via
161 // CRM_Utils_String::ellipsify(), but e.g. for Individual it gets put
162 // back or altered by Individual::format() just above, so we need to
164 // Note also orgs will get ellipsified, but if we do that here then
165 // some existing tests on individual fail.
166 // Also api v3 will enforce org naming length by failing, v4 will truncate.
167 if (mb_strlen($contact->display_name
, 'UTF-8') > 128) {
168 $contact->display_name
= mb_substr($contact->display_name
, 0, 128, 'UTF-8');
170 if (mb_strlen($contact->sort_name
, 'UTF-8') > 128) {
171 $contact->sort_name
= mb_substr($contact->sort_name
, 0, 128, 'UTF-8');
174 $privacy = $params['privacy'] ??
NULL;
175 if ($privacy && is_array($privacy)) {
177 foreach (self
::$_commPrefs as $name) {
178 $contact->$name = $privacy[$name] ??
FALSE;
182 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
183 // @todo - does this mean we can remove this block?
184 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
185 if ((!isset($contact->hash
) ||
!$contact->hash
) && !$contact->id
) {
187 $contact->hash
= md5(uniqid(rand(), TRUE));
190 // Even if we don't need $employerId, it's important to call getFieldValue() before
191 // the contact is saved because we want the existing value to be cached.
192 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
193 $employerId = (!$contactID ||
$contact->contact_type
!== 'Individual') ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
198 CRM_Core_BAO_Log
::register($contact->id
,
204 if ($contact->contact_type
=== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
205 // Create current employer.
206 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : $params['current_employer'] ??
NULL;
208 $newContact = empty($params['contact_id']);
210 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
212 elseif ($employerId) {
213 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
217 // Update cached employer name if the name of an existing organization is being updated.
218 if ($contact->contact_type
=== 'Organization' && !empty($params['organization_name']) && $contactID) {
219 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
228 * takes an associative array and creates a contact object and all the associated
229 * derived objects (i.e. individual, location, email, phone etc)
231 * This function is invoked from within the web form layer and also from the api layer
233 * @param array $params
234 * (reference ) an assoc array of name/value pairs.
235 * @param bool $fixAddress
236 * If we need to fix address.
237 * @param bool $invokeHooks
238 * If we need to invoke hooks.
240 * @param bool $skipDelete
241 * Unclear parameter, passed to website create
243 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
244 * Created or updated contribution object. We are deprecating returning an error in
245 * favour of exceptions
247 * @throws \CRM_Core_Exception
248 * @throws \CiviCRM_API3_Exception
249 * @throws \Civi\API\Exception\UnauthorizedException
251 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
253 if (empty($params['contact_type']) && empty($params['contact_id'])) {
257 $isEdit = !empty($params['contact_id']);
259 if ($isEdit && empty($params['contact_type'])) {
260 $params['contact_type'] = self
::getContactType($params['contact_id']);
263 if (!empty($params['check_permissions']) && isset($params['api_key'])
264 && !CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])
265 && !($isEdit && CRM_Core_Permission
::check('edit own api keys') && $params['contact_id'] == CRM_Core_Session
::getLoggedInContactID())
267 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify api key');
271 if (!empty($params['contact_id'])) {
272 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
275 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
279 self
::ensureGreetingParamsAreSet($params);
281 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
282 if (empty($params['contact_id'])) {
283 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
284 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
285 $params['preferred_language'] = $language;
288 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
289 if (empty($params['communication_style_id'])) {
290 $defaultCommunicationStyleId = CRM_Core_OptionGroup
::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
291 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
295 $transaction = new CRM_Core_Transaction();
297 $contact = self
::add($params);
299 $params['contact_id'] = $contact->id
;
301 if (Civi
::settings()->get('is_enabled')) {
302 // Enabling multisite causes the contact to be added to the domain group.
303 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
304 if (!empty($domainGroupID)) {
305 if (!empty($params['group']) && is_array($params['group'])) {
306 $params['group'][$domainGroupID] = 1;
309 $params['group'] = [$domainGroupID => 1];
314 if (!empty($params['group'])) {
315 $contactIds = [$params['contact_id']];
316 foreach ($params['group'] as $groupId => $flag) {
318 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
320 elseif ($flag == -1) {
321 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
326 // Add location Block data.
327 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
328 foreach ($blocks as $name => $value) {
329 $contact->$name = $value;
331 if (!empty($params['updateBlankLocInfo'])) {
335 if (isset($params['website'])) {
336 CRM_Core_BAO_Website
::process($params['website'], $contact->id
, $skipDelete);
339 $userID = CRM_Core_Session
::singleton()->get('userID');
341 if (!empty($params['note'])) {
342 if (is_array($params['note'])) {
343 foreach ($params['note'] as $note) {
344 $contactId = $contact->id
;
345 if (isset($note['contact_id'])) {
346 $contactId = $note['contact_id'];
348 //if logged in user, overwrite contactId
350 $contactId = $userID;
354 'entity_id' => $contact->id
,
355 'entity_table' => 'civicrm_contact',
356 'note' => $note['note'],
357 'subject' => $note['subject'] ??
NULL,
358 'contact_id' => $contactId,
360 CRM_Core_BAO_Note
::add($noteParams);
364 $contactId = $contact->id
;
365 //if logged in user, overwrite contactId
367 $contactId = $userID;
371 'entity_id' => $contact->id
,
372 'entity_table' => 'civicrm_contact',
373 'note' => $params['note'],
374 'subject' => $params['subject'] ??
NULL,
375 'contact_id' => $contactId,
377 CRM_Core_BAO_Note
::add($noteParams);
381 if (!empty($params['custom']) &&
382 is_array($params['custom'])
384 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
387 $transaction->commit();
389 // CRM-6367: fetch the right label for contact type’s display
390 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
391 'CRM_Contact_DAO_ContactType',
392 $contact->contact_type
,
397 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
401 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
404 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
408 // In order to prevent a series of expensive queries in intensive batch processing
409 // api calls may pass in skip_greeting_processing, probably doing it later via the
410 // scheduled job. CRM-21551
411 if (empty($params['skip_greeting_processing'])) {
412 self
::processGreetings($contact);
415 if (!empty($params['check_permissions'])) {
416 $contacts = [&$contact];
417 self
::unsetProtectedFields($contacts);
420 if (!empty($params['is_deceased'])) {
421 // Edit Membership Status
423 'contact_id' => $contact->id
,
424 'is_deceased' => $params['is_deceased'],
425 'deceased_date' => $params['deceased_date'] ??
NULL,
427 CRM_Member_BAO_Membership
::updateMembershipStatus($deceasedParams, $params['contact_type']);
434 * Format the output of the create contact function
436 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
438 public static function unsetProtectedFields(&$contacts) {
439 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
440 $currentUser = CRM_Core_Session
::getLoggedInContactID();
441 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
442 foreach ($contacts as &$contact) {
443 $cid = is_object($contact) ?
$contact->id
: $contact['id'] ??
NULL;
444 if (!($editOwn && $cid == $currentUser)) {
445 if (is_object($contact)) {
446 unset($contact->api_key
);
449 unset($contact['api_key']);
457 * Ensure greeting parameters are set.
459 * By always populating greetings here we can be sure they are set if required & avoid a call later.
460 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
462 * @param array $params
464 * @throws \CiviCRM_API3_Exception
466 public static function ensureGreetingParamsAreSet(&$params) {
467 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
468 $missingGreetingParams = [];
470 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
471 if (empty($params[$greetingParam])) {
472 $missingGreetingParams[$greetingIndex] = $greetingParam;
476 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
477 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
478 'id' => $params['contact_id'],
479 'return' => array_keys($missingGreetingParams),
482 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
483 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
484 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
487 // Filter out other fields.
488 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
489 $params = array_merge($params, $savedGreetings);
492 foreach ($missingGreetingParams as $greetingName => $greeting) {
493 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
497 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
498 if ($params[$greetingParam] === 'null') {
499 // If we are setting it to null then null out the display field.
500 $params[$greetingIndex . '_display'] = 'null';
506 * Get the display name and image of a contact.
511 * @param bool $includeTypeInReturnParameters
512 * Should type be part of the returned array?
515 * the displayName and contactImage for this contact
517 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
518 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
520 SELECT civicrm_contact.*,
521 civicrm_email.email as email
523 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
524 AND civicrm_email.is_primary = 1
525 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
526 $dao = new CRM_Core_DAO();
529 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
530 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
532 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
533 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
536 // use email if display_name is empty
537 if (empty($dao->display_name
)) {
538 $displayName = $dao->email
;
541 $displayName = $dao->display_name
;
544 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
546 return $includeTypeInReturnParameters ?
[
550 $dao->contact_sub_type
,
552 ] : [$displayName, $image, $imageUrl];
558 * Add billing fields to the params if appropriate.
560 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
561 * don't then we should set the name fields to the billing fields AND add the preserveDBName
562 * parameter (which will tell the BAO only to set those fields if none already exist.
564 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
565 * matching is best done by hipsters.
567 * @param array $params
569 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
571 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
572 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
573 foreach ($nameFields as $field) {
574 if (!empty($params[$field])) {
578 // There are only 3 - we can iterate through them twice :-)
579 foreach ($nameFields as $field) {
580 if (!empty($params['billing_' . $field])) {
581 $params[$field] = $params['billing_' . $field];
583 $params['preserveDBName'] = TRUE;
589 * Resolve a state province string (UT or Utah) to an ID.
591 * If country has been passed in we should select a state belonging to that country.
593 * Alternatively we should choose from enabled countries, prioritising the default country.
595 * @param array $values
596 * @param int|null $countryID
600 * @throws \CRM_Core_Exception
602 protected static function resolveStateProvinceID($values, $countryID) {
605 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
606 if (CRM_Utils_Array
::lookupValue($values,
611 return $values['state_province_id'];
613 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
614 if (CRM_Utils_Array
::lookupValue($values,
619 return $values['state_province_id'];
624 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
625 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
626 // prefer matching country..
627 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, ['country_id' => Civi
::settings()->get('defaultContactCountry')]);
628 if (CRM_Utils_Array
::lookupValue($values,
633 return $values['state_province_id'];
636 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
637 if (CRM_Utils_Array
::lookupValue($values,
642 return $values['state_province_id'];
645 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
646 if (CRM_Utils_Array
::lookupValue($values,
651 return $values['state_province_id'];
653 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
654 if (CRM_Utils_Array
::lookupValue($values,
659 return $values['state_province_id'];
667 * Get the relevant location entity for the array key.
669 * Based on the field name we determine which location entity
670 * we are dealing with. Apart from a few specific ones they
671 * are mostly 'address' (the default).
673 * @param string $fieldName
677 protected static function getLocationEntityForKey($fieldName) {
678 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
681 if ($fieldName === 'phone_ext') {
688 * Soft delete a contact.
690 * Call this via the api, not directly.
692 * @param \CRM_Contact_BAO_Contact $contact
695 * @throws \CRM_Core_Exception
697 protected static function contactTrash($contact): bool {
699 'id' => $contact->id
,
702 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
704 $params = [1 => [$contact->id
, 'Integer']];
705 $query = 'DELETE FROM civicrm_uf_match WHERE contact_id = %1';
706 CRM_Core_DAO
::executeQuery($query, $params);
708 $contact->copyValues($updateParams);
710 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
712 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
718 * Get the values for pseudoconstants for name->value and reverse.
720 * @param array $defaults
721 * (reference) the default values, some of which need to be resolved.
722 * @param bool $reverse
723 * Always true as this function is only called from one place..
727 * This is called specifically from the contact import parser & should be moved there
728 * as it is not truly a generic function.
731 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
732 // Hack for birth_date.
733 if (!empty($defaults['birth_date'])) {
734 if (is_array($defaults['birth_date'])) {
735 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
739 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
740 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
741 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
742 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
744 //lookup value of email/postal greeting, addressee, CRM-4575
745 foreach (self
::$_greetingTypes as $greeting) {
747 'contact_type' => $defaults['contact_type'] ??
NULL,
748 'greeting_type' => $greeting,
750 CRM_Utils_Array
::lookupValue($defaults, $greeting,
751 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
755 $blocks = ['address', 'im', 'phone'];
756 foreach ($blocks as $name) {
757 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
760 foreach ($defaults[$name] as $count => & $values) {
762 //get location type id.
763 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
765 if ($name == 'address') {
766 // FIXME: lookupValue doesn't work for vcard_name
767 if (!empty($values['location_type_id'])) {
768 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', ['labelColumn' => 'vcard_name']);
769 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
772 if (!CRM_Utils_Array
::lookupValue($values,
774 CRM_Core_PseudoConstant
::country(),
779 CRM_Utils_Array
::lookupValue($values,
781 CRM_Core_PseudoConstant
::countryIsoCode(),
785 $stateProvinceID = self
::resolveStateProvinceID($values, $values['country_id'] ??
NULL);
786 if ($stateProvinceID) {
787 $values['state_province_id'] = $stateProvinceID;
790 if (!empty($values['state_province_id'])) {
791 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
794 $countyList = CRM_Core_PseudoConstant
::county();
796 CRM_Utils_Array
::lookupValue($values,
804 CRM_Utils_Array
::lookupValue($values,
806 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
811 if ($name == 'phone') {
812 CRM_Utils_Array
::lookupValue($values,
814 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
819 // Kill the reference.
826 * Fetch object based on array of properties.
828 * @param array $params
829 * (reference ) an assoc array of name/value pairs.
830 * @param array $defaults
831 * (reference ) an assoc array to hold the name / value pairs.
832 * in a hierarchical manner
833 * @param bool $microformat
834 * For location in microformat.
836 * @return CRM_Contact_BAO_Contact
838 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
839 if (array_key_exists('contact_id', $params)) {
840 $params['id'] = $params['contact_id'];
842 elseif (array_key_exists('id', $params)) {
843 $params['contact_id'] = $params['id'];
846 $contact = self
::getValues($params, $defaults);
848 unset($params['id']);
850 //get the block information for this contact
851 $entityBlock = ['contact_id' => $params['contact_id']];
852 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
853 $defaults = array_merge($defaults, $blocks);
854 foreach ($blocks as $block => $value) {
855 $contact->$block = $value;
858 if (!isset($params['noNotes'])) {
859 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
862 if (!isset($params['noRelationships'])) {
863 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
866 if (!isset($params['noGroups'])) {
867 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
870 if (!isset($params['noWebsite'])) {
871 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
878 * Get the display name of a contact.
883 * @return null|string
884 * display name of the contact if found
886 public static function displayName($id) {
889 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
896 * Delete a contact and all its associated records.
899 * Id of the contact to delete.
900 * @param bool $restore
901 * Whether to actually restore, not delete.
902 * @param bool $skipUndelete
903 * Whether to force contact delete or not.
904 * @param bool $checkPermissions
907 * Was contact deleted?
909 * @throws \CRM_Core_Exception
910 * @throws \CiviCRM_API3_Exception
912 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
914 if (!$id ||
!is_numeric($id)) {
915 CRM_Core_Error
::deprecatedFunctionWarning('calling delete contact without a valid contact ID is deprecated.');
918 // If trash is disabled in system settings then we always skip
919 if (!Civi
::settings()->get('contact_undelete')) {
920 $skipUndelete = TRUE;
923 // make sure we have edit permission for this contact
925 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
926 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
932 // Restrict contact to be delete if contact has financial trxns
934 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent([$id], $error)) {
938 // make sure this contact_id does not have any membership types
939 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
942 'member_of_contact_id'
944 if ($membershipTypeID) {
948 $contact = new CRM_Contact_DAO_Contact();
950 if (!$contact->find(TRUE)) {
954 $contactType = $contact->contact_type
;
956 // @todo deprecate calling contactDelete with the intention to restore.
958 'id' => $contact->id
,
959 'is_deleted' => FALSE,
961 self
::create($updateParams);
965 // start a new transaction
966 $transaction = new CRM_Core_Transaction();
969 $hookParams = ['check_permissions' => $checkPermissions];
970 CRM_Utils_Hook
::pre('delete', $contactType, $id, $hookParams);
972 //delete billing address if exists.
973 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
975 // delete the log entries since we dont have triggers enabled as yet
976 $logDAO = new CRM_Core_DAO_Log();
977 $logDAO->entity_table
= 'civicrm_contact';
978 $logDAO->entity_id
= $id;
981 // delete contact participants CRM-12155
982 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
984 // delete contact contributions CRM-12155
985 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
987 // do activity cleanup, CRM-5604
988 CRM_Activity_BAO_Activity
::cleanupActivity($id);
990 // delete all notes related to contact
991 CRM_Core_BAO_Note
::cleanContactNotes($id);
993 // delete cases related to contact
994 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
995 if (!empty($contactCases)) {
996 foreach ($contactCases as $caseId) {
997 //check if case is associate with other contact or not.
998 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
999 if (count($caseContactId) <= 1) {
1000 CRM_Case_BAO_Case
::deleteCase($caseId);
1008 self
::contactTrash($contact);
1010 // currently we only clear employer cache.
1011 // we are now deleting inherited membership if any.
1012 if ($contact->contact_type
== 'Organization') {
1013 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
1014 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
1015 if (!empty($relationshipDtls)) {
1016 foreach ($relationshipDtls as $rId => $details) {
1017 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
1020 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
1023 //delete the contact id from recently view
1024 CRM_Utils_Recent
::delContact($id);
1025 self
::updateContactCache($id, empty($restore));
1027 // delete any prevnext/dupe cache entry
1028 // These two calls are redundant in default deployments, but they're
1029 // meaningful if "prevnext" is memory-backed.
1030 Civi
::service('prevnext')->deleteItem($id);
1031 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1033 $transaction->commit();
1035 if ($skipUndelete) {
1036 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1043 * Action to update any caches relating to a recently update contact.
1045 * I was going to call this from delete as well as from create to ensure the delete is being
1046 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1047 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1048 * where the call involved a subquery that was locking the table.
1050 * @param int $contactID
1051 * @param bool $isTrashed
1053 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1056 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1057 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1058 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1059 // but this should not cause any change as long as contacts are not being trashed outside the
1060 // main functions for that.
1061 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1064 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1069 * Delete the image of a contact.
1072 * Id of the contact.
1075 * Was contact image deleted?
1077 public static function deleteContactImage($id) {
1082 $contact = new self();
1084 $contact->image_URL
= 'null';
1091 * Return proportional height and width of the image.
1093 * @param int $imageWidth
1096 * @param int $imageHeight
1100 * Thumb dimension of image
1102 public static function getThumbSize($imageWidth, $imageHeight) {
1104 if ($imageWidth && $imageHeight) {
1105 $imageRatio = $imageWidth / $imageHeight;
1110 if ($imageRatio > 1) {
1111 $imageThumbWidth = $thumbWidth;
1112 $imageThumbHeight = round($thumbWidth / $imageRatio);
1115 $imageThumbHeight = $thumbWidth;
1116 $imageThumbWidth = round($thumbWidth * $imageRatio);
1119 return [$imageThumbWidth, $imageThumbHeight];
1123 * Validate type of contact image.
1125 * @param array $params
1126 * @param string $imageIndex
1127 * Index of image field.
1128 * @param string $statusMsg
1129 * Status message to be set after operation.
1130 * @param string $opType
1131 * Type of operation like fatal, bounce etc.
1134 * true if valid image extension
1136 public static function processImageParams(
1138 $imageIndex = 'image_URL',
1152 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1153 $photo = basename($params[$imageIndex]['name']);
1154 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1158 unset($params[$imageIndex]);
1160 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1162 if ($opType == 'status') {
1163 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1165 // FIXME: additional support for fatal, bounce etc could be added.
1171 * Extract contact id from url for deleting contact image.
1173 public static function processImage() {
1175 $action = CRM_Utils_Request
::retrieve('action', 'String');
1176 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1177 // retrieve contact id in case of Profile context
1178 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1179 $cid = $cid ?
$cid : $id;
1180 if ($action & CRM_Core_Action
::DELETE
) {
1181 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1182 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1183 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1184 $session = CRM_Core_Session
::singleton();
1185 $toUrl = $session->popUserContext();
1186 CRM_Utils_System
::redirect($toUrl);
1192 * Function to set is_delete true or restore deleted contact.
1194 * @param CRM_Contact_DAO_Contact $contact
1195 * Contact DAO object.
1196 * @param bool $restore
1197 * True to set the is_delete = 1 else false to restore deleted contact,
1198 * i.e. is_delete = 0
1203 * @throws \CRM_Core_Exception
1205 public static function contactTrashRestore($contact, $restore = FALSE) {
1206 CRM_Core_Error
::deprecatedFunctionWarning('Use the api');
1209 CRM_Core_Error
::deprecatedFunctionWarning('Use contact.create to restore - this does nothing much');
1210 // @todo deprecate calling contactDelete with the intention to restore.
1212 'id' => $contact->id
,
1213 'is_deleted' => FALSE,
1215 self
::create($updateParams);
1218 return self
::contactTrash($contact);
1222 * Get contact type for a contact.
1225 * Id of the contact whose contact type is needed.
1228 * contact_type if $id found else null ""
1230 public static function getContactType($id) {
1231 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1235 * Get contact sub type for a contact.
1238 * Id of the contact whose contact sub type is needed.
1240 * @param string $implodeDelimiter
1243 * contact_sub_type if $id found else null ""
1245 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1246 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1248 return $implodeDelimiter ?
NULL : [];
1251 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1253 if ($implodeDelimiter) {
1254 $subtype = implode($implodeDelimiter, $subtype);
1260 * Get pair of contact-type and sub-type for a contact.
1263 * Id of the contact whose contact sub/contact type is needed.
1267 public static function getContactTypes($id) {
1268 $params = ['id' => $id];
1270 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1273 ['contact_type', 'contact_sub_type']
1278 if ($contact->contact_sub_type
) {
1279 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1281 array_unshift($contactTypes, $contact->contact_type
);
1283 return $contactTypes;
1286 throw new CRM_Core_Exception();
1291 * Combine all the importable fields from the lower levels object.
1293 * The ordering is important, since currently we do not have a weight
1294 * scheme. Adding weight is super important
1296 * @param int|string $contactType contact Type
1297 * @param bool $status
1298 * Status is used to manipulate first title.
1299 * @param bool $showAll
1300 * If true returns all fields (includes disabled fields).
1301 * @param bool $isProfile
1302 * If its profile mode.
1303 * @param bool $checkPermission
1304 * If false, do not include permissioning clause (for custom data).
1306 * @param bool $withMultiCustomFields
1309 * array of importable Fields
1311 public static function importableFields(
1312 $contactType = 'Individual',
1316 $checkPermission = TRUE,
1317 $withMultiCustomFields = FALSE
1319 if (empty($contactType)) {
1320 $contactType = 'All';
1323 $cacheKeyString = "importableFields $contactType";
1324 $cacheKeyString .= $status ?
'_1' : '_0';
1325 $cacheKeyString .= $showAll ?
'_1' : '_0';
1326 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1327 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1328 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1330 $fields = self
::$_importableFields[$cacheKeyString] ?? Civi
::cache('fields')->get($cacheKeyString);
1333 $fields = CRM_Contact_DAO_Contact
::import();
1335 // get the fields thar are meant for contact types
1336 if (in_array($contactType, [
1342 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1345 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1346 CRM_Core_DAO_Phone
::import(),
1347 CRM_Core_DAO_Email
::import(),
1348 CRM_Core_DAO_IM
::import(TRUE),
1349 CRM_Core_DAO_OpenID
::import()
1352 $locationFields = array_merge($locationFields,
1353 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1361 foreach ($locationFields as $key => $field) {
1362 $locationFields[$key]['hasLocationType'] = TRUE;
1365 $fields = array_merge($fields, $locationFields);
1367 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1368 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1371 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1372 $fields['url']['hasWebsiteType'] = TRUE;
1374 if ($contactType != 'All') {
1375 $fields = array_merge($fields,
1376 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1381 $withMultiCustomFields
1384 // Unset the fields which are not related to their contact type.
1385 foreach (CRM_Contact_DAO_Contact
::import() as $name => $value) {
1386 if (!empty($value['contactType']) && $value['contactType'] !== $contactType) {
1387 unset($fields[$name]);
1392 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1393 $fields = array_merge($fields,
1394 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1399 $withMultiCustomFields
1406 $fields = array_merge($fields, [
1408 'title' => ts('Group(s)'),
1412 'title' => ts('Tag(s)'),
1416 'title' => ts('Note'),
1419 'communication_style_id' => [
1420 'title' => ts('Communication Style'),
1421 'name' => 'communication_style_id',
1426 //Sorting fields in alphabetical order(CRM-1507)
1427 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1429 Civi
::cache('fields')->set($cacheKeyString, $fields);
1432 self
::$_importableFields[$cacheKeyString] = $fields;
1436 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1437 self
::$_importableFields[$cacheKeyString]
1441 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1442 self
::$_importableFields[$cacheKeyString]
1450 * Combine all the exportable fields from the lower levels object.
1452 * Currently we are using importable fields as exportable fields
1454 * @param int|string $contactType contact Type
1455 * @param bool $status
1456 * True while exporting primary contacts.
1457 * @param bool $export
1458 * True when used during export.
1459 * @param bool $search
1460 * True when used during search, might conflict with export param?.
1462 * @param bool $withMultiRecord
1463 * @param bool $checkPermissions
1466 * array of exportable Fields
1468 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1469 if (empty($contactType)) {
1470 $contactType = 'All';
1473 $cacheKeyString = "exportableFields $contactType";
1474 $cacheKeyString .= $export ?
'_1' : '_0';
1475 $cacheKeyString .= $status ?
'_1' : '_0';
1476 $cacheKeyString .= $search ?
'_1' : '_0';
1477 $cacheKeyString .= '_' . (bool) $checkPermissions;
1478 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1479 //calculates custom fields takes into account the logged in user & caches that for all users
1480 //as an interim fix we will cache the fields by contact
1481 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1483 if (!self
::$_exportableFields ||
empty(self
::$_exportableFields[$cacheKeyString])) {
1484 if (!self
::$_exportableFields) {
1485 self
::$_exportableFields = [];
1488 // check if we can retrieve from database cache
1489 $fields = Civi
::cache('fields')->get($cacheKeyString);
1492 $fields = CRM_Contact_DAO_Contact
::export();
1494 // The fields are meant for contact types.
1495 if (in_array($contactType, [
1501 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1503 // add current employer for individuals
1504 $fields = array_merge($fields, [
1505 'current_employer' =>
1507 'name' => 'organization_name',
1508 'title' => ts('Current Employer'),
1509 'type' => CRM_Utils_Type
::T_STRING
,
1513 // This probably would be added anyway by appendPseudoConstantsToFields.
1515 'location_type' => [
1516 'name' => 'location_type',
1517 'where' => 'civicrm_location_type.name',
1518 'title' => ts('Location Type'),
1519 'type' => CRM_Utils_Type
::T_STRING
,
1525 'name' => 'im_provider',
1526 'where' => 'civicrm_im.provider_id',
1527 'title' => ts('IM Provider'),
1528 'type' => CRM_Utils_Type
::T_STRING
,
1532 $phoneFields = CRM_Core_DAO_Phone
::export();
1533 // This adds phone_type to the exportable fields and make it available for export.
1534 // with testing the same can be done to the other entities.
1535 CRM_Core_DAO
::appendPseudoConstantsToFields($phoneFields);
1536 $locationFields = array_merge($locationType,
1537 CRM_Core_DAO_Address
::export(),
1539 CRM_Core_DAO_Email
::export(),
1541 CRM_Core_DAO_IM
::export(TRUE),
1542 CRM_Core_DAO_OpenID
::export()
1545 $locationFields = array_merge($locationFields,
1546 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1549 foreach ($locationFields as $key => $field) {
1550 $locationFields[$key]['hasLocationType'] = TRUE;
1553 $fields = array_merge($fields, $locationFields);
1556 $fields = array_merge($fields,
1557 CRM_Core_DAO_Worldregion
::export()
1560 $fields = array_merge($fields,
1561 CRM_Contact_DAO_Contact
::export()
1565 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1567 if ($contactType != 'All') {
1568 $fields = array_merge($fields,
1569 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1573 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1574 $fields = array_merge($fields,
1575 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1581 $fields = array_merge($fields, [
1583 'title' => ts('Group(s)'),
1587 'title' => ts('Tag(s)'),
1591 'title' => ts('Note(s)'),
1597 $fields = array_merge($fields, [
1599 'title' => ts('Group(s)'),
1603 'title' => ts('Tag(s)'),
1607 'title' => ts('Note(s)'),
1613 //Sorting fields in alphabetical order(CRM-1507)
1614 foreach ($fields as $k => $v) {
1615 $sortArray[$k] = $v['title'] ??
NULL;
1618 $fields = array_merge($sortArray, $fields);
1619 //unset the field which are not related to their contact type.
1620 if ($contactType != 'All') {
1626 'organization_name',
1627 'email_greeting_custom',
1628 'postal_greeting_custom',
1641 'organization_name',
1649 'email_greeting_custom',
1650 'postal_greeting_custom',
1666 'email_greeting_custom',
1667 'postal_greeting_custom',
1677 foreach ($commonValues[$contactType] as $value) {
1678 unset($fields[$value]);
1682 Civi
::cache('fields')->set($cacheKeyString, $fields);
1684 self
::$_exportableFields[$cacheKeyString] = $fields;
1688 $fields = self
::$_exportableFields[$cacheKeyString];
1691 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1692 self
::$_exportableFields[$cacheKeyString]
1700 * Get the all contact details (Hierarchical).
1702 * @param int $contactId
1704 * @param array $fields
1710 public static function getHierContactDetails($contactId, $fields) {
1711 $params = [['contact_id', '=', $contactId, 0, 0]];
1713 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1715 // We don't know the contents of return properties, but we need the lower
1716 // level ids of the contact so add a few fields.
1717 $returnProperties['first_name'] = 1;
1718 $returnProperties['organization_name'] = 1;
1719 $returnProperties['household_name'] = 1;
1720 $returnProperties['contact_type'] = 1;
1721 $returnProperties['contact_sub_type'] = 1;
1722 list($query) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties);
1727 * Given a set of flat profile style field names, create a hierarchy.
1729 * This is for the query to use, create the right sql.
1732 * @param int $contactId
1736 * A hierarchical property tree if appropriate
1738 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1739 $locationTypes = CRM_Core_BAO_Address
::buildOptions('location_type_id', 'validate');
1741 $returnProperties = [];
1743 $multipleFields = ['website' => 'url'];
1744 foreach ($fields as $name => $dontCare) {
1745 if (strpos($name, '-') !== FALSE) {
1746 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1748 if (!in_array($fieldName, $multipleFields)) {
1749 if ($id == 'Primary') {
1750 $locationTypeName = 1;
1753 $locationTypeName = $locationTypes[$id] ??
NULL;
1754 if (!$locationTypeName) {
1759 if (empty($returnProperties['location'])) {
1760 $returnProperties['location'] = [];
1762 if (empty($returnProperties['location'][$locationTypeName])) {
1763 $returnProperties['location'][$locationTypeName] = [];
1764 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1766 if (in_array($fieldName, [
1774 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1777 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1780 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1781 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1784 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1788 $returnProperties['website'][$id][$fieldName] = 1;
1792 $returnProperties[$name] = 1;
1796 return $returnProperties;
1800 * Return the primary location type of a contact.
1802 * $params int $contactId contact_id
1803 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1804 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1806 * @param int $contactId
1807 * @param bool $skipDefaultPriamry
1808 * @param null $block
1811 * $locationType location_type_id
1813 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1815 $entityBlock = ['contact_id' => $contactId];
1816 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1817 foreach ($blocks[$block] as $key => $value) {
1818 if (!empty($value['is_primary'])) {
1819 $locationType = $value['location_type_id'] ??
NULL;
1826 IF ( civicrm_email.location_type_id IS NULL,
1827 IF ( civicrm_address.location_type_id IS NULL,
1828 IF ( civicrm_phone.location_type_id IS NULL,
1829 IF ( civicrm_im.location_type_id IS NULL,
1830 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1831 ,civicrm_im.location_type_id)
1832 ,civicrm_phone.location_type_id)
1833 ,civicrm_address.location_type_id)
1834 ,civicrm_email.location_type_id) as locationType
1835 FROM civicrm_contact
1836 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1837 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1838 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1839 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1840 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1841 WHERE civicrm_contact.id = %1 ";
1843 $params = [1 => [$contactId, 'Integer']];
1845 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1847 $locationType = NULL;
1848 if ($dao->fetch()) {
1849 $locationType = $dao->locationType
;
1852 if (isset($locationType)) {
1853 return $locationType;
1855 elseif ($skipDefaultPriamry) {
1856 // if there is no primary contact location then return null
1860 // if there is no primart contact location, then return default
1861 // location type of the system
1862 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1863 return $defaultLocationType->id
;
1868 * Get the display name, primary email and location type of a contact.
1871 * Id of the contact.
1874 * Array of display_name, email if found, do_not_email or (null,null,null)
1876 public static function getContactDetails($id) {
1877 // check if the contact type
1878 $contactType = self
::getContactType($id);
1880 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1883 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1884 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1885 WHERE civicrm_contact.id = %1
1886 ORDER BY civicrm_email.is_primary DESC";
1887 $params = [1 => [$id, 'Integer']];
1888 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1890 if ($dao->fetch()) {
1891 if ($contactType == 'Individual') {
1892 if ($dao->first_name ||
$dao->last_name
) {
1893 $name = "{$dao->first_name} {$dao->last_name}";
1896 $name = $dao->display_name
;
1900 $name = $dao->display_name
;
1902 $email = $dao->email
;
1903 $doNotEmail = (bool) $dao->do_not_email
;
1904 $onHold = (bool) $dao->on_hold
;
1905 $isDeceased = (bool) $dao->is_deceased
;
1906 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1908 return [NULL, NULL, NULL, NULL, NULL];
1912 * Add/edit/register contacts through profile.
1914 * @param array $params
1915 * Array of profile fields to be edited/added.
1916 * @param array $fields
1917 * Array of fields from UFGroup.
1918 * @param int $contactID
1919 * Id of the contact to be edited/added.
1920 * @param int $addToGroupID
1921 * Specifies the default group to which contact is added.
1922 * @param int $ufGroupId
1923 * Uf group id (profile id).
1924 * @param string $ctype
1925 * @param bool $visibility
1926 * Basically lets us know where this request is coming from.
1927 * if via a profile from web, we restrict what groups are changed
1930 * contact id created/edited
1932 * @throws \CRM_Core_Exception
1933 * @throws \CiviCRM_API3_Exception
1934 * @throws \Civi\API\Exception\UnauthorizedException
1936 public static function createProfileContact(
1940 $addToGroupID = NULL,
1945 // add ufGroupID to params array ( CRM-2012 )
1947 $params['uf_group_id'] = $ufGroupId;
1949 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1951 // If a user has logged in, or accessed via a checksum
1952 // Then deliberately 'blanking' a value in the profile should remove it from their record
1953 $session = CRM_Core_Session
::singleton();
1954 $params['updateBlankLocInfo'] = TRUE;
1955 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1956 $params['updateBlankLocInfo'] = FALSE;
1961 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1965 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1968 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1970 // manage is_opt_out
1971 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1972 $wasOptOut = $contactDetails['is_opt_out'] ??
FALSE;
1973 $isOptOut = $params['is_opt_out'];
1974 $data['is_opt_out'] = $isOptOut;
1975 // on change, create new civicrm_subscription_history entry
1976 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1978 'contact_id' => $contactDetails['contact_id'],
1979 'status' => $isOptOut ?
'Removed' : 'Added',
1982 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1986 $contact = self
::create($data);
1988 // contact is null if the profile does not have any contact fields
1990 $contactID = $contact->id
;
1993 if (empty($contactID)) {
1994 throw new CRM_Core_Exception('Cannot proceed without a valid contact id');
1997 // Process group and tag
1998 if (isset($params['group'])) {
2000 // this for sure means we are coming in via profile since i added it to fix
2001 // removing contacts from user groups -- lobo
2005 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2008 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2009 // Convert comma separated form values from select2 v3
2010 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2011 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2014 //to add profile in default group
2015 if (is_array($addToGroupID)) {
2016 $contactIds = [$contactID];
2017 foreach ($addToGroupID as $groupId) {
2018 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2021 elseif ($addToGroupID) {
2022 $contactIds = [$contactID];
2023 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2027 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2030 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2036 * Format profile contact parameters.
2038 * @param array $params
2040 * @param int $contactID
2041 * @param int $ufGroupId
2042 * @param null $ctype
2043 * @param bool $skipCustom
2047 public static function formatProfileContactParams(
2056 $data = $contactDetails = [];
2058 // get the contact details (hier)
2060 $details = self
::getHierContactDetails($contactID, $fields);
2062 $contactDetails = $details[$contactID];
2063 $data['contact_type'] = $contactDetails['contact_type'] ??
NULL;
2064 $data['contact_sub_type'] = $contactDetails['contact_sub_type'] ??
NULL;
2067 //we should get contact type only if contact
2069 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId, TRUE, FALSE, TRUE);
2071 //special case to handle profile with only contact fields
2072 if ($data['contact_type'] == 'Contact') {
2073 $data['contact_type'] = 'Individual';
2075 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2076 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2080 $data['contact_type'] = $ctype;
2083 $data['contact_type'] = 'Individual';
2087 //fix contact sub type CRM-5125
2088 if (array_key_exists('contact_sub_type', $params) &&
2089 !empty($params['contact_sub_type'])
2091 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2093 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2094 !empty($params['contact_sub_type_hidden'])
2096 // if profile was used, and had any subtype, we obtain it from there
2097 //CRM-13596 - add to existing contact types, rather than overwriting
2098 if (empty($data['contact_sub_type'])) {
2099 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2100 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2103 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2104 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2105 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2106 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2107 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2112 if ($ctype == 'Organization') {
2113 $data['organization_name'] = $contactDetails['organization_name'] ??
NULL;
2115 elseif ($ctype == 'Household') {
2116 $data['household_name'] = $contactDetails['household_name'] ??
NULL;
2124 $data['contact_id'] = $contactID;
2125 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2128 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2129 $defaultLocationId = $defaultLocation->id
;
2132 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2134 $blocks = ['email', 'phone', 'im', 'openid'];
2136 $multiplFields = ['url'];
2137 // prevent overwritten of formatted array, reset all block from
2138 // params if it is not in valid format (since import pass valid format)
2139 foreach ($blocks as $blk) {
2140 if (array_key_exists($blk, $params) &&
2141 !is_array($params[$blk])
2143 unset($params[$blk]);
2147 $primaryPhoneLoc = NULL;
2148 $session = CRM_Core_Session
::singleton();
2149 foreach ($params as $key => $value) {
2150 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2152 if ($locTypeId == 'Primary') {
2154 if (in_array($fieldName, $blocks)) {
2155 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2158 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2160 $primaryLocationType = $locTypeId;
2163 $locTypeId = $defaultLocationId;
2167 if (is_numeric($locTypeId) &&
2168 !in_array($fieldName, $multiplFields) &&
2169 substr($fieldName, 0, 7) != 'custom_'
2171 $index = $locTypeId;
2173 if (is_numeric($typeId)) {
2174 $index .= '-' . $typeId;
2176 if (!in_array($index, $locationType)) {
2177 $locationType[$count] = $index;
2181 $loc = CRM_Utils_Array
::key($index, $locationType);
2183 $blockName = self
::getLocationEntityForKey($fieldName);
2185 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2187 //set is_billing true, for location type "Billing"
2188 if ($locTypeId == $billingLocationTypeId) {
2189 $data[$blockName][$loc]['is_billing'] = 1;
2193 //get the primary location type
2194 if ($locTypeId == $primaryLocationType) {
2195 $data[$blockName][$loc]['is_primary'] = 1;
2198 elseif ($locTypeId == $defaultLocationId) {
2199 $data[$blockName][$loc]['is_primary'] = 1;
2202 if (in_array($fieldName, ['phone'])) {
2204 $data['phone'][$loc]['phone_type_id'] = $typeId;
2207 $data['phone'][$loc]['phone_type_id'] = '';
2209 $data['phone'][$loc]['phone'] = $value;
2211 //special case to handle primary phone with different phone types
2212 // in this case we make first phone type as primary
2213 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2214 $primaryPhoneLoc = $loc;
2217 if ($loc != $primaryPhoneLoc) {
2218 unset($data['phone'][$loc]['is_primary']);
2221 elseif ($fieldName == 'email') {
2222 $data['email'][$loc]['email'] = $value;
2223 if (empty($contactID)) {
2224 $data['email'][$loc]['is_primary'] = 1;
2227 elseif ($fieldName == 'im') {
2228 if (isset($params[$key . '-provider_id'])) {
2229 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2231 if (strpos($key, '-provider_id') !== FALSE) {
2232 $data['im'][$loc]['provider_id'] = $params[$key];
2235 $data['im'][$loc]['name'] = $value;
2238 elseif ($fieldName == 'openid') {
2239 $data['openid'][$loc]['openid'] = $value;
2242 if ($fieldName === 'state_province') {
2244 if (is_numeric($value) && ((int ) $value) >= 1000) {
2245 $data['address'][$loc]['state_province_id'] = $value;
2247 elseif (empty($value)) {
2248 $data['address'][$loc]['state_province_id'] = '';
2251 $data['address'][$loc]['state_province'] = $value;
2254 elseif ($fieldName === 'country') {
2256 if (is_numeric($value) && ((int ) $value) >= 1000
2258 $data['address'][$loc]['country_id'] = $value;
2260 elseif (empty($value)) {
2261 $data['address'][$loc]['country_id'] = '';
2264 $data['address'][$loc]['country'] = $value;
2267 elseif ($fieldName === 'county') {
2268 $data['address'][$loc]['county_id'] = $value;
2270 elseif ($fieldName == 'address_name') {
2271 $data['address'][$loc]['name'] = $value;
2273 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2274 $data['address'][$loc][substr($fieldName, 8)] = $value;
2277 $data[$blockName][$loc][$fieldName] = $value;
2282 if (substr($key, 0, 4) === 'url-') {
2283 $websiteField = explode('-', $key);
2284 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2285 $data['website'][$websiteField[1]]['url'] = $value;
2287 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2288 //save email/postal greeting and addressee values if any, CRM-4575
2289 $data[$key . '_id'] = $value;
2291 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2292 // for autocomplete transfer hidden value instead of label
2293 if ($params[$key] && isset($params[$key . '_id'])) {
2294 $value = $params[$key . '_id'];
2297 // we need to append time with date
2298 if ($params[$key] && isset($params[$key . '_time'])) {
2299 $value .= ' ' . $params[$key . '_time'];
2302 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2303 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2304 ($value == '' ||
!isset($value))
2310 if (!empty($params['customRecordValues'])) {
2311 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2312 foreach ($params['customRecordValues'] as $recId => $customFields) {
2313 if (is_array($customFields) && !empty($customFields)) {
2314 foreach ($customFields as $customFieldName) {
2315 if ($customFieldName == $key) {
2325 //CRM-13596 - check for contact_sub_type_hidden first
2326 if (array_key_exists('contact_sub_type_hidden', $params)) {
2327 $type = $params['contact_sub_type_hidden'];
2330 $type = $data['contact_type'];
2331 if (!empty($data['contact_sub_type'])) {
2332 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2336 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2346 elseif ($key === 'edit') {
2350 if ($key === 'location') {
2351 foreach ($value as $locationTypeId => $field) {
2352 foreach ($field as $block => $val) {
2353 if ($block === 'address' && array_key_exists('address_name', $val)) {
2354 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2359 if ($key === 'phone' && isset($params['phone_ext'])) {
2360 $data[$key] = $value;
2361 foreach ($value as $cnt => $phoneBlock) {
2362 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2363 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2367 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2368 && ($value == '' ||
!isset($value)) &&
2369 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2370 ($key === 'current_employer' && empty($params['current_employer']))) {
2371 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2372 // to avoid update with empty values
2376 $data[$key] = $value;
2382 if (!isset($data['contact_type'])) {
2383 $data['contact_type'] = 'Individual';
2386 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2387 $privacy = CRM_Core_SelectValues
::privacy();
2388 foreach ($privacy as $key => $value) {
2389 if (array_key_exists($key, $fields)) {
2390 // do not reset values for existing contacts, if fields are added to a profile
2391 if (array_key_exists($key, $params)) {
2392 $data[$key] = $params[$key];
2393 if (empty($params[$key])) {
2397 elseif (!$contactID) {
2403 return [$data, $contactDetails];
2407 * Find the get contact details.
2409 * This function does not respect ACLs for now, which might need to be rectified at some
2410 * stage based on how its used.
2412 * @param string $mail
2413 * Primary email address of the contact.
2414 * @param string $ctype
2417 * @return object|null
2418 * $dao contact details
2420 public static function matchContactOnEmail($mail, $ctype = NULL) {
2421 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2422 $mail = $strtolower(trim($mail));
2424 SELECT civicrm_contact.id as contact_id,
2425 civicrm_contact.hash as hash,
2426 civicrm_contact.contact_type as contact_type,
2427 civicrm_contact.contact_sub_type as contact_sub_type
2428 FROM civicrm_contact
2429 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2431 if (Civi
::settings()->get('uniq_email_per_site')) {
2432 // try to find a match within a site (multisite).
2433 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2434 if (!empty($groups)) {
2436 INNER JOIN civicrm_group_contact gc ON
2437 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2442 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2443 $p = [1 => [$mail, 'String']];
2446 $query .= " AND civicrm_contact.contact_type = %3";
2447 $p[3] = [$ctype, 'String'];
2450 $query .= " ORDER BY civicrm_email.is_primary DESC";
2452 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2454 if ($dao->fetch()) {
2461 * Find the contact details associated with an OpenID.
2463 * @param string $openId
2464 * OpenId of the contact.
2465 * @param string $ctype
2468 * @return object|null
2469 * $dao contact details
2471 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2472 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2473 $openId = $strtolower(trim($openId));
2475 SELECT civicrm_contact.id as contact_id,
2476 civicrm_contact.hash as hash,
2477 civicrm_contact.contact_type as contact_type,
2478 civicrm_contact.contact_sub_type as contact_sub_type
2479 FROM civicrm_contact
2480 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2481 WHERE civicrm_openid.openid = %1";
2482 $p = [1 => [$openId, 'String']];
2485 $query .= " AND civicrm_contact.contact_type = %3";
2486 $p[3] = [$ctype, 'String'];
2489 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2491 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2493 if ($dao->fetch()) {
2500 * Get primary email of the contact.
2502 * @param int $contactID
2504 * @param bool $polite
2505 * Whether to only pull an email if it's okay to send to it--that is, if it
2506 * is not on_hold and the contact is not do_not_email.
2509 * Email address if present else null
2511 public static function getPrimaryEmail($contactID, $polite = FALSE) {
2512 // fetch the primary email
2514 SELECT civicrm_email.email as email
2515 FROM civicrm_contact
2516 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2517 WHERE civicrm_email.is_primary = 1
2518 AND civicrm_contact.id = %1";
2521 AND civicrm_contact.do_not_email = 0
2522 AND civicrm_email.on_hold = 0';
2524 $p = [1 => [$contactID, 'Integer']];
2525 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2528 if ($dao->fetch()) {
2529 $email = $dao->email
;
2535 * Fetch the object and store the values in the values array.
2537 * @param array $params
2538 * Input parameters to find object.
2539 * @param array $values
2540 * Output values of the object.
2542 * @return CRM_Contact_BAO_Contact|null
2543 * The found object or null
2545 public static function getValues(&$params, &$values) {
2546 $contact = new CRM_Contact_BAO_Contact();
2548 $contact->copyValues($params);
2550 if ($contact->find(TRUE)) {
2552 CRM_Core_DAO
::storeValues($contact, $values);
2555 foreach (self
::$_commPrefs as $name) {
2556 if (isset($contact->$name)) {
2557 $privacy[$name] = $contact->$name;
2561 if (!empty($privacy)) {
2562 $values['privacy'] = $privacy;
2565 // communication Prefferance
2566 $preffComm = $comm = [];
2567 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2568 $contact->preferred_communication_method
2570 foreach ($comm as $value) {
2571 $preffComm[$value] = 1;
2573 $temp = ['preferred_communication_method' => $contact->preferred_communication_method
];
2576 'preferred_communication_method' => [
2577 'newName' => 'preferred_communication_method_display',
2578 'groupName' => 'preferred_communication_method',
2582 // @todo This can be figured out from metadata & we can avoid the uncached query.
2583 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2585 $values['preferred_communication_method'] = $preffComm;
2586 $values['preferred_communication_method_display'] = $temp['preferred_communication_method_display'] ??
NULL;
2588 if ($contact->preferred_mail_format
) {
2589 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2590 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2593 // get preferred languages
2594 if (!empty($contact->preferred_language
)) {
2595 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2598 // Calculating Year difference
2599 if ($contact->birth_date
) {
2600 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2601 if ($birthDate < date('Ymd')) {
2602 $age = CRM_Utils_Date
::calculateAge($birthDate);
2603 $values['age']['y'] = $age['years'] ??
NULL;
2604 $values['age']['m'] = $age['months'] ??
NULL;
2608 $contact->contact_id
= $contact->id
;
2616 * Given the component name and returns the count of participation of contact.
2618 * @param string $component
2619 * Input component name.
2620 * @param int $contactId
2622 * @param string $tableName
2623 * Optional tableName if component is custom group.
2626 * total number in database
2628 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2630 switch ($component) {
2632 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2635 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2636 CRM_Contact_BAO_Relationship
::CURRENT
,
2645 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2648 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2651 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2654 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2656 case 'contribution':
2657 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2660 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2663 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2666 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2669 return CRM_Case_BAO_Case
::caseCount($contactId);
2672 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2676 'contact_id' => $contactId,
2679 'context' => 'activity',
2681 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2684 $params = ['contact_id' => $contactId];
2685 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2688 $custom = explode('_', $component);
2689 if ($custom['0'] = 'custom') {
2691 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2693 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2694 return CRM_Core_DAO
::singleValueQuery($queryString);
2700 * Update contact greetings if an update has resulted in a custom field change.
2702 * @param array $updatedFields
2703 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2704 * @param array $contactParams
2705 * Parameters known about the contact. At minimum array('contact_id' => x).
2706 * Fields in this array will take precedence over DB fields (so far only
2707 * in the case of greeting id fields).
2709 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2710 $contactID = $contactParams['contact_id'];
2711 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2712 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2713 if (!empty($tokens['all']['contact'])) {
2714 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2715 if (!empty($affectedTokens)) {
2716 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2717 $contact = new CRM_Contact_BAO_Contact();
2718 $contact->id
= $contactID;
2719 CRM_Contact_BAO_Contact
::processGreetings($contact);
2725 * Process greetings and cache.
2727 * @param object $contact
2728 * Contact object after save.
2730 public static function processGreetings(&$contact) {
2732 //@todo this function does a lot of unnecessary loading.
2733 // ensureGreetingParamsAreSet now makes sure that the contact is
2734 // loaded and using updateGreetingsOnTokenFieldChange
2735 // allows us the possibility of only doing an update if required.
2737 // The contact object has not always required the
2738 // fields that are required to calculate greetings
2739 // so we need to retrieve it again.
2740 if ($contact->_query
!== FALSE) {
2741 $contact->find(TRUE);
2744 // store object values to an array
2745 $contactDetails = [];
2746 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2747 $contactDetails = [[$contact->id
=> $contactDetails]];
2749 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2750 $updateQueryString = [];
2752 //cache email and postal greeting to greeting display
2753 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2754 $emailGreetingString = $contact->email_greeting_custom
;
2756 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2757 // the filter value for Individual contact type is set to 1
2759 'contact_type' => $contact->contact_type
,
2760 'greeting_type' => 'email_greeting',
2763 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2764 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2765 $updateQueryString[] = " email_greeting_custom = NULL ";
2768 if ($contact->email_greeting_custom
) {
2769 $updateQueryString[] = " email_greeting_display = NULL ";
2773 if ($emailGreetingString) {
2774 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2777 'CRM_Contact_BAO_Contact'
2779 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2780 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2784 if ($contact->postal_greeting_custom
!== 'null' && $contact->postal_greeting_custom
) {
2785 $postalGreetingString = $contact->postal_greeting_custom
;
2787 elseif ($contact->postal_greeting_id
!== 'null' && $contact->postal_greeting_id
) {
2789 'contact_type' => $contact->contact_type
,
2790 'greeting_type' => 'postal_greeting',
2792 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2793 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2794 $updateQueryString[] = " postal_greeting_custom = NULL ";
2797 if ($contact->postal_greeting_custom
) {
2798 $updateQueryString[] = " postal_greeting_display = NULL ";
2802 if ($postalGreetingString) {
2803 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2806 'CRM_Contact_BAO_Contact'
2808 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2809 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2813 if ($contact->addressee_custom
!== 'null' && $contact->addressee_custom
) {
2814 $addresseeString = $contact->addressee_custom
;
2816 elseif ($contact->addressee_id
!== 'null' && $contact->addressee_id
) {
2818 'contact_type' => $contact->contact_type
,
2819 'greeting_type' => 'addressee',
2822 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2823 $addresseeString = $addressee[$contact->addressee_id
];
2824 $updateQueryString[] = " addressee_custom = NULL ";
2827 if ($contact->addressee_custom
) {
2828 $updateQueryString[] = " addressee_display = NULL ";
2832 if ($addresseeString) {
2833 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2836 'CRM_Contact_BAO_Contact'
2838 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2839 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2842 if (!empty($updateQueryString)) {
2843 $updateQueryString = implode(',', $updateQueryString);
2844 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2845 CRM_Core_DAO
::executeQuery($queryString);
2850 * Retrieve loc block ids w/ given condition.
2852 * @param int $contactId
2854 * @param array $criteria
2855 * Key => value pair which should be.
2856 * fulfill by return record ids.
2857 * @param string $condOperator
2858 * Operator use for grouping multiple conditions.
2861 * loc block ids which fulfill condition.
2863 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2866 return $locBlockIds;
2869 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2870 $name = strtolower($block);
2871 $className = "CRM_Core_DAO_$block";
2872 $blockDAO = new $className();
2874 // build the condition.
2875 if (is_array($criteria)) {
2876 $fields = $blockDAO->fields();
2878 foreach ($criteria as $field => $value) {
2879 if (array_key_exists($field, $fields)) {
2880 $cond = "( $field = $value )";
2881 // value might be zero or null.
2882 if (!$value ||
strtolower($value) === 'null') {
2883 $cond = "( $field = 0 OR $field IS NULL )";
2885 $conditions[] = $cond;
2888 if (!empty($conditions)) {
2889 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2893 $blockDAO->contact_id
= $contactId;
2895 while ($blockDAO->fetch()) {
2896 $locBlockIds[$name][] = $blockDAO->id
;
2900 return $locBlockIds;
2904 * Build context menu items.
2906 * @param int $contactId
2909 * Array of context menu for logged in user.
2911 public static function contextMenu($contactId = NULL) {
2914 'title' => ts('View Contact'),
2916 'ref' => 'view-contact',
2917 'class' => 'no-popup',
2919 'permissions' => ['view all contacts'],
2922 'title' => ts('Edit Contact'),
2924 'ref' => 'edit-contact',
2925 'class' => 'no-popup',
2927 'permissions' => ['edit all contacts'],
2930 'title' => ts('Delete Contact'),
2932 'ref' => 'delete-contact',
2934 'permissions' => ['access deleted contacts', 'delete contacts'],
2937 'title' => ts('Add Contribution'),
2939 'ref' => 'new-contribution',
2940 'key' => 'contribution',
2941 'tab' => 'contribute',
2942 'component' => 'CiviContribute',
2943 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2944 'reset=1&action=add&context=contribution'
2947 'access CiviContribute',
2948 'edit contributions',
2952 'title' => ts('Register for Event'),
2954 'ref' => 'new-participant',
2955 'key' => 'participant',
2956 'tab' => 'participant',
2957 'component' => 'CiviEvent',
2958 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2961 'edit event participants',
2965 'title' => ts('Record Activity'),
2967 'ref' => 'new-activity',
2968 'key' => 'activity',
2969 'permissions' => ['edit all contacts'],
2972 'title' => ts('Add Pledge'),
2974 'ref' => 'new-pledge',
2977 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2978 'reset=1&action=add&context=pledge'
2980 'component' => 'CiviPledge',
2982 'access CiviPledge',
2987 'title' => ts('Add Membership'),
2989 'ref' => 'new-membership',
2990 'key' => 'membership',
2992 'component' => 'CiviMember',
2993 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
2994 'reset=1&action=add&context=membership'
2997 'access CiviMember',
3002 'title' => ts('Add Case'),
3004 'ref' => 'new-case',
3007 'component' => 'CiviCase',
3008 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3009 'permissions' => ['add cases'],
3012 'title' => ts('Add Grant'),
3014 'ref' => 'new-grant',
3017 'component' => 'CiviGrant',
3018 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3019 'reset=1&action=add&context=grant'
3021 'permissions' => ['edit grants'],
3024 'title' => ts('Add Relationship'),
3026 'ref' => 'new-relationship',
3029 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3030 'reset=1&action=add'
3032 'permissions' => ['edit all contacts'],
3035 'title' => ts('Add Note'),
3037 'ref' => 'new-note',
3040 'class' => 'medium-popup',
3041 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3042 'reset=1&action=add'
3044 'permissions' => ['edit all contacts'],
3047 'title' => ts('Send an Email'),
3049 'ref' => 'new-email',
3051 'permissions' => ['view all contacts'],
3054 'title' => ts('Add to Group'),
3056 'ref' => 'group-add-contact',
3059 'permissions' => ['edit groups'],
3062 'title' => ts('Tag Contact'),
3064 'ref' => 'tag-contact',
3067 'permissions' => ['edit all contacts'],
3071 $menu['otherActions'] = [
3073 'title' => ts('Print Summary'),
3074 'description' => ts('Printer-friendly view of this page.'),
3076 'ref' => 'crm-contact-print',
3079 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3083 'icon' => 'crm-i fa-print',
3086 'title' => ts('vCard'),
3087 'description' => ts('vCard record for this contact.'),
3089 'ref' => 'crm-contact-vcard',
3092 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3096 'icon' => 'crm-i fa-list-alt',
3100 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3101 $menu['otherActions']['dashboard'] = [
3102 'title' => ts('Contact Dashboard'),
3103 'description' => ts('Contact Dashboard'),
3105 'ref' => 'crm-contact-dashboard',
3106 'key' => 'dashboard',
3107 'tab' => 'dashboard',
3108 'class' => 'dashboard',
3109 // NOTE: As an alternative you can also build url on CMS specific way
3110 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3111 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3112 'icon' => 'crm-i fa-tachometer',
3116 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3118 $menu['otherActions']['user-record'] = [
3119 'title' => ts('User Record'),
3120 'description' => ts('User Record'),
3122 'ref' => 'crm-contact-user-record',
3123 'key' => 'user-record',
3124 'tab' => 'user-record',
3125 'class' => 'user-record',
3126 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3127 'icon' => 'crm-i fa-user',
3130 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3131 $menu['otherActions']['user-add'] = [
3132 'title' => ts('Create User Record'),
3133 'description' => ts('Create User Record'),
3135 'ref' => 'crm-contact-user-add',
3136 'key' => 'user-add',
3137 'tab' => 'user-add',
3138 'class' => 'user-add',
3139 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3140 'icon' => 'crm-i fa-user-plus',
3144 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3145 //1. check for component is active.
3146 //2. check for user permissions.
3147 //3. check for acls.
3148 //3. edit and view contact are directly accessible to user.
3150 $aclPermissionedTasks = [
3155 'group-add-contact',
3159 $corePermission = CRM_Core_Permission
::getPermission();
3162 foreach ($menu as $key => $values) {
3163 if ($key !== 'otherActions') {
3165 // user does not have necessary permissions.
3166 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3169 // build directly accessible action menu.
3170 if (in_array($values['ref'], [
3174 $contextMenu['primaryActions'][$key] = [
3175 'title' => $values['title'],
3176 'ref' => $values['ref'],
3177 'class' => $values['class'] ??
NULL,
3178 'key' => $values['key'],
3183 // finally get menu item for -more- action widget.
3184 while (!empty($contextMenu['moreActions'][$values['weight']])) {
3185 // Quick & dirty way of handling 2 items with the same weight
3186 // without clobbering one.
3187 $values['weight']++
;
3189 $contextMenu['moreActions'][$values['weight']] = [
3190 'title' => $values['title'],
3191 'ref' => $values['ref'],
3192 'href' => $values['href'] ??
NULL,
3193 'tab' => $values['tab'] ??
NULL,
3194 'class' => $values['class'] ??
NULL,
3195 'key' => $values['key'],
3199 foreach ($values as $value) {
3200 // user does not have necessary permissions.
3201 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3205 // finally get menu item for -more- action widget.
3206 while (!empty($contextMenu['otherActions'][$value['weight']])) {
3207 // Quick & dirty way of handling 2 items with the same weight
3208 // without clobbering one.
3211 $contextMenu['otherActions'][$value['weight']] = [
3212 'title' => $value['title'],
3213 'ref' => $value['ref'],
3214 'href' => $value['href'] ??
NULL,
3215 'tab' => $value['tab'] ??
NULL,
3216 'class' => $value['class'] ??
NULL,
3217 'icon' => $value['icon'] ??
NULL,
3218 'key' => $value['key'],
3224 ksort($contextMenu['moreActions']);
3225 ksort($contextMenu['otherActions']);
3227 return $contextMenu;
3231 * Check if user has permissions to access items in action menu.
3233 * @param array $aclPermissionedTasks
3234 * Array containing ACL related tasks.
3235 * @param string $corePermission
3236 * The permission of the user (edit or view or null).
3237 * @param array $menuOptions
3238 * Array containing params of the menu (title, href, etc).
3241 * TRUE if user has all permissions, FALSE if otherwise.
3243 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3244 $componentName = $menuOptions['component'] ??
NULL;
3246 // if component action - make sure component is enable.
3247 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3251 // make sure user has all required permissions.
3252 $hasAllPermissions = FALSE;
3254 $permissions = $menuOptions['permissions'] ??
NULL;
3255 if (!is_array($permissions) ||
empty($permissions)) {
3256 $hasAllPermissions = TRUE;
3259 // iterate for required permissions in given permissions array.
3260 if (!$hasAllPermissions) {
3261 $hasPermissions = 0;
3262 foreach ($permissions as $permission) {
3263 if (CRM_Core_Permission
::check($permission)) {
3268 if (count($permissions) == $hasPermissions) {
3269 $hasAllPermissions = TRUE;
3272 // if still user does not have required permissions, check acl.
3273 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3274 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3275 $corePermission == CRM_Core_Permission
::EDIT
3277 $hasAllPermissions = TRUE;
3279 elseif (in_array($menuOptions['ref'], [
3282 // grant permissions for these tasks.
3283 $hasAllPermissions = TRUE;
3288 return $hasAllPermissions;
3292 * Retrieve display name of contact that address is shared.
3294 * This is based on $masterAddressId or $contactId .
3296 * @param int $masterAddressId
3298 * @param int $contactId
3299 * Contact id. (deprecated - do not use)
3301 * @return string|null
3302 * the found display name or null.
3304 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3305 $masterDisplayName = NULL;
3306 if (!$masterAddressId) {
3307 return $masterDisplayName;
3311 SELECT display_name from civicrm_contact
3312 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3313 WHERE civicrm_address.id = " . $masterAddressId;
3315 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3316 return $masterDisplayName;
3320 * Get the creation/modification times for a contact.
3322 * @param int $contactId
3325 * Dates - ('created_date' => $, 'modified_date' => $)
3327 public static function getTimestamps($contactId) {
3328 $timestamps = CRM_Core_DAO
::executeQuery(
3329 'SELECT created_date, modified_date
3330 FROM civicrm_contact
3333 1 => [$contactId, 'Integer'],
3336 if ($timestamps->fetch()) {
3338 'created_date' => $timestamps->created_date
,
3339 'modified_date' => $timestamps->modified_date
,
3348 * Get a list of triggers for the contact table.
3351 * @param null $tableName
3353 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3355 * @see hook_civicrm_triggerInfo
3356 * @see CRM_Core_DAO::triggerRebuild
3358 public static function triggerInfo(&$info, $tableName = NULL) {
3360 // Modifications to these records should update the contact timestamps.
3361 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3363 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3364 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3365 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3366 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3367 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3369 ->alterTriggerInfo($info, $tableName);
3371 // Update phone table to populate phone_numeric field
3372 if (!$tableName ||
$tableName == 'civicrm_phone') {
3373 // Define stored sql function needed for phones
3374 $sqlTriggers = Civi
::service('sql_triggers');
3375 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3376 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3378 'table' => ['civicrm_phone'],
3380 'event' => ['INSERT', 'UPDATE'],
3381 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3387 * Check if contact is being used in civicrm_domain based on $contactId.
3389 * @param int $contactId
3393 * true if present else false.
3395 public static function checkDomainContact($contactId) {
3399 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3410 * Get options for a given contact field.
3412 * @param string $fieldName
3413 * @param string $context
3414 * @param array $props
3415 * whatever is known about this dao object.
3417 * @return array|bool
3418 * @see CRM_Core_DAO::buildOptions
3420 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3421 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3423 * @see CRM_Core_DAO::buildOptionsContext
3425 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3427 // Special logic for fields whose options depend on context or properties
3428 switch ($fieldName) {
3429 case 'contact_sub_type':
3430 if (!empty($props['contact_type'])) {
3431 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3435 case 'contact_type':
3436 if ($context == 'search') {
3437 // CRM-15495 - EntityRef filters and basic search forms expect this format
3438 // FIXME: Search builder does not
3439 return CRM_Contact_BAO_ContactType
::getSelectElements();
3443 // The contact api supports some related entities so we'll honor that by fetching their options
3446 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3450 $props['entity_table'] = 'civicrm_contact';
3451 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3453 case 'state_province_id':
3454 case 'state_province':
3455 case 'state_province_name':
3460 case 'worldregion_id':
3461 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3464 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3468 * Delete a contact-related object that has an 'is_primary' field.
3470 * Ensures that is_primary gets assigned to another object if available
3471 * Also calls pre/post hooks
3473 * @param string $type
3478 public static function deleteObjectWithPrimary($type, $id) {
3479 if (!$id ||
!is_numeric($id)) {
3482 $daoName = "CRM_Core_DAO_$type";
3483 $obj = new $daoName();
3487 if ($obj->fetch()) {
3488 CRM_Utils_Hook
::pre('delete', $type, $id);
3489 $contactId = $obj->contact_id
;
3495 // is_primary is only relavent if this field belongs to a contact
3497 $dao = new $daoName();
3498 $dao->contact_id
= $contactId;
3499 $dao->is_primary
= 1;
3500 // Pick another record to be primary (if one isn't already)
3501 if (!$dao->find(TRUE)) {
3502 $dao->is_primary
= 0;
3504 if ($dao->fetch()) {
3505 $dao->is_primary
= 1;
3507 if ($type === 'Email') {
3508 CRM_Core_BAO_UFMatch
::updateUFName($dao->contact_id
);
3513 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3520 public function addSelectWhereClause() {
3521 // We always return an array with these keys, even if they are empty,
3522 // because this tells the query builder that we have considered these fields for acls
3524 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3525 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
[] : ['!= 1'],
3527 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3532 * Get any existing duplicate contacts based on the input parameters.
3534 * @param array $input
3535 * Input parameters to be matched.
3536 * @param string $contactType
3537 * @param string $rule
3540 * @param $excludedContactIDs
3541 * An array of ids not to be included in the results.
3542 * @param bool $checkPermissions
3543 * @param int $ruleGroupID
3544 * ID of the rule group to be used if an override is desirable.
3545 * @param array $contextParams
3546 * The context if relevant, eg. ['event_id' => X]
3550 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3551 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3552 $dedupeParams['check_permission'] = $checkPermissions;
3553 $dedupeParams['contact_type'] = $contactType;
3554 $dedupeParams['rule'] = $rule;
3555 $dedupeParams['rule_group_id'] = $ruleGroupID;
3556 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3557 $dedupeResults['ids'] = [];
3558 $dedupeResults['handled'] = FALSE;
3559 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3560 if (!$dedupeResults['handled']) {
3561 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3563 return $dedupeResults['ids'];
3567 * Get the first duplicate contacts based on the input parameters.
3569 * @param array $input
3570 * Input parameters to be matched.
3571 * @param string $contactType
3572 * @param string $rule
3575 * @param $excludedContactIDs
3576 * An array of ids not to be included in the results.
3577 * @param bool $checkPermissions
3578 * @param int $ruleGroupID
3579 * ID of the rule group to be used if an override is desirable.
3580 * @param array $contextParams
3581 * The context if relevant, eg. ['event_id' => X]
3585 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3586 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3594 * Check if a field is associated with an entity that has a location type.
3596 * (ie. is an address, phone, email etc field).
3598 * @param string $fieldTitle
3599 * Title of the field (not the name - create a new function for that if required).
3603 public static function isFieldHasLocationType($fieldTitle) {
3604 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3605 if ($field['title'] === $fieldTitle) {
3606 return $field['hasLocationType'] ??
NULL;
3613 * @param array $appendProfiles
3614 * Name of profile(s) to append to each link.
3618 public static function getEntityRefCreateLinks($appendProfiles = []) {
3619 // You'd think that "create contacts" would be the permission to check,
3620 // But new contact popups are profile forms and those use their own permissions.
3621 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3625 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3626 $profiles[] = 'new_' . strtolower($contactType);
3628 $retrieved = civicrm_api3('uf_group', 'get', [
3629 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3632 $links = $append = [];
3633 if (!empty($retrieved['values'])) {
3635 'individual' => 'fa-user',
3636 'organization' => 'fa-building',
3637 'household' => 'fa-home',
3639 foreach ($retrieved['values'] as $id => $profile) {
3640 if (in_array($profile['name'], $profiles)) {
3642 'label' => $profile['title'],
3643 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3644 NULL, NULL, FALSE, FALSE, TRUE),
3645 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3646 'icon' => $icons[str_replace('new_', '', $profile['name'])] ??
NULL,
3653 foreach ($append as $id) {
3654 foreach ($links as &$link) {
3655 $link['url'] .= ",$id";
3665 public static function getEntityRefFilters() {
3667 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3668 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3669 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3670 ['key' => 'city', 'value' => ts('City'), 'type' => 'text', 'entity' => 'Address'],
3671 ['key' => 'postal_code', 'value' => ts('Postal Code'), 'type' => 'text', 'entity' => 'Address'],
3672 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3673 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3674 ['key' => 'first_name', 'value' => ts('First Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3675 ['key' => 'last_name', 'value' => ts('Last Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3676 ['key' => 'nick_name', 'value' => ts('Nick Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3677 ['key' => 'organization_name', 'value' => ts('Employer name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3678 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3679 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3680 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3681 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3682 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],