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 if (strlen($contact->display_name
) > 128) {
161 $contact->display_name
= substr($contact->display_name
, 0, 128);
163 if (strlen($contact->sort_name
) > 128) {
164 $contact->sort_name
= substr($contact->sort_name
, 0, 128);
167 $privacy = $params['privacy'] ??
NULL;
168 if ($privacy && is_array($privacy)) {
170 foreach (self
::$_commPrefs as $name) {
171 $contact->$name = $privacy[$name] ??
FALSE;
175 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
176 // @todo - does this mean we can remove this block?
177 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
178 if ((!isset($contact->hash
) ||
!$contact->hash
) && !$contact->id
) {
180 $contact->hash
= md5(uniqid(rand(), TRUE));
183 // Even if we don't need $employerId, it's important to call getFieldValue() before
184 // the contact is saved because we want the existing value to be cached.
185 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
186 $employerId = (!$contactID ||
$contact->contact_type
!== 'Individual') ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
191 CRM_Core_BAO_Log
::register($contact->id
,
197 if ($contact->contact_type
=== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
198 // Create current employer.
199 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : $params['current_employer'] ??
NULL;
201 $newContact = empty($params['contact_id']);
203 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
205 elseif ($employerId) {
206 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
210 // Update cached employer name if the name of an existing organization is being updated.
211 if ($contact->contact_type
=== 'Organization' && !empty($params['organization_name']) && $contactID) {
212 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
221 * takes an associative array and creates a contact object and all the associated
222 * derived objects (i.e. individual, location, email, phone etc)
224 * This function is invoked from within the web form layer and also from the api layer
226 * @param array $params
227 * (reference ) an assoc array of name/value pairs.
228 * @param bool $fixAddress
229 * If we need to fix address.
230 * @param bool $invokeHooks
231 * If we need to invoke hooks.
233 * @param bool $skipDelete
234 * Unclear parameter, passed to website create
236 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
237 * Created or updated contribution object. We are deprecating returning an error in
238 * favour of exceptions
240 * @throws \CRM_Core_Exception
241 * @throws \CiviCRM_API3_Exception
242 * @throws \Civi\API\Exception\UnauthorizedException
244 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
246 if (empty($params['contact_type']) && empty($params['contact_id'])) {
250 $isEdit = !empty($params['contact_id']);
252 if ($isEdit && empty($params['contact_type'])) {
253 $params['contact_type'] = self
::getContactType($params['contact_id']);
256 if (!empty($params['check_permissions']) && isset($params['api_key'])
257 && !CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])
258 && !($isEdit && CRM_Core_Permission
::check('edit own api keys') && $params['contact_id'] == CRM_Core_Session
::getLoggedInContactID())
260 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify api key');
264 if (!empty($params['contact_id'])) {
265 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
268 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
272 self
::ensureGreetingParamsAreSet($params);
274 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
275 if (empty($params['contact_id'])) {
276 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
277 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
278 $params['preferred_language'] = $language;
281 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
282 if (empty($params['communication_style_id'])) {
283 $defaultCommunicationStyleId = CRM_Core_OptionGroup
::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
284 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
288 $transaction = new CRM_Core_Transaction();
290 $contact = self
::add($params);
292 $params['contact_id'] = $contact->id
;
294 if (Civi
::settings()->get('is_enabled')) {
295 // Enabling multisite causes the contact to be added to the domain group.
296 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
297 if (!empty($domainGroupID)) {
298 if (!empty($params['group']) && is_array($params['group'])) {
299 $params['group'][$domainGroupID] = 1;
302 $params['group'] = [$domainGroupID => 1];
307 if (!empty($params['group'])) {
308 $contactIds = [$params['contact_id']];
309 foreach ($params['group'] as $groupId => $flag) {
311 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
313 elseif ($flag == -1) {
314 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
319 // Add location Block data.
320 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
321 foreach ($blocks as $name => $value) {
322 $contact->$name = $value;
324 if (!empty($params['updateBlankLocInfo'])) {
328 if (isset($params['website'])) {
329 CRM_Core_BAO_Website
::process($params['website'], $contact->id
, $skipDelete);
332 $userID = CRM_Core_Session
::singleton()->get('userID');
334 if (!empty($params['note'])) {
335 if (is_array($params['note'])) {
336 foreach ($params['note'] as $note) {
337 $contactId = $contact->id
;
338 if (isset($note['contact_id'])) {
339 $contactId = $note['contact_id'];
341 //if logged in user, overwrite contactId
343 $contactId = $userID;
347 'entity_id' => $contact->id
,
348 'entity_table' => 'civicrm_contact',
349 'note' => $note['note'],
350 'subject' => $note['subject'] ??
NULL,
351 'contact_id' => $contactId,
353 CRM_Core_BAO_Note
::add($noteParams);
357 $contactId = $contact->id
;
358 //if logged in user, overwrite contactId
360 $contactId = $userID;
364 'entity_id' => $contact->id
,
365 'entity_table' => 'civicrm_contact',
366 'note' => $params['note'],
367 'subject' => $params['subject'] ??
NULL,
368 'contact_id' => $contactId,
370 CRM_Core_BAO_Note
::add($noteParams);
374 // update the UF user_unique_id if that has changed
375 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
377 if (!empty($params['custom']) &&
378 is_array($params['custom'])
380 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
383 $transaction->commit();
385 // CRM-6367: fetch the right label for contact type’s display
386 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
387 'CRM_Contact_DAO_ContactType',
388 $contact->contact_type
,
393 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
397 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
400 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
404 // In order to prevent a series of expensive queries in intensive batch processing
405 // api calls may pass in skip_greeting_processing, probably doing it later via the
406 // scheduled job. CRM-21551
407 if (empty($params['skip_greeting_processing'])) {
408 self
::processGreetings($contact);
411 if (!empty($params['check_permissions'])) {
412 $contacts = [&$contact];
413 self
::unsetProtectedFields($contacts);
416 if (!empty($params['is_deceased'])) {
417 // Edit Membership Status
419 'contact_id' => $contact->id
,
420 'is_deceased' => $params['is_deceased'],
421 'deceased_date' => $params['deceased_date'] ??
NULL,
423 CRM_Member_BAO_Membership
::updateMembershipStatus($deceasedParams, $params['contact_type']);
430 * Format the output of the create contact function
432 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
434 public static function unsetProtectedFields(&$contacts) {
435 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
436 $currentUser = CRM_Core_Session
::getLoggedInContactID();
437 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
438 foreach ($contacts as &$contact) {
439 $cid = is_object($contact) ?
$contact->id
: $contact['id'] ??
NULL;
440 if (!($editOwn && $cid == $currentUser)) {
441 if (is_object($contact)) {
442 unset($contact->api_key
);
445 unset($contact['api_key']);
453 * Ensure greeting parameters are set.
455 * By always populating greetings here we can be sure they are set if required & avoid a call later.
456 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
458 * @param array $params
460 * @throws \CiviCRM_API3_Exception
462 public static function ensureGreetingParamsAreSet(&$params) {
463 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
464 $missingGreetingParams = [];
466 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
467 if (empty($params[$greetingParam])) {
468 $missingGreetingParams[$greetingIndex] = $greetingParam;
472 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
473 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
474 'id' => $params['contact_id'],
475 'return' => array_keys($missingGreetingParams),
478 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
479 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
480 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
483 // Filter out other fields.
484 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
485 $params = array_merge($params, $savedGreetings);
488 foreach ($missingGreetingParams as $greetingName => $greeting) {
489 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
493 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
494 if ($params[$greetingParam] === 'null') {
495 // If we are setting it to null then null out the display field.
496 $params[$greetingIndex . '_display'] = 'null';
502 * Get the display name and image of a contact.
507 * @param bool $includeTypeInReturnParameters
508 * Should type be part of the returned array?
511 * the displayName and contactImage for this contact
513 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
514 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
516 SELECT civicrm_contact.*,
517 civicrm_email.email as email
519 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
520 AND civicrm_email.is_primary = 1
521 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
522 $dao = new CRM_Core_DAO();
525 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
526 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
528 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
529 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
532 // use email if display_name is empty
533 if (empty($dao->display_name
)) {
534 $displayName = $dao->email
;
537 $displayName = $dao->display_name
;
540 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
542 return $includeTypeInReturnParameters ?
[
546 $dao->contact_sub_type
,
548 ] : [$displayName, $image, $imageUrl];
554 * Add billing fields to the params if appropriate.
556 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
557 * don't then we should set the name fields to the billing fields AND add the preserveDBName
558 * parameter (which will tell the BAO only to set those fields if none already exist.
560 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
561 * matching is best done by hipsters.
563 * @param array $params
565 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
567 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
568 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
569 foreach ($nameFields as $field) {
570 if (!empty($params[$field])) {
574 // There are only 3 - we can iterate through them twice :-)
575 foreach ($nameFields as $field) {
576 if (!empty($params['billing_' . $field])) {
577 $params[$field] = $params['billing_' . $field];
579 $params['preserveDBName'] = TRUE;
585 * Resolve a state province string (UT or Utah) to an ID.
587 * If country has been passed in we should select a state belonging to that country.
589 * Alternatively we should choose from enabled countries, prioritising the default country.
591 * @param array $values
592 * @param int|null $countryID
596 * @throws \CRM_Core_Exception
598 protected static function resolveStateProvinceID($values, $countryID) {
601 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
602 if (CRM_Utils_Array
::lookupValue($values,
607 return $values['state_province_id'];
609 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
610 if (CRM_Utils_Array
::lookupValue($values,
615 return $values['state_province_id'];
620 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
621 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
622 // prefer matching country..
623 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, ['country_id' => Civi
::settings()->get('defaultContactCountry')]);
624 if (CRM_Utils_Array
::lookupValue($values,
629 return $values['state_province_id'];
632 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
633 if (CRM_Utils_Array
::lookupValue($values,
638 return $values['state_province_id'];
641 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
642 if (CRM_Utils_Array
::lookupValue($values,
647 return $values['state_province_id'];
649 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
650 if (CRM_Utils_Array
::lookupValue($values,
655 return $values['state_province_id'];
663 * Get the relevant location entity for the array key.
665 * Based on the field name we determine which location entity
666 * we are dealing with. Apart from a few specific ones they
667 * are mostly 'address' (the default).
669 * @param string $fieldName
673 protected static function getLocationEntityForKey($fieldName) {
674 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
677 if ($fieldName === 'phone_ext') {
684 * Soft delete a contact.
686 * Call this via the api, not directly.
688 * @param \CRM_Contact_BAO_Contact $contact
691 * @throws \CRM_Core_Exception
693 protected static function contactTrash($contact): bool {
695 'id' => $contact->id
,
698 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
700 $params = [1 => [$contact->id
, 'Integer']];
701 $query = 'DELETE FROM civicrm_uf_match WHERE contact_id = %1';
702 CRM_Core_DAO
::executeQuery($query, $params);
704 $contact->copyValues($updateParams);
706 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
708 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
714 * Create last viewed link to recently updated contact.
716 * @param array $crudLinkSpec
717 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
718 * - entity_table: string, eg "civicrm_contact"
722 * NULL if unavailable, or
723 * [path: string, query: string, title: string]
724 * @see CRM_Utils_System::createDefaultCrudLink
726 public function createDefaultCrudLink($crudLinkSpec) {
727 switch ($crudLinkSpec['action']) {
728 case CRM_Core_Action
::VIEW
:
730 'title' => $this->display_name
,
731 'path' => 'civicrm/contact/view',
739 case CRM_Core_Action
::UPDATE
:
741 'title' => $this->display_name
,
742 'path' => 'civicrm/contact/add',
745 'action' => 'update',
755 * Get the values for pseudoconstants for name->value and reverse.
757 * @param array $defaults
758 * (reference) the default values, some of which need to be resolved.
759 * @param bool $reverse
760 * Always true as this function is only called from one place..
764 * This is called specifically from the contact import parser & should be moved there
765 * as it is not truly a generic function.
768 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
769 // Hack for birth_date.
770 if (!empty($defaults['birth_date'])) {
771 if (is_array($defaults['birth_date'])) {
772 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
776 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
777 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
778 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
779 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
781 //lookup value of email/postal greeting, addressee, CRM-4575
782 foreach (self
::$_greetingTypes as $greeting) {
784 'contact_type' => $defaults['contact_type'] ??
NULL,
785 'greeting_type' => $greeting,
787 CRM_Utils_Array
::lookupValue($defaults, $greeting,
788 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
792 $blocks = ['address', 'im', 'phone'];
793 foreach ($blocks as $name) {
794 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
797 foreach ($defaults[$name] as $count => & $values) {
799 //get location type id.
800 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
802 if ($name == 'address') {
803 // FIXME: lookupValue doesn't work for vcard_name
804 if (!empty($values['location_type_id'])) {
805 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', ['labelColumn' => 'vcard_name']);
806 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
809 if (!CRM_Utils_Array
::lookupValue($values,
811 CRM_Core_PseudoConstant
::country(),
816 CRM_Utils_Array
::lookupValue($values,
818 CRM_Core_PseudoConstant
::countryIsoCode(),
822 $stateProvinceID = self
::resolveStateProvinceID($values, $values['country_id'] ??
NULL);
823 if ($stateProvinceID) {
824 $values['state_province_id'] = $stateProvinceID;
827 if (!empty($values['state_province_id'])) {
828 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
831 $countyList = CRM_Core_PseudoConstant
::county();
833 CRM_Utils_Array
::lookupValue($values,
841 CRM_Utils_Array
::lookupValue($values,
843 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
848 if ($name == 'phone') {
849 CRM_Utils_Array
::lookupValue($values,
851 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
856 // Kill the reference.
863 * Fetch object based on array of properties.
865 * @param array $params
866 * (reference ) an assoc array of name/value pairs.
867 * @param array $defaults
868 * (reference ) an assoc array to hold the name / value pairs.
869 * in a hierarchical manner
870 * @param bool $microformat
871 * For location in microformat.
873 * @return CRM_Contact_BAO_Contact
875 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
876 if (array_key_exists('contact_id', $params)) {
877 $params['id'] = $params['contact_id'];
879 elseif (array_key_exists('id', $params)) {
880 $params['contact_id'] = $params['id'];
883 $contact = self
::getValues($params, $defaults);
885 unset($params['id']);
887 //get the block information for this contact
888 $entityBlock = ['contact_id' => $params['contact_id']];
889 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
890 $defaults = array_merge($defaults, $blocks);
891 foreach ($blocks as $block => $value) {
892 $contact->$block = $value;
895 if (!isset($params['noNotes'])) {
896 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
899 if (!isset($params['noRelationships'])) {
900 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
903 if (!isset($params['noGroups'])) {
904 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
907 if (!isset($params['noWebsite'])) {
908 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
915 * Get the display name of a contact.
920 * @return null|string
921 * display name of the contact if found
923 public static function displayName($id) {
926 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
933 * Delete a contact and all its associated records.
936 * Id of the contact to delete.
937 * @param bool $restore
938 * Whether to actually restore, not delete.
939 * @param bool $skipUndelete
940 * Whether to force contact delete or not.
941 * @param bool $checkPermissions
944 * Was contact deleted?
946 * @throws \CRM_Core_Exception
947 * @throws \CiviCRM_API3_Exception
949 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
951 if (!$id ||
!is_numeric($id)) {
952 CRM_Core_Error
::deprecatedFunctionWarning('calling delete contact without a valid contact ID is deprecated.');
955 // If trash is disabled in system settings then we always skip
956 if (!Civi
::settings()->get('contact_undelete')) {
957 $skipUndelete = TRUE;
960 // make sure we have edit permission for this contact
962 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
963 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
969 // Restrict contact to be delete if contact has financial trxns
971 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent([$id], $error)) {
975 // make sure this contact_id does not have any membership types
976 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
979 'member_of_contact_id'
981 if ($membershipTypeID) {
985 $contact = new CRM_Contact_DAO_Contact();
987 if (!$contact->find(TRUE)) {
991 $contactType = $contact->contact_type
;
993 // @todo deprecate calling contactDelete with the intention to restore.
995 'id' => $contact->id
,
996 'is_deleted' => FALSE,
998 self
::create($updateParams);
1002 // start a new transaction
1003 $transaction = new CRM_Core_Transaction();
1005 if ($skipUndelete) {
1006 $hookParams = ['check_permissions' => $checkPermissions];
1007 CRM_Utils_Hook
::pre('delete', $contactType, $id, $hookParams);
1009 //delete billing address if exists.
1010 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
1012 // delete the log entries since we dont have triggers enabled as yet
1013 $logDAO = new CRM_Core_DAO_Log();
1014 $logDAO->entity_table
= 'civicrm_contact';
1015 $logDAO->entity_id
= $id;
1018 // delete contact participants CRM-12155
1019 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
1021 // delete contact contributions CRM-12155
1022 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
1024 // do activity cleanup, CRM-5604
1025 CRM_Activity_BAO_Activity
::cleanupActivity($id);
1027 // delete all notes related to contact
1028 CRM_Core_BAO_Note
::cleanContactNotes($id);
1030 // delete cases related to contact
1031 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
1032 if (!empty($contactCases)) {
1033 foreach ($contactCases as $caseId) {
1034 //check if case is associate with other contact or not.
1035 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
1036 if (count($caseContactId) <= 1) {
1037 CRM_Case_BAO_Case
::deleteCase($caseId);
1045 self
::contactTrash($contact);
1047 // currently we only clear employer cache.
1048 // we are now deleting inherited membership if any.
1049 if ($contact->contact_type
== 'Organization') {
1050 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
1051 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
1052 if (!empty($relationshipDtls)) {
1053 foreach ($relationshipDtls as $rId => $details) {
1054 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
1057 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
1060 //delete the contact id from recently view
1061 CRM_Utils_Recent
::delContact($id);
1062 self
::updateContactCache($id, empty($restore));
1064 // delete any prevnext/dupe cache entry
1065 // These two calls are redundant in default deployments, but they're
1066 // meaningful if "prevnext" is memory-backed.
1067 Civi
::service('prevnext')->deleteItem($id);
1068 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1070 $transaction->commit();
1072 if ($skipUndelete) {
1073 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1080 * Action to update any caches relating to a recently update contact.
1082 * I was going to call this from delete as well as from create to ensure the delete is being
1083 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1084 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1085 * where the call involved a subquery that was locking the table.
1087 * @param int $contactID
1088 * @param bool $isTrashed
1090 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1093 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1094 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1095 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1096 // but this should not cause any change as long as contacts are not being trashed outside the
1097 // main functions for that.
1098 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1101 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1106 * Delete the image of a contact.
1109 * Id of the contact.
1112 * Was contact image deleted?
1114 public static function deleteContactImage($id) {
1119 $contact = new self();
1121 $contact->image_URL
= 'null';
1128 * Return proportional height and width of the image.
1130 * @param int $imageWidth
1133 * @param int $imageHeight
1137 * Thumb dimension of image
1139 public static function getThumbSize($imageWidth, $imageHeight) {
1141 if ($imageWidth && $imageHeight) {
1142 $imageRatio = $imageWidth / $imageHeight;
1147 if ($imageRatio > 1) {
1148 $imageThumbWidth = $thumbWidth;
1149 $imageThumbHeight = round($thumbWidth / $imageRatio);
1152 $imageThumbHeight = $thumbWidth;
1153 $imageThumbWidth = round($thumbWidth * $imageRatio);
1156 return [$imageThumbWidth, $imageThumbHeight];
1160 * Validate type of contact image.
1162 * @param array $params
1163 * @param string $imageIndex
1164 * Index of image field.
1165 * @param string $statusMsg
1166 * Status message to be set after operation.
1167 * @param string $opType
1168 * Type of operation like fatal, bounce etc.
1171 * true if valid image extension
1173 public static function processImageParams(
1175 $imageIndex = 'image_URL',
1189 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1190 $photo = basename($params[$imageIndex]['name']);
1191 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1195 unset($params[$imageIndex]);
1197 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1199 if ($opType == 'status') {
1200 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1202 // FIXME: additional support for fatal, bounce etc could be added.
1208 * Extract contact id from url for deleting contact image.
1210 public static function processImage() {
1212 $action = CRM_Utils_Request
::retrieve('action', 'String');
1213 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1214 // retrieve contact id in case of Profile context
1215 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1216 $cid = $cid ?
$cid : $id;
1217 if ($action & CRM_Core_Action
::DELETE
) {
1218 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1219 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1220 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1221 $session = CRM_Core_Session
::singleton();
1222 $toUrl = $session->popUserContext();
1223 CRM_Utils_System
::redirect($toUrl);
1229 * Function to set is_delete true or restore deleted contact.
1231 * @param CRM_Contact_DAO_Contact $contact
1232 * Contact DAO object.
1233 * @param bool $restore
1234 * True to set the is_delete = 1 else false to restore deleted contact,
1235 * i.e. is_delete = 0
1240 * @throws \CRM_Core_Exception
1242 public static function contactTrashRestore($contact, $restore = FALSE) {
1243 CRM_Core_Error
::deprecatedFunctionWarning('Use the api');
1246 CRM_Core_Error
::deprecatedFunctionWarning('Use contact.create to restore - this does nothing much');
1247 // @todo deprecate calling contactDelete with the intention to restore.
1249 'id' => $contact->id
,
1250 'is_deleted' => FALSE,
1252 self
::create($updateParams);
1255 return self
::contactTrash($contact);
1259 * Get contact type for a contact.
1262 * Id of the contact whose contact type is needed.
1265 * contact_type if $id found else null ""
1267 public static function getContactType($id) {
1268 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1272 * Get contact sub type for a contact.
1275 * Id of the contact whose contact sub type is needed.
1277 * @param string $implodeDelimiter
1280 * contact_sub_type if $id found else null ""
1282 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1283 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1285 return $implodeDelimiter ?
NULL : [];
1288 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1290 if ($implodeDelimiter) {
1291 $subtype = implode($implodeDelimiter, $subtype);
1297 * Get pair of contact-type and sub-type for a contact.
1300 * Id of the contact whose contact sub/contact type is needed.
1304 public static function getContactTypes($id) {
1305 $params = ['id' => $id];
1307 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1310 ['contact_type', 'contact_sub_type']
1315 if ($contact->contact_sub_type
) {
1316 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1318 array_unshift($contactTypes, $contact->contact_type
);
1320 return $contactTypes;
1323 throw new CRM_Core_Exception();
1328 * Combine all the importable fields from the lower levels object.
1330 * The ordering is important, since currently we do not have a weight
1331 * scheme. Adding weight is super important
1333 * @param int|string $contactType contact Type
1334 * @param bool $status
1335 * Status is used to manipulate first title.
1336 * @param bool $showAll
1337 * If true returns all fields (includes disabled fields).
1338 * @param bool $isProfile
1339 * If its profile mode.
1340 * @param bool $checkPermission
1341 * If false, do not include permissioning clause (for custom data).
1343 * @param bool $withMultiCustomFields
1346 * array of importable Fields
1348 public static function importableFields(
1349 $contactType = 'Individual',
1353 $checkPermission = TRUE,
1354 $withMultiCustomFields = FALSE
1356 if (empty($contactType)) {
1357 $contactType = 'All';
1360 $cacheKeyString = "importableFields $contactType";
1361 $cacheKeyString .= $status ?
'_1' : '_0';
1362 $cacheKeyString .= $showAll ?
'_1' : '_0';
1363 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1364 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1365 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1367 $fields = self
::$_importableFields[$cacheKeyString] ?? Civi
::cache('fields')->get($cacheKeyString);
1370 $fields = CRM_Contact_DAO_Contact
::import();
1372 // get the fields thar are meant for contact types
1373 if (in_array($contactType, [
1379 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1382 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1383 CRM_Core_DAO_Phone
::import(),
1384 CRM_Core_DAO_Email
::import(),
1385 CRM_Core_DAO_IM
::import(TRUE),
1386 CRM_Core_DAO_OpenID
::import()
1389 $locationFields = array_merge($locationFields,
1390 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1398 foreach ($locationFields as $key => $field) {
1399 $locationFields[$key]['hasLocationType'] = TRUE;
1402 $fields = array_merge($fields, $locationFields);
1404 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1405 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1408 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1409 $fields['url']['hasWebsiteType'] = TRUE;
1411 if ($contactType != 'All') {
1412 $fields = array_merge($fields,
1413 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1418 $withMultiCustomFields
1421 // Unset the fields which are not related to their contact type.
1422 foreach (CRM_Contact_DAO_Contact
::import() as $name => $value) {
1423 if (!empty($value['contactType']) && $value['contactType'] !== $contactType) {
1424 unset($fields[$name]);
1429 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1430 $fields = array_merge($fields,
1431 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1436 $withMultiCustomFields
1443 $fields = array_merge($fields, [
1445 'title' => ts('Group(s)'),
1449 'title' => ts('Tag(s)'),
1453 'title' => ts('Note'),
1456 'communication_style_id' => [
1457 'title' => ts('Communication Style'),
1458 'name' => 'communication_style_id',
1463 //Sorting fields in alphabetical order(CRM-1507)
1464 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1466 Civi
::cache('fields')->set($cacheKeyString, $fields);
1469 self
::$_importableFields[$cacheKeyString] = $fields;
1473 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1474 self
::$_importableFields[$cacheKeyString]
1478 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1479 self
::$_importableFields[$cacheKeyString]
1487 * Combine all the exportable fields from the lower levels object.
1489 * Currently we are using importable fields as exportable fields
1491 * @param int|string $contactType contact Type
1492 * @param bool $status
1493 * True while exporting primary contacts.
1494 * @param bool $export
1495 * True when used during export.
1496 * @param bool $search
1497 * True when used during search, might conflict with export param?.
1499 * @param bool $withMultiRecord
1500 * @param bool $checkPermissions
1503 * array of exportable Fields
1505 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1506 if (empty($contactType)) {
1507 $contactType = 'All';
1510 $cacheKeyString = "exportableFields $contactType";
1511 $cacheKeyString .= $export ?
'_1' : '_0';
1512 $cacheKeyString .= $status ?
'_1' : '_0';
1513 $cacheKeyString .= $search ?
'_1' : '_0';
1514 $cacheKeyString .= '_' . (bool) $checkPermissions;
1515 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1516 //calculates custom fields takes into account the logged in user & caches that for all users
1517 //as an interim fix we will cache the fields by contact
1518 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1520 if (!self
::$_exportableFields ||
empty(self
::$_exportableFields[$cacheKeyString])) {
1521 if (!self
::$_exportableFields) {
1522 self
::$_exportableFields = [];
1525 // check if we can retrieve from database cache
1526 $fields = Civi
::cache('fields')->get($cacheKeyString);
1529 $fields = CRM_Contact_DAO_Contact
::export();
1531 // The fields are meant for contact types.
1532 if (in_array($contactType, [
1538 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1540 // add current employer for individuals
1541 $fields = array_merge($fields, [
1542 'current_employer' =>
1544 'name' => 'organization_name',
1545 'title' => ts('Current Employer'),
1550 'location_type' => [
1551 'name' => 'location_type',
1552 'where' => 'civicrm_location_type.name',
1553 'title' => ts('Location Type'),
1559 'name' => 'im_provider',
1560 'where' => 'civicrm_im.provider_id',
1561 'title' => ts('IM Provider'),
1565 $phoneFields = CRM_Core_DAO_Phone
::export();
1566 // This adds phone_type to the exportable fields and make it available for export.
1567 // with testing the same can be done to the other entities.
1568 CRM_Core_DAO
::appendPseudoConstantsToFields($phoneFields);
1569 $locationFields = array_merge($locationType,
1570 CRM_Core_DAO_Address
::export(),
1572 CRM_Core_DAO_Email
::export(),
1574 CRM_Core_DAO_IM
::export(TRUE),
1575 CRM_Core_DAO_OpenID
::export()
1578 $locationFields = array_merge($locationFields,
1579 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1582 foreach ($locationFields as $key => $field) {
1583 $locationFields[$key]['hasLocationType'] = TRUE;
1586 $fields = array_merge($fields, $locationFields);
1589 $fields = array_merge($fields,
1590 CRM_Core_DAO_Worldregion
::export()
1593 $fields = array_merge($fields,
1594 CRM_Contact_DAO_Contact
::export()
1598 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1600 if ($contactType != 'All') {
1601 $fields = array_merge($fields,
1602 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1606 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1607 $fields = array_merge($fields,
1608 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1612 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1615 $fields = array_merge($fields, [
1617 'title' => ts('Group(s)'),
1621 'title' => ts('Tag(s)'),
1625 'title' => ts('Note(s)'),
1631 $fields = array_merge($fields, [
1633 'title' => ts('Group(s)'),
1637 'title' => ts('Tag(s)'),
1641 'title' => ts('Note(s)'),
1647 //Sorting fields in alphabetical order(CRM-1507)
1648 foreach ($fields as $k => $v) {
1649 $sortArray[$k] = $v['title'] ??
NULL;
1652 $fields = array_merge($sortArray, $fields);
1653 //unset the field which are not related to their contact type.
1654 if ($contactType != 'All') {
1660 'organization_name',
1661 'email_greeting_custom',
1662 'postal_greeting_custom',
1675 'organization_name',
1683 'email_greeting_custom',
1684 'postal_greeting_custom',
1700 'email_greeting_custom',
1701 'postal_greeting_custom',
1711 foreach ($commonValues[$contactType] as $value) {
1712 unset($fields[$value]);
1716 Civi
::cache('fields')->set($cacheKeyString, $fields);
1718 self
::$_exportableFields[$cacheKeyString] = $fields;
1722 $fields = self
::$_exportableFields[$cacheKeyString];
1725 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1726 self
::$_exportableFields[$cacheKeyString]
1734 * Get the all contact details (Hierarchical).
1736 * @param int $contactId
1738 * @param array $fields
1744 public static function getHierContactDetails($contactId, $fields) {
1745 $params = [['contact_id', '=', $contactId, 0, 0]];
1747 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1749 // We don't know the contents of return properties, but we need the lower
1750 // level ids of the contact so add a few fields.
1751 $returnProperties['first_name'] = 1;
1752 $returnProperties['organization_name'] = 1;
1753 $returnProperties['household_name'] = 1;
1754 $returnProperties['contact_type'] = 1;
1755 $returnProperties['contact_sub_type'] = 1;
1756 list($query) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties);
1761 * Given a set of flat profile style field names, create a hierarchy.
1763 * This is for the query to use, create the right sql.
1766 * @param int $contactId
1770 * A hierarchical property tree if appropriate
1772 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1773 $locationTypes = CRM_Core_BAO_Address
::buildOptions('location_type_id', 'validate');
1775 $returnProperties = [];
1777 $multipleFields = ['website' => 'url'];
1778 foreach ($fields as $name => $dontCare) {
1779 if (strpos($name, '-') !== FALSE) {
1780 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1782 if (!in_array($fieldName, $multipleFields)) {
1783 if ($id == 'Primary') {
1784 $locationTypeName = 1;
1787 $locationTypeName = $locationTypes[$id] ??
NULL;
1788 if (!$locationTypeName) {
1793 if (empty($returnProperties['location'])) {
1794 $returnProperties['location'] = [];
1796 if (empty($returnProperties['location'][$locationTypeName])) {
1797 $returnProperties['location'][$locationTypeName] = [];
1798 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1800 if (in_array($fieldName, [
1808 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1811 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1814 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1815 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1818 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1822 $returnProperties['website'][$id][$fieldName] = 1;
1826 $returnProperties[$name] = 1;
1830 return $returnProperties;
1834 * Return the primary location type of a contact.
1836 * $params int $contactId contact_id
1837 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1838 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1840 * @param int $contactId
1841 * @param bool $skipDefaultPriamry
1842 * @param null $block
1845 * $locationType location_type_id
1847 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1849 $entityBlock = ['contact_id' => $contactId];
1850 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1851 foreach ($blocks[$block] as $key => $value) {
1852 if (!empty($value['is_primary'])) {
1853 $locationType = $value['location_type_id'] ??
NULL;
1860 IF ( civicrm_email.location_type_id IS NULL,
1861 IF ( civicrm_address.location_type_id IS NULL,
1862 IF ( civicrm_phone.location_type_id IS NULL,
1863 IF ( civicrm_im.location_type_id IS NULL,
1864 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1865 ,civicrm_im.location_type_id)
1866 ,civicrm_phone.location_type_id)
1867 ,civicrm_address.location_type_id)
1868 ,civicrm_email.location_type_id) as locationType
1869 FROM civicrm_contact
1870 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1871 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1872 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1873 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1874 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1875 WHERE civicrm_contact.id = %1 ";
1877 $params = [1 => [$contactId, 'Integer']];
1879 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1881 $locationType = NULL;
1882 if ($dao->fetch()) {
1883 $locationType = $dao->locationType
;
1886 if (isset($locationType)) {
1887 return $locationType;
1889 elseif ($skipDefaultPriamry) {
1890 // if there is no primary contact location then return null
1894 // if there is no primart contact location, then return default
1895 // location type of the system
1896 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1897 return $defaultLocationType->id
;
1902 * Get the display name, primary email and location type of a contact.
1905 * Id of the contact.
1908 * Array of display_name, email if found, do_not_email or (null,null,null)
1910 public static function getContactDetails($id) {
1911 // check if the contact type
1912 $contactType = self
::getContactType($id);
1914 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1917 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1918 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1919 WHERE civicrm_contact.id = %1
1920 ORDER BY civicrm_email.is_primary DESC";
1921 $params = [1 => [$id, 'Integer']];
1922 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1924 if ($dao->fetch()) {
1925 if ($contactType == 'Individual') {
1926 if ($dao->first_name ||
$dao->last_name
) {
1927 $name = "{$dao->first_name} {$dao->last_name}";
1930 $name = $dao->display_name
;
1934 $name = $dao->display_name
;
1936 $email = $dao->email
;
1937 $doNotEmail = (bool) $dao->do_not_email
;
1938 $onHold = (bool) $dao->on_hold
;
1939 $isDeceased = (bool) $dao->is_deceased
;
1940 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1942 return [NULL, NULL, NULL, NULL, NULL];
1946 * Add/edit/register contacts through profile.
1948 * @param array $params
1949 * Array of profile fields to be edited/added.
1950 * @param array $fields
1951 * Array of fields from UFGroup.
1952 * @param int $contactID
1953 * Id of the contact to be edited/added.
1954 * @param int $addToGroupID
1955 * Specifies the default group to which contact is added.
1956 * @param int $ufGroupId
1957 * Uf group id (profile id).
1958 * @param string $ctype
1959 * @param bool $visibility
1960 * Basically lets us know where this request is coming from.
1961 * if via a profile from web, we restrict what groups are changed
1964 * contact id created/edited
1966 * @throws \CRM_Core_Exception
1967 * @throws \CiviCRM_API3_Exception
1968 * @throws \Civi\API\Exception\UnauthorizedException
1970 public static function createProfileContact(
1974 $addToGroupID = NULL,
1979 // add ufGroupID to params array ( CRM-2012 )
1981 $params['uf_group_id'] = $ufGroupId;
1983 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1985 // If a user has logged in, or accessed via a checksum
1986 // Then deliberately 'blanking' a value in the profile should remove it from their record
1987 $session = CRM_Core_Session
::singleton();
1988 $params['updateBlankLocInfo'] = TRUE;
1989 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1990 $params['updateBlankLocInfo'] = FALSE;
1995 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1999 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
2002 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
2004 // manage is_opt_out
2005 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
2006 $wasOptOut = $contactDetails['is_opt_out'] ??
FALSE;
2007 $isOptOut = $params['is_opt_out'];
2008 $data['is_opt_out'] = $isOptOut;
2009 // on change, create new civicrm_subscription_history entry
2010 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2012 'contact_id' => $contactDetails['contact_id'],
2013 'status' => $isOptOut ?
'Removed' : 'Added',
2016 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2020 $contact = self
::create($data);
2022 // contact is null if the profile does not have any contact fields
2024 $contactID = $contact->id
;
2027 if (empty($contactID)) {
2028 throw new CRM_Core_Exception('Cannot proceed without a valid contact id');
2031 // Process group and tag
2032 if (isset($params['group'])) {
2034 // this for sure means we are coming in via profile since i added it to fix
2035 // removing contacts from user groups -- lobo
2039 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2042 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2043 // Convert comma separated form values from select2 v3
2044 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2045 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2048 //to add profile in default group
2049 if (is_array($addToGroupID)) {
2050 $contactIds = [$contactID];
2051 foreach ($addToGroupID as $groupId) {
2052 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2055 elseif ($addToGroupID) {
2056 $contactIds = [$contactID];
2057 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2061 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2064 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2070 * Format profile contact parameters.
2072 * @param array $params
2074 * @param int $contactID
2075 * @param int $ufGroupId
2076 * @param null $ctype
2077 * @param bool $skipCustom
2081 public static function formatProfileContactParams(
2090 $data = $contactDetails = [];
2092 // get the contact details (hier)
2094 $details = self
::getHierContactDetails($contactID, $fields);
2096 $contactDetails = $details[$contactID];
2097 $data['contact_type'] = $contactDetails['contact_type'] ??
NULL;
2098 $data['contact_sub_type'] = $contactDetails['contact_sub_type'] ??
NULL;
2101 //we should get contact type only if contact
2103 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2105 //special case to handle profile with only contact fields
2106 if ($data['contact_type'] == 'Contact') {
2107 $data['contact_type'] = 'Individual';
2109 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2110 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2114 $data['contact_type'] = $ctype;
2117 $data['contact_type'] = 'Individual';
2121 //fix contact sub type CRM-5125
2122 if (array_key_exists('contact_sub_type', $params) &&
2123 !empty($params['contact_sub_type'])
2125 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2127 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2128 !empty($params['contact_sub_type_hidden'])
2130 // if profile was used, and had any subtype, we obtain it from there
2131 //CRM-13596 - add to existing contact types, rather than overwriting
2132 if (empty($data['contact_sub_type'])) {
2133 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2134 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2137 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2138 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2139 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2140 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2141 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2146 if ($ctype == 'Organization') {
2147 $data['organization_name'] = $contactDetails['organization_name'] ??
NULL;
2149 elseif ($ctype == 'Household') {
2150 $data['household_name'] = $contactDetails['household_name'] ??
NULL;
2158 $data['contact_id'] = $contactID;
2159 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2162 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2163 $defaultLocationId = $defaultLocation->id
;
2166 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2168 $blocks = ['email', 'phone', 'im', 'openid'];
2170 $multiplFields = ['url'];
2171 // prevent overwritten of formatted array, reset all block from
2172 // params if it is not in valid format (since import pass valid format)
2173 foreach ($blocks as $blk) {
2174 if (array_key_exists($blk, $params) &&
2175 !is_array($params[$blk])
2177 unset($params[$blk]);
2181 $primaryPhoneLoc = NULL;
2182 $session = CRM_Core_Session
::singleton();
2183 foreach ($params as $key => $value) {
2184 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2186 if ($locTypeId == 'Primary') {
2188 if (in_array($fieldName, $blocks)) {
2189 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2192 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2194 $primaryLocationType = $locTypeId;
2197 $locTypeId = $defaultLocationId;
2201 if (is_numeric($locTypeId) &&
2202 !in_array($fieldName, $multiplFields) &&
2203 substr($fieldName, 0, 7) != 'custom_'
2205 $index = $locTypeId;
2207 if (is_numeric($typeId)) {
2208 $index .= '-' . $typeId;
2210 if (!in_array($index, $locationType)) {
2211 $locationType[$count] = $index;
2215 $loc = CRM_Utils_Array
::key($index, $locationType);
2217 $blockName = self
::getLocationEntityForKey($fieldName);
2219 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2221 //set is_billing true, for location type "Billing"
2222 if ($locTypeId == $billingLocationTypeId) {
2223 $data[$blockName][$loc]['is_billing'] = 1;
2227 //get the primary location type
2228 if ($locTypeId == $primaryLocationType) {
2229 $data[$blockName][$loc]['is_primary'] = 1;
2232 elseif ($locTypeId == $defaultLocationId) {
2233 $data[$blockName][$loc]['is_primary'] = 1;
2236 if (in_array($fieldName, ['phone'])) {
2238 $data['phone'][$loc]['phone_type_id'] = $typeId;
2241 $data['phone'][$loc]['phone_type_id'] = '';
2243 $data['phone'][$loc]['phone'] = $value;
2245 //special case to handle primary phone with different phone types
2246 // in this case we make first phone type as primary
2247 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2248 $primaryPhoneLoc = $loc;
2251 if ($loc != $primaryPhoneLoc) {
2252 unset($data['phone'][$loc]['is_primary']);
2255 elseif ($fieldName == 'email') {
2256 $data['email'][$loc]['email'] = $value;
2257 if (empty($contactID)) {
2258 $data['email'][$loc]['is_primary'] = 1;
2261 elseif ($fieldName == 'im') {
2262 if (isset($params[$key . '-provider_id'])) {
2263 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2265 if (strpos($key, '-provider_id') !== FALSE) {
2266 $data['im'][$loc]['provider_id'] = $params[$key];
2269 $data['im'][$loc]['name'] = $value;
2272 elseif ($fieldName == 'openid') {
2273 $data['openid'][$loc]['openid'] = $value;
2276 if ($fieldName === 'state_province') {
2278 if (is_numeric($value) && ((int ) $value) >= 1000) {
2279 $data['address'][$loc]['state_province_id'] = $value;
2281 elseif (empty($value)) {
2282 $data['address'][$loc]['state_province_id'] = '';
2285 $data['address'][$loc]['state_province'] = $value;
2288 elseif ($fieldName === 'country') {
2290 if (is_numeric($value) && ((int ) $value) >= 1000
2292 $data['address'][$loc]['country_id'] = $value;
2294 elseif (empty($value)) {
2295 $data['address'][$loc]['country_id'] = '';
2298 $data['address'][$loc]['country'] = $value;
2301 elseif ($fieldName === 'county') {
2302 $data['address'][$loc]['county_id'] = $value;
2304 elseif ($fieldName == 'address_name') {
2305 $data['address'][$loc]['name'] = $value;
2307 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2308 $data['address'][$loc][substr($fieldName, 8)] = $value;
2311 $data[$blockName][$loc][$fieldName] = $value;
2316 if (substr($key, 0, 4) === 'url-') {
2317 $websiteField = explode('-', $key);
2318 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2319 $data['website'][$websiteField[1]]['url'] = $value;
2321 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2322 //save email/postal greeting and addressee values if any, CRM-4575
2323 $data[$key . '_id'] = $value;
2325 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2326 // for autocomplete transfer hidden value instead of label
2327 if ($params[$key] && isset($params[$key . '_id'])) {
2328 $value = $params[$key . '_id'];
2331 // we need to append time with date
2332 if ($params[$key] && isset($params[$key . '_time'])) {
2333 $value .= ' ' . $params[$key . '_time'];
2336 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2337 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2338 ($value == '' ||
!isset($value))
2344 if (!empty($params['customRecordValues'])) {
2345 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2346 foreach ($params['customRecordValues'] as $recId => $customFields) {
2347 if (is_array($customFields) && !empty($customFields)) {
2348 foreach ($customFields as $customFieldName) {
2349 if ($customFieldName == $key) {
2359 //CRM-13596 - check for contact_sub_type_hidden first
2360 if (array_key_exists('contact_sub_type_hidden', $params)) {
2361 $type = $params['contact_sub_type_hidden'];
2364 $type = $data['contact_type'];
2365 if (!empty($data['contact_sub_type'])) {
2366 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2370 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2380 elseif ($key === 'edit') {
2384 if ($key === 'location') {
2385 foreach ($value as $locationTypeId => $field) {
2386 foreach ($field as $block => $val) {
2387 if ($block === 'address' && array_key_exists('address_name', $val)) {
2388 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2393 if ($key === 'phone' && isset($params['phone_ext'])) {
2394 $data[$key] = $value;
2395 foreach ($value as $cnt => $phoneBlock) {
2396 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2397 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2401 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2402 && ($value == '' ||
!isset($value)) &&
2403 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2404 ($key === 'current_employer' && empty($params['current_employer']))) {
2405 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2406 // to avoid update with empty values
2410 $data[$key] = $value;
2416 if (!isset($data['contact_type'])) {
2417 $data['contact_type'] = 'Individual';
2420 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2421 $privacy = CRM_Core_SelectValues
::privacy();
2422 foreach ($privacy as $key => $value) {
2423 if (array_key_exists($key, $fields)) {
2424 // do not reset values for existing contacts, if fields are added to a profile
2425 if (array_key_exists($key, $params)) {
2426 $data[$key] = $params[$key];
2427 if (empty($params[$key])) {
2431 elseif (!$contactID) {
2437 return [$data, $contactDetails];
2441 * Find the get contact details.
2443 * This function does not respect ACLs for now, which might need to be rectified at some
2444 * stage based on how its used.
2446 * @param string $mail
2447 * Primary email address of the contact.
2448 * @param string $ctype
2451 * @return object|null
2452 * $dao contact details
2454 public static function matchContactOnEmail($mail, $ctype = NULL) {
2455 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2456 $mail = $strtolower(trim($mail));
2458 SELECT civicrm_contact.id as contact_id,
2459 civicrm_contact.hash as hash,
2460 civicrm_contact.contact_type as contact_type,
2461 civicrm_contact.contact_sub_type as contact_sub_type
2462 FROM civicrm_contact
2463 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2465 if (Civi
::settings()->get('uniq_email_per_site')) {
2466 // try to find a match within a site (multisite).
2467 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2468 if (!empty($groups)) {
2470 INNER JOIN civicrm_group_contact gc ON
2471 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2476 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2477 $p = [1 => [$mail, 'String']];
2480 $query .= " AND civicrm_contact.contact_type = %3";
2481 $p[3] = [$ctype, 'String'];
2484 $query .= " ORDER BY civicrm_email.is_primary DESC";
2486 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2488 if ($dao->fetch()) {
2495 * Find the contact details associated with an OpenID.
2497 * @param string $openId
2498 * OpenId of the contact.
2499 * @param string $ctype
2502 * @return object|null
2503 * $dao contact details
2505 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2506 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2507 $openId = $strtolower(trim($openId));
2509 SELECT civicrm_contact.id as contact_id,
2510 civicrm_contact.hash as hash,
2511 civicrm_contact.contact_type as contact_type,
2512 civicrm_contact.contact_sub_type as contact_sub_type
2513 FROM civicrm_contact
2514 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2515 WHERE civicrm_openid.openid = %1";
2516 $p = [1 => [$openId, 'String']];
2519 $query .= " AND civicrm_contact.contact_type = %3";
2520 $p[3] = [$ctype, 'String'];
2523 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2525 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2527 if ($dao->fetch()) {
2534 * Get primary email of the contact.
2536 * @param int $contactID
2538 * @param bool $polite
2539 * Whether to only pull an email if it's okay to send to it--that is, if it
2540 * is not on_hold and the contact is not do_not_email.
2543 * Email address if present else null
2545 public static function getPrimaryEmail($contactID, $polite = FALSE) {
2546 // fetch the primary email
2548 SELECT civicrm_email.email as email
2549 FROM civicrm_contact
2550 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2551 WHERE civicrm_email.is_primary = 1
2552 AND civicrm_contact.id = %1";
2555 AND civicrm_contact.do_not_email = 0
2556 AND civicrm_email.on_hold = 0';
2558 $p = [1 => [$contactID, 'Integer']];
2559 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2562 if ($dao->fetch()) {
2563 $email = $dao->email
;
2569 * Function to get primary OpenID of the contact.
2571 * @param int $contactID
2575 * >openid OpenID if present else null
2577 public static function getPrimaryOpenId($contactID) {
2578 // fetch the primary OpenID
2580 SELECT civicrm_openid.openid as openid
2581 FROM civicrm_contact
2582 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2583 WHERE civicrm_contact.id = %1
2584 AND civicrm_openid.is_primary = 1";
2585 $p = [1 => [$contactID, 'Integer']];
2586 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2589 if ($dao->fetch()) {
2590 $openId = $dao->openid
;
2596 * Fetch the object and store the values in the values array.
2598 * @param array $params
2599 * Input parameters to find object.
2600 * @param array $values
2601 * Output values of the object.
2603 * @return CRM_Contact_BAO_Contact|null
2604 * The found object or null
2606 public static function getValues(&$params, &$values) {
2607 $contact = new CRM_Contact_BAO_Contact();
2609 $contact->copyValues($params);
2611 if ($contact->find(TRUE)) {
2613 CRM_Core_DAO
::storeValues($contact, $values);
2616 foreach (self
::$_commPrefs as $name) {
2617 if (isset($contact->$name)) {
2618 $privacy[$name] = $contact->$name;
2622 if (!empty($privacy)) {
2623 $values['privacy'] = $privacy;
2626 // communication Prefferance
2627 $preffComm = $comm = [];
2628 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2629 $contact->preferred_communication_method
2631 foreach ($comm as $value) {
2632 $preffComm[$value] = 1;
2634 $temp = ['preferred_communication_method' => $contact->preferred_communication_method
];
2637 'preferred_communication_method' => [
2638 'newName' => 'preferred_communication_method_display',
2639 'groupName' => 'preferred_communication_method',
2643 // @todo This can be figured out from metadata & we can avoid the uncached query.
2644 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2646 $values['preferred_communication_method'] = $preffComm;
2647 $values['preferred_communication_method_display'] = $temp['preferred_communication_method_display'] ??
NULL;
2649 if ($contact->preferred_mail_format
) {
2650 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2651 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2654 // get preferred languages
2655 if (!empty($contact->preferred_language
)) {
2656 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2659 // Calculating Year difference
2660 if ($contact->birth_date
) {
2661 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2662 if ($birthDate < date('Ymd')) {
2663 $age = CRM_Utils_Date
::calculateAge($birthDate);
2664 $values['age']['y'] = $age['years'] ??
NULL;
2665 $values['age']['m'] = $age['months'] ??
NULL;
2669 $contact->contact_id
= $contact->id
;
2677 * Given the component name and returns the count of participation of contact.
2679 * @param string $component
2680 * Input component name.
2681 * @param int $contactId
2683 * @param string $tableName
2684 * Optional tableName if component is custom group.
2687 * total number in database
2689 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2691 switch ($component) {
2693 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2696 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2697 CRM_Contact_BAO_Relationship
::CURRENT
,
2706 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2709 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2712 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2715 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2717 case 'contribution':
2718 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2721 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2724 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2727 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2730 return CRM_Case_BAO_Case
::caseCount($contactId);
2733 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2737 'contact_id' => $contactId,
2740 'context' => 'activity',
2742 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2745 $params = ['contact_id' => $contactId];
2746 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2749 $custom = explode('_', $component);
2750 if ($custom['0'] = 'custom') {
2752 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2754 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2755 return CRM_Core_DAO
::singleValueQuery($queryString);
2761 * Update contact greetings if an update has resulted in a custom field change.
2763 * @param array $updatedFields
2764 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2765 * @param array $contactParams
2766 * Parameters known about the contact. At minimum array('contact_id' => x).
2767 * Fields in this array will take precedence over DB fields (so far only
2768 * in the case of greeting id fields).
2770 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2771 $contactID = $contactParams['contact_id'];
2772 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2773 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2774 if (!empty($tokens['all']['contact'])) {
2775 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2776 if (!empty($affectedTokens)) {
2777 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2778 $contact = new CRM_Contact_BAO_Contact();
2779 $contact->id
= $contactID;
2780 CRM_Contact_BAO_Contact
::processGreetings($contact);
2786 * Process greetings and cache.
2788 * @param object $contact
2789 * Contact object after save.
2791 public static function processGreetings(&$contact) {
2793 //@todo this function does a lot of unnecessary loading.
2794 // ensureGreetingParamsAreSet now makes sure that the contact is
2795 // loaded and using updateGreetingsOnTokenFieldChange
2796 // allows us the possibility of only doing an update if required.
2798 // The contact object has not always required the
2799 // fields that are required to calculate greetings
2800 // so we need to retrieve it again.
2801 if ($contact->_query
!== FALSE) {
2802 $contact->find(TRUE);
2805 // store object values to an array
2806 $contactDetails = [];
2807 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2808 $contactDetails = [[$contact->id
=> $contactDetails]];
2810 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2811 $updateQueryString = [];
2813 //cache email and postal greeting to greeting display
2814 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2815 $emailGreetingString = $contact->email_greeting_custom
;
2817 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2818 // the filter value for Individual contact type is set to 1
2820 'contact_type' => $contact->contact_type
,
2821 'greeting_type' => 'email_greeting',
2824 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2825 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2826 $updateQueryString[] = " email_greeting_custom = NULL ";
2829 if ($contact->email_greeting_custom
) {
2830 $updateQueryString[] = " email_greeting_display = NULL ";
2834 if ($emailGreetingString) {
2835 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2838 'CRM_Contact_BAO_Contact'
2840 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2841 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2845 if ($contact->postal_greeting_custom
!== 'null' && $contact->postal_greeting_custom
) {
2846 $postalGreetingString = $contact->postal_greeting_custom
;
2848 elseif ($contact->postal_greeting_id
!== 'null' && $contact->postal_greeting_id
) {
2850 'contact_type' => $contact->contact_type
,
2851 'greeting_type' => 'postal_greeting',
2853 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2854 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2855 $updateQueryString[] = " postal_greeting_custom = NULL ";
2858 if ($contact->postal_greeting_custom
) {
2859 $updateQueryString[] = " postal_greeting_display = NULL ";
2863 if ($postalGreetingString) {
2864 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2867 'CRM_Contact_BAO_Contact'
2869 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2870 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2874 if ($contact->addressee_custom
!== 'null' && $contact->addressee_custom
) {
2875 $addresseeString = $contact->addressee_custom
;
2877 elseif ($contact->addressee_id
!== 'null' && $contact->addressee_id
) {
2879 'contact_type' => $contact->contact_type
,
2880 'greeting_type' => 'addressee',
2883 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2884 $addresseeString = $addressee[$contact->addressee_id
];
2885 $updateQueryString[] = " addressee_custom = NULL ";
2888 if ($contact->addressee_custom
) {
2889 $updateQueryString[] = " addressee_display = NULL ";
2893 if ($addresseeString) {
2894 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2897 'CRM_Contact_BAO_Contact'
2899 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2900 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2903 if (!empty($updateQueryString)) {
2904 $updateQueryString = implode(',', $updateQueryString);
2905 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2906 CRM_Core_DAO
::executeQuery($queryString);
2911 * Retrieve loc block ids w/ given condition.
2913 * @param int $contactId
2915 * @param array $criteria
2916 * Key => value pair which should be.
2917 * fulfill by return record ids.
2918 * @param string $condOperator
2919 * Operator use for grouping multiple conditions.
2922 * loc block ids which fulfill condition.
2924 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2927 return $locBlockIds;
2930 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2931 $name = strtolower($block);
2932 $className = "CRM_Core_DAO_$block";
2933 $blockDAO = new $className();
2935 // build the condition.
2936 if (is_array($criteria)) {
2937 $fields = $blockDAO->fields();
2939 foreach ($criteria as $field => $value) {
2940 if (array_key_exists($field, $fields)) {
2941 $cond = "( $field = $value )";
2942 // value might be zero or null.
2943 if (!$value ||
strtolower($value) === 'null') {
2944 $cond = "( $field = 0 OR $field IS NULL )";
2946 $conditions[] = $cond;
2949 if (!empty($conditions)) {
2950 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2954 $blockDAO->contact_id
= $contactId;
2956 while ($blockDAO->fetch()) {
2957 $locBlockIds[$name][] = $blockDAO->id
;
2961 return $locBlockIds;
2965 * Build context menu items.
2967 * @param int $contactId
2970 * Array of context menu for logged in user.
2972 public static function contextMenu($contactId = NULL) {
2975 'title' => ts('View Contact'),
2977 'ref' => 'view-contact',
2978 'class' => 'no-popup',
2980 'permissions' => ['view all contacts'],
2983 'title' => ts('Edit Contact'),
2985 'ref' => 'edit-contact',
2986 'class' => 'no-popup',
2988 'permissions' => ['edit all contacts'],
2991 'title' => ts('Delete Contact'),
2993 'ref' => 'delete-contact',
2995 'permissions' => ['access deleted contacts', 'delete contacts'],
2998 'title' => ts('Add Contribution'),
3000 'ref' => 'new-contribution',
3001 'key' => 'contribution',
3002 'tab' => 'contribute',
3003 'component' => 'CiviContribute',
3004 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
3005 'reset=1&action=add&context=contribution'
3008 'access CiviContribute',
3009 'edit contributions',
3013 'title' => ts('Register for Event'),
3015 'ref' => 'new-participant',
3016 'key' => 'participant',
3017 'tab' => 'participant',
3018 'component' => 'CiviEvent',
3019 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3022 'edit event participants',
3026 'title' => ts('Record Activity'),
3028 'ref' => 'new-activity',
3029 'key' => 'activity',
3030 'permissions' => ['edit all contacts'],
3033 'title' => ts('Add Pledge'),
3035 'ref' => 'new-pledge',
3038 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3039 'reset=1&action=add&context=pledge'
3041 'component' => 'CiviPledge',
3043 'access CiviPledge',
3048 'title' => ts('Add Membership'),
3050 'ref' => 'new-membership',
3051 'key' => 'membership',
3053 'component' => 'CiviMember',
3054 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3055 'reset=1&action=add&context=membership'
3058 'access CiviMember',
3063 'title' => ts('Add Case'),
3065 'ref' => 'new-case',
3068 'component' => 'CiviCase',
3069 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3070 'permissions' => ['add cases'],
3073 'title' => ts('Add Grant'),
3075 'ref' => 'new-grant',
3078 'component' => 'CiviGrant',
3079 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3080 'reset=1&action=add&context=grant'
3082 'permissions' => ['edit grants'],
3085 'title' => ts('Add Relationship'),
3087 'ref' => 'new-relationship',
3090 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3091 'reset=1&action=add'
3093 'permissions' => ['edit all contacts'],
3096 'title' => ts('Add Note'),
3098 'ref' => 'new-note',
3101 'class' => 'medium-popup',
3102 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3103 'reset=1&action=add'
3105 'permissions' => ['edit all contacts'],
3108 'title' => ts('Send an Email'),
3110 'ref' => 'new-email',
3112 'permissions' => ['view all contacts'],
3115 'title' => ts('Add to Group'),
3117 'ref' => 'group-add-contact',
3120 'permissions' => ['edit groups'],
3123 'title' => ts('Tag Contact'),
3125 'ref' => 'tag-contact',
3128 'permissions' => ['edit all contacts'],
3132 $menu['otherActions'] = [
3134 'title' => ts('Print Summary'),
3135 'description' => ts('Printer-friendly view of this page.'),
3137 'ref' => 'crm-contact-print',
3140 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3144 'icon' => 'crm-i fa-print',
3147 'title' => ts('vCard'),
3148 'description' => ts('vCard record for this contact.'),
3150 'ref' => 'crm-contact-vcard',
3153 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3157 'icon' => 'crm-i fa-list-alt',
3161 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3162 $menu['otherActions']['dashboard'] = [
3163 'title' => ts('Contact Dashboard'),
3164 'description' => ts('Contact Dashboard'),
3166 'ref' => 'crm-contact-dashboard',
3167 'key' => 'dashboard',
3168 'tab' => 'dashboard',
3169 'class' => 'dashboard',
3170 // NOTE: As an alternative you can also build url on CMS specific way
3171 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3172 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3173 'icon' => 'crm-i fa-tachometer',
3177 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3179 $menu['otherActions']['user-record'] = [
3180 'title' => ts('User Record'),
3181 'description' => ts('User Record'),
3183 'ref' => 'crm-contact-user-record',
3184 'key' => 'user-record',
3185 'tab' => 'user-record',
3186 'class' => 'user-record',
3187 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3188 'icon' => 'crm-i fa-user',
3191 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3192 $menu['otherActions']['user-add'] = [
3193 'title' => ts('Create User Record'),
3194 'description' => ts('Create User Record'),
3196 'ref' => 'crm-contact-user-add',
3197 'key' => 'user-add',
3198 'tab' => 'user-add',
3199 'class' => 'user-add',
3200 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3201 'icon' => 'crm-i fa-user-plus',
3205 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3206 //1. check for component is active.
3207 //2. check for user permissions.
3208 //3. check for acls.
3209 //3. edit and view contact are directly accessible to user.
3211 $aclPermissionedTasks = [
3216 'group-add-contact',
3220 $corePermission = CRM_Core_Permission
::getPermission();
3223 foreach ($menu as $key => $values) {
3224 if ($key !== 'otherActions') {
3226 // user does not have necessary permissions.
3227 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3230 // build directly accessible action menu.
3231 if (in_array($values['ref'], [
3235 $contextMenu['primaryActions'][$key] = [
3236 'title' => $values['title'],
3237 'ref' => $values['ref'],
3238 'class' => $values['class'] ??
NULL,
3239 'key' => $values['key'],
3244 // finally get menu item for -more- action widget.
3245 $contextMenu['moreActions'][$values['weight']] = [
3246 'title' => $values['title'],
3247 'ref' => $values['ref'],
3248 'href' => $values['href'] ??
NULL,
3249 'tab' => $values['tab'] ??
NULL,
3250 'class' => $values['class'] ??
NULL,
3251 'key' => $values['key'],
3255 foreach ($values as $value) {
3256 // user does not have necessary permissions.
3257 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3261 // finally get menu item for -more- action widget.
3262 $contextMenu['otherActions'][$value['weight']] = [
3263 'title' => $value['title'],
3264 'ref' => $value['ref'],
3265 'href' => $value['href'] ??
NULL,
3266 'tab' => $value['tab'] ??
NULL,
3267 'class' => $value['class'] ??
NULL,
3268 'icon' => $value['icon'] ??
NULL,
3269 'key' => $value['key'],
3275 ksort($contextMenu['moreActions']);
3276 ksort($contextMenu['otherActions']);
3278 return $contextMenu;
3282 * Check if user has permissions to access items in action menu.
3284 * @param array $aclPermissionedTasks
3285 * Array containing ACL related tasks.
3286 * @param string $corePermission
3287 * The permission of the user (edit or view or null).
3288 * @param array $menuOptions
3289 * Array containing params of the menu (title, href, etc).
3292 * TRUE if user has all permissions, FALSE if otherwise.
3294 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3295 $componentName = $menuOptions['component'] ??
NULL;
3297 // if component action - make sure component is enable.
3298 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3302 // make sure user has all required permissions.
3303 $hasAllPermissions = FALSE;
3305 $permissions = $menuOptions['permissions'] ??
NULL;
3306 if (!is_array($permissions) ||
empty($permissions)) {
3307 $hasAllPermissions = TRUE;
3310 // iterate for required permissions in given permissions array.
3311 if (!$hasAllPermissions) {
3312 $hasPermissions = 0;
3313 foreach ($permissions as $permission) {
3314 if (CRM_Core_Permission
::check($permission)) {
3319 if (count($permissions) == $hasPermissions) {
3320 $hasAllPermissions = TRUE;
3323 // if still user does not have required permissions, check acl.
3324 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3325 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3326 $corePermission == CRM_Core_Permission
::EDIT
3328 $hasAllPermissions = TRUE;
3330 elseif (in_array($menuOptions['ref'], [
3333 // grant permissions for these tasks.
3334 $hasAllPermissions = TRUE;
3339 return $hasAllPermissions;
3343 * Retrieve display name of contact that address is shared.
3345 * This is based on $masterAddressId or $contactId .
3347 * @param int $masterAddressId
3349 * @param int $contactId
3350 * Contact id. (deprecated - do not use)
3352 * @return string|null
3353 * the found display name or null.
3355 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3356 $masterDisplayName = NULL;
3357 if (!$masterAddressId) {
3358 return $masterDisplayName;
3362 SELECT display_name from civicrm_contact
3363 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3364 WHERE civicrm_address.id = " . $masterAddressId;
3366 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3367 return $masterDisplayName;
3371 * Get the creation/modification times for a contact.
3373 * @param int $contactId
3376 * Dates - ('created_date' => $, 'modified_date' => $)
3378 public static function getTimestamps($contactId) {
3379 $timestamps = CRM_Core_DAO
::executeQuery(
3380 'SELECT created_date, modified_date
3381 FROM civicrm_contact
3384 1 => [$contactId, 'Integer'],
3387 if ($timestamps->fetch()) {
3389 'created_date' => $timestamps->created_date
,
3390 'modified_date' => $timestamps->modified_date
,
3399 * Get a list of triggers for the contact table.
3402 * @param null $tableName
3404 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3406 * @see hook_civicrm_triggerInfo
3407 * @see CRM_Core_DAO::triggerRebuild
3409 public static function triggerInfo(&$info, $tableName = NULL) {
3411 // Modifications to these records should update the contact timestamps.
3412 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3414 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3415 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3416 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3417 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3418 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3420 ->alterTriggerInfo($info, $tableName);
3422 // Update phone table to populate phone_numeric field
3423 if (!$tableName ||
$tableName == 'civicrm_phone') {
3424 // Define stored sql function needed for phones
3425 $sqlTriggers = Civi
::service('sql_triggers');
3426 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3427 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3429 'table' => ['civicrm_phone'],
3431 'event' => ['INSERT', 'UPDATE'],
3432 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3438 * Check if contact is being used in civicrm_domain based on $contactId.
3440 * @param int $contactId
3444 * true if present else false.
3446 public static function checkDomainContact($contactId) {
3450 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3461 * Get options for a given contact field.
3463 * @param string $fieldName
3464 * @param string $context
3465 * @param array $props
3466 * whatever is known about this dao object.
3468 * @return array|bool
3469 * @see CRM_Core_DAO::buildOptions
3471 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3472 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3474 * @see CRM_Core_DAO::buildOptionsContext
3476 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3478 // Special logic for fields whose options depend on context or properties
3479 switch ($fieldName) {
3480 case 'contact_sub_type':
3481 if (!empty($props['contact_type'])) {
3482 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3486 case 'contact_type':
3487 if ($context == 'search') {
3488 // CRM-15495 - EntityRef filters and basic search forms expect this format
3489 // FIXME: Search builder does not
3490 return CRM_Contact_BAO_ContactType
::getSelectElements();
3494 // The contact api supports some related entities so we'll honor that by fetching their options
3497 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3501 $props['entity_table'] = 'civicrm_contact';
3502 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3504 case 'state_province_id':
3505 case 'state_province':
3506 case 'state_province_name':
3511 case 'worldregion_id':
3512 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3515 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3519 * Delete a contact-related object that has an 'is_primary' field.
3521 * Ensures that is_primary gets assigned to another object if available
3522 * Also calls pre/post hooks
3524 * @param string $type
3529 public static function deleteObjectWithPrimary($type, $id) {
3530 if (!$id ||
!is_numeric($id)) {
3533 $daoName = "CRM_Core_DAO_$type";
3534 $obj = new $daoName();
3538 if ($obj->fetch()) {
3539 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3540 $contactId = $obj->contact_id
;
3546 // is_primary is only relavent if this field belongs to a contact
3548 $dao = new $daoName();
3549 $dao->contact_id
= $contactId;
3550 $dao->is_primary
= 1;
3551 // Pick another record to be primary (if one isn't already)
3552 if (!$dao->find(TRUE)) {
3553 $dao->is_primary
= 0;
3555 if ($dao->fetch()) {
3556 $dao->is_primary
= 1;
3561 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3568 public function addSelectWhereClause() {
3569 // We always return an array with these keys, even if they are empty,
3570 // because this tells the query builder that we have considered these fields for acls
3572 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3573 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
[] : ['!= 1'],
3575 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3580 * Get any existing duplicate contacts based on the input parameters.
3582 * @param array $input
3583 * Input parameters to be matched.
3584 * @param string $contactType
3585 * @param string $rule
3588 * @param $excludedContactIDs
3589 * An array of ids not to be included in the results.
3590 * @param bool $checkPermissions
3591 * @param int $ruleGroupID
3592 * ID of the rule group to be used if an override is desirable.
3593 * @param array $contextParams
3594 * The context if relevant, eg. ['event_id' => X]
3598 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3599 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3600 $dedupeParams['check_permission'] = $checkPermissions;
3601 $dedupeParams['contact_type'] = $contactType;
3602 $dedupeParams['rule'] = $rule;
3603 $dedupeParams['rule_group_id'] = $ruleGroupID;
3604 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3605 $dedupeResults['ids'] = [];
3606 $dedupeResults['handled'] = FALSE;
3607 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3608 if (!$dedupeResults['handled']) {
3609 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3611 return $dedupeResults['ids'];
3615 * Get the first duplicate contacts based on the input parameters.
3617 * @param array $input
3618 * Input parameters to be matched.
3619 * @param string $contactType
3620 * @param string $rule
3623 * @param $excludedContactIDs
3624 * An array of ids not to be included in the results.
3625 * @param bool $checkPermissions
3626 * @param int $ruleGroupID
3627 * ID of the rule group to be used if an override is desirable.
3628 * @param array $contextParams
3629 * The context if relevant, eg. ['event_id' => X]
3633 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3634 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3642 * Check if a field is associated with an entity that has a location type.
3644 * (ie. is an address, phone, email etc field).
3646 * @param string $fieldTitle
3647 * Title of the field (not the name - create a new function for that if required).
3651 public static function isFieldHasLocationType($fieldTitle) {
3652 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3653 if ($field['title'] === $fieldTitle) {
3654 return $field['hasLocationType'] ??
NULL;
3661 * @param array $appendProfiles
3662 * Name of profile(s) to append to each link.
3666 public static function getEntityRefCreateLinks($appendProfiles = []) {
3667 // You'd think that "create contacts" would be the permission to check,
3668 // But new contact popups are profile forms and those use their own permissions.
3669 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3673 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3674 $profiles[] = 'new_' . strtolower($contactType);
3676 $retrieved = civicrm_api3('uf_group', 'get', [
3677 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3680 $links = $append = [];
3681 if (!empty($retrieved['values'])) {
3683 'individual' => 'fa-user',
3684 'organization' => 'fa-building',
3685 'household' => 'fa-home',
3687 foreach ($retrieved['values'] as $id => $profile) {
3688 if (in_array($profile['name'], $profiles)) {
3690 'label' => $profile['title'],
3691 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3692 NULL, NULL, FALSE, FALSE, TRUE),
3693 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3694 'icon' => $icons[str_replace('new_', '', $profile['name'])] ??
NULL,
3701 foreach ($append as $id) {
3702 foreach ($links as &$link) {
3703 $link['url'] .= ",$id";
3713 public static function getEntityRefFilters() {
3715 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3716 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3717 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3718 ['key' => 'city', 'value' => ts('City'), 'type' => 'text', 'entity' => 'Address'],
3719 ['key' => 'postal_code', 'value' => ts('Postal Code'), 'type' => 'text', 'entity' => 'Address'],
3720 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3721 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3722 ['key' => 'first_name', 'value' => ts('First Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3723 ['key' => 'last_name', 'value' => ts('Last Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3724 ['key' => 'nick_name', 'value' => ts('Nick Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3725 ['key' => 'organization_name', 'value' => ts('Employer name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3726 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3727 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3728 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3729 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3730 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],