3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
{
20 * SQL function used to format the phone_numeric field via trigger.
22 * @see self::triggerInfo()
24 * Note that this is also used by the 4.3 upgrade script.
25 * @see CRM_Upgrade_Incremental_php_FourThree
27 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
29 const CREATE_STRIP_FUNCTION_43
= "
30 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
31 RETURNS VARCHAR(255) CHARACTER SET utf8
35 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
36 DECLARE iterator INT DEFAULT 1;
37 WHILE iterator < (LENGTH(input) + 1) DO
38 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
39 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
41 SET iterator = iterator + 1;
47 * The types of communication preferences.
51 public static $_commPrefs = [
64 public static $_greetingTypes = [
71 * Static field for all the contact information that we can potentially import.
75 public static $_importableFields = [];
78 * Static field for all the contact information that we can potentially export.
82 public static $_exportableFields = NULL;
87 public function __construct() {
88 parent
::__construct();
92 * Takes an associative array and creates a contact object.
94 * The function extracts all the params it needs to initialize the create a
95 * contact object. the params array could contain additional unused name/value
98 * @param array $params
99 * (reference) an assoc array of name/value pairs.
101 * @return CRM_Contact_DAO_Contact|CRM_Core_Error|NULL
102 * Created or updated contact object or error object.
103 * (error objects are being phased out in favour of exceptions)
106 public static function add(&$params) {
107 $contact = new CRM_Contact_DAO_Contact();
108 $contactID = CRM_Utils_Array
::value('contact_id', $params);
109 if (empty($params)) {
113 // Fix for validate contact sub type CRM-5143.
114 if (isset($params['contact_sub_type'])) {
115 if (empty($params['contact_sub_type'])) {
116 $params['contact_sub_type'] = 'null';
118 elseif ($params['contact_sub_type'] !== 'null') {
119 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
120 $params['contact_type'], TRUE
123 // we'll need to fix tests to handle this
125 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
= $contactID;
152 if ($contact->contact_type
=== 'Individual') {
154 // @todo allow the lines below to be overridden by input or hooks & add tests,
155 // as has been done for households and organizations.
156 // Format individual fields.
157 CRM_Contact_BAO_Individual
::format($params, $contact);
160 if (strlen($contact->display_name
) > 128) {
161 $contact->display_name
= substr($contact->display_name
, 0, 128);
163 if (strlen($contact->sort_name
) > 128) {
164 $contact->sort_name
= substr($contact->sort_name
, 0, 128);
167 $privacy = CRM_Utils_Array
::value('privacy', $params);
169 is_array($privacy) &&
173 foreach (self
::$_commPrefs as $name) {
174 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
178 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
179 // @todo - does this mean we can remove this block?
180 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
181 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
183 $contact->hash
= md5(uniqid(rand(), TRUE));
186 // Even if we don't need $employerId, it's important to call getFieldValue() before
187 // the contact is saved because we want the existing value to be cached.
188 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
189 $employerId = (!$contactID ||
$contact->contact_type
!== 'Individual') ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
194 CRM_Core_BAO_Log
::register($contact->id
,
200 if ($contact->contact_type
=== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
201 // Create current employer.
202 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
205 if (empty($params['contact_id'])) {
209 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
213 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
218 // Update cached employer name if the name of an existing organization is being updated.
219 if ($contact->contact_type
=== 'Organization' && !empty($params['organization_name']) && $contactID) {
220 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
229 * takes an associative array and creates a contact object and all the associated
230 * derived objects (i.e. individual, location, email, phone etc)
232 * This function is invoked from within the web form layer and also from the api layer
234 * @param array $params
235 * (reference ) an assoc array of name/value pairs.
236 * @param bool $fixAddress
237 * If we need to fix address.
238 * @param bool $invokeHooks
239 * If we need to invoke hooks.
241 * @param bool $skipDelete
242 * Unclear parameter, passed to website create
244 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
245 * Created or updated contribution object. We are deprecating returning an error in
246 * favour of exceptions
248 * @todo explain this parameter
251 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
253 if (empty($params['contact_type']) && empty($params['contact_id'])) {
257 $isEdit = !empty($params['contact_id']);
259 if ($isEdit && empty($params['contact_type'])) {
260 $params['contact_type'] = self
::getContactType($params['contact_id']);
263 if (!empty($params['check_permissions']) && isset($params['api_key'])
264 && !CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])
265 && !($isEdit && CRM_Core_Permission
::check('edit own api keys') && $params['contact_id'] == CRM_Core_Session
::getLoggedInContactID())
267 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify api key');
271 if (!empty($params['contact_id'])) {
272 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
275 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
279 self
::ensureGreetingParamsAreSet($params);
281 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
282 if (empty($params['contact_id'])) {
283 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
284 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
285 $params['preferred_language'] = $language;
288 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
289 if (empty($params['communication_style_id'])) {
290 $defaultCommunicationStyleId = CRM_Core_OptionGroup
::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
291 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
295 $transaction = new CRM_Core_Transaction();
297 $contact = self
::add($params);
299 // 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 $transaction->commit();
398 // CRM-6367: fetch the right label for contact type’s display
399 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
400 'CRM_Contact_DAO_ContactType',
401 $contact->contact_type
,
406 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
410 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
413 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
417 // In order to prevent a series of expensive queries in intensive batch processing
418 // api calls may pass in skip_greeting_processing, probably doing it later via the
419 // scheduled job. CRM-21551
420 if (empty($params['skip_greeting_processing'])) {
421 self
::processGreetings($contact);
424 if (!empty($params['check_permissions'])) {
425 $contacts = [&$contact];
426 self
::unsetProtectedFields($contacts);
433 * Format the output of the create contact function
435 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
437 public static function unsetProtectedFields(&$contacts) {
438 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
439 $currentUser = CRM_Core_Session
::getLoggedInContactID();
440 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
441 foreach ($contacts as &$contact) {
442 $cid = is_object($contact) ?
$contact->id
: CRM_Utils_Array
::value('id', $contact);
443 if (!($editOwn && $cid == $currentUser)) {
444 if (is_object($contact)) {
445 unset($contact->api_key
);
448 unset($contact['api_key']);
456 * Ensure greeting parameters are set.
458 * By always populating greetings here we can be sure they are set if required & avoid a call later.
459 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
461 * @param array $params
463 * @throws \CiviCRM_API3_Exception
465 public static function ensureGreetingParamsAreSet(&$params) {
466 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
467 $missingGreetingParams = [];
469 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
470 if (empty($params[$greetingParam])) {
471 $missingGreetingParams[$greetingIndex] = $greetingParam;
475 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
476 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
477 'id' => $params['contact_id'],
478 'return' => array_keys($missingGreetingParams),
481 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
482 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
483 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
486 // Filter out other fields.
487 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
488 $params = array_merge($params, $savedGreetings);
491 foreach ($missingGreetingParams as $greetingName => $greeting) {
492 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
496 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
497 if ($params[$greetingParam] === 'null') {
498 // If we are setting it to null then null out the display field.
499 $params[$greetingIndex . '_display'] = 'null';
505 * Get the display name and image of a contact.
510 * @param bool $includeTypeInReturnParameters
511 * Should type be part of the returned array?
514 * the displayName and contactImage for this contact
516 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
517 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
519 SELECT civicrm_contact.*,
520 civicrm_email.email as email
522 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
523 AND civicrm_email.is_primary = 1
524 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
525 $dao = new CRM_Core_DAO();
528 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
529 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
531 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
532 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
535 // use email if display_name is empty
536 if (empty($dao->display_name
)) {
537 $displayName = $dao->email
;
540 $displayName = $dao->display_name
;
543 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
545 return $includeTypeInReturnParameters ?
[
549 $dao->contact_sub_type
,
551 ] : [$displayName, $image, $imageUrl];
557 * Add billing fields to the params if appropriate.
559 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
560 * don't then we should set the name fields to the billing fields AND add the preserveDBName
561 * parameter (which will tell the BAO only to set those fields if none already exist.
563 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
564 * matching is best done by hipsters.
566 * @param array $params
568 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
570 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
571 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
572 foreach ($nameFields as $field) {
573 if (!empty($params[$field])) {
577 // There are only 3 - we can iterate through them twice :-)
578 foreach ($nameFields as $field) {
579 if (!empty($params['billing_' . $field])) {
580 $params[$field] = $params['billing_' . $field];
582 $params['preserveDBName'] = TRUE;
588 * Resolve a state province string (UT or Utah) to an ID.
590 * If country has been passed in we should select a state belonging to that country.
592 * Alternatively we should choose from enabled countries, prioritising the default country.
594 * @param array $values
595 * @param int|null $countryID
599 * @throws \CRM_Core_Exception
601 protected static function resolveStateProvinceID($values, $countryID) {
604 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
605 if (CRM_Utils_Array
::lookupValue($values,
610 return $values['state_province_id'];
612 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
613 if (CRM_Utils_Array
::lookupValue($values,
618 return $values['state_province_id'];
623 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
624 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
625 // prefer matching country..
626 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, ['country_id' => Civi
::settings()->get('defaultContactCountry')]);
627 if (CRM_Utils_Array
::lookupValue($values,
632 return $values['state_province_id'];
635 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
636 if (CRM_Utils_Array
::lookupValue($values,
641 return $values['state_province_id'];
644 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
645 if (CRM_Utils_Array
::lookupValue($values,
650 return $values['state_province_id'];
652 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
653 if (CRM_Utils_Array
::lookupValue($values,
658 return $values['state_province_id'];
666 * Get the relevant location entity for the array key.
668 * Based on the field name we determine which location entity
669 * we are dealing with. Apart from a few specific ones they
670 * are mostly 'address' (the default).
672 * @param string $fieldName
676 protected static function getLocationEntityForKey($fieldName) {
677 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
680 if ($fieldName === 'phone_ext') {
687 * Create last viewed link to recently updated contact.
689 * @param array $crudLinkSpec
690 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
691 * - entity_table: string, eg "civicrm_contact"
695 * NULL if unavailable, or
696 * [path: string, query: string, title: string]
697 * @see CRM_Utils_System::createDefaultCrudLink
699 public function createDefaultCrudLink($crudLinkSpec) {
700 switch ($crudLinkSpec['action']) {
701 case CRM_Core_Action
::VIEW
:
703 'title' => $this->display_name
,
704 'path' => 'civicrm/contact/view',
712 case CRM_Core_Action
::UPDATE
:
714 'title' => $this->display_name
,
715 'path' => 'civicrm/contact/add',
718 'action' => 'update',
728 * Get the values for pseudoconstants for name->value and reverse.
730 * @param array $defaults
731 * (reference) the default values, some of which need to be resolved.
732 * @param bool $reverse
733 * Always true as this function is only called from one place..
737 * This is called specifically from the contact import parser & should be moved there
738 * as it is not truly a generic function.
741 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
742 // Hack for birth_date.
743 if (!empty($defaults['birth_date'])) {
744 if (is_array($defaults['birth_date'])) {
745 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
749 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
750 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
751 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
752 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
754 //lookup value of email/postal greeting, addressee, CRM-4575
755 foreach (self
::$_greetingTypes as $greeting) {
757 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
758 'greeting_type' => $greeting,
760 CRM_Utils_Array
::lookupValue($defaults, $greeting,
761 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
765 $blocks = ['address', 'im', 'phone'];
766 foreach ($blocks as $name) {
767 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
770 foreach ($defaults[$name] as $count => & $values) {
772 //get location type id.
773 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
775 if ($name == 'address') {
776 // FIXME: lookupValue doesn't work for vcard_name
777 if (!empty($values['location_type_id'])) {
778 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', ['labelColumn' => 'vcard_name']);
779 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
782 if (!CRM_Utils_Array
::lookupValue($values,
784 CRM_Core_PseudoConstant
::country(),
789 CRM_Utils_Array
::lookupValue($values,
791 CRM_Core_PseudoConstant
::countryIsoCode(),
795 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
796 if ($stateProvinceID) {
797 $values['state_province_id'] = $stateProvinceID;
800 if (!empty($values['state_province_id'])) {
801 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
804 $countyList = CRM_Core_PseudoConstant
::county();
806 CRM_Utils_Array
::lookupValue($values,
814 CRM_Utils_Array
::lookupValue($values,
816 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
821 if ($name == 'phone') {
822 CRM_Utils_Array
::lookupValue($values,
824 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
829 // Kill the reference.
836 * Fetch object based on array of properties.
838 * @param array $params
839 * (reference ) an assoc array of name/value pairs.
840 * @param array $defaults
841 * (reference ) an assoc array to hold the name / value pairs.
842 * in a hierarchical manner
843 * @param bool $microformat
844 * For location in microformat.
846 * @return CRM_Contact_BAO_Contact
848 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
849 if (array_key_exists('contact_id', $params)) {
850 $params['id'] = $params['contact_id'];
852 elseif (array_key_exists('id', $params)) {
853 $params['contact_id'] = $params['id'];
856 $contact = self
::getValues($params, $defaults);
858 unset($params['id']);
860 //get the block information for this contact
861 $entityBlock = ['contact_id' => $params['contact_id']];
862 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
863 $defaults = array_merge($defaults, $blocks);
864 foreach ($blocks as $block => $value) {
865 $contact->$block = $value;
868 if (!isset($params['noNotes'])) {
869 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
872 if (!isset($params['noRelationships'])) {
873 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
876 if (!isset($params['noGroups'])) {
877 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
880 if (!isset($params['noWebsite'])) {
881 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
888 * Get the display name of a contact.
893 * @return null|string
894 * display name of the contact if found
896 public static function displayName($id) {
899 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
906 * Delete a contact and all its associated records.
909 * Id of the contact to delete.
910 * @param bool $restore
911 * Whether to actually restore, not delete.
912 * @param bool $skipUndelete
913 * Whether to force contact delete or not.
914 * @param bool $checkPermissions
917 * Was contact deleted?
919 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
924 // If trash is disabled in system settings then we always skip
925 if (!Civi
::settings()->get('contact_undelete')) {
926 $skipUndelete = TRUE;
929 // make sure we have edit permission for this contact
931 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
932 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
938 // Restrict contact to be delete if contact has financial trxns
940 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent([$id], $error)) {
944 // make sure this contact_id does not have any membership types
945 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
948 'member_of_contact_id'
950 if ($membershipTypeID) {
954 $contact = new CRM_Contact_DAO_Contact();
956 if (!$contact->find(TRUE)) {
960 $contactType = $contact->contact_type
;
962 return self
::contactTrashRestore($contact, TRUE);
965 // start a new transaction
966 $transaction = new CRM_Core_Transaction();
969 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
971 //delete billing address if exists.
972 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
974 // delete the log entries since we dont have triggers enabled as yet
975 $logDAO = new CRM_Core_DAO_Log();
976 $logDAO->entity_table
= 'civicrm_contact';
977 $logDAO->entity_id
= $id;
980 // delete contact participants CRM-12155
981 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
983 // delete contact contributions CRM-12155
984 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
986 // do activity cleanup, CRM-5604
987 CRM_Activity_BAO_Activity
::cleanupActivity($id);
989 // delete all notes related to contact
990 CRM_Core_BAO_Note
::cleanContactNotes($id);
992 // delete cases related to contact
993 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
994 if (!empty($contactCases)) {
995 foreach ($contactCases as $caseId) {
996 //check if case is associate with other contact or not.
997 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
998 if (count($caseContactId) <= 1) {
999 CRM_Case_BAO_Case
::deleteCase($caseId);
1007 self
::contactTrashRestore($contact);
1009 // currently we only clear employer cache.
1010 // we are now deleting inherited membership if any.
1011 if ($contact->contact_type
== 'Organization') {
1012 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
1013 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
1014 if (!empty($relationshipDtls)) {
1015 foreach ($relationshipDtls as $rId => $details) {
1016 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
1019 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
1022 //delete the contact id from recently view
1023 CRM_Utils_Recent
::delContact($id);
1024 self
::updateContactCache($id, empty($restore));
1026 // delete any prevnext/dupe cache entry
1027 // These two calls are redundant in default deployments, but they're
1028 // meaningful if "prevnext" is memory-backed.
1029 Civi
::service('prevnext')->deleteItem($id);
1030 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1032 $transaction->commit();
1034 if ($skipUndelete) {
1035 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1042 * Action to update any caches relating to a recently update contact.
1044 * I was going to call this from delete as well as from create to ensure the delete is being
1045 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1046 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1047 * where the call involved a subquery that was locking the table.
1049 * @param int $contactID
1050 * @param bool $isTrashed
1052 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1055 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1056 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1057 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1058 // but this should not cause any change as long as contacts are not being trashed outside the
1059 // main functions for that.
1060 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1063 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1068 * Delete the image of a contact.
1071 * Id of the contact.
1074 * Was contact image deleted?
1076 public static function deleteContactImage($id) {
1081 $contact = new self();
1083 $contact->image_URL
= 'null';
1090 * Return proportional height and width of the image.
1092 * @param int $imageWidth
1095 * @param int $imageHeight
1099 * Thumb dimension of image
1101 public static function getThumbSize($imageWidth, $imageHeight) {
1103 if ($imageWidth && $imageHeight) {
1104 $imageRatio = $imageWidth / $imageHeight;
1109 if ($imageRatio > 1) {
1110 $imageThumbWidth = $thumbWidth;
1111 $imageThumbHeight = round($thumbWidth / $imageRatio);
1114 $imageThumbHeight = $thumbWidth;
1115 $imageThumbWidth = round($thumbWidth * $imageRatio);
1118 return [$imageThumbWidth, $imageThumbHeight];
1122 * Validate type of contact image.
1124 * @param array $params
1125 * @param string $imageIndex
1126 * Index of image field.
1127 * @param string $statusMsg
1128 * Status message to be set after operation.
1129 * @param string $opType
1130 * Type of operation like fatal, bounce etc.
1133 * true if valid image extension
1135 public static function processImageParams(
1137 $imageIndex = 'image_URL',
1151 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1152 $photo = basename($params[$imageIndex]['name']);
1153 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1157 unset($params[$imageIndex]);
1159 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1161 if ($opType == 'status') {
1162 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1164 // FIXME: additional support for fatal, bounce etc could be added.
1170 * Extract contact id from url for deleting contact image.
1172 public static function processImage() {
1174 $action = CRM_Utils_Request
::retrieve('action', 'String');
1175 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1176 // retrieve contact id in case of Profile context
1177 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1178 $cid = $cid ?
$cid : $id;
1179 if ($action & CRM_Core_Action
::DELETE
) {
1180 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1181 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1182 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1183 $session = CRM_Core_Session
::singleton();
1184 $toUrl = $session->popUserContext();
1185 CRM_Utils_System
::redirect($toUrl);
1191 * Function to set is_delete true or restore deleted contact.
1193 * @param CRM_Contact_DAO_Contact $contact
1194 * Contact DAO object.
1195 * @param bool $restore
1196 * True to set the is_delete = 1 else false to restore deleted contact,
1197 * i.e. is_delete = 0
1201 public static function contactTrashRestore($contact, $restore = FALSE) {
1203 'id' => $contact->id
,
1204 'is_deleted' => $restore ?
0 : 1,
1207 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1209 $params = [1 => [$contact->id
, 'Integer']];
1211 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1212 CRM_Core_DAO
::executeQuery($query, $params);
1215 $contact->copyValues($updateParams);
1217 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
1219 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1225 * Get contact type for a contact.
1228 * Id of the contact whose contact type is needed.
1231 * contact_type if $id found else null ""
1233 public static function getContactType($id) {
1234 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1238 * Get contact sub type for a contact.
1241 * Id of the contact whose contact sub type is needed.
1243 * @param string $implodeDelimiter
1246 * contact_sub_type if $id found else null ""
1248 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1249 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1251 return $implodeDelimiter ?
NULL : [];
1254 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1256 if ($implodeDelimiter) {
1257 $subtype = implode($implodeDelimiter, $subtype);
1263 * Get pair of contact-type and sub-type for a contact.
1266 * Id of the contact whose contact sub/contact type is needed.
1270 public static function getContactTypes($id) {
1271 $params = ['id' => $id];
1273 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1276 ['contact_type', 'contact_sub_type']
1281 if ($contact->contact_sub_type
) {
1282 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1284 array_unshift($contactTypes, $contact->contact_type
);
1286 return $contactTypes;
1289 CRM_Core_Error
::fatal();
1294 * Combine all the importable fields from the lower levels object.
1296 * The ordering is important, since currently we do not have a weight
1297 * scheme. Adding weight is super important
1299 * @param int|string $contactType contact Type
1300 * @param bool $status
1301 * Status is used to manipulate first title.
1302 * @param bool $showAll
1303 * If true returns all fields (includes disabled fields).
1304 * @param bool $isProfile
1305 * If its profile mode.
1306 * @param bool $checkPermission
1307 * If false, do not include permissioning clause (for custom data).
1309 * @param bool $withMultiCustomFields
1312 * array of importable Fields
1314 public static function importableFields(
1315 $contactType = 'Individual',
1319 $checkPermission = TRUE,
1320 $withMultiCustomFields = FALSE
1322 if (empty($contactType)) {
1323 $contactType = 'All';
1326 $cacheKeyString = "importableFields $contactType";
1327 $cacheKeyString .= $status ?
'_1' : '_0';
1328 $cacheKeyString .= $showAll ?
'_1' : '_0';
1329 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1330 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1331 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1333 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields) ?
: Civi
::cache('fields')->get($cacheKeyString);
1336 $fields = CRM_Contact_DAO_Contact
::import();
1338 // get the fields thar are meant for contact types
1339 if (in_array($contactType, [
1345 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1348 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1349 CRM_Core_DAO_Phone
::import(),
1350 CRM_Core_DAO_Email
::import(),
1351 CRM_Core_DAO_IM
::import(TRUE),
1352 CRM_Core_DAO_OpenID
::import()
1355 $locationFields = array_merge($locationFields,
1356 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1364 foreach ($locationFields as $key => $field) {
1365 $locationFields[$key]['hasLocationType'] = TRUE;
1368 $fields = array_merge($fields, $locationFields);
1370 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1371 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1374 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1375 $fields['url']['hasWebsiteType'] = TRUE;
1377 if ($contactType != 'All') {
1378 $fields = array_merge($fields,
1379 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1384 $withMultiCustomFields
1387 // Unset the fields which are not related to their contact type.
1388 foreach (CRM_Contact_DAO_Contact
::import() as $name => $value) {
1389 if (!empty($value['contactType']) && $value['contactType'] !== $contactType) {
1390 unset($fields[$name]);
1395 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1396 $fields = array_merge($fields,
1397 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1402 $withMultiCustomFields
1409 $fields = array_merge($fields, [
1411 'title' => ts('Group(s)'),
1415 'title' => ts('Tag(s)'),
1419 'title' => ts('Note'),
1422 'communication_style_id' => [
1423 'title' => ts('Communication Style'),
1424 'name' => 'communication_style_id',
1429 //Sorting fields in alphabetical order(CRM-1507)
1430 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1432 Civi
::cache('fields')->set($cacheKeyString, $fields);
1435 self
::$_importableFields[$cacheKeyString] = $fields;
1439 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1440 self
::$_importableFields[$cacheKeyString]
1444 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1445 self
::$_importableFields[$cacheKeyString]
1453 * Combine all the exportable fields from the lower levels object.
1455 * Currently we are using importable fields as exportable fields
1457 * @param int|string $contactType contact Type
1458 * @param bool $status
1459 * True while exporting primary contacts.
1460 * @param bool $export
1461 * True when used during export.
1462 * @param bool $search
1463 * True when used during search, might conflict with export param?.
1465 * @param bool $withMultiRecord
1466 * @param bool $checkPermissions
1469 * array of exportable Fields
1471 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1472 if (empty($contactType)) {
1473 $contactType = 'All';
1476 $cacheKeyString = "exportableFields $contactType";
1477 $cacheKeyString .= $export ?
'_1' : '_0';
1478 $cacheKeyString .= $status ?
'_1' : '_0';
1479 $cacheKeyString .= $search ?
'_1' : '_0';
1480 $cacheKeyString .= '_' . (bool) $checkPermissions;
1481 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1482 //calculates custom fields takes into account the logged in user & caches that for all users
1483 //as an interim fix we will cache the fields by contact
1484 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1486 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1487 if (!self
::$_exportableFields) {
1488 self
::$_exportableFields = [];
1491 // check if we can retrieve from database cache
1492 $fields = Civi
::cache('fields')->get($cacheKeyString);
1495 $fields = CRM_Contact_DAO_Contact
::export();
1497 // The fields are meant for contact types.
1498 if (in_array($contactType, [
1504 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1506 // add current employer for individuals
1507 $fields = array_merge($fields, [
1508 'current_employer' =>
1510 'name' => 'organization_name',
1511 'title' => ts('Current Employer'),
1516 'location_type' => [
1517 'name' => 'location_type',
1518 'where' => 'civicrm_location_type.name',
1519 'title' => ts('Location Type'),
1525 'name' => 'im_provider',
1526 'where' => 'civicrm_im.provider_id',
1527 'title' => ts('IM Provider'),
1531 $locationFields = array_merge($locationType,
1532 CRM_Core_DAO_Address
::export(),
1533 CRM_Core_DAO_Phone
::export(),
1534 CRM_Core_DAO_Email
::export(),
1536 CRM_Core_DAO_IM
::export(TRUE),
1537 CRM_Core_DAO_OpenID
::export()
1540 $locationFields = array_merge($locationFields,
1541 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1544 foreach ($locationFields as $key => $field) {
1545 $locationFields[$key]['hasLocationType'] = TRUE;
1548 $fields = array_merge($fields, $locationFields);
1551 $fields = array_merge($fields,
1552 CRM_Core_DAO_Worldregion
::export()
1555 $fields = array_merge($fields,
1556 CRM_Contact_DAO_Contact
::export()
1560 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1562 if ($contactType != 'All') {
1563 $fields = array_merge($fields,
1564 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1568 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $type) {
1569 $fields = array_merge($fields,
1570 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1574 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1577 $fields = array_merge($fields, [
1579 'title' => ts('Group(s)'),
1583 'title' => ts('Tag(s)'),
1587 'title' => ts('Note(s)'),
1593 $fields = array_merge($fields, [
1595 'title' => ts('Group(s)'),
1599 'title' => ts('Tag(s)'),
1603 'title' => ts('Note(s)'),
1609 //Sorting fields in alphabetical order(CRM-1507)
1610 foreach ($fields as $k => $v) {
1611 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1614 $fields = array_merge($sortArray, $fields);
1615 //unset the field which are not related to their contact type.
1616 if ($contactType != 'All') {
1622 'organization_name',
1623 'email_greeting_custom',
1624 'postal_greeting_custom',
1637 'organization_name',
1645 'email_greeting_custom',
1646 'postal_greeting_custom',
1662 'email_greeting_custom',
1663 'postal_greeting_custom',
1673 foreach ($commonValues[$contactType] as $value) {
1674 unset($fields[$value]);
1678 Civi
::cache('fields')->set($cacheKeyString, $fields);
1680 self
::$_exportableFields[$cacheKeyString] = $fields;
1684 $fields = self
::$_exportableFields[$cacheKeyString];
1687 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1688 self
::$_exportableFields[$cacheKeyString]
1696 * Get the all contact details (Hierarchical).
1698 * @param int $contactId
1700 * @param array $fields
1706 public static function getHierContactDetails($contactId, $fields) {
1707 $params = [['contact_id', '=', $contactId, 0, 0]];
1709 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1711 // We don't know the contents of return properties, but we need the lower
1712 // level ids of the contact so add a few fields.
1713 $returnProperties['first_name'] = 1;
1714 $returnProperties['organization_name'] = 1;
1715 $returnProperties['household_name'] = 1;
1716 $returnProperties['contact_type'] = 1;
1717 $returnProperties['contact_sub_type'] = 1;
1718 list($query) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties);
1723 * Given a set of flat profile style field names, create a hierarchy.
1725 * This is for the query to use, create the right sql.
1728 * @param int $contactId
1732 * A hierarchical property tree if appropriate
1734 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1735 $locationTypes = CRM_Core_BAO_Address
::buildOptions('location_type_id', 'validate');
1737 $returnProperties = [];
1739 $multipleFields = ['website' => 'url'];
1740 foreach ($fields as $name => $dontCare) {
1741 if (strpos($name, '-') !== FALSE) {
1742 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1744 if (!in_array($fieldName, $multipleFields)) {
1745 if ($id == 'Primary') {
1746 $locationTypeName = 1;
1749 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1750 if (!$locationTypeName) {
1755 if (empty($returnProperties['location'])) {
1756 $returnProperties['location'] = [];
1758 if (empty($returnProperties['location'][$locationTypeName])) {
1759 $returnProperties['location'][$locationTypeName] = [];
1760 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1762 if (in_array($fieldName, [
1770 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1773 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1776 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1777 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1780 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1784 $returnProperties['website'][$id][$fieldName] = 1;
1788 $returnProperties[$name] = 1;
1792 return $returnProperties;
1796 * Return the primary location type of a contact.
1798 * $params int $contactId contact_id
1799 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1800 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1802 * @param int $contactId
1803 * @param bool $skipDefaultPriamry
1804 * @param null $block
1807 * $locationType location_type_id
1809 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1811 $entityBlock = ['contact_id' => $contactId];
1812 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1813 foreach ($blocks[$block] as $key => $value) {
1814 if (!empty($value['is_primary'])) {
1815 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1822 IF ( civicrm_email.location_type_id IS NULL,
1823 IF ( civicrm_address.location_type_id IS NULL,
1824 IF ( civicrm_phone.location_type_id IS NULL,
1825 IF ( civicrm_im.location_type_id IS NULL,
1826 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1827 ,civicrm_im.location_type_id)
1828 ,civicrm_phone.location_type_id)
1829 ,civicrm_address.location_type_id)
1830 ,civicrm_email.location_type_id) as locationType
1831 FROM civicrm_contact
1832 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1833 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1834 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1835 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1836 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1837 WHERE civicrm_contact.id = %1 ";
1839 $params = [1 => [$contactId, 'Integer']];
1841 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1843 $locationType = NULL;
1844 if ($dao->fetch()) {
1845 $locationType = $dao->locationType
;
1848 if (isset($locationType)) {
1849 return $locationType;
1851 elseif ($skipDefaultPriamry) {
1852 // if there is no primary contact location then return null
1856 // if there is no primart contact location, then return default
1857 // location type of the system
1858 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1859 return $defaultLocationType->id
;
1864 * Get the display name, primary email and location type of a contact.
1867 * Id of the contact.
1870 * Array of display_name, email if found, do_not_email or (null,null,null)
1872 public static function getContactDetails($id) {
1873 // check if the contact type
1874 $contactType = self
::getContactType($id);
1876 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1879 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1880 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1881 WHERE civicrm_contact.id = %1
1882 ORDER BY civicrm_email.is_primary DESC";
1883 $params = [1 => [$id, 'Integer']];
1884 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1886 if ($dao->fetch()) {
1887 if ($contactType == 'Individual') {
1888 if ($dao->first_name ||
$dao->last_name
) {
1889 $name = "{$dao->first_name} {$dao->last_name}";
1892 $name = $dao->display_name
;
1896 $name = $dao->display_name
;
1898 $email = $dao->email
;
1899 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1900 $onHold = $dao->on_hold ?
TRUE : FALSE;
1901 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1902 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1904 return [NULL, NULL, NULL, NULL, NULL];
1908 * Add/edit/register contacts through profile.
1910 * @param array $params
1911 * Array of profile fields to be edited/added.
1912 * @param array $fields
1913 * Array of fields from UFGroup.
1914 * @param int $contactID
1915 * Id of the contact to be edited/added.
1916 * @param int $addToGroupID
1917 * Specifies the default group to which contact is added.
1918 * @param int $ufGroupId
1919 * Uf group id (profile id).
1920 * @param string $ctype
1921 * @param bool $visibility
1922 * Basically lets us know where this request is coming from.
1923 * if via a profile from web, we restrict what groups are changed
1926 * contact id created/edited
1928 public static function createProfileContact(
1932 $addToGroupID = NULL,
1937 // add ufGroupID to params array ( CRM-2012 )
1939 $params['uf_group_id'] = $ufGroupId;
1941 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1943 // If a user has logged in, or accessed via a checksum
1944 // Then deliberately 'blanking' a value in the profile should remove it from their record
1945 $session = CRM_Core_Session
::singleton();
1946 $params['updateBlankLocInfo'] = TRUE;
1947 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1948 $params['updateBlankLocInfo'] = FALSE;
1953 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1957 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1960 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1962 // manage is_opt_out
1963 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1964 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1965 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1966 $data['is_opt_out'] = $isOptOut;
1967 // on change, create new civicrm_subscription_history entry
1968 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1970 'contact_id' => $contactDetails['contact_id'],
1971 'status' => $isOptOut ?
'Removed' : 'Added',
1974 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1978 $contact = self
::create($data);
1980 // contact is null if the profile does not have any contact fields
1982 $contactID = $contact->id
;
1985 if (empty($contactID)) {
1986 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
1989 // Process group and tag
1990 if (!empty($fields['group'])) {
1992 // this for sure means we are coming in via profile since i added it to fix
1993 // removing contacts from user groups -- lobo
1997 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2000 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2001 // Convert comma separated form values from select2 v3
2002 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2003 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2006 //to add profile in default group
2007 if (is_array($addToGroupID)) {
2008 $contactIds = [$contactID];
2009 foreach ($addToGroupID as $groupId) {
2010 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2013 elseif ($addToGroupID) {
2014 $contactIds = [$contactID];
2015 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2018 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
2021 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2024 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2030 * Format profile contact parameters.
2032 * @param array $params
2034 * @param int $contactID
2035 * @param int $ufGroupId
2036 * @param null $ctype
2037 * @param bool $skipCustom
2041 public static function formatProfileContactParams(
2050 $data = $contactDetails = [];
2052 // get the contact details (hier)
2054 $details = self
::getHierContactDetails($contactID, $fields);
2056 $contactDetails = $details[$contactID];
2057 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
2058 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
2061 //we should get contact type only if contact
2063 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2065 //special case to handle profile with only contact fields
2066 if ($data['contact_type'] == 'Contact') {
2067 $data['contact_type'] = 'Individual';
2069 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2070 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2074 $data['contact_type'] = $ctype;
2077 $data['contact_type'] = 'Individual';
2081 //fix contact sub type CRM-5125
2082 if (array_key_exists('contact_sub_type', $params) &&
2083 !empty($params['contact_sub_type'])
2085 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2087 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2088 !empty($params['contact_sub_type_hidden'])
2090 // if profile was used, and had any subtype, we obtain it from there
2091 //CRM-13596 - add to existing contact types, rather than overwriting
2092 if (empty($data['contact_sub_type'])) {
2093 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2094 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2097 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2098 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2099 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2100 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2101 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2106 if ($ctype == 'Organization') {
2107 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2109 elseif ($ctype == 'Household') {
2110 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2118 $data['contact_id'] = $contactID;
2119 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2122 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2123 $defaultLocationId = $defaultLocation->id
;
2126 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2128 $blocks = ['email', 'phone', 'im', 'openid'];
2130 $multiplFields = ['url'];
2131 // prevent overwritten of formatted array, reset all block from
2132 // params if it is not in valid format (since import pass valid format)
2133 foreach ($blocks as $blk) {
2134 if (array_key_exists($blk, $params) &&
2135 !is_array($params[$blk])
2137 unset($params[$blk]);
2141 $primaryPhoneLoc = NULL;
2142 $session = CRM_Core_Session
::singleton();
2143 foreach ($params as $key => $value) {
2144 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2146 if ($locTypeId == 'Primary') {
2148 if (in_array($fieldName, $blocks)) {
2149 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2152 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2154 $primaryLocationType = $locTypeId;
2157 $locTypeId = $defaultLocationId;
2161 if (is_numeric($locTypeId) &&
2162 !in_array($fieldName, $multiplFields) &&
2163 substr($fieldName, 0, 7) != 'custom_'
2165 $index = $locTypeId;
2167 if (is_numeric($typeId)) {
2168 $index .= '-' . $typeId;
2170 if (!in_array($index, $locationType)) {
2171 $locationType[$count] = $index;
2175 $loc = CRM_Utils_Array
::key($index, $locationType);
2177 $blockName = self
::getLocationEntityForKey($fieldName);
2179 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2181 //set is_billing true, for location type "Billing"
2182 if ($locTypeId == $billingLocationTypeId) {
2183 $data[$blockName][$loc]['is_billing'] = 1;
2187 //get the primary location type
2188 if ($locTypeId == $primaryLocationType) {
2189 $data[$blockName][$loc]['is_primary'] = 1;
2192 elseif ($locTypeId == $defaultLocationId) {
2193 $data[$blockName][$loc]['is_primary'] = 1;
2196 if (in_array($fieldName, ['phone'])) {
2198 $data['phone'][$loc]['phone_type_id'] = $typeId;
2201 $data['phone'][$loc]['phone_type_id'] = '';
2203 $data['phone'][$loc]['phone'] = $value;
2205 //special case to handle primary phone with different phone types
2206 // in this case we make first phone type as primary
2207 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2208 $primaryPhoneLoc = $loc;
2211 if ($loc != $primaryPhoneLoc) {
2212 unset($data['phone'][$loc]['is_primary']);
2215 elseif ($fieldName == 'email') {
2216 $data['email'][$loc]['email'] = $value;
2217 if (empty($contactID)) {
2218 $data['email'][$loc]['is_primary'] = 1;
2221 elseif ($fieldName == 'im') {
2222 if (isset($params[$key . '-provider_id'])) {
2223 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2225 if (strpos($key, '-provider_id') !== FALSE) {
2226 $data['im'][$loc]['provider_id'] = $params[$key];
2229 $data['im'][$loc]['name'] = $value;
2232 elseif ($fieldName == 'openid') {
2233 $data['openid'][$loc]['openid'] = $value;
2236 if ($fieldName === 'state_province') {
2238 if (is_numeric($value) && ((int ) $value) >= 1000) {
2239 $data['address'][$loc]['state_province_id'] = $value;
2241 elseif (empty($value)) {
2242 $data['address'][$loc]['state_province_id'] = '';
2245 $data['address'][$loc]['state_province'] = $value;
2248 elseif ($fieldName === 'country') {
2250 if (is_numeric($value) && ((int ) $value) >= 1000
2252 $data['address'][$loc]['country_id'] = $value;
2254 elseif (empty($value)) {
2255 $data['address'][$loc]['country_id'] = '';
2258 $data['address'][$loc]['country'] = $value;
2261 elseif ($fieldName === 'county') {
2262 $data['address'][$loc]['county_id'] = $value;
2264 elseif ($fieldName == 'address_name') {
2265 $data['address'][$loc]['name'] = $value;
2267 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2268 $data['address'][$loc][substr($fieldName, 8)] = $value;
2271 $data[$blockName][$loc][$fieldName] = $value;
2276 if (substr($key, 0, 4) === 'url-') {
2277 $websiteField = explode('-', $key);
2278 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2279 $data['website'][$websiteField[1]]['url'] = $value;
2281 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2282 //save email/postal greeting and addressee values if any, CRM-4575
2283 $data[$key . '_id'] = $value;
2285 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2286 // for autocomplete transfer hidden value instead of label
2287 if ($params[$key] && isset($params[$key . '_id'])) {
2288 $value = $params[$key . '_id'];
2291 // we need to append time with date
2292 if ($params[$key] && isset($params[$key . '_time'])) {
2293 $value .= ' ' . $params[$key . '_time'];
2296 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2297 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2298 ($value == '' ||
!isset($value))
2304 if (!empty($params['customRecordValues'])) {
2305 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2306 foreach ($params['customRecordValues'] as $recId => $customFields) {
2307 if (is_array($customFields) && !empty($customFields)) {
2308 foreach ($customFields as $customFieldName) {
2309 if ($customFieldName == $key) {
2319 //CRM-13596 - check for contact_sub_type_hidden first
2320 if (array_key_exists('contact_sub_type_hidden', $params)) {
2321 $type = $params['contact_sub_type_hidden'];
2324 $type = $data['contact_type'];
2325 if (!empty($data['contact_sub_type'])) {
2326 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2330 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2340 elseif ($key === 'edit') {
2344 if ($key === 'location') {
2345 foreach ($value as $locationTypeId => $field) {
2346 foreach ($field as $block => $val) {
2347 if ($block === 'address' && array_key_exists('address_name', $val)) {
2348 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2353 if ($key === 'phone' && isset($params['phone_ext'])) {
2354 $data[$key] = $value;
2355 foreach ($value as $cnt => $phoneBlock) {
2356 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2357 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2361 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2362 && ($value == '' ||
!isset($value)) &&
2363 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2364 ($key === 'current_employer' && empty($params['current_employer']))) {
2365 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2366 // to avoid update with empty values
2370 $data[$key] = $value;
2376 if (!isset($data['contact_type'])) {
2377 $data['contact_type'] = 'Individual';
2380 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2381 $privacy = CRM_Core_SelectValues
::privacy();
2382 foreach ($privacy as $key => $value) {
2383 if (array_key_exists($key, $fields)) {
2384 // do not reset values for existing contacts, if fields are added to a profile
2385 if (array_key_exists($key, $params)) {
2386 $data[$key] = $params[$key];
2387 if (empty($params[$key])) {
2391 elseif (!$contactID) {
2397 return [$data, $contactDetails];
2401 * Find the get contact details.
2403 * This function does not respect ACLs for now, which might need to be rectified at some
2404 * stage based on how its used.
2406 * @param string $mail
2407 * Primary email address of the contact.
2408 * @param string $ctype
2411 * @return object|null
2412 * $dao contact details
2414 public static function matchContactOnEmail($mail, $ctype = NULL) {
2415 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2416 $mail = $strtolower(trim($mail));
2418 SELECT civicrm_contact.id as contact_id,
2419 civicrm_contact.hash as hash,
2420 civicrm_contact.contact_type as contact_type,
2421 civicrm_contact.contact_sub_type as contact_sub_type
2422 FROM civicrm_contact
2423 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2425 if (Civi
::settings()->get('uniq_email_per_site')) {
2426 // try to find a match within a site (multisite).
2427 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2428 if (!empty($groups)) {
2430 INNER JOIN civicrm_group_contact gc ON
2431 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2436 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2437 $p = [1 => [$mail, 'String']];
2440 $query .= " AND civicrm_contact.contact_type = %3";
2441 $p[3] = [$ctype, 'String'];
2444 $query .= " ORDER BY civicrm_email.is_primary DESC";
2446 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2448 if ($dao->fetch()) {
2455 * Find the contact details associated with an OpenID.
2457 * @param string $openId
2458 * OpenId of the contact.
2459 * @param string $ctype
2462 * @return object|null
2463 * $dao contact details
2465 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2466 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2467 $openId = $strtolower(trim($openId));
2469 SELECT civicrm_contact.id as contact_id,
2470 civicrm_contact.hash as hash,
2471 civicrm_contact.contact_type as contact_type,
2472 civicrm_contact.contact_sub_type as contact_sub_type
2473 FROM civicrm_contact
2474 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2475 WHERE civicrm_openid.openid = %1";
2476 $p = [1 => [$openId, 'String']];
2479 $query .= " AND civicrm_contact.contact_type = %3";
2480 $p[3] = [$ctype, 'String'];
2483 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2485 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2487 if ($dao->fetch()) {
2494 * Get primary email of the contact.
2496 * @param int $contactID
2498 * @param bool $polite
2499 * Whether to only pull an email if it's okay to send to it--that is, if it
2500 * is not on_hold and the contact is not do_not_email.
2503 * Email address if present else null
2505 public static function getPrimaryEmail($contactID, $polite = FALSE) {
2506 // fetch the primary email
2508 SELECT civicrm_email.email as email
2509 FROM civicrm_contact
2510 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2511 WHERE civicrm_email.is_primary = 1
2512 AND civicrm_contact.id = %1";
2515 AND civicrm_contact.do_not_email = 0
2516 AND civicrm_email.on_hold = 0';
2518 $p = [1 => [$contactID, 'Integer']];
2519 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2522 if ($dao->fetch()) {
2523 $email = $dao->email
;
2529 * Function to get primary OpenID of the contact.
2531 * @param int $contactID
2535 * >openid OpenID if present else null
2537 public static function getPrimaryOpenId($contactID) {
2538 // fetch the primary OpenID
2540 SELECT civicrm_openid.openid as openid
2541 FROM civicrm_contact
2542 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2543 WHERE civicrm_contact.id = %1
2544 AND civicrm_openid.is_primary = 1";
2545 $p = [1 => [$contactID, 'Integer']];
2546 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2549 if ($dao->fetch()) {
2550 $openId = $dao->openid
;
2556 * Fetch the object and store the values in the values array.
2558 * @param array $params
2559 * Input parameters to find object.
2560 * @param array $values
2561 * Output values of the object.
2563 * @return CRM_Contact_BAO_Contact|null
2564 * The found object or null
2566 public static function getValues(&$params, &$values) {
2567 $contact = new CRM_Contact_BAO_Contact();
2569 $contact->copyValues($params);
2571 if ($contact->find(TRUE)) {
2573 CRM_Core_DAO
::storeValues($contact, $values);
2576 foreach (self
::$_commPrefs as $name) {
2577 if (isset($contact->$name)) {
2578 $privacy[$name] = $contact->$name;
2582 if (!empty($privacy)) {
2583 $values['privacy'] = $privacy;
2586 // communication Prefferance
2587 $preffComm = $comm = [];
2588 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2589 $contact->preferred_communication_method
2591 foreach ($comm as $value) {
2592 $preffComm[$value] = 1;
2594 $temp = ['preferred_communication_method' => $contact->preferred_communication_method
];
2597 'preferred_communication_method' => [
2598 'newName' => 'preferred_communication_method_display',
2599 'groupName' => 'preferred_communication_method',
2603 // @todo This can be figured out from metadata & we can avoid the uncached query.
2604 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2606 $values['preferred_communication_method'] = $preffComm;
2607 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2609 if ($contact->preferred_mail_format
) {
2610 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2611 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2614 // get preferred languages
2615 if (!empty($contact->preferred_language
)) {
2616 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2619 // Calculating Year difference
2620 if ($contact->birth_date
) {
2621 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2622 if ($birthDate < date('Ymd')) {
2623 $age = CRM_Utils_Date
::calculateAge($birthDate);
2624 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2625 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2629 $contact->contact_id
= $contact->id
;
2637 * Given the component name and returns the count of participation of contact.
2639 * @param string $component
2640 * Input component name.
2641 * @param int $contactId
2643 * @param string $tableName
2644 * Optional tableName if component is custom group.
2647 * total number in database
2649 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2651 switch ($component) {
2653 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2656 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2657 CRM_Contact_BAO_Relationship
::CURRENT
,
2666 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2669 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2672 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2675 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2677 case 'contribution':
2678 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2681 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2684 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2687 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2690 return CRM_Case_BAO_Case
::caseCount($contactId);
2693 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2697 'contact_id' => $contactId,
2700 'context' => 'activity',
2702 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2705 $params = ['contact_id' => $contactId];
2706 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2709 $custom = explode('_', $component);
2710 if ($custom['0'] = 'custom') {
2712 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2714 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2715 return CRM_Core_DAO
::singleValueQuery($queryString);
2721 * Update contact greetings if an update has resulted in a custom field change.
2723 * @param array $updatedFields
2724 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2725 * @param array $contactParams
2726 * Parameters known about the contact. At minimum array('contact_id' => x).
2727 * Fields in this array will take precedence over DB fields (so far only
2728 * in the case of greeting id fields).
2730 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2731 $contactID = $contactParams['contact_id'];
2732 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2733 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2734 if (!empty($tokens['all']['contact'])) {
2735 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2736 if (!empty($affectedTokens)) {
2737 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2738 $contact = new CRM_Contact_BAO_Contact();
2739 $contact->id
= $contactID;
2740 CRM_Contact_BAO_Contact
::processGreetings($contact);
2746 * Process greetings and cache.
2748 * @param object $contact
2749 * Contact object after save.
2751 public static function processGreetings(&$contact) {
2753 //@todo this function does a lot of unnecessary loading.
2754 // ensureGreetingParamsAreSet now makes sure that the contact is
2755 // loaded and using updateGreetingsOnTokenFieldChange
2756 // allows us the possibility of only doing an update if required.
2758 // The contact object has not always required the
2759 // fields that are required to calculate greetings
2760 // so we need to retrieve it again.
2761 if ($contact->_query
!== FALSE) {
2762 $contact->find(TRUE);
2765 // store object values to an array
2766 $contactDetails = [];
2767 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2768 $contactDetails = [[$contact->id
=> $contactDetails]];
2770 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2771 $updateQueryString = [];
2773 //cache email and postal greeting to greeting display
2774 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2775 $emailGreetingString = $contact->email_greeting_custom
;
2777 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2778 // the filter value for Individual contact type is set to 1
2780 'contact_type' => $contact->contact_type
,
2781 'greeting_type' => 'email_greeting',
2784 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2785 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2786 $updateQueryString[] = " email_greeting_custom = NULL ";
2789 if ($contact->email_greeting_custom
) {
2790 $updateQueryString[] = " email_greeting_display = NULL ";
2794 if ($emailGreetingString) {
2795 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2798 'CRM_Contact_BAO_Contact'
2800 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2801 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2805 if ($contact->postal_greeting_custom
!== 'null' && $contact->postal_greeting_custom
) {
2806 $postalGreetingString = $contact->postal_greeting_custom
;
2808 elseif ($contact->postal_greeting_id
!== 'null' && $contact->postal_greeting_id
) {
2810 'contact_type' => $contact->contact_type
,
2811 'greeting_type' => 'postal_greeting',
2813 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2814 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2815 $updateQueryString[] = " postal_greeting_custom = NULL ";
2818 if ($contact->postal_greeting_custom
) {
2819 $updateQueryString[] = " postal_greeting_display = NULL ";
2823 if ($postalGreetingString) {
2824 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2827 'CRM_Contact_BAO_Contact'
2829 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2830 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2834 if ($contact->addressee_custom
!== 'null' && $contact->addressee_custom
) {
2835 $addresseeString = $contact->addressee_custom
;
2837 elseif ($contact->addressee_id
!== 'null' && $contact->addressee_id
) {
2839 'contact_type' => $contact->contact_type
,
2840 'greeting_type' => 'addressee',
2843 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2844 $addresseeString = $addressee[$contact->addressee_id
];
2845 $updateQueryString[] = " addressee_custom = NULL ";
2848 if ($contact->addressee_custom
) {
2849 $updateQueryString[] = " addressee_display = NULL ";
2853 if ($addresseeString) {
2854 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2857 'CRM_Contact_BAO_Contact'
2859 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2860 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2863 if (!empty($updateQueryString)) {
2864 $updateQueryString = implode(',', $updateQueryString);
2865 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2866 CRM_Core_DAO
::executeQuery($queryString);
2871 * Retrieve loc block ids w/ given condition.
2873 * @param int $contactId
2875 * @param array $criteria
2876 * Key => value pair which should be.
2877 * fulfill by return record ids.
2878 * @param string $condOperator
2879 * Operator use for grouping multiple conditions.
2882 * loc block ids which fulfill condition.
2884 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2887 return $locBlockIds;
2890 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2891 $name = strtolower($block);
2892 $className = "CRM_Core_DAO_$block";
2893 $blockDAO = new $className();
2895 // build the condition.
2896 if (is_array($criteria)) {
2897 $fields = $blockDAO->fields();
2899 foreach ($criteria as $field => $value) {
2900 if (array_key_exists($field, $fields)) {
2901 $cond = "( $field = $value )";
2902 // value might be zero or null.
2903 if (!$value ||
strtolower($value) === 'null') {
2904 $cond = "( $field = 0 OR $field IS NULL )";
2906 $conditions[] = $cond;
2909 if (!empty($conditions)) {
2910 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2914 $blockDAO->contact_id
= $contactId;
2916 while ($blockDAO->fetch()) {
2917 $locBlockIds[$name][] = $blockDAO->id
;
2921 return $locBlockIds;
2925 * Build context menu items.
2927 * @param int $contactId
2930 * Array of context menu for logged in user.
2932 public static function contextMenu($contactId = NULL) {
2935 'title' => ts('View Contact'),
2937 'ref' => 'view-contact',
2938 'class' => 'no-popup',
2940 'permissions' => ['view all contacts'],
2943 'title' => ts('Edit Contact'),
2945 'ref' => 'edit-contact',
2946 'class' => 'no-popup',
2948 'permissions' => ['edit all contacts'],
2951 'title' => ts('Delete Contact'),
2953 'ref' => 'delete-contact',
2955 'permissions' => ['access deleted contacts', 'delete contacts'],
2958 'title' => ts('Add Contribution'),
2960 'ref' => 'new-contribution',
2961 'key' => 'contribution',
2962 'tab' => 'contribute',
2963 'component' => 'CiviContribute',
2964 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2965 'reset=1&action=add&context=contribution'
2968 'access CiviContribute',
2969 'edit contributions',
2973 'title' => ts('Register for Event'),
2975 'ref' => 'new-participant',
2976 'key' => 'participant',
2977 'tab' => 'participant',
2978 'component' => 'CiviEvent',
2979 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2982 'edit event participants',
2986 'title' => ts('Record Activity'),
2988 'ref' => 'new-activity',
2989 'key' => 'activity',
2990 'permissions' => ['edit all contacts'],
2993 'title' => ts('Add Pledge'),
2995 'ref' => 'new-pledge',
2998 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
2999 'reset=1&action=add&context=pledge'
3001 'component' => 'CiviPledge',
3003 'access CiviPledge',
3008 'title' => ts('Add Membership'),
3010 'ref' => 'new-membership',
3011 'key' => 'membership',
3013 'component' => 'CiviMember',
3014 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3015 'reset=1&action=add&context=membership'
3018 'access CiviMember',
3023 'title' => ts('Add Case'),
3025 'ref' => 'new-case',
3028 'component' => 'CiviCase',
3029 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3030 'permissions' => ['add cases'],
3033 'title' => ts('Add Grant'),
3035 'ref' => 'new-grant',
3038 'component' => 'CiviGrant',
3039 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3040 'reset=1&action=add&context=grant'
3042 'permissions' => ['edit grants'],
3045 'title' => ts('Add Relationship'),
3047 'ref' => 'new-relationship',
3050 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3051 'reset=1&action=add'
3053 'permissions' => ['edit all contacts'],
3056 'title' => ts('Add Note'),
3058 'ref' => 'new-note',
3061 'class' => 'medium-popup',
3062 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3063 'reset=1&action=add'
3065 'permissions' => ['edit all contacts'],
3068 'title' => ts('Send an Email'),
3070 'ref' => 'new-email',
3072 'permissions' => ['view all contacts'],
3075 'title' => ts('Add to Group'),
3077 'ref' => 'group-add-contact',
3080 'permissions' => ['edit groups'],
3083 'title' => ts('Tag Contact'),
3085 'ref' => 'tag-contact',
3088 'permissions' => ['edit all contacts'],
3092 $menu['otherActions'] = [
3094 'title' => ts('Print Summary'),
3095 'description' => ts('Printer-friendly view of this page.'),
3097 'ref' => 'crm-contact-print',
3100 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3104 'icon' => 'crm-i fa-print',
3107 'title' => ts('vCard'),
3108 'description' => ts('vCard record for this contact.'),
3110 'ref' => 'crm-contact-vcard',
3113 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3117 'icon' => 'crm-i fa-list-alt',
3121 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3122 $menu['otherActions']['dashboard'] = [
3123 'title' => ts('Contact Dashboard'),
3124 'description' => ts('Contact Dashboard'),
3126 'ref' => 'crm-contact-dashboard',
3127 'key' => 'dashboard',
3128 'tab' => 'dashboard',
3129 'class' => 'dashboard',
3130 // NOTE: As an alternative you can also build url on CMS specific way
3131 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3132 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3133 'icon' => 'crm-i fa-tachometer',
3137 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3139 $menu['otherActions']['user-record'] = [
3140 'title' => ts('User Record'),
3141 'description' => ts('User Record'),
3143 'ref' => 'crm-contact-user-record',
3144 'key' => 'user-record',
3145 'tab' => 'user-record',
3146 'class' => 'user-record',
3147 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3148 'icon' => 'crm-i fa-user',
3151 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3152 $menu['otherActions']['user-add'] = [
3153 'title' => ts('Create User Record'),
3154 'description' => ts('Create User Record'),
3156 'ref' => 'crm-contact-user-add',
3157 'key' => 'user-add',
3158 'tab' => 'user-add',
3159 'class' => 'user-add',
3160 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3161 'icon' => 'crm-i fa-user-plus',
3165 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3166 //1. check for component is active.
3167 //2. check for user permissions.
3168 //3. check for acls.
3169 //3. edit and view contact are directly accessible to user.
3171 $aclPermissionedTasks = [
3176 'group-add-contact',
3180 $corePermission = CRM_Core_Permission
::getPermission();
3183 foreach ($menu as $key => $values) {
3184 if ($key !== 'otherActions') {
3186 // user does not have necessary permissions.
3187 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3190 // build directly accessible action menu.
3191 if (in_array($values['ref'], [
3195 $contextMenu['primaryActions'][$key] = [
3196 'title' => $values['title'],
3197 'ref' => $values['ref'],
3198 'class' => CRM_Utils_Array
::value('class', $values),
3199 'key' => $values['key'],
3204 // finally get menu item for -more- action widget.
3205 $contextMenu['moreActions'][$values['weight']] = [
3206 'title' => $values['title'],
3207 'ref' => $values['ref'],
3208 'href' => CRM_Utils_Array
::value('href', $values),
3209 'tab' => CRM_Utils_Array
::value('tab', $values),
3210 'class' => CRM_Utils_Array
::value('class', $values),
3211 'key' => $values['key'],
3215 foreach ($values as $value) {
3216 // user does not have necessary permissions.
3217 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3221 // finally get menu item for -more- action widget.
3222 $contextMenu['otherActions'][$value['weight']] = [
3223 'title' => $value['title'],
3224 'ref' => $value['ref'],
3225 'href' => CRM_Utils_Array
::value('href', $value),
3226 'tab' => CRM_Utils_Array
::value('tab', $value),
3227 'class' => CRM_Utils_Array
::value('class', $value),
3228 'icon' => CRM_Utils_Array
::value('icon', $value),
3229 'key' => $value['key'],
3235 ksort($contextMenu['moreActions']);
3236 ksort($contextMenu['otherActions']);
3238 return $contextMenu;
3242 * Check if user has permissions to access items in action menu.
3244 * @param array $aclPermissionedTasks
3245 * Array containing ACL related tasks.
3246 * @param string $corePermission
3247 * The permission of the user (edit or view or null).
3248 * @param array $menuOptions
3249 * Array containing params of the menu (title, href, etc).
3252 * TRUE if user has all permissions, FALSE if otherwise.
3254 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3255 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3257 // if component action - make sure component is enable.
3258 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3262 // make sure user has all required permissions.
3263 $hasAllPermissions = FALSE;
3265 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3266 if (!is_array($permissions) ||
empty($permissions)) {
3267 $hasAllPermissions = TRUE;
3270 // iterate for required permissions in given permissions array.
3271 if (!$hasAllPermissions) {
3272 $hasPermissions = 0;
3273 foreach ($permissions as $permission) {
3274 if (CRM_Core_Permission
::check($permission)) {
3279 if (count($permissions) == $hasPermissions) {
3280 $hasAllPermissions = TRUE;
3283 // if still user does not have required permissions, check acl.
3284 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3285 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3286 $corePermission == CRM_Core_Permission
::EDIT
3288 $hasAllPermissions = TRUE;
3290 elseif (in_array($menuOptions['ref'], [
3293 // grant permissions for these tasks.
3294 $hasAllPermissions = TRUE;
3299 return $hasAllPermissions;
3303 * Retrieve display name of contact that address is shared.
3305 * This is based on $masterAddressId or $contactId .
3307 * @param int $masterAddressId
3309 * @param int $contactId
3310 * Contact id. (deprecated - do not use)
3312 * @return string|null
3313 * the found display name or null.
3315 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3316 $masterDisplayName = NULL;
3317 if (!$masterAddressId) {
3318 return $masterDisplayName;
3322 SELECT display_name from civicrm_contact
3323 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3324 WHERE civicrm_address.id = " . $masterAddressId;
3326 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3327 return $masterDisplayName;
3331 * Get the creation/modification times for a contact.
3333 * @param int $contactId
3336 * Dates - ('created_date' => $, 'modified_date' => $)
3338 public static function getTimestamps($contactId) {
3339 $timestamps = CRM_Core_DAO
::executeQuery(
3340 'SELECT created_date, modified_date
3341 FROM civicrm_contact
3344 1 => [$contactId, 'Integer'],
3347 if ($timestamps->fetch()) {
3349 'created_date' => $timestamps->created_date
,
3350 'modified_date' => $timestamps->modified_date
,
3359 * Get a list of triggers for the contact table.
3362 * @param null $tableName
3364 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3366 * @see hook_civicrm_triggerInfo
3367 * @see CRM_Core_DAO::triggerRebuild
3369 public static function triggerInfo(&$info, $tableName = NULL) {
3370 //during upgrade, first check for valid version and then create triggers
3371 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3372 if (CRM_Core_Config
::isUpgradeMode()) {
3373 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3374 //if current version is less than 4.3.alpha1 dont create below triggers
3375 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3380 // Modifications to these records should update the contact timestamps.
3381 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3383 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3384 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3385 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3386 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3387 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3389 ->alterTriggerInfo($info, $tableName);
3391 // Update phone table to populate phone_numeric field
3392 if (!$tableName ||
$tableName == 'civicrm_phone') {
3393 // Define stored sql function needed for phones
3394 $sqlTriggers = Civi
::service('sql_triggers');
3395 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3396 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3398 'table' => ['civicrm_phone'],
3400 'event' => ['INSERT', 'UPDATE'],
3401 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3407 * Check if contact is being used in civicrm_domain based on $contactId.
3409 * @param int $contactId
3413 * true if present else false.
3415 public static function checkDomainContact($contactId) {
3419 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3430 * Get options for a given contact field.
3432 * @param string $fieldName
3433 * @param string $context
3434 * @param array $props
3435 * whatever is known about this dao object.
3437 * @return array|bool
3438 * @see CRM_Core_DAO::buildOptions
3440 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3441 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3443 * @see CRM_Core_DAO::buildOptionsContext
3445 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3447 // Special logic for fields whose options depend on context or properties
3448 switch ($fieldName) {
3449 case 'contact_sub_type':
3450 if (!empty($props['contact_type'])) {
3451 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3455 case 'contact_type':
3456 if ($context == 'search') {
3457 // CRM-15495 - EntityRef filters and basic search forms expect this format
3458 // FIXME: Search builder does not
3459 return CRM_Contact_BAO_ContactType
::getSelectElements();
3463 // The contact api supports some related entities so we'll honor that by fetching their options
3466 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3470 $props['entity_table'] = 'civicrm_contact';
3471 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3473 case 'state_province_id':
3474 case 'state_province':
3475 case 'state_province_name':
3480 case 'worldregion_id':
3481 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3484 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3488 * Delete a contact-related object that has an 'is_primary' field.
3490 * Ensures that is_primary gets assigned to another object if available
3491 * Also calls pre/post hooks
3493 * @param string $type
3498 public static function deleteObjectWithPrimary($type, $id) {
3499 if (!$id ||
!is_numeric($id)) {
3502 $daoName = "CRM_Core_DAO_$type";
3503 $obj = new $daoName();
3507 if ($obj->fetch()) {
3508 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3509 $contactId = $obj->contact_id
;
3515 // is_primary is only relavent if this field belongs to a contact
3517 $dao = new $daoName();
3518 $dao->contact_id
= $contactId;
3519 $dao->is_primary
= 1;
3520 // Pick another record to be primary (if one isn't already)
3521 if (!$dao->find(TRUE)) {
3522 $dao->is_primary
= 0;
3524 if ($dao->fetch()) {
3525 $dao->is_primary
= 1;
3530 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3537 public function addSelectWhereClause() {
3538 // We always return an array with these keys, even if they are empty,
3539 // because this tells the query builder that we have considered these fields for acls
3541 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3542 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
[] : ['!= 1'],
3544 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3549 * Get any existing duplicate contacts based on the input parameters.
3551 * @param array $input
3552 * Input parameters to be matched.
3553 * @param string $contactType
3554 * @param string $rule
3557 * @param $excludedContactIDs
3558 * An array of ids not to be included in the results.
3559 * @param bool $checkPermissions
3560 * @param int $ruleGroupID
3561 * ID of the rule group to be used if an override is desirable.
3562 * @param array $contextParams
3563 * The context if relevant, eg. ['event_id' => X]
3567 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3568 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3569 $dedupeParams['check_permission'] = $checkPermissions;
3570 $dedupeParams['contact_type'] = $contactType;
3571 $dedupeParams['rule'] = $rule;
3572 $dedupeParams['rule_group_id'] = $ruleGroupID;
3573 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3574 $dedupeResults['ids'] = [];
3575 $dedupeResults['handled'] = FALSE;
3576 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3577 if (!$dedupeResults['handled']) {
3578 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3580 return $dedupeResults['ids'];
3584 * Get the first duplicate contacts based on the input parameters.
3586 * @param array $input
3587 * Input parameters to be matched.
3588 * @param string $contactType
3589 * @param string $rule
3592 * @param $excludedContactIDs
3593 * An array of ids not to be included in the results.
3594 * @param bool $checkPermissions
3595 * @param int $ruleGroupID
3596 * ID of the rule group to be used if an override is desirable.
3597 * @param array $contextParams
3598 * The context if relevant, eg. ['event_id' => X]
3602 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3603 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3611 * Check if a field is associated with an entity that has a location type.
3613 * (ie. is an address, phone, email etc field).
3615 * @param string $fieldTitle
3616 * Title of the field (not the name - create a new function for that if required).
3620 public static function isFieldHasLocationType($fieldTitle) {
3621 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3622 if ($field['title'] === $fieldTitle) {
3623 return CRM_Utils_Array
::value('hasLocationType', $field);
3630 * @param array $appendProfiles
3631 * Name of profile(s) to append to each link.
3635 public static function getEntityRefCreateLinks($appendProfiles = []) {
3636 // You'd think that "create contacts" would be the permission to check,
3637 // But new contact popups are profile forms and those use their own permissions.
3638 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3642 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3643 $profiles[] = 'new_' . strtolower($contactType);
3645 $retrieved = civicrm_api3('uf_group', 'get', [
3646 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3649 $links = $append = [];
3650 if (!empty($retrieved['values'])) {
3652 'individual' => 'fa-user',
3653 'organization' => 'fa-building',
3654 'household' => 'fa-home',
3656 foreach ($retrieved['values'] as $id => $profile) {
3657 if (in_array($profile['name'], $profiles)) {
3659 'label' => $profile['title'],
3660 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3661 NULL, NULL, FALSE, FALSE, TRUE),
3662 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3663 'icon' => CRM_Utils_Array
::value(str_replace('new_', '', $profile['name']), $icons),
3670 foreach ($append as $id) {
3671 foreach ($links as &$link) {
3672 $link['url'] .= ",$id";
3682 public static function getEntityRefFilters() {
3684 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3685 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3686 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3687 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3688 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3689 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3690 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3691 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3692 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3693 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],