3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
{
36 * SQL function used to format the phone_numeric field via trigger.
37 * @see self::triggerInfo()
39 * Note that this is also used by the 4.3 upgrade script.
40 * @see CRM_Upgrade_Incremental_php_FourThree
42 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
43 const CREATE_STRIP_FUNCTION_43
= "
44 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
45 RETURNS VARCHAR(255) CHARACTER SET utf8
49 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
50 DECLARE iterator INT DEFAULT 1;
51 WHILE iterator < (LENGTH(input) + 1) DO
52 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
53 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
55 SET iterator = iterator + 1;
61 * The types of communication preferences.
65 public static $_commPrefs = array(
78 public static $_greetingTypes = array(
85 * Static field for all the contact information that we can potentially import.
89 public static $_importableFields = array();
92 * Static field for all the contact information that we can potentially export.
96 public static $_exportableFields = NULL;
101 public function __construct() {
102 parent
::__construct();
106 * Takes an associative array and creates a contact object.
108 * The function extracts all the params it needs to initialize the create a
109 * contact object. the params array could contain additional unused name/value
112 * @param array $params
113 * (reference) an assoc array of name/value pairs.
115 * @return CRM_Contact_BAO_Contact|CRM_Core_Error|NULL
116 * Created or updated contact object or error object.
117 * (error objects are being phased out in favour of exceptions)
119 public static function add(&$params) {
120 $contact = new CRM_Contact_DAO_Contact();
122 if (empty($params)) {
126 // Fix for validate contact sub type CRM-5143.
127 if (isset($params['contact_sub_type'])) {
128 if (empty($params['contact_sub_type'])) {
129 $params['contact_sub_type'] = 'null';
132 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
133 $params['contact_type'], TRUE
136 // we'll need to fix tests to handle this
138 CRM_Core_Error
::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
140 $params['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
146 $params['contact_sub_type'] = 'null';
149 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
150 CRM_Utils_Array
::formatArrayKeys($params['preferred_communication_method']);
151 $contact->preferred_communication_method
= CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
152 unset($params['preferred_communication_method']);
155 $defaults = ['source' => CRM_Utils_Array
::value('contact_source', $params)];
156 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
157 $defaults['display_name'] = $params['organization_name'];
158 $defaults['sort_name'] = $params['organization_name'];
160 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
161 $defaults['display_name'] = $params['household_name'];
162 $defaults['sort_name'] = $params['household_name'];
164 $params = array_merge($defaults, $params);
166 $allNull = $contact->copyValues($params);
168 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
170 if ($contact->contact_type
== 'Individual') {
172 // @todo allow the lines below to be overridden by input or hooks & add tests,
173 // as has been done for households and organizations.
174 // Format individual fields.
175 CRM_Contact_BAO_Individual
::format($params, $contact);
178 if (strlen($contact->display_name
) > 128) {
179 $contact->display_name
= substr($contact->display_name
, 0, 128);
181 if (strlen($contact->sort_name
) > 128) {
182 $contact->sort_name
= substr($contact->sort_name
, 0, 128);
185 $privacy = CRM_Utils_Array
::value('privacy', $params);
187 is_array($privacy) &&
191 foreach (self
::$_commPrefs as $name) {
192 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
196 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
197 // @todo - does this mean we can remove this block?
198 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
199 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
201 $contact->hash
= md5(uniqid(rand(), TRUE));
204 // Even if we don't need $employerId, it's important to call getFieldValue() before
205 // the contact is saved because we want the existing value to be cached.
206 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
207 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
212 CRM_Core_BAO_Log
::register($contact->id
,
218 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
219 // Create current employer.
220 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
223 if (empty($params['contact_id'])) {
227 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
231 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
236 // Update cached employer name.
237 if ($contact->contact_type
== 'Organization') {
238 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
247 * takes an associative array and creates a contact object and all the associated
248 * derived objects (i.e. individual, location, email, phone etc)
250 * This function is invoked from within the web form layer and also from the api layer
252 * @param array $params
253 * (reference ) an assoc array of name/value pairs.
254 * @param bool $fixAddress
255 * If we need to fix address.
256 * @param bool $invokeHooks
257 * If we need to invoke hooks.
259 * @param bool $skipDelete
260 * Unclear parameter, passed to website create
262 * @todo explain this parameter
265 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
266 * Created or updated contribution object. We are deprecating returning an error in
267 * favour of exceptions
269 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
271 if (empty($params['contact_type']) && empty($params['contact_id'])) {
275 if (!empty($params['contact_id']) && empty($params['contact_type'])) {
276 $params['contact_type'] = self
::getContactType($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),
473 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
474 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
475 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
478 // Filter out other fields.
479 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
480 $params = array_merge($params, $savedGreetings);
483 foreach ($missingGreetingParams as $greetingName => $greeting) {
484 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
488 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
489 if ($params[$greetingParam] === 'null') {
490 // If we are setting it to null then null out the display field.
491 $params[$greetingIndex . '_display'] = 'null';
497 * Get the display name and image of a contact.
502 * @param bool $includeTypeInReturnParameters
503 * Should type be part of the returned array?
506 * the displayName and contactImage for this contact
508 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
509 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
511 SELECT civicrm_contact.*,
512 civicrm_email.email as email
514 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
515 AND civicrm_email.is_primary = 1
516 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
517 $dao = new CRM_Core_DAO();
520 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
521 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
523 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
524 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
527 // use email if display_name is empty
528 if (empty($dao->display_name
)) {
529 $displayName = $dao->email
;
532 $displayName = $dao->display_name
;
535 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
537 return $includeTypeInReturnParameters ?
array(
541 $dao->contact_sub_type
,
543 ) : array($displayName, $image, $imageUrl);
549 * Add billing fields to the params if appropriate.
551 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
552 * don't then we should set the name fields to the filling fields AND add the preserveDBName
553 * parameter (which will tell the BAO only to set those fields if none already exist.
555 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
556 * matching is best done by hipsters.
558 * @param array $params
560 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
561 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
562 foreach ($nameFields as $field) {
563 if (!empty($params[$field])) {
567 // There are only 3 - we can iterate through them twice :-)
568 foreach ($nameFields as $field) {
569 if (!empty($params['billing_' . $field])) {
570 $params[$field] = $params['billing_' . $field];
572 $params['preserveDBName'] = TRUE;
578 * Resolve a state province string (UT or Utah) to an ID.
580 * If country has been passed in we should select a state belonging to that country.
582 * Alternatively we should choose from enabled countries, prioritising the default country.
584 * @param array $values
585 * @param int|null $countryID
589 * @throws \CRM_Core_Exception
591 protected static function resolveStateProvinceID($values, $countryID) {
594 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
595 if (CRM_Utils_Array
::lookupValue($values,
600 return $values['state_province_id'];
602 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
603 if (CRM_Utils_Array
::lookupValue($values,
608 return $values['state_province_id'];
613 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
614 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
615 // prefer matching country..
616 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, array('country_id' => Civi
::settings()->get('defaultContactCountry')));
617 if (CRM_Utils_Array
::lookupValue($values,
622 return $values['state_province_id'];
625 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
626 if (CRM_Utils_Array
::lookupValue($values,
631 return $values['state_province_id'];
634 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
635 if (CRM_Utils_Array
::lookupValue($values,
640 return $values['state_province_id'];
642 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
643 if (CRM_Utils_Array
::lookupValue($values,
648 return $values['state_province_id'];
656 * Get the relevant location entity for the array key.
658 * Based on the field name we determine which location entity
659 * we are dealing with. Apart from a few specific ones they
660 * are mostly 'address' (the default).
662 * @param string $fieldName
666 protected static function getLocationEntityForKey($fieldName) {
667 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
670 if ($fieldName === 'phone_ext') {
677 * Create last viewed link to recently updated contact.
679 * @param array $crudLinkSpec
680 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
681 * - entity_table: string, eg "civicrm_contact"
685 * NULL if unavailable, or
686 * [path: string, query: string, title: string]
687 * @see CRM_Utils_System::createDefaultCrudLink
689 public function createDefaultCrudLink($crudLinkSpec) {
690 switch ($crudLinkSpec['action']) {
691 case CRM_Core_Action
::VIEW
:
693 'title' => $this->display_name
,
694 'path' => 'civicrm/contact/view',
702 case CRM_Core_Action
::UPDATE
:
704 'title' => $this->display_name
,
705 'path' => 'civicrm/contact/add',
708 'action' => 'update',
718 * Get the values for pseudoconstants for name->value and reverse.
722 * This is called specifically from the contact import parser & should be moved there
723 * as it is not truly a generic function.
725 * @param array $defaults
726 * (reference) the default values, some of which need to be resolved.
727 * @param bool $reverse
728 * Always true as this function is only called from one place..
730 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
731 // Hack for birth_date.
732 if (!empty($defaults['birth_date'])) {
733 if (is_array($defaults['birth_date'])) {
734 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
738 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
739 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
740 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
741 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
743 //lookup value of email/postal greeting, addressee, CRM-4575
744 foreach (self
::$_greetingTypes as $greeting) {
745 $filterCondition = array(
746 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
747 'greeting_type' => $greeting,
749 CRM_Utils_Array
::lookupValue($defaults, $greeting,
750 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
754 $blocks = array('address', 'im', 'phone');
755 foreach ($blocks as $name) {
756 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
759 foreach ($defaults[$name] as $count => & $values) {
761 //get location type id.
762 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
764 if ($name == 'address') {
765 // FIXME: lookupValue doesn't work for vcard_name
766 if (!empty($values['location_type_id'])) {
767 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
768 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
771 if (!CRM_Utils_Array
::lookupValue($values,
773 CRM_Core_PseudoConstant
::country(),
778 CRM_Utils_Array
::lookupValue($values,
780 CRM_Core_PseudoConstant
::countryIsoCode(),
784 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
785 if ($stateProvinceID) {
786 $values['state_province_id'] = $stateProvinceID;
789 if (!empty($values['state_province_id'])) {
790 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
793 $countyList = CRM_Core_PseudoConstant
::county();
795 CRM_Utils_Array
::lookupValue($values,
803 CRM_Utils_Array
::lookupValue($values,
805 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
810 if ($name == 'phone') {
811 CRM_Utils_Array
::lookupValue($values,
813 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
818 // Kill the reference.
825 * Fetch object based on array of properties.
827 * @param array $params
828 * (reference ) an assoc array of name/value pairs.
829 * @param array $defaults
830 * (reference ) an assoc array to hold the name / value pairs.
831 * in a hierarchical manner
832 * @param bool $microformat
833 * For location in microformat.
835 * @return CRM_Contact_BAO_Contact
837 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
838 if (array_key_exists('contact_id', $params)) {
839 $params['id'] = $params['contact_id'];
841 elseif (array_key_exists('id', $params)) {
842 $params['contact_id'] = $params['id'];
845 $contact = self
::getValues($params, $defaults);
847 unset($params['id']);
849 //get the block information for this contact
850 $entityBlock = array('contact_id' => $params['contact_id']);
851 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
852 $defaults = array_merge($defaults, $blocks);
853 foreach ($blocks as $block => $value) {
854 $contact->$block = $value;
857 if (!isset($params['noNotes'])) {
858 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
861 if (!isset($params['noRelationships'])) {
862 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
865 if (!isset($params['noGroups'])) {
866 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
869 if (!isset($params['noWebsite'])) {
870 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
877 * Get the display name of a contact.
882 * @return null|string
883 * display name of the contact if found
885 public static function displayName($id) {
888 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
895 * Delete a contact and all its associated records.
898 * Id of the contact to delete.
899 * @param bool $restore
900 * Whether to actually restore, not delete.
901 * @param bool $skipUndelete
902 * Whether to force contact delete or not.
903 * @param bool $checkPermissions
906 * Was contact deleted?
908 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
913 // If trash is disabled in system settings then we always skip
914 if (!Civi
::settings()->get('contact_undelete')) {
915 $skipUndelete = TRUE;
918 // make sure we have edit permission for this contact
920 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
921 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
927 // Restrict contact to be delete if contact has financial trxns
929 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
933 // make sure this contact_id does not have any membership types
934 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
937 'member_of_contact_id'
939 if ($membershipTypeID) {
943 $contact = new CRM_Contact_DAO_Contact();
945 if (!$contact->find(TRUE)) {
949 $contactType = $contact->contact_type
;
950 // currently we only clear employer cache.
951 // we are now deleting inherited membership if any.
952 if ($contact->contact_type
== 'Organization') {
953 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
954 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
955 if (!empty($relationshipDtls)) {
956 foreach ($relationshipDtls as $rId => $details) {
957 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
960 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
964 return self
::contactTrashRestore($contact, TRUE);
967 // start a new transaction
968 $transaction = new CRM_Core_Transaction();
971 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
973 //delete billing address if exists.
974 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
976 // delete the log entries since we dont have triggers enabled as yet
977 $logDAO = new CRM_Core_DAO_Log();
978 $logDAO->entity_table
= 'civicrm_contact';
979 $logDAO->entity_id
= $id;
982 // delete contact participants CRM-12155
983 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
985 // delete contact contributions CRM-12155
986 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
988 // do activity cleanup, CRM-5604
989 CRM_Activity_BAO_Activity
::cleanupActivity($id);
991 // delete all notes related to contact
992 CRM_Core_BAO_Note
::cleanContactNotes($id);
994 // delete cases related to contact
995 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
996 if (!empty($contactCases)) {
997 foreach ($contactCases as $caseId) {
998 //check if case is associate with other contact or not.
999 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
1000 if (count($caseContactId) <= 1) {
1001 CRM_Case_BAO_Case
::deleteCase($caseId);
1009 self
::contactTrashRestore($contact);
1012 //delete the contact id from recently view
1013 CRM_Utils_Recent
::delContact($id);
1014 self
::updateContactCache($id, empty($restore));
1016 // delete any prevnext/dupe cache entry
1017 // These two calls are redundant in default deployments, but they're
1018 // meaningful if "prevnext" is memory-backed.
1019 Civi
::service('prevnext')->deleteItem($id);
1020 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1022 $transaction->commit();
1024 if ($skipUndelete) {
1025 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1032 * Action to update any caches relating to a recently update contact.
1034 * I was going to call this from delete as well as from create to ensure the delete is being
1035 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1036 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1037 * where the call involved a subquery that was locking the table.
1039 * @param int $contactID
1040 * @param bool $isTrashed
1042 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1045 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1046 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1047 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1048 // but this should not cause any change as long as contacts are not being trashed outside the
1049 // main functions for that.
1050 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
1053 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1058 * Delete the image of a contact.
1061 * Id of the contact.
1064 * Was contact image deleted?
1066 public static function deleteContactImage($id) {
1071 $contact = new self();
1073 $contact->image_URL
= 'null';
1080 * Return proportional height and width of the image.
1082 * @param int $imageWidth
1085 * @param int $imageHeight
1089 * Thumb dimension of image
1091 public static function getThumbSize($imageWidth, $imageHeight) {
1093 if ($imageWidth && $imageHeight) {
1094 $imageRatio = $imageWidth / $imageHeight;
1099 if ($imageRatio > 1) {
1100 $imageThumbWidth = $thumbWidth;
1101 $imageThumbHeight = round($thumbWidth / $imageRatio);
1104 $imageThumbHeight = $thumbWidth;
1105 $imageThumbWidth = round($thumbWidth * $imageRatio);
1108 return array($imageThumbWidth, $imageThumbHeight);
1112 * Validate type of contact image.
1114 * @param array $params
1115 * @param string $imageIndex
1116 * Index of image field.
1117 * @param string $statusMsg
1118 * Status message to be set after operation.
1119 * @param string $opType
1120 * Type of operation like fatal, bounce etc.
1123 * true if valid image extension
1125 public static function processImageParams(
1127 $imageIndex = 'image_URL',
1141 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1142 $photo = basename($params[$imageIndex]['name']);
1143 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1147 unset($params[$imageIndex]);
1149 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1151 if ($opType == 'status') {
1152 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1154 // FIXME: additional support for fatal, bounce etc could be added.
1160 * Extract contact id from url for deleting contact image.
1162 public static function processImage() {
1164 $action = CRM_Utils_Request
::retrieve('action', 'String');
1165 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1166 // retrieve contact id in case of Profile context
1167 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1168 $cid = $cid ?
$cid : $id;
1169 if ($action & CRM_Core_Action
::DELETE
) {
1170 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1171 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1172 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1173 $session = CRM_Core_Session
::singleton();
1174 $toUrl = $session->popUserContext();
1175 CRM_Utils_System
::redirect($toUrl);
1181 * Function to set is_delete true or restore deleted contact.
1183 * @param CRM_Contact_DAO_Contact $contact
1184 * Contact DAO object.
1185 * @param bool $restore
1186 * True to set the is_delete = 1 else false to restore deleted contact,
1187 * i.e. is_delete = 0
1191 public static function contactTrashRestore($contact, $restore = FALSE) {
1192 $updateParams = array(
1193 'id' => $contact->id
,
1194 'is_deleted' => $restore ?
0 : 1,
1197 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1199 $params = array(1 => array($contact->id
, 'Integer'));
1201 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1202 CRM_Core_DAO
::executeQuery($query, $params);
1205 $contact->copyValues($updateParams);
1207 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
1209 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1215 * Get contact type for a contact.
1218 * Id of the contact whose contact type is needed.
1221 * contact_type if $id found else null ""
1223 public static function getContactType($id) {
1224 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1228 * Get contact sub type for a contact.
1231 * Id of the contact whose contact sub type is needed.
1233 * @param string $implodeDelimiter
1236 * contact_sub_type if $id found else null ""
1238 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1239 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1241 return $implodeDelimiter ?
NULL : array();
1244 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1246 if ($implodeDelimiter) {
1247 $subtype = implode($implodeDelimiter, $subtype);
1253 * Get pair of contact-type and sub-type for a contact.
1256 * Id of the contact whose contact sub/contact type is needed.
1260 public static function getContactTypes($id) {
1261 $params = array('id' => $id);
1263 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1266 array('contact_type', 'contact_sub_type')
1270 $contactTypes = array();
1271 if ($contact->contact_sub_type
) {
1272 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1274 array_unshift($contactTypes, $contact->contact_type
);
1276 return $contactTypes;
1279 CRM_Core_Error
::fatal();
1284 * Combine all the importable fields from the lower levels object.
1286 * The ordering is important, since currently we do not have a weight
1287 * scheme. Adding weight is super important
1289 * @param int|string $contactType contact Type
1290 * @param bool $status
1291 * Status is used to manipulate first title.
1292 * @param bool $showAll
1293 * If true returns all fields (includes disabled fields).
1294 * @param bool $isProfile
1295 * If its profile mode.
1296 * @param bool $checkPermission
1297 * If false, do not include permissioning clause (for custom data).
1299 * @param bool $withMultiCustomFields
1302 * array of importable Fields
1304 public static function importableFields(
1305 $contactType = 'Individual',
1309 $checkPermission = TRUE,
1310 $withMultiCustomFields = FALSE
1312 if (empty($contactType)) {
1313 $contactType = 'All';
1316 $cacheKeyString = "importableFields $contactType";
1317 $cacheKeyString .= $status ?
'_1' : '_0';
1318 $cacheKeyString .= $showAll ?
'_1' : '_0';
1319 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1320 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1322 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1325 // check if we can retrieve from database cache
1326 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1330 $fields = CRM_Contact_DAO_Contact
::import();
1332 // get the fields thar are meant for contact types
1333 if (in_array($contactType, array(
1339 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1342 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1343 CRM_Core_DAO_Phone
::import(),
1344 CRM_Core_DAO_Email
::import(),
1345 CRM_Core_DAO_IM
::import(TRUE),
1346 CRM_Core_DAO_OpenID
::import()
1349 $locationFields = array_merge($locationFields,
1350 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1358 foreach ($locationFields as $key => $field) {
1359 $locationFields[$key]['hasLocationType'] = TRUE;
1362 $fields = array_merge($fields, $locationFields);
1364 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1365 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1368 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1369 $fields['url']['hasWebsiteType'] = TRUE;
1371 if ($contactType != 'All') {
1372 $fields = array_merge($fields,
1373 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1378 $withMultiCustomFields
1381 //unset the fields, which are not related to their
1383 $commonValues = array(
1384 'Individual' => array(
1388 'organization_name',
1390 'Household' => array(
1400 'organization_name',
1408 'Organization' => array(
1423 foreach ($commonValues[$contactType] as $value) {
1424 unset($fields[$value]);
1428 foreach (array('Individual', 'Household', 'Organization') as $type) {
1429 $fields = array_merge($fields,
1430 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1435 $withMultiCustomFields
1442 $fields = array_merge($fields, array(
1444 'title' => ts('Group(s)'),
1448 'title' => ts('Tag(s)'),
1452 'title' => ts('Note'),
1455 'communication_style_id' => array(
1456 'title' => ts('Communication Style'),
1457 'name' => 'communication_style_id',
1462 //Sorting fields in alphabetical order(CRM-1507)
1463 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1465 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1468 self
::$_importableFields[$cacheKeyString] = $fields;
1472 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1473 self
::$_importableFields[$cacheKeyString]
1477 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1478 self
::$_importableFields[$cacheKeyString]
1486 * Combine all the exportable fields from the lower levels object.
1488 * Currently we are using importable fields as exportable fields
1490 * @param int|string $contactType contact Type
1491 * @param bool $status
1492 * True while exporting primary contacts.
1493 * @param bool $export
1494 * True when used during export.
1495 * @param bool $search
1496 * True when used during search, might conflict with export param?.
1498 * @param bool $withMultiRecord
1499 * @param bool $checkPermissions
1501 * array of exportable Fields
1503 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1504 if (empty($contactType)) {
1505 $contactType = 'All';
1508 $cacheKeyString = "exportableFields $contactType";
1509 $cacheKeyString .= $export ?
'_1' : '_0';
1510 $cacheKeyString .= $status ?
'_1' : '_0';
1511 $cacheKeyString .= $search ?
'_1' : '_0';
1512 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1513 //calculates custom fields takes into account the logged in user & caches that for all users
1514 //as an interim fix we will cache the fields by contact
1515 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1517 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1518 if (!self
::$_exportableFields) {
1519 self
::$_exportableFields = array();
1522 // check if we can retrieve from database cache
1523 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1526 $fields = CRM_Contact_DAO_Contact
::export();
1528 // The fields are meant for contact types.
1529 if (in_array($contactType, array(
1535 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1537 // add current employer for individuals
1538 $fields = array_merge($fields, array(
1539 'current_employer' =>
1541 'name' => 'organization_name',
1542 'title' => ts('Current Employer'),
1546 $locationType = array(
1547 'location_type' => array(
1548 'name' => 'location_type',
1549 'where' => 'civicrm_location_type.name',
1550 'title' => ts('Location Type'),
1554 $IMProvider = array(
1555 'im_provider' => array(
1556 'name' => 'im_provider',
1557 'where' => 'civicrm_im.provider_id',
1558 'title' => ts('IM Provider'),
1562 $locationFields = array_merge($locationType,
1563 CRM_Core_DAO_Address
::export(),
1564 CRM_Core_DAO_Phone
::export(),
1565 CRM_Core_DAO_Email
::export(),
1567 CRM_Core_DAO_IM
::export(TRUE),
1568 CRM_Core_DAO_OpenID
::export()
1571 $locationFields = array_merge($locationFields,
1572 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1575 foreach ($locationFields as $key => $field) {
1576 $locationFields[$key]['hasLocationType'] = TRUE;
1579 $fields = array_merge($fields, $locationFields);
1582 $fields = array_merge($fields,
1583 CRM_Core_DAO_Worldregion
::export()
1586 $fields = array_merge($fields,
1587 CRM_Contact_DAO_Contact
::export()
1591 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1593 if ($contactType != 'All') {
1594 $fields = array_merge($fields,
1595 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1604 $fields = array_merge($fields,
1605 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1609 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1612 $fields = array_merge($fields, array(
1614 'title' => ts('Group(s)'),
1618 'title' => ts('Tag(s)'),
1622 'title' => ts('Note(s)'),
1628 $fields = array_merge($fields, array(
1630 'title' => ts('Group(s)'),
1634 'title' => ts('Tag(s)'),
1638 'title' => ts('Note(s)'),
1644 //Sorting fields in alphabetical order(CRM-1507)
1645 foreach ($fields as $k => $v) {
1646 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1649 $fields = array_merge($sortArray, $fields);
1650 //unset the field which are not related to their contact type.
1651 if ($contactType != 'All') {
1652 $commonValues = array(
1653 'Individual' => array(
1657 'organization_name',
1658 'email_greeting_custom',
1659 'postal_greeting_custom',
1662 'Household' => array(
1672 'organization_name',
1680 'email_greeting_custom',
1681 'postal_greeting_custom',
1686 'Organization' => array(
1697 'email_greeting_custom',
1698 'postal_greeting_custom',
1708 foreach ($commonValues[$contactType] as $value) {
1709 unset($fields[$value]);
1713 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1715 self
::$_exportableFields[$cacheKeyString] = $fields;
1719 $fields = self
::$_exportableFields[$cacheKeyString];
1722 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1723 self
::$_exportableFields[$cacheKeyString]
1731 * Get the all contact details (Hierarchical).
1733 * @param int $contactId
1735 * @param array $fields
1741 public static function getHierContactDetails($contactId, $fields) {
1742 $params = array(array('contact_id', '=', $contactId, 0, 0));
1745 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1747 // We don't know the contents of return properties, but we need the lower
1748 // level ids of the contact so add a few fields.
1749 $returnProperties['first_name'] = 1;
1750 $returnProperties['organization_name'] = 1;
1751 $returnProperties['household_name'] = 1;
1752 $returnProperties['contact_type'] = 1;
1753 $returnProperties['contact_sub_type'] = 1;
1754 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1758 * Given a set of flat profile style field names, create a hierarchy.
1760 * This is for the query to use, create the right sql.
1763 * @param int $contactId
1767 * A hierarchical property tree if appropriate
1769 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1770 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1772 $returnProperties = array();
1774 $multipleFields = array('website' => 'url');
1775 foreach ($fields as $name => $dontCare) {
1776 if (strpos($name, '-') !== FALSE) {
1777 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1779 if (!in_array($fieldName, $multipleFields)) {
1780 if ($id == 'Primary') {
1781 $locationTypeName = 1;
1784 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1785 if (!$locationTypeName) {
1790 if (empty($returnProperties['location'])) {
1791 $returnProperties['location'] = array();
1793 if (empty($returnProperties['location'][$locationTypeName])) {
1794 $returnProperties['location'][$locationTypeName] = array();
1795 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1797 if (in_array($fieldName, array(
1805 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1808 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1811 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1812 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1815 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1819 $returnProperties['website'][$id][$fieldName] = 1;
1823 $returnProperties[$name] = 1;
1827 return $returnProperties;
1831 * Return the primary location type of a contact.
1833 * $params int $contactId contact_id
1834 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1835 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1837 * @param int $contactId
1838 * @param bool $skipDefaultPriamry
1839 * @param null $block
1842 * $locationType location_type_id
1844 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1846 $entityBlock = array('contact_id' => $contactId);
1847 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1848 foreach ($blocks[$block] as $key => $value) {
1849 if (!empty($value['is_primary'])) {
1850 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1857 IF ( civicrm_email.location_type_id IS NULL,
1858 IF ( civicrm_address.location_type_id IS NULL,
1859 IF ( civicrm_phone.location_type_id IS NULL,
1860 IF ( civicrm_im.location_type_id IS NULL,
1861 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1862 ,civicrm_im.location_type_id)
1863 ,civicrm_phone.location_type_id)
1864 ,civicrm_address.location_type_id)
1865 ,civicrm_email.location_type_id) as locationType
1866 FROM civicrm_contact
1867 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1868 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1869 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1870 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1871 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1872 WHERE civicrm_contact.id = %1 ";
1874 $params = array(1 => array($contactId, 'Integer'));
1876 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1878 $locationType = NULL;
1879 if ($dao->fetch()) {
1880 $locationType = $dao->locationType
;
1883 if (isset($locationType)) {
1884 return $locationType;
1886 elseif ($skipDefaultPriamry) {
1887 // if there is no primary contact location then return null
1891 // if there is no primart contact location, then return default
1892 // location type of the system
1893 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1894 return $defaultLocationType->id
;
1899 * Get the display name, primary email and location type of a contact.
1902 * Id of the contact.
1905 * Array of display_name, email if found, do_not_email or (null,null,null)
1907 public static function getContactDetails($id) {
1908 // check if the contact type
1909 $contactType = self
::getContactType($id);
1911 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1914 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1915 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1916 WHERE civicrm_contact.id = %1
1917 ORDER BY civicrm_email.is_primary DESC";
1918 $params = array(1 => array($id, 'Integer'));
1919 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1921 if ($dao->fetch()) {
1922 if ($contactType == 'Individual') {
1923 if ($dao->first_name ||
$dao->last_name
) {
1924 $name = "{$dao->first_name} {$dao->last_name}";
1927 $name = $dao->display_name
;
1931 $name = $dao->display_name
;
1933 $email = $dao->email
;
1934 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1935 $onHold = $dao->on_hold ?
TRUE : FALSE;
1936 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1937 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1939 return array(NULL, NULL, NULL, NULL, NULL);
1943 * Add/edit/register contacts through profile.
1945 * @param array $params
1946 * Array of profile fields to be edited/added.
1947 * @param array $fields
1948 * Array of fields from UFGroup.
1949 * @param int $contactID
1950 * Id of the contact to be edited/added.
1951 * @param int $addToGroupID
1952 * Specifies the default group to which contact is added.
1953 * @param int $ufGroupId
1954 * Uf group id (profile id).
1955 * @param string $ctype
1956 * @param bool $visibility
1957 * Basically lets us know where this request is coming from.
1958 * if via a profile from web, we restrict what groups are changed
1961 * contact id created/edited
1963 public static function createProfileContact(
1967 $addToGroupID = NULL,
1972 // add ufGroupID to params array ( CRM-2012 )
1974 $params['uf_group_id'] = $ufGroupId;
1976 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1978 // If a user has logged in, or accessed via a checksum
1979 // Then deliberately 'blanking' a value in the profile should remove it from their record
1980 $session = CRM_Core_Session
::singleton();
1981 $params['updateBlankLocInfo'] = TRUE;
1982 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1983 $params['updateBlankLocInfo'] = FALSE;
1988 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1992 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1995 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1997 // manage is_opt_out
1998 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1999 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
2000 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
2001 $data['is_opt_out'] = $isOptOut;
2002 // on change, create new civicrm_subscription_history entry
2003 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2005 'contact_id' => $contactDetails['contact_id'],
2006 'status' => $isOptOut ?
'Removed' : 'Added',
2009 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2013 $contact = self
::create($data);
2015 // contact is null if the profile does not have any contact fields
2017 $contactID = $contact->id
;
2020 if (empty($contactID)) {
2021 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
2024 // Process group and tag
2025 if (!empty($fields['group'])) {
2027 // this for sure means we are coming in via profile since i added it to fix
2028 // removing contacts from user groups -- lobo
2032 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2035 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2036 // Convert comma separated form values from select2 v3
2037 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2038 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2041 //to add profile in default group
2042 if (is_array($addToGroupID)) {
2043 $contactIds = array($contactID);
2044 foreach ($addToGroupID as $groupId) {
2045 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2048 elseif ($addToGroupID) {
2049 $contactIds = array($contactID);
2050 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2053 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
2056 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2059 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2065 * Format profile contact parameters.
2067 * @param array $params
2069 * @param int $contactID
2070 * @param int $ufGroupId
2071 * @param null $ctype
2072 * @param bool $skipCustom
2076 public static function formatProfileContactParams(
2085 $data = $contactDetails = array();
2087 // get the contact details (hier)
2089 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
2091 $contactDetails = $details[$contactID];
2092 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
2093 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
2096 //we should get contact type only if contact
2098 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2100 //special case to handle profile with only contact fields
2101 if ($data['contact_type'] == 'Contact') {
2102 $data['contact_type'] = 'Individual';
2104 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2105 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2109 $data['contact_type'] = $ctype;
2112 $data['contact_type'] = 'Individual';
2116 //fix contact sub type CRM-5125
2117 if (array_key_exists('contact_sub_type', $params) &&
2118 !empty($params['contact_sub_type'])
2120 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2122 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2123 !empty($params['contact_sub_type_hidden'])
2125 // if profile was used, and had any subtype, we obtain it from there
2126 //CRM-13596 - add to existing contact types, rather than overwriting
2127 if (empty($data['contact_sub_type'])) {
2128 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2129 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2132 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2133 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2134 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2135 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2136 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2141 if ($ctype == 'Organization') {
2142 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2144 elseif ($ctype == 'Household') {
2145 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2148 $locationType = array();
2153 $data['contact_id'] = $contactID;
2154 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2157 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2158 $defaultLocationId = $defaultLocation->id
;
2161 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2163 $blocks = array('email', 'phone', 'im', 'openid');
2165 $multiplFields = array('url');
2166 // prevent overwritten of formatted array, reset all block from
2167 // params if it is not in valid format (since import pass valid format)
2168 foreach ($blocks as $blk) {
2169 if (array_key_exists($blk, $params) &&
2170 !is_array($params[$blk])
2172 unset($params[$blk]);
2176 $primaryPhoneLoc = NULL;
2177 $session = CRM_Core_Session
::singleton();
2178 foreach ($params as $key => $value) {
2179 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2181 if ($locTypeId == 'Primary') {
2183 if (in_array($fieldName, $blocks)) {
2184 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2187 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2189 $primaryLocationType = $locTypeId;
2192 $locTypeId = $defaultLocationId;
2196 if (is_numeric($locTypeId) &&
2197 !in_array($fieldName, $multiplFields) &&
2198 substr($fieldName, 0, 7) != 'custom_'
2200 $index = $locTypeId;
2202 if (is_numeric($typeId)) {
2203 $index .= '-' . $typeId;
2205 if (!in_array($index, $locationType)) {
2206 $locationType[$count] = $index;
2210 $loc = CRM_Utils_Array
::key($index, $locationType);
2212 $blockName = self
::getLocationEntityForKey($fieldName);
2214 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2216 //set is_billing true, for location type "Billing"
2217 if ($locTypeId == $billingLocationTypeId) {
2218 $data[$blockName][$loc]['is_billing'] = 1;
2222 //get the primary location type
2223 if ($locTypeId == $primaryLocationType) {
2224 $data[$blockName][$loc]['is_primary'] = 1;
2227 elseif ($locTypeId == $defaultLocationId) {
2228 $data[$blockName][$loc]['is_primary'] = 1;
2231 if (in_array($fieldName, array('phone'))) {
2233 $data['phone'][$loc]['phone_type_id'] = $typeId;
2236 $data['phone'][$loc]['phone_type_id'] = '';
2238 $data['phone'][$loc]['phone'] = $value;
2240 //special case to handle primary phone with different phone types
2241 // in this case we make first phone type as primary
2242 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2243 $primaryPhoneLoc = $loc;
2246 if ($loc != $primaryPhoneLoc) {
2247 unset($data['phone'][$loc]['is_primary']);
2250 elseif ($fieldName == 'email') {
2251 $data['email'][$loc]['email'] = $value;
2252 if (empty($contactID)) {
2253 $data['email'][$loc]['is_primary'] = 1;
2256 elseif ($fieldName == 'im') {
2257 if (isset($params[$key . '-provider_id'])) {
2258 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2260 if (strpos($key, '-provider_id') !== FALSE) {
2261 $data['im'][$loc]['provider_id'] = $params[$key];
2264 $data['im'][$loc]['name'] = $value;
2267 elseif ($fieldName == 'openid') {
2268 $data['openid'][$loc]['openid'] = $value;
2271 if ($fieldName === 'state_province') {
2273 if (is_numeric($value) && ((int ) $value) >= 1000) {
2274 $data['address'][$loc]['state_province_id'] = $value;
2276 elseif (empty($value)) {
2277 $data['address'][$loc]['state_province_id'] = '';
2280 $data['address'][$loc]['state_province'] = $value;
2283 elseif ($fieldName === 'country') {
2285 if (is_numeric($value) && ((int ) $value) >= 1000
2287 $data['address'][$loc]['country_id'] = $value;
2289 elseif (empty($value)) {
2290 $data['address'][$loc]['country_id'] = '';
2293 $data['address'][$loc]['country'] = $value;
2296 elseif ($fieldName === 'county') {
2297 $data['address'][$loc]['county_id'] = $value;
2299 elseif ($fieldName == 'address_name') {
2300 $data['address'][$loc]['name'] = $value;
2302 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2303 $data['address'][$loc][substr($fieldName, 8)] = $value;
2306 $data[$blockName][$loc][$fieldName] = $value;
2311 if (substr($key, 0, 4) === 'url-') {
2312 $websiteField = explode('-', $key);
2313 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2314 $data['website'][$websiteField[1]]['url'] = $value;
2316 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2317 //save email/postal greeting and addressee values if any, CRM-4575
2318 $data[$key . '_id'] = $value;
2320 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2321 // for autocomplete transfer hidden value instead of label
2322 if ($params[$key] && isset($params[$key . '_id'])) {
2323 $value = $params[$key . '_id'];
2326 // we need to append time with date
2327 if ($params[$key] && isset($params[$key . '_time'])) {
2328 $value .= ' ' . $params[$key . '_time'];
2331 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2332 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2333 ($value == '' ||
!isset($value))
2339 if (!empty($params['customRecordValues'])) {
2340 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2341 foreach ($params['customRecordValues'] as $recId => $customFields) {
2342 if (is_array($customFields) && !empty($customFields)) {
2343 foreach ($customFields as $customFieldName) {
2344 if ($customFieldName == $key) {
2354 //CRM-13596 - check for contact_sub_type_hidden first
2355 if (array_key_exists('contact_sub_type_hidden', $params)) {
2356 $type = $params['contact_sub_type_hidden'];
2359 $type = $data['contact_type'];
2360 if (!empty($data['contact_sub_type'])) {
2361 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2365 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2375 elseif ($key == 'edit') {
2379 if ($key == 'location') {
2380 foreach ($value as $locationTypeId => $field) {
2381 foreach ($field as $block => $val) {
2382 if ($block == 'address' && array_key_exists('address_name', $val)) {
2383 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2388 if ($key == 'phone' && isset($params['phone_ext'])) {
2389 $data[$key] = $value;
2390 foreach ($value as $cnt => $phoneBlock) {
2391 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2392 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2396 elseif (in_array($key, array(
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
::getActivitiesCount($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
;
2956 return $locBlockIds;
2960 * Build context menu items.
2962 * @param int $contactId
2965 * Array of context menu for logged in user.
2967 public static function contextMenu($contactId = NULL) {
2970 'title' => ts('View Contact'),
2972 'ref' => 'view-contact',
2973 'class' => 'no-popup',
2975 'permissions' => array('view all contacts'),
2978 'title' => ts('Edit Contact'),
2980 'ref' => 'edit-contact',
2981 'class' => 'no-popup',
2983 'permissions' => array('edit all contacts'),
2986 'title' => ts('Delete Contact'),
2988 'ref' => 'delete-contact',
2990 'permissions' => array('access deleted contacts', 'delete contacts'),
2992 'contribution' => array(
2993 'title' => ts('Add Contribution'),
2995 'ref' => 'new-contribution',
2996 'key' => 'contribution',
2997 'tab' => 'contribute',
2998 'component' => 'CiviContribute',
2999 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
3000 'reset=1&action=add&context=contribution'
3002 'permissions' => array(
3003 'access CiviContribute',
3004 'edit contributions',
3007 'participant' => array(
3008 'title' => ts('Register for Event'),
3010 'ref' => 'new-participant',
3011 'key' => 'participant',
3012 'tab' => 'participant',
3013 'component' => 'CiviEvent',
3014 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3015 'permissions' => array(
3017 'edit event participants',
3020 'activity' => array(
3021 'title' => ts('Record Activity'),
3023 'ref' => 'new-activity',
3024 'key' => 'activity',
3025 'permissions' => array('edit all contacts'),
3028 'title' => ts('Add Pledge'),
3030 'ref' => 'new-pledge',
3033 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3034 'reset=1&action=add&context=pledge'
3036 'component' => 'CiviPledge',
3037 'permissions' => array(
3038 'access CiviPledge',
3042 'membership' => array(
3043 'title' => ts('Add Membership'),
3045 'ref' => 'new-membership',
3046 'key' => 'membership',
3048 'component' => 'CiviMember',
3049 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3050 'reset=1&action=add&context=membership'
3052 'permissions' => array(
3053 'access CiviMember',
3058 'title' => ts('Add Case'),
3060 'ref' => 'new-case',
3063 'component' => 'CiviCase',
3064 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3065 'permissions' => array('add cases'),
3068 'title' => ts('Add Grant'),
3070 'ref' => 'new-grant',
3073 'component' => 'CiviGrant',
3074 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3075 'reset=1&action=add&context=grant'
3077 'permissions' => array('edit grants'),
3080 'title' => ts('Add Relationship'),
3082 'ref' => 'new-relationship',
3085 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3086 'reset=1&action=add'
3088 'permissions' => array('edit all contacts'),
3091 'title' => ts('Add Note'),
3093 'ref' => 'new-note',
3096 'class' => 'medium-popup',
3097 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3098 'reset=1&action=add'
3100 'permissions' => array('edit all contacts'),
3103 'title' => ts('Send an Email'),
3105 'ref' => 'new-email',
3107 'permissions' => array('view all contacts'),
3110 'title' => ts('Add to Group'),
3112 'ref' => 'group-add-contact',
3115 'permissions' => array('edit groups'),
3118 'title' => ts('Tag Contact'),
3120 'ref' => 'tag-contact',
3123 'permissions' => array('edit all contacts'),
3127 $menu['otherActions'] = array(
3129 'title' => ts('Print Summary'),
3130 'description' => ts('Printer-friendly view of this page.'),
3132 'ref' => 'crm-contact-print',
3135 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3139 'icon' => 'crm-i fa-print',
3142 'title' => ts('vCard'),
3143 'description' => ts('vCard record for this contact.'),
3145 'ref' => 'crm-contact-vcard',
3148 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3152 'icon' => 'crm-i fa-list-alt',
3156 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3157 $menu['otherActions']['dashboard'] = array(
3158 'title' => ts('Contact Dashboard'),
3159 'description' => ts('Contact Dashboard'),
3161 'ref' => 'crm-contact-dashboard',
3162 'key' => 'dashboard',
3163 'tab' => 'dashboard',
3164 'class' => 'dashboard',
3165 // NOTE: As an alternative you can also build url on CMS specific way
3166 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3167 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3168 'icon' => 'crm-i fa-tachometer',
3172 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3174 $menu['otherActions']['user-record'] = array(
3175 'title' => ts('User Record'),
3176 'description' => ts('User Record'),
3178 'ref' => 'crm-contact-user-record',
3179 'key' => 'user-record',
3180 'tab' => 'user-record',
3181 'class' => 'user-record',
3182 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3183 'icon' => 'crm-i fa-user',
3186 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3187 $menu['otherActions']['user-add'] = array(
3188 'title' => ts('Create User Record'),
3189 'description' => ts('Create User Record'),
3191 'ref' => 'crm-contact-user-add',
3192 'key' => 'user-add',
3193 'tab' => 'user-add',
3194 'class' => 'user-add',
3195 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3196 'icon' => 'crm-i fa-user-plus',
3200 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3201 //1. check for component is active.
3202 //2. check for user permissions.
3203 //3. check for acls.
3204 //3. edit and view contact are directly accessible to user.
3206 $aclPermissionedTasks = array(
3211 'group-add-contact',
3215 $corePermission = CRM_Core_Permission
::getPermission();
3217 $contextMenu = array();
3218 foreach ($menu as $key => $values) {
3219 if ($key != 'otherActions') {
3221 // user does not have necessary permissions.
3222 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3225 // build directly accessible action menu.
3226 if (in_array($values['ref'], array(
3230 $contextMenu['primaryActions'][$key] = array(
3231 'title' => $values['title'],
3232 'ref' => $values['ref'],
3233 'class' => CRM_Utils_Array
::value('class', $values),
3234 'key' => $values['key'],
3239 // finally get menu item for -more- action widget.
3240 $contextMenu['moreActions'][$values['weight']] = array(
3241 'title' => $values['title'],
3242 'ref' => $values['ref'],
3243 'href' => CRM_Utils_Array
::value('href', $values),
3244 'tab' => CRM_Utils_Array
::value('tab', $values),
3245 'class' => CRM_Utils_Array
::value('class', $values),
3246 'key' => $values['key'],
3250 foreach ($values as $value) {
3251 // user does not have necessary permissions.
3252 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3256 // finally get menu item for -more- action widget.
3257 $contextMenu['otherActions'][$value['weight']] = array(
3258 'title' => $value['title'],
3259 'ref' => $value['ref'],
3260 'href' => CRM_Utils_Array
::value('href', $value),
3261 'tab' => CRM_Utils_Array
::value('tab', $value),
3262 'class' => CRM_Utils_Array
::value('class', $value),
3263 'icon' => CRM_Utils_Array
::value('icon', $value),
3264 'key' => $value['key'],
3270 ksort($contextMenu['moreActions']);
3271 ksort($contextMenu['otherActions']);
3273 return $contextMenu;
3277 * Check if user has permissions to access items in action menu.
3279 * @param array $aclPermissionedTasks
3280 * Array containing ACL related tasks.
3281 * @param string $corePermission
3282 * The permission of the user (edit or view or null).
3283 * @param array $menuOptions
3284 * Array containing params of the menu (title, href, etc).
3287 * TRUE if user has all permissions, FALSE if otherwise.
3289 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3290 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3292 // if component action - make sure component is enable.
3293 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3297 // make sure user has all required permissions.
3298 $hasAllPermissions = FALSE;
3300 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3301 if (!is_array($permissions) ||
empty($permissions)) {
3302 $hasAllPermissions = TRUE;
3305 // iterate for required permissions in given permissions array.
3306 if (!$hasAllPermissions) {
3307 $hasPermissions = 0;
3308 foreach ($permissions as $permission) {
3309 if (CRM_Core_Permission
::check($permission)) {
3314 if (count($permissions) == $hasPermissions) {
3315 $hasAllPermissions = TRUE;
3318 // if still user does not have required permissions, check acl.
3319 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3320 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3321 $corePermission == CRM_Core_Permission
::EDIT
3323 $hasAllPermissions = TRUE;
3325 elseif (in_array($menuOptions['ref'], array(
3328 // grant permissions for these tasks.
3329 $hasAllPermissions = TRUE;
3334 return $hasAllPermissions;
3338 * Retrieve display name of contact that address is shared.
3340 * This is based on $masterAddressId or $contactId .
3342 * @param int $masterAddressId
3344 * @param int $contactId
3345 * Contact id. (deprecated - do not use)
3347 * @return string|null
3348 * the found display name or null.
3350 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3351 $masterDisplayName = NULL;
3352 if (!$masterAddressId) {
3353 return $masterDisplayName;
3357 SELECT display_name from civicrm_contact
3358 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3359 WHERE civicrm_address.id = " . $masterAddressId;
3361 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3362 return $masterDisplayName;
3366 * Get the creation/modification times for a contact.
3368 * @param int $contactId
3371 * Dates - ('created_date' => $, 'modified_date' => $)
3373 public static function getTimestamps($contactId) {
3374 $timestamps = CRM_Core_DAO
::executeQuery(
3375 'SELECT created_date, modified_date
3376 FROM civicrm_contact
3379 1 => array($contactId, 'Integer'),
3382 if ($timestamps->fetch()) {
3384 'created_date' => $timestamps->created_date
,
3385 'modified_date' => $timestamps->modified_date
,
3394 * Get a list of triggers for the contact table.
3396 * @see hook_civicrm_triggerInfo
3397 * @see CRM_Core_DAO::triggerRebuild
3398 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3401 * @param null $tableName
3403 public static function triggerInfo(&$info, $tableName = NULL) {
3404 //during upgrade, first check for valid version and then create triggers
3405 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3406 if (CRM_Core_Config
::isUpgradeMode()) {
3407 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3408 //if current version is less than 4.3.alpha1 dont create below triggers
3409 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3414 // Modifications to these records should update the contact timestamps.
3415 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3416 ->setRelations(array(
3417 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3418 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3419 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3420 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3421 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3423 ->alterTriggerInfo($info, $tableName);
3425 // Update phone table to populate phone_numeric field
3426 if (!$tableName ||
$tableName == 'civicrm_phone') {
3427 // Define stored sql function needed for phones
3428 $sqlTriggers = Civi
::service('sql_triggers');
3429 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3430 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3432 'table' => array('civicrm_phone'),
3434 'event' => array('INSERT', 'UPDATE'),
3435 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3441 * Check if contact is being used in civicrm_domain based on $contactId.
3443 * @param int $contactId
3447 * true if present else false.
3449 public static function checkDomainContact($contactId) {
3453 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3464 * Get options for a given contact field.
3466 * @see CRM_Core_DAO::buildOptions
3468 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3469 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3471 * @param string $fieldName
3472 * @param string $context
3473 * @see CRM_Core_DAO::buildOptionsContext
3474 * @param array $props
3475 * whatever is known about this dao object.
3477 * @return array|bool
3479 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3481 // Special logic for fields whose options depend on context or properties
3482 switch ($fieldName) {
3483 case 'contact_sub_type':
3484 if (!empty($props['contact_type'])) {
3485 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3489 case 'contact_type':
3490 if ($context == 'search') {
3491 // CRM-15495 - EntityRef filters and basic search forms expect this format
3492 // FIXME: Search builder does not
3493 return CRM_Contact_BAO_ContactType
::getSelectElements();
3497 // The contact api supports some related entities so we'll honor that by fetching their options
3500 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3504 $props['entity_table'] = 'civicrm_contact';
3505 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3507 case 'state_province_id':
3508 case 'state_province':
3509 case 'state_province_name':
3514 case 'worldregion_id':
3515 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3518 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3522 * Delete a contact-related object that has an 'is_primary' field.
3524 * Ensures that is_primary gets assigned to another object if available
3525 * Also calls pre/post hooks
3527 * @param string $type
3531 public static function deleteObjectWithPrimary($type, $id) {
3532 if (!$id ||
!is_numeric($id)) {
3535 $daoName = "CRM_Core_DAO_$type";
3536 $obj = new $daoName();
3540 if ($obj->fetch()) {
3541 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3542 $contactId = $obj->contact_id
;
3548 // is_primary is only relavent if this field belongs to a contact
3550 $dao = new $daoName();
3551 $dao->contact_id
= $contactId;
3552 $dao->is_primary
= 1;
3553 // Pick another record to be primary (if one isn't already)
3554 if (!$dao->find(TRUE)) {
3555 $dao->is_primary
= 0;
3557 if ($dao->fetch()) {
3558 $dao->is_primary
= 1;
3563 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3570 public function addSelectWhereClause() {
3571 // We always return an array with these keys, even if they are empty,
3572 // because this tells the query builder that we have considered these fields for acls
3574 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3575 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
array() : array('!= 1'),
3577 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3582 * Get any existing duplicate contacts based on the input parameters.
3584 * @param array $input
3585 * Input parameters to be matched.
3586 * @param string $contactType
3587 * @param string $rule
3590 * @param $excludedContactIDs
3591 * An array of ids not to be included in the results.
3592 * @param bool $checkPermissions
3593 * @param int $ruleGroupID
3594 * ID of the rule group to be used if an override is desirable.
3595 * @param array $contextParams
3596 * The context if relevant, eg. ['event_id' => X]
3600 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3601 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3602 $dedupeParams['check_permission'] = $checkPermissions;
3603 $dedupeParams['contact_type'] = $contactType;
3604 $dedupeParams['rule'] = $rule;
3605 $dedupeParams['rule_group_id'] = $ruleGroupID;
3606 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3607 $dedupeResults['ids'] = [];
3608 $dedupeResults['handled'] = FALSE;
3609 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3610 if (!$dedupeResults['handled']) {
3611 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3613 return $dedupeResults['ids'];
3617 * Get the first duplicate contacts based on the input parameters.
3619 * @param array $input
3620 * Input parameters to be matched.
3621 * @param string $contactType
3622 * @param string $rule
3625 * @param $excludedContactIDs
3626 * An array of ids not to be included in the results.
3627 * @param bool $checkPermissions
3628 * @param int $ruleGroupID
3629 * ID of the rule group to be used if an override is desirable.
3630 * @param array $contextParams
3631 * The context if relevant, eg. ['event_id' => X]
3635 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3636 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3644 * Check if a field is associated with an entity that has a location type.
3646 * (ie. is an address, phone, email etc field).
3648 * @param string $fieldTitle
3649 * Title of the field (not the name - create a new function for that if required).
3653 public static function isFieldHasLocationType($fieldTitle) {
3654 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3655 if ($field['title'] === $fieldTitle) {
3656 return CRM_Utils_Array
::value('hasLocationType', $field);
3663 * @param array $appendProfiles
3664 * Name of profile(s) to append to each link.
3668 public static function getEntityRefCreateLinks($appendProfiles = []) {
3669 // You'd think that "create contacts" would be the permission to check,
3670 // But new contact popups are profile forms and those use their own permissions.
3671 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3675 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3676 $profiles[] = 'new_' . strtolower($contactType);
3678 $retrieved = civicrm_api3('uf_group', 'get', [
3679 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3682 $links = $append = [];
3683 if (!empty($retrieved['values'])) {
3685 'individual' => 'fa-user',
3686 'organization' => 'fa-building',
3687 'household' => 'fa-home',
3689 foreach ($retrieved['values'] as $id => $profile) {
3690 if (in_array($profile['name'], $profiles)) {
3692 'label' => $profile['title'],
3693 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3694 NULL, NULL, FALSE, FALSE, TRUE),
3695 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3696 'icon' => CRM_Utils_Array
::value(str_replace('new_', '', $profile['name']), $icons),
3703 foreach ($append as $id) {
3704 foreach ($links as &$link) {
3705 $link['url'] .= ",$id";
3715 public static function getEntityRefFilters() {
3717 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3718 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3719 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3720 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3721 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3722 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3723 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3724 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3725 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3726 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],