3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
{
36 * SQL function used to format the phone_numeric field via trigger.
37 * @see self::triggerInfo()
39 * Note that this is also used by the 4.3 upgrade script.
40 * @see CRM_Upgrade_Incremental_php_FourThree
42 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
43 const CREATE_STRIP_FUNCTION_43
= "
44 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
45 RETURNS VARCHAR(255) CHARACTER SET utf8
49 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
50 DECLARE iterator INT DEFAULT 1;
51 WHILE iterator < (LENGTH(input) + 1) DO
52 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
53 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
55 SET iterator = iterator + 1;
61 * The types of communication preferences.
65 public static $_commPrefs = array(
78 public static $_greetingTypes = array(
85 * Static field for all the contact information that we can potentially import.
89 public static $_importableFields = array();
92 * Static field for all the contact information that we can potentially export.
96 public static $_exportableFields = NULL;
101 public function __construct() {
102 parent
::__construct();
106 * Takes an associative array and creates a contact object.
108 * The function extracts all the params it needs to initialize the create a
109 * contact object. the params array could contain additional unused name/value
112 * @param array $params
113 * (reference) an assoc array of name/value pairs.
115 * @return CRM_Contact_BAO_Contact|CRM_Core_Error|NULL
116 * Created or updated contact object or error object.
117 * (error objects are being phased out in favour of exceptions)
119 public static function add(&$params) {
120 $contact = new CRM_Contact_DAO_Contact();
122 if (empty($params)) {
126 // Fix for validate contact sub type CRM-5143.
127 if (isset($params['contact_sub_type'])) {
128 if (empty($params['contact_sub_type'])) {
129 $params['contact_sub_type'] = 'null';
131 elseif ($params['contact_sub_type'] !== 'null') {
132 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
133 $params['contact_type'], TRUE
136 // we'll need to fix tests to handle this
138 CRM_Core_Error
::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
140 $params['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
144 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
145 CRM_Utils_Array
::formatArrayKeys($params['preferred_communication_method']);
146 $contact->preferred_communication_method
= CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
147 unset($params['preferred_communication_method']);
150 $defaults = ['source' => CRM_Utils_Array
::value('contact_source', $params)];
151 if ($params['contact_type'] === 'Organization' && isset($params['organization_name'])) {
152 $defaults['display_name'] = $params['organization_name'];
153 $defaults['sort_name'] = $params['organization_name'];
155 if ($params['contact_type'] === 'Household' && isset($params['household_name'])) {
156 $defaults['display_name'] = $params['household_name'];
157 $defaults['sort_name'] = $params['household_name'];
159 $params = array_merge($defaults, $params);
161 $allNull = $contact->copyValues($params);
163 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
165 if ($contact->contact_type
== 'Individual') {
167 // @todo allow the lines below to be overridden by input or hooks & add tests,
168 // as has been done for households and organizations.
169 // Format individual fields.
170 CRM_Contact_BAO_Individual
::format($params, $contact);
173 if (strlen($contact->display_name
) > 128) {
174 $contact->display_name
= substr($contact->display_name
, 0, 128);
176 if (strlen($contact->sort_name
) > 128) {
177 $contact->sort_name
= substr($contact->sort_name
, 0, 128);
180 $privacy = CRM_Utils_Array
::value('privacy', $params);
182 is_array($privacy) &&
186 foreach (self
::$_commPrefs as $name) {
187 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
191 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
192 // @todo - does this mean we can remove this block?
193 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
194 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
196 $contact->hash
= md5(uniqid(rand(), TRUE));
199 // Even if we don't need $employerId, it's important to call getFieldValue() before
200 // the contact is saved because we want the existing value to be cached.
201 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
202 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
207 CRM_Core_BAO_Log
::register($contact->id
,
213 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
214 // Create current employer.
215 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
218 if (empty($params['contact_id'])) {
222 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
226 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
231 // Update cached employer name.
232 if ($contact->contact_type
== 'Organization') {
233 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
242 * takes an associative array and creates a contact object and all the associated
243 * derived objects (i.e. individual, location, email, phone etc)
245 * This function is invoked from within the web form layer and also from the api layer
247 * @param array $params
248 * (reference ) an assoc array of name/value pairs.
249 * @param bool $fixAddress
250 * If we need to fix address.
251 * @param bool $invokeHooks
252 * If we need to invoke hooks.
254 * @param bool $skipDelete
255 * Unclear parameter, passed to website create
257 * @todo explain this parameter
260 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
261 * Created or updated contribution object. We are deprecating returning an error in
262 * favour of exceptions
264 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
266 if (empty($params['contact_type']) && empty($params['contact_id'])) {
270 $isEdit = !empty($params['contact_id']);
272 if ($isEdit && empty($params['contact_type'])) {
273 $params['contact_type'] = self
::getContactType($params['contact_id']);
276 if (!empty($params['check_permissions']) && isset($params['api_key'])
277 && !CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])
278 && !($isEdit && CRM_Core_Permission
::check('edit own api keys') && $params['contact_id'] == CRM_Core_Session
::getLoggedInContactID())
280 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify api key');
284 if (!empty($params['contact_id'])) {
285 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
288 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
292 self
::ensureGreetingParamsAreSet($params);
294 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
295 if (empty($params['contact_id'])) {
296 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
297 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
298 $params['preferred_language'] = $language;
301 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
302 if (empty($params['communication_style_id'])) {
303 $defaultCommunicationStyleId = CRM_Core_OptionGroup
::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
304 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
308 $transaction = new CRM_Core_Transaction();
310 $contact = self
::add($params);
312 // Not dying here is stupid, since we get into weird situation and into a bug that
313 // is impossible to figure out for the user or for us
315 CRM_Core_Error
::fatal();
318 $params['contact_id'] = $contact->id
;
320 if (Civi
::settings()->get('is_enabled')) {
321 // Enabling multisite causes the contact to be added to the domain group.
322 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
323 if (!empty($domainGroupID)) {
324 if (!empty($params['group']) && is_array($params['group'])) {
325 $params['group'][$domainGroupID] = 1;
328 $params['group'] = array($domainGroupID => 1);
333 if (array_key_exists('group', $params)) {
334 $contactIds = array($params['contact_id']);
335 foreach ($params['group'] as $groupId => $flag) {
337 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
339 elseif ($flag == -1) {
340 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
345 // Add location Block data.
346 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
347 foreach ($blocks as $name => $value) {
348 $contact->$name = $value;
350 if (!empty($params['updateBlankLocInfo'])) {
354 if (isset($params['website'])) {
355 CRM_Core_BAO_Website
::process($params['website'], $contact->id
, $skipDelete);
358 $userID = CRM_Core_Session
::singleton()->get('userID');
360 if (!empty($params['note'])) {
361 if (is_array($params['note'])) {
362 foreach ($params['note'] as $note) {
363 $contactId = $contact->id
;
364 if (isset($note['contact_id'])) {
365 $contactId = $note['contact_id'];
367 //if logged in user, overwrite contactId
369 $contactId = $userID;
373 'entity_id' => $contact->id
,
374 'entity_table' => 'civicrm_contact',
375 'note' => $note['note'],
376 'subject' => CRM_Utils_Array
::value('subject', $note),
377 'contact_id' => $contactId,
379 CRM_Core_BAO_Note
::add($noteParams);
383 $contactId = $contact->id
;
384 //if logged in user, overwrite contactId
386 $contactId = $userID;
390 'entity_id' => $contact->id
,
391 'entity_table' => 'civicrm_contact',
392 'note' => $params['note'],
393 'subject' => CRM_Utils_Array
::value('subject', $params),
394 'contact_id' => $contactId,
396 CRM_Core_BAO_Note
::add($noteParams);
400 // update the UF user_unique_id if that has changed
401 CRM_Core_BAO_UFMatch
::updateUFName($contact->id
);
403 if (!empty($params['custom']) &&
404 is_array($params['custom'])
406 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contact', $contact->id
);
409 // make a civicrm_subscription_history entry only on contact create (CRM-777)
410 if (empty($params['contact_id'])) {
411 $subscriptionParams = array(
412 'contact_id' => $contact->id
,
416 CRM_Contact_BAO_SubscriptionHistory
::create($subscriptionParams);
419 $transaction->commit();
421 // CRM-6367: fetch the right label for contact type’s display
422 $contact->contact_type_display
= CRM_Core_DAO
::getFieldValue(
423 'CRM_Contact_DAO_ContactType',
424 $contact->contact_type
,
429 CRM_Contact_BAO_Contact_Utils
::clearContactCaches();
433 CRM_Utils_Hook
::post('edit', $params['contact_type'], $contact->id
, $contact);
436 CRM_Utils_Hook
::post('create', $params['contact_type'], $contact->id
, $contact);
440 // In order to prevent a series of expensive queries in intensive batch processing
441 // api calls may pass in skip_greeting_processing, probably doing it later via the
442 // scheduled job. CRM-21551
443 if (empty($params['skip_greeting_processing'])) {
444 self
::processGreetings($contact);
447 if (!empty($params['check_permissions'])) {
448 $contacts = [&$contact];
449 self
::unsetProtectedFields($contacts);
456 * Format the output of the create contact function
457 * @param CRM_Contact_DAO_Contact[]|array[] $contacts
459 public static function unsetProtectedFields(&$contacts) {
460 if (!CRM_Core_Permission
::check([['edit api keys', 'administer CiviCRM']])) {
461 $currentUser = CRM_Core_Session
::getLoggedInContactID();
462 $editOwn = $currentUser && CRM_Core_Permission
::check('edit own api keys');
463 foreach ($contacts as &$contact) {
464 $cid = is_object($contact) ?
$contact->id
: CRM_Utils_Array
::value('id', $contact);
465 if (!($editOwn && $cid == $currentUser)) {
466 if (is_object($contact)) {
467 unset($contact->api_key
);
470 unset($contact['api_key']);
478 * Ensure greeting parameters are set.
480 * By always populating greetings here we can be sure they are set if required & avoid a call later.
481 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
483 * @param array $params
485 public static function ensureGreetingParamsAreSet(&$params) {
486 $allGreetingParams = array('addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id');
487 $missingGreetingParams = array();
489 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
490 if (empty($params[$greetingParam])) {
491 $missingGreetingParams[$greetingIndex] = $greetingParam;
495 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
496 $savedGreetings = civicrm_api3('Contact', 'getsingle', array(
497 'id' => $params['contact_id'],
498 'return' => array_keys($missingGreetingParams),
502 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
503 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
504 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
507 // Filter out other fields.
508 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
509 $params = array_merge($params, $savedGreetings);
512 foreach ($missingGreetingParams as $greetingName => $greeting) {
513 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
517 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
518 if ($params[$greetingParam] === 'null') {
519 // If we are setting it to null then null out the display field.
520 $params[$greetingIndex . '_display'] = 'null';
526 * Get the display name and image of a contact.
531 * @param bool $includeTypeInReturnParameters
532 * Should type be part of the returned array?
535 * the displayName and contactImage for this contact
537 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
538 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
540 SELECT civicrm_contact.*,
541 civicrm_email.email as email
543 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
544 AND civicrm_email.is_primary = 1
545 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
546 $dao = new CRM_Core_DAO();
549 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
550 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
552 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
553 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
556 // use email if display_name is empty
557 if (empty($dao->display_name
)) {
558 $displayName = $dao->email
;
561 $displayName = $dao->display_name
;
564 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
566 return $includeTypeInReturnParameters ?
array(
570 $dao->contact_sub_type
,
572 ) : array($displayName, $image, $imageUrl);
578 * Add billing fields to the params if appropriate.
580 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
581 * don't then we should set the name fields to the billing fields AND add the preserveDBName
582 * parameter (which will tell the BAO only to set those fields if none already exist.
584 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
585 * matching is best done by hipsters.
587 * @param array $params
589 * @fixme How does this relate to almost the same thing being done in CRM_Core_Form::formatParamsForPaymentProcessor()
591 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
592 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
593 foreach ($nameFields as $field) {
594 if (!empty($params[$field])) {
598 // There are only 3 - we can iterate through them twice :-)
599 foreach ($nameFields as $field) {
600 if (!empty($params['billing_' . $field])) {
601 $params[$field] = $params['billing_' . $field];
603 $params['preserveDBName'] = TRUE;
609 * Resolve a state province string (UT or Utah) to an ID.
611 * If country has been passed in we should select a state belonging to that country.
613 * Alternatively we should choose from enabled countries, prioritising the default country.
615 * @param array $values
616 * @param int|null $countryID
620 * @throws \CRM_Core_Exception
622 protected static function resolveStateProvinceID($values, $countryID) {
625 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
626 if (CRM_Utils_Array
::lookupValue($values,
631 return $values['state_province_id'];
633 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
634 if (CRM_Utils_Array
::lookupValue($values,
639 return $values['state_province_id'];
644 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
645 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
646 // prefer matching country..
647 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, array('country_id' => Civi
::settings()->get('defaultContactCountry')));
648 if (CRM_Utils_Array
::lookupValue($values,
653 return $values['state_province_id'];
656 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
657 if (CRM_Utils_Array
::lookupValue($values,
662 return $values['state_province_id'];
665 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
666 if (CRM_Utils_Array
::lookupValue($values,
671 return $values['state_province_id'];
673 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
674 if (CRM_Utils_Array
::lookupValue($values,
679 return $values['state_province_id'];
687 * Get the relevant location entity for the array key.
689 * Based on the field name we determine which location entity
690 * we are dealing with. Apart from a few specific ones they
691 * are mostly 'address' (the default).
693 * @param string $fieldName
697 protected static function getLocationEntityForKey($fieldName) {
698 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
701 if ($fieldName === 'phone_ext') {
708 * Create last viewed link to recently updated contact.
710 * @param array $crudLinkSpec
711 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
712 * - entity_table: string, eg "civicrm_contact"
716 * NULL if unavailable, or
717 * [path: string, query: string, title: string]
718 * @see CRM_Utils_System::createDefaultCrudLink
720 public function createDefaultCrudLink($crudLinkSpec) {
721 switch ($crudLinkSpec['action']) {
722 case CRM_Core_Action
::VIEW
:
724 'title' => $this->display_name
,
725 'path' => 'civicrm/contact/view',
733 case CRM_Core_Action
::UPDATE
:
735 'title' => $this->display_name
,
736 'path' => 'civicrm/contact/add',
739 'action' => 'update',
749 * Get the values for pseudoconstants for name->value and reverse.
753 * This is called specifically from the contact import parser & should be moved there
754 * as it is not truly a generic function.
756 * @param array $defaults
757 * (reference) the default values, some of which need to be resolved.
758 * @param bool $reverse
759 * Always true as this function is only called from one place..
761 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
762 // Hack for birth_date.
763 if (!empty($defaults['birth_date'])) {
764 if (is_array($defaults['birth_date'])) {
765 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
769 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
770 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
771 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
772 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
774 //lookup value of email/postal greeting, addressee, CRM-4575
775 foreach (self
::$_greetingTypes as $greeting) {
776 $filterCondition = array(
777 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
778 'greeting_type' => $greeting,
780 CRM_Utils_Array
::lookupValue($defaults, $greeting,
781 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
785 $blocks = array('address', 'im', 'phone');
786 foreach ($blocks as $name) {
787 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
790 foreach ($defaults[$name] as $count => & $values) {
792 //get location type id.
793 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
795 if ($name == 'address') {
796 // FIXME: lookupValue doesn't work for vcard_name
797 if (!empty($values['location_type_id'])) {
798 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
799 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
802 if (!CRM_Utils_Array
::lookupValue($values,
804 CRM_Core_PseudoConstant
::country(),
809 CRM_Utils_Array
::lookupValue($values,
811 CRM_Core_PseudoConstant
::countryIsoCode(),
815 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
816 if ($stateProvinceID) {
817 $values['state_province_id'] = $stateProvinceID;
820 if (!empty($values['state_province_id'])) {
821 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
824 $countyList = CRM_Core_PseudoConstant
::county();
826 CRM_Utils_Array
::lookupValue($values,
834 CRM_Utils_Array
::lookupValue($values,
836 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
841 if ($name == 'phone') {
842 CRM_Utils_Array
::lookupValue($values,
844 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
849 // Kill the reference.
856 * Fetch object based on array of properties.
858 * @param array $params
859 * (reference ) an assoc array of name/value pairs.
860 * @param array $defaults
861 * (reference ) an assoc array to hold the name / value pairs.
862 * in a hierarchical manner
863 * @param bool $microformat
864 * For location in microformat.
866 * @return CRM_Contact_BAO_Contact
868 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
869 if (array_key_exists('contact_id', $params)) {
870 $params['id'] = $params['contact_id'];
872 elseif (array_key_exists('id', $params)) {
873 $params['contact_id'] = $params['id'];
876 $contact = self
::getValues($params, $defaults);
878 unset($params['id']);
880 //get the block information for this contact
881 $entityBlock = array('contact_id' => $params['contact_id']);
882 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
883 $defaults = array_merge($defaults, $blocks);
884 foreach ($blocks as $block => $value) {
885 $contact->$block = $value;
888 if (!isset($params['noNotes'])) {
889 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
892 if (!isset($params['noRelationships'])) {
893 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
896 if (!isset($params['noGroups'])) {
897 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
900 if (!isset($params['noWebsite'])) {
901 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
908 * Get the display name of a contact.
913 * @return null|string
914 * display name of the contact if found
916 public static function displayName($id) {
919 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
926 * Delete a contact and all its associated records.
929 * Id of the contact to delete.
930 * @param bool $restore
931 * Whether to actually restore, not delete.
932 * @param bool $skipUndelete
933 * Whether to force contact delete or not.
934 * @param bool $checkPermissions
937 * Was contact deleted?
939 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
944 // If trash is disabled in system settings then we always skip
945 if (!Civi
::settings()->get('contact_undelete')) {
946 $skipUndelete = TRUE;
949 // make sure we have edit permission for this contact
951 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
952 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
958 // Restrict contact to be delete if contact has financial trxns
960 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
964 // make sure this contact_id does not have any membership types
965 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
968 'member_of_contact_id'
970 if ($membershipTypeID) {
974 $contact = new CRM_Contact_DAO_Contact();
976 if (!$contact->find(TRUE)) {
980 $contactType = $contact->contact_type
;
981 // currently we only clear employer cache.
982 // we are now deleting inherited membership if any.
983 if ($contact->contact_type
== 'Organization') {
984 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
985 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
986 if (!empty($relationshipDtls)) {
987 foreach ($relationshipDtls as $rId => $details) {
988 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
991 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
995 return self
::contactTrashRestore($contact, TRUE);
998 // start a new transaction
999 $transaction = new CRM_Core_Transaction();
1001 if ($skipUndelete) {
1002 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
1004 //delete billing address if exists.
1005 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
1007 // delete the log entries since we dont have triggers enabled as yet
1008 $logDAO = new CRM_Core_DAO_Log();
1009 $logDAO->entity_table
= 'civicrm_contact';
1010 $logDAO->entity_id
= $id;
1013 // delete contact participants CRM-12155
1014 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
1016 // delete contact contributions CRM-12155
1017 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
1019 // do activity cleanup, CRM-5604
1020 CRM_Activity_BAO_Activity
::cleanupActivity($id);
1022 // delete all notes related to contact
1023 CRM_Core_BAO_Note
::cleanContactNotes($id);
1025 // delete cases related to contact
1026 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
1027 if (!empty($contactCases)) {
1028 foreach ($contactCases as $caseId) {
1029 //check if case is associate with other contact or not.
1030 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
1031 if (count($caseContactId) <= 1) {
1032 CRM_Case_BAO_Case
::deleteCase($caseId);
1040 self
::contactTrashRestore($contact);
1043 //delete the contact id from recently view
1044 CRM_Utils_Recent
::delContact($id);
1045 self
::updateContactCache($id, empty($restore));
1047 // delete any prevnext/dupe cache entry
1048 // These two calls are redundant in default deployments, but they're
1049 // meaningful if "prevnext" is memory-backed.
1050 Civi
::service('prevnext')->deleteItem($id);
1051 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
1053 $transaction->commit();
1055 if ($skipUndelete) {
1056 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1063 * Action to update any caches relating to a recently update contact.
1065 * I was going to call this from delete as well as from create to ensure the delete is being
1066 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1067 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1068 * where the call involved a subquery that was locking the table.
1070 * @param int $contactID
1071 * @param bool $isTrashed
1073 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1076 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1077 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1078 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1079 // but this should not cause any change as long as contacts are not being trashed outside the
1080 // main functions for that.
1081 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
1084 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1089 * Delete the image of a contact.
1092 * Id of the contact.
1095 * Was contact image deleted?
1097 public static function deleteContactImage($id) {
1102 $contact = new self();
1104 $contact->image_URL
= 'null';
1111 * Return proportional height and width of the image.
1113 * @param int $imageWidth
1116 * @param int $imageHeight
1120 * Thumb dimension of image
1122 public static function getThumbSize($imageWidth, $imageHeight) {
1124 if ($imageWidth && $imageHeight) {
1125 $imageRatio = $imageWidth / $imageHeight;
1130 if ($imageRatio > 1) {
1131 $imageThumbWidth = $thumbWidth;
1132 $imageThumbHeight = round($thumbWidth / $imageRatio);
1135 $imageThumbHeight = $thumbWidth;
1136 $imageThumbWidth = round($thumbWidth * $imageRatio);
1139 return array($imageThumbWidth, $imageThumbHeight);
1143 * Validate type of contact image.
1145 * @param array $params
1146 * @param string $imageIndex
1147 * Index of image field.
1148 * @param string $statusMsg
1149 * Status message to be set after operation.
1150 * @param string $opType
1151 * Type of operation like fatal, bounce etc.
1154 * true if valid image extension
1156 public static function processImageParams(
1158 $imageIndex = 'image_URL',
1172 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1173 $photo = basename($params[$imageIndex]['name']);
1174 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1178 unset($params[$imageIndex]);
1180 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1182 if ($opType == 'status') {
1183 CRM_Core_Session
::setStatus($statusMsg, ts('Error'), 'error');
1185 // FIXME: additional support for fatal, bounce etc could be added.
1191 * Extract contact id from url for deleting contact image.
1193 public static function processImage() {
1195 $action = CRM_Utils_Request
::retrieve('action', 'String');
1196 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1197 // retrieve contact id in case of Profile context
1198 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1199 $cid = $cid ?
$cid : $id;
1200 if ($action & CRM_Core_Action
::DELETE
) {
1201 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1202 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1203 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1204 $session = CRM_Core_Session
::singleton();
1205 $toUrl = $session->popUserContext();
1206 CRM_Utils_System
::redirect($toUrl);
1212 * Function to set is_delete true or restore deleted contact.
1214 * @param CRM_Contact_DAO_Contact $contact
1215 * Contact DAO object.
1216 * @param bool $restore
1217 * True to set the is_delete = 1 else false to restore deleted contact,
1218 * i.e. is_delete = 0
1222 public static function contactTrashRestore($contact, $restore = FALSE) {
1223 $updateParams = array(
1224 'id' => $contact->id
,
1225 'is_deleted' => $restore ?
0 : 1,
1228 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1230 $params = array(1 => array($contact->id
, 'Integer'));
1232 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1233 CRM_Core_DAO
::executeQuery($query, $params);
1236 $contact->copyValues($updateParams);
1238 CRM_Core_BAO_Log
::register($contact->id
, 'civicrm_contact', $contact->id
);
1240 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1246 * Get contact type for a contact.
1249 * Id of the contact whose contact type is needed.
1252 * contact_type if $id found else null ""
1254 public static function getContactType($id) {
1255 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1259 * Get contact sub type for a contact.
1262 * Id of the contact whose contact sub type is needed.
1264 * @param string $implodeDelimiter
1267 * contact_sub_type if $id found else null ""
1269 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1270 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1272 return $implodeDelimiter ?
NULL : array();
1275 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1277 if ($implodeDelimiter) {
1278 $subtype = implode($implodeDelimiter, $subtype);
1284 * Get pair of contact-type and sub-type for a contact.
1287 * Id of the contact whose contact sub/contact type is needed.
1291 public static function getContactTypes($id) {
1292 $params = array('id' => $id);
1294 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1297 array('contact_type', 'contact_sub_type')
1301 $contactTypes = array();
1302 if ($contact->contact_sub_type
) {
1303 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1305 array_unshift($contactTypes, $contact->contact_type
);
1307 return $contactTypes;
1310 CRM_Core_Error
::fatal();
1315 * Combine all the importable fields from the lower levels object.
1317 * The ordering is important, since currently we do not have a weight
1318 * scheme. Adding weight is super important
1320 * @param int|string $contactType contact Type
1321 * @param bool $status
1322 * Status is used to manipulate first title.
1323 * @param bool $showAll
1324 * If true returns all fields (includes disabled fields).
1325 * @param bool $isProfile
1326 * If its profile mode.
1327 * @param bool $checkPermission
1328 * If false, do not include permissioning clause (for custom data).
1330 * @param bool $withMultiCustomFields
1333 * array of importable Fields
1335 public static function importableFields(
1336 $contactType = 'Individual',
1340 $checkPermission = TRUE,
1341 $withMultiCustomFields = FALSE
1343 if (empty($contactType)) {
1344 $contactType = 'All';
1347 $cacheKeyString = "importableFields $contactType";
1348 $cacheKeyString .= $status ?
'_1' : '_0';
1349 $cacheKeyString .= $showAll ?
'_1' : '_0';
1350 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1351 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1352 $cacheKeyString .= '_' . CRM_Core_Config
::domainID() . '_';
1354 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1357 // check if we can retrieve from database cache
1358 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1362 $fields = CRM_Contact_DAO_Contact
::import();
1364 // get the fields thar are meant for contact types
1365 if (in_array($contactType, array(
1371 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1374 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1375 CRM_Core_DAO_Phone
::import(),
1376 CRM_Core_DAO_Email
::import(),
1377 CRM_Core_DAO_IM
::import(TRUE),
1378 CRM_Core_DAO_OpenID
::import()
1381 $locationFields = array_merge($locationFields,
1382 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1390 foreach ($locationFields as $key => $field) {
1391 $locationFields[$key]['hasLocationType'] = TRUE;
1394 $fields = array_merge($fields, $locationFields);
1396 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1397 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1400 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1401 $fields['url']['hasWebsiteType'] = TRUE;
1403 if ($contactType != 'All') {
1404 $fields = array_merge($fields,
1405 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1410 $withMultiCustomFields
1413 //unset the fields, which are not related to their
1415 $commonValues = array(
1416 'Individual' => array(
1420 'organization_name',
1422 'Household' => array(
1432 'organization_name',
1440 'Organization' => array(
1455 foreach ($commonValues[$contactType] as $value) {
1456 unset($fields[$value]);
1460 foreach (array('Individual', 'Household', 'Organization') as $type) {
1461 $fields = array_merge($fields,
1462 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1467 $withMultiCustomFields
1474 $fields = array_merge($fields, array(
1476 'title' => ts('Group(s)'),
1480 'title' => ts('Tag(s)'),
1484 'title' => ts('Note'),
1487 'communication_style_id' => array(
1488 'title' => ts('Communication Style'),
1489 'name' => 'communication_style_id',
1494 //Sorting fields in alphabetical order(CRM-1507)
1495 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1497 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1500 self
::$_importableFields[$cacheKeyString] = $fields;
1504 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1505 self
::$_importableFields[$cacheKeyString]
1509 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1510 self
::$_importableFields[$cacheKeyString]
1518 * Combine all the exportable fields from the lower levels object.
1520 * Currently we are using importable fields as exportable fields
1522 * @param int|string $contactType contact Type
1523 * @param bool $status
1524 * True while exporting primary contacts.
1525 * @param bool $export
1526 * True when used during export.
1527 * @param bool $search
1528 * True when used during search, might conflict with export param?.
1530 * @param bool $withMultiRecord
1531 * @param bool $checkPermissions
1533 * array of exportable Fields
1535 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1536 if (empty($contactType)) {
1537 $contactType = 'All';
1540 $cacheKeyString = "exportableFields $contactType";
1541 $cacheKeyString .= $export ?
'_1' : '_0';
1542 $cacheKeyString .= $status ?
'_1' : '_0';
1543 $cacheKeyString .= $search ?
'_1' : '_0';
1544 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1545 //calculates custom fields takes into account the logged in user & caches that for all users
1546 //as an interim fix we will cache the fields by contact
1547 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1549 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1550 if (!self
::$_exportableFields) {
1551 self
::$_exportableFields = array();
1554 // check if we can retrieve from database cache
1555 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1558 $fields = CRM_Contact_DAO_Contact
::export();
1560 // The fields are meant for contact types.
1561 if (in_array($contactType, array(
1567 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1569 // add current employer for individuals
1570 $fields = array_merge($fields, array(
1571 'current_employer' =>
1573 'name' => 'organization_name',
1574 'title' => ts('Current Employer'),
1578 $locationType = array(
1579 'location_type' => array(
1580 'name' => 'location_type',
1581 'where' => 'civicrm_location_type.name',
1582 'title' => ts('Location Type'),
1586 $IMProvider = array(
1587 'im_provider' => array(
1588 'name' => 'im_provider',
1589 'where' => 'civicrm_im.provider_id',
1590 'title' => ts('IM Provider'),
1594 $locationFields = array_merge($locationType,
1595 CRM_Core_DAO_Address
::export(),
1596 CRM_Core_DAO_Phone
::export(),
1597 CRM_Core_DAO_Email
::export(),
1599 CRM_Core_DAO_IM
::export(TRUE),
1600 CRM_Core_DAO_OpenID
::export()
1603 $locationFields = array_merge($locationFields,
1604 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1607 foreach ($locationFields as $key => $field) {
1608 $locationFields[$key]['hasLocationType'] = TRUE;
1611 $fields = array_merge($fields, $locationFields);
1614 $fields = array_merge($fields,
1615 CRM_Core_DAO_Worldregion
::export()
1618 $fields = array_merge($fields,
1619 CRM_Contact_DAO_Contact
::export()
1623 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1625 if ($contactType != 'All') {
1626 $fields = array_merge($fields,
1627 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1636 $fields = array_merge($fields,
1637 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1641 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1644 $fields = array_merge($fields, array(
1646 'title' => ts('Group(s)'),
1650 'title' => ts('Tag(s)'),
1654 'title' => ts('Note(s)'),
1660 $fields = array_merge($fields, array(
1662 'title' => ts('Group(s)'),
1666 'title' => ts('Tag(s)'),
1670 'title' => ts('Note(s)'),
1676 //Sorting fields in alphabetical order(CRM-1507)
1677 foreach ($fields as $k => $v) {
1678 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1681 $fields = array_merge($sortArray, $fields);
1682 //unset the field which are not related to their contact type.
1683 if ($contactType != 'All') {
1684 $commonValues = array(
1685 'Individual' => array(
1689 'organization_name',
1690 'email_greeting_custom',
1691 'postal_greeting_custom',
1694 'Household' => array(
1704 'organization_name',
1712 'email_greeting_custom',
1713 'postal_greeting_custom',
1718 'Organization' => array(
1729 'email_greeting_custom',
1730 'postal_greeting_custom',
1740 foreach ($commonValues[$contactType] as $value) {
1741 unset($fields[$value]);
1745 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1747 self
::$_exportableFields[$cacheKeyString] = $fields;
1751 $fields = self
::$_exportableFields[$cacheKeyString];
1754 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1755 self
::$_exportableFields[$cacheKeyString]
1763 * Get the all contact details (Hierarchical).
1765 * @param int $contactId
1767 * @param array $fields
1773 public static function getHierContactDetails($contactId, $fields) {
1774 $params = array(array('contact_id', '=', $contactId, 0, 0));
1777 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1779 // We don't know the contents of return properties, but we need the lower
1780 // level ids of the contact so add a few fields.
1781 $returnProperties['first_name'] = 1;
1782 $returnProperties['organization_name'] = 1;
1783 $returnProperties['household_name'] = 1;
1784 $returnProperties['contact_type'] = 1;
1785 $returnProperties['contact_sub_type'] = 1;
1786 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1790 * Given a set of flat profile style field names, create a hierarchy.
1792 * This is for the query to use, create the right sql.
1795 * @param int $contactId
1799 * A hierarchical property tree if appropriate
1801 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1802 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1804 $returnProperties = array();
1806 $multipleFields = array('website' => 'url');
1807 foreach ($fields as $name => $dontCare) {
1808 if (strpos($name, '-') !== FALSE) {
1809 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1811 if (!in_array($fieldName, $multipleFields)) {
1812 if ($id == 'Primary') {
1813 $locationTypeName = 1;
1816 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1817 if (!$locationTypeName) {
1822 if (empty($returnProperties['location'])) {
1823 $returnProperties['location'] = array();
1825 if (empty($returnProperties['location'][$locationTypeName])) {
1826 $returnProperties['location'][$locationTypeName] = array();
1827 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1829 if (in_array($fieldName, array(
1837 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1840 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1843 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1844 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1847 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1851 $returnProperties['website'][$id][$fieldName] = 1;
1855 $returnProperties[$name] = 1;
1859 return $returnProperties;
1863 * Return the primary location type of a contact.
1865 * $params int $contactId contact_id
1866 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1867 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1869 * @param int $contactId
1870 * @param bool $skipDefaultPriamry
1871 * @param null $block
1874 * $locationType location_type_id
1876 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1878 $entityBlock = array('contact_id' => $contactId);
1879 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1880 foreach ($blocks[$block] as $key => $value) {
1881 if (!empty($value['is_primary'])) {
1882 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1889 IF ( civicrm_email.location_type_id IS NULL,
1890 IF ( civicrm_address.location_type_id IS NULL,
1891 IF ( civicrm_phone.location_type_id IS NULL,
1892 IF ( civicrm_im.location_type_id IS NULL,
1893 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1894 ,civicrm_im.location_type_id)
1895 ,civicrm_phone.location_type_id)
1896 ,civicrm_address.location_type_id)
1897 ,civicrm_email.location_type_id) as locationType
1898 FROM civicrm_contact
1899 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1900 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1901 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1902 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1903 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1904 WHERE civicrm_contact.id = %1 ";
1906 $params = array(1 => array($contactId, 'Integer'));
1908 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1910 $locationType = NULL;
1911 if ($dao->fetch()) {
1912 $locationType = $dao->locationType
;
1915 if (isset($locationType)) {
1916 return $locationType;
1918 elseif ($skipDefaultPriamry) {
1919 // if there is no primary contact location then return null
1923 // if there is no primart contact location, then return default
1924 // location type of the system
1925 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1926 return $defaultLocationType->id
;
1931 * Get the display name, primary email and location type of a contact.
1934 * Id of the contact.
1937 * Array of display_name, email if found, do_not_email or (null,null,null)
1939 public static function getContactDetails($id) {
1940 // check if the contact type
1941 $contactType = self
::getContactType($id);
1943 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1946 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1947 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1948 WHERE civicrm_contact.id = %1
1949 ORDER BY civicrm_email.is_primary DESC";
1950 $params = array(1 => array($id, 'Integer'));
1951 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1953 if ($dao->fetch()) {
1954 if ($contactType == 'Individual') {
1955 if ($dao->first_name ||
$dao->last_name
) {
1956 $name = "{$dao->first_name} {$dao->last_name}";
1959 $name = $dao->display_name
;
1963 $name = $dao->display_name
;
1965 $email = $dao->email
;
1966 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1967 $onHold = $dao->on_hold ?
TRUE : FALSE;
1968 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1969 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1971 return array(NULL, NULL, NULL, NULL, NULL);
1975 * Add/edit/register contacts through profile.
1977 * @param array $params
1978 * Array of profile fields to be edited/added.
1979 * @param array $fields
1980 * Array of fields from UFGroup.
1981 * @param int $contactID
1982 * Id of the contact to be edited/added.
1983 * @param int $addToGroupID
1984 * Specifies the default group to which contact is added.
1985 * @param int $ufGroupId
1986 * Uf group id (profile id).
1987 * @param string $ctype
1988 * @param bool $visibility
1989 * Basically lets us know where this request is coming from.
1990 * if via a profile from web, we restrict what groups are changed
1993 * contact id created/edited
1995 public static function createProfileContact(
1999 $addToGroupID = NULL,
2004 // add ufGroupID to params array ( CRM-2012 )
2006 $params['uf_group_id'] = $ufGroupId;
2008 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
2010 // If a user has logged in, or accessed via a checksum
2011 // Then deliberately 'blanking' a value in the profile should remove it from their record
2012 $session = CRM_Core_Session
::singleton();
2013 $params['updateBlankLocInfo'] = TRUE;
2014 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
2015 $params['updateBlankLocInfo'] = FALSE;
2020 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
2024 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
2027 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
2029 // manage is_opt_out
2030 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
2031 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
2032 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
2033 $data['is_opt_out'] = $isOptOut;
2034 // on change, create new civicrm_subscription_history entry
2035 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
2037 'contact_id' => $contactDetails['contact_id'],
2038 'status' => $isOptOut ?
'Removed' : 'Added',
2041 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
2045 $contact = self
::create($data);
2047 // contact is null if the profile does not have any contact fields
2049 $contactID = $contact->id
;
2052 if (empty($contactID)) {
2053 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
2056 // Process group and tag
2057 if (!empty($fields['group'])) {
2059 // this for sure means we are coming in via profile since i added it to fix
2060 // removing contacts from user groups -- lobo
2064 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2067 if (!empty($fields['tag']) && array_key_exists('tag', $params)) {
2068 // Convert comma separated form values from select2 v3
2069 $tags = is_array($params['tag']) ?
$params['tag'] : array_fill_keys(array_filter(explode(',', $params['tag'])), 1);
2070 CRM_Core_BAO_EntityTag
::create($tags, 'civicrm_contact', $contactID);
2073 //to add profile in default group
2074 if (is_array($addToGroupID)) {
2075 $contactIds = array($contactID);
2076 foreach ($addToGroupID as $groupId) {
2077 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2080 elseif ($addToGroupID) {
2081 $contactIds = array($contactID);
2082 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2085 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
2088 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2091 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2097 * Format profile contact parameters.
2099 * @param array $params
2101 * @param int $contactID
2102 * @param int $ufGroupId
2103 * @param null $ctype
2104 * @param bool $skipCustom
2108 public static function formatProfileContactParams(
2117 $data = $contactDetails = array();
2119 // get the contact details (hier)
2121 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
2123 $contactDetails = $details[$contactID];
2124 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
2125 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
2128 //we should get contact type only if contact
2130 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2132 //special case to handle profile with only contact fields
2133 if ($data['contact_type'] == 'Contact') {
2134 $data['contact_type'] = 'Individual';
2136 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2137 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2141 $data['contact_type'] = $ctype;
2144 $data['contact_type'] = 'Individual';
2148 //fix contact sub type CRM-5125
2149 if (array_key_exists('contact_sub_type', $params) &&
2150 !empty($params['contact_sub_type'])
2152 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2154 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2155 !empty($params['contact_sub_type_hidden'])
2157 // if profile was used, and had any subtype, we obtain it from there
2158 //CRM-13596 - add to existing contact types, rather than overwriting
2159 if (empty($data['contact_sub_type'])) {
2160 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
2161 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2164 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2165 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2166 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2167 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2168 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2173 if ($ctype == 'Organization') {
2174 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2176 elseif ($ctype == 'Household') {
2177 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2180 $locationType = array();
2185 $data['contact_id'] = $contactID;
2186 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2189 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2190 $defaultLocationId = $defaultLocation->id
;
2193 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2195 $blocks = array('email', 'phone', 'im', 'openid');
2197 $multiplFields = array('url');
2198 // prevent overwritten of formatted array, reset all block from
2199 // params if it is not in valid format (since import pass valid format)
2200 foreach ($blocks as $blk) {
2201 if (array_key_exists($blk, $params) &&
2202 !is_array($params[$blk])
2204 unset($params[$blk]);
2208 $primaryPhoneLoc = NULL;
2209 $session = CRM_Core_Session
::singleton();
2210 foreach ($params as $key => $value) {
2211 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2213 if ($locTypeId == 'Primary') {
2215 if (in_array($fieldName, $blocks)) {
2216 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2219 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2221 $primaryLocationType = $locTypeId;
2224 $locTypeId = $defaultLocationId;
2228 if (is_numeric($locTypeId) &&
2229 !in_array($fieldName, $multiplFields) &&
2230 substr($fieldName, 0, 7) != 'custom_'
2232 $index = $locTypeId;
2234 if (is_numeric($typeId)) {
2235 $index .= '-' . $typeId;
2237 if (!in_array($index, $locationType)) {
2238 $locationType[$count] = $index;
2242 $loc = CRM_Utils_Array
::key($index, $locationType);
2244 $blockName = self
::getLocationEntityForKey($fieldName);
2246 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2248 //set is_billing true, for location type "Billing"
2249 if ($locTypeId == $billingLocationTypeId) {
2250 $data[$blockName][$loc]['is_billing'] = 1;
2254 //get the primary location type
2255 if ($locTypeId == $primaryLocationType) {
2256 $data[$blockName][$loc]['is_primary'] = 1;
2259 elseif ($locTypeId == $defaultLocationId) {
2260 $data[$blockName][$loc]['is_primary'] = 1;
2263 if (in_array($fieldName, array('phone'))) {
2265 $data['phone'][$loc]['phone_type_id'] = $typeId;
2268 $data['phone'][$loc]['phone_type_id'] = '';
2270 $data['phone'][$loc]['phone'] = $value;
2272 //special case to handle primary phone with different phone types
2273 // in this case we make first phone type as primary
2274 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2275 $primaryPhoneLoc = $loc;
2278 if ($loc != $primaryPhoneLoc) {
2279 unset($data['phone'][$loc]['is_primary']);
2282 elseif ($fieldName == 'email') {
2283 $data['email'][$loc]['email'] = $value;
2284 if (empty($contactID)) {
2285 $data['email'][$loc]['is_primary'] = 1;
2288 elseif ($fieldName == 'im') {
2289 if (isset($params[$key . '-provider_id'])) {
2290 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2292 if (strpos($key, '-provider_id') !== FALSE) {
2293 $data['im'][$loc]['provider_id'] = $params[$key];
2296 $data['im'][$loc]['name'] = $value;
2299 elseif ($fieldName == 'openid') {
2300 $data['openid'][$loc]['openid'] = $value;
2303 if ($fieldName === 'state_province') {
2305 if (is_numeric($value) && ((int ) $value) >= 1000) {
2306 $data['address'][$loc]['state_province_id'] = $value;
2308 elseif (empty($value)) {
2309 $data['address'][$loc]['state_province_id'] = '';
2312 $data['address'][$loc]['state_province'] = $value;
2315 elseif ($fieldName === 'country') {
2317 if (is_numeric($value) && ((int ) $value) >= 1000
2319 $data['address'][$loc]['country_id'] = $value;
2321 elseif (empty($value)) {
2322 $data['address'][$loc]['country_id'] = '';
2325 $data['address'][$loc]['country'] = $value;
2328 elseif ($fieldName === 'county') {
2329 $data['address'][$loc]['county_id'] = $value;
2331 elseif ($fieldName == 'address_name') {
2332 $data['address'][$loc]['name'] = $value;
2334 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2335 $data['address'][$loc][substr($fieldName, 8)] = $value;
2338 $data[$blockName][$loc][$fieldName] = $value;
2343 if (substr($key, 0, 4) === 'url-') {
2344 $websiteField = explode('-', $key);
2345 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2346 $data['website'][$websiteField[1]]['url'] = $value;
2348 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2349 //save email/postal greeting and addressee values if any, CRM-4575
2350 $data[$key . '_id'] = $value;
2352 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2353 // for autocomplete transfer hidden value instead of label
2354 if ($params[$key] && isset($params[$key . '_id'])) {
2355 $value = $params[$key . '_id'];
2358 // we need to append time with date
2359 if ($params[$key] && isset($params[$key . '_time'])) {
2360 $value .= ' ' . $params[$key . '_time'];
2363 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2364 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2365 ($value == '' ||
!isset($value))
2371 if (!empty($params['customRecordValues'])) {
2372 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2373 foreach ($params['customRecordValues'] as $recId => $customFields) {
2374 if (is_array($customFields) && !empty($customFields)) {
2375 foreach ($customFields as $customFieldName) {
2376 if ($customFieldName == $key) {
2386 //CRM-13596 - check for contact_sub_type_hidden first
2387 if (array_key_exists('contact_sub_type_hidden', $params)) {
2388 $type = $params['contact_sub_type_hidden'];
2391 $type = $data['contact_type'];
2392 if (!empty($data['contact_sub_type'])) {
2393 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2397 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2407 elseif ($key == 'edit') {
2411 if ($key == 'location') {
2412 foreach ($value as $locationTypeId => $field) {
2413 foreach ($field as $block => $val) {
2414 if ($block == 'address' && array_key_exists('address_name', $val)) {
2415 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2420 if ($key == 'phone' && isset($params['phone_ext'])) {
2421 $data[$key] = $value;
2422 foreach ($value as $cnt => $phoneBlock) {
2423 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2424 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2428 elseif (in_array($key, array(
2437 )) && ($value == '' ||
!isset($value)) &&
2438 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2439 ($key == 'current_employer' && empty($params['current_employer']))) {
2440 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2441 // to avoid update with empty values
2445 $data[$key] = $value;
2451 if (!isset($data['contact_type'])) {
2452 $data['contact_type'] = 'Individual';
2455 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2456 $privacy = CRM_Core_SelectValues
::privacy();
2457 foreach ($privacy as $key => $value) {
2458 if (array_key_exists($key, $fields)) {
2459 // do not reset values for existing contacts, if fields are added to a profile
2460 if (array_key_exists($key, $params)) {
2461 $data[$key] = $params[$key];
2462 if (empty($params[$key])) {
2466 elseif (!$contactID) {
2472 return array($data, $contactDetails);
2476 * Find the get contact details.
2478 * This function does not respect ACLs for now, which might need to be rectified at some
2479 * stage based on how its used.
2481 * @param string $mail
2482 * Primary email address of the contact.
2483 * @param string $ctype
2486 * @return object|null
2487 * $dao contact details
2489 public static function matchContactOnEmail($mail, $ctype = NULL) {
2490 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2491 $mail = $strtolower(trim($mail));
2493 SELECT civicrm_contact.id as contact_id,
2494 civicrm_contact.hash as hash,
2495 civicrm_contact.contact_type as contact_type,
2496 civicrm_contact.contact_sub_type as contact_sub_type
2497 FROM civicrm_contact
2498 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2500 if (Civi
::settings()->get('uniq_email_per_site')) {
2501 // try to find a match within a site (multisite).
2502 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2503 if (!empty($groups)) {
2505 INNER JOIN civicrm_group_contact gc ON
2506 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2511 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2512 $p = array(1 => array($mail, 'String'));
2515 $query .= " AND civicrm_contact.contact_type = %3";
2516 $p[3] = array($ctype, 'String');
2519 $query .= " ORDER BY civicrm_email.is_primary DESC";
2521 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2523 if ($dao->fetch()) {
2530 * Find the contact details associated with an OpenID.
2532 * @param string $openId
2533 * OpenId of the contact.
2534 * @param string $ctype
2537 * @return object|null
2538 * $dao contact details
2540 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2541 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2542 $openId = $strtolower(trim($openId));
2544 SELECT civicrm_contact.id as contact_id,
2545 civicrm_contact.hash as hash,
2546 civicrm_contact.contact_type as contact_type,
2547 civicrm_contact.contact_sub_type as contact_sub_type
2548 FROM civicrm_contact
2549 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2550 WHERE civicrm_openid.openid = %1";
2551 $p = array(1 => array($openId, 'String'));
2554 $query .= " AND civicrm_contact.contact_type = %3";
2555 $p[3] = array($ctype, 'String');
2558 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2560 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2562 if ($dao->fetch()) {
2569 * Get primary email of the contact.
2571 * @param int $contactID
2575 * Email address if present else null
2577 public static function getPrimaryEmail($contactID) {
2578 // fetch the primary email
2580 SELECT civicrm_email.email as email
2581 FROM civicrm_contact
2582 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2583 WHERE civicrm_email.is_primary = 1
2584 AND civicrm_contact.id = %1";
2585 $p = array(1 => array($contactID, 'Integer'));
2586 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2589 if ($dao->fetch()) {
2590 $email = $dao->email
;
2596 * Function to get primary OpenID of the contact.
2598 * @param int $contactID
2602 * >openid OpenID if present else null
2604 public static function getPrimaryOpenId($contactID) {
2605 // fetch the primary OpenID
2607 SELECT civicrm_openid.openid as openid
2608 FROM civicrm_contact
2609 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2610 WHERE civicrm_contact.id = %1
2611 AND civicrm_openid.is_primary = 1";
2612 $p = array(1 => array($contactID, 'Integer'));
2613 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2616 if ($dao->fetch()) {
2617 $openId = $dao->openid
;
2623 * Fetch the object and store the values in the values array.
2625 * @param array $params
2626 * Input parameters to find object.
2627 * @param array $values
2628 * Output values of the object.
2630 * @return CRM_Contact_BAO_Contact|null
2631 * The found object or null
2633 public static function getValues(&$params, &$values) {
2634 $contact = new CRM_Contact_BAO_Contact();
2636 $contact->copyValues($params);
2638 if ($contact->find(TRUE)) {
2640 CRM_Core_DAO
::storeValues($contact, $values);
2643 foreach (self
::$_commPrefs as $name) {
2644 if (isset($contact->$name)) {
2645 $privacy[$name] = $contact->$name;
2649 if (!empty($privacy)) {
2650 $values['privacy'] = $privacy;
2653 // communication Prefferance
2654 $preffComm = $comm = array();
2655 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2656 $contact->preferred_communication_method
2658 foreach ($comm as $value) {
2659 $preffComm[$value] = 1;
2661 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2664 'preferred_communication_method' => array(
2665 'newName' => 'preferred_communication_method_display',
2666 'groupName' => 'preferred_communication_method',
2670 // @todo This can be figured out from metadata & we can avoid the uncached query.
2671 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2673 $values['preferred_communication_method'] = $preffComm;
2674 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2676 if ($contact->preferred_mail_format
) {
2677 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2678 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2681 // get preferred languages
2682 if (!empty($contact->preferred_language
)) {
2683 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2686 // Calculating Year difference
2687 if ($contact->birth_date
) {
2688 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2689 if ($birthDate < date('Ymd')) {
2690 $age = CRM_Utils_Date
::calculateAge($birthDate);
2691 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2692 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2696 $contact->contact_id
= $contact->id
;
2704 * Given the component name and returns the count of participation of contact.
2706 * @param string $component
2707 * Input component name.
2708 * @param int $contactId
2710 * @param string $tableName
2711 * Optional tableName if component is custom group.
2714 * total number in database
2716 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2718 switch ($component) {
2720 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2723 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2724 CRM_Contact_BAO_Relationship
::CURRENT
,
2733 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2736 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2739 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2742 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2744 case 'contribution':
2745 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2748 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2751 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2754 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2757 return CRM_Case_BAO_Case
::caseCount($contactId);
2760 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2764 'contact_id' => $contactId,
2767 'context' => 'activity',
2769 return CRM_Activity_BAO_Activity
::getActivitiesCount($input);
2772 $params = array('contact_id' => $contactId);
2773 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2776 $custom = explode('_', $component);
2777 if ($custom['0'] = 'custom') {
2779 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2781 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2782 return CRM_Core_DAO
::singleValueQuery($queryString);
2788 * Update contact greetings if an update has resulted in a custom field change.
2790 * @param array $updatedFields
2791 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2792 * @param array $contactParams
2793 * Parameters known about the contact. At minimum array('contact_id' => x).
2794 * Fields in this array will take precedence over DB fields (so far only
2795 * in the case of greeting id fields).
2797 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2798 $contactID = $contactParams['contact_id'];
2799 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2800 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2801 if (!empty($tokens['all']['contact'])) {
2802 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2803 if (!empty($affectedTokens)) {
2804 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2805 $contact = new CRM_Contact_BAO_Contact();
2806 $contact->id
= $contactID;
2807 CRM_Contact_BAO_Contact
::processGreetings($contact);
2813 * Process greetings and cache.
2815 * @param object $contact
2816 * Contact object after save.
2818 public static function processGreetings(&$contact) {
2820 //@todo this function does a lot of unnecessary loading.
2821 // ensureGreetingParamsAreSet now makes sure that the contact is
2822 // loaded and using updateGreetingsOnTokenFieldChange
2823 // allows us the possibility of only doing an update if required.
2825 // The contact object has not always required the
2826 // fields that are required to calculate greetings
2827 // so we need to retrieve it again.
2828 if ($contact->_query
!== FALSE) {
2829 $contact->find(TRUE);
2832 // store object values to an array
2833 $contactDetails = array();
2834 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2835 $contactDetails = array(array($contact->id
=> $contactDetails));
2837 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2838 $updateQueryString = array();
2840 //cache email and postal greeting to greeting display
2841 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2842 $emailGreetingString = $contact->email_greeting_custom
;
2844 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2845 // the filter value for Individual contact type is set to 1
2847 'contact_type' => $contact->contact_type
,
2848 'greeting_type' => 'email_greeting',
2851 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2852 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2853 $updateQueryString[] = " email_greeting_custom = NULL ";
2856 if ($contact->email_greeting_custom
) {
2857 $updateQueryString[] = " email_greeting_display = NULL ";
2861 if ($emailGreetingString) {
2862 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2865 'CRM_Contact_BAO_Contact'
2867 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2868 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2872 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2873 $postalGreetingString = $contact->postal_greeting_custom
;
2875 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2877 'contact_type' => $contact->contact_type
,
2878 'greeting_type' => 'postal_greeting',
2880 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2881 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2882 $updateQueryString[] = " postal_greeting_custom = NULL ";
2885 if ($contact->postal_greeting_custom
) {
2886 $updateQueryString[] = " postal_greeting_display = NULL ";
2890 if ($postalGreetingString) {
2891 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2894 'CRM_Contact_BAO_Contact'
2896 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2897 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2901 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2902 $addresseeString = $contact->addressee_custom
;
2904 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2906 'contact_type' => $contact->contact_type
,
2907 'greeting_type' => 'addressee',
2910 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2911 $addresseeString = $addressee[$contact->addressee_id
];
2912 $updateQueryString[] = " addressee_custom = NULL ";
2915 if ($contact->addressee_custom
) {
2916 $updateQueryString[] = " addressee_display = NULL ";
2920 if ($addresseeString) {
2921 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2924 'CRM_Contact_BAO_Contact'
2926 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2927 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2930 if (!empty($updateQueryString)) {
2931 $updateQueryString = implode(',', $updateQueryString);
2932 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2933 CRM_Core_DAO
::executeQuery($queryString);
2938 * Retrieve loc block ids w/ given condition.
2940 * @param int $contactId
2942 * @param array $criteria
2943 * Key => value pair which should be.
2944 * fulfill by return record ids.
2945 * @param string $condOperator
2946 * Operator use for grouping multiple conditions.
2949 * loc block ids which fulfill condition.
2951 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2952 $locBlockIds = array();
2954 return $locBlockIds;
2957 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2958 $name = strtolower($block);
2959 $className = "CRM_Core_DAO_$block";
2960 $blockDAO = new $className();
2962 // build the condition.
2963 if (is_array($criteria)) {
2964 $fields = $blockDAO->fields();
2965 $conditions = array();
2966 foreach ($criteria as $field => $value) {
2967 if (array_key_exists($field, $fields)) {
2968 $cond = "( $field = $value )";
2969 // value might be zero or null.
2970 if (!$value ||
strtolower($value) == 'null') {
2971 $cond = "( $field = 0 OR $field IS NULL )";
2973 $conditions[] = $cond;
2976 if (!empty($conditions)) {
2977 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2981 $blockDAO->contact_id
= $contactId;
2983 while ($blockDAO->fetch()) {
2984 $locBlockIds[$name][] = $blockDAO->id
;
2988 return $locBlockIds;
2992 * Build context menu items.
2994 * @param int $contactId
2997 * Array of context menu for logged in user.
2999 public static function contextMenu($contactId = NULL) {
3002 'title' => ts('View Contact'),
3004 'ref' => 'view-contact',
3005 'class' => 'no-popup',
3007 'permissions' => array('view all contacts'),
3010 'title' => ts('Edit Contact'),
3012 'ref' => 'edit-contact',
3013 'class' => 'no-popup',
3015 'permissions' => array('edit all contacts'),
3018 'title' => ts('Delete Contact'),
3020 'ref' => 'delete-contact',
3022 'permissions' => array('access deleted contacts', 'delete contacts'),
3024 'contribution' => array(
3025 'title' => ts('Add Contribution'),
3027 'ref' => 'new-contribution',
3028 'key' => 'contribution',
3029 'tab' => 'contribute',
3030 'component' => 'CiviContribute',
3031 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
3032 'reset=1&action=add&context=contribution'
3034 'permissions' => array(
3035 'access CiviContribute',
3036 'edit contributions',
3039 'participant' => array(
3040 'title' => ts('Register for Event'),
3042 'ref' => 'new-participant',
3043 'key' => 'participant',
3044 'tab' => 'participant',
3045 'component' => 'CiviEvent',
3046 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
3047 'permissions' => array(
3049 'edit event participants',
3052 'activity' => array(
3053 'title' => ts('Record Activity'),
3055 'ref' => 'new-activity',
3056 'key' => 'activity',
3057 'permissions' => array('edit all contacts'),
3060 'title' => ts('Add Pledge'),
3062 'ref' => 'new-pledge',
3065 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3066 'reset=1&action=add&context=pledge'
3068 'component' => 'CiviPledge',
3069 'permissions' => array(
3070 'access CiviPledge',
3074 'membership' => array(
3075 'title' => ts('Add Membership'),
3077 'ref' => 'new-membership',
3078 'key' => 'membership',
3080 'component' => 'CiviMember',
3081 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3082 'reset=1&action=add&context=membership'
3084 'permissions' => array(
3085 'access CiviMember',
3090 'title' => ts('Add Case'),
3092 'ref' => 'new-case',
3095 'component' => 'CiviCase',
3096 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3097 'permissions' => array('add cases'),
3100 'title' => ts('Add Grant'),
3102 'ref' => 'new-grant',
3105 'component' => 'CiviGrant',
3106 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3107 'reset=1&action=add&context=grant'
3109 'permissions' => array('edit grants'),
3112 'title' => ts('Add Relationship'),
3114 'ref' => 'new-relationship',
3117 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3118 'reset=1&action=add'
3120 'permissions' => array('edit all contacts'),
3123 'title' => ts('Add Note'),
3125 'ref' => 'new-note',
3128 'class' => 'medium-popup',
3129 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3130 'reset=1&action=add'
3132 'permissions' => array('edit all contacts'),
3135 'title' => ts('Send an Email'),
3137 'ref' => 'new-email',
3139 'permissions' => array('view all contacts'),
3142 'title' => ts('Add to Group'),
3144 'ref' => 'group-add-contact',
3147 'permissions' => array('edit groups'),
3150 'title' => ts('Tag Contact'),
3152 'ref' => 'tag-contact',
3155 'permissions' => array('edit all contacts'),
3159 $menu['otherActions'] = array(
3161 'title' => ts('Print Summary'),
3162 'description' => ts('Printer-friendly view of this page.'),
3164 'ref' => 'crm-contact-print',
3167 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3171 'icon' => 'crm-i fa-print',
3174 'title' => ts('vCard'),
3175 'description' => ts('vCard record for this contact.'),
3177 'ref' => 'crm-contact-vcard',
3180 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3184 'icon' => 'crm-i fa-list-alt',
3188 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3189 $menu['otherActions']['dashboard'] = array(
3190 'title' => ts('Contact Dashboard'),
3191 'description' => ts('Contact Dashboard'),
3193 'ref' => 'crm-contact-dashboard',
3194 'key' => 'dashboard',
3195 'tab' => 'dashboard',
3196 'class' => 'dashboard',
3197 // NOTE: As an alternative you can also build url on CMS specific way
3198 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3199 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3200 'icon' => 'crm-i fa-tachometer',
3204 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3206 $menu['otherActions']['user-record'] = array(
3207 'title' => ts('User Record'),
3208 'description' => ts('User Record'),
3210 'ref' => 'crm-contact-user-record',
3211 'key' => 'user-record',
3212 'tab' => 'user-record',
3213 'class' => 'user-record',
3214 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3215 'icon' => 'crm-i fa-user',
3218 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3219 $menu['otherActions']['user-add'] = array(
3220 'title' => ts('Create User Record'),
3221 'description' => ts('Create User Record'),
3223 'ref' => 'crm-contact-user-add',
3224 'key' => 'user-add',
3225 'tab' => 'user-add',
3226 'class' => 'user-add',
3227 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3228 'icon' => 'crm-i fa-user-plus',
3232 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3233 //1. check for component is active.
3234 //2. check for user permissions.
3235 //3. check for acls.
3236 //3. edit and view contact are directly accessible to user.
3238 $aclPermissionedTasks = array(
3243 'group-add-contact',
3247 $corePermission = CRM_Core_Permission
::getPermission();
3249 $contextMenu = array();
3250 foreach ($menu as $key => $values) {
3251 if ($key != 'otherActions') {
3253 // user does not have necessary permissions.
3254 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3257 // build directly accessible action menu.
3258 if (in_array($values['ref'], array(
3262 $contextMenu['primaryActions'][$key] = array(
3263 'title' => $values['title'],
3264 'ref' => $values['ref'],
3265 'class' => CRM_Utils_Array
::value('class', $values),
3266 'key' => $values['key'],
3271 // finally get menu item for -more- action widget.
3272 $contextMenu['moreActions'][$values['weight']] = array(
3273 'title' => $values['title'],
3274 'ref' => $values['ref'],
3275 'href' => CRM_Utils_Array
::value('href', $values),
3276 'tab' => CRM_Utils_Array
::value('tab', $values),
3277 'class' => CRM_Utils_Array
::value('class', $values),
3278 'key' => $values['key'],
3282 foreach ($values as $value) {
3283 // user does not have necessary permissions.
3284 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3288 // finally get menu item for -more- action widget.
3289 $contextMenu['otherActions'][$value['weight']] = array(
3290 'title' => $value['title'],
3291 'ref' => $value['ref'],
3292 'href' => CRM_Utils_Array
::value('href', $value),
3293 'tab' => CRM_Utils_Array
::value('tab', $value),
3294 'class' => CRM_Utils_Array
::value('class', $value),
3295 'icon' => CRM_Utils_Array
::value('icon', $value),
3296 'key' => $value['key'],
3302 ksort($contextMenu['moreActions']);
3303 ksort($contextMenu['otherActions']);
3305 return $contextMenu;
3309 * Check if user has permissions to access items in action menu.
3311 * @param array $aclPermissionedTasks
3312 * Array containing ACL related tasks.
3313 * @param string $corePermission
3314 * The permission of the user (edit or view or null).
3315 * @param array $menuOptions
3316 * Array containing params of the menu (title, href, etc).
3319 * TRUE if user has all permissions, FALSE if otherwise.
3321 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3322 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3324 // if component action - make sure component is enable.
3325 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3329 // make sure user has all required permissions.
3330 $hasAllPermissions = FALSE;
3332 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3333 if (!is_array($permissions) ||
empty($permissions)) {
3334 $hasAllPermissions = TRUE;
3337 // iterate for required permissions in given permissions array.
3338 if (!$hasAllPermissions) {
3339 $hasPermissions = 0;
3340 foreach ($permissions as $permission) {
3341 if (CRM_Core_Permission
::check($permission)) {
3346 if (count($permissions) == $hasPermissions) {
3347 $hasAllPermissions = TRUE;
3350 // if still user does not have required permissions, check acl.
3351 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3352 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3353 $corePermission == CRM_Core_Permission
::EDIT
3355 $hasAllPermissions = TRUE;
3357 elseif (in_array($menuOptions['ref'], array(
3360 // grant permissions for these tasks.
3361 $hasAllPermissions = TRUE;
3366 return $hasAllPermissions;
3370 * Retrieve display name of contact that address is shared.
3372 * This is based on $masterAddressId or $contactId .
3374 * @param int $masterAddressId
3376 * @param int $contactId
3377 * Contact id. (deprecated - do not use)
3379 * @return string|null
3380 * the found display name or null.
3382 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3383 $masterDisplayName = NULL;
3384 if (!$masterAddressId) {
3385 return $masterDisplayName;
3389 SELECT display_name from civicrm_contact
3390 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3391 WHERE civicrm_address.id = " . $masterAddressId;
3393 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3394 return $masterDisplayName;
3398 * Get the creation/modification times for a contact.
3400 * @param int $contactId
3403 * Dates - ('created_date' => $, 'modified_date' => $)
3405 public static function getTimestamps($contactId) {
3406 $timestamps = CRM_Core_DAO
::executeQuery(
3407 'SELECT created_date, modified_date
3408 FROM civicrm_contact
3411 1 => array($contactId, 'Integer'),
3414 if ($timestamps->fetch()) {
3416 'created_date' => $timestamps->created_date
,
3417 'modified_date' => $timestamps->modified_date
,
3426 * Get a list of triggers for the contact table.
3428 * @see hook_civicrm_triggerInfo
3429 * @see CRM_Core_DAO::triggerRebuild
3430 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3433 * @param null $tableName
3435 public static function triggerInfo(&$info, $tableName = NULL) {
3436 //during upgrade, first check for valid version and then create triggers
3437 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3438 if (CRM_Core_Config
::isUpgradeMode()) {
3439 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3440 //if current version is less than 4.3.alpha1 dont create below triggers
3441 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3446 // Modifications to these records should update the contact timestamps.
3447 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3448 ->setRelations(array(
3449 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3450 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3451 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3452 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3453 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3455 ->alterTriggerInfo($info, $tableName);
3457 // Update phone table to populate phone_numeric field
3458 if (!$tableName ||
$tableName == 'civicrm_phone') {
3459 // Define stored sql function needed for phones
3460 $sqlTriggers = Civi
::service('sql_triggers');
3461 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3462 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3464 'table' => array('civicrm_phone'),
3466 'event' => array('INSERT', 'UPDATE'),
3467 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3473 * Check if contact is being used in civicrm_domain based on $contactId.
3475 * @param int $contactId
3479 * true if present else false.
3481 public static function checkDomainContact($contactId) {
3485 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3496 * Get options for a given contact field.
3498 * @see CRM_Core_DAO::buildOptions
3500 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3501 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3503 * @param string $fieldName
3504 * @param string $context
3505 * @see CRM_Core_DAO::buildOptionsContext
3506 * @param array $props
3507 * whatever is known about this dao object.
3509 * @return array|bool
3511 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3513 // Special logic for fields whose options depend on context or properties
3514 switch ($fieldName) {
3515 case 'contact_sub_type':
3516 if (!empty($props['contact_type'])) {
3517 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3521 case 'contact_type':
3522 if ($context == 'search') {
3523 // CRM-15495 - EntityRef filters and basic search forms expect this format
3524 // FIXME: Search builder does not
3525 return CRM_Contact_BAO_ContactType
::getSelectElements();
3529 // The contact api supports some related entities so we'll honor that by fetching their options
3532 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3536 $props['entity_table'] = 'civicrm_contact';
3537 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3539 case 'state_province_id':
3540 case 'state_province':
3541 case 'state_province_name':
3546 case 'worldregion_id':
3547 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3550 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3554 * Delete a contact-related object that has an 'is_primary' field.
3556 * Ensures that is_primary gets assigned to another object if available
3557 * Also calls pre/post hooks
3559 * @param string $type
3563 public static function deleteObjectWithPrimary($type, $id) {
3564 if (!$id ||
!is_numeric($id)) {
3567 $daoName = "CRM_Core_DAO_$type";
3568 $obj = new $daoName();
3572 if ($obj->fetch()) {
3573 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3574 $contactId = $obj->contact_id
;
3580 // is_primary is only relavent if this field belongs to a contact
3582 $dao = new $daoName();
3583 $dao->contact_id
= $contactId;
3584 $dao->is_primary
= 1;
3585 // Pick another record to be primary (if one isn't already)
3586 if (!$dao->find(TRUE)) {
3587 $dao->is_primary
= 0;
3589 if ($dao->fetch()) {
3590 $dao->is_primary
= 1;
3595 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3602 public function addSelectWhereClause() {
3603 // We always return an array with these keys, even if they are empty,
3604 // because this tells the query builder that we have considered these fields for acls
3606 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3607 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
array() : array('!= 1'),
3609 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3614 * Get any existing duplicate contacts based on the input parameters.
3616 * @param array $input
3617 * Input parameters to be matched.
3618 * @param string $contactType
3619 * @param string $rule
3622 * @param $excludedContactIDs
3623 * An array of ids not to be included in the results.
3624 * @param bool $checkPermissions
3625 * @param int $ruleGroupID
3626 * ID of the rule group to be used if an override is desirable.
3627 * @param array $contextParams
3628 * The context if relevant, eg. ['event_id' => X]
3632 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3633 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3634 $dedupeParams['check_permission'] = $checkPermissions;
3635 $dedupeParams['contact_type'] = $contactType;
3636 $dedupeParams['rule'] = $rule;
3637 $dedupeParams['rule_group_id'] = $ruleGroupID;
3638 $dedupeParams['excluded_contact_ids'] = $excludedContactIDs;
3639 $dedupeResults['ids'] = [];
3640 $dedupeResults['handled'] = FALSE;
3641 CRM_Utils_Hook
::findDuplicates($dedupeParams, $dedupeResults, $contextParams);
3642 if (!$dedupeResults['handled']) {
3643 $dedupeResults['ids'] = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3645 return $dedupeResults['ids'];
3649 * Get the first duplicate contacts based on the input parameters.
3651 * @param array $input
3652 * Input parameters to be matched.
3653 * @param string $contactType
3654 * @param string $rule
3657 * @param $excludedContactIDs
3658 * An array of ids not to be included in the results.
3659 * @param bool $checkPermissions
3660 * @param int $ruleGroupID
3661 * ID of the rule group to be used if an override is desirable.
3662 * @param array $contextParams
3663 * The context if relevant, eg. ['event_id' => X]
3667 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = [], $checkPermissions = TRUE, $ruleGroupID = NULL, $contextParams = []) {
3668 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID, $contextParams);
3676 * Check if a field is associated with an entity that has a location type.
3678 * (ie. is an address, phone, email etc field).
3680 * @param string $fieldTitle
3681 * Title of the field (not the name - create a new function for that if required).
3685 public static function isFieldHasLocationType($fieldTitle) {
3686 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3687 if ($field['title'] === $fieldTitle) {
3688 return CRM_Utils_Array
::value('hasLocationType', $field);
3695 * @param array $appendProfiles
3696 * Name of profile(s) to append to each link.
3700 public static function getEntityRefCreateLinks($appendProfiles = []) {
3701 // You'd think that "create contacts" would be the permission to check,
3702 // But new contact popups are profile forms and those use their own permissions.
3703 if (!CRM_Core_Permission
::check([['profile create', 'profile listings and forms']])) {
3707 foreach (CRM_Contact_BAO_ContactType
::basicTypes() as $contactType) {
3708 $profiles[] = 'new_' . strtolower($contactType);
3710 $retrieved = civicrm_api3('uf_group', 'get', [
3711 'name' => ['IN' => array_merge($profiles, (array) $appendProfiles)],
3714 $links = $append = [];
3715 if (!empty($retrieved['values'])) {
3717 'individual' => 'fa-user',
3718 'organization' => 'fa-building',
3719 'household' => 'fa-home',
3721 foreach ($retrieved['values'] as $id => $profile) {
3722 if (in_array($profile['name'], $profiles)) {
3724 'label' => $profile['title'],
3725 'url' => CRM_Utils_System
::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id",
3726 NULL, NULL, FALSE, FALSE, TRUE),
3727 'type' => ucfirst(str_replace('new_', '', $profile['name'])),
3728 'icon' => CRM_Utils_Array
::value(str_replace('new_', '', $profile['name']), $icons),
3735 foreach ($append as $id) {
3736 foreach ($links as &$link) {
3737 $link['url'] .= ",$id";
3747 public static function getEntityRefFilters() {
3749 ['key' => 'contact_type', 'value' => ts('Contact Type')],
3750 ['key' => 'group', 'value' => ts('Group'), 'entity' => 'GroupContact'],
3751 ['key' => 'tag', 'value' => ts('Tag'), 'entity' => 'EntityTag'],
3752 ['key' => 'state_province', 'value' => ts('State/Province'), 'entity' => 'Address'],
3753 ['key' => 'country', 'value' => ts('Country'), 'entity' => 'Address'],
3754 ['key' => 'gender_id', 'value' => ts('Gender'), 'condition' => ['contact_type' => 'Individual']],
3755 ['key' => 'is_deceased', 'value' => ts('Deceased'), 'condition' => ['contact_type' => 'Individual']],
3756 ['key' => 'contact_id', 'value' => ts('Contact ID'), 'type' => 'text'],
3757 ['key' => 'external_identifier', 'value' => ts('External ID'), 'type' => 'text'],
3758 ['key' => 'source', 'value' => ts('Contact Source'), 'type' => 'text'],