3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
33 class CRM_Contact_BAO_Contact
extends CRM_Contact_DAO_Contact
{
36 * SQL function used to format the phone_numeric field via trigger.
37 * @see self::triggerInfo()
39 * Note that this is also used by the 4.3 upgrade script.
40 * @see CRM_Upgrade_Incremental_php_FourThree
42 const DROP_STRIP_FUNCTION_43
= "DROP FUNCTION IF EXISTS civicrm_strip_non_numeric";
43 const CREATE_STRIP_FUNCTION_43
= "
44 CREATE FUNCTION civicrm_strip_non_numeric(input VARCHAR(255) CHARACTER SET utf8)
45 RETURNS VARCHAR(255) CHARACTER SET utf8
49 DECLARE output VARCHAR(255) CHARACTER SET utf8 DEFAULT '';
50 DECLARE iterator INT DEFAULT 1;
51 WHILE iterator < (LENGTH(input) + 1) DO
52 IF SUBSTRING(input, iterator, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') THEN
53 SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
55 SET iterator = iterator + 1;
61 * The types of communication preferences.
65 static $_commPrefs = array(
78 static $_greetingTypes = array(
85 * Static field for all the contact information that we can potentially import.
89 static $_importableFields = array();
92 * Static field for all the contact information that we can potentially export.
96 static $_exportableFields = NULL;
101 public function __construct() {
102 parent
::__construct();
106 * Takes an associative array and creates a contact object.
108 * The function extracts all the params it needs to initialize the create a
109 * contact object. the params array could contain additional unused name/value
112 * @param array $params
113 * (reference) an assoc array of name/value pairs.
115 * @return CRM_Contact_BAO_Contact|CRM_Core_Error|NULL
116 * Created or updated contact object or error object.
117 * (error objects are being phased out in favour of exceptions)
119 public static function add(&$params) {
120 $contact = new CRM_Contact_DAO_Contact();
122 if (empty($params)) {
126 // Fix for validate contact sub type CRM-5143.
127 if (isset($params['contact_sub_type'])) {
128 if (empty($params['contact_sub_type'])) {
129 $params['contact_sub_type'] = 'null';
132 if (!CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'],
133 $params['contact_type'], TRUE
136 // we'll need to fix tests to handle this
138 CRM_Core_Error
::fatal(ts('The Contact Sub Type does not match the Contact type for this record'));
140 $params['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
146 $params['contact_sub_type'] = 'null';
149 // Fixed contact source.
150 if (isset($params['contact_source'])) {
151 $params['source'] = $params['contact_source'];
154 if (isset($params['preferred_communication_method']) && is_array($params['preferred_communication_method'])) {
155 CRM_Utils_Array
::formatArrayKeys($params['preferred_communication_method']);
156 $contact->preferred_communication_method
= CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
157 unset($params['preferred_communication_method']);
160 $allNull = $contact->copyValues($params);
162 $contact->id
= CRM_Utils_Array
::value('contact_id', $params);
164 if ($contact->contact_type
== 'Individual') {
167 // Format individual fields.
168 CRM_Contact_BAO_Individual
::format($params, $contact);
170 elseif ($contact->contact_type
== 'Household') {
171 if (isset($params['household_name'])) {
173 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('household_name', $params, '');
176 elseif ($contact->contact_type
== 'Organization') {
177 if (isset($params['organization_name'])) {
179 $contact->display_name
= $contact->sort_name
= CRM_Utils_Array
::value('organization_name', $params, '');
182 if (strlen($contact->display_name
) > 128) {
183 $contact->display_name
= substr($contact->display_name
, 0, 128);
185 if (strlen($contact->sort_name
) > 128) {
186 $contact->sort_name
= substr($contact->sort_name
, 0, 128);
189 $privacy = CRM_Utils_Array
::value('privacy', $params);
191 is_array($privacy) &&
195 foreach (self
::$_commPrefs as $name) {
196 $contact->$name = CRM_Utils_Array
::value($name, $privacy, FALSE);
200 // Since hash was required, make sure we have a 0 value for it (CRM-1063).
201 // @todo - does this mean we can remove this block?
202 // Fixed in 1.5 by making hash optional, only do this in create mode, not update.
203 if ((!array_key_exists('hash', $contact) ||
!$contact->hash
) && !$contact->id
) {
205 $contact->hash
= md5(uniqid(rand(), TRUE));
208 // Even if we don't need $employerId, it's important to call getFieldValue() before
209 // the contact is saved because we want the existing value to be cached.
210 // createCurrentEmployerRelationship() needs the old value not the updated one. CRM-10788
211 $employerId = empty($contact->id
) ?
NULL : CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contact->id
, 'employer_id');
216 CRM_Core_BAO_Log
::register($contact->id
,
222 if ($contact->contact_type
== 'Individual' && (isset($params['current_employer']) ||
isset($params['employer_id']))) {
223 // Create current employer.
224 $newEmployer = !empty($params['employer_id']) ?
$params['employer_id'] : CRM_Utils_Array
::value('current_employer', $params);
227 if (empty($params['contact_id'])) {
231 CRM_Contact_BAO_Contact_Utils
::createCurrentEmployerRelationship($contact->id
, $newEmployer, $employerId, $newContact);
235 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($contact->id
, $employerId);
240 // Update cached employer name.
241 if ($contact->contact_type
== 'Organization') {
242 CRM_Contact_BAO_Contact_Utils
::updateCurrentEmployer($contact->id
);
251 * takes an associative array and creates a contact object and all the associated
252 * derived objects (i.e. individual, location, email, phone etc)
254 * This function is invoked from within the web form layer and also from the api layer
256 * @param array $params
257 * (reference ) an assoc array of name/value pairs.
258 * @param bool $fixAddress
259 * If we need to fix address.
260 * @param bool $invokeHooks
261 * If we need to invoke hooks.
263 * @param bool $skipDelete
264 * Unclear parameter, passed to website create
266 * @todo explain this parameter
269 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
270 * Created or updated contribution object. We are deprecating returning an error in
271 * favour of exceptions
273 public static function &create(&$params, $fixAddress = TRUE, $invokeHooks = TRUE, $skipDelete = FALSE) {
275 if (empty($params['contact_type']) && empty($params['contact_id'])) {
281 if (!empty($params['contact_id'])) {
282 CRM_Utils_Hook
::pre('edit', $params['contact_type'], $params['contact_id'], $params);
285 CRM_Utils_Hook
::pre('create', $params['contact_type'], NULL, $params);
290 self
::ensureGreetingParamsAreSet($params);
292 // CRM-6942: set preferred language to the current language if it’s unset (and we’re creating a contact).
293 if (empty($params['contact_id'])) {
294 // A case could be made for checking isset rather than empty but this is more consistent with previous behaviour.
295 if (empty($params['preferred_language']) && ($language = CRM_Core_I18n
::getContactDefaultLanguage()) != FALSE) {
296 $params['preferred_language'] = $language;
299 // CRM-21041: set default 'Communication Style' if unset when creating a contact.
300 if (empty($params['communication_style_id'])) {
301 $defaultCommunicationStyleId = CRM_Core_OptionGroup
::values('communication_style', TRUE, NULL, NULL, 'AND is_default = 1');
302 $params['communication_style_id'] = array_pop($defaultCommunicationStyleId);
306 $transaction = new CRM_Core_Transaction();
308 $contact = self
::add($params);
310 // Not dying here is stupid, since we get into weird situation and into a bug that
311 // is impossible to figure out for the user or for us
313 CRM_Core_Error
::fatal();
316 $params['contact_id'] = $contact->id
;
318 if (Civi
::settings()->get('is_enabled')) {
319 // Enabling multisite causes the contact to be added to the domain group.
320 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
321 if (!empty($domainGroupID)) {
322 if (!empty($params['group']) && is_array($params['group'])) {
323 $params['group'][$domainGroupID] = 1;
326 $params['group'] = array($domainGroupID => 1);
331 if (array_key_exists('group', $params)) {
332 $contactIds = array($params['contact_id']);
333 foreach ($params['group'] as $groupId => $flag) {
335 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
337 elseif ($flag == -1) {
338 CRM_Contact_BAO_GroupContact
::removeContactsFromGroup($contactIds, $groupId);
343 // Add location Block data.
344 $blocks = CRM_Core_BAO_Location
::create($params, $fixAddress);
345 foreach ($blocks as $name => $value) {
346 $contact->$name = $value;
348 if (!empty($params['updateBlankLocInfo'])) {
353 CRM_Core_BAO_Website
::create($params['website'], $contact->id
, $skipDelete);
355 $userID = CRM_Core_Session
::singleton()->get('userID');
357 if (!empty($params['note'])) {
358 if (is_array($params['note'])) {
359 foreach ($params['note'] as $note) {
360 $contactId = $contact->id
;
361 if (isset($note['contact_id'])) {
362 $contactId = $note['contact_id'];
364 //if logged in user, overwrite contactId
366 $contactId = $userID;
370 'entity_id' => $contact->id
,
371 'entity_table' => 'civicrm_contact',
372 'note' => $note['note'],
373 'subject' => CRM_Utils_Array
::value('subject', $note),
374 'contact_id' => $contactId,
376 CRM_Core_BAO_Note
::add($noteParams, CRM_Core_DAO
::$_nullArray);
380 $contactId = $contact->id
;
381 if (isset($note['contact_id'])) {
382 $contactId = $note['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, CRM_Core_DAO
::$_nullArray);
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);
451 * Ensure greeting parameters are set.
453 * By always populating greetings here we can be sure they are set if required & avoid a call later.
454 * (ie. knowing we have definitely tried disambiguates between NULL & not loaded.)
456 * @param array $params
458 public static function ensureGreetingParamsAreSet(&$params) {
459 $allGreetingParams = array('addressee' => 'addressee_id', 'postal_greeting' => 'postal_greeting_id', 'email_greeting' => 'email_greeting_id');
460 $missingGreetingParams = array();
462 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
463 if (empty($params[$greetingParam])) {
464 $missingGreetingParams[$greetingIndex] = $greetingParam;
468 if (!empty($params['contact_id']) && !empty($missingGreetingParams)) {
469 $savedGreetings = civicrm_api3('Contact', 'getsingle', array(
470 'id' => $params['contact_id'],
471 'return' => array_keys($missingGreetingParams))
474 foreach (array_keys($missingGreetingParams) as $missingGreetingParam) {
475 if (!empty($savedGreetings[$missingGreetingParam . '_custom'])) {
476 $missingGreetingParams[$missingGreetingParam . '_custom'] = $missingGreetingParam . '_custom';
479 // Filter out other fields.
480 $savedGreetings = array_intersect_key($savedGreetings, array_flip($missingGreetingParams));
481 $params = array_merge($params, $savedGreetings);
484 foreach ($missingGreetingParams as $greetingName => $greeting) {
485 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting($params['contact_type'], $greetingName);
489 foreach ($allGreetingParams as $greetingIndex => $greetingParam) {
490 if ($params[$greetingParam] === 'null') {
491 // If we are setting it to null then null out the display field.
492 $params[$greetingIndex . '_display'] = 'null';
498 * Get the display name and image of a contact.
503 * @param bool $includeTypeInReturnParameters
504 * Should type be part of the returned array?
507 * the displayName and contactImage for this contact
509 public static function getDisplayAndImage($id, $includeTypeInReturnParameters = FALSE) {
510 //CRM-14276 added the * on the civicrm_contact table so that we have all the contact info available
512 SELECT civicrm_contact.*,
513 civicrm_email.email as email
515 LEFT JOIN civicrm_email ON civicrm_email.contact_id = civicrm_contact.id
516 AND civicrm_email.is_primary = 1
517 WHERE civicrm_contact.id = " . CRM_Utils_Type
::escape($id, 'Integer');
518 $dao = new CRM_Core_DAO();
521 $image = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
522 $dao->contact_sub_type
: $dao->contact_type
, FALSE, $id
524 $imageUrl = CRM_Contact_BAO_Contact_Utils
::getImage($dao->contact_sub_type ?
525 $dao->contact_sub_type
: $dao->contact_type
, TRUE, $id
528 // use email if display_name is empty
529 if (empty($dao->display_name
)) {
530 $displayName = $dao->email
;
533 $displayName = $dao->display_name
;
536 CRM_Utils_Hook
::alterDisplayName($displayName, $id, $dao);
538 return $includeTypeInReturnParameters ?
array(
542 $dao->contact_sub_type
,
544 ) : array($displayName, $image, $imageUrl);
550 * Add billing fields to the params if appropriate.
552 * If we have ANY name fields then we want to ignore all the billing name fields. However, if we
553 * don't then we should set the name fields to the filling fields AND add the preserveDBName
554 * parameter (which will tell the BAO only to set those fields if none already exist.
556 * We specifically don't want to set first name from billing and last name form an on-page field. Mixing &
557 * matching is best done by hipsters.
559 * @param array $params
561 public static function addBillingNameFieldsIfOtherwiseNotSet(&$params) {
562 $nameFields = array('first_name', 'middle_name', 'last_name', 'nick_name', 'prefix_id', 'suffix_id');
563 foreach ($nameFields as $field) {
564 if (!empty($params[$field])) {
568 // There are only 3 - we can iterate through them twice :-)
569 foreach ($nameFields as $field) {
570 if (!empty($params['billing_' . $field])) {
571 $params[$field] = $params['billing_' . $field];
573 $params['preserveDBName'] = TRUE;
579 * Resolve a state province string (UT or Utah) to an ID.
581 * If country has been passed in we should select a state belonging to that country.
583 * Alternatively we should choose from enabled countries, prioritising the default country.
585 * @param array $values
586 * @param int|NULL $countryID
590 protected static function resolveStateProvinceID($values, $countryID) {
593 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID);
594 if (CRM_Utils_Array
::lookupValue($values,
599 return $values['state_province_id'];
601 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceForCountry($countryID, 'abbreviation');
602 if (CRM_Utils_Array
::lookupValue($values,
607 return $values['state_province_id'];
612 // The underlying lookupValue function needs some de-fanging. Until that has been unravelled we
613 // continue to resolve stateprovince lists in descending order of preference & just 'keep trying'.
614 // prefer matching country..
615 $stateProvinceList = CRM_Core_BAO_Address
::buildOptions('state_province_id', NULL, array('country_id' => Civi
::settings()->get('defaultContactCountry')));
616 if (CRM_Utils_Array
::lookupValue($values,
621 return $values['state_province_id'];
624 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvince();
625 if (CRM_Utils_Array
::lookupValue($values,
630 return $values['state_province_id'];
633 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviationForDefaultCountry();
634 if (CRM_Utils_Array
::lookupValue($values,
639 return $values['state_province_id'];
641 $stateProvinceList = CRM_Core_PseudoConstant
::stateProvinceAbbreviation();
642 if (CRM_Utils_Array
::lookupValue($values,
647 return $values['state_province_id'];
655 * Create last viewed link to recently updated contact.
657 * @param array $crudLinkSpec
658 * - action: int, CRM_Core_Action::UPDATE or CRM_Core_Action::VIEW [default: VIEW]
659 * - entity_table: string, eg "civicrm_contact"
663 * NULL if unavailable, or
664 * [path: string, query: string, title: string]
665 * @see CRM_Utils_System::createDefaultCrudLink
667 public function createDefaultCrudLink($crudLinkSpec) {
668 switch ($crudLinkSpec['action']) {
669 case CRM_Core_Action
::VIEW
:
671 'title' => $this->display_name
,
672 'path' => 'civicrm/contact/view',
680 case CRM_Core_Action
::UPDATE
:
682 'title' => $this->display_name
,
683 'path' => 'civicrm/contact/add',
686 'action' => 'update',
696 * Get the values for pseudoconstants for name->value and reverse.
700 * This is called specifically from the contact import parser & should be moved there
701 * as it is not truly a generic function.
703 * @param array $defaults
704 * (reference) the default values, some of which need to be resolved.
705 * @param bool $reverse
706 * Always true as this function is only called from one place..
708 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
709 // Hack for birth_date.
710 if (!empty($defaults['birth_date'])) {
711 if (is_array($defaults['birth_date'])) {
712 $defaults['birth_date'] = CRM_Utils_Date
::format($defaults['birth_date'], '-');
716 CRM_Utils_Array
::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
717 CRM_Utils_Array
::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
718 CRM_Utils_Array
::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
719 CRM_Utils_Array
::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
721 //lookup value of email/postal greeting, addressee, CRM-4575
722 foreach (self
::$_greetingTypes as $greeting) {
723 $filterCondition = array(
724 'contact_type' => CRM_Utils_Array
::value('contact_type', $defaults),
725 'greeting_type' => $greeting,
727 CRM_Utils_Array
::lookupValue($defaults, $greeting,
728 CRM_Core_PseudoConstant
::greeting($filterCondition), $reverse
732 $blocks = array('address', 'im', 'phone');
733 foreach ($blocks as $name) {
734 if (!array_key_exists($name, $defaults) ||
!is_array($defaults[$name])) {
737 foreach ($defaults[$name] as $count => & $values) {
739 //get location type id.
740 CRM_Utils_Array
::lookupValue($values, 'location_type', CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
742 if ($name == 'address') {
743 // FIXME: lookupValue doesn't work for vcard_name
744 if (!empty($values['location_type_id'])) {
745 $vcardNames = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
746 $values['vcard_name'] = $vcardNames[$values['location_type_id']];
749 if (!CRM_Utils_Array
::lookupValue($values,
751 CRM_Core_PseudoConstant
::country(),
756 CRM_Utils_Array
::lookupValue($values,
758 CRM_Core_PseudoConstant
::countryIsoCode(),
762 $stateProvinceID = self
::resolveStateProvinceID($values, CRM_Utils_Array
::value('country_id', $values));
763 if ($stateProvinceID) {
764 $values['state_province_id'] = $stateProvinceID;
767 if (!empty($values['state_province_id'])) {
768 $countyList = CRM_Core_PseudoConstant
::countyForState($values['state_province_id']);
771 $countyList = CRM_Core_PseudoConstant
::county();
773 CRM_Utils_Array
::lookupValue($values,
781 CRM_Utils_Array
::lookupValue($values,
783 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id'),
788 if ($name == 'phone') {
789 CRM_Utils_Array
::lookupValue($values,
791 CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id'),
796 // Kill the reference.
803 * Fetch object based on array of properties.
805 * @param array $params
806 * (reference ) an assoc array of name/value pairs.
807 * @param array $defaults
808 * (reference ) an assoc array to hold the name / value pairs.
809 * in a hierarchical manner
810 * @param bool $microformat
811 * For location in microformat.
813 * @return CRM_Contact_BAO_Contact
815 public static function &retrieve(&$params, &$defaults, $microformat = FALSE) {
816 if (array_key_exists('contact_id', $params)) {
817 $params['id'] = $params['contact_id'];
819 elseif (array_key_exists('id', $params)) {
820 $params['contact_id'] = $params['id'];
823 $contact = self
::getValues($params, $defaults);
825 unset($params['id']);
827 //get the block information for this contact
828 $entityBlock = array('contact_id' => $params['contact_id']);
829 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock, $microformat);
830 $defaults = array_merge($defaults, $blocks);
831 foreach ($blocks as $block => $value) {
832 $contact->$block = $value;
835 if (!isset($params['noNotes'])) {
836 $contact->notes
= CRM_Core_BAO_Note
::getValues($params, $defaults);
839 if (!isset($params['noRelationships'])) {
840 $contact->relationship
= CRM_Contact_BAO_Relationship
::getValues($params, $defaults);
843 if (!isset($params['noGroups'])) {
844 $contact->groupContact
= CRM_Contact_BAO_GroupContact
::getValues($params, $defaults);
847 if (!isset($params['noWebsite'])) {
848 $contact->website
= CRM_Core_BAO_Website
::getValues($params, $defaults);
855 * Get the display name of a contact.
860 * @return null|string
861 * display name of the contact if found
863 public static function displayName($id) {
866 $displayName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'display_name');
873 * Delete a contact and all its associated records.
876 * Id of the contact to delete.
877 * @param bool $restore
878 * Whether to actually restore, not delete.
879 * @param bool $skipUndelete
880 * Whether to force contact delete or not.
881 * @param bool $checkPermissions
884 * Was contact deleted?
886 public static function deleteContact($id, $restore = FALSE, $skipUndelete = FALSE, $checkPermissions = TRUE) {
891 // If trash is disabled in system settings then we always skip
892 if (!Civi
::settings()->get('contact_undelete')) {
893 $skipUndelete = TRUE;
896 // make sure we have edit permission for this contact
898 if ($checkPermissions && (($skipUndelete && !CRM_Core_Permission
::check('delete contacts')) ||
899 ($restore && !CRM_Core_Permission
::check('access deleted contacts')))
905 // Restrict contact to be delete if contact has financial trxns
907 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($id), $error)) {
911 // make sure this contact_id does not have any membership types
912 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
915 'member_of_contact_id'
917 if ($membershipTypeID) {
921 $contact = new CRM_Contact_DAO_Contact();
923 if (!$contact->find(TRUE)) {
927 $contactType = $contact->contact_type
;
928 // currently we only clear employer cache.
929 // we are now deleting inherited membership if any.
930 if ($contact->contact_type
== 'Organization') {
931 $action = $restore ? CRM_Core_Action
::ENABLE
: CRM_Core_Action
::DISABLE
;
932 $relationshipDtls = CRM_Contact_BAO_Relationship
::getRelationship($id);
933 if (!empty($relationshipDtls)) {
934 foreach ($relationshipDtls as $rId => $details) {
935 CRM_Contact_BAO_Relationship
::disableEnableRelationship($rId, $action);
938 CRM_Contact_BAO_Contact_Utils
::clearAllEmployee($id);
942 return self
::contactTrashRestore($contact, TRUE);
945 // start a new transaction
946 $transaction = new CRM_Core_Transaction();
949 CRM_Utils_Hook
::pre('delete', $contactType, $id, CRM_Core_DAO
::$_nullArray);
951 //delete billing address if exists.
952 CRM_Contribute_BAO_Contribution
::deleteAddress(NULL, $id);
954 // delete the log entries since we dont have triggers enabled as yet
955 $logDAO = new CRM_Core_DAO_Log();
956 $logDAO->entity_table
= 'civicrm_contact';
957 $logDAO->entity_id
= $id;
960 // delete contact participants CRM-12155
961 CRM_Event_BAO_Participant
::deleteContactParticipant($id);
963 // delete contact contributions CRM-12155
964 CRM_Contribute_BAO_Contribution
::deleteContactContribution($id);
966 // do activity cleanup, CRM-5604
967 CRM_Activity_BAO_Activity
::cleanupActivity($id);
969 // delete all notes related to contact
970 CRM_Core_BAO_Note
::cleanContactNotes($id);
972 // delete cases related to contact
973 $contactCases = CRM_Case_BAO_Case
::retrieveCaseIdsByContactId($id);
974 if (!empty($contactCases)) {
975 foreach ($contactCases as $caseId) {
976 //check if case is associate with other contact or not.
977 $caseContactId = CRM_Case_BAO_Case
::getCaseClients($caseId);
978 if (count($caseContactId) <= 1) {
979 CRM_Case_BAO_Case
::deleteCase($caseId);
987 self
::contactTrashRestore($contact);
990 //delete the contact id from recently view
991 CRM_Utils_Recent
::delContact($id);
992 self
::updateContactCache($id, empty($restore));
994 // delete any dupe cache entry
995 CRM_Core_BAO_PrevNextCache
::deleteItem($id);
997 $transaction->commit();
1000 CRM_Utils_Hook
::post('delete', $contactType, $contact->id
, $contact);
1003 // also reset the DB_DO global array so we can reuse the memory
1004 // http://issues.civicrm.org/jira/browse/CRM-4387
1005 CRM_Core_DAO
::freeResult();
1011 * Action to update any caches relating to a recently update contact.
1013 * I was going to call this from delete as well as from create to ensure the delete is being
1014 * done whenever a contact is set to is_deleted=1 BUT I found create is already over-aggressive in
1015 * that regard so adding it to delete seems to be enough to remove it from CRM_Contact_BAO_Contact_Permission
1016 * where the call involved a subquery that was locking the table.
1018 * @param int $contactID
1019 * @param bool $isTrashed
1021 public static function updateContactCache($contactID, $isTrashed = FALSE) {
1024 CRM_Contact_BAO_GroupContactCache
::removeContact($contactID);
1025 // This has been moved to here from CRM_Contact_BAO_Contact_Permission as that was causing
1026 // a table-locking query. It still seems a bit inadequate as it assumes the acl users can't see deleted
1027 // but this should not cause any change as long as contacts are not being trashed outside the
1028 // main functions for that.
1029 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_acl_contact_cache WHERE contact_id = %1', array(1 => array($contactID, 'Integer')));
1032 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
1037 * Delete the image of a contact.
1040 * Id of the contact.
1043 * Was contact image deleted?
1045 public static function deleteContactImage($id) {
1050 $contact = new self();
1052 $contact->image_URL
= 'null';
1059 * Return proportional height and width of the image.
1061 * @param int $imageWidth
1064 * @param int $imageHeight
1068 * Thumb dimension of image
1070 public static function getThumbSize($imageWidth, $imageHeight) {
1072 if ($imageWidth && $imageHeight) {
1073 $imageRatio = $imageWidth / $imageHeight;
1078 if ($imageRatio > 1) {
1079 $imageThumbWidth = $thumbWidth;
1080 $imageThumbHeight = round($thumbWidth / $imageRatio);
1083 $imageThumbHeight = $thumbWidth;
1084 $imageThumbWidth = round($thumbWidth * $imageRatio);
1087 return array($imageThumbWidth, $imageThumbHeight);
1091 * Validate type of contact image.
1093 * @param array $params
1094 * @param string $imageIndex
1095 * Index of image field.
1096 * @param string $statusMsg
1097 * Status message to be set after operation.
1098 * @param string $opType
1099 * Type of operation like fatal, bounce etc.
1102 * true if valid image extension
1104 public static function processImageParams(
1106 $imageIndex = 'image_URL',
1120 if (in_array($params[$imageIndex]['type'], $mimeType)) {
1121 $photo = basename($params[$imageIndex]['name']);
1122 $params[$imageIndex] = CRM_Utils_System
::url('civicrm/contact/imagefile', 'photo=' . $photo, TRUE, NULL, TRUE, TRUE);
1126 unset($params[$imageIndex]);
1128 $statusMsg = ts('Image could not be uploaded due to invalid type extension.');
1130 if ($opType == 'status') {
1131 CRM_Core_Session
::setStatus($statusMsg, 'Sorry', 'error');
1133 // FIXME: additional support for fatal, bounce etc could be added.
1139 * Extract contact id from url for deleting contact image.
1141 public static function processImage() {
1143 $action = CRM_Utils_Request
::retrieve('action', 'String');
1144 $cid = CRM_Utils_Request
::retrieve('cid', 'Positive');
1145 // retrieve contact id in case of Profile context
1146 $id = CRM_Utils_Request
::retrieve('id', 'Positive');
1147 $cid = $cid ?
$cid : $id;
1148 if ($action & CRM_Core_Action
::DELETE
) {
1149 if (CRM_Utils_Request
::retrieve('confirmed', 'Boolean')) {
1150 CRM_Contact_BAO_Contact
::deleteContactImage($cid);
1151 CRM_Core_Session
::setStatus(ts('Contact image deleted successfully'), ts('Image Deleted'), 'success');
1152 $session = CRM_Core_Session
::singleton();
1153 $toUrl = $session->popUserContext();
1154 CRM_Utils_System
::redirect($toUrl);
1160 * Function to set is_delete true or restore deleted contact.
1162 * @param CRM_Contact_DAO_Contact $contact
1163 * Contact DAO object.
1164 * @param bool $restore
1165 * True to set the is_delete = 1 else false to restore deleted contact,
1166 * i.e. is_delete = 0
1170 public static function contactTrashRestore($contact, $restore = FALSE) {
1171 $updateParams = array(
1172 'id' => $contact->id
,
1173 'is_deleted' => $restore ?
0 : 1,
1176 CRM_Utils_Hook
::pre('update', $contact->contact_type
, $contact->id
, $updateParams);
1178 $params = array(1 => array($contact->id
, 'Integer'));
1180 $query = "DELETE FROM civicrm_uf_match WHERE contact_id = %1";
1181 CRM_Core_DAO
::executeQuery($query, $params);
1184 $contact->copyValues($updateParams);
1187 CRM_Utils_Hook
::post('update', $contact->contact_type
, $contact->id
, $contact);
1193 * Get contact type for a contact.
1196 * Id of the contact whose contact type is needed.
1199 * contact_type if $id found else null ""
1201 public static function getContactType($id) {
1202 return CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_type');
1206 * Get contact sub type for a contact.
1209 * Id of the contact whose contact sub type is needed.
1211 * @param string $implodeDelimiter
1214 * contact_sub_type if $id found else null ""
1216 public static function getContactSubType($id, $implodeDelimiter = NULL) {
1217 $subtype = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'contact_sub_type');
1219 return $implodeDelimiter ?
NULL : array();
1222 $subtype = CRM_Utils_Array
::explodePadded($subtype);
1224 if ($implodeDelimiter) {
1225 $subtype = implode($implodeDelimiter, $subtype);
1231 * Get pair of contact-type and sub-type for a contact.
1234 * Id of the contact whose contact sub/contact type is needed.
1238 public static function getContactTypes($id) {
1239 $params = array('id' => $id);
1241 $contact = CRM_Core_DAO
::commonRetrieve('CRM_Contact_DAO_Contact',
1244 array('contact_type', 'contact_sub_type')
1248 $contactTypes = array();
1249 if ($contact->contact_sub_type
) {
1250 $contactTypes = CRM_Utils_Array
::explodePadded($contact->contact_sub_type
);
1252 array_unshift($contactTypes, $contact->contact_type
);
1254 return $contactTypes;
1257 CRM_Core_Error
::fatal();
1262 * Combine all the importable fields from the lower levels object.
1264 * The ordering is important, since currently we do not have a weight
1265 * scheme. Adding weight is super important
1267 * @param int|string $contactType contact Type
1268 * @param bool $status
1269 * Status is used to manipulate first title.
1270 * @param bool $showAll
1271 * If true returns all fields (includes disabled fields).
1272 * @param bool $isProfile
1273 * If its profile mode.
1274 * @param bool $checkPermission
1275 * If false, do not include permissioning clause (for custom data).
1277 * @param bool $withMultiCustomFields
1280 * array of importable Fields
1282 public static function importableFields(
1283 $contactType = 'Individual',
1287 $checkPermission = TRUE,
1288 $withMultiCustomFields = FALSE
1290 if (empty($contactType)) {
1291 $contactType = 'All';
1294 $cacheKeyString = "importableFields $contactType";
1295 $cacheKeyString .= $status ?
'_1' : '_0';
1296 $cacheKeyString .= $showAll ?
'_1' : '_0';
1297 $cacheKeyString .= $isProfile ?
'_1' : '_0';
1298 $cacheKeyString .= $checkPermission ?
'_1' : '_0';
1300 $fields = CRM_Utils_Array
::value($cacheKeyString, self
::$_importableFields);
1303 // check if we can retrieve from database cache
1304 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1308 $fields = CRM_Contact_DAO_Contact
::import();
1310 // get the fields thar are meant for contact types
1311 if (in_array($contactType, array(
1317 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1320 $locationFields = array_merge(CRM_Core_DAO_Address
::import(),
1321 CRM_Core_DAO_Phone
::import(),
1322 CRM_Core_DAO_Email
::import(),
1323 CRM_Core_DAO_IM
::import(TRUE),
1324 CRM_Core_DAO_OpenID
::import()
1327 $locationFields = array_merge($locationFields,
1328 CRM_Core_BAO_CustomField
::getFieldsForImport('Address',
1336 foreach ($locationFields as $key => $field) {
1337 $locationFields[$key]['hasLocationType'] = TRUE;
1340 $fields = array_merge($fields, $locationFields);
1342 $fields = array_merge($fields, CRM_Contact_DAO_Contact
::import());
1343 $fields = array_merge($fields, CRM_Core_DAO_Note
::import());
1346 $fields = array_merge($fields, CRM_Core_DAO_Website
::import());
1347 $fields['url']['hasWebsiteType'] = TRUE;
1349 if ($contactType != 'All') {
1350 $fields = array_merge($fields,
1351 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType,
1356 $withMultiCustomFields
1359 //unset the fields, which are not related to their
1361 $commonValues = array(
1362 'Individual' => array(
1366 'organization_name',
1368 'Household' => array(
1378 'organization_name',
1386 'Organization' => array(
1401 foreach ($commonValues[$contactType] as $value) {
1402 unset($fields[$value]);
1406 foreach (array('Individual', 'Household', 'Organization') as $type) {
1407 $fields = array_merge($fields,
1408 CRM_Core_BAO_CustomField
::getFieldsForImport($type,
1413 $withMultiCustomFields
1420 $fields = array_merge($fields, array(
1422 'title' => ts('Group(s)'),
1426 'title' => ts('Tag(s)'),
1430 'title' => ts('Note(s)'),
1433 'communication_style_id' => array(
1434 'title' => ts('Communication Style'),
1435 'name' => 'communication_style_id',
1440 //Sorting fields in alphabetical order(CRM-1507)
1441 $fields = CRM_Utils_Array
::crmArraySortByField($fields, 'title');
1443 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1446 self
::$_importableFields[$cacheKeyString] = $fields;
1450 $fields = array_merge(array('do_not_import' => array('title' => ts('- do not import -'))),
1451 self
::$_importableFields[$cacheKeyString]
1455 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1456 self
::$_importableFields[$cacheKeyString]
1464 * Combine all the exportable fields from the lower levels object.
1466 * Currently we are using importable fields as exportable fields
1468 * @param int|string $contactType contact Type
1469 * @param bool $status
1470 * True while exporting primary contacts.
1471 * @param bool $export
1472 * True when used during export.
1473 * @param bool $search
1474 * True when used during search, might conflict with export param?.
1476 * @param bool $withMultiRecord
1479 * array of exportable Fields
1481 public static function &exportableFields($contactType = 'Individual', $status = FALSE, $export = FALSE, $search = FALSE, $withMultiRecord = FALSE, $checkPermissions = TRUE) {
1482 if (empty($contactType)) {
1483 $contactType = 'All';
1486 $cacheKeyString = "exportableFields $contactType";
1487 $cacheKeyString .= $export ?
'_1' : '_0';
1488 $cacheKeyString .= $status ?
'_1' : '_0';
1489 $cacheKeyString .= $search ?
'_1' : '_0';
1490 //CRM-14501 it turns out that the impact of permissioning here is sometimes inconsistent. The field that
1491 //calculates custom fields takes into account the logged in user & caches that for all users
1492 //as an interim fix we will cache the fields by contact
1493 $cacheKeyString .= '_' . CRM_Core_Session
::getLoggedInContactID();
1495 if (!self
::$_exportableFields ||
!CRM_Utils_Array
::value($cacheKeyString, self
::$_exportableFields)) {
1496 if (!self
::$_exportableFields) {
1497 self
::$_exportableFields = array();
1500 // check if we can retrieve from database cache
1501 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', $cacheKeyString);
1504 $fields = CRM_Contact_DAO_Contact
::export();
1506 // The fields are meant for contact types.
1507 if (in_array($contactType, array(
1514 $fields = array_merge($fields, CRM_Core_OptionValue
::getFields('', $contactType));
1516 // add current employer for individuals
1517 $fields = array_merge($fields, array(
1518 'current_employer' =>
1520 'name' => 'organization_name',
1521 'title' => ts('Current Employer'),
1525 $locationType = array(
1526 'location_type' => array(
1527 'name' => 'location_type',
1528 'where' => 'civicrm_location_type.name',
1529 'title' => ts('Location Type'),
1533 $IMProvider = array(
1534 'im_provider' => array(
1535 'name' => 'im_provider',
1536 'where' => 'civicrm_im.provider_id',
1537 'title' => ts('IM Provider'),
1541 $locationFields = array_merge($locationType,
1542 CRM_Core_DAO_Address
::export(),
1543 CRM_Core_DAO_Phone
::export(),
1544 CRM_Core_DAO_Email
::export(),
1546 CRM_Core_DAO_IM
::export(TRUE),
1547 CRM_Core_DAO_OpenID
::export()
1550 $locationFields = array_merge($locationFields,
1551 CRM_Core_BAO_CustomField
::getFieldsForImport('Address')
1554 foreach ($locationFields as $key => $field) {
1555 $locationFields[$key]['hasLocationType'] = TRUE;
1558 $fields = array_merge($fields, $locationFields);
1561 $fields = array_merge($fields,
1562 CRM_Core_DAO_Worldregion
::export()
1565 $fields = array_merge($fields,
1566 CRM_Contact_DAO_Contact
::export()
1570 $fields = array_merge($fields, CRM_Core_DAO_Website
::export());
1572 if ($contactType != 'All') {
1573 $fields = array_merge($fields,
1574 CRM_Core_BAO_CustomField
::getFieldsForImport($contactType, $status, FALSE, $search, $checkPermissions, $withMultiRecord)
1583 $fields = array_merge($fields,
1584 CRM_Core_BAO_CustomField
::getFieldsForImport($type, FALSE, FALSE, $search, $checkPermissions, $withMultiRecord)
1588 $fields['current_employer_id']['title'] = ts('Current Employer ID');
1591 $fields = array_merge($fields, array(
1593 'title' => ts('Group(s)'),
1597 'title' => ts('Tag(s)'),
1601 'title' => ts('Note(s)'),
1607 $fields = array_merge($fields, array(
1609 'title' => ts('Group(s)'),
1613 'title' => ts('Tag(s)'),
1617 'title' => ts('Note(s)'),
1623 //Sorting fields in alphabetical order(CRM-1507)
1624 foreach ($fields as $k => $v) {
1625 $sortArray[$k] = CRM_Utils_Array
::value('title', $v);
1628 $fields = array_merge($sortArray, $fields);
1629 //unset the field which are not related to their contact type.
1630 if ($contactType != 'All') {
1631 $commonValues = array(
1632 'Individual' => array(
1636 'organization_name',
1637 'email_greeting_custom',
1638 'postal_greeting_custom',
1641 'Household' => array(
1651 'organization_name',
1659 'email_greeting_custom',
1660 'postal_greeting_custom',
1665 'Organization' => array(
1676 'email_greeting_custom',
1677 'postal_greeting_custom',
1687 foreach ($commonValues[$contactType] as $value) {
1688 unset($fields[$value]);
1692 CRM_Core_BAO_Cache
::setItem($fields, 'contact fields', $cacheKeyString);
1694 self
::$_exportableFields[$cacheKeyString] = $fields;
1698 $fields = self
::$_exportableFields[$cacheKeyString];
1701 $fields = array_merge(array('' => array('title' => ts('- Contact Fields -'))),
1702 self
::$_exportableFields[$cacheKeyString]
1710 * Get the all contact details (Hierarchical).
1712 * @param int $contactId
1714 * @param array $fields
1720 public static function getHierContactDetails($contactId, &$fields) {
1721 $params = array(array('contact_id', '=', $contactId, 0, 0));
1724 $returnProperties = self
::makeHierReturnProperties($fields, $contactId);
1726 // We don't know the contents of return properties, but we need the lower
1727 // level ids of the contact so add a few fields.
1728 $returnProperties['first_name'] = 1;
1729 $returnProperties['organization_name'] = 1;
1730 $returnProperties['household_name'] = 1;
1731 $returnProperties['contact_type'] = 1;
1732 $returnProperties['contact_sub_type'] = 1;
1733 return list($query, $options) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, $options);
1737 * Given a set of flat profile style field names, create a hierarchy.
1739 * This is for the query to use, create the right sql.
1742 * @param int $contactId
1746 * A hierarchical property tree if appropriate
1748 public static function &makeHierReturnProperties($fields, $contactId = NULL) {
1749 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
1751 $returnProperties = array();
1753 $multipleFields = array('website' => 'url');
1754 foreach ($fields as $name => $dontCare) {
1755 if (strpos($name, '-') !== FALSE) {
1756 list($fieldName, $id, $type) = CRM_Utils_System
::explode('-', $name, 3);
1758 if (!in_array($fieldName, $multipleFields)) {
1759 if ($id == 'Primary') {
1760 $locationTypeName = 1;
1763 $locationTypeName = CRM_Utils_Array
::value($id, $locationTypes);
1764 if (!$locationTypeName) {
1769 if (empty($returnProperties['location'])) {
1770 $returnProperties['location'] = array();
1772 if (empty($returnProperties['location'][$locationTypeName])) {
1773 $returnProperties['location'][$locationTypeName] = array();
1774 $returnProperties['location'][$locationTypeName]['location_type'] = $id;
1776 if (in_array($fieldName, array(
1784 $returnProperties['location'][$locationTypeName][$fieldName . '-' . $type] = 1;
1787 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1790 elseif (substr($fieldName, 0, 14) === 'address_custom') {
1791 $returnProperties['location'][$locationTypeName][substr($fieldName, 8)] = 1;
1794 $returnProperties['location'][$locationTypeName][$fieldName] = 1;
1798 $returnProperties['website'][$id][$fieldName] = 1;
1802 $returnProperties[$name] = 1;
1806 return $returnProperties;
1810 * Return the primary location type of a contact.
1812 * $params int $contactId contact_id
1813 * $params boolean $isPrimaryExist if true, return primary contact location type otherwise null
1814 * $params boolean $skipDefaultPriamry if true, return primary contact location type otherwise null
1816 * @param int $contactId
1817 * @param bool $skipDefaultPriamry
1818 * @param null $block
1821 * $locationType location_type_id
1823 public static function getPrimaryLocationType($contactId, $skipDefaultPriamry = FALSE, $block = NULL) {
1825 $entityBlock = array('contact_id' => $contactId);
1826 $blocks = CRM_Core_BAO_Location
::getValues($entityBlock);
1827 foreach ($blocks[$block] as $key => $value) {
1828 if (!empty($value['is_primary'])) {
1829 $locationType = CRM_Utils_Array
::value('location_type_id', $value);
1836 IF ( civicrm_email.location_type_id IS NULL,
1837 IF ( civicrm_address.location_type_id IS NULL,
1838 IF ( civicrm_phone.location_type_id IS NULL,
1839 IF ( civicrm_im.location_type_id IS NULL,
1840 IF ( civicrm_openid.location_type_id IS NULL, null, civicrm_openid.location_type_id)
1841 ,civicrm_im.location_type_id)
1842 ,civicrm_phone.location_type_id)
1843 ,civicrm_address.location_type_id)
1844 ,civicrm_email.location_type_id) as locationType
1845 FROM civicrm_contact
1846 LEFT JOIN civicrm_email ON ( civicrm_email.is_primary = 1 AND civicrm_email.contact_id = civicrm_contact.id )
1847 LEFT JOIN civicrm_address ON ( civicrm_address.is_primary = 1 AND civicrm_address.contact_id = civicrm_contact.id)
1848 LEFT JOIN civicrm_phone ON ( civicrm_phone.is_primary = 1 AND civicrm_phone.contact_id = civicrm_contact.id)
1849 LEFT JOIN civicrm_im ON ( civicrm_im.is_primary = 1 AND civicrm_im.contact_id = civicrm_contact.id)
1850 LEFT JOIN civicrm_openid ON ( civicrm_openid.is_primary = 1 AND civicrm_openid.contact_id = civicrm_contact.id)
1851 WHERE civicrm_contact.id = %1 ";
1853 $params = array(1 => array($contactId, 'Integer'));
1855 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1857 $locationType = NULL;
1858 if ($dao->fetch()) {
1859 $locationType = $dao->locationType
;
1862 if (isset($locationType)) {
1863 return $locationType;
1865 elseif ($skipDefaultPriamry) {
1866 // if there is no primary contact location then return null
1870 // if there is no primart contact location, then return default
1871 // location type of the system
1872 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
1873 return $defaultLocationType->id
;
1878 * Get the display name, primary email and location type of a contact.
1881 * Id of the contact.
1884 * Array of display_name, email if found, do_not_email or (null,null,null)
1886 public static function getContactDetails($id) {
1887 // check if the contact type
1888 $contactType = self
::getContactType($id);
1890 $nameFields = ($contactType == 'Individual') ?
"civicrm_contact.first_name, civicrm_contact.last_name, civicrm_contact.display_name" : "civicrm_contact.display_name";
1893 SELECT $nameFields, civicrm_email.email, civicrm_contact.do_not_email, civicrm_email.on_hold, civicrm_contact.is_deceased
1894 FROM civicrm_contact LEFT JOIN civicrm_email ON (civicrm_contact.id = civicrm_email.contact_id)
1895 WHERE civicrm_contact.id = %1
1896 ORDER BY civicrm_email.is_primary DESC";
1897 $params = array(1 => array($id, 'Integer'));
1898 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
1900 if ($dao->fetch()) {
1901 if ($contactType == 'Individual') {
1902 if ($dao->first_name ||
$dao->last_name
) {
1903 $name = "{$dao->first_name} {$dao->last_name}";
1906 $name = $dao->display_name
;
1910 $name = $dao->display_name
;
1912 $email = $dao->email
;
1913 $doNotEmail = $dao->do_not_email ?
TRUE : FALSE;
1914 $onHold = $dao->on_hold ?
TRUE : FALSE;
1915 $isDeceased = $dao->is_deceased ?
TRUE : FALSE;
1916 return array($name, $email, $doNotEmail, $onHold, $isDeceased);
1918 return array(NULL, NULL, NULL, NULL, NULL);
1922 * Add/edit/register contacts through profile.
1924 * @param array $params
1925 * Array of profile fields to be edited/added.
1926 * @param array $fields
1927 * Array of fields from UFGroup.
1928 * @param int $contactID
1929 * Id of the contact to be edited/added.
1930 * @param int $addToGroupID
1931 * Specifies the default group to which contact is added.
1932 * @param int $ufGroupId
1933 * Uf group id (profile id).
1934 * @param string $ctype
1935 * @param bool $visibility
1936 * Basically lets us know where this request is coming from.
1937 * if via a profile from web, we restrict what groups are changed
1940 * contact id created/edited
1942 public static function createProfileContact(
1946 $addToGroupID = NULL,
1951 // add ufGroupID to params array ( CRM-2012 )
1953 $params['uf_group_id'] = $ufGroupId;
1955 self
::addBillingNameFieldsIfOtherwiseNotSet($params);
1957 // If a user has logged in, or accessed via a checksum
1958 // Then deliberately 'blanking' a value in the profile should remove it from their record
1959 $session = CRM_Core_Session
::singleton();
1960 $params['updateBlankLocInfo'] = TRUE;
1961 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0) {
1962 $params['updateBlankLocInfo'] = FALSE;
1967 CRM_Utils_Hook
::pre('edit', 'Profile', $contactID, $params);
1971 CRM_Utils_Hook
::pre('create', 'Profile', NULL, $params);
1974 list($data, $contactDetails) = self
::formatProfileContactParams($params, $fields, $contactID, $ufGroupId, $ctype);
1976 // manage is_opt_out
1977 if (array_key_exists('is_opt_out', $fields) && array_key_exists('is_opt_out', $params)) {
1978 $wasOptOut = CRM_Utils_Array
::value('is_opt_out', $contactDetails, FALSE);
1979 $isOptOut = CRM_Utils_Array
::value('is_opt_out', $params, FALSE);
1980 $data['is_opt_out'] = $isOptOut;
1981 // on change, create new civicrm_subscription_history entry
1982 if (($wasOptOut != $isOptOut) && !empty($contactDetails['contact_id'])) {
1984 'contact_id' => $contactDetails['contact_id'],
1985 'status' => $isOptOut ?
'Removed' : 'Added',
1988 CRM_Contact_BAO_SubscriptionHistory
::create($shParams);
1992 $contact = self
::create($data);
1994 // contact is null if the profile does not have any contact fields
1996 $contactID = $contact->id
;
1999 if (empty($contactID)) {
2000 CRM_Core_Error
::fatal('Cannot proceed without a valid contact id');
2003 // Process group and tag
2004 if (!empty($fields['group'])) {
2006 // this for sure means we are coming in via profile since i added it to fix
2007 // removing contacts from user groups -- lobo
2011 CRM_Contact_BAO_GroupContact
::create($params['group'], $contactID, $visibility, $method);
2014 if (!empty($fields['tag'])) {
2015 CRM_Core_BAO_EntityTag
::create($params['tag'], 'civicrm_contact', $contactID);
2018 //to add profile in default group
2019 if (is_array($addToGroupID)) {
2020 $contactIds = array($contactID);
2021 foreach ($addToGroupID as $groupId) {
2022 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $groupId);
2025 elseif ($addToGroupID) {
2026 $contactIds = array($contactID);
2027 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds, $addToGroupID);
2030 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
2033 CRM_Utils_Hook
::post('edit', 'Profile', $contactID, $params);
2036 CRM_Utils_Hook
::post('create', 'Profile', $contactID, $params);
2042 * Format profile contact parameters.
2044 * @param array $params
2046 * @param int $contactID
2047 * @param int $ufGroupId
2048 * @param null $ctype
2049 * @param bool $skipCustom
2053 public static function formatProfileContactParams(
2062 $data = $contactDetails = array();
2064 // get the contact details (hier)
2066 list($details, $options) = self
::getHierContactDetails($contactID, $fields);
2068 $contactDetails = $details[$contactID];
2069 $data['contact_type'] = CRM_Utils_Array
::value('contact_type', $contactDetails);
2070 $data['contact_sub_type'] = CRM_Utils_Array
::value('contact_sub_type', $contactDetails);
2073 //we should get contact type only if contact
2075 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId);
2077 //special case to handle profile with only contact fields
2078 if ($data['contact_type'] == 'Contact') {
2079 $data['contact_type'] = 'Individual';
2081 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
2082 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
2086 $data['contact_type'] = $ctype;
2089 $data['contact_type'] = 'Individual';
2093 //fix contact sub type CRM-5125
2094 if (array_key_exists('contact_sub_type', $params) &&
2095 !empty($params['contact_sub_type'])
2097 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
2099 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
2100 !empty($params['contact_sub_type_hidden'])
2102 // if profile was used, and had any subtype, we obtain it from there
2103 //CRM-13596 - add to existing contact types, rather than overwriting
2104 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2105 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
2106 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
2107 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
2108 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
2112 if ($ctype == 'Organization') {
2113 $data['organization_name'] = CRM_Utils_Array
::value('organization_name', $contactDetails);
2115 elseif ($ctype == 'Household') {
2116 $data['household_name'] = CRM_Utils_Array
::value('household_name', $contactDetails);
2119 $locationType = array();
2124 $data['contact_id'] = $contactID;
2125 $primaryLocationType = self
::getPrimaryLocationType($contactID);
2128 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
2129 $defaultLocationId = $defaultLocation->id
;
2132 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
2134 $blocks = array('email', 'phone', 'im', 'openid');
2136 $multiplFields = array('url');
2137 // prevent overwritten of formatted array, reset all block from
2138 // params if it is not in valid format (since import pass valid format)
2139 foreach ($blocks as $blk) {
2140 if (array_key_exists($blk, $params) &&
2141 !is_array($params[$blk])
2143 unset($params[$blk]);
2147 $primaryPhoneLoc = NULL;
2148 $session = CRM_Core_Session
::singleton();
2149 foreach ($params as $key => $value) {
2150 list($fieldName, $locTypeId, $typeId) = CRM_Utils_System
::explode('-', $key, 3);
2152 if ($locTypeId == 'Primary') {
2154 if (in_array($fieldName, $blocks)) {
2155 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, $fieldName);
2158 $locTypeId = self
::getPrimaryLocationType($contactID, FALSE, 'address');
2160 $primaryLocationType = $locTypeId;
2163 $locTypeId = $defaultLocationId;
2167 if (is_numeric($locTypeId) &&
2168 !in_array($fieldName, $multiplFields) &&
2169 substr($fieldName, 0, 7) != 'custom_'
2171 $index = $locTypeId;
2173 if (is_numeric($typeId)) {
2174 $index .= '-' . $typeId;
2176 if (!in_array($index, $locationType)) {
2177 $locationType[$count] = $index;
2181 $loc = CRM_Utils_Array
::key($index, $locationType);
2183 $blockName = in_array($fieldName, $blocks) ?
$fieldName : 'address';
2185 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
2187 //set is_billing true, for location type "Billing"
2188 if ($locTypeId == $billingLocationTypeId) {
2189 $data[$blockName][$loc]['is_billing'] = 1;
2193 //get the primary location type
2194 if ($locTypeId == $primaryLocationType) {
2195 $data[$blockName][$loc]['is_primary'] = 1;
2198 elseif ($locTypeId == $defaultLocationId) {
2199 $data[$blockName][$loc]['is_primary'] = 1;
2202 if (in_array($fieldName, array('phone'))) {
2204 $data['phone'][$loc]['phone_type_id'] = $typeId;
2207 $data['phone'][$loc]['phone_type_id'] = '';
2209 $data['phone'][$loc]['phone'] = $value;
2211 //special case to handle primary phone with different phone types
2212 // in this case we make first phone type as primary
2213 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
2214 $primaryPhoneLoc = $loc;
2217 if ($loc != $primaryPhoneLoc) {
2218 unset($data['phone'][$loc]['is_primary']);
2221 elseif ($fieldName == 'phone_ext') {
2222 $data['phone'][$loc]['phone_ext'] = $value;
2224 elseif ($fieldName == 'email') {
2225 $data['email'][$loc]['email'] = $value;
2226 if (empty($contactID)) {
2227 $data['email'][$loc]['is_primary'] = 1;
2230 elseif ($fieldName == 'im') {
2231 if (isset($params[$key . '-provider_id'])) {
2232 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
2234 if (strpos($key, '-provider_id') !== FALSE) {
2235 $data['im'][$loc]['provider_id'] = $params[$key];
2238 $data['im'][$loc]['name'] = $value;
2241 elseif ($fieldName == 'openid') {
2242 $data['openid'][$loc]['openid'] = $value;
2245 if ($fieldName === 'state_province') {
2247 if (is_numeric($value) && ((int ) $value) >= 1000) {
2248 $data['address'][$loc]['state_province_id'] = $value;
2250 elseif (empty($value)) {
2251 $data['address'][$loc]['state_province_id'] = '';
2254 $data['address'][$loc]['state_province'] = $value;
2257 elseif ($fieldName === 'country') {
2259 if (is_numeric($value) && ((int ) $value) >= 1000
2261 $data['address'][$loc]['country_id'] = $value;
2263 elseif (empty($value)) {
2264 $data['address'][$loc]['country_id'] = '';
2267 $data['address'][$loc]['country'] = $value;
2270 elseif ($fieldName === 'county') {
2271 $data['address'][$loc]['county_id'] = $value;
2273 elseif ($fieldName == 'address_name') {
2274 $data['address'][$loc]['name'] = $value;
2276 elseif (substr($fieldName, 0, 14) === 'address_custom') {
2277 $data['address'][$loc][substr($fieldName, 8)] = $value;
2280 $data['address'][$loc][$fieldName] = $value;
2285 if (substr($key, 0, 4) === 'url-') {
2286 $websiteField = explode('-', $key);
2287 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
2288 $data['website'][$websiteField[1]]['url'] = $value;
2290 elseif (in_array($key, self
::$_greetingTypes, TRUE)) {
2291 //save email/postal greeting and addressee values if any, CRM-4575
2292 $data[$key . '_id'] = $value;
2294 elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
2295 // for autocomplete transfer hidden value instead of label
2296 if ($params[$key] && isset($params[$key . '_id'])) {
2297 $value = $params[$key . '_id'];
2300 // we need to append time with date
2301 if ($params[$key] && isset($params[$key . '_time'])) {
2302 $value .= ' ' . $params[$key . '_time'];
2305 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
2306 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
2307 ($value == '' ||
!isset($value))
2313 if (!empty($params['customRecordValues'])) {
2314 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
2315 foreach ($params['customRecordValues'] as $recId => $customFields) {
2316 if (is_array($customFields) && !empty($customFields)) {
2317 foreach ($customFields as $customFieldName) {
2318 if ($customFieldName == $key) {
2328 //CRM-13596 - check for contact_sub_type_hidden first
2329 if (array_key_exists('contact_sub_type_hidden', $params)) {
2330 $type = $params['contact_sub_type_hidden'];
2333 $type = $data['contact_type'];
2334 if (!empty($data['contact_sub_type'])) {
2335 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
2339 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
2349 elseif ($key == 'edit') {
2353 if ($key == 'location') {
2354 foreach ($value as $locationTypeId => $field) {
2355 foreach ($field as $block => $val) {
2356 if ($block == 'address' && array_key_exists('address_name', $val)) {
2357 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
2362 if ($key == 'phone' && isset($params['phone_ext'])) {
2363 $data[$key] = $value;
2364 foreach ($value as $cnt => $phoneBlock) {
2365 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
2366 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
2370 elseif (in_array($key,
2381 ($value == '' ||
!isset($value)) &&
2382 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
2383 ($key == 'current_employer' && empty($params['current_employer']))) {
2384 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
2385 // to avoid update with empty values
2389 $data[$key] = $value;
2395 if (!isset($data['contact_type'])) {
2396 $data['contact_type'] = 'Individual';
2399 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
2400 $privacy = CRM_Core_SelectValues
::privacy();
2401 foreach ($privacy as $key => $value) {
2402 if (array_key_exists($key, $fields)) {
2403 // do not reset values for existing contacts, if fields are added to a profile
2404 if (array_key_exists($key, $params)) {
2405 $data[$key] = $params[$key];
2406 if (empty($params[$key])) {
2410 elseif (!$contactID) {
2416 return array($data, $contactDetails);
2420 * Find the get contact details.
2422 * This function does not respect ACLs for now, which might need to be rectified at some
2423 * stage based on how its used.
2425 * @param string $mail
2426 * Primary email address of the contact.
2427 * @param string $ctype
2430 * @return object|null
2431 * $dao contact details
2433 public static function matchContactOnEmail($mail, $ctype = NULL) {
2434 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2435 $mail = $strtolower(trim($mail));
2437 SELECT civicrm_contact.id as contact_id,
2438 civicrm_contact.hash as hash,
2439 civicrm_contact.contact_type as contact_type,
2440 civicrm_contact.contact_sub_type as contact_sub_type
2441 FROM civicrm_contact
2442 INNER JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )";
2444 if (Civi
::settings()->get('uniq_email_per_site')) {
2445 // try to find a match within a site (multisite).
2446 $groups = CRM_Core_BAO_Domain
::getChildGroupIds();
2447 if (!empty($groups)) {
2449 INNER JOIN civicrm_group_contact gc ON
2450 (civicrm_contact.id = gc.contact_id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $groups) . "))";
2455 WHERE civicrm_email.email = %1 AND civicrm_contact.is_deleted=0";
2456 $p = array(1 => array($mail, 'String'));
2459 $query .= " AND civicrm_contact.contact_type = %3";
2460 $p[3] = array($ctype, 'String');
2463 $query .= " ORDER BY civicrm_email.is_primary DESC";
2465 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2467 if ($dao->fetch()) {
2474 * Find the contact details associated with an OpenID.
2476 * @param string $openId
2477 * OpenId of the contact.
2478 * @param string $ctype
2481 * @return object|null
2482 * $dao contact details
2484 public static function matchContactOnOpenId($openId, $ctype = NULL) {
2485 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
2486 $openId = $strtolower(trim($openId));
2488 SELECT civicrm_contact.id as contact_id,
2489 civicrm_contact.hash as hash,
2490 civicrm_contact.contact_type as contact_type,
2491 civicrm_contact.contact_sub_type as contact_sub_type
2492 FROM civicrm_contact
2493 INNER JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2494 WHERE civicrm_openid.openid = %1";
2495 $p = array(1 => array($openId, 'String'));
2498 $query .= " AND civicrm_contact.contact_type = %3";
2499 $p[3] = array($ctype, 'String');
2502 $query .= " ORDER BY civicrm_openid.is_primary DESC";
2504 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2506 if ($dao->fetch()) {
2513 * Get primary email of the contact.
2515 * @param int $contactID
2519 * Email address if present else null
2521 public static function getPrimaryEmail($contactID) {
2522 // fetch the primary email
2524 SELECT civicrm_email.email as email
2525 FROM civicrm_contact
2526 LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id )
2527 WHERE civicrm_email.is_primary = 1
2528 AND civicrm_contact.id = %1";
2529 $p = array(1 => array($contactID, 'Integer'));
2530 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2533 if ($dao->fetch()) {
2534 $email = $dao->email
;
2541 * Function to get primary OpenID of the contact.
2543 * @param int $contactID
2547 * >openid OpenID if present else null
2549 public static function getPrimaryOpenId($contactID) {
2550 // fetch the primary OpenID
2552 SELECT civicrm_openid.openid as openid
2553 FROM civicrm_contact
2554 LEFT JOIN civicrm_openid ON ( civicrm_contact.id = civicrm_openid.contact_id )
2555 WHERE civicrm_contact.id = %1
2556 AND civicrm_openid.is_primary = 1";
2557 $p = array(1 => array($contactID, 'Integer'));
2558 $dao = CRM_Core_DAO
::executeQuery($query, $p);
2561 if ($dao->fetch()) {
2562 $openId = $dao->openid
;
2569 * Fetch the object and store the values in the values array.
2571 * @param array $params
2572 * Input parameters to find object.
2573 * @param array $values
2574 * Output values of the object.
2576 * @return CRM_Contact_BAO_Contact|null
2577 * The found object or null
2579 public static function getValues(&$params, &$values) {
2580 $contact = new CRM_Contact_BAO_Contact();
2582 $contact->copyValues($params);
2584 if ($contact->find(TRUE)) {
2586 CRM_Core_DAO
::storeValues($contact, $values);
2589 foreach (self
::$_commPrefs as $name) {
2590 if (isset($contact->$name)) {
2591 $privacy[$name] = $contact->$name;
2595 if (!empty($privacy)) {
2596 $values['privacy'] = $privacy;
2599 // communication Prefferance
2600 $preffComm = $comm = array();
2601 $comm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2602 $contact->preferred_communication_method
2604 foreach ($comm as $value) {
2605 $preffComm[$value] = 1;
2607 $temp = array('preferred_communication_method' => $contact->preferred_communication_method
);
2610 'preferred_communication_method' => array(
2611 'newName' => 'preferred_communication_method_display',
2612 'groupName' => 'preferred_communication_method',
2616 // @todo This can be figured out from metadata & we can avoid the uncached query.
2617 CRM_Core_OptionGroup
::lookupValues($temp, $names, FALSE);
2619 $values['preferred_communication_method'] = $preffComm;
2620 $values['preferred_communication_method_display'] = CRM_Utils_Array
::value('preferred_communication_method_display', $temp);
2622 if ($contact->preferred_mail_format
) {
2623 $preferredMailingFormat = CRM_Core_SelectValues
::pmf();
2624 $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format
];
2627 // get preferred languages
2628 if (!empty($contact->preferred_language
)) {
2629 $values['preferred_language'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language
);
2632 // Calculating Year difference
2633 if ($contact->birth_date
) {
2634 $birthDate = CRM_Utils_Date
::customFormat($contact->birth_date
, '%Y%m%d');
2635 if ($birthDate < date('Ymd')) {
2636 $age = CRM_Utils_Date
::calculateAge($birthDate);
2637 $values['age']['y'] = CRM_Utils_Array
::value('years', $age);
2638 $values['age']['m'] = CRM_Utils_Array
::value('months', $age);
2642 $contact->contact_id
= $contact->id
;
2650 * Given the component name and returns the count of participation of contact.
2652 * @param string $component
2653 * Input component name.
2654 * @param int $contactId
2656 * @param string $tableName
2657 * Optional tableName if component is custom group.
2660 * total number in database
2662 public static function getCountComponent($component, $contactId, $tableName = NULL) {
2664 switch ($component) {
2666 return CRM_Core_BAO_EntityTag
::getContactTags($contactId, TRUE);
2669 $result = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
2670 CRM_Contact_BAO_Relationship
::CURRENT
,
2679 return CRM_Contact_BAO_GroupContact
::getContactGroup($contactId, "Added", NULL, TRUE);
2682 if (CRM_Core_BAO_Log
::useLoggingReport()) {
2685 return CRM_Core_BAO_Log
::getContactLogCount($contactId);
2688 return CRM_Core_BAO_Note
::getContactNoteCount($contactId);
2690 case 'contribution':
2691 return CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
2694 return CRM_Member_BAO_Membership
::getContactMembershipCount($contactId, TRUE);
2697 return CRM_Event_BAO_Participant
::getContactParticipantCount($contactId);
2700 return CRM_Pledge_BAO_Pledge
::getContactPledgeCount($contactId);
2703 return CRM_Case_BAO_Case
::caseCount($contactId);
2706 return CRM_Grant_BAO_Grant
::getContactGrantCount($contactId);
2710 'contact_id' => $contactId,
2713 'context' => 'activity',
2715 return CRM_Activity_BAO_Activity
::deprecatedGetActivitiesCount($input);
2718 $params = array('contact_id' => $contactId);
2719 return CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2722 $custom = explode('_', $component);
2723 if ($custom['0'] = 'custom') {
2725 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name');
2727 $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}";
2728 return CRM_Core_DAO
::singleValueQuery($queryString);
2734 * Update contact greetings if an update has resulted in a custom field change.
2736 * @param array $updatedFields
2737 * Array of fields that have been updated e.g array('first_name', 'prefix_id', 'custom_2');
2738 * @param array $contactParams
2739 * Parameters known about the contact. At minimum array('contact_id' => x).
2740 * Fields in this array will take precedence over DB fields (so far only
2741 * in the case of greeting id fields).
2743 public static function updateGreetingsOnTokenFieldChange($updatedFields, $contactParams) {
2744 $contactID = $contactParams['contact_id'];
2745 CRM_Contact_BAO_Contact
::ensureGreetingParamsAreSet($contactParams);
2746 $tokens = CRM_Contact_BAO_Contact_Utils
::getTokensRequiredForContactGreetings($contactParams);
2747 if (!empty($tokens['all']['contact'])) {
2748 $affectedTokens = array_intersect_key($updatedFields[$contactID], array_flip($tokens['all']['contact']));
2749 if (!empty($affectedTokens)) {
2750 // @todo this is still reloading the whole contact -fix to be more selective & use pre-loaded.
2751 $contact = new CRM_Contact_BAO_Contact();
2752 $contact->id
= $contactID;
2753 CRM_Contact_BAO_Contact
::processGreetings($contact);
2759 * Process greetings and cache.
2761 * @param object $contact
2762 * Contact object after save.
2764 public static function processGreetings(&$contact) {
2766 //@todo this function does a lot of unnecessary loading.
2767 // ensureGreetingParamsAreSet now makes sure that the contact is
2768 // loaded and using updateGreetingsOnTokenFieldChange
2769 // allows us the possibility of only doing an update if required.
2771 // The contact object has not always required the
2772 // fields that are required to calculate greetings
2773 // so we need to retrieve it again.
2774 if ($contact->_query
!== FALSE) {
2775 $contact->find(TRUE);
2778 // store object values to an array
2779 $contactDetails = array();
2780 CRM_Core_DAO
::storeValues($contact, $contactDetails);
2781 $contactDetails = array(array($contact->id
=> $contactDetails));
2783 $emailGreetingString = $postalGreetingString = $addresseeString = NULL;
2784 $updateQueryString = array();
2786 //cache email and postal greeting to greeting display
2787 if ($contact->email_greeting_custom
!= 'null' && $contact->email_greeting_custom
) {
2788 $emailGreetingString = $contact->email_greeting_custom
;
2790 elseif ($contact->email_greeting_id
!= 'null' && $contact->email_greeting_id
) {
2791 // the filter value for Individual contact type is set to 1
2793 'contact_type' => $contact->contact_type
,
2794 'greeting_type' => 'email_greeting',
2797 $emailGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2798 $emailGreetingString = $emailGreeting[$contact->email_greeting_id
];
2799 $updateQueryString[] = " email_greeting_custom = NULL ";
2802 if ($contact->email_greeting_custom
) {
2803 $updateQueryString[] = " email_greeting_display = NULL ";
2807 if ($emailGreetingString) {
2808 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($emailGreetingString,
2811 'CRM_Contact_BAO_Contact'
2813 $emailGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($emailGreetingString));
2814 $updateQueryString[] = " email_greeting_display = '{$emailGreetingString}'";
2818 if ($contact->postal_greeting_custom
!= 'null' && $contact->postal_greeting_custom
) {
2819 $postalGreetingString = $contact->postal_greeting_custom
;
2821 elseif ($contact->postal_greeting_id
!= 'null' && $contact->postal_greeting_id
) {
2823 'contact_type' => $contact->contact_type
,
2824 'greeting_type' => 'postal_greeting',
2826 $postalGreeting = CRM_Core_PseudoConstant
::greeting($filter);
2827 $postalGreetingString = $postalGreeting[$contact->postal_greeting_id
];
2828 $updateQueryString[] = " postal_greeting_custom = NULL ";
2831 if ($contact->postal_greeting_custom
) {
2832 $updateQueryString[] = " postal_greeting_display = NULL ";
2836 if ($postalGreetingString) {
2837 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($postalGreetingString,
2840 'CRM_Contact_BAO_Contact'
2842 $postalGreetingString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($postalGreetingString));
2843 $updateQueryString[] = " postal_greeting_display = '{$postalGreetingString}'";
2847 if ($contact->addressee_custom
!= 'null' && $contact->addressee_custom
) {
2848 $addresseeString = $contact->addressee_custom
;
2850 elseif ($contact->addressee_id
!= 'null' && $contact->addressee_id
) {
2852 'contact_type' => $contact->contact_type
,
2853 'greeting_type' => 'addressee',
2856 $addressee = CRM_Core_PseudoConstant
::greeting($filter);
2857 $addresseeString = $addressee[$contact->addressee_id
];
2858 $updateQueryString[] = " addressee_custom = NULL ";
2861 if ($contact->addressee_custom
) {
2862 $updateQueryString[] = " addressee_display = NULL ";
2866 if ($addresseeString) {
2867 CRM_Contact_BAO_Contact_Utils
::processGreetingTemplate($addresseeString,
2870 'CRM_Contact_BAO_Contact'
2872 $addresseeString = CRM_Core_DAO
::escapeString(CRM_Utils_String
::stripSpaces($addresseeString));
2873 $updateQueryString[] = " addressee_display = '{$addresseeString}'";
2876 if (!empty($updateQueryString)) {
2877 $updateQueryString = implode(',', $updateQueryString);
2878 $queryString = "UPDATE civicrm_contact SET {$updateQueryString} WHERE id = {$contact->id}";
2879 CRM_Core_DAO
::executeQuery($queryString);
2884 * Retrieve loc block ids w/ given condition.
2886 * @param int $contactId
2888 * @param array $criteria
2889 * Key => value pair which should be.
2890 * fulfill by return record ids.
2891 * @param string $condOperator
2892 * Operator use for grouping multiple conditions.
2895 * loc block ids which fulfill condition.
2897 public static function getLocBlockIds($contactId, $criteria = array(), $condOperator = 'AND') {
2898 $locBlockIds = array();
2900 return $locBlockIds;
2903 foreach (array('Email', 'OpenID', 'Phone', 'Address', 'IM') as $block) {
2904 $name = strtolower($block);
2905 $className = "CRM_Core_DAO_$block";
2906 $blockDAO = new $className();
2908 // build the condition.
2909 if (is_array($criteria)) {
2910 $fields = $blockDAO->fields();
2911 $conditions = array();
2912 foreach ($criteria as $field => $value) {
2913 if (array_key_exists($field, $fields)) {
2914 $cond = "( $field = $value )";
2915 // value might be zero or null.
2916 if (!$value ||
strtolower($value) == 'null') {
2917 $cond = "( $field = 0 OR $field IS NULL )";
2919 $conditions[] = $cond;
2922 if (!empty($conditions)) {
2923 $blockDAO->whereAdd(implode(" $condOperator ", $conditions));
2927 $blockDAO->contact_id
= $contactId;
2929 while ($blockDAO->fetch()) {
2930 $locBlockIds[$name][] = $blockDAO->id
;
2935 return $locBlockIds;
2939 * Build context menu items.
2941 * @param int $contactId
2944 * Array of context menu for logged in user.
2946 public static function contextMenu($contactId = NULL) {
2949 'title' => ts('View Contact'),
2951 'ref' => 'view-contact',
2952 'class' => 'no-popup',
2954 'permissions' => array('view all contacts'),
2957 'title' => ts('Edit Contact'),
2959 'ref' => 'edit-contact',
2960 'class' => 'no-popup',
2962 'permissions' => array('edit all contacts'),
2965 'title' => ts('Delete Contact'),
2967 'ref' => 'delete-contact',
2969 'permissions' => array('access deleted contacts', 'delete contacts'),
2971 'contribution' => array(
2972 'title' => ts('Add Contribution'),
2974 'ref' => 'new-contribution',
2975 'key' => 'contribution',
2976 'tab' => 'contribute',
2977 'component' => 'CiviContribute',
2978 'href' => CRM_Utils_System
::url('civicrm/contact/view/contribution',
2979 'reset=1&action=add&context=contribution'
2981 'permissions' => array(
2982 'access CiviContribute',
2983 'edit contributions',
2986 'participant' => array(
2987 'title' => ts('Register for Event'),
2989 'ref' => 'new-participant',
2990 'key' => 'participant',
2991 'tab' => 'participant',
2992 'component' => 'CiviEvent',
2993 'href' => CRM_Utils_System
::url('civicrm/contact/view/participant', 'reset=1&action=add&context=participant'),
2994 'permissions' => array(
2996 'edit event participants',
2999 'activity' => array(
3000 'title' => ts('Record Activity'),
3002 'ref' => 'new-activity',
3003 'key' => 'activity',
3004 'permissions' => array('edit all contacts'),
3007 'title' => ts('Add Pledge'),
3009 'ref' => 'new-pledge',
3012 'href' => CRM_Utils_System
::url('civicrm/contact/view/pledge',
3013 'reset=1&action=add&context=pledge'
3015 'component' => 'CiviPledge',
3016 'permissions' => array(
3017 'access CiviPledge',
3021 'membership' => array(
3022 'title' => ts('Add Membership'),
3024 'ref' => 'new-membership',
3025 'key' => 'membership',
3027 'component' => 'CiviMember',
3028 'href' => CRM_Utils_System
::url('civicrm/contact/view/membership',
3029 'reset=1&action=add&context=membership'
3031 'permissions' => array(
3032 'access CiviMember',
3037 'title' => ts('Add Case'),
3039 'ref' => 'new-case',
3042 'component' => 'CiviCase',
3043 'href' => CRM_Utils_System
::url('civicrm/case/add', 'reset=1&action=add&context=case'),
3044 'permissions' => array('add cases'),
3047 'title' => ts('Add Grant'),
3049 'ref' => 'new-grant',
3052 'component' => 'CiviGrant',
3053 'href' => CRM_Utils_System
::url('civicrm/contact/view/grant',
3054 'reset=1&action=add&context=grant'
3056 'permissions' => array('edit grants'),
3059 'title' => ts('Add Relationship'),
3061 'ref' => 'new-relationship',
3064 'href' => CRM_Utils_System
::url('civicrm/contact/view/rel',
3065 'reset=1&action=add'
3067 'permissions' => array('edit all contacts'),
3070 'title' => ts('Add Note'),
3072 'ref' => 'new-note',
3075 'class' => 'medium-popup',
3076 'href' => CRM_Utils_System
::url('civicrm/contact/view/note',
3077 'reset=1&action=add'
3079 'permissions' => array('edit all contacts'),
3082 'title' => ts('Send an Email'),
3084 'ref' => 'new-email',
3086 'permissions' => array('view all contacts'),
3089 'title' => ts('Add to Group'),
3091 'ref' => 'group-add-contact',
3094 'permissions' => array('edit groups'),
3097 'title' => ts('Tag Contact'),
3099 'ref' => 'tag-contact',
3102 'permissions' => array('edit all contacts'),
3106 $menu['otherActions'] = array(
3108 'title' => ts('Print Summary'),
3109 'description' => ts('Printer-friendly view of this page.'),
3111 'ref' => 'crm-contact-print',
3114 'href' => CRM_Utils_System
::url('civicrm/contact/view/print',
3118 'icon' => 'crm-i fa-print',
3121 'title' => ts('vCard'),
3122 'description' => ts('vCard record for this contact.'),
3124 'ref' => 'crm-contact-vcard',
3127 'href' => CRM_Utils_System
::url('civicrm/contact/view/vcard',
3131 'icon' => 'crm-i fa-list-alt',
3135 if (CRM_Core_Permission
::check('access Contact Dashboard')) {
3136 $menu['otherActions']['dashboard'] = array(
3137 'title' => ts('Contact Dashboard'),
3138 'description' => ts('Contact Dashboard'),
3140 'ref' => 'crm-contact-dashboard',
3141 'key' => 'dashboard',
3142 'tab' => 'dashboard',
3143 'class' => 'dashboard',
3144 // NOTE: As an alternative you can also build url on CMS specific way
3145 // as CRM_Core_Config::singleton()->userSystem->getUserRecordUrl($contactId)
3146 'href' => CRM_Utils_System
::url('civicrm/user', "reset=1&id={$contactId}"),
3147 'icon' => 'crm-i fa-tachometer',
3151 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactId);
3153 $menu['otherActions']['user-record'] = array(
3154 'title' => ts('User Record'),
3155 'description' => ts('User Record'),
3157 'ref' => 'crm-contact-user-record',
3158 'key' => 'user-record',
3159 'tab' => 'user-record',
3160 'class' => 'user-record',
3161 'href' => CRM_Core_Config
::singleton()->userSystem
->getUserRecordUrl($contactId),
3162 'icon' => 'crm-i fa-user',
3165 elseif (CRM_Core_Config
::singleton()->userSystem
->checkPermissionAddUser()) {
3166 $menu['otherActions']['user-add'] = array(
3167 'title' => ts('Create User Record'),
3168 'description' => ts('Create User Record'),
3170 'ref' => 'crm-contact-user-add',
3171 'key' => 'user-add',
3172 'tab' => 'user-add',
3173 'class' => 'user-add',
3174 'href' => CRM_Utils_System
::url('civicrm/contact/view/useradd', 'reset=1&action=add&cid=' . $contactId),
3175 'icon' => 'crm-i fa-user-plus',
3179 CRM_Utils_Hook
::summaryActions($menu, $contactId);
3180 //1. check for component is active.
3181 //2. check for user permissions.
3182 //3. check for acls.
3183 //3. edit and view contact are directly accessible to user.
3185 $aclPermissionedTasks = array(
3190 'group-add-contact',
3194 $corePermission = CRM_Core_Permission
::getPermission();
3196 $contextMenu = array();
3197 foreach ($menu as $key => $values) {
3198 if ($key != 'otherActions') {
3200 // user does not have necessary permissions.
3201 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $values)) {
3204 // build directly accessible action menu.
3205 if (in_array($values['ref'], array(
3209 $contextMenu['primaryActions'][$key] = array(
3210 'title' => $values['title'],
3211 'ref' => $values['ref'],
3212 'class' => CRM_Utils_Array
::value('class', $values),
3213 'key' => $values['key'],
3218 // finally get menu item for -more- action widget.
3219 $contextMenu['moreActions'][$values['weight']] = array(
3220 'title' => $values['title'],
3221 'ref' => $values['ref'],
3222 'href' => CRM_Utils_Array
::value('href', $values),
3223 'tab' => CRM_Utils_Array
::value('tab', $values),
3224 'class' => CRM_Utils_Array
::value('class', $values),
3225 'key' => $values['key'],
3229 foreach ($values as $value) {
3230 // user does not have necessary permissions.
3231 if (!self
::checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $value)) {
3235 // finally get menu item for -more- action widget.
3236 $contextMenu['otherActions'][$value['weight']] = array(
3237 'title' => $value['title'],
3238 'ref' => $value['ref'],
3239 'href' => CRM_Utils_Array
::value('href', $value),
3240 'tab' => CRM_Utils_Array
::value('tab', $value),
3241 'class' => CRM_Utils_Array
::value('class', $value),
3242 'icon' => CRM_Utils_Array
::value('icon', $value),
3243 'key' => $value['key'],
3249 ksort($contextMenu['moreActions']);
3250 ksort($contextMenu['otherActions']);
3252 return $contextMenu;
3256 * Check if user has permissions to access items in action menu.
3258 * @param array $aclPermissionedTasks
3259 * Array containing ACL related tasks.
3260 * @param string $corePermission
3261 * The permission of the user (edit or view or null).
3262 * @param array $menuOptions
3263 * Array containing params of the menu (title, href, etc).
3266 * TRUE if user has all permissions, FALSE if otherwise.
3268 public static function checkUserMenuPermissions($aclPermissionedTasks, $corePermission, $menuOptions) {
3269 $componentName = CRM_Utils_Array
::value('component', $menuOptions);
3271 // if component action - make sure component is enable.
3272 if ($componentName && !in_array($componentName, CRM_Core_Config
::singleton()->enableComponents
)) {
3276 // make sure user has all required permissions.
3277 $hasAllPermissions = FALSE;
3279 $permissions = CRM_Utils_Array
::value('permissions', $menuOptions);
3280 if (!is_array($permissions) ||
empty($permissions)) {
3281 $hasAllPermissions = TRUE;
3284 // iterate for required permissions in given permissions array.
3285 if (!$hasAllPermissions) {
3286 $hasPermissions = 0;
3287 foreach ($permissions as $permission) {
3288 if (CRM_Core_Permission
::check($permission)) {
3293 if (count($permissions) == $hasPermissions) {
3294 $hasAllPermissions = TRUE;
3297 // if still user does not have required permissions, check acl.
3298 if (!$hasAllPermissions && $menuOptions['ref'] != 'delete-contact') {
3299 if (in_array($menuOptions['ref'], $aclPermissionedTasks) &&
3300 $corePermission == CRM_Core_Permission
::EDIT
3302 $hasAllPermissions = TRUE;
3304 elseif (in_array($menuOptions['ref'], array(
3307 // grant permissions for these tasks.
3308 $hasAllPermissions = TRUE;
3313 return $hasAllPermissions;
3317 * Retrieve display name of contact that address is shared.
3319 * This is based on $masterAddressId or $contactId .
3321 * @param int $masterAddressId
3323 * @param int $contactId
3326 * @return string|null
3327 * the found display name or null.
3329 public static function getMasterDisplayName($masterAddressId = NULL, $contactId = NULL) {
3330 $masterDisplayName = NULL;
3332 if (!$masterAddressId && !$contactId) {
3333 return $masterDisplayName;
3336 if ($masterAddressId) {
3338 SELECT display_name from civicrm_contact
3339 LEFT JOIN civicrm_address ON ( civicrm_address.contact_id = civicrm_contact.id )
3340 WHERE civicrm_address.id = " . $masterAddressId;
3342 elseif ($contactId) {
3344 SELECT display_name from civicrm_contact cc, civicrm_address add1
3345 LEFT JOIN civicrm_address add2 ON ( add1.master_id = add2.id )
3346 WHERE cc.id = add2.contact_id AND add1.contact_id = " . $contactId;
3349 $masterDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
3350 return $masterDisplayName;
3354 * Get the creation/modification times for a contact.
3356 * @param int $contactId
3359 * Dates - ('created_date' => $, 'modified_date' => $)
3361 public static function getTimestamps($contactId) {
3362 $timestamps = CRM_Core_DAO
::executeQuery(
3363 'SELECT created_date, modified_date
3364 FROM civicrm_contact
3367 1 => array($contactId, 'Integer'),
3370 if ($timestamps->fetch()) {
3372 'created_date' => $timestamps->created_date
,
3373 'modified_date' => $timestamps->modified_date
,
3382 * Get a list of triggers for the contact table.
3384 * @see hook_civicrm_triggerInfo
3385 * @see CRM_Core_DAO::triggerRebuild
3386 * @see http://issues.civicrm.org/jira/browse/CRM-10554
3389 * @param null $tableName
3391 public static function triggerInfo(&$info, $tableName = NULL) {
3392 //during upgrade, first check for valid version and then create triggers
3393 //i.e the columns created_date and modified_date are introduced in 4.3.alpha1 so dont create triggers for older version
3394 if (CRM_Core_Config
::isUpgradeMode()) {
3395 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
3396 //if current version is less than 4.3.alpha1 dont create below triggers
3397 if (version_compare($currentVer, '4.3.alpha1') < 0) {
3402 // Modifications to these records should update the contact timestamps.
3403 \Civi\Core\SqlTrigger\TimestampTriggers
::create('civicrm_contact', 'Contact')
3404 ->setRelations(array(
3405 array('table' => 'civicrm_address', 'column' => 'contact_id'),
3406 array('table' => 'civicrm_email', 'column' => 'contact_id'),
3407 array('table' => 'civicrm_im', 'column' => 'contact_id'),
3408 array('table' => 'civicrm_phone', 'column' => 'contact_id'),
3409 array('table' => 'civicrm_website', 'column' => 'contact_id'),
3412 ->alterTriggerInfo($info, $tableName);
3414 // Update phone table to populate phone_numeric field
3415 if (!$tableName ||
$tableName == 'civicrm_phone') {
3416 // Define stored sql function needed for phones
3417 $sqlTriggers = Civi
::service('sql_triggers');
3418 $sqlTriggers->enqueueQuery(self
::DROP_STRIP_FUNCTION_43
);
3419 $sqlTriggers->enqueueQuery(self
::CREATE_STRIP_FUNCTION_43
);
3421 'table' => array('civicrm_phone'),
3423 'event' => array('INSERT', 'UPDATE'),
3424 'sql' => "\nSET NEW.phone_numeric = civicrm_strip_non_numeric(NEW.phone);\n",
3430 * Check if contact is being used in civicrm_domain based on $contactId.
3432 * @param int $contactId
3436 * true if present else false.
3438 public static function checkDomainContact($contactId) {
3442 $domainId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain', $contactId, 'id', 'contact_id');
3453 * Get options for a given contact field.
3455 * @see CRM_Core_DAO::buildOptions
3457 * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
3458 * TODO: In context of chainselect, what to return if e.g. a country has no states?
3460 * @param string $fieldName
3461 * @param string $context
3462 * @see CRM_Core_DAO::buildOptionsContext
3463 * @param array $props
3464 * whatever is known about this dao object.
3466 * @return array|bool
3468 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3470 // Special logic for fields whose options depend on context or properties
3471 switch ($fieldName) {
3472 case 'contact_sub_type':
3473 if (!empty($props['contact_type'])) {
3474 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
3478 case 'contact_type':
3479 if ($context == 'search') {
3480 // CRM-15495 - EntityRef filters and basic search forms expect this format
3481 // FIXME: Search builder does not
3482 return CRM_Contact_BAO_ContactType
::getSelectElements();
3486 // The contact api supports some related entities so we'll honor that by fetching their options
3489 return CRM_Contact_BAO_GroupContact
::buildOptions('group_id', $context, $props);
3493 $props['entity_table'] = 'civicrm_contact';
3494 return CRM_Core_BAO_EntityTag
::buildOptions('tag_id', $context, $props);
3496 case 'state_province_id':
3497 case 'state_province':
3498 case 'state_province_name':
3503 case 'worldregion_id':
3504 return CRM_Core_BAO_Address
::buildOptions($fieldName, 'get', $props);
3507 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
3511 * Delete a contact-related object that has an 'is_primary' field.
3513 * Ensures that is_primary gets assigned to another object if available
3514 * Also calls pre/post hooks
3516 * @param string $type
3520 public static function deleteObjectWithPrimary($type, $id) {
3521 if (!$id ||
!is_numeric($id)) {
3524 $daoName = "CRM_Core_DAO_$type";
3525 $obj = new $daoName();
3529 if ($obj->fetch()) {
3530 CRM_Utils_Hook
::pre('delete', $type, $id, $hookParams);
3531 $contactId = $obj->contact_id
;
3537 // is_primary is only relavent if this field belongs to a contact
3539 $dao = new $daoName();
3540 $dao->contact_id
= $contactId;
3541 $dao->is_primary
= 1;
3542 // Pick another record to be primary (if one isn't already)
3543 if (!$dao->find(TRUE)) {
3544 $dao->is_primary
= 0;
3546 if ($dao->fetch()) {
3547 $dao->is_primary
= 1;
3553 CRM_Utils_Hook
::post('delete', $type, $id, $obj);
3561 public function addSelectWhereClause() {
3562 // We always return an array with these keys, even if they are empty,
3563 // because this tells the query builder that we have considered these fields for acls
3565 'id' => (array) CRM_Contact_BAO_Contact_Permission
::cacheSubquery(),
3566 'is_deleted' => CRM_Core_Permission
::check('access deleted contacts') ?
array() : array('!= 1'),
3568 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3573 * Get any existing duplicate contacts based on the input parameters.
3575 * @param array $input
3576 * Input parameters to be matched.
3577 * @param string $contactType
3578 * @param string $rule
3581 * @param $excludedContactIDs
3582 * An array of ids not to be included in the results.
3583 * @param bool $checkPermissions
3584 * @param int $ruleGroupID
3585 * ID of the rule group to be used if an override is desirable.
3589 public static function getDuplicateContacts($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3590 $dedupeParams = CRM_Dedupe_Finder
::formatParams($input, $contactType);
3591 $dedupeParams['check_permission'] = $checkPermissions;
3592 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $contactType, $rule, $excludedContactIDs, $ruleGroupID);
3597 * Get the first duplicate contacts based on the input parameters.
3599 * @param array $input
3600 * Input parameters to be matched.
3601 * @param string $contactType
3602 * @param string $rule
3605 * @param $excludedContactIDs
3606 * An array of ids not to be included in the results.
3607 * @param bool $checkPermissions
3608 * @param int $ruleGroupID
3609 * ID of the rule group to be used if an override is desirable.
3613 public static function getFirstDuplicateContact($input, $contactType, $rule = 'Unsupervised', $excludedContactIDs = array(), $checkPermissions = TRUE, $ruleGroupID = NULL) {
3614 $ids = self
::getDuplicateContacts($input, $contactType, $rule, $excludedContactIDs, $checkPermissions, $ruleGroupID);
3622 * Check if a field is associated with an entity that has a location type.
3624 * (ie. is an address, phone, email etc field).
3626 * @param string $fieldTitle
3627 * Title of the field (not the name - create a new function for that if required).
3631 public static function isFieldHasLocationType($fieldTitle) {
3632 foreach (CRM_Contact_BAO_Contact
::importableFields() as $key => $field) {
3633 if ($field['title'] === $fieldTitle) {
3634 return CRM_Utils_Array
::value('hasLocationType', $field);