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) CHARACTER SET utf8)
31 RETURNS VARCHAR(255) CHARACTER SET utf8
35 DECLARE output VARCHAR(255) CHARACTER SET utf8 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)
106 public static function add(&$params) {
107 $contact = new CRM_Contact_DAO_Contact();
108 $contactID = CRM_Utils_Array
::value('contact_id', $params);
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' => CRM_Utils_Array
::value('contact_source', $params)];
138 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
139 $defaults['display_name'] = $params['organization_name'];
140 $defaults['sort_name'] = $params['organization_name'];
142 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
143 $defaults['display_name'] = $params['household_name'];
144 $defaults['sort_name'] = $params['household_name'];
146 $params = array_merge($defaults, $params);
148 $allNull = $contact->copyValues($params);
150 $contact->id
= $contactID;
152 if ($contact->contact_type
=== 'Individual') {
154 // @todo allow the lines below to be overridden by input or hooks & add tests,
155 // as has been done for households and organizations.
156 // Format individual fields.
157 CRM_Contact_BAO_Individual
::format($params, $contact);
160 if (strlen($contact->display_name
) > 128) {
161 $contact->display_name
= substr($contact->display_name
, 0, 128);
163 if (strlen($contact->sort_name
) > 128) {
164 $contact->sort_name
= substr($contact->sort_name
, 0, 128);
167 $privacy = CRM_Utils_Array
::value('privacy', $params);
169 is_array($privacy) &&
173 foreach (self
::$_commPrefs as $name) {
174 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
178 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
179 // @todo - does this mean we can remove this block?
180 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
181 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
183 $contact->hash
= md5(uniqid(rand(), TRUE));
186 // Even if we don't need $employerId, it's important to call getFieldValue() before
187 // the contact is saved because we want the existing value to be cached.
188 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
189 $employerId = (!$contactID ||
$contact->contact_type
!== 'Individual') ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
194 CRM_Core_BAO_Log
::register($contact->id
,
200 if ($contact->contact_type
=== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
201 // Create current employer.
202 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
205 if (empty($params['contact_id'])) {
209 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
213 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
218 // Update cached employer name if the name of an existing organization is being updated.
219 if ($contact->contact_type
=== 'Organization' && !empty($params['organization_name']) && $contactID) {
220 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
229 * takes an associative array and creates a contact object and all the associated
230 * derived objects (i.e. individual, location, email, phone etc)
232 * This function is invoked from within the web form layer and also from the api layer
234 * @param array $params
235 * (reference ) an assoc array of name/value pairs.
236 * @param bool $fixAddress
237 * If we need to fix address.
238 * @param bool $invokeHooks
239 * If we need to invoke hooks.
241 * @param bool $skipDelete
242 * Unclear parameter, passed to website create
244 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
245 * Created or updated contribution object. We are deprecating returning an error in
246 * favour of exceptions
248 * @todo explain this parameter
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 (array_key_exists('group', $params)) {
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 // update the UF user_unique_id if that has changed
382 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
384 if (!empty($params['custom']) &&
385 is_array($params['custom'])
387 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
390 $transaction->commit();
392 // CRM-6367: fetch the right label for contact type’s display
393 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
394 'CRM_Contact_DAO_ContactType',
395 $contact->contact_type
,
400 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
404 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
407 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
411 // In order to prevent a series of expensive queries in intensive batch processing
412 // api calls may pass in skip_greeting_processing, probably doing it later via the
413 // scheduled job. CRM-21551
414 if (empty($params['skip_greeting_processing'])) {
415 self
::processGreetings($contact);
418 if (!empty($params['check_permissions'])) {
419 $contacts = [&$contact];
420 self
::unsetProtectedFields($contacts);
423 // Edit Membership Status
425 'contact_id' => CRM_Utils_Array
::value('contact_id', $params),
426 'is_deceased' => CRM_Utils_Array
::value('is_deceased', $params, FALSE),
427 'deceased_date' => CRM_Utils_Array
::value('deceased_date', $params, NULL),
429 CRM_Member_BAO_Membership
::updateMembershipStatus($deceasedParams, $params['contact_type']);
435 * Format the output of the create contact function
437 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
439 public static function unsetProtectedFields(&$contacts) {
440 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
441 $currentUser = CRM_Core_Session
::getLoggedInContactID();
442 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
443 foreach ($contacts as &$contact) {
444 $cid = is_object($contact) ?
$contact->id
: CRM_Utils_Array
::value('id', $contact);
445 if (!($editOwn && $cid == $currentUser)) {
446 if (is_object($contact)) {
447 unset($contact->api_key
);
450 unset($contact['api_key']);
458 * Ensure greeting parameters are set.
460 * By always populating greetings here we can be sure they are set if required & avoid a call later.
461 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
463 * @param array $params
465 * @throws \CiviCRM_API3_Exception
467 public static function ensureGreetingParamsAreSet(&$params) {
468 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
469 $missingGreetingParams = [];
471 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
472 if (empty($params[$greetingParam])) {
473 $missingGreetingParams[$greetingIndex] = $greetingParam;
477 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
478 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
479 'id' => $params['contact_id'],
480 'return' => array_keys($missingGreetingParams),
483 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
484 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
485 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
488 // Filter out other fields.
489 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
490 $params = array_merge($params, $savedGreetings);
493 foreach ($missingGreetingParams as $greetingName => $greeting) {
494 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
498 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
499 if ($params[$greetingParam] === 'null') {
500 // If we are setting it to null then null out the display field.
501 $params[$greetingIndex . '_display'] = 'null';
507 * Get the display name and image of a contact.
512 * @param bool $includeTypeInReturnParameters
513 * Should type be part of the returned array?
516 * the displayName and contactImage for this contact
518 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
519 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
521 SELECT civicrm_contact.*,
522 civicrm_email.email as email
524 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
525 AND civicrm_email.is_primary = 1
526 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
527 $dao = new CRM_Core_DAO();
530 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
531 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
533 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
534 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
537 // use email if display_name is empty
538 if (empty($dao->display_name
)) {
539 $displayName = $dao->email
;
542 $displayName = $dao->display_name
;
545 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
547 return $includeTypeInReturnParameters ?
[
551 $dao->contact_sub_type
,
553 ] : [$displayName, $image, $imageUrl];
559 * Add billing fields to the params if appropriate.
561 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
562 * don't then we should set the name fields to the billing fields AND add the preserveDBName
563 * parameter (which will tell the BAO only to set those fields if none already exist.
565 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
566 * matching is best done by hipsters.
568 * @param array $params
570 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
572 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
573 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
574 foreach ($nameFields as $field) {
575 if (!empty($params[$field])) {
579 // There are only 3 - we can iterate through them twice :-)
580 foreach ($nameFields as $field) {
581 if (!empty($params['billing_' . $field])) {
582 $params[$field] = $params['billing_' . $field];
584 $params['preserveDBName'] = TRUE;
590 * Resolve a state province string (UT or Utah) to an ID.
592 * If country has been passed in we should select a state belonging to that country.
594 * Alternatively we should choose from enabled countries, prioritising the default country.
596 * @param array $values
597 * @param int|null $countryID
601 * @throws \CRM_Core_Exception
603 protected static function resolveStateProvinceID($values, $countryID) {
606 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
607 if (CRM_Utils_Array
::lookupValue($values,
612 return $values['state_province_id'];
614 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
615 if (CRM_Utils_Array
::lookupValue($values,
620 return $values['state_province_id'];
625 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
626 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
627 // prefer matching country..
628 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, ['country_id' => Civi
::settings()->get('defaultContactCountry')]);
629 if (CRM_Utils_Array
::lookupValue($values,
634 return $values['state_province_id'];
637 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
638 if (CRM_Utils_Array
::lookupValue($values,
643 return $values['state_province_id'];
646 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
647 if (CRM_Utils_Array
::lookupValue($values,
652 return $values['state_province_id'];
654 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
655 if (CRM_Utils_Array
::lookupValue($values,
660 return $values['state_province_id'];
668 * Get the relevant location entity for the array key.
670 * Based on the field name we determine which location entity
671 * we are dealing with. Apart from a few specific ones they
672 * are mostly 'address' (the default).
674 * @param string $fieldName
678 protected static function getLocationEntityForKey($fieldName) {
679 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
682 if ($fieldName === 'phone_ext') {
689 * Create last viewed link to recently updated contact.
691 * @param array $crudLinkSpec
692 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
693 * - entity_table: string, eg "civicrm_contact"
697 * NULL if unavailable, or
698 * [path: string, query: string, title: string]
699 * @see CRM_Utils_System::createDefaultCrudLink
701 public function createDefaultCrudLink($crudLinkSpec) {
702 switch ($crudLinkSpec['action']) {
703 case CRM_Core_Action
::VIEW
:
705 'title' => $this->display_name
,
706 'path' => 'civicrm/contact/view',
714 case CRM_Core_Action
::UPDATE
:
716 'title' => $this->display_name
,
717 'path' => 'civicrm/contact/add',
720 'action' => 'update',
730 * Get the values for pseudoconstants for name->value and reverse.
732 * @param array $defaults
733 * (reference) the default values, some of which need to be resolved.
734 * @param bool $reverse
735 * Always true as this function is only called from one place..
739 * This is called specifically from the contact import parser & should be moved there
740 * as it is not truly a generic function.
743 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
744 // Hack for birth_date.
745 if (!empty($defaults['birth_date'])) {
746 if (is_array($defaults['birth_date'])) {
747 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
751 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
752 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
753 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
754 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
756 //lookup value of email/postal greeting, addressee, CRM-4575
757 foreach (self
::$_greetingTypes as $greeting) {
759 'contact_type' => $defaults['contact_type'] ??
NULL,
760 'greeting_type' => $greeting,
762 CRM_Utils_Array
::lookupValue($defaults, $greeting,
763 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
767 $blocks = ['address', 'im', 'phone'];
768 foreach ($blocks as $name) {
769 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
772 foreach ($defaults[$name] as $count => & $values) {
774 //get location type id.
775 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
777 if ($name == 'address') {
778 // FIXME: lookupValue doesn't work for vcard_name
779 if (!empty($values['location_type_id'])) {
780 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', ['labelColumn' => 'vcard_name']);
781 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
784 if (!CRM_Utils_Array
::lookupValue($values,
786 CRM_Core_PseudoConstant
::country(),
791 CRM_Utils_Array
::lookupValue($values,
793 CRM_Core_PseudoConstant
::countryIsoCode(),
797 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
798 if ($stateProvinceID) {
799 $values['state_province_id'] = $stateProvinceID;
802 if (!empty($values['state_province_id'])) {
803 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
806 $countyList = CRM_Core_PseudoConstant
::county();
808 CRM_Utils_Array
::lookupValue($values,
816 CRM_Utils_Array
::lookupValue($values,
818 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
823 if ($name == 'phone') {
824 CRM_Utils_Array
::lookupValue($values,
826 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
831 // Kill the reference.
838 * Fetch object based on array of properties.
840 * @param array $params
841 * (reference ) an assoc array of name/value pairs.
842 * @param array $defaults
843 * (reference ) an assoc array to hold the name / value pairs.
844 * in a hierarchical manner
845 * @param bool $microformat
846 * For location in microformat.
848 * @return CRM_Contact_BAO_Contact
850 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
851 if (array_key_exists('contact_id', $params)) {
852 $params['id'] = $params['contact_id'];
854 elseif (array_key_exists('id', $params)) {
855 $params['contact_id'] = $params['id'];
858 $contact = self
::getValues($params, $defaults);
860 unset($params['id']);
862 //get the block information for this contact
863 $entityBlock = ['contact_id' => $params['contact_id']];
864 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
865 $defaults = array_merge($defaults, $blocks);
866 foreach ($blocks as $block => $value) {
867 $contact->$block = $value;
870 if (!isset($params['noNotes'])) {
871 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
874 if (!isset($params['noRelationships'])) {
875 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
878 if (!isset($params['noGroups'])) {
879 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
882 if (!isset($params['noWebsite'])) {
883 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
890 * Get the display name of a contact.
895 * @return null|string
896 * display name of the contact if found
898 public static function displayName($id) {
901 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
908 * Delete a contact and all its associated records.
911 * Id of the contact to delete.
912 * @param bool $restore
913 * Whether to actually restore, not delete.
914 * @param bool $skipUndelete
915 * Whether to force contact delete or not.
916 * @param bool $checkPermissions
919 * Was contact deleted?
921 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
926 // If trash is disabled in system settings then we always skip
927 if (!Civi
::settings()->get('contact_undelete')) {
928 $skipUndelete = TRUE;
931 // make sure we have edit permission for this contact
933 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
934 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
940 // Restrict contact to be delete if contact has financial trxns
942 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent([$id], $error)) {
946 // make sure this contact_id does not have any membership types
947 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
950 'member_of_contact_id'
952 if ($membershipTypeID) {
956 $contact = new CRM_Contact_DAO_Contact();
958 if (!$contact->find(TRUE)) {
962 $contactType = $contact->contact_type
;
964 return self
::contactTrashRestore($contact, TRUE);
967 // start a new transaction
968 $transaction = new CRM_Core_Transaction();
971 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
973 //delete billing address if exists.
974 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
976 // delete the log entries since we dont have triggers enabled as yet
977 $logDAO = new CRM_Core_DAO_Log();
978 $logDAO->entity_table
= 'civicrm_contact';
979 $logDAO->entity_id
= $id;
982 // delete contact participants CRM-12155
983 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
985 // delete contact contributions CRM-12155
986 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
988 // do activity cleanup, CRM-5604
989 CRM_Activity_BAO_Activity
::cleanupActivity($id);
991 // delete all notes related to contact
992 CRM_Core_BAO_Note
::cleanContactNotes($id);
994 // delete cases related to contact
995 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
996 if (!empty($contactCases)) {
997 foreach ($contactCases as $caseId) {
998 //check if case is associate with other contact or not.
999 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
1000 if (count($caseContactId) <= 1) {
1001 CRM_Case_BAO_Case
::deleteCase($caseId);
1009 self
::contactTrashRestore($contact);
1011 // currently we only clear employer cache.
1012 // we are now deleting inherited membership if any.
1013 if ($contact->contact_type
== 'Organization') {
1014 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
1015 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
1016 if (!empty($relationshipDtls)) {
1017 foreach ($relationshipDtls as $rId => $details) {
1018 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
1021 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
1024 //delete the contact id from recently view
1025 CRM_Utils_Recent
::delContact($id);
1026 self
::updateContactCache($id, empty($restore));
1028 // delete any prevnext/dupe cache entry
1029 // These two calls are redundant in default deployments, but they're
1030 // meaningful if "prevnext" is memory-backed.
1031 Civi
::service('prevnext')->deleteItem($id);
1032 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1034 $transaction->commit();
1036 if ($skipUndelete) {
1037 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1044 * Action to update any caches relating to a recently update contact.
1046 * I was going to call this from delete as well as from create to ensure the delete is being
1047 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1048 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1049 * where the call involved a subquery that was locking the table.
1051 * @param int $contactID
1052 * @param bool $isTrashed
1054 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1057 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1058 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1059 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1060 // but this should not cause any change as long as contacts are not being trashed outside the
1061 // main functions for that.
1062 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1065 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1070 * Delete the image of a contact.
1073 * Id of the contact.
1076 * Was contact image deleted?
1078 public static function deleteContactImage($id) {
1083 $contact = new self();
1085 $contact->image_URL
= 'null';
1092 * Return proportional height and width of the image.
1094 * @param int $imageWidth
1097 * @param int $imageHeight
1101 * Thumb dimension of image
1103 public static function getThumbSize($imageWidth, $imageHeight) {
1105 if ($imageWidth && $imageHeight) {
1106 $imageRatio = $imageWidth / $imageHeight;
1111 if ($imageRatio > 1) {
1112 $imageThumbWidth = $thumbWidth;
1113 $imageThumbHeight = round($thumbWidth / $imageRatio);
1116 $imageThumbHeight = $thumbWidth;
1117 $imageThumbWidth = round($thumbWidth * $imageRatio);
1120 return [$imageThumbWidth, $imageThumbHeight];
1124 * Validate type of contact image.
1126 * @param array $params
1127 * @param string $imageIndex
1128 * Index of image field.
1129 * @param string $statusMsg
1130 * Status message to be set after operation.
1131 * @param string $opType
1132 * Type of operation like fatal, bounce etc.
1135 * true if valid image extension
1137 public static function processImageParams(
1139 $imageIndex = 'image_URL',
1153 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1154 $photo = basename($params[$imageIndex]['name']);
1155 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1159 unset($params[$imageIndex]);
1161 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1163 if ($opType == 'status') {
1164 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1166 // FIXME: additional support for fatal, bounce etc could be added.
1172 * Extract contact id from url for deleting contact image.
1174 public static function processImage() {
1176 $action = CRM_Utils_Request
::retrieve('action', 'String');
1177 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1178 // retrieve contact id in case of Profile context
1179 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1180 $cid = $cid ?
$cid : $id;
1181 if ($action & CRM_Core_Action
::DELETE
) {
1182 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1183 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1184 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1185 $session = CRM_Core_Session
::singleton();
1186 $toUrl = $session->popUserContext();
1187 CRM_Utils_System
::redirect($toUrl);
1193 * Function to set is_delete true or restore deleted contact.
1195 * @param CRM_Contact_DAO_Contact $contact
1196 * Contact DAO object.
1197 * @param bool $restore
1198 * True to set the is_delete = 1 else false to restore deleted contact,
1199 * i.e. is_delete = 0
1203 public static function contactTrashRestore($contact, $restore = FALSE) {
1205 'id' => $contact->id
,
1206 'is_deleted' => $restore ?
0 : 1,
1209 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1211 $params = [1 => [$contact->id
, 'Integer']];
1213 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1214 CRM_Core_DAO
::executeQuery($query, $params);
1217 $contact->copyValues($updateParams);
1219 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
1221 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1227 * Get contact type for a contact.
1230 * Id of the contact whose contact type is needed.
1233 * contact_type if $id found else null ""
1235 public static function getContactType($id) {
1236 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1240 * Get contact sub type for a contact.
1243 * Id of the contact whose contact sub type is needed.
1245 * @param string $implodeDelimiter
1248 * contact_sub_type if $id found else null ""
1250 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1251 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1253 return $implodeDelimiter ?
NULL : [];
1256 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1258 if ($implodeDelimiter) {
1259 $subtype = implode($implodeDelimiter, $subtype);
1265 * Get pair of contact-type and sub-type for a contact.
1268 * Id of the contact whose contact sub/contact type is needed.
1272 public static function getContactTypes($id) {
1273 $params = ['id' => $id];
1275 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1278 ['contact_type', 'contact_sub_type']
1283 if ($contact->contact_sub_type
) {
1284 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1286 array_unshift($contactTypes, $contact->contact_type
);
1288 return $contactTypes;
1291 CRM_Core_Error
::fatal();
1296 * Combine all the importable fields from the lower levels object.
1298 * The ordering is important, since currently we do not have a weight
1299 * scheme. Adding weight is super important
1301 * @param int|string $contactType contact Type
1302 * @param bool $status
1303 * Status is used to manipulate first title.
1304 * @param bool $showAll
1305 * If true returns all fields (includes disabled fields).
1306 * @param bool $isProfile
1307 * If its profile mode.
1308 * @param bool $checkPermission
1309 * If false, do not include permissioning clause (for custom data).
1311 * @param bool $withMultiCustomFields
1314 * array of importable Fields
1316 public static function importableFields(
1317 $contactType = 'Individual',
1321 $checkPermission = TRUE,
1322 $withMultiCustomFields = FALSE
1324 if (empty($contactType)) {
1325 $contactType = 'All';
1328 $cacheKeyString = "importableFields $contactType";
1329 $cacheKeyString .= $status ?
'_1' : '_0';
1330 $cacheKeyString .= $showAll ?
'_1' : '_0';
1331 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1332 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1333 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1335 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields) ?
: Civi
::cache('fields')->get($cacheKeyString);
1338 $fields = CRM_Contact_DAO_Contact
::import();
1340 // get the fields thar are meant for contact types
1341 if (in_array($contactType, [
1347 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1350 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1351 CRM_Core_DAO_Phone
::import(),
1352 CRM_Core_DAO_Email
::import(),
1353 CRM_Core_DAO_IM
::import(TRUE),
1354 CRM_Core_DAO_OpenID
::import()
1357 $locationFields = array_merge($locationFields,
1358 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1366 foreach ($locationFields as $key => $field) {
1367 $locationFields[$key]['hasLocationType'] = TRUE;
1370 $fields = array_merge($fields, $locationFields);
1372 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1373 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1376 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1377 $fields['url']['hasWebsiteType'] = TRUE;
1379 if ($contactType != 'All') {
1380 $fields = array_merge($fields,
1381 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1386 $withMultiCustomFields
1389 // Unset the fields which are not related to their contact type.
1390 foreach (CRM_Contact_DAO_Contact
::import() as $name => $value) {
1391 if (!empty($value['contactType']) && $value['contactType'] !== $contactType) {
1392 unset($fields[$name]);
1397 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1398 $fields = array_merge($fields,
1399 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1404 $withMultiCustomFields
1411 $fields = array_merge($fields, [
1413 'title' => ts('Group(s)'),
1417 'title' => ts('Tag(s)'),
1421 'title' => ts('Note'),
1424 'communication_style_id' => [
1425 'title' => ts('Communication Style'),
1426 'name' => 'communication_style_id',
1431 //Sorting fields in alphabetical order(CRM-1507)
1432 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1434 Civi
::cache('fields')->set($cacheKeyString, $fields);
1437 self
::$_importableFields[$cacheKeyString] = $fields;
1441 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1442 self
::$_importableFields[$cacheKeyString]
1446 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1447 self
::$_importableFields[$cacheKeyString]
1455 * Combine all the exportable fields from the lower levels object.
1457 * Currently we are using importable fields as exportable fields
1459 * @param int|string $contactType contact Type
1460 * @param bool $status
1461 * True while exporting primary contacts.
1462 * @param bool $export
1463 * True when used during export.
1464 * @param bool $search
1465 * True when used during search, might conflict with export param?.
1467 * @param bool $withMultiRecord
1468 * @param bool $checkPermissions
1471 * array of exportable Fields
1473 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1474 if (empty($contactType)) {
1475 $contactType = 'All';
1478 $cacheKeyString = "exportableFields $contactType";
1479 $cacheKeyString .= $export ?
'_1' : '_0';
1480 $cacheKeyString .= $status ?
'_1' : '_0';
1481 $cacheKeyString .= $search ?
'_1' : '_0';
1482 $cacheKeyString .= '_' . (bool) $checkPermissions;
1483 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1484 //calculates custom fields takes into account the logged in user & caches that for all users
1485 //as an interim fix we will cache the fields by contact
1486 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1488 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1489 if (!self
::$_exportableFields) {
1490 self
::$_exportableFields = [];
1493 // check if we can retrieve from database cache
1494 $fields = Civi
::cache('fields')->get($cacheKeyString);
1497 $fields = CRM_Contact_DAO_Contact
::export();
1499 // The fields are meant for contact types.
1500 if (in_array($contactType, [
1506 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1508 // add current employer for individuals
1509 $fields = array_merge($fields, [
1510 'current_employer' =>
1512 'name' => 'organization_name',
1513 'title' => ts('Current Employer'),
1518 'location_type' => [
1519 'name' => 'location_type',
1520 'where' => 'civicrm_location_type.name',
1521 'title' => ts('Location Type'),
1527 'name' => 'im_provider',
1528 'where' => 'civicrm_im.provider_id',
1529 'title' => ts('IM Provider'),
1533 $locationFields = array_merge($locationType,
1534 CRM_Core_DAO_Address
::export(),
1535 CRM_Core_DAO_Phone
::export(),
1536 CRM_Core_DAO_Email
::export(),
1538 CRM_Core_DAO_IM
::export(TRUE),
1539 CRM_Core_DAO_OpenID
::export()
1542 $locationFields = array_merge($locationFields,
1543 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1546 foreach ($locationFields as $key => $field) {
1547 $locationFields[$key]['hasLocationType'] = TRUE;
1550 $fields = array_merge($fields, $locationFields);
1553 $fields = array_merge($fields,
1554 CRM_Core_DAO_Worldregion
::export()
1557 $fields = array_merge($fields,
1558 CRM_Contact_DAO_Contact
::export()
1562 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1564 if ($contactType != 'All') {
1565 $fields = array_merge($fields,
1566 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1570 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1571 $fields = array_merge($fields,
1572 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1576 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1579 $fields = array_merge($fields, [
1581 'title' => ts('Group(s)'),
1585 'title' => ts('Tag(s)'),
1589 'title' => ts('Note(s)'),
1595 $fields = array_merge($fields, [
1597 'title' => ts('Group(s)'),
1601 'title' => ts('Tag(s)'),
1605 'title' => ts('Note(s)'),
1611 //Sorting fields in alphabetical order(CRM-1507)
1612 foreach ($fields as $k => $v) {
1613 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1616 $fields = array_merge($sortArray, $fields);
1617 //unset the field which are not related to their contact type.
1618 if ($contactType != 'All') {
1624 'organization_name',
1625 'email_greeting_custom',
1626 'postal_greeting_custom',
1639 'organization_name',
1647 'email_greeting_custom',
1648 'postal_greeting_custom',
1664 'email_greeting_custom',
1665 'postal_greeting_custom',
1675 foreach ($commonValues[$contactType] as $value) {
1676 unset($fields[$value]);
1680 Civi
::cache('fields')->set($cacheKeyString, $fields);
1682 self
::$_exportableFields[$cacheKeyString] = $fields;
1686 $fields = self
::$_exportableFields[$cacheKeyString];
1689 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1690 self
::$_exportableFields[$cacheKeyString]
1698 * Get the all contact details (Hierarchical).
1700 * @param int $contactId
1702 * @param array $fields
1708 public static function getHierContactDetails($contactId, $fields) {
1709 $params = [['contact_id', '=', $contactId, 0, 0]];
1711 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1713 // We don't know the contents of return properties, but we need the lower
1714 // level ids of the contact so add a few fields.
1715 $returnProperties['first_name'] = 1;
1716 $returnProperties['organization_name'] = 1;
1717 $returnProperties['household_name'] = 1;
1718 $returnProperties['contact_type'] = 1;
1719 $returnProperties['contact_sub_type'] = 1;
1720 list($query) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties);
1725 * Given a set of flat profile style field names, create a hierarchy.
1727 * This is for the query to use, create the right sql.
1730 * @param int $contactId
1734 * A hierarchical property tree if appropriate
1736 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1737 $locationTypes = CRM_Core_BAO_Address
::buildOptions('location_type_id', 'validate');
1739 $returnProperties = [];
1741 $multipleFields = ['website' => 'url'];
1742 foreach ($fields as $name => $dontCare) {
1743 if (strpos($name, '-') !== FALSE) {
1744 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1746 if (!in_array($fieldName, $multipleFields)) {
1747 if ($id == 'Primary') {
1748 $locationTypeName = 1;
1751 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1752 if (!$locationTypeName) {
1757 if (empty($returnProperties['location'])) {
1758 $returnProperties['location'] = [];
1760 if (empty($returnProperties['location'][$locationTypeName])) {
1761 $returnProperties['location'][$locationTypeName] = [];
1762 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1764 if (in_array($fieldName, [
1772 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1775 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1778 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1779 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1782 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1786 $returnProperties['website'][$id][$fieldName] = 1;
1790 $returnProperties[$name] = 1;
1794 return $returnProperties;
1798 * Return the primary location type of a contact.
1800 * $params int $contactId contact_id
1801 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1802 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1804 * @param int $contactId
1805 * @param bool $skipDefaultPriamry
1806 * @param null $block
1809 * $locationType location_type_id
1811 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1813 $entityBlock = ['contact_id' => $contactId];
1814 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1815 foreach ($blocks[$block] as $key => $value) {
1816 if (!empty($value['is_primary'])) {
1817 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1824 IF ( civicrm_email.location_type_id IS NULL,
1825 IF ( civicrm_address.location_type_id IS NULL,
1826 IF ( civicrm_phone.location_type_id IS NULL,
1827 IF ( civicrm_im.location_type_id IS NULL,
1828 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1829 ,civicrm_im.location_type_id)
1830 ,civicrm_phone.location_type_id)
1831 ,civicrm_address.location_type_id)
1832 ,civicrm_email.location_type_id) as locationType
1833 FROM civicrm_contact
1834 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1835 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1836 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1837 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1838 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1839 WHERE civicrm_contact.id = %1 ";
1841 $params = [1 => [$contactId, 'Integer']];
1843 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1845 $locationType = NULL;
1846 if ($dao->fetch()) {
1847 $locationType = $dao->locationType
;
1850 if (isset($locationType)) {
1851 return $locationType;
1853 elseif ($skipDefaultPriamry) {
1854 // if there is no primary contact location then return null
1858 // if there is no primart contact location, then return default
1859 // location type of the system
1860 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1861 return $defaultLocationType->id
;
1866 * Get the display name, primary email and location type of a contact.
1869 * Id of the contact.
1872 * Array of display_name, email if found, do_not_email or (null,null,null)
1874 public static function getContactDetails($id) {
1875 // check if the contact type
1876 $contactType = self
::getContactType($id);
1878 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1881 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1882 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1883 WHERE civicrm_contact.id = %1
1884 ORDER BY civicrm_email.is_primary DESC";
1885 $params = [1 => [$id, 'Integer']];
1886 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1888 if ($dao->fetch()) {
1889 if ($contactType == 'Individual') {
1890 if ($dao->first_name ||
$dao->last_name
) {
1891 $name = "{$dao->first_name} {$dao->last_name}";
1894 $name = $dao->display_name
;
1898 $name = $dao->display_name
;
1900 $email = $dao->email
;
1901 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1902 $onHold = $dao->on_hold ?
TRUE : FALSE;
1903 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1904 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1906 return [NULL, NULL, NULL, NULL, NULL];
1910 * Add/edit/register contacts through profile.
1912 * @param array $params
1913 * Array of profile fields to be edited/added.
1914 * @param array $fields
1915 * Array of fields from UFGroup.
1916 * @param int $contactID
1917 * Id of the contact to be edited/added.
1918 * @param int $addToGroupID
1919 * Specifies the default group to which contact is added.
1920 * @param int $ufGroupId
1921 * Uf group id (profile id).
1922 * @param string $ctype
1923 * @param bool $visibility
1924 * Basically lets us know where this request is coming from.
1925 * if via a profile from web, we restrict what groups are changed
1928 * contact id created/edited
1930 public static function createProfileContact(
1934 $addToGroupID = NULL,
1939 // add ufGroupID to params array ( CRM-2012 )
1941 $params['uf_group_id'] = $ufGroupId;
1943 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1945 // If a user has logged in, or accessed via a checksum
1946 // Then deliberately 'blanking' a value in the profile should remove it from their record
1947 $session = CRM_Core_Session
::singleton();
1948 $params['updateBlankLocInfo'] = TRUE;
1949 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1950 $params['updateBlankLocInfo'] = FALSE;
1955 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1959 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1962 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1964 // manage is_opt_out
1965 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1966 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1967 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1968 $data['is_opt_out'] = $isOptOut;
1969 // on change, create new civicrm_subscription_history entry
1970 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1972 'contact_id' => $contactDetails['contact_id'],
1973 'status' => $isOptOut ?
'Removed' : 'Added',
1976 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1980 $contact = self
::create($data);
1982 // contact is null if the profile does not have any contact fields
1984 $contactID = $contact->id
;
1987 if (empty($contactID)) {
1988 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1991 // Process group and tag
1992 if (!empty($fields['group'])) {
1994 // this for sure means we are coming in via profile since i added it to fix
1995 // removing contacts from user groups -- lobo
1999 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2002 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2003 // Convert comma separated form values from select2 v3
2004 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2005 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2008 //to add profile in default group
2009 if (is_array($addToGroupID)) {
2010 $contactIds = [$contactID];
2011 foreach ($addToGroupID as $groupId) {
2012 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2015 elseif ($addToGroupID) {
2016 $contactIds = [$contactID];
2017 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2020 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
2023 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2026 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2032 * Format profile contact parameters.
2034 * @param array $params
2036 * @param int $contactID
2037 * @param int $ufGroupId
2038 * @param null $ctype
2039 * @param bool $skipCustom
2043 public static function formatProfileContactParams(
2052 $data = $contactDetails = [];
2054 // get the contact details (hier)
2056 $details = self
::getHierContactDetails($contactID, $fields);
2058 $contactDetails = $details[$contactID];
2059 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
2060 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
2063 //we should get contact type only if contact
2065 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2067 //special case to handle profile with only contact fields
2068 if ($data['contact_type'] == 'Contact') {
2069 $data['contact_type'] = 'Individual';
2071 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2072 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2076 $data['contact_type'] = $ctype;
2079 $data['contact_type'] = 'Individual';
2083 //fix contact sub type CRM-5125
2084 if (array_key_exists('contact_sub_type', $params) &&
2085 !empty($params['contact_sub_type'])
2087 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2089 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2090 !empty($params['contact_sub_type_hidden'])
2092 // if profile was used, and had any subtype, we obtain it from there
2093 //CRM-13596 - add to existing contact types, rather than overwriting
2094 if (empty($data['contact_sub_type'])) {
2095 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2096 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2099 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2100 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2101 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2102 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2103 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2108 if ($ctype == 'Organization') {
2109 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2111 elseif ($ctype == 'Household') {
2112 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2120 $data['contact_id'] = $contactID;
2121 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2124 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2125 $defaultLocationId = $defaultLocation->id
;
2128 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2130 $blocks = ['email', 'phone', 'im', 'openid'];
2132 $multiplFields = ['url'];
2133 // prevent overwritten of formatted array, reset all block from
2134 // params if it is not in valid format (since import pass valid format)
2135 foreach ($blocks as $blk) {
2136 if (array_key_exists($blk, $params) &&
2137 !is_array($params[$blk])
2139 unset($params[$blk]);
2143 $primaryPhoneLoc = NULL;
2144 $session = CRM_Core_Session
::singleton();
2145 foreach ($params as $key => $value) {
2146 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2148 if ($locTypeId == 'Primary') {
2150 if (in_array($fieldName, $blocks)) {
2151 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2154 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2156 $primaryLocationType = $locTypeId;
2159 $locTypeId = $defaultLocationId;
2163 if (is_numeric($locTypeId) &&
2164 !in_array($fieldName, $multiplFields) &&
2165 substr($fieldName, 0, 7) != 'custom_'
2167 $index = $locTypeId;
2169 if (is_numeric($typeId)) {
2170 $index .= '-' . $typeId;
2172 if (!in_array($index, $locationType)) {
2173 $locationType[$count] = $index;
2177 $loc = CRM_Utils_Array
::key($index, $locationType);
2179 $blockName = self
::getLocationEntityForKey($fieldName);
2181 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2183 //set is_billing true, for location type "Billing"
2184 if ($locTypeId == $billingLocationTypeId) {
2185 $data[$blockName][$loc]['is_billing'] = 1;
2189 //get the primary location type
2190 if ($locTypeId == $primaryLocationType) {
2191 $data[$blockName][$loc]['is_primary'] = 1;
2194 elseif ($locTypeId == $defaultLocationId) {
2195 $data[$blockName][$loc]['is_primary'] = 1;
2198 if (in_array($fieldName, ['phone'])) {
2200 $data['phone'][$loc]['phone_type_id'] = $typeId;
2203 $data['phone'][$loc]['phone_type_id'] = '';
2205 $data['phone'][$loc]['phone'] = $value;
2207 //special case to handle primary phone with different phone types
2208 // in this case we make first phone type as primary
2209 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2210 $primaryPhoneLoc = $loc;
2213 if ($loc != $primaryPhoneLoc) {
2214 unset($data['phone'][$loc]['is_primary']);
2217 elseif ($fieldName == 'email') {
2218 $data['email'][$loc]['email'] = $value;
2219 if (empty($contactID)) {
2220 $data['email'][$loc]['is_primary'] = 1;
2223 elseif ($fieldName == 'im') {
2224 if (isset($params[$key . '-provider_id'])) {
2225 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2227 if (strpos($key, '-provider_id') !== FALSE) {
2228 $data['im'][$loc]['provider_id'] = $params[$key];
2231 $data['im'][$loc]['name'] = $value;
2234 elseif ($fieldName == 'openid') {
2235 $data['openid'][$loc]['openid'] = $value;
2238 if ($fieldName === 'state_province') {
2240 if (is_numeric($value) && ((int ) $value) >= 1000) {
2241 $data['address'][$loc]['state_province_id'] = $value;
2243 elseif (empty($value)) {
2244 $data['address'][$loc]['state_province_id'] = '';
2247 $data['address'][$loc]['state_province'] = $value;
2250 elseif ($fieldName === 'country') {
2252 if (is_numeric($value) && ((int ) $value) >= 1000
2254 $data['address'][$loc]['country_id'] = $value;
2256 elseif (empty($value)) {
2257 $data['address'][$loc]['country_id'] = '';
2260 $data['address'][$loc]['country'] = $value;
2263 elseif ($fieldName === 'county') {
2264 $data['address'][$loc]['county_id'] = $value;
2266 elseif ($fieldName == 'address_name') {
2267 $data['address'][$loc]['name'] = $value;
2269 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2270 $data['address'][$loc][substr($fieldName, 8)] = $value;
2273 $data[$blockName][$loc][$fieldName] = $value;
2278 if (substr($key, 0, 4) === 'url-') {
2279 $websiteField = explode('-', $key);
2280 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2281 $data['website'][$websiteField[1]]['url'] = $value;
2283 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2284 //save email/postal greeting and addressee values if any, CRM-4575
2285 $data[$key . '_id'] = $value;
2287 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2288 // for autocomplete transfer hidden value instead of label
2289 if ($params[$key] && isset($params[$key . '_id'])) {
2290 $value = $params[$key . '_id'];
2293 // we need to append time with date
2294 if ($params[$key] && isset($params[$key . '_time'])) {
2295 $value .= ' ' . $params[$key . '_time'];
2298 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2299 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2300 ($value == '' ||
!isset($value))
2306 if (!empty($params['customRecordValues'])) {
2307 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2308 foreach ($params['customRecordValues'] as $recId => $customFields) {
2309 if (is_array($customFields) && !empty($customFields)) {
2310 foreach ($customFields as $customFieldName) {
2311 if ($customFieldName == $key) {
2321 //CRM-13596 - check for contact_sub_type_hidden first
2322 if (array_key_exists('contact_sub_type_hidden', $params)) {
2323 $type = $params['contact_sub_type_hidden'];
2326 $type = $data['contact_type'];
2327 if (!empty($data['contact_sub_type'])) {
2328 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2332 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2342 elseif ($key === 'edit') {
2346 if ($key === 'location') {
2347 foreach ($value as $locationTypeId => $field) {
2348 foreach ($field as $block => $val) {
2349 if ($block === 'address' && array_key_exists('address_name', $val)) {
2350 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2355 if ($key === 'phone' && isset($params['phone_ext'])) {
2356 $data[$key] = $value;
2357 foreach ($value as $cnt => $phoneBlock) {
2358 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2359 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2363 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2364 && ($value == '' ||
!isset($value)) &&
2365 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2366 ($key === 'current_employer' && empty($params['current_employer']))) {
2367 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2368 // to avoid update with empty values
2372 $data[$key] = $value;
2378 if (!isset($data['contact_type'])) {
2379 $data['contact_type'] = 'Individual';
2382 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2383 $privacy = CRM_Core_SelectValues
::privacy();
2384 foreach ($privacy as $key => $value) {
2385 if (array_key_exists($key, $fields)) {
2386 // do not reset values for existing contacts, if fields are added to a profile
2387 if (array_key_exists($key, $params)) {
2388 $data[$key] = $params[$key];
2389 if (empty($params[$key])) {
2393 elseif (!$contactID) {
2399 return [$data, $contactDetails];
2403 * Find the get contact details.
2405 * This function does not respect ACLs for now, which might need to be rectified at some
2406 * stage based on how its used.
2408 * @param string $mail
2409 * Primary email address of the contact.
2410 * @param string $ctype
2413 * @return object|null
2414 * $dao contact details
2416 public static function matchContactOnEmail($mail, $ctype = NULL) {
2417 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2418 $mail = $strtolower(trim($mail));
2420 SELECT civicrm_contact.id as contact_id,
2421 civicrm_contact.hash as hash,
2422 civicrm_contact.contact_type as contact_type,
2423 civicrm_contact.contact_sub_type as contact_sub_type
2424 FROM civicrm_contact
2425 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2427 if (Civi
::settings()->get('uniq_email_per_site')) {
2428 // try to find a match within a site (multisite).
2429 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2430 if (!empty($groups)) {
2432 INNER JOIN civicrm_group_contact gc ON
2433 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2438 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2439 $p = [1 => [$mail, 'String']];
2442 $query .= " AND civicrm_contact.contact_type = %3";
2443 $p[3] = [$ctype, 'String'];
2446 $query .= " ORDER BY civicrm_email.is_primary DESC";
2448 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2450 if ($dao->fetch()) {
2457 * Find the contact details associated with an OpenID.
2459 * @param string $openId
2460 * OpenId of the contact.
2461 * @param string $ctype
2464 * @return object|null
2465 * $dao contact details
2467 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2468 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2469 $openId = $strtolower(trim($openId));
2471 SELECT civicrm_contact.id as contact_id,
2472 civicrm_contact.hash as hash,
2473 civicrm_contact.contact_type as contact_type,
2474 civicrm_contact.contact_sub_type as contact_sub_type
2475 FROM civicrm_contact
2476 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2477 WHERE civicrm_openid.openid = %1";
2478 $p = [1 => [$openId, 'String']];
2481 $query .= " AND civicrm_contact.contact_type = %3";
2482 $p[3] = [$ctype, 'String'];
2485 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2487 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2489 if ($dao->fetch()) {
2496 * Get primary email of the contact.
2498 * @param int $contactID
2500 * @param bool $polite
2501 * Whether to only pull an email if it's okay to send to it--that is, if it
2502 * is not on_hold and the contact is not do_not_email.
2505 * Email address if present else null
2507 public static function getPrimaryEmail($contactID, $polite = FALSE) {
2508 // fetch the primary email
2510 SELECT civicrm_email.email as email
2511 FROM civicrm_contact
2512 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2513 WHERE civicrm_email.is_primary = 1
2514 AND civicrm_contact.id = %1";
2517 AND civicrm_contact.do_not_email = 0
2518 AND civicrm_email.on_hold = 0';
2520 $p = [1 => [$contactID, 'Integer']];
2521 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2524 if ($dao->fetch()) {
2525 $email = $dao->email
;
2531 * Function to get primary OpenID of the contact.
2533 * @param int $contactID
2537 * >openid OpenID if present else null
2539 public static function getPrimaryOpenId($contactID) {
2540 // fetch the primary OpenID
2542 SELECT civicrm_openid.openid as openid
2543 FROM civicrm_contact
2544 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2545 WHERE civicrm_contact.id = %1
2546 AND civicrm_openid.is_primary = 1";
2547 $p = [1 => [$contactID, 'Integer']];
2548 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2551 if ($dao->fetch()) {
2552 $openId = $dao->openid
;
2558 * Fetch the object and store the values in the values array.
2560 * @param array $params
2561 * Input parameters to find object.
2562 * @param array $values
2563 * Output values of the object.
2565 * @return CRM_Contact_BAO_Contact|null
2566 * The found object or null
2568 public static function getValues(&$params, &$values) {
2569 $contact = new CRM_Contact_BAO_Contact();
2571 $contact->copyValues($params);
2573 if ($contact->find(TRUE)) {
2575 CRM_Core_DAO
::storeValues($contact, $values);
2578 foreach (self
::$_commPrefs as $name) {
2579 if (isset($contact->$name)) {
2580 $privacy[$name] = $contact->$name;
2584 if (!empty($privacy)) {
2585 $values['privacy'] = $privacy;
2588 // communication Prefferance
2589 $preffComm = $comm = [];
2590 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2591 $contact->preferred_communication_method
2593 foreach ($comm as $value) {
2594 $preffComm[$value] = 1;
2596 $temp = ['preferred_communication_method' => $contact->preferred_communication_method
];
2599 'preferred_communication_method' => [
2600 'newName' => 'preferred_communication_method_display',
2601 'groupName' => 'preferred_communication_method',
2605 // @todo This can be figured out from metadata & we can avoid the uncached query.
2606 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2608 $values['preferred_communication_method'] = $preffComm;
2609 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2611 if ($contact->preferred_mail_format
) {
2612 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2613 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2616 // get preferred languages
2617 if (!empty($contact->preferred_language
)) {
2618 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2621 // Calculating Year difference
2622 if ($contact->birth_date
) {
2623 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2624 if ($birthDate < date('Ymd')) {
2625 $age = CRM_Utils_Date
::calculateAge($birthDate);
2626 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2627 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2631 $contact->contact_id
= $contact->id
;
2639 * Given the component name and returns the count of participation of contact.
2641 * @param string $component
2642 * Input component name.
2643 * @param int $contactId
2645 * @param string $tableName
2646 * Optional tableName if component is custom group.
2649 * total number in database
2651 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2653 switch ($component) {
2655 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2658 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2659 CRM_Contact_BAO_Relationship
::CURRENT
,
2668 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2671 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2674 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2677 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2679 case 'contribution':
2680 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2683 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2686 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2689 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2692 return CRM_Case_BAO_Case
::caseCount($contactId);
2695 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2699 'contact_id' => $contactId,
2702 'context' => 'activity',
2704 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2707 $params = ['contact_id' => $contactId];
2708 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2711 $custom = explode('_', $component);
2712 if ($custom['0'] = 'custom') {
2714 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2716 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2717 return CRM_Core_DAO
::singleValueQuery($queryString);
2723 * Update contact greetings if an update has resulted in a custom field change.
2725 * @param array $updatedFields
2726 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2727 * @param array $contactParams
2728 * Parameters known about the contact. At minimum array('contact_id' => x).
2729 * Fields in this array will take precedence over DB fields (so far only
2730 * in the case of greeting id fields).
2732 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2733 $contactID = $contactParams['contact_id'];
2734 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2735 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2736 if (!empty($tokens['all']['contact'])) {
2737 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2738 if (!empty($affectedTokens)) {
2739 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2740 $contact = new CRM_Contact_BAO_Contact();
2741 $contact->id
= $contactID;
2742 CRM_Contact_BAO_Contact
::processGreetings($contact);
2748 * Process greetings and cache.
2750 * @param object $contact
2751 * Contact object after save.
2753 public static function processGreetings(&$contact) {
2755 //@todo this function does a lot of unnecessary loading.
2756 // ensureGreetingParamsAreSet now makes sure that the contact is
2757 // loaded and using updateGreetingsOnTokenFieldChange
2758 // allows us the possibility of only doing an update if required.
2760 // The contact object has not always required the
2761 // fields that are required to calculate greetings
2762 // so we need to retrieve it again.
2763 if ($contact->_query
!== FALSE) {
2764 $contact->find(TRUE);
2767 // store object values to an array
2768 $contactDetails = [];
2769 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2770 $contactDetails = [[$contact->id
=> $contactDetails]];
2772 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2773 $updateQueryString = [];
2775 //cache email and postal greeting to greeting display
2776 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2777 $emailGreetingString = $contact->email_greeting_custom
;
2779 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2780 // the filter value for Individual contact type is set to 1
2782 'contact_type' => $contact->contact_type
,
2783 'greeting_type' => 'email_greeting',
2786 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2787 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2788 $updateQueryString[] = " email_greeting_custom = NULL ";
2791 if ($contact->email_greeting_custom
) {
2792 $updateQueryString[] = " email_greeting_display = NULL ";
2796 if ($emailGreetingString) {
2797 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2800 'CRM_Contact_BAO_Contact'
2802 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2803 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2807 if ($contact->postal_greeting_custom
!== 'null' && $contact->postal_greeting_custom
) {
2808 $postalGreetingString = $contact->postal_greeting_custom
;
2810 elseif ($contact->postal_greeting_id
!== 'null' && $contact->postal_greeting_id
) {
2812 'contact_type' => $contact->contact_type
,
2813 'greeting_type' => 'postal_greeting',
2815 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2816 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2817 $updateQueryString[] = " postal_greeting_custom = NULL ";
2820 if ($contact->postal_greeting_custom
) {
2821 $updateQueryString[] = " postal_greeting_display = NULL ";
2825 if ($postalGreetingString) {
2826 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2829 'CRM_Contact_BAO_Contact'
2831 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2832 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2836 if ($contact->addressee_custom
!== 'null' && $contact->addressee_custom
) {
2837 $addresseeString = $contact->addressee_custom
;
2839 elseif ($contact->addressee_id
!== 'null' && $contact->addressee_id
) {
2841 'contact_type' => $contact->contact_type
,
2842 'greeting_type' => 'addressee',
2845 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2846 $addresseeString = $addressee[$contact->addressee_id
];
2847 $updateQueryString[] = " addressee_custom = NULL ";
2850 if ($contact->addressee_custom
) {
2851 $updateQueryString[] = " addressee_display = NULL ";
2855 if ($addresseeString) {
2856 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2859 'CRM_Contact_BAO_Contact'
2861 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2862 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2865 if (!empty($updateQueryString)) {
2866 $updateQueryString = implode(',', $updateQueryString);
2867 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2868 CRM_Core_DAO
::executeQuery($queryString);
2873 * Retrieve loc block ids w/ given condition.
2875 * @param int $contactId
2877 * @param array $criteria
2878 * Key => value pair which should be.
2879 * fulfill by return record ids.
2880 * @param string $condOperator
2881 * Operator use for grouping multiple conditions.
2884 * loc block ids which fulfill condition.
2886 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2889 return $locBlockIds;
2892 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2893 $name = strtolower($block);
2894 $className = "CRM_Core_DAO_$block";
2895 $blockDAO = new $className();
2897 // build the condition.
2898 if (is_array($criteria)) {
2899 $fields = $blockDAO->fields();
2901 foreach ($criteria as $field => $value) {
2902 if (array_key_exists($field, $fields)) {
2903 $cond = "( $field = $value )";
2904 // value might be zero or null.
2905 if (!$value ||
strtolower($value) === 'null') {
2906 $cond = "( $field = 0 OR $field IS NULL )";
2908 $conditions[] = $cond;
2911 if (!empty($conditions)) {
2912 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2916 $blockDAO->contact_id
= $contactId;
2918 while ($blockDAO->fetch()) {
2919 $locBlockIds[$name][] = $blockDAO->id
;
2923 return $locBlockIds;
2927 * Build context menu items.
2929 * @param int $contactId
2932 * Array of context menu for logged in user.
2934 public static function contextMenu($contactId = NULL) {
2937 'title' => ts('View Contact'),
2939 'ref' => 'view-contact',
2940 'class' => 'no-popup',
2942 'permissions' => ['view all contacts'],
2945 'title' => ts('Edit Contact'),
2947 'ref' => 'edit-contact',
2948 'class' => 'no-popup',
2950 'permissions' => ['edit all contacts'],
2953 'title' => ts('Delete Contact'),
2955 'ref' => 'delete-contact',
2957 'permissions' => ['access deleted contacts', 'delete contacts'],
2960 'title' => ts('Add Contribution'),
2962 'ref' => 'new-contribution',
2963 'key' => 'contribution',
2964 'tab' => 'contribute',
2965 'component' => 'CiviContribute',
2966 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2967 'reset=1&action=add&context=contribution'
2970 'access CiviContribute',
2971 'edit contributions',
2975 'title' => ts('Register for Event'),
2977 'ref' => 'new-participant',
2978 'key' => 'participant',
2979 'tab' => 'participant',
2980 'component' => 'CiviEvent',
2981 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2984 'edit event participants',
2988 'title' => ts('Record Activity'),
2990 'ref' => 'new-activity',
2991 'key' => 'activity',
2992 'permissions' => ['edit all contacts'],
2995 'title' => ts('Add Pledge'),
2997 'ref' => 'new-pledge',
3000 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3001 'reset=1&action=add&context=pledge'
3003 'component' => 'CiviPledge',
3005 'access CiviPledge',
3010 'title' => ts('Add Membership'),
3012 'ref' => 'new-membership',
3013 'key' => 'membership',
3015 'component' => 'CiviMember',
3016 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3017 'reset=1&action=add&context=membership'
3020 'access CiviMember',
3025 'title' => ts('Add Case'),
3027 'ref' => 'new-case',
3030 'component' => 'CiviCase',
3031 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3032 'permissions' => ['add cases'],
3035 'title' => ts('Add Grant'),
3037 'ref' => 'new-grant',
3040 'component' => 'CiviGrant',
3041 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3042 'reset=1&action=add&context=grant'
3044 'permissions' => ['edit grants'],
3047 'title' => ts('Add Relationship'),
3049 'ref' => 'new-relationship',
3052 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3053 'reset=1&action=add'
3055 'permissions' => ['edit all contacts'],
3058 'title' => ts('Add Note'),
3060 'ref' => 'new-note',
3063 'class' => 'medium-popup',
3064 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3065 'reset=1&action=add'
3067 'permissions' => ['edit all contacts'],
3070 'title' => ts('Send an Email'),
3072 'ref' => 'new-email',
3074 'permissions' => ['view all contacts'],
3077 'title' => ts('Add to Group'),
3079 'ref' => 'group-add-contact',
3082 'permissions' => ['edit groups'],
3085 'title' => ts('Tag Contact'),
3087 'ref' => 'tag-contact',
3090 'permissions' => ['edit all contacts'],
3094 $menu['otherActions'] = [
3096 'title' => ts('Print Summary'),
3097 'description' => ts('Printer-friendly view of this page.'),
3099 'ref' => 'crm-contact-print',
3102 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3106 'icon' => 'crm-i fa-print',
3109 'title' => ts('vCard'),
3110 'description' => ts('vCard record for this contact.'),
3112 'ref' => 'crm-contact-vcard',
3115 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3119 'icon' => 'crm-i fa-list-alt',
3123 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3124 $menu['otherActions']['dashboard'] = [
3125 'title' => ts('Contact Dashboard'),
3126 'description' => ts('Contact Dashboard'),
3128 'ref' => 'crm-contact-dashboard',
3129 'key' => 'dashboard',
3130 'tab' => 'dashboard',
3131 'class' => 'dashboard',
3132 // NOTE: As an alternative you can also build url on CMS specific way
3133 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3134 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3135 'icon' => 'crm-i fa-tachometer',
3139 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3141 $menu['otherActions']['user-record'] = [
3142 'title' => ts('User Record'),
3143 'description' => ts('User Record'),
3145 'ref' => 'crm-contact-user-record',
3146 'key' => 'user-record',
3147 'tab' => 'user-record',
3148 'class' => 'user-record',
3149 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3150 'icon' => 'crm-i fa-user',
3153 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3154 $menu['otherActions']['user-add'] = [
3155 'title' => ts('Create User Record'),
3156 'description' => ts('Create User Record'),
3158 'ref' => 'crm-contact-user-add',
3159 'key' => 'user-add',
3160 'tab' => 'user-add',
3161 'class' => 'user-add',
3162 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3163 'icon' => 'crm-i fa-user-plus',
3167 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3168 //1. check for component is active.
3169 //2. check for user permissions.
3170 //3. check for acls.
3171 //3. edit and view contact are directly accessible to user.
3173 $aclPermissionedTasks = [
3178 'group-add-contact',
3182 $corePermission = CRM_Core_Permission
::getPermission();
3185 foreach ($menu as $key => $values) {
3186 if ($key !== 'otherActions') {
3188 // user does not have necessary permissions.
3189 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3192 // build directly accessible action menu.
3193 if (in_array($values['ref'], [
3197 $contextMenu['primaryActions'][$key] = [
3198 'title' => $values['title'],
3199 'ref' => $values['ref'],
3200 'class' => $values['class'] ??
NULL,
3201 'key' => $values['key'],
3206 // finally get menu item for -more- action widget.
3207 $contextMenu['moreActions'][$values['weight']] = [
3208 'title' => $values['title'],
3209 'ref' => $values['ref'],
3210 'href' => $values['href'] ??
NULL,
3211 'tab' => $values['tab'] ??
NULL,
3212 'class' => $values['class'] ??
NULL,
3213 'key' => $values['key'],
3217 foreach ($values as $value) {
3218 // user does not have necessary permissions.
3219 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3223 // finally get menu item for -more- action widget.
3224 $contextMenu['otherActions'][$value['weight']] = [
3225 'title' => $value['title'],
3226 'ref' => $value['ref'],
3227 'href' => $value['href'] ??
NULL,
3228 'tab' => $value['tab'] ??
NULL,
3229 'class' => $value['class'] ??
NULL,
3230 'icon' => $value['icon'] ??
NULL,
3231 'key' => $value['key'],
3237 ksort($contextMenu['moreActions']);
3238 ksort($contextMenu['otherActions']);
3240 return $contextMenu;
3244 * Check if user has permissions to access items in action menu.
3246 * @param array $aclPermissionedTasks
3247 * Array containing ACL related tasks.
3248 * @param string $corePermission
3249 * The permission of the user (edit or view or null).
3250 * @param array $menuOptions
3251 * Array containing params of the menu (title, href, etc).
3254 * TRUE if user has all permissions, FALSE if otherwise.
3256 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3257 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3259 // if component action - make sure component is enable.
3260 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3264 // make sure user has all required permissions.
3265 $hasAllPermissions = FALSE;
3267 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3268 if (!is_array($permissions) ||
empty($permissions)) {
3269 $hasAllPermissions = TRUE;
3272 // iterate for required permissions in given permissions array.
3273 if (!$hasAllPermissions) {
3274 $hasPermissions = 0;
3275 foreach ($permissions as $permission) {
3276 if (CRM_Core_Permission
::check($permission)) {
3281 if (count($permissions) == $hasPermissions) {
3282 $hasAllPermissions = TRUE;
3285 // if still user does not have required permissions, check acl.
3286 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3287 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3288 $corePermission == CRM_Core_Permission
::EDIT
3290 $hasAllPermissions = TRUE;
3292 elseif (in_array($menuOptions['ref'], [
3295 // grant permissions for these tasks.
3296 $hasAllPermissions = TRUE;
3301 return $hasAllPermissions;
3305 * Retrieve display name of contact that address is shared.
3307 * This is based on $masterAddressId or $contactId .
3309 * @param int $masterAddressId
3311 * @param int $contactId
3312 * Contact id. (deprecated - do not use)
3314 * @return string|null
3315 * the found display name or null.
3317 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3318 $masterDisplayName = NULL;
3319 if (!$masterAddressId) {
3320 return $masterDisplayName;
3324 SELECT display_name from civicrm_contact
3325 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3326 WHERE civicrm_address.id = " . $masterAddressId;
3328 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3329 return $masterDisplayName;
3333 * Get the creation/modification times for a contact.
3335 * @param int $contactId
3338 * Dates - ('created_date' => $, 'modified_date' => $)
3340 public static function getTimestamps($contactId) {
3341 $timestamps = CRM_Core_DAO
::executeQuery(
3342 'SELECT created_date, modified_date
3343 FROM civicrm_contact
3346 1 => [$contactId, 'Integer'],
3349 if ($timestamps->fetch()) {
3351 'created_date' => $timestamps->created_date
,
3352 'modified_date' => $timestamps->modified_date
,
3361 * Get a list of triggers for the contact table.
3364 * @param null $tableName
3366 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3368 * @see hook_civicrm_triggerInfo
3369 * @see CRM_Core_DAO::triggerRebuild
3371 public static function triggerInfo(&$info, $tableName = NULL) {
3372 //during upgrade, first check for valid version and then create triggers
3373 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3374 if (CRM_Core_Config
::isUpgradeMode()) {
3375 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3376 //if current version is less than 4.3.alpha1 dont create below triggers
3377 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3382 // Modifications to these records should update the contact timestamps.
3383 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3385 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3386 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3387 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3388 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3389 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3391 ->alterTriggerInfo($info, $tableName);
3393 // Update phone table to populate phone_numeric field
3394 if (!$tableName ||
$tableName == 'civicrm_phone') {
3395 // Define stored sql function needed for phones
3396 $sqlTriggers = Civi
::service('sql_triggers');
3397 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3398 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3400 'table' => ['civicrm_phone'],
3402 'event' => ['INSERT', 'UPDATE'],
3403 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3409 * Check if contact is being used in civicrm_domain based on $contactId.
3411 * @param int $contactId
3415 * true if present else false.
3417 public static function checkDomainContact($contactId) {
3421 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3432 * Get options for a given contact field.
3434 * @param string $fieldName
3435 * @param string $context
3436 * @param array $props
3437 * whatever is known about this dao object.
3439 * @return array|bool
3440 * @see CRM_Core_DAO::buildOptions
3442 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3443 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3445 * @see CRM_Core_DAO::buildOptionsContext
3447 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3449 // Special logic for fields whose options depend on context or properties
3450 switch ($fieldName) {
3451 case 'contact_sub_type':
3452 if (!empty($props['contact_type'])) {
3453 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3457 case 'contact_type':
3458 if ($context == 'search') {
3459 // CRM-15495 - EntityRef filters and basic search forms expect this format
3460 // FIXME: Search builder does not
3461 return CRM_Contact_BAO_ContactType
::getSelectElements();
3465 // The contact api supports some related entities so we'll honor that by fetching their options
3468 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3472 $props['entity_table'] = 'civicrm_contact';
3473 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3475 case 'state_province_id':
3476 case 'state_province':
3477 case 'state_province_name':
3482 case 'worldregion_id':
3483 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3486 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3490 * Delete a contact-related object that has an 'is_primary' field.
3492 * Ensures that is_primary gets assigned to another object if available
3493 * Also calls pre/post hooks
3495 * @param string $type
3500 public static function deleteObjectWithPrimary($type, $id) {
3501 if (!$id ||
!is_numeric($id)) {
3504 $daoName = "CRM_Core_DAO_$type";
3505 $obj = new $daoName();
3509 if ($obj->fetch()) {
3510 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3511 $contactId = $obj->contact_id
;
3517 // is_primary is only relavent if this field belongs to a contact
3519 $dao = new $daoName();
3520 $dao->contact_id
= $contactId;
3521 $dao->is_primary
= 1;
3522 // Pick another record to be primary (if one isn't already)
3523 if (!$dao->find(TRUE)) {
3524 $dao->is_primary
= 0;
3526 if ($dao->fetch()) {
3527 $dao->is_primary
= 1;
3532 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3539 public function addSelectWhereClause() {
3540 // We always return an array with these keys, even if they are empty,
3541 // because this tells the query builder that we have considered these fields for acls
3543 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3544 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
[] : ['!= 1'],
3546 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3551 * Get any existing duplicate contacts based on the input parameters.
3553 * @param array $input
3554 * Input parameters to be matched.
3555 * @param string $contactType
3556 * @param string $rule
3559 * @param $excludedContactIDs
3560 * An array of ids not to be included in the results.
3561 * @param bool $checkPermissions
3562 * @param int $ruleGroupID
3563 * ID of the rule group to be used if an override is desirable.
3564 * @param array $contextParams
3565 * The context if relevant, eg. ['event_id' => X]
3569 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3570 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3571 $dedupeParams['check_permission'] = $checkPermissions;
3572 $dedupeParams['contact_type'] = $contactType;
3573 $dedupeParams['rule'] = $rule;
3574 $dedupeParams['rule_group_id'] = $ruleGroupID;
3575 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3576 $dedupeResults['ids'] = [];
3577 $dedupeResults['handled'] = FALSE;
3578 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3579 if (!$dedupeResults['handled']) {
3580 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3582 return $dedupeResults['ids'];
3586 * Get the first duplicate contacts based on the input parameters.
3588 * @param array $input
3589 * Input parameters to be matched.
3590 * @param string $contactType
3591 * @param string $rule
3594 * @param $excludedContactIDs
3595 * An array of ids not to be included in the results.
3596 * @param bool $checkPermissions
3597 * @param int $ruleGroupID
3598 * ID of the rule group to be used if an override is desirable.
3599 * @param array $contextParams
3600 * The context if relevant, eg. ['event_id' => X]
3604 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3605 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3613 * Check if a field is associated with an entity that has a location type.
3615 * (ie. is an address, phone, email etc field).
3617 * @param string $fieldTitle
3618 * Title of the field (not the name - create a new function for that if required).
3622 public static function isFieldHasLocationType($fieldTitle) {
3623 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3624 if ($field['title'] === $fieldTitle) {
3625 return $field['hasLocationType'] ??
NULL;
3632 * @param array $appendProfiles
3633 * Name of profile(s) to append to each link.
3637 public static function getEntityRefCreateLinks($appendProfiles = []) {
3638 // You'd think that "create contacts" would be the permission to check,
3639 // But new contact popups are profile forms and those use their own permissions.
3640 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3644 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3645 $profiles[] = 'new_' . strtolower($contactType);
3647 $retrieved = civicrm_api3('uf_group', 'get', [
3648 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3651 $links = $append = [];
3652 if (!empty($retrieved['values'])) {
3654 'individual' => 'fa-user',
3655 'organization' => 'fa-building',
3656 'household' => 'fa-home',
3658 foreach ($retrieved['values'] as $id => $profile) {
3659 if (in_array($profile['name'], $profiles)) {
3661 'label' => $profile['title'],
3662 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3663 NULL, NULL, FALSE, FALSE, TRUE),
3664 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3665 'icon' => CRM_Utils_Array
::value(str_replace('new_', '', $profile['name']), $icons),
3672 foreach ($append as $id) {
3673 foreach ($links as &$link) {
3674 $link['url'] .= ",$id";
3684 public static function getEntityRefFilters() {
3686 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3687 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3688 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3689 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3690 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3691 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3692 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3693 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3694 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3695 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],