3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
{
20 * SQL function used to format the phone_numeric field via trigger.
22 * @see self::triggerInfo()
24 * Note that this is also used by the 4.3 upgrade script.
25 * @see CRM_Upgrade_Incremental_php_FourThree
27 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
29 const CREATE_STRIP_FUNCTION_43
= "
30 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255))
35 DECLARE output VARCHAR(255) DEFAULT '';
36 DECLARE iterator INT DEFAULT 1;
37 WHILE iterator < (LENGTH(input) + 1) DO
38 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
39 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
41 SET iterator = iterator + 1;
47 * The types of communication preferences.
51 public static $_commPrefs = [
64 public static $_greetingTypes = [
71 * Static field for all the contact information that we can potentially import.
75 public static $_importableFields = [];
78 * Static field for all the contact information that we can potentially export.
82 public static $_exportableFields = NULL;
87 public function __construct() {
88 parent
::__construct();
92 * Takes an associative array and creates a contact object.
94 * The function extracts all the params it needs to initialize the create a
95 * contact object. the params array could contain additional unused name/value
98 * @param array $params
99 * (reference) an assoc array of name/value pairs.
101 * @return CRM_Contact_DAO_Contact|CRM_Core_Error|NULL
102 * Created or updated contact object or error object.
103 * (error objects are being phased out in favour of exceptions)
104 * @throws \CRM_Core_Exception
106 public static function add(&$params) {
107 $contact = new CRM_Contact_DAO_Contact();
108 $contactID = $params['contact_id'] ??
NULL;
109 if (empty($params)) {
113 // Fix for validate contact sub type CRM-5143.
114 if (isset($params['contact_sub_type'])) {
115 if (empty($params['contact_sub_type'])) {
116 $params['contact_sub_type'] = 'null';
118 elseif ($params['contact_sub_type'] !== 'null') {
119 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
120 $params['contact_type'], TRUE
123 // we'll need to fix tests to handle this
125 throw new CRM_Core_Exception(ts('The Contact Sub Type does not match the Contact type for this record'));
127 $params['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
131 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
132 CRM_Utils_Array
::formatArrayKeys($params['preferred_communication_method']);
133 $contact->preferred_communication_method
= CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
134 unset($params['preferred_communication_method']);
137 $defaults = ['source' => $params['contact_source'] ??
NULL];
138 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
139 $defaults['display_name'] = $params['organization_name'];
140 $defaults['sort_name'] = $params['organization_name'];
142 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
143 $defaults['display_name'] = $params['household_name'];
144 $defaults['sort_name'] = $params['household_name'];
146 $params = array_merge($defaults, $params);
148 $allNull = $contact->copyValues($params);
150 $contact->id
= $contactID;
152 if ($contact->contact_type
=== 'Individual') {
154 // @todo allow the lines below to be overridden by input or hooks & add tests,
155 // as has been done for households and organizations.
156 // Format individual fields.
157 CRM_Contact_BAO_Individual
::format($params, $contact);
160 // Note that copyValues() above might already call this, via
161 // CRM_Utils_String::ellipsify(), but e.g. for Individual it gets put
162 // back or altered by Individual::format() just above, so we need to
164 // Note also orgs will get ellipsified, but if we do that here then
165 // some existing tests on individual fail.
166 // Also api v3 will enforce org naming length by failing, v4 will truncate.
167 if (mb_strlen($contact->display_name
, 'UTF-8') > 128) {
168 $contact->display_name
= mb_substr($contact->display_name
, 0, 128, 'UTF-8');
170 if (mb_strlen($contact->sort_name
, 'UTF-8') > 128) {
171 $contact->sort_name
= mb_substr($contact->sort_name
, 0, 128, 'UTF-8');
174 $privacy = $params['privacy'] ??
NULL;
175 if ($privacy && is_array($privacy)) {
177 foreach (self
::$_commPrefs as $name) {
178 $contact->$name = $privacy[$name] ??
FALSE;
182 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
183 // @todo - does this mean we can remove this block?
184 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
185 if ((!isset($contact->hash
) ||
!$contact->hash
) && !$contact->id
) {
187 $contact->hash
= md5(uniqid(rand(), TRUE));
190 // Even if we don't need $employerId, it's important to call getFieldValue() before
191 // the contact is saved because we want the existing value to be cached.
192 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
193 $employerId = (!$contactID ||
$contact->contact_type
!== 'Individual') ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
198 CRM_Core_BAO_Log
::register($contact->id
,
204 if ($contact->contact_type
=== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
205 // Create current employer.
206 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : $params['current_employer'] ??
NULL;
208 $newContact = empty($params['contact_id']);
210 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
212 elseif ($employerId) {
213 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
217 // Update cached employer name if the name of an existing organization is being updated.
218 if ($contact->contact_type
=== 'Organization' && !empty($params['organization_name']) && $contactID) {
219 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
228 * takes an associative array and creates a contact object and all the associated
229 * derived objects (i.e. individual, location, email, phone etc)
231 * This function is invoked from within the web form layer and also from the api layer
233 * @param array $params
234 * (reference ) an assoc array of name/value pairs.
235 * @param bool $fixAddress
236 * If we need to fix address.
237 * @param bool $invokeHooks
238 * If we need to invoke hooks.
240 * @param bool $skipDelete
241 * Unclear parameter, passed to website create
243 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
244 * Created or updated contribution object. We are deprecating returning an error in
245 * favour of exceptions
247 * @throws \CRM_Core_Exception
248 * @throws \CiviCRM_API3_Exception
249 * @throws \Civi\API\Exception\UnauthorizedException
251 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
253 if (empty($params['contact_type']) && empty($params['contact_id'])) {
257 $isEdit = !empty($params['contact_id']);
259 if ($isEdit && empty($params['contact_type'])) {
260 $params['contact_type'] = self
::getContactType($params['contact_id']);
263 if (!empty($params['check_permissions']) && isset($params['api_key'])
264 && !CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])
265 && !($isEdit && CRM_Core_Permission
::check('edit own api keys') && $params['contact_id'] == CRM_Core_Session
::getLoggedInContactID())
267 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify api key');
271 if (!empty($params['contact_id'])) {
272 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
275 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
279 self
::ensureGreetingParamsAreSet($params);
281 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
282 if (empty($params['contact_id'])) {
283 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
284 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
285 $params['preferred_language'] = $language;
288 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
289 if (empty($params['communication_style_id'])) {
290 $defaultCommunicationStyleId = CRM_Core_OptionGroup
::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
291 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
295 $transaction = new CRM_Core_Transaction();
297 $contact = self
::add($params);
299 $params['contact_id'] = $contact->id
;
301 if (Civi
::settings()->get('is_enabled')) {
302 // Enabling multisite causes the contact to be added to the domain group.
303 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
304 if (!empty($domainGroupID)) {
305 if (!empty($params['group']) && is_array($params['group'])) {
306 $params['group'][$domainGroupID] = 1;
309 $params['group'] = [$domainGroupID => 1];
314 if (!empty($params['group'])) {
315 $contactIds = [$params['contact_id']];
316 foreach ($params['group'] as $groupId => $flag) {
318 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
320 elseif ($flag == -1) {
321 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
326 // Add location Block data.
327 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
328 foreach ($blocks as $name => $value) {
329 $contact->$name = $value;
331 if (!empty($params['updateBlankLocInfo'])) {
335 if (isset($params['website'])) {
336 CRM_Core_BAO_Website
::process($params['website'], $contact->id
, $skipDelete);
339 $userID = CRM_Core_Session
::singleton()->get('userID');
341 if (!empty($params['note'])) {
342 if (is_array($params['note'])) {
343 foreach ($params['note'] as $note) {
344 $contactId = $contact->id
;
345 if (isset($note['contact_id'])) {
346 $contactId = $note['contact_id'];
348 //if logged in user, overwrite contactId
350 $contactId = $userID;
354 'entity_id' => $contact->id
,
355 'entity_table' => 'civicrm_contact',
356 'note' => $note['note'],
357 'subject' => $note['subject'] ??
NULL,
358 'contact_id' => $contactId,
360 CRM_Core_BAO_Note
::add($noteParams);
364 $contactId = $contact->id
;
365 //if logged in user, overwrite contactId
367 $contactId = $userID;
371 'entity_id' => $contact->id
,
372 'entity_table' => 'civicrm_contact',
373 'note' => $params['note'],
374 'subject' => $params['subject'] ??
NULL,
375 'contact_id' => $contactId,
377 CRM_Core_BAO_Note
::add($noteParams);
381 if (!empty($params['custom']) &&
382 is_array($params['custom'])
384 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
387 $transaction->commit();
389 // CRM-6367: fetch the right label for contact type’s display
390 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
391 'CRM_Contact_DAO_ContactType',
392 $contact->contact_type
,
397 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
401 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
404 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
408 // In order to prevent a series of expensive queries in intensive batch processing
409 // api calls may pass in skip_greeting_processing, probably doing it later via the
410 // scheduled job. CRM-21551
411 if (empty($params['skip_greeting_processing'])) {
412 self
::processGreetings($contact);
415 if (!empty($params['check_permissions'])) {
416 $contacts = [&$contact];
417 self
::unsetProtectedFields($contacts);
420 if (!empty($params['is_deceased'])) {
421 // Edit Membership Status
423 'contact_id' => $contact->id
,
424 'is_deceased' => $params['is_deceased'],
425 'deceased_date' => $params['deceased_date'] ??
NULL,
427 CRM_Member_BAO_Membership
::updateMembershipStatus($deceasedParams, $params['contact_type']);
434 * Format the output of the create contact function
436 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
438 public static function unsetProtectedFields(&$contacts) {
439 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
440 $currentUser = CRM_Core_Session
::getLoggedInContactID();
441 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
442 foreach ($contacts as &$contact) {
443 $cid = is_object($contact) ?
$contact->id
: $contact['id'] ??
NULL;
444 if (!($editOwn && $cid == $currentUser)) {
445 if (is_object($contact)) {
446 unset($contact->api_key
);
449 unset($contact['api_key']);
457 * Ensure greeting parameters are set.
459 * By always populating greetings here we can be sure they are set if required & avoid a call later.
460 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
462 * @param array $params
464 * @throws \CiviCRM_API3_Exception
466 public static function ensureGreetingParamsAreSet(&$params) {
467 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
468 $missingGreetingParams = [];
470 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
471 if (empty($params[$greetingParam])) {
472 $missingGreetingParams[$greetingIndex] = $greetingParam;
476 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
477 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
478 'id' => $params['contact_id'],
479 'return' => array_keys($missingGreetingParams),
482 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
483 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
484 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
487 // Filter out other fields.
488 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
489 $params = array_merge($params, $savedGreetings);
492 foreach ($missingGreetingParams as $greetingName => $greeting) {
493 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
497 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
498 if ($params[$greetingParam] === 'null') {
499 // If we are setting it to null then null out the display field.
500 $params[$greetingIndex . '_display'] = 'null';
506 * Get the display name and image of a contact.
511 * @param bool $includeTypeInReturnParameters
512 * Should type be part of the returned array?
515 * the displayName and contactImage for this contact
517 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
518 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
520 SELECT civicrm_contact.*,
521 civicrm_email.email as email
523 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
524 AND civicrm_email.is_primary = 1
525 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
526 $dao = new CRM_Core_DAO();
529 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
530 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
532 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
533 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
536 // use email if display_name is empty
537 if (empty($dao->display_name
)) {
538 $displayName = $dao->email
;
541 $displayName = $dao->display_name
;
544 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
546 return $includeTypeInReturnParameters ?
[
550 $dao->contact_sub_type
,
552 ] : [$displayName, $image, $imageUrl];
558 * Add billing fields to the params if appropriate.
560 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
561 * don't then we should set the name fields to the billing fields AND add the preserveDBName
562 * parameter (which will tell the BAO only to set those fields if none already exist.
564 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
565 * matching is best done by hipsters.
567 * @param array $params
569 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
571 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
572 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
573 foreach ($nameFields as $field) {
574 if (!empty($params[$field])) {
578 // There are only 3 - we can iterate through them twice :-)
579 foreach ($nameFields as $field) {
580 if (!empty($params['billing_' . $field])) {
581 $params[$field] = $params['billing_' . $field];
583 $params['preserveDBName'] = TRUE;
589 * Resolve a state province string (UT or Utah) to an ID.
591 * If country has been passed in we should select a state belonging to that country.
593 * Alternatively we should choose from enabled countries, prioritising the default country.
595 * @param array $values
596 * @param int|null $countryID
600 * @throws \CRM_Core_Exception
602 protected static function resolveStateProvinceID($values, $countryID) {
605 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
606 if (CRM_Utils_Array
::lookupValue($values,
611 return $values['state_province_id'];
613 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
614 if (CRM_Utils_Array
::lookupValue($values,
619 return $values['state_province_id'];
624 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
625 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
626 // prefer matching country..
627 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, ['country_id' => Civi
::settings()->get('defaultContactCountry')]);
628 if (CRM_Utils_Array
::lookupValue($values,
633 return $values['state_province_id'];
636 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
637 if (CRM_Utils_Array
::lookupValue($values,
642 return $values['state_province_id'];
645 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
646 if (CRM_Utils_Array
::lookupValue($values,
651 return $values['state_province_id'];
653 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
654 if (CRM_Utils_Array
::lookupValue($values,
659 return $values['state_province_id'];
667 * Get the relevant location entity for the array key.
669 * Based on the field name we determine which location entity
670 * we are dealing with. Apart from a few specific ones they
671 * are mostly 'address' (the default).
673 * @param string $fieldName
677 protected static function getLocationEntityForKey($fieldName) {
678 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
681 if ($fieldName === 'phone_ext') {
688 * Soft delete a contact.
690 * Call this via the api, not directly.
692 * @param \CRM_Contact_BAO_Contact $contact
695 * @throws \CRM_Core_Exception
697 protected static function contactTrash($contact): bool {
699 'id' => $contact->id
,
702 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
704 $params = [1 => [$contact->id
, 'Integer']];
705 $query = 'DELETE FROM civicrm_uf_match WHERE contact_id = %1';
706 CRM_Core_DAO
::executeQuery($query, $params);
708 $contact->copyValues($updateParams);
710 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
712 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
718 * Create last viewed link to recently updated contact.
720 * @param array $crudLinkSpec
721 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
722 * - entity_table: string, eg "civicrm_contact"
726 * NULL if unavailable, or
727 * [path: string, query: string, title: string]
728 * @see CRM_Utils_System::createDefaultCrudLink
730 public function createDefaultCrudLink($crudLinkSpec) {
731 switch ($crudLinkSpec['action']) {
732 case CRM_Core_Action
::VIEW
:
734 'title' => $this->display_name
,
735 'path' => 'civicrm/contact/view',
743 case CRM_Core_Action
::UPDATE
:
745 'title' => $this->display_name
,
746 'path' => 'civicrm/contact/add',
749 'action' => 'update',
759 * Get the values for pseudoconstants for name->value and reverse.
761 * @param array $defaults
762 * (reference) the default values, some of which need to be resolved.
763 * @param bool $reverse
764 * Always true as this function is only called from one place..
768 * This is called specifically from the contact import parser & should be moved there
769 * as it is not truly a generic function.
772 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
773 // Hack for birth_date.
774 if (!empty($defaults['birth_date'])) {
775 if (is_array($defaults['birth_date'])) {
776 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
780 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
781 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
782 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
783 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
785 //lookup value of email/postal greeting, addressee, CRM-4575
786 foreach (self
::$_greetingTypes as $greeting) {
788 'contact_type' => $defaults['contact_type'] ??
NULL,
789 'greeting_type' => $greeting,
791 CRM_Utils_Array
::lookupValue($defaults, $greeting,
792 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
796 $blocks = ['address', 'im', 'phone'];
797 foreach ($blocks as $name) {
798 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
801 foreach ($defaults[$name] as $count => & $values) {
803 //get location type id.
804 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
806 if ($name == 'address') {
807 // FIXME: lookupValue doesn't work for vcard_name
808 if (!empty($values['location_type_id'])) {
809 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', ['labelColumn' => 'vcard_name']);
810 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
813 if (!CRM_Utils_Array
::lookupValue($values,
815 CRM_Core_PseudoConstant
::country(),
820 CRM_Utils_Array
::lookupValue($values,
822 CRM_Core_PseudoConstant
::countryIsoCode(),
826 $stateProvinceID = self
::resolveStateProvinceID($values, $values['country_id'] ??
NULL);
827 if ($stateProvinceID) {
828 $values['state_province_id'] = $stateProvinceID;
831 if (!empty($values['state_province_id'])) {
832 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
835 $countyList = CRM_Core_PseudoConstant
::county();
837 CRM_Utils_Array
::lookupValue($values,
845 CRM_Utils_Array
::lookupValue($values,
847 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
852 if ($name == 'phone') {
853 CRM_Utils_Array
::lookupValue($values,
855 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
860 // Kill the reference.
867 * Fetch object based on array of properties.
869 * @param array $params
870 * (reference ) an assoc array of name/value pairs.
871 * @param array $defaults
872 * (reference ) an assoc array to hold the name / value pairs.
873 * in a hierarchical manner
874 * @param bool $microformat
875 * For location in microformat.
877 * @return CRM_Contact_BAO_Contact
879 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
880 if (array_key_exists('contact_id', $params)) {
881 $params['id'] = $params['contact_id'];
883 elseif (array_key_exists('id', $params)) {
884 $params['contact_id'] = $params['id'];
887 $contact = self
::getValues($params, $defaults);
889 unset($params['id']);
891 //get the block information for this contact
892 $entityBlock = ['contact_id' => $params['contact_id']];
893 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
894 $defaults = array_merge($defaults, $blocks);
895 foreach ($blocks as $block => $value) {
896 $contact->$block = $value;
899 if (!isset($params['noNotes'])) {
900 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
903 if (!isset($params['noRelationships'])) {
904 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
907 if (!isset($params['noGroups'])) {
908 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
911 if (!isset($params['noWebsite'])) {
912 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
919 * Get the display name of a contact.
924 * @return null|string
925 * display name of the contact if found
927 public static function displayName($id) {
930 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
937 * Delete a contact and all its associated records.
940 * Id of the contact to delete.
941 * @param bool $restore
942 * Whether to actually restore, not delete.
943 * @param bool $skipUndelete
944 * Whether to force contact delete or not.
945 * @param bool $checkPermissions
948 * Was contact deleted?
950 * @throws \CRM_Core_Exception
951 * @throws \CiviCRM_API3_Exception
953 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
955 if (!$id ||
!is_numeric($id)) {
956 CRM_Core_Error
::deprecatedFunctionWarning('calling delete contact without a valid contact ID is deprecated.');
959 // If trash is disabled in system settings then we always skip
960 if (!Civi
::settings()->get('contact_undelete')) {
961 $skipUndelete = TRUE;
964 // make sure we have edit permission for this contact
966 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
967 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
973 // Restrict contact to be delete if contact has financial trxns
975 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent([$id], $error)) {
979 // make sure this contact_id does not have any membership types
980 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
983 'member_of_contact_id'
985 if ($membershipTypeID) {
989 $contact = new CRM_Contact_DAO_Contact();
991 if (!$contact->find(TRUE)) {
995 $contactType = $contact->contact_type
;
997 // @todo deprecate calling contactDelete with the intention to restore.
999 'id' => $contact->id
,
1000 'is_deleted' => FALSE,
1002 self
::create($updateParams);
1006 // start a new transaction
1007 $transaction = new CRM_Core_Transaction();
1009 if ($skipUndelete) {
1010 $hookParams = ['check_permissions' => $checkPermissions];
1011 CRM_Utils_Hook
::pre('delete', $contactType, $id, $hookParams);
1013 //delete billing address if exists.
1014 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
1016 // delete the log entries since we dont have triggers enabled as yet
1017 $logDAO = new CRM_Core_DAO_Log();
1018 $logDAO->entity_table
= 'civicrm_contact';
1019 $logDAO->entity_id
= $id;
1022 // delete contact participants CRM-12155
1023 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
1025 // delete contact contributions CRM-12155
1026 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
1028 // do activity cleanup, CRM-5604
1029 CRM_Activity_BAO_Activity
::cleanupActivity($id);
1031 // delete all notes related to contact
1032 CRM_Core_BAO_Note
::cleanContactNotes($id);
1034 // delete cases related to contact
1035 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
1036 if (!empty($contactCases)) {
1037 foreach ($contactCases as $caseId) {
1038 //check if case is associate with other contact or not.
1039 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
1040 if (count($caseContactId) <= 1) {
1041 CRM_Case_BAO_Case
::deleteCase($caseId);
1049 self
::contactTrash($contact);
1051 // currently we only clear employer cache.
1052 // we are now deleting inherited membership if any.
1053 if ($contact->contact_type
== 'Organization') {
1054 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
1055 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
1056 if (!empty($relationshipDtls)) {
1057 foreach ($relationshipDtls as $rId => $details) {
1058 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
1061 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
1064 //delete the contact id from recently view
1065 CRM_Utils_Recent
::delContact($id);
1066 self
::updateContactCache($id, empty($restore));
1068 // delete any prevnext/dupe cache entry
1069 // These two calls are redundant in default deployments, but they're
1070 // meaningful if "prevnext" is memory-backed.
1071 Civi
::service('prevnext')->deleteItem($id);
1072 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1074 $transaction->commit();
1076 if ($skipUndelete) {
1077 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1084 * Action to update any caches relating to a recently update contact.
1086 * I was going to call this from delete as well as from create to ensure the delete is being
1087 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1088 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1089 * where the call involved a subquery that was locking the table.
1091 * @param int $contactID
1092 * @param bool $isTrashed
1094 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1097 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1098 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1099 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1100 // but this should not cause any change as long as contacts are not being trashed outside the
1101 // main functions for that.
1102 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1105 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1110 * Delete the image of a contact.
1113 * Id of the contact.
1116 * Was contact image deleted?
1118 public static function deleteContactImage($id) {
1123 $contact = new self();
1125 $contact->image_URL
= 'null';
1132 * Return proportional height and width of the image.
1134 * @param int $imageWidth
1137 * @param int $imageHeight
1141 * Thumb dimension of image
1143 public static function getThumbSize($imageWidth, $imageHeight) {
1145 if ($imageWidth && $imageHeight) {
1146 $imageRatio = $imageWidth / $imageHeight;
1151 if ($imageRatio > 1) {
1152 $imageThumbWidth = $thumbWidth;
1153 $imageThumbHeight = round($thumbWidth / $imageRatio);
1156 $imageThumbHeight = $thumbWidth;
1157 $imageThumbWidth = round($thumbWidth * $imageRatio);
1160 return [$imageThumbWidth, $imageThumbHeight];
1164 * Validate type of contact image.
1166 * @param array $params
1167 * @param string $imageIndex
1168 * Index of image field.
1169 * @param string $statusMsg
1170 * Status message to be set after operation.
1171 * @param string $opType
1172 * Type of operation like fatal, bounce etc.
1175 * true if valid image extension
1177 public static function processImageParams(
1179 $imageIndex = 'image_URL',
1193 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1194 $photo = basename($params[$imageIndex]['name']);
1195 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1199 unset($params[$imageIndex]);
1201 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1203 if ($opType == 'status') {
1204 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1206 // FIXME: additional support for fatal, bounce etc could be added.
1212 * Extract contact id from url for deleting contact image.
1214 public static function processImage() {
1216 $action = CRM_Utils_Request
::retrieve('action', 'String');
1217 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1218 // retrieve contact id in case of Profile context
1219 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1220 $cid = $cid ?
$cid : $id;
1221 if ($action & CRM_Core_Action
::DELETE
) {
1222 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1223 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1224 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1225 $session = CRM_Core_Session
::singleton();
1226 $toUrl = $session->popUserContext();
1227 CRM_Utils_System
::redirect($toUrl);
1233 * Function to set is_delete true or restore deleted contact.
1235 * @param CRM_Contact_DAO_Contact $contact
1236 * Contact DAO object.
1237 * @param bool $restore
1238 * True to set the is_delete = 1 else false to restore deleted contact,
1239 * i.e. is_delete = 0
1244 * @throws \CRM_Core_Exception
1246 public static function contactTrashRestore($contact, $restore = FALSE) {
1247 CRM_Core_Error
::deprecatedFunctionWarning('Use the api');
1250 CRM_Core_Error
::deprecatedFunctionWarning('Use contact.create to restore - this does nothing much');
1251 // @todo deprecate calling contactDelete with the intention to restore.
1253 'id' => $contact->id
,
1254 'is_deleted' => FALSE,
1256 self
::create($updateParams);
1259 return self
::contactTrash($contact);
1263 * Get contact type for a contact.
1266 * Id of the contact whose contact type is needed.
1269 * contact_type if $id found else null ""
1271 public static function getContactType($id) {
1272 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1276 * Get contact sub type for a contact.
1279 * Id of the contact whose contact sub type is needed.
1281 * @param string $implodeDelimiter
1284 * contact_sub_type if $id found else null ""
1286 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1287 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1289 return $implodeDelimiter ?
NULL : [];
1292 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1294 if ($implodeDelimiter) {
1295 $subtype = implode($implodeDelimiter, $subtype);
1301 * Get pair of contact-type and sub-type for a contact.
1304 * Id of the contact whose contact sub/contact type is needed.
1308 public static function getContactTypes($id) {
1309 $params = ['id' => $id];
1311 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1314 ['contact_type', 'contact_sub_type']
1319 if ($contact->contact_sub_type
) {
1320 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1322 array_unshift($contactTypes, $contact->contact_type
);
1324 return $contactTypes;
1327 throw new CRM_Core_Exception();
1332 * Combine all the importable fields from the lower levels object.
1334 * The ordering is important, since currently we do not have a weight
1335 * scheme. Adding weight is super important
1337 * @param int|string $contactType contact Type
1338 * @param bool $status
1339 * Status is used to manipulate first title.
1340 * @param bool $showAll
1341 * If true returns all fields (includes disabled fields).
1342 * @param bool $isProfile
1343 * If its profile mode.
1344 * @param bool $checkPermission
1345 * If false, do not include permissioning clause (for custom data).
1347 * @param bool $withMultiCustomFields
1350 * array of importable Fields
1352 public static function importableFields(
1353 $contactType = 'Individual',
1357 $checkPermission = TRUE,
1358 $withMultiCustomFields = FALSE
1360 if (empty($contactType)) {
1361 $contactType = 'All';
1364 $cacheKeyString = "importableFields $contactType";
1365 $cacheKeyString .= $status ?
'_1' : '_0';
1366 $cacheKeyString .= $showAll ?
'_1' : '_0';
1367 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1368 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1369 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1371 $fields = self
::$_importableFields[$cacheKeyString] ?? Civi
::cache('fields')->get($cacheKeyString);
1374 $fields = CRM_Contact_DAO_Contact
::import();
1376 // get the fields thar are meant for contact types
1377 if (in_array($contactType, [
1383 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1386 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1387 CRM_Core_DAO_Phone
::import(),
1388 CRM_Core_DAO_Email
::import(),
1389 CRM_Core_DAO_IM
::import(TRUE),
1390 CRM_Core_DAO_OpenID
::import()
1393 $locationFields = array_merge($locationFields,
1394 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1402 foreach ($locationFields as $key => $field) {
1403 $locationFields[$key]['hasLocationType'] = TRUE;
1406 $fields = array_merge($fields, $locationFields);
1408 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1409 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1412 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1413 $fields['url']['hasWebsiteType'] = TRUE;
1415 if ($contactType != 'All') {
1416 $fields = array_merge($fields,
1417 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1422 $withMultiCustomFields
1425 // Unset the fields which are not related to their contact type.
1426 foreach (CRM_Contact_DAO_Contact
::import() as $name => $value) {
1427 if (!empty($value['contactType']) && $value['contactType'] !== $contactType) {
1428 unset($fields[$name]);
1433 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1434 $fields = array_merge($fields,
1435 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1440 $withMultiCustomFields
1447 $fields = array_merge($fields, [
1449 'title' => ts('Group(s)'),
1453 'title' => ts('Tag(s)'),
1457 'title' => ts('Note'),
1460 'communication_style_id' => [
1461 'title' => ts('Communication Style'),
1462 'name' => 'communication_style_id',
1467 //Sorting fields in alphabetical order(CRM-1507)
1468 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1470 Civi
::cache('fields')->set($cacheKeyString, $fields);
1473 self
::$_importableFields[$cacheKeyString] = $fields;
1477 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1478 self
::$_importableFields[$cacheKeyString]
1482 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1483 self
::$_importableFields[$cacheKeyString]
1491 * Combine all the exportable fields from the lower levels object.
1493 * Currently we are using importable fields as exportable fields
1495 * @param int|string $contactType contact Type
1496 * @param bool $status
1497 * True while exporting primary contacts.
1498 * @param bool $export
1499 * True when used during export.
1500 * @param bool $search
1501 * True when used during search, might conflict with export param?.
1503 * @param bool $withMultiRecord
1504 * @param bool $checkPermissions
1507 * array of exportable Fields
1509 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1510 if (empty($contactType)) {
1511 $contactType = 'All';
1514 $cacheKeyString = "exportableFields $contactType";
1515 $cacheKeyString .= $export ?
'_1' : '_0';
1516 $cacheKeyString .= $status ?
'_1' : '_0';
1517 $cacheKeyString .= $search ?
'_1' : '_0';
1518 $cacheKeyString .= '_' . (bool) $checkPermissions;
1519 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1520 //calculates custom fields takes into account the logged in user & caches that for all users
1521 //as an interim fix we will cache the fields by contact
1522 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1524 if (!self
::$_exportableFields ||
empty(self
::$_exportableFields[$cacheKeyString])) {
1525 if (!self
::$_exportableFields) {
1526 self
::$_exportableFields = [];
1529 // check if we can retrieve from database cache
1530 $fields = Civi
::cache('fields')->get($cacheKeyString);
1533 $fields = CRM_Contact_DAO_Contact
::export();
1535 // The fields are meant for contact types.
1536 if (in_array($contactType, [
1542 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1544 // add current employer for individuals
1545 $fields = array_merge($fields, [
1546 'current_employer' =>
1548 'name' => 'organization_name',
1549 'title' => ts('Current Employer'),
1550 'type' => CRM_Utils_Type
::T_STRING
,
1554 // This probably would be added anyway by appendPseudoConstantsToFields.
1556 'location_type' => [
1557 'name' => 'location_type',
1558 'where' => 'civicrm_location_type.name',
1559 'title' => ts('Location Type'),
1560 'type' => CRM_Utils_Type
::T_STRING
,
1566 'name' => 'im_provider',
1567 'where' => 'civicrm_im.provider_id',
1568 'title' => ts('IM Provider'),
1569 'type' => CRM_Utils_Type
::T_STRING
,
1573 $phoneFields = CRM_Core_DAO_Phone
::export();
1574 // This adds phone_type to the exportable fields and make it available for export.
1575 // with testing the same can be done to the other entities.
1576 CRM_Core_DAO
::appendPseudoConstantsToFields($phoneFields);
1577 $locationFields = array_merge($locationType,
1578 CRM_Core_DAO_Address
::export(),
1580 CRM_Core_DAO_Email
::export(),
1582 CRM_Core_DAO_IM
::export(TRUE),
1583 CRM_Core_DAO_OpenID
::export()
1586 $locationFields = array_merge($locationFields,
1587 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1590 foreach ($locationFields as $key => $field) {
1591 $locationFields[$key]['hasLocationType'] = TRUE;
1594 $fields = array_merge($fields, $locationFields);
1597 $fields = array_merge($fields,
1598 CRM_Core_DAO_Worldregion
::export()
1601 $fields = array_merge($fields,
1602 CRM_Contact_DAO_Contact
::export()
1606 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1608 if ($contactType != 'All') {
1609 $fields = array_merge($fields,
1610 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1614 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1615 $fields = array_merge($fields,
1616 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1622 $fields = array_merge($fields, [
1624 'title' => ts('Group(s)'),
1628 'title' => ts('Tag(s)'),
1632 'title' => ts('Note(s)'),
1638 $fields = array_merge($fields, [
1640 'title' => ts('Group(s)'),
1644 'title' => ts('Tag(s)'),
1648 'title' => ts('Note(s)'),
1654 //Sorting fields in alphabetical order(CRM-1507)
1655 foreach ($fields as $k => $v) {
1656 $sortArray[$k] = $v['title'] ??
NULL;
1659 $fields = array_merge($sortArray, $fields);
1660 //unset the field which are not related to their contact type.
1661 if ($contactType != 'All') {
1667 'organization_name',
1668 'email_greeting_custom',
1669 'postal_greeting_custom',
1682 'organization_name',
1690 'email_greeting_custom',
1691 'postal_greeting_custom',
1707 'email_greeting_custom',
1708 'postal_greeting_custom',
1718 foreach ($commonValues[$contactType] as $value) {
1719 unset($fields[$value]);
1723 Civi
::cache('fields')->set($cacheKeyString, $fields);
1725 self
::$_exportableFields[$cacheKeyString] = $fields;
1729 $fields = self
::$_exportableFields[$cacheKeyString];
1732 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1733 self
::$_exportableFields[$cacheKeyString]
1741 * Get the all contact details (Hierarchical).
1743 * @param int $contactId
1745 * @param array $fields
1751 public static function getHierContactDetails($contactId, $fields) {
1752 $params = [['contact_id', '=', $contactId, 0, 0]];
1754 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1756 // We don't know the contents of return properties, but we need the lower
1757 // level ids of the contact so add a few fields.
1758 $returnProperties['first_name'] = 1;
1759 $returnProperties['organization_name'] = 1;
1760 $returnProperties['household_name'] = 1;
1761 $returnProperties['contact_type'] = 1;
1762 $returnProperties['contact_sub_type'] = 1;
1763 list($query) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties);
1768 * Given a set of flat profile style field names, create a hierarchy.
1770 * This is for the query to use, create the right sql.
1773 * @param int $contactId
1777 * A hierarchical property tree if appropriate
1779 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1780 $locationTypes = CRM_Core_BAO_Address
::buildOptions('location_type_id', 'validate');
1782 $returnProperties = [];
1784 $multipleFields = ['website' => 'url'];
1785 foreach ($fields as $name => $dontCare) {
1786 if (strpos($name, '-') !== FALSE) {
1787 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1789 if (!in_array($fieldName, $multipleFields)) {
1790 if ($id == 'Primary') {
1791 $locationTypeName = 1;
1794 $locationTypeName = $locationTypes[$id] ??
NULL;
1795 if (!$locationTypeName) {
1800 if (empty($returnProperties['location'])) {
1801 $returnProperties['location'] = [];
1803 if (empty($returnProperties['location'][$locationTypeName])) {
1804 $returnProperties['location'][$locationTypeName] = [];
1805 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1807 if (in_array($fieldName, [
1815 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1818 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1821 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1822 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1825 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1829 $returnProperties['website'][$id][$fieldName] = 1;
1833 $returnProperties[$name] = 1;
1837 return $returnProperties;
1841 * Return the primary location type of a contact.
1843 * $params int $contactId contact_id
1844 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1845 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1847 * @param int $contactId
1848 * @param bool $skipDefaultPriamry
1849 * @param null $block
1852 * $locationType location_type_id
1854 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1856 $entityBlock = ['contact_id' => $contactId];
1857 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1858 foreach ($blocks[$block] as $key => $value) {
1859 if (!empty($value['is_primary'])) {
1860 $locationType = $value['location_type_id'] ??
NULL;
1867 IF ( civicrm_email.location_type_id IS NULL,
1868 IF ( civicrm_address.location_type_id IS NULL,
1869 IF ( civicrm_phone.location_type_id IS NULL,
1870 IF ( civicrm_im.location_type_id IS NULL,
1871 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1872 ,civicrm_im.location_type_id)
1873 ,civicrm_phone.location_type_id)
1874 ,civicrm_address.location_type_id)
1875 ,civicrm_email.location_type_id) as locationType
1876 FROM civicrm_contact
1877 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1878 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1879 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1880 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1881 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1882 WHERE civicrm_contact.id = %1 ";
1884 $params = [1 => [$contactId, 'Integer']];
1886 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1888 $locationType = NULL;
1889 if ($dao->fetch()) {
1890 $locationType = $dao->locationType
;
1893 if (isset($locationType)) {
1894 return $locationType;
1896 elseif ($skipDefaultPriamry) {
1897 // if there is no primary contact location then return null
1901 // if there is no primart contact location, then return default
1902 // location type of the system
1903 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1904 return $defaultLocationType->id
;
1909 * Get the display name, primary email and location type of a contact.
1912 * Id of the contact.
1915 * Array of display_name, email if found, do_not_email or (null,null,null)
1917 public static function getContactDetails($id) {
1918 // check if the contact type
1919 $contactType = self
::getContactType($id);
1921 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1924 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1925 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1926 WHERE civicrm_contact.id = %1
1927 ORDER BY civicrm_email.is_primary DESC";
1928 $params = [1 => [$id, 'Integer']];
1929 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1931 if ($dao->fetch()) {
1932 if ($contactType == 'Individual') {
1933 if ($dao->first_name ||
$dao->last_name
) {
1934 $name = "{$dao->first_name} {$dao->last_name}";
1937 $name = $dao->display_name
;
1941 $name = $dao->display_name
;
1943 $email = $dao->email
;
1944 $doNotEmail = (bool) $dao->do_not_email
;
1945 $onHold = (bool) $dao->on_hold
;
1946 $isDeceased = (bool) $dao->is_deceased
;
1947 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1949 return [NULL, NULL, NULL, NULL, NULL];
1953 * Add/edit/register contacts through profile.
1955 * @param array $params
1956 * Array of profile fields to be edited/added.
1957 * @param array $fields
1958 * Array of fields from UFGroup.
1959 * @param int $contactID
1960 * Id of the contact to be edited/added.
1961 * @param int $addToGroupID
1962 * Specifies the default group to which contact is added.
1963 * @param int $ufGroupId
1964 * Uf group id (profile id).
1965 * @param string $ctype
1966 * @param bool $visibility
1967 * Basically lets us know where this request is coming from.
1968 * if via a profile from web, we restrict what groups are changed
1971 * contact id created/edited
1973 * @throws \CRM_Core_Exception
1974 * @throws \CiviCRM_API3_Exception
1975 * @throws \Civi\API\Exception\UnauthorizedException
1977 public static function createProfileContact(
1981 $addToGroupID = NULL,
1986 // add ufGroupID to params array ( CRM-2012 )
1988 $params['uf_group_id'] = $ufGroupId;
1990 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1992 // If a user has logged in, or accessed via a checksum
1993 // Then deliberately 'blanking' a value in the profile should remove it from their record
1994 $session = CRM_Core_Session
::singleton();
1995 $params['updateBlankLocInfo'] = TRUE;
1996 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1997 $params['updateBlankLocInfo'] = FALSE;
2002 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
2006 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
2009 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
2011 // manage is_opt_out
2012 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
2013 $wasOptOut = $contactDetails['is_opt_out'] ??
FALSE;
2014 $isOptOut = $params['is_opt_out'];
2015 $data['is_opt_out'] = $isOptOut;
2016 // on change, create new civicrm_subscription_history entry
2017 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2019 'contact_id' => $contactDetails['contact_id'],
2020 'status' => $isOptOut ?
'Removed' : 'Added',
2023 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2027 $contact = self
::create($data);
2029 // contact is null if the profile does not have any contact fields
2031 $contactID = $contact->id
;
2034 if (empty($contactID)) {
2035 throw new CRM_Core_Exception('Cannot proceed without a valid contact id');
2038 // Process group and tag
2039 if (isset($params['group'])) {
2041 // this for sure means we are coming in via profile since i added it to fix
2042 // removing contacts from user groups -- lobo
2046 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2049 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2050 // Convert comma separated form values from select2 v3
2051 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2052 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2055 //to add profile in default group
2056 if (is_array($addToGroupID)) {
2057 $contactIds = [$contactID];
2058 foreach ($addToGroupID as $groupId) {
2059 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2062 elseif ($addToGroupID) {
2063 $contactIds = [$contactID];
2064 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2068 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2071 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2077 * Format profile contact parameters.
2079 * @param array $params
2081 * @param int $contactID
2082 * @param int $ufGroupId
2083 * @param null $ctype
2084 * @param bool $skipCustom
2088 public static function formatProfileContactParams(
2097 $data = $contactDetails = [];
2099 // get the contact details (hier)
2101 $details = self
::getHierContactDetails($contactID, $fields);
2103 $contactDetails = $details[$contactID];
2104 $data['contact_type'] = $contactDetails['contact_type'] ??
NULL;
2105 $data['contact_sub_type'] = $contactDetails['contact_sub_type'] ??
NULL;
2108 //we should get contact type only if contact
2110 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2112 //special case to handle profile with only contact fields
2113 if ($data['contact_type'] == 'Contact') {
2114 $data['contact_type'] = 'Individual';
2116 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2117 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2121 $data['contact_type'] = $ctype;
2124 $data['contact_type'] = 'Individual';
2128 //fix contact sub type CRM-5125
2129 if (array_key_exists('contact_sub_type', $params) &&
2130 !empty($params['contact_sub_type'])
2132 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2134 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2135 !empty($params['contact_sub_type_hidden'])
2137 // if profile was used, and had any subtype, we obtain it from there
2138 //CRM-13596 - add to existing contact types, rather than overwriting
2139 if (empty($data['contact_sub_type'])) {
2140 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2141 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2144 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2145 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2146 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2147 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2148 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2153 if ($ctype == 'Organization') {
2154 $data['organization_name'] = $contactDetails['organization_name'] ??
NULL;
2156 elseif ($ctype == 'Household') {
2157 $data['household_name'] = $contactDetails['household_name'] ??
NULL;
2165 $data['contact_id'] = $contactID;
2166 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2169 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2170 $defaultLocationId = $defaultLocation->id
;
2173 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2175 $blocks = ['email', 'phone', 'im', 'openid'];
2177 $multiplFields = ['url'];
2178 // prevent overwritten of formatted array, reset all block from
2179 // params if it is not in valid format (since import pass valid format)
2180 foreach ($blocks as $blk) {
2181 if (array_key_exists($blk, $params) &&
2182 !is_array($params[$blk])
2184 unset($params[$blk]);
2188 $primaryPhoneLoc = NULL;
2189 $session = CRM_Core_Session
::singleton();
2190 foreach ($params as $key => $value) {
2191 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2193 if ($locTypeId == 'Primary') {
2195 if (in_array($fieldName, $blocks)) {
2196 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2199 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2201 $primaryLocationType = $locTypeId;
2204 $locTypeId = $defaultLocationId;
2208 if (is_numeric($locTypeId) &&
2209 !in_array($fieldName, $multiplFields) &&
2210 substr($fieldName, 0, 7) != 'custom_'
2212 $index = $locTypeId;
2214 if (is_numeric($typeId)) {
2215 $index .= '-' . $typeId;
2217 if (!in_array($index, $locationType)) {
2218 $locationType[$count] = $index;
2222 $loc = CRM_Utils_Array
::key($index, $locationType);
2224 $blockName = self
::getLocationEntityForKey($fieldName);
2226 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2228 //set is_billing true, for location type "Billing"
2229 if ($locTypeId == $billingLocationTypeId) {
2230 $data[$blockName][$loc]['is_billing'] = 1;
2234 //get the primary location type
2235 if ($locTypeId == $primaryLocationType) {
2236 $data[$blockName][$loc]['is_primary'] = 1;
2239 elseif ($locTypeId == $defaultLocationId) {
2240 $data[$blockName][$loc]['is_primary'] = 1;
2243 if (in_array($fieldName, ['phone'])) {
2245 $data['phone'][$loc]['phone_type_id'] = $typeId;
2248 $data['phone'][$loc]['phone_type_id'] = '';
2250 $data['phone'][$loc]['phone'] = $value;
2252 //special case to handle primary phone with different phone types
2253 // in this case we make first phone type as primary
2254 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2255 $primaryPhoneLoc = $loc;
2258 if ($loc != $primaryPhoneLoc) {
2259 unset($data['phone'][$loc]['is_primary']);
2262 elseif ($fieldName == 'email') {
2263 $data['email'][$loc]['email'] = $value;
2264 if (empty($contactID)) {
2265 $data['email'][$loc]['is_primary'] = 1;
2268 elseif ($fieldName == 'im') {
2269 if (isset($params[$key . '-provider_id'])) {
2270 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2272 if (strpos($key, '-provider_id') !== FALSE) {
2273 $data['im'][$loc]['provider_id'] = $params[$key];
2276 $data['im'][$loc]['name'] = $value;
2279 elseif ($fieldName == 'openid') {
2280 $data['openid'][$loc]['openid'] = $value;
2283 if ($fieldName === 'state_province') {
2285 if (is_numeric($value) && ((int ) $value) >= 1000) {
2286 $data['address'][$loc]['state_province_id'] = $value;
2288 elseif (empty($value)) {
2289 $data['address'][$loc]['state_province_id'] = '';
2292 $data['address'][$loc]['state_province'] = $value;
2295 elseif ($fieldName === 'country') {
2297 if (is_numeric($value) && ((int ) $value) >= 1000
2299 $data['address'][$loc]['country_id'] = $value;
2301 elseif (empty($value)) {
2302 $data['address'][$loc]['country_id'] = '';
2305 $data['address'][$loc]['country'] = $value;
2308 elseif ($fieldName === 'county') {
2309 $data['address'][$loc]['county_id'] = $value;
2311 elseif ($fieldName == 'address_name') {
2312 $data['address'][$loc]['name'] = $value;
2314 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2315 $data['address'][$loc][substr($fieldName, 8)] = $value;
2318 $data[$blockName][$loc][$fieldName] = $value;
2323 if (substr($key, 0, 4) === 'url-') {
2324 $websiteField = explode('-', $key);
2325 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2326 $data['website'][$websiteField[1]]['url'] = $value;
2328 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2329 //save email/postal greeting and addressee values if any, CRM-4575
2330 $data[$key . '_id'] = $value;
2332 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2333 // for autocomplete transfer hidden value instead of label
2334 if ($params[$key] && isset($params[$key . '_id'])) {
2335 $value = $params[$key . '_id'];
2338 // we need to append time with date
2339 if ($params[$key] && isset($params[$key . '_time'])) {
2340 $value .= ' ' . $params[$key . '_time'];
2343 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2344 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2345 ($value == '' ||
!isset($value))
2351 if (!empty($params['customRecordValues'])) {
2352 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2353 foreach ($params['customRecordValues'] as $recId => $customFields) {
2354 if (is_array($customFields) && !empty($customFields)) {
2355 foreach ($customFields as $customFieldName) {
2356 if ($customFieldName == $key) {
2366 //CRM-13596 - check for contact_sub_type_hidden first
2367 if (array_key_exists('contact_sub_type_hidden', $params)) {
2368 $type = $params['contact_sub_type_hidden'];
2371 $type = $data['contact_type'];
2372 if (!empty($data['contact_sub_type'])) {
2373 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2377 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2387 elseif ($key === 'edit') {
2391 if ($key === 'location') {
2392 foreach ($value as $locationTypeId => $field) {
2393 foreach ($field as $block => $val) {
2394 if ($block === 'address' && array_key_exists('address_name', $val)) {
2395 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2400 if ($key === 'phone' && isset($params['phone_ext'])) {
2401 $data[$key] = $value;
2402 foreach ($value as $cnt => $phoneBlock) {
2403 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2404 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2408 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2409 && ($value == '' ||
!isset($value)) &&
2410 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2411 ($key === 'current_employer' && empty($params['current_employer']))) {
2412 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2413 // to avoid update with empty values
2417 $data[$key] = $value;
2423 if (!isset($data['contact_type'])) {
2424 $data['contact_type'] = 'Individual';
2427 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2428 $privacy = CRM_Core_SelectValues
::privacy();
2429 foreach ($privacy as $key => $value) {
2430 if (array_key_exists($key, $fields)) {
2431 // do not reset values for existing contacts, if fields are added to a profile
2432 if (array_key_exists($key, $params)) {
2433 $data[$key] = $params[$key];
2434 if (empty($params[$key])) {
2438 elseif (!$contactID) {
2444 return [$data, $contactDetails];
2448 * Find the get contact details.
2450 * This function does not respect ACLs for now, which might need to be rectified at some
2451 * stage based on how its used.
2453 * @param string $mail
2454 * Primary email address of the contact.
2455 * @param string $ctype
2458 * @return object|null
2459 * $dao contact details
2461 public static function matchContactOnEmail($mail, $ctype = NULL) {
2462 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2463 $mail = $strtolower(trim($mail));
2465 SELECT civicrm_contact.id as contact_id,
2466 civicrm_contact.hash as hash,
2467 civicrm_contact.contact_type as contact_type,
2468 civicrm_contact.contact_sub_type as contact_sub_type
2469 FROM civicrm_contact
2470 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2472 if (Civi
::settings()->get('uniq_email_per_site')) {
2473 // try to find a match within a site (multisite).
2474 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2475 if (!empty($groups)) {
2477 INNER JOIN civicrm_group_contact gc ON
2478 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2483 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2484 $p = [1 => [$mail, 'String']];
2487 $query .= " AND civicrm_contact.contact_type = %3";
2488 $p[3] = [$ctype, 'String'];
2491 $query .= " ORDER BY civicrm_email.is_primary DESC";
2493 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2495 if ($dao->fetch()) {
2502 * Find the contact details associated with an OpenID.
2504 * @param string $openId
2505 * OpenId of the contact.
2506 * @param string $ctype
2509 * @return object|null
2510 * $dao contact details
2512 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2513 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2514 $openId = $strtolower(trim($openId));
2516 SELECT civicrm_contact.id as contact_id,
2517 civicrm_contact.hash as hash,
2518 civicrm_contact.contact_type as contact_type,
2519 civicrm_contact.contact_sub_type as contact_sub_type
2520 FROM civicrm_contact
2521 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2522 WHERE civicrm_openid.openid = %1";
2523 $p = [1 => [$openId, 'String']];
2526 $query .= " AND civicrm_contact.contact_type = %3";
2527 $p[3] = [$ctype, 'String'];
2530 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2532 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2534 if ($dao->fetch()) {
2541 * Get primary email of the contact.
2543 * @param int $contactID
2545 * @param bool $polite
2546 * Whether to only pull an email if it's okay to send to it--that is, if it
2547 * is not on_hold and the contact is not do_not_email.
2550 * Email address if present else null
2552 public static function getPrimaryEmail($contactID, $polite = FALSE) {
2553 // fetch the primary email
2555 SELECT civicrm_email.email as email
2556 FROM civicrm_contact
2557 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2558 WHERE civicrm_email.is_primary = 1
2559 AND civicrm_contact.id = %1";
2562 AND civicrm_contact.do_not_email = 0
2563 AND civicrm_email.on_hold = 0';
2565 $p = [1 => [$contactID, 'Integer']];
2566 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2569 if ($dao->fetch()) {
2570 $email = $dao->email
;
2576 * Fetch the object and store the values in the values array.
2578 * @param array $params
2579 * Input parameters to find object.
2580 * @param array $values
2581 * Output values of the object.
2583 * @return CRM_Contact_BAO_Contact|null
2584 * The found object or null
2586 public static function getValues(&$params, &$values) {
2587 $contact = new CRM_Contact_BAO_Contact();
2589 $contact->copyValues($params);
2591 if ($contact->find(TRUE)) {
2593 CRM_Core_DAO
::storeValues($contact, $values);
2596 foreach (self
::$_commPrefs as $name) {
2597 if (isset($contact->$name)) {
2598 $privacy[$name] = $contact->$name;
2602 if (!empty($privacy)) {
2603 $values['privacy'] = $privacy;
2606 // communication Prefferance
2607 $preffComm = $comm = [];
2608 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2609 $contact->preferred_communication_method
2611 foreach ($comm as $value) {
2612 $preffComm[$value] = 1;
2614 $temp = ['preferred_communication_method' => $contact->preferred_communication_method
];
2617 'preferred_communication_method' => [
2618 'newName' => 'preferred_communication_method_display',
2619 'groupName' => 'preferred_communication_method',
2623 // @todo This can be figured out from metadata & we can avoid the uncached query.
2624 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2626 $values['preferred_communication_method'] = $preffComm;
2627 $values['preferred_communication_method_display'] = $temp['preferred_communication_method_display'] ??
NULL;
2629 if ($contact->preferred_mail_format
) {
2630 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2631 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2634 // get preferred languages
2635 if (!empty($contact->preferred_language
)) {
2636 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2639 // Calculating Year difference
2640 if ($contact->birth_date
) {
2641 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2642 if ($birthDate < date('Ymd')) {
2643 $age = CRM_Utils_Date
::calculateAge($birthDate);
2644 $values['age']['y'] = $age['years'] ??
NULL;
2645 $values['age']['m'] = $age['months'] ??
NULL;
2649 $contact->contact_id
= $contact->id
;
2657 * Given the component name and returns the count of participation of contact.
2659 * @param string $component
2660 * Input component name.
2661 * @param int $contactId
2663 * @param string $tableName
2664 * Optional tableName if component is custom group.
2667 * total number in database
2669 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2671 switch ($component) {
2673 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2676 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2677 CRM_Contact_BAO_Relationship
::CURRENT
,
2686 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2689 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2692 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2695 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2697 case 'contribution':
2698 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2701 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2704 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2707 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2710 return CRM_Case_BAO_Case
::caseCount($contactId);
2713 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2717 'contact_id' => $contactId,
2720 'context' => 'activity',
2722 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2725 $params = ['contact_id' => $contactId];
2726 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2729 $custom = explode('_', $component);
2730 if ($custom['0'] = 'custom') {
2732 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2734 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2735 return CRM_Core_DAO
::singleValueQuery($queryString);
2741 * Update contact greetings if an update has resulted in a custom field change.
2743 * @param array $updatedFields
2744 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2745 * @param array $contactParams
2746 * Parameters known about the contact. At minimum array('contact_id' => x).
2747 * Fields in this array will take precedence over DB fields (so far only
2748 * in the case of greeting id fields).
2750 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2751 $contactID = $contactParams['contact_id'];
2752 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2753 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2754 if (!empty($tokens['all']['contact'])) {
2755 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2756 if (!empty($affectedTokens)) {
2757 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2758 $contact = new CRM_Contact_BAO_Contact();
2759 $contact->id
= $contactID;
2760 CRM_Contact_BAO_Contact
::processGreetings($contact);
2766 * Process greetings and cache.
2768 * @param object $contact
2769 * Contact object after save.
2771 public static function processGreetings(&$contact) {
2773 //@todo this function does a lot of unnecessary loading.
2774 // ensureGreetingParamsAreSet now makes sure that the contact is
2775 // loaded and using updateGreetingsOnTokenFieldChange
2776 // allows us the possibility of only doing an update if required.
2778 // The contact object has not always required the
2779 // fields that are required to calculate greetings
2780 // so we need to retrieve it again.
2781 if ($contact->_query
!== FALSE) {
2782 $contact->find(TRUE);
2785 // store object values to an array
2786 $contactDetails = [];
2787 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2788 $contactDetails = [[$contact->id
=> $contactDetails]];
2790 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2791 $updateQueryString = [];
2793 //cache email and postal greeting to greeting display
2794 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2795 $emailGreetingString = $contact->email_greeting_custom
;
2797 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2798 // the filter value for Individual contact type is set to 1
2800 'contact_type' => $contact->contact_type
,
2801 'greeting_type' => 'email_greeting',
2804 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2805 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2806 $updateQueryString[] = " email_greeting_custom = NULL ";
2809 if ($contact->email_greeting_custom
) {
2810 $updateQueryString[] = " email_greeting_display = NULL ";
2814 if ($emailGreetingString) {
2815 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2818 'CRM_Contact_BAO_Contact'
2820 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2821 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2825 if ($contact->postal_greeting_custom
!== 'null' && $contact->postal_greeting_custom
) {
2826 $postalGreetingString = $contact->postal_greeting_custom
;
2828 elseif ($contact->postal_greeting_id
!== 'null' && $contact->postal_greeting_id
) {
2830 'contact_type' => $contact->contact_type
,
2831 'greeting_type' => 'postal_greeting',
2833 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2834 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2835 $updateQueryString[] = " postal_greeting_custom = NULL ";
2838 if ($contact->postal_greeting_custom
) {
2839 $updateQueryString[] = " postal_greeting_display = NULL ";
2843 if ($postalGreetingString) {
2844 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2847 'CRM_Contact_BAO_Contact'
2849 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2850 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2854 if ($contact->addressee_custom
!== 'null' && $contact->addressee_custom
) {
2855 $addresseeString = $contact->addressee_custom
;
2857 elseif ($contact->addressee_id
!== 'null' && $contact->addressee_id
) {
2859 'contact_type' => $contact->contact_type
,
2860 'greeting_type' => 'addressee',
2863 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2864 $addresseeString = $addressee[$contact->addressee_id
];
2865 $updateQueryString[] = " addressee_custom = NULL ";
2868 if ($contact->addressee_custom
) {
2869 $updateQueryString[] = " addressee_display = NULL ";
2873 if ($addresseeString) {
2874 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2877 'CRM_Contact_BAO_Contact'
2879 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2880 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2883 if (!empty($updateQueryString)) {
2884 $updateQueryString = implode(',', $updateQueryString);
2885 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2886 CRM_Core_DAO
::executeQuery($queryString);
2891 * Retrieve loc block ids w/ given condition.
2893 * @param int $contactId
2895 * @param array $criteria
2896 * Key => value pair which should be.
2897 * fulfill by return record ids.
2898 * @param string $condOperator
2899 * Operator use for grouping multiple conditions.
2902 * loc block ids which fulfill condition.
2904 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2907 return $locBlockIds;
2910 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2911 $name = strtolower($block);
2912 $className = "CRM_Core_DAO_$block";
2913 $blockDAO = new $className();
2915 // build the condition.
2916 if (is_array($criteria)) {
2917 $fields = $blockDAO->fields();
2919 foreach ($criteria as $field => $value) {
2920 if (array_key_exists($field, $fields)) {
2921 $cond = "( $field = $value )";
2922 // value might be zero or null.
2923 if (!$value ||
strtolower($value) === 'null') {
2924 $cond = "( $field = 0 OR $field IS NULL )";
2926 $conditions[] = $cond;
2929 if (!empty($conditions)) {
2930 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2934 $blockDAO->contact_id
= $contactId;
2936 while ($blockDAO->fetch()) {
2937 $locBlockIds[$name][] = $blockDAO->id
;
2941 return $locBlockIds;
2945 * Build context menu items.
2947 * @param int $contactId
2950 * Array of context menu for logged in user.
2952 public static function contextMenu($contactId = NULL) {
2955 'title' => ts('View Contact'),
2957 'ref' => 'view-contact',
2958 'class' => 'no-popup',
2960 'permissions' => ['view all contacts'],
2963 'title' => ts('Edit Contact'),
2965 'ref' => 'edit-contact',
2966 'class' => 'no-popup',
2968 'permissions' => ['edit all contacts'],
2971 'title' => ts('Delete Contact'),
2973 'ref' => 'delete-contact',
2975 'permissions' => ['access deleted contacts', 'delete contacts'],
2978 'title' => ts('Add Contribution'),
2980 'ref' => 'new-contribution',
2981 'key' => 'contribution',
2982 'tab' => 'contribute',
2983 'component' => 'CiviContribute',
2984 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2985 'reset=1&action=add&context=contribution'
2988 'access CiviContribute',
2989 'edit contributions',
2993 'title' => ts('Register for Event'),
2995 'ref' => 'new-participant',
2996 'key' => 'participant',
2997 'tab' => 'participant',
2998 'component' => 'CiviEvent',
2999 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3002 'edit event participants',
3006 'title' => ts('Record Activity'),
3008 'ref' => 'new-activity',
3009 'key' => 'activity',
3010 'permissions' => ['edit all contacts'],
3013 'title' => ts('Add Pledge'),
3015 'ref' => 'new-pledge',
3018 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3019 'reset=1&action=add&context=pledge'
3021 'component' => 'CiviPledge',
3023 'access CiviPledge',
3028 'title' => ts('Add Membership'),
3030 'ref' => 'new-membership',
3031 'key' => 'membership',
3033 'component' => 'CiviMember',
3034 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3035 'reset=1&action=add&context=membership'
3038 'access CiviMember',
3043 'title' => ts('Add Case'),
3045 'ref' => 'new-case',
3048 'component' => 'CiviCase',
3049 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3050 'permissions' => ['add cases'],
3053 'title' => ts('Add Grant'),
3055 'ref' => 'new-grant',
3058 'component' => 'CiviGrant',
3059 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3060 'reset=1&action=add&context=grant'
3062 'permissions' => ['edit grants'],
3065 'title' => ts('Add Relationship'),
3067 'ref' => 'new-relationship',
3070 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3071 'reset=1&action=add'
3073 'permissions' => ['edit all contacts'],
3076 'title' => ts('Add Note'),
3078 'ref' => 'new-note',
3081 'class' => 'medium-popup',
3082 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3083 'reset=1&action=add'
3085 'permissions' => ['edit all contacts'],
3088 'title' => ts('Send an Email'),
3090 'ref' => 'new-email',
3092 'permissions' => ['view all contacts'],
3095 'title' => ts('Add to Group'),
3097 'ref' => 'group-add-contact',
3100 'permissions' => ['edit groups'],
3103 'title' => ts('Tag Contact'),
3105 'ref' => 'tag-contact',
3108 'permissions' => ['edit all contacts'],
3112 $menu['otherActions'] = [
3114 'title' => ts('Print Summary'),
3115 'description' => ts('Printer-friendly view of this page.'),
3117 'ref' => 'crm-contact-print',
3120 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3124 'icon' => 'crm-i fa-print',
3127 'title' => ts('vCard'),
3128 'description' => ts('vCard record for this contact.'),
3130 'ref' => 'crm-contact-vcard',
3133 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3137 'icon' => 'crm-i fa-list-alt',
3141 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3142 $menu['otherActions']['dashboard'] = [
3143 'title' => ts('Contact Dashboard'),
3144 'description' => ts('Contact Dashboard'),
3146 'ref' => 'crm-contact-dashboard',
3147 'key' => 'dashboard',
3148 'tab' => 'dashboard',
3149 'class' => 'dashboard',
3150 // NOTE: As an alternative you can also build url on CMS specific way
3151 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3152 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3153 'icon' => 'crm-i fa-tachometer',
3157 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3159 $menu['otherActions']['user-record'] = [
3160 'title' => ts('User Record'),
3161 'description' => ts('User Record'),
3163 'ref' => 'crm-contact-user-record',
3164 'key' => 'user-record',
3165 'tab' => 'user-record',
3166 'class' => 'user-record',
3167 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3168 'icon' => 'crm-i fa-user',
3171 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3172 $menu['otherActions']['user-add'] = [
3173 'title' => ts('Create User Record'),
3174 'description' => ts('Create User Record'),
3176 'ref' => 'crm-contact-user-add',
3177 'key' => 'user-add',
3178 'tab' => 'user-add',
3179 'class' => 'user-add',
3180 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3181 'icon' => 'crm-i fa-user-plus',
3185 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3186 //1. check for component is active.
3187 //2. check for user permissions.
3188 //3. check for acls.
3189 //3. edit and view contact are directly accessible to user.
3191 $aclPermissionedTasks = [
3196 'group-add-contact',
3200 $corePermission = CRM_Core_Permission
::getPermission();
3203 foreach ($menu as $key => $values) {
3204 if ($key !== 'otherActions') {
3206 // user does not have necessary permissions.
3207 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3210 // build directly accessible action menu.
3211 if (in_array($values['ref'], [
3215 $contextMenu['primaryActions'][$key] = [
3216 'title' => $values['title'],
3217 'ref' => $values['ref'],
3218 'class' => $values['class'] ??
NULL,
3219 'key' => $values['key'],
3224 // finally get menu item for -more- action widget.
3225 $contextMenu['moreActions'][$values['weight']] = [
3226 'title' => $values['title'],
3227 'ref' => $values['ref'],
3228 'href' => $values['href'] ??
NULL,
3229 'tab' => $values['tab'] ??
NULL,
3230 'class' => $values['class'] ??
NULL,
3231 'key' => $values['key'],
3235 foreach ($values as $value) {
3236 // user does not have necessary permissions.
3237 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3241 // finally get menu item for -more- action widget.
3242 $contextMenu['otherActions'][$value['weight']] = [
3243 'title' => $value['title'],
3244 'ref' => $value['ref'],
3245 'href' => $value['href'] ??
NULL,
3246 'tab' => $value['tab'] ??
NULL,
3247 'class' => $value['class'] ??
NULL,
3248 'icon' => $value['icon'] ??
NULL,
3249 'key' => $value['key'],
3255 ksort($contextMenu['moreActions']);
3256 ksort($contextMenu['otherActions']);
3258 return $contextMenu;
3262 * Check if user has permissions to access items in action menu.
3264 * @param array $aclPermissionedTasks
3265 * Array containing ACL related tasks.
3266 * @param string $corePermission
3267 * The permission of the user (edit or view or null).
3268 * @param array $menuOptions
3269 * Array containing params of the menu (title, href, etc).
3272 * TRUE if user has all permissions, FALSE if otherwise.
3274 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3275 $componentName = $menuOptions['component'] ??
NULL;
3277 // if component action - make sure component is enable.
3278 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3282 // make sure user has all required permissions.
3283 $hasAllPermissions = FALSE;
3285 $permissions = $menuOptions['permissions'] ??
NULL;
3286 if (!is_array($permissions) ||
empty($permissions)) {
3287 $hasAllPermissions = TRUE;
3290 // iterate for required permissions in given permissions array.
3291 if (!$hasAllPermissions) {
3292 $hasPermissions = 0;
3293 foreach ($permissions as $permission) {
3294 if (CRM_Core_Permission
::check($permission)) {
3299 if (count($permissions) == $hasPermissions) {
3300 $hasAllPermissions = TRUE;
3303 // if still user does not have required permissions, check acl.
3304 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3305 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3306 $corePermission == CRM_Core_Permission
::EDIT
3308 $hasAllPermissions = TRUE;
3310 elseif (in_array($menuOptions['ref'], [
3313 // grant permissions for these tasks.
3314 $hasAllPermissions = TRUE;
3319 return $hasAllPermissions;
3323 * Retrieve display name of contact that address is shared.
3325 * This is based on $masterAddressId or $contactId .
3327 * @param int $masterAddressId
3329 * @param int $contactId
3330 * Contact id. (deprecated - do not use)
3332 * @return string|null
3333 * the found display name or null.
3335 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3336 $masterDisplayName = NULL;
3337 if (!$masterAddressId) {
3338 return $masterDisplayName;
3342 SELECT display_name from civicrm_contact
3343 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3344 WHERE civicrm_address.id = " . $masterAddressId;
3346 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3347 return $masterDisplayName;
3351 * Get the creation/modification times for a contact.
3353 * @param int $contactId
3356 * Dates - ('created_date' => $, 'modified_date' => $)
3358 public static function getTimestamps($contactId) {
3359 $timestamps = CRM_Core_DAO
::executeQuery(
3360 'SELECT created_date, modified_date
3361 FROM civicrm_contact
3364 1 => [$contactId, 'Integer'],
3367 if ($timestamps->fetch()) {
3369 'created_date' => $timestamps->created_date
,
3370 'modified_date' => $timestamps->modified_date
,
3379 * Get a list of triggers for the contact table.
3382 * @param null $tableName
3384 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3386 * @see hook_civicrm_triggerInfo
3387 * @see CRM_Core_DAO::triggerRebuild
3389 public static function triggerInfo(&$info, $tableName = NULL) {
3391 // Modifications to these records should update the contact timestamps.
3392 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3394 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3395 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3396 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3397 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3398 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3400 ->alterTriggerInfo($info, $tableName);
3402 // Update phone table to populate phone_numeric field
3403 if (!$tableName ||
$tableName == 'civicrm_phone') {
3404 // Define stored sql function needed for phones
3405 $sqlTriggers = Civi
::service('sql_triggers');
3406 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3407 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3409 'table' => ['civicrm_phone'],
3411 'event' => ['INSERT', 'UPDATE'],
3412 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3418 * Check if contact is being used in civicrm_domain based on $contactId.
3420 * @param int $contactId
3424 * true if present else false.
3426 public static function checkDomainContact($contactId) {
3430 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3441 * Get options for a given contact field.
3443 * @param string $fieldName
3444 * @param string $context
3445 * @param array $props
3446 * whatever is known about this dao object.
3448 * @return array|bool
3449 * @see CRM_Core_DAO::buildOptions
3451 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3452 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3454 * @see CRM_Core_DAO::buildOptionsContext
3456 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3458 // Special logic for fields whose options depend on context or properties
3459 switch ($fieldName) {
3460 case 'contact_sub_type':
3461 if (!empty($props['contact_type'])) {
3462 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3466 case 'contact_type':
3467 if ($context == 'search') {
3468 // CRM-15495 - EntityRef filters and basic search forms expect this format
3469 // FIXME: Search builder does not
3470 return CRM_Contact_BAO_ContactType
::getSelectElements();
3474 // The contact api supports some related entities so we'll honor that by fetching their options
3477 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3481 $props['entity_table'] = 'civicrm_contact';
3482 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3484 case 'state_province_id':
3485 case 'state_province':
3486 case 'state_province_name':
3491 case 'worldregion_id':
3492 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3495 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3499 * Delete a contact-related object that has an 'is_primary' field.
3501 * Ensures that is_primary gets assigned to another object if available
3502 * Also calls pre/post hooks
3504 * @param string $type
3509 public static function deleteObjectWithPrimary($type, $id) {
3510 if (!$id ||
!is_numeric($id)) {
3513 $daoName = "CRM_Core_DAO_$type";
3514 $obj = new $daoName();
3518 if ($obj->fetch()) {
3519 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3520 $contactId = $obj->contact_id
;
3526 // is_primary is only relavent if this field belongs to a contact
3528 $dao = new $daoName();
3529 $dao->contact_id
= $contactId;
3530 $dao->is_primary
= 1;
3531 // Pick another record to be primary (if one isn't already)
3532 if (!$dao->find(TRUE)) {
3533 $dao->is_primary
= 0;
3535 if ($dao->fetch()) {
3536 $dao->is_primary
= 1;
3538 if ($type === 'Email') {
3539 CRM_Core_BAO_UFMatch
::updateUFName($dao->contact_id
);
3544 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3551 public function addSelectWhereClause() {
3552 // We always return an array with these keys, even if they are empty,
3553 // because this tells the query builder that we have considered these fields for acls
3555 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3556 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
[] : ['!= 1'],
3558 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3563 * Get any existing duplicate contacts based on the input parameters.
3565 * @param array $input
3566 * Input parameters to be matched.
3567 * @param string $contactType
3568 * @param string $rule
3571 * @param $excludedContactIDs
3572 * An array of ids not to be included in the results.
3573 * @param bool $checkPermissions
3574 * @param int $ruleGroupID
3575 * ID of the rule group to be used if an override is desirable.
3576 * @param array $contextParams
3577 * The context if relevant, eg. ['event_id' => X]
3581 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3582 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3583 $dedupeParams['check_permission'] = $checkPermissions;
3584 $dedupeParams['contact_type'] = $contactType;
3585 $dedupeParams['rule'] = $rule;
3586 $dedupeParams['rule_group_id'] = $ruleGroupID;
3587 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3588 $dedupeResults['ids'] = [];
3589 $dedupeResults['handled'] = FALSE;
3590 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3591 if (!$dedupeResults['handled']) {
3592 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3594 return $dedupeResults['ids'];
3598 * Get the first duplicate contacts based on the input parameters.
3600 * @param array $input
3601 * Input parameters to be matched.
3602 * @param string $contactType
3603 * @param string $rule
3606 * @param $excludedContactIDs
3607 * An array of ids not to be included in the results.
3608 * @param bool $checkPermissions
3609 * @param int $ruleGroupID
3610 * ID of the rule group to be used if an override is desirable.
3611 * @param array $contextParams
3612 * The context if relevant, eg. ['event_id' => X]
3616 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3617 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3625 * Check if a field is associated with an entity that has a location type.
3627 * (ie. is an address, phone, email etc field).
3629 * @param string $fieldTitle
3630 * Title of the field (not the name - create a new function for that if required).
3634 public static function isFieldHasLocationType($fieldTitle) {
3635 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3636 if ($field['title'] === $fieldTitle) {
3637 return $field['hasLocationType'] ??
NULL;
3644 * @param array $appendProfiles
3645 * Name of profile(s) to append to each link.
3649 public static function getEntityRefCreateLinks($appendProfiles = []) {
3650 // You'd think that "create contacts" would be the permission to check,
3651 // But new contact popups are profile forms and those use their own permissions.
3652 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3656 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3657 $profiles[] = 'new_' . strtolower($contactType);
3659 $retrieved = civicrm_api3('uf_group', 'get', [
3660 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3663 $links = $append = [];
3664 if (!empty($retrieved['values'])) {
3666 'individual' => 'fa-user',
3667 'organization' => 'fa-building',
3668 'household' => 'fa-home',
3670 foreach ($retrieved['values'] as $id => $profile) {
3671 if (in_array($profile['name'], $profiles)) {
3673 'label' => $profile['title'],
3674 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3675 NULL, NULL, FALSE, FALSE, TRUE),
3676 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3677 'icon' => $icons[str_replace('new_', '', $profile['name'])] ??
NULL,
3684 foreach ($append as $id) {
3685 foreach ($links as &$link) {
3686 $link['url'] .= ",$id";
3696 public static function getEntityRefFilters() {
3698 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3699 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3700 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3701 ['key' => 'city', 'value' => ts('City'), 'type' => 'text', 'entity' => 'Address'],
3702 ['key' => 'postal_code', 'value' => ts('Postal Code'), 'type' => 'text', 'entity' => 'Address'],
3703 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3704 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3705 ['key' => 'first_name', 'value' => ts('First Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3706 ['key' => 'last_name', 'value' => ts('Last Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3707 ['key' => 'nick_name', 'value' => ts('Nick Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3708 ['key' => 'organization_name', 'value' => ts('Employer name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3709 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3710 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3711 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3712 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3713 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],