3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
{
36 * SQL function used to format the phone_numeric field via trigger.
38 * @see self::triggerInfo()
40 * Note that this is also used by the 4.3 upgrade script.
41 * @see CRM_Upgrade_Incremental_php_FourThree
43 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
45 const CREATE_STRIP_FUNCTION_43
= "
46 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
47 RETURNS VARCHAR(255) CHARACTER SET utf8
51 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
52 DECLARE iterator INT DEFAULT 1;
53 WHILE iterator < (LENGTH(input) + 1) DO
54 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
55 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
57 SET iterator = iterator + 1;
63 * The types of communication preferences.
67 public static $_commPrefs = [
80 public static $_greetingTypes = [
87 * Static field for all the contact information that we can potentially import.
91 public static $_importableFields = [];
94 * Static field for all the contact information that we can potentially export.
98 public static $_exportableFields = NULL;
103 public function __construct() {
104 parent
::__construct();
108 * Takes an associative array and creates a contact object.
110 * The function extracts all the params it needs to initialize the create a
111 * contact object. the params array could contain additional unused name/value
114 * @param array $params
115 * (reference) an assoc array of name/value pairs.
117 * @return CRM_Contact_BAO_Contact|CRM_Core_Error|NULL
118 * Created or updated contact object or error object.
119 * (error objects are being phased out in favour of exceptions)
122 public static function add(&$params) {
123 $contact = new CRM_Contact_DAO_Contact();
125 if (empty($params)) {
129 // Fix for validate contact sub type CRM-5143.
130 if (isset($params['contact_sub_type'])) {
131 if (empty($params['contact_sub_type'])) {
132 $params['contact_sub_type'] = 'null';
134 elseif ($params['contact_sub_type'] !== 'null') {
135 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
136 $params['contact_type'], TRUE
139 // we'll need to fix tests to handle this
141 CRM_Core_Error
::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
143 $params['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
147 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
148 CRM_Utils_Array
::formatArrayKeys($params['preferred_communication_method']);
149 $contact->preferred_communication_method
= CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
150 unset($params['preferred_communication_method']);
153 $defaults = ['source' => CRM_Utils_Array
::value('contact_source', $params)];
154 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
155 $defaults['display_name'] = $params['organization_name'];
156 $defaults['sort_name'] = $params['organization_name'];
158 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
159 $defaults['display_name'] = $params['household_name'];
160 $defaults['sort_name'] = $params['household_name'];
162 $params = array_merge($defaults, $params);
164 $allNull = $contact->copyValues($params);
166 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
168 if ($contact->contact_type
=== 'Individual') {
170 // @todo allow the lines below to be overridden by input or hooks & add tests,
171 // as has been done for households and organizations.
172 // Format individual fields.
173 CRM_Contact_BAO_Individual
::format($params, $contact);
176 if (strlen($contact->display_name
) > 128) {
177 $contact->display_name
= substr($contact->display_name
, 0, 128);
179 if (strlen($contact->sort_name
) > 128) {
180 $contact->sort_name
= substr($contact->sort_name
, 0, 128);
183 $privacy = CRM_Utils_Array
::value('privacy', $params);
185 is_array($privacy) &&
189 foreach (self
::$_commPrefs as $name) {
190 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
194 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
195 // @todo - does this mean we can remove this block?
196 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
197 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
199 $contact->hash
= md5(uniqid(rand(), TRUE));
202 // Even if we don't need $employerId, it's important to call getFieldValue() before
203 // the contact is saved because we want the existing value to be cached.
204 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
205 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
210 CRM_Core_BAO_Log
::register($contact->id
,
216 if ($contact->contact_type
=== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
217 // Create current employer.
218 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
221 if (empty($params['contact_id'])) {
225 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
229 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
234 // Update cached employer name.
235 if ($contact->contact_type
=== 'Organization') {
236 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
245 * takes an associative array and creates a contact object and all the associated
246 * derived objects (i.e. individual, location, email, phone etc)
248 * This function is invoked from within the web form layer and also from the api layer
250 * @param array $params
251 * (reference ) an assoc array of name/value pairs.
252 * @param bool $fixAddress
253 * If we need to fix address.
254 * @param bool $invokeHooks
255 * If we need to invoke hooks.
257 * @param bool $skipDelete
258 * Unclear parameter, passed to website create
260 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
261 * Created or updated contribution object. We are deprecating returning an error in
262 * favour of exceptions
264 * @todo explain this parameter
267 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
269 if (empty($params['contact_type']) && empty($params['contact_id'])) {
273 $isEdit = !empty($params['contact_id']);
275 if ($isEdit && empty($params['contact_type'])) {
276 $params['contact_type'] = self
::getContactType($params['contact_id']);
279 if (!empty($params['check_permissions']) && isset($params['api_key'])
280 && !CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])
281 && !($isEdit && CRM_Core_Permission
::check('edit own api keys') && $params['contact_id'] == CRM_Core_Session
::getLoggedInContactID())
283 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify api key');
287 if (!empty($params['contact_id'])) {
288 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
291 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
295 self
::ensureGreetingParamsAreSet($params);
297 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
298 if (empty($params['contact_id'])) {
299 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
300 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
301 $params['preferred_language'] = $language;
304 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
305 if (empty($params['communication_style_id'])) {
306 $defaultCommunicationStyleId = CRM_Core_OptionGroup
::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
307 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
311 $transaction = new CRM_Core_Transaction();
313 $contact = self
::add($params);
315 // Not dying here is stupid, since we get into weird situation and into a bug that
316 // is impossible to figure out for the user or for us
318 CRM_Core_Error
::fatal();
321 $params['contact_id'] = $contact->id
;
323 if (Civi
::settings()->get('is_enabled')) {
324 // Enabling multisite causes the contact to be added to the domain group.
325 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
326 if (!empty($domainGroupID)) {
327 if (!empty($params['group']) && is_array($params['group'])) {
328 $params['group'][$domainGroupID] = 1;
331 $params['group'] = [$domainGroupID => 1];
336 if (array_key_exists('group', $params)) {
337 $contactIds = [$params['contact_id']];
338 foreach ($params['group'] as $groupId => $flag) {
340 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
342 elseif ($flag == -1) {
343 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
348 // Add location Block data.
349 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
350 foreach ($blocks as $name => $value) {
351 $contact->$name = $value;
353 if (!empty($params['updateBlankLocInfo'])) {
357 if (isset($params['website'])) {
358 CRM_Core_BAO_Website
::process($params['website'], $contact->id
, $skipDelete);
361 $userID = CRM_Core_Session
::singleton()->get('userID');
363 if (!empty($params['note'])) {
364 if (is_array($params['note'])) {
365 foreach ($params['note'] as $note) {
366 $contactId = $contact->id
;
367 if (isset($note['contact_id'])) {
368 $contactId = $note['contact_id'];
370 //if logged in user, overwrite contactId
372 $contactId = $userID;
376 'entity_id' => $contact->id
,
377 'entity_table' => 'civicrm_contact',
378 'note' => $note['note'],
379 'subject' => CRM_Utils_Array
::value('subject', $note),
380 'contact_id' => $contactId,
382 CRM_Core_BAO_Note
::add($noteParams);
386 $contactId = $contact->id
;
387 //if logged in user, overwrite contactId
389 $contactId = $userID;
393 'entity_id' => $contact->id
,
394 'entity_table' => 'civicrm_contact',
395 'note' => $params['note'],
396 'subject' => CRM_Utils_Array
::value('subject', $params),
397 'contact_id' => $contactId,
399 CRM_Core_BAO_Note
::add($noteParams);
403 // update the UF user_unique_id if that has changed
404 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
406 if (!empty($params['custom']) &&
407 is_array($params['custom'])
409 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
412 // make a civicrm_subscription_history entry only on contact create (CRM-777)
413 if (empty($params['contact_id'])) {
414 $subscriptionParams = [
415 'contact_id' => $contact->id
,
419 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
422 $transaction->commit();
424 // CRM-6367: fetch the right label for contact type’s display
425 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
426 'CRM_Contact_DAO_ContactType',
427 $contact->contact_type
,
432 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
436 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
439 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
443 // In order to prevent a series of expensive queries in intensive batch processing
444 // api calls may pass in skip_greeting_processing, probably doing it later via the
445 // scheduled job. CRM-21551
446 if (empty($params['skip_greeting_processing'])) {
447 self
::processGreetings($contact);
450 if (!empty($params['check_permissions'])) {
451 $contacts = [&$contact];
452 self
::unsetProtectedFields($contacts);
459 * Format the output of the create contact function
461 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
463 public static function unsetProtectedFields(&$contacts) {
464 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
465 $currentUser = CRM_Core_Session
::getLoggedInContactID();
466 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
467 foreach ($contacts as &$contact) {
468 $cid = is_object($contact) ?
$contact->id
: CRM_Utils_Array
::value('id', $contact);
469 if (!($editOwn && $cid == $currentUser)) {
470 if (is_object($contact)) {
471 unset($contact->api_key
);
474 unset($contact['api_key']);
482 * Ensure greeting parameters are set.
484 * By always populating greetings here we can be sure they are set if required & avoid a call later.
485 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
487 * @param array $params
489 * @throws \CiviCRM_API3_Exception
491 public static function ensureGreetingParamsAreSet(&$params) {
492 $allGreetingParams = ['addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id'];
493 $missingGreetingParams = [];
495 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
496 if (empty($params[$greetingParam])) {
497 $missingGreetingParams[$greetingIndex] = $greetingParam;
501 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
502 $savedGreetings = civicrm_api3('Contact', 'getsingle', [
503 'id' => $params['contact_id'],
504 'return' => array_keys($missingGreetingParams),
507 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
508 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
509 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
512 // Filter out other fields.
513 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
514 $params = array_merge($params, $savedGreetings);
517 foreach ($missingGreetingParams as $greetingName => $greeting) {
518 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
522 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
523 if ($params[$greetingParam] === 'null') {
524 // If we are setting it to null then null out the display field.
525 $params[$greetingIndex . '_display'] = 'null';
531 * Get the display name and image of a contact.
536 * @param bool $includeTypeInReturnParameters
537 * Should type be part of the returned array?
540 * the displayName and contactImage for this contact
542 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
543 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
545 SELECT civicrm_contact.*,
546 civicrm_email.email as email
548 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
549 AND civicrm_email.is_primary = 1
550 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
551 $dao = new CRM_Core_DAO();
554 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
555 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
557 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
558 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
561 // use email if display_name is empty
562 if (empty($dao->display_name
)) {
563 $displayName = $dao->email
;
566 $displayName = $dao->display_name
;
569 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
571 return $includeTypeInReturnParameters ?
[
575 $dao->contact_sub_type
,
577 ] : [$displayName, $image, $imageUrl];
583 * Add billing fields to the params if appropriate.
585 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
586 * don't then we should set the name fields to the billing fields AND add the preserveDBName
587 * parameter (which will tell the BAO only to set those fields if none already exist.
589 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
590 * matching is best done by hipsters.
592 * @param array $params
594 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
596 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
597 $nameFields = ['first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id'];
598 foreach ($nameFields as $field) {
599 if (!empty($params[$field])) {
603 // There are only 3 - we can iterate through them twice :-)
604 foreach ($nameFields as $field) {
605 if (!empty($params['billing_' . $field])) {
606 $params[$field] = $params['billing_' . $field];
608 $params['preserveDBName'] = TRUE;
614 * Resolve a state province string (UT or Utah) to an ID.
616 * If country has been passed in we should select a state belonging to that country.
618 * Alternatively we should choose from enabled countries, prioritising the default country.
620 * @param array $values
621 * @param int|null $countryID
625 * @throws \CRM_Core_Exception
627 protected static function resolveStateProvinceID($values, $countryID) {
630 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
631 if (CRM_Utils_Array
::lookupValue($values,
636 return $values['state_province_id'];
638 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
639 if (CRM_Utils_Array
::lookupValue($values,
644 return $values['state_province_id'];
649 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
650 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
651 // prefer matching country..
652 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, ['country_id' => Civi
::settings()->get('defaultContactCountry')]);
653 if (CRM_Utils_Array
::lookupValue($values,
658 return $values['state_province_id'];
661 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
662 if (CRM_Utils_Array
::lookupValue($values,
667 return $values['state_province_id'];
670 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
671 if (CRM_Utils_Array
::lookupValue($values,
676 return $values['state_province_id'];
678 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
679 if (CRM_Utils_Array
::lookupValue($values,
684 return $values['state_province_id'];
692 * Get the relevant location entity for the array key.
694 * Based on the field name we determine which location entity
695 * we are dealing with. Apart from a few specific ones they
696 * are mostly 'address' (the default).
698 * @param string $fieldName
702 protected static function getLocationEntityForKey($fieldName) {
703 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
706 if ($fieldName === 'phone_ext') {
713 * Create last viewed link to recently updated contact.
715 * @param array $crudLinkSpec
716 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
717 * - entity_table: string, eg "civicrm_contact"
721 * NULL if unavailable, or
722 * [path: string, query: string, title: string]
723 * @see CRM_Utils_System::createDefaultCrudLink
725 public function createDefaultCrudLink($crudLinkSpec) {
726 switch ($crudLinkSpec['action']) {
727 case CRM_Core_Action
::VIEW
:
729 'title' => $this->display_name
,
730 'path' => 'civicrm/contact/view',
738 case CRM_Core_Action
::UPDATE
:
740 'title' => $this->display_name
,
741 'path' => 'civicrm/contact/add',
744 'action' => 'update',
754 * Get the values for pseudoconstants for name->value and reverse.
756 * @param array $defaults
757 * (reference) the default values, some of which need to be resolved.
758 * @param bool $reverse
759 * Always true as this function is only called from one place..
763 * This is called specifically from the contact import parser & should be moved there
764 * as it is not truly a generic function.
767 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
768 // Hack for birth_date.
769 if (!empty($defaults['birth_date'])) {
770 if (is_array($defaults['birth_date'])) {
771 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
775 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
776 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
777 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
778 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
780 //lookup value of email/postal greeting, addressee, CRM-4575
781 foreach (self
::$_greetingTypes as $greeting) {
783 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
784 'greeting_type' => $greeting,
786 CRM_Utils_Array
::lookupValue($defaults, $greeting,
787 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
791 $blocks = ['address', 'im', 'phone'];
792 foreach ($blocks as $name) {
793 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
796 foreach ($defaults[$name] as $count => & $values) {
798 //get location type id.
799 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
801 if ($name == 'address') {
802 // FIXME: lookupValue doesn't work for vcard_name
803 if (!empty($values['location_type_id'])) {
804 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', ['labelColumn' => 'vcard_name']);
805 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
808 if (!CRM_Utils_Array
::lookupValue($values,
810 CRM_Core_PseudoConstant
::country(),
815 CRM_Utils_Array
::lookupValue($values,
817 CRM_Core_PseudoConstant
::countryIsoCode(),
821 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
822 if ($stateProvinceID) {
823 $values['state_province_id'] = $stateProvinceID;
826 if (!empty($values['state_province_id'])) {
827 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
830 $countyList = CRM_Core_PseudoConstant
::county();
832 CRM_Utils_Array
::lookupValue($values,
840 CRM_Utils_Array
::lookupValue($values,
842 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
847 if ($name == 'phone') {
848 CRM_Utils_Array
::lookupValue($values,
850 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
855 // Kill the reference.
862 * Fetch object based on array of properties.
864 * @param array $params
865 * (reference ) an assoc array of name/value pairs.
866 * @param array $defaults
867 * (reference ) an assoc array to hold the name / value pairs.
868 * in a hierarchical manner
869 * @param bool $microformat
870 * For location in microformat.
872 * @return CRM_Contact_BAO_Contact
874 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
875 if (array_key_exists('contact_id', $params)) {
876 $params['id'] = $params['contact_id'];
878 elseif (array_key_exists('id', $params)) {
879 $params['contact_id'] = $params['id'];
882 $contact = self
::getValues($params, $defaults);
884 unset($params['id']);
886 //get the block information for this contact
887 $entityBlock = ['contact_id' => $params['contact_id']];
888 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
889 $defaults = array_merge($defaults, $blocks);
890 foreach ($blocks as $block => $value) {
891 $contact->$block = $value;
894 if (!isset($params['noNotes'])) {
895 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
898 if (!isset($params['noRelationships'])) {
899 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
902 if (!isset($params['noGroups'])) {
903 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
906 if (!isset($params['noWebsite'])) {
907 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
914 * Get the display name of a contact.
919 * @return null|string
920 * display name of the contact if found
922 public static function displayName($id) {
925 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
932 * Delete a contact and all its associated records.
935 * Id of the contact to delete.
936 * @param bool $restore
937 * Whether to actually restore, not delete.
938 * @param bool $skipUndelete
939 * Whether to force contact delete or not.
940 * @param bool $checkPermissions
943 * Was contact deleted?
945 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
950 // If trash is disabled in system settings then we always skip
951 if (!Civi
::settings()->get('contact_undelete')) {
952 $skipUndelete = TRUE;
955 // make sure we have edit permission for this contact
957 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
958 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
964 // Restrict contact to be delete if contact has financial trxns
966 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent([$id], $error)) {
970 // make sure this contact_id does not have any membership types
971 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
974 'member_of_contact_id'
976 if ($membershipTypeID) {
980 $contact = new CRM_Contact_DAO_Contact();
982 if (!$contact->find(TRUE)) {
986 $contactType = $contact->contact_type
;
987 // currently we only clear employer cache.
988 // we are now deleting inherited membership if any.
989 if ($contact->contact_type
== 'Organization') {
990 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
991 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
992 if (!empty($relationshipDtls)) {
993 foreach ($relationshipDtls as $rId => $details) {
994 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
997 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
1001 return self
::contactTrashRestore($contact, TRUE);
1004 // start a new transaction
1005 $transaction = new CRM_Core_Transaction();
1007 if ($skipUndelete) {
1008 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
1010 //delete billing address if exists.
1011 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
1013 // delete the log entries since we dont have triggers enabled as yet
1014 $logDAO = new CRM_Core_DAO_Log();
1015 $logDAO->entity_table
= 'civicrm_contact';
1016 $logDAO->entity_id
= $id;
1019 // delete contact participants CRM-12155
1020 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
1022 // delete contact contributions CRM-12155
1023 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
1025 // do activity cleanup, CRM-5604
1026 CRM_Activity_BAO_Activity
::cleanupActivity($id);
1028 // delete all notes related to contact
1029 CRM_Core_BAO_Note
::cleanContactNotes($id);
1031 // delete cases related to contact
1032 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
1033 if (!empty($contactCases)) {
1034 foreach ($contactCases as $caseId) {
1035 //check if case is associate with other contact or not.
1036 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
1037 if (count($caseContactId) <= 1) {
1038 CRM_Case_BAO_Case
::deleteCase($caseId);
1046 self
::contactTrashRestore($contact);
1049 //delete the contact id from recently view
1050 CRM_Utils_Recent
::delContact($id);
1051 self
::updateContactCache($id, empty($restore));
1053 // delete any prevnext/dupe cache entry
1054 // These two calls are redundant in default deployments, but they're
1055 // meaningful if "prevnext" is memory-backed.
1056 Civi
::service('prevnext')->deleteItem($id);
1057 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1059 $transaction->commit();
1061 if ($skipUndelete) {
1062 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1069 * Action to update any caches relating to a recently update contact.
1071 * I was going to call this from delete as well as from create to ensure the delete is being
1072 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1073 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1074 * where the call involved a subquery that was locking the table.
1076 * @param int $contactID
1077 * @param bool $isTrashed
1079 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1082 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1083 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1084 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1085 // but this should not cause any change as long as contacts are not being trashed outside the
1086 // main functions for that.
1087 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', [1 => [$contactID, 'Integer']]);
1090 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1095 * Delete the image of a contact.
1098 * Id of the contact.
1101 * Was contact image deleted?
1103 public static function deleteContactImage($id) {
1108 $contact = new self();
1110 $contact->image_URL
= 'null';
1117 * Return proportional height and width of the image.
1119 * @param int $imageWidth
1122 * @param int $imageHeight
1126 * Thumb dimension of image
1128 public static function getThumbSize($imageWidth, $imageHeight) {
1130 if ($imageWidth && $imageHeight) {
1131 $imageRatio = $imageWidth / $imageHeight;
1136 if ($imageRatio > 1) {
1137 $imageThumbWidth = $thumbWidth;
1138 $imageThumbHeight = round($thumbWidth / $imageRatio);
1141 $imageThumbHeight = $thumbWidth;
1142 $imageThumbWidth = round($thumbWidth * $imageRatio);
1145 return [$imageThumbWidth, $imageThumbHeight];
1149 * Validate type of contact image.
1151 * @param array $params
1152 * @param string $imageIndex
1153 * Index of image field.
1154 * @param string $statusMsg
1155 * Status message to be set after operation.
1156 * @param string $opType
1157 * Type of operation like fatal, bounce etc.
1160 * true if valid image extension
1162 public static function processImageParams(
1164 $imageIndex = 'image_URL',
1178 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1179 $photo = basename($params[$imageIndex]['name']);
1180 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1184 unset($params[$imageIndex]);
1186 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1188 if ($opType == 'status') {
1189 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1191 // FIXME: additional support for fatal, bounce etc could be added.
1197 * Extract contact id from url for deleting contact image.
1199 public static function processImage() {
1201 $action = CRM_Utils_Request
::retrieve('action', 'String');
1202 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1203 // retrieve contact id in case of Profile context
1204 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1205 $cid = $cid ?
$cid : $id;
1206 if ($action & CRM_Core_Action
::DELETE
) {
1207 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1208 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1209 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1210 $session = CRM_Core_Session
::singleton();
1211 $toUrl = $session->popUserContext();
1212 CRM_Utils_System
::redirect($toUrl);
1218 * Function to set is_delete true or restore deleted contact.
1220 * @param CRM_Contact_DAO_Contact $contact
1221 * Contact DAO object.
1222 * @param bool $restore
1223 * True to set the is_delete = 1 else false to restore deleted contact,
1224 * i.e. is_delete = 0
1228 public static function contactTrashRestore($contact, $restore = FALSE) {
1230 'id' => $contact->id
,
1231 'is_deleted' => $restore ?
0 : 1,
1234 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1236 $params = [1 => [$contact->id
, 'Integer']];
1238 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1239 CRM_Core_DAO
::executeQuery($query, $params);
1242 $contact->copyValues($updateParams);
1244 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
1246 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1252 * Get contact type for a contact.
1255 * Id of the contact whose contact type is needed.
1258 * contact_type if $id found else null ""
1260 public static function getContactType($id) {
1261 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1265 * Get contact sub type for a contact.
1268 * Id of the contact whose contact sub type is needed.
1270 * @param string $implodeDelimiter
1273 * contact_sub_type if $id found else null ""
1275 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1276 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1278 return $implodeDelimiter ?
NULL : [];
1281 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1283 if ($implodeDelimiter) {
1284 $subtype = implode($implodeDelimiter, $subtype);
1290 * Get pair of contact-type and sub-type for a contact.
1293 * Id of the contact whose contact sub/contact type is needed.
1297 public static function getContactTypes($id) {
1298 $params = ['id' => $id];
1300 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1303 ['contact_type', 'contact_sub_type']
1308 if ($contact->contact_sub_type
) {
1309 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1311 array_unshift($contactTypes, $contact->contact_type
);
1313 return $contactTypes;
1316 CRM_Core_Error
::fatal();
1321 * Combine all the importable fields from the lower levels object.
1323 * The ordering is important, since currently we do not have a weight
1324 * scheme. Adding weight is super important
1326 * @param int|string $contactType contact Type
1327 * @param bool $status
1328 * Status is used to manipulate first title.
1329 * @param bool $showAll
1330 * If true returns all fields (includes disabled fields).
1331 * @param bool $isProfile
1332 * If its profile mode.
1333 * @param bool $checkPermission
1334 * If false, do not include permissioning clause (for custom data).
1336 * @param bool $withMultiCustomFields
1339 * array of importable Fields
1341 public static function importableFields(
1342 $contactType = 'Individual',
1346 $checkPermission = TRUE,
1347 $withMultiCustomFields = FALSE
1349 if (empty($contactType)) {
1350 $contactType = 'All';
1353 $cacheKeyString = "importableFields $contactType";
1354 $cacheKeyString .= $status ?
'_1' : '_0';
1355 $cacheKeyString .= $showAll ?
'_1' : '_0';
1356 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1357 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1358 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1360 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields) ?
: Civi
::cache('fields')->get($cacheKeyString);
1363 $fields = CRM_Contact_DAO_Contact
::import();
1365 // get the fields thar are meant for contact types
1366 if (in_array($contactType, [
1372 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1375 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1376 CRM_Core_DAO_Phone
::import(),
1377 CRM_Core_DAO_Email
::import(),
1378 CRM_Core_DAO_IM
::import(TRUE),
1379 CRM_Core_DAO_OpenID
::import()
1382 $locationFields = array_merge($locationFields,
1383 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1391 foreach ($locationFields as $key => $field) {
1392 $locationFields[$key]['hasLocationType'] = TRUE;
1395 $fields = array_merge($fields, $locationFields);
1397 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1398 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1401 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1402 $fields['url']['hasWebsiteType'] = TRUE;
1404 if ($contactType != 'All') {
1405 $fields = array_merge($fields,
1406 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1411 $withMultiCustomFields
1414 //unset the fields, which are not related to their
1421 'organization_name',
1433 'organization_name',
1456 foreach ($commonValues[$contactType] as $value) {
1457 unset($fields[$value]);
1461 foreach (['Individual', 'Household', 'Organization'] as $type) {
1462 $fields = array_merge($fields,
1463 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1468 $withMultiCustomFields
1475 $fields = array_merge($fields, [
1477 'title' => ts('Group(s)'),
1481 'title' => ts('Tag(s)'),
1485 'title' => ts('Note'),
1488 'communication_style_id' => [
1489 'title' => ts('Communication Style'),
1490 'name' => 'communication_style_id',
1495 //Sorting fields in alphabetical order(CRM-1507)
1496 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1498 Civi
::cache('fields')->set($cacheKeyString, $fields);
1501 self
::$_importableFields[$cacheKeyString] = $fields;
1505 $fields = array_merge(['do_not_import' => ['title' => ts('- do not import -')]],
1506 self
::$_importableFields[$cacheKeyString]
1510 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1511 self
::$_importableFields[$cacheKeyString]
1519 * Combine all the exportable fields from the lower levels object.
1521 * Currently we are using importable fields as exportable fields
1523 * @param int|string $contactType contact Type
1524 * @param bool $status
1525 * True while exporting primary contacts.
1526 * @param bool $export
1527 * True when used during export.
1528 * @param bool $search
1529 * True when used during search, might conflict with export param?.
1531 * @param bool $withMultiRecord
1532 * @param bool $checkPermissions
1535 * array of exportable Fields
1537 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1538 if (empty($contactType)) {
1539 $contactType = 'All';
1542 $cacheKeyString = "exportableFields $contactType";
1543 $cacheKeyString .= $export ?
'_1' : '_0';
1544 $cacheKeyString .= $status ?
'_1' : '_0';
1545 $cacheKeyString .= $search ?
'_1' : '_0';
1546 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1547 //calculates custom fields takes into account the logged in user & caches that for all users
1548 //as an interim fix we will cache the fields by contact
1549 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1551 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1552 if (!self
::$_exportableFields) {
1553 self
::$_exportableFields = [];
1556 // check if we can retrieve from database cache
1557 $fields = Civi
::cache('fields')->get($cacheKeyString);
1560 $fields = CRM_Contact_DAO_Contact
::export();
1562 // The fields are meant for contact types.
1563 if (in_array($contactType, [
1569 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1571 // add current employer for individuals
1572 $fields = array_merge($fields, [
1573 'current_employer' =>
1575 'name' => 'organization_name',
1576 'title' => ts('Current Employer'),
1581 'location_type' => [
1582 'name' => 'location_type',
1583 'where' => 'civicrm_location_type.name',
1584 'title' => ts('Location Type'),
1590 'name' => 'im_provider',
1591 'where' => 'civicrm_im.provider_id',
1592 'title' => ts('IM Provider'),
1596 $locationFields = array_merge($locationType,
1597 CRM_Core_DAO_Address
::export(),
1598 CRM_Core_DAO_Phone
::export(),
1599 CRM_Core_DAO_Email
::export(),
1601 CRM_Core_DAO_IM
::export(TRUE),
1602 CRM_Core_DAO_OpenID
::export()
1605 $locationFields = array_merge($locationFields,
1606 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1609 foreach ($locationFields as $key => $field) {
1610 $locationFields[$key]['hasLocationType'] = TRUE;
1613 $fields = array_merge($fields, $locationFields);
1616 $fields = array_merge($fields,
1617 CRM_Core_DAO_Worldregion
::export()
1620 $fields = array_merge($fields,
1621 CRM_Contact_DAO_Contact
::export()
1625 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1627 if ($contactType != 'All') {
1628 $fields = array_merge($fields,
1629 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1633 foreach (['Individual', 'Household', 'Organization'] as $type) {
1634 $fields = array_merge($fields,
1635 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1639 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1642 $fields = array_merge($fields, [
1644 'title' => ts('Group(s)'),
1648 'title' => ts('Tag(s)'),
1652 'title' => ts('Note(s)'),
1658 $fields = array_merge($fields, [
1660 'title' => ts('Group(s)'),
1664 'title' => ts('Tag(s)'),
1668 'title' => ts('Note(s)'),
1674 //Sorting fields in alphabetical order(CRM-1507)
1675 foreach ($fields as $k => $v) {
1676 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1679 $fields = array_merge($sortArray, $fields);
1680 //unset the field which are not related to their contact type.
1681 if ($contactType != 'All') {
1687 'organization_name',
1688 'email_greeting_custom',
1689 'postal_greeting_custom',
1702 'organization_name',
1710 'email_greeting_custom',
1711 'postal_greeting_custom',
1727 'email_greeting_custom',
1728 'postal_greeting_custom',
1738 foreach ($commonValues[$contactType] as $value) {
1739 unset($fields[$value]);
1743 Civi
::cache('fields')->set($cacheKeyString, $fields);
1745 self
::$_exportableFields[$cacheKeyString] = $fields;
1749 $fields = self
::$_exportableFields[$cacheKeyString];
1752 $fields = array_merge(['' => ['title' => ts('- Contact Fields -')]],
1753 self
::$_exportableFields[$cacheKeyString]
1761 * Get the all contact details (Hierarchical).
1763 * @param int $contactId
1765 * @param array $fields
1771 public static function getHierContactDetails($contactId, $fields) {
1772 $params = [['contact_id', '=', $contactId, 0, 0]];
1775 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1777 // We don't know the contents of return properties, but we need the lower
1778 // level ids of the contact so add a few fields.
1779 $returnProperties['first_name'] = 1;
1780 $returnProperties['organization_name'] = 1;
1781 $returnProperties['household_name'] = 1;
1782 $returnProperties['contact_type'] = 1;
1783 $returnProperties['contact_sub_type'] = 1;
1784 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1788 * Given a set of flat profile style field names, create a hierarchy.
1790 * This is for the query to use, create the right sql.
1793 * @param int $contactId
1797 * A hierarchical property tree if appropriate
1799 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1800 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1802 $returnProperties = [];
1804 $multipleFields = ['website' => 'url'];
1805 foreach ($fields as $name => $dontCare) {
1806 if (strpos($name, '-') !== FALSE) {
1807 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1809 if (!in_array($fieldName, $multipleFields)) {
1810 if ($id == 'Primary') {
1811 $locationTypeName = 1;
1814 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1815 if (!$locationTypeName) {
1820 if (empty($returnProperties['location'])) {
1821 $returnProperties['location'] = [];
1823 if (empty($returnProperties['location'][$locationTypeName])) {
1824 $returnProperties['location'][$locationTypeName] = [];
1825 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1827 if (in_array($fieldName, [
1835 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1838 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1841 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1842 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1845 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1849 $returnProperties['website'][$id][$fieldName] = 1;
1853 $returnProperties[$name] = 1;
1857 return $returnProperties;
1861 * Return the primary location type of a contact.
1863 * $params int $contactId contact_id
1864 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1865 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1867 * @param int $contactId
1868 * @param bool $skipDefaultPriamry
1869 * @param null $block
1872 * $locationType location_type_id
1874 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1876 $entityBlock = ['contact_id' => $contactId];
1877 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1878 foreach ($blocks[$block] as $key => $value) {
1879 if (!empty($value['is_primary'])) {
1880 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1887 IF ( civicrm_email.location_type_id IS NULL,
1888 IF ( civicrm_address.location_type_id IS NULL,
1889 IF ( civicrm_phone.location_type_id IS NULL,
1890 IF ( civicrm_im.location_type_id IS NULL,
1891 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1892 ,civicrm_im.location_type_id)
1893 ,civicrm_phone.location_type_id)
1894 ,civicrm_address.location_type_id)
1895 ,civicrm_email.location_type_id) as locationType
1896 FROM civicrm_contact
1897 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1898 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1899 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1900 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1901 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1902 WHERE civicrm_contact.id = %1 ";
1904 $params = [1 => [$contactId, 'Integer']];
1906 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1908 $locationType = NULL;
1909 if ($dao->fetch()) {
1910 $locationType = $dao->locationType
;
1913 if (isset($locationType)) {
1914 return $locationType;
1916 elseif ($skipDefaultPriamry) {
1917 // if there is no primary contact location then return null
1921 // if there is no primart contact location, then return default
1922 // location type of the system
1923 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1924 return $defaultLocationType->id
;
1929 * Get the display name, primary email and location type of a contact.
1932 * Id of the contact.
1935 * Array of display_name, email if found, do_not_email or (null,null,null)
1937 public static function getContactDetails($id) {
1938 // check if the contact type
1939 $contactType = self
::getContactType($id);
1941 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1944 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1945 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1946 WHERE civicrm_contact.id = %1
1947 ORDER BY civicrm_email.is_primary DESC";
1948 $params = [1 => [$id, 'Integer']];
1949 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1951 if ($dao->fetch()) {
1952 if ($contactType == 'Individual') {
1953 if ($dao->first_name ||
$dao->last_name
) {
1954 $name = "{$dao->first_name} {$dao->last_name}";
1957 $name = $dao->display_name
;
1961 $name = $dao->display_name
;
1963 $email = $dao->email
;
1964 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1965 $onHold = $dao->on_hold ?
TRUE : FALSE;
1966 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1967 return [$name, $email, $doNotEmail, $onHold, $isDeceased];
1969 return [NULL, NULL, NULL, NULL, NULL];
1973 * Add/edit/register contacts through profile.
1975 * @param array $params
1976 * Array of profile fields to be edited/added.
1977 * @param array $fields
1978 * Array of fields from UFGroup.
1979 * @param int $contactID
1980 * Id of the contact to be edited/added.
1981 * @param int $addToGroupID
1982 * Specifies the default group to which contact is added.
1983 * @param int $ufGroupId
1984 * Uf group id (profile id).
1985 * @param string $ctype
1986 * @param bool $visibility
1987 * Basically lets us know where this request is coming from.
1988 * if via a profile from web, we restrict what groups are changed
1991 * contact id created/edited
1993 public static function createProfileContact(
1997 $addToGroupID = NULL,
2002 // add ufGroupID to params array ( CRM-2012 )
2004 $params['uf_group_id'] = $ufGroupId;
2006 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
2008 // If a user has logged in, or accessed via a checksum
2009 // Then deliberately 'blanking' a value in the profile should remove it from their record
2010 $session = CRM_Core_Session
::singleton();
2011 $params['updateBlankLocInfo'] = TRUE;
2012 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
2013 $params['updateBlankLocInfo'] = FALSE;
2018 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
2022 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
2025 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
2027 // manage is_opt_out
2028 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
2029 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
2030 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
2031 $data['is_opt_out'] = $isOptOut;
2032 // on change, create new civicrm_subscription_history entry
2033 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2035 'contact_id' => $contactDetails['contact_id'],
2036 'status' => $isOptOut ?
'Removed' : 'Added',
2039 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2043 $contact = self
::create($data);
2045 // contact is null if the profile does not have any contact fields
2047 $contactID = $contact->id
;
2050 if (empty($contactID)) {
2051 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
2054 // Process group and tag
2055 if (!empty($fields['group'])) {
2057 // this for sure means we are coming in via profile since i added it to fix
2058 // removing contacts from user groups -- lobo
2062 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2065 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2066 // Convert comma separated form values from select2 v3
2067 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2068 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2071 //to add profile in default group
2072 if (is_array($addToGroupID)) {
2073 $contactIds = [$contactID];
2074 foreach ($addToGroupID as $groupId) {
2075 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2078 elseif ($addToGroupID) {
2079 $contactIds = [$contactID];
2080 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2083 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
2086 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2089 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2095 * Format profile contact parameters.
2097 * @param array $params
2099 * @param int $contactID
2100 * @param int $ufGroupId
2101 * @param null $ctype
2102 * @param bool $skipCustom
2106 public static function formatProfileContactParams(
2115 $data = $contactDetails = [];
2117 // get the contact details (hier)
2119 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
2121 $contactDetails = $details[$contactID];
2122 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
2123 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
2126 //we should get contact type only if contact
2128 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2130 //special case to handle profile with only contact fields
2131 if ($data['contact_type'] == 'Contact') {
2132 $data['contact_type'] = 'Individual';
2134 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2135 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2139 $data['contact_type'] = $ctype;
2142 $data['contact_type'] = 'Individual';
2146 //fix contact sub type CRM-5125
2147 if (array_key_exists('contact_sub_type', $params) &&
2148 !empty($params['contact_sub_type'])
2150 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2152 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2153 !empty($params['contact_sub_type_hidden'])
2155 // if profile was used, and had any subtype, we obtain it from there
2156 //CRM-13596 - add to existing contact types, rather than overwriting
2157 if (empty($data['contact_sub_type'])) {
2158 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2159 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2162 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2163 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2164 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2165 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2166 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2171 if ($ctype == 'Organization') {
2172 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2174 elseif ($ctype == 'Household') {
2175 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2183 $data['contact_id'] = $contactID;
2184 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2187 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2188 $defaultLocationId = $defaultLocation->id
;
2191 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2193 $blocks = ['email', 'phone', 'im', 'openid'];
2195 $multiplFields = ['url'];
2196 // prevent overwritten of formatted array, reset all block from
2197 // params if it is not in valid format (since import pass valid format)
2198 foreach ($blocks as $blk) {
2199 if (array_key_exists($blk, $params) &&
2200 !is_array($params[$blk])
2202 unset($params[$blk]);
2206 $primaryPhoneLoc = NULL;
2207 $session = CRM_Core_Session
::singleton();
2208 foreach ($params as $key => $value) {
2209 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2211 if ($locTypeId == 'Primary') {
2213 if (in_array($fieldName, $blocks)) {
2214 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2217 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2219 $primaryLocationType = $locTypeId;
2222 $locTypeId = $defaultLocationId;
2226 if (is_numeric($locTypeId) &&
2227 !in_array($fieldName, $multiplFields) &&
2228 substr($fieldName, 0, 7) != 'custom_'
2230 $index = $locTypeId;
2232 if (is_numeric($typeId)) {
2233 $index .= '-' . $typeId;
2235 if (!in_array($index, $locationType)) {
2236 $locationType[$count] = $index;
2240 $loc = CRM_Utils_Array
::key($index, $locationType);
2242 $blockName = self
::getLocationEntityForKey($fieldName);
2244 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2246 //set is_billing true, for location type "Billing"
2247 if ($locTypeId == $billingLocationTypeId) {
2248 $data[$blockName][$loc]['is_billing'] = 1;
2252 //get the primary location type
2253 if ($locTypeId == $primaryLocationType) {
2254 $data[$blockName][$loc]['is_primary'] = 1;
2257 elseif ($locTypeId == $defaultLocationId) {
2258 $data[$blockName][$loc]['is_primary'] = 1;
2261 if (in_array($fieldName, ['phone'])) {
2263 $data['phone'][$loc]['phone_type_id'] = $typeId;
2266 $data['phone'][$loc]['phone_type_id'] = '';
2268 $data['phone'][$loc]['phone'] = $value;
2270 //special case to handle primary phone with different phone types
2271 // in this case we make first phone type as primary
2272 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2273 $primaryPhoneLoc = $loc;
2276 if ($loc != $primaryPhoneLoc) {
2277 unset($data['phone'][$loc]['is_primary']);
2280 elseif ($fieldName == 'email') {
2281 $data['email'][$loc]['email'] = $value;
2282 if (empty($contactID)) {
2283 $data['email'][$loc]['is_primary'] = 1;
2286 elseif ($fieldName == 'im') {
2287 if (isset($params[$key . '-provider_id'])) {
2288 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2290 if (strpos($key, '-provider_id') !== FALSE) {
2291 $data['im'][$loc]['provider_id'] = $params[$key];
2294 $data['im'][$loc]['name'] = $value;
2297 elseif ($fieldName == 'openid') {
2298 $data['openid'][$loc]['openid'] = $value;
2301 if ($fieldName === 'state_province') {
2303 if (is_numeric($value) && ((int ) $value) >= 1000) {
2304 $data['address'][$loc]['state_province_id'] = $value;
2306 elseif (empty($value)) {
2307 $data['address'][$loc]['state_province_id'] = '';
2310 $data['address'][$loc]['state_province'] = $value;
2313 elseif ($fieldName === 'country') {
2315 if (is_numeric($value) && ((int ) $value) >= 1000
2317 $data['address'][$loc]['country_id'] = $value;
2319 elseif (empty($value)) {
2320 $data['address'][$loc]['country_id'] = '';
2323 $data['address'][$loc]['country'] = $value;
2326 elseif ($fieldName === 'county') {
2327 $data['address'][$loc]['county_id'] = $value;
2329 elseif ($fieldName == 'address_name') {
2330 $data['address'][$loc]['name'] = $value;
2332 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2333 $data['address'][$loc][substr($fieldName, 8)] = $value;
2336 $data[$blockName][$loc][$fieldName] = $value;
2341 if (substr($key, 0, 4) === 'url-') {
2342 $websiteField = explode('-', $key);
2343 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2344 $data['website'][$websiteField[1]]['url'] = $value;
2346 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2347 //save email/postal greeting and addressee values if any, CRM-4575
2348 $data[$key . '_id'] = $value;
2350 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2351 // for autocomplete transfer hidden value instead of label
2352 if ($params[$key] && isset($params[$key . '_id'])) {
2353 $value = $params[$key . '_id'];
2356 // we need to append time with date
2357 if ($params[$key] && isset($params[$key . '_time'])) {
2358 $value .= ' ' . $params[$key . '_time'];
2361 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2362 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2363 ($value == '' ||
!isset($value))
2369 if (!empty($params['customRecordValues'])) {
2370 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2371 foreach ($params['customRecordValues'] as $recId => $customFields) {
2372 if (is_array($customFields) && !empty($customFields)) {
2373 foreach ($customFields as $customFieldName) {
2374 if ($customFieldName == $key) {
2384 //CRM-13596 - check for contact_sub_type_hidden first
2385 if (array_key_exists('contact_sub_type_hidden', $params)) {
2386 $type = $params['contact_sub_type_hidden'];
2389 $type = $data['contact_type'];
2390 if (!empty($data['contact_sub_type'])) {
2391 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2395 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2405 elseif ($key === 'edit') {
2409 if ($key === 'location') {
2410 foreach ($value as $locationTypeId => $field) {
2411 foreach ($field as $block => $val) {
2412 if ($block === 'address' && array_key_exists('address_name', $val)) {
2413 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2418 if ($key === 'phone' && isset($params['phone_ext'])) {
2419 $data[$key] = $value;
2420 foreach ($value as $cnt => $phoneBlock) {
2421 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2422 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2426 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
2427 && ($value == '' ||
!isset($value)) &&
2428 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2429 ($key === 'current_employer' && empty($params['current_employer']))) {
2430 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2431 // to avoid update with empty values
2435 $data[$key] = $value;
2441 if (!isset($data['contact_type'])) {
2442 $data['contact_type'] = 'Individual';
2445 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2446 $privacy = CRM_Core_SelectValues
::privacy();
2447 foreach ($privacy as $key => $value) {
2448 if (array_key_exists($key, $fields)) {
2449 // do not reset values for existing contacts, if fields are added to a profile
2450 if (array_key_exists($key, $params)) {
2451 $data[$key] = $params[$key];
2452 if (empty($params[$key])) {
2456 elseif (!$contactID) {
2462 return [$data, $contactDetails];
2466 * Find the get contact details.
2468 * This function does not respect ACLs for now, which might need to be rectified at some
2469 * stage based on how its used.
2471 * @param string $mail
2472 * Primary email address of the contact.
2473 * @param string $ctype
2476 * @return object|null
2477 * $dao contact details
2479 public static function matchContactOnEmail($mail, $ctype = NULL) {
2480 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2481 $mail = $strtolower(trim($mail));
2483 SELECT civicrm_contact.id as contact_id,
2484 civicrm_contact.hash as hash,
2485 civicrm_contact.contact_type as contact_type,
2486 civicrm_contact.contact_sub_type as contact_sub_type
2487 FROM civicrm_contact
2488 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2490 if (Civi
::settings()->get('uniq_email_per_site')) {
2491 // try to find a match within a site (multisite).
2492 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2493 if (!empty($groups)) {
2495 INNER JOIN civicrm_group_contact gc ON
2496 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2501 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2502 $p = [1 => [$mail, 'String']];
2505 $query .= " AND civicrm_contact.contact_type = %3";
2506 $p[3] = [$ctype, 'String'];
2509 $query .= " ORDER BY civicrm_email.is_primary DESC";
2511 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2513 if ($dao->fetch()) {
2520 * Find the contact details associated with an OpenID.
2522 * @param string $openId
2523 * OpenId of the contact.
2524 * @param string $ctype
2527 * @return object|null
2528 * $dao contact details
2530 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2531 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2532 $openId = $strtolower(trim($openId));
2534 SELECT civicrm_contact.id as contact_id,
2535 civicrm_contact.hash as hash,
2536 civicrm_contact.contact_type as contact_type,
2537 civicrm_contact.contact_sub_type as contact_sub_type
2538 FROM civicrm_contact
2539 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2540 WHERE civicrm_openid.openid = %1";
2541 $p = [1 => [$openId, 'String']];
2544 $query .= " AND civicrm_contact.contact_type = %3";
2545 $p[3] = [$ctype, 'String'];
2548 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2550 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2552 if ($dao->fetch()) {
2559 * Get primary email of the contact.
2561 * @param int $contactID
2565 * Email address if present else null
2567 public static function getPrimaryEmail($contactID) {
2568 // fetch the primary email
2570 SELECT civicrm_email.email as email
2571 FROM civicrm_contact
2572 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2573 WHERE civicrm_email.is_primary = 1
2574 AND civicrm_contact.id = %1";
2575 $p = [1 => [$contactID, 'Integer']];
2576 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2579 if ($dao->fetch()) {
2580 $email = $dao->email
;
2586 * Function to get primary OpenID of the contact.
2588 * @param int $contactID
2592 * >openid OpenID if present else null
2594 public static function getPrimaryOpenId($contactID) {
2595 // fetch the primary OpenID
2597 SELECT civicrm_openid.openid as openid
2598 FROM civicrm_contact
2599 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2600 WHERE civicrm_contact.id = %1
2601 AND civicrm_openid.is_primary = 1";
2602 $p = [1 => [$contactID, 'Integer']];
2603 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2606 if ($dao->fetch()) {
2607 $openId = $dao->openid
;
2613 * Fetch the object and store the values in the values array.
2615 * @param array $params
2616 * Input parameters to find object.
2617 * @param array $values
2618 * Output values of the object.
2620 * @return CRM_Contact_BAO_Contact|null
2621 * The found object or null
2623 public static function getValues(&$params, &$values) {
2624 $contact = new CRM_Contact_BAO_Contact();
2626 $contact->copyValues($params);
2628 if ($contact->find(TRUE)) {
2630 CRM_Core_DAO
::storeValues($contact, $values);
2633 foreach (self
::$_commPrefs as $name) {
2634 if (isset($contact->$name)) {
2635 $privacy[$name] = $contact->$name;
2639 if (!empty($privacy)) {
2640 $values['privacy'] = $privacy;
2643 // communication Prefferance
2644 $preffComm = $comm = [];
2645 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2646 $contact->preferred_communication_method
2648 foreach ($comm as $value) {
2649 $preffComm[$value] = 1;
2651 $temp = ['preferred_communication_method' => $contact->preferred_communication_method
];
2654 'preferred_communication_method' => [
2655 'newName' => 'preferred_communication_method_display',
2656 'groupName' => 'preferred_communication_method',
2660 // @todo This can be figured out from metadata & we can avoid the uncached query.
2661 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2663 $values['preferred_communication_method'] = $preffComm;
2664 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2666 if ($contact->preferred_mail_format
) {
2667 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2668 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2671 // get preferred languages
2672 if (!empty($contact->preferred_language
)) {
2673 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2676 // Calculating Year difference
2677 if ($contact->birth_date
) {
2678 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2679 if ($birthDate < date('Ymd')) {
2680 $age = CRM_Utils_Date
::calculateAge($birthDate);
2681 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2682 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2686 $contact->contact_id
= $contact->id
;
2694 * Given the component name and returns the count of participation of contact.
2696 * @param string $component
2697 * Input component name.
2698 * @param int $contactId
2700 * @param string $tableName
2701 * Optional tableName if component is custom group.
2704 * total number in database
2706 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2708 switch ($component) {
2710 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2713 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2714 CRM_Contact_BAO_Relationship
::CURRENT
,
2723 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2726 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2729 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2732 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2734 case 'contribution':
2735 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2738 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2741 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2744 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2747 return CRM_Case_BAO_Case
::caseCount($contactId);
2750 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2754 'contact_id' => $contactId,
2757 'context' => 'activity',
2759 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2762 $params = ['contact_id' => $contactId];
2763 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2766 $custom = explode('_', $component);
2767 if ($custom['0'] = 'custom') {
2769 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2771 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2772 return CRM_Core_DAO
::singleValueQuery($queryString);
2778 * Update contact greetings if an update has resulted in a custom field change.
2780 * @param array $updatedFields
2781 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2782 * @param array $contactParams
2783 * Parameters known about the contact. At minimum array('contact_id' => x).
2784 * Fields in this array will take precedence over DB fields (so far only
2785 * in the case of greeting id fields).
2787 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2788 $contactID = $contactParams['contact_id'];
2789 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2790 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2791 if (!empty($tokens['all']['contact'])) {
2792 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2793 if (!empty($affectedTokens)) {
2794 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2795 $contact = new CRM_Contact_BAO_Contact();
2796 $contact->id
= $contactID;
2797 CRM_Contact_BAO_Contact
::processGreetings($contact);
2803 * Process greetings and cache.
2805 * @param object $contact
2806 * Contact object after save.
2808 public static function processGreetings(&$contact) {
2810 //@todo this function does a lot of unnecessary loading.
2811 // ensureGreetingParamsAreSet now makes sure that the contact is
2812 // loaded and using updateGreetingsOnTokenFieldChange
2813 // allows us the possibility of only doing an update if required.
2815 // The contact object has not always required the
2816 // fields that are required to calculate greetings
2817 // so we need to retrieve it again.
2818 if ($contact->_query
!== FALSE) {
2819 $contact->find(TRUE);
2822 // store object values to an array
2823 $contactDetails = [];
2824 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2825 $contactDetails = [[$contact->id
=> $contactDetails]];
2827 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2828 $updateQueryString = [];
2830 //cache email and postal greeting to greeting display
2831 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2832 $emailGreetingString = $contact->email_greeting_custom
;
2834 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2835 // the filter value for Individual contact type is set to 1
2837 'contact_type' => $contact->contact_type
,
2838 'greeting_type' => 'email_greeting',
2841 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2842 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2843 $updateQueryString[] = " email_greeting_custom = NULL ";
2846 if ($contact->email_greeting_custom
) {
2847 $updateQueryString[] = " email_greeting_display = NULL ";
2851 if ($emailGreetingString) {
2852 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2855 'CRM_Contact_BAO_Contact'
2857 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2858 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2862 if ($contact->postal_greeting_custom
!== 'null' && $contact->postal_greeting_custom
) {
2863 $postalGreetingString = $contact->postal_greeting_custom
;
2865 elseif ($contact->postal_greeting_id
!== 'null' && $contact->postal_greeting_id
) {
2867 'contact_type' => $contact->contact_type
,
2868 'greeting_type' => 'postal_greeting',
2870 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2871 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2872 $updateQueryString[] = " postal_greeting_custom = NULL ";
2875 if ($contact->postal_greeting_custom
) {
2876 $updateQueryString[] = " postal_greeting_display = NULL ";
2880 if ($postalGreetingString) {
2881 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2884 'CRM_Contact_BAO_Contact'
2886 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2887 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2891 if ($contact->addressee_custom
!== 'null' && $contact->addressee_custom
) {
2892 $addresseeString = $contact->addressee_custom
;
2894 elseif ($contact->addressee_id
!== 'null' && $contact->addressee_id
) {
2896 'contact_type' => $contact->contact_type
,
2897 'greeting_type' => 'addressee',
2900 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2901 $addresseeString = $addressee[$contact->addressee_id
];
2902 $updateQueryString[] = " addressee_custom = NULL ";
2905 if ($contact->addressee_custom
) {
2906 $updateQueryString[] = " addressee_display = NULL ";
2910 if ($addresseeString) {
2911 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2914 'CRM_Contact_BAO_Contact'
2916 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2917 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2920 if (!empty($updateQueryString)) {
2921 $updateQueryString = implode(',', $updateQueryString);
2922 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2923 CRM_Core_DAO
::executeQuery($queryString);
2928 * Retrieve loc block ids w/ given condition.
2930 * @param int $contactId
2932 * @param array $criteria
2933 * Key => value pair which should be.
2934 * fulfill by return record ids.
2935 * @param string $condOperator
2936 * Operator use for grouping multiple conditions.
2939 * loc block ids which fulfill condition.
2941 public static function getLocBlockIds($contactId, $criteria = [], $condOperator = 'AND') {
2944 return $locBlockIds;
2947 foreach (['Email', 'OpenID', 'Phone', 'Address', 'IM'] as $block) {
2948 $name = strtolower($block);
2949 $className = "CRM_Core_DAO_$block";
2950 $blockDAO = new $className();
2952 // build the condition.
2953 if (is_array($criteria)) {
2954 $fields = $blockDAO->fields();
2956 foreach ($criteria as $field => $value) {
2957 if (array_key_exists($field, $fields)) {
2958 $cond = "( $field = $value )";
2959 // value might be zero or null.
2960 if (!$value ||
strtolower($value) === 'null') {
2961 $cond = "( $field = 0 OR $field IS NULL )";
2963 $conditions[] = $cond;
2966 if (!empty($conditions)) {
2967 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2971 $blockDAO->contact_id
= $contactId;
2973 while ($blockDAO->fetch()) {
2974 $locBlockIds[$name][] = $blockDAO->id
;
2978 return $locBlockIds;
2982 * Build context menu items.
2984 * @param int $contactId
2987 * Array of context menu for logged in user.
2989 public static function contextMenu($contactId = NULL) {
2992 'title' => ts('View Contact'),
2994 'ref' => 'view-contact',
2995 'class' => 'no-popup',
2997 'permissions' => ['view all contacts'],
3000 'title' => ts('Edit Contact'),
3002 'ref' => 'edit-contact',
3003 'class' => 'no-popup',
3005 'permissions' => ['edit all contacts'],
3008 'title' => ts('Delete Contact'),
3010 'ref' => 'delete-contact',
3012 'permissions' => ['access deleted contacts', 'delete contacts'],
3015 'title' => ts('Add Contribution'),
3017 'ref' => 'new-contribution',
3018 'key' => 'contribution',
3019 'tab' => 'contribute',
3020 'component' => 'CiviContribute',
3021 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
3022 'reset=1&action=add&context=contribution'
3025 'access CiviContribute',
3026 'edit contributions',
3030 'title' => ts('Register for Event'),
3032 'ref' => 'new-participant',
3033 'key' => 'participant',
3034 'tab' => 'participant',
3035 'component' => 'CiviEvent',
3036 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3039 'edit event participants',
3043 'title' => ts('Record Activity'),
3045 'ref' => 'new-activity',
3046 'key' => 'activity',
3047 'permissions' => ['edit all contacts'],
3050 'title' => ts('Add Pledge'),
3052 'ref' => 'new-pledge',
3055 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3056 'reset=1&action=add&context=pledge'
3058 'component' => 'CiviPledge',
3060 'access CiviPledge',
3065 'title' => ts('Add Membership'),
3067 'ref' => 'new-membership',
3068 'key' => 'membership',
3070 'component' => 'CiviMember',
3071 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3072 'reset=1&action=add&context=membership'
3075 'access CiviMember',
3080 'title' => ts('Add Case'),
3082 'ref' => 'new-case',
3085 'component' => 'CiviCase',
3086 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3087 'permissions' => ['add cases'],
3090 'title' => ts('Add Grant'),
3092 'ref' => 'new-grant',
3095 'component' => 'CiviGrant',
3096 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3097 'reset=1&action=add&context=grant'
3099 'permissions' => ['edit grants'],
3102 'title' => ts('Add Relationship'),
3104 'ref' => 'new-relationship',
3107 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3108 'reset=1&action=add'
3110 'permissions' => ['edit all contacts'],
3113 'title' => ts('Add Note'),
3115 'ref' => 'new-note',
3118 'class' => 'medium-popup',
3119 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3120 'reset=1&action=add'
3122 'permissions' => ['edit all contacts'],
3125 'title' => ts('Send an Email'),
3127 'ref' => 'new-email',
3129 'permissions' => ['view all contacts'],
3132 'title' => ts('Add to Group'),
3134 'ref' => 'group-add-contact',
3137 'permissions' => ['edit groups'],
3140 'title' => ts('Tag Contact'),
3142 'ref' => 'tag-contact',
3145 'permissions' => ['edit all contacts'],
3149 $menu['otherActions'] = [
3151 'title' => ts('Print Summary'),
3152 'description' => ts('Printer-friendly view of this page.'),
3154 'ref' => 'crm-contact-print',
3157 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3161 'icon' => 'crm-i fa-print',
3164 'title' => ts('vCard'),
3165 'description' => ts('vCard record for this contact.'),
3167 'ref' => 'crm-contact-vcard',
3170 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3174 'icon' => 'crm-i fa-list-alt',
3178 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3179 $menu['otherActions']['dashboard'] = [
3180 'title' => ts('Contact Dashboard'),
3181 'description' => ts('Contact Dashboard'),
3183 'ref' => 'crm-contact-dashboard',
3184 'key' => 'dashboard',
3185 'tab' => 'dashboard',
3186 'class' => 'dashboard',
3187 // NOTE: As an alternative you can also build url on CMS specific way
3188 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3189 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3190 'icon' => 'crm-i fa-tachometer',
3194 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3196 $menu['otherActions']['user-record'] = [
3197 'title' => ts('User Record'),
3198 'description' => ts('User Record'),
3200 'ref' => 'crm-contact-user-record',
3201 'key' => 'user-record',
3202 'tab' => 'user-record',
3203 'class' => 'user-record',
3204 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3205 'icon' => 'crm-i fa-user',
3208 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3209 $menu['otherActions']['user-add'] = [
3210 'title' => ts('Create User Record'),
3211 'description' => ts('Create User Record'),
3213 'ref' => 'crm-contact-user-add',
3214 'key' => 'user-add',
3215 'tab' => 'user-add',
3216 'class' => 'user-add',
3217 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3218 'icon' => 'crm-i fa-user-plus',
3222 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3223 //1. check for component is active.
3224 //2. check for user permissions.
3225 //3. check for acls.
3226 //3. edit and view contact are directly accessible to user.
3228 $aclPermissionedTasks = [
3233 'group-add-contact',
3237 $corePermission = CRM_Core_Permission
::getPermission();
3240 foreach ($menu as $key => $values) {
3241 if ($key !== 'otherActions') {
3243 // user does not have necessary permissions.
3244 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3247 // build directly accessible action menu.
3248 if (in_array($values['ref'], [
3252 $contextMenu['primaryActions'][$key] = [
3253 'title' => $values['title'],
3254 'ref' => $values['ref'],
3255 'class' => CRM_Utils_Array
::value('class', $values),
3256 'key' => $values['key'],
3261 // finally get menu item for -more- action widget.
3262 $contextMenu['moreActions'][$values['weight']] = [
3263 'title' => $values['title'],
3264 'ref' => $values['ref'],
3265 'href' => CRM_Utils_Array
::value('href', $values),
3266 'tab' => CRM_Utils_Array
::value('tab', $values),
3267 'class' => CRM_Utils_Array
::value('class', $values),
3268 'key' => $values['key'],
3272 foreach ($values as $value) {
3273 // user does not have necessary permissions.
3274 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3278 // finally get menu item for -more- action widget.
3279 $contextMenu['otherActions'][$value['weight']] = [
3280 'title' => $value['title'],
3281 'ref' => $value['ref'],
3282 'href' => CRM_Utils_Array
::value('href', $value),
3283 'tab' => CRM_Utils_Array
::value('tab', $value),
3284 'class' => CRM_Utils_Array
::value('class', $value),
3285 'icon' => CRM_Utils_Array
::value('icon', $value),
3286 'key' => $value['key'],
3292 ksort($contextMenu['moreActions']);
3293 ksort($contextMenu['otherActions']);
3295 return $contextMenu;
3299 * Check if user has permissions to access items in action menu.
3301 * @param array $aclPermissionedTasks
3302 * Array containing ACL related tasks.
3303 * @param string $corePermission
3304 * The permission of the user (edit or view or null).
3305 * @param array $menuOptions
3306 * Array containing params of the menu (title, href, etc).
3309 * TRUE if user has all permissions, FALSE if otherwise.
3311 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3312 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3314 // if component action - make sure component is enable.
3315 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3319 // make sure user has all required permissions.
3320 $hasAllPermissions = FALSE;
3322 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3323 if (!is_array($permissions) ||
empty($permissions)) {
3324 $hasAllPermissions = TRUE;
3327 // iterate for required permissions in given permissions array.
3328 if (!$hasAllPermissions) {
3329 $hasPermissions = 0;
3330 foreach ($permissions as $permission) {
3331 if (CRM_Core_Permission
::check($permission)) {
3336 if (count($permissions) == $hasPermissions) {
3337 $hasAllPermissions = TRUE;
3340 // if still user does not have required permissions, check acl.
3341 if (!$hasAllPermissions && $menuOptions['ref'] !== 'delete-contact') {
3342 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3343 $corePermission == CRM_Core_Permission
::EDIT
3345 $hasAllPermissions = TRUE;
3347 elseif (in_array($menuOptions['ref'], [
3350 // grant permissions for these tasks.
3351 $hasAllPermissions = TRUE;
3356 return $hasAllPermissions;
3360 * Retrieve display name of contact that address is shared.
3362 * This is based on $masterAddressId or $contactId .
3364 * @param int $masterAddressId
3366 * @param int $contactId
3367 * Contact id. (deprecated - do not use)
3369 * @return string|null
3370 * the found display name or null.
3372 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3373 $masterDisplayName = NULL;
3374 if (!$masterAddressId) {
3375 return $masterDisplayName;
3379 SELECT display_name from civicrm_contact
3380 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3381 WHERE civicrm_address.id = " . $masterAddressId;
3383 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3384 return $masterDisplayName;
3388 * Get the creation/modification times for a contact.
3390 * @param int $contactId
3393 * Dates - ('created_date' => $, 'modified_date' => $)
3395 public static function getTimestamps($contactId) {
3396 $timestamps = CRM_Core_DAO
::executeQuery(
3397 'SELECT created_date, modified_date
3398 FROM civicrm_contact
3401 1 => [$contactId, 'Integer'],
3404 if ($timestamps->fetch()) {
3406 'created_date' => $timestamps->created_date
,
3407 'modified_date' => $timestamps->modified_date
,
3416 * Get a list of triggers for the contact table.
3419 * @param null $tableName
3421 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3423 * @see hook_civicrm_triggerInfo
3424 * @see CRM_Core_DAO::triggerRebuild
3426 public static function triggerInfo(&$info, $tableName = NULL) {
3427 //during upgrade, first check for valid version and then create triggers
3428 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3429 if (CRM_Core_Config
::isUpgradeMode()) {
3430 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3431 //if current version is less than 4.3.alpha1 dont create below triggers
3432 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3437 // Modifications to these records should update the contact timestamps.
3438 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3440 ['table' => 'civicrm_address', 'column' => 'contact_id'],
3441 ['table' => 'civicrm_email', 'column' => 'contact_id'],
3442 ['table' => 'civicrm_im', 'column' => 'contact_id'],
3443 ['table' => 'civicrm_phone', 'column' => 'contact_id'],
3444 ['table' => 'civicrm_website', 'column' => 'contact_id'],
3446 ->alterTriggerInfo($info, $tableName);
3448 // Update phone table to populate phone_numeric field
3449 if (!$tableName ||
$tableName == 'civicrm_phone') {
3450 // Define stored sql function needed for phones
3451 $sqlTriggers = Civi
::service('sql_triggers');
3452 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3453 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3455 'table' => ['civicrm_phone'],
3457 'event' => ['INSERT', 'UPDATE'],
3458 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3464 * Check if contact is being used in civicrm_domain based on $contactId.
3466 * @param int $contactId
3470 * true if present else false.
3472 public static function checkDomainContact($contactId) {
3476 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3487 * Get options for a given contact field.
3489 * @param string $fieldName
3490 * @param string $context
3491 * @param array $props
3492 * whatever is known about this dao object.
3494 * @return array|bool
3495 * @see CRM_Core_DAO::buildOptions
3497 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3498 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3500 * @see CRM_Core_DAO::buildOptionsContext
3502 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3504 // Special logic for fields whose options depend on context or properties
3505 switch ($fieldName) {
3506 case 'contact_sub_type':
3507 if (!empty($props['contact_type'])) {
3508 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3512 case 'contact_type':
3513 if ($context == 'search') {
3514 // CRM-15495 - EntityRef filters and basic search forms expect this format
3515 // FIXME: Search builder does not
3516 return CRM_Contact_BAO_ContactType
::getSelectElements();
3520 // The contact api supports some related entities so we'll honor that by fetching their options
3523 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3527 $props['entity_table'] = 'civicrm_contact';
3528 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3530 case 'state_province_id':
3531 case 'state_province':
3532 case 'state_province_name':
3537 case 'worldregion_id':
3538 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3541 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3545 * Delete a contact-related object that has an 'is_primary' field.
3547 * Ensures that is_primary gets assigned to another object if available
3548 * Also calls pre/post hooks
3550 * @param string $type
3555 public static function deleteObjectWithPrimary($type, $id) {
3556 if (!$id ||
!is_numeric($id)) {
3559 $daoName = "CRM_Core_DAO_$type";
3560 $obj = new $daoName();
3564 if ($obj->fetch()) {
3565 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3566 $contactId = $obj->contact_id
;
3572 // is_primary is only relavent if this field belongs to a contact
3574 $dao = new $daoName();
3575 $dao->contact_id
= $contactId;
3576 $dao->is_primary
= 1;
3577 // Pick another record to be primary (if one isn't already)
3578 if (!$dao->find(TRUE)) {
3579 $dao->is_primary
= 0;
3581 if ($dao->fetch()) {
3582 $dao->is_primary
= 1;
3587 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3594 public function addSelectWhereClause() {
3595 // We always return an array with these keys, even if they are empty,
3596 // because this tells the query builder that we have considered these fields for acls
3598 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3599 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
[] : ['!= 1'],
3601 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3606 * Get any existing duplicate contacts based on the input parameters.
3608 * @param array $input
3609 * Input parameters to be matched.
3610 * @param string $contactType
3611 * @param string $rule
3614 * @param $excludedContactIDs
3615 * An array of ids not to be included in the results.
3616 * @param bool $checkPermissions
3617 * @param int $ruleGroupID
3618 * ID of the rule group to be used if an override is desirable.
3619 * @param array $contextParams
3620 * The context if relevant, eg. ['event_id' => X]
3624 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3625 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3626 $dedupeParams['check_permission'] = $checkPermissions;
3627 $dedupeParams['contact_type'] = $contactType;
3628 $dedupeParams['rule'] = $rule;
3629 $dedupeParams['rule_group_id'] = $ruleGroupID;
3630 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3631 $dedupeResults['ids'] = [];
3632 $dedupeResults['handled'] = FALSE;
3633 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3634 if (!$dedupeResults['handled']) {
3635 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3637 return $dedupeResults['ids'];
3641 * Get the first duplicate contacts based on the input parameters.
3643 * @param array $input
3644 * Input parameters to be matched.
3645 * @param string $contactType
3646 * @param string $rule
3649 * @param $excludedContactIDs
3650 * An array of ids not to be included in the results.
3651 * @param bool $checkPermissions
3652 * @param int $ruleGroupID
3653 * ID of the rule group to be used if an override is desirable.
3654 * @param array $contextParams
3655 * The context if relevant, eg. ['event_id' => X]
3659 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3660 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3668 * Check if a field is associated with an entity that has a location type.
3670 * (ie. is an address, phone, email etc field).
3672 * @param string $fieldTitle
3673 * Title of the field (not the name - create a new function for that if required).
3677 public static function isFieldHasLocationType($fieldTitle) {
3678 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3679 if ($field['title'] === $fieldTitle) {
3680 return CRM_Utils_Array
::value('hasLocationType', $field);
3687 * @param array $appendProfiles
3688 * Name of profile(s) to append to each link.
3692 public static function getEntityRefCreateLinks($appendProfiles = []) {
3693 // You'd think that "create contacts" would be the permission to check,
3694 // But new contact popups are profile forms and those use their own permissions.
3695 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3699 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3700 $profiles[] = 'new_' . strtolower($contactType);
3702 $retrieved = civicrm_api3('uf_group', 'get', [
3703 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3706 $links = $append = [];
3707 if (!empty($retrieved['values'])) {
3709 'individual' => 'fa-user',
3710 'organization' => 'fa-building',
3711 'household' => 'fa-home',
3713 foreach ($retrieved['values'] as $id => $profile) {
3714 if (in_array($profile['name'], $profiles)) {
3716 'label' => $profile['title'],
3717 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3718 NULL, NULL, FALSE, FALSE, TRUE),
3719 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3720 'icon' => CRM_Utils_Array
::value(str_replace('new_', '', $profile['name']), $icons),
3727 foreach ($append as $id) {
3728 foreach ($links as &$link) {
3729 $link['url'] .= ",$id";
3739 public static function getEntityRefFilters() {
3741 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3742 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3743 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3744 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3745 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3746 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3747 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3748 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3749 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3750 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],