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 // Fixed contact source.
150 if (isset($params['contact_source'])) {
151 $params['source'] = $params['contact_source'];
154 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
155 CRM_Utils_Array
::formatArrayKeys($params['preferred_communication_method']);
156 $contact->preferred_communication_method
= CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
157 unset($params['preferred_communication_method']);
160 $allNull = $contact->copyValues($params);
162 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
164 if ($contact->contact_type
== 'Individual') {
167 // Format individual fields.
168 CRM_Contact_BAO_Individual
::format($params, $contact);
170 elseif ($contact->contact_type
== 'Household') {
171 if (isset($params['household_name'])) {
173 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('household_name', $params, '');
176 elseif ($contact->contact_type
== 'Organization') {
177 if (isset($params['organization_name'])) {
179 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('organization_name', $params, '');
182 if (strlen($contact->display_name
) > 128) {
183 $contact->display_name
= substr($contact->display_name
, 0, 128);
185 if (strlen($contact->sort_name
) > 128) {
186 $contact->sort_name
= substr($contact->sort_name
, 0, 128);
189 $privacy = CRM_Utils_Array
::value('privacy', $params);
191 is_array($privacy) &&
195 foreach (self
::$_commPrefs as $name) {
196 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
200 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
201 // @todo - does this mean we can remove this block?
202 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
203 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
205 $contact->hash
= md5(uniqid(rand(), TRUE));
208 // Even if we don't need $employerId, it's important to call getFieldValue() before
209 // the contact is saved because we want the existing value to be cached.
210 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
211 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
216 CRM_Core_BAO_Log
::register($contact->id
,
222 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
223 // Create current employer.
224 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
227 if (empty($params['contact_id'])) {
231 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
235 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
240 // Update cached employer name.
241 if ($contact->contact_type
== 'Organization') {
242 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
251 * takes an associative array and creates a contact object and all the associated
252 * derived objects (i.e. individual, location, email, phone etc)
254 * This function is invoked from within the web form layer and also from the api layer
256 * @param array $params
257 * (reference ) an assoc array of name/value pairs.
258 * @param bool $fixAddress
259 * If we need to fix address.
260 * @param bool $invokeHooks
261 * If we need to invoke hooks.
263 * @param bool $skipDelete
264 * Unclear parameter, passed to website create
266 * @todo explain this parameter
269 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
270 * Created or updated contribution object. We are deprecating returning an error in
271 * favour of exceptions
273 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
275 if (empty($params['contact_type']) && empty($params['contact_id'])) {
281 if (!empty($params['contact_id'])) {
282 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
285 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
290 self
::ensureGreetingParamsAreSet($params);
292 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
293 if (empty($params['contact_id'])) {
294 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
295 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
296 $params['preferred_language'] = $language;
299 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
300 if (empty($params['communication_style_id'])) {
301 $defaultCommunicationStyleId = CRM_Core_OptionGroup
::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
302 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
306 $transaction = new CRM_Core_Transaction();
308 $contact = self
::add($params);
310 // Not dying here is stupid, since we get into weird situation and into a bug that
311 // is impossible to figure out for the user or for us
313 CRM_Core_Error
::fatal();
316 $params['contact_id'] = $contact->id
;
318 if (Civi
::settings()->get('is_enabled')) {
319 // Enabling multisite causes the contact to be added to the domain group.
320 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
321 if (!empty($domainGroupID)) {
322 if (!empty($params['group']) && is_array($params['group'])) {
323 $params['group'][$domainGroupID] = 1;
326 $params['group'] = array($domainGroupID => 1);
331 if (array_key_exists('group', $params)) {
332 $contactIds = array($params['contact_id']);
333 foreach ($params['group'] as $groupId => $flag) {
335 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
337 elseif ($flag == -1) {
338 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
343 // Add location Block data.
344 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
345 foreach ($blocks as $name => $value) {
346 $contact->$name = $value;
348 if (!empty($params['updateBlankLocInfo'])) {
352 if (isset($params['website'])) {
353 CRM_Core_BAO_Website
::process($params['website'], $contact->id
, $skipDelete);
356 $userID = CRM_Core_Session
::singleton()->get('userID');
358 if (!empty($params['note'])) {
359 if (is_array($params['note'])) {
360 foreach ($params['note'] as $note) {
361 $contactId = $contact->id
;
362 if (isset($note['contact_id'])) {
363 $contactId = $note['contact_id'];
365 //if logged in user, overwrite contactId
367 $contactId = $userID;
371 'entity_id' => $contact->id
,
372 'entity_table' => 'civicrm_contact',
373 'note' => $note['note'],
374 'subject' => CRM_Utils_Array
::value('subject', $note),
375 'contact_id' => $contactId,
377 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
381 $contactId = $contact->id
;
382 //if logged in user, overwrite contactId
384 $contactId = $userID;
388 'entity_id' => $contact->id
,
389 'entity_table' => 'civicrm_contact',
390 'note' => $params['note'],
391 'subject' => CRM_Utils_Array
::value('subject', $params),
392 'contact_id' => $contactId,
394 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
398 // update the UF user_unique_id if that has changed
399 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
401 if (!empty($params['custom']) &&
402 is_array($params['custom'])
404 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
407 // make a civicrm_subscription_history entry only on contact create (CRM-777)
408 if (empty($params['contact_id'])) {
409 $subscriptionParams = array(
410 'contact_id' => $contact->id
,
414 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
417 $transaction->commit();
419 // CRM-6367: fetch the right label for contact type’s display
420 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
421 'CRM_Contact_DAO_ContactType',
422 $contact->contact_type
,
427 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
431 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
434 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
438 // In order to prevent a series of expensive queries in intensive batch processing
439 // api calls may pass in skip_greeting_processing, probably doing it later via the
440 // scheduled job. CRM-21551
441 if (empty($params['skip_greeting_processing'])) {
442 self
::processGreetings($contact);
449 * Ensure greeting parameters are set.
451 * By always populating greetings here we can be sure they are set if required & avoid a call later.
452 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
454 * @param array $params
456 public static function ensureGreetingParamsAreSet(&$params) {
457 $allGreetingParams = array('addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id');
458 $missingGreetingParams = array();
460 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
461 if (empty($params[$greetingParam])) {
462 $missingGreetingParams[$greetingIndex] = $greetingParam;
466 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
467 $savedGreetings = civicrm_api3('Contact', 'getsingle', array(
468 'id' => $params['contact_id'],
469 'return' => array_keys($missingGreetingParams))
472 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
473 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
474 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
477 // Filter out other fields.
478 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
479 $params = array_merge($params, $savedGreetings);
482 foreach ($missingGreetingParams as $greetingName => $greeting) {
483 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
487 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
488 if ($params[$greetingParam] === 'null') {
489 // If we are setting it to null then null out the display field.
490 $params[$greetingIndex . '_display'] = 'null';
496 * Get the display name and image of a contact.
501 * @param bool $includeTypeInReturnParameters
502 * Should type be part of the returned array?
505 * the displayName and contactImage for this contact
507 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
508 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
510 SELECT civicrm_contact.*,
511 civicrm_email.email as email
513 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
514 AND civicrm_email.is_primary = 1
515 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
516 $dao = new CRM_Core_DAO();
519 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
520 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
522 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
523 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
526 // use email if display_name is empty
527 if (empty($dao->display_name
)) {
528 $displayName = $dao->email
;
531 $displayName = $dao->display_name
;
534 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
536 return $includeTypeInReturnParameters ?
array(
540 $dao->contact_sub_type
,
542 ) : array($displayName, $image, $imageUrl);
548 * Add billing fields to the params if appropriate.
550 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
551 * don't then we should set the name fields to the filling fields AND add the preserveDBName
552 * parameter (which will tell the BAO only to set those fields if none already exist.
554 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
555 * matching is best done by hipsters.
557 * @param array $params
559 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
560 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
561 foreach ($nameFields as $field) {
562 if (!empty($params[$field])) {
566 // There are only 3 - we can iterate through them twice :-)
567 foreach ($nameFields as $field) {
568 if (!empty($params['billing_' . $field])) {
569 $params[$field] = $params['billing_' . $field];
571 $params['preserveDBName'] = TRUE;
577 * Resolve a state province string (UT or Utah) to an ID.
579 * If country has been passed in we should select a state belonging to that country.
581 * Alternatively we should choose from enabled countries, prioritising the default country.
583 * @param array $values
584 * @param int|NULL $countryID
588 protected static function resolveStateProvinceID($values, $countryID) {
591 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
592 if (CRM_Utils_Array
::lookupValue($values,
597 return $values['state_province_id'];
599 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
600 if (CRM_Utils_Array
::lookupValue($values,
605 return $values['state_province_id'];
610 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
611 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
612 // prefer matching country..
613 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, array('country_id' => Civi
::settings()->get('defaultContactCountry')));
614 if (CRM_Utils_Array
::lookupValue($values,
619 return $values['state_province_id'];
622 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
623 if (CRM_Utils_Array
::lookupValue($values,
628 return $values['state_province_id'];
631 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
632 if (CRM_Utils_Array
::lookupValue($values,
637 return $values['state_province_id'];
639 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
640 if (CRM_Utils_Array
::lookupValue($values,
645 return $values['state_province_id'];
653 * Get the relevant location entity for the array key.
655 * Based on the field name we determine which location entity
656 * we are dealing with. Apart from a few specific ones they
657 * are mostly 'address' (the default).
659 * @param string $fieldName
663 protected static function getLocationEntityForKey($fieldName) {
664 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
667 if ($fieldName === 'phone_ext') {
674 * Create last viewed link to recently updated contact.
676 * @param array $crudLinkSpec
677 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
678 * - entity_table: string, eg "civicrm_contact"
682 * NULL if unavailable, or
683 * [path: string, query: string, title: string]
684 * @see CRM_Utils_System::createDefaultCrudLink
686 public function createDefaultCrudLink($crudLinkSpec) {
687 switch ($crudLinkSpec['action']) {
688 case CRM_Core_Action
::VIEW
:
690 'title' => $this->display_name
,
691 'path' => 'civicrm/contact/view',
699 case CRM_Core_Action
::UPDATE
:
701 'title' => $this->display_name
,
702 'path' => 'civicrm/contact/add',
705 'action' => 'update',
715 * Get the values for pseudoconstants for name->value and reverse.
719 * This is called specifically from the contact import parser & should be moved there
720 * as it is not truly a generic function.
722 * @param array $defaults
723 * (reference) the default values, some of which need to be resolved.
724 * @param bool $reverse
725 * Always true as this function is only called from one place..
727 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
728 // Hack for birth_date.
729 if (!empty($defaults['birth_date'])) {
730 if (is_array($defaults['birth_date'])) {
731 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
735 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
736 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
737 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
738 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
740 //lookup value of email/postal greeting, addressee, CRM-4575
741 foreach (self
::$_greetingTypes as $greeting) {
742 $filterCondition = array(
743 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
744 'greeting_type' => $greeting,
746 CRM_Utils_Array
::lookupValue($defaults, $greeting,
747 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
751 $blocks = array('address', 'im', 'phone');
752 foreach ($blocks as $name) {
753 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
756 foreach ($defaults[$name] as $count => & $values) {
758 //get location type id.
759 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
761 if ($name == 'address') {
762 // FIXME: lookupValue doesn't work for vcard_name
763 if (!empty($values['location_type_id'])) {
764 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
765 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
768 if (!CRM_Utils_Array
::lookupValue($values,
770 CRM_Core_PseudoConstant
::country(),
775 CRM_Utils_Array
::lookupValue($values,
777 CRM_Core_PseudoConstant
::countryIsoCode(),
781 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
782 if ($stateProvinceID) {
783 $values['state_province_id'] = $stateProvinceID;
786 if (!empty($values['state_province_id'])) {
787 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
790 $countyList = CRM_Core_PseudoConstant
::county();
792 CRM_Utils_Array
::lookupValue($values,
800 CRM_Utils_Array
::lookupValue($values,
802 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
807 if ($name == 'phone') {
808 CRM_Utils_Array
::lookupValue($values,
810 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
815 // Kill the reference.
822 * Fetch object based on array of properties.
824 * @param array $params
825 * (reference ) an assoc array of name/value pairs.
826 * @param array $defaults
827 * (reference ) an assoc array to hold the name / value pairs.
828 * in a hierarchical manner
829 * @param bool $microformat
830 * For location in microformat.
832 * @return CRM_Contact_BAO_Contact
834 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
835 if (array_key_exists('contact_id', $params)) {
836 $params['id'] = $params['contact_id'];
838 elseif (array_key_exists('id', $params)) {
839 $params['contact_id'] = $params['id'];
842 $contact = self
::getValues($params, $defaults);
844 unset($params['id']);
846 //get the block information for this contact
847 $entityBlock = array('contact_id' => $params['contact_id']);
848 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
849 $defaults = array_merge($defaults, $blocks);
850 foreach ($blocks as $block => $value) {
851 $contact->$block = $value;
854 if (!isset($params['noNotes'])) {
855 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
858 if (!isset($params['noRelationships'])) {
859 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
862 if (!isset($params['noGroups'])) {
863 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
866 if (!isset($params['noWebsite'])) {
867 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
874 * Get the display name of a contact.
879 * @return null|string
880 * display name of the contact if found
882 public static function displayName($id) {
885 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
892 * Delete a contact and all its associated records.
895 * Id of the contact to delete.
896 * @param bool $restore
897 * Whether to actually restore, not delete.
898 * @param bool $skipUndelete
899 * Whether to force contact delete or not.
900 * @param bool $checkPermissions
903 * Was contact deleted?
905 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
910 // If trash is disabled in system settings then we always skip
911 if (!Civi
::settings()->get('contact_undelete')) {
912 $skipUndelete = TRUE;
915 // make sure we have edit permission for this contact
917 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
918 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
924 // Restrict contact to be delete if contact has financial trxns
926 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
930 // make sure this contact_id does not have any membership types
931 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
934 'member_of_contact_id'
936 if ($membershipTypeID) {
940 $contact = new CRM_Contact_DAO_Contact();
942 if (!$contact->find(TRUE)) {
946 $contactType = $contact->contact_type
;
947 // currently we only clear employer cache.
948 // we are now deleting inherited membership if any.
949 if ($contact->contact_type
== 'Organization') {
950 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
951 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
952 if (!empty($relationshipDtls)) {
953 foreach ($relationshipDtls as $rId => $details) {
954 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
957 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
961 return self
::contactTrashRestore($contact, TRUE);
964 // start a new transaction
965 $transaction = new CRM_Core_Transaction();
968 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
970 //delete billing address if exists.
971 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
973 // delete the log entries since we dont have triggers enabled as yet
974 $logDAO = new CRM_Core_DAO_Log();
975 $logDAO->entity_table
= 'civicrm_contact';
976 $logDAO->entity_id
= $id;
979 // delete contact participants CRM-12155
980 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
982 // delete contact contributions CRM-12155
983 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
985 // do activity cleanup, CRM-5604
986 CRM_Activity_BAO_Activity
::cleanupActivity($id);
988 // delete all notes related to contact
989 CRM_Core_BAO_Note
::cleanContactNotes($id);
991 // delete cases related to contact
992 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
993 if (!empty($contactCases)) {
994 foreach ($contactCases as $caseId) {
995 //check if case is associate with other contact or not.
996 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
997 if (count($caseContactId) <= 1) {
998 CRM_Case_BAO_Case
::deleteCase($caseId);
1006 self
::contactTrashRestore($contact);
1009 //delete the contact id from recently view
1010 CRM_Utils_Recent
::delContact($id);
1011 self
::updateContactCache($id, empty($restore));
1013 // delete any prevnext/dupe cache entry
1014 // These two calls are redundant in default deployments, but they're
1015 // meaningful if "prevnext" is memory-backed.
1016 Civi
::service('prevnext')->deleteItem($id);
1017 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1019 $transaction->commit();
1021 if ($skipUndelete) {
1022 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1029 * Action to update any caches relating to a recently update contact.
1031 * I was going to call this from delete as well as from create to ensure the delete is being
1032 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1033 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1034 * where the call involved a subquery that was locking the table.
1036 * @param int $contactID
1037 * @param bool $isTrashed
1039 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1042 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1043 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1044 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1045 // but this should not cause any change as long as contacts are not being trashed outside the
1046 // main functions for that.
1047 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
1050 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1055 * Delete the image of a contact.
1058 * Id of the contact.
1061 * Was contact image deleted?
1063 public static function deleteContactImage($id) {
1068 $contact = new self();
1070 $contact->image_URL
= 'null';
1077 * Return proportional height and width of the image.
1079 * @param int $imageWidth
1082 * @param int $imageHeight
1086 * Thumb dimension of image
1088 public static function getThumbSize($imageWidth, $imageHeight) {
1090 if ($imageWidth && $imageHeight) {
1091 $imageRatio = $imageWidth / $imageHeight;
1096 if ($imageRatio > 1) {
1097 $imageThumbWidth = $thumbWidth;
1098 $imageThumbHeight = round($thumbWidth / $imageRatio);
1101 $imageThumbHeight = $thumbWidth;
1102 $imageThumbWidth = round($thumbWidth * $imageRatio);
1105 return array($imageThumbWidth, $imageThumbHeight);
1109 * Validate type of contact image.
1111 * @param array $params
1112 * @param string $imageIndex
1113 * Index of image field.
1114 * @param string $statusMsg
1115 * Status message to be set after operation.
1116 * @param string $opType
1117 * Type of operation like fatal, bounce etc.
1120 * true if valid image extension
1122 public static function processImageParams(
1124 $imageIndex = 'image_URL',
1138 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1139 $photo = basename($params[$imageIndex]['name']);
1140 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1144 unset($params[$imageIndex]);
1146 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1148 if ($opType == 'status') {
1149 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1151 // FIXME: additional support for fatal, bounce etc could be added.
1157 * Extract contact id from url for deleting contact image.
1159 public static function processImage() {
1161 $action = CRM_Utils_Request
::retrieve('action', 'String');
1162 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1163 // retrieve contact id in case of Profile context
1164 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1165 $cid = $cid ?
$cid : $id;
1166 if ($action & CRM_Core_Action
::DELETE
) {
1167 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1168 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1169 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1170 $session = CRM_Core_Session
::singleton();
1171 $toUrl = $session->popUserContext();
1172 CRM_Utils_System
::redirect($toUrl);
1178 * Function to set is_delete true or restore deleted contact.
1180 * @param CRM_Contact_DAO_Contact $contact
1181 * Contact DAO object.
1182 * @param bool $restore
1183 * True to set the is_delete = 1 else false to restore deleted contact,
1184 * i.e. is_delete = 0
1188 public static function contactTrashRestore($contact, $restore = FALSE) {
1189 $updateParams = array(
1190 'id' => $contact->id
,
1191 'is_deleted' => $restore ?
0 : 1,
1194 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1196 $params = array(1 => array($contact->id
, 'Integer'));
1198 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1199 CRM_Core_DAO
::executeQuery($query, $params);
1202 $contact->copyValues($updateParams);
1204 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
1206 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1212 * Get contact type for a contact.
1215 * Id of the contact whose contact type is needed.
1218 * contact_type if $id found else null ""
1220 public static function getContactType($id) {
1221 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1225 * Get contact sub type for a contact.
1228 * Id of the contact whose contact sub type is needed.
1230 * @param string $implodeDelimiter
1233 * contact_sub_type if $id found else null ""
1235 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1236 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1238 return $implodeDelimiter ?
NULL : array();
1241 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1243 if ($implodeDelimiter) {
1244 $subtype = implode($implodeDelimiter, $subtype);
1250 * Get pair of contact-type and sub-type for a contact.
1253 * Id of the contact whose contact sub/contact type is needed.
1257 public static function getContactTypes($id) {
1258 $params = array('id' => $id);
1260 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1263 array('contact_type', 'contact_sub_type')
1267 $contactTypes = array();
1268 if ($contact->contact_sub_type
) {
1269 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1271 array_unshift($contactTypes, $contact->contact_type
);
1273 return $contactTypes;
1276 CRM_Core_Error
::fatal();
1281 * Combine all the importable fields from the lower levels object.
1283 * The ordering is important, since currently we do not have a weight
1284 * scheme. Adding weight is super important
1286 * @param int|string $contactType contact Type
1287 * @param bool $status
1288 * Status is used to manipulate first title.
1289 * @param bool $showAll
1290 * If true returns all fields (includes disabled fields).
1291 * @param bool $isProfile
1292 * If its profile mode.
1293 * @param bool $checkPermission
1294 * If false, do not include permissioning clause (for custom data).
1296 * @param bool $withMultiCustomFields
1299 * array of importable Fields
1301 public static function importableFields(
1302 $contactType = 'Individual',
1306 $checkPermission = TRUE,
1307 $withMultiCustomFields = FALSE
1309 if (empty($contactType)) {
1310 $contactType = 'All';
1313 $cacheKeyString = "importableFields $contactType";
1314 $cacheKeyString .= $status ?
'_1' : '_0';
1315 $cacheKeyString .= $showAll ?
'_1' : '_0';
1316 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1317 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1319 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1322 // check if we can retrieve from database cache
1323 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1327 $fields = CRM_Contact_DAO_Contact
::import();
1329 // get the fields thar are meant for contact types
1330 if (in_array($contactType, array(
1336 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1339 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1340 CRM_Core_DAO_Phone
::import(),
1341 CRM_Core_DAO_Email
::import(),
1342 CRM_Core_DAO_IM
::import(TRUE),
1343 CRM_Core_DAO_OpenID
::import()
1346 $locationFields = array_merge($locationFields,
1347 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1355 foreach ($locationFields as $key => $field) {
1356 $locationFields[$key]['hasLocationType'] = TRUE;
1359 $fields = array_merge($fields, $locationFields);
1361 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1362 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1365 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1366 $fields['url']['hasWebsiteType'] = TRUE;
1368 if ($contactType != 'All') {
1369 $fields = array_merge($fields,
1370 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1375 $withMultiCustomFields
1378 //unset the fields, which are not related to their
1380 $commonValues = array(
1381 'Individual' => array(
1385 'organization_name',
1387 'Household' => array(
1397 'organization_name',
1405 'Organization' => array(
1420 foreach ($commonValues[$contactType] as $value) {
1421 unset($fields[$value]);
1425 foreach (array('Individual', 'Household', 'Organization') as $type) {
1426 $fields = array_merge($fields,
1427 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1432 $withMultiCustomFields
1439 $fields = array_merge($fields, array(
1441 'title' => ts('Group(s)'),
1445 'title' => ts('Tag(s)'),
1449 'title' => ts('Note'),
1452 'communication_style_id' => array(
1453 'title' => ts('Communication Style'),
1454 'name' => 'communication_style_id',
1459 //Sorting fields in alphabetical order(CRM-1507)
1460 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1462 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1465 self
::$_importableFields[$cacheKeyString] = $fields;
1469 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1470 self
::$_importableFields[$cacheKeyString]
1474 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1475 self
::$_importableFields[$cacheKeyString]
1483 * Combine all the exportable fields from the lower levels object.
1485 * Currently we are using importable fields as exportable fields
1487 * @param int|string $contactType contact Type
1488 * @param bool $status
1489 * True while exporting primary contacts.
1490 * @param bool $export
1491 * True when used during export.
1492 * @param bool $search
1493 * True when used during search, might conflict with export param?.
1495 * @param bool $withMultiRecord
1498 * array of exportable Fields
1500 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1501 if (empty($contactType)) {
1502 $contactType = 'All';
1505 $cacheKeyString = "exportableFields $contactType";
1506 $cacheKeyString .= $export ?
'_1' : '_0';
1507 $cacheKeyString .= $status ?
'_1' : '_0';
1508 $cacheKeyString .= $search ?
'_1' : '_0';
1509 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1510 //calculates custom fields takes into account the logged in user & caches that for all users
1511 //as an interim fix we will cache the fields by contact
1512 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1514 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1515 if (!self
::$_exportableFields) {
1516 self
::$_exportableFields = array();
1519 // check if we can retrieve from database cache
1520 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1523 $fields = CRM_Contact_DAO_Contact
::export();
1525 // The fields are meant for contact types.
1526 if (in_array($contactType, array(
1533 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1535 // add current employer for individuals
1536 $fields = array_merge($fields, array(
1537 'current_employer' =>
1539 'name' => 'organization_name',
1540 'title' => ts('Current Employer'),
1544 $locationType = array(
1545 'location_type' => array(
1546 'name' => 'location_type',
1547 'where' => 'civicrm_location_type.name',
1548 'title' => ts('Location Type'),
1552 $IMProvider = array(
1553 'im_provider' => array(
1554 'name' => 'im_provider',
1555 'where' => 'civicrm_im.provider_id',
1556 'title' => ts('IM Provider'),
1560 $locationFields = array_merge($locationType,
1561 CRM_Core_DAO_Address
::export(),
1562 CRM_Core_DAO_Phone
::export(),
1563 CRM_Core_DAO_Email
::export(),
1565 CRM_Core_DAO_IM
::export(TRUE),
1566 CRM_Core_DAO_OpenID
::export()
1569 $locationFields = array_merge($locationFields,
1570 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1573 foreach ($locationFields as $key => $field) {
1574 $locationFields[$key]['hasLocationType'] = TRUE;
1577 $fields = array_merge($fields, $locationFields);
1580 $fields = array_merge($fields,
1581 CRM_Core_DAO_Worldregion
::export()
1584 $fields = array_merge($fields,
1585 CRM_Contact_DAO_Contact
::export()
1589 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1591 if ($contactType != 'All') {
1592 $fields = array_merge($fields,
1593 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1602 $fields = array_merge($fields,
1603 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1607 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1610 $fields = array_merge($fields, array(
1612 'title' => ts('Group(s)'),
1616 'title' => ts('Tag(s)'),
1620 'title' => ts('Note(s)'),
1626 $fields = array_merge($fields, array(
1628 'title' => ts('Group(s)'),
1632 'title' => ts('Tag(s)'),
1636 'title' => ts('Note(s)'),
1642 //Sorting fields in alphabetical order(CRM-1507)
1643 foreach ($fields as $k => $v) {
1644 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1647 $fields = array_merge($sortArray, $fields);
1648 //unset the field which are not related to their contact type.
1649 if ($contactType != 'All') {
1650 $commonValues = array(
1651 'Individual' => array(
1655 'organization_name',
1656 'email_greeting_custom',
1657 'postal_greeting_custom',
1660 'Household' => array(
1670 'organization_name',
1678 'email_greeting_custom',
1679 'postal_greeting_custom',
1684 'Organization' => array(
1695 'email_greeting_custom',
1696 'postal_greeting_custom',
1706 foreach ($commonValues[$contactType] as $value) {
1707 unset($fields[$value]);
1711 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1713 self
::$_exportableFields[$cacheKeyString] = $fields;
1717 $fields = self
::$_exportableFields[$cacheKeyString];
1720 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1721 self
::$_exportableFields[$cacheKeyString]
1729 * Get the all contact details (Hierarchical).
1731 * @param int $contactId
1733 * @param array $fields
1739 public static function getHierContactDetails($contactId, &$fields) {
1740 $params = array(array('contact_id', '=', $contactId, 0, 0));
1743 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1745 // We don't know the contents of return properties, but we need the lower
1746 // level ids of the contact so add a few fields.
1747 $returnProperties['first_name'] = 1;
1748 $returnProperties['organization_name'] = 1;
1749 $returnProperties['household_name'] = 1;
1750 $returnProperties['contact_type'] = 1;
1751 $returnProperties['contact_sub_type'] = 1;
1752 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1756 * Given a set of flat profile style field names, create a hierarchy.
1758 * This is for the query to use, create the right sql.
1761 * @param int $contactId
1765 * A hierarchical property tree if appropriate
1767 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1768 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1770 $returnProperties = array();
1772 $multipleFields = array('website' => 'url');
1773 foreach ($fields as $name => $dontCare) {
1774 if (strpos($name, '-') !== FALSE) {
1775 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1777 if (!in_array($fieldName, $multipleFields)) {
1778 if ($id == 'Primary') {
1779 $locationTypeName = 1;
1782 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1783 if (!$locationTypeName) {
1788 if (empty($returnProperties['location'])) {
1789 $returnProperties['location'] = array();
1791 if (empty($returnProperties['location'][$locationTypeName])) {
1792 $returnProperties['location'][$locationTypeName] = array();
1793 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1795 if (in_array($fieldName, array(
1803 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1806 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1809 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1810 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1813 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1817 $returnProperties['website'][$id][$fieldName] = 1;
1821 $returnProperties[$name] = 1;
1825 return $returnProperties;
1829 * Return the primary location type of a contact.
1831 * $params int $contactId contact_id
1832 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1833 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1835 * @param int $contactId
1836 * @param bool $skipDefaultPriamry
1837 * @param null $block
1840 * $locationType location_type_id
1842 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1844 $entityBlock = array('contact_id' => $contactId);
1845 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1846 foreach ($blocks[$block] as $key => $value) {
1847 if (!empty($value['is_primary'])) {
1848 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1855 IF ( civicrm_email.location_type_id IS NULL,
1856 IF ( civicrm_address.location_type_id IS NULL,
1857 IF ( civicrm_phone.location_type_id IS NULL,
1858 IF ( civicrm_im.location_type_id IS NULL,
1859 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1860 ,civicrm_im.location_type_id)
1861 ,civicrm_phone.location_type_id)
1862 ,civicrm_address.location_type_id)
1863 ,civicrm_email.location_type_id) as locationType
1864 FROM civicrm_contact
1865 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1866 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1867 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1868 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1869 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1870 WHERE civicrm_contact.id = %1 ";
1872 $params = array(1 => array($contactId, 'Integer'));
1874 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1876 $locationType = NULL;
1877 if ($dao->fetch()) {
1878 $locationType = $dao->locationType
;
1881 if (isset($locationType)) {
1882 return $locationType;
1884 elseif ($skipDefaultPriamry) {
1885 // if there is no primary contact location then return null
1889 // if there is no primart contact location, then return default
1890 // location type of the system
1891 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1892 return $defaultLocationType->id
;
1897 * Get the display name, primary email and location type of a contact.
1900 * Id of the contact.
1903 * Array of display_name, email if found, do_not_email or (null,null,null)
1905 public static function getContactDetails($id) {
1906 // check if the contact type
1907 $contactType = self
::getContactType($id);
1909 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1912 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1913 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1914 WHERE civicrm_contact.id = %1
1915 ORDER BY civicrm_email.is_primary DESC";
1916 $params = array(1 => array($id, 'Integer'));
1917 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1919 if ($dao->fetch()) {
1920 if ($contactType == 'Individual') {
1921 if ($dao->first_name ||
$dao->last_name
) {
1922 $name = "{$dao->first_name} {$dao->last_name}";
1925 $name = $dao->display_name
;
1929 $name = $dao->display_name
;
1931 $email = $dao->email
;
1932 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1933 $onHold = $dao->on_hold ?
TRUE : FALSE;
1934 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1935 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1937 return array(NULL, NULL, NULL, NULL, NULL);
1941 * Add/edit/register contacts through profile.
1943 * @param array $params
1944 * Array of profile fields to be edited/added.
1945 * @param array $fields
1946 * Array of fields from UFGroup.
1947 * @param int $contactID
1948 * Id of the contact to be edited/added.
1949 * @param int $addToGroupID
1950 * Specifies the default group to which contact is added.
1951 * @param int $ufGroupId
1952 * Uf group id (profile id).
1953 * @param string $ctype
1954 * @param bool $visibility
1955 * Basically lets us know where this request is coming from.
1956 * if via a profile from web, we restrict what groups are changed
1959 * contact id created/edited
1961 public static function createProfileContact(
1965 $addToGroupID = NULL,
1970 // add ufGroupID to params array ( CRM-2012 )
1972 $params['uf_group_id'] = $ufGroupId;
1974 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1976 // If a user has logged in, or accessed via a checksum
1977 // Then deliberately 'blanking' a value in the profile should remove it from their record
1978 $session = CRM_Core_Session
::singleton();
1979 $params['updateBlankLocInfo'] = TRUE;
1980 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1981 $params['updateBlankLocInfo'] = FALSE;
1986 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1990 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1993 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1995 // manage is_opt_out
1996 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1997 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1998 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1999 $data['is_opt_out'] = $isOptOut;
2000 // on change, create new civicrm_subscription_history entry
2001 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2003 'contact_id' => $contactDetails['contact_id'],
2004 'status' => $isOptOut ?
'Removed' : 'Added',
2007 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2011 $contact = self
::create($data);
2013 // contact is null if the profile does not have any contact fields
2015 $contactID = $contact->id
;
2018 if (empty($contactID)) {
2019 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
2022 // Process group and tag
2023 if (!empty($fields['group'])) {
2025 // this for sure means we are coming in via profile since i added it to fix
2026 // removing contacts from user groups -- lobo
2030 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2033 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2034 // Convert comma separated form values from select2 v3
2035 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2036 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2039 //to add profile in default group
2040 if (is_array($addToGroupID)) {
2041 $contactIds = array($contactID);
2042 foreach ($addToGroupID as $groupId) {
2043 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2046 elseif ($addToGroupID) {
2047 $contactIds = array($contactID);
2048 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2051 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
2054 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2057 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2063 * Format profile contact parameters.
2065 * @param array $params
2067 * @param int $contactID
2068 * @param int $ufGroupId
2069 * @param null $ctype
2070 * @param bool $skipCustom
2074 public static function formatProfileContactParams(
2083 $data = $contactDetails = array();
2085 // get the contact details (hier)
2087 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
2089 $contactDetails = $details[$contactID];
2090 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
2091 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
2094 //we should get contact type only if contact
2096 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2098 //special case to handle profile with only contact fields
2099 if ($data['contact_type'] == 'Contact') {
2100 $data['contact_type'] = 'Individual';
2102 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2103 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2107 $data['contact_type'] = $ctype;
2110 $data['contact_type'] = 'Individual';
2114 //fix contact sub type CRM-5125
2115 if (array_key_exists('contact_sub_type', $params) &&
2116 !empty($params['contact_sub_type'])
2118 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2120 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2121 !empty($params['contact_sub_type_hidden'])
2123 // if profile was used, and had any subtype, we obtain it from there
2124 //CRM-13596 - add to existing contact types, rather than overwriting
2125 if (empty($data['contact_sub_type'])) {
2126 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2127 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2130 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2131 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2132 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2133 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2134 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2139 if ($ctype == 'Organization') {
2140 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2142 elseif ($ctype == 'Household') {
2143 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2146 $locationType = array();
2151 $data['contact_id'] = $contactID;
2152 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2155 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2156 $defaultLocationId = $defaultLocation->id
;
2159 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2161 $blocks = array('email', 'phone', 'im', 'openid');
2163 $multiplFields = array('url');
2164 // prevent overwritten of formatted array, reset all block from
2165 // params if it is not in valid format (since import pass valid format)
2166 foreach ($blocks as $blk) {
2167 if (array_key_exists($blk, $params) &&
2168 !is_array($params[$blk])
2170 unset($params[$blk]);
2174 $primaryPhoneLoc = NULL;
2175 $session = CRM_Core_Session
::singleton();
2176 foreach ($params as $key => $value) {
2177 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2179 if ($locTypeId == 'Primary') {
2181 if (in_array($fieldName, $blocks)) {
2182 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2185 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2187 $primaryLocationType = $locTypeId;
2190 $locTypeId = $defaultLocationId;
2194 if (is_numeric($locTypeId) &&
2195 !in_array($fieldName, $multiplFields) &&
2196 substr($fieldName, 0, 7) != 'custom_'
2198 $index = $locTypeId;
2200 if (is_numeric($typeId)) {
2201 $index .= '-' . $typeId;
2203 if (!in_array($index, $locationType)) {
2204 $locationType[$count] = $index;
2208 $loc = CRM_Utils_Array
::key($index, $locationType);
2210 $blockName = self
::getLocationEntityForKey($fieldName);
2212 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2214 //set is_billing true, for location type "Billing"
2215 if ($locTypeId == $billingLocationTypeId) {
2216 $data[$blockName][$loc]['is_billing'] = 1;
2220 //get the primary location type
2221 if ($locTypeId == $primaryLocationType) {
2222 $data[$blockName][$loc]['is_primary'] = 1;
2225 elseif ($locTypeId == $defaultLocationId) {
2226 $data[$blockName][$loc]['is_primary'] = 1;
2229 if (in_array($fieldName, array('phone'))) {
2231 $data['phone'][$loc]['phone_type_id'] = $typeId;
2234 $data['phone'][$loc]['phone_type_id'] = '';
2236 $data['phone'][$loc]['phone'] = $value;
2238 //special case to handle primary phone with different phone types
2239 // in this case we make first phone type as primary
2240 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2241 $primaryPhoneLoc = $loc;
2244 if ($loc != $primaryPhoneLoc) {
2245 unset($data['phone'][$loc]['is_primary']);
2248 elseif ($fieldName == 'email') {
2249 $data['email'][$loc]['email'] = $value;
2250 if (empty($contactID)) {
2251 $data['email'][$loc]['is_primary'] = 1;
2254 elseif ($fieldName == 'im') {
2255 if (isset($params[$key . '-provider_id'])) {
2256 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2258 if (strpos($key, '-provider_id') !== FALSE) {
2259 $data['im'][$loc]['provider_id'] = $params[$key];
2262 $data['im'][$loc]['name'] = $value;
2265 elseif ($fieldName == 'openid') {
2266 $data['openid'][$loc]['openid'] = $value;
2269 if ($fieldName === 'state_province') {
2271 if (is_numeric($value) && ((int ) $value) >= 1000) {
2272 $data['address'][$loc]['state_province_id'] = $value;
2274 elseif (empty($value)) {
2275 $data['address'][$loc]['state_province_id'] = '';
2278 $data['address'][$loc]['state_province'] = $value;
2281 elseif ($fieldName === 'country') {
2283 if (is_numeric($value) && ((int ) $value) >= 1000
2285 $data['address'][$loc]['country_id'] = $value;
2287 elseif (empty($value)) {
2288 $data['address'][$loc]['country_id'] = '';
2291 $data['address'][$loc]['country'] = $value;
2294 elseif ($fieldName === 'county') {
2295 $data['address'][$loc]['county_id'] = $value;
2297 elseif ($fieldName == 'address_name') {
2298 $data['address'][$loc]['name'] = $value;
2300 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2301 $data['address'][$loc][substr($fieldName, 8)] = $value;
2304 $data[$blockName][$loc][$fieldName] = $value;
2309 if (substr($key, 0, 4) === 'url-') {
2310 $websiteField = explode('-', $key);
2311 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2312 $data['website'][$websiteField[1]]['url'] = $value;
2314 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2315 //save email/postal greeting and addressee values if any, CRM-4575
2316 $data[$key . '_id'] = $value;
2318 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2319 // for autocomplete transfer hidden value instead of label
2320 if ($params[$key] && isset($params[$key . '_id'])) {
2321 $value = $params[$key . '_id'];
2324 // we need to append time with date
2325 if ($params[$key] && isset($params[$key . '_time'])) {
2326 $value .= ' ' . $params[$key . '_time'];
2329 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2330 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2331 ($value == '' ||
!isset($value))
2337 if (!empty($params['customRecordValues'])) {
2338 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2339 foreach ($params['customRecordValues'] as $recId => $customFields) {
2340 if (is_array($customFields) && !empty($customFields)) {
2341 foreach ($customFields as $customFieldName) {
2342 if ($customFieldName == $key) {
2352 //CRM-13596 - check for contact_sub_type_hidden first
2353 if (array_key_exists('contact_sub_type_hidden', $params)) {
2354 $type = $params['contact_sub_type_hidden'];
2357 $type = $data['contact_type'];
2358 if (!empty($data['contact_sub_type'])) {
2359 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2363 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2373 elseif ($key == 'edit') {
2377 if ($key == 'location') {
2378 foreach ($value as $locationTypeId => $field) {
2379 foreach ($field as $block => $val) {
2380 if ($block == 'address' && array_key_exists('address_name', $val)) {
2381 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2386 if ($key == 'phone' && isset($params['phone_ext'])) {
2387 $data[$key] = $value;
2388 foreach ($value as $cnt => $phoneBlock) {
2389 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2390 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2394 elseif (in_array($key,
2405 ($value == '' ||
!isset($value)) &&
2406 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2407 ($key == 'current_employer' && empty($params['current_employer']))) {
2408 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2409 // to avoid update with empty values
2413 $data[$key] = $value;
2419 if (!isset($data['contact_type'])) {
2420 $data['contact_type'] = 'Individual';
2423 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2424 $privacy = CRM_Core_SelectValues
::privacy();
2425 foreach ($privacy as $key => $value) {
2426 if (array_key_exists($key, $fields)) {
2427 // do not reset values for existing contacts, if fields are added to a profile
2428 if (array_key_exists($key, $params)) {
2429 $data[$key] = $params[$key];
2430 if (empty($params[$key])) {
2434 elseif (!$contactID) {
2440 return array($data, $contactDetails);
2444 * Find the get contact details.
2446 * This function does not respect ACLs for now, which might need to be rectified at some
2447 * stage based on how its used.
2449 * @param string $mail
2450 * Primary email address of the contact.
2451 * @param string $ctype
2454 * @return object|null
2455 * $dao contact details
2457 public static function matchContactOnEmail($mail, $ctype = NULL) {
2458 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2459 $mail = $strtolower(trim($mail));
2461 SELECT civicrm_contact.id as contact_id,
2462 civicrm_contact.hash as hash,
2463 civicrm_contact.contact_type as contact_type,
2464 civicrm_contact.contact_sub_type as contact_sub_type
2465 FROM civicrm_contact
2466 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2468 if (Civi
::settings()->get('uniq_email_per_site')) {
2469 // try to find a match within a site (multisite).
2470 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2471 if (!empty($groups)) {
2473 INNER JOIN civicrm_group_contact gc ON
2474 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2479 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2480 $p = array(1 => array($mail, 'String'));
2483 $query .= " AND civicrm_contact.contact_type = %3";
2484 $p[3] = array($ctype, 'String');
2487 $query .= " ORDER BY civicrm_email.is_primary DESC";
2489 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2491 if ($dao->fetch()) {
2498 * Find the contact details associated with an OpenID.
2500 * @param string $openId
2501 * OpenId of the contact.
2502 * @param string $ctype
2505 * @return object|null
2506 * $dao contact details
2508 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2509 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2510 $openId = $strtolower(trim($openId));
2512 SELECT civicrm_contact.id as contact_id,
2513 civicrm_contact.hash as hash,
2514 civicrm_contact.contact_type as contact_type,
2515 civicrm_contact.contact_sub_type as contact_sub_type
2516 FROM civicrm_contact
2517 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2518 WHERE civicrm_openid.openid = %1";
2519 $p = array(1 => array($openId, 'String'));
2522 $query .= " AND civicrm_contact.contact_type = %3";
2523 $p[3] = array($ctype, 'String');
2526 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2528 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2530 if ($dao->fetch()) {
2537 * Get primary email of the contact.
2539 * @param int $contactID
2543 * Email address if present else null
2545 public static function getPrimaryEmail($contactID) {
2546 // fetch the primary email
2548 SELECT civicrm_email.email as email
2549 FROM civicrm_contact
2550 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2551 WHERE civicrm_email.is_primary = 1
2552 AND civicrm_contact.id = %1";
2553 $p = array(1 => array($contactID, 'Integer'));
2554 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2557 if ($dao->fetch()) {
2558 $email = $dao->email
;
2564 * Function to get primary OpenID of the contact.
2566 * @param int $contactID
2570 * >openid OpenID if present else null
2572 public static function getPrimaryOpenId($contactID) {
2573 // fetch the primary OpenID
2575 SELECT civicrm_openid.openid as openid
2576 FROM civicrm_contact
2577 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2578 WHERE civicrm_contact.id = %1
2579 AND civicrm_openid.is_primary = 1";
2580 $p = array(1 => array($contactID, 'Integer'));
2581 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2584 if ($dao->fetch()) {
2585 $openId = $dao->openid
;
2591 * Fetch the object and store the values in the values array.
2593 * @param array $params
2594 * Input parameters to find object.
2595 * @param array $values
2596 * Output values of the object.
2598 * @return CRM_Contact_BAO_Contact|null
2599 * The found object or null
2601 public static function getValues(&$params, &$values) {
2602 $contact = new CRM_Contact_BAO_Contact();
2604 $contact->copyValues($params);
2606 if ($contact->find(TRUE)) {
2608 CRM_Core_DAO
::storeValues($contact, $values);
2611 foreach (self
::$_commPrefs as $name) {
2612 if (isset($contact->$name)) {
2613 $privacy[$name] = $contact->$name;
2617 if (!empty($privacy)) {
2618 $values['privacy'] = $privacy;
2621 // communication Prefferance
2622 $preffComm = $comm = array();
2623 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2624 $contact->preferred_communication_method
2626 foreach ($comm as $value) {
2627 $preffComm[$value] = 1;
2629 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2632 'preferred_communication_method' => array(
2633 'newName' => 'preferred_communication_method_display',
2634 'groupName' => 'preferred_communication_method',
2638 // @todo This can be figured out from metadata & we can avoid the uncached query.
2639 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2641 $values['preferred_communication_method'] = $preffComm;
2642 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2644 if ($contact->preferred_mail_format
) {
2645 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2646 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2649 // get preferred languages
2650 if (!empty($contact->preferred_language
)) {
2651 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2654 // Calculating Year difference
2655 if ($contact->birth_date
) {
2656 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2657 if ($birthDate < date('Ymd')) {
2658 $age = CRM_Utils_Date
::calculateAge($birthDate);
2659 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2660 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2664 $contact->contact_id
= $contact->id
;
2672 * Given the component name and returns the count of participation of contact.
2674 * @param string $component
2675 * Input component name.
2676 * @param int $contactId
2678 * @param string $tableName
2679 * Optional tableName if component is custom group.
2682 * total number in database
2684 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2686 switch ($component) {
2688 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2691 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2692 CRM_Contact_BAO_Relationship
::CURRENT
,
2701 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2704 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2707 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2710 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2712 case 'contribution':
2713 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2716 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2719 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2722 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2725 return CRM_Case_BAO_Case
::caseCount($contactId);
2728 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2732 'contact_id' => $contactId,
2735 'context' => 'activity',
2737 return CRM_Activity_BAO_Activity
::deprecatedGetActivitiesCount($input);
2740 $params = array('contact_id' => $contactId);
2741 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2744 $custom = explode('_', $component);
2745 if ($custom['0'] = 'custom') {
2747 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2749 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2750 return CRM_Core_DAO
::singleValueQuery($queryString);
2756 * Update contact greetings if an update has resulted in a custom field change.
2758 * @param array $updatedFields
2759 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2760 * @param array $contactParams
2761 * Parameters known about the contact. At minimum array('contact_id' => x).
2762 * Fields in this array will take precedence over DB fields (so far only
2763 * in the case of greeting id fields).
2765 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2766 $contactID = $contactParams['contact_id'];
2767 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2768 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2769 if (!empty($tokens['all']['contact'])) {
2770 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2771 if (!empty($affectedTokens)) {
2772 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2773 $contact = new CRM_Contact_BAO_Contact();
2774 $contact->id
= $contactID;
2775 CRM_Contact_BAO_Contact
::processGreetings($contact);
2781 * Process greetings and cache.
2783 * @param object $contact
2784 * Contact object after save.
2786 public static function processGreetings(&$contact) {
2788 //@todo this function does a lot of unnecessary loading.
2789 // ensureGreetingParamsAreSet now makes sure that the contact is
2790 // loaded and using updateGreetingsOnTokenFieldChange
2791 // allows us the possibility of only doing an update if required.
2793 // The contact object has not always required the
2794 // fields that are required to calculate greetings
2795 // so we need to retrieve it again.
2796 if ($contact->_query
!== FALSE) {
2797 $contact->find(TRUE);
2800 // store object values to an array
2801 $contactDetails = array();
2802 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2803 $contactDetails = array(array($contact->id
=> $contactDetails));
2805 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2806 $updateQueryString = array();
2808 //cache email and postal greeting to greeting display
2809 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2810 $emailGreetingString = $contact->email_greeting_custom
;
2812 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2813 // the filter value for Individual contact type is set to 1
2815 'contact_type' => $contact->contact_type
,
2816 'greeting_type' => 'email_greeting',
2819 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2820 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2821 $updateQueryString[] = " email_greeting_custom = NULL ";
2824 if ($contact->email_greeting_custom
) {
2825 $updateQueryString[] = " email_greeting_display = NULL ";
2829 if ($emailGreetingString) {
2830 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2833 'CRM_Contact_BAO_Contact'
2835 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2836 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2840 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2841 $postalGreetingString = $contact->postal_greeting_custom
;
2843 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2845 'contact_type' => $contact->contact_type
,
2846 'greeting_type' => 'postal_greeting',
2848 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2849 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2850 $updateQueryString[] = " postal_greeting_custom = NULL ";
2853 if ($contact->postal_greeting_custom
) {
2854 $updateQueryString[] = " postal_greeting_display = NULL ";
2858 if ($postalGreetingString) {
2859 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2862 'CRM_Contact_BAO_Contact'
2864 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2865 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2869 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2870 $addresseeString = $contact->addressee_custom
;
2872 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2874 'contact_type' => $contact->contact_type
,
2875 'greeting_type' => 'addressee',
2878 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2879 $addresseeString = $addressee[$contact->addressee_id
];
2880 $updateQueryString[] = " addressee_custom = NULL ";
2883 if ($contact->addressee_custom
) {
2884 $updateQueryString[] = " addressee_display = NULL ";
2888 if ($addresseeString) {
2889 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2892 'CRM_Contact_BAO_Contact'
2894 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2895 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2898 if (!empty($updateQueryString)) {
2899 $updateQueryString = implode(',', $updateQueryString);
2900 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2901 CRM_Core_DAO
::executeQuery($queryString);
2906 * Retrieve loc block ids w/ given condition.
2908 * @param int $contactId
2910 * @param array $criteria
2911 * Key => value pair which should be.
2912 * fulfill by return record ids.
2913 * @param string $condOperator
2914 * Operator use for grouping multiple conditions.
2917 * loc block ids which fulfill condition.
2919 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2920 $locBlockIds = array();
2922 return $locBlockIds;
2925 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2926 $name = strtolower($block);
2927 $className = "CRM_Core_DAO_$block";
2928 $blockDAO = new $className();
2930 // build the condition.
2931 if (is_array($criteria)) {
2932 $fields = $blockDAO->fields();
2933 $conditions = array();
2934 foreach ($criteria as $field => $value) {
2935 if (array_key_exists($field, $fields)) {
2936 $cond = "( $field = $value )";
2937 // value might be zero or null.
2938 if (!$value ||
strtolower($value) == 'null') {
2939 $cond = "( $field = 0 OR $field IS NULL )";
2941 $conditions[] = $cond;
2944 if (!empty($conditions)) {
2945 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2949 $blockDAO->contact_id
= $contactId;
2951 while ($blockDAO->fetch()) {
2952 $locBlockIds[$name][] = $blockDAO->id
;
2957 return $locBlockIds;
2961 * Build context menu items.
2963 * @param int $contactId
2966 * Array of context menu for logged in user.
2968 public static function contextMenu($contactId = NULL) {
2971 'title' => ts('View Contact'),
2973 'ref' => 'view-contact',
2974 'class' => 'no-popup',
2976 'permissions' => array('view all contacts'),
2979 'title' => ts('Edit Contact'),
2981 'ref' => 'edit-contact',
2982 'class' => 'no-popup',
2984 'permissions' => array('edit all contacts'),
2987 'title' => ts('Delete Contact'),
2989 'ref' => 'delete-contact',
2991 'permissions' => array('access deleted contacts', 'delete contacts'),
2993 'contribution' => array(
2994 'title' => ts('Add Contribution'),
2996 'ref' => 'new-contribution',
2997 'key' => 'contribution',
2998 'tab' => 'contribute',
2999 'component' => 'CiviContribute',
3000 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
3001 'reset=1&action=add&context=contribution'
3003 'permissions' => array(
3004 'access CiviContribute',
3005 'edit contributions',
3008 'participant' => array(
3009 'title' => ts('Register for Event'),
3011 'ref' => 'new-participant',
3012 'key' => 'participant',
3013 'tab' => 'participant',
3014 'component' => 'CiviEvent',
3015 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3016 'permissions' => array(
3018 'edit event participants',
3021 'activity' => array(
3022 'title' => ts('Record Activity'),
3024 'ref' => 'new-activity',
3025 'key' => 'activity',
3026 'permissions' => array('edit all contacts'),
3029 'title' => ts('Add Pledge'),
3031 'ref' => 'new-pledge',
3034 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3035 'reset=1&action=add&context=pledge'
3037 'component' => 'CiviPledge',
3038 'permissions' => array(
3039 'access CiviPledge',
3043 'membership' => array(
3044 'title' => ts('Add Membership'),
3046 'ref' => 'new-membership',
3047 'key' => 'membership',
3049 'component' => 'CiviMember',
3050 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3051 'reset=1&action=add&context=membership'
3053 'permissions' => array(
3054 'access CiviMember',
3059 'title' => ts('Add Case'),
3061 'ref' => 'new-case',
3064 'component' => 'CiviCase',
3065 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3066 'permissions' => array('add cases'),
3069 'title' => ts('Add Grant'),
3071 'ref' => 'new-grant',
3074 'component' => 'CiviGrant',
3075 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3076 'reset=1&action=add&context=grant'
3078 'permissions' => array('edit grants'),
3081 'title' => ts('Add Relationship'),
3083 'ref' => 'new-relationship',
3086 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3087 'reset=1&action=add'
3089 'permissions' => array('edit all contacts'),
3092 'title' => ts('Add Note'),
3094 'ref' => 'new-note',
3097 'class' => 'medium-popup',
3098 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3099 'reset=1&action=add'
3101 'permissions' => array('edit all contacts'),
3104 'title' => ts('Send an Email'),
3106 'ref' => 'new-email',
3108 'permissions' => array('view all contacts'),
3111 'title' => ts('Add to Group'),
3113 'ref' => 'group-add-contact',
3116 'permissions' => array('edit groups'),
3119 'title' => ts('Tag Contact'),
3121 'ref' => 'tag-contact',
3124 'permissions' => array('edit all contacts'),
3128 $menu['otherActions'] = array(
3130 'title' => ts('Print Summary'),
3131 'description' => ts('Printer-friendly view of this page.'),
3133 'ref' => 'crm-contact-print',
3136 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3140 'icon' => 'crm-i fa-print',
3143 'title' => ts('vCard'),
3144 'description' => ts('vCard record for this contact.'),
3146 'ref' => 'crm-contact-vcard',
3149 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3153 'icon' => 'crm-i fa-list-alt',
3157 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3158 $menu['otherActions']['dashboard'] = array(
3159 'title' => ts('Contact Dashboard'),
3160 'description' => ts('Contact Dashboard'),
3162 'ref' => 'crm-contact-dashboard',
3163 'key' => 'dashboard',
3164 'tab' => 'dashboard',
3165 'class' => 'dashboard',
3166 // NOTE: As an alternative you can also build url on CMS specific way
3167 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3168 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3169 'icon' => 'crm-i fa-tachometer',
3173 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3175 $menu['otherActions']['user-record'] = array(
3176 'title' => ts('User Record'),
3177 'description' => ts('User Record'),
3179 'ref' => 'crm-contact-user-record',
3180 'key' => 'user-record',
3181 'tab' => 'user-record',
3182 'class' => 'user-record',
3183 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3184 'icon' => 'crm-i fa-user',
3187 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3188 $menu['otherActions']['user-add'] = array(
3189 'title' => ts('Create User Record'),
3190 'description' => ts('Create User Record'),
3192 'ref' => 'crm-contact-user-add',
3193 'key' => 'user-add',
3194 'tab' => 'user-add',
3195 'class' => 'user-add',
3196 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3197 'icon' => 'crm-i fa-user-plus',
3201 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3202 //1. check for component is active.
3203 //2. check for user permissions.
3204 //3. check for acls.
3205 //3. edit and view contact are directly accessible to user.
3207 $aclPermissionedTasks = array(
3212 'group-add-contact',
3216 $corePermission = CRM_Core_Permission
::getPermission();
3218 $contextMenu = array();
3219 foreach ($menu as $key => $values) {
3220 if ($key != 'otherActions') {
3222 // user does not have necessary permissions.
3223 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3226 // build directly accessible action menu.
3227 if (in_array($values['ref'], array(
3231 $contextMenu['primaryActions'][$key] = array(
3232 'title' => $values['title'],
3233 'ref' => $values['ref'],
3234 'class' => CRM_Utils_Array
::value('class', $values),
3235 'key' => $values['key'],
3240 // finally get menu item for -more- action widget.
3241 $contextMenu['moreActions'][$values['weight']] = array(
3242 'title' => $values['title'],
3243 'ref' => $values['ref'],
3244 'href' => CRM_Utils_Array
::value('href', $values),
3245 'tab' => CRM_Utils_Array
::value('tab', $values),
3246 'class' => CRM_Utils_Array
::value('class', $values),
3247 'key' => $values['key'],
3251 foreach ($values as $value) {
3252 // user does not have necessary permissions.
3253 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3257 // finally get menu item for -more- action widget.
3258 $contextMenu['otherActions'][$value['weight']] = array(
3259 'title' => $value['title'],
3260 'ref' => $value['ref'],
3261 'href' => CRM_Utils_Array
::value('href', $value),
3262 'tab' => CRM_Utils_Array
::value('tab', $value),
3263 'class' => CRM_Utils_Array
::value('class', $value),
3264 'icon' => CRM_Utils_Array
::value('icon', $value),
3265 'key' => $value['key'],
3271 ksort($contextMenu['moreActions']);
3272 ksort($contextMenu['otherActions']);
3274 return $contextMenu;
3278 * Check if user has permissions to access items in action menu.
3280 * @param array $aclPermissionedTasks
3281 * Array containing ACL related tasks.
3282 * @param string $corePermission
3283 * The permission of the user (edit or view or null).
3284 * @param array $menuOptions
3285 * Array containing params of the menu (title, href, etc).
3288 * TRUE if user has all permissions, FALSE if otherwise.
3290 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3291 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3293 // if component action - make sure component is enable.
3294 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3298 // make sure user has all required permissions.
3299 $hasAllPermissions = FALSE;
3301 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3302 if (!is_array($permissions) ||
empty($permissions)) {
3303 $hasAllPermissions = TRUE;
3306 // iterate for required permissions in given permissions array.
3307 if (!$hasAllPermissions) {
3308 $hasPermissions = 0;
3309 foreach ($permissions as $permission) {
3310 if (CRM_Core_Permission
::check($permission)) {
3315 if (count($permissions) == $hasPermissions) {
3316 $hasAllPermissions = TRUE;
3319 // if still user does not have required permissions, check acl.
3320 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3321 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3322 $corePermission == CRM_Core_Permission
::EDIT
3324 $hasAllPermissions = TRUE;
3326 elseif (in_array($menuOptions['ref'], array(
3329 // grant permissions for these tasks.
3330 $hasAllPermissions = TRUE;
3335 return $hasAllPermissions;
3339 * Retrieve display name of contact that address is shared.
3341 * This is based on $masterAddressId or $contactId .
3343 * @param int $masterAddressId
3345 * @param int $contactId
3346 * Contact id. (deprecated - do not use)
3348 * @return string|null
3349 * the found display name or null.
3351 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3352 $masterDisplayName = NULL;
3353 if (!$masterAddressId) {
3354 return $masterDisplayName;
3358 SELECT display_name from civicrm_contact
3359 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3360 WHERE civicrm_address.id = " . $masterAddressId;
3362 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3363 return $masterDisplayName;
3367 * Get the creation/modification times for a contact.
3369 * @param int $contactId
3372 * Dates - ('created_date' => $, 'modified_date' => $)
3374 public static function getTimestamps($contactId) {
3375 $timestamps = CRM_Core_DAO
::executeQuery(
3376 'SELECT created_date, modified_date
3377 FROM civicrm_contact
3380 1 => array($contactId, 'Integer'),
3383 if ($timestamps->fetch()) {
3385 'created_date' => $timestamps->created_date
,
3386 'modified_date' => $timestamps->modified_date
,
3395 * Get a list of triggers for the contact table.
3397 * @see hook_civicrm_triggerInfo
3398 * @see CRM_Core_DAO::triggerRebuild
3399 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3402 * @param null $tableName
3404 public static function triggerInfo(&$info, $tableName = NULL) {
3405 //during upgrade, first check for valid version and then create triggers
3406 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3407 if (CRM_Core_Config
::isUpgradeMode()) {
3408 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3409 //if current version is less than 4.3.alpha1 dont create below triggers
3410 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3415 // Modifications to these records should update the contact timestamps.
3416 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3417 ->setRelations(array(
3418 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3419 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3420 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3421 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3422 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3425 ->alterTriggerInfo($info, $tableName);
3427 // Update phone table to populate phone_numeric field
3428 if (!$tableName ||
$tableName == 'civicrm_phone') {
3429 // Define stored sql function needed for phones
3430 $sqlTriggers = Civi
::service('sql_triggers');
3431 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3432 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3434 'table' => array('civicrm_phone'),
3436 'event' => array('INSERT', 'UPDATE'),
3437 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3443 * Check if contact is being used in civicrm_domain based on $contactId.
3445 * @param int $contactId
3449 * true if present else false.
3451 public static function checkDomainContact($contactId) {
3455 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3466 * Get options for a given contact field.
3468 * @see CRM_Core_DAO::buildOptions
3470 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3471 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3473 * @param string $fieldName
3474 * @param string $context
3475 * @see CRM_Core_DAO::buildOptionsContext
3476 * @param array $props
3477 * whatever is known about this dao object.
3479 * @return array|bool
3481 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3483 // Special logic for fields whose options depend on context or properties
3484 switch ($fieldName) {
3485 case 'contact_sub_type':
3486 if (!empty($props['contact_type'])) {
3487 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3491 case 'contact_type':
3492 if ($context == 'search') {
3493 // CRM-15495 - EntityRef filters and basic search forms expect this format
3494 // FIXME: Search builder does not
3495 return CRM_Contact_BAO_ContactType
::getSelectElements();
3499 // The contact api supports some related entities so we'll honor that by fetching their options
3502 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3506 $props['entity_table'] = 'civicrm_contact';
3507 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3509 case 'state_province_id':
3510 case 'state_province':
3511 case 'state_province_name':
3516 case 'worldregion_id':
3517 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3520 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3524 * Delete a contact-related object that has an 'is_primary' field.
3526 * Ensures that is_primary gets assigned to another object if available
3527 * Also calls pre/post hooks
3529 * @param string $type
3533 public static function deleteObjectWithPrimary($type, $id) {
3534 if (!$id ||
!is_numeric($id)) {
3537 $daoName = "CRM_Core_DAO_$type";
3538 $obj = new $daoName();
3542 if ($obj->fetch()) {
3543 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3544 $contactId = $obj->contact_id
;
3550 // is_primary is only relavent if this field belongs to a contact
3552 $dao = new $daoName();
3553 $dao->contact_id
= $contactId;
3554 $dao->is_primary
= 1;
3555 // Pick another record to be primary (if one isn't already)
3556 if (!$dao->find(TRUE)) {
3557 $dao->is_primary
= 0;
3559 if ($dao->fetch()) {
3560 $dao->is_primary
= 1;
3565 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3573 public function addSelectWhereClause() {
3574 // We always return an array with these keys, even if they are empty,
3575 // because this tells the query builder that we have considered these fields for acls
3577 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3578 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
array() : array('!= 1'),
3580 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3585 * Get any existing duplicate contacts based on the input parameters.
3587 * @param array $input
3588 * Input parameters to be matched.
3589 * @param string $contactType
3590 * @param string $rule
3593 * @param $excludedContactIDs
3594 * An array of ids not to be included in the results.
3595 * @param bool $checkPermissions
3596 * @param int $ruleGroupID
3597 * ID of the rule group to be used if an override is desirable.
3601 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3602 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3603 $dedupeParams['check_permission'] = $checkPermissions;
3604 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3609 * Get the first duplicate contacts based on the input parameters.
3611 * @param array $input
3612 * Input parameters to be matched.
3613 * @param string $contactType
3614 * @param string $rule
3617 * @param $excludedContactIDs
3618 * An array of ids not to be included in the results.
3619 * @param bool $checkPermissions
3620 * @param int $ruleGroupID
3621 * ID of the rule group to be used if an override is desirable.
3625 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3626 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID);
3634 * Check if a field is associated with an entity that has a location type.
3636 * (ie. is an address, phone, email etc field).
3638 * @param string $fieldTitle
3639 * Title of the field (not the name - create a new function for that if required).
3643 public static function isFieldHasLocationType($fieldTitle) {
3644 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3645 if ($field['title'] === $fieldTitle) {
3646 return CRM_Utils_Array
::value('hasLocationType', $field);
3653 * @param array $appendProfiles
3654 * Name of profile(s) to append to each link.
3658 public static function getEntityRefCreateLinks($appendProfiles = []) {
3659 // You'd think that "create contacts" would be the permission to check,
3660 // But new contact popups are profile forms and those use their own permissions.
3661 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3665 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3666 $profiles[] = 'new_' . strtolower($contactType);
3668 $retrieved = civicrm_api3('uf_group', 'get', [
3669 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3672 $links = $append = [];
3673 if (!empty($retrieved['values'])) {
3675 'individual' => 'fa-user',
3676 'organization' => 'fa-building',
3677 'household' => 'fa-home',
3679 foreach ($retrieved['values'] as $id => $profile) {
3680 if (in_array($profile['name'], $profiles)) {
3682 'label' => $profile['title'],
3683 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3684 NULL, NULL, FALSE, FALSE, TRUE),
3685 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3686 'icon' => CRM_Utils_Array
::value(str_replace('new_', '', $profile['name']), $icons),
3693 foreach ($append as $id) {
3694 foreach ($links as &$link) {
3695 $link['url'] .= ",$id";
3705 public static function getEntityRefFilters() {
3707 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3708 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3709 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3710 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3711 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3712 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3713 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3714 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3715 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3716 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],