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';
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']);
146 $params['contact_sub_type'] = 'null';
149 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
150 CRM_Utils_Array
::formatArrayKeys($params['preferred_communication_method']);
151 $contact->preferred_communication_method
= CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
152 unset($params['preferred_communication_method']);
155 $defaults = ['source' => CRM_Utils_Array
::value('contact_source', $params)];
156 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
157 $defaults['display_name'] = $params['organization_name'];
158 $defaults['sort_name'] = $params['organization_name'];
160 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
161 $defaults['display_name'] = $params['household_name'];
162 $defaults['sort_name'] = $params['household_name'];
164 $params = array_merge($defaults, $params);
166 $allNull = $contact->copyValues($params);
168 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
170 if ($contact->contact_type
== 'Individual') {
172 // @todo allow the lines below to be overridden by input or hooks & add tests,
173 // as has been done for households and organizations.
174 // Format individual fields.
175 CRM_Contact_BAO_Individual
::format($params, $contact);
178 if (strlen($contact->display_name
) > 128) {
179 $contact->display_name
= substr($contact->display_name
, 0, 128);
181 if (strlen($contact->sort_name
) > 128) {
182 $contact->sort_name
= substr($contact->sort_name
, 0, 128);
185 $privacy = CRM_Utils_Array
::value('privacy', $params);
187 is_array($privacy) &&
191 foreach (self
::$_commPrefs as $name) {
192 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
196 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
197 // @todo - does this mean we can remove this block?
198 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
199 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
201 $contact->hash
= md5(uniqid(rand(), TRUE));
204 // Even if we don't need $employerId, it's important to call getFieldValue() before
205 // the contact is saved because we want the existing value to be cached.
206 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
207 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
212 CRM_Core_BAO_Log
::register($contact->id
,
218 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
219 // Create current employer.
220 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
223 if (empty($params['contact_id'])) {
227 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
231 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
236 // Update cached employer name.
237 if ($contact->contact_type
== 'Organization') {
238 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
247 * takes an associative array and creates a contact object and all the associated
248 * derived objects (i.e. individual, location, email, phone etc)
250 * This function is invoked from within the web form layer and also from the api layer
252 * @param array $params
253 * (reference ) an assoc array of name/value pairs.
254 * @param bool $fixAddress
255 * If we need to fix address.
256 * @param bool $invokeHooks
257 * If we need to invoke hooks.
259 * @param bool $skipDelete
260 * Unclear parameter, passed to website create
262 * @todo explain this parameter
265 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
266 * Created or updated contribution object. We are deprecating returning an error in
267 * favour of exceptions
269 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
271 if (empty($params['contact_type']) && empty($params['contact_id'])) {
277 if (!empty($params['contact_id'])) {
278 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
281 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
286 self
::ensureGreetingParamsAreSet($params);
288 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
289 if (empty($params['contact_id'])) {
290 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
291 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
292 $params['preferred_language'] = $language;
295 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
296 if (empty($params['communication_style_id'])) {
297 $defaultCommunicationStyleId = CRM_Core_OptionGroup
::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
298 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
302 $transaction = new CRM_Core_Transaction();
304 $contact = self
::add($params);
306 // Not dying here is stupid, since we get into weird situation and into a bug that
307 // is impossible to figure out for the user or for us
309 CRM_Core_Error
::fatal();
312 $params['contact_id'] = $contact->id
;
314 if (Civi
::settings()->get('is_enabled')) {
315 // Enabling multisite causes the contact to be added to the domain group.
316 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
317 if (!empty($domainGroupID)) {
318 if (!empty($params['group']) && is_array($params['group'])) {
319 $params['group'][$domainGroupID] = 1;
322 $params['group'] = array($domainGroupID => 1);
327 if (array_key_exists('group', $params)) {
328 $contactIds = array($params['contact_id']);
329 foreach ($params['group'] as $groupId => $flag) {
331 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
333 elseif ($flag == -1) {
334 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
339 // Add location Block data.
340 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
341 foreach ($blocks as $name => $value) {
342 $contact->$name = $value;
344 if (!empty($params['updateBlankLocInfo'])) {
348 if (isset($params['website'])) {
349 CRM_Core_BAO_Website
::process($params['website'], $contact->id
, $skipDelete);
352 $userID = CRM_Core_Session
::singleton()->get('userID');
354 if (!empty($params['note'])) {
355 if (is_array($params['note'])) {
356 foreach ($params['note'] as $note) {
357 $contactId = $contact->id
;
358 if (isset($note['contact_id'])) {
359 $contactId = $note['contact_id'];
361 //if logged in user, overwrite contactId
363 $contactId = $userID;
367 'entity_id' => $contact->id
,
368 'entity_table' => 'civicrm_contact',
369 'note' => $note['note'],
370 'subject' => CRM_Utils_Array
::value('subject', $note),
371 'contact_id' => $contactId,
373 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
377 $contactId = $contact->id
;
378 //if logged in user, overwrite contactId
380 $contactId = $userID;
384 'entity_id' => $contact->id
,
385 'entity_table' => 'civicrm_contact',
386 'note' => $params['note'],
387 'subject' => CRM_Utils_Array
::value('subject', $params),
388 'contact_id' => $contactId,
390 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
394 // update the UF user_unique_id if that has changed
395 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
397 if (!empty($params['custom']) &&
398 is_array($params['custom'])
400 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
403 // make a civicrm_subscription_history entry only on contact create (CRM-777)
404 if (empty($params['contact_id'])) {
405 $subscriptionParams = array(
406 'contact_id' => $contact->id
,
410 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
413 $transaction->commit();
415 // CRM-6367: fetch the right label for contact type’s display
416 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
417 'CRM_Contact_DAO_ContactType',
418 $contact->contact_type
,
423 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
427 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
430 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
434 // In order to prevent a series of expensive queries in intensive batch processing
435 // api calls may pass in skip_greeting_processing, probably doing it later via the
436 // scheduled job. CRM-21551
437 if (empty($params['skip_greeting_processing'])) {
438 self
::processGreetings($contact);
445 * Ensure greeting parameters are set.
447 * By always populating greetings here we can be sure they are set if required & avoid a call later.
448 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
450 * @param array $params
452 public static function ensureGreetingParamsAreSet(&$params) {
453 $allGreetingParams = array('addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id');
454 $missingGreetingParams = array();
456 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
457 if (empty($params[$greetingParam])) {
458 $missingGreetingParams[$greetingIndex] = $greetingParam;
462 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
463 $savedGreetings = civicrm_api3('Contact', 'getsingle', array(
464 'id' => $params['contact_id'],
465 'return' => array_keys($missingGreetingParams),
469 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
470 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
471 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
474 // Filter out other fields.
475 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
476 $params = array_merge($params, $savedGreetings);
479 foreach ($missingGreetingParams as $greetingName => $greeting) {
480 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
484 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
485 if ($params[$greetingParam] === 'null') {
486 // If we are setting it to null then null out the display field.
487 $params[$greetingIndex . '_display'] = 'null';
493 * Get the display name and image of a contact.
498 * @param bool $includeTypeInReturnParameters
499 * Should type be part of the returned array?
502 * the displayName and contactImage for this contact
504 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
505 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
507 SELECT civicrm_contact.*,
508 civicrm_email.email as email
510 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
511 AND civicrm_email.is_primary = 1
512 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
513 $dao = new CRM_Core_DAO();
516 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
517 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
519 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
520 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
523 // use email if display_name is empty
524 if (empty($dao->display_name
)) {
525 $displayName = $dao->email
;
528 $displayName = $dao->display_name
;
531 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
533 return $includeTypeInReturnParameters ?
array(
537 $dao->contact_sub_type
,
539 ) : array($displayName, $image, $imageUrl);
545 * Add billing fields to the params if appropriate.
547 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
548 * don't then we should set the name fields to the filling fields AND add the preserveDBName
549 * parameter (which will tell the BAO only to set those fields if none already exist.
551 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
552 * matching is best done by hipsters.
554 * @param array $params
556 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
557 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
558 foreach ($nameFields as $field) {
559 if (!empty($params[$field])) {
563 // There are only 3 - we can iterate through them twice :-)
564 foreach ($nameFields as $field) {
565 if (!empty($params['billing_' . $field])) {
566 $params[$field] = $params['billing_' . $field];
568 $params['preserveDBName'] = TRUE;
574 * Resolve a state province string (UT or Utah) to an ID.
576 * If country has been passed in we should select a state belonging to that country.
578 * Alternatively we should choose from enabled countries, prioritising the default country.
580 * @param array $values
581 * @param int|NULL $countryID
585 protected static function resolveStateProvinceID($values, $countryID) {
588 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
589 if (CRM_Utils_Array
::lookupValue($values,
594 return $values['state_province_id'];
596 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
597 if (CRM_Utils_Array
::lookupValue($values,
602 return $values['state_province_id'];
607 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
608 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
609 // prefer matching country..
610 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, array('country_id' => Civi
::settings()->get('defaultContactCountry')));
611 if (CRM_Utils_Array
::lookupValue($values,
616 return $values['state_province_id'];
619 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
620 if (CRM_Utils_Array
::lookupValue($values,
625 return $values['state_province_id'];
628 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
629 if (CRM_Utils_Array
::lookupValue($values,
634 return $values['state_province_id'];
636 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
637 if (CRM_Utils_Array
::lookupValue($values,
642 return $values['state_province_id'];
650 * Get the relevant location entity for the array key.
652 * Based on the field name we determine which location entity
653 * we are dealing with. Apart from a few specific ones they
654 * are mostly 'address' (the default).
656 * @param string $fieldName
660 protected static function getLocationEntityForKey($fieldName) {
661 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
664 if ($fieldName === 'phone_ext') {
671 * Create last viewed link to recently updated contact.
673 * @param array $crudLinkSpec
674 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
675 * - entity_table: string, eg "civicrm_contact"
679 * NULL if unavailable, or
680 * [path: string, query: string, title: string]
681 * @see CRM_Utils_System::createDefaultCrudLink
683 public function createDefaultCrudLink($crudLinkSpec) {
684 switch ($crudLinkSpec['action']) {
685 case CRM_Core_Action
::VIEW
:
687 'title' => $this->display_name
,
688 'path' => 'civicrm/contact/view',
696 case CRM_Core_Action
::UPDATE
:
698 'title' => $this->display_name
,
699 'path' => 'civicrm/contact/add',
702 'action' => 'update',
712 * Get the values for pseudoconstants for name->value and reverse.
716 * This is called specifically from the contact import parser & should be moved there
717 * as it is not truly a generic function.
719 * @param array $defaults
720 * (reference) the default values, some of which need to be resolved.
721 * @param bool $reverse
722 * Always true as this function is only called from one place..
724 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
725 // Hack for birth_date.
726 if (!empty($defaults['birth_date'])) {
727 if (is_array($defaults['birth_date'])) {
728 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
732 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
733 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
734 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
735 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
737 //lookup value of email/postal greeting, addressee, CRM-4575
738 foreach (self
::$_greetingTypes as $greeting) {
739 $filterCondition = array(
740 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
741 'greeting_type' => $greeting,
743 CRM_Utils_Array
::lookupValue($defaults, $greeting,
744 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
748 $blocks = array('address', 'im', 'phone');
749 foreach ($blocks as $name) {
750 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
753 foreach ($defaults[$name] as $count => & $values) {
755 //get location type id.
756 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
758 if ($name == 'address') {
759 // FIXME: lookupValue doesn't work for vcard_name
760 if (!empty($values['location_type_id'])) {
761 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
762 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
765 if (!CRM_Utils_Array
::lookupValue($values,
767 CRM_Core_PseudoConstant
::country(),
772 CRM_Utils_Array
::lookupValue($values,
774 CRM_Core_PseudoConstant
::countryIsoCode(),
778 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
779 if ($stateProvinceID) {
780 $values['state_province_id'] = $stateProvinceID;
783 if (!empty($values['state_province_id'])) {
784 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
787 $countyList = CRM_Core_PseudoConstant
::county();
789 CRM_Utils_Array
::lookupValue($values,
797 CRM_Utils_Array
::lookupValue($values,
799 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
804 if ($name == 'phone') {
805 CRM_Utils_Array
::lookupValue($values,
807 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
812 // Kill the reference.
819 * Fetch object based on array of properties.
821 * @param array $params
822 * (reference ) an assoc array of name/value pairs.
823 * @param array $defaults
824 * (reference ) an assoc array to hold the name / value pairs.
825 * in a hierarchical manner
826 * @param bool $microformat
827 * For location in microformat.
829 * @return CRM_Contact_BAO_Contact
831 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
832 if (array_key_exists('contact_id', $params)) {
833 $params['id'] = $params['contact_id'];
835 elseif (array_key_exists('id', $params)) {
836 $params['contact_id'] = $params['id'];
839 $contact = self
::getValues($params, $defaults);
841 unset($params['id']);
843 //get the block information for this contact
844 $entityBlock = array('contact_id' => $params['contact_id']);
845 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
846 $defaults = array_merge($defaults, $blocks);
847 foreach ($blocks as $block => $value) {
848 $contact->$block = $value;
851 if (!isset($params['noNotes'])) {
852 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
855 if (!isset($params['noRelationships'])) {
856 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
859 if (!isset($params['noGroups'])) {
860 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
863 if (!isset($params['noWebsite'])) {
864 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
871 * Get the display name of a contact.
876 * @return null|string
877 * display name of the contact if found
879 public static function displayName($id) {
882 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
889 * Delete a contact and all its associated records.
892 * Id of the contact to delete.
893 * @param bool $restore
894 * Whether to actually restore, not delete.
895 * @param bool $skipUndelete
896 * Whether to force contact delete or not.
897 * @param bool $checkPermissions
900 * Was contact deleted?
902 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
907 // If trash is disabled in system settings then we always skip
908 if (!Civi
::settings()->get('contact_undelete')) {
909 $skipUndelete = TRUE;
912 // make sure we have edit permission for this contact
914 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
915 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
921 // Restrict contact to be delete if contact has financial trxns
923 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
927 // make sure this contact_id does not have any membership types
928 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
931 'member_of_contact_id'
933 if ($membershipTypeID) {
937 $contact = new CRM_Contact_DAO_Contact();
939 if (!$contact->find(TRUE)) {
943 $contactType = $contact->contact_type
;
944 // currently we only clear employer cache.
945 // we are now deleting inherited membership if any.
946 if ($contact->contact_type
== 'Organization') {
947 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
948 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
949 if (!empty($relationshipDtls)) {
950 foreach ($relationshipDtls as $rId => $details) {
951 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
954 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
958 return self
::contactTrashRestore($contact, TRUE);
961 // start a new transaction
962 $transaction = new CRM_Core_Transaction();
965 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
967 //delete billing address if exists.
968 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
970 // delete the log entries since we dont have triggers enabled as yet
971 $logDAO = new CRM_Core_DAO_Log();
972 $logDAO->entity_table
= 'civicrm_contact';
973 $logDAO->entity_id
= $id;
976 // delete contact participants CRM-12155
977 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
979 // delete contact contributions CRM-12155
980 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
982 // do activity cleanup, CRM-5604
983 CRM_Activity_BAO_Activity
::cleanupActivity($id);
985 // delete all notes related to contact
986 CRM_Core_BAO_Note
::cleanContactNotes($id);
988 // delete cases related to contact
989 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
990 if (!empty($contactCases)) {
991 foreach ($contactCases as $caseId) {
992 //check if case is associate with other contact or not.
993 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
994 if (count($caseContactId) <= 1) {
995 CRM_Case_BAO_Case
::deleteCase($caseId);
1003 self
::contactTrashRestore($contact);
1006 //delete the contact id from recently view
1007 CRM_Utils_Recent
::delContact($id);
1008 self
::updateContactCache($id, empty($restore));
1010 // delete any prevnext/dupe cache entry
1011 // These two calls are redundant in default deployments, but they're
1012 // meaningful if "prevnext" is memory-backed.
1013 Civi
::service('prevnext')->deleteItem($id);
1014 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1016 $transaction->commit();
1018 if ($skipUndelete) {
1019 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1026 * Action to update any caches relating to a recently update contact.
1028 * I was going to call this from delete as well as from create to ensure the delete is being
1029 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1030 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1031 * where the call involved a subquery that was locking the table.
1033 * @param int $contactID
1034 * @param bool $isTrashed
1036 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1039 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1040 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1041 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1042 // but this should not cause any change as long as contacts are not being trashed outside the
1043 // main functions for that.
1044 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
1047 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1052 * Delete the image of a contact.
1055 * Id of the contact.
1058 * Was contact image deleted?
1060 public static function deleteContactImage($id) {
1065 $contact = new self();
1067 $contact->image_URL
= 'null';
1074 * Return proportional height and width of the image.
1076 * @param int $imageWidth
1079 * @param int $imageHeight
1083 * Thumb dimension of image
1085 public static function getThumbSize($imageWidth, $imageHeight) {
1087 if ($imageWidth && $imageHeight) {
1088 $imageRatio = $imageWidth / $imageHeight;
1093 if ($imageRatio > 1) {
1094 $imageThumbWidth = $thumbWidth;
1095 $imageThumbHeight = round($thumbWidth / $imageRatio);
1098 $imageThumbHeight = $thumbWidth;
1099 $imageThumbWidth = round($thumbWidth * $imageRatio);
1102 return array($imageThumbWidth, $imageThumbHeight);
1106 * Validate type of contact image.
1108 * @param array $params
1109 * @param string $imageIndex
1110 * Index of image field.
1111 * @param string $statusMsg
1112 * Status message to be set after operation.
1113 * @param string $opType
1114 * Type of operation like fatal, bounce etc.
1117 * true if valid image extension
1119 public static function processImageParams(
1121 $imageIndex = 'image_URL',
1135 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1136 $photo = basename($params[$imageIndex]['name']);
1137 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1141 unset($params[$imageIndex]);
1143 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1145 if ($opType == 'status') {
1146 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1148 // FIXME: additional support for fatal, bounce etc could be added.
1154 * Extract contact id from url for deleting contact image.
1156 public static function processImage() {
1158 $action = CRM_Utils_Request
::retrieve('action', 'String');
1159 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1160 // retrieve contact id in case of Profile context
1161 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1162 $cid = $cid ?
$cid : $id;
1163 if ($action & CRM_Core_Action
::DELETE
) {
1164 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1165 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1166 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1167 $session = CRM_Core_Session
::singleton();
1168 $toUrl = $session->popUserContext();
1169 CRM_Utils_System
::redirect($toUrl);
1175 * Function to set is_delete true or restore deleted contact.
1177 * @param CRM_Contact_DAO_Contact $contact
1178 * Contact DAO object.
1179 * @param bool $restore
1180 * True to set the is_delete = 1 else false to restore deleted contact,
1181 * i.e. is_delete = 0
1185 public static function contactTrashRestore($contact, $restore = FALSE) {
1186 $updateParams = array(
1187 'id' => $contact->id
,
1188 'is_deleted' => $restore ?
0 : 1,
1191 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1193 $params = array(1 => array($contact->id
, 'Integer'));
1195 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1196 CRM_Core_DAO
::executeQuery($query, $params);
1199 $contact->copyValues($updateParams);
1201 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
1203 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1209 * Get contact type for a contact.
1212 * Id of the contact whose contact type is needed.
1215 * contact_type if $id found else null ""
1217 public static function getContactType($id) {
1218 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1222 * Get contact sub type for a contact.
1225 * Id of the contact whose contact sub type is needed.
1227 * @param string $implodeDelimiter
1230 * contact_sub_type if $id found else null ""
1232 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1233 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1235 return $implodeDelimiter ?
NULL : array();
1238 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1240 if ($implodeDelimiter) {
1241 $subtype = implode($implodeDelimiter, $subtype);
1247 * Get pair of contact-type and sub-type for a contact.
1250 * Id of the contact whose contact sub/contact type is needed.
1254 public static function getContactTypes($id) {
1255 $params = array('id' => $id);
1257 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1260 array('contact_type', 'contact_sub_type')
1264 $contactTypes = array();
1265 if ($contact->contact_sub_type
) {
1266 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1268 array_unshift($contactTypes, $contact->contact_type
);
1270 return $contactTypes;
1273 CRM_Core_Error
::fatal();
1278 * Combine all the importable fields from the lower levels object.
1280 * The ordering is important, since currently we do not have a weight
1281 * scheme. Adding weight is super important
1283 * @param int|string $contactType contact Type
1284 * @param bool $status
1285 * Status is used to manipulate first title.
1286 * @param bool $showAll
1287 * If true returns all fields (includes disabled fields).
1288 * @param bool $isProfile
1289 * If its profile mode.
1290 * @param bool $checkPermission
1291 * If false, do not include permissioning clause (for custom data).
1293 * @param bool $withMultiCustomFields
1296 * array of importable Fields
1298 public static function importableFields(
1299 $contactType = 'Individual',
1303 $checkPermission = TRUE,
1304 $withMultiCustomFields = FALSE
1306 if (empty($contactType)) {
1307 $contactType = 'All';
1310 $cacheKeyString = "importableFields $contactType";
1311 $cacheKeyString .= $status ?
'_1' : '_0';
1312 $cacheKeyString .= $showAll ?
'_1' : '_0';
1313 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1314 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1316 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1319 // check if we can retrieve from database cache
1320 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1324 $fields = CRM_Contact_DAO_Contact
::import();
1326 // get the fields thar are meant for contact types
1327 if (in_array($contactType, array(
1333 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1336 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1337 CRM_Core_DAO_Phone
::import(),
1338 CRM_Core_DAO_Email
::import(),
1339 CRM_Core_DAO_IM
::import(TRUE),
1340 CRM_Core_DAO_OpenID
::import()
1343 $locationFields = array_merge($locationFields,
1344 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1352 foreach ($locationFields as $key => $field) {
1353 $locationFields[$key]['hasLocationType'] = TRUE;
1356 $fields = array_merge($fields, $locationFields);
1358 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1359 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1362 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1363 $fields['url']['hasWebsiteType'] = TRUE;
1365 if ($contactType != 'All') {
1366 $fields = array_merge($fields,
1367 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1372 $withMultiCustomFields
1375 //unset the fields, which are not related to their
1377 $commonValues = array(
1378 'Individual' => array(
1382 'organization_name',
1384 'Household' => array(
1394 'organization_name',
1402 'Organization' => array(
1417 foreach ($commonValues[$contactType] as $value) {
1418 unset($fields[$value]);
1422 foreach (array('Individual', 'Household', 'Organization') as $type) {
1423 $fields = array_merge($fields,
1424 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1429 $withMultiCustomFields
1436 $fields = array_merge($fields, array(
1438 'title' => ts('Group(s)'),
1442 'title' => ts('Tag(s)'),
1446 'title' => ts('Note'),
1449 'communication_style_id' => array(
1450 'title' => ts('Communication Style'),
1451 'name' => 'communication_style_id',
1456 //Sorting fields in alphabetical order(CRM-1507)
1457 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1459 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1462 self
::$_importableFields[$cacheKeyString] = $fields;
1466 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1467 self
::$_importableFields[$cacheKeyString]
1471 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1472 self
::$_importableFields[$cacheKeyString]
1480 * Combine all the exportable fields from the lower levels object.
1482 * Currently we are using importable fields as exportable fields
1484 * @param int|string $contactType contact Type
1485 * @param bool $status
1486 * True while exporting primary contacts.
1487 * @param bool $export
1488 * True when used during export.
1489 * @param bool $search
1490 * True when used during search, might conflict with export param?.
1492 * @param bool $withMultiRecord
1493 * @param bool $checkPermissions
1495 * array of exportable Fields
1497 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1498 if (empty($contactType)) {
1499 $contactType = 'All';
1502 $cacheKeyString = "exportableFields $contactType";
1503 $cacheKeyString .= $export ?
'_1' : '_0';
1504 $cacheKeyString .= $status ?
'_1' : '_0';
1505 $cacheKeyString .= $search ?
'_1' : '_0';
1506 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1507 //calculates custom fields takes into account the logged in user & caches that for all users
1508 //as an interim fix we will cache the fields by contact
1509 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1511 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1512 if (!self
::$_exportableFields) {
1513 self
::$_exportableFields = array();
1516 // check if we can retrieve from database cache
1517 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1520 $fields = CRM_Contact_DAO_Contact
::export();
1522 // The fields are meant for contact types.
1523 if (in_array($contactType, array(
1529 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1531 // add current employer for individuals
1532 $fields = array_merge($fields, array(
1533 'current_employer' =>
1535 'name' => 'organization_name',
1536 'title' => ts('Current Employer'),
1540 $locationType = array(
1541 'location_type' => array(
1542 'name' => 'location_type',
1543 'where' => 'civicrm_location_type.name',
1544 'title' => ts('Location Type'),
1548 $IMProvider = array(
1549 'im_provider' => array(
1550 'name' => 'im_provider',
1551 'where' => 'civicrm_im.provider_id',
1552 'title' => ts('IM Provider'),
1556 $locationFields = array_merge($locationType,
1557 CRM_Core_DAO_Address
::export(),
1558 CRM_Core_DAO_Phone
::export(),
1559 CRM_Core_DAO_Email
::export(),
1561 CRM_Core_DAO_IM
::export(TRUE),
1562 CRM_Core_DAO_OpenID
::export()
1565 $locationFields = array_merge($locationFields,
1566 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1569 foreach ($locationFields as $key => $field) {
1570 $locationFields[$key]['hasLocationType'] = TRUE;
1573 $fields = array_merge($fields, $locationFields);
1576 $fields = array_merge($fields,
1577 CRM_Core_DAO_Worldregion
::export()
1580 $fields = array_merge($fields,
1581 CRM_Contact_DAO_Contact
::export()
1585 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1587 if ($contactType != 'All') {
1588 $fields = array_merge($fields,
1589 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1598 $fields = array_merge($fields,
1599 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1603 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1606 $fields = array_merge($fields, array(
1608 'title' => ts('Group(s)'),
1612 'title' => ts('Tag(s)'),
1616 'title' => ts('Note(s)'),
1622 $fields = array_merge($fields, array(
1624 'title' => ts('Group(s)'),
1628 'title' => ts('Tag(s)'),
1632 'title' => ts('Note(s)'),
1638 //Sorting fields in alphabetical order(CRM-1507)
1639 foreach ($fields as $k => $v) {
1640 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1643 $fields = array_merge($sortArray, $fields);
1644 //unset the field which are not related to their contact type.
1645 if ($contactType != 'All') {
1646 $commonValues = array(
1647 'Individual' => array(
1651 'organization_name',
1652 'email_greeting_custom',
1653 'postal_greeting_custom',
1656 'Household' => array(
1666 'organization_name',
1674 'email_greeting_custom',
1675 'postal_greeting_custom',
1680 'Organization' => array(
1691 'email_greeting_custom',
1692 'postal_greeting_custom',
1702 foreach ($commonValues[$contactType] as $value) {
1703 unset($fields[$value]);
1707 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1709 self
::$_exportableFields[$cacheKeyString] = $fields;
1713 $fields = self
::$_exportableFields[$cacheKeyString];
1716 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1717 self
::$_exportableFields[$cacheKeyString]
1725 * Get the all contact details (Hierarchical).
1727 * @param int $contactId
1729 * @param array $fields
1735 public static function getHierContactDetails($contactId, &$fields) {
1736 $params = array(array('contact_id', '=', $contactId, 0, 0));
1739 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1741 // We don't know the contents of return properties, but we need the lower
1742 // level ids of the contact so add a few fields.
1743 $returnProperties['first_name'] = 1;
1744 $returnProperties['organization_name'] = 1;
1745 $returnProperties['household_name'] = 1;
1746 $returnProperties['contact_type'] = 1;
1747 $returnProperties['contact_sub_type'] = 1;
1748 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1752 * Given a set of flat profile style field names, create a hierarchy.
1754 * This is for the query to use, create the right sql.
1757 * @param int $contactId
1761 * A hierarchical property tree if appropriate
1763 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1764 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1766 $returnProperties = array();
1768 $multipleFields = array('website' => 'url');
1769 foreach ($fields as $name => $dontCare) {
1770 if (strpos($name, '-') !== FALSE) {
1771 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1773 if (!in_array($fieldName, $multipleFields)) {
1774 if ($id == 'Primary') {
1775 $locationTypeName = 1;
1778 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1779 if (!$locationTypeName) {
1784 if (empty($returnProperties['location'])) {
1785 $returnProperties['location'] = array();
1787 if (empty($returnProperties['location'][$locationTypeName])) {
1788 $returnProperties['location'][$locationTypeName] = array();
1789 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1791 if (in_array($fieldName, array(
1799 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1802 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1805 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1806 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1809 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1813 $returnProperties['website'][$id][$fieldName] = 1;
1817 $returnProperties[$name] = 1;
1821 return $returnProperties;
1825 * Return the primary location type of a contact.
1827 * $params int $contactId contact_id
1828 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1829 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1831 * @param int $contactId
1832 * @param bool $skipDefaultPriamry
1833 * @param null $block
1836 * $locationType location_type_id
1838 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1840 $entityBlock = array('contact_id' => $contactId);
1841 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1842 foreach ($blocks[$block] as $key => $value) {
1843 if (!empty($value['is_primary'])) {
1844 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1851 IF ( civicrm_email.location_type_id IS NULL,
1852 IF ( civicrm_address.location_type_id IS NULL,
1853 IF ( civicrm_phone.location_type_id IS NULL,
1854 IF ( civicrm_im.location_type_id IS NULL,
1855 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1856 ,civicrm_im.location_type_id)
1857 ,civicrm_phone.location_type_id)
1858 ,civicrm_address.location_type_id)
1859 ,civicrm_email.location_type_id) as locationType
1860 FROM civicrm_contact
1861 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1862 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1863 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1864 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1865 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1866 WHERE civicrm_contact.id = %1 ";
1868 $params = array(1 => array($contactId, 'Integer'));
1870 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1872 $locationType = NULL;
1873 if ($dao->fetch()) {
1874 $locationType = $dao->locationType
;
1877 if (isset($locationType)) {
1878 return $locationType;
1880 elseif ($skipDefaultPriamry) {
1881 // if there is no primary contact location then return null
1885 // if there is no primart contact location, then return default
1886 // location type of the system
1887 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1888 return $defaultLocationType->id
;
1893 * Get the display name, primary email and location type of a contact.
1896 * Id of the contact.
1899 * Array of display_name, email if found, do_not_email or (null,null,null)
1901 public static function getContactDetails($id) {
1902 // check if the contact type
1903 $contactType = self
::getContactType($id);
1905 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1908 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1909 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1910 WHERE civicrm_contact.id = %1
1911 ORDER BY civicrm_email.is_primary DESC";
1912 $params = array(1 => array($id, 'Integer'));
1913 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1915 if ($dao->fetch()) {
1916 if ($contactType == 'Individual') {
1917 if ($dao->first_name ||
$dao->last_name
) {
1918 $name = "{$dao->first_name} {$dao->last_name}";
1921 $name = $dao->display_name
;
1925 $name = $dao->display_name
;
1927 $email = $dao->email
;
1928 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1929 $onHold = $dao->on_hold ?
TRUE : FALSE;
1930 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1931 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1933 return array(NULL, NULL, NULL, NULL, NULL);
1937 * Add/edit/register contacts through profile.
1939 * @param array $params
1940 * Array of profile fields to be edited/added.
1941 * @param array $fields
1942 * Array of fields from UFGroup.
1943 * @param int $contactID
1944 * Id of the contact to be edited/added.
1945 * @param int $addToGroupID
1946 * Specifies the default group to which contact is added.
1947 * @param int $ufGroupId
1948 * Uf group id (profile id).
1949 * @param string $ctype
1950 * @param bool $visibility
1951 * Basically lets us know where this request is coming from.
1952 * if via a profile from web, we restrict what groups are changed
1955 * contact id created/edited
1957 public static function createProfileContact(
1961 $addToGroupID = NULL,
1966 // add ufGroupID to params array ( CRM-2012 )
1968 $params['uf_group_id'] = $ufGroupId;
1970 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1972 // If a user has logged in, or accessed via a checksum
1973 // Then deliberately 'blanking' a value in the profile should remove it from their record
1974 $session = CRM_Core_Session
::singleton();
1975 $params['updateBlankLocInfo'] = TRUE;
1976 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1977 $params['updateBlankLocInfo'] = FALSE;
1982 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1986 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1989 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1991 // manage is_opt_out
1992 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1993 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1994 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1995 $data['is_opt_out'] = $isOptOut;
1996 // on change, create new civicrm_subscription_history entry
1997 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1999 'contact_id' => $contactDetails['contact_id'],
2000 'status' => $isOptOut ?
'Removed' : 'Added',
2003 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2007 $contact = self
::create($data);
2009 // contact is null if the profile does not have any contact fields
2011 $contactID = $contact->id
;
2014 if (empty($contactID)) {
2015 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
2018 // Process group and tag
2019 if (!empty($fields['group'])) {
2021 // this for sure means we are coming in via profile since i added it to fix
2022 // removing contacts from user groups -- lobo
2026 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2029 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2030 // Convert comma separated form values from select2 v3
2031 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2032 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2035 //to add profile in default group
2036 if (is_array($addToGroupID)) {
2037 $contactIds = array($contactID);
2038 foreach ($addToGroupID as $groupId) {
2039 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2042 elseif ($addToGroupID) {
2043 $contactIds = array($contactID);
2044 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2047 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
2050 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2053 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2059 * Format profile contact parameters.
2061 * @param array $params
2063 * @param int $contactID
2064 * @param int $ufGroupId
2065 * @param null $ctype
2066 * @param bool $skipCustom
2070 public static function formatProfileContactParams(
2079 $data = $contactDetails = array();
2081 // get the contact details (hier)
2083 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
2085 $contactDetails = $details[$contactID];
2086 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
2087 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
2090 //we should get contact type only if contact
2092 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2094 //special case to handle profile with only contact fields
2095 if ($data['contact_type'] == 'Contact') {
2096 $data['contact_type'] = 'Individual';
2098 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2099 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2103 $data['contact_type'] = $ctype;
2106 $data['contact_type'] = 'Individual';
2110 //fix contact sub type CRM-5125
2111 if (array_key_exists('contact_sub_type', $params) &&
2112 !empty($params['contact_sub_type'])
2114 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2116 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2117 !empty($params['contact_sub_type_hidden'])
2119 // if profile was used, and had any subtype, we obtain it from there
2120 //CRM-13596 - add to existing contact types, rather than overwriting
2121 if (empty($data['contact_sub_type'])) {
2122 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2123 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2126 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2127 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2128 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2129 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2130 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2135 if ($ctype == 'Organization') {
2136 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2138 elseif ($ctype == 'Household') {
2139 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2142 $locationType = array();
2147 $data['contact_id'] = $contactID;
2148 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2151 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2152 $defaultLocationId = $defaultLocation->id
;
2155 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2157 $blocks = array('email', 'phone', 'im', 'openid');
2159 $multiplFields = array('url');
2160 // prevent overwritten of formatted array, reset all block from
2161 // params if it is not in valid format (since import pass valid format)
2162 foreach ($blocks as $blk) {
2163 if (array_key_exists($blk, $params) &&
2164 !is_array($params[$blk])
2166 unset($params[$blk]);
2170 $primaryPhoneLoc = NULL;
2171 $session = CRM_Core_Session
::singleton();
2172 foreach ($params as $key => $value) {
2173 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2175 if ($locTypeId == 'Primary') {
2177 if (in_array($fieldName, $blocks)) {
2178 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2181 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2183 $primaryLocationType = $locTypeId;
2186 $locTypeId = $defaultLocationId;
2190 if (is_numeric($locTypeId) &&
2191 !in_array($fieldName, $multiplFields) &&
2192 substr($fieldName, 0, 7) != 'custom_'
2194 $index = $locTypeId;
2196 if (is_numeric($typeId)) {
2197 $index .= '-' . $typeId;
2199 if (!in_array($index, $locationType)) {
2200 $locationType[$count] = $index;
2204 $loc = CRM_Utils_Array
::key($index, $locationType);
2206 $blockName = self
::getLocationEntityForKey($fieldName);
2208 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2210 //set is_billing true, for location type "Billing"
2211 if ($locTypeId == $billingLocationTypeId) {
2212 $data[$blockName][$loc]['is_billing'] = 1;
2216 //get the primary location type
2217 if ($locTypeId == $primaryLocationType) {
2218 $data[$blockName][$loc]['is_primary'] = 1;
2221 elseif ($locTypeId == $defaultLocationId) {
2222 $data[$blockName][$loc]['is_primary'] = 1;
2225 if (in_array($fieldName, array('phone'))) {
2227 $data['phone'][$loc]['phone_type_id'] = $typeId;
2230 $data['phone'][$loc]['phone_type_id'] = '';
2232 $data['phone'][$loc]['phone'] = $value;
2234 //special case to handle primary phone with different phone types
2235 // in this case we make first phone type as primary
2236 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2237 $primaryPhoneLoc = $loc;
2240 if ($loc != $primaryPhoneLoc) {
2241 unset($data['phone'][$loc]['is_primary']);
2244 elseif ($fieldName == 'email') {
2245 $data['email'][$loc]['email'] = $value;
2246 if (empty($contactID)) {
2247 $data['email'][$loc]['is_primary'] = 1;
2250 elseif ($fieldName == 'im') {
2251 if (isset($params[$key . '-provider_id'])) {
2252 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2254 if (strpos($key, '-provider_id') !== FALSE) {
2255 $data['im'][$loc]['provider_id'] = $params[$key];
2258 $data['im'][$loc]['name'] = $value;
2261 elseif ($fieldName == 'openid') {
2262 $data['openid'][$loc]['openid'] = $value;
2265 if ($fieldName === 'state_province') {
2267 if (is_numeric($value) && ((int ) $value) >= 1000) {
2268 $data['address'][$loc]['state_province_id'] = $value;
2270 elseif (empty($value)) {
2271 $data['address'][$loc]['state_province_id'] = '';
2274 $data['address'][$loc]['state_province'] = $value;
2277 elseif ($fieldName === 'country') {
2279 if (is_numeric($value) && ((int ) $value) >= 1000
2281 $data['address'][$loc]['country_id'] = $value;
2283 elseif (empty($value)) {
2284 $data['address'][$loc]['country_id'] = '';
2287 $data['address'][$loc]['country'] = $value;
2290 elseif ($fieldName === 'county') {
2291 $data['address'][$loc]['county_id'] = $value;
2293 elseif ($fieldName == 'address_name') {
2294 $data['address'][$loc]['name'] = $value;
2296 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2297 $data['address'][$loc][substr($fieldName, 8)] = $value;
2300 $data[$blockName][$loc][$fieldName] = $value;
2305 if (substr($key, 0, 4) === 'url-') {
2306 $websiteField = explode('-', $key);
2307 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2308 $data['website'][$websiteField[1]]['url'] = $value;
2310 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2311 //save email/postal greeting and addressee values if any, CRM-4575
2312 $data[$key . '_id'] = $value;
2314 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2315 // for autocomplete transfer hidden value instead of label
2316 if ($params[$key] && isset($params[$key . '_id'])) {
2317 $value = $params[$key . '_id'];
2320 // we need to append time with date
2321 if ($params[$key] && isset($params[$key . '_time'])) {
2322 $value .= ' ' . $params[$key . '_time'];
2325 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2326 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2327 ($value == '' ||
!isset($value))
2333 if (!empty($params['customRecordValues'])) {
2334 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2335 foreach ($params['customRecordValues'] as $recId => $customFields) {
2336 if (is_array($customFields) && !empty($customFields)) {
2337 foreach ($customFields as $customFieldName) {
2338 if ($customFieldName == $key) {
2348 //CRM-13596 - check for contact_sub_type_hidden first
2349 if (array_key_exists('contact_sub_type_hidden', $params)) {
2350 $type = $params['contact_sub_type_hidden'];
2353 $type = $data['contact_type'];
2354 if (!empty($data['contact_sub_type'])) {
2355 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2359 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2369 elseif ($key == 'edit') {
2373 if ($key == 'location') {
2374 foreach ($value as $locationTypeId => $field) {
2375 foreach ($field as $block => $val) {
2376 if ($block == 'address' && array_key_exists('address_name', $val)) {
2377 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2382 if ($key == 'phone' && isset($params['phone_ext'])) {
2383 $data[$key] = $value;
2384 foreach ($value as $cnt => $phoneBlock) {
2385 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2386 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2390 elseif (in_array($key, array(
2399 )) && ($value == '' ||
!isset($value)) &&
2400 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2401 ($key == 'current_employer' && empty($params['current_employer']))) {
2402 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2403 // to avoid update with empty values
2407 $data[$key] = $value;
2413 if (!isset($data['contact_type'])) {
2414 $data['contact_type'] = 'Individual';
2417 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2418 $privacy = CRM_Core_SelectValues
::privacy();
2419 foreach ($privacy as $key => $value) {
2420 if (array_key_exists($key, $fields)) {
2421 // do not reset values for existing contacts, if fields are added to a profile
2422 if (array_key_exists($key, $params)) {
2423 $data[$key] = $params[$key];
2424 if (empty($params[$key])) {
2428 elseif (!$contactID) {
2434 return array($data, $contactDetails);
2438 * Find the get contact details.
2440 * This function does not respect ACLs for now, which might need to be rectified at some
2441 * stage based on how its used.
2443 * @param string $mail
2444 * Primary email address of the contact.
2445 * @param string $ctype
2448 * @return object|null
2449 * $dao contact details
2451 public static function matchContactOnEmail($mail, $ctype = NULL) {
2452 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2453 $mail = $strtolower(trim($mail));
2455 SELECT civicrm_contact.id as contact_id,
2456 civicrm_contact.hash as hash,
2457 civicrm_contact.contact_type as contact_type,
2458 civicrm_contact.contact_sub_type as contact_sub_type
2459 FROM civicrm_contact
2460 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2462 if (Civi
::settings()->get('uniq_email_per_site')) {
2463 // try to find a match within a site (multisite).
2464 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2465 if (!empty($groups)) {
2467 INNER JOIN civicrm_group_contact gc ON
2468 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2473 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2474 $p = array(1 => array($mail, 'String'));
2477 $query .= " AND civicrm_contact.contact_type = %3";
2478 $p[3] = array($ctype, 'String');
2481 $query .= " ORDER BY civicrm_email.is_primary DESC";
2483 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2485 if ($dao->fetch()) {
2492 * Find the contact details associated with an OpenID.
2494 * @param string $openId
2495 * OpenId of the contact.
2496 * @param string $ctype
2499 * @return object|null
2500 * $dao contact details
2502 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2503 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2504 $openId = $strtolower(trim($openId));
2506 SELECT civicrm_contact.id as contact_id,
2507 civicrm_contact.hash as hash,
2508 civicrm_contact.contact_type as contact_type,
2509 civicrm_contact.contact_sub_type as contact_sub_type
2510 FROM civicrm_contact
2511 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2512 WHERE civicrm_openid.openid = %1";
2513 $p = array(1 => array($openId, 'String'));
2516 $query .= " AND civicrm_contact.contact_type = %3";
2517 $p[3] = array($ctype, 'String');
2520 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2522 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2524 if ($dao->fetch()) {
2531 * Get primary email of the contact.
2533 * @param int $contactID
2537 * Email address if present else null
2539 public static function getPrimaryEmail($contactID) {
2540 // fetch the primary email
2542 SELECT civicrm_email.email as email
2543 FROM civicrm_contact
2544 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2545 WHERE civicrm_email.is_primary = 1
2546 AND civicrm_contact.id = %1";
2547 $p = array(1 => array($contactID, 'Integer'));
2548 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2551 if ($dao->fetch()) {
2552 $email = $dao->email
;
2558 * Function to get primary OpenID of the contact.
2560 * @param int $contactID
2564 * >openid OpenID if present else null
2566 public static function getPrimaryOpenId($contactID) {
2567 // fetch the primary OpenID
2569 SELECT civicrm_openid.openid as openid
2570 FROM civicrm_contact
2571 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2572 WHERE civicrm_contact.id = %1
2573 AND civicrm_openid.is_primary = 1";
2574 $p = array(1 => array($contactID, 'Integer'));
2575 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2578 if ($dao->fetch()) {
2579 $openId = $dao->openid
;
2585 * Fetch the object and store the values in the values array.
2587 * @param array $params
2588 * Input parameters to find object.
2589 * @param array $values
2590 * Output values of the object.
2592 * @return CRM_Contact_BAO_Contact|null
2593 * The found object or null
2595 public static function getValues(&$params, &$values) {
2596 $contact = new CRM_Contact_BAO_Contact();
2598 $contact->copyValues($params);
2600 if ($contact->find(TRUE)) {
2602 CRM_Core_DAO
::storeValues($contact, $values);
2605 foreach (self
::$_commPrefs as $name) {
2606 if (isset($contact->$name)) {
2607 $privacy[$name] = $contact->$name;
2611 if (!empty($privacy)) {
2612 $values['privacy'] = $privacy;
2615 // communication Prefferance
2616 $preffComm = $comm = array();
2617 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2618 $contact->preferred_communication_method
2620 foreach ($comm as $value) {
2621 $preffComm[$value] = 1;
2623 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2626 'preferred_communication_method' => array(
2627 'newName' => 'preferred_communication_method_display',
2628 'groupName' => 'preferred_communication_method',
2632 // @todo This can be figured out from metadata & we can avoid the uncached query.
2633 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2635 $values['preferred_communication_method'] = $preffComm;
2636 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2638 if ($contact->preferred_mail_format
) {
2639 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2640 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2643 // get preferred languages
2644 if (!empty($contact->preferred_language
)) {
2645 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2648 // Calculating Year difference
2649 if ($contact->birth_date
) {
2650 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2651 if ($birthDate < date('Ymd')) {
2652 $age = CRM_Utils_Date
::calculateAge($birthDate);
2653 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2654 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2658 $contact->contact_id
= $contact->id
;
2666 * Given the component name and returns the count of participation of contact.
2668 * @param string $component
2669 * Input component name.
2670 * @param int $contactId
2672 * @param string $tableName
2673 * Optional tableName if component is custom group.
2676 * total number in database
2678 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2680 switch ($component) {
2682 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2685 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2686 CRM_Contact_BAO_Relationship
::CURRENT
,
2695 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2698 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2701 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2704 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2706 case 'contribution':
2707 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2710 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2713 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2716 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2719 return CRM_Case_BAO_Case
::caseCount($contactId);
2722 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2726 'contact_id' => $contactId,
2729 'context' => 'activity',
2731 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2734 $params = array('contact_id' => $contactId);
2735 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2738 $custom = explode('_', $component);
2739 if ($custom['0'] = 'custom') {
2741 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2743 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2744 return CRM_Core_DAO
::singleValueQuery($queryString);
2750 * Update contact greetings if an update has resulted in a custom field change.
2752 * @param array $updatedFields
2753 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2754 * @param array $contactParams
2755 * Parameters known about the contact. At minimum array('contact_id' => x).
2756 * Fields in this array will take precedence over DB fields (so far only
2757 * in the case of greeting id fields).
2759 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2760 $contactID = $contactParams['contact_id'];
2761 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2762 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2763 if (!empty($tokens['all']['contact'])) {
2764 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2765 if (!empty($affectedTokens)) {
2766 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2767 $contact = new CRM_Contact_BAO_Contact();
2768 $contact->id
= $contactID;
2769 CRM_Contact_BAO_Contact
::processGreetings($contact);
2775 * Process greetings and cache.
2777 * @param object $contact
2778 * Contact object after save.
2780 public static function processGreetings(&$contact) {
2782 //@todo this function does a lot of unnecessary loading.
2783 // ensureGreetingParamsAreSet now makes sure that the contact is
2784 // loaded and using updateGreetingsOnTokenFieldChange
2785 // allows us the possibility of only doing an update if required.
2787 // The contact object has not always required the
2788 // fields that are required to calculate greetings
2789 // so we need to retrieve it again.
2790 if ($contact->_query
!== FALSE) {
2791 $contact->find(TRUE);
2794 // store object values to an array
2795 $contactDetails = array();
2796 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2797 $contactDetails = array(array($contact->id
=> $contactDetails));
2799 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2800 $updateQueryString = array();
2802 //cache email and postal greeting to greeting display
2803 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2804 $emailGreetingString = $contact->email_greeting_custom
;
2806 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2807 // the filter value for Individual contact type is set to 1
2809 'contact_type' => $contact->contact_type
,
2810 'greeting_type' => 'email_greeting',
2813 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2814 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2815 $updateQueryString[] = " email_greeting_custom = NULL ";
2818 if ($contact->email_greeting_custom
) {
2819 $updateQueryString[] = " email_greeting_display = NULL ";
2823 if ($emailGreetingString) {
2824 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2827 'CRM_Contact_BAO_Contact'
2829 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2830 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2834 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2835 $postalGreetingString = $contact->postal_greeting_custom
;
2837 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2839 'contact_type' => $contact->contact_type
,
2840 'greeting_type' => 'postal_greeting',
2842 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2843 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2844 $updateQueryString[] = " postal_greeting_custom = NULL ";
2847 if ($contact->postal_greeting_custom
) {
2848 $updateQueryString[] = " postal_greeting_display = NULL ";
2852 if ($postalGreetingString) {
2853 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2856 'CRM_Contact_BAO_Contact'
2858 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2859 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2863 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2864 $addresseeString = $contact->addressee_custom
;
2866 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2868 'contact_type' => $contact->contact_type
,
2869 'greeting_type' => 'addressee',
2872 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2873 $addresseeString = $addressee[$contact->addressee_id
];
2874 $updateQueryString[] = " addressee_custom = NULL ";
2877 if ($contact->addressee_custom
) {
2878 $updateQueryString[] = " addressee_display = NULL ";
2882 if ($addresseeString) {
2883 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2886 'CRM_Contact_BAO_Contact'
2888 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2889 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2892 if (!empty($updateQueryString)) {
2893 $updateQueryString = implode(',', $updateQueryString);
2894 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2895 CRM_Core_DAO
::executeQuery($queryString);
2900 * Retrieve loc block ids w/ given condition.
2902 * @param int $contactId
2904 * @param array $criteria
2905 * Key => value pair which should be.
2906 * fulfill by return record ids.
2907 * @param string $condOperator
2908 * Operator use for grouping multiple conditions.
2911 * loc block ids which fulfill condition.
2913 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2914 $locBlockIds = array();
2916 return $locBlockIds;
2919 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2920 $name = strtolower($block);
2921 $className = "CRM_Core_DAO_$block";
2922 $blockDAO = new $className();
2924 // build the condition.
2925 if (is_array($criteria)) {
2926 $fields = $blockDAO->fields();
2927 $conditions = array();
2928 foreach ($criteria as $field => $value) {
2929 if (array_key_exists($field, $fields)) {
2930 $cond = "( $field = $value )";
2931 // value might be zero or null.
2932 if (!$value ||
strtolower($value) == 'null') {
2933 $cond = "( $field = 0 OR $field IS NULL )";
2935 $conditions[] = $cond;
2938 if (!empty($conditions)) {
2939 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2943 $blockDAO->contact_id
= $contactId;
2945 while ($blockDAO->fetch()) {
2946 $locBlockIds[$name][] = $blockDAO->id
;
2951 return $locBlockIds;
2955 * Build context menu items.
2957 * @param int $contactId
2960 * Array of context menu for logged in user.
2962 public static function contextMenu($contactId = NULL) {
2965 'title' => ts('View Contact'),
2967 'ref' => 'view-contact',
2968 'class' => 'no-popup',
2970 'permissions' => array('view all contacts'),
2973 'title' => ts('Edit Contact'),
2975 'ref' => 'edit-contact',
2976 'class' => 'no-popup',
2978 'permissions' => array('edit all contacts'),
2981 'title' => ts('Delete Contact'),
2983 'ref' => 'delete-contact',
2985 'permissions' => array('access deleted contacts', 'delete contacts'),
2987 'contribution' => array(
2988 'title' => ts('Add Contribution'),
2990 'ref' => 'new-contribution',
2991 'key' => 'contribution',
2992 'tab' => 'contribute',
2993 'component' => 'CiviContribute',
2994 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2995 'reset=1&action=add&context=contribution'
2997 'permissions' => array(
2998 'access CiviContribute',
2999 'edit contributions',
3002 'participant' => array(
3003 'title' => ts('Register for Event'),
3005 'ref' => 'new-participant',
3006 'key' => 'participant',
3007 'tab' => 'participant',
3008 'component' => 'CiviEvent',
3009 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3010 'permissions' => array(
3012 'edit event participants',
3015 'activity' => array(
3016 'title' => ts('Record Activity'),
3018 'ref' => 'new-activity',
3019 'key' => 'activity',
3020 'permissions' => array('edit all contacts'),
3023 'title' => ts('Add Pledge'),
3025 'ref' => 'new-pledge',
3028 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3029 'reset=1&action=add&context=pledge'
3031 'component' => 'CiviPledge',
3032 'permissions' => array(
3033 'access CiviPledge',
3037 'membership' => array(
3038 'title' => ts('Add Membership'),
3040 'ref' => 'new-membership',
3041 'key' => 'membership',
3043 'component' => 'CiviMember',
3044 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3045 'reset=1&action=add&context=membership'
3047 'permissions' => array(
3048 'access CiviMember',
3053 'title' => ts('Add Case'),
3055 'ref' => 'new-case',
3058 'component' => 'CiviCase',
3059 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3060 'permissions' => array('add cases'),
3063 'title' => ts('Add Grant'),
3065 'ref' => 'new-grant',
3068 'component' => 'CiviGrant',
3069 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3070 'reset=1&action=add&context=grant'
3072 'permissions' => array('edit grants'),
3075 'title' => ts('Add Relationship'),
3077 'ref' => 'new-relationship',
3080 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3081 'reset=1&action=add'
3083 'permissions' => array('edit all contacts'),
3086 'title' => ts('Add Note'),
3088 'ref' => 'new-note',
3091 'class' => 'medium-popup',
3092 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3093 'reset=1&action=add'
3095 'permissions' => array('edit all contacts'),
3098 'title' => ts('Send an Email'),
3100 'ref' => 'new-email',
3102 'permissions' => array('view all contacts'),
3105 'title' => ts('Add to Group'),
3107 'ref' => 'group-add-contact',
3110 'permissions' => array('edit groups'),
3113 'title' => ts('Tag Contact'),
3115 'ref' => 'tag-contact',
3118 'permissions' => array('edit all contacts'),
3122 $menu['otherActions'] = array(
3124 'title' => ts('Print Summary'),
3125 'description' => ts('Printer-friendly view of this page.'),
3127 'ref' => 'crm-contact-print',
3130 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3134 'icon' => 'crm-i fa-print',
3137 'title' => ts('vCard'),
3138 'description' => ts('vCard record for this contact.'),
3140 'ref' => 'crm-contact-vcard',
3143 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3147 'icon' => 'crm-i fa-list-alt',
3151 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3152 $menu['otherActions']['dashboard'] = array(
3153 'title' => ts('Contact Dashboard'),
3154 'description' => ts('Contact Dashboard'),
3156 'ref' => 'crm-contact-dashboard',
3157 'key' => 'dashboard',
3158 'tab' => 'dashboard',
3159 'class' => 'dashboard',
3160 // NOTE: As an alternative you can also build url on CMS specific way
3161 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3162 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3163 'icon' => 'crm-i fa-tachometer',
3167 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3169 $menu['otherActions']['user-record'] = array(
3170 'title' => ts('User Record'),
3171 'description' => ts('User Record'),
3173 'ref' => 'crm-contact-user-record',
3174 'key' => 'user-record',
3175 'tab' => 'user-record',
3176 'class' => 'user-record',
3177 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3178 'icon' => 'crm-i fa-user',
3181 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3182 $menu['otherActions']['user-add'] = array(
3183 'title' => ts('Create User Record'),
3184 'description' => ts('Create User Record'),
3186 'ref' => 'crm-contact-user-add',
3187 'key' => 'user-add',
3188 'tab' => 'user-add',
3189 'class' => 'user-add',
3190 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3191 'icon' => 'crm-i fa-user-plus',
3195 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3196 //1. check for component is active.
3197 //2. check for user permissions.
3198 //3. check for acls.
3199 //3. edit and view contact are directly accessible to user.
3201 $aclPermissionedTasks = array(
3206 'group-add-contact',
3210 $corePermission = CRM_Core_Permission
::getPermission();
3212 $contextMenu = array();
3213 foreach ($menu as $key => $values) {
3214 if ($key != 'otherActions') {
3216 // user does not have necessary permissions.
3217 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3220 // build directly accessible action menu.
3221 if (in_array($values['ref'], array(
3225 $contextMenu['primaryActions'][$key] = array(
3226 'title' => $values['title'],
3227 'ref' => $values['ref'],
3228 'class' => CRM_Utils_Array
::value('class', $values),
3229 'key' => $values['key'],
3234 // finally get menu item for -more- action widget.
3235 $contextMenu['moreActions'][$values['weight']] = array(
3236 'title' => $values['title'],
3237 'ref' => $values['ref'],
3238 'href' => CRM_Utils_Array
::value('href', $values),
3239 'tab' => CRM_Utils_Array
::value('tab', $values),
3240 'class' => CRM_Utils_Array
::value('class', $values),
3241 'key' => $values['key'],
3245 foreach ($values as $value) {
3246 // user does not have necessary permissions.
3247 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3251 // finally get menu item for -more- action widget.
3252 $contextMenu['otherActions'][$value['weight']] = array(
3253 'title' => $value['title'],
3254 'ref' => $value['ref'],
3255 'href' => CRM_Utils_Array
::value('href', $value),
3256 'tab' => CRM_Utils_Array
::value('tab', $value),
3257 'class' => CRM_Utils_Array
::value('class', $value),
3258 'icon' => CRM_Utils_Array
::value('icon', $value),
3259 'key' => $value['key'],
3265 ksort($contextMenu['moreActions']);
3266 ksort($contextMenu['otherActions']);
3268 return $contextMenu;
3272 * Check if user has permissions to access items in action menu.
3274 * @param array $aclPermissionedTasks
3275 * Array containing ACL related tasks.
3276 * @param string $corePermission
3277 * The permission of the user (edit or view or null).
3278 * @param array $menuOptions
3279 * Array containing params of the menu (title, href, etc).
3282 * TRUE if user has all permissions, FALSE if otherwise.
3284 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3285 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3287 // if component action - make sure component is enable.
3288 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3292 // make sure user has all required permissions.
3293 $hasAllPermissions = FALSE;
3295 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3296 if (!is_array($permissions) ||
empty($permissions)) {
3297 $hasAllPermissions = TRUE;
3300 // iterate for required permissions in given permissions array.
3301 if (!$hasAllPermissions) {
3302 $hasPermissions = 0;
3303 foreach ($permissions as $permission) {
3304 if (CRM_Core_Permission
::check($permission)) {
3309 if (count($permissions) == $hasPermissions) {
3310 $hasAllPermissions = TRUE;
3313 // if still user does not have required permissions, check acl.
3314 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3315 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3316 $corePermission == CRM_Core_Permission
::EDIT
3318 $hasAllPermissions = TRUE;
3320 elseif (in_array($menuOptions['ref'], array(
3323 // grant permissions for these tasks.
3324 $hasAllPermissions = TRUE;
3329 return $hasAllPermissions;
3333 * Retrieve display name of contact that address is shared.
3335 * This is based on $masterAddressId or $contactId .
3337 * @param int $masterAddressId
3339 * @param int $contactId
3340 * Contact id. (deprecated - do not use)
3342 * @return string|null
3343 * the found display name or null.
3345 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3346 $masterDisplayName = NULL;
3347 if (!$masterAddressId) {
3348 return $masterDisplayName;
3352 SELECT display_name from civicrm_contact
3353 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3354 WHERE civicrm_address.id = " . $masterAddressId;
3356 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3357 return $masterDisplayName;
3361 * Get the creation/modification times for a contact.
3363 * @param int $contactId
3366 * Dates - ('created_date' => $, 'modified_date' => $)
3368 public static function getTimestamps($contactId) {
3369 $timestamps = CRM_Core_DAO
::executeQuery(
3370 'SELECT created_date, modified_date
3371 FROM civicrm_contact
3374 1 => array($contactId, 'Integer'),
3377 if ($timestamps->fetch()) {
3379 'created_date' => $timestamps->created_date
,
3380 'modified_date' => $timestamps->modified_date
,
3389 * Get a list of triggers for the contact table.
3391 * @see hook_civicrm_triggerInfo
3392 * @see CRM_Core_DAO::triggerRebuild
3393 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3396 * @param null $tableName
3398 public static function triggerInfo(&$info, $tableName = NULL) {
3399 //during upgrade, first check for valid version and then create triggers
3400 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3401 if (CRM_Core_Config
::isUpgradeMode()) {
3402 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3403 //if current version is less than 4.3.alpha1 dont create below triggers
3404 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3409 // Modifications to these records should update the contact timestamps.
3410 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3411 ->setRelations(array(
3412 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3413 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3414 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3415 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3416 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3418 ->alterTriggerInfo($info, $tableName);
3420 // Update phone table to populate phone_numeric field
3421 if (!$tableName ||
$tableName == 'civicrm_phone') {
3422 // Define stored sql function needed for phones
3423 $sqlTriggers = Civi
::service('sql_triggers');
3424 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3425 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3427 'table' => array('civicrm_phone'),
3429 'event' => array('INSERT', 'UPDATE'),
3430 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3436 * Check if contact is being used in civicrm_domain based on $contactId.
3438 * @param int $contactId
3442 * true if present else false.
3444 public static function checkDomainContact($contactId) {
3448 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3459 * Get options for a given contact field.
3461 * @see CRM_Core_DAO::buildOptions
3463 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3464 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3466 * @param string $fieldName
3467 * @param string $context
3468 * @see CRM_Core_DAO::buildOptionsContext
3469 * @param array $props
3470 * whatever is known about this dao object.
3472 * @return array|bool
3474 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3476 // Special logic for fields whose options depend on context or properties
3477 switch ($fieldName) {
3478 case 'contact_sub_type':
3479 if (!empty($props['contact_type'])) {
3480 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3484 case 'contact_type':
3485 if ($context == 'search') {
3486 // CRM-15495 - EntityRef filters and basic search forms expect this format
3487 // FIXME: Search builder does not
3488 return CRM_Contact_BAO_ContactType
::getSelectElements();
3492 // The contact api supports some related entities so we'll honor that by fetching their options
3495 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3499 $props['entity_table'] = 'civicrm_contact';
3500 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3502 case 'state_province_id':
3503 case 'state_province':
3504 case 'state_province_name':
3509 case 'worldregion_id':
3510 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3513 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3517 * Delete a contact-related object that has an 'is_primary' field.
3519 * Ensures that is_primary gets assigned to another object if available
3520 * Also calls pre/post hooks
3522 * @param string $type
3526 public static function deleteObjectWithPrimary($type, $id) {
3527 if (!$id ||
!is_numeric($id)) {
3530 $daoName = "CRM_Core_DAO_$type";
3531 $obj = new $daoName();
3535 if ($obj->fetch()) {
3536 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3537 $contactId = $obj->contact_id
;
3543 // is_primary is only relavent if this field belongs to a contact
3545 $dao = new $daoName();
3546 $dao->contact_id
= $contactId;
3547 $dao->is_primary
= 1;
3548 // Pick another record to be primary (if one isn't already)
3549 if (!$dao->find(TRUE)) {
3550 $dao->is_primary
= 0;
3552 if ($dao->fetch()) {
3553 $dao->is_primary
= 1;
3558 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3566 public function addSelectWhereClause() {
3567 // We always return an array with these keys, even if they are empty,
3568 // because this tells the query builder that we have considered these fields for acls
3570 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3571 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
array() : array('!= 1'),
3573 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3578 * Get any existing duplicate contacts based on the input parameters.
3580 * @param array $input
3581 * Input parameters to be matched.
3582 * @param string $contactType
3583 * @param string $rule
3586 * @param $excludedContactIDs
3587 * An array of ids not to be included in the results.
3588 * @param bool $checkPermissions
3589 * @param int $ruleGroupID
3590 * ID of the rule group to be used if an override is desirable.
3591 * @param array $contextParams
3592 * The context if relevant, eg. ['event_id' => X]
3596 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3597 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3598 $dedupeParams['check_permission'] = $checkPermissions;
3599 $dedupeParams['contact_type'] = $contactType;
3600 $dedupeParams['rule'] = $rule;
3601 $dedupeParams['rule_group_id'] = $ruleGroupID;
3602 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3603 $dedupeResults['ids'] = [];
3604 $dedupeResults['handled'] = FALSE;
3605 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3606 if (!$dedupeResults['handled']) {
3607 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3609 return $dedupeResults['ids'];
3613 * Get the first duplicate contacts based on the input parameters.
3615 * @param array $input
3616 * Input parameters to be matched.
3617 * @param string $contactType
3618 * @param string $rule
3621 * @param $excludedContactIDs
3622 * An array of ids not to be included in the results.
3623 * @param bool $checkPermissions
3624 * @param int $ruleGroupID
3625 * ID of the rule group to be used if an override is desirable.
3626 * @param array $contextParams
3627 * The context if relevant, eg. ['event_id' => X]
3631 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3632 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3640 * Check if a field is associated with an entity that has a location type.
3642 * (ie. is an address, phone, email etc field).
3644 * @param string $fieldTitle
3645 * Title of the field (not the name - create a new function for that if required).
3649 public static function isFieldHasLocationType($fieldTitle) {
3650 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3651 if ($field['title'] === $fieldTitle) {
3652 return CRM_Utils_Array
::value('hasLocationType', $field);
3659 * @param array $appendProfiles
3660 * Name of profile(s) to append to each link.
3664 public static function getEntityRefCreateLinks($appendProfiles = []) {
3665 // You'd think that "create contacts" would be the permission to check,
3666 // But new contact popups are profile forms and those use their own permissions.
3667 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3671 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3672 $profiles[] = 'new_' . strtolower($contactType);
3674 $retrieved = civicrm_api3('uf_group', 'get', [
3675 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3678 $links = $append = [];
3679 if (!empty($retrieved['values'])) {
3681 'individual' => 'fa-user',
3682 'organization' => 'fa-building',
3683 'household' => 'fa-home',
3685 foreach ($retrieved['values'] as $id => $profile) {
3686 if (in_array($profile['name'], $profiles)) {
3688 'label' => $profile['title'],
3689 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3690 NULL, NULL, FALSE, FALSE, TRUE),
3691 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3692 'icon' => CRM_Utils_Array
::value(str_replace('new_', '', $profile['name']), $icons),
3699 foreach ($append as $id) {
3700 foreach ($links as &$link) {
3701 $link['url'] .= ",$id";
3711 public static function getEntityRefFilters() {
3713 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3714 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3715 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3716 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3717 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3718 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3719 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3720 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3721 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3722 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],