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 * Check if a contact has a name.
436 * - Individuals need a first_name or last_name
437 * - Organizations need organization_name
438 * - Households need household_name
440 * @param array $contact
443 public static function hasName(array $contact): bool {
445 'Individual' => ['first_name', 'last_name'],
446 'Organization' => ['organization_name'],
447 'Household' => ['household_name'],
449 // Casting to int filters out the string 'null'
450 $cid = (int) ($contact['id'] ??
NULL);
451 $contactType = $contact['contact_type'] ??
NULL;
452 if (!$contactType && $cid) {
453 $contactType = CRM_Core_DAO
::getFieldValue(__CLASS__
, $cid, 'contact_type');
455 if (!$contactType ||
!isset($nameFields[$contactType])) {
456 throw new CRM_Core_Exception('No contact_type given to ' . __CLASS__
. '::' . __FUNCTION__
);
458 foreach ($nameFields[$contactType] as $field) {
459 if (isset($contact[$field]) && is_string($contact[$field]) && $contact[$field] !== '') {
463 // For existing contacts, look up name from database
465 foreach ($nameFields[$contactType] as $field) {
466 $value = $contact[$field] ?? CRM_Core_DAO
::getFieldValue(__CLASS__
, $cid, $field);
467 if (isset($value) && $value !== '') {
476 * Format the output of the create contact function
478 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
480 public static function unsetProtectedFields(&$contacts) {
481 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
482 $currentUser = CRM_Core_Session
::getLoggedInContactID();
483 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
484 foreach ($contacts as &$contact) {
485 $cid = is_object($contact) ?
$contact->id
: $contact['id'] ??
NULL;
486 if (!($editOwn && $cid == $currentUser)) {
487 if (is_object($contact)) {
488 unset($contact->api_key
);
491 unset($contact['api_key']);
499 * Ensure greeting parameters are set.
501 * By always populating greetings here we can be sure they are set if required & avoid a call later.
502 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
504 * @param array $params
506 * @throws \CiviCRM_API3_Exception
508 public static function ensureGreetingParamsAreSet(&$params) {
509 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
510 $missingGreetingParams = [];
512 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
513 if (empty($params[$greetingParam])) {
514 $missingGreetingParams[$greetingIndex] = $greetingParam;
518 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
519 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
520 'id' => $params['contact_id'],
521 'return' => array_keys($missingGreetingParams),
524 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
525 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
526 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
529 // Filter out other fields.
530 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
531 $params = array_merge($params, $savedGreetings);
534 foreach ($missingGreetingParams as $greetingName => $greeting) {
535 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
539 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
540 if ($params[$greetingParam] === 'null') {
541 // If we are setting it to null then null out the display field.
542 $params[$greetingIndex . '_display'] = 'null';
548 * Get the display name and image of a contact.
553 * @param bool $includeTypeInReturnParameters
554 * Should type be part of the returned array?
557 * the displayName and contactImage for this contact
559 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
560 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
562 SELECT civicrm_contact.*,
563 civicrm_email.email as email
565 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
566 AND civicrm_email.is_primary = 1
567 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
568 $dao = new CRM_Core_DAO();
571 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
572 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
574 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
575 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
578 // use email if display_name is empty
579 if (empty($dao->display_name
)) {
580 $displayName = $dao->email
;
583 $displayName = $dao->display_name
;
586 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
588 return $includeTypeInReturnParameters ?
[
592 $dao->contact_sub_type
,
594 ] : [$displayName, $image, $imageUrl];
600 * Add billing fields to the params if appropriate.
602 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
603 * don't then we should set the name fields to the billing fields AND add the preserveDBName
604 * parameter (which will tell the BAO only to set those fields if none already exist.
606 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
607 * matching is best done by hipsters.
609 * @param array $params
611 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
613 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
614 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
615 foreach ($nameFields as $field) {
616 if (!empty($params[$field])) {
620 // There are only 3 - we can iterate through them twice :-)
621 foreach ($nameFields as $field) {
622 if (!empty($params['billing_' . $field])) {
623 $params[$field] = $params['billing_' . $field];
625 $params['preserveDBName'] = TRUE;
631 * Resolve a state province string (UT or Utah) to an ID.
633 * If country has been passed in we should select a state belonging to that country.
635 * Alternatively we should choose from enabled countries, prioritising the default country.
637 * @param array $values
638 * @param int|null $countryID
642 * @throws \CRM_Core_Exception
644 protected static function resolveStateProvinceID($values, $countryID) {
647 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
648 if (CRM_Utils_Array
::lookupValue($values,
653 return $values['state_province_id'];
655 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
656 if (CRM_Utils_Array
::lookupValue($values,
661 return $values['state_province_id'];
666 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
667 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
668 // prefer matching country..
669 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, ['country_id' => Civi
::settings()->get('defaultContactCountry')]);
670 if (CRM_Utils_Array
::lookupValue($values,
675 return $values['state_province_id'];
678 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
679 if (CRM_Utils_Array
::lookupValue($values,
684 return $values['state_province_id'];
687 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
688 if (CRM_Utils_Array
::lookupValue($values,
693 return $values['state_province_id'];
695 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
696 if (CRM_Utils_Array
::lookupValue($values,
701 return $values['state_province_id'];
709 * Get the relevant location entity for the array key.
711 * Based on the field name we determine which location entity
712 * we are dealing with. Apart from a few specific ones they
713 * are mostly 'address' (the default).
715 * @param string $fieldName
719 protected static function getLocationEntityForKey($fieldName) {
720 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
723 if ($fieldName === 'phone_ext') {
730 * Soft delete a contact.
732 * Call this via the api, not directly.
734 * @param \CRM_Contact_BAO_Contact $contact
737 * @throws \CRM_Core_Exception
739 protected static function contactTrash($contact): bool {
741 'id' => $contact->id
,
744 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
746 $params = [1 => [$contact->id
, 'Integer']];
747 $query = 'DELETE FROM civicrm_uf_match WHERE contact_id = %1';
748 CRM_Core_DAO
::executeQuery($query, $params);
750 $contact->copyValues($updateParams);
752 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
754 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
760 * Get the values for pseudoconstants for name->value and reverse.
762 * @param array $defaults
763 * (reference) the default values, some of which need to be resolved.
764 * @param bool $reverse
765 * Always true as this function is only called from one place..
769 * This is called specifically from the contact import parser & should be moved there
770 * as it is not truly a generic function.
773 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
774 // Hack for birth_date.
775 if (!empty($defaults['birth_date'])) {
776 if (is_array($defaults['birth_date'])) {
777 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
781 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
782 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
783 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
784 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
786 //lookup value of email/postal greeting, addressee, CRM-4575
787 foreach (self
::$_greetingTypes as $greeting) {
789 'contact_type' => $defaults['contact_type'] ??
NULL,
790 'greeting_type' => $greeting,
792 CRM_Utils_Array
::lookupValue($defaults, $greeting,
793 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
797 $blocks = ['address', 'im', 'phone'];
798 foreach ($blocks as $name) {
799 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
802 foreach ($defaults[$name] as $count => & $values) {
804 //get location type id.
805 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
807 if ($name == 'address') {
808 // FIXME: lookupValue doesn't work for vcard_name
809 if (!empty($values['location_type_id'])) {
810 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', ['labelColumn' => 'vcard_name']);
811 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
814 if (!CRM_Utils_Array
::lookupValue($values,
816 CRM_Core_PseudoConstant
::country(),
821 CRM_Utils_Array
::lookupValue($values,
823 CRM_Core_PseudoConstant
::countryIsoCode(),
827 $stateProvinceID = self
::resolveStateProvinceID($values, $values['country_id'] ??
NULL);
828 if ($stateProvinceID) {
829 $values['state_province_id'] = $stateProvinceID;
832 if (!empty($values['state_province_id'])) {
833 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
836 $countyList = CRM_Core_PseudoConstant
::county();
838 CRM_Utils_Array
::lookupValue($values,
846 CRM_Utils_Array
::lookupValue($values,
848 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
853 if ($name == 'phone') {
854 CRM_Utils_Array
::lookupValue($values,
856 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
861 // Kill the reference.
868 * Fetch object based on array of properties.
870 * @param array $params
871 * (reference ) an assoc array of name/value pairs.
872 * @param array $defaults
873 * (reference ) an assoc array to hold the name / value pairs.
874 * in a hierarchical manner
875 * @param bool $microformat
876 * For location in microformat.
878 * @return CRM_Contact_BAO_Contact
880 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
881 if (array_key_exists('contact_id', $params)) {
882 $params['id'] = $params['contact_id'];
884 elseif (array_key_exists('id', $params)) {
885 $params['contact_id'] = $params['id'];
888 $contact = self
::getValues($params, $defaults);
890 unset($params['id']);
892 //get the block information for this contact
893 $entityBlock = ['contact_id' => $params['contact_id']];
894 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
895 $defaults = array_merge($defaults, $blocks);
896 foreach ($blocks as $block => $value) {
897 $contact->$block = $value;
900 if (!isset($params['noNotes'])) {
901 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
904 if (!isset($params['noRelationships'])) {
905 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
908 if (!isset($params['noGroups'])) {
909 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
912 if (!isset($params['noWebsite'])) {
913 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
920 * Get the display name of a contact.
925 * @return null|string
926 * display name of the contact if found
928 public static function displayName($id) {
931 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
938 * Delete a contact and all its associated records.
941 * Id of the contact to delete.
942 * @param bool $restore
943 * Whether to actually restore, not delete.
944 * @param bool $skipUndelete
945 * Whether to force contact delete or not.
946 * @param bool $checkPermissions
949 * Was contact deleted?
951 * @throws \CRM_Core_Exception
952 * @throws \CiviCRM_API3_Exception
954 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
956 if (!$id ||
!is_numeric($id)) {
957 CRM_Core_Error
::deprecatedFunctionWarning('calling delete contact without a valid contact ID is deprecated.');
960 // If trash is disabled in system settings then we always skip
961 if (!Civi
::settings()->get('contact_undelete')) {
962 $skipUndelete = TRUE;
965 // make sure we have edit permission for this contact
967 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
968 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
974 // Restrict contact to be delete if contact has financial trxns
976 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent([$id], $error)) {
980 // make sure this contact_id does not have any membership types
981 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
984 'member_of_contact_id'
986 if ($membershipTypeID) {
990 $contact = new CRM_Contact_DAO_Contact();
992 if (!$contact->find(TRUE)) {
996 $contactType = $contact->contact_type
;
998 // @todo deprecate calling contactDelete with the intention to restore.
1000 'id' => $contact->id
,
1001 'is_deleted' => FALSE,
1003 self
::create($updateParams);
1007 // start a new transaction
1008 $transaction = new CRM_Core_Transaction();
1010 if ($skipUndelete) {
1011 $hookParams = ['check_permissions' => $checkPermissions];
1012 CRM_Utils_Hook
::pre('delete', $contactType, $id, $hookParams);
1014 //delete billing address if exists.
1015 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
1017 // delete the log entries since we dont have triggers enabled as yet
1018 $logDAO = new CRM_Core_DAO_Log();
1019 $logDAO->entity_table
= 'civicrm_contact';
1020 $logDAO->entity_id
= $id;
1023 // delete contact participants CRM-12155
1024 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
1026 // delete contact contributions CRM-12155
1027 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
1029 // do activity cleanup, CRM-5604
1030 CRM_Activity_BAO_Activity
::cleanupActivity($id);
1032 // delete all notes related to contact
1033 CRM_Core_BAO_Note
::cleanContactNotes($id);
1035 // delete cases related to contact
1036 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
1037 if (!empty($contactCases)) {
1038 foreach ($contactCases as $caseId) {
1039 //check if case is associate with other contact or not.
1040 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
1041 if (count($caseContactId) <= 1) {
1042 CRM_Case_BAO_Case
::deleteCase($caseId);
1050 self
::contactTrash($contact);
1052 // currently we only clear employer cache.
1053 // we are now deleting inherited membership if any.
1054 if ($contact->contact_type
== 'Organization') {
1055 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
1056 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
1057 if (!empty($relationshipDtls)) {
1058 foreach ($relationshipDtls as $rId => $details) {
1059 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
1062 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
1065 //delete the contact id from recently view
1066 CRM_Utils_Recent
::delContact($id);
1067 self
::updateContactCache($id, empty($restore));
1069 // delete any prevnext/dupe cache entry
1070 // These two calls are redundant in default deployments, but they're
1071 // meaningful if "prevnext" is memory-backed.
1072 Civi
::service('prevnext')->deleteItem($id);
1073 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1075 $transaction->commit();
1077 if ($skipUndelete) {
1078 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1085 * Action to update any caches relating to a recently update contact.
1087 * I was going to call this from delete as well as from create to ensure the delete is being
1088 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1089 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1090 * where the call involved a subquery that was locking the table.
1092 * @param int $contactID
1093 * @param bool $isTrashed
1095 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1098 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1099 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1100 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1101 // but this should not cause any change as long as contacts are not being trashed outside the
1102 // main functions for that.
1103 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1106 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1111 * Delete the image of a contact.
1114 * Id of the contact.
1117 * Was contact image deleted?
1119 public static function deleteContactImage($id) {
1124 $contact = new self();
1126 $contact->image_URL
= 'null';
1133 * Return proportional height and width of the image.
1135 * @param int $imageWidth
1138 * @param int $imageHeight
1142 * Thumb dimension of image
1144 public static function getThumbSize($imageWidth, $imageHeight) {
1146 if ($imageWidth && $imageHeight) {
1147 $imageRatio = $imageWidth / $imageHeight;
1152 if ($imageRatio > 1) {
1153 $imageThumbWidth = $thumbWidth;
1154 $imageThumbHeight = round($thumbWidth / $imageRatio);
1157 $imageThumbHeight = $thumbWidth;
1158 $imageThumbWidth = round($thumbWidth * $imageRatio);
1161 return [$imageThumbWidth, $imageThumbHeight];
1165 * Validate type of contact image.
1167 * @param array $params
1168 * @param string $imageIndex
1169 * Index of image field.
1170 * @param string $statusMsg
1171 * Status message to be set after operation.
1172 * @param string $opType
1173 * Type of operation like fatal, bounce etc.
1176 * true if valid image extension
1178 public static function processImageParams(
1180 $imageIndex = 'image_URL',
1194 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1195 $photo = basename($params[$imageIndex]['name']);
1196 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1200 unset($params[$imageIndex]);
1202 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1204 if ($opType == 'status') {
1205 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1207 // FIXME: additional support for fatal, bounce etc could be added.
1213 * Extract contact id from url for deleting contact image.
1215 public static function processImage() {
1217 $action = CRM_Utils_Request
::retrieve('action', 'String');
1218 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1219 // retrieve contact id in case of Profile context
1220 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1221 $cid = $cid ?
$cid : $id;
1222 if ($action & CRM_Core_Action
::DELETE
) {
1223 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1224 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1225 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1226 $session = CRM_Core_Session
::singleton();
1227 $toUrl = $session->popUserContext();
1228 CRM_Utils_System
::redirect($toUrl);
1234 * Function to set is_delete true or restore deleted contact.
1236 * @param CRM_Contact_DAO_Contact $contact
1237 * Contact DAO object.
1238 * @param bool $restore
1239 * True to set the is_delete = 1 else false to restore deleted contact,
1240 * i.e. is_delete = 0
1245 * @throws \CRM_Core_Exception
1247 public static function contactTrashRestore($contact, $restore = FALSE) {
1248 CRM_Core_Error
::deprecatedFunctionWarning('Use the api');
1251 CRM_Core_Error
::deprecatedFunctionWarning('Use contact.create to restore - this does nothing much');
1252 // @todo deprecate calling contactDelete with the intention to restore.
1254 'id' => $contact->id
,
1255 'is_deleted' => FALSE,
1257 self
::create($updateParams);
1260 return self
::contactTrash($contact);
1264 * Get contact type for a contact.
1267 * Id of the contact whose contact type is needed.
1270 * contact_type if $id found else null ""
1272 public static function getContactType($id) {
1273 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1277 * Get contact sub type for a contact.
1280 * Id of the contact whose contact sub type is needed.
1282 * @param string $implodeDelimiter
1285 * contact_sub_type if $id found else null ""
1287 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1288 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1290 return $implodeDelimiter ?
NULL : [];
1293 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1295 if ($implodeDelimiter) {
1296 $subtype = implode($implodeDelimiter, $subtype);
1302 * Get pair of contact-type and sub-type for a contact.
1305 * Id of the contact whose contact sub/contact type is needed.
1309 public static function getContactTypes($id) {
1310 $params = ['id' => $id];
1312 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1315 ['contact_type', 'contact_sub_type']
1320 if ($contact->contact_sub_type
) {
1321 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1323 array_unshift($contactTypes, $contact->contact_type
);
1325 return $contactTypes;
1328 throw new CRM_Core_Exception();
1333 * Combine all the importable fields from the lower levels object.
1335 * The ordering is important, since currently we do not have a weight
1336 * scheme. Adding weight is super important
1338 * @param int|string $contactType contact Type
1339 * @param bool $status
1340 * Status is used to manipulate first title.
1341 * @param bool $showAll
1342 * If true returns all fields (includes disabled fields).
1343 * @param bool $isProfile
1344 * If its profile mode.
1345 * @param bool $checkPermission
1346 * If false, do not include permissioning clause (for custom data).
1348 * @param bool $withMultiCustomFields
1351 * array of importable Fields
1353 public static function importableFields(
1354 $contactType = 'Individual',
1358 $checkPermission = TRUE,
1359 $withMultiCustomFields = FALSE
1361 if (empty($contactType)) {
1362 $contactType = 'All';
1365 $cacheKeyString = "importableFields $contactType";
1366 $cacheKeyString .= $status ?
'_1' : '_0';
1367 $cacheKeyString .= $showAll ?
'_1' : '_0';
1368 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1369 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1370 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1372 $fields = self
::$_importableFields[$cacheKeyString] ?? Civi
::cache('fields')->get($cacheKeyString);
1375 $fields = CRM_Contact_DAO_Contact
::import();
1377 // get the fields thar are meant for contact types
1378 if (in_array($contactType, [
1384 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1387 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1388 CRM_Core_DAO_Phone
::import(),
1389 CRM_Core_DAO_Email
::import(),
1390 CRM_Core_DAO_IM
::import(TRUE),
1391 CRM_Core_DAO_OpenID
::import()
1394 $locationFields = array_merge($locationFields,
1395 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1403 foreach ($locationFields as $key => $field) {
1404 $locationFields[$key]['hasLocationType'] = TRUE;
1407 $fields = array_merge($fields, $locationFields);
1409 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1410 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1413 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1414 $fields['url']['hasWebsiteType'] = TRUE;
1416 if ($contactType != 'All') {
1417 $fields = array_merge($fields,
1418 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1423 $withMultiCustomFields
1426 // Unset the fields which are not related to their contact type.
1427 foreach (CRM_Contact_DAO_Contact
::import() as $name => $value) {
1428 if (!empty($value['contactType']) && $value['contactType'] !== $contactType) {
1429 unset($fields[$name]);
1434 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1435 $fields = array_merge($fields,
1436 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1441 $withMultiCustomFields
1448 $fields = array_merge($fields, [
1450 'title' => ts('Group(s)'),
1454 'title' => ts('Tag(s)'),
1458 'title' => ts('Note'),
1461 'communication_style_id' => [
1462 'title' => ts('Communication Style'),
1463 'name' => 'communication_style_id',
1468 //Sorting fields in alphabetical order(CRM-1507)
1469 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1471 Civi
::cache('fields')->set($cacheKeyString, $fields);
1474 self
::$_importableFields[$cacheKeyString] = $fields;
1478 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1479 self
::$_importableFields[$cacheKeyString]
1483 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1484 self
::$_importableFields[$cacheKeyString]
1492 * Combine all the exportable fields from the lower levels object.
1494 * Currently we are using importable fields as exportable fields
1496 * @param int|string $contactType contact Type
1497 * @param bool $status
1498 * True while exporting primary contacts.
1499 * @param bool $export
1500 * True when used during export.
1501 * @param bool $search
1502 * True when used during search, might conflict with export param?.
1504 * @param bool $withMultiRecord
1505 * @param bool $checkPermissions
1508 * array of exportable Fields
1510 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1511 if (empty($contactType)) {
1512 $contactType = 'All';
1515 $cacheKeyString = "exportableFields $contactType";
1516 $cacheKeyString .= $export ?
'_1' : '_0';
1517 $cacheKeyString .= $status ?
'_1' : '_0';
1518 $cacheKeyString .= $search ?
'_1' : '_0';
1519 $cacheKeyString .= '_' . (bool) $checkPermissions;
1520 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1521 //calculates custom fields takes into account the logged in user & caches that for all users
1522 //as an interim fix we will cache the fields by contact
1523 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1525 if (!self
::$_exportableFields ||
empty(self
::$_exportableFields[$cacheKeyString])) {
1526 if (!self
::$_exportableFields) {
1527 self
::$_exportableFields = [];
1530 // check if we can retrieve from database cache
1531 $fields = Civi
::cache('fields')->get($cacheKeyString);
1534 $fields = CRM_Contact_DAO_Contact
::export();
1536 // The fields are meant for contact types.
1537 if (in_array($contactType, [
1543 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1545 // add current employer for individuals
1546 $fields = array_merge($fields, [
1547 'current_employer' =>
1549 'name' => 'organization_name',
1550 'title' => ts('Current Employer'),
1551 'type' => CRM_Utils_Type
::T_STRING
,
1555 // This probably would be added anyway by appendPseudoConstantsToFields.
1557 'location_type' => [
1558 'name' => 'location_type',
1559 'where' => 'civicrm_location_type.name',
1560 'title' => ts('Location Type'),
1561 'type' => CRM_Utils_Type
::T_STRING
,
1567 'name' => 'im_provider',
1568 'where' => 'civicrm_im.provider_id',
1569 'title' => ts('IM Provider'),
1570 'type' => CRM_Utils_Type
::T_STRING
,
1574 $phoneFields = CRM_Core_DAO_Phone
::export();
1575 // This adds phone_type to the exportable fields and make it available for export.
1576 // with testing the same can be done to the other entities.
1577 CRM_Core_DAO
::appendPseudoConstantsToFields($phoneFields);
1578 $locationFields = array_merge($locationType,
1579 CRM_Core_DAO_Address
::export(),
1581 CRM_Core_DAO_Email
::export(),
1583 CRM_Core_DAO_IM
::export(TRUE),
1584 CRM_Core_DAO_OpenID
::export()
1587 $locationFields = array_merge($locationFields,
1588 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1591 foreach ($locationFields as $key => $field) {
1592 $locationFields[$key]['hasLocationType'] = TRUE;
1595 $fields = array_merge($fields, $locationFields);
1598 $fields = array_merge($fields,
1599 CRM_Core_DAO_Worldregion
::export()
1602 $fields = array_merge($fields,
1603 CRM_Contact_DAO_Contact
::export()
1607 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1609 if ($contactType != 'All') {
1610 $fields = array_merge($fields,
1611 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1615 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1616 $fields = array_merge($fields,
1617 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1623 $fields = array_merge($fields, [
1625 'title' => ts('Group(s)'),
1629 'title' => ts('Tag(s)'),
1633 'title' => ts('Note(s)'),
1639 $fields = array_merge($fields, [
1641 'title' => ts('Group(s)'),
1645 'title' => ts('Tag(s)'),
1649 'title' => ts('Note(s)'),
1655 //Sorting fields in alphabetical order(CRM-1507)
1656 foreach ($fields as $k => $v) {
1657 $sortArray[$k] = $v['title'] ??
NULL;
1660 $fields = array_merge($sortArray, $fields);
1661 //unset the field which are not related to their contact type.
1662 if ($contactType != 'All') {
1668 'organization_name',
1669 'email_greeting_custom',
1670 'postal_greeting_custom',
1683 'organization_name',
1691 'email_greeting_custom',
1692 'postal_greeting_custom',
1708 'email_greeting_custom',
1709 'postal_greeting_custom',
1719 foreach ($commonValues[$contactType] as $value) {
1720 unset($fields[$value]);
1724 Civi
::cache('fields')->set($cacheKeyString, $fields);
1726 self
::$_exportableFields[$cacheKeyString] = $fields;
1730 $fields = self
::$_exportableFields[$cacheKeyString];
1733 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1734 self
::$_exportableFields[$cacheKeyString]
1742 * Get the all contact details (Hierarchical).
1744 * @param int $contactId
1746 * @param array $fields
1752 public static function getHierContactDetails($contactId, $fields) {
1753 $params = [['contact_id', '=', $contactId, 0, 0]];
1755 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1757 // We don't know the contents of return properties, but we need the lower
1758 // level ids of the contact so add a few fields.
1759 $returnProperties['first_name'] = 1;
1760 $returnProperties['organization_name'] = 1;
1761 $returnProperties['household_name'] = 1;
1762 $returnProperties['contact_type'] = 1;
1763 $returnProperties['contact_sub_type'] = 1;
1764 list($query) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties);
1769 * Given a set of flat profile style field names, create a hierarchy.
1771 * This is for the query to use, create the right sql.
1774 * @param int $contactId
1778 * A hierarchical property tree if appropriate
1780 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1781 $locationTypes = CRM_Core_BAO_Address
::buildOptions('location_type_id', 'validate');
1783 $returnProperties = [];
1785 $multipleFields = ['website' => 'url'];
1786 foreach ($fields as $name => $dontCare) {
1787 if (strpos($name, '-') !== FALSE) {
1788 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1790 if (!in_array($fieldName, $multipleFields)) {
1791 if ($id == 'Primary') {
1792 $locationTypeName = 1;
1795 $locationTypeName = $locationTypes[$id] ??
NULL;
1796 if (!$locationTypeName) {
1801 if (empty($returnProperties['location'])) {
1802 $returnProperties['location'] = [];
1804 if (empty($returnProperties['location'][$locationTypeName])) {
1805 $returnProperties['location'][$locationTypeName] = [];
1806 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1808 if (in_array($fieldName, [
1816 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1819 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1822 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1823 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1826 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1830 $returnProperties['website'][$id][$fieldName] = 1;
1834 $returnProperties[$name] = 1;
1838 return $returnProperties;
1842 * Return the primary location type of a contact.
1844 * $params int $contactId contact_id
1845 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1846 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1848 * @param int $contactId
1849 * @param bool $skipDefaultPriamry
1850 * @param null $block
1853 * $locationType location_type_id
1855 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1857 $entityBlock = ['contact_id' => $contactId];
1858 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1859 foreach ($blocks[$block] as $key => $value) {
1860 if (!empty($value['is_primary'])) {
1861 $locationType = $value['location_type_id'] ??
NULL;
1868 IF ( civicrm_email.location_type_id IS NULL,
1869 IF ( civicrm_address.location_type_id IS NULL,
1870 IF ( civicrm_phone.location_type_id IS NULL,
1871 IF ( civicrm_im.location_type_id IS NULL,
1872 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1873 ,civicrm_im.location_type_id)
1874 ,civicrm_phone.location_type_id)
1875 ,civicrm_address.location_type_id)
1876 ,civicrm_email.location_type_id) as locationType
1877 FROM civicrm_contact
1878 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1879 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1880 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1881 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1882 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1883 WHERE civicrm_contact.id = %1 ";
1885 $params = [1 => [$contactId, 'Integer']];
1887 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1889 $locationType = NULL;
1890 if ($dao->fetch()) {
1891 $locationType = $dao->locationType
;
1894 if (isset($locationType)) {
1895 return $locationType;
1897 elseif ($skipDefaultPriamry) {
1898 // if there is no primary contact location then return null
1902 // if there is no primart contact location, then return default
1903 // location type of the system
1904 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1905 return $defaultLocationType->id
;
1910 * Get the display name, primary email and location type of a contact.
1913 * Id of the contact.
1916 * Array of display_name, email if found, do_not_email or (null,null,null)
1918 public static function getContactDetails($id) {
1919 // check if the contact type
1920 $contactType = self
::getContactType($id);
1922 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1925 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1926 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1927 WHERE civicrm_contact.id = %1
1928 ORDER BY civicrm_email.is_primary DESC";
1929 $params = [1 => [$id, 'Integer']];
1930 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1932 if ($dao->fetch()) {
1933 if ($contactType == 'Individual') {
1934 if ($dao->first_name ||
$dao->last_name
) {
1935 $name = "{$dao->first_name} {$dao->last_name}";
1938 $name = $dao->display_name
;
1942 $name = $dao->display_name
;
1944 $email = $dao->email
;
1945 $doNotEmail = (bool) $dao->do_not_email
;
1946 $onHold = (bool) $dao->on_hold
;
1947 $isDeceased = (bool) $dao->is_deceased
;
1948 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1950 return [NULL, NULL, NULL, NULL, NULL];
1954 * Add/edit/register contacts through profile.
1956 * @param array $params
1957 * Array of profile fields to be edited/added.
1958 * @param array $fields
1959 * Array of fields from UFGroup.
1960 * @param int $contactID
1961 * Id of the contact to be edited/added.
1962 * @param int $addToGroupID
1963 * Specifies the default group to which contact is added.
1964 * @param int $ufGroupId
1965 * Uf group id (profile id).
1966 * @param string $ctype
1967 * @param bool $visibility
1968 * Basically lets us know where this request is coming from.
1969 * if via a profile from web, we restrict what groups are changed
1972 * contact id created/edited
1974 * @throws \CRM_Core_Exception
1975 * @throws \CiviCRM_API3_Exception
1976 * @throws \Civi\API\Exception\UnauthorizedException
1978 public static function createProfileContact(
1982 $addToGroupID = NULL,
1987 // add ufGroupID to params array ( CRM-2012 )
1989 $params['uf_group_id'] = $ufGroupId;
1991 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1993 // If a user has logged in, or accessed via a checksum
1994 // Then deliberately 'blanking' a value in the profile should remove it from their record
1995 $session = CRM_Core_Session
::singleton();
1996 $params['updateBlankLocInfo'] = TRUE;
1997 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1998 $params['updateBlankLocInfo'] = FALSE;
2003 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
2007 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
2010 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
2012 // manage is_opt_out
2013 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
2014 $wasOptOut = $contactDetails['is_opt_out'] ??
FALSE;
2015 $isOptOut = $params['is_opt_out'];
2016 $data['is_opt_out'] = $isOptOut;
2017 // on change, create new civicrm_subscription_history entry
2018 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2020 'contact_id' => $contactDetails['contact_id'],
2021 'status' => $isOptOut ?
'Removed' : 'Added',
2024 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2028 $contact = self
::create($data);
2030 // contact is null if the profile does not have any contact fields
2032 $contactID = $contact->id
;
2035 if (empty($contactID)) {
2036 throw new CRM_Core_Exception('Cannot proceed without a valid contact id');
2039 // Process group and tag
2040 if (isset($params['group'])) {
2042 // this for sure means we are coming in via profile since i added it to fix
2043 // removing contacts from user groups -- lobo
2047 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2050 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2051 // Convert comma separated form values from select2 v3
2052 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2053 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2056 //to add profile in default group
2057 if (is_array($addToGroupID)) {
2058 $contactIds = [$contactID];
2059 foreach ($addToGroupID as $groupId) {
2060 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2063 elseif ($addToGroupID) {
2064 $contactIds = [$contactID];
2065 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2069 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2072 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2078 * Format profile contact parameters.
2080 * @param array $params
2082 * @param int $contactID
2083 * @param int $ufGroupId
2084 * @param null $ctype
2085 * @param bool $skipCustom
2089 public static function formatProfileContactParams(
2098 $data = $contactDetails = [];
2100 // get the contact details (hier)
2102 $details = self
::getHierContactDetails($contactID, $fields);
2104 $contactDetails = $details[$contactID];
2105 $data['contact_type'] = $contactDetails['contact_type'] ??
NULL;
2106 $data['contact_sub_type'] = $contactDetails['contact_sub_type'] ??
NULL;
2109 //we should get contact type only if contact
2111 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId, TRUE, FALSE, TRUE);
2113 //special case to handle profile with only contact fields
2114 if ($data['contact_type'] == 'Contact') {
2115 $data['contact_type'] = 'Individual';
2117 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2118 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2122 $data['contact_type'] = $ctype;
2125 $data['contact_type'] = 'Individual';
2129 //fix contact sub type CRM-5125
2130 if (array_key_exists('contact_sub_type', $params) &&
2131 !empty($params['contact_sub_type'])
2133 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2135 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2136 !empty($params['contact_sub_type_hidden'])
2138 // if profile was used, and had any subtype, we obtain it from there
2139 //CRM-13596 - add to existing contact types, rather than overwriting
2140 if (empty($data['contact_sub_type'])) {
2141 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2142 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2145 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2146 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2147 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2148 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2149 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2154 if ($ctype == 'Organization') {
2155 $data['organization_name'] = $contactDetails['organization_name'] ??
NULL;
2157 elseif ($ctype == 'Household') {
2158 $data['household_name'] = $contactDetails['household_name'] ??
NULL;
2166 $data['contact_id'] = $contactID;
2167 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2170 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2171 $defaultLocationId = $defaultLocation->id
;
2174 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2176 $blocks = ['email', 'phone', 'im', 'openid'];
2178 $multiplFields = ['url'];
2179 // prevent overwritten of formatted array, reset all block from
2180 // params if it is not in valid format (since import pass valid format)
2181 foreach ($blocks as $blk) {
2182 if (array_key_exists($blk, $params) &&
2183 !is_array($params[$blk])
2185 unset($params[$blk]);
2189 $primaryPhoneLoc = NULL;
2190 $session = CRM_Core_Session
::singleton();
2191 foreach ($params as $key => $value) {
2192 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2194 if ($locTypeId == 'Primary') {
2196 if (in_array($fieldName, $blocks)) {
2197 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2200 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2202 $primaryLocationType = $locTypeId;
2205 $locTypeId = $defaultLocationId;
2209 if (is_numeric($locTypeId) &&
2210 !in_array($fieldName, $multiplFields) &&
2211 substr($fieldName, 0, 7) != 'custom_'
2213 $index = $locTypeId;
2215 if (is_numeric($typeId)) {
2216 $index .= '-' . $typeId;
2218 if (!in_array($index, $locationType)) {
2219 $locationType[$count] = $index;
2223 $loc = CRM_Utils_Array
::key($index, $locationType);
2225 $blockName = self
::getLocationEntityForKey($fieldName);
2227 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2229 //set is_billing true, for location type "Billing"
2230 if ($locTypeId == $billingLocationTypeId) {
2231 $data[$blockName][$loc]['is_billing'] = 1;
2235 //get the primary location type
2236 if ($locTypeId == $primaryLocationType) {
2237 $data[$blockName][$loc]['is_primary'] = 1;
2240 elseif ($locTypeId == $defaultLocationId) {
2241 $data[$blockName][$loc]['is_primary'] = 1;
2244 if (in_array($fieldName, ['phone'])) {
2246 $data['phone'][$loc]['phone_type_id'] = $typeId;
2249 $data['phone'][$loc]['phone_type_id'] = '';
2251 $data['phone'][$loc]['phone'] = $value;
2253 //special case to handle primary phone with different phone types
2254 // in this case we make first phone type as primary
2255 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2256 $primaryPhoneLoc = $loc;
2259 if ($loc != $primaryPhoneLoc) {
2260 unset($data['phone'][$loc]['is_primary']);
2263 elseif ($fieldName == 'email') {
2264 $data['email'][$loc]['email'] = $value;
2265 if (empty($contactID)) {
2266 $data['email'][$loc]['is_primary'] = 1;
2269 elseif ($fieldName == 'im') {
2270 if (isset($params[$key . '-provider_id'])) {
2271 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2273 if (strpos($key, '-provider_id') !== FALSE) {
2274 $data['im'][$loc]['provider_id'] = $params[$key];
2277 $data['im'][$loc]['name'] = $value;
2280 elseif ($fieldName == 'openid') {
2281 $data['openid'][$loc]['openid'] = $value;
2284 if ($fieldName === 'state_province') {
2286 if (is_numeric($value) && ((int ) $value) >= 1000) {
2287 $data['address'][$loc]['state_province_id'] = $value;
2289 elseif (empty($value)) {
2290 $data['address'][$loc]['state_province_id'] = '';
2293 $data['address'][$loc]['state_province'] = $value;
2296 elseif ($fieldName === 'country') {
2298 if (is_numeric($value) && ((int ) $value) >= 1000
2300 $data['address'][$loc]['country_id'] = $value;
2302 elseif (empty($value)) {
2303 $data['address'][$loc]['country_id'] = '';
2306 $data['address'][$loc]['country'] = $value;
2309 elseif ($fieldName === 'county') {
2310 $data['address'][$loc]['county_id'] = $value;
2312 elseif ($fieldName == 'address_name') {
2313 $data['address'][$loc]['name'] = $value;
2315 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2316 $data['address'][$loc][substr($fieldName, 8)] = $value;
2319 $data[$blockName][$loc][$fieldName] = $value;
2324 if (substr($key, 0, 4) === 'url-') {
2325 $websiteField = explode('-', $key);
2326 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2327 $data['website'][$websiteField[1]]['url'] = $value;
2329 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2330 //save email/postal greeting and addressee values if any, CRM-4575
2331 $data[$key . '_id'] = $value;
2333 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2334 // for autocomplete transfer hidden value instead of label
2335 if ($params[$key] && isset($params[$key . '_id'])) {
2336 $value = $params[$key . '_id'];
2339 // we need to append time with date
2340 if ($params[$key] && isset($params[$key . '_time'])) {
2341 $value .= ' ' . $params[$key . '_time'];
2344 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2345 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2346 ($value == '' ||
!isset($value))
2352 if (!empty($params['customRecordValues'])) {
2353 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2354 foreach ($params['customRecordValues'] as $recId => $customFields) {
2355 if (is_array($customFields) && !empty($customFields)) {
2356 foreach ($customFields as $customFieldName) {
2357 if ($customFieldName == $key) {
2367 //CRM-13596 - check for contact_sub_type_hidden first
2368 if (array_key_exists('contact_sub_type_hidden', $params)) {
2369 $type = $params['contact_sub_type_hidden'];
2372 $type = $data['contact_type'];
2373 if (!empty($data['contact_sub_type'])) {
2374 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2378 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2388 elseif ($key === 'edit') {
2392 if ($key === 'location') {
2393 foreach ($value as $locationTypeId => $field) {
2394 foreach ($field as $block => $val) {
2395 if ($block === 'address' && array_key_exists('address_name', $val)) {
2396 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2401 if ($key === 'phone' && isset($params['phone_ext'])) {
2402 $data[$key] = $value;
2403 foreach ($value as $cnt => $phoneBlock) {
2404 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2405 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2409 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2410 && ($value == '' ||
!isset($value)) &&
2411 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2412 ($key === 'current_employer' && empty($params['current_employer']))) {
2413 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2414 // to avoid update with empty values
2418 $data[$key] = $value;
2424 if (!isset($data['contact_type'])) {
2425 $data['contact_type'] = 'Individual';
2428 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2429 $privacy = CRM_Core_SelectValues
::privacy();
2430 foreach ($privacy as $key => $value) {
2431 if (array_key_exists($key, $fields)) {
2432 // do not reset values for existing contacts, if fields are added to a profile
2433 if (array_key_exists($key, $params)) {
2434 $data[$key] = $params[$key];
2435 if (empty($params[$key])) {
2439 elseif (!$contactID) {
2445 return [$data, $contactDetails];
2449 * Find the get contact details.
2451 * This function does not respect ACLs for now, which might need to be rectified at some
2452 * stage based on how its used.
2454 * @param string $mail
2455 * Primary email address of the contact.
2456 * @param string $ctype
2459 * @return object|null
2460 * $dao contact details
2462 public static function matchContactOnEmail($mail, $ctype = NULL) {
2463 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2464 $mail = $strtolower(trim($mail));
2466 SELECT civicrm_contact.id as contact_id,
2467 civicrm_contact.hash as hash,
2468 civicrm_contact.contact_type as contact_type,
2469 civicrm_contact.contact_sub_type as contact_sub_type
2470 FROM civicrm_contact
2471 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2473 if (Civi
::settings()->get('uniq_email_per_site')) {
2474 // try to find a match within a site (multisite).
2475 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2476 if (!empty($groups)) {
2478 INNER JOIN civicrm_group_contact gc ON
2479 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2484 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2485 $p = [1 => [$mail, 'String']];
2488 $query .= " AND civicrm_contact.contact_type = %3";
2489 $p[3] = [$ctype, 'String'];
2492 $query .= " ORDER BY civicrm_email.is_primary DESC";
2494 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2496 if ($dao->fetch()) {
2503 * Find the contact details associated with an OpenID.
2505 * @param string $openId
2506 * OpenId of the contact.
2507 * @param string $ctype
2510 * @return object|null
2511 * $dao contact details
2513 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2514 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2515 $openId = $strtolower(trim($openId));
2517 SELECT civicrm_contact.id as contact_id,
2518 civicrm_contact.hash as hash,
2519 civicrm_contact.contact_type as contact_type,
2520 civicrm_contact.contact_sub_type as contact_sub_type
2521 FROM civicrm_contact
2522 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2523 WHERE civicrm_openid.openid = %1";
2524 $p = [1 => [$openId, 'String']];
2527 $query .= " AND civicrm_contact.contact_type = %3";
2528 $p[3] = [$ctype, 'String'];
2531 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2533 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2535 if ($dao->fetch()) {
2542 * Get primary email of the contact.
2544 * @param int $contactID
2546 * @param bool $polite
2547 * Whether to only pull an email if it's okay to send to it--that is, if it
2548 * is not on_hold and the contact is not do_not_email.
2551 * Email address if present else null
2553 public static function getPrimaryEmail($contactID, $polite = FALSE) {
2554 // fetch the primary email
2556 SELECT civicrm_email.email as email
2557 FROM civicrm_contact
2558 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2559 WHERE civicrm_email.is_primary = 1
2560 AND civicrm_contact.id = %1";
2563 AND civicrm_contact.do_not_email = 0
2564 AND civicrm_email.on_hold = 0';
2566 $p = [1 => [$contactID, 'Integer']];
2567 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2570 if ($dao->fetch()) {
2571 $email = $dao->email
;
2577 * Fetch the object and store the values in the values array.
2579 * @param array $params
2580 * Input parameters to find object.
2581 * @param array $values
2582 * Output values of the object.
2584 * @return CRM_Contact_BAO_Contact|null
2585 * The found object or null
2587 public static function getValues(&$params, &$values) {
2588 $contact = new CRM_Contact_BAO_Contact();
2590 $contact->copyValues($params);
2592 if ($contact->find(TRUE)) {
2594 CRM_Core_DAO
::storeValues($contact, $values);
2597 foreach (self
::$_commPrefs as $name) {
2598 if (isset($contact->$name)) {
2599 $privacy[$name] = $contact->$name;
2603 if (!empty($privacy)) {
2604 $values['privacy'] = $privacy;
2607 // communication Prefferance
2608 $preffComm = $comm = [];
2609 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2610 $contact->preferred_communication_method
2612 foreach ($comm as $value) {
2613 $preffComm[$value] = 1;
2615 $temp = ['preferred_communication_method' => $contact->preferred_communication_method
];
2618 'preferred_communication_method' => [
2619 'newName' => 'preferred_communication_method_display',
2620 'groupName' => 'preferred_communication_method',
2624 // @todo This can be figured out from metadata & we can avoid the uncached query.
2625 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2627 $values['preferred_communication_method'] = $preffComm;
2628 $values['preferred_communication_method_display'] = $temp['preferred_communication_method_display'] ??
NULL;
2630 if ($contact->preferred_mail_format
) {
2631 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2632 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2635 // get preferred languages
2636 if (!empty($contact->preferred_language
)) {
2637 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2640 // Calculating Year difference
2641 if ($contact->birth_date
) {
2642 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2643 if ($birthDate < date('Ymd')) {
2644 $deceasedDate = NULL;
2645 if (!empty($contact->is_deceased
) && !empty($contact->deceased_date
)) {
2646 $deceasedDate = $contact->deceased_date
;
2648 $age = CRM_Utils_Date
::calculateAge($birthDate, $deceasedDate);
2649 $values['age']['y'] = $age['years'] ??
NULL;
2650 $values['age']['m'] = $age['months'] ??
NULL;
2654 $contact->contact_id
= $contact->id
;
2662 * Given the component name and returns the count of participation of contact.
2664 * @param string $component
2665 * Input component name.
2666 * @param int $contactId
2668 * @param string $tableName
2669 * Optional tableName if component is custom group.
2672 * total number in database
2674 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2676 switch ($component) {
2678 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2681 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2682 CRM_Contact_BAO_Relationship
::CURRENT
,
2691 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2694 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2697 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2700 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2702 case 'contribution':
2703 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2706 return CRM_Member_BAO_Membership
::getContactMembershipCount((int) $contactId, TRUE);
2709 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2712 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2715 return CRM_Case_BAO_Case
::caseCount($contactId);
2718 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2722 'contact_id' => $contactId,
2725 'context' => 'activity',
2727 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2730 $params = ['contact_id' => $contactId];
2731 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2734 $custom = explode('_', $component);
2735 if ($custom['0'] = 'custom') {
2737 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2739 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2740 return CRM_Core_DAO
::singleValueQuery($queryString);
2746 * Update contact greetings if an update has resulted in a custom field change.
2748 * @param array $updatedFields
2749 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2750 * @param array $contactParams
2751 * Parameters known about the contact. At minimum array('contact_id' => x).
2752 * Fields in this array will take precedence over DB fields (so far only
2753 * in the case of greeting id fields).
2755 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2756 $contactID = $contactParams['contact_id'];
2757 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2758 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2759 if (!empty($tokens['all']['contact'])) {
2760 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2761 if (!empty($affectedTokens)) {
2762 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2763 $contact = new CRM_Contact_BAO_Contact();
2764 $contact->id
= $contactID;
2765 CRM_Contact_BAO_Contact
::processGreetings($contact);
2771 * Process greetings and cache.
2773 * @param object $contact
2774 * Contact object after save.
2776 public static function processGreetings(&$contact) {
2778 //@todo this function does a lot of unnecessary loading.
2779 // ensureGreetingParamsAreSet now makes sure that the contact is
2780 // loaded and using updateGreetingsOnTokenFieldChange
2781 // allows us the possibility of only doing an update if required.
2783 // The contact object has not always required the
2784 // fields that are required to calculate greetings
2785 // so we need to retrieve it again.
2786 if ($contact->_query
!== FALSE) {
2787 $contact->find(TRUE);
2790 // store object values to an array
2791 $contactDetails = [];
2792 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2793 $contactDetails = [[$contact->id
=> $contactDetails]];
2795 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2796 $updateQueryString = [];
2798 //cache email and postal greeting to greeting display
2799 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2800 $emailGreetingString = $contact->email_greeting_custom
;
2802 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2803 // the filter value for Individual contact type is set to 1
2805 'contact_type' => $contact->contact_type
,
2806 'greeting_type' => 'email_greeting',
2809 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2810 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2811 $updateQueryString[] = " email_greeting_custom = NULL ";
2814 if ($contact->email_greeting_custom
) {
2815 $updateQueryString[] = " email_greeting_display = NULL ";
2819 if ($emailGreetingString) {
2820 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2823 'CRM_Contact_BAO_Contact'
2825 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2826 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2830 if ($contact->postal_greeting_custom
!== 'null' && $contact->postal_greeting_custom
) {
2831 $postalGreetingString = $contact->postal_greeting_custom
;
2833 elseif ($contact->postal_greeting_id
!== 'null' && $contact->postal_greeting_id
) {
2835 'contact_type' => $contact->contact_type
,
2836 'greeting_type' => 'postal_greeting',
2838 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2839 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2840 $updateQueryString[] = " postal_greeting_custom = NULL ";
2843 if ($contact->postal_greeting_custom
) {
2844 $updateQueryString[] = " postal_greeting_display = NULL ";
2848 if ($postalGreetingString) {
2849 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2852 'CRM_Contact_BAO_Contact'
2854 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2855 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2859 if ($contact->addressee_custom
!== 'null' && $contact->addressee_custom
) {
2860 $addresseeString = $contact->addressee_custom
;
2862 elseif ($contact->addressee_id
!== 'null' && $contact->addressee_id
) {
2864 'contact_type' => $contact->contact_type
,
2865 'greeting_type' => 'addressee',
2868 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2869 $addresseeString = $addressee[$contact->addressee_id
];
2870 $updateQueryString[] = " addressee_custom = NULL ";
2873 if ($contact->addressee_custom
) {
2874 $updateQueryString[] = " addressee_display = NULL ";
2878 if ($addresseeString) {
2879 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2882 'CRM_Contact_BAO_Contact'
2884 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2885 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2888 if (!empty($updateQueryString)) {
2889 $updateQueryString = implode(',', $updateQueryString);
2890 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2891 CRM_Core_DAO
::executeQuery($queryString);
2896 * Retrieve loc block ids w/ given condition.
2898 * @param int $contactId
2900 * @param array $criteria
2901 * Key => value pair which should be.
2902 * fulfill by return record ids.
2903 * @param string $condOperator
2904 * Operator use for grouping multiple conditions.
2907 * loc block ids which fulfill condition.
2909 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2912 return $locBlockIds;
2915 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2916 $name = strtolower($block);
2917 $className = "CRM_Core_DAO_$block";
2918 $blockDAO = new $className();
2920 // build the condition.
2921 if (is_array($criteria)) {
2922 $fields = $blockDAO->fields();
2924 foreach ($criteria as $field => $value) {
2925 if (array_key_exists($field, $fields)) {
2926 $cond = "( $field = $value )";
2927 // value might be zero or null.
2928 if (!$value ||
strtolower($value) === 'null') {
2929 $cond = "( $field = 0 OR $field IS NULL )";
2931 $conditions[] = $cond;
2934 if (!empty($conditions)) {
2935 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2939 $blockDAO->contact_id
= $contactId;
2941 while ($blockDAO->fetch()) {
2942 $locBlockIds[$name][] = $blockDAO->id
;
2946 return $locBlockIds;
2950 * Build context menu items.
2952 * @param int $contactId
2955 * Array of context menu for logged in user.
2957 public static function contextMenu($contactId = NULL) {
2960 'title' => ts('View Contact'),
2962 'ref' => 'view-contact',
2963 'class' => 'no-popup',
2965 'permissions' => ['view all contacts'],
2968 'title' => ts('Edit Contact'),
2970 'ref' => 'edit-contact',
2971 'class' => 'no-popup',
2973 'permissions' => ['edit all contacts'],
2976 'title' => ts('Delete Contact'),
2978 'ref' => 'delete-contact',
2980 'permissions' => ['access deleted contacts', 'delete contacts'],
2983 'title' => ts('Add Contribution'),
2985 'ref' => 'new-contribution',
2986 'key' => 'contribution',
2987 'tab' => 'contribute',
2988 'component' => 'CiviContribute',
2989 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2990 'reset=1&action=add&context=contribution'
2993 'access CiviContribute',
2994 'edit contributions',
2998 'title' => ts('Register for Event'),
3000 'ref' => 'new-participant',
3001 'key' => 'participant',
3002 'tab' => 'participant',
3003 'component' => 'CiviEvent',
3004 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3007 'edit event participants',
3011 'title' => ts('Record Activity'),
3013 'ref' => 'new-activity',
3014 'key' => 'activity',
3015 'permissions' => ['edit all contacts'],
3018 'title' => ts('Add Pledge'),
3020 'ref' => 'new-pledge',
3023 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3024 'reset=1&action=add&context=pledge'
3026 'component' => 'CiviPledge',
3028 'access CiviPledge',
3033 'title' => ts('Add Membership'),
3035 'ref' => 'new-membership',
3036 'key' => 'membership',
3038 'component' => 'CiviMember',
3039 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3040 'reset=1&action=add&context=membership'
3043 'access CiviMember',
3048 'title' => ts('Add Case'),
3050 'ref' => 'new-case',
3053 'component' => 'CiviCase',
3054 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3055 'permissions' => ['add cases'],
3058 'title' => ts('Add Grant'),
3060 'ref' => 'new-grant',
3063 'component' => 'CiviGrant',
3064 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3065 'reset=1&action=add&context=grant'
3067 'permissions' => ['edit grants'],
3070 'title' => ts('Add Relationship'),
3072 'ref' => 'new-relationship',
3075 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3076 'reset=1&action=add'
3078 'permissions' => ['edit all contacts'],
3081 'title' => ts('Add Note'),
3083 'ref' => 'new-note',
3086 'class' => 'medium-popup',
3087 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3088 'reset=1&action=add'
3090 'permissions' => ['edit all contacts'],
3093 'title' => ts('Send an Email'),
3095 'ref' => 'new-email',
3097 'permissions' => ['view all contacts'],
3100 'title' => ts('Add to Group'),
3102 'ref' => 'group-add-contact',
3105 'permissions' => ['edit groups'],
3108 'title' => ts('Tag Contact'),
3110 'ref' => 'tag-contact',
3113 'permissions' => ['edit all contacts'],
3117 $menu['otherActions'] = [
3119 'title' => ts('Print Summary'),
3120 'description' => ts('Printer-friendly view of this page.'),
3122 'ref' => 'crm-contact-print',
3125 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3129 'icon' => 'crm-i fa-print',
3132 'title' => ts('vCard'),
3133 'description' => ts('vCard record for this contact.'),
3135 'ref' => 'crm-contact-vcard',
3138 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3142 'icon' => 'crm-i fa-list-alt',
3146 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3147 $menu['otherActions']['dashboard'] = [
3148 'title' => ts('Contact Dashboard'),
3149 'description' => ts('Contact Dashboard'),
3151 'ref' => 'crm-contact-dashboard',
3152 'key' => 'dashboard',
3153 'tab' => 'dashboard',
3154 'class' => 'dashboard',
3155 // NOTE: As an alternative you can also build url on CMS specific way
3156 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3157 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3158 'icon' => 'crm-i fa-tachometer',
3162 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3164 $menu['otherActions']['user-record'] = [
3165 'title' => ts('User Record'),
3166 'description' => ts('User Record'),
3168 'ref' => 'crm-contact-user-record',
3169 'key' => 'user-record',
3170 'tab' => 'user-record',
3171 'class' => 'user-record',
3172 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3173 'icon' => 'crm-i fa-user',
3176 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3177 $menu['otherActions']['user-add'] = [
3178 'title' => ts('Create User Record'),
3179 'description' => ts('Create User Record'),
3181 'ref' => 'crm-contact-user-add',
3182 'key' => 'user-add',
3183 'tab' => 'user-add',
3184 'class' => 'user-add',
3185 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3186 'icon' => 'crm-i fa-user-plus',
3190 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3191 //1. check for component is active.
3192 //2. check for user permissions.
3193 //3. check for acls.
3194 //3. edit and view contact are directly accessible to user.
3196 $aclPermissionedTasks = [
3201 'group-add-contact',
3205 $corePermission = CRM_Core_Permission
::getPermission();
3208 foreach ($menu as $key => $values) {
3209 if ($key !== 'otherActions') {
3211 // user does not have necessary permissions.
3212 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3215 // build directly accessible action menu.
3216 if (in_array($values['ref'], [
3220 $contextMenu['primaryActions'][$key] = [
3221 'title' => $values['title'],
3222 'ref' => $values['ref'],
3223 'class' => $values['class'] ??
NULL,
3224 'key' => $values['key'],
3229 // finally get menu item for -more- action widget.
3230 while (!empty($contextMenu['moreActions'][$values['weight']])) {
3231 // Quick & dirty way of handling 2 items with the same weight
3232 // without clobbering one.
3233 $values['weight']++
;
3235 $contextMenu['moreActions'][$values['weight']] = [
3236 'title' => $values['title'],
3237 'ref' => $values['ref'],
3238 'href' => $values['href'] ??
NULL,
3239 'tab' => $values['tab'] ??
NULL,
3240 'class' => $values['class'] ??
NULL,
3241 'key' => $values['key'],
3245 foreach ($values as $value) {
3246 // user does not have necessary permissions.
3247 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3251 // finally get menu item for -more- action widget.
3252 while (!empty($contextMenu['otherActions'][$value['weight']])) {
3253 // Quick & dirty way of handling 2 items with the same weight
3254 // without clobbering one.
3257 $contextMenu['otherActions'][$value['weight']] = [
3258 'title' => $value['title'],
3259 'ref' => $value['ref'],
3260 'href' => $value['href'] ??
NULL,
3261 'tab' => $value['tab'] ??
NULL,
3262 'class' => $value['class'] ??
NULL,
3263 'icon' => $value['icon'] ??
NULL,
3264 'key' => $value['key'],
3270 ksort($contextMenu['moreActions']);
3271 ksort($contextMenu['otherActions']);
3273 return $contextMenu;
3277 * Check if user has permissions to access items in action menu.
3279 * @param array $aclPermissionedTasks
3280 * Array containing ACL related tasks.
3281 * @param string $corePermission
3282 * The permission of the user (edit or view or null).
3283 * @param array $menuOptions
3284 * Array containing params of the menu (title, href, etc).
3287 * TRUE if user has all permissions, FALSE if otherwise.
3289 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3290 $componentName = $menuOptions['component'] ??
NULL;
3292 // if component action - make sure component is enable.
3293 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3297 // make sure user has all required permissions.
3298 $hasAllPermissions = FALSE;
3300 $permissions = $menuOptions['permissions'] ??
NULL;
3301 if (!is_array($permissions) ||
empty($permissions)) {
3302 $hasAllPermissions = TRUE;
3305 // iterate for required permissions in given permissions array.
3306 if (!$hasAllPermissions) {
3307 $hasPermissions = 0;
3308 foreach ($permissions as $permission) {
3309 if (CRM_Core_Permission
::check($permission)) {
3314 if (count($permissions) == $hasPermissions) {
3315 $hasAllPermissions = TRUE;
3318 // if still user does not have required permissions, check acl.
3319 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3320 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3321 $corePermission == CRM_Core_Permission
::EDIT
3323 $hasAllPermissions = TRUE;
3325 elseif (in_array($menuOptions['ref'], [
3328 // grant permissions for these tasks.
3329 $hasAllPermissions = TRUE;
3334 return $hasAllPermissions;
3338 * Retrieve display name of contact that address is shared.
3340 * This is based on $masterAddressId or $contactId .
3342 * @param int $masterAddressId
3344 * @param int $contactId
3345 * Contact id. (deprecated - do not use)
3347 * @return string|null
3348 * the found display name or null.
3350 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3351 $masterDisplayName = NULL;
3352 if (!$masterAddressId) {
3353 return $masterDisplayName;
3357 SELECT display_name from civicrm_contact
3358 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3359 WHERE civicrm_address.id = " . $masterAddressId;
3361 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3362 return $masterDisplayName;
3366 * Get the creation/modification times for a contact.
3368 * @param int $contactId
3371 * Dates - ('created_date' => $, 'modified_date' => $)
3373 public static function getTimestamps($contactId) {
3374 $timestamps = CRM_Core_DAO
::executeQuery(
3375 'SELECT created_date, modified_date
3376 FROM civicrm_contact
3379 1 => [$contactId, 'Integer'],
3382 if ($timestamps->fetch()) {
3384 'created_date' => $timestamps->created_date
,
3385 'modified_date' => $timestamps->modified_date
,
3394 * Get a list of triggers for the contact table.
3397 * @param null $tableName
3399 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3401 * @see hook_civicrm_triggerInfo
3402 * @see CRM_Core_DAO::triggerRebuild
3404 public static function triggerInfo(&$info, $tableName = NULL) {
3406 // Modifications to these records should update the contact timestamps.
3407 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3409 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3410 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3411 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3412 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3413 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3415 ->alterTriggerInfo($info, $tableName);
3417 // Update phone table to populate phone_numeric field
3418 if (!$tableName ||
$tableName == 'civicrm_phone') {
3419 // Define stored sql function needed for phones
3420 $sqlTriggers = Civi
::service('sql_triggers');
3421 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3422 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3424 'table' => ['civicrm_phone'],
3426 'event' => ['INSERT', 'UPDATE'],
3427 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3433 * Check if contact is being used in civicrm_domain based on $contactId.
3435 * @param int $contactId
3439 * true if present else false.
3441 public static function checkDomainContact($contactId) {
3445 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3456 * Get options for a given contact field.
3458 * @param string $fieldName
3459 * @param string $context
3460 * @param array $props
3461 * whatever is known about this dao object.
3463 * @return array|bool
3464 * @see CRM_Core_DAO::buildOptions
3466 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3467 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3469 * @see CRM_Core_DAO::buildOptionsContext
3471 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3473 // Special logic for fields whose options depend on context or properties
3474 switch ($fieldName) {
3475 case 'contact_sub_type':
3476 if (!empty($props['contact_type'])) {
3477 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3481 case 'contact_type':
3482 if ($context == 'search') {
3483 // CRM-15495 - EntityRef filters and basic search forms expect this format
3484 // FIXME: Search builder does not
3485 return CRM_Contact_BAO_ContactType
::getSelectElements();
3489 // The contact api supports some related entities so we'll honor that by fetching their options
3492 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3496 $props['entity_table'] = 'civicrm_contact';
3497 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3499 case 'state_province_id':
3500 case 'state_province':
3501 case 'state_province_name':
3506 case 'worldregion_id':
3507 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3510 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3514 * Delete a contact-related object that has an 'is_primary' field.
3516 * Ensures that is_primary gets assigned to another object if available
3517 * Also calls pre/post hooks
3519 * @param string $type
3524 public static function deleteObjectWithPrimary($type, $id) {
3525 if (!$id ||
!is_numeric($id)) {
3528 $daoName = "CRM_Core_DAO_$type";
3529 $obj = new $daoName();
3533 if ($obj->fetch()) {
3534 CRM_Utils_Hook
::pre('delete', $type, $id);
3535 $contactId = $obj->contact_id
;
3541 // is_primary is only relavent if this field belongs to a contact
3543 $dao = new $daoName();
3544 $dao->contact_id
= $contactId;
3545 $dao->is_primary
= 1;
3546 // Pick another record to be primary (if one isn't already)
3547 if (!$dao->find(TRUE)) {
3548 $dao->is_primary
= 0;
3550 if ($dao->fetch()) {
3551 $dao->is_primary
= 1;
3553 if ($type === 'Email') {
3554 CRM_Core_BAO_UFMatch
::updateUFName($dao->contact_id
);
3559 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3566 public function addSelectWhereClause() {
3567 // We always return an array with these keys, even if they are empty,
3568 // because this tells the query builder that we have considered these fields for acls
3570 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3571 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
[] : ['!= 1'],
3573 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3578 * Get any existing duplicate contacts based on the input parameters.
3580 * @param array $input
3581 * Input parameters to be matched.
3582 * @param string $contactType
3583 * @param string $rule
3586 * @param $excludedContactIDs
3587 * An array of ids not to be included in the results.
3588 * @param bool $checkPermissions
3589 * @param int $ruleGroupID
3590 * ID of the rule group to be used if an override is desirable.
3591 * @param array $contextParams
3592 * The context if relevant, eg. ['event_id' => X]
3596 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3597 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3598 $dedupeParams['check_permission'] = $checkPermissions;
3599 $dedupeParams['contact_type'] = $contactType;
3600 $dedupeParams['rule'] = $rule;
3601 $dedupeParams['rule_group_id'] = $ruleGroupID;
3602 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3603 $dedupeResults['ids'] = [];
3604 $dedupeResults['handled'] = FALSE;
3605 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3606 if (!$dedupeResults['handled']) {
3607 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3609 return $dedupeResults['ids'];
3613 * Get the first duplicate contacts based on the input parameters.
3615 * @param array $input
3616 * Input parameters to be matched.
3617 * @param string $contactType
3618 * @param string $rule
3621 * @param $excludedContactIDs
3622 * An array of ids not to be included in the results.
3623 * @param bool $checkPermissions
3624 * @param int $ruleGroupID
3625 * ID of the rule group to be used if an override is desirable.
3626 * @param array $contextParams
3627 * The context if relevant, eg. ['event_id' => X]
3631 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3632 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3640 * Check if a field is associated with an entity that has a location type.
3642 * (ie. is an address, phone, email etc field).
3644 * @param string $fieldTitle
3645 * Title of the field (not the name - create a new function for that if required).
3649 public static function isFieldHasLocationType($fieldTitle) {
3650 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3651 if ($field['title'] === $fieldTitle) {
3652 return $field['hasLocationType'] ??
NULL;
3659 * @param array $appendProfiles
3660 * Name of profile(s) to append to each link.
3664 public static function getEntityRefCreateLinks($appendProfiles = []) {
3665 // You'd think that "create contacts" would be the permission to check,
3666 // But new contact popups are profile forms and those use their own permissions.
3667 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3671 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3672 $profiles[] = 'new_' . strtolower($contactType);
3674 $retrieved = civicrm_api3('uf_group', 'get', [
3675 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3678 $links = $append = [];
3679 if (!empty($retrieved['values'])) {
3681 'individual' => 'fa-user',
3682 'organization' => 'fa-building',
3683 'household' => 'fa-home',
3685 foreach ($retrieved['values'] as $id => $profile) {
3686 if (in_array($profile['name'], $profiles)) {
3688 'label' => $profile['title'],
3689 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3690 NULL, NULL, FALSE, FALSE, TRUE),
3691 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3692 'icon' => $icons[str_replace('new_', '', $profile['name'])] ??
NULL,
3699 foreach ($append as $id) {
3700 foreach ($links as &$link) {
3701 $link['url'] .= ",$id";
3711 public static function getEntityRefFilters() {
3713 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3714 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3715 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3716 ['key' => 'city', 'value' => ts('City'), 'type' => 'text', 'entity' => 'Address'],
3717 ['key' => 'postal_code', 'value' => ts('Postal Code'), 'type' => 'text', 'entity' => 'Address'],
3718 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3719 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3720 ['key' => 'first_name', 'value' => ts('First Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3721 ['key' => 'last_name', 'value' => ts('Last Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3722 ['key' => 'nick_name', 'value' => ts('Nick Name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3723 ['key' => 'organization_name', 'value' => ts('Employer name'), 'type' => 'text', 'condition' => ['contact_type' => 'Individual']],
3724 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3725 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3726 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3727 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],
3732 * @param string $action
3733 * @param array $record
3736 * @see CRM_Core_DAO::checkAccess
3738 public static function _checkAccess(string $action, array $record, $userID): bool {
3741 return CRM_Core_Permission
::check('add contacts', $userID);
3744 $actionType = CRM_Core_Permission
::VIEW
;
3748 $actionType = CRM_Core_Permission
::DELETE
;
3752 $actionType = CRM_Core_Permission
::EDIT
;
3756 return CRM_Contact_BAO_Contact_Permission
::allow($record['id'], $actionType, $userID);