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 static $_commPrefs = array(
78 static $_greetingTypes = array(
85 * Static field for all the contact information that we can potentially import.
89 static $_importableFields = array();
92 * Static field for all the contact information that we can potentially export.
96 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))
468 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
469 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
470 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
473 // Filter out other fields.
474 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
475 $params = array_merge($params, $savedGreetings);
478 foreach ($missingGreetingParams as $greetingName => $greeting) {
479 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
483 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
484 if ($params[$greetingParam] === 'null') {
485 // If we are setting it to null then null out the display field.
486 $params[$greetingIndex . '_display'] = 'null';
492 * Get the display name and image of a contact.
497 * @param bool $includeTypeInReturnParameters
498 * Should type be part of the returned array?
501 * the displayName and contactImage for this contact
503 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
504 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
506 SELECT civicrm_contact.*,
507 civicrm_email.email as email
509 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
510 AND civicrm_email.is_primary = 1
511 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
512 $dao = new CRM_Core_DAO();
515 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
516 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
518 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
519 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
522 // use email if display_name is empty
523 if (empty($dao->display_name
)) {
524 $displayName = $dao->email
;
527 $displayName = $dao->display_name
;
530 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
532 return $includeTypeInReturnParameters ?
array(
536 $dao->contact_sub_type
,
538 ) : array($displayName, $image, $imageUrl);
544 * Add billing fields to the params if appropriate.
546 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
547 * don't then we should set the name fields to the filling fields AND add the preserveDBName
548 * parameter (which will tell the BAO only to set those fields if none already exist.
550 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
551 * matching is best done by hipsters.
553 * @param array $params
555 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
556 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
557 foreach ($nameFields as $field) {
558 if (!empty($params[$field])) {
562 // There are only 3 - we can iterate through them twice :-)
563 foreach ($nameFields as $field) {
564 if (!empty($params['billing_' . $field])) {
565 $params[$field] = $params['billing_' . $field];
567 $params['preserveDBName'] = TRUE;
573 * Resolve a state province string (UT or Utah) to an ID.
575 * If country has been passed in we should select a state belonging to that country.
577 * Alternatively we should choose from enabled countries, prioritising the default country.
579 * @param array $values
580 * @param int|NULL $countryID
584 protected static function resolveStateProvinceID($values, $countryID) {
587 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
588 if (CRM_Utils_Array
::lookupValue($values,
593 return $values['state_province_id'];
595 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
596 if (CRM_Utils_Array
::lookupValue($values,
601 return $values['state_province_id'];
606 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
607 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
608 // prefer matching country..
609 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, array('country_id' => Civi
::settings()->get('defaultContactCountry')));
610 if (CRM_Utils_Array
::lookupValue($values,
615 return $values['state_province_id'];
618 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
619 if (CRM_Utils_Array
::lookupValue($values,
624 return $values['state_province_id'];
627 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
628 if (CRM_Utils_Array
::lookupValue($values,
633 return $values['state_province_id'];
635 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
636 if (CRM_Utils_Array
::lookupValue($values,
641 return $values['state_province_id'];
649 * Get the relevant location entity for the array key.
651 * Based on the field name we determine which location entity
652 * we are dealing with. Apart from a few specific ones they
653 * are mostly 'address' (the default).
655 * @param string $fieldName
659 protected static function getLocationEntityForKey($fieldName) {
660 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
663 if ($fieldName === 'phone_ext') {
670 * Create last viewed link to recently updated contact.
672 * @param array $crudLinkSpec
673 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
674 * - entity_table: string, eg "civicrm_contact"
678 * NULL if unavailable, or
679 * [path: string, query: string, title: string]
680 * @see CRM_Utils_System::createDefaultCrudLink
682 public function createDefaultCrudLink($crudLinkSpec) {
683 switch ($crudLinkSpec['action']) {
684 case CRM_Core_Action
::VIEW
:
686 'title' => $this->display_name
,
687 'path' => 'civicrm/contact/view',
695 case CRM_Core_Action
::UPDATE
:
697 'title' => $this->display_name
,
698 'path' => 'civicrm/contact/add',
701 'action' => 'update',
711 * Get the values for pseudoconstants for name->value and reverse.
715 * This is called specifically from the contact import parser & should be moved there
716 * as it is not truly a generic function.
718 * @param array $defaults
719 * (reference) the default values, some of which need to be resolved.
720 * @param bool $reverse
721 * Always true as this function is only called from one place..
723 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
724 // Hack for birth_date.
725 if (!empty($defaults['birth_date'])) {
726 if (is_array($defaults['birth_date'])) {
727 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
731 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
732 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
733 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
734 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
736 //lookup value of email/postal greeting, addressee, CRM-4575
737 foreach (self
::$_greetingTypes as $greeting) {
738 $filterCondition = array(
739 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
740 'greeting_type' => $greeting,
742 CRM_Utils_Array
::lookupValue($defaults, $greeting,
743 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
747 $blocks = array('address', 'im', 'phone');
748 foreach ($blocks as $name) {
749 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
752 foreach ($defaults[$name] as $count => & $values) {
754 //get location type id.
755 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
757 if ($name == 'address') {
758 // FIXME: lookupValue doesn't work for vcard_name
759 if (!empty($values['location_type_id'])) {
760 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
761 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
764 if (!CRM_Utils_Array
::lookupValue($values,
766 CRM_Core_PseudoConstant
::country(),
771 CRM_Utils_Array
::lookupValue($values,
773 CRM_Core_PseudoConstant
::countryIsoCode(),
777 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
778 if ($stateProvinceID) {
779 $values['state_province_id'] = $stateProvinceID;
782 if (!empty($values['state_province_id'])) {
783 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
786 $countyList = CRM_Core_PseudoConstant
::county();
788 CRM_Utils_Array
::lookupValue($values,
796 CRM_Utils_Array
::lookupValue($values,
798 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
803 if ($name == 'phone') {
804 CRM_Utils_Array
::lookupValue($values,
806 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
811 // Kill the reference.
818 * Fetch object based on array of properties.
820 * @param array $params
821 * (reference ) an assoc array of name/value pairs.
822 * @param array $defaults
823 * (reference ) an assoc array to hold the name / value pairs.
824 * in a hierarchical manner
825 * @param bool $microformat
826 * For location in microformat.
828 * @return CRM_Contact_BAO_Contact
830 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
831 if (array_key_exists('contact_id', $params)) {
832 $params['id'] = $params['contact_id'];
834 elseif (array_key_exists('id', $params)) {
835 $params['contact_id'] = $params['id'];
838 $contact = self
::getValues($params, $defaults);
840 unset($params['id']);
842 //get the block information for this contact
843 $entityBlock = array('contact_id' => $params['contact_id']);
844 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
845 $defaults = array_merge($defaults, $blocks);
846 foreach ($blocks as $block => $value) {
847 $contact->$block = $value;
850 if (!isset($params['noNotes'])) {
851 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
854 if (!isset($params['noRelationships'])) {
855 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
858 if (!isset($params['noGroups'])) {
859 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
862 if (!isset($params['noWebsite'])) {
863 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
870 * Get the display name of a contact.
875 * @return null|string
876 * display name of the contact if found
878 public static function displayName($id) {
881 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
888 * Delete a contact and all its associated records.
891 * Id of the contact to delete.
892 * @param bool $restore
893 * Whether to actually restore, not delete.
894 * @param bool $skipUndelete
895 * Whether to force contact delete or not.
896 * @param bool $checkPermissions
899 * Was contact deleted?
901 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
906 // If trash is disabled in system settings then we always skip
907 if (!Civi
::settings()->get('contact_undelete')) {
908 $skipUndelete = TRUE;
911 // make sure we have edit permission for this contact
913 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
914 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
920 // Restrict contact to be delete if contact has financial trxns
922 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
926 // make sure this contact_id does not have any membership types
927 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
930 'member_of_contact_id'
932 if ($membershipTypeID) {
936 $contact = new CRM_Contact_DAO_Contact();
938 if (!$contact->find(TRUE)) {
942 $contactType = $contact->contact_type
;
943 // currently we only clear employer cache.
944 // we are now deleting inherited membership if any.
945 if ($contact->contact_type
== 'Organization') {
946 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
947 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
948 if (!empty($relationshipDtls)) {
949 foreach ($relationshipDtls as $rId => $details) {
950 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
953 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
957 return self
::contactTrashRestore($contact, TRUE);
960 // start a new transaction
961 $transaction = new CRM_Core_Transaction();
964 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
966 //delete billing address if exists.
967 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
969 // delete the log entries since we dont have triggers enabled as yet
970 $logDAO = new CRM_Core_DAO_Log();
971 $logDAO->entity_table
= 'civicrm_contact';
972 $logDAO->entity_id
= $id;
975 // delete contact participants CRM-12155
976 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
978 // delete contact contributions CRM-12155
979 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
981 // do activity cleanup, CRM-5604
982 CRM_Activity_BAO_Activity
::cleanupActivity($id);
984 // delete all notes related to contact
985 CRM_Core_BAO_Note
::cleanContactNotes($id);
987 // delete cases related to contact
988 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
989 if (!empty($contactCases)) {
990 foreach ($contactCases as $caseId) {
991 //check if case is associate with other contact or not.
992 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
993 if (count($caseContactId) <= 1) {
994 CRM_Case_BAO_Case
::deleteCase($caseId);
1002 self
::contactTrashRestore($contact);
1005 //delete the contact id from recently view
1006 CRM_Utils_Recent
::delContact($id);
1007 self
::updateContactCache($id, empty($restore));
1009 // delete any prevnext/dupe cache entry
1010 // These two calls are redundant in default deployments, but they're
1011 // meaningful if "prevnext" is memory-backed.
1012 Civi
::service('prevnext')->deleteItem($id);
1013 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1015 $transaction->commit();
1017 if ($skipUndelete) {
1018 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1025 * Action to update any caches relating to a recently update contact.
1027 * I was going to call this from delete as well as from create to ensure the delete is being
1028 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1029 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1030 * where the call involved a subquery that was locking the table.
1032 * @param int $contactID
1033 * @param bool $isTrashed
1035 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1038 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1039 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1040 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1041 // but this should not cause any change as long as contacts are not being trashed outside the
1042 // main functions for that.
1043 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
1046 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1051 * Delete the image of a contact.
1054 * Id of the contact.
1057 * Was contact image deleted?
1059 public static function deleteContactImage($id) {
1064 $contact = new self();
1066 $contact->image_URL
= 'null';
1073 * Return proportional height and width of the image.
1075 * @param int $imageWidth
1078 * @param int $imageHeight
1082 * Thumb dimension of image
1084 public static function getThumbSize($imageWidth, $imageHeight) {
1086 if ($imageWidth && $imageHeight) {
1087 $imageRatio = $imageWidth / $imageHeight;
1092 if ($imageRatio > 1) {
1093 $imageThumbWidth = $thumbWidth;
1094 $imageThumbHeight = round($thumbWidth / $imageRatio);
1097 $imageThumbHeight = $thumbWidth;
1098 $imageThumbWidth = round($thumbWidth * $imageRatio);
1101 return array($imageThumbWidth, $imageThumbHeight);
1105 * Validate type of contact image.
1107 * @param array $params
1108 * @param string $imageIndex
1109 * Index of image field.
1110 * @param string $statusMsg
1111 * Status message to be set after operation.
1112 * @param string $opType
1113 * Type of operation like fatal, bounce etc.
1116 * true if valid image extension
1118 public static function processImageParams(
1120 $imageIndex = 'image_URL',
1134 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1135 $photo = basename($params[$imageIndex]['name']);
1136 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1140 unset($params[$imageIndex]);
1142 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1144 if ($opType == 'status') {
1145 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1147 // FIXME: additional support for fatal, bounce etc could be added.
1153 * Extract contact id from url for deleting contact image.
1155 public static function processImage() {
1157 $action = CRM_Utils_Request
::retrieve('action', 'String');
1158 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1159 // retrieve contact id in case of Profile context
1160 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1161 $cid = $cid ?
$cid : $id;
1162 if ($action & CRM_Core_Action
::DELETE
) {
1163 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1164 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1165 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1166 $session = CRM_Core_Session
::singleton();
1167 $toUrl = $session->popUserContext();
1168 CRM_Utils_System
::redirect($toUrl);
1174 * Function to set is_delete true or restore deleted contact.
1176 * @param CRM_Contact_DAO_Contact $contact
1177 * Contact DAO object.
1178 * @param bool $restore
1179 * True to set the is_delete = 1 else false to restore deleted contact,
1180 * i.e. is_delete = 0
1184 public static function contactTrashRestore($contact, $restore = FALSE) {
1185 $updateParams = array(
1186 'id' => $contact->id
,
1187 'is_deleted' => $restore ?
0 : 1,
1190 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1192 $params = array(1 => array($contact->id
, 'Integer'));
1194 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1195 CRM_Core_DAO
::executeQuery($query, $params);
1198 $contact->copyValues($updateParams);
1200 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
1202 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1208 * Get contact type for a contact.
1211 * Id of the contact whose contact type is needed.
1214 * contact_type if $id found else null ""
1216 public static function getContactType($id) {
1217 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1221 * Get contact sub type for a contact.
1224 * Id of the contact whose contact sub type is needed.
1226 * @param string $implodeDelimiter
1229 * contact_sub_type if $id found else null ""
1231 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1232 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1234 return $implodeDelimiter ?
NULL : array();
1237 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1239 if ($implodeDelimiter) {
1240 $subtype = implode($implodeDelimiter, $subtype);
1246 * Get pair of contact-type and sub-type for a contact.
1249 * Id of the contact whose contact sub/contact type is needed.
1253 public static function getContactTypes($id) {
1254 $params = array('id' => $id);
1256 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1259 array('contact_type', 'contact_sub_type')
1263 $contactTypes = array();
1264 if ($contact->contact_sub_type
) {
1265 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1267 array_unshift($contactTypes, $contact->contact_type
);
1269 return $contactTypes;
1272 CRM_Core_Error
::fatal();
1277 * Combine all the importable fields from the lower levels object.
1279 * The ordering is important, since currently we do not have a weight
1280 * scheme. Adding weight is super important
1282 * @param int|string $contactType contact Type
1283 * @param bool $status
1284 * Status is used to manipulate first title.
1285 * @param bool $showAll
1286 * If true returns all fields (includes disabled fields).
1287 * @param bool $isProfile
1288 * If its profile mode.
1289 * @param bool $checkPermission
1290 * If false, do not include permissioning clause (for custom data).
1292 * @param bool $withMultiCustomFields
1295 * array of importable Fields
1297 public static function importableFields(
1298 $contactType = 'Individual',
1302 $checkPermission = TRUE,
1303 $withMultiCustomFields = FALSE
1305 if (empty($contactType)) {
1306 $contactType = 'All';
1309 $cacheKeyString = "importableFields $contactType";
1310 $cacheKeyString .= $status ?
'_1' : '_0';
1311 $cacheKeyString .= $showAll ?
'_1' : '_0';
1312 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1313 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1315 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1318 // check if we can retrieve from database cache
1319 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1323 $fields = CRM_Contact_DAO_Contact
::import();
1325 // get the fields thar are meant for contact types
1326 if (in_array($contactType, array(
1332 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1335 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1336 CRM_Core_DAO_Phone
::import(),
1337 CRM_Core_DAO_Email
::import(),
1338 CRM_Core_DAO_IM
::import(TRUE),
1339 CRM_Core_DAO_OpenID
::import()
1342 $locationFields = array_merge($locationFields,
1343 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1351 foreach ($locationFields as $key => $field) {
1352 $locationFields[$key]['hasLocationType'] = TRUE;
1355 $fields = array_merge($fields, $locationFields);
1357 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1358 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1361 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1362 $fields['url']['hasWebsiteType'] = TRUE;
1364 if ($contactType != 'All') {
1365 $fields = array_merge($fields,
1366 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1371 $withMultiCustomFields
1374 //unset the fields, which are not related to their
1376 $commonValues = array(
1377 'Individual' => array(
1381 'organization_name',
1383 'Household' => array(
1393 'organization_name',
1401 'Organization' => array(
1416 foreach ($commonValues[$contactType] as $value) {
1417 unset($fields[$value]);
1421 foreach (array('Individual', 'Household', 'Organization') as $type) {
1422 $fields = array_merge($fields,
1423 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1428 $withMultiCustomFields
1435 $fields = array_merge($fields, array(
1437 'title' => ts('Group(s)'),
1441 'title' => ts('Tag(s)'),
1445 'title' => ts('Note'),
1448 'communication_style_id' => array(
1449 'title' => ts('Communication Style'),
1450 'name' => 'communication_style_id',
1455 //Sorting fields in alphabetical order(CRM-1507)
1456 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1458 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1461 self
::$_importableFields[$cacheKeyString] = $fields;
1465 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1466 self
::$_importableFields[$cacheKeyString]
1470 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1471 self
::$_importableFields[$cacheKeyString]
1479 * Combine all the exportable fields from the lower levels object.
1481 * Currently we are using importable fields as exportable fields
1483 * @param int|string $contactType contact Type
1484 * @param bool $status
1485 * True while exporting primary contacts.
1486 * @param bool $export
1487 * True when used during export.
1488 * @param bool $search
1489 * True when used during search, might conflict with export param?.
1491 * @param bool $withMultiRecord
1494 * array of exportable Fields
1496 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1497 if (empty($contactType)) {
1498 $contactType = 'All';
1501 $cacheKeyString = "exportableFields $contactType";
1502 $cacheKeyString .= $export ?
'_1' : '_0';
1503 $cacheKeyString .= $status ?
'_1' : '_0';
1504 $cacheKeyString .= $search ?
'_1' : '_0';
1505 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1506 //calculates custom fields takes into account the logged in user & caches that for all users
1507 //as an interim fix we will cache the fields by contact
1508 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1510 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1511 if (!self
::$_exportableFields) {
1512 self
::$_exportableFields = array();
1515 // check if we can retrieve from database cache
1516 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1519 $fields = CRM_Contact_DAO_Contact
::export();
1521 // The fields are meant for contact types.
1522 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,
2401 ($value == '' ||
!isset($value)) &&
2402 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2403 ($key == 'current_employer' && empty($params['current_employer']))) {
2404 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2405 // to avoid update with empty values
2409 $data[$key] = $value;
2415 if (!isset($data['contact_type'])) {
2416 $data['contact_type'] = 'Individual';
2419 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2420 $privacy = CRM_Core_SelectValues
::privacy();
2421 foreach ($privacy as $key => $value) {
2422 if (array_key_exists($key, $fields)) {
2423 // do not reset values for existing contacts, if fields are added to a profile
2424 if (array_key_exists($key, $params)) {
2425 $data[$key] = $params[$key];
2426 if (empty($params[$key])) {
2430 elseif (!$contactID) {
2436 return array($data, $contactDetails);
2440 * Find the get contact details.
2442 * This function does not respect ACLs for now, which might need to be rectified at some
2443 * stage based on how its used.
2445 * @param string $mail
2446 * Primary email address of the contact.
2447 * @param string $ctype
2450 * @return object|null
2451 * $dao contact details
2453 public static function matchContactOnEmail($mail, $ctype = NULL) {
2454 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2455 $mail = $strtolower(trim($mail));
2457 SELECT civicrm_contact.id as contact_id,
2458 civicrm_contact.hash as hash,
2459 civicrm_contact.contact_type as contact_type,
2460 civicrm_contact.contact_sub_type as contact_sub_type
2461 FROM civicrm_contact
2462 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2464 if (Civi
::settings()->get('uniq_email_per_site')) {
2465 // try to find a match within a site (multisite).
2466 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2467 if (!empty($groups)) {
2469 INNER JOIN civicrm_group_contact gc ON
2470 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2475 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2476 $p = array(1 => array($mail, 'String'));
2479 $query .= " AND civicrm_contact.contact_type = %3";
2480 $p[3] = array($ctype, 'String');
2483 $query .= " ORDER BY civicrm_email.is_primary DESC";
2485 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2487 if ($dao->fetch()) {
2494 * Find the contact details associated with an OpenID.
2496 * @param string $openId
2497 * OpenId of the contact.
2498 * @param string $ctype
2501 * @return object|null
2502 * $dao contact details
2504 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2505 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2506 $openId = $strtolower(trim($openId));
2508 SELECT civicrm_contact.id as contact_id,
2509 civicrm_contact.hash as hash,
2510 civicrm_contact.contact_type as contact_type,
2511 civicrm_contact.contact_sub_type as contact_sub_type
2512 FROM civicrm_contact
2513 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2514 WHERE civicrm_openid.openid = %1";
2515 $p = array(1 => array($openId, 'String'));
2518 $query .= " AND civicrm_contact.contact_type = %3";
2519 $p[3] = array($ctype, 'String');
2522 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2524 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2526 if ($dao->fetch()) {
2533 * Get primary email of the contact.
2535 * @param int $contactID
2539 * Email address if present else null
2541 public static function getPrimaryEmail($contactID) {
2542 // fetch the primary email
2544 SELECT civicrm_email.email as email
2545 FROM civicrm_contact
2546 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2547 WHERE civicrm_email.is_primary = 1
2548 AND civicrm_contact.id = %1";
2549 $p = array(1 => array($contactID, 'Integer'));
2550 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2553 if ($dao->fetch()) {
2554 $email = $dao->email
;
2560 * Function to get primary OpenID of the contact.
2562 * @param int $contactID
2566 * >openid OpenID if present else null
2568 public static function getPrimaryOpenId($contactID) {
2569 // fetch the primary OpenID
2571 SELECT civicrm_openid.openid as openid
2572 FROM civicrm_contact
2573 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2574 WHERE civicrm_contact.id = %1
2575 AND civicrm_openid.is_primary = 1";
2576 $p = array(1 => array($contactID, 'Integer'));
2577 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2580 if ($dao->fetch()) {
2581 $openId = $dao->openid
;
2587 * Fetch the object and store the values in the values array.
2589 * @param array $params
2590 * Input parameters to find object.
2591 * @param array $values
2592 * Output values of the object.
2594 * @return CRM_Contact_BAO_Contact|null
2595 * The found object or null
2597 public static function getValues(&$params, &$values) {
2598 $contact = new CRM_Contact_BAO_Contact();
2600 $contact->copyValues($params);
2602 if ($contact->find(TRUE)) {
2604 CRM_Core_DAO
::storeValues($contact, $values);
2607 foreach (self
::$_commPrefs as $name) {
2608 if (isset($contact->$name)) {
2609 $privacy[$name] = $contact->$name;
2613 if (!empty($privacy)) {
2614 $values['privacy'] = $privacy;
2617 // communication Prefferance
2618 $preffComm = $comm = array();
2619 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2620 $contact->preferred_communication_method
2622 foreach ($comm as $value) {
2623 $preffComm[$value] = 1;
2625 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2628 'preferred_communication_method' => array(
2629 'newName' => 'preferred_communication_method_display',
2630 'groupName' => 'preferred_communication_method',
2634 // @todo This can be figured out from metadata & we can avoid the uncached query.
2635 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2637 $values['preferred_communication_method'] = $preffComm;
2638 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2640 if ($contact->preferred_mail_format
) {
2641 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2642 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2645 // get preferred languages
2646 if (!empty($contact->preferred_language
)) {
2647 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2650 // Calculating Year difference
2651 if ($contact->birth_date
) {
2652 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2653 if ($birthDate < date('Ymd')) {
2654 $age = CRM_Utils_Date
::calculateAge($birthDate);
2655 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2656 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2660 $contact->contact_id
= $contact->id
;
2668 * Given the component name and returns the count of participation of contact.
2670 * @param string $component
2671 * Input component name.
2672 * @param int $contactId
2674 * @param string $tableName
2675 * Optional tableName if component is custom group.
2678 * total number in database
2680 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2682 switch ($component) {
2684 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2687 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2688 CRM_Contact_BAO_Relationship
::CURRENT
,
2697 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2700 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2703 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2706 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2708 case 'contribution':
2709 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2712 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2715 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2718 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2721 return CRM_Case_BAO_Case
::caseCount($contactId);
2724 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2728 'contact_id' => $contactId,
2731 'context' => 'activity',
2733 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2736 $params = array('contact_id' => $contactId);
2737 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2740 $custom = explode('_', $component);
2741 if ($custom['0'] = 'custom') {
2743 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2745 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2746 return CRM_Core_DAO
::singleValueQuery($queryString);
2752 * Update contact greetings if an update has resulted in a custom field change.
2754 * @param array $updatedFields
2755 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2756 * @param array $contactParams
2757 * Parameters known about the contact. At minimum array('contact_id' => x).
2758 * Fields in this array will take precedence over DB fields (so far only
2759 * in the case of greeting id fields).
2761 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2762 $contactID = $contactParams['contact_id'];
2763 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2764 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2765 if (!empty($tokens['all']['contact'])) {
2766 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2767 if (!empty($affectedTokens)) {
2768 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2769 $contact = new CRM_Contact_BAO_Contact();
2770 $contact->id
= $contactID;
2771 CRM_Contact_BAO_Contact
::processGreetings($contact);
2777 * Process greetings and cache.
2779 * @param object $contact
2780 * Contact object after save.
2782 public static function processGreetings(&$contact) {
2784 //@todo this function does a lot of unnecessary loading.
2785 // ensureGreetingParamsAreSet now makes sure that the contact is
2786 // loaded and using updateGreetingsOnTokenFieldChange
2787 // allows us the possibility of only doing an update if required.
2789 // The contact object has not always required the
2790 // fields that are required to calculate greetings
2791 // so we need to retrieve it again.
2792 if ($contact->_query
!== FALSE) {
2793 $contact->find(TRUE);
2796 // store object values to an array
2797 $contactDetails = array();
2798 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2799 $contactDetails = array(array($contact->id
=> $contactDetails));
2801 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2802 $updateQueryString = array();
2804 //cache email and postal greeting to greeting display
2805 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2806 $emailGreetingString = $contact->email_greeting_custom
;
2808 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2809 // the filter value for Individual contact type is set to 1
2811 'contact_type' => $contact->contact_type
,
2812 'greeting_type' => 'email_greeting',
2815 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2816 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2817 $updateQueryString[] = " email_greeting_custom = NULL ";
2820 if ($contact->email_greeting_custom
) {
2821 $updateQueryString[] = " email_greeting_display = NULL ";
2825 if ($emailGreetingString) {
2826 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2829 'CRM_Contact_BAO_Contact'
2831 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2832 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2836 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2837 $postalGreetingString = $contact->postal_greeting_custom
;
2839 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2841 'contact_type' => $contact->contact_type
,
2842 'greeting_type' => 'postal_greeting',
2844 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2845 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2846 $updateQueryString[] = " postal_greeting_custom = NULL ";
2849 if ($contact->postal_greeting_custom
) {
2850 $updateQueryString[] = " postal_greeting_display = NULL ";
2854 if ($postalGreetingString) {
2855 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2858 'CRM_Contact_BAO_Contact'
2860 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2861 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2865 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2866 $addresseeString = $contact->addressee_custom
;
2868 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2870 'contact_type' => $contact->contact_type
,
2871 'greeting_type' => 'addressee',
2874 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2875 $addresseeString = $addressee[$contact->addressee_id
];
2876 $updateQueryString[] = " addressee_custom = NULL ";
2879 if ($contact->addressee_custom
) {
2880 $updateQueryString[] = " addressee_display = NULL ";
2884 if ($addresseeString) {
2885 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2888 'CRM_Contact_BAO_Contact'
2890 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2891 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2894 if (!empty($updateQueryString)) {
2895 $updateQueryString = implode(',', $updateQueryString);
2896 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2897 CRM_Core_DAO
::executeQuery($queryString);
2902 * Retrieve loc block ids w/ given condition.
2904 * @param int $contactId
2906 * @param array $criteria
2907 * Key => value pair which should be.
2908 * fulfill by return record ids.
2909 * @param string $condOperator
2910 * Operator use for grouping multiple conditions.
2913 * loc block ids which fulfill condition.
2915 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2916 $locBlockIds = array();
2918 return $locBlockIds;
2921 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2922 $name = strtolower($block);
2923 $className = "CRM_Core_DAO_$block";
2924 $blockDAO = new $className();
2926 // build the condition.
2927 if (is_array($criteria)) {
2928 $fields = $blockDAO->fields();
2929 $conditions = array();
2930 foreach ($criteria as $field => $value) {
2931 if (array_key_exists($field, $fields)) {
2932 $cond = "( $field = $value )";
2933 // value might be zero or null.
2934 if (!$value ||
strtolower($value) == 'null') {
2935 $cond = "( $field = 0 OR $field IS NULL )";
2937 $conditions[] = $cond;
2940 if (!empty($conditions)) {
2941 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2945 $blockDAO->contact_id
= $contactId;
2947 while ($blockDAO->fetch()) {
2948 $locBlockIds[$name][] = $blockDAO->id
;
2953 return $locBlockIds;
2957 * Build context menu items.
2959 * @param int $contactId
2962 * Array of context menu for logged in user.
2964 public static function contextMenu($contactId = NULL) {
2967 'title' => ts('View Contact'),
2969 'ref' => 'view-contact',
2970 'class' => 'no-popup',
2972 'permissions' => array('view all contacts'),
2975 'title' => ts('Edit Contact'),
2977 'ref' => 'edit-contact',
2978 'class' => 'no-popup',
2980 'permissions' => array('edit all contacts'),
2983 'title' => ts('Delete Contact'),
2985 'ref' => 'delete-contact',
2987 'permissions' => array('access deleted contacts', 'delete contacts'),
2989 'contribution' => array(
2990 'title' => ts('Add Contribution'),
2992 'ref' => 'new-contribution',
2993 'key' => 'contribution',
2994 'tab' => 'contribute',
2995 'component' => 'CiviContribute',
2996 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2997 'reset=1&action=add&context=contribution'
2999 'permissions' => array(
3000 'access CiviContribute',
3001 'edit contributions',
3004 'participant' => array(
3005 'title' => ts('Register for Event'),
3007 'ref' => 'new-participant',
3008 'key' => 'participant',
3009 'tab' => 'participant',
3010 'component' => 'CiviEvent',
3011 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3012 'permissions' => array(
3014 'edit event participants',
3017 'activity' => array(
3018 'title' => ts('Record Activity'),
3020 'ref' => 'new-activity',
3021 'key' => 'activity',
3022 'permissions' => array('edit all contacts'),
3025 'title' => ts('Add Pledge'),
3027 'ref' => 'new-pledge',
3030 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3031 'reset=1&action=add&context=pledge'
3033 'component' => 'CiviPledge',
3034 'permissions' => array(
3035 'access CiviPledge',
3039 'membership' => array(
3040 'title' => ts('Add Membership'),
3042 'ref' => 'new-membership',
3043 'key' => 'membership',
3045 'component' => 'CiviMember',
3046 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3047 'reset=1&action=add&context=membership'
3049 'permissions' => array(
3050 'access CiviMember',
3055 'title' => ts('Add Case'),
3057 'ref' => 'new-case',
3060 'component' => 'CiviCase',
3061 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3062 'permissions' => array('add cases'),
3065 'title' => ts('Add Grant'),
3067 'ref' => 'new-grant',
3070 'component' => 'CiviGrant',
3071 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3072 'reset=1&action=add&context=grant'
3074 'permissions' => array('edit grants'),
3077 'title' => ts('Add Relationship'),
3079 'ref' => 'new-relationship',
3082 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3083 'reset=1&action=add'
3085 'permissions' => array('edit all contacts'),
3088 'title' => ts('Add Note'),
3090 'ref' => 'new-note',
3093 'class' => 'medium-popup',
3094 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3095 'reset=1&action=add'
3097 'permissions' => array('edit all contacts'),
3100 'title' => ts('Send an Email'),
3102 'ref' => 'new-email',
3104 'permissions' => array('view all contacts'),
3107 'title' => ts('Add to Group'),
3109 'ref' => 'group-add-contact',
3112 'permissions' => array('edit groups'),
3115 'title' => ts('Tag Contact'),
3117 'ref' => 'tag-contact',
3120 'permissions' => array('edit all contacts'),
3124 $menu['otherActions'] = array(
3126 'title' => ts('Print Summary'),
3127 'description' => ts('Printer-friendly view of this page.'),
3129 'ref' => 'crm-contact-print',
3132 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3136 'icon' => 'crm-i fa-print',
3139 'title' => ts('vCard'),
3140 'description' => ts('vCard record for this contact.'),
3142 'ref' => 'crm-contact-vcard',
3145 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3149 'icon' => 'crm-i fa-list-alt',
3153 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3154 $menu['otherActions']['dashboard'] = array(
3155 'title' => ts('Contact Dashboard'),
3156 'description' => ts('Contact Dashboard'),
3158 'ref' => 'crm-contact-dashboard',
3159 'key' => 'dashboard',
3160 'tab' => 'dashboard',
3161 'class' => 'dashboard',
3162 // NOTE: As an alternative you can also build url on CMS specific way
3163 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3164 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3165 'icon' => 'crm-i fa-tachometer',
3169 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3171 $menu['otherActions']['user-record'] = array(
3172 'title' => ts('User Record'),
3173 'description' => ts('User Record'),
3175 'ref' => 'crm-contact-user-record',
3176 'key' => 'user-record',
3177 'tab' => 'user-record',
3178 'class' => 'user-record',
3179 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3180 'icon' => 'crm-i fa-user',
3183 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3184 $menu['otherActions']['user-add'] = array(
3185 'title' => ts('Create User Record'),
3186 'description' => ts('Create User Record'),
3188 'ref' => 'crm-contact-user-add',
3189 'key' => 'user-add',
3190 'tab' => 'user-add',
3191 'class' => 'user-add',
3192 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3193 'icon' => 'crm-i fa-user-plus',
3197 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3198 //1. check for component is active.
3199 //2. check for user permissions.
3200 //3. check for acls.
3201 //3. edit and view contact are directly accessible to user.
3203 $aclPermissionedTasks = array(
3208 'group-add-contact',
3212 $corePermission = CRM_Core_Permission
::getPermission();
3214 $contextMenu = array();
3215 foreach ($menu as $key => $values) {
3216 if ($key != 'otherActions') {
3218 // user does not have necessary permissions.
3219 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3222 // build directly accessible action menu.
3223 if (in_array($values['ref'], array(
3227 $contextMenu['primaryActions'][$key] = array(
3228 'title' => $values['title'],
3229 'ref' => $values['ref'],
3230 'class' => CRM_Utils_Array
::value('class', $values),
3231 'key' => $values['key'],
3236 // finally get menu item for -more- action widget.
3237 $contextMenu['moreActions'][$values['weight']] = array(
3238 'title' => $values['title'],
3239 'ref' => $values['ref'],
3240 'href' => CRM_Utils_Array
::value('href', $values),
3241 'tab' => CRM_Utils_Array
::value('tab', $values),
3242 'class' => CRM_Utils_Array
::value('class', $values),
3243 'key' => $values['key'],
3247 foreach ($values as $value) {
3248 // user does not have necessary permissions.
3249 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3253 // finally get menu item for -more- action widget.
3254 $contextMenu['otherActions'][$value['weight']] = array(
3255 'title' => $value['title'],
3256 'ref' => $value['ref'],
3257 'href' => CRM_Utils_Array
::value('href', $value),
3258 'tab' => CRM_Utils_Array
::value('tab', $value),
3259 'class' => CRM_Utils_Array
::value('class', $value),
3260 'icon' => CRM_Utils_Array
::value('icon', $value),
3261 'key' => $value['key'],
3267 ksort($contextMenu['moreActions']);
3268 ksort($contextMenu['otherActions']);
3270 return $contextMenu;
3274 * Check if user has permissions to access items in action menu.
3276 * @param array $aclPermissionedTasks
3277 * Array containing ACL related tasks.
3278 * @param string $corePermission
3279 * The permission of the user (edit or view or null).
3280 * @param array $menuOptions
3281 * Array containing params of the menu (title, href, etc).
3284 * TRUE if user has all permissions, FALSE if otherwise.
3286 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3287 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3289 // if component action - make sure component is enable.
3290 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3294 // make sure user has all required permissions.
3295 $hasAllPermissions = FALSE;
3297 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3298 if (!is_array($permissions) ||
empty($permissions)) {
3299 $hasAllPermissions = TRUE;
3302 // iterate for required permissions in given permissions array.
3303 if (!$hasAllPermissions) {
3304 $hasPermissions = 0;
3305 foreach ($permissions as $permission) {
3306 if (CRM_Core_Permission
::check($permission)) {
3311 if (count($permissions) == $hasPermissions) {
3312 $hasAllPermissions = TRUE;
3315 // if still user does not have required permissions, check acl.
3316 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3317 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3318 $corePermission == CRM_Core_Permission
::EDIT
3320 $hasAllPermissions = TRUE;
3322 elseif (in_array($menuOptions['ref'], array(
3325 // grant permissions for these tasks.
3326 $hasAllPermissions = TRUE;
3331 return $hasAllPermissions;
3335 * Retrieve display name of contact that address is shared.
3337 * This is based on $masterAddressId or $contactId .
3339 * @param int $masterAddressId
3341 * @param int $contactId
3342 * Contact id. (deprecated - do not use)
3344 * @return string|null
3345 * the found display name or null.
3347 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3348 $masterDisplayName = NULL;
3349 if (!$masterAddressId) {
3350 return $masterDisplayName;
3354 SELECT display_name from civicrm_contact
3355 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3356 WHERE civicrm_address.id = " . $masterAddressId;
3358 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3359 return $masterDisplayName;
3363 * Get the creation/modification times for a contact.
3365 * @param int $contactId
3368 * Dates - ('created_date' => $, 'modified_date' => $)
3370 public static function getTimestamps($contactId) {
3371 $timestamps = CRM_Core_DAO
::executeQuery(
3372 'SELECT created_date, modified_date
3373 FROM civicrm_contact
3376 1 => array($contactId, 'Integer'),
3379 if ($timestamps->fetch()) {
3381 'created_date' => $timestamps->created_date
,
3382 'modified_date' => $timestamps->modified_date
,
3391 * Get a list of triggers for the contact table.
3393 * @see hook_civicrm_triggerInfo
3394 * @see CRM_Core_DAO::triggerRebuild
3395 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3398 * @param null $tableName
3400 public static function triggerInfo(&$info, $tableName = NULL) {
3401 //during upgrade, first check for valid version and then create triggers
3402 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3403 if (CRM_Core_Config
::isUpgradeMode()) {
3404 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3405 //if current version is less than 4.3.alpha1 dont create below triggers
3406 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3411 // Modifications to these records should update the contact timestamps.
3412 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3413 ->setRelations(array(
3414 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3415 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3416 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3417 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3418 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3421 ->alterTriggerInfo($info, $tableName);
3423 // Update phone table to populate phone_numeric field
3424 if (!$tableName ||
$tableName == 'civicrm_phone') {
3425 // Define stored sql function needed for phones
3426 $sqlTriggers = Civi
::service('sql_triggers');
3427 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3428 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3430 'table' => array('civicrm_phone'),
3432 'event' => array('INSERT', 'UPDATE'),
3433 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3439 * Check if contact is being used in civicrm_domain based on $contactId.
3441 * @param int $contactId
3445 * true if present else false.
3447 public static function checkDomainContact($contactId) {
3451 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3462 * Get options for a given contact field.
3464 * @see CRM_Core_DAO::buildOptions
3466 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3467 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3469 * @param string $fieldName
3470 * @param string $context
3471 * @see CRM_Core_DAO::buildOptionsContext
3472 * @param array $props
3473 * whatever is known about this dao object.
3475 * @return array|bool
3477 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3479 // Special logic for fields whose options depend on context or properties
3480 switch ($fieldName) {
3481 case 'contact_sub_type':
3482 if (!empty($props['contact_type'])) {
3483 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3487 case 'contact_type':
3488 if ($context == 'search') {
3489 // CRM-15495 - EntityRef filters and basic search forms expect this format
3490 // FIXME: Search builder does not
3491 return CRM_Contact_BAO_ContactType
::getSelectElements();
3495 // The contact api supports some related entities so we'll honor that by fetching their options
3498 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3502 $props['entity_table'] = 'civicrm_contact';
3503 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3505 case 'state_province_id':
3506 case 'state_province':
3507 case 'state_province_name':
3512 case 'worldregion_id':
3513 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3516 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3520 * Delete a contact-related object that has an 'is_primary' field.
3522 * Ensures that is_primary gets assigned to another object if available
3523 * Also calls pre/post hooks
3525 * @param string $type
3529 public static function deleteObjectWithPrimary($type, $id) {
3530 if (!$id ||
!is_numeric($id)) {
3533 $daoName = "CRM_Core_DAO_$type";
3534 $obj = new $daoName();
3538 if ($obj->fetch()) {
3539 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3540 $contactId = $obj->contact_id
;
3546 // is_primary is only relavent if this field belongs to a contact
3548 $dao = new $daoName();
3549 $dao->contact_id
= $contactId;
3550 $dao->is_primary
= 1;
3551 // Pick another record to be primary (if one isn't already)
3552 if (!$dao->find(TRUE)) {
3553 $dao->is_primary
= 0;
3555 if ($dao->fetch()) {
3556 $dao->is_primary
= 1;
3561 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3569 public function addSelectWhereClause() {
3570 // We always return an array with these keys, even if they are empty,
3571 // because this tells the query builder that we have considered these fields for acls
3573 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3574 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
array() : array('!= 1'),
3576 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3581 * Get any existing duplicate contacts based on the input parameters.
3583 * @param array $input
3584 * Input parameters to be matched.
3585 * @param string $contactType
3586 * @param string $rule
3589 * @param $excludedContactIDs
3590 * An array of ids not to be included in the results.
3591 * @param bool $checkPermissions
3592 * @param int $ruleGroupID
3593 * ID of the rule group to be used if an override is desirable.
3594 * @param array $contextParams
3595 * The context if relevant, eg. ['event_id' => X]
3599 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3600 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3601 $dedupeParams['check_permission'] = $checkPermissions;
3602 $dedupeParams['contact_type'] = $contactType;
3603 $dedupeParams['rule'] = $rule;
3604 $dedupeParams['rule_group_id'] = $ruleGroupID;
3605 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3606 $dedupeResults['ids'] = [];
3607 $dedupeResults['handled'] = FALSE;
3608 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3609 if (!$dedupeResults['handled']) {
3610 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3612 return $dedupeResults['ids'];
3616 * Get the first duplicate contacts based on the input parameters.
3618 * @param array $input
3619 * Input parameters to be matched.
3620 * @param string $contactType
3621 * @param string $rule
3624 * @param $excludedContactIDs
3625 * An array of ids not to be included in the results.
3626 * @param bool $checkPermissions
3627 * @param int $ruleGroupID
3628 * ID of the rule group to be used if an override is desirable.
3629 * @param array $contextParams
3630 * The context if relevant, eg. ['event_id' => X]
3634 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3635 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3643 * Check if a field is associated with an entity that has a location type.
3645 * (ie. is an address, phone, email etc field).
3647 * @param string $fieldTitle
3648 * Title of the field (not the name - create a new function for that if required).
3652 public static function isFieldHasLocationType($fieldTitle) {
3653 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3654 if ($field['title'] === $fieldTitle) {
3655 return CRM_Utils_Array
::value('hasLocationType', $field);
3662 * @param array $appendProfiles
3663 * Name of profile(s) to append to each link.
3667 public static function getEntityRefCreateLinks($appendProfiles = []) {
3668 // You'd think that "create contacts" would be the permission to check,
3669 // But new contact popups are profile forms and those use their own permissions.
3670 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3674 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3675 $profiles[] = 'new_' . strtolower($contactType);
3677 $retrieved = civicrm_api3('uf_group', 'get', [
3678 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3681 $links = $append = [];
3682 if (!empty($retrieved['values'])) {
3684 'individual' => 'fa-user',
3685 'organization' => 'fa-building',
3686 'household' => 'fa-home',
3688 foreach ($retrieved['values'] as $id => $profile) {
3689 if (in_array($profile['name'], $profiles)) {
3691 'label' => $profile['title'],
3692 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3693 NULL, NULL, FALSE, FALSE, TRUE),
3694 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3695 'icon' => CRM_Utils_Array
::value(str_replace('new_', '', $profile['name']), $icons),
3702 foreach ($append as $id) {
3703 foreach ($links as &$link) {
3704 $link['url'] .= ",$id";
3714 public static function getEntityRefFilters() {
3716 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3717 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3718 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3719 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3720 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3721 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3722 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3723 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3724 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3725 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],