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_BAO_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();
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 CRM_Core_Error
::fatal(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
= CRM_Utils_Array
::value('contact_id', $params);
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 = empty($contact->id
) ?
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.
219 if ($contact->contact_type
=== 'Organization') {
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 // Not dying here is stupid, since we get into weird situation and into a bug that
300 // is impossible to figure out for the user or for us
302 CRM_Core_Error
::fatal();
305 $params['contact_id'] = $contact->id
;
307 if (Civi
::settings()->get('is_enabled')) {
308 // Enabling multisite causes the contact to be added to the domain group.
309 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
310 if (!empty($domainGroupID)) {
311 if (!empty($params['group']) && is_array($params['group'])) {
312 $params['group'][$domainGroupID] = 1;
315 $params['group'] = [$domainGroupID => 1];
320 if (array_key_exists('group', $params)) {
321 $contactIds = [$params['contact_id']];
322 foreach ($params['group'] as $groupId => $flag) {
324 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
326 elseif ($flag == -1) {
327 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
332 // Add location Block data.
333 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
334 foreach ($blocks as $name => $value) {
335 $contact->$name = $value;
337 if (!empty($params['updateBlankLocInfo'])) {
341 if (isset($params['website'])) {
342 CRM_Core_BAO_Website
::process($params['website'], $contact->id
, $skipDelete);
345 $userID = CRM_Core_Session
::singleton()->get('userID');
347 if (!empty($params['note'])) {
348 if (is_array($params['note'])) {
349 foreach ($params['note'] as $note) {
350 $contactId = $contact->id
;
351 if (isset($note['contact_id'])) {
352 $contactId = $note['contact_id'];
354 //if logged in user, overwrite contactId
356 $contactId = $userID;
360 'entity_id' => $contact->id
,
361 'entity_table' => 'civicrm_contact',
362 'note' => $note['note'],
363 'subject' => CRM_Utils_Array
::value('subject', $note),
364 'contact_id' => $contactId,
366 CRM_Core_BAO_Note
::add($noteParams);
370 $contactId = $contact->id
;
371 //if logged in user, overwrite contactId
373 $contactId = $userID;
377 'entity_id' => $contact->id
,
378 'entity_table' => 'civicrm_contact',
379 'note' => $params['note'],
380 'subject' => CRM_Utils_Array
::value('subject', $params),
381 'contact_id' => $contactId,
383 CRM_Core_BAO_Note
::add($noteParams);
387 // update the UF user_unique_id if that has changed
388 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
390 if (!empty($params['custom']) &&
391 is_array($params['custom'])
393 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
396 // make a civicrm_subscription_history entry only on contact create (CRM-777)
397 if (empty($params['contact_id'])) {
398 $subscriptionParams = [
399 'contact_id' => $contact->id
,
403 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
406 $transaction->commit();
408 // CRM-6367: fetch the right label for contact type’s display
409 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
410 'CRM_Contact_DAO_ContactType',
411 $contact->contact_type
,
416 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
420 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
423 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
427 // In order to prevent a series of expensive queries in intensive batch processing
428 // api calls may pass in skip_greeting_processing, probably doing it later via the
429 // scheduled job. CRM-21551
430 if (empty($params['skip_greeting_processing'])) {
431 self
::processGreetings($contact);
434 if (!empty($params['check_permissions'])) {
435 $contacts = [&$contact];
436 self
::unsetProtectedFields($contacts);
443 * Format the output of the create contact function
445 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
447 public static function unsetProtectedFields(&$contacts) {
448 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
449 $currentUser = CRM_Core_Session
::getLoggedInContactID();
450 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
451 foreach ($contacts as &$contact) {
452 $cid = is_object($contact) ?
$contact->id
: CRM_Utils_Array
::value('id', $contact);
453 if (!($editOwn && $cid == $currentUser)) {
454 if (is_object($contact)) {
455 unset($contact->api_key
);
458 unset($contact['api_key']);
466 * Ensure greeting parameters are set.
468 * By always populating greetings here we can be sure they are set if required & avoid a call later.
469 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
471 * @param array $params
473 * @throws \CiviCRM_API3_Exception
475 public static function ensureGreetingParamsAreSet(&$params) {
476 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
477 $missingGreetingParams = [];
479 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
480 if (empty($params[$greetingParam])) {
481 $missingGreetingParams[$greetingIndex] = $greetingParam;
485 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
486 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
487 'id' => $params['contact_id'],
488 'return' => array_keys($missingGreetingParams),
491 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
492 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
493 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
496 // Filter out other fields.
497 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
498 $params = array_merge($params, $savedGreetings);
501 foreach ($missingGreetingParams as $greetingName => $greeting) {
502 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
506 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
507 if ($params[$greetingParam] === 'null') {
508 // If we are setting it to null then null out the display field.
509 $params[$greetingIndex . '_display'] = 'null';
515 * Get the display name and image of a contact.
520 * @param bool $includeTypeInReturnParameters
521 * Should type be part of the returned array?
524 * the displayName and contactImage for this contact
526 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
527 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
529 SELECT civicrm_contact.*,
530 civicrm_email.email as email
532 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
533 AND civicrm_email.is_primary = 1
534 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
535 $dao = new CRM_Core_DAO();
538 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
539 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
541 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
542 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
545 // use email if display_name is empty
546 if (empty($dao->display_name
)) {
547 $displayName = $dao->email
;
550 $displayName = $dao->display_name
;
553 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
555 return $includeTypeInReturnParameters ?
[
559 $dao->contact_sub_type
,
561 ] : [$displayName, $image, $imageUrl];
567 * Add billing fields to the params if appropriate.
569 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
570 * don't then we should set the name fields to the billing fields AND add the preserveDBName
571 * parameter (which will tell the BAO only to set those fields if none already exist.
573 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
574 * matching is best done by hipsters.
576 * @param array $params
578 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
580 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
581 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
582 foreach ($nameFields as $field) {
583 if (!empty($params[$field])) {
587 // There are only 3 - we can iterate through them twice :-)
588 foreach ($nameFields as $field) {
589 if (!empty($params['billing_' . $field])) {
590 $params[$field] = $params['billing_' . $field];
592 $params['preserveDBName'] = TRUE;
598 * Resolve a state province string (UT or Utah) to an ID.
600 * If country has been passed in we should select a state belonging to that country.
602 * Alternatively we should choose from enabled countries, prioritising the default country.
604 * @param array $values
605 * @param int|null $countryID
609 * @throws \CRM_Core_Exception
611 protected static function resolveStateProvinceID($values, $countryID) {
614 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
615 if (CRM_Utils_Array
::lookupValue($values,
620 return $values['state_province_id'];
622 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
623 if (CRM_Utils_Array
::lookupValue($values,
628 return $values['state_province_id'];
633 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
634 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
635 // prefer matching country..
636 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, ['country_id' => Civi
::settings()->get('defaultContactCountry')]);
637 if (CRM_Utils_Array
::lookupValue($values,
642 return $values['state_province_id'];
645 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
646 if (CRM_Utils_Array
::lookupValue($values,
651 return $values['state_province_id'];
654 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
655 if (CRM_Utils_Array
::lookupValue($values,
660 return $values['state_province_id'];
662 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
663 if (CRM_Utils_Array
::lookupValue($values,
668 return $values['state_province_id'];
676 * Get the relevant location entity for the array key.
678 * Based on the field name we determine which location entity
679 * we are dealing with. Apart from a few specific ones they
680 * are mostly 'address' (the default).
682 * @param string $fieldName
686 protected static function getLocationEntityForKey($fieldName) {
687 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
690 if ($fieldName === 'phone_ext') {
697 * Create last viewed link to recently updated contact.
699 * @param array $crudLinkSpec
700 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
701 * - entity_table: string, eg "civicrm_contact"
705 * NULL if unavailable, or
706 * [path: string, query: string, title: string]
707 * @see CRM_Utils_System::createDefaultCrudLink
709 public function createDefaultCrudLink($crudLinkSpec) {
710 switch ($crudLinkSpec['action']) {
711 case CRM_Core_Action
::VIEW
:
713 'title' => $this->display_name
,
714 'path' => 'civicrm/contact/view',
722 case CRM_Core_Action
::UPDATE
:
724 'title' => $this->display_name
,
725 'path' => 'civicrm/contact/add',
728 'action' => 'update',
738 * Get the values for pseudoconstants for name->value and reverse.
740 * @param array $defaults
741 * (reference) the default values, some of which need to be resolved.
742 * @param bool $reverse
743 * Always true as this function is only called from one place..
747 * This is called specifically from the contact import parser & should be moved there
748 * as it is not truly a generic function.
751 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
752 // Hack for birth_date.
753 if (!empty($defaults['birth_date'])) {
754 if (is_array($defaults['birth_date'])) {
755 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
759 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
760 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
761 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
762 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
764 //lookup value of email/postal greeting, addressee, CRM-4575
765 foreach (self
::$_greetingTypes as $greeting) {
767 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
768 'greeting_type' => $greeting,
770 CRM_Utils_Array
::lookupValue($defaults, $greeting,
771 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
775 $blocks = ['address', 'im', 'phone'];
776 foreach ($blocks as $name) {
777 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
780 foreach ($defaults[$name] as $count => & $values) {
782 //get location type id.
783 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
785 if ($name == 'address') {
786 // FIXME: lookupValue doesn't work for vcard_name
787 if (!empty($values['location_type_id'])) {
788 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', ['labelColumn' => 'vcard_name']);
789 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
792 if (!CRM_Utils_Array
::lookupValue($values,
794 CRM_Core_PseudoConstant
::country(),
799 CRM_Utils_Array
::lookupValue($values,
801 CRM_Core_PseudoConstant
::countryIsoCode(),
805 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
806 if ($stateProvinceID) {
807 $values['state_province_id'] = $stateProvinceID;
810 if (!empty($values['state_province_id'])) {
811 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
814 $countyList = CRM_Core_PseudoConstant
::county();
816 CRM_Utils_Array
::lookupValue($values,
824 CRM_Utils_Array
::lookupValue($values,
826 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
831 if ($name == 'phone') {
832 CRM_Utils_Array
::lookupValue($values,
834 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
839 // Kill the reference.
846 * Fetch object based on array of properties.
848 * @param array $params
849 * (reference ) an assoc array of name/value pairs.
850 * @param array $defaults
851 * (reference ) an assoc array to hold the name / value pairs.
852 * in a hierarchical manner
853 * @param bool $microformat
854 * For location in microformat.
856 * @return CRM_Contact_BAO_Contact
858 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
859 if (array_key_exists('contact_id', $params)) {
860 $params['id'] = $params['contact_id'];
862 elseif (array_key_exists('id', $params)) {
863 $params['contact_id'] = $params['id'];
866 $contact = self
::getValues($params, $defaults);
868 unset($params['id']);
870 //get the block information for this contact
871 $entityBlock = ['contact_id' => $params['contact_id']];
872 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
873 $defaults = array_merge($defaults, $blocks);
874 foreach ($blocks as $block => $value) {
875 $contact->$block = $value;
878 if (!isset($params['noNotes'])) {
879 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
882 if (!isset($params['noRelationships'])) {
883 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
886 if (!isset($params['noGroups'])) {
887 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
890 if (!isset($params['noWebsite'])) {
891 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
898 * Get the display name of a contact.
903 * @return null|string
904 * display name of the contact if found
906 public static function displayName($id) {
909 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
916 * Delete a contact and all its associated records.
919 * Id of the contact to delete.
920 * @param bool $restore
921 * Whether to actually restore, not delete.
922 * @param bool $skipUndelete
923 * Whether to force contact delete or not.
924 * @param bool $checkPermissions
927 * Was contact deleted?
929 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
934 // If trash is disabled in system settings then we always skip
935 if (!Civi
::settings()->get('contact_undelete')) {
936 $skipUndelete = TRUE;
939 // make sure we have edit permission for this contact
941 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
942 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
948 // Restrict contact to be delete if contact has financial trxns
950 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent([$id], $error)) {
954 // make sure this contact_id does not have any membership types
955 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
958 'member_of_contact_id'
960 if ($membershipTypeID) {
964 $contact = new CRM_Contact_DAO_Contact();
966 if (!$contact->find(TRUE)) {
970 $contactType = $contact->contact_type
;
972 return self
::contactTrashRestore($contact, TRUE);
975 // start a new transaction
976 $transaction = new CRM_Core_Transaction();
979 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
981 //delete billing address if exists.
982 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
984 // delete the log entries since we dont have triggers enabled as yet
985 $logDAO = new CRM_Core_DAO_Log();
986 $logDAO->entity_table
= 'civicrm_contact';
987 $logDAO->entity_id
= $id;
990 // delete contact participants CRM-12155
991 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
993 // delete contact contributions CRM-12155
994 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
996 // do activity cleanup, CRM-5604
997 CRM_Activity_BAO_Activity
::cleanupActivity($id);
999 // delete all notes related to contact
1000 CRM_Core_BAO_Note
::cleanContactNotes($id);
1002 // delete cases related to contact
1003 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
1004 if (!empty($contactCases)) {
1005 foreach ($contactCases as $caseId) {
1006 //check if case is associate with other contact or not.
1007 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
1008 if (count($caseContactId) <= 1) {
1009 CRM_Case_BAO_Case
::deleteCase($caseId);
1017 self
::contactTrashRestore($contact);
1019 // currently we only clear employer cache.
1020 // we are now deleting inherited membership if any.
1021 if ($contact->contact_type
== 'Organization') {
1022 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
1023 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
1024 if (!empty($relationshipDtls)) {
1025 foreach ($relationshipDtls as $rId => $details) {
1026 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
1029 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
1032 //delete the contact id from recently view
1033 CRM_Utils_Recent
::delContact($id);
1034 self
::updateContactCache($id, empty($restore));
1036 // delete any prevnext/dupe cache entry
1037 // These two calls are redundant in default deployments, but they're
1038 // meaningful if "prevnext" is memory-backed.
1039 Civi
::service('prevnext')->deleteItem($id);
1040 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1042 $transaction->commit();
1044 if ($skipUndelete) {
1045 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1052 * Action to update any caches relating to a recently update contact.
1054 * I was going to call this from delete as well as from create to ensure the delete is being
1055 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1056 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1057 * where the call involved a subquery that was locking the table.
1059 * @param int $contactID
1060 * @param bool $isTrashed
1062 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1065 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1066 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1067 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1068 // but this should not cause any change as long as contacts are not being trashed outside the
1069 // main functions for that.
1070 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1073 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1078 * Delete the image of a contact.
1081 * Id of the contact.
1084 * Was contact image deleted?
1086 public static function deleteContactImage($id) {
1091 $contact = new self();
1093 $contact->image_URL
= 'null';
1100 * Return proportional height and width of the image.
1102 * @param int $imageWidth
1105 * @param int $imageHeight
1109 * Thumb dimension of image
1111 public static function getThumbSize($imageWidth, $imageHeight) {
1113 if ($imageWidth && $imageHeight) {
1114 $imageRatio = $imageWidth / $imageHeight;
1119 if ($imageRatio > 1) {
1120 $imageThumbWidth = $thumbWidth;
1121 $imageThumbHeight = round($thumbWidth / $imageRatio);
1124 $imageThumbHeight = $thumbWidth;
1125 $imageThumbWidth = round($thumbWidth * $imageRatio);
1128 return [$imageThumbWidth, $imageThumbHeight];
1132 * Validate type of contact image.
1134 * @param array $params
1135 * @param string $imageIndex
1136 * Index of image field.
1137 * @param string $statusMsg
1138 * Status message to be set after operation.
1139 * @param string $opType
1140 * Type of operation like fatal, bounce etc.
1143 * true if valid image extension
1145 public static function processImageParams(
1147 $imageIndex = 'image_URL',
1161 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1162 $photo = basename($params[$imageIndex]['name']);
1163 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1167 unset($params[$imageIndex]);
1169 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1171 if ($opType == 'status') {
1172 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1174 // FIXME: additional support for fatal, bounce etc could be added.
1180 * Extract contact id from url for deleting contact image.
1182 public static function processImage() {
1184 $action = CRM_Utils_Request
::retrieve('action', 'String');
1185 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1186 // retrieve contact id in case of Profile context
1187 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1188 $cid = $cid ?
$cid : $id;
1189 if ($action & CRM_Core_Action
::DELETE
) {
1190 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1191 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1192 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1193 $session = CRM_Core_Session
::singleton();
1194 $toUrl = $session->popUserContext();
1195 CRM_Utils_System
::redirect($toUrl);
1201 * Function to set is_delete true or restore deleted contact.
1203 * @param CRM_Contact_DAO_Contact $contact
1204 * Contact DAO object.
1205 * @param bool $restore
1206 * True to set the is_delete = 1 else false to restore deleted contact,
1207 * i.e. is_delete = 0
1211 public static function contactTrashRestore($contact, $restore = FALSE) {
1213 'id' => $contact->id
,
1214 'is_deleted' => $restore ?
0 : 1,
1217 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1219 $params = [1 => [$contact->id
, 'Integer']];
1221 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1222 CRM_Core_DAO
::executeQuery($query, $params);
1225 $contact->copyValues($updateParams);
1227 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
1229 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1235 * Get contact type for a contact.
1238 * Id of the contact whose contact type is needed.
1241 * contact_type if $id found else null ""
1243 public static function getContactType($id) {
1244 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1248 * Get contact sub type for a contact.
1251 * Id of the contact whose contact sub type is needed.
1253 * @param string $implodeDelimiter
1256 * contact_sub_type if $id found else null ""
1258 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1259 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1261 return $implodeDelimiter ?
NULL : [];
1264 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1266 if ($implodeDelimiter) {
1267 $subtype = implode($implodeDelimiter, $subtype);
1273 * Get pair of contact-type and sub-type for a contact.
1276 * Id of the contact whose contact sub/contact type is needed.
1280 public static function getContactTypes($id) {
1281 $params = ['id' => $id];
1283 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1286 ['contact_type', 'contact_sub_type']
1291 if ($contact->contact_sub_type
) {
1292 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1294 array_unshift($contactTypes, $contact->contact_type
);
1296 return $contactTypes;
1299 CRM_Core_Error
::fatal();
1304 * Combine all the importable fields from the lower levels object.
1306 * The ordering is important, since currently we do not have a weight
1307 * scheme. Adding weight is super important
1309 * @param int|string $contactType contact Type
1310 * @param bool $status
1311 * Status is used to manipulate first title.
1312 * @param bool $showAll
1313 * If true returns all fields (includes disabled fields).
1314 * @param bool $isProfile
1315 * If its profile mode.
1316 * @param bool $checkPermission
1317 * If false, do not include permissioning clause (for custom data).
1319 * @param bool $withMultiCustomFields
1322 * array of importable Fields
1324 public static function importableFields(
1325 $contactType = 'Individual',
1329 $checkPermission = TRUE,
1330 $withMultiCustomFields = FALSE
1332 if (empty($contactType)) {
1333 $contactType = 'All';
1336 $cacheKeyString = "importableFields $contactType";
1337 $cacheKeyString .= $status ?
'_1' : '_0';
1338 $cacheKeyString .= $showAll ?
'_1' : '_0';
1339 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1340 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1341 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1343 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields) ?
: Civi
::cache('fields')->get($cacheKeyString);
1346 $fields = CRM_Contact_DAO_Contact
::import();
1348 // get the fields thar are meant for contact types
1349 if (in_array($contactType, [
1355 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1358 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1359 CRM_Core_DAO_Phone
::import(),
1360 CRM_Core_DAO_Email
::import(),
1361 CRM_Core_DAO_IM
::import(TRUE),
1362 CRM_Core_DAO_OpenID
::import()
1365 $locationFields = array_merge($locationFields,
1366 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1374 foreach ($locationFields as $key => $field) {
1375 $locationFields[$key]['hasLocationType'] = TRUE;
1378 $fields = array_merge($fields, $locationFields);
1380 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1381 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1384 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1385 $fields['url']['hasWebsiteType'] = TRUE;
1387 if ($contactType != 'All') {
1388 $fields = array_merge($fields,
1389 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1394 $withMultiCustomFields
1397 //unset the fields, which are not related to their
1404 'organization_name',
1416 'organization_name',
1439 foreach ($commonValues[$contactType] as $value) {
1440 unset($fields[$value]);
1444 foreach (['Individual', 'Household', 'Organization'] as $type) {
1445 $fields = array_merge($fields,
1446 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1451 $withMultiCustomFields
1458 $fields = array_merge($fields, [
1460 'title' => ts('Group(s)'),
1464 'title' => ts('Tag(s)'),
1468 'title' => ts('Note'),
1471 'communication_style_id' => [
1472 'title' => ts('Communication Style'),
1473 'name' => 'communication_style_id',
1478 //Sorting fields in alphabetical order(CRM-1507)
1479 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1481 Civi
::cache('fields')->set($cacheKeyString, $fields);
1484 self
::$_importableFields[$cacheKeyString] = $fields;
1488 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1489 self
::$_importableFields[$cacheKeyString]
1493 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1494 self
::$_importableFields[$cacheKeyString]
1502 * Combine all the exportable fields from the lower levels object.
1504 * Currently we are using importable fields as exportable fields
1506 * @param int|string $contactType contact Type
1507 * @param bool $status
1508 * True while exporting primary contacts.
1509 * @param bool $export
1510 * True when used during export.
1511 * @param bool $search
1512 * True when used during search, might conflict with export param?.
1514 * @param bool $withMultiRecord
1515 * @param bool $checkPermissions
1518 * array of exportable Fields
1520 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1521 if (empty($contactType)) {
1522 $contactType = 'All';
1525 $cacheKeyString = "exportableFields $contactType";
1526 $cacheKeyString .= $export ?
'_1' : '_0';
1527 $cacheKeyString .= $status ?
'_1' : '_0';
1528 $cacheKeyString .= $search ?
'_1' : '_0';
1529 $cacheKeyString .= '_' . (bool) $checkPermissions;
1530 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1531 //calculates custom fields takes into account the logged in user & caches that for all users
1532 //as an interim fix we will cache the fields by contact
1533 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1535 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1536 if (!self
::$_exportableFields) {
1537 self
::$_exportableFields = [];
1540 // check if we can retrieve from database cache
1541 $fields = Civi
::cache('fields')->get($cacheKeyString);
1544 $fields = CRM_Contact_DAO_Contact
::export();
1546 // The fields are meant for contact types.
1547 if (in_array($contactType, [
1553 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1555 // add current employer for individuals
1556 $fields = array_merge($fields, [
1557 'current_employer' =>
1559 'name' => 'organization_name',
1560 'title' => ts('Current Employer'),
1565 'location_type' => [
1566 'name' => 'location_type',
1567 'where' => 'civicrm_location_type.name',
1568 'title' => ts('Location Type'),
1574 'name' => 'im_provider',
1575 'where' => 'civicrm_im.provider_id',
1576 'title' => ts('IM Provider'),
1580 $locationFields = array_merge($locationType,
1581 CRM_Core_DAO_Address
::export(),
1582 CRM_Core_DAO_Phone
::export(),
1583 CRM_Core_DAO_Email
::export(),
1585 CRM_Core_DAO_IM
::export(TRUE),
1586 CRM_Core_DAO_OpenID
::export()
1589 $locationFields = array_merge($locationFields,
1590 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1593 foreach ($locationFields as $key => $field) {
1594 $locationFields[$key]['hasLocationType'] = TRUE;
1597 $fields = array_merge($fields, $locationFields);
1600 $fields = array_merge($fields,
1601 CRM_Core_DAO_Worldregion
::export()
1604 $fields = array_merge($fields,
1605 CRM_Contact_DAO_Contact
::export()
1609 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1611 if ($contactType != 'All') {
1612 $fields = array_merge($fields,
1613 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1617 foreach (['Individual', 'Household', 'Organization'] as $type) {
1618 $fields = array_merge($fields,
1619 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1623 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1626 $fields = array_merge($fields, [
1628 'title' => ts('Group(s)'),
1632 'title' => ts('Tag(s)'),
1636 'title' => ts('Note(s)'),
1642 $fields = array_merge($fields, [
1644 'title' => ts('Group(s)'),
1648 'title' => ts('Tag(s)'),
1652 'title' => ts('Note(s)'),
1658 //Sorting fields in alphabetical order(CRM-1507)
1659 foreach ($fields as $k => $v) {
1660 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1663 $fields = array_merge($sortArray, $fields);
1664 //unset the field which are not related to their contact type.
1665 if ($contactType != 'All') {
1671 'organization_name',
1672 'email_greeting_custom',
1673 'postal_greeting_custom',
1686 'organization_name',
1694 'email_greeting_custom',
1695 'postal_greeting_custom',
1711 'email_greeting_custom',
1712 'postal_greeting_custom',
1722 foreach ($commonValues[$contactType] as $value) {
1723 unset($fields[$value]);
1727 Civi
::cache('fields')->set($cacheKeyString, $fields);
1729 self
::$_exportableFields[$cacheKeyString] = $fields;
1733 $fields = self
::$_exportableFields[$cacheKeyString];
1736 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1737 self
::$_exportableFields[$cacheKeyString]
1745 * Get the all contact details (Hierarchical).
1747 * @param int $contactId
1749 * @param array $fields
1755 public static function getHierContactDetails($contactId, $fields) {
1756 $params = [['contact_id', '=', $contactId, 0, 0]];
1758 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1760 // We don't know the contents of return properties, but we need the lower
1761 // level ids of the contact so add a few fields.
1762 $returnProperties['first_name'] = 1;
1763 $returnProperties['organization_name'] = 1;
1764 $returnProperties['household_name'] = 1;
1765 $returnProperties['contact_type'] = 1;
1766 $returnProperties['contact_sub_type'] = 1;
1767 list($query) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties);
1772 * Given a set of flat profile style field names, create a hierarchy.
1774 * This is for the query to use, create the right sql.
1777 * @param int $contactId
1781 * A hierarchical property tree if appropriate
1783 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1784 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1786 $returnProperties = [];
1788 $multipleFields = ['website' => 'url'];
1789 foreach ($fields as $name => $dontCare) {
1790 if (strpos($name, '-') !== FALSE) {
1791 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1793 if (!in_array($fieldName, $multipleFields)) {
1794 if ($id == 'Primary') {
1795 $locationTypeName = 1;
1798 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1799 if (!$locationTypeName) {
1804 if (empty($returnProperties['location'])) {
1805 $returnProperties['location'] = [];
1807 if (empty($returnProperties['location'][$locationTypeName])) {
1808 $returnProperties['location'][$locationTypeName] = [];
1809 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1811 if (in_array($fieldName, [
1819 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1822 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1825 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1826 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1829 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1833 $returnProperties['website'][$id][$fieldName] = 1;
1837 $returnProperties[$name] = 1;
1841 return $returnProperties;
1845 * Return the primary location type of a contact.
1847 * $params int $contactId contact_id
1848 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1849 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1851 * @param int $contactId
1852 * @param bool $skipDefaultPriamry
1853 * @param null $block
1856 * $locationType location_type_id
1858 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1860 $entityBlock = ['contact_id' => $contactId];
1861 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1862 foreach ($blocks[$block] as $key => $value) {
1863 if (!empty($value['is_primary'])) {
1864 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1871 IF ( civicrm_email.location_type_id IS NULL,
1872 IF ( civicrm_address.location_type_id IS NULL,
1873 IF ( civicrm_phone.location_type_id IS NULL,
1874 IF ( civicrm_im.location_type_id IS NULL,
1875 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1876 ,civicrm_im.location_type_id)
1877 ,civicrm_phone.location_type_id)
1878 ,civicrm_address.location_type_id)
1879 ,civicrm_email.location_type_id) as locationType
1880 FROM civicrm_contact
1881 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1882 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1883 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1884 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1885 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1886 WHERE civicrm_contact.id = %1 ";
1888 $params = [1 => [$contactId, 'Integer']];
1890 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1892 $locationType = NULL;
1893 if ($dao->fetch()) {
1894 $locationType = $dao->locationType
;
1897 if (isset($locationType)) {
1898 return $locationType;
1900 elseif ($skipDefaultPriamry) {
1901 // if there is no primary contact location then return null
1905 // if there is no primart contact location, then return default
1906 // location type of the system
1907 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1908 return $defaultLocationType->id
;
1913 * Get the display name, primary email and location type of a contact.
1916 * Id of the contact.
1919 * Array of display_name, email if found, do_not_email or (null,null,null)
1921 public static function getContactDetails($id) {
1922 // check if the contact type
1923 $contactType = self
::getContactType($id);
1925 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1928 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1929 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1930 WHERE civicrm_contact.id = %1
1931 ORDER BY civicrm_email.is_primary DESC";
1932 $params = [1 => [$id, 'Integer']];
1933 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1935 if ($dao->fetch()) {
1936 if ($contactType == 'Individual') {
1937 if ($dao->first_name ||
$dao->last_name
) {
1938 $name = "{$dao->first_name} {$dao->last_name}";
1941 $name = $dao->display_name
;
1945 $name = $dao->display_name
;
1947 $email = $dao->email
;
1948 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1949 $onHold = $dao->on_hold ?
TRUE : FALSE;
1950 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1951 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1953 return [NULL, NULL, NULL, NULL, NULL];
1957 * Add/edit/register contacts through profile.
1959 * @param array $params
1960 * Array of profile fields to be edited/added.
1961 * @param array $fields
1962 * Array of fields from UFGroup.
1963 * @param int $contactID
1964 * Id of the contact to be edited/added.
1965 * @param int $addToGroupID
1966 * Specifies the default group to which contact is added.
1967 * @param int $ufGroupId
1968 * Uf group id (profile id).
1969 * @param string $ctype
1970 * @param bool $visibility
1971 * Basically lets us know where this request is coming from.
1972 * if via a profile from web, we restrict what groups are changed
1975 * contact id created/edited
1977 public static function createProfileContact(
1981 $addToGroupID = NULL,
1986 // add ufGroupID to params array ( CRM-2012 )
1988 $params['uf_group_id'] = $ufGroupId;
1990 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1992 // If a user has logged in, or accessed via a checksum
1993 // Then deliberately 'blanking' a value in the profile should remove it from their record
1994 $session = CRM_Core_Session
::singleton();
1995 $params['updateBlankLocInfo'] = TRUE;
1996 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1997 $params['updateBlankLocInfo'] = FALSE;
2002 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
2006 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
2009 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
2011 // manage is_opt_out
2012 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
2013 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
2014 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
2015 $data['is_opt_out'] = $isOptOut;
2016 // on change, create new civicrm_subscription_history entry
2017 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2019 'contact_id' => $contactDetails['contact_id'],
2020 'status' => $isOptOut ?
'Removed' : 'Added',
2023 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2027 $contact = self
::create($data);
2029 // contact is null if the profile does not have any contact fields
2031 $contactID = $contact->id
;
2034 if (empty($contactID)) {
2035 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
2038 // Process group and tag
2039 if (!empty($fields['group'])) {
2041 // this for sure means we are coming in via profile since i added it to fix
2042 // removing contacts from user groups -- lobo
2046 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2049 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2050 // Convert comma separated form values from select2 v3
2051 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2052 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2055 //to add profile in default group
2056 if (is_array($addToGroupID)) {
2057 $contactIds = [$contactID];
2058 foreach ($addToGroupID as $groupId) {
2059 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2062 elseif ($addToGroupID) {
2063 $contactIds = [$contactID];
2064 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2067 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
2070 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2073 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2079 * Format profile contact parameters.
2081 * @param array $params
2083 * @param int $contactID
2084 * @param int $ufGroupId
2085 * @param null $ctype
2086 * @param bool $skipCustom
2090 public static function formatProfileContactParams(
2099 $data = $contactDetails = [];
2101 // get the contact details (hier)
2103 $details = self
::getHierContactDetails($contactID, $fields);
2105 $contactDetails = $details[$contactID];
2106 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
2107 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
2110 //we should get contact type only if contact
2112 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2114 //special case to handle profile with only contact fields
2115 if ($data['contact_type'] == 'Contact') {
2116 $data['contact_type'] = 'Individual';
2118 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2119 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2123 $data['contact_type'] = $ctype;
2126 $data['contact_type'] = 'Individual';
2130 //fix contact sub type CRM-5125
2131 if (array_key_exists('contact_sub_type', $params) &&
2132 !empty($params['contact_sub_type'])
2134 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2136 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2137 !empty($params['contact_sub_type_hidden'])
2139 // if profile was used, and had any subtype, we obtain it from there
2140 //CRM-13596 - add to existing contact types, rather than overwriting
2141 if (empty($data['contact_sub_type'])) {
2142 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2143 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2146 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2147 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2148 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2149 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2150 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2155 if ($ctype == 'Organization') {
2156 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2158 elseif ($ctype == 'Household') {
2159 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2167 $data['contact_id'] = $contactID;
2168 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2171 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2172 $defaultLocationId = $defaultLocation->id
;
2175 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2177 $blocks = ['email', 'phone', 'im', 'openid'];
2179 $multiplFields = ['url'];
2180 // prevent overwritten of formatted array, reset all block from
2181 // params if it is not in valid format (since import pass valid format)
2182 foreach ($blocks as $blk) {
2183 if (array_key_exists($blk, $params) &&
2184 !is_array($params[$blk])
2186 unset($params[$blk]);
2190 $primaryPhoneLoc = NULL;
2191 $session = CRM_Core_Session
::singleton();
2192 foreach ($params as $key => $value) {
2193 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2195 if ($locTypeId == 'Primary') {
2197 if (in_array($fieldName, $blocks)) {
2198 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2201 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2203 $primaryLocationType = $locTypeId;
2206 $locTypeId = $defaultLocationId;
2210 if (is_numeric($locTypeId) &&
2211 !in_array($fieldName, $multiplFields) &&
2212 substr($fieldName, 0, 7) != 'custom_'
2214 $index = $locTypeId;
2216 if (is_numeric($typeId)) {
2217 $index .= '-' . $typeId;
2219 if (!in_array($index, $locationType)) {
2220 $locationType[$count] = $index;
2224 $loc = CRM_Utils_Array
::key($index, $locationType);
2226 $blockName = self
::getLocationEntityForKey($fieldName);
2228 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2230 //set is_billing true, for location type "Billing"
2231 if ($locTypeId == $billingLocationTypeId) {
2232 $data[$blockName][$loc]['is_billing'] = 1;
2236 //get the primary location type
2237 if ($locTypeId == $primaryLocationType) {
2238 $data[$blockName][$loc]['is_primary'] = 1;
2241 elseif ($locTypeId == $defaultLocationId) {
2242 $data[$blockName][$loc]['is_primary'] = 1;
2245 if (in_array($fieldName, ['phone'])) {
2247 $data['phone'][$loc]['phone_type_id'] = $typeId;
2250 $data['phone'][$loc]['phone_type_id'] = '';
2252 $data['phone'][$loc]['phone'] = $value;
2254 //special case to handle primary phone with different phone types
2255 // in this case we make first phone type as primary
2256 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2257 $primaryPhoneLoc = $loc;
2260 if ($loc != $primaryPhoneLoc) {
2261 unset($data['phone'][$loc]['is_primary']);
2264 elseif ($fieldName == 'email') {
2265 $data['email'][$loc]['email'] = $value;
2266 if (empty($contactID)) {
2267 $data['email'][$loc]['is_primary'] = 1;
2270 elseif ($fieldName == 'im') {
2271 if (isset($params[$key . '-provider_id'])) {
2272 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2274 if (strpos($key, '-provider_id') !== FALSE) {
2275 $data['im'][$loc]['provider_id'] = $params[$key];
2278 $data['im'][$loc]['name'] = $value;
2281 elseif ($fieldName == 'openid') {
2282 $data['openid'][$loc]['openid'] = $value;
2285 if ($fieldName === 'state_province') {
2287 if (is_numeric($value) && ((int ) $value) >= 1000) {
2288 $data['address'][$loc]['state_province_id'] = $value;
2290 elseif (empty($value)) {
2291 $data['address'][$loc]['state_province_id'] = '';
2294 $data['address'][$loc]['state_province'] = $value;
2297 elseif ($fieldName === 'country') {
2299 if (is_numeric($value) && ((int ) $value) >= 1000
2301 $data['address'][$loc]['country_id'] = $value;
2303 elseif (empty($value)) {
2304 $data['address'][$loc]['country_id'] = '';
2307 $data['address'][$loc]['country'] = $value;
2310 elseif ($fieldName === 'county') {
2311 $data['address'][$loc]['county_id'] = $value;
2313 elseif ($fieldName == 'address_name') {
2314 $data['address'][$loc]['name'] = $value;
2316 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2317 $data['address'][$loc][substr($fieldName, 8)] = $value;
2320 $data[$blockName][$loc][$fieldName] = $value;
2325 if (substr($key, 0, 4) === 'url-') {
2326 $websiteField = explode('-', $key);
2327 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2328 $data['website'][$websiteField[1]]['url'] = $value;
2330 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2331 //save email/postal greeting and addressee values if any, CRM-4575
2332 $data[$key . '_id'] = $value;
2334 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2335 // for autocomplete transfer hidden value instead of label
2336 if ($params[$key] && isset($params[$key . '_id'])) {
2337 $value = $params[$key . '_id'];
2340 // we need to append time with date
2341 if ($params[$key] && isset($params[$key . '_time'])) {
2342 $value .= ' ' . $params[$key . '_time'];
2345 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2346 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2347 ($value == '' ||
!isset($value))
2353 if (!empty($params['customRecordValues'])) {
2354 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2355 foreach ($params['customRecordValues'] as $recId => $customFields) {
2356 if (is_array($customFields) && !empty($customFields)) {
2357 foreach ($customFields as $customFieldName) {
2358 if ($customFieldName == $key) {
2368 //CRM-13596 - check for contact_sub_type_hidden first
2369 if (array_key_exists('contact_sub_type_hidden', $params)) {
2370 $type = $params['contact_sub_type_hidden'];
2373 $type = $data['contact_type'];
2374 if (!empty($data['contact_sub_type'])) {
2375 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2379 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2389 elseif ($key === 'edit') {
2393 if ($key === 'location') {
2394 foreach ($value as $locationTypeId => $field) {
2395 foreach ($field as $block => $val) {
2396 if ($block === 'address' && array_key_exists('address_name', $val)) {
2397 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2402 if ($key === 'phone' && isset($params['phone_ext'])) {
2403 $data[$key] = $value;
2404 foreach ($value as $cnt => $phoneBlock) {
2405 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2406 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2410 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2411 && ($value == '' ||
!isset($value)) &&
2412 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2413 ($key === 'current_employer' && empty($params['current_employer']))) {
2414 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2415 // to avoid update with empty values
2419 $data[$key] = $value;
2425 if (!isset($data['contact_type'])) {
2426 $data['contact_type'] = 'Individual';
2429 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2430 $privacy = CRM_Core_SelectValues
::privacy();
2431 foreach ($privacy as $key => $value) {
2432 if (array_key_exists($key, $fields)) {
2433 // do not reset values for existing contacts, if fields are added to a profile
2434 if (array_key_exists($key, $params)) {
2435 $data[$key] = $params[$key];
2436 if (empty($params[$key])) {
2440 elseif (!$contactID) {
2446 return [$data, $contactDetails];
2450 * Find the get contact details.
2452 * This function does not respect ACLs for now, which might need to be rectified at some
2453 * stage based on how its used.
2455 * @param string $mail
2456 * Primary email address of the contact.
2457 * @param string $ctype
2460 * @return object|null
2461 * $dao contact details
2463 public static function matchContactOnEmail($mail, $ctype = NULL) {
2464 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2465 $mail = $strtolower(trim($mail));
2467 SELECT civicrm_contact.id as contact_id,
2468 civicrm_contact.hash as hash,
2469 civicrm_contact.contact_type as contact_type,
2470 civicrm_contact.contact_sub_type as contact_sub_type
2471 FROM civicrm_contact
2472 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2474 if (Civi
::settings()->get('uniq_email_per_site')) {
2475 // try to find a match within a site (multisite).
2476 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2477 if (!empty($groups)) {
2479 INNER JOIN civicrm_group_contact gc ON
2480 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2485 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2486 $p = [1 => [$mail, 'String']];
2489 $query .= " AND civicrm_contact.contact_type = %3";
2490 $p[3] = [$ctype, 'String'];
2493 $query .= " ORDER BY civicrm_email.is_primary DESC";
2495 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2497 if ($dao->fetch()) {
2504 * Find the contact details associated with an OpenID.
2506 * @param string $openId
2507 * OpenId of the contact.
2508 * @param string $ctype
2511 * @return object|null
2512 * $dao contact details
2514 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2515 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2516 $openId = $strtolower(trim($openId));
2518 SELECT civicrm_contact.id as contact_id,
2519 civicrm_contact.hash as hash,
2520 civicrm_contact.contact_type as contact_type,
2521 civicrm_contact.contact_sub_type as contact_sub_type
2522 FROM civicrm_contact
2523 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2524 WHERE civicrm_openid.openid = %1";
2525 $p = [1 => [$openId, 'String']];
2528 $query .= " AND civicrm_contact.contact_type = %3";
2529 $p[3] = [$ctype, 'String'];
2532 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2534 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2536 if ($dao->fetch()) {
2543 * Get primary email of the contact.
2545 * @param int $contactID
2549 * Email address if present else null
2551 public static function getPrimaryEmail($contactID) {
2552 // fetch the primary email
2554 SELECT civicrm_email.email as email
2555 FROM civicrm_contact
2556 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2557 WHERE civicrm_email.is_primary = 1
2558 AND civicrm_contact.id = %1";
2559 $p = [1 => [$contactID, 'Integer']];
2560 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2563 if ($dao->fetch()) {
2564 $email = $dao->email
;
2570 * Function to get primary OpenID of the contact.
2572 * @param int $contactID
2576 * >openid OpenID if present else null
2578 public static function getPrimaryOpenId($contactID) {
2579 // fetch the primary OpenID
2581 SELECT civicrm_openid.openid as openid
2582 FROM civicrm_contact
2583 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2584 WHERE civicrm_contact.id = %1
2585 AND civicrm_openid.is_primary = 1";
2586 $p = [1 => [$contactID, 'Integer']];
2587 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2590 if ($dao->fetch()) {
2591 $openId = $dao->openid
;
2597 * Fetch the object and store the values in the values array.
2599 * @param array $params
2600 * Input parameters to find object.
2601 * @param array $values
2602 * Output values of the object.
2604 * @return CRM_Contact_BAO_Contact|null
2605 * The found object or null
2607 public static function getValues(&$params, &$values) {
2608 $contact = new CRM_Contact_BAO_Contact();
2610 $contact->copyValues($params);
2612 if ($contact->find(TRUE)) {
2614 CRM_Core_DAO
::storeValues($contact, $values);
2617 foreach (self
::$_commPrefs as $name) {
2618 if (isset($contact->$name)) {
2619 $privacy[$name] = $contact->$name;
2623 if (!empty($privacy)) {
2624 $values['privacy'] = $privacy;
2627 // communication Prefferance
2628 $preffComm = $comm = [];
2629 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2630 $contact->preferred_communication_method
2632 foreach ($comm as $value) {
2633 $preffComm[$value] = 1;
2635 $temp = ['preferred_communication_method' => $contact->preferred_communication_method
];
2638 'preferred_communication_method' => [
2639 'newName' => 'preferred_communication_method_display',
2640 'groupName' => 'preferred_communication_method',
2644 // @todo This can be figured out from metadata & we can avoid the uncached query.
2645 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2647 $values['preferred_communication_method'] = $preffComm;
2648 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2650 if ($contact->preferred_mail_format
) {
2651 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2652 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2655 // get preferred languages
2656 if (!empty($contact->preferred_language
)) {
2657 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2660 // Calculating Year difference
2661 if ($contact->birth_date
) {
2662 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2663 if ($birthDate < date('Ymd')) {
2664 $age = CRM_Utils_Date
::calculateAge($birthDate);
2665 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2666 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2670 $contact->contact_id
= $contact->id
;
2678 * Given the component name and returns the count of participation of contact.
2680 * @param string $component
2681 * Input component name.
2682 * @param int $contactId
2684 * @param string $tableName
2685 * Optional tableName if component is custom group.
2688 * total number in database
2690 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2692 switch ($component) {
2694 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2697 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2698 CRM_Contact_BAO_Relationship
::CURRENT
,
2707 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2710 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2713 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2716 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2718 case 'contribution':
2719 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2722 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2725 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2728 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2731 return CRM_Case_BAO_Case
::caseCount($contactId);
2734 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2738 'contact_id' => $contactId,
2741 'context' => 'activity',
2743 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2746 $params = ['contact_id' => $contactId];
2747 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2750 $custom = explode('_', $component);
2751 if ($custom['0'] = 'custom') {
2753 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2755 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2756 return CRM_Core_DAO
::singleValueQuery($queryString);
2762 * Update contact greetings if an update has resulted in a custom field change.
2764 * @param array $updatedFields
2765 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2766 * @param array $contactParams
2767 * Parameters known about the contact. At minimum array('contact_id' => x).
2768 * Fields in this array will take precedence over DB fields (so far only
2769 * in the case of greeting id fields).
2771 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2772 $contactID = $contactParams['contact_id'];
2773 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2774 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2775 if (!empty($tokens['all']['contact'])) {
2776 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2777 if (!empty($affectedTokens)) {
2778 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2779 $contact = new CRM_Contact_BAO_Contact();
2780 $contact->id
= $contactID;
2781 CRM_Contact_BAO_Contact
::processGreetings($contact);
2787 * Process greetings and cache.
2789 * @param object $contact
2790 * Contact object after save.
2792 public static function processGreetings(&$contact) {
2794 //@todo this function does a lot of unnecessary loading.
2795 // ensureGreetingParamsAreSet now makes sure that the contact is
2796 // loaded and using updateGreetingsOnTokenFieldChange
2797 // allows us the possibility of only doing an update if required.
2799 // The contact object has not always required the
2800 // fields that are required to calculate greetings
2801 // so we need to retrieve it again.
2802 if ($contact->_query
!== FALSE) {
2803 $contact->find(TRUE);
2806 // store object values to an array
2807 $contactDetails = [];
2808 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2809 $contactDetails = [[$contact->id
=> $contactDetails]];
2811 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2812 $updateQueryString = [];
2814 //cache email and postal greeting to greeting display
2815 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2816 $emailGreetingString = $contact->email_greeting_custom
;
2818 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2819 // the filter value for Individual contact type is set to 1
2821 'contact_type' => $contact->contact_type
,
2822 'greeting_type' => 'email_greeting',
2825 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2826 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2827 $updateQueryString[] = " email_greeting_custom = NULL ";
2830 if ($contact->email_greeting_custom
) {
2831 $updateQueryString[] = " email_greeting_display = NULL ";
2835 if ($emailGreetingString) {
2836 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2839 'CRM_Contact_BAO_Contact'
2841 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2842 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2846 if ($contact->postal_greeting_custom
!== 'null' && $contact->postal_greeting_custom
) {
2847 $postalGreetingString = $contact->postal_greeting_custom
;
2849 elseif ($contact->postal_greeting_id
!== 'null' && $contact->postal_greeting_id
) {
2851 'contact_type' => $contact->contact_type
,
2852 'greeting_type' => 'postal_greeting',
2854 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2855 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2856 $updateQueryString[] = " postal_greeting_custom = NULL ";
2859 if ($contact->postal_greeting_custom
) {
2860 $updateQueryString[] = " postal_greeting_display = NULL ";
2864 if ($postalGreetingString) {
2865 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2868 'CRM_Contact_BAO_Contact'
2870 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2871 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2875 if ($contact->addressee_custom
!== 'null' && $contact->addressee_custom
) {
2876 $addresseeString = $contact->addressee_custom
;
2878 elseif ($contact->addressee_id
!== 'null' && $contact->addressee_id
) {
2880 'contact_type' => $contact->contact_type
,
2881 'greeting_type' => 'addressee',
2884 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2885 $addresseeString = $addressee[$contact->addressee_id
];
2886 $updateQueryString[] = " addressee_custom = NULL ";
2889 if ($contact->addressee_custom
) {
2890 $updateQueryString[] = " addressee_display = NULL ";
2894 if ($addresseeString) {
2895 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2898 'CRM_Contact_BAO_Contact'
2900 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2901 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2904 if (!empty($updateQueryString)) {
2905 $updateQueryString = implode(',', $updateQueryString);
2906 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2907 CRM_Core_DAO
::executeQuery($queryString);
2912 * Retrieve loc block ids w/ given condition.
2914 * @param int $contactId
2916 * @param array $criteria
2917 * Key => value pair which should be.
2918 * fulfill by return record ids.
2919 * @param string $condOperator
2920 * Operator use for grouping multiple conditions.
2923 * loc block ids which fulfill condition.
2925 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2928 return $locBlockIds;
2931 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2932 $name = strtolower($block);
2933 $className = "CRM_Core_DAO_$block";
2934 $blockDAO = new $className();
2936 // build the condition.
2937 if (is_array($criteria)) {
2938 $fields = $blockDAO->fields();
2940 foreach ($criteria as $field => $value) {
2941 if (array_key_exists($field, $fields)) {
2942 $cond = "( $field = $value )";
2943 // value might be zero or null.
2944 if (!$value ||
strtolower($value) === 'null') {
2945 $cond = "( $field = 0 OR $field IS NULL )";
2947 $conditions[] = $cond;
2950 if (!empty($conditions)) {
2951 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2955 $blockDAO->contact_id
= $contactId;
2957 while ($blockDAO->fetch()) {
2958 $locBlockIds[$name][] = $blockDAO->id
;
2962 return $locBlockIds;
2966 * Build context menu items.
2968 * @param int $contactId
2971 * Array of context menu for logged in user.
2973 public static function contextMenu($contactId = NULL) {
2976 'title' => ts('View Contact'),
2978 'ref' => 'view-contact',
2979 'class' => 'no-popup',
2981 'permissions' => ['view all contacts'],
2984 'title' => ts('Edit Contact'),
2986 'ref' => 'edit-contact',
2987 'class' => 'no-popup',
2989 'permissions' => ['edit all contacts'],
2992 'title' => ts('Delete Contact'),
2994 'ref' => 'delete-contact',
2996 'permissions' => ['access deleted contacts', 'delete contacts'],
2999 'title' => ts('Add Contribution'),
3001 'ref' => 'new-contribution',
3002 'key' => 'contribution',
3003 'tab' => 'contribute',
3004 'component' => 'CiviContribute',
3005 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
3006 'reset=1&action=add&context=contribution'
3009 'access CiviContribute',
3010 'edit contributions',
3014 'title' => ts('Register for Event'),
3016 'ref' => 'new-participant',
3017 'key' => 'participant',
3018 'tab' => 'participant',
3019 'component' => 'CiviEvent',
3020 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3023 'edit event participants',
3027 'title' => ts('Record Activity'),
3029 'ref' => 'new-activity',
3030 'key' => 'activity',
3031 'permissions' => ['edit all contacts'],
3034 'title' => ts('Add Pledge'),
3036 'ref' => 'new-pledge',
3039 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3040 'reset=1&action=add&context=pledge'
3042 'component' => 'CiviPledge',
3044 'access CiviPledge',
3049 'title' => ts('Add Membership'),
3051 'ref' => 'new-membership',
3052 'key' => 'membership',
3054 'component' => 'CiviMember',
3055 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3056 'reset=1&action=add&context=membership'
3059 'access CiviMember',
3064 'title' => ts('Add Case'),
3066 'ref' => 'new-case',
3069 'component' => 'CiviCase',
3070 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3071 'permissions' => ['add cases'],
3074 'title' => ts('Add Grant'),
3076 'ref' => 'new-grant',
3079 'component' => 'CiviGrant',
3080 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3081 'reset=1&action=add&context=grant'
3083 'permissions' => ['edit grants'],
3086 'title' => ts('Add Relationship'),
3088 'ref' => 'new-relationship',
3091 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3092 'reset=1&action=add'
3094 'permissions' => ['edit all contacts'],
3097 'title' => ts('Add Note'),
3099 'ref' => 'new-note',
3102 'class' => 'medium-popup',
3103 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3104 'reset=1&action=add'
3106 'permissions' => ['edit all contacts'],
3109 'title' => ts('Send an Email'),
3111 'ref' => 'new-email',
3113 'permissions' => ['view all contacts'],
3116 'title' => ts('Add to Group'),
3118 'ref' => 'group-add-contact',
3121 'permissions' => ['edit groups'],
3124 'title' => ts('Tag Contact'),
3126 'ref' => 'tag-contact',
3129 'permissions' => ['edit all contacts'],
3133 $menu['otherActions'] = [
3135 'title' => ts('Print Summary'),
3136 'description' => ts('Printer-friendly view of this page.'),
3138 'ref' => 'crm-contact-print',
3141 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3145 'icon' => 'crm-i fa-print',
3148 'title' => ts('vCard'),
3149 'description' => ts('vCard record for this contact.'),
3151 'ref' => 'crm-contact-vcard',
3154 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3158 'icon' => 'crm-i fa-list-alt',
3162 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3163 $menu['otherActions']['dashboard'] = [
3164 'title' => ts('Contact Dashboard'),
3165 'description' => ts('Contact Dashboard'),
3167 'ref' => 'crm-contact-dashboard',
3168 'key' => 'dashboard',
3169 'tab' => 'dashboard',
3170 'class' => 'dashboard',
3171 // NOTE: As an alternative you can also build url on CMS specific way
3172 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3173 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3174 'icon' => 'crm-i fa-tachometer',
3178 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3180 $menu['otherActions']['user-record'] = [
3181 'title' => ts('User Record'),
3182 'description' => ts('User Record'),
3184 'ref' => 'crm-contact-user-record',
3185 'key' => 'user-record',
3186 'tab' => 'user-record',
3187 'class' => 'user-record',
3188 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3189 'icon' => 'crm-i fa-user',
3192 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3193 $menu['otherActions']['user-add'] = [
3194 'title' => ts('Create User Record'),
3195 'description' => ts('Create User Record'),
3197 'ref' => 'crm-contact-user-add',
3198 'key' => 'user-add',
3199 'tab' => 'user-add',
3200 'class' => 'user-add',
3201 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3202 'icon' => 'crm-i fa-user-plus',
3206 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3207 //1. check for component is active.
3208 //2. check for user permissions.
3209 //3. check for acls.
3210 //3. edit and view contact are directly accessible to user.
3212 $aclPermissionedTasks = [
3217 'group-add-contact',
3221 $corePermission = CRM_Core_Permission
::getPermission();
3224 foreach ($menu as $key => $values) {
3225 if ($key !== 'otherActions') {
3227 // user does not have necessary permissions.
3228 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3231 // build directly accessible action menu.
3232 if (in_array($values['ref'], [
3236 $contextMenu['primaryActions'][$key] = [
3237 'title' => $values['title'],
3238 'ref' => $values['ref'],
3239 'class' => CRM_Utils_Array
::value('class', $values),
3240 'key' => $values['key'],
3245 // finally get menu item for -more- action widget.
3246 $contextMenu['moreActions'][$values['weight']] = [
3247 'title' => $values['title'],
3248 'ref' => $values['ref'],
3249 'href' => CRM_Utils_Array
::value('href', $values),
3250 'tab' => CRM_Utils_Array
::value('tab', $values),
3251 'class' => CRM_Utils_Array
::value('class', $values),
3252 'key' => $values['key'],
3256 foreach ($values as $value) {
3257 // user does not have necessary permissions.
3258 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3262 // finally get menu item for -more- action widget.
3263 $contextMenu['otherActions'][$value['weight']] = [
3264 'title' => $value['title'],
3265 'ref' => $value['ref'],
3266 'href' => CRM_Utils_Array
::value('href', $value),
3267 'tab' => CRM_Utils_Array
::value('tab', $value),
3268 'class' => CRM_Utils_Array
::value('class', $value),
3269 'icon' => CRM_Utils_Array
::value('icon', $value),
3270 'key' => $value['key'],
3276 ksort($contextMenu['moreActions']);
3277 ksort($contextMenu['otherActions']);
3279 return $contextMenu;
3283 * Check if user has permissions to access items in action menu.
3285 * @param array $aclPermissionedTasks
3286 * Array containing ACL related tasks.
3287 * @param string $corePermission
3288 * The permission of the user (edit or view or null).
3289 * @param array $menuOptions
3290 * Array containing params of the menu (title, href, etc).
3293 * TRUE if user has all permissions, FALSE if otherwise.
3295 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3296 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3298 // if component action - make sure component is enable.
3299 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3303 // make sure user has all required permissions.
3304 $hasAllPermissions = FALSE;
3306 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3307 if (!is_array($permissions) ||
empty($permissions)) {
3308 $hasAllPermissions = TRUE;
3311 // iterate for required permissions in given permissions array.
3312 if (!$hasAllPermissions) {
3313 $hasPermissions = 0;
3314 foreach ($permissions as $permission) {
3315 if (CRM_Core_Permission
::check($permission)) {
3320 if (count($permissions) == $hasPermissions) {
3321 $hasAllPermissions = TRUE;
3324 // if still user does not have required permissions, check acl.
3325 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3326 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3327 $corePermission == CRM_Core_Permission
::EDIT
3329 $hasAllPermissions = TRUE;
3331 elseif (in_array($menuOptions['ref'], [
3334 // grant permissions for these tasks.
3335 $hasAllPermissions = TRUE;
3340 return $hasAllPermissions;
3344 * Retrieve display name of contact that address is shared.
3346 * This is based on $masterAddressId or $contactId .
3348 * @param int $masterAddressId
3350 * @param int $contactId
3351 * Contact id. (deprecated - do not use)
3353 * @return string|null
3354 * the found display name or null.
3356 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3357 $masterDisplayName = NULL;
3358 if (!$masterAddressId) {
3359 return $masterDisplayName;
3363 SELECT display_name from civicrm_contact
3364 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3365 WHERE civicrm_address.id = " . $masterAddressId;
3367 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3368 return $masterDisplayName;
3372 * Get the creation/modification times for a contact.
3374 * @param int $contactId
3377 * Dates - ('created_date' => $, 'modified_date' => $)
3379 public static function getTimestamps($contactId) {
3380 $timestamps = CRM_Core_DAO
::executeQuery(
3381 'SELECT created_date, modified_date
3382 FROM civicrm_contact
3385 1 => [$contactId, 'Integer'],
3388 if ($timestamps->fetch()) {
3390 'created_date' => $timestamps->created_date
,
3391 'modified_date' => $timestamps->modified_date
,
3400 * Get a list of triggers for the contact table.
3403 * @param null $tableName
3405 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3407 * @see hook_civicrm_triggerInfo
3408 * @see CRM_Core_DAO::triggerRebuild
3410 public static function triggerInfo(&$info, $tableName = NULL) {
3411 //during upgrade, first check for valid version and then create triggers
3412 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3413 if (CRM_Core_Config
::isUpgradeMode()) {
3414 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3415 //if current version is less than 4.3.alpha1 dont create below triggers
3416 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3421 // Modifications to these records should update the contact timestamps.
3422 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3424 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3425 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3426 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3427 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3428 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3430 ->alterTriggerInfo($info, $tableName);
3432 // Update phone table to populate phone_numeric field
3433 if (!$tableName ||
$tableName == 'civicrm_phone') {
3434 // Define stored sql function needed for phones
3435 $sqlTriggers = Civi
::service('sql_triggers');
3436 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3437 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3439 'table' => ['civicrm_phone'],
3441 'event' => ['INSERT', 'UPDATE'],
3442 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3448 * Check if contact is being used in civicrm_domain based on $contactId.
3450 * @param int $contactId
3454 * true if present else false.
3456 public static function checkDomainContact($contactId) {
3460 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3471 * Get options for a given contact field.
3473 * @param string $fieldName
3474 * @param string $context
3475 * @param array $props
3476 * whatever is known about this dao object.
3478 * @return array|bool
3479 * @see CRM_Core_DAO::buildOptions
3481 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3482 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3484 * @see CRM_Core_DAO::buildOptionsContext
3486 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3488 // Special logic for fields whose options depend on context or properties
3489 switch ($fieldName) {
3490 case 'contact_sub_type':
3491 if (!empty($props['contact_type'])) {
3492 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3496 case 'contact_type':
3497 if ($context == 'search') {
3498 // CRM-15495 - EntityRef filters and basic search forms expect this format
3499 // FIXME: Search builder does not
3500 return CRM_Contact_BAO_ContactType
::getSelectElements();
3504 // The contact api supports some related entities so we'll honor that by fetching their options
3507 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3511 $props['entity_table'] = 'civicrm_contact';
3512 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3514 case 'state_province_id':
3515 case 'state_province':
3516 case 'state_province_name':
3521 case 'worldregion_id':
3522 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3525 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3529 * Delete a contact-related object that has an 'is_primary' field.
3531 * Ensures that is_primary gets assigned to another object if available
3532 * Also calls pre/post hooks
3534 * @param string $type
3539 public static function deleteObjectWithPrimary($type, $id) {
3540 if (!$id ||
!is_numeric($id)) {
3543 $daoName = "CRM_Core_DAO_$type";
3544 $obj = new $daoName();
3548 if ($obj->fetch()) {
3549 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3550 $contactId = $obj->contact_id
;
3556 // is_primary is only relavent if this field belongs to a contact
3558 $dao = new $daoName();
3559 $dao->contact_id
= $contactId;
3560 $dao->is_primary
= 1;
3561 // Pick another record to be primary (if one isn't already)
3562 if (!$dao->find(TRUE)) {
3563 $dao->is_primary
= 0;
3565 if ($dao->fetch()) {
3566 $dao->is_primary
= 1;
3571 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3578 public function addSelectWhereClause() {
3579 // We always return an array with these keys, even if they are empty,
3580 // because this tells the query builder that we have considered these fields for acls
3582 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3583 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
[] : ['!= 1'],
3585 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3590 * Get any existing duplicate contacts based on the input parameters.
3592 * @param array $input
3593 * Input parameters to be matched.
3594 * @param string $contactType
3595 * @param string $rule
3598 * @param $excludedContactIDs
3599 * An array of ids not to be included in the results.
3600 * @param bool $checkPermissions
3601 * @param int $ruleGroupID
3602 * ID of the rule group to be used if an override is desirable.
3603 * @param array $contextParams
3604 * The context if relevant, eg. ['event_id' => X]
3608 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3609 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3610 $dedupeParams['check_permission'] = $checkPermissions;
3611 $dedupeParams['contact_type'] = $contactType;
3612 $dedupeParams['rule'] = $rule;
3613 $dedupeParams['rule_group_id'] = $ruleGroupID;
3614 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3615 $dedupeResults['ids'] = [];
3616 $dedupeResults['handled'] = FALSE;
3617 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3618 if (!$dedupeResults['handled']) {
3619 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3621 return $dedupeResults['ids'];
3625 * Get the first duplicate contacts based on the input parameters.
3627 * @param array $input
3628 * Input parameters to be matched.
3629 * @param string $contactType
3630 * @param string $rule
3633 * @param $excludedContactIDs
3634 * An array of ids not to be included in the results.
3635 * @param bool $checkPermissions
3636 * @param int $ruleGroupID
3637 * ID of the rule group to be used if an override is desirable.
3638 * @param array $contextParams
3639 * The context if relevant, eg. ['event_id' => X]
3643 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3644 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3652 * Check if a field is associated with an entity that has a location type.
3654 * (ie. is an address, phone, email etc field).
3656 * @param string $fieldTitle
3657 * Title of the field (not the name - create a new function for that if required).
3661 public static function isFieldHasLocationType($fieldTitle) {
3662 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3663 if ($field['title'] === $fieldTitle) {
3664 return CRM_Utils_Array
::value('hasLocationType', $field);
3671 * @param array $appendProfiles
3672 * Name of profile(s) to append to each link.
3676 public static function getEntityRefCreateLinks($appendProfiles = []) {
3677 // You'd think that "create contacts" would be the permission to check,
3678 // But new contact popups are profile forms and those use their own permissions.
3679 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3683 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3684 $profiles[] = 'new_' . strtolower($contactType);
3686 $retrieved = civicrm_api3('uf_group', 'get', [
3687 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3690 $links = $append = [];
3691 if (!empty($retrieved['values'])) {
3693 'individual' => 'fa-user',
3694 'organization' => 'fa-building',
3695 'household' => 'fa-home',
3697 foreach ($retrieved['values'] as $id => $profile) {
3698 if (in_array($profile['name'], $profiles)) {
3700 'label' => $profile['title'],
3701 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3702 NULL, NULL, FALSE, FALSE, TRUE),
3703 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3704 'icon' => CRM_Utils_Array
::value(str_replace('new_', '', $profile['name']), $icons),
3711 foreach ($append as $id) {
3712 foreach ($links as &$link) {
3713 $link['url'] .= ",$id";
3723 public static function getEntityRefFilters() {
3725 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3726 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3727 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3728 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3729 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3730 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3731 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3732 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3733 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3734 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],