3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
implements Civi\Core\HookInterface
{
20 * SQL function used to format the phone_numeric field via trigger.
22 * @see self::triggerInfo()
24 * Note that this is also used by the 4.3 upgrade script.
25 * @see CRM_Upgrade_Incremental_php_FourThree
27 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
29 const CREATE_STRIP_FUNCTION_43
= "
30 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255))
35 DECLARE output VARCHAR(255) DEFAULT '';
36 DECLARE iterator INT DEFAULT 1;
37 WHILE iterator < (LENGTH(input) + 1) DO
38 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
39 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
41 SET iterator = iterator + 1;
47 * The types of communication preferences.
51 public static $_commPrefs = [
64 public static $_greetingTypes = [
71 * Static field for all the contact information that we can potentially import.
75 public static $_importableFields = [];
78 * Static field for all the contact information that we can potentially export.
82 public static $_exportableFields = NULL;
85 * Takes an associative array and creates a contact object.
87 * The function extracts all the params it needs to initialize the create a
88 * contact object. the params array could contain additional unused name/value
91 * @param array $params
92 * (reference) an assoc array of name/value pairs.
94 * @return CRM_Contact_DAO_Contact|CRM_Core_Error|NULL
95 * Created or updated contact object or error object.
96 * (error objects are being phased out in favour of exceptions)
97 * @throws \CRM_Core_Exception
99 public static function add(&$params) {
100 $contact = new CRM_Contact_DAO_Contact();
101 $contactID = $params['contact_id'] ??
NULL;
102 if (empty($params)) {
106 // Fix for validate contact sub type CRM-5143.
107 if (isset($params['contact_sub_type'])) {
108 if (empty($params['contact_sub_type'])) {
109 $params['contact_sub_type'] = 'null';
111 elseif ($params['contact_sub_type'] !== 'null') {
112 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
113 $params['contact_type'], TRUE
116 // we'll need to fix tests to handle this
118 throw new CRM_Core_Exception(ts('The Contact Sub Type does not match the Contact type for this record'));
120 $params['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
124 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
125 CRM_Utils_Array
::formatArrayKeys($params['preferred_communication_method']);
126 $contact->preferred_communication_method
= CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
127 unset($params['preferred_communication_method']);
130 $defaults = ['source' => $params['contact_source'] ??
NULL];
131 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
132 $defaults['display_name'] = $params['organization_name'];
133 $defaults['sort_name'] = $params['organization_name'];
135 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
136 $defaults['display_name'] = $params['household_name'];
137 $defaults['sort_name'] = $params['household_name'];
139 $params = array_merge($defaults, $params);
141 $allNull = $contact->copyValues($params);
143 $contact->id
= $contactID;
145 if ($contact->contact_type
=== 'Individual') {
147 // @todo allow the lines below to be overridden by input or hooks & add tests,
148 // as has been done for households and organizations.
149 // Format individual fields.
150 CRM_Contact_BAO_Individual
::format($params, $contact);
153 // Note that copyValues() above might already call this, via
154 // CRM_Utils_String::ellipsify(), but e.g. for Individual it gets put
155 // back or altered by Individual::format() just above, so we need to
157 // Note also orgs will get ellipsified, but if we do that here then
158 // some existing tests on individual fail.
159 // Also api v3 will enforce org naming length by failing, v4 will truncate.
160 if (mb_strlen($contact->display_name
, 'UTF-8') > 128) {
161 $contact->display_name
= mb_substr($contact->display_name
, 0, 128, 'UTF-8');
163 if (mb_strlen($contact->sort_name
, 'UTF-8') > 128) {
164 $contact->sort_name
= mb_substr($contact->sort_name
, 0, 128, 'UTF-8');
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']);
202 if (!CRM_Utils_System
::isNull($newEmployer)) {
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|NULL
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 if (!empty($params['custom']) &&
375 is_array($params['custom'])
377 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
, $isEdit ?
'edit' : 'create');
380 $transaction->commit();
382 // CRM-6367: fetch the right label for contact type’s display
383 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
384 'CRM_Contact_DAO_ContactType',
385 $contact->contact_type
,
390 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
394 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
397 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
401 // In order to prevent a series of expensive queries in intensive batch processing
402 // api calls may pass in skip_greeting_processing, probably doing it later via the
403 // scheduled job. CRM-21551
404 if (empty($params['skip_greeting_processing'])) {
405 self
::processGreetings($contact);
408 if (!empty($params['check_permissions'])) {
409 $contacts = [&$contact];
410 self
::unsetProtectedFields($contacts);
413 if (!empty($params['is_deceased'])) {
414 // Edit Membership Status
416 'contact_id' => $contact->id
,
417 'is_deceased' => $params['is_deceased'],
418 'deceased_date' => $params['deceased_date'] ??
NULL,
420 CRM_Member_BAO_Membership
::updateMembershipStatus($deceasedParams, $params['contact_type']);
427 * Check if a contact has a name.
429 * - Individuals need a first_name or last_name
430 * - Organizations need organization_name
431 * - Households need household_name
433 * @param array $contact
436 public static function hasName(array $contact): bool {
438 'Individual' => ['first_name', 'last_name'],
439 'Organization' => ['organization_name'],
440 'Household' => ['household_name'],
442 // Casting to int filters out the string 'null'
443 $cid = (int) ($contact['id'] ??
NULL);
444 $contactType = $contact['contact_type'] ??
NULL;
445 if (!$contactType && $cid) {
446 $contactType = CRM_Core_DAO
::getFieldValue(__CLASS__
, $cid, 'contact_type');
448 if (!$contactType ||
!isset($nameFields[$contactType])) {
449 throw new CRM_Core_Exception('No contact_type given to ' . __CLASS__
. '::' . __FUNCTION__
);
451 foreach ($nameFields[$contactType] as $field) {
452 if (isset($contact[$field]) && is_string($contact[$field]) && $contact[$field] !== '') {
456 // For existing contacts, look up name from database
458 foreach ($nameFields[$contactType] as $field) {
459 $value = $contact[$field] ?? CRM_Core_DAO
::getFieldValue(__CLASS__
, $cid, $field);
460 if (isset($value) && $value !== '') {
469 * Format the output of the create contact function
471 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
473 public static function unsetProtectedFields(&$contacts) {
474 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
475 $currentUser = CRM_Core_Session
::getLoggedInContactID();
476 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
477 foreach ($contacts as &$contact) {
478 $cid = is_object($contact) ?
$contact->id
: $contact['id'] ??
NULL;
479 if (!($editOwn && $cid == $currentUser)) {
480 if (is_object($contact)) {
481 unset($contact->api_key
);
484 unset($contact['api_key']);
492 * Ensure greeting parameters are set.
494 * By always populating greetings here we can be sure they are set if required & avoid a call later.
495 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
497 * @param array $params
499 * @throws \CiviCRM_API3_Exception
501 public static function ensureGreetingParamsAreSet(&$params) {
502 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
503 $missingGreetingParams = [];
505 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
506 // An empty string means NULL
507 if (($params[$greetingParam] ??
NULL) === '') {
508 $params[$greetingParam] = 'null';
510 if (empty($params[$greetingParam])) {
511 $missingGreetingParams[$greetingIndex] = $greetingParam;
515 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
516 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
517 'id' => $params['contact_id'],
518 'return' => array_keys($missingGreetingParams),
521 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
522 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
523 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
526 // Filter out other fields.
527 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
528 $params = array_merge($params, $savedGreetings);
531 foreach ($missingGreetingParams as $greetingName => $greeting) {
532 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
536 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
537 if ($params[$greetingParam] === 'null') {
538 // If we are setting it to null then null out the display field.
539 $params[$greetingIndex . '_display'] = 'null';
541 if ((int) $params[$greetingParam] != CRM_Core_PseudoConstant
::getKey('CRM_Contact_BAO_Contact', $greetingParam, 'Customized')) {
542 $params[$greetingIndex . '_custom'] = 'null';
549 * Get the display name and image of a contact.
554 * @param bool $includeTypeInReturnParameters
555 * Should type be part of the returned array?
558 * the displayName and contactImage for this contact
560 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
561 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
563 SELECT civicrm_contact.*,
564 civicrm_email.email as email
566 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
567 AND civicrm_email.is_primary = 1
568 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
569 $dao = new CRM_Core_DAO();
572 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
573 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
575 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
576 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
579 // use email if display_name is empty
580 if (empty($dao->display_name
)) {
581 $displayName = $dao->email
;
584 $displayName = $dao->display_name
;
587 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
589 return $includeTypeInReturnParameters ?
[
593 $dao->contact_sub_type
,
595 ] : [$displayName, $image, $imageUrl];
601 * Add billing fields to the params if appropriate.
603 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
604 * don't then we should set the name fields to the billing fields AND add the preserveDBName
605 * parameter (which will tell the BAO only to set those fields if none already exist.
607 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
608 * matching is best done by hipsters.
610 * @param array $params
612 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
614 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
615 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
616 foreach ($nameFields as $field) {
617 if (!empty($params[$field])) {
621 // There are only 3 - we can iterate through them twice :-)
622 foreach ($nameFields as $field) {
623 if (!empty($params['billing_' . $field])) {
624 $params[$field] = $params['billing_' . $field];
626 $params['preserveDBName'] = TRUE;
632 * Resolve a state province string (UT or Utah) to an ID.
634 * If country has been passed in we should select a state belonging to that country.
636 * Alternatively we should choose from enabled countries, prioritising the default country.
638 * @param array $values
639 * @param int|null $countryID
643 * @throws \CRM_Core_Exception
645 protected static function resolveStateProvinceID($values, $countryID) {
648 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
649 if (CRM_Utils_Array
::lookupValue($values,
654 return $values['state_province_id'];
656 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
657 if (CRM_Utils_Array
::lookupValue($values,
662 return $values['state_province_id'];
667 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
668 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
669 // prefer matching country..
670 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, ['country_id' => Civi
::settings()->get('defaultContactCountry')]);
671 if (CRM_Utils_Array
::lookupValue($values,
676 return $values['state_province_id'];
679 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
680 if (CRM_Utils_Array
::lookupValue($values,
685 return $values['state_province_id'];
688 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
689 if (CRM_Utils_Array
::lookupValue($values,
694 return $values['state_province_id'];
696 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
697 if (CRM_Utils_Array
::lookupValue($values,
702 return $values['state_province_id'];
710 * Get the relevant location entity for the array key.
712 * Based on the field name we determine which location entity
713 * we are dealing with. Apart from a few specific ones they
714 * are mostly 'address' (the default).
716 * @param string $fieldName
720 protected static function getLocationEntityForKey($fieldName) {
721 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
724 if ($fieldName === 'phone_ext') {
731 * Soft delete a contact.
733 * Call this via the api, not directly.
735 * @param \CRM_Contact_BAO_Contact $contact
738 * @throws \CRM_Core_Exception
740 protected static function contactTrash($contact): bool {
742 'id' => $contact->id
,
745 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
747 $params = [1 => [$contact->id
, 'Integer']];
748 $query = 'DELETE FROM civicrm_uf_match WHERE contact_id = %1';
749 CRM_Core_DAO
::executeQuery($query, $params);
751 $contact->copyValues($updateParams);
753 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
755 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
761 * Get the values for pseudoconstants for name->value and reverse.
763 * @param array $defaults
764 * (reference) the default values, some of which need to be resolved.
765 * @param bool $reverse
766 * Always true as this function is only called from one place..
770 * This is called specifically from the contact import parser & should be moved there
771 * as it is not truly a generic function.
774 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
775 // Hack for birth_date.
776 if (!empty($defaults['birth_date'])) {
777 if (is_array($defaults['birth_date'])) {
778 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
782 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
783 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
784 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
785 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
787 //lookup value of email/postal greeting, addressee, CRM-4575
788 foreach (self
::$_greetingTypes as $greeting) {
790 'contact_type' => $defaults['contact_type'] ??
NULL,
791 'greeting_type' => $greeting,
793 CRM_Utils_Array
::lookupValue($defaults, $greeting,
794 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
798 $blocks = ['address', 'im', 'phone'];
799 foreach ($blocks as $name) {
800 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
803 foreach ($defaults[$name] as $count => & $values) {
805 //get location type id.
806 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
808 if ($name == 'address') {
809 // FIXME: lookupValue doesn't work for vcard_name
810 if (!empty($values['location_type_id'])) {
811 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', ['labelColumn' => 'vcard_name']);
812 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
815 if (!CRM_Utils_Array
::lookupValue($values,
817 CRM_Core_PseudoConstant
::country(),
822 CRM_Utils_Array
::lookupValue($values,
824 CRM_Core_PseudoConstant
::countryIsoCode(),
828 $stateProvinceID = self
::resolveStateProvinceID($values, $values['country_id'] ??
NULL);
829 if ($stateProvinceID) {
830 $values['state_province_id'] = $stateProvinceID;
833 if (!empty($values['state_province_id'])) {
834 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
837 $countyList = CRM_Core_PseudoConstant
::county();
839 CRM_Utils_Array
::lookupValue($values,
847 CRM_Utils_Array
::lookupValue($values,
849 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
854 if ($name == 'phone') {
855 CRM_Utils_Array
::lookupValue($values,
857 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
862 // Kill the reference.
869 * Fetch object based on array of properties.
871 * @param array $params
872 * (reference ) an assoc array of name/value pairs.
873 * @param array $defaults
874 * (reference ) an assoc array to hold the name / value pairs.
875 * in a hierarchical manner
876 * @param bool $microformat
877 * For location in microformat.
879 * @return CRM_Contact_BAO_Contact
881 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
882 if (array_key_exists('contact_id', $params)) {
883 $params['id'] = $params['contact_id'];
885 elseif (array_key_exists('id', $params)) {
886 $params['contact_id'] = $params['id'];
889 $contact = self
::getValues($params, $defaults);
891 unset($params['id']);
893 $contact->im
= $defaults['im'] = CRM_Core_BAO_IM
::getValues(['contact_id' => $params['contact_id']]);
894 $contact->email
= $defaults['email'] = CRM_Core_BAO_Email
::getValues(['contact_id' => $params['contact_id']]);
895 $contact->openid
= $defaults['openid'] = CRM_Core_BAO_OpenID
::getValues(['contact_id' => $params['contact_id']]);
896 $contact->phone
= $defaults['phone'] = CRM_Core_BAO_Phone
::getValues(['contact_id' => $params['contact_id']]);
897 $contact->address
= $defaults['address'] = CRM_Core_BAO_Address
::getValues(['contact_id' => $params['contact_id']], $microformat);
898 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
900 if (!isset($params['noNotes'])) {
901 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
904 if (!isset($params['noRelationships'])) {
905 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
908 if (!isset($params['noGroups'])) {
909 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
916 * Get the display name of a contact.
921 * @return null|string
922 * display name of the contact if found
924 public static function displayName($id) {
927 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
934 * Delete a contact and all its associated records.
937 * Id of the contact to delete.
938 * @param bool $restore
939 * Whether to actually restore, not delete.
940 * @param bool $skipUndelete
941 * Whether to force contact delete or not.
942 * @param bool $checkPermissions
945 * Was contact deleted?
947 * @throws \CRM_Core_Exception
948 * @throws \CiviCRM_API3_Exception
950 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
952 if (!$id ||
!is_numeric($id)) {
953 CRM_Core_Error
::deprecatedFunctionWarning('calling delete contact without a valid contact ID is deprecated.');
956 // If trash is disabled in system settings then we always skip
957 if (!Civi
::settings()->get('contact_undelete')) {
958 $skipUndelete = TRUE;
961 // make sure we have edit permission for this contact
963 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
964 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
970 // Restrict contact to be delete if contact has financial trxns
972 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent([$id], $error)) {
976 // make sure this contact_id does not have any membership types
977 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
980 'member_of_contact_id'
982 if ($membershipTypeID) {
986 $contact = new CRM_Contact_DAO_Contact();
988 if (!$contact->find(TRUE)) {
992 $contactType = $contact->contact_type
;
994 // @todo deprecate calling contactDelete with the intention to restore.
996 'id' => $contact->id
,
997 'is_deleted' => FALSE,
999 self
::create($updateParams);
1003 // start a new transaction
1004 $transaction = new CRM_Core_Transaction();
1006 if ($skipUndelete) {
1007 $hookParams = ['check_permissions' => $checkPermissions];
1008 CRM_Utils_Hook
::pre('delete', $contactType, $id, $hookParams);
1010 //delete billing address if exists.
1011 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
1013 // delete the log entries since we dont have triggers enabled as yet
1014 $logDAO = new CRM_Core_DAO_Log();
1015 $logDAO->entity_table
= 'civicrm_contact';
1016 $logDAO->entity_id
= $id;
1019 // delete contact participants CRM-12155
1020 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
1022 // delete contact contributions CRM-12155
1023 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
1025 // do activity cleanup, CRM-5604
1026 CRM_Activity_BAO_Activity
::cleanupActivity($id);
1028 // delete all notes related to contact
1029 CRM_Core_BAO_Note
::cleanContactNotes($id);
1031 // delete cases related to contact
1032 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
1033 if (!empty($contactCases)) {
1034 foreach ($contactCases as $caseId) {
1035 //check if case is associate with other contact or not.
1036 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
1037 if (count($caseContactId) <= 1) {
1038 CRM_Case_BAO_Case
::deleteCase($caseId);
1046 self
::contactTrash($contact);
1048 // currently we only clear employer cache.
1049 // we are now deleting inherited membership if any.
1050 if ($contact->contact_type
== 'Organization') {
1051 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
1052 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
1053 if (!empty($relationshipDtls)) {
1054 foreach ($relationshipDtls as $rId => $details) {
1055 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
1058 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
1061 //delete the contact id from recently view
1062 CRM_Utils_Recent
::del(['contact_id' => $id]);
1063 self
::updateContactCache($id, empty($restore));
1065 // delete any prevnext/dupe cache entry
1066 // These two calls are redundant in default deployments, but they're
1067 // meaningful if "prevnext" is memory-backed.
1068 Civi
::service('prevnext')->deleteItem($id);
1069 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1071 $transaction->commit();
1073 if ($skipUndelete) {
1074 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1081 * Action to update any caches relating to a recently update contact.
1083 * I was going to call this from delete as well as from create to ensure the delete is being
1084 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1085 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1086 * where the call involved a subquery that was locking the table.
1088 * @param int $contactID
1089 * @param bool $isTrashed
1091 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1094 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1095 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1096 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1097 // but this should not cause any change as long as contacts are not being trashed outside the
1098 // main functions for that.
1099 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1102 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1107 * Delete the image of a contact.
1110 * Id of the contact.
1113 * Was contact image deleted?
1115 public static function deleteContactImage($id) {
1120 $contact = new self();
1122 $contact->image_URL
= 'null';
1129 * Return proportional height and width of the image.
1131 * @param int $imageWidth
1134 * @param int $imageHeight
1138 * Thumb dimension of image
1140 public static function getThumbSize($imageWidth, $imageHeight) {
1142 if ($imageWidth && $imageHeight) {
1143 $imageRatio = $imageWidth / $imageHeight;
1148 if ($imageRatio > 1) {
1149 $imageThumbWidth = $thumbWidth;
1150 $imageThumbHeight = round($thumbWidth / $imageRatio);
1153 $imageThumbHeight = $thumbWidth;
1154 $imageThumbWidth = round($thumbWidth * $imageRatio);
1157 return [$imageThumbWidth, $imageThumbHeight];
1161 * Validate type of contact image.
1163 * @param array $params
1164 * @param string $imageIndex
1165 * Index of image field.
1166 * @param string $statusMsg
1167 * Status message to be set after operation.
1168 * @param string $opType
1169 * Type of operation like fatal, bounce etc.
1172 * true if valid image extension
1174 public static function processImageParams(
1176 $imageIndex = 'image_URL',
1190 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1191 $photo = basename($params[$imageIndex]['name']);
1192 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1196 unset($params[$imageIndex]);
1198 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1200 if ($opType == 'status') {
1201 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1203 // FIXME: additional support for fatal, bounce etc could be added.
1209 * Extract contact id from url for deleting contact image.
1211 public static function processImage() {
1213 $action = CRM_Utils_Request
::retrieve('action', 'String');
1214 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1215 // retrieve contact id in case of Profile context
1216 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1217 $cid = $cid ?
$cid : $id;
1218 if ($action & CRM_Core_Action
::DELETE
) {
1219 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1220 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1221 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1222 $session = CRM_Core_Session
::singleton();
1223 $toUrl = $session->popUserContext();
1224 CRM_Utils_System
::redirect($toUrl);
1230 * Function to set is_delete true or restore deleted contact.
1232 * @param CRM_Contact_DAO_Contact $contact
1233 * Contact DAO object.
1234 * @param bool $restore
1235 * True to set the is_delete = 1 else false to restore deleted contact,
1236 * i.e. is_delete = 0
1241 * @throws \CRM_Core_Exception
1243 public static function contactTrashRestore($contact, $restore = FALSE) {
1244 CRM_Core_Error
::deprecatedFunctionWarning('Use the api');
1247 CRM_Core_Error
::deprecatedFunctionWarning('Use contact.create to restore - this does nothing much');
1248 // @todo deprecate calling contactDelete with the intention to restore.
1250 'id' => $contact->id
,
1251 'is_deleted' => FALSE,
1253 self
::create($updateParams);
1256 return self
::contactTrash($contact);
1260 * Get contact type for a contact.
1263 * Id of the contact whose contact type is needed.
1266 * contact_type if $id found else null ""
1268 public static function getContactType($id) {
1269 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1273 * Get contact sub type for a contact.
1276 * Id of the contact whose contact sub type is needed.
1278 * @param string $implodeDelimiter
1281 * contact_sub_type if $id found else null ""
1283 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1284 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1286 return $implodeDelimiter ?
NULL : [];
1289 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1291 if ($implodeDelimiter) {
1292 $subtype = implode($implodeDelimiter, $subtype);
1298 * Get pair of contact-type and sub-type for a contact.
1301 * Id of the contact whose contact sub/contact type is needed.
1305 public static function getContactTypes($id) {
1306 $params = ['id' => $id];
1308 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1311 ['contact_type', 'contact_sub_type']
1316 if ($contact->contact_sub_type
) {
1317 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1319 array_unshift($contactTypes, $contact->contact_type
);
1321 return $contactTypes;
1324 throw new CRM_Core_Exception('Cannot proceed without a valid contact');
1329 * Combine all the importable fields from the lower levels object.
1331 * The ordering is important, since currently we do not have a weight
1332 * scheme. Adding weight is super important
1334 * @param int|string $contactType contact Type
1335 * @param bool $status
1336 * Status is used to manipulate first title.
1337 * @param bool $showAll
1338 * If true returns all fields (includes disabled fields).
1339 * @param bool $isProfile
1340 * If its profile mode.
1341 * @param bool $checkPermission
1342 * If false, do not include permissioning clause (for custom data).
1344 * @param bool $withMultiCustomFields
1347 * array of importable Fields
1349 public static function importableFields(
1350 $contactType = 'Individual',
1354 $checkPermission = TRUE,
1355 $withMultiCustomFields = FALSE
1357 if (empty($contactType)) {
1358 $contactType = 'All';
1361 $cacheKeyString = "importableFields $contactType";
1362 $cacheKeyString .= $status ?
'_1' : '_0';
1363 $cacheKeyString .= $showAll ?
'_1' : '_0';
1364 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1365 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1366 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1368 $fields = self
::$_importableFields[$cacheKeyString] ?? Civi
::cache('fields')->get($cacheKeyString);
1371 $fields = CRM_Contact_DAO_Contact
::import();
1373 // get the fields thar are meant for contact types
1374 if (in_array($contactType, [
1380 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1383 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1384 CRM_Core_DAO_Phone
::import(),
1385 CRM_Core_DAO_Email
::import(),
1386 CRM_Core_DAO_IM
::import(TRUE),
1387 CRM_Core_DAO_OpenID
::import()
1390 $locationFields = array_merge($locationFields,
1391 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1399 foreach ($locationFields as $key => $field) {
1400 $locationFields[$key]['hasLocationType'] = TRUE;
1403 $fields = array_merge($fields, $locationFields);
1405 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1406 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1409 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1410 $fields['url']['hasWebsiteType'] = TRUE;
1412 if ($contactType != 'All') {
1413 $fields = array_merge($fields,
1414 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1419 $withMultiCustomFields
1422 // Unset the fields which are not related to their contact type.
1423 foreach (CRM_Contact_DAO_Contact
::import() as $name => $value) {
1424 if (!empty($value['contactType']) && $value['contactType'] !== $contactType) {
1425 unset($fields[$name]);
1430 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1431 $fields = array_merge($fields,
1432 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1437 $withMultiCustomFields
1444 $fields = array_merge($fields, [
1446 'title' => ts('Group(s)'),
1450 'title' => ts('Tag(s)'),
1454 'title' => ts('Note'),
1457 'communication_style_id' => [
1458 'title' => ts('Communication Style'),
1459 'name' => 'communication_style_id',
1464 //Sorting fields in alphabetical order(CRM-1507)
1465 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1467 Civi
::cache('fields')->set($cacheKeyString, $fields);
1470 self
::$_importableFields[$cacheKeyString] = $fields;
1474 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1475 self
::$_importableFields[$cacheKeyString]
1479 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1480 self
::$_importableFields[$cacheKeyString]
1488 * Combine all the exportable fields from the lower levels object.
1490 * Currently we are using importable fields as exportable fields
1492 * @param int|string $contactType contact Type
1493 * @param bool $status
1494 * True while exporting primary contacts.
1495 * @param bool $export
1496 * True when used during export.
1497 * @param bool $search
1498 * True when used during search, might conflict with export param?.
1500 * @param bool $withMultiRecord
1501 * @param bool $checkPermissions
1504 * array of exportable Fields
1506 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1507 if (empty($contactType)) {
1508 $contactType = 'All';
1511 $cacheKeyString = "exportableFields $contactType";
1512 $cacheKeyString .= $export ?
'_1' : '_0';
1513 $cacheKeyString .= $status ?
'_1' : '_0';
1514 $cacheKeyString .= $search ?
'_1' : '_0';
1515 $cacheKeyString .= '_' . (bool) $checkPermissions;
1516 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1517 //calculates custom fields takes into account the logged in user & caches that for all users
1518 //as an interim fix we will cache the fields by contact
1519 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1521 if (!self
::$_exportableFields ||
empty(self
::$_exportableFields[$cacheKeyString])) {
1522 if (!self
::$_exportableFields) {
1523 self
::$_exportableFields = [];
1526 // check if we can retrieve from database cache
1527 $fields = Civi
::cache('fields')->get($cacheKeyString);
1530 $fields = CRM_Contact_DAO_Contact
::export();
1532 // The fields are meant for contact types.
1533 if (in_array($contactType, [
1539 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1541 // add current employer for individuals
1542 $fields = array_merge($fields, [
1543 'current_employer' =>
1545 'name' => 'organization_name',
1546 'title' => ts('Current Employer'),
1547 'type' => CRM_Utils_Type
::T_STRING
,
1551 // This probably would be added anyway by appendPseudoConstantsToFields.
1553 'location_type' => [
1554 'name' => 'location_type',
1555 'where' => 'civicrm_location_type.name',
1556 'title' => ts('Location Type'),
1557 'type' => CRM_Utils_Type
::T_STRING
,
1563 'name' => 'im_provider',
1564 'where' => 'civicrm_im.provider_id',
1565 'title' => ts('IM Provider'),
1566 'type' => CRM_Utils_Type
::T_STRING
,
1570 $phoneFields = CRM_Core_DAO_Phone
::export();
1571 // This adds phone_type to the exportable fields and make it available for export.
1572 // with testing the same can be done to the other entities.
1573 CRM_Core_DAO
::appendPseudoConstantsToFields($phoneFields);
1574 $locationFields = array_merge($locationType,
1575 CRM_Core_DAO_Address
::export(),
1577 CRM_Core_DAO_Email
::export(),
1579 CRM_Core_DAO_IM
::export(TRUE),
1580 CRM_Core_DAO_OpenID
::export()
1583 $locationFields = array_merge($locationFields,
1584 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1587 foreach ($locationFields as $key => $field) {
1588 $locationFields[$key]['hasLocationType'] = TRUE;
1591 $fields = array_merge($fields, $locationFields);
1594 $fields = array_merge($fields,
1595 CRM_Core_DAO_Worldregion
::export()
1598 $fields = array_merge($fields,
1599 CRM_Contact_DAO_Contact
::export()
1603 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1605 if ($contactType != 'All') {
1606 $fields = array_merge($fields,
1607 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1611 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1612 $fields = array_merge($fields,
1613 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions ? CRM_Core_Permission
::VIEW
: FALSE, $withMultiRecord)
1619 $fields = array_merge($fields, [
1621 'title' => ts('Group(s)'),
1625 'title' => ts('Tag(s)'),
1629 'title' => ts('Note(s)'),
1635 $fields = array_merge($fields, [
1637 'title' => ts('Group(s)'),
1641 'title' => ts('Tag(s)'),
1645 'title' => ts('Note(s)'),
1651 //Sorting fields in alphabetical order(CRM-1507)
1652 foreach ($fields as $k => $v) {
1653 $sortArray[$k] = $v['title'] ??
NULL;
1656 $fields = array_merge($sortArray, $fields);
1657 //unset the field which are not related to their contact type.
1658 if ($contactType != 'All') {
1664 'organization_name',
1665 'email_greeting_custom',
1666 'postal_greeting_custom',
1679 'organization_name',
1687 'email_greeting_custom',
1688 'postal_greeting_custom',
1704 'email_greeting_custom',
1705 'postal_greeting_custom',
1715 foreach ($commonValues[$contactType] as $value) {
1716 unset($fields[$value]);
1720 Civi
::cache('fields')->set($cacheKeyString, $fields);
1722 self
::$_exportableFields[$cacheKeyString] = $fields;
1726 $fields = self
::$_exportableFields[$cacheKeyString];
1729 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1730 self
::$_exportableFields[$cacheKeyString]
1738 * Get the all contact details (Hierarchical).
1740 * @param int $contactId
1742 * @param array $fields
1748 public static function getHierContactDetails($contactId, $fields) {
1749 $params = [['contact_id', '=', $contactId, 0, 0]];
1751 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1753 // We don't know the contents of return properties, but we need the lower
1754 // level ids of the contact so add a few fields.
1755 $returnProperties['first_name'] = 1;
1756 $returnProperties['organization_name'] = 1;
1757 $returnProperties['household_name'] = 1;
1758 $returnProperties['contact_type'] = 1;
1759 $returnProperties['contact_sub_type'] = 1;
1760 [$query] = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties);
1765 * Given a set of flat profile style field names, create a hierarchy.
1767 * This is for the query to use, create the right sql.
1769 * @param array $fields
1770 * @param int $contactId
1774 * A hierarchical property tree if appropriate
1776 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1777 $locationTypes = CRM_Core_BAO_Address
::buildOptions('location_type_id', 'validate');
1779 $returnProperties = [];
1781 $multipleFields = ['website' => 'url'];
1782 foreach ($fields as $name => $dontCare) {
1783 if (strpos($name, '-') !== FALSE) {
1784 [$fieldName, $id, $type] = CRM_Utils_System
::explode('-', $name, 3);
1786 if (!in_array($fieldName, $multipleFields)) {
1787 if ($id == 'Primary') {
1788 $locationTypeName = 1;
1791 $locationTypeName = $locationTypes[$id] ??
NULL;
1792 if (!$locationTypeName) {
1797 if (empty($returnProperties['location'])) {
1798 $returnProperties['location'] = [];
1800 if (empty($returnProperties['location'][$locationTypeName])) {
1801 $returnProperties['location'][$locationTypeName] = [];
1802 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1804 if (in_array($fieldName, [
1812 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1815 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1818 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1819 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1822 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1826 $returnProperties['website'][$id][$fieldName] = 1;
1830 $returnProperties[$name] = 1;
1834 return $returnProperties;
1838 * Return the primary location type of a contact.
1840 * $params int $contactId contact_id
1841 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1842 * $params boolean $skipDefaultPrimary if true, return primary contact location type otherwise null
1844 * @param int $contactId
1845 * @param bool $skipDefaultPrimary
1846 * @param string|null $block
1849 * $locationType location_type_id
1851 public static function getPrimaryLocationType($contactId, $skipDefaultPrimary = FALSE, $block = NULL) {
1853 $entityBlock = ['contact_id' => $contactId];
1854 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1855 foreach ($blocks[$block] as $key => $value) {
1856 if (!empty($value['is_primary'])) {
1857 $locationType = $value['location_type_id'] ??
NULL;
1864 IF ( civicrm_email.location_type_id IS NULL,
1865 IF ( civicrm_address.location_type_id IS NULL,
1866 IF ( civicrm_phone.location_type_id IS NULL,
1867 IF ( civicrm_im.location_type_id IS NULL,
1868 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1869 ,civicrm_im.location_type_id)
1870 ,civicrm_phone.location_type_id)
1871 ,civicrm_address.location_type_id)
1872 ,civicrm_email.location_type_id) as locationType
1873 FROM civicrm_contact
1874 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1875 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1876 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1877 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1878 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1879 WHERE civicrm_contact.id = %1 ";
1881 $params = [1 => [$contactId, 'Integer']];
1883 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1885 $locationType = NULL;
1886 if ($dao->fetch()) {
1887 $locationType = $dao->locationType
;
1890 if (isset($locationType)) {
1891 return $locationType;
1893 elseif ($skipDefaultPrimary) {
1894 // if there is no primary contact location then return null
1898 // if there is no primart contact location, then return default
1899 // location type of the system
1900 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1901 return $defaultLocationType->id
;
1906 * Get the display name, primary email and location type of a contact.
1909 * Id of the contact.
1912 * Array of display_name, email if found, do_not_email or (null,null,null)
1914 public static function getContactDetails($id) {
1915 // check if the contact type
1916 $contactType = self
::getContactType($id);
1918 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1921 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1922 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1923 WHERE civicrm_contact.id = %1
1924 ORDER BY civicrm_email.is_primary DESC";
1925 $params = [1 => [$id, 'Integer']];
1926 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1928 if ($dao->fetch()) {
1929 if ($contactType == 'Individual') {
1930 if ($dao->first_name ||
$dao->last_name
) {
1931 $name = "{$dao->first_name} {$dao->last_name}";
1934 $name = $dao->display_name
;
1938 $name = $dao->display_name
;
1940 $email = $dao->email
;
1941 $doNotEmail = (bool) $dao->do_not_email
;
1942 $onHold = (bool) $dao->on_hold
;
1943 $isDeceased = (bool) $dao->is_deceased
;
1944 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1946 return [NULL, NULL, NULL, NULL, NULL];
1950 * Add/edit/register contacts through profile.
1952 * @param array $params
1953 * Array of profile fields to be edited/added.
1954 * @param array $fields
1955 * Array of fields from UFGroup.
1956 * @param int $contactID
1957 * Id of the contact to be edited/added.
1958 * @param int $addToGroupID
1959 * Specifies the default group to which contact is added.
1960 * @param int $ufGroupId
1961 * Uf group id (profile id).
1962 * @param string $ctype
1963 * @param bool $visibility
1964 * Basically lets us know where this request is coming from.
1965 * if via a profile from web, we restrict what groups are changed
1968 * contact id created/edited
1970 * @throws \CRM_Core_Exception
1971 * @throws \CiviCRM_API3_Exception
1972 * @throws \Civi\API\Exception\UnauthorizedException
1974 public static function createProfileContact(
1978 $addToGroupID = NULL,
1983 // add ufGroupID to params array ( CRM-2012 )
1985 $params['uf_group_id'] = $ufGroupId;
1987 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1989 // If a user has logged in, or accessed via a checksum
1990 // Then deliberately 'blanking' a value in the profile should remove it from their record
1991 $session = CRM_Core_Session
::singleton();
1992 $params['updateBlankLocInfo'] = TRUE;
1993 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1994 $params['updateBlankLocInfo'] = FALSE;
1999 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
2003 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
2006 [$data, $contactDetails] = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
2008 // manage is_opt_out
2009 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
2010 $wasOptOut = $contactDetails['is_opt_out'] ??
FALSE;
2011 $isOptOut = $params['is_opt_out'];
2012 $data['is_opt_out'] = $isOptOut;
2013 // on change, create new civicrm_subscription_history entry
2014 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2016 'contact_id' => $contactDetails['contact_id'],
2017 'status' => $isOptOut ?
'Removed' : 'Added',
2020 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2024 $contact = self
::create($data);
2026 // contact is null if the profile does not have any contact fields
2028 $contactID = $contact->id
;
2031 if (empty($contactID)) {
2032 throw new CRM_Core_Exception('Cannot proceed without a valid contact id');
2035 // Process group and tag
2036 // @todo Contact::create also calls addContactsToGroup/removeContactsToGroup
2037 // Remove from here and use the existing functionality in Contact::create
2038 if (isset($params['group'])) {
2040 // this for sure means we are coming in via profile since i added it to fix
2041 // removing contacts from user groups -- lobo
2045 $groupParams = $params['group'] ??
[];
2046 $contactIds = [$contactID];
2050 $contactGroupList = CRM_Contact_BAO_GroupContact
::getContactGroup($contactID, 'Added',
2051 NULL, FALSE, $visibility
2053 if (is_array($contactGroupList)) {
2054 foreach ($contactGroupList as $key) {
2055 $groupId = $key['group_id'];
2056 $contactGroup[$groupId] = $groupId;
2060 // get the list of all the groups
2061 $allGroup = CRM_Contact_BAO_GroupContact
::getGroupList(0, $visibility);
2063 // check which values has to be add/remove contact from group
2064 foreach ($allGroup as $key => $varValue) {
2065 if (!empty($groupParams[$key]) && !array_key_exists($key, $contactGroup)) {
2066 // add contact to group
2067 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $key, $method);
2069 elseif (empty($groupParams[$key]) && array_key_exists($key, $contactGroup)) {
2070 // remove contact from group
2071 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $key, $method);
2076 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2077 // Convert comma separated form values from select2 v3
2078 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2079 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2082 // to add profile in default group
2083 // @todo merge this with code above which also calls addContactsToGroup
2084 if (is_array($addToGroupID)) {
2085 $contactIds = [$contactID];
2086 foreach ($addToGroupID as $groupId) {
2087 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2090 elseif ($addToGroupID) {
2091 $contactIds = [$contactID];
2092 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2096 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2099 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2105 * Format profile contact parameters.
2107 * @param array $params
2108 * @param array $fields
2109 * @param int|null $contactID
2110 * @param int|null $ufGroupId
2111 * @param string|null $ctype
2112 * @param bool $skipCustom
2116 public static function formatProfileContactParams(
2125 $data = $contactDetails = [];
2127 // get the contact details (hier)
2129 $details = self
::getHierContactDetails($contactID, $fields);
2131 $contactDetails = $details[$contactID];
2132 $data['contact_type'] = $contactDetails['contact_type'] ??
NULL;
2133 $data['contact_sub_type'] = $contactDetails['contact_sub_type'] ??
NULL;
2136 //we should get contact type only if contact
2138 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId, TRUE, FALSE, TRUE);
2140 //special case to handle profile with only contact fields
2141 if ($data['contact_type'] == 'Contact') {
2142 $data['contact_type'] = 'Individual';
2144 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2145 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2149 $data['contact_type'] = $ctype;
2152 $data['contact_type'] = 'Individual';
2156 //fix contact sub type CRM-5125
2157 if (array_key_exists('contact_sub_type', $params) &&
2158 !empty($params['contact_sub_type'])
2160 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2162 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2163 !empty($params['contact_sub_type_hidden'])
2165 // if profile was used, and had any subtype, we obtain it from there
2166 //CRM-13596 - add to existing contact types, rather than overwriting
2167 if (empty($data['contact_sub_type'])) {
2168 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2169 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2172 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2173 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2174 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2175 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2176 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2181 if ($ctype == 'Organization') {
2182 $data['organization_name'] = $contactDetails['organization_name'] ??
NULL;
2184 elseif ($ctype == 'Household') {
2185 $data['household_name'] = $contactDetails['household_name'] ??
NULL;
2193 $data['contact_id'] = $contactID;
2194 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2197 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2198 $defaultLocationId = $defaultLocation->id
;
2201 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2203 $blocks = ['email', 'phone', 'im', 'openid'];
2205 $multiplFields = ['url'];
2206 // prevent overwritten of formatted array, reset all block from
2207 // params if it is not in valid format (since import pass valid format)
2208 foreach ($blocks as $blk) {
2209 if (array_key_exists($blk, $params) &&
2210 !is_array($params[$blk])
2212 unset($params[$blk]);
2216 $primaryPhoneLoc = NULL;
2217 $session = CRM_Core_Session
::singleton();
2218 foreach ($params as $key => $value) {
2219 [$fieldName, $locTypeId, $typeId] = CRM_Utils_System
::explode('-', $key, 3);
2221 if ($locTypeId == 'Primary') {
2223 if (in_array($fieldName, $blocks)) {
2224 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2227 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2229 $primaryLocationType = $locTypeId;
2232 $locTypeId = $defaultLocationId;
2236 if (is_numeric($locTypeId) &&
2237 !in_array($fieldName, $multiplFields) &&
2238 substr($fieldName, 0, 7) != 'custom_'
2240 $index = $locTypeId;
2242 if (is_numeric($typeId)) {
2243 $index .= '-' . $typeId;
2245 if (!in_array($index, $locationType)) {
2246 $locationType[$count] = $index;
2250 $loc = CRM_Utils_Array
::key($index, $locationType);
2252 $blockName = self
::getLocationEntityForKey($fieldName);
2254 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2256 //set is_billing true, for location type "Billing"
2257 if ($locTypeId == $billingLocationTypeId) {
2258 $data[$blockName][$loc]['is_billing'] = 1;
2262 //get the primary location type
2263 if ($locTypeId == $primaryLocationType) {
2264 $data[$blockName][$loc]['is_primary'] = 1;
2267 elseif ($locTypeId == $defaultLocationId) {
2268 $data[$blockName][$loc]['is_primary'] = 1;
2271 if (in_array($fieldName, ['phone'])) {
2273 $data['phone'][$loc]['phone_type_id'] = $typeId;
2276 $data['phone'][$loc]['phone_type_id'] = '';
2278 $data['phone'][$loc]['phone'] = $value;
2280 //special case to handle primary phone with different phone types
2281 // in this case we make first phone type as primary
2282 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2283 $primaryPhoneLoc = $loc;
2286 if ($loc != $primaryPhoneLoc) {
2287 unset($data['phone'][$loc]['is_primary']);
2290 elseif ($fieldName == 'email') {
2291 $data['email'][$loc]['email'] = $value;
2292 if (empty($contactID)) {
2293 $data['email'][$loc]['is_primary'] = 1;
2296 elseif ($fieldName == 'im') {
2297 if (isset($params[$key . '-provider_id'])) {
2298 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2300 if (strpos($key, '-provider_id') !== FALSE) {
2301 $data['im'][$loc]['provider_id'] = $params[$key];
2304 $data['im'][$loc]['name'] = $value;
2307 elseif ($fieldName == 'openid') {
2308 $data['openid'][$loc]['openid'] = $value;
2311 if ($fieldName === 'state_province') {
2313 if (is_numeric($value) && ((int ) $value) >= 1000) {
2314 $data['address'][$loc]['state_province_id'] = $value;
2316 elseif (empty($value)) {
2317 $data['address'][$loc]['state_province_id'] = '';
2320 $data['address'][$loc]['state_province'] = $value;
2323 elseif ($fieldName === 'country') {
2325 if (is_numeric($value) && ((int ) $value) >= 1000
2327 $data['address'][$loc]['country_id'] = $value;
2329 elseif (empty($value)) {
2330 $data['address'][$loc]['country_id'] = '';
2333 $data['address'][$loc]['country'] = $value;
2336 elseif ($fieldName === 'county') {
2337 $data['address'][$loc]['county_id'] = $value;
2339 elseif ($fieldName == 'address_name') {
2340 $data['address'][$loc]['name'] = $value;
2342 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2343 $data['address'][$loc][substr($fieldName, 8)] = $value;
2346 $data[$blockName][$loc][$fieldName] = $value;
2351 if (substr($key, 0, 4) === 'url-') {
2352 $websiteField = explode('-', $key);
2353 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2354 $data['website'][$websiteField[1]]['url'] = $value;
2356 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2357 //save email/postal greeting and addressee values if any, CRM-4575
2358 $data[$key . '_id'] = $value;
2360 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2361 // for autocomplete transfer hidden value instead of label
2362 if ($params[$key] && isset($params[$key . '_id'])) {
2363 $value = $params[$key . '_id'];
2366 // we need to append time with date
2367 if ($params[$key] && isset($params[$key . '_time'])) {
2368 $value .= ' ' . $params[$key . '_time'];
2371 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2372 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2373 ($value == '' ||
!isset($value))
2379 if (!empty($params['customRecordValues'])) {
2380 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2381 foreach ($params['customRecordValues'] as $recId => $customFields) {
2382 if (is_array($customFields) && !empty($customFields)) {
2383 foreach ($customFields as $customFieldName) {
2384 if ($customFieldName == $key) {
2394 //CRM-13596 - check for contact_sub_type_hidden first
2395 if (array_key_exists('contact_sub_type_hidden', $params)) {
2396 $type = $params['contact_sub_type_hidden'];
2399 $type = $data['contact_type'];
2400 if (!empty($data['contact_sub_type'])) {
2401 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2405 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2415 elseif ($key === 'edit') {
2419 if ($key === 'location') {
2420 foreach ($value as $locationTypeId => $field) {
2421 foreach ($field as $block => $val) {
2422 if ($block === 'address' && array_key_exists('address_name', $val)) {
2423 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2428 if ($key === 'phone' && isset($params['phone_ext'])) {
2429 $data[$key] = $value;
2430 foreach ($value as $cnt => $phoneBlock) {
2431 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2432 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2436 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2437 && ($value == '' ||
!isset($value)) &&
2438 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2439 ($key === 'current_employer' && empty($params['current_employer']))) {
2440 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2441 // to avoid update with empty values
2445 $data[$key] = $value;
2451 if (!isset($data['contact_type'])) {
2452 $data['contact_type'] = 'Individual';
2455 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2456 $privacy = CRM_Core_SelectValues
::privacy();
2457 foreach ($privacy as $key => $value) {
2458 if (array_key_exists($key, $fields)) {
2459 // do not reset values for existing contacts, if fields are added to a profile
2460 if (array_key_exists($key, $params)) {
2461 $data[$key] = $params[$key];
2462 if (empty($params[$key])) {
2466 elseif (!$contactID) {
2472 return [$data, $contactDetails];
2476 * Find the get contact details.
2478 * This function does not respect ACLs for now, which might need to be rectified at some
2479 * stage based on how its used.
2481 * @param string $mail
2482 * Primary email address of the contact.
2483 * @param string $ctype
2486 * @return object|null
2487 * $dao contact details
2489 public static function matchContactOnEmail($mail, $ctype = NULL) {
2490 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2491 $mail = $strtolower(trim($mail));
2493 SELECT civicrm_contact.id as contact_id,
2494 civicrm_contact.hash as hash,
2495 civicrm_contact.contact_type as contact_type,
2496 civicrm_contact.contact_sub_type as contact_sub_type
2497 FROM civicrm_contact
2498 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2500 if (Civi
::settings()->get('uniq_email_per_site')) {
2501 // try to find a match within a site (multisite).
2502 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2503 if (!empty($groups)) {
2505 INNER JOIN civicrm_group_contact gc ON
2506 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2511 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2512 $p = [1 => [$mail, 'String']];
2515 $query .= " AND civicrm_contact.contact_type = %3";
2516 $p[3] = [$ctype, 'String'];
2519 $query .= " ORDER BY civicrm_email.is_primary DESC";
2521 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2523 if ($dao->fetch()) {
2530 * Find the contact details associated with an OpenID.
2532 * @param string $openId
2533 * OpenId of the contact.
2534 * @param string $ctype
2537 * @return object|null
2538 * $dao contact details
2540 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2541 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2542 $openId = $strtolower(trim($openId));
2544 SELECT civicrm_contact.id as contact_id,
2545 civicrm_contact.hash as hash,
2546 civicrm_contact.contact_type as contact_type,
2547 civicrm_contact.contact_sub_type as contact_sub_type
2548 FROM civicrm_contact
2549 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2550 WHERE civicrm_openid.openid = %1";
2551 $p = [1 => [$openId, 'String']];
2554 $query .= " AND civicrm_contact.contact_type = %3";
2555 $p[3] = [$ctype, 'String'];
2558 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2560 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2562 if ($dao->fetch()) {
2569 * Get primary email of the contact.
2571 * @param int $contactID
2573 * @param bool $polite
2574 * Whether to only pull an email if it's okay to send to it--that is, if it
2575 * is not on_hold and the contact is not do_not_email.
2578 * Email address if present else null
2580 public static function getPrimaryEmail($contactID, $polite = FALSE) {
2581 // fetch the primary email
2583 SELECT civicrm_email.email as email
2584 FROM civicrm_contact
2585 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2586 WHERE civicrm_email.is_primary = 1
2587 AND civicrm_contact.id = %1";
2590 AND civicrm_contact.do_not_email = 0
2591 AND civicrm_email.on_hold = 0';
2593 $p = [1 => [$contactID, 'Integer']];
2594 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2597 if ($dao->fetch()) {
2598 $email = $dao->email
;
2604 * Fetch the object and store the values in the values array.
2606 * @param array $params
2607 * Input parameters to find object.
2608 * @param array $values
2609 * Output values of the object.
2611 * @return CRM_Contact_BAO_Contact|null
2612 * The found object or null
2614 public static function getValues($params, &$values) {
2615 $contact = new CRM_Contact_BAO_Contact();
2617 $contact->copyValues($params);
2619 if ($contact->find(TRUE)) {
2621 CRM_Core_DAO
::storeValues($contact, $values);
2624 foreach (self
::$_commPrefs as $name) {
2625 if (isset($contact->$name)) {
2626 $privacy[$name] = $contact->$name;
2630 if (!empty($privacy)) {
2631 $values['privacy'] = $privacy;
2634 // communication Prefferance
2635 $preffComm = $comm = [];
2636 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2637 $contact->preferred_communication_method
2639 foreach ($comm as $value) {
2640 $preffComm[$value] = 1;
2642 $temp = ['preferred_communication_method' => $contact->preferred_communication_method
];
2645 'preferred_communication_method' => [
2646 'newName' => 'preferred_communication_method_display',
2647 'groupName' => 'preferred_communication_method',
2651 // @todo This can be figured out from metadata & we can avoid the uncached query.
2652 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2654 $values['preferred_communication_method'] = $preffComm;
2655 $values['preferred_communication_method_display'] = $temp['preferred_communication_method_display'] ??
NULL;
2657 if ($contact->preferred_mail_format
) {
2658 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2659 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2662 // get preferred languages
2663 if (!empty($contact->preferred_language
)) {
2664 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2667 // Calculating Year difference
2668 if ($contact->birth_date
) {
2669 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2670 if ($birthDate < date('Ymd')) {
2671 $deceasedDate = NULL;
2672 if (!empty($contact->is_deceased
) && !empty($contact->deceased_date
)) {
2673 $deceasedDate = $contact->deceased_date
;
2675 $age = CRM_Utils_Date
::calculateAge($birthDate, $deceasedDate);
2676 $values['age']['y'] = $age['years'] ??
NULL;
2677 $values['age']['m'] = $age['months'] ??
NULL;
2681 $contact->contact_id
= $contact->id
;
2689 * Provides counts for the contact summary tabs.
2691 * @param string $type
2692 * Type of record to count.
2693 * @param int $contactId
2695 * @param string|null $tableName
2696 * Deprecated - do not use
2699 * total number in database
2701 public static function getCountComponent(string $type, int $contactId, ?
string $tableName = NULL) {
2703 // TODO: Fix LineItemEditor extension to not use this function, then enable warning
2704 // CRM_Core_Error::deprecatedWarning('Deprecated argument $tableName passed to ' . __CLASS__ . '::' . __FUNCTION__);
2708 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2711 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2712 CRM_Contact_BAO_Relationship
::CURRENT
,
2720 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2723 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2726 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2729 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2731 case 'contribution':
2732 if (CRM_Core_Component
::isEnabled('CiviContribute')) {
2733 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2738 if (CRM_Core_Component
::isEnabled('CiviMember')) {
2739 return CRM_Member_BAO_Membership
::getContactMembershipCount((int) $contactId, TRUE);
2744 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2747 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2750 return CRM_Case_BAO_Case
::caseCount($contactId);
2754 'contact_id' => $contactId,
2757 'context' => 'activity',
2759 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2762 $params = ['contact_id' => $contactId];
2763 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2767 $custom = explode('_', $type);
2768 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom[1], 'table_name');
2770 $queryString = "SELECT count(id) FROM $tableName WHERE entity_id = $contactId";
2771 return (int) CRM_Core_DAO
::singleValueQuery($queryString);
2776 * Update contact greetings if an update has resulted in a custom field change.
2778 * @param array $updatedFields
2779 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2780 * @param array $contactParams
2781 * Parameters known about the contact. At minimum array('contact_id' => x).
2782 * Fields in this array will take precedence over DB fields (so far only
2783 * in the case of greeting id fields).
2785 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2786 $contactID = $contactParams['contact_id'];
2787 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2788 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2789 if (!empty($tokens['all']['contact'])) {
2790 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2791 if (!empty($affectedTokens)) {
2792 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2793 $contact = new CRM_Contact_BAO_Contact();
2794 $contact->id
= $contactID;
2795 $contact->find(TRUE);
2796 CRM_Contact_BAO_Contact
::processGreetings($contact);
2802 * Process greetings and cache.
2804 * @param \CRM_Contact_DAO_Contact $contact
2805 * Contact object after save.
2807 public static function processGreetings(&$contact) {
2809 $emailGreetingString = self
::getTemplateForGreeting('email_greeting', $contact);
2810 $postalGreetingString = self
::getTemplateForGreeting('postal_greeting', $contact);
2811 $addresseeString = self
::getTemplateForGreeting('addressee', $contact);
2812 //@todo this function does a lot of unnecessary loading.
2813 // ensureGreetingParamsAreSet now makes sure that the contact is
2814 // loaded and using updateGreetingsOnTokenFieldChange
2815 // allows us the possibility of only doing an update if required.
2817 // The contact object has not always required the
2818 // fields that are required to calculate greetings
2819 // so we need to retrieve it again.
2820 if ($contact->_query
!== FALSE) {
2821 $contact->find(TRUE);
2824 // store object values to an array
2825 $contactDetails = [];
2826 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2827 $contactDetails = [[$contact->id
=> $contactDetails]];
2829 $updateQueryString = [];
2831 if ($emailGreetingString) {
2832 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2835 'CRM_Contact_BAO_Contact'
2837 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2838 $updateQueryString[] = " email_greeting_display = '$emailGreetingString'";
2841 if ($postalGreetingString) {
2842 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2845 'CRM_Contact_BAO_Contact'
2847 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2848 $updateQueryString[] = " postal_greeting_display = '$postalGreetingString'";
2851 if ($addresseeString) {
2852 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2855 'CRM_Contact_BAO_Contact'
2857 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2858 $updateQueryString[] = " addressee_display = '$addresseeString'";
2861 if (!empty($updateQueryString)) {
2862 $updateQueryString = implode(',', $updateQueryString);
2863 $queryString = "UPDATE civicrm_contact SET $updateQueryString WHERE id = {$contact->id}";
2864 CRM_Core_DAO
::executeQuery($queryString);
2869 * Retrieve loc block ids w/ given condition.
2871 * @param int $contactId
2873 * @param array $criteria
2874 * Key => value pair which should be.
2875 * fulfill by return record ids.
2876 * @param string $condOperator
2877 * Operator use for grouping multiple conditions.
2880 * loc block ids which fulfill condition.
2882 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2885 return $locBlockIds;
2888 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2889 $name = strtolower($block);
2890 $className = "CRM_Core_DAO_$block";
2891 $blockDAO = new $className();
2893 // build the condition.
2894 if (is_array($criteria)) {
2895 $fields = $blockDAO->fields();
2897 foreach ($criteria as $field => $value) {
2898 if (array_key_exists($field, $fields)) {
2899 $cond = "( $field = $value )";
2900 // value might be zero or null.
2901 if (!$value ||
strtolower($value) === 'null') {
2902 $cond = "( $field = 0 OR $field IS NULL )";
2904 $conditions[] = $cond;
2907 if (!empty($conditions)) {
2908 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2912 $blockDAO->contact_id
= $contactId;
2914 while ($blockDAO->fetch()) {
2915 $locBlockIds[$name][] = $blockDAO->id
;
2919 return $locBlockIds;
2923 * Build context menu items.
2925 * @param int $contactId
2928 * Array of context menu for logged in user.
2930 public static function contextMenu($contactId = NULL) {
2933 'title' => ts('View Contact'),
2935 'ref' => 'view-contact',
2936 'class' => 'no-popup',
2938 'permissions' => ['view all contacts'],
2941 'title' => ts('Edit Contact'),
2943 'ref' => 'edit-contact',
2944 'class' => 'no-popup',
2946 'permissions' => ['edit all contacts'],
2949 'title' => ts('Delete Contact'),
2951 'ref' => 'delete-contact',
2953 'permissions' => ['access deleted contacts', 'delete contacts'],
2956 'title' => ts('Add Contribution'),
2958 'ref' => 'new-contribution',
2959 'key' => 'contribution',
2960 'tab' => 'contribute',
2961 'component' => 'CiviContribute',
2962 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2963 'reset=1&action=add&context=contribution'
2966 'access CiviContribute',
2967 'edit contributions',
2971 'title' => ts('Register for Event'),
2973 'ref' => 'new-participant',
2974 'key' => 'participant',
2975 'tab' => 'participant',
2976 'component' => 'CiviEvent',
2977 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2980 'edit event participants',
2984 'title' => ts('Record Activity'),
2986 'ref' => 'new-activity',
2987 'key' => 'activity',
2988 'permissions' => ['edit all contacts'],
2991 'title' => ts('Add Pledge'),
2993 'ref' => 'new-pledge',
2996 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2997 'reset=1&action=add&context=pledge'
2999 'component' => 'CiviPledge',
3001 'access CiviPledge',
3006 'title' => ts('Add Membership'),
3008 'ref' => 'new-membership',
3009 'key' => 'membership',
3011 'component' => 'CiviMember',
3012 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3013 'reset=1&action=add&context=membership'
3016 'access CiviMember',
3021 'title' => ts('Add Case'),
3023 'ref' => 'new-case',
3026 'component' => 'CiviCase',
3027 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3028 'permissions' => ['add cases'],
3031 'title' => ts('Add Grant'),
3033 'ref' => 'new-grant',
3036 'component' => 'CiviGrant',
3037 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3038 'reset=1&action=add&context=grant'
3040 'permissions' => ['edit grants'],
3043 'title' => ts('Add Relationship'),
3045 'ref' => 'new-relationship',
3048 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3049 'reset=1&action=add'
3051 'permissions' => ['edit all contacts'],
3054 'title' => ts('Add Note'),
3056 'ref' => 'new-note',
3059 'class' => 'medium-popup',
3060 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3061 'reset=1&action=add'
3063 'permissions' => ['edit all contacts'],
3066 'title' => ts('Send an Email'),
3068 'ref' => 'new-email',
3070 'permissions' => ['view all contacts'],
3073 'title' => ts('Add to Group'),
3075 'ref' => 'group-add-contact',
3078 'permissions' => ['edit groups'],
3081 'title' => ts('Tag Contact'),
3083 'ref' => 'tag-contact',
3086 'permissions' => ['edit all contacts'],
3090 $menu['otherActions'] = [
3092 'title' => ts('Print Summary'),
3093 'description' => ts('Printer-friendly view of this page.'),
3095 'ref' => 'crm-contact-print',
3098 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3102 'icon' => 'crm-i fa-print',
3105 'title' => ts('vCard'),
3106 'description' => ts('vCard record for this contact.'),
3108 'ref' => 'crm-contact-vcard',
3111 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3115 'icon' => 'crm-i fa-list-alt',
3119 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3120 $menu['otherActions']['dashboard'] = [
3121 'title' => ts('Contact Dashboard'),
3122 'description' => ts('Contact Dashboard'),
3124 'ref' => 'crm-contact-dashboard',
3125 'key' => 'dashboard',
3126 'tab' => 'dashboard',
3127 'class' => 'dashboard',
3128 // NOTE: As an alternative you can also build url on CMS specific way
3129 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3130 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id=$contactId"),
3131 'icon' => 'crm-i fa-tachometer',
3135 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3137 $menu['otherActions']['user-record'] = [
3138 'title' => ts('User Record'),
3139 'description' => ts('User Record'),
3141 'ref' => 'crm-contact-user-record',
3142 'key' => 'user-record',
3143 'tab' => 'user-record',
3144 'class' => 'user-record',
3145 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3146 'icon' => 'crm-i fa-user',
3149 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3150 $menu['otherActions']['user-add'] = [
3151 'title' => ts('Create User Record'),
3152 'description' => ts('Create User Record'),
3154 'ref' => 'crm-contact-user-add',
3155 'key' => 'user-add',
3156 'tab' => 'user-add',
3157 'class' => 'user-add',
3158 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3159 'icon' => 'crm-i fa-user-plus',
3163 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3164 //1. check for component is active.
3165 //2. check for user permissions.
3166 //3. check for acls.
3167 //3. edit and view contact are directly accessible to user.
3169 $aclPermissionedTasks = [
3174 'group-add-contact',
3178 $corePermission = CRM_Core_Permission
::getPermission();
3181 foreach ($menu as $key => $values) {
3182 if ($key !== 'otherActions') {
3184 // user does not have necessary permissions.
3185 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3188 // build directly accessible action menu.
3189 if (in_array($values['ref'], [
3193 $contextMenu['primaryActions'][$key] = [
3194 'title' => $values['title'],
3195 'ref' => $values['ref'],
3196 'class' => $values['class'] ??
NULL,
3197 'key' => $values['key'],
3202 // finally get menu item for -more- action widget.
3203 while (!empty($contextMenu['moreActions'][$values['weight']])) {
3204 // Quick & dirty way of handling 2 items with the same weight
3205 // without clobbering one.
3206 $values['weight']++
;
3208 $contextMenu['moreActions'][$values['weight']] = [
3209 'title' => $values['title'],
3210 'ref' => $values['ref'],
3211 'href' => $values['href'] ??
NULL,
3212 'tab' => $values['tab'] ??
NULL,
3213 'class' => $values['class'] ??
NULL,
3214 'key' => $values['key'],
3218 foreach ($values as $value) {
3219 // user does not have necessary permissions.
3220 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3224 // finally get menu item for -more- action widget.
3225 while (!empty($contextMenu['otherActions'][$value['weight']])) {
3226 // Quick & dirty way of handling 2 items with the same weight
3227 // without clobbering one.
3230 $contextMenu['otherActions'][$value['weight']] = [
3231 'title' => $value['title'],
3232 'ref' => $value['ref'],
3233 'href' => $value['href'] ??
NULL,
3234 'tab' => $value['tab'] ??
NULL,
3235 'class' => $value['class'] ??
NULL,
3236 'icon' => $value['icon'] ??
NULL,
3237 'key' => $value['key'],
3243 ksort($contextMenu['moreActions']);
3244 ksort($contextMenu['otherActions']);
3246 return $contextMenu;
3250 * Check if user has permissions to access items in action menu.
3252 * @param array $aclPermissionedTasks
3253 * Array containing ACL related tasks.
3254 * @param string $corePermission
3255 * The permission of the user (edit or view or null).
3256 * @param array $menuOptions
3257 * Array containing params of the menu (title, href, etc).
3260 * TRUE if user has all permissions, FALSE if otherwise.
3262 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3263 $componentName = $menuOptions['component'] ??
NULL;
3265 // if component action - make sure component is enable.
3266 if ($componentName && !CRM_Core_Component
::isEnabled($componentName)) {
3270 // make sure user has all required permissions.
3271 $hasAllPermissions = FALSE;
3273 $permissions = $menuOptions['permissions'] ??
NULL;
3274 if (!is_array($permissions) ||
empty($permissions)) {
3275 $hasAllPermissions = TRUE;
3278 // iterate for required permissions in given permissions array.
3279 if (!$hasAllPermissions) {
3280 $hasPermissions = 0;
3281 foreach ($permissions as $permission) {
3282 if (CRM_Core_Permission
::check($permission)) {
3287 if (count($permissions) == $hasPermissions) {
3288 $hasAllPermissions = TRUE;
3291 // if still user does not have required permissions, check acl.
3292 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3293 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3294 $corePermission == CRM_Core_Permission
::EDIT
3296 $hasAllPermissions = TRUE;
3298 elseif (in_array($menuOptions['ref'], [
3301 // grant permissions for these tasks.
3302 $hasAllPermissions = TRUE;
3307 return $hasAllPermissions;
3311 * Retrieve display name of contact that address is shared.
3313 * This is based on $masterAddressId or $contactId .
3315 * @param int $masterAddressId
3317 * @param int $contactId
3318 * Contact id. (deprecated - do not use)
3320 * @return string|null
3321 * the found display name or null.
3323 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3324 $masterDisplayName = NULL;
3325 if (!$masterAddressId) {
3326 return $masterDisplayName;
3330 SELECT display_name from civicrm_contact
3331 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3332 WHERE civicrm_address.id = " . $masterAddressId;
3334 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3335 return $masterDisplayName;
3339 * Get the creation/modification times for a contact.
3341 * @param int $contactId
3344 * Dates - ('created_date' => $, 'modified_date' => $)
3346 public static function getTimestamps($contactId) {
3347 $timestamps = CRM_Core_DAO
::executeQuery(
3348 'SELECT created_date, modified_date
3349 FROM civicrm_contact
3352 1 => [$contactId, 'Integer'],
3355 if ($timestamps->fetch()) {
3357 'created_date' => $timestamps->created_date
,
3358 'modified_date' => $timestamps->modified_date
,
3367 * Get a list of triggers for the contact table.
3369 * @param array $info
3370 * @param string|null $tableName
3372 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3374 * @see hook_civicrm_triggerInfo
3375 * @see CRM_Core_DAO::triggerRebuild
3377 public static function triggerInfo(&$info, $tableName = NULL) {
3379 // Modifications to these records should update the contact timestamps.
3380 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3382 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3383 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3384 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3385 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3386 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3388 ->alterTriggerInfo($info, $tableName);
3390 // Update phone table to populate phone_numeric field
3391 if (!$tableName ||
$tableName == 'civicrm_phone') {
3392 // Define stored sql function needed for phones
3393 $sqlTriggers = Civi
::service('sql_triggers');
3394 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3395 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3397 'table' => ['civicrm_phone'],
3399 'event' => ['INSERT', 'UPDATE'],
3400 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3406 * Check if contact is being used in civicrm_domain based on $contactId.
3408 * @param int $contactId
3412 * true if present else false.
3414 public static function checkDomainContact($contactId) {
3418 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3429 * Get options for a given contact field.
3431 * @param string $fieldName
3432 * @param string $context
3433 * @param array $props
3434 * whatever is known about this dao object.
3436 * @return array|bool
3437 * @see CRM_Core_DAO::buildOptions
3439 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3440 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3442 * @see CRM_Core_DAO::buildOptionsContext
3444 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3446 // Special logic for fields whose options depend on context or properties
3447 switch ($fieldName) {
3448 case 'contact_sub_type':
3449 if (!empty($props['contact_type'])) {
3450 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3454 case 'contact_type':
3455 if ($context == 'search') {
3456 // CRM-15495 - EntityRef filters and basic search forms expect this format
3457 // FIXME: Search builder does not
3458 return CRM_Contact_BAO_ContactType
::getSelectElements();
3462 // The contact api supports some related entities so we'll honor that by fetching their options
3465 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3469 $props['entity_table'] = 'civicrm_contact';
3470 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3472 case 'state_province_id':
3473 case 'state_province':
3474 case 'state_province_name':
3479 case 'worldregion_id':
3480 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3483 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3487 * Event fired after modifying any entity.
3488 * @param \Civi\Core\Event\PostEvent $event
3490 public static function on_hook_civicrm_post(\Civi\Core\Event\PostEvent
$event) {
3491 // Handle deleting a related entity with is_primary
3492 $hasPrimary = ['Address', 'Email', 'IM', 'OpenID', 'Phone'];
3494 $event->action
=== 'delete' && $event->id
&&
3495 in_array($event->entity
, $hasPrimary) &&
3496 !empty($event->object->is_primary
) &&
3497 !empty($event->object->contact_id
)
3499 $daoClass = CRM_Core_DAO_AllCoreTables
::getFullName($event->entity
);
3500 $dao = new $daoClass();
3501 $dao->contact_id
= $event->object->contact_id
;
3502 $dao->is_primary
= 1;
3503 // Pick another record to be primary (if one isn't already)
3504 if (!$dao->find(TRUE)) {
3505 $dao->is_primary
= 0;
3506 if ($dao->find(TRUE)) {
3507 $baoClass = CRM_Core_DAO_AllCoreTables
::getBAOClassName($daoClass);
3508 $baoClass::writeRecord(['id' => $dao->id
, 'is_primary' => 1]);
3515 * Get the template string for the given greeting.
3517 * @param string $greetingType
3518 * @param CRM_Contact_DAO_Contact $contact
3522 private static function getTemplateForGreeting(string $greetingType, CRM_Contact_DAO_Contact
$contact): string {
3523 $customFieldName = $greetingType . '_custom';
3524 if (!CRM_Utils_System
::isNull($contact->$customFieldName)) {
3525 return $contact->$customFieldName;
3527 $idField = $greetingType . '_id';
3528 if (!is_numeric($contact->$idField)) {
3532 'contact_type' => $contact->contact_type
,
3533 'greeting_type' => $greetingType,
3535 return CRM_Core_PseudoConstant
::greeting($filter)[$contact->$idField] ??
'';
3541 public function addSelectWhereClause() {
3542 // We always return an array with these keys, even if they are empty,
3543 // because this tells the query builder that we have considered these fields for acls
3545 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3546 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
[] : ['!= 1'],
3548 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3553 * Get any existing duplicate contacts based on the input parameters.
3555 * @param array $input
3556 * Input parameters to be matched.
3557 * @param string $contactType
3558 * @param string $rule
3561 * @param $excludedContactIDs
3562 * An array of ids not to be included in the results.
3563 * @param bool $checkPermissions
3564 * @param int $ruleGroupID
3565 * ID of the rule group to be used if an override is desirable.
3566 * @param array $contextParams
3567 * The context if relevant, eg. ['event_id' => X]
3570 * @throws \CRM_Core_Exception
3572 public static function getDuplicateContacts(array $input, string $contactType, string $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []): array {
3573 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3574 $dedupeParams['check_permission'] = $checkPermissions;
3575 $dedupeParams['contact_type'] = $contactType;
3576 $dedupeParams['rule'] = $rule;
3577 $dedupeParams['rule_group_id'] = $ruleGroupID;
3578 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3579 $dedupeResults['ids'] = [];
3580 $dedupeResults['handled'] = FALSE;
3581 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3582 if (!$dedupeResults['handled']) {
3583 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3585 return $dedupeResults['ids'] ??
[];
3589 * Get the first duplicate contacts based on the input parameters.
3591 * @param array $input
3592 * Input parameters to be matched.
3593 * @param string $contactType
3594 * @param string $rule
3597 * @param $excludedContactIDs
3598 * An array of ids not to be included in the results.
3599 * @param bool $checkPermissions
3600 * @param int $ruleGroupID
3601 * ID of the rule group to be used if an override is desirable.
3602 * @param array $contextParams
3603 * The context if relevant, eg. ['event_id' => X]
3607 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3608 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3616 * Check if a field is associated with an entity that has a location type.
3618 * (ie. is an address, phone, email etc field).
3620 * @param string $fieldTitle
3621 * Title of the field (not the name - create a new function for that if required).
3625 public static function isFieldHasLocationType($fieldTitle) {
3626 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3627 if ($field['title'] === $fieldTitle) {
3628 return $field['hasLocationType'] ??
NULL;
3635 * @param array $appendProfiles
3636 * Name of profile(s) to append to each link.
3638 * @return array|false
3640 public static function getEntityRefCreateLinks($appendProfiles = []) {
3641 // You'd think that "create contacts" would be the permission to check,
3642 // But new contact popups are profile forms and those use their own permissions.
3643 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3647 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3648 $profiles[] = 'new_' . strtolower($contactType);
3650 $retrieved = civicrm_api3('uf_group', 'get', [
3651 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3654 $links = $append = [];
3655 if (!empty($retrieved['values'])) {
3657 'individual' => 'fa-user',
3658 'organization' => 'fa-building',
3659 'household' => 'fa-home',
3661 foreach ($retrieved['values'] as $id => $profile) {
3662 if (in_array($profile['name'], $profiles)) {
3664 'label' => $profile['title'],
3665 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3666 NULL, NULL, FALSE, FALSE, TRUE),
3667 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3668 'icon' => $icons[str_replace('new_', '', $profile['name'])] ??
NULL,
3675 foreach ($append as $id) {
3676 foreach ($links as &$link) {
3677 $link['url'] .= ",$id";
3687 public static function getEntityRefFilters() {
3689 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3690 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3691 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3692 ['key' => 'city', 'value' => ts('City'), 'type' => 'text', 'entity' => 'Address'],
3693 ['key' => 'postal_code', 'value' => ts('Postal Code'), 'type' => 'text', 'entity' => 'Address'],
3694 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3695 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3696 ['key' => 'first_name', 'value' => ts('First Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3697 ['key' => 'last_name', 'value' => ts('Last Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3698 ['key' => 'nick_name', 'value' => ts('Nick Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3699 ['key' => 'organization_name', 'value' => ts('Employer name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3700 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3701 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3702 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3703 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],
3708 * @param string $entityName
3709 * @param string $action
3710 * @param array $record
3713 * @see CRM_Core_DAO::checkAccess
3715 public static function _checkAccess(string $entityName, string $action, array $record, $userID): bool {
3718 return CRM_Core_Permission
::check('add contacts', $userID);
3721 $actionType = CRM_Core_Permission
::VIEW
;
3725 $actionType = CRM_Core_Permission
::DELETE
;
3729 $actionType = CRM_Core_Permission
::EDIT
;
3733 return CRM_Contact_BAO_Contact_Permission
::allow($record['id'], $actionType, $userID);