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.
37 * @see self::triggerInfo()
39 * Note that this is also used by the 4.3 upgrade script.
40 * @see CRM_Upgrade_Incremental_php_FourThree
42 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
43 const CREATE_STRIP_FUNCTION_43
= "
44 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
45 RETURNS VARCHAR(255) CHARACTER SET utf8
49 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
50 DECLARE iterator INT DEFAULT 1;
51 WHILE iterator < (LENGTH(input) + 1) DO
52 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
53 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
55 SET iterator = iterator + 1;
61 * The types of communication preferences.
65 public static $_commPrefs = array(
78 public static $_greetingTypes = array(
85 * Static field for all the contact information that we can potentially import.
89 public static $_importableFields = array();
92 * Static field for all the contact information that we can potentially export.
96 public static $_exportableFields = NULL;
101 public function __construct() {
102 parent
::__construct();
106 * Takes an associative array and creates a contact object.
108 * The function extracts all the params it needs to initialize the create a
109 * contact object. the params array could contain additional unused name/value
112 * @param array $params
113 * (reference) an assoc array of name/value pairs.
115 * @return CRM_Contact_BAO_Contact|CRM_Core_Error|NULL
116 * Created or updated contact object or error object.
117 * (error objects are being phased out in favour of exceptions)
119 public static function add(&$params) {
120 $contact = new CRM_Contact_DAO_Contact();
122 if (empty($params)) {
126 // Fix for validate contact sub type CRM-5143.
127 if (isset($params['contact_sub_type'])) {
128 if (empty($params['contact_sub_type'])) {
129 $params['contact_sub_type'] = 'null';
131 elseif ($params['contact_sub_type'] !== 'null') {
132 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
133 $params['contact_type'], TRUE
136 // we'll need to fix tests to handle this
138 CRM_Core_Error
::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
140 $params['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
144 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
145 CRM_Utils_Array
::formatArrayKeys($params['preferred_communication_method']);
146 $contact->preferred_communication_method
= CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
147 unset($params['preferred_communication_method']);
150 $defaults = ['source' => CRM_Utils_Array
::value('contact_source', $params)];
151 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
152 $defaults['display_name'] = $params['organization_name'];
153 $defaults['sort_name'] = $params['organization_name'];
155 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
156 $defaults['display_name'] = $params['household_name'];
157 $defaults['sort_name'] = $params['household_name'];
159 $params = array_merge($defaults, $params);
161 $allNull = $contact->copyValues($params);
163 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
165 if ($contact->contact_type
== 'Individual') {
167 // @todo allow the lines below to be overridden by input or hooks & add tests,
168 // as has been done for households and organizations.
169 // Format individual fields.
170 CRM_Contact_BAO_Individual
::format($params, $contact);
173 if (strlen($contact->display_name
) > 128) {
174 $contact->display_name
= substr($contact->display_name
, 0, 128);
176 if (strlen($contact->sort_name
) > 128) {
177 $contact->sort_name
= substr($contact->sort_name
, 0, 128);
180 $privacy = CRM_Utils_Array
::value('privacy', $params);
182 is_array($privacy) &&
186 foreach (self
::$_commPrefs as $name) {
187 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
191 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
192 // @todo - does this mean we can remove this block?
193 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
194 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
196 $contact->hash
= md5(uniqid(rand(), TRUE));
199 // Even if we don't need $employerId, it's important to call getFieldValue() before
200 // the contact is saved because we want the existing value to be cached.
201 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
202 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
207 CRM_Core_BAO_Log
::register($contact->id
,
213 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
214 // Create current employer.
215 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
218 if (empty($params['contact_id'])) {
222 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
226 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
231 // Update cached employer name.
232 if ($contact->contact_type
== 'Organization') {
233 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
242 * takes an associative array and creates a contact object and all the associated
243 * derived objects (i.e. individual, location, email, phone etc)
245 * This function is invoked from within the web form layer and also from the api layer
247 * @param array $params
248 * (reference ) an assoc array of name/value pairs.
249 * @param bool $fixAddress
250 * If we need to fix address.
251 * @param bool $invokeHooks
252 * If we need to invoke hooks.
254 * @param bool $skipDelete
255 * Unclear parameter, passed to website create
257 * @todo explain this parameter
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 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
266 if (empty($params['contact_type']) && empty($params['contact_id'])) {
270 $isEdit = !empty($params['contact_id']);
272 if ($isEdit && empty($params['contact_type'])) {
273 $params['contact_type'] = self
::getContactType($params['contact_id']);
276 if (!empty($params['check_permissions']) && isset($params['api_key'])
277 && !CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])
278 && !($isEdit && CRM_Core_Permission
::check('edit own api keys') && $params['contact_id'] == CRM_Core_Session
::getLoggedInContactID())
280 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify api key');
284 if (!empty($params['contact_id'])) {
285 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
288 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
292 self
::ensureGreetingParamsAreSet($params);
294 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
295 if (empty($params['contact_id'])) {
296 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
297 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
298 $params['preferred_language'] = $language;
301 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
302 if (empty($params['communication_style_id'])) {
303 $defaultCommunicationStyleId = CRM_Core_OptionGroup
::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
304 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
308 $transaction = new CRM_Core_Transaction();
310 $contact = self
::add($params);
312 // Not dying here is stupid, since we get into weird situation and into a bug that
313 // is impossible to figure out for the user or for us
315 CRM_Core_Error
::fatal();
318 $params['contact_id'] = $contact->id
;
320 if (Civi
::settings()->get('is_enabled')) {
321 // Enabling multisite causes the contact to be added to the domain group.
322 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
323 if (!empty($domainGroupID)) {
324 if (!empty($params['group']) && is_array($params['group'])) {
325 $params['group'][$domainGroupID] = 1;
328 $params['group'] = array($domainGroupID => 1);
333 if (array_key_exists('group', $params)) {
334 $contactIds = array($params['contact_id']);
335 foreach ($params['group'] as $groupId => $flag) {
337 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
339 elseif ($flag == -1) {
340 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
345 // Add location Block data.
346 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
347 foreach ($blocks as $name => $value) {
348 $contact->$name = $value;
350 if (!empty($params['updateBlankLocInfo'])) {
354 if (isset($params['website'])) {
355 CRM_Core_BAO_Website
::process($params['website'], $contact->id
, $skipDelete);
358 $userID = CRM_Core_Session
::singleton()->get('userID');
360 if (!empty($params['note'])) {
361 if (is_array($params['note'])) {
362 foreach ($params['note'] as $note) {
363 $contactId = $contact->id
;
364 if (isset($note['contact_id'])) {
365 $contactId = $note['contact_id'];
367 //if logged in user, overwrite contactId
369 $contactId = $userID;
373 'entity_id' => $contact->id
,
374 'entity_table' => 'civicrm_contact',
375 'note' => $note['note'],
376 'subject' => CRM_Utils_Array
::value('subject', $note),
377 'contact_id' => $contactId,
379 CRM_Core_BAO_Note
::add($noteParams);
383 $contactId = $contact->id
;
384 //if logged in user, overwrite contactId
386 $contactId = $userID;
390 'entity_id' => $contact->id
,
391 'entity_table' => 'civicrm_contact',
392 'note' => $params['note'],
393 'subject' => CRM_Utils_Array
::value('subject', $params),
394 'contact_id' => $contactId,
396 CRM_Core_BAO_Note
::add($noteParams);
400 // update the UF user_unique_id if that has changed
401 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
403 if (!empty($params['custom']) &&
404 is_array($params['custom'])
406 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
409 // make a civicrm_subscription_history entry only on contact create (CRM-777)
410 if (empty($params['contact_id'])) {
411 $subscriptionParams = array(
412 'contact_id' => $contact->id
,
416 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
419 $transaction->commit();
421 // CRM-6367: fetch the right label for contact type’s display
422 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
423 'CRM_Contact_DAO_ContactType',
424 $contact->contact_type
,
429 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
433 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
436 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
440 // In order to prevent a series of expensive queries in intensive batch processing
441 // api calls may pass in skip_greeting_processing, probably doing it later via the
442 // scheduled job. CRM-21551
443 if (empty($params['skip_greeting_processing'])) {
444 self
::processGreetings($contact);
447 if (!empty($params['check_permissions'])) {
448 $contacts = [&$contact];
449 self
::unsetProtectedFields($contacts);
456 * Format the output of the create contact function
457 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
459 public static function unsetProtectedFields(&$contacts) {
460 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
461 $currentUser = CRM_Core_Session
::getLoggedInContactID();
462 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
463 foreach ($contacts as &$contact) {
464 $cid = is_object($contact) ?
$contact->id
: CRM_Utils_Array
::value('id', $contact);
465 if (!($editOwn && $cid == $currentUser)) {
466 if (is_object($contact)) {
467 unset($contact->api_key
);
470 unset($contact['api_key']);
478 * Ensure greeting parameters are set.
480 * By always populating greetings here we can be sure they are set if required & avoid a call later.
481 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
483 * @param array $params
485 public static function ensureGreetingParamsAreSet(&$params) {
486 $allGreetingParams = array('addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id');
487 $missingGreetingParams = array();
489 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
490 if (empty($params[$greetingParam])) {
491 $missingGreetingParams[$greetingIndex] = $greetingParam;
495 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
496 $savedGreetings = civicrm_api3('Contact', 'getsingle', array(
497 'id' => $params['contact_id'],
498 'return' => array_keys($missingGreetingParams),
502 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
503 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
504 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
507 // Filter out other fields.
508 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
509 $params = array_merge($params, $savedGreetings);
512 foreach ($missingGreetingParams as $greetingName => $greeting) {
513 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
517 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
518 if ($params[$greetingParam] === 'null') {
519 // If we are setting it to null then null out the display field.
520 $params[$greetingIndex . '_display'] = 'null';
526 * Get the display name and image of a contact.
531 * @param bool $includeTypeInReturnParameters
532 * Should type be part of the returned array?
535 * the displayName and contactImage for this contact
537 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
538 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
540 SELECT civicrm_contact.*,
541 civicrm_email.email as email
543 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
544 AND civicrm_email.is_primary = 1
545 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
546 $dao = new CRM_Core_DAO();
549 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
550 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
552 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
553 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
556 // use email if display_name is empty
557 if (empty($dao->display_name
)) {
558 $displayName = $dao->email
;
561 $displayName = $dao->display_name
;
564 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
566 return $includeTypeInReturnParameters ?
array(
570 $dao->contact_sub_type
,
572 ) : array($displayName, $image, $imageUrl);
578 * Add billing fields to the params if appropriate.
580 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
581 * don't then we should set the name fields to the billing fields AND add the preserveDBName
582 * parameter (which will tell the BAO only to set those fields if none already exist.
584 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
585 * matching is best done by hipsters.
587 * @param array $params
589 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
591 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
592 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
593 foreach ($nameFields as $field) {
594 if (!empty($params[$field])) {
598 // There are only 3 - we can iterate through them twice :-)
599 foreach ($nameFields as $field) {
600 if (!empty($params['billing_' . $field])) {
601 $params[$field] = $params['billing_' . $field];
603 $params['preserveDBName'] = TRUE;
609 * Resolve a state province string (UT or Utah) to an ID.
611 * If country has been passed in we should select a state belonging to that country.
613 * Alternatively we should choose from enabled countries, prioritising the default country.
615 * @param array $values
616 * @param int|null $countryID
620 * @throws \CRM_Core_Exception
622 protected static function resolveStateProvinceID($values, $countryID) {
625 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
626 if (CRM_Utils_Array
::lookupValue($values,
631 return $values['state_province_id'];
633 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
634 if (CRM_Utils_Array
::lookupValue($values,
639 return $values['state_province_id'];
644 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
645 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
646 // prefer matching country..
647 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, array('country_id' => Civi
::settings()->get('defaultContactCountry')));
648 if (CRM_Utils_Array
::lookupValue($values,
653 return $values['state_province_id'];
656 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
657 if (CRM_Utils_Array
::lookupValue($values,
662 return $values['state_province_id'];
665 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
666 if (CRM_Utils_Array
::lookupValue($values,
671 return $values['state_province_id'];
673 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
674 if (CRM_Utils_Array
::lookupValue($values,
679 return $values['state_province_id'];
687 * Get the relevant location entity for the array key.
689 * Based on the field name we determine which location entity
690 * we are dealing with. Apart from a few specific ones they
691 * are mostly 'address' (the default).
693 * @param string $fieldName
697 protected static function getLocationEntityForKey($fieldName) {
698 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
701 if ($fieldName === 'phone_ext') {
708 * Create last viewed link to recently updated contact.
710 * @param array $crudLinkSpec
711 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
712 * - entity_table: string, eg "civicrm_contact"
716 * NULL if unavailable, or
717 * [path: string, query: string, title: string]
718 * @see CRM_Utils_System::createDefaultCrudLink
720 public function createDefaultCrudLink($crudLinkSpec) {
721 switch ($crudLinkSpec['action']) {
722 case CRM_Core_Action
::VIEW
:
724 'title' => $this->display_name
,
725 'path' => 'civicrm/contact/view',
733 case CRM_Core_Action
::UPDATE
:
735 'title' => $this->display_name
,
736 'path' => 'civicrm/contact/add',
739 'action' => 'update',
749 * Get the values for pseudoconstants for name->value and reverse.
753 * This is called specifically from the contact import parser & should be moved there
754 * as it is not truly a generic function.
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..
761 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
762 // Hack for birth_date.
763 if (!empty($defaults['birth_date'])) {
764 if (is_array($defaults['birth_date'])) {
765 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
769 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
770 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
771 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
772 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
774 //lookup value of email/postal greeting, addressee, CRM-4575
775 foreach (self
::$_greetingTypes as $greeting) {
776 $filterCondition = array(
777 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
778 'greeting_type' => $greeting,
780 CRM_Utils_Array
::lookupValue($defaults, $greeting,
781 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
785 $blocks = array('address', 'im', 'phone');
786 foreach ($blocks as $name) {
787 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
790 foreach ($defaults[$name] as $count => & $values) {
792 //get location type id.
793 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
795 if ($name == 'address') {
796 // FIXME: lookupValue doesn't work for vcard_name
797 if (!empty($values['location_type_id'])) {
798 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
799 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
802 if (!CRM_Utils_Array
::lookupValue($values,
804 CRM_Core_PseudoConstant
::country(),
809 CRM_Utils_Array
::lookupValue($values,
811 CRM_Core_PseudoConstant
::countryIsoCode(),
815 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
816 if ($stateProvinceID) {
817 $values['state_province_id'] = $stateProvinceID;
820 if (!empty($values['state_province_id'])) {
821 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
824 $countyList = CRM_Core_PseudoConstant
::county();
826 CRM_Utils_Array
::lookupValue($values,
834 CRM_Utils_Array
::lookupValue($values,
836 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
841 if ($name == 'phone') {
842 CRM_Utils_Array
::lookupValue($values,
844 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
849 // Kill the reference.
856 * Fetch object based on array of properties.
858 * @param array $params
859 * (reference ) an assoc array of name/value pairs.
860 * @param array $defaults
861 * (reference ) an assoc array to hold the name / value pairs.
862 * in a hierarchical manner
863 * @param bool $microformat
864 * For location in microformat.
866 * @return CRM_Contact_BAO_Contact
868 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
869 if (array_key_exists('contact_id', $params)) {
870 $params['id'] = $params['contact_id'];
872 elseif (array_key_exists('id', $params)) {
873 $params['contact_id'] = $params['id'];
876 $contact = self
::getValues($params, $defaults);
878 unset($params['id']);
880 //get the block information for this contact
881 $entityBlock = array('contact_id' => $params['contact_id']);
882 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
883 $defaults = array_merge($defaults, $blocks);
884 foreach ($blocks as $block => $value) {
885 $contact->$block = $value;
888 if (!isset($params['noNotes'])) {
889 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
892 if (!isset($params['noRelationships'])) {
893 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
896 if (!isset($params['noGroups'])) {
897 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
900 if (!isset($params['noWebsite'])) {
901 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
908 * Get the display name of a contact.
913 * @return null|string
914 * display name of the contact if found
916 public static function displayName($id) {
919 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
926 * Delete a contact and all its associated records.
929 * Id of the contact to delete.
930 * @param bool $restore
931 * Whether to actually restore, not delete.
932 * @param bool $skipUndelete
933 * Whether to force contact delete or not.
934 * @param bool $checkPermissions
937 * Was contact deleted?
939 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
944 // If trash is disabled in system settings then we always skip
945 if (!Civi
::settings()->get('contact_undelete')) {
946 $skipUndelete = TRUE;
949 // make sure we have edit permission for this contact
951 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
952 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
958 // Restrict contact to be delete if contact has financial trxns
960 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
964 // make sure this contact_id does not have any membership types
965 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
968 'member_of_contact_id'
970 if ($membershipTypeID) {
974 $contact = new CRM_Contact_DAO_Contact();
976 if (!$contact->find(TRUE)) {
980 $contactType = $contact->contact_type
;
981 // currently we only clear employer cache.
982 // we are now deleting inherited membership if any.
983 if ($contact->contact_type
== 'Organization') {
984 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
985 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
986 if (!empty($relationshipDtls)) {
987 foreach ($relationshipDtls as $rId => $details) {
988 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
991 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
995 return self
::contactTrashRestore($contact, TRUE);
998 // start a new transaction
999 $transaction = new CRM_Core_Transaction();
1001 if ($skipUndelete) {
1002 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
1004 //delete billing address if exists.
1005 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
1007 // delete the log entries since we dont have triggers enabled as yet
1008 $logDAO = new CRM_Core_DAO_Log();
1009 $logDAO->entity_table
= 'civicrm_contact';
1010 $logDAO->entity_id
= $id;
1013 // delete contact participants CRM-12155
1014 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
1016 // delete contact contributions CRM-12155
1017 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
1019 // do activity cleanup, CRM-5604
1020 CRM_Activity_BAO_Activity
::cleanupActivity($id);
1022 // delete all notes related to contact
1023 CRM_Core_BAO_Note
::cleanContactNotes($id);
1025 // delete cases related to contact
1026 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
1027 if (!empty($contactCases)) {
1028 foreach ($contactCases as $caseId) {
1029 //check if case is associate with other contact or not.
1030 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
1031 if (count($caseContactId) <= 1) {
1032 CRM_Case_BAO_Case
::deleteCase($caseId);
1040 self
::contactTrashRestore($contact);
1043 //delete the contact id from recently view
1044 CRM_Utils_Recent
::delContact($id);
1045 self
::updateContactCache($id, empty($restore));
1047 // delete any prevnext/dupe cache entry
1048 // These two calls are redundant in default deployments, but they're
1049 // meaningful if "prevnext" is memory-backed.
1050 Civi
::service('prevnext')->deleteItem($id);
1051 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1053 $transaction->commit();
1055 if ($skipUndelete) {
1056 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1063 * Action to update any caches relating to a recently update contact.
1065 * I was going to call this from delete as well as from create to ensure the delete is being
1066 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1067 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1068 * where the call involved a subquery that was locking the table.
1070 * @param int $contactID
1071 * @param bool $isTrashed
1073 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1076 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1077 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1078 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1079 // but this should not cause any change as long as contacts are not being trashed outside the
1080 // main functions for that.
1081 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
1084 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1089 * Delete the image of a contact.
1092 * Id of the contact.
1095 * Was contact image deleted?
1097 public static function deleteContactImage($id) {
1102 $contact = new self();
1104 $contact->image_URL
= 'null';
1111 * Return proportional height and width of the image.
1113 * @param int $imageWidth
1116 * @param int $imageHeight
1120 * Thumb dimension of image
1122 public static function getThumbSize($imageWidth, $imageHeight) {
1124 if ($imageWidth && $imageHeight) {
1125 $imageRatio = $imageWidth / $imageHeight;
1130 if ($imageRatio > 1) {
1131 $imageThumbWidth = $thumbWidth;
1132 $imageThumbHeight = round($thumbWidth / $imageRatio);
1135 $imageThumbHeight = $thumbWidth;
1136 $imageThumbWidth = round($thumbWidth * $imageRatio);
1139 return array($imageThumbWidth, $imageThumbHeight);
1143 * Validate type of contact image.
1145 * @param array $params
1146 * @param string $imageIndex
1147 * Index of image field.
1148 * @param string $statusMsg
1149 * Status message to be set after operation.
1150 * @param string $opType
1151 * Type of operation like fatal, bounce etc.
1154 * true if valid image extension
1156 public static function processImageParams(
1158 $imageIndex = 'image_URL',
1172 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1173 $photo = basename($params[$imageIndex]['name']);
1174 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1178 unset($params[$imageIndex]);
1180 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1182 if ($opType == 'status') {
1183 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1185 // FIXME: additional support for fatal, bounce etc could be added.
1191 * Extract contact id from url for deleting contact image.
1193 public static function processImage() {
1195 $action = CRM_Utils_Request
::retrieve('action', 'String');
1196 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1197 // retrieve contact id in case of Profile context
1198 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1199 $cid = $cid ?
$cid : $id;
1200 if ($action & CRM_Core_Action
::DELETE
) {
1201 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1202 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1203 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1204 $session = CRM_Core_Session
::singleton();
1205 $toUrl = $session->popUserContext();
1206 CRM_Utils_System
::redirect($toUrl);
1212 * Function to set is_delete true or restore deleted contact.
1214 * @param CRM_Contact_DAO_Contact $contact
1215 * Contact DAO object.
1216 * @param bool $restore
1217 * True to set the is_delete = 1 else false to restore deleted contact,
1218 * i.e. is_delete = 0
1222 public static function contactTrashRestore($contact, $restore = FALSE) {
1223 $updateParams = array(
1224 'id' => $contact->id
,
1225 'is_deleted' => $restore ?
0 : 1,
1228 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1230 $params = array(1 => array($contact->id
, 'Integer'));
1232 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1233 CRM_Core_DAO
::executeQuery($query, $params);
1236 $contact->copyValues($updateParams);
1238 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
1240 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1246 * Get contact type for a contact.
1249 * Id of the contact whose contact type is needed.
1252 * contact_type if $id found else null ""
1254 public static function getContactType($id) {
1255 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1259 * Get contact sub type for a contact.
1262 * Id of the contact whose contact sub type is needed.
1264 * @param string $implodeDelimiter
1267 * contact_sub_type if $id found else null ""
1269 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1270 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1272 return $implodeDelimiter ?
NULL : array();
1275 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1277 if ($implodeDelimiter) {
1278 $subtype = implode($implodeDelimiter, $subtype);
1284 * Get pair of contact-type and sub-type for a contact.
1287 * Id of the contact whose contact sub/contact type is needed.
1291 public static function getContactTypes($id) {
1292 $params = array('id' => $id);
1294 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1297 array('contact_type', 'contact_sub_type')
1301 $contactTypes = array();
1302 if ($contact->contact_sub_type
) {
1303 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1305 array_unshift($contactTypes, $contact->contact_type
);
1307 return $contactTypes;
1310 CRM_Core_Error
::fatal();
1315 * Combine all the importable fields from the lower levels object.
1317 * The ordering is important, since currently we do not have a weight
1318 * scheme. Adding weight is super important
1320 * @param int|string $contactType contact Type
1321 * @param bool $status
1322 * Status is used to manipulate first title.
1323 * @param bool $showAll
1324 * If true returns all fields (includes disabled fields).
1325 * @param bool $isProfile
1326 * If its profile mode.
1327 * @param bool $checkPermission
1328 * If false, do not include permissioning clause (for custom data).
1330 * @param bool $withMultiCustomFields
1333 * array of importable Fields
1335 public static function importableFields(
1336 $contactType = 'Individual',
1340 $checkPermission = TRUE,
1341 $withMultiCustomFields = FALSE
1343 if (empty($contactType)) {
1344 $contactType = 'All';
1347 $cacheKeyString = "importableFields $contactType";
1348 $cacheKeyString .= $status ?
'_1' : '_0';
1349 $cacheKeyString .= $showAll ?
'_1' : '_0';
1350 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1351 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1352 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1354 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields) ?
: Civi
::cache('fields')->get($cacheKeyString);
1357 $fields = CRM_Contact_DAO_Contact
::import();
1359 // get the fields thar are meant for contact types
1360 if (in_array($contactType, array(
1366 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1369 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1370 CRM_Core_DAO_Phone
::import(),
1371 CRM_Core_DAO_Email
::import(),
1372 CRM_Core_DAO_IM
::import(TRUE),
1373 CRM_Core_DAO_OpenID
::import()
1376 $locationFields = array_merge($locationFields,
1377 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1385 foreach ($locationFields as $key => $field) {
1386 $locationFields[$key]['hasLocationType'] = TRUE;
1389 $fields = array_merge($fields, $locationFields);
1391 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1392 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1395 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1396 $fields['url']['hasWebsiteType'] = TRUE;
1398 if ($contactType != 'All') {
1399 $fields = array_merge($fields,
1400 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1405 $withMultiCustomFields
1408 //unset the fields, which are not related to their
1410 $commonValues = array(
1411 'Individual' => array(
1415 'organization_name',
1417 'Household' => array(
1427 'organization_name',
1435 'Organization' => array(
1450 foreach ($commonValues[$contactType] as $value) {
1451 unset($fields[$value]);
1455 foreach (array('Individual', 'Household', 'Organization') as $type) {
1456 $fields = array_merge($fields,
1457 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1462 $withMultiCustomFields
1469 $fields = array_merge($fields, array(
1471 'title' => ts('Group(s)'),
1475 'title' => ts('Tag(s)'),
1479 'title' => ts('Note'),
1482 'communication_style_id' => array(
1483 'title' => ts('Communication Style'),
1484 'name' => 'communication_style_id',
1489 //Sorting fields in alphabetical order(CRM-1507)
1490 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1492 Civi
::cache('fields')->set($cacheKeyString, $fields);
1495 self
::$_importableFields[$cacheKeyString] = $fields;
1499 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1500 self
::$_importableFields[$cacheKeyString]
1504 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1505 self
::$_importableFields[$cacheKeyString]
1513 * Combine all the exportable fields from the lower levels object.
1515 * Currently we are using importable fields as exportable fields
1517 * @param int|string $contactType contact Type
1518 * @param bool $status
1519 * True while exporting primary contacts.
1520 * @param bool $export
1521 * True when used during export.
1522 * @param bool $search
1523 * True when used during search, might conflict with export param?.
1525 * @param bool $withMultiRecord
1526 * @param bool $checkPermissions
1528 * array of exportable Fields
1530 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1531 if (empty($contactType)) {
1532 $contactType = 'All';
1535 $cacheKeyString = "exportableFields $contactType";
1536 $cacheKeyString .= $export ?
'_1' : '_0';
1537 $cacheKeyString .= $status ?
'_1' : '_0';
1538 $cacheKeyString .= $search ?
'_1' : '_0';
1539 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1540 //calculates custom fields takes into account the logged in user & caches that for all users
1541 //as an interim fix we will cache the fields by contact
1542 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1544 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1545 if (!self
::$_exportableFields) {
1546 self
::$_exportableFields = array();
1549 // check if we can retrieve from database cache
1550 $fields = Civi
::cache('fields')->get($cacheKeyString);
1553 $fields = CRM_Contact_DAO_Contact
::export();
1555 // The fields are meant for contact types.
1556 if (in_array($contactType, array(
1562 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1564 // add current employer for individuals
1565 $fields = array_merge($fields, array(
1566 'current_employer' =>
1568 'name' => 'organization_name',
1569 'title' => ts('Current Employer'),
1573 $locationType = array(
1574 'location_type' => array(
1575 'name' => 'location_type',
1576 'where' => 'civicrm_location_type.name',
1577 'title' => ts('Location Type'),
1581 $IMProvider = array(
1582 'im_provider' => array(
1583 'name' => 'im_provider',
1584 'where' => 'civicrm_im.provider_id',
1585 'title' => ts('IM Provider'),
1589 $locationFields = array_merge($locationType,
1590 CRM_Core_DAO_Address
::export(),
1591 CRM_Core_DAO_Phone
::export(),
1592 CRM_Core_DAO_Email
::export(),
1594 CRM_Core_DAO_IM
::export(TRUE),
1595 CRM_Core_DAO_OpenID
::export()
1598 $locationFields = array_merge($locationFields,
1599 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1602 foreach ($locationFields as $key => $field) {
1603 $locationFields[$key]['hasLocationType'] = TRUE;
1606 $fields = array_merge($fields, $locationFields);
1609 $fields = array_merge($fields,
1610 CRM_Core_DAO_Worldregion
::export()
1613 $fields = array_merge($fields,
1614 CRM_Contact_DAO_Contact
::export()
1618 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1620 if ($contactType != 'All') {
1621 $fields = array_merge($fields,
1622 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1631 $fields = array_merge($fields,
1632 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1636 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1639 $fields = array_merge($fields, array(
1641 'title' => ts('Group(s)'),
1645 'title' => ts('Tag(s)'),
1649 'title' => ts('Note(s)'),
1655 $fields = array_merge($fields, array(
1657 'title' => ts('Group(s)'),
1661 'title' => ts('Tag(s)'),
1665 'title' => ts('Note(s)'),
1671 //Sorting fields in alphabetical order(CRM-1507)
1672 foreach ($fields as $k => $v) {
1673 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1676 $fields = array_merge($sortArray, $fields);
1677 //unset the field which are not related to their contact type.
1678 if ($contactType != 'All') {
1679 $commonValues = array(
1680 'Individual' => array(
1684 'organization_name',
1685 'email_greeting_custom',
1686 'postal_greeting_custom',
1689 'Household' => array(
1699 'organization_name',
1707 'email_greeting_custom',
1708 'postal_greeting_custom',
1713 'Organization' => array(
1724 'email_greeting_custom',
1725 'postal_greeting_custom',
1735 foreach ($commonValues[$contactType] as $value) {
1736 unset($fields[$value]);
1740 Civi
::cache('fields')->set($cacheKeyString, $fields);
1742 self
::$_exportableFields[$cacheKeyString] = $fields;
1746 $fields = self
::$_exportableFields[$cacheKeyString];
1749 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1750 self
::$_exportableFields[$cacheKeyString]
1758 * Get the all contact details (Hierarchical).
1760 * @param int $contactId
1762 * @param array $fields
1768 public static function getHierContactDetails($contactId, $fields) {
1769 $params = array(array('contact_id', '=', $contactId, 0, 0));
1772 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1774 // We don't know the contents of return properties, but we need the lower
1775 // level ids of the contact so add a few fields.
1776 $returnProperties['first_name'] = 1;
1777 $returnProperties['organization_name'] = 1;
1778 $returnProperties['household_name'] = 1;
1779 $returnProperties['contact_type'] = 1;
1780 $returnProperties['contact_sub_type'] = 1;
1781 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1785 * Given a set of flat profile style field names, create a hierarchy.
1787 * This is for the query to use, create the right sql.
1790 * @param int $contactId
1794 * A hierarchical property tree if appropriate
1796 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1797 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1799 $returnProperties = array();
1801 $multipleFields = array('website' => 'url');
1802 foreach ($fields as $name => $dontCare) {
1803 if (strpos($name, '-') !== FALSE) {
1804 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1806 if (!in_array($fieldName, $multipleFields)) {
1807 if ($id == 'Primary') {
1808 $locationTypeName = 1;
1811 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1812 if (!$locationTypeName) {
1817 if (empty($returnProperties['location'])) {
1818 $returnProperties['location'] = array();
1820 if (empty($returnProperties['location'][$locationTypeName])) {
1821 $returnProperties['location'][$locationTypeName] = array();
1822 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1824 if (in_array($fieldName, array(
1832 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1835 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1838 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1839 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1842 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1846 $returnProperties['website'][$id][$fieldName] = 1;
1850 $returnProperties[$name] = 1;
1854 return $returnProperties;
1858 * Return the primary location type of a contact.
1860 * $params int $contactId contact_id
1861 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1862 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1864 * @param int $contactId
1865 * @param bool $skipDefaultPriamry
1866 * @param null $block
1869 * $locationType location_type_id
1871 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1873 $entityBlock = array('contact_id' => $contactId);
1874 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1875 foreach ($blocks[$block] as $key => $value) {
1876 if (!empty($value['is_primary'])) {
1877 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1884 IF ( civicrm_email.location_type_id IS NULL,
1885 IF ( civicrm_address.location_type_id IS NULL,
1886 IF ( civicrm_phone.location_type_id IS NULL,
1887 IF ( civicrm_im.location_type_id IS NULL,
1888 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1889 ,civicrm_im.location_type_id)
1890 ,civicrm_phone.location_type_id)
1891 ,civicrm_address.location_type_id)
1892 ,civicrm_email.location_type_id) as locationType
1893 FROM civicrm_contact
1894 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1895 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1896 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1897 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1898 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1899 WHERE civicrm_contact.id = %1 ";
1901 $params = array(1 => array($contactId, 'Integer'));
1903 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1905 $locationType = NULL;
1906 if ($dao->fetch()) {
1907 $locationType = $dao->locationType
;
1910 if (isset($locationType)) {
1911 return $locationType;
1913 elseif ($skipDefaultPriamry) {
1914 // if there is no primary contact location then return null
1918 // if there is no primart contact location, then return default
1919 // location type of the system
1920 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1921 return $defaultLocationType->id
;
1926 * Get the display name, primary email and location type of a contact.
1929 * Id of the contact.
1932 * Array of display_name, email if found, do_not_email or (null,null,null)
1934 public static function getContactDetails($id) {
1935 // check if the contact type
1936 $contactType = self
::getContactType($id);
1938 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1941 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1942 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1943 WHERE civicrm_contact.id = %1
1944 ORDER BY civicrm_email.is_primary DESC";
1945 $params = array(1 => array($id, 'Integer'));
1946 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1948 if ($dao->fetch()) {
1949 if ($contactType == 'Individual') {
1950 if ($dao->first_name ||
$dao->last_name
) {
1951 $name = "{$dao->first_name} {$dao->last_name}";
1954 $name = $dao->display_name
;
1958 $name = $dao->display_name
;
1960 $email = $dao->email
;
1961 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1962 $onHold = $dao->on_hold ?
TRUE : FALSE;
1963 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1964 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1966 return array(NULL, NULL, NULL, NULL, NULL);
1970 * Add/edit/register contacts through profile.
1972 * @param array $params
1973 * Array of profile fields to be edited/added.
1974 * @param array $fields
1975 * Array of fields from UFGroup.
1976 * @param int $contactID
1977 * Id of the contact to be edited/added.
1978 * @param int $addToGroupID
1979 * Specifies the default group to which contact is added.
1980 * @param int $ufGroupId
1981 * Uf group id (profile id).
1982 * @param string $ctype
1983 * @param bool $visibility
1984 * Basically lets us know where this request is coming from.
1985 * if via a profile from web, we restrict what groups are changed
1988 * contact id created/edited
1990 public static function createProfileContact(
1994 $addToGroupID = NULL,
1999 // add ufGroupID to params array ( CRM-2012 )
2001 $params['uf_group_id'] = $ufGroupId;
2003 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
2005 // If a user has logged in, or accessed via a checksum
2006 // Then deliberately 'blanking' a value in the profile should remove it from their record
2007 $session = CRM_Core_Session
::singleton();
2008 $params['updateBlankLocInfo'] = TRUE;
2009 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
2010 $params['updateBlankLocInfo'] = FALSE;
2015 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
2019 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
2022 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
2024 // manage is_opt_out
2025 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
2026 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
2027 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
2028 $data['is_opt_out'] = $isOptOut;
2029 // on change, create new civicrm_subscription_history entry
2030 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2032 'contact_id' => $contactDetails['contact_id'],
2033 'status' => $isOptOut ?
'Removed' : 'Added',
2036 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2040 $contact = self
::create($data);
2042 // contact is null if the profile does not have any contact fields
2044 $contactID = $contact->id
;
2047 if (empty($contactID)) {
2048 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
2051 // Process group and tag
2052 if (!empty($fields['group'])) {
2054 // this for sure means we are coming in via profile since i added it to fix
2055 // removing contacts from user groups -- lobo
2059 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2062 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2063 // Convert comma separated form values from select2 v3
2064 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2065 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2068 //to add profile in default group
2069 if (is_array($addToGroupID)) {
2070 $contactIds = array($contactID);
2071 foreach ($addToGroupID as $groupId) {
2072 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2075 elseif ($addToGroupID) {
2076 $contactIds = array($contactID);
2077 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2080 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
2083 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2086 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2092 * Format profile contact parameters.
2094 * @param array $params
2096 * @param int $contactID
2097 * @param int $ufGroupId
2098 * @param null $ctype
2099 * @param bool $skipCustom
2103 public static function formatProfileContactParams(
2112 $data = $contactDetails = array();
2114 // get the contact details (hier)
2116 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
2118 $contactDetails = $details[$contactID];
2119 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
2120 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
2123 //we should get contact type only if contact
2125 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2127 //special case to handle profile with only contact fields
2128 if ($data['contact_type'] == 'Contact') {
2129 $data['contact_type'] = 'Individual';
2131 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2132 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2136 $data['contact_type'] = $ctype;
2139 $data['contact_type'] = 'Individual';
2143 //fix contact sub type CRM-5125
2144 if (array_key_exists('contact_sub_type', $params) &&
2145 !empty($params['contact_sub_type'])
2147 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2149 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2150 !empty($params['contact_sub_type_hidden'])
2152 // if profile was used, and had any subtype, we obtain it from there
2153 //CRM-13596 - add to existing contact types, rather than overwriting
2154 if (empty($data['contact_sub_type'])) {
2155 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2156 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2159 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2160 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2161 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2162 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2163 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2168 if ($ctype == 'Organization') {
2169 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2171 elseif ($ctype == 'Household') {
2172 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2175 $locationType = array();
2180 $data['contact_id'] = $contactID;
2181 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2184 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2185 $defaultLocationId = $defaultLocation->id
;
2188 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2190 $blocks = array('email', 'phone', 'im', 'openid');
2192 $multiplFields = array('url');
2193 // prevent overwritten of formatted array, reset all block from
2194 // params if it is not in valid format (since import pass valid format)
2195 foreach ($blocks as $blk) {
2196 if (array_key_exists($blk, $params) &&
2197 !is_array($params[$blk])
2199 unset($params[$blk]);
2203 $primaryPhoneLoc = NULL;
2204 $session = CRM_Core_Session
::singleton();
2205 foreach ($params as $key => $value) {
2206 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2208 if ($locTypeId == 'Primary') {
2210 if (in_array($fieldName, $blocks)) {
2211 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2214 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2216 $primaryLocationType = $locTypeId;
2219 $locTypeId = $defaultLocationId;
2223 if (is_numeric($locTypeId) &&
2224 !in_array($fieldName, $multiplFields) &&
2225 substr($fieldName, 0, 7) != 'custom_'
2227 $index = $locTypeId;
2229 if (is_numeric($typeId)) {
2230 $index .= '-' . $typeId;
2232 if (!in_array($index, $locationType)) {
2233 $locationType[$count] = $index;
2237 $loc = CRM_Utils_Array
::key($index, $locationType);
2239 $blockName = self
::getLocationEntityForKey($fieldName);
2241 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2243 //set is_billing true, for location type "Billing"
2244 if ($locTypeId == $billingLocationTypeId) {
2245 $data[$blockName][$loc]['is_billing'] = 1;
2249 //get the primary location type
2250 if ($locTypeId == $primaryLocationType) {
2251 $data[$blockName][$loc]['is_primary'] = 1;
2254 elseif ($locTypeId == $defaultLocationId) {
2255 $data[$blockName][$loc]['is_primary'] = 1;
2258 if (in_array($fieldName, array('phone'))) {
2260 $data['phone'][$loc]['phone_type_id'] = $typeId;
2263 $data['phone'][$loc]['phone_type_id'] = '';
2265 $data['phone'][$loc]['phone'] = $value;
2267 //special case to handle primary phone with different phone types
2268 // in this case we make first phone type as primary
2269 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2270 $primaryPhoneLoc = $loc;
2273 if ($loc != $primaryPhoneLoc) {
2274 unset($data['phone'][$loc]['is_primary']);
2277 elseif ($fieldName == 'email') {
2278 $data['email'][$loc]['email'] = $value;
2279 if (empty($contactID)) {
2280 $data['email'][$loc]['is_primary'] = 1;
2283 elseif ($fieldName == 'im') {
2284 if (isset($params[$key . '-provider_id'])) {
2285 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2287 if (strpos($key, '-provider_id') !== FALSE) {
2288 $data['im'][$loc]['provider_id'] = $params[$key];
2291 $data['im'][$loc]['name'] = $value;
2294 elseif ($fieldName == 'openid') {
2295 $data['openid'][$loc]['openid'] = $value;
2298 if ($fieldName === 'state_province') {
2300 if (is_numeric($value) && ((int ) $value) >= 1000) {
2301 $data['address'][$loc]['state_province_id'] = $value;
2303 elseif (empty($value)) {
2304 $data['address'][$loc]['state_province_id'] = '';
2307 $data['address'][$loc]['state_province'] = $value;
2310 elseif ($fieldName === 'country') {
2312 if (is_numeric($value) && ((int ) $value) >= 1000
2314 $data['address'][$loc]['country_id'] = $value;
2316 elseif (empty($value)) {
2317 $data['address'][$loc]['country_id'] = '';
2320 $data['address'][$loc]['country'] = $value;
2323 elseif ($fieldName === 'county') {
2324 $data['address'][$loc]['county_id'] = $value;
2326 elseif ($fieldName == 'address_name') {
2327 $data['address'][$loc]['name'] = $value;
2329 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2330 $data['address'][$loc][substr($fieldName, 8)] = $value;
2333 $data[$blockName][$loc][$fieldName] = $value;
2338 if (substr($key, 0, 4) === 'url-') {
2339 $websiteField = explode('-', $key);
2340 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2341 $data['website'][$websiteField[1]]['url'] = $value;
2343 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2344 //save email/postal greeting and addressee values if any, CRM-4575
2345 $data[$key . '_id'] = $value;
2347 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2348 // for autocomplete transfer hidden value instead of label
2349 if ($params[$key] && isset($params[$key . '_id'])) {
2350 $value = $params[$key . '_id'];
2353 // we need to append time with date
2354 if ($params[$key] && isset($params[$key . '_time'])) {
2355 $value .= ' ' . $params[$key . '_time'];
2358 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2359 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2360 ($value == '' ||
!isset($value))
2366 if (!empty($params['customRecordValues'])) {
2367 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2368 foreach ($params['customRecordValues'] as $recId => $customFields) {
2369 if (is_array($customFields) && !empty($customFields)) {
2370 foreach ($customFields as $customFieldName) {
2371 if ($customFieldName == $key) {
2381 //CRM-13596 - check for contact_sub_type_hidden first
2382 if (array_key_exists('contact_sub_type_hidden', $params)) {
2383 $type = $params['contact_sub_type_hidden'];
2386 $type = $data['contact_type'];
2387 if (!empty($data['contact_sub_type'])) {
2388 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2392 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2402 elseif ($key == 'edit') {
2406 if ($key == 'location') {
2407 foreach ($value as $locationTypeId => $field) {
2408 foreach ($field as $block => $val) {
2409 if ($block == 'address' && array_key_exists('address_name', $val)) {
2410 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2415 if ($key == 'phone' && isset($params['phone_ext'])) {
2416 $data[$key] = $value;
2417 foreach ($value as $cnt => $phoneBlock) {
2418 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2419 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2423 elseif (in_array($key, array(
2432 )) && ($value == '' ||
!isset($value)) &&
2433 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2434 ($key == 'current_employer' && empty($params['current_employer']))) {
2435 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2436 // to avoid update with empty values
2440 $data[$key] = $value;
2446 if (!isset($data['contact_type'])) {
2447 $data['contact_type'] = 'Individual';
2450 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2451 $privacy = CRM_Core_SelectValues
::privacy();
2452 foreach ($privacy as $key => $value) {
2453 if (array_key_exists($key, $fields)) {
2454 // do not reset values for existing contacts, if fields are added to a profile
2455 if (array_key_exists($key, $params)) {
2456 $data[$key] = $params[$key];
2457 if (empty($params[$key])) {
2461 elseif (!$contactID) {
2467 return array($data, $contactDetails);
2471 * Find the get contact details.
2473 * This function does not respect ACLs for now, which might need to be rectified at some
2474 * stage based on how its used.
2476 * @param string $mail
2477 * Primary email address of the contact.
2478 * @param string $ctype
2481 * @return object|null
2482 * $dao contact details
2484 public static function matchContactOnEmail($mail, $ctype = NULL) {
2485 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2486 $mail = $strtolower(trim($mail));
2488 SELECT civicrm_contact.id as contact_id,
2489 civicrm_contact.hash as hash,
2490 civicrm_contact.contact_type as contact_type,
2491 civicrm_contact.contact_sub_type as contact_sub_type
2492 FROM civicrm_contact
2493 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2495 if (Civi
::settings()->get('uniq_email_per_site')) {
2496 // try to find a match within a site (multisite).
2497 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2498 if (!empty($groups)) {
2500 INNER JOIN civicrm_group_contact gc ON
2501 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2506 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2507 $p = array(1 => array($mail, 'String'));
2510 $query .= " AND civicrm_contact.contact_type = %3";
2511 $p[3] = array($ctype, 'String');
2514 $query .= " ORDER BY civicrm_email.is_primary DESC";
2516 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2518 if ($dao->fetch()) {
2525 * Find the contact details associated with an OpenID.
2527 * @param string $openId
2528 * OpenId of the contact.
2529 * @param string $ctype
2532 * @return object|null
2533 * $dao contact details
2535 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2536 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2537 $openId = $strtolower(trim($openId));
2539 SELECT civicrm_contact.id as contact_id,
2540 civicrm_contact.hash as hash,
2541 civicrm_contact.contact_type as contact_type,
2542 civicrm_contact.contact_sub_type as contact_sub_type
2543 FROM civicrm_contact
2544 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2545 WHERE civicrm_openid.openid = %1";
2546 $p = array(1 => array($openId, 'String'));
2549 $query .= " AND civicrm_contact.contact_type = %3";
2550 $p[3] = array($ctype, 'String');
2553 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2555 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2557 if ($dao->fetch()) {
2564 * Get primary email of the contact.
2566 * @param int $contactID
2570 * Email address if present else null
2572 public static function getPrimaryEmail($contactID) {
2573 // fetch the primary email
2575 SELECT civicrm_email.email as email
2576 FROM civicrm_contact
2577 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2578 WHERE civicrm_email.is_primary = 1
2579 AND civicrm_contact.id = %1";
2580 $p = array(1 => array($contactID, 'Integer'));
2581 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2584 if ($dao->fetch()) {
2585 $email = $dao->email
;
2591 * Function to get primary OpenID of the contact.
2593 * @param int $contactID
2597 * >openid OpenID if present else null
2599 public static function getPrimaryOpenId($contactID) {
2600 // fetch the primary OpenID
2602 SELECT civicrm_openid.openid as openid
2603 FROM civicrm_contact
2604 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2605 WHERE civicrm_contact.id = %1
2606 AND civicrm_openid.is_primary = 1";
2607 $p = array(1 => array($contactID, 'Integer'));
2608 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2611 if ($dao->fetch()) {
2612 $openId = $dao->openid
;
2618 * Fetch the object and store the values in the values array.
2620 * @param array $params
2621 * Input parameters to find object.
2622 * @param array $values
2623 * Output values of the object.
2625 * @return CRM_Contact_BAO_Contact|null
2626 * The found object or null
2628 public static function getValues(&$params, &$values) {
2629 $contact = new CRM_Contact_BAO_Contact();
2631 $contact->copyValues($params);
2633 if ($contact->find(TRUE)) {
2635 CRM_Core_DAO
::storeValues($contact, $values);
2638 foreach (self
::$_commPrefs as $name) {
2639 if (isset($contact->$name)) {
2640 $privacy[$name] = $contact->$name;
2644 if (!empty($privacy)) {
2645 $values['privacy'] = $privacy;
2648 // communication Prefferance
2649 $preffComm = $comm = array();
2650 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2651 $contact->preferred_communication_method
2653 foreach ($comm as $value) {
2654 $preffComm[$value] = 1;
2656 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2659 'preferred_communication_method' => array(
2660 'newName' => 'preferred_communication_method_display',
2661 'groupName' => 'preferred_communication_method',
2665 // @todo This can be figured out from metadata & we can avoid the uncached query.
2666 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2668 $values['preferred_communication_method'] = $preffComm;
2669 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2671 if ($contact->preferred_mail_format
) {
2672 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2673 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2676 // get preferred languages
2677 if (!empty($contact->preferred_language
)) {
2678 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2681 // Calculating Year difference
2682 if ($contact->birth_date
) {
2683 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2684 if ($birthDate < date('Ymd')) {
2685 $age = CRM_Utils_Date
::calculateAge($birthDate);
2686 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2687 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2691 $contact->contact_id
= $contact->id
;
2699 * Given the component name and returns the count of participation of contact.
2701 * @param string $component
2702 * Input component name.
2703 * @param int $contactId
2705 * @param string $tableName
2706 * Optional tableName if component is custom group.
2709 * total number in database
2711 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2713 switch ($component) {
2715 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2718 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2719 CRM_Contact_BAO_Relationship
::CURRENT
,
2728 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE, FALSE, FALSE, TRUE, NULL, TRUE);
2731 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2734 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2737 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2739 case 'contribution':
2740 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2743 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2746 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2749 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2752 return CRM_Case_BAO_Case
::caseCount($contactId);
2755 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2759 'contact_id' => $contactId,
2762 'context' => 'activity',
2764 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2767 $params = array('contact_id' => $contactId);
2768 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2771 $custom = explode('_', $component);
2772 if ($custom['0'] = 'custom') {
2774 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2776 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2777 return CRM_Core_DAO
::singleValueQuery($queryString);
2783 * Update contact greetings if an update has resulted in a custom field change.
2785 * @param array $updatedFields
2786 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2787 * @param array $contactParams
2788 * Parameters known about the contact. At minimum array('contact_id' => x).
2789 * Fields in this array will take precedence over DB fields (so far only
2790 * in the case of greeting id fields).
2792 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2793 $contactID = $contactParams['contact_id'];
2794 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2795 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2796 if (!empty($tokens['all']['contact'])) {
2797 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2798 if (!empty($affectedTokens)) {
2799 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2800 $contact = new CRM_Contact_BAO_Contact();
2801 $contact->id
= $contactID;
2802 CRM_Contact_BAO_Contact
::processGreetings($contact);
2808 * Process greetings and cache.
2810 * @param object $contact
2811 * Contact object after save.
2813 public static function processGreetings(&$contact) {
2815 //@todo this function does a lot of unnecessary loading.
2816 // ensureGreetingParamsAreSet now makes sure that the contact is
2817 // loaded and using updateGreetingsOnTokenFieldChange
2818 // allows us the possibility of only doing an update if required.
2820 // The contact object has not always required the
2821 // fields that are required to calculate greetings
2822 // so we need to retrieve it again.
2823 if ($contact->_query
!== FALSE) {
2824 $contact->find(TRUE);
2827 // store object values to an array
2828 $contactDetails = array();
2829 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2830 $contactDetails = array(array($contact->id
=> $contactDetails));
2832 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2833 $updateQueryString = array();
2835 //cache email and postal greeting to greeting display
2836 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2837 $emailGreetingString = $contact->email_greeting_custom
;
2839 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2840 // the filter value for Individual contact type is set to 1
2842 'contact_type' => $contact->contact_type
,
2843 'greeting_type' => 'email_greeting',
2846 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2847 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2848 $updateQueryString[] = " email_greeting_custom = NULL ";
2851 if ($contact->email_greeting_custom
) {
2852 $updateQueryString[] = " email_greeting_display = NULL ";
2856 if ($emailGreetingString) {
2857 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2860 'CRM_Contact_BAO_Contact'
2862 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2863 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2867 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2868 $postalGreetingString = $contact->postal_greeting_custom
;
2870 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2872 'contact_type' => $contact->contact_type
,
2873 'greeting_type' => 'postal_greeting',
2875 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2876 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2877 $updateQueryString[] = " postal_greeting_custom = NULL ";
2880 if ($contact->postal_greeting_custom
) {
2881 $updateQueryString[] = " postal_greeting_display = NULL ";
2885 if ($postalGreetingString) {
2886 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2889 'CRM_Contact_BAO_Contact'
2891 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2892 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2896 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2897 $addresseeString = $contact->addressee_custom
;
2899 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2901 'contact_type' => $contact->contact_type
,
2902 'greeting_type' => 'addressee',
2905 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2906 $addresseeString = $addressee[$contact->addressee_id
];
2907 $updateQueryString[] = " addressee_custom = NULL ";
2910 if ($contact->addressee_custom
) {
2911 $updateQueryString[] = " addressee_display = NULL ";
2915 if ($addresseeString) {
2916 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2919 'CRM_Contact_BAO_Contact'
2921 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2922 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2925 if (!empty($updateQueryString)) {
2926 $updateQueryString = implode(',', $updateQueryString);
2927 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2928 CRM_Core_DAO
::executeQuery($queryString);
2933 * Retrieve loc block ids w/ given condition.
2935 * @param int $contactId
2937 * @param array $criteria
2938 * Key => value pair which should be.
2939 * fulfill by return record ids.
2940 * @param string $condOperator
2941 * Operator use for grouping multiple conditions.
2944 * loc block ids which fulfill condition.
2946 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2947 $locBlockIds = array();
2949 return $locBlockIds;
2952 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2953 $name = strtolower($block);
2954 $className = "CRM_Core_DAO_$block";
2955 $blockDAO = new $className();
2957 // build the condition.
2958 if (is_array($criteria)) {
2959 $fields = $blockDAO->fields();
2960 $conditions = array();
2961 foreach ($criteria as $field => $value) {
2962 if (array_key_exists($field, $fields)) {
2963 $cond = "( $field = $value )";
2964 // value might be zero or null.
2965 if (!$value ||
strtolower($value) == 'null') {
2966 $cond = "( $field = 0 OR $field IS NULL )";
2968 $conditions[] = $cond;
2971 if (!empty($conditions)) {
2972 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2976 $blockDAO->contact_id
= $contactId;
2978 while ($blockDAO->fetch()) {
2979 $locBlockIds[$name][] = $blockDAO->id
;
2983 return $locBlockIds;
2987 * Build context menu items.
2989 * @param int $contactId
2992 * Array of context menu for logged in user.
2994 public static function contextMenu($contactId = NULL) {
2997 'title' => ts('View Contact'),
2999 'ref' => 'view-contact',
3000 'class' => 'no-popup',
3002 'permissions' => array('view all contacts'),
3005 'title' => ts('Edit Contact'),
3007 'ref' => 'edit-contact',
3008 'class' => 'no-popup',
3010 'permissions' => array('edit all contacts'),
3013 'title' => ts('Delete Contact'),
3015 'ref' => 'delete-contact',
3017 'permissions' => array('access deleted contacts', 'delete contacts'),
3019 'contribution' => array(
3020 'title' => ts('Add Contribution'),
3022 'ref' => 'new-contribution',
3023 'key' => 'contribution',
3024 'tab' => 'contribute',
3025 'component' => 'CiviContribute',
3026 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
3027 'reset=1&action=add&context=contribution'
3029 'permissions' => array(
3030 'access CiviContribute',
3031 'edit contributions',
3034 'participant' => array(
3035 'title' => ts('Register for Event'),
3037 'ref' => 'new-participant',
3038 'key' => 'participant',
3039 'tab' => 'participant',
3040 'component' => 'CiviEvent',
3041 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3042 'permissions' => array(
3044 'edit event participants',
3047 'activity' => array(
3048 'title' => ts('Record Activity'),
3050 'ref' => 'new-activity',
3051 'key' => 'activity',
3052 'permissions' => array('edit all contacts'),
3055 'title' => ts('Add Pledge'),
3057 'ref' => 'new-pledge',
3060 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3061 'reset=1&action=add&context=pledge'
3063 'component' => 'CiviPledge',
3064 'permissions' => array(
3065 'access CiviPledge',
3069 'membership' => array(
3070 'title' => ts('Add Membership'),
3072 'ref' => 'new-membership',
3073 'key' => 'membership',
3075 'component' => 'CiviMember',
3076 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3077 'reset=1&action=add&context=membership'
3079 'permissions' => array(
3080 'access CiviMember',
3085 'title' => ts('Add Case'),
3087 'ref' => 'new-case',
3090 'component' => 'CiviCase',
3091 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3092 'permissions' => array('add cases'),
3095 'title' => ts('Add Grant'),
3097 'ref' => 'new-grant',
3100 'component' => 'CiviGrant',
3101 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3102 'reset=1&action=add&context=grant'
3104 'permissions' => array('edit grants'),
3107 'title' => ts('Add Relationship'),
3109 'ref' => 'new-relationship',
3112 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3113 'reset=1&action=add'
3115 'permissions' => array('edit all contacts'),
3118 'title' => ts('Add Note'),
3120 'ref' => 'new-note',
3123 'class' => 'medium-popup',
3124 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3125 'reset=1&action=add'
3127 'permissions' => array('edit all contacts'),
3130 'title' => ts('Send an Email'),
3132 'ref' => 'new-email',
3134 'permissions' => array('view all contacts'),
3137 'title' => ts('Add to Group'),
3139 'ref' => 'group-add-contact',
3142 'permissions' => array('edit groups'),
3145 'title' => ts('Tag Contact'),
3147 'ref' => 'tag-contact',
3150 'permissions' => array('edit all contacts'),
3154 $menu['otherActions'] = array(
3156 'title' => ts('Print Summary'),
3157 'description' => ts('Printer-friendly view of this page.'),
3159 'ref' => 'crm-contact-print',
3162 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3166 'icon' => 'crm-i fa-print',
3169 'title' => ts('vCard'),
3170 'description' => ts('vCard record for this contact.'),
3172 'ref' => 'crm-contact-vcard',
3175 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3179 'icon' => 'crm-i fa-list-alt',
3183 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3184 $menu['otherActions']['dashboard'] = array(
3185 'title' => ts('Contact Dashboard'),
3186 'description' => ts('Contact Dashboard'),
3188 'ref' => 'crm-contact-dashboard',
3189 'key' => 'dashboard',
3190 'tab' => 'dashboard',
3191 'class' => 'dashboard',
3192 // NOTE: As an alternative you can also build url on CMS specific way
3193 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3194 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3195 'icon' => 'crm-i fa-tachometer',
3199 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3201 $menu['otherActions']['user-record'] = array(
3202 'title' => ts('User Record'),
3203 'description' => ts('User Record'),
3205 'ref' => 'crm-contact-user-record',
3206 'key' => 'user-record',
3207 'tab' => 'user-record',
3208 'class' => 'user-record',
3209 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3210 'icon' => 'crm-i fa-user',
3213 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3214 $menu['otherActions']['user-add'] = array(
3215 'title' => ts('Create User Record'),
3216 'description' => ts('Create User Record'),
3218 'ref' => 'crm-contact-user-add',
3219 'key' => 'user-add',
3220 'tab' => 'user-add',
3221 'class' => 'user-add',
3222 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3223 'icon' => 'crm-i fa-user-plus',
3227 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3228 //1. check for component is active.
3229 //2. check for user permissions.
3230 //3. check for acls.
3231 //3. edit and view contact are directly accessible to user.
3233 $aclPermissionedTasks = array(
3238 'group-add-contact',
3242 $corePermission = CRM_Core_Permission
::getPermission();
3244 $contextMenu = array();
3245 foreach ($menu as $key => $values) {
3246 if ($key != 'otherActions') {
3248 // user does not have necessary permissions.
3249 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3252 // build directly accessible action menu.
3253 if (in_array($values['ref'], array(
3257 $contextMenu['primaryActions'][$key] = array(
3258 'title' => $values['title'],
3259 'ref' => $values['ref'],
3260 'class' => CRM_Utils_Array
::value('class', $values),
3261 'key' => $values['key'],
3266 // finally get menu item for -more- action widget.
3267 $contextMenu['moreActions'][$values['weight']] = array(
3268 'title' => $values['title'],
3269 'ref' => $values['ref'],
3270 'href' => CRM_Utils_Array
::value('href', $values),
3271 'tab' => CRM_Utils_Array
::value('tab', $values),
3272 'class' => CRM_Utils_Array
::value('class', $values),
3273 'key' => $values['key'],
3277 foreach ($values as $value) {
3278 // user does not have necessary permissions.
3279 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3283 // finally get menu item for -more- action widget.
3284 $contextMenu['otherActions'][$value['weight']] = array(
3285 'title' => $value['title'],
3286 'ref' => $value['ref'],
3287 'href' => CRM_Utils_Array
::value('href', $value),
3288 'tab' => CRM_Utils_Array
::value('tab', $value),
3289 'class' => CRM_Utils_Array
::value('class', $value),
3290 'icon' => CRM_Utils_Array
::value('icon', $value),
3291 'key' => $value['key'],
3297 ksort($contextMenu['moreActions']);
3298 ksort($contextMenu['otherActions']);
3300 return $contextMenu;
3304 * Check if user has permissions to access items in action menu.
3306 * @param array $aclPermissionedTasks
3307 * Array containing ACL related tasks.
3308 * @param string $corePermission
3309 * The permission of the user (edit or view or null).
3310 * @param array $menuOptions
3311 * Array containing params of the menu (title, href, etc).
3314 * TRUE if user has all permissions, FALSE if otherwise.
3316 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3317 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3319 // if component action - make sure component is enable.
3320 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3324 // make sure user has all required permissions.
3325 $hasAllPermissions = FALSE;
3327 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3328 if (!is_array($permissions) ||
empty($permissions)) {
3329 $hasAllPermissions = TRUE;
3332 // iterate for required permissions in given permissions array.
3333 if (!$hasAllPermissions) {
3334 $hasPermissions = 0;
3335 foreach ($permissions as $permission) {
3336 if (CRM_Core_Permission
::check($permission)) {
3341 if (count($permissions) == $hasPermissions) {
3342 $hasAllPermissions = TRUE;
3345 // if still user does not have required permissions, check acl.
3346 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3347 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3348 $corePermission == CRM_Core_Permission
::EDIT
3350 $hasAllPermissions = TRUE;
3352 elseif (in_array($menuOptions['ref'], array(
3355 // grant permissions for these tasks.
3356 $hasAllPermissions = TRUE;
3361 return $hasAllPermissions;
3365 * Retrieve display name of contact that address is shared.
3367 * This is based on $masterAddressId or $contactId .
3369 * @param int $masterAddressId
3371 * @param int $contactId
3372 * Contact id. (deprecated - do not use)
3374 * @return string|null
3375 * the found display name or null.
3377 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3378 $masterDisplayName = NULL;
3379 if (!$masterAddressId) {
3380 return $masterDisplayName;
3384 SELECT display_name from civicrm_contact
3385 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3386 WHERE civicrm_address.id = " . $masterAddressId;
3388 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3389 return $masterDisplayName;
3393 * Get the creation/modification times for a contact.
3395 * @param int $contactId
3398 * Dates - ('created_date' => $, 'modified_date' => $)
3400 public static function getTimestamps($contactId) {
3401 $timestamps = CRM_Core_DAO
::executeQuery(
3402 'SELECT created_date, modified_date
3403 FROM civicrm_contact
3406 1 => array($contactId, 'Integer'),
3409 if ($timestamps->fetch()) {
3411 'created_date' => $timestamps->created_date
,
3412 'modified_date' => $timestamps->modified_date
,
3421 * Get a list of triggers for the contact table.
3423 * @see hook_civicrm_triggerInfo
3424 * @see CRM_Core_DAO::triggerRebuild
3425 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3428 * @param null $tableName
3430 public static function triggerInfo(&$info, $tableName = NULL) {
3431 //during upgrade, first check for valid version and then create triggers
3432 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3433 if (CRM_Core_Config
::isUpgradeMode()) {
3434 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3435 //if current version is less than 4.3.alpha1 dont create below triggers
3436 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3441 // Modifications to these records should update the contact timestamps.
3442 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3443 ->setRelations(array(
3444 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3445 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3446 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3447 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3448 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3450 ->alterTriggerInfo($info, $tableName);
3452 // Update phone table to populate phone_numeric field
3453 if (!$tableName ||
$tableName == 'civicrm_phone') {
3454 // Define stored sql function needed for phones
3455 $sqlTriggers = Civi
::service('sql_triggers');
3456 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3457 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3459 'table' => array('civicrm_phone'),
3461 'event' => array('INSERT', 'UPDATE'),
3462 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3468 * Check if contact is being used in civicrm_domain based on $contactId.
3470 * @param int $contactId
3474 * true if present else false.
3476 public static function checkDomainContact($contactId) {
3480 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3491 * Get options for a given contact field.
3493 * @see CRM_Core_DAO::buildOptions
3495 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3496 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3498 * @param string $fieldName
3499 * @param string $context
3500 * @see CRM_Core_DAO::buildOptionsContext
3501 * @param array $props
3502 * whatever is known about this dao object.
3504 * @return array|bool
3506 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3508 // Special logic for fields whose options depend on context or properties
3509 switch ($fieldName) {
3510 case 'contact_sub_type':
3511 if (!empty($props['contact_type'])) {
3512 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3516 case 'contact_type':
3517 if ($context == 'search') {
3518 // CRM-15495 - EntityRef filters and basic search forms expect this format
3519 // FIXME: Search builder does not
3520 return CRM_Contact_BAO_ContactType
::getSelectElements();
3524 // The contact api supports some related entities so we'll honor that by fetching their options
3527 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3531 $props['entity_table'] = 'civicrm_contact';
3532 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3534 case 'state_province_id':
3535 case 'state_province':
3536 case 'state_province_name':
3541 case 'worldregion_id':
3542 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3545 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3549 * Delete a contact-related object that has an 'is_primary' field.
3551 * Ensures that is_primary gets assigned to another object if available
3552 * Also calls pre/post hooks
3554 * @param string $type
3558 public static function deleteObjectWithPrimary($type, $id) {
3559 if (!$id ||
!is_numeric($id)) {
3562 $daoName = "CRM_Core_DAO_$type";
3563 $obj = new $daoName();
3567 if ($obj->fetch()) {
3568 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3569 $contactId = $obj->contact_id
;
3575 // is_primary is only relavent if this field belongs to a contact
3577 $dao = new $daoName();
3578 $dao->contact_id
= $contactId;
3579 $dao->is_primary
= 1;
3580 // Pick another record to be primary (if one isn't already)
3581 if (!$dao->find(TRUE)) {
3582 $dao->is_primary
= 0;
3584 if ($dao->fetch()) {
3585 $dao->is_primary
= 1;
3590 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3597 public function addSelectWhereClause() {
3598 // We always return an array with these keys, even if they are empty,
3599 // because this tells the query builder that we have considered these fields for acls
3601 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3602 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
array() : array('!= 1'),
3604 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3609 * Get any existing duplicate contacts based on the input parameters.
3611 * @param array $input
3612 * Input parameters to be matched.
3613 * @param string $contactType
3614 * @param string $rule
3617 * @param $excludedContactIDs
3618 * An array of ids not to be included in the results.
3619 * @param bool $checkPermissions
3620 * @param int $ruleGroupID
3621 * ID of the rule group to be used if an override is desirable.
3622 * @param array $contextParams
3623 * The context if relevant, eg. ['event_id' => X]
3627 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3628 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3629 $dedupeParams['check_permission'] = $checkPermissions;
3630 $dedupeParams['contact_type'] = $contactType;
3631 $dedupeParams['rule'] = $rule;
3632 $dedupeParams['rule_group_id'] = $ruleGroupID;
3633 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3634 $dedupeResults['ids'] = [];
3635 $dedupeResults['handled'] = FALSE;
3636 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3637 if (!$dedupeResults['handled']) {
3638 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3640 return $dedupeResults['ids'];
3644 * Get the first duplicate contacts based on the input parameters.
3646 * @param array $input
3647 * Input parameters to be matched.
3648 * @param string $contactType
3649 * @param string $rule
3652 * @param $excludedContactIDs
3653 * An array of ids not to be included in the results.
3654 * @param bool $checkPermissions
3655 * @param int $ruleGroupID
3656 * ID of the rule group to be used if an override is desirable.
3657 * @param array $contextParams
3658 * The context if relevant, eg. ['event_id' => X]
3662 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3663 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3671 * Check if a field is associated with an entity that has a location type.
3673 * (ie. is an address, phone, email etc field).
3675 * @param string $fieldTitle
3676 * Title of the field (not the name - create a new function for that if required).
3680 public static function isFieldHasLocationType($fieldTitle) {
3681 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3682 if ($field['title'] === $fieldTitle) {
3683 return CRM_Utils_Array
::value('hasLocationType', $field);
3690 * @param array $appendProfiles
3691 * Name of profile(s) to append to each link.
3695 public static function getEntityRefCreateLinks($appendProfiles = []) {
3696 // You'd think that "create contacts" would be the permission to check,
3697 // But new contact popups are profile forms and those use their own permissions.
3698 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3702 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3703 $profiles[] = 'new_' . strtolower($contactType);
3705 $retrieved = civicrm_api3('uf_group', 'get', [
3706 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3709 $links = $append = [];
3710 if (!empty($retrieved['values'])) {
3712 'individual' => 'fa-user',
3713 'organization' => 'fa-building',
3714 'household' => 'fa-home',
3716 foreach ($retrieved['values'] as $id => $profile) {
3717 if (in_array($profile['name'], $profiles)) {
3719 'label' => $profile['title'],
3720 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3721 NULL, NULL, FALSE, FALSE, TRUE),
3722 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3723 'icon' => CRM_Utils_Array
::value(str_replace('new_', '', $profile['name']), $icons),
3730 foreach ($append as $id) {
3731 foreach ($links as &$link) {
3732 $link['url'] .= ",$id";
3742 public static function getEntityRefFilters() {
3744 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3745 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3746 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3747 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3748 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3749 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3750 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3751 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3752 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3753 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],